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

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

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