Index: uc_multiprice_import/uc_multiprice_import.info
===================================================================
--- uc_multiprice_import/uc_multiprice_import.info	(revision 0)
+++ uc_multiprice_import/uc_multiprice_import.info	(revision 0)
@@ -0,0 +1,11 @@
+; $Id: uc_multiprice_import.info,v 6.x.0.1 2010/10/21 00:00:00 Bartezz Exp $
+name = Multiprice Import
+description = Allows import of charcater delimited files for Multiprice module
+version = VERSION
+core = 6.x
+package = Ubercart - extra
+dependencies[] = uc_multiprice
+
+version = "6.x-0.1-beta1"
+core = "6.x"
+project = "uc_multiprice_import"
Index: uc_multiprice_import/uc_multiprice_import.install
===================================================================
--- uc_multiprice_import/uc_multiprice_import.install	(revision 0)
+++ uc_multiprice_import/uc_multiprice_import.install	(revision 0)
@@ -0,0 +1,24 @@
+<?php
+// $Id: uc_multiprice_import.info,v 6.x.0.1 2010/10/21 00:00:00 Bartezz Exp $
+
+/**
+ * @file
+ *   UC Multiprice import module install/schema hooks.
+ */
+
+/**
+ * Implementation of hook_install().
+ * This will install the module, create the neccesary variables and database
+ */
+function uc_multiprice_import_install() {
+  drupal_set_message(st('Multiprice import module installed successfully.'));
+}
+
+/**
+ * Implementation of hook_uninstall().
+ * This will delete the uc_multiprice_import.module database
+ * table and the module's variables
+ */
+function uc_multiprice_import_uninstall() {
+  cache_clear_all('variables', 'cache');
+}
Index: uc_multiprice_import/uc_multiprice_import.module
===================================================================
--- uc_multiprice_import/uc_multiprice_import.module	(revision 0)
+++ uc_multiprice_import/uc_multiprice_import.module	(revision 0)
@@ -0,0 +1,386 @@
+<?php
+// $Id: uc_multiprice_import.info,v 6.x.0.1 2010/10/21 00:00:00 Bartezz Exp $
+
+/**
+ * This module provides an import function in order
+ * to update uc_multiprice pricing via a character
+ * delimited file
+ *
+ * Module developed by Bartezz | Intrige.nl
+ * @author Bartezz <bartezz@gmail.com>
+ *
+ */
+
+/**
+ * Implementation of hook_menu().
+ */
+function uc_multiprice_import_menu() {
+  $items = array();    
+  $items['admin/store/settings/multiprice/import'] = array(
+    'title' => 'Multiprice Import',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('uc_multiprice_import_step_1'),
+    'access callback' => TRUE,
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 5
+  );
+  return $items;
+}
+
+
+function uc_multiprice_import_step_1($form_state) {
+  
+  if (isset($form_state['storage']['step'])) {
+    return uc_multiprice_import_step_2($form_state);
+  }
+  
+  $form = array();
+  $form['#attributes'] = array('enctype' => "multipart/form-data");
+  
+  $form['uc_multiprice_admin_import'] = array(
+    '#type'  => 'fieldset',
+    '#title'  => t('Step 1 of 3'),
+    '#collapsible'  => TRUE, 
+    '#collapsed'  => FALSE,
+    '#description'  => t('Please select a character delimited file. The file should at least contain 2 columns with SKU and sell price. After clicking the upload button you will be present options to map the contents.')
+  );
+    $form['uc_multiprice_admin_import']['uc_multiprice_csv'] = array(
+      '#type'  => 'file',
+      '#title'  => t('Delimited text file'),
+      '#description'  => t('Please upload a plain text file delimited by commas, tabs, or other characters. This file should have a .txt or .csv extension.')
+    );
+    $form['uc_multiprice_admin_import']['uc_multiprice_delimiter'] = array(
+      '#type'  => 'select',
+      '#title'  => t('Delimiter'),
+      '#description'  => t('Please select the field delimiter character.'),
+      '#options' => array(
+        ';'  => t('Semicolon (;)'),
+        ','  => t('Comma (,)'),
+        '\t' => t('Tab (\t)'),        
+        ':'  => t('Colon (:)'),
+        '|'  => t('Pipe (|)'),
+        '.'  => t('Period (.)'),
+        ' '  => t('Space ( )'),
+      ),
+      '#default_value' => ';',
+      '#required'  => TRUE
+    );
+    $form['uc_multiprice_admin_import']['uc_multiprice_enclosure'] = array(
+      '#type'  => 'select',
+      '#title'  => t('Enclosure'),
+      '#description'  => t('Please select the field enclosure character.'),
+      '#options' => array(
+        ''  => t('None'),
+        '"' => t('Double quotes (")'),
+        '\'' => t('Single quotes (\')'),
+      ),
+      '#required'  => FALSE
+    );
+  $form['next'] = array(
+    '#type' => 'submit',
+    '#value' => t('Next'),
+  );
+
+  $form['#after_build'] = array('uc_multiprice_import_step_1_after_build');
+  return $form;
+}
+
+function uc_multiprice_import_step_1_after_build($form) {
+  // make file field show asterix
+  $form['uc_multiprice_admin_import']['uc_multiprice_csv']['#required'] = TRUE;
+  return $form;
+}
+
+function uc_multiprice_import_step_1_submit($form, &$form_state) {
+  // if step 1 is submitted
+  if ($form_state['clicked_button']['#id'] == 'edit-next') {
+    // set some valid extensions
+    $validators = array('file_validate_extensions' => array('csv txt'));
+    // if we have a file to upload
+    if ($file = file_save_upload('uc_multiprice_csv', $validators, 0, 0)) {
+      // set step 2
+      $form_state['storage']['step'] = 2;
+      // store file info in form
+      $form_state['storage']['file'] = $file;
+      // store delimiter info
+      $form_state['storage']['uc_multiprice_delimiter'] = $form_state['values']['uc_multiprice_delimiter'];
+      // store enclosure info
+      $form_state['storage']['uc_multiprice_enclosure'] = $form_state['values']['uc_multiprice_enclosure'];
+    } 
+    else {
+      form_set_error('uc_multiprice_admin_import', t('Please upload a character delimited file.'));
+    }
+  } 
+  elseif ($form_state['clicked_button']['#id'] == 'edit-import') {
+    // first get all nids of original nodes, not translations
+    $result = db_query("SELECT min(nid) as nid, model FROM {uc_products} group by model");
+    $skunid = array();
+    while ($row = db_fetch_array($result)) {
+      $skunid[$row['model']] = $row['nid'];
+    }
+    // create an array of fields for the first part of the query
+    $insert = array('nid', 'created', 'country_id', 'role_id');
+    for ($i=0; $i < $form_state['values']['uc_multiprice_colnum']; $i++) {
+      if ($form_state['values']['uc_multiprice_field' . $i] != 'sku') {
+        $insert[] = $form_state['values']['uc_multiprice_field' . $i];
+      }
+      if ($form_state['values']['uc_multiprice_field' . $i] == 'sku') {
+        $skuindex = $i;
+      }
+    }
+    
+    // read the file to extract some data we'll be needing
+    $delimiter = $form_state['storage']['uc_multiprice_delimiter'];
+    $enclosure = $form_state['storage']['uc_multiprice_enclosure'];
+    
+    list($multiprice_type, $multiprice_id) = explode('|', $form_state['values']['uc_multiprice_multiprice']);
+    if ($multiprice_type == 'country') {
+      $multiprice_name = uc_country_get_by_id($multiprice_id);
+       $multiprice_id = ($multiprice_id != uc_store_default_country()) ? $multiprice_id : 0;
+      $country_id = $multiprice_id;
+      $role_id = NULL;
+    } 
+    else {
+      $roles = user_roles();
+      $multiprice_name = $roles[$multiprice_id];
+      $country_id = NULL;
+      $role_id = $multiprice_id;
+    }
+    
+    $values = array();
+  
+    if (($handle = fopen($form_state['storage']['file']->filepath, "r")) !== FALSE) {
+      // if no field enclosure was selected, fgetcsv() doesn't allow empty value
+      if (!$enclosure) {        
+        while (($data = fgetcsv($handle, 256, $delimiter)) !== FALSE) {
+          if ($nid = $skunid[$data[$skuindex]]) {
+            $num = count($data);
+            $value = array('nid' => $nid, 'multiprice_type' => $multiprice_type, 'multiprice_id' => $multiprice_id, 'multiprice_name' => $multiprice_name, 'country_id' => $country_id, 'role_id' => $role_id);
+            for ($c=0; $c < $num; $c++) {  
+              if ($form_state['values']['uc_multiprice_field' . $c] && $form_state['values']['uc_multiprice_field' . $c] != 'sku') {
+                $value[$form_state['values']['uc_multiprice_field' . $c]] = $data[$c];
+              }
+            }
+            $values[] = $value;
+          }
+        }
+      }
+      elseif ($enclosure) {
+        while (($data = fgetcsv($handle, 256, $delimiter)) !== FALSE) {
+          if ($nid = $skunid[$data[$skuindex]]) {
+            $num = count($data);
+            $value = array('nid' => $nid, 'multiprice_type' => $multiprice_type, 'multiprice_id' => $multiprice_id, 'multiprice_name' => $multiprice_name, 'country_id' => $country_id, 'role_id' => $role_id);
+            for ($c=0; $c < $num; $c++) {  
+              if ($form_state['values']['uc_multiprice_field' . $c] && $form_state['values']['uc_multiprice_field' . $c] != 'sku') {
+                $value[$form_state['values']['uc_multiprice_field' . $c]] = $data[$c];
+              }
+            }
+            $values[] = $value;
+          }
+        }
+      }
+      fclose($handle);
+    }
+    //define batch API process.
+    $batch = array(
+      'operations' => array(
+                      array('uc_multiprice_import_process', array($values))
+                      ),
+      'finished' => 'uc_multiprice_import_finished',
+      'title' => t('Importing prices for country or role: @multiprice', array('@multiprice' => $multiprice_name)),
+      'init_message' => t('Starting...'),
+      'progress_message' => t('Processing price imports and/or updates...'),
+      'error_message' => t('An error occurred and some or all of the batch has failed.'),
+    );
+    unset($form_state['storage']);
+    batch_set($batch);
+  }
+}
+
+/**
+ * Batch Operation Callback
+ *
+ */
+function uc_multiprice_import_process($items = array(), &$context) {
+  
+  if (!isset($context['sandbox']['progress'])) {
+    $context['results']['multiprice_name'] = $items[0]['multiprice_name'];
+    $context['sandbox']['progress'] = 0;
+    $context['sandbox']['max'] = count($items);
+  }
+  module_load_include('inc', 'node', 'node.pages');
+
+  $node_update = $items[$context['sandbox']['progress']];
+  // Here we actually perform our processing on the current node.
+  $node = node_load($node_update['nid'], NULL, TRUE);
+  
+  // trun objects into arrays...
+  // the uc_multiprice nodeapi save hook needs arrays
+  foreach ((array)$node->multiprice['country'] as $k => $v) {
+    $node->multiprice['country'][$k] = (array)$v;
+  }
+  foreach ((array)$node->multiprice['role'] as $k => $v) {
+    $node->multiprice['role'][$k] = (array)$v;
+  }  
+  $node->multiprice['multiprices'] = $node->multiprice;
+
+  if ($node_update['multiprice_id']) {
+    $node->multiprice['multiprices'][$node_update['multiprice_type']][$node_update['multiprice_id']]['country_id'] = $node_update['country_id'];  
+    $node->multiprice['multiprices'][$node_update['multiprice_type']][$node_update['multiprice_id']]['list_price'] = floatval($node_update['list_price']);
+    $node->multiprice['multiprices'][$node_update['multiprice_type']][$node_update['multiprice_id']]['cost'] = floatval($node_update['cost']);
+    $node->multiprice['multiprices'][$node_update['multiprice_type']][$node_update['multiprice_id']]['sell_price'] = floatval($node_update['sell_price']);
+    $node->multiprice['multiprices'][$node_update['multiprice_type']][$node_update['multiprice_id']]['role_id'] = $node_update['role_id'];  
+  }
+  else {
+    $node->list_price = floatval($node_update['list_price']);
+    $node->cost = floatval($node_update['cost']);
+    $node->sell_price = floatval($node_update['sell_price']);
+  }
+
+  node_save($node);
+
+  // Remove current node's update values from array
+  unset($items[$context['sandbox']['progress']]);
+  
+  // Store some result for post-processing in the finished callback.
+  $context['results']['titles'][] = check_plain($node->title);
+
+  // Update our progress information.
+  $context['sandbox']['progress']++;
+  $context['message'] = t('Now processing %node', array('%node' => $node->title));
+  
+  // Inform the batch engine that we are not finished,
+  // and provide an estimation of the completion level we reached.
+  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
+    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
+  }
+
+}
+
+/**
+ * Batch 'finished' callback
+ *
+ */
+function uc_multiprice_import_finished($success, $results, $operations) {
+  if ($success) {
+    // Here we do something meaningful with the results.
+    $count = array_count_values($_SESSION['messages']['status']);
+    if ($count[t('One node translation has been synchronized.')] > 1) {
+      // Make sure drupal_set_message returns only one
+      // statement regarding nodes being synchronized
+      $_SESSION['messages']['status'] = array_unique($_SESSION['messages']['status']);
+      $_SESSION['messages']['status'][array_search(t('One node translation has been synchronized.'), $_SESSION['messages']['status'])] = t('All translations for @results nodes have been synchronized.', array('@results' => count($results['titles'])));
+    } 
+    $message = t('A total of @results products were price updated for country or role: @multiprice.', array('@multiprice' => $results['multiprice_name'], '@results' => count($results['titles'])));
+  }
+  else {
+    // An error occurred.
+    // $operations contains the operations that remained unprocessed.
+    $error_operation = reset($operations);
+    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
+    watchdog('Multiprice import', 'An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)), WATCHDOG_ERROR);
+  }
+  drupal_set_message($message);
+}
+
+function uc_multiprice_import_step_2($form_state) {
+  // read the file to extract some data we'll be needing
+  $delimiter = $form_state['values']['uc_multiprice_delimiter'];
+  $enclosure = $form_state['values']['uc_multiprice_enclosure'];
+  $values = array();
+
+  if (($handle = fopen($form_state['storage']['file']->filepath, "r")) !== FALSE) {
+    // if no field enclosure was selected, fgetcsv() doesn't allow empty value
+    if (!$enclosure) {
+      while (($data = fgetcsv($handle, 256, $delimiter)) !== FALSE) {
+        $num = count($data);
+        for ($c=0; $c < $num; $c++) {          
+          $values[] = $data[$c];
+        }
+        break;
+      }
+    }
+    elseif ($enclosure) {
+      while (($data = fgetcsv($handle, 256, $delimiter, $enclosure)) !== FALSE) {
+        $num = count($data);
+        for ($c=0; $c < $num; $c++) {          
+          $values[] = $data[$c];
+        }
+        break;
+      }
+    }
+    fclose($handle);
+  }
+
+  $multiprices = array();
+  // add the enabled roles to be used as options
+  $enabled_roles = array_filter(variable_get('uc_multiprice_roles', array()));
+  $roles = user_roles();
+  if (variable_get('role_weights_reorder_forms', FALSE)) {
+    uksort($roles, '_role_weights_rid_compare');
+  }
+  foreach ($enabled_roles as $k => $v) {
+    $multiprices['role|' . $k] = $roles[$k];
+  }
+  // load the enabled countries to be used as options
+  $uc_store_default_country = uc_store_default_country();
+  $result = db_query("SELECT country_id, country_name FROM {uc_countries} WHERE version > 0 ORDER BY country_name ASC");
+  while ($country = db_fetch_object($result)) {
+    if ($country->country_id == $uc_store_default_country) {
+      $multiprices['country|' . $country->country_id] = $country->country_name . ' (' . t('store default country') . ')';
+    }
+    else {
+      $multiprices['country|' . $country->country_id] = $country->country_name;
+    }
+  }
+  
+  // create the options array for select boxes
+  $mapping_opts =  array(''  => t('None'), 'sku'  => t('SKU'), 'list_price'  => t('List price'), 'cost'  => t('Cost'), 'sell_price'  => t('Sell price'));  
+  
+  $form = array();
+  $form['#attributes'] = array('enctype' => "multipart/form-data");
+  
+  $form['uc_multiprice_admin_import'] = array(
+    '#type'  => 'fieldset',
+    '#title'  => t('Step 2 of 3'),
+    '#collapsible'  => TRUE, 
+    '#collapsed'  => FALSE,
+    '#description'  => t("Please select the field to which each column's value should be mapped. Or you can leave the select at 'none' if the value of that column should not be mapped/imported.")
+  );
+    // create a select for each column in csv
+    for ($c=0; $c < $num; $c++) {
+      $form['uc_multiprice_admin_import']['uc_multiprice_field' . $c] = array(
+        '#type'  => 'select',
+        '#title'  => t('Column !colnum (@field)', array('!colnum' => $c+1, '@field' => $values[$c])),
+        '#options' => $mapping_opts,
+        '#default_value' => '',
+        '#required'  => FALSE
+      );
+    }
+    $form['uc_multiprice_admin_import']['uc_multiprice_colnum'] = array(
+      '#type'  => 'hidden',
+      '#value' => (int)$num,                            
+    );
+    $form['uc_multiprice_admin_import']['uc_multiprice_header'] = array(
+      '#type'  => 'radios',
+      '#title'  => t('Header record (@values)', array('@values' => implode($values, ', '))),
+      '#description'  => t('The first row of the uploaded file has these values; <strong>@values</strong>. If these are values are column names that should not be imported then check yes, if these values are values you wish to import then select no.', array('@values' => implode($values, ', ')) ),
+      '#options'  => array(t('No'), t('Yes')),
+      '#required'  => TRUE
+    );
+    
+    $form['uc_multiprice_admin_import']['uc_multiprice_multiprice'] = array(
+      '#type'  => 'select',
+      '#title'  => t('Country or role'),
+      '#description'  => t('Please select the country or role for which to import the prices.'),
+      '#options' => (array)$multiprices,
+      '#required'  => TRUE
+    );
+    
+  $form['import'] = array(
+    '#type' => 'submit',
+    '#value' => t('Start import'),
+  );
+  
+  return $form;
+}
\ No newline at end of file
