You are here

public function TaxReport::generateReports in Commerce Reporting 8

Generates order reports for an order.

Parameters

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

Overrides ReportTypeInterface::generateReports

File

src/Plugin/Commerce/ReportType/TaxReport.php, line 131

Class

TaxReport
Provide a report for Taxes on behalf of commerce_tax.

Namespace

Drupal\commerce_reports\Plugin\Commerce\ReportType

Code

public function generateReports(OrderInterface $order) {
  $adjustments = $order
    ->collectAdjustments();
  $adjustments = array_filter($order
    ->collectAdjustments(), function (Adjustment $adjustment) {
    return $adjustment
      ->getType() == 'tax' && !empty($adjustment
      ->getSourceId());
  });

  /** @var \Drupal\commerce_order\Adjustment $adjustment */
  foreach ($adjustments as $adjustment) {
    $source_id = $adjustment
      ->getSourceId();
    list($tax_entity_id, $zone_id, $rate_id) = explode('|', $source_id) + [
      NULL,
      NULL,
      NULL,
    ];
    if (empty($tax_entity_id)) {
      continue;
    }

    /** @var \Drupal\commerce_tax\Entity\TaxTypeInterface $tax_type */
    $tax_type = $this->taxTypeStorage
      ->load($tax_entity_id);
    if (!$tax_type) {
      continue;
    }

    // Base values for order report.
    $values = [
      'tax_amount' => $adjustment
        ->getAmount(),
      'tax_type_id' => $tax_type
        ->id(),
      'tax_type_label' => $tax_type
        ->label(),
      'zone_id' => NULL,
      'zone_label' => NULL,
      'rate_id' => NULL,
      'rate_label' => NULL,
    ];
    if ($tax_type
      ->getPlugin() instanceof LocalTaxTypeInterface) {
      $zones = $tax_type
        ->getPlugin()
        ->getZones();
      if (!empty($zones) && isset($zones[$zone_id])) {
        $values['zone_id'] = $zone_id;
        $values['zone_label'] = $zones[$zone_id]
          ->getLabel();

        /** @var \Drupal\commerce_tax\TaxRate $rate */
        foreach ($zones[$zone_id]
          ->getRates() as $rate) {
          if ($rate
            ->getId() == $rate_id) {
            $values['rate_id'] = $rate
              ->getId();
            $values['rate_label'] = $rate
              ->getLabel();
            break;
          }
        }
      }
    }
    $this
      ->createFromOrder($order, $values);
  }
}