Renew form now is creating invoice and payment to invoice.
authorSteve Sutton <steve@gaslightmedia.com>
Wed, 28 Mar 2018 17:10:59 +0000 (13:10 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Wed, 28 Mar 2018 17:10:59 +0000 (13:10 -0400)
Creates an invoice for the membership renewal.
Creates a payment and applies it to that invoice.
Updates the members renewal date.

classes/billingSupport.php
models/admin/ajax/accountsListExport.php
models/admin/billing/accounts.php
models/admin/billing/index.php
models/admin/member/billing.php
setup/commonHooks.php
views/admin/billing/memberBillingSubHeader.html

index dbe3dc8..a9c543f 100644 (file)
@@ -113,12 +113,12 @@ class GlmBillingSupport
                 // Mark this as paid then
                 $this->updateInvoiceBalance( $invoice['id'], (float)0.00 );
                 // Record the payment to the invoice_payments table
-                $this->recordInvoicePayment( $invoice['id'], $payment_id, $invoice['balance'] );
+                $this->recordInvoicePayment( $invoice['id'], $payment_id, $balance );
             } else if ( $payment > $invoice['balance'] ) {
                 $this->updateInvoiceBalance( $invoice['id'], (float)0.00 );
                 $payment -= $invoice['balance'];
                 // Record the payment to the invoice_payments table
-                $this->recordInvoicePayment( $invoice['id'], $payment_id, $invoice['balance'] );
+                $this->recordInvoicePayment( $invoice['id'], $payment_id, $balance );
             } else if ( $invoice['balance'] > $payment ) {
                 // Update the balance of the invoice
                 $balance = (float)$balance - (float)$payment;
@@ -140,14 +140,14 @@ class GlmBillingSupport
                         // Mark this as paid then
                         $this->updateInvoiceBalance( $invoice['id'], (float)0.00 );
                         // Record the payment to the invoice_payments table
-                        $this->recordInvoicePayment( $invoice['id'], $payment_id, $invoice['balance'] );
+                        $this->recordInvoicePayment( $invoice['id'], $payment_id, $balance );
                         // $payment is used up so break from the foreach loop
                         break;
                     } else if ( $payment > $invoice['balance'] ) {
                         $this->updateInvoiceBalance( $invoice['id'], (float)0.00 );
                         $payment -= $invoice['balance'];
                         // Record the payment to the invoice_payments table
-                        $this->recordInvoicePayment( $invoice['id'], $payment_id, $invoice['balance'] );
+                        $this->recordInvoicePayment( $invoice['id'], $payment_id, $balance );
                     } else if ( $invoice['balance'] > $payment ) {
                         // Update the balance of the invoice
                         $balance = (float)$balance - (float)$payment;
@@ -228,13 +228,11 @@ class GlmBillingSupport
                 'invoice'          => $invoice,
                 'payment'          => $payment,
                 'amount'           => $amount,
-                'transaction_time' => date('Y-m-d H:i;s'),
             ),
             array(
                 '%d',
                 '%d',
                 '%s',
-                '%s',
             )
         );
 
@@ -815,7 +813,6 @@ class GlmBillingSupport
             || !isset( $invoice_data['due_date'] )
             || !isset( $invoice_data['member_invoice'] )
             || !isset( $invoice_data['employee_data'] )
-            || !isset( $invoice_data['employees'] )
         ) {
             return false;
         }
@@ -863,20 +860,22 @@ class GlmBillingSupport
         );
         // echo '<pre>$invoice_id: ' . print_r( $invoice_id, true ) . '</pre>';
         if ( $invoice_id ) {
-            // Add line items for each employee.
-            foreach ( $employees as $account_id ) {
-                if ( $employee_data[$account_id]['invoice'] ) {
-                    $this->createLineItemForInvoice(
-                        array(
-                            'invoice_id'     => $invoice_id,
-                            'line_item_type' => $employee_data[(int)$account_id]['invoice']['id'],
-                            'name'           => $employee_data[(int)$account_id]['invoice']['name'],
-                            'amount'         => $employee_data[(int)$account_id]['invoice']['amount'],
-                            'due_date'       => $due_date,
-                            'recurring'      => $employee_data[(int)$account_id]['invoice']['recurring'],
-                            'recurrence'     => $employee_data[(int)$account_id]['invoice']['recurrence'],
-                        )
-                    );
+            if ( isset( $employees ) && is_array( $employees ) ) {
+                // Add line items for each employee.
+                foreach ( $employees as $account_id ) {
+                    if ( $employee_data[$account_id]['invoice'] ) {
+                        $this->createLineItemForInvoice(
+                            array(
+                                'invoice_id'     => $invoice_id,
+                                'line_item_type' => $employee_data[(int)$account_id]['invoice']['id'],
+                                'name'           => $employee_data[(int)$account_id]['invoice']['name'],
+                                'amount'         => $employee_data[(int)$account_id]['invoice']['amount'],
+                                'due_date'       => $due_date,
+                                'recurring'      => $employee_data[(int)$account_id]['invoice']['recurring'],
+                                'recurrence'     => $employee_data[(int)$account_id]['invoice']['recurrence'],
+                            )
+                        );
+                    }
                 }
             }
         }
@@ -938,7 +937,7 @@ class GlmBillingSupport
         $ccProcessor = $this->config['billing_settings']['proc_methods'];
 
         // Setup the required account information for the selected payment processor
-        switch ($ccProcessor) {
+        switch ( $ccProcessor ) {
 
         case $this->config['proc_method_numb']['Authorize.net']:
 
@@ -1024,8 +1023,8 @@ class GlmBillingSupport
             && $cardData['cc_exp'] && $cardData['cc_exp'] != ''
             && $cardData['cc_cvv'] && $cardData['cc_cvv'] > 0
         ) {
-            if (!isset($this->config['credit_card_match'][$cardData['cc_type']]) ||
-                !preg_match($this->config['credit_card_match'][$cardData['cc_type']], $cardData['cc_numb'])
+            if ( !isset( $this->config['credit_card_match'][$cardData['cc_type']] ) ||
+                !preg_match( $this->config['credit_card_match'][$cardData['cc_type']], $cardData['cc_numb'] )
             ) {
                 $errors[] = 'The credit card number you entered does not match the selected type of credit card.';
             }
@@ -1037,38 +1036,47 @@ class GlmBillingSupport
         if (count($errors) == 0) {
 
             // Determine the directory of the payment processor to load and instantiate it.
-            if ($ccProcessor && isset($this->config['proc_dir'][$ccProcessor])) {
+            if ( $ccProcessor && isset( $this->config['proc_dir'][$ccProcessor] ) ) {
                 require_once GLM_MEMBERS_BILLING_PLUGIN_LIB_PATH.'/paymentProcessors/'.$this->config['proc_dir'][$ccProcessor].'/paymentGateway.php';
-                $CcProcessor = new PaymentGateway($account);
+                $CcProcessor = new PaymentGateway( $account );
             }
 
             $payment = array(
                 'name'    => $this->config['settings']['company_name'],  // Company Name
-                'charge'  => $amount,                     // Total charges
+                'charge'  => $amount,                                    // Total charges
                 'cctype'  => $cardData['cc_type'],                       // Card Type
                 'ccname'  => $cardData['cc_name'],                       // Name on Card
                 'ccnumb'  => $cardData['cc_numb'],                       // Card Number
                 'ccexp'   => $cardData['cc_exp'],                        // Expiration Date
                 'cccode'  => $cardData['cc_cvv'],                        // CCV - security code
-                'invoice' => 'billing-'.$paymentData['invoice_id']       // Invoice # is "reg-" plus cart ID
+                'invoice' => 'billing-'.$invoice_id                      // Invoice # is "reg-" plus cart ID
             );
 
             // Now try to run the card processor
-            $ccResult = $CcProcessor->processPayment($payment, $billing);
+            $ccResult = $CcProcessor->processPayment( $payment, $billing );
 
             // If successful submission - say we're complete
-            if (is_array($ccResult) && isset($ccResult['status']) && $ccResult['status'] == 1) {
+            if ( is_array( $ccResult ) && isset( $ccResult['status'] ) && $ccResult['status'] == 1 ) {
                 // Need to record the payment
 
                 // Set transaction_time to current time.
-                $_REQUEST['transaction_time'] = date('Y-m-d H:i:s');
+                $_REQUEST['transaction_time'] = date( 'Y-m-d H:i:s' );
                 // Create new payment.
                 $payment_id = $this->createPayment( $account_id, $amount );
                 // Record the payment.
                 $this->recordPayment( $payment_id, $account_id, $amount, $invoice_id );
 
-                $errors[] = $ccResult['statusText'];
-                $errors[] = $ccResult['description'];
+                // $errors[] = $ccResult['statusText'];
+                // $errors[] = $ccResult['description'];
+
+                // TODO: Need to update the members account renewal_date
+                $this->wpdb->update(
+                    GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'accounts',
+                    array( 'renewal_date' => date( 'Y-m-d' ) ),
+                    array( 'id' => $account_id ),
+                    array( '%s' ),
+                    array( '%d' )
+                );
 
             }
 
index 908d044..ac647fe 100644 (file)
@@ -154,9 +154,16 @@ class GlmMembersAdmin_ajax_accountsListExport extends GlmDataAccounts
             $where_params[] = "T.ref_name like '%" . esc_sql( $searchName ) . "%'";
         }
 
+        // Get the setting for days before and after.
+        $days_before_renewal = $this->config['settings']['days_before_renewal'];
+        $days_after_expired  = $this->config['settings']['days_after_expired'];
+        $curDate             = date( 'Y-m-d' );
+
         if ( isset( $_REQUEST['filterPending'] ) ) {
             $filterPending = filter_var( $_REQUEST['filterPending'], FILTER_VALIDATE_BOOLEAN );
-            $where_params[] = "renewal_date >= now()";
+            // $where_params[] = "renewal_date >= now()";
+            $where_params[] = "T.renewal_date + INTERVAL 1 YEAR - INTERVAL $days_before_renewal DAY  <= '$curDate'";
+            $where_params[] = "T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY >= '$curDate'";
             $filterPending = true;
             $haveFilter    = true;
         }
index 55616d9..93bb372 100644 (file)
@@ -349,6 +349,12 @@ class GlmMembersAdmin_billing_accounts extends GlmDataAccounts
                 )
             );
             // When searching
+            if ( isset( $_REQUEST['filterArchived'] )
+                && $filterArchived = filter_var( $_REQUEST['filterArchived'], FILTER_VALIDATE_BOOLEAN ) ) {
+                $where_params[] = "T.archived = true";
+            } else {
+                $where_params[] = "T.archived <> true";
+            }
             if ( isset( $_REQUEST['fromDate'] ) && $_REQUEST['fromDate']
                 && $fromDate = filter_var( $_REQUEST['fromDate'], FILTER_VALIDATE_REGEXP, $reg_options )
             ) {
@@ -372,20 +378,31 @@ class GlmMembersAdmin_billing_accounts extends GlmDataAccounts
                 $where_params[] = "T.ref_name like '%" . esc_sql( $searchName ) . "%'";
             }
 
+            // Get the setting for days before and after.
+            $days_before_renewal = $this->config['settings']['days_before_renewal'];
+            $days_after_expired  = $this->config['settings']['days_after_expired'];
+            $curDate             = date( 'Y-m-d' );
+
             if ( isset( $_REQUEST['filterPending'] ) ) {
                 $filterPending = filter_var( $_REQUEST['filterPending'], FILTER_VALIDATE_BOOLEAN );
-                $where_params[] = "renewal_date >= now()";
+                // $where_params[] = "T.renewal_date >= now()";
+                $where_params[] = "T.renewal_date + INTERVAL 1 YEAR - INTERVAL $days_before_renewal DAY  <= '$curDate'";
+                $where_params[] = "T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY >= '$curDate'";
             }
             if ( isset( $_REQUEST['filterOverdue'] ) ) {
                 $filterOverdue = filter_var( $_REQUEST['filterOverdue'], FILTER_VALIDATE_BOOLEAN );
-                $expiredDate    = date( 'Y-m-d', mktime( 0, 0, 0, date( 'n' ), date( 'j' ) - 30, date( 'Y' )) );
-                $where_params[] = "renewal_date < now()";
-                $where_params[] = "renewal_date >= '$expiredDate'";
+                // $expiredDate    = date( 'Y-m-d', mktime( 0, 0, 0, date( 'n' ), date( 'j' ) - 30, date( 'Y' )) );
+                // $where_params[] = "T.renewal_date < '$curDate'";
+                // $where_params[] = "T.renewal_date >= '$expiredDate'";
+                $where_params[] = "T.renewal_date + INTERVAL 1 YEAR < '$curDate'";
+                // $where_params[] = "T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY < '$curDate'";
+                $where_params[] = "T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY >= '$curDate'";
             }
             if ( isset( $_REQUEST['filterExpired'] ) ) {
                 $filterExpired = filter_var( $_REQUEST['filterExpired'], FILTER_VALIDATE_BOOLEAN );
-                $expiredDate    = date( 'Y-m-d', mktime( 0, 0, 0, date( 'n' ), date( 'j' ) - 30, date( 'Y' )) );
-                $where_params[] = "renewal_date < '$expiredDate'";
+                // $expiredDate    = date( 'Y-m-d', mktime( 0, 0, 0, date( 'n' ), date( 'j' ) - 30, date( 'Y' )) );
+                // $where_params[] = "T.renewal_date < '$expiredDate'";
+                $where_params[] = "T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY < '$curDate'";
             }
 
 
index 37b3702..9fe2e40 100644 (file)
@@ -241,15 +241,21 @@ class GlmMembersAdmin_billing_index extends GlmDataAccounts
             // Pending
             // Active
             // Get list of pending invoices ( not overdue )
+            $days_before_renewal = $this->config['settings']['days_before_renewal'];
+            $days_after_expired  = $this->config['settings']['days_after_expired'];
             $orderBy = 'renewal_date ASC';
-            $pendingWhere = "renewal_date >= now()";
+            $curDate = date( 'Y-m-d' );
+            $pendingWhere = "T.archived <> true ";
+            $pendingWhere .= " AND T.renewal_date + INTERVAL 1 YEAR - INTERVAL $days_before_renewal DAY  <= '$curDate'" ;
+            $pendingWhere .= " AND T.renewal_date + INTERVAL 1 YEAR + INTERVAL $days_after_expired DAY >= '$curDate'";
             $start        = 1;
             $pending      = $this->getList( $pendingWhere, $orderBy, true, 'id', $start, $limit );
             // echo '<pre>$pending: ' . print_r( $pending, true ) . '</pre>';
             $numberPending = ( isset( $pending['returned'] ) ? $pending['returned'] : 0 );
 
             // Get the number of over due invoices
-            $overDueWhere  = "renewal_date < now()";
+            $overDueWhere  = "T.archived <> true";
+            $overDueWhere .= " AND T.renewal_date + INTERVAL 1 YEAR < '$curDate'";
             $start         = 1;
             $overdue       = $this->getList( $overDueWhere, $orderBy, true, 'id', $start, $limit );
             if ( isset( $overdue['returned'] ) ) {
index afa64b4..20a4768 100644 (file)
@@ -122,7 +122,8 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
         $hasBillingAccount  = false;
         $employees          = false;
         $member_invoice     = false;
-        $payable_types     = false;
+        $payable_types      = false;
+        $account_status     = false;
 
         // For lockedToMember.
         $lockedToMember = false;
@@ -177,6 +178,18 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
             $option = $_REQUEST['option'];
         }
 
+        require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataAccounts.php';
+        $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
+        $accountID = $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT id
+                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts
+                  WHERE ref_dest = %d",
+                $this->memberID
+            )
+        );
+        $account_status = apply_filters( 'glm-billing-get-account-status', '', $accountID );
+
         switch ( $option ) {
         case 'renew':
             $view = 'renew';
@@ -201,15 +214,6 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
 
             // Need to see if there's an account for this member.
             require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataAccounts.php';
-            $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
-            $accountID = $this->wpdb->get_var(
-                $this->wpdb->prepare(
-                    "SELECT id
-                       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts
-                      WHERE ref_dest = %d",
-                    $this->memberID
-                )
-            );
             $account = $Accounts->editEntry( $accountID );
 
             break;
@@ -217,7 +221,7 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
         case 'renewMembership':
             $error = false;
             $view  = 'renewMembership';
-            $messages[] = '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
+            // $messages[] = '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
 
             $member_invoice_id = $BillingSupport->getMembersInvoiceTypeByRefDest( $this->memberID );
             if ( $member_invoice_id ) {
@@ -271,30 +275,17 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
                 $management = $Management->getEntry( 1 );
 
                 // Need to see if there's an account for this member.
-                require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataAccounts.php';
-                $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
-                $accountID = $this->wpdb->get_var(
-                    $this->wpdb->prepare(
-                        "SELECT id
-                           FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts
-                          WHERE ref_dest = %d",
-                        $this->memberID
-                    )
-                );
                 $account = $Accounts->editEntry( $accountID );
             } else {
                 // Do the Payment Processing.
                 $errors = $BillingSupport->processMemberRenewal( $invoice_data['account_id'], $invoice_id, $invoice_data['amount'] );
-                echo '<pre>$errors: ' . print_r( $errors, true ) . '</pre>';
+                // echo '<pre>$errors: ' . print_r( $errors, true ) . '</pre>';
             }
 
 
             break;
 
         case 'account':
-            require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataAccounts.php';
-            $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
-
             // Check to see if we're adding an account or editing one.
             if ( isset( $_REQUEST['ref_name'] ) ) {
                 $_REQUEST['anniversary_date'] = date('Y-m-d', strtotime($_REQUEST['anniversary_date']));
@@ -368,10 +359,6 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
 
         case 'makepayment':
 
-            // Load DataClass for accounts.
-            require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataAccounts.php';
-            $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
-
             // Load DataClass for Management.
             require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataManagement.php';
             $Management = new GlmDataBillingManagement( $this->wpdb, $this->config );
@@ -405,6 +392,7 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
             break;
         case 'list':
             $view = 'statements';
+            // echo '<pre>$test: ' . print_r( $test, true ) . '</pre>';
             break;
         }
 
@@ -451,6 +439,7 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
             'employees'          => $employees,
             'member_invoice'     => $member_invoice,
             'payable_types'      => $payable_types,
+            'account_status'     => $account_status,
         );
 
         // Return status, any suggested view, and any data to controller.
index fa09025..658e81d 100644 (file)
  *  Also note that parameters will be in the context of the main admin controller constructor.
   */
 
+/**
+ * Check the member account and return the status.
+ * (Pending, Expired, Active, Archived)
+ */
+add_filter( 'glm-billing-get-account-status', function( $content, $account_id ){
+    global $config;
+    if ( isset( $account_id ) && $account_id = filter_var( $account_id, FILTER_VALIDATE_INT ) ) {
+        // fetch the account
+        $account = $this->wpdb->get_row(
+            $this->wpdb->prepare(
+                "SELECT *
+                   FROM "  . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts
+                  WHERE id = %d",
+                $account_id
+            ),
+            ARRAY_A
+        );
+        if ( !$account ) {
+            return $content;
+        }
+        $archived     = $account['archived'];
+        $renewal_date = $account['renewal_date'];
+        $renewal_time = strtotime( $account['renewal_date'] );
+        $current_time = mktime( 0, 0, 0,
+            date( 'n' ),
+            date( 'j' ),
+            date( 'Y' )
+        );
+        // Check if account is archived.
+        if ( $archived ) {
+            return 'Archived';
+        }
+        $days_before_renewal = $config['settings']['days_before_renewal'];
+        // echo '<pre>$days_before_renewal: ' . print_r( $days_before_renewal, true ) . '</pre>';
+        $days_before_time = mktime( 0, 0, 0,
+            date( 'n', $renewal_time ),
+            date( 'j', $renewal_time ) - $days_before_renewal,
+            date( 'Y', $renewal_time ) + 1
+        );
+        // echo '<pre>$days_before_time: ' . print_r( date( 'm/d/Y', $days_before_time), true ) . '</pre>';
+
+        $days_after_expired  = $config['settings']['days_after_expired'];
+        // echo '<pre>$days_after_expired: ' . print_r( $days_after_expired, true ) . '</pre>';
+        $days_after_time = mktime( 0, 0, 0,
+            date( 'n', $renewal_time ),
+            date( 'j', $renewal_time ) + $days_after_expired,
+            date( 'Y', $renewal_time ) + 1
+        );
+        // echo '<pre>$days_after_time: ' . print_r( date( 'm/d/Y', $days_after_time), true ) . '</pre>';
+
+        if ( $current_time > $days_after_time ) {
+            return 'Expired';
+        }
+        if ( $current_time > $days_before_time ) {
+            return 'Pending';
+        }
+        return 'Active';
+
+    }
+
+},10, 2 );
index feaf062..8f135c3 100644 (file)
@@ -4,6 +4,7 @@
         <div>{$memberData.member_type_short}</div>
         {if $account_data}
         <div><strong>Renewal date:</strong> {$account_data.renewal_date|strtotime|date_format}</div>
+        <div><strong>Membership Status:</strong> {$account_status}</div>
         {/if}
     </div>
 
                     href="{$thisUrl}?page=glm-members-admin-menu-member&glm_action=billing&member={$memberID}"
                     class="">All Statements</a>
             </li>
+            {if $account_status == 'Pending'}
             <li>
                 <a
                     href="{$thisUrl}?page=glm-members-admin-menu-member&glm_action=billing&member={$memberID}&option=renew"
                     class="">Renew</a>
             </li>
+            {/if}
             <li>
                 <a
                     href="{$thisUrl}?page=glm-members-admin-menu-member&glm_action=billing&member={$memberID}&option=makepayment"