You are here

uc_coupon_purchase.module in Ubercart Discount Coupons 5

File

uc_coupon_purchase/uc_coupon_purchase.module
View source
<?php

/**
 * Implementation of hook_menu().
 */
function uc_coupon_purchase_menu($may_cache) {
  $items = array();
  if (!$may_cache) {
    if (module_exists('uc_notify')) {
      $items[] = array(
        'path' => 'admin/store/settings/notify/edit/coupon',
        'title' => t('Coupon creation'),
        'access' => user_access('administer store'),
        'callback' => 'drupal_get_form',
        'callback arguments' => array(
          'uc_coupon_purchase_notify_settings',
        ),
        'description' => t('Edit the notification settings for coupon purchases.'),
        'type' => MENU_LOCAL_TASK,
      );
    }
  }
  return $items;
}

/**
 * Implementation of hook_product_feature().
 */
function uc_coupon_purchase_product_feature() {
  $features[] = array(
    'id' => 'coupon',
    'title' => t('Coupon creation'),
    'callback' => 'uc_coupon_purchase_feature_form',
    'delete' => 'uc_coupon_purchase_feature_delete',
    'settings' => 'uc_coupon_purchase_feature_settings',
  );
  return $features;
}

/**
 * Form builder for hook_product_feature().
 */
function uc_coupon_purchase_feature_form($node, $feature) {
  $models = array(
    NULL => t('Any'),
    $node->model => $node->model,
  );
  if (module_exists('uc_attribute')) {
    $adjustments = db_query("SELECT model FROM {uc_product_adjustments} WHERE nid = %d", $node->nid);
    while ($adjustment = db_fetch_object($adjustments)) {
      if (!in_array($adjustment->model, $models)) {
        $models[$adjustment->model] = $adjustment->model;
      }
    }
  }
  if (!empty($feature)) {
    $data = db_fetch_object(db_query("SELECT * FROM {uc_coupon_purchase} WHERE pfid = %d", $feature['pfid']));
    $form['pfid'] = array(
      '#type' => 'value',
      '#value' => $feature['pfid'],
    );
  }
  else {
    $data = new stdClass();
  }
  $coupons = array();
  $result = db_query("SELECT cid, name, code FROM {uc_coupons}");
  while ($coupon = db_fetch_object($result)) {
    $coupons[$coupon->cid] = $coupon->name . ' (' . $coupon->code . ')';
  }
  $form['title'] = array(
    '#type' => 'markup',
    '#value' => '<h2>' . t('Coupon creation') . '</h2>',
  );
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  $form['model'] = array(
    '#type' => 'select',
    '#title' => t('Model/SKU'),
    '#default_value' => $data->model,
    '#description' => t('Select the model/SKU of the product that cause a coupon to be created.'),
    '#options' => $models,
  );
  $form['base_cid'] = array(
    '#type' => 'select',
    '#title' => t('Base coupon'),
    '#default_value' => $data->base_cid,
    '#description' => t('Select the coupon that will be cloned and activated when a user purchases this product.'),
    '#options' => $coupons,
  );
  return uc_product_feature_form($form);
}
function uc_coupon_purchase_feature_form_submit($form_id, $form_values) {
  $coupon = uc_coupon_load($form_values['base_cid']);
  $description = empty($form_values['model']) ? t('<strong>SKU:</strong> Any<br/>') : t('<strong>SKU:</strong> !sku<br/>', array(
    '!sku' => $form_values['model'],
  ));
  $description .= t('<strong>Base coupon:</strong> !coupon<br/>', array(
    '!coupon' => $coupon->name . ' (' . $coupon->code . ')',
  ));
  if ($form_values['pfid'] == 0) {
    $pfid = db_next_id('{uc_product_features}_pfid');
  }
  else {
    $pfid = $form_values['pfid'];
    db_query("DELETE FROM {uc_coupon_purchase} WHERE pfid = %d", $pfid);
  }
  db_query("INSERT INTO {uc_coupon_purchase} (pfid, nid, model, base_cid) VALUES (%d, %d, '%s', %d)", $pfid, $form_values['nid'], $form_values['model'], $form_values['base_cid']);
  $data = array(
    'pfid' => $pfid,
    'nid' => $form_values['nid'],
    'fid' => 'coupon',
    'description' => $description,
  );
  return uc_product_feature_save($data);
}

/**
 * Delete callback for product feature.
 */
function uc_coupon_purchase_feature_delete($feature) {
  db_query("DELETE FROM {uc_coupon_purchase} WHERE pfid = %d", $feature['pfid']);
}

/**
 * Form builder for feature settings.
 */
function uc_coupon_purchase_feature_settings() {
  foreach (uc_order_status_list('general') as $status) {
    $statuses[$status['id']] = $status['title'];
  }
  $form['uc_coupon_purchase_order_status'] = array(
    '#type' => 'select',
    '#title' => t('Order status'),
    '#default_value' => variable_get('uc_coupon_purchase_order_status', 'completed'),
    '#description' => t('Select the order status that will cause the coupon to be created. Be aware that if payments are processed automatically, this happens before anonymous customers have an account created. This order status should not be reached before the user account exists.'),
    '#options' => $statuses,
  );
  return $form;
}

/**
 * Implementation of hook_token_list().
 */
function uc_coupon_token_list($type = 'all') {
  if ($type == 'uc_coupon' || $type == 'ubercart' || $type == 'all') {
    $tokens['uc_coupon']['coupon-name'] = t('The coupon name.');
    $tokens['uc_coupon']['coupon-code'] = t('The coupon code.');
    $tokens['uc_coupon']['coupon-bulk-codes'] = t('The list of bulk coupon codes.');
  }
  return $tokens;
}

/**
 * Implementation of hook_token_values().
 */
function uc_coupon_token_values($type, $object = NULL) {
  switch ($type) {
    case 'uc_coupon':
      $values['coupon-name'] = $object->name;
      $values['coupon-code'] = $object->code;
      if ($object->bulk) {
        $codes = array();
        for ($id = 0; $id < $object->data['bulk_number']; $id++) {
          $codes[] = uc_coupon_get_bulk_code($object, $id);
        }
        $values['coupon-bulk-codes'] .= implode("<br />", $codes);
      }
      break;
  }
  return $values;
}

/**
 * Implementation of hook_uc_message().
 */
function uc_coupon_purchase_uc_message() {
  $messages['uc_coupon_purchase_single_subject'] = t('[store-name]: coupon purchase');
  $messages['uc_coupon_purchase_single_message'] = t("[order-first-name] [order-last-name], \n\nThanks to your order, [order-link], at [store-name] you now have a new coupon available to use with the code [coupon-code].\n\nThanks again, \n\n[store-name]\n[site-slogan]");
  $messages['uc_coupon_purchase_bulk_subject'] = t('[store-name]: bulk coupon purchase');
  $messages['uc_coupon_purchase_bulk_message'] = t("[order-first-name] [order-last-name], \n\nThanks to your order, [order-link], at [store-name] you now have a new set of coupons available to use with the following codes:\n\n[coupon-bulk-codes]\n\nThanks again, \n\n[store-name]\n[site-slogan]");
  return $messages;
}

/**
 * Form builder for coupon notification settings.
 */
function uc_coupon_purchase_notify_settings() {
  $form['single'] = array(
    '#type' => 'fieldset',
    '#title' => t('Single coupon creation message'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['single']['uc_coupon_purchase_single_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Message subject'),
    '#default_value' => variable_get('uc_coupon_purchase_single_subject', uc_get_message('uc_coupon_purchase_single_subject')),
  );
  $form['single']['uc_coupon_purchase_single_message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message text'),
    '#default_value' => variable_get('uc_coupon_purchase_single_message', uc_get_message('uc_coupon_purchase_single_message')),
    '#description' => t('The message the user receives when a new coupon is created (<a href="!url">uses order, uc_coupon, and global tokens</a>).', array(
      '!url' => url('admin/store/help/tokens'),
    )),
    '#rows' => 10,
  );
  $form['single']['uc_coupon_purchase_single_format'] = filter_form(variable_get('uc_coupon_purchase_single_format', FILTER_FORMAT_DEFAULT), NULL, array(
    'uc_coupon_purchase_single_format',
  ));
  $form['bulk'] = array(
    '#type' => 'fieldset',
    '#title' => t('Bulk coupon creation message'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['bulk']['uc_coupon_purchase_bulk_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Message subject'),
    '#default_value' => variable_get('uc_coupon_purchase_bulk_subject', uc_get_message('uc_coupon_purchase_bulk_subject')),
  );
  $form['bulk']['uc_coupon_purchase_bulk_message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message text'),
    '#default_value' => variable_get('uc_coupon_purchase_bulk_message', uc_get_message('uc_coupon_purchase_bulk_message')),
    '#description' => t('The message the user receives when a new coupon is created (<a href="!url">uses order, uc_coupon, and global tokens</a>).', array(
      '!url' => url('admin/store/help/tokens'),
    )),
    '#rows' => 10,
  );
  $form['bulk']['uc_coupon_purchase_bulk_format'] = filter_form(variable_get('uc_coupon_purchase_bulk_format', FILTER_FORMAT_DEFAULT), NULL, array(
    'uc_coupon_purchase_bulk_format',
  ));
  return system_settings_form($form);
}

/**
 * Implementation of hook_order().
 */
function uc_coupon_purchase_order($op, $order, $status) {
  switch ($op) {
    case 'update':
      if ($status == variable_get('uc_coupon_purchase_order_status', 'completed') && $order->status != $status && $order->uid > 0 && ($order_user = user_load(array(
        'uid' => $order->uid,
      ))) !== FALSE) {
        foreach ($order->products as $product) {
          $result = db_query("SELECT * FROM {uc_coupon_purchase} WHERE nid = %d", $product->nid);
          while ($row = db_fetch_object($result)) {
            if ($row->model == $product->model || empty($row->model)) {
              $coupon = uc_coupon_load($row->base_cid);
              uc_coupon_purchase_create($coupon, $product->qty, $order);
            }
          }
        }
      }
      break;
  }
}
function uc_coupon_purchase_create($coupon, $qty, $order) {
  global $user;
  $purchaser = $order->billing_company ? $order->billing_company : $order->billing_first_name . ' ' . $order->billing_last_name;
  $coupon->name .= ' ' . t('purchased by !name', array(
    '!name' => $purchaser,
  ));
  $coupon->data['order_id'] = $order->order_id;

  // Generate a new random code and bulk seed.
  $coupon->code = strtoupper(user_password());
  $coupon->bulk_seed = md5(uniqid());

  // If the quantity purchased was more than 1, convert to a bulk coupon.
  if ($qty > 1) {
    $coupon->bulk = TRUE;
    if (!isset($coupon->data['bulk_length'])) {
      $coupon->data['bulk_length'] = 8;
    }
    if (!isset($coupon->data['bulk_number'])) {
      $coupon->data['bulk_number'] = 1;
    }
    $coupon->data['bulk_number'] *= $qty;
  }

  // Create coupon and save order comment.
  db_query("INSERT INTO {uc_coupons} (name, code, value, type, status, valid_from, valid_until, max_uses, minimum_order, data, bulk, bulk_seed) VALUES ('%s', '%s', %f, '%s', 1, %d, %d, %d, %f, '%s', %d, '%s')", $coupon->name, $coupon->code, $coupon->value, $coupon->type, $coupon->valid_from, $coupon->valid_until, $coupon->max_uses, $coupon->minimum_order, serialize($coupon->data), $coupon->bulk, $coupon->bulk_seed);
  uc_order_comment_save($order->order_id, $user->uid, t('Coupon created with code %code.', array(
    '%code' => $coupon->code,
  )));

  // Email coupon details.
  if (module_exists('uc_notify')) {
    if ($coupon->bulk) {
      $subject = variable_get('uc_coupon_purchase_bulk_subject', uc_get_message('uc_coupon_purchase_bulk_subject'));
      $body = variable_get('uc_coupon_purchase_bulk_message', uc_get_message('uc_coupon_purchase_bulk_message'));
      $body = check_markup($body, variable_get('uc_coupon_purchase_bulk_format', FILTER_FORMAT_DEFAULT), FALSE);
    }
    else {
      $subject = variable_get('uc_coupon_purchase_single_subject', uc_get_message('uc_coupon_purchase_single_subject'));
      $body = variable_get('uc_coupon_purchase_single_message', uc_get_message('uc_coupon_purchase_single_message'));
      $body = check_markup($body, variable_get('uc_coupon_purchase_single_format', FILTER_FORMAT_DEFAULT), FALSE);
    }
    $token_filters = array(
      'global' => NULL,
      'user' => $user,
      'order' => $order,
      'uc_coupon' => $coupon,
    );
    $subject = token_replace_multiple($subject, $token_filters);
    $body = token_replace_multiple($body, $token_filters);
    drupal_mail('uc_coupon_purchase', $order->primary_email, $subject, $body, uc_store_email_from(), uc_notify_headers());
  }
}

Functions

Namesort descending Description
uc_coupon_purchase_create
uc_coupon_purchase_feature_delete Delete callback for product feature.
uc_coupon_purchase_feature_form Form builder for hook_product_feature().
uc_coupon_purchase_feature_form_submit
uc_coupon_purchase_feature_settings Form builder for feature settings.
uc_coupon_purchase_menu Implementation of hook_menu().
uc_coupon_purchase_notify_settings Form builder for coupon notification settings.
uc_coupon_purchase_order Implementation of hook_order().
uc_coupon_purchase_product_feature Implementation of hook_product_feature().
uc_coupon_purchase_uc_message Implementation of hook_uc_message().
uc_coupon_token_list Implementation of hook_token_list().
uc_coupon_token_values Implementation of hook_token_values().