Finishing up the import scripting for coupons.
authorSteve Sutton <steve@gaslightmedia.com>
Thu, 15 Dec 2016 16:05:03 +0000 (11:05 -0500)
committerSteve Sutton <steve@gaslightmedia.com>
Thu, 15 Dec 2016 16:05:03 +0000 (11:05 -0500)
This is based on coupon from mackinawcity database. It is the most
current db structure for our old coupon database.

models/admin/management/coupons.php
setup/databaseScripts/create_database_V0.0.3.sql
views/admin/management/coupons.html

index d6e5141..7e12704 100644 (file)
@@ -53,20 +53,34 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
      * @access public
      */
     public $settings = array();
+    /**
+     * categories
+     *
+     * @var array
+     * @access public
+     */
+    public $categories = array();
+    /**
+     * oldCatMap
+     *
+     * @var array
+     * @access public
+     */
+    public $oldCatMap = array();
 
     /**
      * Constructor
      *
-     * This contructor performs the work for this model. This model returns
+     * This constructor 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.
+     * True if successful and false if there was a fatal failure.
      *
      * 'view'
      *
-     * A suggested view name that the contoller should use instead of the
+     * A suggested view name that the controller should use instead of the
      * default view for this model or false to indicate that the default view
      * should be used.
      *
@@ -97,6 +111,7 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
      * modelAction
      *
      * @param bool $actionData
+     *
      * @access public
      * @return void
      */
@@ -108,7 +123,7 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
         $import_result         = false;
         $settings_updated      = false;
         $settings_update_error = false;
-        $coupon_settings        = false;
+        $coupon_settings       = false;
         $icalFeedResult        = false;
         $import_feeds          = false;
         $option2               = false;
@@ -118,6 +133,51 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
         }
 
         switch ($option) {
+            case 'couponimport':
+                $import = false;
+                if (isset($_REQUEST['import'])) {
+                    $import = filter_var( $_REQUEST['import'], FILTER_VALIDATE_BOOLEAN );
+                }
+                if ( $import ) {
+                    $import_result = '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
+                    $db_host       = filter_var( $_REQUEST['db_host'], FILTER_SANITIZE_STRING );
+                    $db_name       = filter_var( $_REQUEST['db_name'], FILTER_SANITIZE_STRING );
+                    $db_user       = filter_var( $_REQUEST['db_user'], FILTER_SANITIZE_STRING );
+                    $db_password   = filter_var( $_REQUEST['db_password'], FILTER_SANITIZE_STRING );
+                    $this->connectPostgresDb( $db_host, $db_name, $db_user, $db_password );
+
+                    $this->settings = filter_var_array(
+                        $_REQUEST,
+                        array(
+                            'schema'       => FILTER_SANITIZE_STRING,
+                            'cattablename' => FILTER_SANITIZE_STRING,
+                            'tablename'    => FILTER_SANITIZE_STRING,
+                            'sdate'        => array(
+                                'filter'  => FILTER_VALIDATE_REGEXP,
+                                'options' => array(
+                                    'regexp' => '%[0-9]{2}/[0-9]{2}/[0-9]{4}%'
+                                )
+                            )
+
+                        )
+                    );
+                    // Add the categories
+                    $this->addCategories();
+                    $import_result .= '<pre>$this->settings: ' . print_r($this->settings, true) . '</pre>';
+                    $import_result .= $this->addCoupons();
+                }
+
+                break;
+
+            case 'couponImagesImport':
+                $this->image_owner = filter_var( $_REQUEST['img_owner_id'], FILTER_SANITIZE_STRING );
+                if ( $this->image_owner ) {
+                    $this->importCouponImages();
+                    $import_result = '<p>All images imported</p>';
+                } else {
+                    $import_result = '<p>Failure: Not given owner id.</p>';
+                }
+                break;
 
             case 'settings':
 
@@ -144,38 +204,39 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
                 if (isset($_REQUEST['option2'])) {
                     $option2 = $_REQUEST['option2'];
                 }
-
                 switch($option2) {
 
-                    // Update the settings and redisplay the form
-                    case 'submit':
 
-                        // Update the coupon management settings
-                        $coupon_settings = $this->updateEntry(1);
-                        if ($coupon_settings['status']) {
-                            $settings_updated = true;
-                        } else {
-                            $settings_update_error = true;
-                        }
 
-                        break;
+                // Update the settings and redisplay the form
+                case 'submit':
 
-                    // Default is to get the current settings and display the form
-                    default:
+                    // Update the coupon management settings
+                    $coupon_settings = $this->updateEntry(1);
+                    if ($coupon_settings['status']) {
+                        $settings_updated = true;
+                    } else {
+                        $settings_update_error = true;
+                    }
 
-                        // Try to get the first (should be only) entry for general settings.
-                        $coupon_settings = $this->editEntry(1);
-                        //echo '<pre>$coupon_settings: ' . print_r( $coupon_settings, true ) . '</pre>';
+                    break;
 
-                        if ($coupon_settings === false) {
+                // Default is to get the current settings and display the form
+                default:
 
-                            if (GLM_MEMBERS_PLUGIN_ADMIN_DEBUG) {
-                                glmMembersAdmin::addNotice("<b>&nbsp;&nbsp;/models/admin/management/coupons.php: Unable to load coupons management settings.", 'Alert');
-                            }
+                    // Try to get the first (should be only) entry for general settings.
+                    $coupon_settings = $this->editEntry(1);
+                    //echo '<pre>$coupon_settings: ' . print_r( $coupon_settings, true ) . '</pre>';
 
+                    if ($coupon_settings === false) {
+
+                        if (GLM_MEMBERS_PLUGIN_ADMIN_DEBUG) {
+                            glmMembersAdmin::addNotice("<b>&nbsp;&nbsp;/models/admin/management/coupons.php: Unable to load coupons management settings.", 'Alert');
                         }
 
-                        break;
+                    }
+
+                    break;
 
                 }
 
@@ -210,6 +271,295 @@ class GlmMembersAdmin_management_coupons extends GlmDataCouponsManagement
 
     }
 
+    /**
+     * connectPostgresDb
+     *
+     * Make a connection to the given database for the site. (postgres)
+     * Sets the $this->dbh with the postgres database connection
+     *
+     * @param mixed $db_host
+     * @param mixed $db_name
+     * @param mixed $db_user
+     * @param mixed $db_password
+     *
+     * @access public
+     * @return void
+     */
+    public function connectPostgresDb($db_host, $db_name, $db_user, $db_password)
+    {
+        $conn_str      = "pgsql:";
+        if ( $db_host ) {
+            $conn_part[] = "host={$db_host}";
+        }
+        if ( $db_name ) {
+            $conn_part[] = "dbname={$db_name}";
+        }
+        if ( $db_user ) {
+            $conn_part[] = "user={$db_user}";
+        }
+        if ( $db_password ) {
+            $conn_part[] = "password={$db_password}";
+        }
+        if ( !empty($conn_part) ) {
+             $conn_str .= implode( " ", $conn_part );
+        }
+        $driver_options = array(
+            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH,
+        );
+        try {
+            $this->dbh = new PDO($conn_str, null, null, $driver_options);
+            $this->dbh->setAttribute(
+                PDO::ATTR_ERRMODE,
+                PDO::ERRMODE_EXCEPTION
+            );
+        } catch(PDOException $e) {
+            echo '<pre>$e: ' . print_r($e, true) . '</pre>';
+            wp_die();
+        }
+    }
+
+    /**
+     * Add coupons from the old site
+     *
+     * Based on Mackinawcity. Which is a current version of the coupon database
+     * structure. The may be some older ones that we'll have to make
+     * adjustments for the categories or some fields in the coupon table.
+     *
+     * @access public
+     * @return void
+     */
+    public function addCoupons()
+    {
+        // clear the coupons data tables
+        $this->clearData();
+        $sql = "
+        SELECT *
+          FROM {$this->settings['schema']}.{$this->settings['tablename']}";
+        try {
+            $coupons = $this->dbh->query( $sql )->fetchAll(PDO::FETCH_ASSOC);
+            foreach ( $coupons as $coupon ) {
+                $refType = $member_id = $found_id = null;
+                if ( isset( $coupon['member'] ) && $coupon['member'] ) {
+                    // get the new member id
+                    $sql = "
+                    SELECT id
+                      FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+                     WHERE old_member_id = " . esc_sql( trim( $coupon['member'] ) );
+                    $found_id = $this->wpdb->get_row( $sql, ARRAY_A );
+                    if ( $found_id ) {
+                        $member_id = $found_id['id'];
+                        $refType = $this->config['ref_type_numb']['Member'];
+                    }
+                }
+                $coupon_data = array(
+                    'status'     => ( ( $coupon['active'] == '1' )
+                        ? $this->config['status_numb']['Active']
+                        : $this->config['status_numb']['Inactive'] ),
+                    'created'    => $coupon['sdate'],
+                    'updated'    => $coupon['sdate'],
+                    'start_date' => $coupon['sdate'],
+                    'end_date'   => $coupon['edate'],
+                    'expire'     => $coupon['expiration'],
+                    'name'       => $coupon['title'],
+                    'ref_type'   => $refType,
+                    'ref_dest'   => $member_id,
+                    'descr'      => strip_tags( trim( $coupon['description'] ) ),
+                    'image'      => $coupon['image'],
+                    'url'        => $coupon['url'],
+                );
+                $coupon_data_format = array(
+                    '%d',
+                    '%s',
+                    '%s',
+                    '%s',
+                    '%s',
+                    '%s',
+                    '%s',
+                    '%d',
+                    '%d',
+                    '%s',
+                    '%s',
+                    '%s',
+                );
+                $this->wpdb->insert(
+                    GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . 'coupons',
+                    $coupon_data,
+                    $coupon_data_format
+                );
+                $coupon_id = $this->wpdb->insert_id;
+                var_dump( $coupon_id );
+                echo '<pre>$couponId: from insert ' . print_r( $coupon_id, true ) . '</pre>';
+                if ( !$coupon_id ) {
+                    die( 'something is wrong no couponId' );
+                }
+                $coupon_abstract = new GlmDataCoupons( $this->wpdb, $this->config );
+                $coupon_abstract->updateSlug( $coupon_id );
+                if ( $coupon['category'] ) {
+                    // find out if the category given in coupon is int or text
+                    $cat_id = filter_var( $coupon['category'], FILTER_VALIDATE_INT );
+                    if ( $cat_id ) {
+                        $this->wpdb->insert(
+                            GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . 'coupon_categories',
+                            array(
+                                'coupon'   => $coupon_id,
+                                'category' => $this->oldCatMap[$cat_id]
+                            ),
+                            array(
+                                '%d',
+                                '%d'
+                            )
+                        );
+                    } else {
+                        // do stuff here for text value
+                        $cat_id = $this->getCategoryId( $coupon['category'] );
+                        $this->wpdb->insert(
+                            GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . 'coupon_categories',
+                            array(
+                                'coupon'   => $coupon_id,
+                                'category' => $cat_id
+                            ),
+                            array(
+                                '%d',
+                                '%d'
+                            )
+                        );
+                    }
+                }
+            }
+        } catch( PDOException $e ) {
+            echo '<pre>$e: ' . print_r( $e, true ) . '</pre>';
+        }
+        return 'Testing';
+    }
+    /**
+     * addCategories
+     *
+     * Checks to see if there's an Coupon Category already in the database.
+     * If not it will create the entry.
+     * Sets up the class variables
+     * $this->categories (contains all the categories that get added keyed with
+     * category id)
+     * $this->oldCatMap (map of the old category id to new category ids)
+     *
+     * @access public
+     * @return void
+     */
+    public function addCategories()
+    {
+        $category_label = 'name';
+        $return = '';
+        $sql = "
+          SELECT *
+            FROM {$this->settings['schema']}.{$this->settings['cattablename']}
+        ORDER BY id";
+        $return .= '<pre>$sql: ' . print_r($sql, true) . '</pre>';
+        try {
+            $categories = $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
+            $return .= '<pre>$categories: ' . print_r($categories, true) . '</pre>';
+            foreach ( $categories as $category ) {
+                // first check to see if the category is already there
+                $sql = "
+                SELECT id
+                  FROM " . GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . "categories
+                 WHERE name = '" . esc_sql( trim($category[$category_label]) ) . "'";
+                $return .= '<pre>$sql: ' . print_r($sql, true) . '</pre>';
+                $found = $this->wpdb->get_row($sql, ARRAY_A);
+                $return .= '<pre>$found: ' . print_r($found, true) . '</pre>';
+                if ( !isset($found) ) {
+                    $this->wpdb->insert(
+                        GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . 'categories',
+                        array( 'name'     => trim($category[$category_label]) ),
+                        array( '%s' )
+                    );
+                    $catid = $this->wpdb->insert_id;
+                    $this->categories[$catid] = trim($category[$category_label]);
+                    $this->oldCatMap[$category['id']] = $catid;
+                } else {
+                    $this->categories[$found['id']] = trim($category[$category_label]);
+                    $this->oldCatMap[$category['id']] = $found['id'];
+                }
+            }
+        } catch(PDOException $e) {
+            echo '<pre>$e: ' . print_r($e, true) . '</pre>';
+            die('end here');
+        }
+        return $return;
+    }
+    /**
+     * clearData
+     *
+     * Clears the coupon and coupon_category data from the wordpress database.
+     *
+     * @access public
+     * @return void
+     */
+    public function clearData()
+    {
+        $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . "coupons" );
+        $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . "coupon_categories" );
+    }
+    /**
+     * getCategoryId
+     *
+     * Get the coupon category id given a coupon category name.
+     * If the coupon category is not found by the name then add it.
+     *
+     * @param mixed $category
+     *
+     * @access public
+     * @return void
+     */
+    public function getCategoryId( $category )
+    {
+        return $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT id
+                   FROM " . GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . "categories
+                  WHERE name = %s",
+                $category
+            )
+        );
+    }
+
+    /**
+     * importCouponImages
+     *
+     * Grabs the coupon images from is0 server and updates each coupon record
+     * with the new image name.
+     *
+     * @access public
+     * @return void
+     */
+    public function importCouponImages()
+    {
+        require_once GLM_MEMBERS_PLUGIN_PATH.'/models/admin/ajax/imageUpload.php';
+        $ImageUpload = new GlmMembersAdmin_ajax_imageUpload($this->wpdb, $this->config);
+        // get all coupons with images
+        $sql = "
+        SELECT id,image
+          FROM " . GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX. "coupons
+         WHERE image != '' AND image IS NOT NULL";
+        $results = $this->wpdb->get_results($sql, ARRAY_A);
+        $out = '<pre>$results: ' . print_r($results, true) . '</pre>';
+        $imgUrl = 'http://is0.gaslightmedia.com/' . $this->image_owner . '/original/';
+        foreach ( $results as $coupon ) {
+            $imageFullUrl = $imgUrl . $coupon['image'];
+            $res          = $ImageUpload->storeImage($imageFullUrl);
+            if ( isset( $res['newFileName']) && $res['newFileName'] ) {
+                $this->wpdb->update(
+                    GLM_MEMBERS_COUPONS_PLUGIN_DB_PREFIX . 'coupons',
+                    array(
+                        'image' => $res['newFileName']
+                    ),
+                    array( 'id' => $coupon['id'] ),
+                    array( '%s' ),
+                    array( '%d' )
+                );
+            }
+        }
+        return $out;
+    }
+
 }
 
 ?>
index 89b9ee9..f87b6a2 100644 (file)
@@ -19,8 +19,8 @@ CREATE TABLE {prefix}coupons (
     created DATETIME NULL,            -- Create date
     updated DATETIME NULL,            -- Update date
     approved DATETIME NULL,           -- Approved date
-    start_date DATE NULL,               -- Starting date of the coupon
-    end_date DATE NULL,                 -- Ending date of the coupon
+    start_date DATE NULL,             -- Starting date of the coupon
+    end_date DATE NULL,               -- Ending date of the coupon
     expire DATE NULL,                 -- Expire date of the coupon
     name TINYTEXT NULL,               -- Coupon name
     name_slug TINYTEXT NULL,          -- Coupon name slug
index fbef15c..7ab60f9 100644 (file)
@@ -2,6 +2,7 @@
 
     <h2 class="nav-tab-wrapper" style="margin-bottom: 1em;">
         <a id="glm-settings" data-show-table="glm-table-settings" class="glm-settings-tab nav-tab{if $option=='settings'} nav-tab-active{/if}">Settings</a>
+        <a id="glm-couponimport" data-show-table="glm-table-couponimport" class="glm-settings-tab nav-tab{if $option=='couponimport'} nav-tab-active{/if}">Import</a>
     </h2>
 
     <!-- Management Settings -->
             </td>
         </tr>
     </table>
+    <!-- Import -->
 
+    <table id="glm-table-couponimport" class="glm-admin-table glm-settings-table{if $option!='couponimport'} glm-hidden{/if}">
+  {if $importResult}
+        <tr><td><a href="{$thisUrl}?page={$thisPage}&glm_action=coupons&option=couponimport">Return to Import Coupons</a></td></tr>
+        <tr>
+            <td colspan="2">
+                {$importResult}
+            </td>
+        </tr>
+  {else}
+        <tr>
+            <td colspan="2"><h1>Import from Gaslight Coupons</h1></td>
+        </tr>
+        <tr>
+            <td colspan="2">
+                <form action="{$thisUrl}">
+                    <input type="hidden" name="page" value="{$thisPage}">
+                    <input type="hidden" name="glm_action" value="coupons">
+                    <input type="hidden" name="option" value="couponimport">
+                    <input type="hidden" name="import" value="true">
+                    <div style="float:left;width: 200px;">
+                        <fieldset>
+                            <legend>Database to import from:</legend>
+                            <label for="db_host">DB Host</label>
+                            <input id="db_host" name="db_host" />
+                            <label for="db_name">DB Name</label>
+                            <input id="db_name" name="db_name" />
+                            <label for="db_user">DB User</label>
+                            <input id="db_user" name="db_user" />
+                            <label for="db_password">DB Password</label>
+                            <input id="db_password" name="db_password" />
+                        <fieldset>
+                    </div>
+                    <div style="float:left;width: 200px;">
+                        <fieldset>
+                            <legend>Settings:</legend>
+                            <label for="schema">Schema</label>
+                            <input id="schema" name="schema" />
+                            <label for="cattablename">Category Table Name</label>
+                            <input id="cattablename" name="cattablename" />
+                            <label for="tablename">Coupon Table Name</label>
+                            <input id="tablename" name="tablename" />
+                            <label for="sdate">Start Date</label>
+                            <input id="sdate" name="sdate" />
+                        </fieldset>
+
+                        <input type="submit" value="Import Coupons" />
+                    </div>
+                </form>
+            </td>
+        </tr>
+        <tr>
+            <td colspan="2">
+                <form action="{$thisUrl}">
+                    <input type="hidden" name="page" value="{$thisPage}">
+                    <input type="hidden" name="glm_action" value="coupons">
+                    <input type="hidden" name="option" value="couponImagesImport">
+                    <div style="float:left;width: 200px;">
+                        <fieldset>
+                            <legend>Image Style Owner:</legend>
+                            <label for="img_owner_id">Owner Id</label>
+                            <input id="img_owner_id" name="img_owner_id" />
+                        <fieldset>
+                        <input type="submit" value="Import Images" />
+                    </div>
+                </form>
+            </td>
+        </tr>
+  {/if}
+
+    </table>
     <script type="text/javascript">
 
         jQuery(document).ready(function($) {