Db updates and testing renewal forms
authorSteve Sutton <steve@gaslightmedia.com>
Tue, 10 Apr 2018 20:54:59 +0000 (16:54 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Tue, 10 Apr 2018 20:54:59 +0000 (16:54 -0400)
Adding new field for invioces so we know which is used for renewals.
If account has one then don't show the renewal form.

classes/billingSupport.php
index.php
models/admin/billing/accounts.php
models/admin/billing/payments.php
models/admin/member/billing.php
setup/commonHooks.php
setup/databaseScripts/create_database_V0.0.19.sql
setup/databaseScripts/dbVersions.php
setup/databaseScripts/update_database_V0.0.20.sql [new file with mode: 0644]
views/admin/billing/memberBillingSubHeader.html
views/admin/billing/payments.html

index 4fb2943..6f96f43 100644 (file)
@@ -104,7 +104,6 @@ class GlmBillingSupport
 
         // If there's an invoice_id
         // If the payment amount is over then go through the other invoices.
-        // TODO: Need to deal with an array of invoice_id's
         if ( isset( $invoices ) ) {
             if ( !is_array( $invoices ) ) {
                 $invoices = array( $invoices );
@@ -216,6 +215,7 @@ class GlmBillingSupport
      */
     public function markInvoiceAsPaid( $invoice_id )
     {
+        // Update the invoice.
         $this->wpdb->update(
             GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'invoices',
             array( 'paid' => 1 ),
@@ -223,6 +223,34 @@ class GlmBillingSupport
             array( '%s' ),
             array( '%d' )
         );
+
+        // find out if this invoice is a renewal.
+        $is_renewal = $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT renewal
+                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
+                  WHERE id = %d",
+                $invoice_id
+            )
+        );
+
+        // If this is a renewal then get all line items and update their renewal dates.
+        if ( $is_renewal ) {
+            $line_items = $this->wpdb->get_results(
+                $this->wpdb->prepare(
+                    "SELECT account
+                       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "line_items
+                      WHERE invoice = %d",
+                    $invoice_id
+                ),
+                ARRAY_A
+            );
+            if ( $line_items ) {
+                foreach ( $line_items as $account ) {
+                    $this->updateAccountRenewalDate( $account['account'] );
+                }
+            }
+        }
     }
 
     /**
@@ -269,7 +297,7 @@ class GlmBillingSupport
     public function updateInvoiceBalance( $invoice_id, $balance )
     {
         // if the balance is 0.00 then set paid to true
-        if ( $balance === 0.00 ) {
+        if ( $balance == 0.00 ) {
             $this->markInvoiceAsPaid( $invoice_id );
         }
         $this->wpdb->update(
@@ -942,6 +970,7 @@ class GlmBillingSupport
                 'due_date'         => $due_date,
                 'paid'             => 0,
                 'notes'            => '',
+                'renewal'          => true,
                 'recurring'        => true,
                 'recurrence'       => 20
             ),
@@ -953,6 +982,7 @@ class GlmBillingSupport
                 '%s', // due_date
                 '%s', // paid
                 '%s', // notes
+                '%s', // renewal
                 '%s', // recurring
                 '%s', // recurrence
             )
@@ -1310,26 +1340,14 @@ class GlmBillingSupport
             // $errors[] = $ccResult['description'];
 
             // 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' )
-            );
+            // $this->updateAccountRenewalDate( $account_id );
 
             // Need to update any employees renewal dates
-            if ( isset( $employees ) && is_array( $employees ) && !empty( $employees ) ) {
-                foreach ( $employees as $employee ) {
-                    $this->wpdb->update(
-                        GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'accounts',
-                        array( 'renewal_date' => date( 'Y-m-d' ) ),
-                        array( 'id' => $employee ),
-                        array( '%s' ),
-                        array( '%d' )
-                    );
-                }
-            }
+            // if ( isset( $employees ) && is_array( $employees ) && !empty( $employees ) ) {
+            //     foreach ( $employees as $employee ) {
+            //         $this->updateAccountRenewalDate( $employee );
+            //     }
+            // }
 
             $errors = $result['errors'];
 
@@ -1390,5 +1408,16 @@ class GlmBillingSupport
         );
     }
 
+    public function updateAccountRenewalDate( $account )
+    {
+        $this->wpdb->update(
+            GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'accounts',
+            array( 'renewal_date' => date( 'Y-m-d' ) ),
+            array( 'id' => $account ),
+            array( '%s' ),
+            array( '%d' )
+        );
+    }
+
 }
 
index 83475b4..2661175 100644 (file)
--- a/index.php
+++ b/index.php
@@ -38,7 +38,7 @@
  *  version from this plugin.
  */
 define('GLM_MEMBERS_BILLING_PLUGIN_VERSION', '0.0.1');
-define('GLM_MEMBERS_BILLING_PLUGIN_DB_VERSION', '0.0.19');
+define('GLM_MEMBERS_BILLING_PLUGIN_DB_VERSION', '0.0.20');
 
 // This is the minimum version of the GLM Members DB plugin require for this plugin.
 define('GLM_MEMBERS_BILLING_PLUGIN_MIN_MEMBERS_REQUIRED_VERSION', '2.8.0');
index c5ae083..dc431f2 100644 (file)
@@ -481,7 +481,7 @@ class GlmMembersAdmin_billing_accounts extends GlmDataAccounts
             'searchName'          => $searchName,
             'filterExpired'       => $filterExpired,
             'filterActive'        => $filterActive,
-            'filterArchived'     => $filterArchived,
+            'filterArchived'      => $filterArchived,
         );
 
         // Return status, any suggested view, and any data to controller
index d4a2353..4006538 100644 (file)
@@ -115,6 +115,7 @@ class GlmMembersAdmin_billing_payments extends GlmDataPayments
         $limit               = 20;        // Set to the number of listings per page
         $invTypes            = array();
         $accounts            = false;
+        $allAccounts         = false;
 
         // Get any provided option
         if (isset($_REQUEST['option'])) {
@@ -207,6 +208,9 @@ class GlmMembersAdmin_billing_payments extends GlmDataPayments
         case 'list':
         default:
 
+            $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
+            $allAccounts = $Accounts->getSimpleAccountList();
+
             $where = 'true';
 
             // Check for paging
@@ -256,6 +260,41 @@ class GlmMembersAdmin_billing_payments extends GlmDataPayments
             //     }
             // }
 
+            // Get any search parameters.
+            $reg_options = array(
+                'options' => array(
+                    'regexp' => '%[0-9]{2}/[0-9]{2}/[0-9]{4}%'
+                )
+            );
+            if ( isset( $_REQUEST['fromDate'] ) && $_REQUEST['fromDate']
+                && $fromDate = filter_var( $_REQUEST['fromDate'], FILTER_VALIDATE_REGEXP, $reg_options )
+            ) {
+                $from_date = date( 'Y-m-d', strtotime( $fromDate ) );
+                $where_params[] = "T.transaction_time >= '$from_date'";
+            }
+            if ( isset( $_REQUEST['toDate'] ) && $_REQUEST['toDate']
+                && $toDate = filter_var( $_REQUEST['toDate'], FILTER_VALIDATE_REGEXP, $reg_options )
+            ) {
+                $to_date = date( 'Y-m-d', strtotime( $toDate ) );
+                $where_params[] = "T.transaction_time <= '$to_date'";
+            }
+            if ( isset( $_REQUEST['filterAccounts'] )
+                && $filterAccounts = filter_var( $_REQUEST['filterAccounts'], FILTER_VALIDATE_INT )
+            ) {
+                $accounts[$filterAccounts]['selected'] = true;
+                $where_params[] = "T.account = $filterAccounts";
+            } else if ( isset( $_REQUEST['searchName'] )
+                && $searchName = filter_var( $_REQUEST['searchName'], FILTER_SANITIZE_STRING )
+            ) {
+                // $where_params[] = "T.ref_name like '%" . esc_sql( $searchName ) . "%'";
+            }
+
+            // Build the $where string from the $where_parts array.
+            // By implode with AND.
+            $where = implode( ' AND ', $where_params );
+
+            // echo '<pre>$where: ' . print_r( $where, true ) . '</pre>';
+
             // Get the list of payments and determine number of payments in list
             $orderBy = 'transaction_time asc';
             $paymentsResult = $this->getList($where, $orderBy, true, 'id', $start, $limit);
@@ -291,26 +330,31 @@ class GlmMembersAdmin_billing_payments extends GlmDataPayments
 
 
         $templateData = array(
-            'option'               => $option,
-            'payment_id'           => $this->payment_id,
-            'payments'             => $payments,
-            'havePayments'         => $havePayments,
-            'paymentUpdated'       => $paymentsUpdated,
-            'paymentUpdateError'   => $paymentsUpdateError,
-            'paymentAdded'         => $paymentsAdded,
-            'paymentAddError'      => $paymentsAddError,
-            'paymentInsertError'   => $paymentsInsertError,
-            'paymentDeleted'       => $paymentsDeleted,
-            'paymentDeleteError'   => $paymentsDeleteError,
-            'paymentInvoiceError'  => $paymentsDeleteError,
-            'numbDisplayed'        => $numbDisplayed,
-            'lastDisplayed'        => $lastDisplayed,
-            'paging'               => $paging,
-            'prevStart'            => $prevStart,
-            'nextStart'            => $nextStart,
-            'start'                => $start = 1,
-            'limit'                => $limit,
-            'accounts'             => $accounts,
+            'option'              => $option,
+            'payment_id'          => $this->payment_id,
+            'payments'            => $payments,
+            'havePayments'        => $havePayments,
+            'paymentUpdated'      => $paymentsUpdated,
+            'paymentUpdateError'  => $paymentsUpdateError,
+            'paymentAdded'        => $paymentsAdded,
+            'paymentAddError'     => $paymentsAddError,
+            'paymentInsertError'  => $paymentsInsertError,
+            'paymentDeleted'      => $paymentsDeleted,
+            'paymentDeleteError'  => $paymentsDeleteError,
+            'paymentInvoiceError' => $paymentsDeleteError,
+            'numbDisplayed'       => $numbDisplayed,
+            'lastDisplayed'       => $lastDisplayed,
+            'paging'              => $paging,
+            'prevStart'           => $prevStart,
+            'nextStart'           => $nextStart,
+            'start'               => $start = 1,
+            'limit'               => $limit,
+            'accounts'            => $accounts,
+            'allAccounts'         => $allAccounts,
+            'fromDate'            => $fromDate,
+            'toDate'              => $toDate,
+            'filterAccounts'      => $filterAccounts,
+            'searchName'          => $searchName,
         );
 
         // Return status, any suggested view, and any data to controller
index 0e63552..caa3610 100644 (file)
@@ -204,6 +204,8 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
             }
             // echo '<pre>$member_invoice: ' . print_r( $member_invoice, true ) . '</pre>';
 
+            // TODO: If there's no member_invoice then we can't create an invoice for renewal.
+
             // Get a list of this accounts employees. If they have any.
             $employees = $BillingSupport->getListOfAccountEmployees( $this->memberID );
             // echo '<pre>$employees: ' . print_r( $employees, true ) . '</pre>';
@@ -295,6 +297,9 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
                             foreach ( $processErrors as $error ) {
                                 $messages[] = '<span style="color: red;">'.$error.'</span>';
                             }
+                            $paymentError = true;
+                        } else {
+                            $paymentSuccess = true;
                         }
                         $view = 'renew';
 
@@ -323,47 +328,47 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
                 }
 
                 // If there's no error reported then show the invoice
-                if ( !$error ) {
-                    // Now need to show the invoice.
-                    $view = 'viewInvoice';
-
-                    // Get the invoice.
-                    $invoiceHtml = $BillingSupport->viewInvoice( $invoice_id );
-
-                    // If the member_type is changing then update member
-                    // Get current member type
-                    $member_id = filter_var( $_REQUEST['member'], FILTER_VALIDATE_INT );
-                    if ( $member_id ) {
-                        $current_member_type = $this->wpdb->get_var(
-                            $this->wpdb->prepare(
-                                "SELECT member_type
-                                   FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
-                                  WHERE id = %d",
-                                $member_id
-                            )
-                        );
-                        $new_type = filter_var( $_REQUEST['member_renewing'], FILTER_VALIDATE_INT );
-                        $new_member_type = $this->wpdb->get_var(
-                            $this->wpdb->prepare(
-                                "SELECT member_type
-                                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoice_types
-                                  WHERE id = %d",
-                                $new_type
-                            )
-                        );
-                        if ( $current_member_type != $new_member_type ) {
-                            $this->update(
-                                GLM_MEMBERS_PLUGIN_DB_PREFIX . 'members',
-                                array( 'member_type' => $new_member_type ),
-                                array( 'id' => $member_id ),
-                                array( '%d' ),
-                                array( '%d' )
-                            );
-                        }
-                    }
-                }
+                // Now need to show the invoice.
+                $view = 'viewInvoice';
+
+                // Get the invoice.
+                $invoiceHtml = $BillingSupport->viewInvoice( $invoice_id );
+
+                // If the member_type is changing then update member
+                // Get current member type
+                // $member_id = filter_var( $_REQUEST['member'], FILTER_VALIDATE_INT );
+                // if ( $member_id ) {
+                //     $current_member_type = $this->wpdb->get_var(
+                //         $this->wpdb->prepare(
+                //             "SELECT member_type
+                //                FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+                //               WHERE id = %d",
+                //             $member_id
+                //         )
+                //     );
+                //     $new_type = filter_var( $_REQUEST['member_renewing'], FILTER_VALIDATE_INT );
+                //     $new_member_type = $this->wpdb->get_var(
+                //         $this->wpdb->prepare(
+                //             "SELECT member_type
+                //                FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoice_types
+                //               WHERE id = %d",
+                //             $new_type
+                //         )
+                //     );
+                //     if ( $current_member_type != $new_member_type ) {
+                //         $this->update(
+                //             GLM_MEMBERS_PLUGIN_DB_PREFIX . 'members',
+                //             array( 'member_type' => $new_member_type ),
+                //             array( 'id' => $member_id ),
+                //             array( '%d' ),
+                //             array( '%d' )
+                //         );
+                //     }
+                // }
             }
 
+            break;
+
         case 'account':
             // Check to see if we're adding an account or editing one.
             if ( isset( $_REQUEST['ref_name'] ) ) {
@@ -425,7 +430,7 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
 
         case 'createPayment':
 
-            echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
+            // echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
 
             $view = 'paymentProcess';
 
@@ -445,6 +450,7 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
                 $errors = $BillingSupport->makePayment( $account_id, $invoices, $amount );
 
                 if ( $errors ) {
+                    $paymentError = true;
                     // Load DataClass for Management.
                     require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH .  '/data/dataManagement.php';
                     $Management = new GlmDataBillingManagement( $this->wpdb, $this->config );
@@ -473,6 +479,8 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
 
                     // Set the file name for the view file.
                     $view = 'makePayment';
+                } else {
+                    $paymentSuccess = true;
                 }
 
 
index 658e81d..f76d60d 100644 (file)
@@ -87,3 +87,17 @@ add_filter( 'glm-billing-get-account-status', function( $content, $account_id ){
     }
 
 },10, 2 );
+
+add_filter( 'glm-billing-account-has-renewal', function( $content, $account_id ){
+    // see if there's already a renewal invoice (not paid)
+    return $this->wpdb->get_var(
+        $this->wpdb->prepare(
+            "SELECT id
+               FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
+              WHERE account = %d
+                AND paid <> true
+                AND renewal is true",
+            $account_id
+        )
+    );
+}, 10, 2 );
index ba08d4d..267b92f 100644 (file)
@@ -65,6 +65,7 @@ CREATE TABLE {prefix}invoices (
     due_date DATE NOT NULL,                                -- Due date for this invoice
     paid BOOLEAN DEFAULT '0',                              -- true/false if invoice is paid
     notes TINYTEXT,                                        -- notes for this invoice
+    renewal BOOLEAN DEFAULT '0',                           -- true/false if a renewal
     recurring BOOLEAN DEFAULT '0',                         -- true/false if recurring
     recurrence INT NULL DEFAULT 0,                         -- recurrence type
     PRIMARY KEY (id),
index c12c896..8a31b8d 100644 (file)
@@ -33,5 +33,6 @@ $glmMembersBillingDbVersions = array(
     '0.0.17' => array('version' => '0.0.17', 'tables' => 14),
     '0.0.18' => array('version' => '0.0.18', 'tables' => 14),
     '0.0.19' => array('version' => '0.0.19', 'tables' => 14),
+    '0.0.20' => array('version' => '0.0.20', 'tables' => 14),
 );
 
diff --git a/setup/databaseScripts/update_database_V0.0.20.sql b/setup/databaseScripts/update_database_V0.0.20.sql
new file mode 100644 (file)
index 0000000..e4780ad
--- /dev/null
@@ -0,0 +1,9 @@
+-- Gaslight Media Billing Database
+-- File Created: 04/06/2018
+-- Database Version: 0.0.19
+--
+-- To permit each query below to be executed separately,
+-- all queries must be separated by a line with four dashes
+
+-- Add renewal
+ALTER TABLE {prefix}invoices ADD renewal BOOLEAN DEFAULT '0';  -- true/false if a renewal
index 63f8c69..e36a06b 100644 (file)
@@ -20,7 +20,7 @@
                     href="{$thisUrl}?page=glm-members-admin-menu-member&glm_action=billing&member={$memberID}"
                     class="">All Statements</a>
             </li>
-            {if $account_status == 'Pending' || $account_status == 'Expired'}
+            {if ($account_status == 'Pending' || $account_status == 'Expired') && !apply_filters('glm-billing-account-has-renewal', true, $accountID )}
             <li>
                 <a
                     href="{$thisUrl}?page=glm-members-admin-menu-member&glm_action=billing&member={$memberID}&option=renew"
index d34a929..c064940 100644 (file)
@@ -5,6 +5,36 @@
 
 <h2>Payments</h2>
 
+<form action="{$thisUrl}?page={$thisPage}" method="post" id="searchForm">
+    <input type="hidden" name="glm_action" value="payments">
+    <input type="hidden" name="option" value="list">
+
+    <input type="hidden" name="searched" value="1">
+    <input type="hidden" name="prevStart" value="{$prevStart}">
+    <input type="hidden" name="nextStart" value="{$nextStart}">
+    <input type="hidden" name="limit" value="{$limit}">
+        <div class="">
+            <span class="glm-nowrap">
+                <b>From Date: </b><input type="text" name="fromDate" value="{$fromDate}" class="glm-form-text-input-short glm-date-input">
+                <b>To Date: </b><input type="text" name="toDate" value="{$toDate}" class="glm-form-text-input-short glm-date-input">
+            </span>
+            <span class="glm-nowrap">
+                <b>Member Account:&nbsp;</b>
+                <input id="member-account" type="hidden" name="filterAccounts" value="{$filterAccounts}">
+                <input id="account_name" name="searchName" value="{if $searchName}{$searchName}{/if}" />
+            </span>
+        <br>
+            <span class="glm-nowrap">
+                <input type="submit" value="Submit">
+            </span>
+        </div>
+
+    {if $paging}
+        <input type="Submit" name="pageSelect" value="Previous {$limit} Accounts" class="button button-secondary glm-button"{if !$prevStart} disabled{/if}>
+        <input type="Submit" name="pageSelect" value="Next {$limit} Accounts" class="button button-secondary glm-button"{if !$nextStart} disabled{/if}>
+    {/if}
+        <br clear="all">
+
 <table class="wp-list-table widefat fixed posts glm-admin-table">
     <thead>
         <tr>
     </tbody>
 </table>
 
+{if $paging}
+    <input type="Submit" name="pageSelect" value="Previous {$limit} Accounts" class="button button-secondary glm-button"{if !$prevStart} disabled{/if}>
+    <input type="Submit" name="pageSelect" value="Next {$limit} Accounts" class="button button-secondary glm-button"{if !$nextStart} disabled{/if}>
+{/if}
+
+</form>
+
 <script type="text/javascript">
-    jQuery(document).ready(function($) {
+jQuery(document).ready(function($) {
+
+    // Date Input
+    $('.glm-date-input').datepicker({
+        dateFormat: 'mm/dd/yy'
+    });
+
+    var availableAccounts = [
+    {foreach $allAccounts as $m}
+        { label: "{$m.ref_name|unescape:'html'|replace:'"':''}", value: "{$m.ref_name|unescape:'html'|replace:'"':''}", id: '{$m.id}' },
+    {/foreach}
+    ]
 
+    // Setup autocomplete for both inputs
+    $('#account_name').autocomplete({
+        source: availableAccounts,
+        select: function( event, ui ){
+            $('#member-account').val( ui.item.id );
+            $('#searchForm').submit();
+        },
+        change: function( event, ui) {
+            if( ui.item == null ) {
+                $('#member-account').val( '' );
+                $('#searchForm').submit();
+            }
+        },
     });
+});
 </script>
 
 {include file='admin/footer.html'}