Passed
Pull Request — master (#74)
by Florian
04:32
created

preparePartialCaptureOrderItems()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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