Updating import data scripts for uptravel
authorSteve Sutton <steve@gaslightmedia.com>
Thu, 28 Mar 2019 09:48:25 +0000 (05:48 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Thu, 28 Mar 2019 09:49:21 +0000 (05:49 -0400)
Fixing the import scripts for billing accounts and data imports.

classes/billingSupport.php
models/admin/billing/invoicing.php
models/admin/billing/reports.php
models/admin/management/importAccounts.php
models/admin/management/importBillingData.php
models/admin/management/verifyBillingData.php
setup/databaseScripts/create_database_V0.0.32.sql [new file with mode: 0644]

index b3a39b5..5727936 100644 (file)
@@ -118,6 +118,7 @@ class GlmBillingSupport
                 // Get the invoice
                 $invoice = $this->getInvoiceById( $invoice_id );
                 $balance = (float)$invoice['balance'];
+                // echo '<pre>invoice_id: ' . $invoice_id . ' payment_id: ' . $payment_id . ' $balance: ' . $balance . '</pre>';
                 if ( $payment == $invoice['balance'] ) {
                     $payment -= $invoice['balance'];
                     // Mark this as paid then
@@ -578,7 +579,7 @@ class GlmBillingSupport
             $this->wpdb->prepare(
                 "SELECT *
                    FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
-                  WHERE paid <> true
+                  WHERE ( paid <> true OR paid IS NULL )
                     AND account = %d
                   ORDER BY transaction_time ASC",
                 $account
@@ -634,7 +635,7 @@ class GlmBillingSupport
         return $this->wpdb->get_results(
             "SELECT *
                FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
-              WHERE paid <> true
+              WHERE ( paid <> true OR paid IS NULL )
               ORDER BY transaction_time ASC",
             ARRAY_A
         );
@@ -703,7 +704,7 @@ class GlmBillingSupport
         $balance_due = (float)0.00;
         $invoices = $this->getUnPaidInvoicesByAccount( $account );
         foreach ( $invoices as $invoice ) {
-            $balance_due += (float)$invoice['balance'];
+            $balance_due += (float)$invoice['amount_total'];
         }
         return $balance_due;
     }
index 0de351f..4e63ef4 100644 (file)
@@ -115,6 +115,9 @@ class GlmMembersAdmin_billing_invoicing //extends GlmDataAccounts
         $BillingSupport = new GlmBillingSupport( $this->wpdb, $this->config );
         $Accounts       = new GlmDataAccounts( $this->wpdb, $this->config );
 
+        // Not paid query
+        $notPaid = "( paid <> true OR paid IS NULL )";
+
         if ( isset( $_REQUEST['invoice_types'] ) ) {
             $invoiceTypes = $_REQUEST['invoice_types'];
             $wParts[] = " T.invoice_type IN (" . implode(',', $invoiceTypes) . ") ";
@@ -136,7 +139,7 @@ class GlmMembersAdmin_billing_invoicing //extends GlmDataAccounts
             $wParts[] = " T.id IN (
                 SELECT account
                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX  . "invoices
-                 WHERE paid <> true ) ";
+                 WHERE $notPaid ) ";
             $wParts[] = " ( T.usmail_invoice OR T.fax_invoice ) ";
             break;
 
@@ -145,7 +148,7 @@ class GlmMembersAdmin_billing_invoicing //extends GlmDataAccounts
                 $wParts[] = " T.id IN (
                     SELECT account
                       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX  . "invoices
-                     WHERE paid <> true ) ";
+                     WHERE $notPaid ) ";
             } else {
                 $wParts[] = " T.id IN (
                     SELECT account
@@ -205,7 +208,7 @@ class GlmMembersAdmin_billing_invoicing //extends GlmDataAccounts
             $wParts[] = " T.id IN (
                 SELECT account
                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX  . "invoices
-                 WHERE paid <> true ) ";
+                 WHERE $notPaid ) ";
             $wParts[] = " ( T.email_invoice ) ";
 
             $type = $this->config['transaction_numb']['Invoice'];
index 60a5084..d092f01 100644 (file)
@@ -175,6 +175,7 @@ class GlmMembersAdmin_billing_reports extends GlmDataTransactions
         // Do selected option
         switch ($option) {
         case 'accountsByAge':
+            // This query is based on the data class of Accounts
             $wParts[] = "T.id IN (
                 SELECT account
                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
@@ -185,6 +186,7 @@ class GlmMembersAdmin_billing_reports extends GlmDataTransactions
             break;
 
         case 'closedAccounts':
+            // This query is based on the data class of Accounts
             $wParts[] = "T.id IN (
                 SELECT account
                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
@@ -219,6 +221,7 @@ class GlmMembersAdmin_billing_reports extends GlmDataTransactions
 
         case 'openAccounts':
         default:
+            // This query is based on the data class of Accounts
             $wParts[] = "T.id IN (
                 SELECT account
                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
@@ -254,6 +257,7 @@ class GlmMembersAdmin_billing_reports extends GlmDataTransactions
             $Accounts->paymentTypes = true;
             $Accounts->balanceDue   = true;
             $accountsResult         = $Accounts->getList( $where, $orderBy, true, 'id', $start, $limit );
+            // echo '<pre>'.print_r($accountsResult, true).'</pre>';
             $totalAccounts          = $Accounts->getStats( $where );
             $Accounts->paymentTypes = false;
             $Accounts->balanceDue   = false;
index 383df98..a03ae37 100644 (file)
@@ -92,8 +92,10 @@ function addPaymentType( $wpdb, $data )
 }
 
 // Connect to their live database.
+// $dbConn = 'pgsql: host=ds5.gaslightmedia.com dbname=uptravel user=postgres';
+$dbConn = 'pgsql: dbname=uptravel user=postgres';
 $dbh = new PDO(
-    'pgsql: host=ds5.gaslightmedia.com dbname=uptravel user=nobody',
+    $dbConn,
     null,
     null,
     array(
@@ -134,7 +136,7 @@ LEFT OUTER JOIN members.member_account MA ON ( MA.member_id = M.member_id )
 LEFT OUTER JOIN members.payment_types PT ON ( MA.payment_type = PT.id )
  WHERE PT.name != ''
    AND PT.name IS NOT NULL
-   AND (M.type = 'full' OR M.type = 'enhanced')
+   -- AND (M.type = 'full' OR M.type = 'enhanced')
 ";
 $totalStmt      = $dbh->query( $sql );
 $totalMembers   = $totalStmt->fetchColumn();
@@ -151,7 +153,7 @@ LEFT OUTER JOIN members.member_account MA ON ( MA.member_id = M.member_id )
 LEFT OUTER JOIN members.payment_types PT ON ( MA.payment_type = PT.id )
  WHERE PT.name != ''
    AND PT.name IS NOT NULL
-   AND (M.type = 'full' OR M.type = 'enhanced')
+  -- AND (M.type = 'full' OR M.type = 'enhanced')
 ORDER BY M.member_id";
 
 //LIMIT 10
index 63f329b..87419b6 100644 (file)
@@ -7,9 +7,11 @@ require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/billingSupport.php';
 $BillingSupport = new GlmBillingSupport( $this->wpdb, $this->config );
 
 $limit = 10;
+// $dbConn = 'pgsql: host=ds5.gaslightmedia.com dbname=uptravel user=postgres';
+$dbConn = 'pgsql: dbname=uptravel user=postgres';
 // Connect to their live database.
 $dbh = new PDO(
-    'pgsql: host=ds5 dbname=uptravel user=postgres',
+    $dbConn,
     null,
     null,
     array(
@@ -19,47 +21,55 @@ $dbh = new PDO(
 
 $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
 
+
 if ( isset( $_REQUEST['start'] ) && $start = filter_var( $_REQUEST['start'], FILTER_VALIDATE_INT ) ) {
+    $numberProcessed = $start;
 } else {
-    $start = 0;
+    $start           = 0;
+    $numberProcessed = 0;
 }
 
 $importResults = '';
+$currentSelect = "A.id,A.ref_dest,M.old_member_id";
+$statSelect = "count(A.id)";
 
-// Get records.
-$sqlWhere = "";
-// $sqlWhere = "
-//  WHERE invoice_id IN (
-//        SELECT invoice_id
-//          FROM members.billing
-//         WHERE billing_type = 1
-//          -- AND transaction_time >= '2017-01-01'
-//         ORDER BY transaction_date,transaction_time)
-//    AND billing_type IN (1,2,3)
-// ";
-$mainSql = "
-SELECT *
-  FROM members.billing
-$sqlWhere
- ORDER BY transaction_date,transaction_time
- LIMIT $limit
+$currentSql =
+    "SELECT $currentSelect
+       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts A
+            LEFT OUTER JOIN " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members M ON ( A.ref_dest = M.id )
+    ORDER BY M.old_member_id
+LIMIT $limit
 OFFSET $start";
+// WHERE A.id = 51
 
-$statsSql = "SELECT count(*)
-  FROM members.billing
-$sqlWhere";
+$statSql =
+    "SELECT $statSelect
+       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts A
+            LEFT OUTER JOIN " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members M ON ( A.ref_dest = M.id )
+    ORDER BY M.old_member_id";
 
-$stmt            = $dbh->query( $mainSql );
-$billingRecords  = $stmt->fetchAll();
-$statsStmt       = $dbh->query( $statsSql );
-$totalImports    = $statsStmt->fetchColumn();
-$numberProcessed = $start;
+$currentAccounts = $this->wpdb->get_results( $currentSql, ARRAY_A );
+$totalImports    = $this->wpdb->get_var( $statSql );
 
 $importResults .= '<pre>$totalImports: ' . print_r( $totalImports, true ) . '</pre>';
-// return;
-// exit;
+// $importResults .= '<pre>' . print_r( $currentAccounts, true ) . '</pre>';
+
+$billingStmtSql = "
+SELECT id,invoice_id,transaction_time,transaction_date,member_name,member_id,account_id,
+       account_number,billing_type,amount,balance,payment_method,payment_data,emailed,
+       printed,paid,notes
+  FROM members.billing
+WHERE member_id = :member_id
+ORDER BY transaction_date,transaction_time";
+$getBilling = $dbh->prepare( $billingStmtSql );
 
-// $importResults .= '<pre>$billingRecords: ' . print_r( $billingRecords, true ) . '</pre>';
+$billingRecords = array();
+
+foreach ( $currentAccounts as $account ) {
+    $getBilling->bindParam( ':member_id', $account['old_member_id'], PDO::PARAM_INT );
+    $getBilling->execute();
+    $billingRecords[$account['ref_dest']] = $getBilling->fetchAll();
+}
 
 if ( $start === 0 ) {
     // Clear the invoices,line_items and transactions
@@ -68,170 +78,182 @@ if ( $start === 0 ) {
     $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "transactions" );
     $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "payments" );
     $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoice_payments" );
+
+    // $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoice_payments
+    //     WHERE invoice IN (
+    //         SELECT id
+    //           FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices WHERE account = 51 )" );
+    // $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices WHERE account = 51" );
+    // $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "line_items WHERE account = 51" );
+    // $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "transactions WHERE account = 51" );
+    // $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "payments WHERE account = 51" );
 }
 
+
 if ( $billingRecords ) {
-    foreach ( $billingRecords as $billingRecord ) {
-        // Have to get the member id and then get it's new account id
-        $refDest = $this->wpdb->get_var(
-            $this->wpdb->prepare(
-                "SELECT id
-                   FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
-                  WHERE old_member_id = %d",
-                $billingRecord['member_id']
-            )
-        );
-        if ( $refDest ) {
-            $account = $BillingSupport->getAccountByRefDest( $refDest );
-            // $importResults .= '<pre>$account: ' . print_r( $account, true ) . '</pre>';
-            if ( $account ) {
-                // Get the invoice Type
-                $invoiceType = $BillingSupport->getInvoiceTypeById( $account['invoice_type'] );
-                // $importResults .= '<pre>$invoiceType: ' . print_r( $invoiceType, true ) . '</pre>';
-                if ( $invoiceType ) {
-                    $numberProcessed++;
-                    // Check the type (1 = invoice, 2 = payment, 3 = Adjustment, 4 = Comment)
-                    switch ( $billingRecord['billing_type']) {
-                    case "1": // Invoices
-                        // Store the invoice
-                        $this->wpdb->insert(
-                            GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'invoices',
-                            array(
-                                'transaction_time' => $billingRecord['transaction_time'],
-                                'account'          => $account['id'],
-                                'old_invoice_id'   => $billingRecord['invoice_id'],
-                                'amount_total'     => $billingRecord['amount'],
-                                'balance'          => $billingRecord['balance'],
-                                'due_date'         => $billingRecord['transaction_date'],
-                                'paid'             => $billingRecord['paid'],
-                                'notes'            => $billingRecord['notes'],
-                                'renewal'          => true,
-                                'recurring'        => true,
-                                'recurrence'       => 20
-                            ),
-                            array(
-                                '%s', // transaction_time
-                                '%d', // account
-                                '%d', // old_invoice_id
-                                '%s', // amount
-                                '%s', // balance
-                                '%s', // due_date
-                                '%s', // paid
-                                '%s', // notes
-                                '%s', // renewal
-                                '%s', // recurring
-                                '%s', // recurrence
-                            )
-                        );
-                        $newInvoiceId = $this->wpdb->insert_id;
-                        if ( $newInvoiceId ) {
+    foreach ( $billingRecords as $refDest => $billingRows ) {
+       foreach ( $billingRows as $billingRecord ) {
+            if ( $refDest ) {
+                $account = $BillingSupport->getAccountByRefDest( $refDest );
+                // $importResults .= '<pre>$account: ' . print_r( $account, true ) . '</pre>';
+                if ( $account ) {
+                    // Get the invoice Type
+                    $invoiceType = $BillingSupport->getInvoiceTypeById( $account['invoice_type'] );
+                    // $importResults .= '<pre>$invoiceType: ' . print_r( $invoiceType, true ) . '</pre>';
+                    if ( $invoiceType ) {
+                        $numberProcessed++;
+                        // Check the type (1 = invoice, 2 = payment, 3 = Adjustment, 4 = Comment)
+                        switch ( $billingRecord['billing_type'] ) {
+                        case "1": // Invoices
+                            // Store the invoice
+                            $this->wpdb->show_errors();
                             $this->wpdb->insert(
-                                GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'line_items',
+                                GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'invoices',
                                 array(
-                                    'invoice'        => $newInvoiceId,
-                                    'line_item_type' => $invoiceType['id'],
-                                    'account'        => $account['id'],
-                                    'name'           => $invoiceType['name'],
-                                    'amount'         => $billingRecord['amount'],
-                                    'quantity'       => 1,
-                                    'total'          => $billingRecord['amount'],
-                                    'created'        => $billingRecord['transaction_time'],
-                                    'first_due_date' => $billingRecord['transaction_date'],
-                                    'next_due_date'  => $billingRecord['transaction_date'],
-                                    'recurring'      => $invoiceType['recurring'],
-                                    'recurrence'     => $invoiceType['recurrence']
+                                    'transaction_time' => $billingRecord['transaction_time'],
+                                    'account'          => $account['id'],
+                                    'old_invoice_id'   => $billingRecord['invoice_id'],
+                                    'amount_total'     => $billingRecord['amount'],
+                                    'balance'          => $billingRecord['balance'],
+                                    'due_date'         => $billingRecord['transaction_date'],
+                                    'paid'             => $billingRecord['paid'],
+                                    'notes'            => $billingRecord['notes'],
+                                    'renewal'          => true,
+                                    'recurring'        => true,
+                                    'recurrence'       => 20
                                 ),
                                 array(
-                                    '%d', // invoice
-                                    '%d', // line_item_type (invoiceType id)
+                                    '%s', // transaction_time
                                     '%d', // account
-                                    '%s', // name
-                                    '%s', // amount
-                                    '%d', // quantity
-                                    '%d', // total
-                                    '%s', // created
-                                    '%s', // first_due_date
-                                    '%s', // next_due_date
+                                    '%d', // old_invoice_id
+                                    '%f', // amount
+                                    '%f', // balance
+                                    '%s', // due_date
+                                    '%s', // paid
+                                    '%s', // notes
+                                    '%s', // renewal
                                     '%s', // recurring
-                                    '%d', // recurrence
+                                    '%s', // recurrence
                                 )
                             );
-                            $BillingSupport->recordInvoice( $newInvoiceId, $account['id'], $billingRecord['amount'], $billingRecord['transaction_time'] );
-                        }
-                        break;
-
-                    case "2": // Payments
-                        // Convert the payment method
-                        $paymentMethod = false;
-                        switch ( $billingRecord['payment_method'] ) {
-                        case "1": // Check 10
-                            $paymentMethod = 'Check';
-                            break;
-                        case "2": // not being used?
-                            $paymentMethod = 'Credit Card';
-                            break;
-                        case "3": // Cash 30
-                            $paymentMethod = 'Cash';
-                            break;
-                        case "4": // Other 40
-                            $paymentMethod = 'Other';
-                            break;
-                        case "5": // Adjustment 50
-                            $paymentMethod = 'Adjustment';
+                            $newInvoiceId = $this->wpdb->insert_id;
+                            // $importResults .= '<pre>$newInvoiceId: ' . print_r( $newInvoiceId, true ) . '</pre>';
+                            if ( $newInvoiceId ) {
+                                $this->wpdb->insert(
+                                    GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'line_items',
+                                    array(
+                                        'invoice'        => $newInvoiceId,
+                                        'line_item_type' => $invoiceType['id'],
+                                        'account'        => $account['id'],
+                                        'name'           => $invoiceType['name'],
+                                        'amount'         => $billingRecord['amount'],
+                                        'quantity'       => 1,
+                                        'total'          => $billingRecord['amount'],
+                                        'created'        => $billingRecord['transaction_time'],
+                                        'first_due_date' => $billingRecord['transaction_date'],
+                                        'next_due_date'  => $billingRecord['transaction_date'],
+                                        'recurring'      => $invoiceType['recurring'],
+                                        'recurrence'     => $invoiceType['recurrence']
+                                    ),
+                                    array(
+                                        '%d', // invoice
+                                        '%d', // line_item_type (invoiceType id)
+                                        '%d', // account
+                                        '%s', // name
+                                        '%s', // amount
+                                        '%d', // quantity
+                                        '%d', // total
+                                        '%s', // created
+                                        '%s', // first_due_date
+                                        '%s', // next_due_date
+                                        '%s', // recurring
+                                        '%d', // recurrence
+                                    )
+                                );
+                                $BillingSupport->recordInvoice( $newInvoiceId, $account['id'], $billingRecord['amount'], $billingRecord['transaction_time'] );
+                            } else {
+                                $this->wpdb->print_error();
+                            }
                             break;
-                        }
-                        // Find the new invoice id
-                        $newInvoiceId = $this->wpdb->get_var(
-                            $this->wpdb->prepare(
-                                "SELECT id
-                                   FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
-                                  WHERE old_invoice_id = %d",
-                                $billingRecord['invoice_id']
-                            )
-                        );
-                        $importResults .= '<pre>$newInvoiceId: ' . print_r( $newInvoiceId, true ) . '</pre>';
-                        if ( $newInvoiceId ) {
-                            $this->wpdb->insert(
-                                GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'payments',
-                                array(
-                                    'transaction_time' => $billingRecord['transaction_time'],
-                                    'account'          => $account['id'],
-                                    'amount'           => $billingRecord['amount'],
-                                    'payment_method'   => $paymentMethod,
-                                    'payment_data'     => $billingRecord['payment_data'],
-                                ),
-                                array(
-                                    '%s', // transaction_time
-                                    '%d', // account
-                                    '%s', // amount
-                                    '%s', // payment_method
-                                    '%s', // payment_data
+
+                        case "2": // Payments
+                            // Convert the payment method
+                            $paymentMethod = false;
+                            switch ( $billingRecord['payment_method'] ) {
+                            case "1": // Check 10
+                                $paymentMethod = 'Check';
+                                break;
+                            case "2": // not being used?
+                                $paymentMethod = 'Credit Card';
+                                break;
+                            case "3": // Cash 30
+                                $paymentMethod = 'Cash';
+                                break;
+                            case "4": // Other 40
+                                $paymentMethod = 'Other';
+                                break;
+                            case "5": // Adjustment 50
+                                $paymentMethod = 'Adjustment';
+                                break;
+                            }
+                            // Find the new invoice id
+                            $invoiceId = $this->wpdb->get_var(
+                                $this->wpdb->prepare(
+                                    "SELECT id
+                                       FROM " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "invoices
+                                      WHERE old_invoice_id = %d
+                                        AND account = %d",
+                                    $billingRecord['invoice_id'],
+                                    $account['id']
                                 )
                             );
-                            $paymentId = $this->wpdb->insert_id;
-                            if ( $paymentId ) {
-                                $BillingSupport->recordPayment(
-                                    $paymentId,
-                                    $account['id'],
-                                    $billingRecord['amount'],
-                                    array( $newInvoiceId ),
-                                    $this->config['transaction_numb']['Payment'],
-                                    $billingRecord['transaction_time']
+                            // $importResults .= '<pre>$invoiceId: ' . print_r( $invoiceId, true ) . '</pre>';
+                            if ( $invoiceId ) {
+                                $this->wpdb->insert(
+                                    GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . 'payments',
+                                    array(
+                                        'transaction_time' => $billingRecord['transaction_time'],
+                                        'account'          => $account['id'],
+                                        'amount'           => $billingRecord['amount'],
+                                        'payment_method'   => $paymentMethod,
+                                        'payment_data'     => $billingRecord['payment_data'],
+                                    ),
+                                    array(
+                                        '%s', // transaction_time
+                                        '%d', // account
+                                        '%s', // amount
+                                        '%s', // payment_method
+                                        '%s', // payment_data
+                                    )
                                 );
+                                $paymentId = $this->wpdb->insert_id;
+                                // $importResults .= '<pre>$paymentId: ' . print_r( $paymentId, true ) . '</pre>';
+                                if ( $paymentId ) {
+                                    $BillingSupport->recordPayment(
+                                        $paymentId,
+                                        $account['id'],
+                                        $billingRecord['amount'],
+                                        array( $invoiceId ),
+                                        $this->config['transaction_numb']['Payment'],
+                                        $billingRecord['transaction_time']
+                                    );
+                                }
                             }
-                        }
 
-                        break;
+                            break;
 
-                    case "3": // Adjustments
-                        break;
+                        case "3": // Adjustments
+                            break;
 
-                    case "4": // Comments
-                        break;
+                        case "4": // Comments
+                            break;
 
-                    default:
-                        die('billing type not correct');
-                        break;
+                        default:
+                            // var_dump( $billingRecord['billing_type'] );
+                            // echo '<pre>' . print_r( $billingRecord['billing_type'], true ) . '</pre>';
+                            // die('billing type not correct');
+                            break;
+                        }
                     }
                 }
             }
index 0a37d9e..8b7607a 100644 (file)
@@ -6,8 +6,10 @@
 require_once GLM_MEMBERS_BILLING_PLUGIN_CLASS_PATH . '/billingSupport.php';
 $BillingSupport = new GlmBillingSupport( $this->wpdb, $this->config );
 // Connect to their live database.
+// $dbConn = 'pgsql: host=ds5.gaslightmedia.com dbname=uptravel user=postgres';
+$dbConn = 'pgsql: dbname=uptravel user=postgres';
 $dbh = new PDO(
-    'pgsql: host=ds5 dbname=uptravel user=postgres',
+    $dbConn,
     null,
     null,
     array(
@@ -23,31 +25,41 @@ if ( isset( $_REQUEST['start'] ) && $start = filter_var( $_REQUEST['start'], FIL
 }
 
 $importResults = '';
+$badAccounts = array();
 
 // Get records.
 $query = "
-SELECT id,name
-  FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
- WHERE id in (
-    SELECT DISTINCT ref_dest
-      FROM  " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts )
-   AND old_member_id IN ( 17484, 4799, 17035, 6040, 5442, 5434, 18660 )
-LIMIT 20 OFFSET 0";
+SELECT M.id,M.name,A.id as account_id,M.old_member_id
+  FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members M
+       LEFT OUTER JOIN " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts A ON (A.ref_dest = M.id)
+ -- WHERE
+       -- id in ( SELECT DISTINCT ref_dest FROM  " . GLM_MEMBERS_BILLING_PLUGIN_DB_PREFIX . "accounts )
+   -- old_member_id IN ( 17484, 4799, 17035, 6040, 5442, 5434, 18660 )
+-- LIMIT 20 OFFSET 0
+";
 
 $results = $this->wpdb->get_results( $query, ARRAY_A );
 
-// $importResults .= '<pre>$results: ' . print_r( $results, true ) . '</pre>';
-
+$prepareSql    = "
+SELECT balance
+  FROM members.billing
+ WHERE member_id = :member_id
+ORDER BY transaction_time DESC
+LIMIT 1
+OFFSET 0";
+$getBalanceDue = $dbh->prepare( $prepareSql );
 
-foreach ( $results as $row ) {
+foreach ( $results as $key => &$row ) {
     // Get balance due
-    $account    = $BillingSupport->getAccountByRefDest( $row['id'] );
-    if ( !$account ) {
-        $importResults .= '<p>No account</p>';
-    } else {
-        $importResults .= '<p>Account: ' . $account['id'] . '</p>';
+    $balanceDue = $BillingSupport->getBalanceDueByAccount( $row['account_id'] );
+    $results[$key]['balanceDue'] = (float)$balanceDue;
+    $getBalanceDue->bindParam( ':member_id', $row['old_member_id'] );
+    $getBalanceDue->execute();
+    $results[$key]['original_balance_due'] = (float)$getBalanceDue->fetchColumn();
+    if ( $results[$key]['original_balance_due'] != $results[$key]['balanceDue'] ) {
+        $badAccounts[] = $results[$key];
     }
-    $balanceDue = $BillingSupport->getBalanceDueByAccount( $account['id'] );
-    $importResults .= '<pre>$balanceDue: ' . print_r( $balanceDue, true ) . '</pre>';
-    // $importResults .= '<pre>$account_id: ' . print_r( $account_id, true ) . '</pre>';
 }
+
+// $importResults .= '<pre>$results: ' . print_r( $results, true ) . '</pre>';
+$importResults .= '<pre>$badAccounts: ' . print_r( $badAccounts, true ) . '</pre>';
diff --git a/setup/databaseScripts/create_database_V0.0.32.sql b/setup/databaseScripts/create_database_V0.0.32.sql
new file mode 100644 (file)
index 0000000..2012bb6
--- /dev/null
@@ -0,0 +1,318 @@
+-- Gaslight Media Billing Module
+-- File Created: 11/19/2018
+-- Database Version: 0.0.27
+-- Database Creation Script
+--
+-- To permit each query below to be executed separately,
+-- all queries must be separated by a line with four dashes
+--
+-- **** BE SURE TO ALSO UPDATE drop_database_Vxxx.sql FILE WHEN CHANGING TABLES ****
+--
+
+-- Billing Accounts
+CREATE TABLE {prefix}accounts (
+    id INT NOT NULL AUTO_INCREMENT,
+    archived BOOLEAN DEFAULT '0',                          -- Marks account as archived
+    ref_dest INT NOT NULL,                                 -- reference to member id
+    ref_name TINYTEXT NOT NULL,                            -- Name of reference member
+    invoice_type INT NOT NULL DEFAULT '0',                 -- Ref to Invoice Type id
+    billing_contact_name TINYTEXT NULL,                    -- Billing Contact Name
+    billing_fname TINYTEXT NULL,                           -- Billing First Name
+    billing_lname TINYTEXT NULL,                           -- Billing Last Name
+    billing_company TINYTEXT NULL,                         -- Billing Company Name
+    billing_position TINYTEXT NULL,                        -- Billing Title/Position
+    billing_addr1 TINYTEXT NULL,                           -- Billing Address 1
+    billing_addr2 TINYTEXT NULL,                           -- Billing Address 2
+    billing_city TINYTEXT NULL,                            -- Billing City
+    billing_county INT NULL,                               -- Billing County
+    billing_state TINYTEXT NULL,                           -- Billing State
+    billing_zip TINYTEXT NULL,                             -- Billing Zip
+    billing_country TINYTEXT NULL,                         -- Billing Country
+    billing_phone TINYTEXT NULL,                           -- Billing Phone
+    billing_fax TINYTEXT NULL,                             -- Billing Fax
+    anniversary_date DATE NULL,                            -- anniversary date
+    renewal_date DATE NULL,                                -- renewal date of account
+    payment_data TEXT NULL,                                -- stored payment data
+    customer_profile_id TINYTEXT NULL,                     -- Customer Profile Id (Authorize.net)
+    payment_profile_id TINYTEXT NULL,                      -- Payment Profile Id (Authorize.net)
+    payment_profile_card TINYTEXT NULL,                    -- Payment Profile Card (Authorize.net)
+    email TINYTEXT NULL,                                   -- billing email
+    boss BOOLEAN DEFAULT '0',                              -- Boss flag
+    account_number TINYTEXT NULL,                          -- Account Number
+    email_invoice BOOLEAN DEFAULT '0',                     -- Invoice by email
+    usmail_invoice BOOLEAN DEFAULT '0',                    -- Invoice by US Mail
+    fax_invoice BOOLEAN DEFAULT '0',                       -- Invoice by Fax
+    PRIMARY KEY (id),
+    INDEX(ref_dest),
+    INDEX(ref_name(20)),
+    INDEX(email(20)),
+    INDEX(invoice_type),
+    INDEX(renewal_date),
+    INDEX(billing_county)
+);
+
+----
+
+-- transactions
+CREATE TABLE {prefix}transactions (
+    id INT NOT NULL AUTO_INCREMENT,
+    type INT NOT NULL,                                     -- type of transaction (payment,invoice,etc)
+    type_id INT NOT NULL,                                  -- reference to type id
+    account INT NOT NULL,                                  -- reference to account id
+    transaction_time DATETIME NOT NULL,                    -- datetime for the transaction
+    current_invoice_total DECIMAL(8, 2) NOT NULL,          -- invoice total
+    current_payment_total DECIMAL(8, 2) NOT NULL,          -- payment total
+    PRIMARY KEY (id),
+    INDEX(account),
+    INDEX(type_id),
+    INDEX(transaction_time)
+);
+
+----
+
+-- Invoices
+CREATE TABLE {prefix}invoices (
+    id INT NOT NULL AUTO_INCREMENT,
+    old_invoice_id INT NULL,                               -- old invoice id from uptra
+    transaction_time DATETIME NOT NULL,                    -- datetime for the invoice
+    account INT NOT NULL,                                  -- ref to account id
+    amount_total DECIMAL(8, 2) NOT NULL,                   -- total amount for invoice
+    balance DECIMAL(8, 2) NOT NULL,                        -- balance for this invoice
+    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(account),
+    INDEX(transaction_time),
+    INDEX(due_date)
+);
+
+----
+
+-- Line Item Types
+CREATE TABLE {prefix}invoice_types (
+    id INT NOT NULL AUTO_INCREMENT,
+    name TINYTEXT NOT NULL,                                -- name
+    parent INT NOT NULL DEFAULT 0,                         -- 0 if top level otherwise ref to another line_item_type as it's parent
+    member_type INT NOT NULL DEFAULT 0,                    -- Member Type assigned Default 0
+    amount DECIMAL(8,2) NOT NULL DEFAULT '0.00',           -- amount
+    recurring BOOLEAN DEFAULT '0',                         -- true/false if recurring
+    recurrence INT NULL DEFAULT 0,                         -- recurrence type
+    dynamic_amount BOOLEAN DEFAULT '0',                    -- true/false if amount is dynamic
+    qcode TINYTEXT NULL,                                   -- qcode for quickbooks
+    category TINYTEXT NULL,                                -- quickbooks category
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Line Items
+CREATE TABLE {prefix}line_items (
+    id INT NOT NULL AUTO_INCREMENT,
+    invoice INT NOT NULL,                                  -- reference to invoice
+    line_item_type INT NOT NULL,                           -- reference to line item type
+    account INT NULL DEFAULT 0,                            -- ref to account id (renewal or employee)
+    name TEXT NOT NULL,                                    -- line item name
+    amount DECIMAL(8,2) DEFAULT '0.00',                    -- line item amount per item
+    quantity INT DEFAULT 1,                                -- quantity
+    total DECIMAL(8,2) DEFAULT '0.00',                     -- line item total
+    recurring BOOLEAN DEFAULT '0',                         -- true/false if recurring
+    recurrence INT NULL DEFAULT 0,                         -- recurrence type
+    created DATE NULL,                                     -- Date this line item was first created
+    first_due_date DATE NULL,                              -- The first due date for this item
+    next_due_date DATE NULL,                               -- Next Due Date for this item
+    PRIMARY KEY (id),
+    INDEX(account),
+    INDEX(created),
+    INDEX(first_due_date),
+    INDEX(next_due_date)
+);
+
+----
+
+-- payments
+CREATE TABLE {prefix}payments (
+    id INT NOT NULL AUTO_INCREMENT,
+    transaction_time DATETIME NOT NULL,                    -- datetime of payment
+    account INT NOT NULL,                                  -- ref to account table
+    amount DECIMAL(8, 2) NOT NULL,                         -- payment amount
+    payment_method TINYTEXT NOT NULL,                      -- payment method
+    payment_data TINYTEXT NULL,                            -- additional payment info
+    notes TEXT NULL,                                       -- Notes/Comments on the payment
+    PRIMARY KEY (id)
+);
+
+----
+
+-- pdfs
+CREATE TABLE {prefix}pdfs (
+    id INT NOT NULL AUTO_INCREMENT,
+    ref_type INT NOT NULL,                                 -- reference type
+    ref_dest INT NOT NULL,                                 -- reference types id
+    pdf MEDIUMTEXT NOT NULL,                               -- saved pdf
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Notification Types
+CREATE TABLE {prefix}notification_types (
+    id INT NOT NULL AUTO_INCREMENT,
+    name TINYTEXT NOT NULL,                                -- name
+    to_email TINYTEXT NULL,                                -- To email
+    from_header TINYTEXT NOT NULL,                         -- from headers
+    replyto TINYTEXT NULL,                                 -- reply-to headers
+    subject TINYTEXT NOT NULL,                             -- Subject
+    message TEXT NOT NULL,                                 -- Message
+    send_by_date BOOLEAN NULL DEFAULT '0',                 -- true/false send by date based on due date
+    send_by_action BOOLEAN NULL DEFAULT '0',               -- send notice based on an action
+    send_action INT NULL DEFAULT 0,                        -- (create invoice or receive payment)
+    send_date_number INT NULL DEFAULT 0,                   -- number to apply to send by date
+    send_date_period INT NULL DEFAULT 0,                   -- (days,weeks,months,years)
+    send_date_when INT NULL DEFAULT 0,                     -- (before or after)
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Notifications
+CREATE TABLE {prefix}notifications (
+    id INT NOT NULL AUTO_INCREMENT,
+    notification_type INT NOT NULL,                        -- ref to notification type
+    account INT NOT NULL,                                  -- ref to account
+    from_replyto TINYTEXT NOT NULL,                        -- from reply-to header
+    subject TEXT NOT NULL,                                 -- subject
+    message TEXT NOT NULL,                                 -- message
+    date_sent DATETIME NOT NULL,                           -- Date the notice was sent
+    email_sent TINYTEXT NOT NULL,                          -- email used
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Notification Queue
+CREATE TABLE {prefix}notification_queue (
+    id INT NOT NULL AUTO_INCREMENT,
+    notification_type INT NOT NULL,                        -- ref to notification type
+    account INT NOT NULL,                                  -- ref to account
+    queued_time DATETIME NOT NULL,                         -- Creation time
+    processed_time DATETIME NULL,                          -- The time this queue was processed. (sent out)
+    PRIMARY KEY (id),
+    INDEX (notification_type),
+    INDEX (account),
+    INDEX (queued_time),
+    INDEX (processed_time)
+);
+
+----
+
+-- Gateway Settings
+CREATE TABLE {prefix}gateway_settings (
+    id INT NOT NULL AUTO_INCREMENT,
+    name TEXT NOT NULL,
+    login_id TINYTEXT NOT NULL,
+    transaction_key TINYTEXT NOT NULL,
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Invoice Payments
+CREATE TABLE {prefix}invoice_payments (
+    id INT NOT NULL AUTO_INCREMENT,
+    invoice INT NOT NULL,                                  -- reference to invoice id
+    payment INT NOT NULL,                                  -- reference to payment id
+    amount DECIMAL(8, 2) NOT NULL,                         -- payment amount
+    PRIMARY KEY (id),
+    INDEX(invoice)
+);
+
+----
+
+-- Settings
+CREATE TABLE {prefix}settings (
+    id INT NOT NULL AUTO_INCREMENT,
+    company_logo TINYTEXT NULL,                            -- Image logo
+    company_logo_height INT NULL,                          -- Logo Height (only used if creating pdf)
+    company_name TINYTEXT NULL,                            -- Company Name
+    company_name2 TINYTEXT NULL,                           -- Company Name 2
+    company_addr1 TINYTEXT NULL,                           -- Company Address 1
+    company_addr2 TINYTEXT NULL,                           -- Company Address 2
+    company_city TINYTEXT NULL,                            -- Company City
+    company_state TINYTEXT NULL,                           -- Company State
+    company_zip TINYTEXT NULL,                             -- Company Zip
+    company_phone TINYTEXT NULL,                           -- Company Phone
+    company_email TINYTEXT NULL,                           -- Company Email
+    company_url TINYTEXT NULL,                             -- Company URL
+    payment_terms TEXT NULL,                               -- Payment Terms
+    days_before_renewal INT NULL,                          -- Number of days before renewal date to allow renewals
+    days_after_expired INT NULL,                           -- Number of days after renewal date expired
+    allow_membership_choice BOOLEAN DEFAULT '0',           -- If memberships can choose their membership levels when they renew
+    allow_employees BOOLEAN DEFAULT '0',                   -- If memberships have employees
+    member_types_enabled BOOLEAN DEFAULT '1',              -- member types determine invoice types
+    quickbooks_enabled BOOLEAN DEFAULT '0',                -- QuickBooks enabled
+    member_billing_enabled BOOLEAN DEFAULT '1',            -- Member have access to billing info tab
+    billing_fields_required BOOLEAN DEFAULT '1',           -- Require Billing Fields
+    invoice_methods_enabled BOOLEAN DEFAULT '0',           -- Enable Uptra invoice methods
+    renewal_day_static BOOLEAN DEFAULT '0',                -- Renewal dates are same day every year
+    renewal_day INT NULL,                                  -- Day of the month for renewals
+    renewal_month INT NULL,                                -- Month of year for renewals
+    billing_county_enabled BOOLEAN DEFAULT '0',            -- Billing uses county field
+    invoice_pdf_enabled BOOLEAN DEFAULT '0',               -- Create PDF invoices
+    billing_contact_name_enabled BOOLEAN DEFAULT '0',      -- Use billing_contact_name instead of fname lname
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Set default billing Settings entry
+INSERT INTO {prefix}settings
+    ( id, days_before_renewal ,days_after_expired, member_types_enabled, quickbooks_enabled, member_billing_enabled )
+    VALUES
+    ( 1, 90, 30, true, false, true );
+
+----
+
+-- Management
+CREATE TABLE {prefix}management (
+    id INT NOT NULL AUTO_INCREMENT,
+    payment_methods SMALLINT NULL,                              -- Payment methods available for all registrations - Bitmap - see payment_method in plugin.ini
+    proc_methods SMALLINT NULL,                                 -- Credit Cart payment processing methods available - Bitmap - see proc_method in plugin.ini
+    cc_accepts SMALLINT NULL,                                   -- Credit Cards Accepted - Bitmap - See credit_card in plugin.ini
+    -- Authorize.net Credentials
+    authorize_net_login TINYTEXT NULL,
+    authorize_net_key TINYTEXT NULL,
+    authorize_net_test TINYINT NULL,                            -- Authorize.net test mode - List - see proc_test_mode in plugin.ini
+    authorize_net_conf BOOLEAN NULL,                            -- Flag to send payment confirmation Email from Authorize.net
+    authorize_net_merchant_email TINYTEXT NULL,                 -- E-Mail Authorize.net will send copy of confirmation E-Mail
+    -- Merchant Solutions Credentials
+    merchant_solutions_acctid TINYTEXT NULL,                    -- Merchant Solutions credentials
+    merchant_solutions_merchantpin TINYTEXT NULL,
+    merchant_solutions_test TINYINT NULL,                       -- Merchant Solutions test mode - List - see proc_test_mode in plugin.ini
+    merchant_solutions_conf BOOLEAN NULL,                       -- Flag to send payment confirmation Email
+    merchant_solutions_merchant_email TINYTEXT NULL,            -- Merchant Solutions will send copy of confirmation E-Mail
+    uptravel_invoice_template BOOLEAN DEFAULT '0',              -- Use uptravel template for invoices.
+    uptravel_payment_form BOOLEAN DEFAULT '0',                  -- Use uptravel payment form style.
+    PRIMARY KEY (id)
+);
+
+----
+
+-- Set default billing Management entry
+INSERT INTO {prefix}management
+    ( id )
+    VALUES
+    ( 1 );
+
+----
+
+-- Employees table
+CREATE TABLE {prefix}employees (
+    id INT NOT NULL AUTO_INCREMENT,
+    account INT NOT NULL,                                      -- Account Id
+    employee INT NOT NULL,                                     -- Employee Account Id
+    PRIMARY KEY (id)
+);