You are here

function uc_tax_uc_order_update in Ubercart 8.4

Implements hook_uc_order_update().

Updates and saves tax line items to the order.

1 call to uc_tax_uc_order_update()
uc_tax_uc_order_insert in uc_tax/uc_tax.module
Implements hook_uc_order_insert().

File

uc_tax/uc_tax.module, line 109
Ubercart Tax module.

Code

function uc_tax_uc_order_update(OrderInterface $order) {
  $changes = [];
  $line_items = uc_tax_calculate($order);
  foreach ($line_items as $id => $tax) {
    $line_items[$id] = _uc_tax_to_line_item($tax);
  }

  // Loop through existing line items and update or delete as necessary.
  if (is_array($order->line_items)) {
    foreach ($order->line_items as $i => $line) {
      if ($line['type'] == 'tax') {
        $delete = TRUE;
        foreach ($line_items as $id => $new_line) {
          if ($new_line['data']['tax_id'] == $line['data']['tax_id']) {
            if ($new_line['amount'] != $line['amount']) {
              uc_order_update_line_item($line['line_item_id'], $new_line['title'], $new_line['amount'], $new_line['data']);
              $order->line_items[$i]['amount'] = $new_line['amount'];
              $order->line_items[$i]['data'] = $new_line['data'];
              $changes[] = t('Changed %title to %amount.', [
                '%amount' => uc_currency_format($new_line['amount']),
                '%title' => $new_line['title'],
              ]);
            }
            unset($line_items[$id]);
            $delete = FALSE;
            break;
          }
        }
        if ($delete) {
          uc_order_delete_line_item($line['line_item_id']);
          unset($order->line_items[$i]);
          $changes[] = t('Removed %title.', [
            '%title' => $line['title'],
          ]);
        }
      }
    }
  }

  // Now add line items for any remaining new taxes.
  if (is_array($line_items)) {
    foreach ($line_items as $line) {
      $order->line_items[] = uc_order_line_item_add($order
        ->id(), 'tax', $line['title'], $line['amount'], $line['weight'], $line['data']);
      $changes[] = t('Added %amount for %title.', [
        '%amount' => uc_currency_format($line['amount']),
        '%title' => $line['title'],
      ]);
    }
  }

  // And log the changes to the order.
  if (count($changes)) {
    $order
      ->logChanges($changes);
    usort($order->line_items, 'Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
  }
}