Passed
Pull Request — master (#74)
by oleksandr
04:34
created

executePartialCapture()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 43
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 26
c 2
b 0
f 0
dl 0
loc 43
rs 9.504
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * MIT License
5
 * Use of this software requires acceptance of the Evaluation License Agreement. See LICENSE file.
6
 */
7
8
namespace SprykerEco\Zed\Payone\Business\Payment\RequestSender;
9
10
use Generated\Shared\Transfer\CaptureResponseTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfer\CaptureResponseTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Generated\Shared\Transfer\ItemTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfer\ItemTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Generated\Shared\Transfer\OrderTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfer\OrderTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Generated\Shared\Transfer\PayoneOrderItemFilterTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfe...OrderItemFilterTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Generated\Shared\Transfer\PayonePartialOperationRequestTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfe...perationRequestTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Generated\Shared\Transfer\PayoneStandardParameterTransfer;
0 ignored issues
show
Bug introduced by
The type Generated\Shared\Transfe...andardParameterTransfer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Orm\Zed\Payone\Persistence\SpyPaymentPayoneApiLog;
0 ignored issues
show
Bug introduced by
The type Orm\Zed\Payone\Persistence\SpyPaymentPayoneApiLog was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Spryker\Shared\Shipment\ShipmentConfig;
18
use SprykerEco\Shared\Payone\PayoneApiConstants;
19
use SprykerEco\Shared\Payone\PayoneTransactionStatusConstants;
20
use SprykerEco\Zed\Payone\Business\Api\Adapter\AdapterInterface;
21
use SprykerEco\Zed\Payone\Business\Api\Request\Container\AbstractRequestContainer;
22
use SprykerEco\Zed\Payone\Business\Api\Request\Container\Capture\BusinessContainer;
23
use SprykerEco\Zed\Payone\Business\Api\Response\Container\CaptureResponseContainer;
24
use SprykerEco\Zed\Payone\Business\Api\Response\Mapper\CaptureResponseMapperInterface;
25
use SprykerEco\Zed\Payone\Business\Distributor\OrderPriceDistributorInterface;
26
use SprykerEco\Zed\Payone\Business\Payment\DataMapper\ExpenseMapperInterface;
27
use SprykerEco\Zed\Payone\Business\Payment\DataMapper\ShipmentMapperInterface;
28
use SprykerEco\Zed\Payone\Business\Payment\DataMapper\StandartParameterMapperInterface;
29
use SprykerEco\Zed\Payone\Business\Payment\PaymentMapperReaderInterface;
30
use SprykerEco\Zed\Payone\Persistence\PayoneEntityManagerInterface;
31
use SprykerEco\Zed\Payone\Persistence\PayoneQueryContainerInterface;
32
use SprykerEco\Zed\Payone\Persistence\PayoneRepositoryInterface;
33
34
class PayonePartialCaptureRequestSender extends AbstractPayoneRequestSender implements PayonePartialCaptureRequestSenderInterface
35
{
36
    /**
37
     * @var string
38
     */
39
    protected const ITEM_STATE_SHIPPED = 'shipped';
40
41
    /**
42
     * @var \SprykerEco\Zed\Payone\Business\Api\Adapter\AdapterInterface
43
     */
44
    protected $executionAdapter;
45
46
    /**
47
     * @var \SprykerEco\Zed\Payone\Persistence\PayoneQueryContainerInterface
48
     */
49
    protected $queryContainer;
50
51
    /**
52
     * @var \Generated\Shared\Transfer\PayoneStandardParameterTransfer
53
     */
54
    protected $standardParameter;
55
56
    /**
57
     * @var \SprykerEco\Zed\Payone\Persistence\PayoneRepositoryInterface
58
     */
59
    protected $payoneRepository;
60
61
    /**
62
     * @var \SprykerEco\Zed\Payone\Persistence\PayoneEntityManagerInterface
63
     */
64
    protected $payoneEntityManager;
65
66
    /**
67
     * @var \SprykerEco\Zed\Payone\Business\Distributor\OrderPriceDistributorInterface
68
     */
69
    protected $orderPriceDistributor;
70
71
    /**
72
     * @var \SprykerEco\Zed\Payone\Business\Payment\DataMapper\StandartParameterMapperInterface
73
     */
74
    protected $standardParameterMapper;
75
76
    /**
77
     * @var \SprykerEco\Zed\Payone\Business\Payment\DataMapper\ShipmentMapperInterface
78
     */
79
    protected $shipmentMapper;
80
81
    /**
82
     * @var \SprykerEco\Zed\Payone\Business\Payment\PaymentMapperReaderInterface
83
     */
84
    protected $paymentMapperReader;
85
86
    /**
87
     * @var \SprykerEco\Zed\Payone\Business\Payment\DataMapper\ExpenseMapperInterface
88
     */
89
    protected $expenseMapper;
90
91
    /**
92
     * @var \SprykerEco\Zed\Payone\Business\Api\Response\Mapper\CaptureResponseMapperInterface
93
     */
94
    protected $captureResponseMapper;
95
96
    /**
97
     * @param \SprykerEco\Zed\Payone\Business\Api\Adapter\AdapterInterface $executionAdapter
98
     * @param \SprykerEco\Zed\Payone\Persistence\PayoneQueryContainerInterface $queryContainer
99
     * @param \SprykerEco\Zed\Payone\Business\Payment\PaymentMapperReaderInterface $paymentMapperReader
100
     * @param \SprykerEco\Zed\Payone\Business\Payment\DataMapper\ExpenseMapperInterface $expenseMapper
101
     * @param \Generated\Shared\Transfer\PayoneStandardParameterTransfer $standardParameter
102
     * @param \SprykerEco\Zed\Payone\Persistence\PayoneRepositoryInterface $payoneRepository
103
     * @param \SprykerEco\Zed\Payone\Persistence\PayoneEntityManagerInterface $payoneEntityManager
104
     * @param \SprykerEco\Zed\Payone\Business\Distributor\OrderPriceDistributorInterface $orderPriceDistributor
105
     * @param \SprykerEco\Zed\Payone\Business\Payment\DataMapper\StandartParameterMapperInterface $standardParameterMapper
106
     * @param \SprykerEco\Zed\Payone\Business\Payment\DataMapper\ShipmentMapperInterface $shipmentMapper
107
     * @param \SprykerEco\Zed\Payone\Business\Api\Response\Mapper\CaptureResponseMapperInterface $captureResponseMapper
108
     */
109
    public function __construct(
110
        AdapterInterface $executionAdapter,
111
        PayoneQueryContainerInterface $queryContainer,
112
        PaymentMapperReaderInterface $paymentMapperReader,
113
        ExpenseMapperInterface $expenseMapper,
114
        PayoneStandardParameterTransfer $standardParameter,
115
        PayoneRepositoryInterface $payoneRepository,
116
        PayoneEntityManagerInterface $payoneEntityManager,
117
        OrderPriceDistributorInterface $orderPriceDistributor,
118
        StandartParameterMapperInterface $standardParameterMapper,
119
        ShipmentMapperInterface $shipmentMapper,
120
        CaptureResponseMapperInterface $captureResponseMapper
121
    ) {
122
        parent::__construct($queryContainer, $paymentMapperReader);
123
        $this->executionAdapter = $executionAdapter;
124
        $this->standardParameter = $standardParameter;
125
        $this->payoneRepository = $payoneRepository;
126
        $this->payoneEntityManager = $payoneEntityManager;
127
        $this->orderPriceDistributor = $orderPriceDistributor;
128
        $this->standardParameterMapper = $standardParameterMapper;
129
        $this->shipmentMapper = $shipmentMapper;
130
        $this->expenseMapper = $expenseMapper;
131
        $this->captureResponseMapper = $captureResponseMapper;
132
    }
133
134
    /**
135
     * @param \Generated\Shared\Transfer\PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
136
     *
137
     * @return \Generated\Shared\Transfer\CaptureResponseTransfer
138
     */
139
    public function executePartialCapture(
140
        PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
141
    ): CaptureResponseTransfer {
142
        $distributedPriceOrderTransfer = $this->orderPriceDistributor->distributeOrderPrice(
143
            $payonePartialOperationRequestTransfer->getOrderOrFail(),
144
        );
145
        $payonePartialOperationRequestTransfer->setOrder($distributedPriceOrderTransfer);
146
147
        $paymentPayoneEntity = $this->getPaymentEntity($payonePartialOperationRequestTransfer->getOrderOrFail()->getIdSalesOrderOrFail());
148
        $paymentMethodMapper = $this->getPaymentMethodMapper($paymentPayoneEntity);
149
150
        /** @var \SprykerEco\Zed\Payone\Business\Api\Request\Container\AbstractRequestContainer $requestContainer */
151
        $requestContainer = $paymentMethodMapper->mapPaymentToCapture($paymentPayoneEntity);
152
        $requestContainer = $this->preparePartialCaptureOrderItems($payonePartialOperationRequestTransfer, $requestContainer);
153
        $captureAmount = $this->calculatePartialCaptureItemsAmount($payonePartialOperationRequestTransfer);
154
155
        if ($this->checkThatDeliveryCostsAreRequired($payonePartialOperationRequestTransfer)) {
156
            $captureAmount += $this->getDeliveryCosts($payonePartialOperationRequestTransfer->getOrderOrFail());
157
            $requestContainer = $this->shipmentMapper->mapShipment($payonePartialOperationRequestTransfer->getOrder(), $requestContainer);
158
        }
159
160
        $captureAmount += $this->calculateExpensesCost($payonePartialOperationRequestTransfer->getOrderOrFail());
161
        /** @var \SprykerEco\Zed\Payone\Business\Api\Request\Container\CaptureContainer $requestContainer */
162
        $requestContainer = $this->expenseMapper->mapExpenses($payonePartialOperationRequestTransfer->getOrderOrFail(), $requestContainer);
163
        $businessContainer = new BusinessContainer();
164
        $businessContainer->setSettleAccount(PayoneApiConstants::SETTLE_ACCOUNT_YES);
165
        $requestContainer->setBusiness($businessContainer);
166
167
        $requestContainer->setAmount($captureAmount);
168
        $this->standardParameterMapper->setStandardParameter($requestContainer, $this->standardParameter);
169
170
        $apiLogEntity = $this->initializeApiLog($paymentPayoneEntity, $requestContainer);
171
172
        $rawResponse = $this->executionAdapter->sendRequest($requestContainer);
173
        $responseContainer = new CaptureResponseContainer($rawResponse);
174
175
        $this->updateApiLogAfterCapture($apiLogEntity, $responseContainer);
176
        $this->updatePaymentPayoneOrderItemsWithStatus(
177
            $payonePartialOperationRequestTransfer,
178
            $this->getPartialCaptureStatus($responseContainer),
179
        );
180
181
        return $this->captureResponseMapper->getCaptureResponseTransfer($responseContainer);
182
    }
183
184
    /**
185
     * @param \Orm\Zed\Payone\Persistence\SpyPaymentPayoneApiLog $apiLogEntity
186
     * @param \SprykerEco\Zed\Payone\Business\Api\Response\Container\CaptureResponseContainer $responseContainer
187
     *
188
     * @return void
189
     */
190
    protected function updateApiLogAfterCapture(SpyPaymentPayoneApiLog $apiLogEntity, CaptureResponseContainer $responseContainer): void
191
    {
192
        $apiLogEntity->setStatus($responseContainer->getStatus());
193
        $apiLogEntity->setTransactionId($responseContainer->getTxid());
194
        $apiLogEntity->setErrorMessageInternal($responseContainer->getErrormessage());
195
        $apiLogEntity->setErrorMessageUser($responseContainer->getCustomerMessage());
196
        $apiLogEntity->setErrorCode($responseContainer->getErrorcode());
197
198
        $apiLogEntity->setRawResponse((string)json_encode($responseContainer->toArray()));
199
        $apiLogEntity->save();
200
    }
201
202
    /**
203
     * @param \Generated\Shared\Transfer\PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
204
     * @param \SprykerEco\Zed\Payone\Business\Api\Request\Container\AbstractRequestContainer $container
205
     *
206
     * @return \SprykerEco\Zed\Payone\Business\Api\Request\Container\AbstractRequestContainer
207
     */
208
    protected function preparePartialCaptureOrderItems(
209
        PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer,
210
        AbstractRequestContainer $container
211
    ): AbstractRequestContainer {
212
        $arrayIt = [];
213
        $arrayId = [];
214
        $arrayPr = [];
215
        $arrayNo = [];
216
        $arrayDe = [];
217
        $arrayVa = [];
218
219
        $key = 1;
220
221
        foreach ($payonePartialOperationRequestTransfer->getOrder()->getItems() as $itemTransfer) {
222
            if (!in_array($itemTransfer->getIdSalesOrderItem(), $payonePartialOperationRequestTransfer->getSalesOrderItemIds())) {
223
                continue;
224
            }
225
226
            $arrayIt[$key] = PayoneApiConstants::INVOICING_ITEM_TYPE_GOODS;
227
            $arrayId[$key] = substr((string)$itemTransfer->getSku(), 0, 32);
228
            $arrayPr[$key] = $itemTransfer->getUnitPriceToPayAggregation();
229
            $arrayNo[$key] = $itemTransfer->getQuantity();
230
            $arrayDe[$key] = $itemTransfer->getName();
231
            $arrayVa[$key] = (int)$itemTransfer->getTaxRate();
232
            $key++;
233
        }
234
235
        $container->setIt($arrayIt);
236
        $container->setId($arrayId);
237
        $container->setPr($arrayPr);
238
        $container->setNo($arrayNo);
239
        $container->setDe($arrayDe);
240
        $container->setVa($arrayVa);
241
242
        return $container;
243
    }
244
245
    /**
246
     * @param \Generated\Shared\Transfer\PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
247
     *
248
     * @return int
249
     */
250
    protected function calculatePartialCaptureItemsAmount(PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer): int
251
    {
252
        $itemsAmount = 0;
253
        foreach ($payonePartialOperationRequestTransfer->getOrder()->getItems() as $itemTransfer) {
254
            if (in_array($itemTransfer->getIdSalesOrderItem(), $payonePartialOperationRequestTransfer->getSalesOrderItemIds())) {
255
                $itemsAmount += $itemTransfer->getSumPriceToPayAggregation();
256
            }
257
        }
258
259
        return $itemsAmount;
260
    }
261
262
    /**
263
     * @param \Generated\Shared\Transfer\OrderTransfer $orderTransfer
264
     *
265
     * @return int
266
     */
267
    protected function getDeliveryCosts(OrderTransfer $orderTransfer): int
268
    {
269
        foreach ($orderTransfer->getExpenses() as $expense) {
270
            if ($expense->getType() === ShipmentConfig::SHIPMENT_EXPENSE_TYPE) {
271
                return (int)$expense->getSumGrossPrice();
272
            }
273
        }
274
275
        return 0;
276
    }
277
278
    /**
279
     * @param \Generated\Shared\Transfer\PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
280
     *
281
     * @return bool
282
     */
283
    protected function checkThatDeliveryCostsAreRequired(PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer): bool
284
    {
285
        foreach ($payonePartialOperationRequestTransfer->getOrder()->getItems() as $itemTransfer) {
286
            if (in_array($itemTransfer->getIdSalesOrderItem(), $payonePartialOperationRequestTransfer->getSalesOrderItemIds(), true)) {
287
                continue;
288
            }
289
            if ($this->isItemTransferWasShipped($itemTransfer)) {
290
                return false;
291
            }
292
        }
293
294
        return true;
295
    }
296
297
    /**
298
     * @param \Generated\Shared\Transfer\ItemTransfer $itemTransfer
299
     *
300
     * @return bool
301
     */
302
    protected function isItemTransferWasShipped(ItemTransfer $itemTransfer): bool
303
    {
304
        foreach ($itemTransfer->getStateHistory() as $itemState) {
305
            if ($itemState->getName() === static::ITEM_STATE_SHIPPED) {
306
                return true;
307
            }
308
        }
309
310
        return false;
311
    }
312
313
    /**
314
     * @param \Generated\Shared\Transfer\OrderTransfer $orderTransfer
315
     *
316
     * @return int
317
     */
318
    protected function calculateExpensesCost(OrderTransfer $orderTransfer): int
319
    {
320
        $expensesCostAmount = 0;
321
322
        foreach ($orderTransfer->getExpenses() as $expense) {
323
            if ($expense->getType() !== ShipmentConfig::SHIPMENT_EXPENSE_TYPE) {
324
                $expensesCostAmount += $expense->getSumGrossPrice();
325
            }
326
        }
327
328
        return $expensesCostAmount;
329
    }
330
331
    /**
332
     * @param \Generated\Shared\Transfer\PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer
333
     * @param string $refundStatus
334
     *
335
     * @return void
336
     */
337
    protected function updatePaymentPayoneOrderItemsWithStatus(
338
        PayonePartialOperationRequestTransfer $payonePartialOperationRequestTransfer,
339
        string $refundStatus
340
    ): void {
341
        $payoneOrderItemFilterTransfer = (new PayoneOrderItemFilterTransfer())
342
            ->setIdSalesOrder($payonePartialOperationRequestTransfer->getOrder()->getIdSalesOrder())
343
            ->setSalesOrderItemIds($payonePartialOperationRequestTransfer->getSalesOrderItemIds());
344
345
        $payoneOrderItemTransfers = $this->payoneRepository->findPaymentPayoneOrderItemByFilter($payoneOrderItemFilterTransfer);
346
347
        foreach ($payoneOrderItemTransfers as $payoneOrderItemTransfer) {
348
            $payoneOrderItemTransfer->setStatus($refundStatus);
349
            $this->payoneEntityManager->updatePaymentPayoneOrderItem($payoneOrderItemTransfer);
350
        }
351
    }
352
353
    /**
354
     * @param \SprykerEco\Zed\Payone\Business\Api\Response\Container\CaptureResponseContainer $responseContainer
355
     *
356
     * @return string
357
     */
358
    protected function getPartialCaptureStatus(CaptureResponseContainer $responseContainer): string
359
    {
360
        if ($responseContainer->getStatus() === PayoneApiConstants::RESPONSE_TYPE_APPROVED) {
361
            return PayoneTransactionStatusConstants::STATUS_CAPTURE_APPROVED;
362
        }
363
364
        return PayoneTransactionStatusConstants::STATUS_CAPTURE_FAILED;
365
    }
366
}
367