QuotationRequestBuilder.php 6.63 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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
<?php
/**
 * @copyright  Vertex. All rights reserved.  https://www.vertexinc.com/
 * @author     Mediotype                     https://www.mediotype.com/
 */

namespace Vertex\Tax\Model\Api\Data;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Tax\Api\Data\QuoteDetailsInterface;
use Magento\Tax\Api\Data\QuoteDetailsItemInterface;
use Magento\Tax\Api\Data\TaxClassKeyInterface;
use Vertex\Data\LineItemInterface;
use Vertex\Services\Quote\RequestInterface;
use Vertex\Services\Quote\RequestInterfaceFactory;
use Vertex\Tax\Model\AddressDeterminer;
use Vertex\Tax\Model\Api\Utility\DeliveryTerm;
use Vertex\Tax\Model\Config;
use Vertex\Tax\Model\DateTimeImmutableFactory;

/**
 * Builds a Quotation Request for the Vertex SDK
 */
class QuotationRequestBuilder
{
    const TRANSACTION_TYPE = 'SALE';

    /** @var AddressDeterminer */
    private $addressDeterminer;

    /** @var Config */
    private $config;

    /** @var CustomerBuilder */
    private $customerBuilder;

    /** @var DateTimeImmutableFactory */
    private $dateTimeFactory;

    /** @var DeliveryTerm */
    private $deliveryTerm;

    /** @var LineItemBuilder */
    private $lineItemBuilder;

    /** @var RequestInterfaceFactory */
    private $requestFactory;

    /** @var SellerBuilder */
    private $sellerBuilder;

    /** @var StoreManagerInterface */
    private $storeManager;

    /**
     * @param LineItemBuilder $lineItemBuilder
     * @param RequestInterfaceFactory $requestFactory
     * @param CustomerBuilder $customerBuilder
     * @param SellerBuilder $sellerBuilder
     * @param Config $config
     * @param DeliveryTerm $deliveryTerm
     * @param DateTimeImmutableFactory $dateTimeFactory
     * @param AddressDeterminer $addressDeterminer
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        LineItemBuilder $lineItemBuilder,
        RequestInterfaceFactory $requestFactory,
        CustomerBuilder $customerBuilder,
        SellerBuilder $sellerBuilder,
        Config $config,
        DeliveryTerm $deliveryTerm,
        DateTimeImmutableFactory $dateTimeFactory,
        AddressDeterminer $addressDeterminer,
        StoreManagerInterface $storeManager
    ) {
        $this->lineItemBuilder = $lineItemBuilder;
        $this->requestFactory = $requestFactory;
        $this->customerBuilder = $customerBuilder;
        $this->sellerBuilder = $sellerBuilder;
        $this->config = $config;
        $this->deliveryTerm = $deliveryTerm;
        $this->dateTimeFactory = $dateTimeFactory;
        $this->addressDeterminer = $addressDeterminer;
        $this->storeManager = $storeManager;
    }

    /**
     * Create a properly formatted Quote Request for the Vertex API
     *
     * @param QuoteDetailsInterface $quoteDetails
     * @param string|null $scopeCode
     * @return RequestInterface
     * @throws LocalizedException
     * @throws NoSuchEntityException
     */
    public function buildFromQuoteDetails(QuoteDetailsInterface $quoteDetails, $scopeCode = null)
    {
        /** @var RequestInterface $request */
        $request = $this->requestFactory->create();
        $request->setShouldReturnAssistedParameters(true);
        $request->setDocumentDate($this->dateTimeFactory->create());
        $request->setTransactionType(static::TRANSACTION_TYPE);
        $request->setCurrencyCode($this->storeManager->getStore($scopeCode)->getBaseCurrencyCode());

        $taxLineItems = $this->getLineItemData($quoteDetails->getItems());
        $request->setLineItems($taxLineItems);

        $address = $this->addressDeterminer->determineAddress(
            $quoteDetails->getShippingAddress() ?: $quoteDetails->getBillingAddress(),
            $quoteDetails->getCustomerId(),
            $this->isVirtual($quoteDetails)
        );

        $seller = $this->sellerBuilder
            ->setScopeCode($scopeCode)
            ->setScopeType(ScopeInterface::SCOPE_STORE)
            ->build();

        $request->setSeller($seller);

        $taxClassKey = $quoteDetails->getCustomerTaxClassKey();
        if ($taxClassKey && $taxClassKey->getType() === TaxClassKeyInterface::TYPE_ID) {
            $customerTaxClassId = $taxClassKey->getValue();
        } else {
            $customerTaxClassId = $quoteDetails->getCustomerTaxClassId();
        }

        $request->setCustomer(
            $this->customerBuilder->buildFromCustomerAddress(
                $address,
                $quoteDetails->getCustomerId(),
                $customerTaxClassId,
                $scopeCode
            )
        );

        $this->deliveryTerm->addIfApplicable($request);

        if ($this->config->getLocationCode($scopeCode)) {
            $request->setLocationCode($this->config->getLocationCode($scopeCode));
        }

        return $request;
    }

    /**
     * Build Line Items for the Request
     *
     * @param QuoteDetailsItemInterface[] $items
     * @return LineItemInterface[]
     */
    private function getLineItemData(array $items)
    {
        // The resulting LineItemInterface[] to be used with Vertex
        $taxLineItems = [];

        // An array of codes for parent items
        $parentCodes = [];

        // A map of all items by their code
        $itemMap = [];

        // Item codes already processed - to prevent duplicates from bundles & configurables
        $processedItems = [];

        foreach ($items as $item) {
            $itemMap[$item->getCode()] = $item;
            if ($item->getParentCode()) {
                $parentCodes[] = $item->getParentCode();
            }
        }

        foreach ($items as $item) {
            if (in_array($item->getCode(), array_merge($parentCodes, $processedItems), true)) {
                // We merge these two arrays together as a convenience so we only need to run in_array once
                continue;
            }

            $quantity = $item->getParentCode()
                ? $item->getQuantity() * $itemMap[$item->getParentCode()]->getQuantity()
                : $item->getQuantity();

            $taxLineItems[] = $this->lineItemBuilder->buildFromQuoteDetailsItem($item, $quantity);
            $processedItems[] = $item->getCode();
        }

        return $taxLineItems;
    }

    /**
     * Determine if the Quote is virtual
     *
     * @param QuoteDetailsInterface $quoteDetails
     * @return bool
     */
    private function isVirtual(QuoteDetailsInterface $quoteDetails)
    {
        foreach ($quoteDetails->getItems() as $item) {
            if ($item->getType() === 'shipping') {
                return false;
            }
        }

        return true;
    }
}