You are here

uc_flatrate.module in Ubercart 5

Shipping quote module that defines a flat shipping rate for each product.

Coded by Lyle Mantooth

File

shipping/uc_flatrate/uc_flatrate.module
View source
<?php

/**
 * @file
 * Shipping quote module that defines a flat shipping rate for each product.
 *
 * Coded by Lyle Mantooth
 */

/******************************************************************************
 * Drupal Hooks                                                               *
 ******************************************************************************/

/**
 * Implementation of hook_menu().
 */
function uc_flatrate_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/store/settings/quotes/methods/flatrate',
      'access' => user_access('configure quotes'),
      'title' => t('Flat rate'),
      'callback' => 'uc_flatrate_admin_methods',
      'type' => MENU_LOCAL_TASK,
    );
  }
  else {
    $items[] = array(
      'path' => 'admin/store/settings/quotes/methods/flatrate/' . arg(6),
      'access' => user_access('configure quotes'),
      'title' => t('Edit flat rate method'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'uc_flatrate_admin_method_edit_form',
        arg(6),
      ),
      'type' => MENU_CALLBACK,
    );
    $items[] = array(
      'path' => 'admin/store/settings/quotes/methods/flatrate/' . arg(6) . '/delete',
      'access' => user_access('configure quotes'),
      'title' => t('Delete flat rate method'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'uc_flatrate_admin_method_confirm_delete',
        arg(6),
      ),
      'type' => MENU_CALLBACK,
    );
  }
  return $items;
}

/**
 * Implementation of hook_form_alter().
 *
 * Add a form element for the shipping rate of a product.
 */
function uc_flatrate_form_alter($form_id, &$form) {
  $node = $form['#node'];
  $product_types = module_invoke_all('product_types');
  if (is_object($node) && $form_id == $node->type . '_node_form' && isset($form['base']['dimensions']) && in_array($node->type, $product_types)) {
    $result = db_query("SELECT mid, title, product_rate FROM {uc_flatrate_methods}");
    if (db_num_rows($result)) {
      $sign_flag = variable_get('uc_sign_after_amount', FALSE);
      $currency_sign = variable_get('uc_currency_sign', '$');
      $enabled = variable_get('uc_quote_enabled', array());
      $weight = variable_get('uc_quote_method_weight', array());
      $form['shipping']['flatrate'] = array(
        '#type' => 'fieldset',
        '#title' => t('Flat shipping rates'),
        '#description' => t('Override the default shipping rate per product for each flat rate shipping method here. Enter -1 to revert to the default value.'),
        '#tree' => true,
        '#collapsible' => true,
        '#collapsed' => false,
        '#weight' => 0,
      );
      while ($method = db_fetch_object($result)) {
        $form['shipping']['flatrate'][$method->mid] = array(
          '#type' => 'textfield',
          '#title' => $method->title,
          '#default_value' => $form['#node']->flatrate[$method->mid],
          '#description' => t('Default rate: %price', array(
            '%price' => uc_currency_format($method->product_rate),
          )),
          '#size' => 16,
          '#field_prefix' => $sign_flag ? '' : $currency_sign,
          '#field_suffix' => $sign_flag ? $currency_sign : '',
          '#weight' => $weight['flatrate_' . $method->mid],
        );
      }
    }
  }
}

/**
 * Implementation of hook_nodeapi().
 */
function uc_flatrate_nodeapi(&$node, $op) {
  if (in_array($node->type, module_invoke_all('product_types'))) {
    switch ($op) {
      case 'insert':
      case 'update':
        if (is_array($node->flatrate)) {
          if (!$node->revision) {
            db_query("DELETE FROM {uc_flatrate_products} WHERE vid = %d", $node->vid);
          }
          foreach ($node->flatrate as $mid => $rate) {
            if ($rate !== '') {
              db_query("INSERT INTO {uc_flatrate_products} (vid, nid, mid, rate) VALUES (%d, %d, %d, %f)", $node->vid, $node->nid, $mid, $rate);
            }
          }
        }
        break;
      case 'load':
        $return = array(
          'flatrate' => array(),
        );
        $result = db_query("SELECT mid, rate FROM {uc_flatrate_products} WHERE vid = %d", $node->vid);
        while ($rate = db_fetch_object($result)) {
          $return['flatrate'][$rate->mid] = $rate->rate;
        }
        $result = db_query("SELECT mid, product_rate FROM {uc_flatrate_methods}");
        while ($method = db_fetch_object($result)) {
          $rate = $return['flatrate'][$method->mid];
          if ($rate === null || $rate < 0) {
            $return['flatrate'][$method->mid] = $method->product_rate;
          }
        }
        return $return;
        break;
      case 'delete':
        db_query("DELETE FROM {uc_flatrate_products} WHERE nid = %d", $node->nid);
        break;
      case 'delete revision':
        db_query("DELETE FROM {uc_flatrate_products} WHERE vid = %d", $node->vid);
        break;
    }
  }
}

/******************************************************************************
 * Workflow-ng Hooks                                                          *
 ******************************************************************************/

/**
 * Implementation of hook_configuration().
 *
 * Connect the quote action with the quote event.
 */
function uc_flatrate_configuration() {
  $enabled = variable_get('uc_quote_enabled', array());
  $configurations = array();
  $action = workflow_ng_use_action('uc_quote_action_get_quote', array(
    '#label' => t('Fetch a shipping quote'),
  ));
  $result = db_query("SELECT mid, title FROM {uc_flatrate_methods}");
  while ($method = db_fetch_object($result)) {
    $configurations['uc_flatrate_get_quote_' . $method->mid] = array(
      '#label' => t('Shipping quote via @method', array(
        '@method' => $method->title,
      )),
      '#event' => 'get_quote_from_flatrate_' . $method->mid,
      '#module' => 'uc_flatrate',
      '#active' => $enabled['flatrate_' . $method->mid],
    );
    $configurations['uc_flatrate_get_quote_' . $method->mid] = workflow_ng_configure($configurations['uc_flatrate_get_quote_' . $method->mid], $action);
  }
  return $configurations;
}

/******************************************************************************
 * Übercart Hooks                                                             *
 ******************************************************************************/

/**
 * Implementation of Übercart's hook_shipping_method().
 */
function uc_flatrate_shipping_method() {
  $methods = array();
  $enabled = variable_get('uc_quote_enabled', array());
  $weight = variable_get('uc_quote_method_weight', array());
  $result = db_query("SELECT mid, title, label FROM {uc_flatrate_methods}");
  while ($method = db_fetch_object($result)) {
    $methods['flatrate_' . $method->mid] = array(
      'id' => 'flatrate_' . $method->mid,
      'module' => 'uc_flatrate',
      'title' => $method->title,
      'enabled' => $enabled['flatrate_' . $method->mid],
      'quote' => array(
        'type' => 'order',
        'callback' => 'uc_flatrate_quote',
        'accessorials' => array(
          $method->label,
        ),
      ),
      'weight' => $weight['flatrate_' . $method->mid],
    );
  }
  return $methods;
}

/******************************************************************************
 * Menu Callbacks                                                             *
 ******************************************************************************/

/**
 * List and compare all flatrate shipping quote methods.
 */
function uc_flatrate_admin_methods() {
  $output = '';
  $rows = array();
  $enabled = variable_get('uc_quote_enabled', array());
  $weight = variable_get('uc_quote_method_weight', array());
  $result = db_query("SELECT mid, title, label, base_rate, product_rate FROM {uc_flatrate_methods}");
  while ($method = db_fetch_object($result)) {
    $row = array();
    $row[] = check_plain($method->title);
    $row[] = check_plain($method->label);
    $row[] = uc_currency_format($method->base_rate);
    $row[] = uc_currency_format($method->product_rate);
    $row[] = l(t('edit'), 'admin/store/settings/quotes/methods/flatrate/' . $method->mid . '/edit');
    $rows[] = $row;
  }
  if (count($rows)) {
    $header = array(
      t('Title'),
      t('Label'),
      t('Base rate'),
      t('Default product rate'),
      t('Actions'),
    );
    $output .= theme('table', $header, $rows);
  }
  $output .= l(t('Add a new flat rate shipping method.'), 'admin/store/settings/quotes/methods/flatrate/add');
  return $output;
}

/**
 * Configure the store default product shipping rates.
 */
function uc_flatrate_admin_method_edit_form($mid = 0) {
  $form = array();
  $sign_flag = variable_get('uc_sign_after_amount', FALSE);
  $currency_sign = variable_get('uc_currency_sign', '$');
  if (is_numeric($mid) && ($method = db_fetch_object(db_query("SELECT * FROM {uc_flatrate_methods} WHERE mid = %d", $mid)))) {
    $form['mid'] = array(
      '#type' => 'value',
      '#value' => $mid,
    );
  }
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping method title'),
    '#description' => t('The name shown to distinguish it from other flatrate methods.'),
    '#default_value' => $method->title,
  );
  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => t('Line item label'),
    '#description' => t('The name shown to the customer when they choose a shipping method at checkout.'),
    '#default_value' => $method->label,
  );
  $form['base_rate'] = array(
    '#type' => 'textfield',
    '#title' => t('Base price'),
    '#description' => t('The starting price for shipping costs.'),
    '#default_value' => $method->base_rate,
    '#size' => 16,
    '#field_prefix' => $sign_flag ? '' : $currency_sign,
    '#field_suffix' => $sign_flag ? $currency_sign : '',
  );
  $form['product_rate'] = array(
    '#type' => 'textfield',
    '#title' => t('Default product shipping rate'),
    '#default_value' => $method->product_rate,
    '#size' => 16,
    '#field_prefix' => $sign_flag ? '' : $currency_sign,
    '#field_suffix' => $sign_flag ? $currency_sign : '',
  );
  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  $form['buttons']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
  );
  return $form;
}
function uc_flatrate_admin_method_edit_form_validate($form_id, $form_values) {
  if ($form_values['op'] == t('Submit')) {
    if (!empty($form_values['base_rate']) && !is_numeric($form_values['base_rate'])) {
      form_set_error('base_rate', t('The base rate must be a numeric amount.'));
    }
    if (!empty($form_values['product_rate']) && !is_numeric($form_values['product_rate'])) {
      form_set_error('product_rate', t('The product rate must be a numeric amount.'));
    }
  }
}
function uc_flatrate_admin_method_edit_form_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Delete')) {
    drupal_goto('admin/store/settings/quotes/methods/flatrate/' . $form_values['mid'] . '/delete');
  }
  if ($form_values['mid']) {
    db_query("UPDATE {uc_flatrate_methods} SET title = '%s', label = '%s', base_rate = %f, product_rate = %f WHERE mid = %d", $form_values['title'], $form_values['label'], $form_values['base_rate'], $form_values['product_rate'], $form_values['mid']);
    drupal_set_message("Flat rate shipping method was updated.");
  }
  else {
    $mid = db_next_id("{uc_flatrate_methods}_mid");
    db_query("INSERT INTO {uc_flatrate_methods} (mid, title, label, base_rate, product_rate) VALUES (%d, '%s', '%s', %f, %f)", $mid, $form_values['title'], $form_values['label'], $form_values['base_rate'], $form_values['product_rate']);
    $enabled = variable_get('uc_quote_enabled', array());
    $enabled['flatrate_' . $mid] = true;
    variable_set('uc_quote_enabled', $enabled);
    $weight = variable_get('uc_quote_method_weight', array());
    $weight['flatrate_' . $mid] = 0;
    variable_set('uc_quote_method_weight', $weight);
    drupal_set_message("Created and enabled new flat rate shipping method.");
  }
  return 'admin/store/settings/quotes/methods/flatrate';
}
function uc_flatrate_admin_method_confirm_delete($mid) {
  $form = array();
  $form['mid'] = array(
    '#type' => 'value',
    '#value' => $mid,
  );
  return confirm_form($form, t('Do you want to delete this shipping method?'), 'admin/store/settings/quotes/methods/flatrate', t('This will remove the shipping method, workflow-ng configuration, and the
      product-specific overrides (if applicable). This action can not be undone.'), t('Delete'));
}
function uc_flatrate_admin_method_confirm_delete_submit($form_id, $form_values) {
  db_query("DELETE FROM {uc_flatrate_methods} WHERE mid = %d", $form_values['mid']);
  db_query("DELETE FROM {uc_flatrate_products} WHERE mid = %d", $form_values['mid']);
  db_query("DELETE FROM {workflow_ng_cfgs} WHERE name = '%s'", 'uc_flatrate_get_quote_by_' . $form_values['type'] . '_rate_' . $form_values['mid']);
  workflow_ng_clear_cache();
  $enabled = variable_get('uc_quote_enabled', array());
  unset($enabled['flatrate_' . $form_values['mid']]);
  variable_set('uc_quote_enabled', $enabled);
  $weight = variable_get('uc_quote_method_weight', array());
  unset($weight['flatrate_' . $form_values['mid']]);
  variable_set('uc_quote_method_weight', $weight);
  drupal_set_message('Flat rate shipping method deleted.');
  return 'admin/store/settings/quotes/methods/flatrate';
}

/******************************************************************************
 * Module Functions                                                           *
 ******************************************************************************/

/**
 * Standard callback to return a shipping rate via the flat rate method.
 *
 * @param $products
 *   The order's products.
 * @param $details
 *   Other order details including a shipping address.
 * @return
 *   A JSON object containing the shipping quote for the order.
 */
function uc_flatrate_quote($products, $details, $method) {
  $method = explode('_', $method['id']);
  $mid = $method[1];
  if ($method = db_fetch_object(db_query("SELECT * FROM {uc_flatrate_methods} WHERE mid = %d", $mid))) {
    $rate = $method->base_rate;
    foreach ($products as $product) {
      if (is_null($product->flatrate)) {
        $rate += $method->product_rate * $product->qty;
      }
      else {

        //$node = node_load($product->nid);
        $rate += $product->flatrate[$mid] * $product->qty;
      }
    }
    $quotes[] = array(
      'rate' => $rate,
      'format' => uc_currency_format($rate),
      'option_label' => check_plain($method->label),
    );
  }
  return $quotes;
}

Functions

Namesort descending Description
uc_flatrate_admin_methods List and compare all flatrate shipping quote methods.
uc_flatrate_admin_method_confirm_delete
uc_flatrate_admin_method_confirm_delete_submit
uc_flatrate_admin_method_edit_form Configure the store default product shipping rates.
uc_flatrate_admin_method_edit_form_submit
uc_flatrate_admin_method_edit_form_validate
uc_flatrate_configuration Implementation of hook_configuration().
uc_flatrate_form_alter Implementation of hook_form_alter().
uc_flatrate_menu Implementation of hook_menu().
uc_flatrate_nodeapi Implementation of hook_nodeapi().
uc_flatrate_quote Standard callback to return a shipping rate via the flat rate method.
uc_flatrate_shipping_method Implementation of Übercart's hook_shipping_method().