PluginProbe
Packeta / 2.3.2
Packeta v2.3.2
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.3.2, at src/Packetery/Module/Order/Metabox.php

692 lines 25.3 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 $invalidFields = $this->orderForm->getInvalidFieldsFromValidationResult( $this->orderValidator->validate( $order ) );
299 $invalidFieldsMessage = $this->orderForm->getInvalidFieldsMessageFromValidationResult( $invalidFields, $order );
300
301 $parts[ self::PART_MAIN ] = $this->latteEngine->renderToString(
302 PACKETERY_PLUGIN_DIR . '/template/order/metabox-common.latte',
303 [
304 'order' => $order,
305 'showConsignPasswordForZBox' => $this->optionsProvider->isShowConsignPasswordForZBoxEnabled(),
306 'packetStatusTranslatedName' => $packetStatusTranslatedName,
307 'statusClass' => $statusClass,
308 'isPacketSubmissionPossible' => false,
309 'orderWarningFields' => [],
310 'invalidFieldsMessage' => $invalidFieldsMessage,
311 'packetCancelLink' => $packetCancelLink,
312 'packetTrackingUrl' => $this->coreHelper->getTrackingUrl( $packetId ),
313 'packetClaimTrackingUrl' => $packetClaimTrackingUrl,
314 'showLogsLink' => $showLogsLink,
315 'packetClaimUrl' => $packetClaimUrl,
316 'packetClaimCancelUrl' => $packetClaimCancelUrl,
317 'runWizardUrl' => $runWizardUrl,
318 'showRunWizardButton' => $showRunWizardButton,
319 'storedUntil' => $this->coreHelper->getStringFromDateTime( $order->getStoredUntil(), CoreHelper::DATEPICKER_FORMAT ),
320 'translations' => [
321 'packetTrackingOnline' => $this->wpAdapter->__( 'Packet tracking online', 'packeta' ),
322 'packetClaimTrackingOnline' => $this->wpAdapter->__( 'Packet claim tracking', 'packeta' ),
323 'showLogs' => $this->wpAdapter->__( 'Show logs', 'packeta' ),
324 // translators: %s: Order number.
325 'reallyCancelPacketHeading' => sprintf( $this->wpAdapter->__( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
326 // translators: %s: Packet number.
327 'reallyCancelPacket' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel parcel number %s?', 'packeta' ), $packetId ),
328 // translators: %s: Packet claim number.
329 'reallyCancelPacketClaim' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel packet claim number %s?', 'packeta' ), $order->getPacketClaimId() ),
330
331 'cancelPacket' => $this->wpAdapter->__( 'Cancel packet', 'packeta' ),
332 'createPacketClaim' => $this->wpAdapter->__( 'Create packet claim', 'packeta' ),
333 'printPacketLabel' => $this->wpAdapter->__( 'Print packet label', 'packeta' ),
334 'printPacketClaimLabel' => $this->wpAdapter->__( 'Print packet claim label', 'packeta' ),
335 'cancelPacketClaim' => $this->wpAdapter->__( 'Cancel packet claim', 'packeta' ),
336 'packetClaimPassword' => $this->wpAdapter->__( 'Packet claim password', 'packeta' ),
337 'submissionPassword' => $this->wpAdapter->__( 'submission password', 'packeta' ),
338 'zboxConsignPassword' => $this->wpAdapter->__( 'Consignment code', 'packeta' ),
339 'setStoredUntil' => $this->wpAdapter->__( 'Set the pickup date extension', 'packeta' ),
340 'runWizard' => $this->wpAdapter->__( 'Run options wizard', 'packeta' ),
341 ],
342 ]
343 );
344
345 $partsCache = $parts;
346
347 return $partsCache;
348 }
349
350 $unit = $this->optionsProvider->getDimensionsUnit();
351 $this->orderForm->setDefaults(
352 $this->form,
353 $order->getFinalWeight(),
354 $order->getCalculatedWeight(),
355 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getLength() ) : $order->getLength(),
356 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getWidth() ) : $order->getWidth(),
357 $unit === OptionsProvider::DIMENSIONS_UNIT_CM ? ModuleHelper::convertToCentimeters( (int) $order->getHeight() ) : $order->getHeight(),
358 $order->getFinalCod(),
359 $order->getCalculatedCod(),
360 $order->getFinalValue(),
361 $order->getCalculatedValue(),
362 $order->containsAdultContent(),
363 $this->coreHelper->getStringFromDateTime( $order->getDeliverOn(), CoreHelper::DATEPICKER_FORMAT )
364 );
365
366 $prevInvalidValues = get_transient( Transients::METABOX_NETTE_FORM_PREV_INVALID_VALUES );
367 if ( $prevInvalidValues !== null && $prevInvalidValues !== false ) {
368 $this->form->setValues( $prevInvalidValues );
369 $this->form->validate();
370 }
371 delete_transient( Transients::METABOX_NETTE_FORM_PREV_INVALID_VALUES );
372
373 $isPacketSubmissionPossible = $this->orderValidator->isValid( $order );
374 $packetSubmitUrl = $this->getOrderActionLink( $order, PacketActionsCommonLogic::ACTION_SUBMIT_PACKET );
375
376 $showWidgetButton = $order->isPickupPointDelivery();
377 $widgetButtonError = null;
378 $shippingCountry = $order->getShippingCountry();
379 $showHdWidget = $order->isHomeDelivery() && in_array( $shippingCountry, Entity\Carrier::ADDRESS_VALIDATION_COUNTRIES, true );
380 if (
381 $shippingCountry === null ||
382 ! $this->carrierRepository->isValidForCountry( $order->getCarrier()->getId(), $shippingCountry )
383 ) {
384 if ( $order->isPickupPointDelivery() ) {
385 $showWidgetButton = false;
386 if ( $shippingCountry === null ) {
387 $widgetButtonError = $this->wpAdapter->__(
388 'The pickup point cannot be changed because the shipping address has no country set. First, change the country of delivery in the shipping address.',
389 'packeta'
390 );
391 } else {
392 $widgetButtonError = sprintf(
393 // translators: %s is country code.
394 $this->wpAdapter->__(
395 '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.',
396 'packeta'
397 ),
398 $shippingCountry
399 );
400 }
401 } elseif ( in_array( $order->getCarrier()->getCountry(), Entity\Carrier::ADDRESS_VALIDATION_COUNTRIES, true ) ) {
402 $showHdWidget = false;
403 if ( $shippingCountry === null ) {
404 $widgetButtonError = $this->wpAdapter->__(
405 'The address cannot be validated because the shipping address has no country set. First, change the country of delivery in the shipping address.',
406 'packeta'
407 );
408 } else {
409 $widgetButtonError = sprintf(
410 // translators: %s is country code.
411 $this->wpAdapter->__(
412 '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.',
413 'packeta'
414 ),
415 $shippingCountry
416 );
417 }
418 }
419 }
420
421 $invalidFields = $this->orderForm->getInvalidFieldsFromValidationResult( $this->orderValidator->validate( $order ) );
422 $invalidFieldsMessage = $this->orderForm->getInvalidFieldsMessageFromValidationResult( $invalidFields, $order );
423
424 $parts[ self::PART_MAIN ] = $this->latteEngine->renderToString(
425 PACKETERY_PLUGIN_DIR . '/template/order/metabox-form.latte',
426 [
427 'form' => $this->form,
428 'order' => $order,
429 'showConsignPasswordForZBox' => $this->optionsProvider->isShowConsignPasswordForZBoxEnabled(),
430 'showWidgetButton' => $showWidgetButton,
431 'widgetButtonError' => $widgetButtonError,
432 'showHdWidget' => $showHdWidget,
433 'isPacketSubmissionPossible' => $isPacketSubmissionPossible,
434 'orderWarningFields' => $invalidFields,
435 'invalidFieldsMessage' => $invalidFieldsMessage,
436 'packetCancelLink' => null,
437 'packetTrackingUrl' => null,
438 'packetStatusTranslatedName' => null,
439 'packetSubmitUrl' => $packetSubmitUrl,
440 'packetClaimTrackingUrl' => $packetClaimTrackingUrl,
441 'packetClaimUrl' => $packetClaimUrl,
442 'packetClaimCancelUrl' => $packetClaimCancelUrl,
443 'runWizardUrl' => $runWizardUrl,
444 'showRunWizardButton' => $showRunWizardButton,
445 'orderCurrency' => get_woocommerce_currency_symbol( $order->getCurrency() ),
446 'isCodPayment' => $order->hasCod(),
447 'allowsAdultContent' => $order->allowsAdultContent(),
448 'requiresSizeDimensions' => $order->getCarrier()->requiresSize(),
449 'logo' => plugin_dir_url( PACKETERY_PLUGIN_DIR . '/packeta.php' ) . 'public/images/packeta-symbol.png',
450 'showLogsLink' => $showLogsLink,
451 'hasOrderManualWeight' => $order->hasManualWeight(),
452 'hasOrderManualCod' => $order->hasManualCod(),
453 'hasOrderManualValue' => $order->hasManualValue(),
454 'isPacketaPickupPoint' => $order->isPacketaInternalPickupPoint(),
455 'pickupPointAttributes' => Attribute::$pickupPointAttributes,
456 'homeDeliveryAttributes' => Attribute::$homeDeliveryAttributes,
457 'translations' => [
458 'packetSubmissionValidationErrorTooltip' => $this->wpAdapter->__( 'It is not possible to submit the shipment because all the information required for this shipment is not filled:', 'packeta' ),
459 'showLogs' => $this->wpAdapter->__( 'Show logs', 'packeta' ),
460 'weightIsManual' => $this->wpAdapter->__( 'Weight is manually set. To calculate weight remove field content and save.', 'packeta' ),
461 'codIsManual' => $this->wpAdapter->__( 'COD value is manually set. To calculate the value remove field content and save.', 'packeta' ),
462 'valueIsManual' => $this->wpAdapter->__( 'Order value is manually set. To calculate the value remove field content and save.', 'packeta' ),
463 'submitPacket' => $this->wpAdapter->__( 'Submit to Packeta', 'packeta' ),
464 'runWizard' => $this->wpAdapter->__( 'Run options wizard', 'packeta' ),
465 'packetClaimTrackingOnline' => $this->wpAdapter->__( 'Packet claim tracking', 'packeta' ),
466 'printPacketClaimLabel' => $this->wpAdapter->__( 'Print packet claim label', 'packeta' ),
467 'cancelPacketClaim' => $this->wpAdapter->__( 'Cancel packet claim', 'packeta' ),
468 'packetClaimPassword' => $this->wpAdapter->__( 'Packet claim password', 'packeta' ),
469 'submissionPassword' => $this->wpAdapter->__( 'submission password', 'packeta' ),
470 'zboxConsignPassword' => $this->wpAdapter->__( 'Z-BOX consign password', 'packeta' ),
471 // translators: %s: Order number.
472 'reallyCancelPacketHeading' => sprintf( $this->wpAdapter->__( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
473 // translators: %s: Packet claim number.
474 'reallyCancelPacketClaim' => sprintf( $this->wpAdapter->__( 'Do you really wish to cancel packet claim number %s?', 'packeta' ), $order->getPacketClaimId() ),
475 ],
476 ]
477 );
478
479 $partsCache = $parts;
480
481 return $partsCache;
482 }
483
484 /**
485 * Saves added packetery form fields to order metas.
486 *
487 * @param Entity\Order $order Order.
488 * @param WC_Order $wcOrder WC Order.
489 *
490 * @return void
491 * @throws WC_Data_Exception When invalid data are passed during shipping address update.
492 */
493 public function saveFields( Entity\Order $order, WC_Order $wcOrder ): void {
494 $this->initializeForm();
495
496 $orderId = (int) $order->getNumber();
497 if (
498 ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ||
499 $this->request->getPost( 'packetery_order_metabox_nonce' ) === null
500 ) {
501 return;
502 }
503
504 if ( $this->form->isValid() === false ) {
505 set_transient( Transients::METABOX_NETTE_FORM_PREV_INVALID_VALUES, $this->form->getValues( 'array' ) );
506 $this->messageManager->flash_message( $this->wpAdapter->__( 'Packeta: entered data is not valid!', 'packeta' ), MessageManager::TYPE_ERROR );
507
508 return;
509 }
510 /** @var array<string, string|float|int|true|null> $formValues */
511 $formValues = $this->form->getValues( 'array' );
512
513 if ( wp_verify_nonce( $formValues['packetery_order_metabox_nonce'] ) !== 1 ) {
514 $this->messageManager->flash_message( $this->wpAdapter->__( 'Session has expired! Please try again.', 'packeta' ), MessageManager::TYPE_ERROR );
515
516 return;
517 }
518
519 if ( ! current_user_can( 'edit_post', $orderId ) ) {
520 $this->messageManager->flash_message( $this->wpAdapter->__( 'You do not have sufficient rights to make changes!', 'packeta' ), MessageManager::TYPE_ERROR );
521
522 return;
523 }
524
525 $propsToSave = [];
526 foreach ( [ Form::FIELD_LENGTH, Form::FIELD_WIDTH, Form::FIELD_HEIGHT ] as $dimension ) {
527 $propsToSave[ $dimension ] = $this->optionsProvider->getSanitizedDimensionValueInMm( $formValues[ $dimension ] );
528 }
529
530 $formWeightEqualsToCalculated = (float) $formValues[ Form::FIELD_WEIGHT ] === (float) $formValues[ Form::FIELD_ORIGINAL_WEIGHT ];
531 if ( ! is_numeric( $formValues[ Form::FIELD_WEIGHT ] ) || $formWeightEqualsToCalculated ) {
532 $propsToSave[ Form::FIELD_WEIGHT ] = null;
533 } else {
534 $propsToSave[ Form::FIELD_WEIGHT ] = (float) $formValues[ Form::FIELD_WEIGHT ];
535 }
536 $order->setWeight( $propsToSave[ Form::FIELD_WEIGHT ] );
537
538 if ( $formValues[ Attribute::POINT_ID ] && $order->isPickupPointDelivery() ) {
539 foreach ( Attribute::$pickupPointAttributes as $pickupPointAttr ) {
540 $pickupPointValue = $formValues[ $pickupPointAttr['name'] ];
541
542 if ( $pickupPointAttr['name'] === Attribute::CARRIER_ID ) {
543 if ( isset( $formValues[ Attribute::CARRIER_ID ] ) && $formValues[ Attribute::CARRIER_ID ] !== '' ) {
544 $pickupPointValue = $formValues[ Attribute::CARRIER_ID ];
545 } else {
546 $pickupPointValue = $order->getCarrier()->getId();
547 }
548 }
549
550 $propsToSave[ $pickupPointAttr['name'] ] = $pickupPointValue;
551
552 if ( $this->optionsProvider->replaceShippingAddressWithPickupPointAddress() ) {
553 $this->mapper->toWcOrderShippingAddress( $wcOrder, $pickupPointAttr['name'], (string) $pickupPointValue );
554 }
555 }
556 }
557
558 if ( $formValues[ Attribute::ADDRESS_IS_VALIDATED ] === '1' && $order->isHomeDelivery() ) {
559 $address = $this->mapper->toValidatedAddress( $formValues );
560 $order->setDeliveryAddress( $address );
561 $order->setAddressValidated( true );
562 }
563
564 $order->setAdultContent( $formValues[ Form::FIELD_ADULT_CONTENT ] );
565
566 $formCodEqualsToCalculated = (float) $formValues[ Form::FIELD_COD ] === (float) $formValues[ Form::FIELD_CALCULATED_COD ];
567 if ( ! is_numeric( $formValues[ Form::FIELD_COD ] ) || $formCodEqualsToCalculated ) {
568 $order->setManualCod( null );
569 } else {
570 $order->setManualCod( is_numeric( $formValues[ Form::FIELD_COD ] ) ? CoreHelper::simplifyFloat( $formValues[ Form::FIELD_COD ], 10 ) : null );
571 }
572
573 $formValueEqualsToCalculated = (float) $formValues[ Form::FIELD_VALUE ] === (float) $formValues[ Form::FIELD_CALCULATED_VALUE ];
574 if ( ! is_numeric( $formValues[ Form::FIELD_VALUE ] ) || $formValueEqualsToCalculated ) {
575 $order->setManualValue( null );
576 } else {
577 $order->setManualValue( is_numeric( $formValues[ Form::FIELD_VALUE ] ) ? CoreHelper::simplifyFloat( $formValues[ Form::FIELD_VALUE ], 10 ) : null );
578 }
579
580 $order->setDeliverOn( $this->coreHelper->getDateTimeFromString( $formValues[ Form::FIELD_DELIVER_ON ] ) );
581
582 $orderSize = $this->mapper->toOrderSize( $order, $propsToSave );
583 $order->setSize( $orderSize );
584
585 $pickupPoint = $this->mapper->toOrderEntityPickupPoint( $order, $propsToSave );
586 $order->setPickupPoint( $pickupPoint );
587
588 $updatedRowCount = $this->orderRepository->save( $order );
589 if ( $updatedRowCount === false ) {
590 $this->messageManager->flash_message(
591 (string) $this->wpAdapter->__( 'An error occurred while saving the order. More details in WC log.', 'packeta' ),
592 MessageManager::TYPE_ERROR
593 );
594 }
595 }
596
597 /**
598 * Creates pickup point picker settings.
599 *
600 * @return array<string, array|string|null>
601 */
602 public function getPickupPointWidgetSettings(): ?array {
603 $order = $this->detailCommonLogic->getOrder();
604 if ( $order === null || $order->isPickupPointDelivery() === false || $order->getShippingCountry() === null ) {
605 return null;
606 }
607
608 $widgetOptions = $this->widgetOptionsBuilder->createPickupPointForAdmin( $order );
609
610 return [
611 'packeteryApiKey' => $this->optionsProvider->get_api_key(),
612 'pickupPointAttrs' => Attribute::$pickupPointAttributes,
613 'widgetOptions' => $widgetOptions,
614 ];
615 }
616
617 /**
618 * Creates address picker settings.
619 *
620 * @return mixed[]|null
621 */
622 public function getAddressWidgetSettings(): ?array {
623 $order = $this->detailCommonLogic->getOrder();
624 if ( $order === null || $order->isHomeDelivery() === false ) {
625 return null;
626 }
627
628 $widgetOptions = $this->widgetOptionsBuilder->createAddressForAdmin( $order );
629
630 return [
631 'packeteryApiKey' => $this->optionsProvider->get_api_key(),
632 'homeDeliveryAttrs' => Attribute::$homeDeliveryAttributes,
633 'widgetOptions' => $widgetOptions,
634 'translations' => [
635 'addressValidationIsOutOfOrder' => $this->wpAdapter->__( 'Address validation is out of order.', 'packeta' ),
636 'invalidAddressCountrySelected' => $this->wpAdapter->__( 'The selected country does not correspond to the destination country.', 'packeta' ),
637 ],
638 ];
639 }
640
641 /**
642 * Gets order action link.
643 *
644 * @param Entity\Order $order Order.
645 * @param string $action Action.
646 * @param array $extraParams Extra params.
647 *
648 * @return string
649 */
650 private function getOrderActionLink( Entity\Order $order, string $action, array $extraParams = [] ): string {
651 $baseParams = [
652 PacketActionsCommonLogic::PARAM_ORDER_ID => $order->getNumber(),
653 PacketActionsCommonLogic::PARAM_REDIRECT_TO => PacketActionsCommonLogic::REDIRECT_TO_ORDER_DETAIL,
654 Plugin::PARAM_PACKETERY_ACTION => $action,
655 Plugin::PARAM_NONCE => wp_create_nonce( PacketActionsCommonLogic::createNonceAction( $action, $order->getNumber() ) ),
656 ];
657
658 return add_query_arg(
659 array_merge( $baseParams, $extraParams ),
660 admin_url( 'admin.php' )
661 );
662 }
663
664 /**
665 * Initializes form to render or process.
666 *
667 * @return void
668 */
669 private function initializeForm(): void {
670 $this->form = $this->orderForm->create();
671 $this->form->addHidden( 'packetery_order_metabox_nonce' );
672 $this->form->setDefaults( [ 'packetery_order_metabox_nonce' => wp_create_nonce() ] );
673
674 foreach ( Attribute::$pickupPointAttributes as $pickupPointAttr ) {
675 $this->form->addHidden( $pickupPointAttr['name'] );
676 }
677
678 foreach ( Attribute::$homeDeliveryAttributes as $homeDeliveryAttr ) {
679 $this->form->addHidden( $homeDeliveryAttr['name'] );
680 }
681
682 $this->form->addButton(
683 'packetery_pick_pickup_point',
684 $this->wpAdapter->__( 'Choose pickup point', 'packeta' )
685 );
686 $this->form->addButton(
687 'packetery_pick_address',
688 $this->wpAdapter->__( 'Check shipping address', 'packeta' )
689 );
690 }
691 }
692