PluginProbe
Packeta / 2.0.9
Packeta v2.0.9
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/LabelPrint.php +244 -200 trunk2.0.9 View file →
@@ -1,5 +1,10 @@
1 1 <?php
2 +/**
3 + * Class LabelPrint.
4 + *
5 + * @package Packetery\Order
6 + */
2 7
3 8 declare( strict_types=1 );
4 9
5 10 namespace Packetery\Module\Order;
@@ -7,23 +12,25 @@
7 12 use Packetery\Core\Api\Soap\Client;
8 13 use Packetery\Core\Api\Soap\ILabelResponse;
9 14 use Packetery\Core\Api\Soap\Request;
10 15 use Packetery\Core\Api\Soap\Response;
16 +use Packetery\Core\Entity\Order;
11 17 use Packetery\Core\Log;
12 18 use Packetery\Latte\Engine;
13 -use Packetery\Module\Dashboard\DashboardPage;
14 -use Packetery\Module\Framework\WpAdapter;
15 -use Packetery\Module\Labels\CarrierLabelService;
16 -use Packetery\Module\Labels\LabelPrintParametersService;
19 +use Packetery\Module\FormFactory;
17 20 use Packetery\Module\MessageManager;
18 21 use Packetery\Module\ModuleHelper;
19 22 use Packetery\Module\Options\OptionsProvider;
20 23 use Packetery\Module\Plugin;
21 -use Packetery\Module\Transients;
24 +use Packetery\Nette\Forms\Form;
22 25 use Packetery\Nette\Http;
23 26
27 +/**
28 + * Class LabelPrint.
29 + *
30 + * @package Packetery\Order
31 + */
24 32 class LabelPrint {
25 -
26 33 public const ACTION_PACKETA_LABELS = 'print_packeta_labels';
27 34 public const ACTION_CARRIER_LABELS = 'print_carrier_labels';
28 35 public const LABEL_TYPE_PARAM = 'label_type';
29 36 public const MENU_SLUG = 'label-print';
@@ -28,70 +35,95 @@
28 35 public const LABEL_TYPE_PARAM = 'label_type';
29 36 public const MENU_SLUG = 'label-print';
30 37
31 38 /**
32 - * @var Engine
39 + * PacketeryLatte Engine.
40 + *
41 + * @var Engine PacketeryLatte engine.
33 42 */
34 43 private $latteEngine;
35 44
36 45 /**
46 + * Options Provider
47 + *
37 48 * @var OptionsProvider
38 49 */
39 50 private $optionsProvider;
40 51
41 52 /**
53 + * Form factory.
54 + *
55 + * @var FormFactory Form factory.
56 + */
57 + private $formFactory;
58 +
59 + /**
60 + * Http Request.
61 + *
42 62 * @var Http\Request
43 63 */
44 64 private $httpRequest;
45 65
46 66 /**
47 - * @var Client
67 + * SOAP API Client.
68 + *
69 + * @var Client SOAP API Client.
48 70 */
49 71 private $soapApiClient;
50 72
51 73 /**
74 + * Message Manager.
75 + *
52 76 * @var MessageManager
53 77 */
54 78 private $messageManager;
55 79
56 80 /**
81 + * Logger.
82 + *
57 83 * @var Log\ILogger
58 84 */
59 85 private $logger;
60 86
61 87 /**
88 + * Order repository.
89 + *
62 90 * @var Repository
63 91 */
64 92 private $orderRepository;
65 93
66 94 /**
95 + * Packet actions common logic.
96 + *
67 97 * @var PacketActionsCommonLogic
68 98 */
69 99 private $packetActionsCommonLogic;
70 100
71 101 /**
102 + * ModuleHelper.
103 + *
72 104 * @var ModuleHelper
73 105 */
74 106 private $moduleHelper;
75 107
76 108 /**
77 - * @var WpAdapter
109 + * LabelPrint constructor.
110 + *
111 + * @param Engine $latteEngine Latte Engine.
112 + * @param OptionsProvider $optionsProvider Options provider.
113 + * @param FormFactory $formFactory Form factory.
114 + * @param Http\Request $httpRequest Http Request.
115 + * @param Client $soapApiClient SOAP API Client.
116 + * @param MessageManager $messageManager Message Manager.
117 + * @param Log\ILogger $logger Logger.
118 + * @param Repository $orderRepository Order repository.
119 + * @param PacketActionsCommonLogic $packetActionsCommonLogic Packet actions common logic.
120 + * @param ModuleHelper $moduleHelper ModuleHelper.
78 121 */
79 - private $wpAdapter;
80 -
81 - /**
82 - * @var CarrierLabelService
83 - */
84 - private $carrierLabelService;
85 -
86 - /**
87 - * @var LabelPrintParametersService
88 - */
89 - private $labelPrintParametersService;
90 -
91 122 public function __construct(
92 123 Engine $latteEngine,
93 124 OptionsProvider $optionsProvider,
125 + FormFactory $formFactory,
94 126 Http\Request $httpRequest,
95 127 Client $soapApiClient,
96 128 MessageManager $messageManager,
97 129 Log\ILogger $logger,
@@ -96,25 +128,20 @@
96 128 MessageManager $messageManager,
97 129 Log\ILogger $logger,
98 130 Repository $orderRepository,
99 131 PacketActionsCommonLogic $packetActionsCommonLogic,
100 - ModuleHelper $moduleHelper,
101 - WpAdapter $wpAdapter,
102 - CarrierLabelService $carrierLabelService,
103 - LabelPrintParametersService $labelPrintParametersService
132 + ModuleHelper $moduleHelper
104 133 ) {
105 - $this->latteEngine = $latteEngine;
106 - $this->optionsProvider = $optionsProvider;
107 - $this->httpRequest = $httpRequest;
108 - $this->soapApiClient = $soapApiClient;
109 - $this->messageManager = $messageManager;
110 - $this->logger = $logger;
111 - $this->orderRepository = $orderRepository;
112 - $this->packetActionsCommonLogic = $packetActionsCommonLogic;
113 - $this->moduleHelper = $moduleHelper;
114 - $this->wpAdapter = $wpAdapter;
115 - $this->carrierLabelService = $carrierLabelService;
116 - $this->labelPrintParametersService = $labelPrintParametersService;
134 + $this->latteEngine = $latteEngine;
135 + $this->optionsProvider = $optionsProvider;
136 + $this->formFactory = $formFactory;
137 + $this->httpRequest = $httpRequest;
138 + $this->soapApiClient = $soapApiClient;
139 + $this->messageManager = $messageManager;
140 + $this->logger = $logger;
141 + $this->orderRepository = $orderRepository;
142 + $this->packetActionsCommonLogic = $packetActionsCommonLogic;
143 + $this->moduleHelper = $moduleHelper;
117 144 }
118 145
119 146 /**
120 147 * Generates id of transient to store order ids.
@@ -121,9 +148,9 @@
121 148 *
122 149 * @return string
123 150 */
124 151 public static function getOrderIdsTransientName(): string {
125 - return Transients::LABEL_PRINT_ORDER_IDS_PREFIX . wp_get_session_token();
152 + return 'packetery_label_print_order_ids_' . wp_get_session_token();
126 153 }
127 154
128 155 /**
129 156 * Generates id of transient to store back link.
@@ -130,16 +157,31 @@
130 157 *
131 158 * @return string
132 159 */
133 160 public static function getBackLinkTransientName(): string {
134 - return Transients::LABEL_PRINT_BACK_LINK_PREFIX . wp_get_session_token();
161 + return 'packetery_label_print_back_link_' . wp_get_session_token();
135 162 }
136 163
137 164 /**
165 + * Gets label type.
166 + *
167 + * @param Order $order Order.
168 + *
169 + * @return string
170 + */
171 + public function getLabelFormatByOrder( Order $order ): string {
172 + if ( $order->isExternalCarrier() ) {
173 + return $this->optionsProvider->get_carrier_label_format();
174 + }
175 +
176 + return $this->optionsProvider->get_packeta_label_format();
177 + }
178 +
179 + /**
138 180 * Prepares form and renders template.
139 181 */
140 182 public function render(): void {
141 - $form = $this->labelPrintParametersService->createForm( $this->optionsProvider->getLabelMaxOffset( $this->labelPrintParametersService->getLabelFormat() ) );
183 + $form = $this->createForm( $this->optionsProvider->getLabelMaxOffset( $this->getLabelFormat() ) );
142 184
143 185 $count = 0;
144 186 $isCarrierLabels = ( $this->httpRequest->getQuery( self::LABEL_TYPE_PARAM ) === self::ACTION_CARRIER_LABELS );
145 187
@@ -170,8 +212,23 @@
170 212 ]
171 213 );
172 214 }
173 215
216 + /**
217 + * Gets label format for current job.
218 + *
219 + * @return string
220 + */
221 + private function getLabelFormat(): string {
222 + $packetaLabelFormat = $this->optionsProvider->get_packeta_label_format();
223 + $carrierLabelFormat = $this->optionsProvider->get_carrier_label_format();
224 +
225 + return ( $this->httpRequest->getQuery( self::LABEL_TYPE_PARAM ) === self::ACTION_CARRIER_LABELS ? $carrierLabelFormat : $packetaLabelFormat );
226 + }
227 +
228 + /**
229 + * Outputs pdf.
230 + */
174 231 public function outputLabelsPdf(): void {
175 232 if ( $this->httpRequest->getQuery( 'page' ) !== self::MENU_SLUG ) {
176 233 return;
177 234 }
@@ -177,13 +234,13 @@
177 234 }
178 235
179 236 $fallbackToPacketaLabel = false;
180 237 $isCarrierLabels = ( $this->httpRequest->getQuery( self::LABEL_TYPE_PARAM ) === self::ACTION_CARRIER_LABELS );
181 - $orderIdParam = $this->httpRequest->getQuery( 'id' ) !== null ? (int) $this->httpRequest->getQuery( 'id' ) : null;
238 + $idParam = $this->httpRequest->getQuery( 'id' ) !== null ? (int) $this->httpRequest->getQuery( 'id' ) : null;
182 239 $packetIdParam = $this->httpRequest->getQuery( 'packet_id' );
183 - if ( $orderIdParam !== null && $packetIdParam !== null ) {
240 + if ( $idParam !== null && $packetIdParam !== null ) {
184 241 $fallbackToPacketaLabel = true;
185 - $packetIds = [ $orderIdParam => $packetIdParam ];
242 + $packetIds = [ $idParam => $packetIdParam ];
186 243 } else {
187 244 $orderIdsTransient = $this->getOrderIdsTransient();
188 245 if ( $orderIdsTransient === null ) {
189 246 return;
@@ -190,61 +247,47 @@
190 247 }
191 248
192 249 $packetIds = $this->getPacketIdsFromTransient( $orderIdsTransient, $isCarrierLabels );
193 250 }
194 - $packetIds = $this->labelPrintParametersService->removeExternalCarrierPacketIds( $packetIds, $isCarrierLabels, $fallbackToPacketaLabel );
195 -
196 251 if ( count( $packetIds ) === 0 ) {
197 - if ( $isCarrierLabels === true ) {
198 - $this->messageManager->flash_message(
199 - $this->wpAdapter->__( 'No orders have been selected for Packeta carriers', 'packeta' ),
200 - 'info'
201 - );
202 - } else {
203 - $this->messageManager->flash_message(
204 - $this->wpAdapter->__( 'No orders have been selected for Packeta pick-up points', 'packeta' ),
205 - 'info'
206 - );
207 - }
208 -
252 + $this->messageManager->flash_message( __( 'No suitable orders were selected', 'packeta' ), 'info' );
209 253 $this->packetActionsCommonLogic->redirectTo( PacketActionsCommonLogic::REDIRECT_TO_ORDER_GRID );
210 254
211 255 return;
212 256 }
213 257
214 - $offset = $this->labelPrintParametersService->getOffset();
215 - if ( $offset === null ) {
258 + $maxOffset = $this->optionsProvider->getLabelMaxOffset( $this->getLabelFormat() );
259 + $form = $this->createForm( $maxOffset );
260 + $offsetParam = $this->httpRequest->getQuery( 'offset' );
261 + if ( $maxOffset === 0 ) {
262 + $offset = 0;
263 + } elseif ( $offsetParam !== null ) {
264 + $offset = (int) $offsetParam;
265 + } elseif ( $form->isSubmitted() ) {
266 + $data = $form->getValues( 'array' );
267 + $offset = $data['offset'];
268 + } else {
216 269 return;
217 270 }
218 271
219 - $response = $this->getResponse( $isCarrierLabels, $packetIds, $fallbackToPacketaLabel, $orderIdParam, $offset );
220 - if ( $response === null ) {
221 - return;
272 + if ( $isCarrierLabels ) {
273 + $response = $this->requestCarrierLabels( $offset, $packetIds );
274 + if ( $fallbackToPacketaLabel && $response->hasFault() ) {
275 + $response = $this->requestPacketaLabels( $offset, $packetIds );
276 + }
277 + } else {
278 + $response = $this->requestPacketaLabels( $offset, $packetIds );
222 279 }
280 + if ( $response->hasFault() ) {
281 + $message = __( 'Label printing failed, you can find more information in the Packeta log.', 'packeta' );
282 + $this->messageManager->flash_message( $message, MessageManager::TYPE_ERROR );
223 283
224 - if ( $response->hasFault() ) {
225 - if ( $fallbackToPacketaLabel === true && count( $packetIds ) === 1 ) {
226 - $message = sprintf(
227 - // translators: %s represents shipment tracking number
228 - $this->wpAdapter->__( 'Label printing for shipment %s failed, you can find more information in the Packeta log.', 'packeta' ),
229 - array_shift( $packetIds )
230 - );
231 - } elseif ( $isCarrierLabels === true ) {
232 - $message = sprintf(
233 - // translators: %s represents error message
234 - $this->wpAdapter->__( 'Carrier label printing failed, you can find more information in the Packeta log. Error: %s', 'packeta' ),
235 - $response->getFaultString()
236 - );
237 - } else {
238 - $message = sprintf(
239 - // translators: %s represents error message
240 - $this->wpAdapter->__( 'Label printing failed, you can find more information in the Packeta log. Error: %s', 'packeta' ),
241 - $response->getFaultString()
242 - );
284 + $redirectTo = $this->httpRequest->getQuery( PacketActionsCommonLogic::PARAM_REDIRECT_TO );
285 + if ( $redirectTo === PacketActionsCommonLogic::REDIRECT_TO_ORDER_DETAIL && $idParam !== null ) {
286 + $this->packetActionsCommonLogic->redirectTo( $redirectTo, $this->orderRepository->findById( $idParam ) );
243 287 }
288 + $this->packetActionsCommonLogic->redirectTo( PacketActionsCommonLogic::REDIRECT_TO_ORDER_GRID );
244 289
245 - $this->flashMessageAndRedirect( $message, $orderIdParam );
246 -
247 290 return;
248 291 }
249 292
250 293 foreach ( $packetIds as $orderId => $packetId ) {
@@ -261,13 +304,41 @@
261 304 exit;
262 305 }
263 306
264 307 /**
308 + * Creates offset setting form.
309 + *
310 + * @param int $maxOffset Maximal offset.
311 + * @param string|null $name Form name.
312 + *
313 + * @return Form
314 + */
315 + public function createForm( int $maxOffset, ?string $name = null ): Form {
316 + $form = $this->formFactory->create( $name );
317 +
318 + $availableOffsets = [];
319 + for ( $i = 0; $i <= $maxOffset; $i++ ) {
320 + $availableOffsets[ $i ] = ( $i === 0 ?
321 + __( "don't skip any field on a print sheet", 'packeta' ) :
322 + // translators: %s is offset.
323 + sprintf( __( 'skip %s fields on first sheet', 'packeta' ), $i )
324 + );
325 + }
326 + $form->addSelect(
327 + 'offset',
328 + __( 'Skip fields', 'packeta' ),
329 + $availableOffsets
330 + )->checkDefaultValue( false );
331 +
332 + return $form;
333 + }
334 +
335 + /**
265 336 * Registers submenu item.
266 337 */
267 338 public function register(): void {
268 339 add_submenu_page(
269 - DashboardPage::SLUG,
340 + \Packetery\Module\Options\Page::SLUG,
270 341 __( 'Print labels', 'packeta' ),
271 342 __( 'Print labels', 'packeta' ),
272 343 'manage_woocommerce',
273 344 self::MENU_SLUG,
@@ -286,53 +357,36 @@
286 357 Plugin::hideSubmenuItem( self::MENU_SLUG );
287 358 }
288 359
289 360 /**
290 - * @param int $offset
291 - * @param string[] $packetIds
361 + * Prepares labels.
362 + *
363 + * @param int $offset Offset value.
364 + * @param string[] $packetIds Packet ids.
365 + *
366 + * @return Response\PacketsLabelsPdf
292 367 */
293 368 private function requestPacketaLabels( int $offset, array $packetIds ): Response\PacketsLabelsPdf {
294 - $request = new Request\PacketsLabelsPdf( array_values( $packetIds ), $this->labelPrintParametersService->getLabelFormat(), $offset );
369 + $request = new Request\PacketsLabelsPdf( array_values( $packetIds ), $this->getLabelFormat(), $offset );
295 370 $response = $this->soapApiClient->packetsLabelsPdf( $request );
371 + // TODO: is possible to merge following part of requestPacketaLabels and requestCarrierLabels?
296 372
297 373 foreach ( $packetIds as $orderId => $packetId ) {
298 - $isClaimAssistantLabel = false;
299 - $order = $this->orderRepository->getByIdWithValidCarrier( $orderId );
300 -
301 - if ( $order === null ) {
302 - // TODO Only a temporary solution to prevent a situation where the order is null and we are unable to verify whether it is a printout from the claim assistant form.
303 - // TODO Needs to be refactored - ticket PES-2896
304 - $this->logLabelPrintWithoutWcOrder( $orderId, $packetId, $response, $request );
305 -
306 - continue;
307 - }
308 -
309 - if ( $order->isPacketClaim( $packetId ) ) {
310 - $isClaimAssistantLabel = true;
311 - }
312 -
313 374 $record = new Log\Record();
314 - $record->action = $isClaimAssistantLabel ? Log\Record::ACTION_CLAIM_LABEL_PRINT : Log\Record::ACTION_LABEL_PRINT;
375 + $record->action = Log\Record::ACTION_LABEL_PRINT;
315 376 $record->orderId = $orderId;
377 + $order = $this->orderRepository->getByIdWithValidCarrier( $orderId );
316 378
317 379 if ( ! $response->hasFault() ) {
318 - if ( $isClaimAssistantLabel === false ) {
380 + if ( $order !== null ) {
319 381 $order->setIsLabelPrinted( true );
320 382 }
321 383
322 384 $record->status = Log\Record::STATUS_SUCCESS;
323 - if ( $isClaimAssistantLabel === true ) {
324 - $record->title = $this->wpAdapter->__( 'Claim assistant label was printed successfully.', 'packeta' );
325 - } else {
326 - $record->title = $this->wpAdapter->__( 'Label was printed successfully.', 'packeta' );
327 - }
385 + $record->title = __( 'Label has been printed successfully.', 'packeta' );
328 386 } else {
329 387 $record->status = Log\Record::STATUS_ERROR;
330 - if ( $isClaimAssistantLabel === true ) {
331 - $record->title = $this->wpAdapter->__( 'Claim assistant label could not be printed.', 'packeta' );
332 - } else {
333 - $record->title = $this->wpAdapter->__( 'Label could not be printed.', 'packeta' );
334 - }
388 + $record->title = __( 'Label could not be printed.', 'packeta' );
335 389 $record->params = [
336 390 'packetId' => $packetId,
337 391 'isPacketIdInvalid' => $response->hasInvalidPacketId( (string) $packetId ),
338 392 'request' => [
@@ -345,10 +399,12 @@
345 399 }
346 400
347 401 $this->logger->add( $record );
348 402
349 - $order->updateApiErrorMessage( $response->getFaultString() );
350 - $this->orderRepository->save( $order );
403 + if ( $order !== null ) {
404 + $order->updateApiErrorMessage( $response->getFaultString() );
405 + $this->orderRepository->save( $order );
406 + }
351 407 }
352 408
353 409 return $response;
354 410 }
@@ -353,14 +409,19 @@
353 409 return $response;
354 410 }
355 411
356 412 /**
357 - * @param int $offset
358 - * @param array[] $packetIdsWithCourierNumbers
413 + * Prepares carrier labels.
414 + *
415 + * @param int $offset Offset value.
416 + * @param string[] $packetIds Packet ids.
417 + *
418 + * @return Response\PacketsCourierLabelsPdf
359 419 */
360 - private function requestCarrierLabels( int $offset, array $packetIdsWithCourierNumbers ): Response\PacketsCourierLabelsPdf {
361 - $request = new Request\PacketsCourierLabelsPdf( array_values( $packetIdsWithCourierNumbers ), $this->labelPrintParametersService->getLabelFormat(), $offset );
362 - $response = $this->soapApiClient->packetsCarrierLabelsPdf( $request );
420 + private function requestCarrierLabels( int $offset, array $packetIds ): Response\PacketsCourierLabelsPdf {
421 + $packetIdsWithCourierNumbers = $this->getPacketIdsWithCourierNumbers( $packetIds );
422 + $request = new Request\PacketsCourierLabelsPdf( array_values( $packetIdsWithCourierNumbers ), $this->getLabelFormat(), $offset );
423 + $response = $this->soapApiClient->packetsCarrierLabelsPdf( $request );
363 424
364 425 foreach ( $packetIdsWithCourierNumbers as $orderId => $pairItem ) {
365 426 $record = new Log\Record();
366 427 $record->action = Log\Record::ACTION_CARRIER_LABEL_PRINT;
@@ -369,8 +430,9 @@
369 430
370 431 if ( ! $response->hasFault() ) {
371 432 if ( $order !== null ) {
372 433 $order->setIsLabelPrinted( true );
434 + $order->setCarrierNumber( $pairItem['courierNumber'] );
373 435 }
374 436
375 437 $record->status = Log\Record::STATUS_SUCCESS;
376 438 $record->title = __( 'Carrier label has been printed successfully.', 'packeta' );
@@ -406,13 +468,17 @@
406 468 *
407 469 * @return string
408 470 */
409 471 private function getFilename(): string {
410 - return 'packeta_labels_' . strtolower( str_replace( ' ', '_', $this->labelPrintParametersService->getLabelFormat() ) ) . '.pdf';
472 + return 'packeta_labels_' . strtolower( str_replace( ' ', '_', $this->getLabelFormat() ) ) . '.pdf';
411 473 }
412 474
413 475 /**
476 + * Gets saved packet ids.
477 + *
414 478 * @param string[] $orderIds Order IDs from transient.
479 + * @param bool $isCarrierLabels Are carrier labels requested?
480 + *
415 481 * @return string[]
416 482 */
417 483 private function getPacketIdsFromTransient( array $orderIds, bool $isCarrierLabels ): array {
418 484 $orders = $this->orderRepository->getByIds( $orderIds );
@@ -429,8 +495,10 @@
429 495 return $packetIds;
430 496 }
431 497
432 498 /**
499 + * Gets order IDs transient.
500 + *
433 501 * @return string[]|null
434 502 */
435 503 private function getOrderIdsTransient(): ?array {
436 504 $orderIds = get_transient( self::getOrderIdsTransientName() );
@@ -441,11 +509,63 @@
441 509 return null;
442 510 }
443 511
444 512 /**
513 + * Gets carrier packet numbers from API.
514 + *
515 + * @param string[] $packetIds List of packet ids.
516 + *
517 + * @return array<int, array{packetId: string, courierNumber: string}>
518 + */
519 + private function getPacketIdsWithCourierNumbers( array $packetIds ): array {
520 + $pairs = [];
521 + foreach ( $packetIds as $orderId => $packetId ) {
522 + $request = new Request\PacketCourierNumber( $packetId );
523 + $response = $this->soapApiClient->packetCourierNumber( $request );
524 + if ( $response->hasFault() ) {
525 + if ( $response->hasWrongPassword() ) {
526 + $this->messageManager->flash_message( __( 'Please set a proper API password.', 'packeta' ), MessageManager::TYPE_ERROR );
527 +
528 + return [];
529 + }
530 +
531 + $record = new Log\Record();
532 + $record->action = Log\Record::ACTION_CARRIER_NUMBER_RETRIEVING;
533 + $record->status = Log\Record::STATUS_ERROR;
534 + $record->title = __( 'Carrier number could not be retrieved.', 'packeta' );
535 + $record->params = [
536 + 'packetId' => $request->getPacketId(),
537 + 'errorMessage' => $response->getFaultString(),
538 + ];
539 + $record->orderId = $orderId;
540 + $this->logger->add( $record );
541 + $order = $this->orderRepository->getByIdWithValidCarrier( $orderId );
542 + if ( $order !== null ) {
543 + $order->updateApiErrorMessage( $response->getFaultString() );
544 + $this->orderRepository->save( $order );
545 + }
546 +
547 + continue;
548 + }
549 + $pairs[ $orderId ] = [
550 + 'packetId' => $packetId,
551 + 'courierNumber' => $response->getNumber(),
552 + ];
553 + }
554 +
555 + return $pairs;
556 + }
557 +
558 + /**
445 559 * Saves information about the creation of the label in the order note.
560 + *
561 + * @param int $orderId Order id.
562 + * @param string $packetId Packet.
563 + * @param ILabelResponse $response Response.
564 + *
565 + * @return void
446 566 */
447 - private function addLabelCreationInfoToWcOrderNote( int $orderId, string $packetId, ?ILabelResponse $response ): void {
567 + private function addLabelCreationInfoToWcOrderNote( int $orderId, string $packetId, ILabelResponse $response ): void {
448 568 $order = $this->orderRepository->findById( $orderId );
449 569 $wcOrder = $this->orderRepository->getWcOrderById( $orderId );
450 570 if ( $wcOrder === null || $order === null ) {
451 571 return;
@@ -463,9 +583,9 @@
463 583 // translators: %s represents a packet tracking link.
464 584 $message = __( 'Packeta: Label for packet %s has been created', 'packeta' );
465 585 }
466 586 } else {
467 - // Response is of type Response\PacketsCourierLabelsPdf or null.
587 + // Response is of type Response\PacketsCourierLabelsPdf.
468 588 // translators: %s represents a packet tracking link.
469 589 $message = __( 'Packeta: Carrier label for packet %s has been created', 'packeta' );
470 590 }
471 591
@@ -475,82 +595,6 @@
475 595 $this->moduleHelper->createHtmlLink( $trackingUrl, $linkText )
476 596 )
477 597 );
478 598 $wcOrder->save();
479 - }
480 -
481 - /**
482 - * Logs label print operation when there is no WooCommerce order.
483 - */
484 - private function logLabelPrintWithoutWcOrder( int $orderId, string $packetId, Response\PacketsLabelsPdf $response, Request\PacketsLabelsPdf $request ): void {
485 - $record = new Log\Record();
486 - $record->action = Log\Record::ACTION_LABEL_PRINT;
487 - $record->orderId = $orderId;
488 -
489 - if ( ! $response->hasFault() ) {
490 - $record->status = Log\Record::STATUS_SUCCESS;
491 - $record->title = $this->wpAdapter->__( 'Label was printed successfully.', 'packeta' );
492 - } else {
493 - $record->status = Log\Record::STATUS_ERROR;
494 - $record->title = $this->wpAdapter->__( 'Label could not be printed.', 'packeta' );
495 - }
496 - $record->params = [
497 - 'packetId' => $packetId,
498 - 'isPacketIdInvalid' => $response->hasInvalidPacketId( $packetId ),
499 - 'request' => [
500 - 'packetIds' => $request->getPacketIds(),
501 - 'format' => $request->getFormat(),
502 - 'offset' => $request->getOffset(),
503 - ],
504 - 'errorMessage' => $response->getFaultString(),
505 - ];
506 - $this->logger->add( $record );
507 - }
508 -
509 - public function flashMessageAndRedirect( string $message, ?int $orderId ): void {
510 - $this->messageManager->flash_message( $message, MessageManager::TYPE_ERROR );
511 -
512 - $redirectTo = $this->httpRequest->getQuery( PacketActionsCommonLogic::PARAM_REDIRECT_TO );
513 - if ( $redirectTo === PacketActionsCommonLogic::REDIRECT_TO_ORDER_DETAIL && $orderId !== null ) {
514 - $this->packetActionsCommonLogic->redirectTo( $redirectTo, $this->orderRepository->findById( $orderId ) );
515 - }
516 - $this->packetActionsCommonLogic->redirectTo( PacketActionsCommonLogic::REDIRECT_TO_ORDER_GRID );
517 - }
518 -
519 - /**
520 - * @param bool $isCarrierLabels
521 - * @param array<string, string> $packetIds
522 - * @param bool $fallbackToPacketaLabel
523 - * @param int|null $orderId
524 - * @param int $offset
525 - *
526 - * @return Response\PacketsCourierLabelsPdf|Response\PacketsLabelsPdf|null
527 - */
528 - private function getResponse(
529 - bool $isCarrierLabels,
530 - array $packetIds,
531 - bool $fallbackToPacketaLabel,
532 - ?int $orderId,
533 - int $offset
534 - ) {
535 - if ( $isCarrierLabels === false ) {
536 - return $this->requestPacketaLabels( $offset, $packetIds );
537 - }
538 -
539 - $packetIdsWithCourierNumbers = $this->carrierLabelService->getPacketIdsWithCourierNumbers( $packetIds );
540 - if ( $fallbackToPacketaLabel === false && $packetIdsWithCourierNumbers === [] ) {
541 - $this->flashMessageAndRedirect(
542 - (string) $this->wpAdapter->__( 'Carrier label printing failed, you can find more information in the Packeta log.', 'packeta' ),
543 - $orderId
544 - );
545 -
546 - return null;
547 - }
548 -
549 - $response = $this->requestCarrierLabels( $offset, $packetIdsWithCourierNumbers );
550 - if ( $fallbackToPacketaLabel === true && $response->hasFault() ) {
551 - return $this->requestPacketaLabels( $offset, $packetIds );
552 - }
553 -
554 - return $response;
555 599 }
556 600 }