If this is your first visit, check our documentation. To post, register or login.
Forums / Zen Cart Code Suggestions / Add admin_id field to orders_status_history table

Add admin_id field to orders_status_history table

Started by lat9 on 19 Jul 2013, 7:53 PM · Views: 230

Results 1 to 20 of 20
19 Jul 2013, 7:53 PM
#1
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Add admin_id field to orders_status_history table

In a busy store, it's important to be able to identify where the orders_status changes (especially the comments) came from. I suggest adding an admin_id field to the orders_status_history table to accomplish this.

This field be displayed as the admin name as part of an order's status history display in the admin; no change required to the account_history_info page's details. A value of 0 (the default) would indicate that the order comment was entered by the customer.

19 Jul 2013, 8:08 PM
#2
drbyte avatar

drbyte

Sensei

Join Date:
Jan 2004
Posts:
63,512
Plugin Contributions:
176

Re: Add admin_id field to orders_status_history table

You'd want to also accommodate cases where a 3rd-party tool is doing direct database edits and injects an update but without having an admin login. So that's 2 defaults to accommodate.

Will give some thought to it. I like the suggestion.

.
Zen Cart - putting the dream of business ownership within reach of anyone!
Donate to: DrByte directly or to the Zen Cart team as a whole

Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

19 Jul 2013, 9:32 PM
#3
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Thanks, DrByte; I'll await your analysis.

20 Jul 2013, 10:31 PM
#4
lhungil avatar

lhungil

Totally Zenned

Join Date:
Feb 2012
Location:
mostly harmless
Posts:
1,816
Plugin Contributions:
4

Re: Add admin_id field to orders_status_history table

lat9:

In a busy store, it's important to be able to identify where the orders_status changes (especially the comments) came from. I suggest adding an admin_id field to the orders_status_history table to accomplish this. ...
+1, nice clean solution.

The glass is not half full. The glass is not half empty. The glass is simply too big!
Where are the Zen Cart Debug Logs? Where are the HTTP 500 / Server Error Logs?
Zen Cart related projects maintained by lhûngîl : Plugin / Module Tracker

23 Jul 2013, 10:19 PM
#5
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

DrByte:

You'd want to also accommodate cases where a 3rd-party tool is doing direct database edits and injects an update but without having an admin login. So that's 2 defaults to accommodate.

Will give some thought to it. I like the suggestion.
Could you give an example of such a 3rd-party tool? Just trying to get a feel for what the database change(s) would be.

24 Jul 2013, 2:22 AM
#6
drbyte avatar

drbyte

Sensei

Join Date:
Jan 2004
Posts:
63,512
Plugin Contributions:
176

Re: Add admin_id field to orders_status_history table

I was thinking of things like 3rd party fulfillment services that operate by installing a php file in the store's admin, and when they ship an order they make a call to that php handler file and have it update the order by updating/inserting the necessary records with direct database manipulation.
There are numerous such services, some with plugins in the plugins library, some are distributed only from their own site.

Unfortunately at this moment I can't think of any of the names of the many I've seen!

.
Zen Cart - putting the dream of business ownership within reach of anyone!
Donate to: DrByte directly or to the Zen Cart team as a whole

Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

24 Jul 2013, 3:59 AM
#7
lankeeyankee avatar

lankeeyankee

Totally Zenned

Join Date:
Jan 2007
Posts:
1,514
Plugin Contributions:
1

Re: Add admin_id field to orders_status_history table

I think shipworks does this and Numinix has one or two like the endicia exporter.


Zen Cart and it's community are the best!!

24 Jul 2013, 4:09 AM
#8
drbyte avatar

drbyte

Sensei

Join Date:
Jan 2004
Posts:
63,512
Plugin Contributions:
176

Re: Add admin_id field to orders_status_history table

lankeeyankee:

I think shipworks does this and Numinix has one or two like the endicia exporter.
Yes, like those! :)

.
Zen Cart - putting the dream of business ownership within reach of anyone!
Donate to: DrByte directly or to the Zen Cart team as a whole

Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

28 Jul 2013, 3:42 PM
#9
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

So, can I morph the suggestion into the addition of a field (updated_by, varchar(45) NOT NULL default '') to the orders_status_history table? That way, it's a free-form field that defaults to '' (empty string) when an order's first created and the community could arrive at some standardization of the text that's added to identify which admin has made the status update. I'm suggesting a varchar width of 45 since an admin's name is varchar(32) ...

I'd propose the format of this field as Admin Name [admin_id] to identify that a specific admin has created the update. The capture of the admin name is based on the idea that and admin might be here today ... but gone tomorrow!

I'd appreciate comments regarding this proposal as I'm trying to incorporate it into a couple of on-going projects!

28 Jul 2013, 5:59 PM
#10
lhungil avatar

lhungil

Totally Zenned

Join Date:
Feb 2012
Location:
mostly harmless
Posts:
1,816
Plugin Contributions:
4

Re: Add admin_id field to orders_status_history table

Just some further thoughts on the subject...

Storing text does make sense. I was thinking initially to just store an INT to save space in the database... But using a VARCHAR instead better handles the case where an admin user is deleted and allows programmatic updates to optionally specify what process added / changed the status (order created, payment modules, shipping modules, package tracking information, and the list goes on). While the same could be done using the comment to specify programmatic source... Placing the name of the process (programmatic update) in the column would make it easier "at a glance" to see the order flow.

An empty string can be used to indicate the source was the customer (saves space to not store the customer name as it is already in the orders table). Other sources can place the appropriate source information.

If for past orders (after a database upgrade) we want to be able to indicate the source was unknown... It may be beneficial to allow NULL values (as opposed to storing "unknown") to save space when a number of past orders exist. Of course for a clean install the column could probably be defined as not allowing NULL (which would save some space going forward).

Here is a quick mockup (not fully functional code):

  function update_order_status($message, $status = -1, $notify = -1, $user = null) {
    // Automatically determine the user if not provided
    if($user === null) {
      $user = ORDERS_STATUS_ADDEDBY_PROGRAM;
      if(IS_ADMIN_FLAG) {
        // Admin user logged into Zen Cart, use the admin_id
        if(isset($_SESSION['admin_id']))
          $user = zen_get_admin_name() . ' [' . (int)$_SESSION['admin_id'] . ']';
      }
      // On catalog side and user logged in
      else if(isset($_SESSION['customer_id'])) {
        $user = ORDERS_STATUS_ADDEDBY_CUSTOMER;
      }
    }

    // Rest of code to update the order status
  }

The glass is not half full. The glass is not half empty. The glass is simply too big!
Where are the Zen Cart Debug Logs? Where are the HTTP 500 / Server Error Logs?
Zen Cart related projects maintained by lhûngîl : Plugin / Module Tracker

29 Jul 2013, 12:06 PM
#11
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Since the order-status update can encompass other processes (e.g. additional fields, like Ty Package Tracker, or the monitoring of a status-change to trigger an event), perhaps it would be better to simply define the additional updated_by field and provide some "recommended usage" notes for plugin developers:

  1. If a status-update results from an admin user clicking a button (an overt action), it is recommended that the updated_by field be populated with the results of zen_updated_by_admin() (see below).
  2. If a status-update results from a process action, it is recommended that the updated_by field be populated with the "name" of that process. For example, a status-update created by a payment method would record the payment method's 'module code'.
  3. For a customer-triggered event (i.e. an order placed), updated_by is set to '' (empty string).
    FWIW, the first orders_status_history record associated with an order always traps the order-creation event so that store owners can safely assume that additional 'empty' updated_by fields are associated with admins and/or processes.
if (!function_exists('zen_updated_by_admin')) {
  function zen_updated_by_admin($admin_id = '') {
    if ($admin_id === '') {
      $admin_id = $_SESSION['admin_id'];
    }
    return zen_get_admin_name($admin_id) . " [$admin_id]";
  }
}
29 Jul 2013, 2:52 PM
#12
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Just to flesh it out ... I propose that any admin-level plugin that plans to use the updated_by feature include the following code fragment to ensure that the database field is created the same and that there is consistency in the "admin updated by" value:

  // -----
  // Provide the staging for the function that provides the "common" orders_status_history "updated_by" for an admin user.
  //
  if (IS_ADMIN_FLAG === true && !function_exists('zen_updated_by_admin')) {
    function zen_updated_by_admin($admin_id = '') {
      if ($admin_id === '') {
        $admin_id = $_SESSION['admin_id'];
      }
      return zen_get_admin_name($admin_id) . " [$admin_id]";
    }
    
    if ($sniffer->field_exists(TABLE_ORDERS_STATUS_HISTORY, 'updated_by') === false) {
      $db->Execute("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD updated_by varchar(45) NOT NULL default ''");
    }
  }
29 Jul 2013, 3:21 PM
#13
lhungil avatar

lhungil

Totally Zenned

Join Date:
Feb 2012
Location:
mostly harmless
Posts:
1,816
Plugin Contributions:
4

Re: Add admin_id field to orders_status_history table

lat9:

... Some "recommended usage" notes for plugin developers:

  1. If a status-update results from an admin user clicking a button (an overt action), it is recommended that the updated_by field be populated with the results of zen_updated_by_admin() (see below).
  1. If a status-update results from a process action, it is recommended that the updated_by field be populated with the "name" of that process. For example, a status-update created by a payment method would record the payment method's 'module code'.
  1. For a customer-triggered event (i.e. an order placed), updated_by is set to '' (empty string).

These sound good to me (and match my current thought process).

I would still like to see a convenience function / method (3rd parties do not need to use them) added to Zen Cart's core code. Preferably the function could be used on either the admin or catalog side of Zen Cart (and return the orders_status_history_id for the new record or -1 if not created). The function / method could then be used elsewhere in Zen Cart and 3rd party code (less code duplication). It would also provide example code for future coders.

lat9:

... FWIW, the first orders_status_history record associated with an order always traps the order-creation event so that store owners can safely assume that additional 'empty' updated_by fields are associated with admins and/or processes. ...
For stores w/o any modifications to the out-of-box Zen Cart 1.5.x order process flow, this is accurate. I can think of a few additional order process flows added by 3rd party modules resulting in the first orders_status_history record not being created by a customer... I can also think of a few process flows where the subsequent records may actually come from the customer...

The question is will a database upgrade assume no out-of-box order process flows (and document the source / updated_by may not be accurate for status histories added before the upgrade)? Or will the database upgrade take alternate order process flows into consideration and use NULL or specific text to indicate the order was from an older version and the source was not captured?

The glass is not half full. The glass is not half empty. The glass is simply too big!
Where are the Zen Cart Debug Logs? Where are the HTTP 500 / Server Error Logs?
Zen Cart related projects maintained by lhûngîl : Plugin / Module Tracker

29 Jul 2013, 3:28 PM
#14
drbyte avatar

drbyte

Sensei

Join Date:
Jan 2004
Posts:
63,512
Plugin Contributions:
176

Re: Add admin_id field to orders_status_history table

lhungil:

I can think of a few additional order process flows added by 3rd party modules resulting in the first orders_status_history record not being created by a customer... I can also think of a few process flows where the subsequent records may actually come from the customer...
Examples?

.
Zen Cart - putting the dream of business ownership within reach of anyone!
Donate to: DrByte directly or to the Zen Cart team as a whole

Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

29 Jul 2013, 4:05 PM
#15
lhungil avatar

lhungil

Totally Zenned

Join Date:
Feb 2012
Location:
mostly harmless
Posts:
1,816
Plugin Contributions:
4

Re: Add admin_id field to orders_status_history table

DrByte:

Examples?
Again, not saying the assumption cannot be made. Just suggesting the documentation should then provide a notice along the lines of "The updated_by field may not be 100% accurate for orders created before the upgrade (or modified by 3rd party code)".

Order process flows resulting in a first record being created by an administrative user.
Called In, Emailed, or Faxed In orders (some people still prefer calling / emailing the in). These orders are typically added via Admin New Order or Encrypted Master Password. Both of these can be used to allow administrative users to create orders for customers (I've seen both mentioned specifically for this purpose on the forums). The administrative user is then creating the order. It may be a semantic difference, but for auditing purposes I would want to know if the customer clicked the button or an administrative user clicked the button (on the customers behalf).

Admin New Order already logs the admin [admin_id] in the comments when the order is created, so not a big deal there... Orders created using Encrypted Master Password currently do not log anything to the effect the customer did not create the order.

Two examples of order process flows where a customer action generates the record.
These are less of a worry as I do not know of any publicly published modifications / plugins supporting these (at this time)... Request Quote -> Create Order -> Add Shipping -> Customer Payment + Confirm (Online or Phone). Create Order -> Customer Cancels (via website - before product has left warehouse / is shipped).

The glass is not half full. The glass is not half empty. The glass is simply too big!
Where are the Zen Cart Debug Logs? Where are the HTTP 500 / Server Error Logs?
Zen Cart related projects maintained by lhûngîl : Plugin / Module Tracker

29 Jul 2013, 4:09 PM
#16
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

lhungil:

... Orders created using Encrypted Master Password currently do not log anything to the effect the customer did not create the order.
That's on my list to update once we've got this interface ironed out ...

29 Jul 2013, 7:40 PM
#17
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Following is my proposal for a separately-included file for any plugin that desires to use this interface "before" it's part of the core. I propose that the code be delivered as /includes/functions/extra_functions/osh_updated_by_functions.php and/or /YOUR_ADMIN/includes/functions/extra_functions/osh_updated_by_functions.php. The language-related defines should be delivered as /YOUR_ADMIN/includes/languages/english/extra_definitions/osh_updated_by.php and are, essentially, copied from the current /YOUR_ADMIN/includes/languages/english/orders.php.

<?php
// -----
// Provide the staging for addition of the 'updated_by' field in the orders_status_history table
//
// -----
// 1) Add the updated_by column to the orders_status_history table, if it doesn't already exist.
//
if ($sniffer->field_exists($table_name, $field_name) === false) {
  $db->Execute("ALTER TABLE" . TABLE_ORDERS_STATUS_HISTORY . " ADD updated_by varchar(45) NOT NULL default ''");

}

// -----
// 2) If not already present, create an instance of the function that provides the "standard" updated_by
//    contents for an admin-related update.
//
if (IS_ADMIN_FLAG === true && !function_exists('zen_updated_by_admin')) {
  function zen_updated_by_admin($admin_id = '') {
    if ($admin_id === '') {
      $admin_id = $_SESSION['admin_id'];
    }
    
    return zen_get_admin_name($admin_id) . " [$admin_id]";
  }
}

// -----
// 3) If not already present, create an instance of the function that provides common handling for processes
//    that want to add an orders_status_history record for a specified order.
//
if (!function_exists('zen_update_orders_history')) {
  // -----
  // Inputs:
  // - $order_id .......... The order for which the status record is to be created
  // - $updated_by ........ If non-null, the specified value will be used for the like-named field.  Otherwise,
  //                        the value will be calculated based on some defaults.
  // - $orders_status ..... The orders_status value for the update.  If set to -1, no change in the status value was detected.
  // - $notify_customer ... Identifies whether the history record is sent and visible to the customer (0), 
  //                        visible but not sent (1) or hidden from the customer (-1).
  // - $message ........... The comments associated with the history record, if non-blank.
  //
  // Returns:
  // - $osh_id ............ Either -1 if no update occurred or the inserted orders_status_history_id value.
  //
  function zen_update_orders_history($orders_id, $updated_by = null, $orders_status = -1, $notify_customer = -1, $message = '') {
    global $zco_notifier;
    $osh_id = -1;
    $orders_id = (int)$orders_id;
    $osh_info = $db->Execute("SELECT customers_name, customers_email_address, orders_status, date_purchased FROM " . TABLE_ORDERS . " WHERE orders_id = $orders_id" );
    if ( ($orders_status != -1 && $osh_info->fields['orders_status'] != $orders_status) || zen_not_null($message)) {
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_STATUS_VALUES', array ( 'new' => $orders_status, 'old' => $osh_info->fields['orders_status'] ));
      $db->Execute( "UPDATE " . TABLE_ORDERS . " SET orders_status = '" . zen_db_input($orders_status) . "', last_modified = now() WHERE orders_id = $orders_id" );
      
      if (IS_ADMIN_FLAG === true && $notify_customer == 1) {
        $email_comments = (zen_not_null($message)) ? (EMAIL_TEXT_COMMENTS_UPDATE . $comments . "\n\n") : '';
 
        //send emails
        $email_text =
          EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
          EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') . "\n\n" .
          EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']) . "\n\n" .
          strip_tags($notify_comments) .
          EMAIL_TEXT_STATUS_UPDATED . sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_array[$status] ) .
          EMAIL_TEXT_STATUS_PLEASE_REPLY;

        $html_msg['EMAIL_CUSTOMERS_NAME']    = $osh_info->fields['customers_name'];
        $html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
        $html_msg['EMAIL_TEXT_INVOICE_URL']  = '<a href="' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') .'">'.str_replace(':','',EMAIL_TEXT_INVOICE_URL).'</a>';
        $html_msg['EMAIL_TEXT_DATE_ORDERED'] = EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']);
        $html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($notify_comments);
        $html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', EMAIL_TEXT_STATUS_UPDATED);
        $html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_array[$status] ));
        $html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_array[$status];
        $html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', EMAIL_TEXT_STATUS_PLEASE_REPLY);
        $html_msg['EMAIL_PAYPAL_TRANSID'] = '';

        zen_mail($osh_info->fields['customers_name'], $osh_info->fields['customers_email_address'], EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');

        // PayPal Trans ID, if any
        $sql = "SELECT txn_id, parent_txn_id FROM " . TABLE_PAYPAL . " WHERE order_id = :orderID ORDER BY last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
        $sql = $db->bindVars($sql, ':orderID', $orders_id, 'integer');
        $result = $db->Execute($sql);
        if ($result->RecordCount() > 0) {
          $email_text .= "\n\n" . ' PayPal Trans ID: ' . $result->fields['txn_id'];
          $html_msg['EMAIL_PAYPAL_TRANSID'] = $result->fields['txn_id'];
        }

        //send extra emails
        if (SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1' and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
          zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
        }
        
      }
      
      if (!zen_not_null($updated_by)) {
        if (IS_ADMIN_FLAG === true && isset($_SESSION['admin_id'])) {
          $updated_by = zen_updated_by_admin();
          
        } elseif (IS_ADMIN_FLAG === false && isset($_SESSION['customers_id']) {
          $updated_by = '';
          
        } else {
          $updated_by = 'N/A';
          
        }
      }
      
      $osh_sql = array ( 'orders_id' => (int)$orders_id,
                         'orders_status_id' => zen_db_input($orders_status),
                         'date_added' => 'now()',
                         'customer_notified' => zen_db_input($notify_customer),
                         'comments' => zen_db_input($message),
                         'updated_by' => $updated_by
                         );
                         
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_BEFORE_INSERT', array(), $osh_sql);
      
      $osh_id = zen_db_perform (TABLE_ORDERS_STATUS_HISTORY, $osh_sql);

    }
    
    return $osh_id;
  }
}
29 Jul 2013, 9:33 PM
#18
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Ouch, that was painful!:blush: The code attached below works a whole lot better. I chose to have the 'prime' code only on the storefront side and to include it via /YOUR_ADMIN/includes/functions/extra_functions/osh_updated_by_admin_functions.php:

<?php
include (DIR_FS_CATALOG . 'includes/functions/extra_functions/osh_updated_by_functions.php');

Here's the version that's actually been tested ...

<?php
// -----
// Provide the staging for addition of the 'updated_by' field in the orders_status_history table
//
// -----
// 1) Add the updated_by column to the orders_status_history table, if it doesn't already exist.
//
if ($sniffer->field_exists(TABLE_ORDERS_STATUS_HISTORY, 'updated_by') === false) {
  $db->Execute("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD updated_by varchar(45) NOT NULL default ''");

}

// -----
// 2) If not already present, create an instance of the function that provides the "standard" updated_by
//    contents for an admin-related update.
//
if (IS_ADMIN_FLAG === true && !function_exists('zen_updated_by_admin')) {
  function zen_updated_by_admin($admin_id = '') {
    if ($admin_id === '') {
      $admin_id = $_SESSION['admin_id'];
    }
    
    return zen_get_admin_name($admin_id) . " [$admin_id]";
  }
}

// -----
// 3) If not already present, create an instance of the function that provides common handling for processes
//    that want to add an orders_status_history record for a specified order.
//
if (!function_exists('zen_update_orders_history')) {
  // -----
  // Inputs:
  // - $order_id .......... The order for which the status record is to be created
  // - $updated_by ........ If non-null, the specified value will be used for the like-named field.  Otherwise,
  //                        the value will be calculated based on some defaults.
  // - $orders_status ..... The orders_status value for the update.  If set to -1, no change in the status value was detected.
  // - $notify_customer ... Identifies whether the history record is sent and visible to the customer (0), 
  //                        visible but not sent (1) or hidden from the customer (-1).
  // - $message ........... The comments associated with the history record, if non-blank.
  //
  // Returns:
  // - $osh_id ............ Either -1 if no update occurred or the inserted orders_status_history_id value.
  //
  function zen_update_orders_history($orders_id, $updated_by = null, $orders_status = -1, $notify_customer = -1, $message = '', $email_include_message = true) {
    global $db, $zco_notifier;
    $osh_id = -1;
    $orders_id = (int)$orders_id;
    $osh_info = $db->Execute("SELECT customers_name, customers_email_address, orders_status, date_purchased FROM " . TABLE_ORDERS . " WHERE orders_id = $orders_id" );
    if ( !$osh_info->EOF && (($orders_status != -1 && $osh_info->fields['orders_status'] != $orders_status) || zen_not_null($message))) {
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_STATUS_VALUES', array ( 'new' => $orders_status, 'old' => $osh_info->fields['orders_status'] ));
      
      if ($orders_status == -1) {
        $orders_status = $osh_info->fields['orders_status'];
      }
      $db->Execute( "UPDATE " . TABLE_ORDERS . " SET orders_status = '" . zen_db_input($orders_status) . "', last_modified = now() WHERE orders_id = $orders_id" );
      
      if (IS_ADMIN_FLAG === true && $notify_customer == 1) {
        $status_name = $db->Execute("SELECT orders_status_name FROM " . TABLE_ORDERS_STATUS . " WHERE orders_status_id = " . (int)$order_status . " AND language_id = " . (int)$_SESSION['languages_id']);
        $orders_status_name = ($status_name->EOF) ? 'N/A' : $status_name->fields['orders_status_name'];

        $email_comments = (zen_not_null($message) && $email_include_message === true) ? (EMAIL_TEXT_COMMENTS_UPDATE . $message . "\n\n") : '';
 
        //send emails
        $email_text =
          EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
          EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') . "\n\n" .
          EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']) . "\n\n" .
          strip_tags($email_comments) .
          EMAIL_TEXT_STATUS_UPDATED . sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ) .
          EMAIL_TEXT_STATUS_PLEASE_REPLY;

        $html_msg['EMAIL_CUSTOMERS_NAME']    = $osh_info->fields['customers_name'];
        $html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
        $html_msg['EMAIL_TEXT_INVOICE_URL']  = '<a href="' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') .'">'.str_replace(':','',EMAIL_TEXT_INVOICE_URL).'</a>';
        $html_msg['EMAIL_TEXT_DATE_ORDERED'] = EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']);
        $html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($email_comments);
        $html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', EMAIL_TEXT_STATUS_UPDATED);
        $html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ));
        $html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_name;
        $html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', EMAIL_TEXT_STATUS_PLEASE_REPLY);
        $html_msg['EMAIL_PAYPAL_TRANSID'] = '';

        zen_mail($osh_info->fields['customers_name'], $osh_info->fields['customers_email_address'], EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');

        // PayPal Trans ID, if any
        $sql = "SELECT txn_id, parent_txn_id FROM " . TABLE_PAYPAL . " WHERE order_id = :orderID ORDER BY last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
        $sql = $db->bindVars($sql, ':orderID', $orders_id, 'integer');
        $result = $db->Execute($sql);
        if ($result->RecordCount() > 0) {
          $email_text .= "\n\n" . ' PayPal Trans ID: ' . $result->fields['txn_id'];
          $html_msg['EMAIL_PAYPAL_TRANSID'] = $result->fields['txn_id'];
        }

        //send extra emails
        if (SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1' and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
          zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
        }
        
      }
      
      if (!zen_not_null($updated_by)) {
        if (IS_ADMIN_FLAG === true && isset($_SESSION['admin_id'])) {
          $updated_by = zen_updated_by_admin();
          
        } elseif (IS_ADMIN_FLAG === false && isset($_SESSION['customers_id'])) {
          $updated_by = '';
          
        } else {
          $updated_by = 'N/A';
          
        }
      }
      
      $osh_sql = array ( 'orders_id' => $orders_id,
                         'orders_status_id' => zen_db_input($orders_status),
                         'date_added' => 'now()',
                         'customer_notified' => zen_db_input($notify_customer),
                         'comments' => zen_db_input($message),
                         'updated_by' => zen_db_input($updated_by)
                         );
                         
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_BEFORE_INSERT', array(), $osh_sql);
      
      zen_db_perform (TABLE_ORDERS_STATUS_HISTORY, $osh_sql);
      $osh_id = $db->Insert_ID();

    }
    
    return $osh_id;
  }
}

Here's a code fragment from /YOUR_ADMIN/orders.php showing how the orders-status update section changes:

      case 'update_order':
        // demo active test
        if (zen_admin_demo()) {
          $_GET['action']= '';
          $messageStack->add_session(ERROR_ADMIN_DEMO, 'caution');
          zen_redirect(zen_href_link(FILENAME_ORDERS, zen_get_all_get_params(array('action')) . 'action=edit', 'NONSSL'));
        }
        $oID = zen_db_prepare_input($_GET['oID']);
        $comments = zen_db_prepare_input($_POST['comments']);
        $status = (int)zen_db_prepare_input($_POST['status']);
        if ($status < 1) break;

//-bof-changes for common orders_history updating 
/* ----- Processing now handled by separate function -----
        $order_updated = false;
        $check_status = $db->Execute("select customers_name, customers_email_address, orders_status,
                                      date_purchased from " . TABLE_ORDERS . "
                                      where orders_id = '" . (int)$oID . "'");

        if ( ($check_status->fields['orders_status'] != $status) || zen_not_null($comments)) {
          $db->Execute("update " . TABLE_ORDERS . "
                        set orders_status = '" . zen_db_input($status) . "', last_modified = now()
                        where orders_id = '" . (int)$oID . "'");

          $customer_notified = '0';
          if (isset($_POST['notify']) && ($_POST['notify'] == '1')) {

            $notify_comments = '';
            if (isset($_POST['notify_comments']) && ($_POST['notify_comments'] == 'on') && zen_not_null($comments)) {
              $notify_comments = EMAIL_TEXT_COMMENTS_UPDATE . $comments . "\n\n";
            }
            //send emails
            $message =
            EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID . "\n\n" .
            EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL') . "\n\n" .
            EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']) . "\n\n" .
            strip_tags($notify_comments) .
            EMAIL_TEXT_STATUS_UPDATED . sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_array[$status] ) .
            EMAIL_TEXT_STATUS_PLEASE_REPLY;

            $html_msg['EMAIL_CUSTOMERS_NAME']    = $check_status->fields['customers_name'];
            $html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID;
            $html_msg['EMAIL_TEXT_INVOICE_URL']  = '<a href="' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL') .'">'.str_replace(':','',EMAIL_TEXT_INVOICE_URL).'</a>';
            $html_msg['EMAIL_TEXT_DATE_ORDERED'] = EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($check_status->fields['date_purchased']);
            $html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($notify_comments);
            $html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', EMAIL_TEXT_STATUS_UPDATED);
            $html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_array[$status] ));
            $html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_array[$status];
            $html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', EMAIL_TEXT_STATUS_PLEASE_REPLY);
            $html_msg['EMAIL_PAYPAL_TRANSID'] = '';

            zen_mail($check_status->fields['customers_name'], $check_status->fields['customers_email_address'], EMAIL_TEXT_SUBJECT . ' #' . $oID, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');
            $customer_notified = '1';

            // PayPal Trans ID, if any
            $sql = "select txn_id, parent_txn_id from " . TABLE_PAYPAL . " where order_id = :orderID order by last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
            $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
            $result = $db->Execute($sql);
            if ($result->RecordCount() > 0) {
              $message .= "\n\n" . ' PayPal Trans ID: ' . $result->fields['txn_id'];
              $html_msg['EMAIL_PAYPAL_TRANSID'] = $result->fields['txn_id'];
            }

            //send extra emails
            if (SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1' and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
              zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . EMAIL_TEXT_SUBJECT . ' #' . $oID, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
            }
          } elseif (isset($_POST['notify']) && ($_POST['notify'] == '-1')) {
            // hide comment
            $customer_notified = '-1';
          }
          
          $db->Execute("insert into " . TABLE_ORDERS_STATUS_HISTORY . "
                      (orders_id, orders_status_id, date_added, customer_notified, comments) 
                      values ('" . (int)$oID . "',
                      '" . zen_db_input($status) . "',
                      now(),
                      '" . zen_db_input($customer_notified) . "',
                      '" . zen_db_input($comments) . "')");

          $order_updated = true;
          
        }
*/
        $customer_notified = '0';
        if (isset($_POST['notify']) && ($_POST['notify'] == '1' || $_POST['notify'] == '-1')) {
          $customer_notified = $_POST['notify'];
        }

        $osh_record_added = zen_update_orders_history($oID, null, $status, $customer_notified, $comments, (isset($_POST['notify_comments']) && $_POST['notify_comments'] == 'on'));
        $order_updated = ($osh_record_added == -1) ? false : true;

//-eof-changes for common orders_history updating 

        // trigger any appropriate updates which should be sent back to the payment gateway:
30 Jul 2013, 1:47 PM
#19
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Continuing on. I've made a couple of enhancements and corrections: /includes/functions/extra_functions/osh_updated_by_functions.php:

<?php
// -----
// Provide the staging for addition of the 'updated_by' field in the orders_status_history table
//
//  CHANGE HISTORY:
//  20130730 - 0.0.3:
//    - Modified parameter input order for zen_update_orders_history (moved $message to parm 2).
//    - Made $osh_sql global, to allow admin notifier-observers (pre ZC v1.6.0) to modify the inputs (like Ty Package Tracker).
//    - Added verification of the $customer_notified variable, so the callers don't have to.
//    - Modified the return values to make a distinction between "not updated" and "no order found".
//    - Updated orders_status name always returned "N/A"
//
define('OSH_UPDATED_BY_VERSION', '0.0.3');
// -----
// 1) Add the updated_by column to the orders_status_history table, if it doesn't already exist.
//
if ($sniffer->field_exists(TABLE_ORDERS_STATUS_HISTORY, 'updated_by') === false) {
  $db->Execute("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD updated_by varchar(45) NOT NULL default ''");

}

// -----
// 2) If not already present, create an instance of the function that provides the "standard" updated_by
//    contents for an admin-related update.
//
if (IS_ADMIN_FLAG === true && !function_exists('zen_updated_by_admin')) {
  function zen_updated_by_admin($admin_id = '') {
    if ($admin_id === '') {
      $admin_id = $_SESSION['admin_id'];
    }
    
    return zen_get_admin_name($admin_id) . " [$admin_id]";
  }
}

// -----
// 3) If not already present, create an instance of the function that provides common handling for processes
//    that want to add an orders_status_history record for a specified order.
//
if (!function_exists('zen_update_orders_history')) {
  // -----
  // Inputs:
  // - $order_id .......... The order for which the status record is to be created
  // - $updated_by ........ If non-null, the specified value will be used for the like-named field.  Otherwise,
  //                        the value will be calculated based on some defaults.
  // - $orders_status ..... The orders_status value for the update.  If set to -1, no change in the status value was detected.
  // - $notify_customer ... Identifies whether the history record is sent and visible to the customer (0), 
  //                        visible but not sent (1) or hidden from the customer (-1).
  // - $message ........... The comments associated with the history record, if non-blank.
  //
  // Returns:
  // - $osh_id ............ A value > 0 if the record has been written (the orders_status_history_id number)
  //                        -2 if no order record was found for the specified $orders_id
  //                        -1 if no status change was detected (i.e. no record written).
  //
  function zen_update_orders_history($orders_id, $message = '', $updated_by = null, $orders_status = -1, $notify_customer = -1, $email_include_message = true) {
    global $db, $zco_notifier, $osh_sql;
    $osh_id = -1;
    $orders_id = (int)$orders_id;
    $osh_info = $db->Execute("SELECT customers_name, customers_email_address, orders_status, date_purchased FROM " . TABLE_ORDERS . " WHERE orders_id = $orders_id" );
    if ( $osh_info->EOF ) {
      $osh_id = -2;
      
    } elseif (($orders_status != -1 && $osh_info->fields['orders_status'] != $orders_status) || zen_not_null($message)) {
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_STATUS_VALUES', array ( 'new' => $orders_status, 'old' => $osh_info->fields['orders_status'] ));
      
      if ($orders_status == -1) {
        $orders_status = $osh_info->fields['orders_status'];
      }
      $db->Execute( "UPDATE " . TABLE_ORDERS . " SET orders_status = '" . zen_db_input($orders_status) . "', last_modified = now() WHERE orders_id = $orders_id" );
      
      $notify_customer = (isset($notify_customer) && ($notify_customer == 1 || $notify_customer == -1)) ? $notify_customer : 0;
      
      if (IS_ADMIN_FLAG === true && $notify_customer == 1) {
        $status_name = $db->Execute("SELECT orders_status_name FROM " . TABLE_ORDERS_STATUS . " WHERE orders_status_id = " . (int)$orders_status . " AND language_id = " . (int)$_SESSION['languages_id']);
        $orders_status_name = ($status_name->EOF) ? 'N/A' : $status_name->fields['orders_status_name'];

        $email_comments = (zen_not_null($message) && $email_include_message === true) ? (EMAIL_TEXT_COMMENTS_UPDATE . $message . "\n\n") : '';
 
        //send emails
        $email_text =
          STORE_NAME . ' ' . EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
          EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') . "\n\n" .
          EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']) . "\n\n" .
          strip_tags($email_comments) .
          EMAIL_TEXT_STATUS_UPDATED . sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ) .
          EMAIL_TEXT_STATUS_PLEASE_REPLY;

        $html_msg['EMAIL_CUSTOMERS_NAME']    = $osh_info->fields['customers_name'];
        $html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
        $html_msg['EMAIL_TEXT_INVOICE_URL']  = '<a href="' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') .'">'.str_replace(':','',EMAIL_TEXT_INVOICE_URL).'</a>';
        $html_msg['EMAIL_TEXT_DATE_ORDERED'] = EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']);
        $html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($email_comments);
        $html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', EMAIL_TEXT_STATUS_UPDATED);
        $html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ));
        $html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_name;
        $html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', EMAIL_TEXT_STATUS_PLEASE_REPLY);
        $html_msg['EMAIL_PAYPAL_TRANSID'] = '';

        zen_mail($osh_info->fields['customers_name'], $osh_info->fields['customers_email_address'], EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');

        // PayPal Trans ID, if any
        $sql = "SELECT txn_id, parent_txn_id FROM " . TABLE_PAYPAL . " WHERE order_id = :orderID ORDER BY last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
        $sql = $db->bindVars($sql, ':orderID', $orders_id, 'integer');
        $result = $db->Execute($sql);
        if ($result->RecordCount() > 0) {
          $email_text .= "\n\n" . ' PayPal Trans ID: ' . $result->fields['txn_id'];
          $html_msg['EMAIL_PAYPAL_TRANSID'] = $result->fields['txn_id'];
        }

        //send extra emails
        if (SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1' and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
          zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
        }
        
      }
      
      if (!zen_not_null($updated_by)) {
        if (IS_ADMIN_FLAG === true && isset($_SESSION['admin_id'])) {
          $updated_by = zen_updated_by_admin();
          
        } elseif (IS_ADMIN_FLAG === false && isset($_SESSION['customers_id'])) {
          $updated_by = '';
          
        } else {
          $updated_by = 'N/A';
          
        }
      }
      
      $osh_sql = array ( 'orders_id' => $orders_id,
                         'orders_status_id' => zen_db_input($orders_status),
                         'date_added' => 'now()',
                         'customer_notified' => zen_db_input($notify_customer),
                         'comments' => zen_db_input($message),
                         'updated_by' => zen_db_input($updated_by)
                         );
                         
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_BEFORE_INSERT', array(), $osh_sql);
      
      zen_db_perform (TABLE_ORDERS_STATUS_HISTORY, $osh_sql);
      $osh_id = $db->Insert_ID();

    }
    
    return $osh_id;
  }
}

Also needed a bit more to the replacement code in /YOUR_ADMIN/orders.php, specifically the $check_status information that's used by the code below this fragment:

        $check_status = $db->Execute("SELECT orders_status, date_purchased FROM " . TABLE_ORDERS . " WHERE orders_id = '" . (int)$oID . "'");
        $customer_notified = (isset($_POST['notify']) && ($_POST['notify'] == 1 || $_POST['notify'] == -1)) ? $_POST['notify'] : 0;
        $osh_record_added = zen_update_orders_history($oID, $comments, null, $status, $customer_notified,, (isset($_POST['notify_comments']) && $_POST['notify_comments'] == 'on'));
        $order_updated = ($osh_record_added == -1) ? false : true;

Checked this out with Ty Package Tracker (which adds status information on the admin's Customers->Orders screen) by creating two files:
/YOUR_ADMIN/includes/auto_loaders/config.ty_package_tracker.php:

<?php
// -----
// Autoloader for the Ty Package Tracker admin processing
//
if (!defined('IS_ADMIN_FLAG')) {
  die('Illegal Access');
} 

$autoLoadConfig[200][] = array(
  'autoType'  => 'class',
  'loadFile'  => 'observers/class.ty_package_tracker.php',
  'classPath' => DIR_WS_CLASSES);
$autoLoadConfig[200][] = array(
  'autoType'   => 'classInstantiate',
  'className'  => 'ty_package_tracker_observer',
  'objectName' => 'ty_package_tracker_observer');

and /YOUR_ADMIN/includes/classes/observers/class.ty_package_tracker.php (also copied the index.html from from /includes/classes/observers):

<?php
// -----
// Observer class for the Ty Package Tracker plugin.  Allows the plugin to add its fields to the
// common orders_status_history record updater.
//
if (!defined('IS_ADMIN_FLAG') || IS_ADMIN_FLAG !== true) {
  die('Illegal Access');
}

class ty_package_tracker_observer extends base {

  function ty_package_tracker_observer() {
    $this->attach($this, array('ZEN_UPDATE_ORDERS_HISTORY_BEFORE_INSERT'));
  }
  
  function update(&$class, $eventID, $paramsArray, &$p2, &$p3, &$p4, &$p5, &$p6, &$p7) {
    global $osh_sql, $current_page;
    
    if ($current_page == 'orders.php' || $current_page == 'edit_orders.php') {
      $osh_sql['track_id1'] = str_replace(" ", "", zen_db_prepare_input($_POST['track_id1']));
      $osh_sql['track_id2'] = str_replace(" ", "", zen_db_prepare_input($_POST['track_id2']));
      $osh_sql['track_id3'] = str_replace(" ", "", zen_db_prepare_input($_POST['track_id3']));
      $osh_sql['track_id4'] = str_replace(" ", "", zen_db_prepare_input($_POST['track_id4']));
      $osh_sql['track_id5'] = str_replace(" ", "", zen_db_prepare_input($_POST['track_id5']));
    }    
  }
 
}
5 Aug 2013, 1:00 PM
#20
lat9 avatar

lat9

Administrator

Join Date:
Sep 2009
Location:
Stuart, FL
Posts:
14,142
Plugin Contributions:
56

Re: Add admin_id field to orders_status_history table

Another refinement to /includes/functions/extra_functions/osh_updated_by_functions.php:

<?php
// -----
// Provide the staging for addition of the 'updated_by' field in the orders_status_history table
//
//  CHANGE HISTORY:
//  20130730 - 0.0.3:
//    - Modified parameter input order for zen_update_orders_history (moved $message to parm 2).
//    - Made $osh_sql global, to allow admin notifier-observers (pre ZC v1.6.0) to modify the inputs (like Ty Package Tracker).
//    - Added verification of the $customer_notified variable, so the callers don't have to.
//    - Modified the return values to make a distinction between "not updated" and "no order found".
//    - Updated orders_status name always returned "N/A"
//  20130805 - 0.0.4:
//    - Pass the order_id value on the old/new orders status notification
//    - Added ZEN_UPDATE_ORDERS_HISTORY_PRE_EMAIL notifier to allow plugins to add to the email message to be sent to the customer.
//    - "unset" the global variables created by the zen_update_orders_history function
//
define('OSH_UPDATED_BY_VERSION', '0.0.4');
// -----
// 1) Add the updated_by column to the orders_status_history table, if it doesn't already exist.
//
if ($sniffer->field_exists(TABLE_ORDERS_STATUS_HISTORY, 'updated_by') === false) {
  $db->Execute("ALTER TABLE " . TABLE_ORDERS_STATUS_HISTORY . " ADD updated_by varchar(45) NOT NULL default ''");

}

// -----
// 2) If not already present, create an instance of the function that provides the "standard" updated_by
//    contents for an admin-related update.
//
if (IS_ADMIN_FLAG === true && !function_exists('zen_updated_by_admin')) {
  function zen_updated_by_admin($admin_id = '') {
    if ($admin_id === '') {
      $admin_id = $_SESSION['admin_id'];
    }
    
    return zen_get_admin_name($admin_id) . " [$admin_id]";
  }
}

// -----
// 3) If not already present, create an instance of the function that provides common handling for processes
//    that want to add an orders_status_history record for a specified order.
//
if (!function_exists('zen_update_orders_history')) {
  // -----
  // Inputs:
  // - $order_id ................ The order for which the status record is to be created
  // - $updated_by .............. If non-null, the specified value will be used for the like-named field.  Otherwise,
  //                              the value will be calculated based on some defaults.
  // - $orders_status ........... The orders_status value for the update.  If set to -1, no change in the status value was detected.
  // - $notify_customer ......... Identifies whether the history record is sent and visible to the customer (0), 
  //                              visible but not sent (1) or hidden from the customer (-1).
  // - $message ................. The comments associated with the history record, if non-blank.
  // - $email_include_message ... Identifies whether (true) or not (false) to include the status message ($message) in any email sent.
  //
  // Returns:
  // - $osh_id ............ A value > 0 if the record has been written (the orders_status_history_id number)
  //                        -2 if no order record was found for the specified $orders_id
  //                        -1 if no status change was detected (i.e. no record written).
  //
  function zen_update_orders_history($orders_id, $message = '', $updated_by = null, $orders_status = -1, $notify_customer = -1, $email_include_message = true) {
    global $db, $zco_notifier, $osh_sql;
    global $osh_additional_comments;  /*v0.0.4a*/
    $osh_id = -1;
    $orders_id = (int)$orders_id;
    $osh_info = $db->Execute("SELECT customers_name, customers_email_address, orders_status, date_purchased FROM " . TABLE_ORDERS . " WHERE orders_id = $orders_id" );
    if ( $osh_info->EOF ) {
      $osh_id = -2;
      
    } elseif (($orders_status != -1 && $osh_info->fields['orders_status'] != $orders_status) || zen_not_null($message)) {
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_STATUS_VALUES', array ( /*-bof-a-v0.0.4*/ 'orders_id' => $orders_id, /*-eof-a-v0.0.4*/ 'new' => $orders_status, 'old' => $osh_info->fields['orders_status'] ));
      
      if ($orders_status == -1) {
        $orders_status = $osh_info->fields['orders_status'];
      }
      $db->Execute( "UPDATE " . TABLE_ORDERS . " SET orders_status = '" . zen_db_input($orders_status) . "', last_modified = now() WHERE orders_id = $orders_id" );
      
      $notify_customer = (isset($notify_customer) && ($notify_customer == 1 || $notify_customer == -1)) ? $notify_customer : 0;
      
      if (IS_ADMIN_FLAG === true && $notify_customer == 1) {
        $status_name = $db->Execute("SELECT orders_status_name FROM " . TABLE_ORDERS_STATUS . " WHERE orders_status_id = " . (int)$orders_status . " AND language_id = " . (int)$_SESSION['languages_id']);
        $orders_status_name = ($status_name->EOF) ? 'N/A' : $status_name->fields['orders_status_name'];
        
//-bof-a-v0.0.4
        if ($email_include_message === true) {
          $osh_additional_comments = '';
          $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_PRE_EMAIL', array( 'message' => $message ) );
          if ($osh_additional_comments != '') {
            $message = $message . "\n\n" . $osh_additional_message;
          }
          unset($osh_additional_comments);
        }
//-eof-a-v0.0.4

        $email_comments = (zen_not_null($message) && $email_include_message === true) ? (EMAIL_TEXT_COMMENTS_UPDATE . $message . "\n\n") : '';
 
        //send emails
        $email_text =
          STORE_NAME . ' ' . EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id . "\n\n" .
          EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') . "\n\n" .
          EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']) . "\n\n" .
          strip_tags($email_comments) .
          EMAIL_TEXT_STATUS_UPDATED . sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ) .
          EMAIL_TEXT_STATUS_PLEASE_REPLY;

        $html_msg['EMAIL_CUSTOMERS_NAME']    = $osh_info->fields['customers_name'];
        $html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id;
        $html_msg['EMAIL_TEXT_INVOICE_URL']  = '<a href="' . zen_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $orders_id, 'SSL') .'">'.str_replace(':','',EMAIL_TEXT_INVOICE_URL).'</a>';
        $html_msg['EMAIL_TEXT_DATE_ORDERED'] = EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long($osh_info->fields['date_purchased']);
        $html_msg['EMAIL_TEXT_STATUS_COMMENTS'] = nl2br($email_comments);
        $html_msg['EMAIL_TEXT_STATUS_UPDATED'] = str_replace('\n','', EMAIL_TEXT_STATUS_UPDATED);
        $html_msg['EMAIL_TEXT_STATUS_LABEL'] = str_replace('\n','', sprintf(EMAIL_TEXT_STATUS_LABEL, $orders_status_name ));
        $html_msg['EMAIL_TEXT_NEW_STATUS'] = $orders_status_name;
        $html_msg['EMAIL_TEXT_STATUS_PLEASE_REPLY'] = str_replace('\n','', EMAIL_TEXT_STATUS_PLEASE_REPLY);
        $html_msg['EMAIL_PAYPAL_TRANSID'] = '';

        zen_mail($osh_info->fields['customers_name'], $osh_info->fields['customers_email_address'], EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status');

        // PayPal Trans ID, if any
        $sql = "SELECT txn_id, parent_txn_id FROM " . TABLE_PAYPAL . " WHERE order_id = :orderID ORDER BY last_modified DESC, date_added DESC, parent_txn_id DESC, paypal_ipn_id DESC ";
        $sql = $db->bindVars($sql, ':orderID', $orders_id, 'integer');
        $result = $db->Execute($sql);
        if ($result->RecordCount() > 0) {
          $email_text .= "\n\n" . ' PayPal Trans ID: ' . $result->fields['txn_id'];
          $html_msg['EMAIL_PAYPAL_TRANSID'] = $result->fields['txn_id'];
        }

        //send extra emails
        if (SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_STATUS == '1' and SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO != '') {
          zen_mail('', SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO, SEND_EXTRA_ORDERS_STATUS_ADMIN_EMAILS_TO_SUBJECT . ' ' . EMAIL_TEXT_SUBJECT . ' #' . $orders_id, $email_text, STORE_NAME, EMAIL_FROM, $html_msg, 'order_status_extra');
        }
        
      }
      
      if (!zen_not_null($updated_by)) {
        if (IS_ADMIN_FLAG === true && isset($_SESSION['admin_id'])) {
          $updated_by = zen_updated_by_admin();
          
        } elseif (IS_ADMIN_FLAG === false && isset($_SESSION['customers_id'])) {
          $updated_by = '';
          
        } else {
          $updated_by = 'N/A';
          
        }
      }
      
      $osh_sql = array ( 'orders_id' => $orders_id,
                         'orders_status_id' => zen_db_input($orders_status),
                         'date_added' => 'now()',
                         'customer_notified' => zen_db_input($notify_customer),
                         'comments' => zen_db_input($message),
                         'updated_by' => zen_db_input($updated_by)
                         );
                         
      $zco_notifier->notify('ZEN_UPDATE_ORDERS_HISTORY_BEFORE_INSERT');
      
      zen_db_perform (TABLE_ORDERS_STATUS_HISTORY, $osh_sql);
      unset($osh_sql);  /*v0.0.4a*/
      $osh_id = $db->Insert_ID();

    }
    
    return $osh_id;
  }
}