You are here

public function Avatax::apply in Drupal Commerce Connector for AvaTax 8

Applies the tax type to the given order.

Taxes should be added on the order item level, to make returns and refunds easier. This is true even for taxes that are only shown at the order level, such as sales taxes.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: The order.

Overrides TaxTypeInterface::apply

File

src/Plugin/Commerce/TaxType/Avatax.php, line 100

Class

Avatax
Provides the AvaTax remote tax type.

Namespace

Drupal\commerce_avatax\Plugin\Commerce\TaxType

Code

public function apply(OrderInterface $order) {
  $response_body = $this->avataxLib
    ->transactionsCreate($order);

  // Do not go further unless there have been lines added.
  if (empty($response_body['lines'])) {
    return;
  }
  $currency_code = $order
    ->getTotalPrice() ? $order
    ->getTotalPrice()
    ->getCurrencyCode() : $order
    ->getStore()
    ->getDefaultCurrencyCode();
  $adjustments = [];
  $applied_adjustments = [];
  foreach ($response_body['lines'] as $tax_adjustment) {
    $label = isset($tax_adjustment['details'][0]['taxName']) ? Html::escape($tax_adjustment['details'][0]['taxName']) : $this
      ->t('Sales tax');
    $adjustments[$tax_adjustment['lineNumber']] = [
      'amount' => $tax_adjustment['tax'],
      'label' => $label,
    ];
  }

  // Add tax adjustments to order items.
  foreach ($order
    ->getItems() as $order_item) {
    if (!isset($adjustments[$order_item
      ->uuid()])) {
      continue;
    }
    $order_item
      ->addAdjustment(new Adjustment([
      'type' => 'tax',
      'label' => $adjustments[$order_item
        ->uuid()]['label'],
      'amount' => new Price((string) $adjustments[$order_item
        ->uuid()]['amount'], $currency_code),
      'source_id' => $this->pluginId . '|' . $this->parentEntity
        ->id(),
    ]));
    $applied_adjustments[$order_item
      ->uuid()] = $order_item
      ->uuid();
  }

  // If we still have Tax adjustments to apply, add a single one to the order.
  $remaining_adjustments = array_diff_key($adjustments, $applied_adjustments);
  if (!$remaining_adjustments) {
    return;
  }
  $tax_adjustment_total = NULL;

  // Calculate the total Tax adjustment to add.
  foreach ($remaining_adjustments as $remaining_adjustment) {
    $adjustment_amount = new Price((string) $remaining_adjustment['amount'], $currency_code);
    $tax_adjustment_total = $tax_adjustment_total ? $tax_adjustment_total
      ->add($adjustment_amount) : $adjustment_amount;
  }
  $order
    ->addAdjustment(new Adjustment([
    'type' => 'tax',
    'label' => $this
      ->t('Sales tax'),
    'amount' => $tax_adjustment_total,
    'source_id' => $this->pluginId . '|' . $this->parentEntity
      ->id(),
  ]));
}