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
<?php
/**
* @copyright Vertex. All rights reserved. https://www.vertexinc.com/
* @author Mediotype https://www.mediotype.com/
*/
namespace Vertex\Tax\Model\Request;
use Magento\Quote\Api\Data\AddressInterface;
use Vertex\Data\LineItemInterface;
use Vertex\Data\LineItemInterfaceFactory;
use Vertex\Tax\Model\Calculation\VertexCalculator;
use Vertex\Tax\Model\Config;
use Vertex\Tax\Model\Repository\TaxClassNameRepository;
/**
* Shipping data formatter for Vertex API Calls
*/
class Shipping
{
const LINE_ITEM_ID = VertexCalculator::VERTEX_SHIPPING_LINE_ITEM_ID;
/** @var Config */
private $config;
/** @var LineItemInterfaceFactory */
private $lineItemFactory;
/** @var TaxClassNameRepository */
private $taxClassNameRepository;
/**
* @param Config $config
* @param TaxClassNameRepository $taxClassNameRepository
* @param LineItemInterfaceFactory $lineItemFactory
*/
public function __construct(
Config $config,
TaxClassNameRepository $taxClassNameRepository,
LineItemInterfaceFactory $lineItemFactory
) {
$this->config = $config;
$this->taxClassNameRepository = $taxClassNameRepository;
$this->lineItemFactory = $lineItemFactory;
}
/**
* Create properly formatted Line Item data for the Order Shipping
*
* @param AddressInterface $taxAddress
* @param string|null $scopeCode
* @return LineItemInterface
*/
public function getFormattedShippingLineItemData(AddressInterface $taxAddress, $scopeCode = null)
{
/** @var LineItemInterface $item */
$item = $this->lineItemFactory->create();
$item->setProductCode(substr($taxAddress->getShippingMethod(), 0, Config::MAX_CHAR_PRODUCT_CODE_ALLOWED));
$item->setProductClass(
substr(
$this->taxClassNameRepository->getById(
$this->config->getShippingTaxClassId($scopeCode)
),
0,
Config::MAX_CHAR_PRODUCT_CODE_ALLOWED
)
);
$item->setQuantity(1);
$rate = $taxAddress->getShippingRateByCode($taxAddress->getShippingMethod());
if (!$rate && $taxAddress->getShippingMethod()) {
$taxAddress->setCollectShippingRates(true)->collectShippingRates();
}
foreach ($taxAddress->getAllShippingRates() as $rateCandidate) {
if ($rateCandidate->getCode() === $taxAddress->getShippingMethod()) {
$rate = $rateCandidate;
break;
}
}
$unitPrice = $rate ? $rate->getPrice() : 0;
$extendedPrice = $unitPrice ? $unitPrice - $taxAddress->getBaseShippingDiscountAmount() : 0;
$item->setUnitPrice($unitPrice);
$item->setExtendedPrice($extendedPrice);
$item->setLineItemId(static::LINE_ITEM_ID);
return $item;
}
}