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
packeta / src / Packetery / Module / Order / Metabox.php

Metabox.php in Packeta 2.0.9, at src/Packetery/Module/Order/Metabox.php

655 lines 23.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare( strict_types=1 );
4
5 namespace Packetery\Module\Order;
6
7 use Packetery\Core\CoreHelper;
8 use Packetery\Core\Entity;
9 use Packetery\Core\Validator;
10 use Packetery\Latte\Engine;
11 use Packetery\Module\Carrier\EntityRepository;
12 use Packetery\Module\Exception\InvalidCarrierException;
13 use Packetery\Module\Framework\WpAdapter;
14 use Packetery\Module\Log;
15 use Packetery\Module\Log\Page;
16 use Packetery\Module\MessageManager;
17 use Packetery\Module\ModuleHelper;
18 use Packetery\Module\Options\OptionsProvider;
19 use Packetery\Module\Plugin;
20 use Packetery\Module\WidgetOptionsBuilder;
21 use Packetery\Nette\Forms;
22 use Packetery\Nette\Http\Request;
23 use WC_Data_Exception;
24 use WC_Order;
25
26 class Metabox {
27 private const PART_ERROR = 'error';
28 private const PART_CARRIER_CHANGE = 'carrierChange';
29 private const PART_MAIN = 'main';
30
31 /**
32 * @var Engine
33 */
34 private $latteEngine;
35
36 /**
37 * @var MessageManager
38 */
39 private $messageManager;
40
41 /**
42 * @var CoreHelper
43 */
44 private $coreHelper;
45
46 /**
47 * @var Request
48 */
49 private $request;
50
51 /**
52 * @var Forms\Form
53 */
54 private $form;
55
56 /**
57 * @var Form
58 */
59 private $orderForm;
60
61 /**
62 * @var OptionsProvider
63 */
64 private $optionsProvider;
65
66 /**
67 * @var Repository
68 */
69 private $orderRepository;
70
71 /**
72 * @var Log\Page
73 */
74 private $logPage;
75
76 /**
77 * @var AttributeMapper
78 */
79 private $mapper;
80
81 /**
82 * @var WidgetOptionsBuilder
83 */
84 private $widgetOptionsBuilder;
85
86 /**
87 * @var EntityRepository
88 */
89 private $carrierRepository;
90
91 /**
92 * @var Validator\Order
93 */
94 private $orderValidator;
95
96 /**
97 * @var DetailCommonLogic
98 */
99 private $detailCommonLogic;
100
101 /**
102 * @var CarrierModal
103 */
104 private $carrierModal;
105
106 /**
107 * @var WpAdapter
108 */
109 private $wpAdapter;
110
111 public function __construct(
112 Engine $latteEngine,
113 MessageManager $messageManager,
114 CoreHelper $coreHelper,
115 Request $request,
116 OptionsProvider $optionsProvider,
117 Repository $orderRepository,
118 Page $logPage,
119 AttributeMapper $mapper,
120 WidgetOptionsBuilder $widgetOptionsBuilder,
121 EntityRepository $carrierRepository,
122 OrderValidatorFactory $orderValidatorFactory,
123 DetailCommonLogic $detailCommonLogic,
124 Form $orderForm,
125 CarrierModal $carrierModal,
126 WpAdapter $wpAdapter
127 ) {
128 $this->latteEngine = $latteEngine;
129 $this->messageManager = $messageManager;
130 $this->coreHelper = $coreHelper;
131 $this->request = $request;
132 $this->optionsProvider = $optionsProvider;
133 $this->orderRepository = $orderRepository;
134 $this->logPage = $logPage;
135 $this->mapper = $mapper;
136 $this->widgetOptionsBuilder = $widgetOptionsBuilder;
137 $this->carrierRepository = $carrierRepository;
138 $this->orderValidator = $orderValidatorFactory->create();
139 $this->detailCommonLogic = $detailCommonLogic;
140 $this->orderForm = $orderForm;
141 $this->carrierModal = $carrierModal;
142 $this->wpAdapter = $wpAdapter;
143 }
144
145 public function register(): void {
146 add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
147 }
148
149 public function add_meta_boxes(): void {
150 if ( ! $this->detailCommonLogic->isPacketeryOrder() ) {
151 return;
152 }
153
154 $this->initializeForm();
155 $parts = $this->prepareMetaboxParts();
156
157 if ( count( $parts ) > 0 ) {
158 add_meta_box(
159 'packetery_metabox',
160 $this->wpAdapter->__( 'Packeta', 'packeta' ),
161 array(
162 $this,
163 'render_metabox',
164 ),
165 ModuleHelper::isHposEnabled() ? wc_get_page_screen_id( 'shop-order' ) : 'shop_order',
166 'side',
167 'high'
168 );
169 }
170 }
171
172 public function render_metabox(): void {
173 $parts = $this->prepareMetaboxParts();
174
175 if ( isset( $parts[ self::PART_ERROR ] ) ) {
176 ModuleHelper::renderString( $parts[ self::PART_ERROR ] );
177
178 return;
179 }
180
181 if ( isset( $parts[ self::PART_CARRIER_CHANGE ] ) ) {
182 ModuleHelper::renderString( $parts[ self::PART_CARRIER_CHANGE ] );
183 }
184 if ( isset( $parts[ self::PART_CARRIER_CHANGE ], $parts[ self::PART_MAIN ] ) ) {
185 ModuleHelper::renderString( '<hr>' );
186 }
187 if ( isset( $parts[ self::PART_MAIN ] ) ) {
188 ModuleHelper::renderString( $parts[ self::PART_MAIN ] );
189 }
190 }
191
192 /**
193 * @return array<string, string>
194 */
195 private function prepareMetaboxParts(): array {
196 static $partsCache;
197
198 if ( isset( $partsCache ) ) {
199 return $partsCache;
200 }
201
202 $orderId = $this->detailCommonLogic->getOrderId();
203 if ( $orderId === null ) {
204 $partsCache = [];
205
206 return $partsCache;
207 }
208
209 try {
210 $order = $this->orderRepository->getById( $orderId );
211 } catch ( InvalidCarrierException $exception ) {
212 $partsCache = [
213 self::PART_ERROR => $this->latteEngine->renderToString(
214 PACKETERY_PLUGIN_DIR . '/template/order/metabox-form-error.latte',
215 [
216 'errorMessage' => $exception->getMessage(),
217 ]
218 ),
219 ];
220
221 return $partsCache;
222 }
223
224 $parts = [];
225 if ( $this->carrierModal->canBeDisplayed() ) {
226 $parts[ self::PART_CARRIER_CHANGE ] = $this->carrierModal->getMetaboxHtml();
227 }
228
229 if ( $order === null ) {
230 $partsCache = $parts;
231
232 return $partsCache;
233 }
234
235 $showLogsLink = null;
236 if ( $this->logPage->hasAnyRows( (int) $order->getNumber() ) ) {
237 $showLogsLink = $this->logPage->createLogListUrl( (int) $order->getNumber() );
238 }
239
240 $packetClaimUrl = null;
241 if ( $order->isPacketClaimCreationPossible() ) {
242 $packetClaimUrl = $this->getOrderActionLink( $order, PacketActionsCommonLogic::ACTION_SUBMIT_PACKET_CLAIM );
243 }
244
245 $packetClaimCancelUrl = null;
246 $packetClaimTrackingUrl = null;
247 if ( $order->getPacketClaimId() !== null ) {
248 $packetClaimCancelUrl = $this->getOrderActionLink(
249 $order,
250 PacketActionsCommonLogic::ACTION_CANCEL_PACKET,
251 [
252 PacketActionsCommonLogic::PARAM_PACKET_ID => $order->getPacketClaimId(),
253 ]
254 );
255 $packetClaimTrackingUrl = $this->coreHelper->getTrackingUrl( $order->getPacketClaimId() );
256 }
257
258 $packetId = $order->getPacketId();
259 if ( $packetId !== null ) {
260 $packetCancelLink = $this->getOrderActionLink(
261 $order,
262 PacketActionsCommonLogic::ACTION_CANCEL_PACKET,
263 [
264 PacketActionsCommonLogic::PARAM_PACKET_ID => $packetId,
265 ]
266 );
267
268 $packetStatusTranslatedName = PacketStatusResolver::getTranslatedName( $order->getPacketStatus() );
269 /** @var array<string, string> $statusClasses */
270 $statusClasses = [
271 'received data' => 'received-data',
272 'unknown' => 'unknown',
273 'delivered' => 'delivered',
274 'cancelled' => 'cancelled',
275 'returned' => 'returned',
276 'rejected by recipient' => 'rejected',
277 ];
278
279 $statusClass = 'delivery-status';
280 $statusType = $order->getPacketStatus();
281
282 if ( isset( $statusClasses[ $statusType ] ) ) {
283 $statusClass = $statusClasses[ $statusType ];
284 }
285
286 $parts[ self::PART_MAIN ] = $this->latteEngine->renderToString(
287 PACKETERY_PLUGIN_DIR . '/template/order/metabox-common.latte',
288 [
289 'order' => $order,
290 'packetStatusTranslatedName' => $packetStatusTranslatedName,
291 'statusClass' => $statusClass,
292 'isPacketSubmissionPossible' => false,
293 'orderWarningFields' => [],
294 'packetCancelLink' => $packetCancelLink,
295 'packetTrackingUrl' => $this->coreHelper->getTrackingUrl( $packetId ),
296 'packetClaimTrackingUrl' => $packetClaimTrackingUrl,
297 'showLogsLink' => $showLogsLink,
298 'packetClaimUrl' => $packetClaimUrl,
299 'packetClaimCancelUrl' => $packetClaimCancelUrl,
300 'storedUntil' => $this->coreHelper->getStringFromDateTime( $order->getStoredUntil(), CoreHelper::DATEPICKER_FORMAT ),
301 'translations' => [
302 'packetTrackingOnline' => $this->wpAdapter->__( 'Packet tracking online', 'packeta' ),
303 'packetClaimTrackingOnline' => $this->wpAdapter->__( 'Packet claim tracking', 'packeta' ),
304 'showLogs' => $this->wpAdapter->__( 'Show logs', 'packeta' ),
305 // translators: %s: Order number.
306 'reallyCancelPacketHeading' => sprintf( $this->wpAdapter->__( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
307 // translators: %s: Packet number.
308 'reallyCancelPacket' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel parcel number %s?', 'packeta' ), $packetId ),
309 // translators: %s: Packet claim number.
310 'reallyCancelPacketClaim' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel packet claim number %s?', 'packeta' ), $order->getPacketClaimId() ),
311
312 'cancelPacket' => $this->wpAdapter->__( 'Cancel packet', 'packeta' ),
313 'createPacketClaim' => $this->wpAdapter->__( 'Create packet claim', 'packeta' ),
314 'printPacketLabel' => $this->wpAdapter->__( 'Print packet label', 'packeta' ),
315 'printPacketClaimLabel' => $this->wpAdapter->__( 'Print packet claim label', 'packeta' ),
316 'cancelPacketClaim' => $this->wpAdapter->__( 'Cancel packet claim', 'packeta' ),
317 'packetClaimPassword' => $this->wpAdapter->__( 'Packet claim password', 'packeta' ),
318 'submissionPassword' => $this->wpAdapter->__( 'submission password', 'packeta' ),
319 'setStoredUntil' => $this->wpAdapter->__( 'Set the pickup date extension', 'packeta' ),
320 ],
321 ]
322 );
323
324 $partsCache = $parts;
325
326 return $partsCache;
327 }
328
329 $unit = $this->optionsProvider->getDimensionsUnit();
330 $this->orderForm->setDefaults(
331 $this->form,
332 $order->getFinalWeight(),
333 $order->getCalculatedWeight(),
334 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getLength() ) : $order->getLength(),
335 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getWidth() ) : $order->getWidth(),
336 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getHeight() ) : $order->getHeight(),
337 $order->getFinalCod(),
338 $order->getCalculatedCod(),
339 $order->getFinalValue(),
340 $order->getCalculatedValue(),
341 $order->containsAdultContent(),
342 $this->coreHelper->getStringFromDateTime( $order->getDeliverOn(), CoreHelper::DATEPICKER_FORMAT )
343 );
344
345 $prevInvalidValues = get_transient( 'packetery_metabox_nette_form_prev_invalid_values' );
346 if ( $prevInvalidValues !== null && $prevInvalidValues !== false ) {
347 $this->form->setValues( $prevInvalidValues );
348 $this->form->validate();
349 }
350 delete_transient( 'packetery_metabox_nette_form_prev_invalid_values' );
351
352 $isPacketSubmissionPossible = $this->orderValidator->isValid( $order );
353 $packetSubmitUrl = $this->getOrderActionLink( $order, PacketActionsCommonLogic::ACTION_SUBMIT_PACKET );
354
355 $showWidgetButton = $order->isPickupPointDelivery();
356 $widgetButtonError = null;
357 $shippingCountry = $order->getShippingCountry();
358 $showHdWidget = $order->isHomeDelivery() && in_array( $shippingCountry, Entity\Carrier::ADDRESS_VALIDATION_COUNTRIES, true );
359 if (
360 $shippingCountry === null ||
361 ! $this->carrierRepository->isValidForCountry( $order->getCarrier()->getId(), $shippingCountry )
362 ) {
363 if ( $order->isPickupPointDelivery() ) {
364 $showWidgetButton = false;
365 if ( $shippingCountry === null ) {
366 $widgetButtonError = $this->wpAdapter->__(
367 'The pickup point cannot be changed because the shipping address has no country set. First, change the country of delivery in the shipping address.',
368 'packeta'
369 );
370 } else {
371 $widgetButtonError = sprintf(
372 // translators: %s is country code.
373 $this->wpAdapter->__(
374 'The pickup point cannot be changed because the selected carrier does not deliver to country "%s". First, change the country of delivery in the shipping address.',
375 'packeta'
376 ),
377 $shippingCountry
378 );
379 }
380 } elseif ( in_array( $order->getCarrier()->getCountry(), Entity\Carrier::ADDRESS_VALIDATION_COUNTRIES, true ) ) {
381 $showHdWidget = false;
382 if ( $shippingCountry === null ) {
383 $widgetButtonError = $this->wpAdapter->__(
384 'The address cannot be validated because the shipping address has no country set. First, change the country of delivery in the shipping address.',
385 'packeta'
386 );
387 } else {
388 $widgetButtonError = sprintf(
389 // translators: %s is country code.
390 $this->wpAdapter->__(
391 'The address cannot be validated because the selected carrier does not deliver to country "%s". First, change the country of delivery in the shipping address.',
392 'packeta'
393 ),
394 $shippingCountry
395 );
396 }
397 }
398 }
399
400 $parts[ self::PART_MAIN ] = $this->latteEngine->renderToString(
401 PACKETERY_PLUGIN_DIR . '/template/order/metabox-form.latte',
402 [
403 'form' => $this->form,
404 'order' => $order,
405 'showWidgetButton' => $showWidgetButton,
406 'widgetButtonError' => $widgetButtonError,
407 'showHdWidget' => $showHdWidget,
408 'isPacketSubmissionPossible' => $isPacketSubmissionPossible,
409 'orderWarningFields' => Form::getInvalidFieldsFromValidationResult( $this->orderValidator->validate( $order ) ),
410 'packetCancelLink' => null,
411 'packetTrackingUrl' => null,
412 'packetStatusTranslatedName' => null,
413 'packetSubmitUrl' => $packetSubmitUrl,
414 'packetClaimTrackingUrl' => $packetClaimTrackingUrl,
415 'packetClaimUrl' => $packetClaimUrl,
416 'packetClaimCancelUrl' => $packetClaimCancelUrl,
417 'orderCurrency' => get_woocommerce_currency_symbol( $order->getCurrency() ),
418 'isCodPayment' => $order->hasCod(),
419 'allowsAdultContent' => $order->allowsAdultContent(),
420 'requiresSizeDimensions' => $order->getCarrier()->requiresSize(),
421 'logo' => plugin_dir_url( PACKETERY_PLUGIN_DIR . '/packeta.php' ) . 'public/images/packeta-symbol.png',
422 'showLogsLink' => $showLogsLink,
423 'hasOrderManualWeight' => $order->hasManualWeight(),
424 'hasOrderManualCod' => $order->hasManualCod(),
425 'hasOrderManualValue' => $order->hasManualValue(),
426 'isPacketaPickupPoint' => $order->isPacketaInternalPickupPoint(),
427 'pickupPointAttributes' => Attribute::$pickupPointAttributes,
428 'homeDeliveryAttributes' => Attribute::$homeDeliveryAttributes,
429 'translations' => [
430 'packetSubmissionValidationErrorTooltip' => $this->wpAdapter->__( 'It is not possible to submit the shipment because all the information required for this shipment is not filled.', 'packeta' ),
431 'showLogs' => $this->wpAdapter->__( 'Show logs', 'packeta' ),
432 'weightIsManual' => $this->wpAdapter->__( 'Weight is manually set. To calculate weight remove field content and save.', 'packeta' ),
433 'codIsManual' => $this->wpAdapter->__( 'COD value is manually set. To calculate the value remove field content and save.', 'packeta' ),
434 'valueIsManual' => $this->wpAdapter->__( 'Order value is manually set. To calculate the value remove field content and save.', 'packeta' ),
435 'submitPacket' => $this->wpAdapter->__( 'Submit to Packeta', 'packeta' ),
436 'packetClaimTrackingOnline' => $this->wpAdapter->__( 'Packet claim tracking', 'packeta' ),
437 'printPacketClaimLabel' => $this->wpAdapter->__( 'Print packet claim label', 'packeta' ),
438 'cancelPacketClaim' => $this->wpAdapter->__( 'Cancel packet claim', 'packeta' ),
439 'packetClaimPassword' => $this->wpAdapter->__( 'Packet claim password', 'packeta' ),
440 'submissionPassword' => $this->wpAdapter->__( 'submission password', 'packeta' ),
441 // translators: %s: Order number.
442 'reallyCancelPacketHeading' => sprintf( $this->wpAdapter->__( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
443 // translators: %s: Packet claim number.
444 'reallyCancelPacketClaim' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel packet claim number %s?', 'packeta' ), $order->getPacketClaimId() ),
445 ],
446 ]
447 );
448
449 $partsCache = $parts;
450
451 return $partsCache;
452 }
453
454 /**
455 * Saves added packetery form fields to order metas.
456 *
457 * @param Entity\Order $order Order.
458 * @param WC_Order $wcOrder WC Order.
459 *
460 * @return void
461 * @throws WC_Data_Exception When invalid data are passed during shipping address update.
462 */
463 public function saveFields( Entity\Order $order, WC_Order $wcOrder ): void {
464 $this->initializeForm();
465
466 $orderId = (int) $order->getNumber();
467 if (
468 ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ||
469 $this->request->getPost( 'packetery_order_metabox_nonce' ) === null
470 ) {
471 return;
472 }
473
474 if ( $this->form->isValid() === false ) {
475 set_transient( 'packetery_metabox_nette_form_prev_invalid_values', $this->form->getValues( 'array' ) );
476 $this->messageManager->flash_message( $this->wpAdapter->__( 'Packeta: entered data is not valid!', 'packeta' ), MessageManager::TYPE_ERROR );
477
478 return;
479 }
480 /** @var array<string, string|float|int|true|null> $formValues */
481 $formValues = $this->form->getValues( 'array' );
482
483 if ( wp_verify_nonce( $formValues['packetery_order_metabox_nonce'] ) !== 1 ) {
484 $this->messageManager->flash_message( $this->wpAdapter->__( 'Session has expired! Please try again.', 'packeta' ), MessageManager::TYPE_ERROR );
485
486 return;
487 }
488
489 if ( ! current_user_can( 'edit_post', $orderId ) ) {
490 $this->messageManager->flash_message( $this->wpAdapter->__( 'You do not have sufficient rights to make changes!', 'packeta' ), MessageManager::TYPE_ERROR );
491
492 return;
493 }
494
495 $propsToSave = [];
496 foreach ( [ Form::FIELD_LENGTH, Form::FIELD_WIDTH, Form::FIELD_HEIGHT ] as $dimension ) {
497 $propsToSave[ $dimension ] = $this->optionsProvider->getSanitizedDimensionValueInMm( $formValues[ $dimension ] );
498 }
499
500 $formWeightEqualsToCalculated = (float) $formValues[ Form::FIELD_WEIGHT ] === (float) $formValues[ Form::FIELD_ORIGINAL_WEIGHT ];
501 if ( ! is_numeric( $formValues[ Form::FIELD_WEIGHT ] ) || $formWeightEqualsToCalculated ) {
502 $propsToSave[ Form::FIELD_WEIGHT ] = null;
503 } else {
504 $propsToSave[ Form::FIELD_WEIGHT ] = (float) $formValues[ Form::FIELD_WEIGHT ];
505 }
506
507 if ( $formValues[ Attribute::POINT_ID ] && $order->isPickupPointDelivery() ) {
508 foreach ( Attribute::$pickupPointAttributes as $pickupPointAttr ) {
509 $pickupPointValue = $formValues[ $pickupPointAttr['name'] ];
510
511 if ( $pickupPointAttr['name'] === Attribute::CARRIER_ID ) {
512 if ( isset( $formValues[ Attribute::CARRIER_ID ] ) && $formValues[ Attribute::CARRIER_ID ] !== '' ) {
513 $pickupPointValue = $formValues[ Attribute::CARRIER_ID ];
514 } else {
515 $pickupPointValue = $order->getCarrier()->getId();
516 }
517 }
518
519 $propsToSave[ $pickupPointAttr['name'] ] = $pickupPointValue;
520
521 if ( $this->optionsProvider->replaceShippingAddressWithPickupPointAddress() ) {
522 $this->mapper->toWcOrderShippingAddress( $wcOrder, $pickupPointAttr['name'], (string) $pickupPointValue );
523 }
524 }
525 }
526
527 if ( $formValues[ Attribute::ADDRESS_IS_VALIDATED ] === '1' && $order->isHomeDelivery() ) {
528 $address = $this->mapper->toValidatedAddress( $formValues );
529 $order->setDeliveryAddress( $address );
530 $order->setAddressValidated( true );
531 }
532
533 $order->setAdultContent( $formValues[ Form::FIELD_ADULT_CONTENT ] );
534
535 $formCodEqualsToCalculated = (float) $formValues[ Form::FIELD_COD ] === (float) $formValues[ Form::FIELD_CALCULATED_COD ];
536 if ( ! is_numeric( $formValues[ Form::FIELD_COD ] ) || $formCodEqualsToCalculated ) {
537 $order->setManualCod( null );
538 } else {
539 $order->setManualCod( is_numeric( $formValues[ Form::FIELD_COD ] ) ? CoreHelper::simplifyFloat( $formValues[ Form::FIELD_COD ], 10 ) : null );
540 }
541
542 $formValueEqualsToCalculated = (float) $formValues[ Form::FIELD_VALUE ] === (float) $formValues[ Form::FIELD_CALCULATED_VALUE ];
543 if ( ! is_numeric( $formValues[ Form::FIELD_VALUE ] ) || $formValueEqualsToCalculated ) {
544 $order->setManualValue( null );
545 } else {
546 $order->setManualValue( is_numeric( $formValues[ Form::FIELD_VALUE ] ) ? CoreHelper::simplifyFloat( $formValues[ Form::FIELD_VALUE ], 10 ) : null );
547 }
548
549 $order->setDeliverOn( $this->coreHelper->getDateTimeFromString( $formValues[ Form::FIELD_DELIVER_ON ] ) );
550
551 $orderSize = $this->mapper->toOrderSize( $order, $propsToSave );
552 $order->setSize( $orderSize );
553
554 $pickupPoint = $this->mapper->toOrderEntityPickupPoint( $order, $propsToSave );
555 $order->setPickupPoint( $pickupPoint );
556
557 $this->orderRepository->save( $order );
558 }
559
560 /**
561 * Creates pickup point picker settings.
562 *
563 * @return array<string, array|string|null>
564 */
565 public function getPickupPointWidgetSettings(): ?array {
566 $order = $this->detailCommonLogic->getOrder();
567 if ( $order === null || $order->isPickupPointDelivery() === false || $order->getShippingCountry() === null ) {
568 return null;
569 }
570
571 $widgetOptions = $this->widgetOptionsBuilder->createPickupPointForAdmin( $order );
572
573 return [
574 'packeteryApiKey' => $this->optionsProvider->get_api_key(),
575 'pickupPointAttrs' => Attribute::$pickupPointAttributes,
576 'widgetOptions' => $widgetOptions,
577 ];
578 }
579
580 /**
581 * Creates address picker settings.
582 *
583 * @return mixed[]|null
584 */
585 public function getAddressWidgetSettings(): ?array {
586 $order = $this->detailCommonLogic->getOrder();
587 if ( $order === null || $order->isHomeDelivery() === false ) {
588 return null;
589 }
590
591 $widgetOptions = $this->widgetOptionsBuilder->createAddressForAdmin( $order );
592
593 return [
594 'packeteryApiKey' => $this->optionsProvider->get_api_key(),
595 'homeDeliveryAttrs' => Attribute::$homeDeliveryAttributes,
596 'widgetOptions' => $widgetOptions,
597 'translations' => [
598 'addressValidationIsOutOfOrder' => $this->wpAdapter->__( 'Address validation is out of order.', 'packeta' ),
599 'invalidAddressCountrySelected' => $this->wpAdapter->__( 'The selected country does not correspond to the destination country.', 'packeta' ),
600 ],
601 ];
602 }
603
604 /**
605 * Gets order action link.
606 *
607 * @param Entity\Order $order Order.
608 * @param string $action Action.
609 * @param array $extraParams Extra params.
610 *
611 * @return string
612 */
613 private function getOrderActionLink( Entity\Order $order, string $action, array $extraParams = [] ): string {
614 $baseParams = [
615 PacketActionsCommonLogic::PARAM_ORDER_ID => $order->getNumber(),
616 PacketActionsCommonLogic::PARAM_REDIRECT_TO => PacketActionsCommonLogic::REDIRECT_TO_ORDER_DETAIL,
617 Plugin::PARAM_PACKETERY_ACTION => $action,
618 Plugin::PARAM_NONCE => wp_create_nonce( PacketActionsCommonLogic::createNonceAction( $action, $order->getNumber() ) ),
619 ];
620
621 return add_query_arg(
622 array_merge( $baseParams, $extraParams ),
623 admin_url( 'admin.php' )
624 );
625 }
626
627 /**
628 * Initializes form to render or process.
629 *
630 * @return void
631 */
632 private function initializeForm(): void {
633 $this->form = $this->orderForm->create();
634 $this->form->addHidden( 'packetery_order_metabox_nonce' );
635 $this->form->setDefaults( [ 'packetery_order_metabox_nonce' => wp_create_nonce() ] );
636
637 foreach ( Attribute::$pickupPointAttributes as $pickupPointAttr ) {
638 $this->form->addHidden( $pickupPointAttr['name'] );
639 }
640
641 foreach ( Attribute::$homeDeliveryAttributes as $homeDeliveryAttr ) {
642 $this->form->addHidden( $homeDeliveryAttr['name'] );
643 }
644
645 $this->form->addButton(
646 'packetery_pick_pickup_point',
647 $this->wpAdapter->__( 'Choose pickup point', 'packeta' )
648 );
649 $this->form->addButton(
650 'packetery_pick_address',
651 $this->wpAdapter->__( 'Check shipping address', 'packeta' )
652 );
653 }
654 }
655