strangerstudios / pmpro-vat-tax

Calculate VAT tax at membership checkout with Paid Memberships Pro. Allows customers with a VAT Number to avoid the tax.
https://www.paidmembershipspro.com/add-ons/vat-tax/
8 stars 20 forks source link

Fix for the recurring orders total/subtotal bug #32

Closed jayjay91 closed 4 years ago

jayjay91 commented 4 years ago

The current VAT Tax plugin version won't calculate the tax for recurring orders.

Here is a fix: This code snippet will check new recurring orders for specific total sums you have to define. Then, it will divide this total by a tax rate defined by you and uses it to calculate a subtotal and tax. These sums are added to the orders database entries.

function my_pmpro_email_template($type, $email){
    global $wpdb;

    if($type == 'invoice'){

        $data = $email->data;
        $code = $data['invoice_id'];
        $total = $data['invoice_total'];
        $toCheck = [36,48,72,3.5, 4.8,7]; /* check for specific total sums in orders to detect which orders to change */
        $total = number_format(floatval($total),1);

        if(in_array($total, $toCheck)) {
            // get order by unique code
            $sql = $wpdb->prepare( "SELECT id, subtotal, tax, total FROM $wpdb->pmpro_membership_orders WHERE code = '%s' LIMIT 1", $code);
            $results = $wpdb->get_results( $sql );
            $morder = [];

            if ( !empty( $results ) ) {
                foreach ( $results as $r ) {
                    $morder['id'] = $r->id;
                    $morder['subtotal'] = $r->subtotal;
                    $morder['tax'] = $r->tax;
                    $morder['total'] = $r->total;
                }

                $tax = intval($morder['tax']);
                if($tax == 0){
                    $divisor = 1.1; /* enter tax rate here to calculate subtotal and tax */ 
                    $y = date('Y');
                    $m = date('m');

                    $no = (float)($total / $divisor);
                    $no = pmpro_round_price($no);
                    $morder['subtotal'] = $no;
                    $tax = pmpro_round_price((float)($total - $no));
                    $id = $morder['id'];

                    $sqlQuery = "UPDATE $wpdb->pmpro_membership_orders
                            SET 
                            `subtotal` = '" . $no . "',
                            `tax` = '" . $tax . "'
                            WHERE id = '" . $id . "'
                            LIMIT 1";
                    $wpdb->query($sqlQuery);
                }

            }

        }
    }
    return $type;
}
add_filter('pmpro_email_template', 'my_pmpro_email_template',10,2);
ideadude commented 4 years ago

Thanks for sharing. I hope to have a general fix for this through the work being done with this issue: https://github.com/strangerstudios/pmpro-vat-tax/issues/29