You are here

function commerce_avatax_commerce_payment_order_paid_in_full in Drupal Commerce Connector for AvaTax 7.5

Same name and namespace in other branches
  1. 7.3 commerce_avatax_erp.inc \commerce_avatax_commerce_payment_order_paid_in_full()

Implements hook_commerce_payment_order_paid_in_full().

Create a committed SalesInvoice transaction when an order is paid in full.

File

./commerce_avatax.module, line 683
AvaTax service integration from Avalara, Inc.

Code

function commerce_avatax_commerce_payment_order_paid_in_full($order) {
  $company_code = commerce_avatax_company_code();

  // Skip the transaction creation.
  if (!commerce_avatax_tax_calculation_enabled() || empty($company_code) || empty($order->data['commerce_avatax']['request'])) {
    return;
  }

  // Check if there's an AvaTax line item present on this order.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $tax_line_item = FALSE;
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if (!$line_item_wrapper
      ->value() || $line_item_wrapper
      ->getBundle() != 'avatax') {
      continue;
    }
    $tax_line_item = $line_item_wrapper
      ->value();
    break;
  }

  // If the tax line item could not be found, stop here.
  if (!$tax_line_item) {
    return;
  }

  // Commit the transaction when "Disable document committing" is unchecked.
  module_load_include('inc', 'commerce_avatax', 'includes/commerce_avatax.calc');
  if (empty($company_code) || !($avatax_object = commerce_avatax_object())) {
    drupal_set_message(t("The Avatax module is not properly configured, please configure the company code."), 'error');
    return;
  }

  // Reuse the stored AvaTax transaction from the line item's data array.
  $request_body = $order->data['commerce_avatax']['request'];

  // Check if the transaction needs to be committed.
  $commit = !variable_get(COMMERCE_AVATAX_VAR_PREFIX . 'disable_document_committing', FALSE);

  // Update the transaction type if it needs to be committed.
  if ($commit) {
    $request_body['type'] = 'SalesInvoice';
  }
  $request_body['commit'] = $commit;
  $response = $avatax_object
    ->transactionsCreate($request_body);

  // Parse the result request.
  if ($response['success'] && isset($response['result']['id'])) {
    $order->data['commerce_avatax'] = array(
      'transaction_id' => $response['result']['id'],
      'transaction_code' => $response['result']['code'],
      // Stores the company code, it might change overtime.
      'company_code' => $company_code,
      'request' => $request_body,
      'response' => $response,
    );
  }
}