You are here

function commerce_gc_commerce_coupon_final_checkout_validate in Commerce GC 7

File

./commerce_gc.module, line 804
Provides Giftcard coupon bundle, Giftcard Transaction entity and basic user interface elements.

Code

function commerce_gc_commerce_coupon_final_checkout_validate($form, $form_state, EntityDrupalWrapper $order_wrapper) {
  $transaction_ids = array();

  // If the form was submitted via the continue button and there are no errors.
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    if ($line_item_wrapper
      ->value() && $line_item_wrapper->type
      ->value() == 'giftcard_use') {
      $coupon = $line_item_wrapper->commerce_giftcard
        ->value();

      // Do not save transactions for giftcards with zero amount.
      if ($coupon) {

        // Attempt to write a pending transaction. This will be set to
        // complete when checkout is complete. This will fail if the balance is
        // too low.
        $transaction_id = commerce_gc_transaction_write($coupon->coupon_id, $line_item_wrapper->commerce_unit_price->amount
          ->value(), COMMERCE_GC_TRANSACTION_PENDING_STATUS);
        if (!$transaction_id) {
          form_set_error('', t('Invalid coupon amount, please try again.'));
        }
        else {

          // Remember which transactions we created so that we can roll them back
          // if the form returns with errors. This is separate from the order
          // data record below because we do not want to cancel pending
          // transactions unless the form is actually being rebuilt from this
          // submission.
          $transaction_ids[] = $transaction_id;
        }
      }
    }
  }
  if (!empty($transaction_ids)) {

    // Also store the transaction ids in the order data so the checkout
    // complete hook knows what to update.
    $order = $order_wrapper
      ->value();
    $order->data['giftcard_transaction_ids'] = $transaction_ids;
    $order_wrapper
      ->save();
  }
  return $transaction_ids;
}