You are here

function commerce_discount_commerce_discount_rule_build in Commerce Discount 7

Implements hook_commerce_discount_rule_build().

File

./commerce_discount.module, line 626
Defines the discount and discount offer entities, bundles and functionality.

Code

function commerce_discount_commerce_discount_rule_build($rule, $discount) {
  $wrapper = entity_metadata_wrapper('commerce_discount', $discount);
  $discount_offer = $wrapper->commerce_discount_offer
    ->value();
  $wrapper_discount_offer = entity_metadata_wrapper('commerce_discount_offer', $discount_offer);

  // Check if property is attached to commerce free shipping!
  if (isset($wrapper_discount_offer->commerce_free_shipping)) {
    if (!($shipping_service = $wrapper_discount_offer->commerce_free_shipping
      ->value())) {

      // No need to change the rules event.
      return;
    }

    // Add missing parameter.
    foreach ($rule
      ->actions() as $action) {
      if ($action
        ->getElementName() == 'commerce_discount_free_shipping_service') {
        $action->settings['shipping_service'] = $shipping_service;
      }
    }
  }

  // Product level discounts must pass the line item's order.
  $map = array(
    'order_discount' => 'commerce-order',
    'product_discount' => 'commerce-line-item:order',
  );
  if (isset($map[$discount->type])) {

    // Add condition for per-person usage.
    if ($wrapper->discount_usage_per_person
      ->value()) {
      $rule
        ->condition('commerce_discount_usage_max_usage_per_person', array(
        'commerce_discount' => $discount->name,
        'order:select' => $map[$discount->type],
        'usage' => $wrapper->discount_usage_per_person
          ->value(),
      ));
    }

    // For normal usage.
    if ($wrapper->discount_usage_limit
      ->value()) {
      $rule
        ->condition('commerce_discount_usage_max_usage', array(
        'commerce_discount' => $discount->name,
        'order:select' => $map[$discount->type],
        'usage' => $wrapper->discount_usage_limit
          ->value(),
      ));
    }
  }
  if (!is_null($wrapper->commerce_discount_date
    ->value())) {

    // If the end date for the discount has already passed, disable the rule.
    // Note that we add a day to the discount end date. The date field value is
    // set for 12:00:00 AM on the end date, but we want the discount to remain
    // valid through that day.
    if (REQUEST_TIME >= $wrapper->commerce_discount_date->value2
      ->value() + 86400) {
      $rule->active = FALSE;
    }

    // Add condition to check usage didn't reach max uses.
    $rule
      ->condition('commerce_discount_date_condition', array(
      'commerce_discount' => $discount->name,
    ));
  }
}