PluginProbe
Packeta / 1.5.0
Packeta v1.5.0
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 / Options / Page.php

Page.php in Packeta 1.5.0, at src/Packetery/Module/Options/Page.php

774 lines 27.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Class Page
4 *
5 * @package Packetery\Options
6 */
7
8 declare( strict_types=1 );
9
10 namespace Packetery\Module\Options;
11
12 use Packetery\Core\Api\Soap\Request\SenderGetReturnRouting;
13 use Packetery\Core\Log;
14 use Packetery\Module\FormFactory;
15 use Packetery\Module\MessageManager;
16 use Packetery\Module\Order\PacketAutoSubmitter;
17 use Packetery\Module\Order\PacketSynchronizer;
18 use PacketeryLatte\Engine;
19 use PacketeryNette\Forms\Form;
20
21 /**
22 * Class Page
23 *
24 * @package Packetery\Options
25 */
26 class Page {
27
28 private const FORM_FIELDS_CONTAINER = 'packetery';
29 private const FORM_FIELD_PACKETA_LABEL_FORMAT = 'packeta_label_format';
30 private const FORM_FIELD_CARRIER_LABEL_FORMAT = 'carrier_label_format';
31 private const FORM_FIELD_ORDER_STATUS_AUTO_CHANGE = 'order_status_auto_change';
32
33 public const ACTION_VALIDATE_SENDER = 'validate-sender';
34
35 public const SLUG = 'packeta-options';
36
37 public const TAB_GENERAL = 'general';
38 public const TAB_SUPPORT = 'support';
39 public const TAB_PACKET_STATUS_SYNC = 'packet-status-sync';
40 public const TAB_AUTO_SUBMISSION = 'auto-submission';
41
42 public const PARAM_TAB = 'tab';
43
44 /**
45 * PacketeryLatte_engine.
46 *
47 * @var Engine PacketeryLatte engine.
48 */
49 private $latte_engine;
50
51 /**
52 * Options Provider
53 *
54 * @var Provider
55 */
56 private $optionsProvider;
57
58 /**
59 * Form factory.
60 *
61 * @var FormFactory Form factory.
62 */
63 private $formFactory;
64
65 /**
66 * Packeta client.
67 *
68 * @var \Packetery\Core\Api\Soap\Client
69 */
70 private $packetaClient;
71
72 /**
73 * Logger
74 *
75 * @var Log\ILogger
76 */
77 private $logger;
78
79 /**
80 * Message manager.
81 *
82 * @var MessageManager
83 */
84 private $messageManager;
85
86 /**
87 * HTTP request.
88 *
89 * @var \PacketeryNette\Http\Request
90 */
91 private $httpRequest;
92
93 /**
94 * Plugin constructor.
95 *
96 * @param Engine $latte_engine PacketeryLatte_engine.
97 * @param Provider $optionsProvider Options provider.
98 * @param FormFactory $formFactory Form factory.
99 * @param \Packetery\Core\Api\Soap\Client $packetaClient Packeta Client.
100 * @param Log\ILogger $logger Logger.
101 * @param MessageManager $messageManager Message manager.
102 * @param \PacketeryNette\Http\Request $httpRequest HTTP request.
103 */
104 public function __construct(
105 Engine $latte_engine,
106 Provider $optionsProvider,
107 FormFactory $formFactory,
108 \Packetery\Core\Api\Soap\Client $packetaClient,
109 Log\ILogger $logger,
110 MessageManager $messageManager,
111 \PacketeryNette\Http\Request $httpRequest
112 ) {
113 $this->latte_engine = $latte_engine;
114 $this->optionsProvider = $optionsProvider;
115 $this->formFactory = $formFactory;
116 $this->packetaClient = $packetaClient;
117 $this->logger = $logger;
118 $this->messageManager = $messageManager;
119 $this->httpRequest = $httpRequest;
120 }
121
122 /**
123 * Registers WP callbacks.
124 */
125 public function register(): void {
126 add_action( 'admin_init', array( $this, 'admin_init' ) );
127 $icon = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDI1LjEuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IlZyc3R2YV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgMzcgNDAiIHN0eWxlPSJmaWxsOiNhN2FhYWQiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsLXJ1bGU6ZXZlbm9kZDtjbGlwLXJ1bGU6ZXZlbm9kZDtmaWxsOiAjYTdhYWFkO30KPC9zdHlsZT4KPHBhdGggY2xhc3M9InN0MCIgZD0iTTE5LjQsMTYuMWwtMC45LDAuNGwtMC45LTAuNGwtMTMtNi41bDYuMi0yLjRsMTMuNCw2LjVMMTkuNCwxNi4xeiBNMzIuNSw5LjZsLTQuNywyLjNsLTEzLjUtNmw0LjItMS42CglMMzIuNSw5LjZ6Ii8+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik0xOSwwbDE3LjIsNi42bC0yLjQsMS45bC0xNS4yLTZMMy4yLDguNkwwLjgsNi42TDE4LDBMMTksMEwxOSwweiBNMzQuMSw5LjFsMi44LTEuMWwtMi4xLDE3LjZsLTAuNCwwLjgKCUwxOS40LDQwbC0wLjUtMy4xbDEzLjQtMTJMMzQuMSw5LjF6IE0yLjUsMjYuNWwtMC40LTAuOEwwLDguMWwyLjgsMS4xbDEuOSwxNS43bDEzLjQsMTJMMTcuNiw0MEwyLjUsMjYuNXoiLz4KPHBhdGggY2xhc3M9InN0MCIgZD0iTTI4LjIsMTIuNGw0LjMtMi43bC0xLjcsMTQuMkwxOC42LDM1bDAuNi0xN2w1LjQtMy4zTDI0LjMsMjNsMy4zLTIuM0wyOC4yLDEyLjR6Ii8+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik0xNy43LDE3LjlsMC42LDE3bC0xMi4yLTExTDQuNCw5LjhMMTcuNywxNy45eiIvPgo8L3N2Zz4K';
128 add_menu_page(
129 __( 'Packeta', 'packeta' ),
130 __( 'Packeta', 'packeta' ),
131 'manage_options',
132 self::SLUG,
133 '',
134 $icon
135 );
136 add_submenu_page(
137 self::SLUG,
138 __( 'Settings', 'packeta' ),
139 __( 'Settings', 'packeta' ),
140 'manage_options',
141 self::SLUG,
142 array(
143 $this,
144 'render',
145 ),
146 1
147 );
148 add_action( 'admin_init', [ $this, 'processActions' ] );
149
150 add_filter( 'custom_menu_order', '__return_true' );
151 add_filter( 'menu_order', [ $this, 'customMenuOrder' ] );
152 }
153
154 /**
155 * Returns menu_order with Packeta item in last position.
156 *
157 * @param array $menuOrder WP $menu_order.
158 *
159 * @return array
160 */
161 public function customMenuOrder( array $menuOrder ): array {
162 $currentPosition = array_search( self::SLUG, $menuOrder, true );
163
164 if ( false !== $currentPosition ) {
165 unset( $menuOrder[ $currentPosition ] );
166 $menuOrder[] = self::SLUG;
167 }
168
169 return $menuOrder;
170 }
171
172 /**
173 * Get chosen keys by hashed choice data.
174 *
175 * @param array $choiceData Choice data.
176 * @param array $chosenHashedFormOrderStatuses Picked items.
177 *
178 * @return array
179 */
180 private function getChosenKeys( array $choiceData, array $chosenHashedFormOrderStatuses ): array {
181 $statuses = [];
182 foreach ( $chosenHashedFormOrderStatuses as $hash => $chosen ) {
183 if ( $chosen ) {
184 $statuses[] = $choiceData[ $hash ]['key'];
185 }
186 }
187
188 return $statuses;
189 }
190
191 /**
192 * Gets all packet statuses.
193 *
194 * @return array
195 */
196 public function getPacketStatusesChoiceData(): array {
197 $statuses = PacketSynchronizer::getPacketStatuses();
198
199 $result = [];
200
201 foreach ( $statuses as $status => $statusEntity ) {
202 $result[ md5( $status ) ] = [
203 'key' => $status,
204 'default' => $statusEntity->hasDefaultSynchronization(),
205 'label' => $statusEntity->getTranslatedName(),
206 ];
207 }
208
209 return $result;
210 }
211
212 /**
213 * Gets order statuses for form.
214 *
215 * @return array
216 */
217 public static function getOrderStatusesChoiceData(): array {
218 $orderStatuses = wc_get_order_statuses();
219 $orderStatusesTransformed = [];
220
221 foreach ( $orderStatuses as $orderStatusKey => $orderStatusLabel ) {
222 $orderStatusesTransformed[ md5( $orderStatusKey ) ] = [
223 'key' => $orderStatusKey,
224 'label' => $orderStatusLabel,
225 ];
226 }
227
228 return $orderStatusesTransformed;
229 }
230
231 /**
232 * Creates auto submission form.
233 *
234 * @return Form
235 */
236 public function createAutoSubmissionForm(): Form {
237 $gateways = $this->getAvailablePaymentGateways();
238 $form = $this->formFactory->create( 'packetery_auto_submission_form' );
239 $defaults = $this->optionsProvider->data_to_array( Provider::OPTION_NAME_PACKETERY_AUTO_SUBMISSION );
240
241 $form->addCheckbox( 'allow', __( 'Allow', 'packeta' ) )
242 ->setRequired( false )
243 ->setDefaultValue( Provider::PACKET_AUTO_SUBMISSION_ALLOWED_DEFAULT );
244
245 $eventChoices = [
246 PacketAutoSubmitter::EVENT_ON_ORDER_CREATION_FE => __( 'On order creation at frontend', 'packeta' ),
247 PacketAutoSubmitter::EVENT_ON_ORDER_PROCESSING => __( 'On order processing', 'packeta' ),
248 PacketAutoSubmitter::EVENT_ON_ORDER_COMPLETED => __( 'On order completed', 'packeta' ),
249 ];
250
251 $paymentMethodEvents = $form->addContainer( 'payment_method_events' );
252 foreach ( $gateways as $gateway ) {
253 $paymentMethodEventsMethod = $paymentMethodEvents->addContainer( $gateway->id );
254 $paymentMethodEventsMethod->addSelect( 'event', $gateway->get_method_title(), $eventChoices )
255 ->setPrompt( __( 'Select event', 'packeta' ) )
256 ->checkDefaultValue( false );
257 }
258
259 $form->addSubmit( 'save', __( 'Save changes', 'packeta' ) );
260
261 $form->setDefaults( $defaults );
262
263 $form->onSuccess[] = [ $this, 'onAutoSubmissionFormSuccess' ];
264
265 return $form;
266 }
267
268 /**
269 * On auto submission form success.
270 *
271 * @param Form $form Form.
272 * @param array $values Form values.
273 *
274 * @return void
275 */
276 public function onAutoSubmissionFormSuccess( Form $form, array $values ): void {
277 update_option( Provider::OPTION_NAME_PACKETERY_AUTO_SUBMISSION, $values );
278
279 $this->messageManager->flash_message( __( 'Settings saved.', 'packeta' ), MessageManager::TYPE_SUCCESS, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
280
281 if ( wp_safe_redirect( $this->createLink( self::TAB_AUTO_SUBMISSION ) ) ) {
282 exit;
283 }
284 }
285
286 /**
287 * Creates settings form.
288 *
289 * @return Form
290 */
291 private function createPacketStatusSyncForm(): Form {
292 $form = $this->formFactory->create( 'packetery_packet_status_sync_form' );
293 $settings = $this->optionsProvider->data_to_array( Provider::OPTION_NAME_PACKETERY_SYNC );
294
295 $form->addText( 'max_status_syncing_packets', __( 'Number of orders synced during one cron call', 'packeta' ) )
296 ->setRequired( false )
297 ->addRule( Form::INTEGER )
298 ->addRule( Form::MIN, null, 0 )
299 ->setDefaultValue( Provider::MAX_STATUS_SYNCING_PACKETS_DEFAULT );
300
301 $form->addText( 'max_days_of_packet_status_syncing', __( 'Number of days for which the order status is checked', 'packeta' ) )
302 ->setRequired( false )
303 ->addRule( Form::INTEGER )
304 ->addRule( Form::MIN, null, 0 )
305 ->setDefaultValue( Provider::MAX_DAYS_OF_PACKET_STATUS_SYNCING_DEFAULT );
306
307 $orderStatusesTransformed = self::getOrderStatusesChoiceData();
308 $orderStatusesContainer = $form->addContainer( 'status_syncing_order_statuses' );
309
310 foreach ( $orderStatusesTransformed as $orderStatusKeyHash => $orderStatusData ) {
311 $item = $orderStatusesContainer->addCheckbox( $orderStatusKeyHash, $orderStatusData['label'] );
312 if ( isset( $settings['status_syncing_order_statuses'] ) && in_array( $orderStatusData['key'], $settings['status_syncing_order_statuses'], true ) ) {
313 $item->setDefaultValue( true );
314 }
315 }
316 unset( $settings['status_syncing_order_statuses'] );
317
318 $packetStatuses = $this->getPacketStatusesChoiceData();
319 $packetStatusesContainer = $form->addContainer( 'status_syncing_packet_statuses' );
320
321 foreach ( $packetStatuses as $packetStatusHash => $packetStatusData ) {
322 $item = $packetStatusesContainer->addCheckbox( $packetStatusHash, $packetStatusData['label'] );
323 if ( ! isset( $settings['status_syncing_packet_statuses'] ) ) {
324 $item->setDefaultValue( $packetStatusData['default'] );
325 } elseif ( in_array( $packetStatusData['key'], $settings['status_syncing_packet_statuses'], true ) ) {
326 $item->setDefaultValue( true );
327 }
328 }
329 unset( $settings['status_syncing_packet_statuses'] );
330
331 $form->setDefaults( $settings );
332
333 $form->addSubmit( 'save', __( 'Save changes', 'packeta' ) );
334
335 $form->onSuccess[] = [ $this, 'onPacketStatusSyncFormSuccess' ];
336
337 return $form;
338 }
339
340 /**
341 * On packet status sync form success.
342 *
343 * @param Form $form Form.
344 * @param array $values Values.
345 *
346 * @return void
347 */
348 public function onPacketStatusSyncFormSuccess( Form $form, array $values ): void {
349
350 $values['status_syncing_order_statuses'] = $this->getChosenKeys(
351 self::getOrderStatusesChoiceData(),
352 $values['status_syncing_order_statuses']
353 );
354 $values['status_syncing_packet_statuses'] = $this->getChosenKeys(
355 $this->getPacketStatusesChoiceData(),
356 $values['status_syncing_packet_statuses']
357 );
358
359 if ( '' === $values['max_status_syncing_packets'] ) {
360 unset( $values['max_status_syncing_packets'] );
361 }
362
363 if ( '' === $values['max_days_of_packet_status_syncing'] ) {
364 unset( $values['max_days_of_packet_status_syncing'] );
365 }
366
367 update_option( Provider::OPTION_NAME_PACKETERY_SYNC, $values );
368
369 $this->messageManager->flash_message( __( 'Settings saved.', 'packeta' ), MessageManager::TYPE_SUCCESS, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
370
371 if ( wp_safe_redirect( $this->createLink( self::TAB_PACKET_STATUS_SYNC ) ) ) {
372 exit;
373 }
374 }
375
376 /**
377 * Creates settings form.
378 *
379 * @return Form
380 */
381 public function create_form(): Form {
382 $form = $this->formFactory->create();
383 $form->setAction( 'options.php' );
384
385 $container = $form->addContainer( self::FORM_FIELDS_CONTAINER );
386 $container->addText( 'api_password', __( 'API password', 'packeta' ) )
387 ->setRequired()
388 ->addRule( $form::PATTERN, __( 'API password must be 32 characters long and must contain valid characters!', 'packeta' ), '[a-z\d]{32}' );
389 $container->addText( 'sender', __( 'Sender', 'packeta' ) )
390 ->setRequired();
391
392 $packetaLabelFormats = $this->optionsProvider->getPacketaLabelFormats();
393 $container->addSelect(
394 self::FORM_FIELD_PACKETA_LABEL_FORMAT,
395 __( 'Packeta Label Format', 'packeta' ),
396 $packetaLabelFormats
397 )->checkDefaultValue( false )->setDefaultValue( Provider::DEFAULT_VALUE_PACKETA_LABEL_FORMAT );
398
399 $carrierLabelFormats = $this->optionsProvider->getCarrierLabelFormat();
400 $container->addSelect(
401 self::FORM_FIELD_CARRIER_LABEL_FORMAT,
402 __( 'Carrier Label Format', 'packeta' ),
403 $carrierLabelFormats
404 )->checkDefaultValue( false )->setDefaultValue( Provider::DEFAULT_VALUE_CARRIER_LABEL_FORMAT );
405
406 $gateways = $this->getAvailablePaymentGateways();
407 $enabledGateways = [];
408 foreach ( $gateways as $gateway ) {
409 $enabledGateways[ $gateway->id ] = $gateway->get_method_title();
410 }
411 $container->addSelect(
412 'cod_payment_method',
413 __( 'Payment method that represents cash on delivery', 'packeta' ),
414 $enabledGateways
415 )->setPrompt( '--' )->checkDefaultValue( false );
416
417 $container->addText( 'packaging_weight', __( 'Weight of packaging material', 'packeta' ) . ' (kg)' )
418 ->setRequired( true )
419 ->addRule( Form::FLOAT )
420 ->addRule( Form::MIN, null, 0 )
421 ->setDefaultValue( 0 );
422
423 $container->addCheckbox( 'default_weight_enabled', __( 'Enable default weight', 'packeta' ) )
424 ->addCondition( Form::EQUAL, true )
425 ->toggle( '#packetery-default-weight-value' );
426
427 $container->addText( 'default_weight', __( 'Default weight', 'packeta' ) . ' (kg)' )
428 ->addRule( Form::FLOAT )
429 ->addRule( Form::MIN, null, 0.1 )
430 ->addConditionOn( $form[ self::FORM_FIELDS_CONTAINER ]['default_weight_enabled'], Form::EQUAL, true )
431 ->setRequired();
432
433 // TODO: Packet status sync.
434
435 $container->addCheckbox( 'replace_shipping_address_with_pickup_point_address', __( 'Replace shipping address with pickup point address', 'packeta' ) )
436 ->setRequired( false );
437
438 $container->addSelect(
439 'checkout_widget_button_location',
440 __( 'Widget button location in checkout', 'packeta' ),
441 [
442 'after_shipping_rate' => __( 'After shipping rate', 'packeta' ),
443 'after_transport_methods' => __( 'After transport methods', 'packeta' ),
444 ]
445 );
446
447 $container->addCheckbox( 'force_packet_cancel', __( 'Force order cancellation', 'packeta' ) )
448 ->setRequired( false )
449 ->setDefaultValue( Provider::FORCE_PACKET_CANCEL_DEFAULT );
450
451 $container->addCheckbox( 'widget_auto_open', __( 'Automatically open widget when shipping was selected', 'packeta' ) )
452 ->setRequired( false )
453 ->setDefaultValue( Provider::WIDGET_AUTO_OPEN_DEFAULT );
454
455 $container->addCheckbox( self::FORM_FIELD_ORDER_STATUS_AUTO_CHANGE, __( 'Order status auto change', 'packeta' ) )
456 ->setRequired( false )
457 ->setDefaultValue( Provider::ORDER_STATUS_AUTO_CHANGE_DEFAULT )
458 ->addCondition( Form::EQUAL, true )
459 ->toggle( '.packetery-order-status-auto-change-row' );
460
461 $orderStatuses = wc_get_order_statuses();
462 $container->addSelect(
463 Provider::AUTO_ORDER_STATUS,
464 __( 'New order status', 'packeta' ),
465 $orderStatuses
466 )
467 ->checkDefaultValue( false )
468 ->setDefaultValue( Provider::AUTO_ORDER_STATUS_DEFAULT )
469 ->setPrompt( __( 'Select new order status', 'packeta' ) )
470 ->addRule( Form::IS_IN, __( 'Select valid order status', 'packeta' ), array_keys( $orderStatuses ) )
471 ->addConditionOn( $form[ self::FORM_FIELDS_CONTAINER ][ self::FORM_FIELD_ORDER_STATUS_AUTO_CHANGE ], Form::EQUAL, true )
472 ->setRequired();
473
474 $container->addCheckbox(
475 'order_status_auto_change_for_auto_submit_at_frontend',
476 __( 'Change order status after automatic packet submit at frontend', 'packeta' )
477 );
478
479 $form->addSubmit( 'save', __( 'Save changes', 'packeta' ) );
480
481 if ( $this->optionsProvider->has_any( Provider::OPTION_NAME_PACKETERY ) ) {
482 $container->setDefaults( $this->optionsProvider->data_to_array( Provider::OPTION_NAME_PACKETERY ) );
483 }
484
485 return $form;
486 }
487
488 /**
489 * Get available gateways.
490 *
491 * @return \WC_Payment_Gateway[]
492 */
493 public function getAvailablePaymentGateways(): array {
494 $availableGateways = [];
495
496 foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) {
497 if ( 'yes' === $gateway->enabled ) {
498 $availableGateways[ $gateway->id ] = $gateway;
499 }
500 }
501
502 return array_filter( $availableGateways, [ $this, 'filterValidGatewayClass' ] );
503 }
504
505 /**
506 * Tells if options page uses given payment gateway.
507 *
508 * @param \WC_Payment_Gateway $paymentGateway Payment gateway.
509 *
510 * @return bool
511 */
512 public function hasPaymentGateway( \WC_Payment_Gateway $paymentGateway ): bool {
513 return array_key_exists( $paymentGateway->id, $this->getAvailablePaymentGateways() );
514 }
515
516 /**
517 * Callback for array filter. Returns true if gateway is of correct type.
518 *
519 * @param object $gateway Gateway to check.
520 * @return bool
521 */
522 protected function filterValidGatewayClass( object $gateway ): bool {
523 return ( $gateway instanceof \WC_Payment_Gateway );
524 }
525
526 /**
527 * Admin_init callback.
528 */
529 public function admin_init(): void {
530 register_setting( self::FORM_FIELDS_CONTAINER, self::FORM_FIELDS_CONTAINER, array( $this, 'options_validate' ) );
531 add_settings_section( 'packetery_main', __( 'Main Settings', 'packeta' ), '', self::SLUG );
532 }
533
534 /**
535 * Validates options.
536 *
537 * @param array $options Packetery_options.
538 *
539 * @return array
540 */
541 public function options_validate( array $options ): array {
542 $form = $this->create_form();
543 $form[ self::FORM_FIELDS_CONTAINER ]->setValues( $options );
544 if ( $form->isValid() === false ) {
545 foreach ( $form[ self::FORM_FIELDS_CONTAINER ]->getControls() as $control ) {
546 if ( $control->hasErrors() === false ) {
547 continue;
548 }
549
550 add_settings_error( $control->getCaption(), esc_attr( $control->getName() ), $control->getError() );
551 $options[ $control->getName() ] = '';
552 }
553 }
554
555 $api_password = $form[ self::FORM_FIELDS_CONTAINER ]['api_password'];
556 if ( $api_password->hasErrors() === false ) {
557 $api_pass = $api_password->getValue();
558 $options['api_key'] = substr( $api_pass, 0, 16 );
559 $this->packetaClient->setApiPassword( $api_pass );
560 } else {
561 $options['api_key'] = '';
562 }
563
564 $this->validateSender( $options['sender'] );
565 $options['force_packet_cancel'] = (int) $form[ self::FORM_FIELDS_CONTAINER ]['force_packet_cancel']->getValue();
566
567 return $options;
568 }
569
570 /**
571 * Validates sender.
572 *
573 * @param string $senderLabel Sender label.
574 *
575 * @return bool|null
576 */
577 private function validateSender( string $senderLabel ): ?bool {
578 $senderValidationRequest = new SenderGetReturnRouting( $senderLabel );
579 $senderValidationResponse = $this->packetaClient->senderGetReturnRouting( $senderValidationRequest );
580
581 $senderValidationLog = new Log\Record();
582 $senderValidationLog->action = Log\Record::ACTION_SENDER_VALIDATION;
583
584 $senderValidationLog->status = Log\Record::STATUS_SUCCESS;
585 $senderValidationLog->title = __( 'Sender validation was successful', 'packeta' );
586
587 if ( $senderValidationResponse->hasFault() ) {
588 $senderValidationLog->status = Log\Record::STATUS_ERROR;
589 $senderValidationLog->params = [
590 'errorMessage' => $senderValidationResponse->getFaultString(),
591 ];
592 $senderValidationLog->title = __( 'Sender could not be validated', 'packeta' );
593 }
594
595 $this->logger->add( $senderValidationLog );
596
597 $senderExists = $senderValidationResponse->senderExists();
598
599 if ( false === $senderExists ) {
600 $this->messageManager->flash_message( __( 'Specified sender does not exist', 'packeta' ), MessageManager::TYPE_INFO, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
601 }
602
603 if ( null === $senderExists ) {
604 $this->messageManager->flash_message( __( 'Unable to check specified sender', 'packeta' ), MessageManager::TYPE_INFO, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
605 }
606
607 return $senderExists;
608 }
609
610 /**
611 * Process actions.
612 *
613 * @return void
614 */
615 public function processActions(): void {
616 $action = $this->httpRequest->getQuery( 'action' );
617 if ( self::ACTION_VALIDATE_SENDER === $action ) {
618 $result = $this->validateSender( $this->optionsProvider->get_sender() );
619
620 if ( true === $result ) {
621 $this->messageManager->flash_message( __( 'Specified sender has been validated.', 'packeta' ), MessageManager::TYPE_SUCCESS, MessageManager::RENDERER_PACKETERY, 'plugin-options' );
622 }
623
624 $doRedirect = wp_safe_redirect(
625 add_query_arg(
626 [
627 'page' => self::SLUG,
628 ],
629 get_admin_url( null, 'admin.php' )
630 )
631 );
632
633 if ( $doRedirect ) {
634 exit;
635 }
636 }
637
638 $packetStatusSyncForm = $this->createPacketStatusSyncForm();
639 if ( $packetStatusSyncForm['save']->isSubmittedBy() ) {
640 $packetStatusSyncForm->fireEvents();
641 }
642
643 $autoSubmissionForm = $this->createAutoSubmissionForm();
644 if ( $autoSubmissionForm['save']->isSubmittedBy() ) {
645 $autoSubmissionForm->fireEvents();
646 }
647 }
648
649 /**
650 * Renders page.
651 */
652 public function render(): void {
653 $activeTab = ( $this->httpRequest->getQuery( self::PARAM_TAB ) ?? self::TAB_GENERAL );
654
655 $latteParams = [];
656 if ( self::TAB_PACKET_STATUS_SYNC === $activeTab ) {
657 $latteParams = [ 'form' => $this->createPacketStatusSyncForm() ];
658 } elseif ( self::TAB_AUTO_SUBMISSION === $activeTab ) {
659 $latteParams = [ 'form' => $this->createAutoSubmissionForm() ];
660 } elseif ( self::TAB_GENERAL === $activeTab ) {
661 $latteParams = [ 'form' => $this->create_form() ];
662 }
663
664 if ( ! extension_loaded( 'soap' ) ) {
665 $latteParams['error'] = __( 'This plugin requires an active SOAP library for proper operation. Contact your web hosting administrator.', 'packeta' );
666 }
667
668 $latteParams['apiPasswordLink'] = trim( $this->latte_engine->renderToString( PACKETERY_PLUGIN_DIR . '/template/options/help-block-link.latte', [ 'href' => 'https://client.packeta.com/support' ] ) );
669
670 $latteParams['exportLink'] = add_query_arg(
671 [
672 'page' => self::SLUG,
673 'action' => Exporter::ACTION_EXPORT_SETTINGS,
674 ],
675 get_admin_url( null, 'admin.php' )
676 );
677
678 $latteParams['activeTab'] = ( $this->httpRequest->getQuery( self::PARAM_TAB ) ?? self::TAB_GENERAL );
679 $latteParams['generalTabLink'] = $this->createLink();
680 $latteParams['supportTabLink'] = $this->createLink( self::TAB_SUPPORT );
681 $latteParams['packetStatusSyncTabLink'] = $this->createLink( self::TAB_PACKET_STATUS_SYNC );
682 $latteParams['autoSubmissionTabLink'] = $this->createLink( self::TAB_AUTO_SUBMISSION );
683
684 $latteParams['canValidateSender'] = (bool) $this->optionsProvider->get_sender();
685 $latteParams['senderValidationLink'] = add_query_arg(
686 [
687 'page' => self::SLUG,
688 'action' => self::ACTION_VALIDATE_SENDER,
689 ],
690 get_admin_url( null, 'admin.php' )
691 );
692
693 $lastExport = null;
694 $lastExportOption = get_option( Exporter::OPTION_LAST_SETTINGS_EXPORT );
695 if ( false !== $lastExportOption ) {
696 $date = \DateTime::createFromFormat( DATE_ATOM, $lastExportOption );
697 if ( false !== $date ) {
698 $date->setTimezone( wp_timezone() );
699 $lastExport = $date->format( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) );
700 }
701 }
702 if ( $lastExport ) {
703 $latteParams['lastExport'] = $lastExport;
704 }
705
706 $latteParams['forcePacketCancelDescription'] = __( 'Cancel the order even if the cancellation in the Packeta system will be unsuccessful', 'packeta' );
707 $latteParams['messages'] = $this->messageManager->renderToString( MessageManager::RENDERER_PACKETERY, 'plugin-options' );
708 $latteParams['translations'] = [
709 'packeta' => __( 'Packeta', 'packeta' ),
710 'title' => __( 'Options', 'packeta' ),
711 'general' => __( 'General', 'packeta' ),
712 'packetAutoSubmission' => __( 'Packet auto-submission', 'packeta' ),
713 'packetAutoSubmissionMappingDescription' => __( 'Choose events for payment methods that will trigger packet submission', 'packeta' ),
714 // translators: %s represents URL, keep intact.
715 'apiPasswordCanBeFoundAt%sUrl' => __( 'API password can be found at %s', 'packeta' ),
716 'saveChanges' => __( 'Save changes', 'packeta' ),
717 'validateSender' => __( 'Validate sender', 'packeta' ),
718 'support' => __( 'Support', 'packeta' ),
719 'optionsExportInfo1' => __(
720 'By clicking the button, you will export the settings of your plugin into a separate file. The export does not contain any sensitive information about your e-shop. Please send the resulting file to the technical support of Packeta (you can find the e-mail address here:',
721 'packeta'
722 ),
723 'optionsExportInfo2' => __(
724 ') along with the description of your problem. For a better understanding of your problem, we recommend adding screenshots, which show the problem (if possible).',
725 'packeta'
726 ),
727 'exportPluginSettings' => __( 'Export the plugin settings', 'packeta' ),
728 'settingsExportDatetime' => __( 'Date and time of the last export of settings', 'packeta' ),
729 'settingsNotYetExported' => __( 'The settings have not been exported yet.', 'packeta' ),
730 'senderDescription' => sprintf(
731 /* translators: 1: emphasis start 2: emphasis end 3: client section link start 4: client section link end */
732 esc_html__( 'Fill here %1$ssender label%2$s - you will find it in %3$sclient section%4$s - user information - field \'Indication\'.', 'packeta' ),
733 '<strong>',
734 '</strong>',
735 '<a href="https://client.packeta.com/senders" target="_blank">',
736 '</a>'
737 ),
738 'packagingWeightDescription' => __( 'This parameter is used to determine the weight of the packaging material. This value is automatically added to the total weight of each order that contains products with non-zero weight. This value is also taken into account when evaluating the weight rules in the cart.', 'packeta' ),
739 'defaultWeightDescription' => __( 'This value is automatically added to the total weight of each order that contains products with zero weight.', 'packeta' ),
740 'packetStatusSyncTabLinkLabel' => __( 'Packet status tracking', 'packeta' ),
741 'statusSyncingOrderStatusesLabel' => __( 'Order statuses, for which cron will check the packet status', 'packeta' ),
742 'statusSyncingOrderStatusesDescription' => __( 'Cron will automatically track all orders with these statuses and check if the shipment status has changed.', 'packeta' ),
743 'statusSyncingPacketStatusesLabel' => __( 'Packet statuses that are being checked', 'packeta' ),
744 'statusSyncingPacketStatusesDescription' => __( 'If an order has a shipment with one of these selected statuses, the shipment status will be tracked.', 'packeta' ),
745 'numberOfDaysToCheckDescription' => __( 'Number of days after the creation of an order, during which the order status will be checked.', 'packeta' ),
746 'widgetAutoOpenDescription' => __( 'If this option is active, the widget for selecting pickup points will open automatically after selecting the shipping method at the checkout.', 'packeta' ),
747 'autoOrderStatusChangeDescription' => __( 'Change order status after data submission to Packeta.', 'packeta' ),
748 ];
749
750 $this->latte_engine->render( PACKETERY_PLUGIN_DIR . '/template/options/page.latte', $latteParams );
751 }
752
753 /**
754 * Creates tab link.
755 *
756 * @param string|null $tab Tab ID.
757 * @return string
758 */
759 public function createLink( ?string $tab = null ): string {
760 $params = [
761 'page' => self::SLUG,
762 ];
763
764 if ( null !== $tab ) {
765 $params[ self::PARAM_TAB ] = $tab;
766 }
767
768 return add_query_arg(
769 $params,
770 get_admin_url( null, 'admin.php' )
771 );
772 }
773 }
774