Updates for the admin. Import csv file.
authorSteve Sutton <steve@gaslightmedia.com>
Tue, 18 Sep 2018 20:40:14 +0000 (16:40 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Tue, 18 Sep 2018 20:40:59 +0000 (16:40 -0400)
Import the csv file.
Importing will update based on the email address field.
Must be a valid csv file.

classes/data/dataStaff.php
models/admin/staff/import.php [new file with mode: 0644]
models/admin/staff/index.php
setup/validActions.php
views/admin/staff/header.html
views/admin/staff/import.html [new file with mode: 0644]
views/admin/staff/index.html
views/admin/staff/settings.html

index 5f26ad6..524f2a0 100644 (file)
@@ -149,7 +149,7 @@ class GlmDataStaff extends GlmDataAbstract
             'extension' => array (
                 'field'    => 'extension',
                 'type'     => 'text',
-                'required' => true,
+                'required' => false,
                 'use'      => 'a'
             ),
 
diff --git a/models/admin/staff/import.php b/models/admin/staff/import.php
new file mode 100644 (file)
index 0000000..e8020a1
--- /dev/null
@@ -0,0 +1,380 @@
+<?php
+
+/**
+ * Gaslight Media Members Database
+ * Admin Members Dashboard
+ *
+ * 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_STAFF_PLUGIN_CLASS_PATH.'/data/dataStaff.php';
+require_once GLM_MEMBERS_STAFF_PLUGIN_CLASS_PATH.'/data/dataBuildings.php';
+require_once GLM_MEMBERS_STAFF_PLUGIN_CLASS_PATH.'/data/dataDepartments.php';
+
+/*
+ * This class performs the work for the default action of the "Members" menu
+ * option, which is to display the members dashboard.
+ *
+ */
+class GlmMembersAdmin_staff_import extends GlmDataStaff
+{
+
+    const CSV_CHARS_PER_LINE = 100000;
+    /**
+     * WordPress Database Object
+     *
+     * @var $wpdb
+     * @access public
+     */
+    public $wpdb;
+    /**
+     * Plugin Configuration Data
+     *
+     * @var $config
+     * @access public
+     */
+    public $config;
+
+    /*
+     * Constructor
+     *
+     * This contructor 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 members data class
+        parent::__construct(false, false);
+
+    }
+
+    /*
+     * Perform Model Action
+     *
+     * This method does the work for this model and returns any resulting data
+     *
+     * @return array Status and data array
+     *
+     * 'status'
+     *
+     * True if successfull and false if there was a fatal failure.
+     *
+     * 'menuItemRedirect'
+     *
+     * If not false, provides a menu item the controller should
+     * execute after this one. Normally if this is used, there would also be a
+     * modelRedirect value supplied as well.
+     *
+     * 'modelRedirect'
+     *
+     * If not false, provides an action the controller should execute after
+     * this one.
+     *
+     * '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.
+     *
+     */
+    public function modelAction ($actionData = false)
+    {
+        $success       = true;
+        $message       = '';
+        $view          = 'import';
+        $file_name     = 'staff-import.csv';
+        $imported      = 0;
+        $updated       = 0;
+        $import_good   = false;
+        $processed     = false;
+        $valid_headers = array(
+            'firstname',
+            'lastname',
+            'email',
+            'extension',
+            'building',
+            'department'
+        );
+
+        // Get any provided option
+        if ( isset( $_REQUEST['option'] ) ) {
+            $option = $_REQUEST['option'];
+        }
+
+        // echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
+
+        // Do selected option
+        switch ( $option ) {
+
+        case 'upload':
+            // Set variable for the upload directory
+            $wpUploadDir = wp_get_upload_dir();
+
+            // Set the $upload_path for import files
+            $upload_path = $wpUploadDir['basedir'] . '/' . 'glm-member-staff';
+
+            // If the folder for the upload import files doesn't exists create one.
+            if ( !is_dir( $upload_path ) ) {
+                // Get old umask
+                $oldMask = umask(0);
+                // Set folder permission
+                mkdir( $upload_path, 0770 );
+                // reset old umask
+                umask( $oldMask );
+            }
+
+            // echo '<pre>$_FILES: ' . print_r( $_FILES, true ) . '</pre>';
+
+            if ( isset( $_FILES['csv_file'] ) && !$_FILES['csv_file']['error'] ) {
+                move_uploaded_file( $_FILES['csv_file']['tmp_name'], $upload_path . '/'. $file_name );
+            }
+
+            $full_file_name = $upload_path . '/' . $file_name;
+
+            if ( is_file( $upload_path . '/' . $file_name ) ) {
+                $processed = true;
+                $headers   = $this->readCSVFileHeaders( $full_file_name );
+                // echo '<pre>$headers: ' . print_r( $headers, true ) . '</pre>';
+                if ( $valid_headers == $headers ) {
+                    $file_data = $this->readCSVFile( $full_file_name );
+                    // echo '<pre>$file_data: ' . print_r( $file_data, true ) . '</pre>';
+                    if ( $file_data ) {
+                        foreach ( $file_data as $row ) {
+                            if ( $row['email'] ) {
+                                // Get Department.
+                                $department_id = $this->getDepartment( $row['department'] );
+                                $building_id   = $this->getBuilding( $row['building'] );
+                                $staff_id      = $this->wpdb->get_var(
+                                    $this->wpdb->prepare(
+                                    "SELECT id
+                                       FROM " . GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . "staff
+                                      WHERE email = %s",
+                                    $row['email']
+                                  )
+                                );
+                                if ( $staff_id ) {
+                                    $this->wpdb->update(
+                                        GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . 'staff',
+                                        array(
+                                            'fname'      => $row['firstname'],
+                                            'lname'      => $row['lastname'],
+                                            'extension'  => $row['extension'],
+                                            'building'   => $building_id,
+                                            'department' => $department_id,
+                                        ),
+                                        array( 'email' => $row['email'] ),
+                                        array(
+                                            '%s', // fname
+                                            '%s', // lname
+                                            '%s', // extension
+                                            '%d', // building
+                                            '%d', // department
+                                        ),
+                                        array( '%s' )
+                                    );
+                                    $updated++;
+                                } else {
+                                    $this->wpdb->insert(
+                                        GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . 'staff',
+                                        array(
+                                            'fname'      => $row['firstname'],
+                                            'lname'      => $row['lastname'],
+                                            'email'      => $row['email'],
+                                            'extension'  => $row['extension'],
+                                            'building'   => $building_id,
+                                            'department' => $department_id,
+                                        ),
+                                        array(
+                                            '%s', // fname
+                                            '%s', // lname
+                                            '%s', // email
+                                            '%s', // extension
+                                            '%d', // building
+                                            '%d', // department
+                                        )
+                                    );
+                                    $imported++;
+                                }
+                            }
+                        }
+                    }
+                    $import_good = true;
+                } else {
+                    $import_good = false;
+                    $message     = 'File was not in correct format';
+                }
+            }
+
+            break;
+
+        default:
+            break;
+
+        }
+
+
+        // Compile template data
+        $templateData = array(
+            'imported'    => $imported,
+            'updated'     => $updated,
+            'import_good' => $import_good,
+            'processed'   => $processed,
+            'message'     => $message,
+        );
+
+        // Return status, suggested view, and data to controller
+        return array(
+            'status'           => $success,
+            'menuItemRedirect' => false,
+            'modelRedirect'    => false,
+            'view'             => 'admin/staff/' . $view . '.html',
+            'data'             => $templateData
+        );
+
+    }
+
+    /**
+     * getBuilding
+     *
+     * Return the id for given building if found.
+     * Else add the new one and return the id.
+     *
+     * @param string $name
+     *
+     * @return int Id of building.
+     */
+    public function getBuilding( $name )
+    {
+        // If the building already exists then return the id.
+        $building_id = $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT id
+                   FROM " . GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . "buildings
+                  WHERE name = %s",
+                $name
+            )
+        );
+        if ( $building_id ) {
+            return $building_id;
+        }
+        // Else insert it and return new id.
+        $this->wpdb->insert(
+            GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . 'buildings',
+            array( 'name' => $name ),
+            array( '%s' )
+        );
+        // Return insert id.
+        return $this->wpdb->insert_id;
+    }
+
+
+    /**
+     * getDepartment
+     *
+     * Return the id for given department if found.
+     * Else add the new one and return the id.
+     *
+     * @param string $name
+     *
+     * @return int Id of department.
+     */
+    public function getDepartment( $name )
+    {
+        // If the department already exists then return the id.
+        $department_id = $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT id
+                   FROM " . GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . "departments
+                  WHERE name = %s",
+                $name
+            )
+        );
+        if ( $department_id ) {
+            return $department_id;
+        }
+        // Else insert it and return new id.
+        $this->wpdb->insert(
+            GLM_MEMBERS_STAFF_PLUGIN_DB_PREFIX . 'departments',
+            array( 'name' => $name ),
+            array( '%s' )
+        );
+        // Return insert id.
+        return $this->wpdb->insert_id;
+    }
+
+    /**
+     * readCSVFile
+     *
+     * Read the entire csv file. First line is used for headers of the returned
+     * array.
+     *
+     * @param mixed $fileName
+     * @access public
+     * @return void
+     */
+    public function readCSVFile( $fileName )
+    {
+        $fileData    = array();
+        $fileHeaders = array();
+        if ( ( $fp = fopen( $fileName, 'r' ) ) !== false ) {
+            // get first line to use as headers
+            $rowNumber = 0;
+            while ( ( $data = fgetcsv( $fp, SELF::CSV_CHARS_PER_LINE, ',', '"', '"' ) ) !== false ) {
+                if ( $rowNumber == 0 ) {
+                    $fileHeaders = $data;
+                } else {
+                    for ( $index = 0; $index < count( $data ); ++$index ) {
+                        $fileData[$rowNumber][$fileHeaders[$index]] = $data[$index];
+                    }
+                }
+                $rowNumber++;
+            }
+            fclose( $fp );
+        }
+        return $fileData;
+    }
+
+    /**
+     * readCSVFileHeaders
+     *
+     * Read the cvs file. Just the first line is read.
+     *
+     * @param mixed $fileName Name of the file (path)
+
+     * @access public
+     * @return void
+     */
+    public function readCSVFileHeaders( $fileName )
+    {
+        $fileHeaders = array();
+        if ( ( $fp = fopen( $fileName, 'r' ) ) !== false ) {
+            // get first line to use as headers
+            $fileHeaders = fgetcsv( $fp, SELF::CSV_CHARS_PER_LINE, ',' );
+            fclose( $fp );
+        }
+
+        return $fileHeaders;
+    }
+}
index 03507ac..b5af602 100644 (file)
@@ -119,6 +119,10 @@ class GlmMembersAdmin_staff_index extends GlmDataStaff
         $alphaList     = false;
         $alphaWhere    = '';
         $alphaSelected = false;
+        $numbDisplayed = false;
+        $lastDisplayed = false;
+        $departments   = false;
+        $buildings     = false;
 
         // Get any provided option
         if (isset($_REQUEST['option'])) {
index 4efd318..af511f3 100644 (file)
@@ -65,6 +65,7 @@ $glmMembersStaffAddOnValidActions = array(
         'staff' => array(
             'index'    => GLM_MEMBERS_STAFF_PLUGIN_SLUG,
             'settings' => GLM_MEMBERS_STAFF_PLUGIN_SLUG,
+            'import'   => GLM_MEMBERS_STAFF_PLUGIN_SLUG,
         ),
     ),
     'frontActions' => array(
index ff762b9..04bfde8 100644 (file)
@@ -4,6 +4,7 @@
     <h2 class="nav-tab-wrapper">
         <a href="{$thisUrl}?page={$thisPage}&glm_action=index" class="nav-tab{if $thisAction==index} nav-tab-active{/if}">Staff List</a>
         <a href="{$thisUrl}?page={$thisPage}&glm_action=settings" class="nav-tab{if $thisAction==settings} nav-tab-active{/if}">Settings</a>
+        <a href="{$thisUrl}?page={$thisPage}&glm_action=import" class="nav-tab{if $thisAction==import} nav-tab-active{/if}">Import CSV File</a>
         <a href="{$thisUrl}?page={$thisPage}&glm_action=index&option=add" class="nav-tab">Add Staff</a>
     </h2>
 
diff --git a/views/admin/staff/import.html b/views/admin/staff/import.html
new file mode 100644 (file)
index 0000000..62a66fb
--- /dev/null
@@ -0,0 +1,31 @@
+{include file='admin/staff/header.html'}
+
+<h2>Staff Importer</h2>
+
+<form action="{$thisUrl}?page={$thisPage}" method="post" enctype="multipart/form-data">
+    <input type="hidden" name="page" value="{$thisPage}" />
+    <input type="hidden" name="glm_action" value="{$thisAction}" />
+    <input type="hidden" name="option" value="upload" />
+
+    <input type="file" name="csv_file" />
+
+    <input type="submit" value="Import CSV File" />
+
+</form>
+
+{if $processed}
+    {if $import_good}
+    <div>
+        Import Success:<br>
+        Updated: {$updated}<br>
+        Added: {$imported}<br>
+    </div>
+    {else}
+    <div>
+        Import Failed:<br>
+        {$message}
+    </div>
+    {/if}
+{/if}
+
+{include file='admin/staff/footer.html'}
index 4e11c68..b6c59d5 100644 (file)
@@ -5,10 +5,10 @@
 <form id="search_form" action="{$thisUrl}">
     <input type="hidden" name="page" value="{$thisPage}" />
     <input type="hidden" name="glm_action" value="{$thisAction}" />
-    <input type="hidden" name="prevStart" value="{$prevStart}">
-    <input type="hidden" name="nextStart" value="{$nextStart}">
-    <input type="hidden" name="limit" value="{$limit}">
-    <input type="hidden" name="savedAlpha" value="{$alphaSelected}">
+    <input type="hidden" name="prevStart" value="{$prevStart}" />
+    <input type="hidden" name="nextStart" value="{$nextStart}" />
+    <input type="hidden" name="limit" value="{$limit}" />
+    <input type="hidden" name="savedAlpha" value="{$alphaSelected}" />
 
     <div >
         <input name="filter_name" value="{if isset($smarty.request.filter_name)}{$smarty.request.filter_name}{/if}" />
index 6593a78..217608b 100644 (file)
@@ -45,7 +45,7 @@
 </table>
 
 {* Edit Add Building Dialog *}
-<div id="building_dialog" class="glm-dialog-box" title="Edit this Building">
+<div id="building_dialog" class="glm-dialog-box" title="Edit Building">
     <form action="{$thisUrl}?page={$thisPage}" method="post">
         <input type="hidden" name="glm_action" value="settings">
         <input id="building_option" type="hidden" name="option" value="updateBuilding">
@@ -66,7 +66,7 @@
 {* End Building Dialog *}
 
 {* Edit Add Department Dialog *}
-<div id="department_dialog" class="glm-dialog-box" title="Edit this Department">
+<div id="department_dialog" class="glm-dialog-box" title="Edit Department">
     <form action="{$thisUrl}?page={$thisPage}" method="post">
         <input type="hidden" name="glm_action" value="settings">
         <input id="department_option" type="hidden" name="option" value="updateBuilding">
             $('#building_id').val(building_id);
             $('#building_name').val(building_name);
             $('#building_option').val('updateBuilding');
+            $('#building_dialog').dialog({ title: 'Edit Building'});
 
             // Open dialog
             $('#building_dialog').dialog('open');
             $('#building_id').val('');
             $('#building_name').val('');
             $('#building_option').val('addBuilding');
+            $('#building_dialog').dialog({ title: 'Add Building'});
 
             // Open dialog
             $('#building_dialog').dialog('open');
             $('#department_id').val(department_id);
             $('#department_name').val(department_name);
             $('#department_option').val('updateDepartment');
+            $('#department_dialog').dialog({ title: 'Edit Department'});
 
             // Open dialog
             $('#department_dialog').dialog('open');
             $('#department_id').val('');
             $('#department_name').val('');
             $('#department_option').val('addDepartment');
+            $('#department_dialog').dialog({ title: 'Add Department'});
 
             // Open dialog
             $('#department_dialog').dialog('open');