OrderItemProcessor.php 5.23 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
<?php

namespace Vertex\Tax\Model\Api\Data\InvoiceRequestBuilder;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Vertex\Data\LineItemInterfaceFactory;
use Vertex\Services\Invoice\RequestInterface;
use Vertex\Tax\Model\Repository\TaxClassNameRepository;

/**
 * Processes Items on an Order and adds them to a Vertex Invoice's LineItems
 */
class OrderItemProcessor implements OrderProcessorInterface
{
    /** @var TaxClassNameRepository */
    private $classNameRepository;

    /** @var SearchCriteriaBuilderFactory */
    private $criteriaBuilderFactory;

    /** @var LineItemInterfaceFactory */
    private $lineItemFactory;

    /** @var ProductRepositoryInterface */
    private $productRepository;

    /**
     * @param LineItemInterfaceFactory $lineItemFactory
     * @param ProductRepositoryInterface $productRepository
     * @param SearchCriteriaBuilderFactory $criteriaBuilderFactory
     * @param TaxClassNameRepository $classNameRepository
     */
    public function __construct(
        LineItemInterfaceFactory $lineItemFactory,
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilderFactory $criteriaBuilderFactory,
        TaxClassNameRepository $classNameRepository
    ) {
        $this->lineItemFactory = $lineItemFactory;
        $this->productRepository = $productRepository;
        $this->criteriaBuilderFactory = $criteriaBuilderFactory;
        $this->classNameRepository = $classNameRepository;
    }

    /**
     * @inheritdoc
     */
    public function process(RequestInterface $request, OrderInterface $order)
    {
        $lineItems = [];

        $orderItems = [];
        $productIds = [];
        /** @var int[] $taxClasses Key is OrderItem ID, Value is Tax Class ID */
        $taxClasses = [];

        foreach ($order->getItems() as $item) {
            if ($item->getBaseRowTotal() === null) {
                continue;
            }
            $orderItems[$item->getItemId()] = $item;
            $productIds[] = $item->getProductId();
        }

        $products = $this->getProductsIndexedById($productIds);

        foreach ($orderItems as $item) {
            if (in_array($item->getProductType(), ['bundle', 'configurable'])) {
                // Bundle's component parts are available with correct data
                // Configurables are handled on the child level with getParentItem for pricing data
                continue;
            }

            $parentItem = $item->getParentItem();
            if ($parentItem && $parentItem->getProductType() === 'configurable') {
                // The child of a configurable does not have the pricing information
                $unitPrice = $parentItem->getBasePrice();
                $extendedPrice = $parentItem->getBaseRowTotal() - $parentItem->getBaseDiscountAmount();
            } else {
                $unitPrice = $item->getBasePrice();
                $extendedPrice = $item->getBaseRowTotal() - $item->getBaseDiscountAmount();
            }

            $product = $products[$item->getProductId()];
            $taxClassAttribute = $product->getCustomAttribute('tax_class_id');
            $taxClassId = $taxClassAttribute ? $taxClassAttribute->getValue() : 0;
            $taxClasses[$item->getItemId()] = $taxClassId;

            $lineItem = $this->lineItemFactory->create();
            $lineItem->setProductCode($item->getSku());
            $lineItem->setQuantity($item->getQtyOrdered());
            $lineItem->setUnitPrice($unitPrice);
            $lineItem->setExtendedPrice($extendedPrice);
            $lineItem->setLineItemId($item->getItemId());

            $lineItems[] = $lineItem;
        }

        /** @var string[int] $taxClassNames Tax Classes indexed by ID */
        $taxClassNames = $this->classNameRepository->getListByIds(array_values($taxClasses));

        foreach ($lineItems as $lineItem) {
            $lineItemId = $lineItem->getLineItemId();
            $taxClass = $taxClasses[$lineItemId];
            $taxClassName = $taxClassNames[$taxClass];
            $lineItem->setProductClass($taxClassName);
        }

        $request->setLineItems(array_merge($request->getLineItems(), $lineItems));
        return $request;
    }

    /**
     * Retrieve an array of products indexed by their ID
     *
     * @param int[] $productIds
     * @return ProductInterface[] Indexed by id
     */
    private function getProductsIndexedById(array $productIds)
    {
        /** @var SearchCriteriaBuilder $criteriaBuilder */
        $criteriaBuilder = $this->criteriaBuilderFactory->create();
        $criteriaBuilder->addFilter('entity_id', $productIds, 'in');
        $criteria = $criteriaBuilder->create();

        $items = $this->productRepository->getList($criteria)->getItems();

        /** @var ProductInterface[] $products */
        return array_reduce(
            $items,
            function (array $carry, ProductInterface $product) {
                // This ensures that all products are indexed by ID, it is not an API guarantee
                $carry[$product->getId()] = $product;
                return $carry;
            },
            []
        );
    }
}