PluginProbe
Packeta / 2.1
Packeta v2.1
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
← All changes | src/Packetery/Module/Order/PacketSubmitter.php +80 -121 1.6.12.1 View file →
@@ -1,10 +1,5 @@
1 1 <?php
2 -/**
3 - * Class PacketSubmitter
4 - *
5 - * @package Packetery\Module\Order
6 - */
7 2
8 3 declare( strict_types=1 );
9 4
10 5 namespace Packetery\Module\Order;
@@ -10,124 +5,92 @@
10 5 namespace Packetery\Module\Order;
11 6
12 7 use Packetery\Core\Api\InvalidRequestException;
13 8 use Packetery\Core\Api\Soap;
9 +use Packetery\Core\Api\Soap\CreatePacketMapper;
10 +use Packetery\Core\CoreHelper;
14 11 use Packetery\Core\Entity;
15 12 use Packetery\Core\Log;
16 -use Packetery\Core\Rounder;
17 13 use Packetery\Core\Validator;
18 -use Packetery\Core\Api\Soap\CreatePacketMapper;
19 -use Packetery\Module\Carrier\Options;
14 +use Packetery\Module;
20 15 use Packetery\Module\CustomsDeclaration;
21 -use Packetery\Module\Exception\InvalidCarrierException;
22 16 use Packetery\Module\MessageManager;
23 -use Packetery\Module\ShippingMethod;
17 +use Packetery\Module\ModuleHelper;
18 +use Packetery\Module\Shipping\ShippingProvider;
24 19 use Packetery\Nette\Http\Request;
25 20 use WC_Order;
26 -use Packetery\Module;
27 21
28 -/**
29 - * Class PacketSubmitter
30 - *
31 - * @package Packetery\Module\Order
32 - */
33 22 class PacketSubmitter {
23 + const HOOK_PACKET_STATUS_SYNC = 'packetery_packet_status_sync_hook';
34 24
35 25 /**
36 - * SOAP API Client.
37 - *
38 - * @var Soap\Client SOAP API Client.
26 + * @var Soap\Client
39 27 */
40 28 private $soapApiClient;
41 29
42 30 /**
43 - * Order validator.
44 - *
45 31 * @var Validator\Order
46 32 */
47 33 private $orderValidator;
48 34
49 35 /**
50 - * ILogger.
51 - *
52 36 * @var Log\ILogger
53 37 */
54 38 private $logger;
55 39
56 40 /**
57 - * Order repository.
58 - *
59 41 * @var Repository
60 42 */
61 43 private $orderRepository;
62 44
63 45 /**
64 - * CreatePacketMapper.
65 - *
66 46 * @var CreatePacketMapper
67 47 */
68 48 private $createPacketMapper;
69 49
70 50 /**
71 - * Request.
72 - *
73 51 * @var Request
74 52 */
75 53 private $request;
76 54
77 55 /**
78 - * Message manager.
79 - *
80 56 * @var MessageManager
81 57 */
82 58 private $messageManager;
83 59
84 60 /**
85 - * Log page.
86 - *
87 61 * @var Module\Log\Page
88 62 */
89 63 private $logPage;
90 64
91 65 /**
92 - * Common logic.
93 - *
94 66 * @var PacketActionsCommonLogic
95 67 */
96 68 private $commonLogic;
97 69
98 70 /**
99 - * Options provider.
100 - *
101 - * @var Module\Options\Provider
71 + * @var CustomsDeclaration\Repository
102 72 */
103 - private $optionsProvider;
73 + private $customsDeclarationRepository;
104 74
105 75 /**
106 - * Customs declaration repository.
107 - *
108 - * @var CustomsDeclaration\Repository
76 + * @var PacketSynchronizer
109 77 */
110 - private $customsDeclarationRepository;
78 + private $packetSynchronizer;
111 79
112 80 /**
113 - * OrderApi constructor.
114 - *
115 - * @param Soap\Client $soapApiClient SOAP API Client.
116 - * @param Validator\Order $orderValidator Order validator.
117 - * @param Log\ILogger $logger Logger.
118 - * @param Repository $orderRepository Order repository.
119 - * @param CreatePacketMapper $createPacketMapper CreatePacketMapper.
120 - * @param Request $request Request.
121 - * @param MessageManager $messageManager Message manager.
122 - * @param Module\Log\Page $logPage Log page.
123 - * @param PacketActionsCommonLogic $commonLogic Common logic.
124 - * @param Module\Options\Provider $optionsProvider Options provider.
125 - * @param CustomsDeclaration\Repository $customsDeclarationRepository Customs declaration repository.
81 + * @var ModuleHelper
126 82 */
83 + private $moduleHelper;
84 +
85 + /**
86 + * @var CoreHelper
87 + */
88 + private $coreHelper;
89 +
127 90 public function __construct(
128 91 Soap\Client $soapApiClient,
129 - Validator\Order $orderValidator,
92 + OrderValidatorFactory $orderValidatorFactory,
130 93 Log\ILogger $logger,
131 94 Repository $orderRepository,
132 95 CreatePacketMapper $createPacketMapper,
133 96 Request $request,
@@ -133,13 +96,15 @@
133 96 Request $request,
134 97 MessageManager $messageManager,
135 98 Module\Log\Page $logPage,
136 99 PacketActionsCommonLogic $commonLogic,
137 - Module\Options\Provider $optionsProvider,
138 - CustomsDeclaration\Repository $customsDeclarationRepository
100 + CustomsDeclaration\Repository $customsDeclarationRepository,
101 + PacketSynchronizer $packetSynchronizer,
102 + ModuleHelper $moduleHelper,
103 + CoreHelper $coreHelper
139 104 ) {
140 105 $this->soapApiClient = $soapApiClient;
141 - $this->orderValidator = $orderValidator;
106 + $this->orderValidator = $orderValidatorFactory->create();
142 107 $this->logger = $logger;
143 108 $this->orderRepository = $orderRepository;
144 109 $this->createPacketMapper = $createPacketMapper;
145 110 $this->request = $request;
@@ -145,10 +110,12 @@
145 110 $this->request = $request;
146 111 $this->messageManager = $messageManager;
147 112 $this->logPage = $logPage;
148 113 $this->commonLogic = $commonLogic;
149 - $this->optionsProvider = $optionsProvider;
150 114 $this->customsDeclarationRepository = $customsDeclarationRepository;
115 + $this->packetSynchronizer = $packetSynchronizer;
116 + $this->moduleHelper = $moduleHelper;
117 + $this->coreHelper = $coreHelper;
151 118 }
152 119
153 120 /**
154 121 * Process action
@@ -158,9 +125,9 @@
158 125 public function processAction(): void {
159 126 $order = $this->commonLogic->getOrder();
160 127 $redirectTo = $this->request->getQuery( PacketActionsCommonLogic::PARAM_REDIRECT_TO );
161 128
162 - if ( null === $order ) {
129 + if ( $order === null ) {
163 130 $record = new Log\Record();
164 131 $record->action = Log\Record::ACTION_PACKET_SENDING;
165 132 $record->status = Log\Record::STATUS_ERROR;
166 133 $record->orderId = null;
@@ -181,10 +148,10 @@
181 148 $this->commonLogic->checkAction( PacketActionsCommonLogic::ACTION_SUBMIT_PACKET, $order );
182 149
183 150 $submissionResult = $this->submitPacket(
184 151 $this->orderRepository->getWcOrderById( (int) $order->getNumber() ),
185 - $this->optionsProvider->isOrderStatusAutoChangeEnabled(),
186 - $order
152 + $order,
153 + true
187 154 );
188 155 $resultsCounter = $submissionResult->getCounter();
189 156 $submissionResultMessages = $this->getTranslatedSubmissionMessages( $resultsCounter, (int) $order->getNumber() );
190 157
@@ -220,28 +187,24 @@
220 187
221 188 /**
222 189 * Submits packet data to Packeta API.
223 190 *
224 - * @param WC_Order $wcOrder WC order.
225 - * @param bool $updateOrderStatus Updates WC order status if packet was successfully created. Value is based on plugin settings.
226 - * @param Entity\Order|null $order Order.
191 + * @param WC_Order $wcOrder WC order.
192 + * @param Entity\Order|null $order Order.
193 + * @param bool $immediatePacketStatusCheck Whether to sync status immediately.
227 194 *
228 195 * @return PacketSubmissionResult
229 196 */
230 197 public function submitPacket(
231 198 WC_Order $wcOrder,
232 - bool $updateOrderStatus,
233 - ?Entity\Order $order = null
199 + ?Entity\Order $order = null,
200 + bool $immediatePacketStatusCheck = false
234 201 ): PacketSubmissionResult {
235 202 $submissionResult = new PacketSubmissionResult();
236 - if ( null === $order ) {
237 - try {
238 - $order = $this->orderRepository->getByWcOrder( $wcOrder );
239 - } catch ( InvalidCarrierException $exception ) {
240 - $order = null;
241 - }
203 + if ( $order === null ) {
204 + $order = $this->orderRepository->getByWcOrderWithValidCarrier( $wcOrder );
242 205 }
243 - if ( null === $order ) {
206 + if ( $order === null ) {
244 207 $submissionResult->increaseIgnoredCount();
245 208
246 209 return $submissionResult;
247 210 }
@@ -251,14 +214,13 @@
251 214 $shippingMethod = reset( $shippingMethods );
252 215
253 216 $shippingMethodData = $shippingMethod->get_data();
254 217 $shippingMethodId = $shippingMethodData['method_id'];
255 - if ( ShippingMethod::PACKETERY_METHOD_ID === $shippingMethodId && ! $order->isExported() ) {
256 -
218 + if ( ShippingProvider::isPacketaMethod( $shippingMethodId ) && ! $order->isExported() ) {
257 219 $customsDeclaration = $order->getCustomsDeclaration();
258 220 if (
259 - null !== $customsDeclaration &&
260 - null === $customsDeclaration->getInvoiceFileId() &&
221 + $customsDeclaration !== null &&
222 + $customsDeclaration->getInvoiceFileId() === null &&
261 223 $customsDeclaration->hasInvoiceFileContent()
262 224 ) {
263 225 $invoiceFileResponse = $this->soapApiClient->createStorageFile(
264 226 new Soap\Request\CreateStorageFile(
@@ -291,10 +253,10 @@
291 253 $this->customsDeclarationRepository->save( $customsDeclaration );
292 254 }
293 255
294 256 if (
295 - null !== $customsDeclaration &&
296 - null === $customsDeclaration->getEadFileId() &&
257 + $customsDeclaration !== null &&
258 + $customsDeclaration->getEadFileId() === null &&
297 259 $customsDeclaration->hasEadFileContent()
298 260 ) {
299 261 $eadFileResponse = $this->soapApiClient->createStorageFile(
300 262 new Soap\Request\CreateStorageFile(
@@ -363,8 +325,9 @@
363 325 $submissionResult->increaseErrorsCount();
364 326 } else {
365 327 $order->setIsExported( true );
366 328 $order->setPacketId( $response->getId() );
329 + $order->setPacketTrackingUrl( $this->coreHelper->getTrackingUrl( $response->getId() ) );
367 330
368 331 $record = new Log\Record();
369 332 $record->action = Log\Record::ACTION_PACKET_SENDING;
370 333 $record->status = Log\Record::STATUS_SUCCESS;
@@ -376,8 +339,23 @@
376 339 $record->orderId = $order->getNumber();
377 340 $errorMessage = null;
378 341
379 342 $submissionResult->increaseSuccessCount();
343 +
344 + $wcOrder->add_order_note(
345 + sprintf(
346 + // translators: %s represents a packet tracking link.
347 + __( 'Packeta: Packet %s has been created', 'packeta' ),
348 + $this->moduleHelper->createHtmlLink( $order->getPacketTrackingUrl(), $order->getPacketBarcode() )
349 + )
350 + );
351 + $wcOrder->save();
352 +
353 + if ( $immediatePacketStatusCheck || ! function_exists( 'as_enqueue_async_action' ) ) {
354 + $this->packetSynchronizer->syncStatus( $order );
355 + } else {
356 + as_enqueue_async_action( self::HOOK_PACKET_STATUS_SYNC, [ $order->getNumber() ] );
357 + }
380 358 }
381 359
382 360 $submissionResult->increaseLogsCount();
383 361 $this->logger->add( $record );
@@ -382,12 +360,8 @@
382 360 $submissionResult->increaseLogsCount();
383 361 $this->logger->add( $record );
384 362 $order->updateApiErrorMessage( $errorMessage );
385 363 $this->orderRepository->save( $order );
386 -
387 - if ( $updateOrderStatus && false === $response->hasFault() ) {
388 - $this->updateOrderStatusOrLogError( $wcOrder, $order->getNumber(), $submissionResult );
389 - }
390 364 } else {
391 365 $submissionResult->increaseIgnoredCount();
392 366 }
393 367
@@ -397,23 +371,18 @@
397 371 /**
398 372 * Prepares packet attributes.
399 373 *
400 374 * @param Entity\Order $order Order entity.
401 - * @return array
375 + * @return array<string, string|null|bool>
402 376 * @throws InvalidRequestException For the case request is not eligible to be sent to API.
403 377 */
404 378 private function preparePacketData( Entity\Order $order ): array {
405 379 $validationErrors = $this->orderValidator->validate( $order );
406 - if ( ! empty( $validationErrors ) ) {
380 + if ( count( $validationErrors ) > 0 ) {
407 381 throw new InvalidRequestException( 'All required order attributes are not set.', $validationErrors );
408 382 }
409 383
410 384 $createPacketData = $this->createPacketMapper->fromOrderToArray( $order );
411 - if ( ! empty( $createPacketData['cod'] ) ) {
412 - $roundingType = Options::createByCarrierId( $order->getCarrier()->getId() )->getCodRoundingType();
413 - $roundedCod = Rounder::roundByCurrency( $createPacketData['cod'], $createPacketData['currency'], $roundingType );
414 - $createPacketData['cod'] = $roundedCod;
415 - }
416 385
417 386 /**
418 387 * Allows to update CreatePacket request data.
419 388 *
@@ -426,12 +395,12 @@
426 395
427 396 /**
428 397 * Gets translated messages by submission result.
429 398 *
430 - * @param array $submissionResult Submission result.
431 - * @param int|null $orderId Order ID.
399 + * @param array<string, int> $submissionResult Submission result.
400 + * @param int|null $orderId Order ID.
432 401 *
433 - * @return array
402 + * @return array<string, null|string>
434 403 */
435 404 public function getTranslatedSubmissionMessages( array $submissionResult, ?int $orderId ): array {
436 405 $success = null;
437 406 if ( is_numeric( $submissionResult['success'] ) && $submissionResult['success'] > 0 ) {
@@ -476,9 +445,9 @@
476 445 $submissionResult['errors']
477 446 );
478 447 }
479 448 } elseif ( isset( $submissionResult['errors'] ) ) {
480 - $errors = esc_html( $submissionResult['errors'] );
449 + $errors = esc_html( (string) $submissionResult['errors'] );
481 450 }
482 451
483 452 if ( is_numeric( $submissionResult['statusUnchanged'] ) && $submissionResult['statusUnchanged'] > 0 ) {
484 453 $errors = esc_html__( 'Some order statuses have not been automatically changed.', 'packeta' );
@@ -491,33 +460,23 @@
491 460 ];
492 461 }
493 462
494 463 /**
495 - * Updates order status or logs error.
464 + * Registers action for cron.
496 465 *
497 - * @param WC_Order $order WC Order.
498 - * @param string $orderId Order ID.
499 - * @param PacketSubmissionResult $submissionResult Packet submission result.
500 - *
501 466 * @return void
502 467 */
503 - private function updateOrderStatusOrLogError( WC_Order $order, string $orderId, PacketSubmissionResult $submissionResult ):void {
504 - $autoOrderStatus = $this->optionsProvider->getValidAutoOrderStatus();
505 - if ( '' === $autoOrderStatus ) {
506 - $record = new Log\Record();
507 - $record->action = Log\Record::ACTION_PACKET_SENDING;
508 - $record->status = Log\Record::STATUS_ERROR;
509 -
510 - $record->title = sprintf(
511 - // translators: %s represents unknown order status.
512 - __( 'Order status has not been changed, status "%s" doesn\'t exist.', 'packeta' ),
513 - $this->optionsProvider->getAutoOrderStatus()
514 - );
515 - $record->orderId = $orderId;
516 - $this->logger->add( $record );
517 - $submissionResult->increaseStatusUnchangedCount();
518 - } else {
519 - $order->update_status( $autoOrderStatus );
520 - }
468 + public function registerCronAction(): void {
469 + add_action(
470 + self::HOOK_PACKET_STATUS_SYNC,
471 + function ( string $orderId ): void {
472 + $order = $this->orderRepository->getByIdWithValidCarrier( (int) $orderId );
473 + if ( $order === null ) {
474 + return;
475 + }
476 + $this->packetSynchronizer->syncStatus( $order );
477 + },
478 + 10,
479 + 1
480 + );
521 481 }
522 -
523 482 }