First, your code is a little outdated for the cart negative fee part:
add_action( 'woocommerce_cart_calculate_fees', 'custom_flat_discount', 20, 1 );
function custom_flat_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart->add_fee( __("Discount", "woocommerce"), -15 );
}
Now what you have to know is that a negative fee always apply taxes.
To get the order gran total excluding all discounts you will use the following in your function:
add_action( 'woocommerce_payment_complete', 'action_payment_complete', 20, 1 );
function action_payment_complete( $order_id ) {
// get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Initialising variables
$subtotal = $subtotal_taxes = 0;
// Get order items subtotal and subtotal tax
foreach( $order->get_items() as $item ){
$subtotal += (double) $item->get_subtotal();
$subtotal_taxes += (double) $item->get_subtotal_tax();
}
// Order subtotal without any discounts, shipping…
$order_subtotal = $subtotal + $subtotal_taxes;
// Get order shipping totals
$shipping_total = $order->get_shipping_total();
$shipping_total_tax = $order->get_shipping_tax();
// Order subtotal with shipping but without any discounts
$order_subtotal_with_shipping = round($order_subtotal + $shipping_total + $shipping_total_tax, 2);
// Your other code goes here
}
Alternatively you can use woocommerce_order_status_{$status_transition[to]}
action hook on "processing" and "completed" paid statuses:
add_action( 'woocommerce_order_status_processing', 'action_order_status_completed', 20, 2 );
add_action( 'woocommerce_order_status_completed', 'action_order_status_completed', 20, 2 );
function action_order_status_completed( $order_id, $order ) {
// Initialising variables
$subtotal = $subtotal_taxes = 0;
// Get order items subtotal and subtotal tax
foreach( $order->get_items() as $item ){
$subtotal += (double) $item->get_subtotal();
$subtotal_taxes += (double) $item->get_subtotal_tax();
}
// Order subtotal without any discounts, shipping…
$order_subtotal = $subtotal + $subtotal_taxes;
// Get order shipping totals
$shipping_total = $order->get_shipping_total();
$shipping_total_tax = $order->get_shipping_tax();
// Order subtotal with shipping but without any discounts
$order_subtotal_with_shipping = round($order_subtotal + $shipping_total + $shipping_total_tax, 2);
// Your other code goes here
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.