Finish the create Invoice for MiGCSA
authorSteve Sutton <steve@gaslightmedia.com>
Fri, 16 Mar 2018 15:12:10 +0000 (11:12 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Fri, 16 Mar 2018 15:12:10 +0000 (11:12 -0400)
Pull data from migcsa current site and create invoices.

classes/data/dataAccounts.php
models/admin/management/billing.php
models/admin/management/createInvoices.php [new file with mode: 0644]
models/admin/management/import.php [deleted file]
views/admin/management/createInvoices.html

index 220bb7a..f45f73c 100644 (file)
@@ -258,7 +258,7 @@ class GlmDataAccounts extends GlmDataAbstract
     public function entryPostProcessing($r, $a)
     {
         // Setup the accounts anniversary date
-        $current_date = mktime( 0, 0, 0, date( 'd' ), date( 'n' ), date( 'Y' ) );
+        $current_date = mktime( 0, 0, 0, date( 'n' ), date( 'j' ), date( 'Y' ) );
         if ( $r['anniversary_date'] ) {
             // Need to find the next (current) date for this account's
             // anniversary
@@ -270,14 +270,12 @@ class GlmDataAccounts extends GlmDataAbstract
                 // Make the year current year.
                 $year = date( 'Y' );
                 // If the month and day have already occurred then add a year.
-                $test_date = mktime( 0, 0, 0, date( 'n', $anniversary ), date( 'd', $anniversary ), $year );
+                $test_date = mktime( 0, 0, 0, date( 'n', $anniversary ), date( 'j', $anniversary ), $year );
                 if ( $test_date <= $current_date ) {
-                    $test_date = mktime( 0, 0, 0, date( 'n', $anniversary ), date( 'd', $anniversary ), $year );
+                    $year++;
+                    $test_date = mktime( 0, 0, 0, date( 'n', $anniversary ), date( 'j', $anniversary ), $year );
                 }
-                $r['next_anniversary_date'] = date( 'm/d/Y', $test_date);
-                // $anniversary_date = new DateTime( $r['anniversary_date']['mysql_date'] );
-                // $anniversary_date->modify('+1 year');
-                // $r['next_anniversary_date'] = $anniversary_date->format('m/d/Y');
+                $r['next_anniversary_date'] = date( 'm/d/Y', $test_date );
             }
         }
         return $r;
index 37c05dd..2bbf0f1 100644 (file)
@@ -106,7 +106,7 @@ class GlmMembersAdmin_management_billing extends GlmDataBillingManagement
      * @access public
      * @return void
      */
-    public function modelAction($actionData = false)
+    public function modelAction( $actionData = false )
     {
 
         $option              = false;
@@ -114,12 +114,15 @@ class GlmMembersAdmin_management_billing extends GlmDataBillingManagement
         $settingsUpdateError = false;
         $regSettings         = false;
         $view                = 'billing';
+        $importResults       = false;
+        $totalMembers        = false;
+        $numberProcessed     = false;
 
         // General settings are always stored in a record with ID=1.
         $id = 1;
 
         // Determine if current user can edit configurations
-        if (!current_user_can('glm_members_management')) {
+        if ( !current_user_can( 'glm_members_management' ) ) {
             return array(
                 'status'           => false,
                 'menuItemRedirect' => 'error',
@@ -133,7 +136,7 @@ class GlmMembersAdmin_management_billing extends GlmDataBillingManagement
 
         // Check for submission option
         $option = '';
-        if (isset($_REQUEST['option'])) {
+        if ( isset( $_REQUEST['option'] ) ) {
             $option = $_REQUEST['option'];
         }
 
@@ -163,6 +166,19 @@ class GlmMembersAdmin_management_billing extends GlmDataBillingManagement
 
             case 'createInvoices':
                 $view = 'createInvoices';
+                if ( isset( $_REQUEST['option2'] ) ) {
+                    $option2 = $_REQUEST['option2'];
+                }
+                if ( !isset( $option2 ) ) {
+                    $option2 = '';
+                }
+                switch ( $option2 ) {
+                case 'create':
+                    require_once GLM_MEMBERS_BILLING_PLUGIN_PATH.'/models/admin/management/createInvoices.php';
+                    break;
+                default:
+                    break;
+                }
                 break;
 
             // Default is to get the current settings and display the form
@@ -199,10 +215,12 @@ class GlmMembersAdmin_management_billing extends GlmDataBillingManagement
             'settingsUpdated'     => $settingsUpdated,
             'settingsUpdateError' => $settingsUpdateError,
             'option'              => $option,
+            'importResults'       => $importResults,
+            'totalMembers'        => $totalMembers,
+            'numberProcessed'     => $numberProcessed,
+            'start'               => ( isset( $start ) ? $start : false ),
         );
 
-        // echo "<pre>" . print_r($regSettings, true) . "</pre>";
-
         // Return status, suggested view, and data to controller
         return array(
             'status'           => true,
diff --git a/models/admin/management/createInvoices.php b/models/admin/management/createInvoices.php
new file mode 100644 (file)
index 0000000..22cad8d
--- /dev/null
@@ -0,0 +1,181 @@
+<?php
+/**
+ * Create Invoices (MiGCSA)
+ */
+// For billing support functions
+require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/billingSupport.php';
+$BillingSupport = new GlmBillingSupport( $this->wpdb, $this->config );
+
+// For invoices
+require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/data/dataInvoices.php';
+$Invoice = new GlmDataInvoices( $this->wpdb, $this->config );
+
+// For Accounts
+require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/data/dataAccounts.php';
+$Account = new GlmDataAccounts( $this->wpdb, $this->config );
+
+// Get all Invoice Types
+require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/data/dataInvoiceTypes.php';
+$InvoiceTypes  = new GlmDataInvoiceTypes( $this->wpdb, $this->config );
+$invoiceTypes  = $InvoiceTypes->getList();
+$importResults = '<pre>$invoice_line_items: ' . print_r( $invoice_line_items, true ) . '</pre>';
+
+// Connect to their live database.
+$dbh = new PDO(
+    'pgsql: host=ds4.gaslightmedia.com dbname=migcsa2_update user=nobody',
+    null,
+    null,
+    array(
+        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
+    )
+);
+
+$dbh->setAttribute(
+    PDO::ATTR_ERRMODE,
+    PDO::ERRMODE_EXCEPTION
+);
+
+// These are the member class that need to be used for creating invoices
+// All the other member classes are free.
+$paid_classes = array(
+    'A',
+    'AFF',
+    'C',
+    'EM',
+    'R',
+    'SA',
+    'SM'
+);
+
+if ( isset( $_REQUEST['start'] ) && $start = filter_var( $_REQUEST['start'], FILTER_VALIDATE_INT ) ) {
+} else {
+    $start = 0;
+}
+
+$importResults = '';
+// Get total number of members.
+$sql = "
+SELECT count(member_id) as total
+FROM member
+WHERE member_id IN (
+    SELECT member_id
+      FROM member_category
+     WHERE category_id IN (40,42))
+  AND member_class in ('" . implode( "','", $paid_classes ) . "')";
+$totalStmt      = $dbh->query( $sql );
+$totalMembers   = $totalStmt->fetchColumn();
+$importResults .= 'Total Members: ' . $totalMembers . "<br>";
+
+// Need to get all members from old database that are in Members 2017 and Member 2018 categories.
+$sql = "
+SELECT member_id,member_name,join_date,renew_date,member_class
+FROM member
+WHERE member_id IN (
+    SELECT member_id
+      FROM member_category
+     WHERE category_id IN (40,42))
+  AND member_class in ('" . implode( "','", $paid_classes ) . "')
+ORDER BY renew_date DESC
+LIMIT 10
+OFFSET $start";
+$stmt = $dbh->query( $sql );
+$members = $stmt->fetchAll();
+$numberMembers = count( $members );
+
+$importResults .= 'Total Members this round: ' . count( $members ) . "<br>";
+
+if ( $start === 0 ) {
+    // Clear the invoices,line_items and transactions
+    $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices" );
+    $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "line_items" );
+    $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "transactions" );
+}
+
+foreach ( $members as $member ) {
+    // $importResults .= '<pre>$member: ' . print_r( $member, true ) . '</pre>';
+    // Find the invoice type needed for this member based on their member_class.
+    $invoiceTypeId = $this->wpdb->get_var(
+        "SELECT id
+           FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoice_types
+          WHERE name like 'Class " . $member['member_class'] . "%'"
+    );
+    // $importResults .= '<pre>$invoiceTypeId: ' . print_r( $invoiceTypeId, true ) . '</pre>';
+    // $importResults .= '<pre>$member: ' . print_r( $member, true ) . '</pre>';
+    // We need to get the ref_dest for this member
+    $ref_dest = $this->wpdb->get_var(
+        $this->wpdb->prepare(
+            "SELECT id
+               FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+              WHERE old_member_id = %d",
+            $member['member_id']
+        )
+    );
+    // $importResults .= '<pre>$ref_dest: ' . print_r( $ref_dest, true ) . '</pre>';
+    // Get this members account
+    // $account = $BillingSupport->getAccountByRefDest( $ref_dest );
+    $account_id = $this->wpdb->get_var(
+        $this->wpdb->prepare(
+            "SELECT *
+               FROM "  . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts
+              WHERE ref_dest = %d",
+            $ref_dest
+        )
+    );
+    // $importResults .= '<pre>$account_id: ' . print_r( $account_id, true ) . '</pre>';
+    // Check on the account next_anniversary_date
+    $account = $Account->getEntry( $account_id );
+
+    if ( $invoiceTypeId && $account ) {
+        $next_anniversary_date = $account['next_anniversary_date'];
+        // $importResults        .= '<pre>$next_anniversary_date: ' . print_r( $next_anniversary_date, true ) . '</pre>';
+
+        // $importResults .= '<pre>$invoiceTypeId: ' . print_r( $invoiceTypeId, true ) . '</pre>';
+        // Now that we have the invoiceTypeId we can add an invoice for this member.
+        // Steps
+        // 1) Create the invoice
+        $_REQUEST['account']          = $account['id'];
+        $_REQUEST['transaction_time'] = date('Y-m-d H:i:s');
+        $_REQUEST['due_date']         = $account['next_anniversary_date'];
+        $invoice                      = $Invoice->insertEntry();
+        // $importResults .= '<pre>$invoice: ' . print_r( $invoice, true ) . '</pre>';
+        $invoice_id                   = $invoice['fieldData']['id'];
+        // 2) Create line items
+        if ( $invoice_id ) {
+            $this->wpdb->insert(
+                GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'line_items',
+                array(
+                    'invoice'        => $invoice_id,
+                    'line_item_type' => $invoiceTypeId,
+                    'name'           => $invoiceTypes[$invoiceTypeId]['name'],
+                    'amount'         => $invoiceTypes[$invoiceTypeId]['amount'],
+                    'quantity'       => 1,
+                    'total'          => $invoiceTypes[$invoiceTypeId]['amount'],
+                    'created'        => date('Y-m-d'),
+                    'first_due_date' => date( 'Y-m-d', strtotime( $next_anniversary_date) ),
+                    'next_due_date'  => date( 'Y-m-d', strtotime( $next_anniversary_date) ),
+                    'recurring'      => $invoiceTypes[$invoiceTypeId]['recurring']['value'],
+                    'recurrence'     => $invoiceTypes[$invoiceTypeId]['recurrence']
+                ),
+                array(
+                    '%d', // invoice
+                    '%d', // line_item_type
+                    '%s', // name
+                    '%s', // amount
+                    '%d', // quantity
+                    '%d', // total
+                    '%s', // created
+                    '%s', // first_due_date
+                    '%s', // next_due_date
+                    '%d', // recurring
+                    '%d', // recurrence
+                )
+            );
+        }
+        // 3) Generate Invoice Total
+        $totals = $Invoice->generateInvoiceTotal( $invoice_id );
+        // 4) Record Invoice
+        $BillingSupport->recordInvoice( $invoice_id, $account['id'], $totals['amount_total'] );
+    }
+}
+
+$numberProcessed = $start + 10;
diff --git a/models/admin/management/import.php b/models/admin/management/import.php
deleted file mode 100644 (file)
index 3c40dce..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-<?php
-/**
- * Gaslight Media Members Database
- * GLM Members DB - Billing Add-on - Management Billing Tab
- *
- * PHP version 5.5
- *
- * @category glmWordPressPlugin
- * @package  glmMembersDatabase
- * @author     Chuck Scott <cscott@gaslightmedia.com>
- * @license  http://www.gaslightmedia.com Gaslightmedia
- * @release  billing.php,v 1.0 2014/10/31 19:31:47 cscott Exp $
- * @link     http://dev.gaslightmedia.com/
- */
-
-// Load Management Billing data abstract
-require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH.'/data/dataManagement.php';
-
-/**
- * GlmMembersAdmin_management_import
- *
- * PHP version 5
- *
- * @category Model
- * @package GLM Member DB
- * @author    Chuck Scott <cscott@gaslightmedia.com>
- * @license http://www.gaslightmedia.com Gaslightmedia
- *            @release SVN: $Id: packaging.php,v 1.0 2011/01/25 19:31:47 cscott
- *            Exp $
- */
-class GlmMembersAdmin_management_import // extends GlmDataBillingManagement
-{
-
-    /**
-     * WordPress Database Object
-     *
-     * @var $wpdb
-     * @access public
-     */
-    public $wpdb;
-    /**
-     * dbh Postgres database connection
-     *
-     * @var mixed
-     * @access public
-     */
-    public $config;
-    /**
-     * settings used for the schema and tablenames
-     *
-     * @var mixed
-     * @access public
-     */
-//    public $settings = array();
-//    /**
-//     * billing
-//     *
-//     * @var bool
-//     * @access public
-//     */
-//    public $billing = array();
-
-    /**
-     * Constructor
-     *
-     * This contructor performs the work for this model. This model returns
-     * an array containing the following.
-     *
-     * 'status'
-     *
-     * True if successfull and false if there was a fatal failure.
-     *
-     * 'view'
-     *
-     * A suggested view name that the contoller should use instead of the
-     * default view for this model or false to indicate that the default view
-     * should be used.
-     *
-     * 'data'
-     *
-     * Data that the model is returning for use in merging with the view to
-     * produce output.
-     *
-     * @wpdb object WordPress database object
-     *
-     * @return array Array containing status, suggested view, and any data
-     */
-    public function __construct ($wpdb, $config)
-    {
-
-        // Save WordPress Database object
-        $this->wpdb = $wpdb;
-
-        // Save plugin configuration object
-        $this->config = $config;
-
-        // Run constructor for members data class
-        // parent::__construct(false, false);
-
-    }
-
-    /**
-     * modelAction
-     *
-     * @param bool $actionData
-     * @access public
-     * @return void
-     */
-    public function modelAction($actionData = false)
-    {
-
-        $option        = false;
-        $importResults = importResults;
-
-        // General settings are always stored in a record with ID=1.
-        $id = 1;
-
-        // Determine if current user can import billing
-        if (!current_user_can('glm_members_management')) {
-            return array(
-                'status'           => false,
-                'menuItemRedirect' => 'error',
-                'modelRedirect'    => 'index',
-                'view'             => 'admin/error/index.html',
-                'data'             => array(
-                    'reason' => 'User does not have rights to import.'
-                )
-            );
-        }
-
-        // Check for submission option
-        $option = '';
-        if (isset($_REQUEST['option']) && $_REQUEST['option'] == 'submit') {
-            $option = $_REQUEST['option'];
-        }
-
-        switch( $option ) {
-
-            // Update the settings and redisplay the form
-            case 'submit':
-
-                break;
-
-            // Default is to get the current settings and display the form
-            default:
-
-                break;
-
-        }
-
-        // Compile template data
-        $template_data = array(
-            'importResults' => $importResults,
-        );
-
-        // Return status, suggested view, and data to controller
-        return array(
-            'status'           => true,
-            'menuItemRedirect' => false,
-            'modelRedirect'    => false,
-            'view'             => 'admin/management/import.html',
-            'data'             => $template_data
-        );
-    }
-}
-?>
index a127aea..4a476ac 100644 (file)
@@ -2,7 +2,36 @@
 
 {include file='admin/management/subHeader.html'}
 
-<table class="glm-admin-table glm-settings-table">
-</table>
+{if $importResults}
+    {$importResults}
+{else}
+    <form action="{$thisUrl}?page={$thisPage}" method="post">
+
+        <input type="hidden" name="glm_action" value="billing" />
+        <input type="hidden" name="option" value="createInvoices" />
+        <input type="hidden" name="option2" value="create" />
+
+        <table class="glm-admin-table glm-settings-table">
+
+            <tr>
+                <td><input type="submit" value="Create Invoices for MiGCSA" /></td>
+            </tr>
+
+        </table>
+    </form>
+{/if}
+
+Number processed: {$numberProcessed}
+
+{if $numberProcessed < $totalMembers}
+<script>
+jQuery(document).ready(function($){
+
+    window.location.href = '{$thisUrl}?page={$thisPage}&glm_action=billing&option=createInvoices&option2=create&start={$numberProcessed}';
+
+});
+
+</script>
+{/if}
 
 {include file='admin/management/footer.html'}