Add new Invoice now adds new account.
authorSteve Sutton <steve@gaslightmedia.com>
Tue, 6 Feb 2018 19:19:34 +0000 (14:19 -0500)
committerSteve Sutton <steve@gaslightmedia.com>
Tue, 6 Feb 2018 19:19:34 +0000 (14:19 -0500)
Can now add a billing account from the add invoice page.

models/admin/ajax/account.php [new file with mode: 0644]
models/admin/billing/invoices.php
models/admin/member/billing.php
setup/validActions.php
views/admin/billing/editInvoice.html

diff --git a/models/admin/ajax/account.php b/models/admin/ajax/account.php
new file mode 100644 (file)
index 0000000..856d9d5
--- /dev/null
@@ -0,0 +1,131 @@
+<?php
+
+/**
+ * Gaslight Media Members Database
+ * PDF Output by admin-ajax
+ *
+ * PHP version 5.5
+ *
+ * @category glmWordPressPlugin
+ * @package  glmMembersDatabase
+ * @author   Chuck Scott <cscott@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @version  0.1
+ */
+
+// Load Members data abstract
+require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/data/dataAccounts.php';
+
+/**
+ * This class performs the work of handling images passed to it via
+ * an AJAX call that goes through the WorPress AJAX Handler.
+ *
+ */
+class GlmMembersAdmin_ajax_account extends GlmDataAccounts
+{
+
+    /**
+     * WordPress Database Object
+     *
+     * @var $wpdb
+     * @access public
+     */
+    public $wpdb;
+    /**
+     * Plugin Configuration Data
+     *
+     * @var $config
+     * @access public
+     */
+    public $config;
+
+    /*
+     * Constructor
+     *
+     * This constructor sets up this model. At this time that only includes
+     * storing away the WordPress data object.
+     *
+     * @return object Class object
+     *
+     */
+    public function __construct ($wpdb, $config)
+    {
+
+        // Save WordPress Database object
+        $this->wpdb = $wpdb;
+
+        // Save plugin configuration object
+        $this->config = $config;
+
+        // Run constructor for data class
+        parent::__construct(false, false);
+
+    }
+
+    /*
+     * Perform Model Action
+     *
+     * This model checks to see if the credentials passed in are correct.
+     *
+     * This model action does not return, it simply does it's work then calls die();
+     *
+     * @param $actionData
+     *
+     * Output JSON string as response and does not return
+     */
+    public function modelAction( $actionData = false )
+    {
+        $return = false;
+
+        $option = filter_var( $_REQUEST['option'], FILTER_SANITIZE_STRING );
+        trigger_error( print_r( $_REQUEST, E_USER_NOTICE ) );
+
+        switch ( $option ) {
+        case 'add':
+            $account = $this->insertEntry();
+            trigger_error( print_r( $account, E_USER_NOTICE ) );
+            if ( !$account['status'] ) {
+                $accountInsertError = true;
+                $return = $account;
+            } else {
+                $accountAdded = true;
+                $return = array(
+                    'status' => true
+                );
+            }
+            break;
+        case 'list':
+            $accounts = $this->getList( '', 'ref_name', 'id,ref_name' );
+            $return = array();
+            foreach ( $accounts as $account ) {
+                $return[] = array(
+                    'id'       => $account['id'],
+                    'ref_name' => htmlspecialchars_decode( $account['ref_name'] )
+                );
+            }
+
+            break;
+        case 'listNonAccounts':
+            $nonAccountMembers = $this->wpdb->get_results(
+                "SELECT id,name
+                   FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+                  WHERE id NOT IN (
+                        SELECT distinct ref_dest
+                          FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX .  "accounts   )
+                ORDER BY name",
+                ARRAY_A
+            );
+            foreach ( $nonAccountMembers as $members ) {
+                $return[] = array(
+                    'id'   => $members['id'],
+                    'name' => htmlspecialchars_decode( $members['name'] )
+                );
+            }
+            break;
+        }
+
+        header( 'Content-type:application/json;charset=utf-8', true );
+        echo json_encode( $return, true );
+        exit();
+    }
+}
index c1c7979..bc83e53 100644 (file)
@@ -141,7 +141,7 @@ class GlmMembersAdmin_billing_invoices extends GlmDataInvoices
             $invoiceTypes    = $InvoiceTypesObj->sortParentChild($invoiceTypes);
             // Need to get the accounts
             $Accounts = new GlmDataAccounts( $this->wpdb, $this->config );
-            $accounts = $Accounts->getList();
+            $accounts = $Accounts->getList( '', 'ref_name' );
             // echo '<pre>$accounts: ' . print_r( $accounts, true ) . '</pre>';
 
             // Need a list of members that don't have an account.
index 9546c04..b9fb255 100644 (file)
@@ -171,7 +171,6 @@ class GlmMembersAdmin_member_billing // extends GlmDataBilling
             // 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']));
-                // echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
                 // if there's no id then add account.
                 if ( !isset( $_REQUEST['id'] ) ) {
                     $account = $Accounts->insertEntry();
index ad30ded..ce0161e 100644 (file)
@@ -62,6 +62,7 @@ $glmMembersBillingAddOnValidActions = array(
         'ajax' => array(
             'setupQueue' => GLM_MEMBERS_BILLING_PLUGIN_SLUG,
             'runQueue'   => GLM_MEMBERS_BILLING_PLUGIN_SLUG,
+            'account'    => GLM_MEMBERS_BILLING_PLUGIN_SLUG,
         ),
         'management' => array(
             'billing' => GLM_MEMBERS_BILLING_PLUGIN_SLUG,
index 16848d0..cbce92e 100644 (file)
@@ -6,7 +6,7 @@
 {if $invoiceUpdateError}<span class="glm-notice glm-flash-updated">Notification Update Error</span>{/if}
 {if $invoiceInsertError}<span class="glm-notice glm-flash-updated">Notification Insert Error</span>{/if}
 {if $invoiceAdded}<span class="glm-notice glm-flash-updated">Notification Added</span>{/if}
-
+{$ajaxUrl}
 <div id="billing-invoice-form">
     <form action="{$thisUrl}?page={$thisPage}&glm_action=invoices" method="post">
         {if $invoice_id}
@@ -26,7 +26,7 @@
                         <select id="member-account" name="account" required>
                             <option value="">Select an Account</option>
                             {foreach $accounts as $account}
-                            <option value="{$account.id}" data-anniversary="{$account.next_anniversary_date}">{$account.ref_name}</option>
+                                <option value="{$account.id}">{$account.ref_name}</option>
                             {/foreach}
                         </select>
                         <a id="newAccountButton" href="#">New Account</a>
 <div id="newAccountDialog" class="glm-dialog-box" title="New Account">
     <p class="validateAccountTips">* required.</p>
     <form id="addAccountForm">
-        <input type="hidden" name="glm_action" value="invoices">
-        <input type="hidden" name="option" value="addAccount">
         <table>
             <tr>
                 <th class="glm-required">Member</th>
                 <td>
-                    <select name="ref_dest" style="width: 300px;">
+                    <select id="non-member-account" name="ref_dest" style="width: 300px;">
                         <option value="">Select Member</option>
                         {foreach $nonAccountMembers as $m}
                         <option value="{$m.id}">{$m.name}</option>
                     </select>
                 </td>
             </tr>
+            <tr>
+                <th class="glm-required">Name</th>
+                <td>
+                    <input id="glm_member_name" type="text" name="ref_name" value="">
+                </td>
+            </tr>
             <tr>
                 <th class="glm-required">Anniversary Date</th>
                 <td>
@@ -189,6 +193,7 @@ jQuery(document).ready(function($){
         line_items       = [],                                   // Array holding line_items json objects
         allFields        = $( [] ).add( line_item_type ),        // Array holding the form fields - add line_item form
         ref_dest         = $( 'select[name="ref_dest"' ),
+        ref_name         = $( 'input[name="ref_name"' ),
         anniversary_date = $( 'input[name="anniversary_date"' ),
         renewal_date     = $( 'input[name="renewal_date"' ),
         email            = $( 'input[name="email"' ),
@@ -200,12 +205,17 @@ jQuery(document).ready(function($){
         billing_phone    = $( 'input[name="billing_phone"' ),
         lineTips         = $('.validateTips'),
         accountTips      = $('.validateAccountTips'),
-        allAccountFields = $( [] ).add( ref_dest ) .add( anniversary_date ) .add( renewal_date )
+        allAccountFields = $( [] ).add( ref_dest ) .add( ref_name ) .add( anniversary_date ) .add( renewal_date )
             .add( email ) .add( billing_addr1 ) .add( billing_addr2 ) .add( billing_city )
             .add( billing_state ) .add( billing_zip )
             .add( billing_phone ) ,        // Array holding the form fields - add line_item form
         invoiceTypeJSON  = $.parseJSON( '{$invoiceTypeJSON}' ); // Json object with all of the invoices types
 
+        // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
+       {literal}
+        var emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
+       {/literal}
+
     /**
      * totalInvoice
      *
@@ -293,12 +303,31 @@ jQuery(document).ready(function($){
         allAccountFields.removeClass( 'ui-state-error' );
 
         valid = valid && checkRequired( ref_dest, accountTips, 'Member is required!' );
+        valid = valid && checkRequired( ref_name, accountTips, 'Name is required!' );
         valid = valid && checkRequired( anniversary_date, accountTips, 'Anniversary Date is required!' );
         valid = valid && checkRequired( email, accountTips, 'Email is required!' );
+        valid = valid && checkRegexp( email, emailRegex, 'Use valid email!' );
 
         if ( valid ) {
-
-        } else {
+            // console.log( newAccountForm.serialize() );
+            $.ajax({
+                url: '{$ajaxUrl}?action=glm_members_admin_ajax&glm_action=account&option=add',
+                cache: false,
+                type: 'POST',
+                data: newAccountForm.serialize(),
+                encode: true,
+                dataType: 'json'
+            }).done(function( msg ){
+                if ( msg.status === true ) {
+                    // Reload the account select
+                    updateBillingAccountSelect();
+                    updateNonAccountMemberSelect();
+                    // Close the dialog
+                    newAccountDialog.dialog( 'close' );
+                } else {
+                    console.log( 'return', msg );
+                }
+            });
         }
 
         return valid;
@@ -323,6 +352,16 @@ jQuery(document).ready(function($){
         }
     }
 
+    function checkRegexp( fieldName, regexp, message ) {
+        if ( !( regexp.test( fieldName.val() ) ) ) {
+            fieldName.addClass( 'ui-state-error' );
+            updateTips( accountTips, message );
+            return false;
+        } else {
+            return true;
+        }
+    }
+
 
     function updateTips( tips, t ) {
         tips
@@ -333,6 +372,50 @@ jQuery(document).ready(function($){
         }, 500);
     }
 
+    /**
+     * Ajax call to get the list of billing accounts and update the select
+     * for the Billing account drop down.
+     */
+    function updateBillingAccountSelect() {
+        $.ajax({
+            url: '{$ajaxUrl}',
+            cache: false,
+            type: 'GET',
+            data: 'action=glm_members_admin_ajax&glm_action=account&option=list',
+            encode: true,
+            dataType: 'json'
+        }).done(function(msg){
+            // console.log( msg.length );
+            var memberAccount = document.getElementById('member-account');
+            memberAccount.options.length = 0;
+            memberAccount.options[memberAccount.options.length] = new Option( 'Select an Account', '' );
+            for ( index in msg ) {
+                var obj = msg[index];
+                memberAccount.options[memberAccount.options.length] = new Option( obj.ref_name, obj.id );
+            }
+        });
+    }
+
+    function updateNonAccountMemberSelect() {
+        $.ajax({
+            url: '{$ajaxUrl}',
+            cache: false,
+            type: 'GET',
+            data: 'action=glm_members_admin_ajax&glm_action=account&option=listNonAccounts',
+            encode: true,
+            dataType: 'json'
+        }).done(function(msg){
+            // console.log( msg.length );
+            var nonMemberAccount = document.getElementById('non-member-account');
+            nonMemberAccount.options.length = 0;
+            nonMemberAccount.options[nonMemberAccount.options.length] = new Option( 'Select Member', '' );
+            for ( index in msg ) {
+                var obj = msg[index];
+                nonMemberAccount.options[nonMemberAccount.options.length] = new Option( obj.name, obj.id );
+            }
+        });
+    }
+
     /**
      * dialog
      *
@@ -412,7 +495,8 @@ jQuery(document).ready(function($){
      *
      * Activates the dialog for adding line items.
      */
-    $('#newAccountButton').click( function() {
+    $('#newAccountButton').click( function(e) {
+        e.preventDefault();
         $("#newAccountDialog").dialog("open");
         return false;
     });
@@ -442,6 +526,10 @@ jQuery(document).ready(function($){
         $('#invoice_due_date').val( $(this).find('option:selected').data('anniversary') );
     });
 
+    $('#non-member-account').change(function(){
+        $('#glm_member_name').val( $(this).find('option:selected').text() );
+    });
+
     // Flash certain elements for a short time after display
     $(".glm-flash-updated").fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500);