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 / GridExtender.php

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

512 lines 16.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Class GridExtender.
4 *
5 * @package Packetery\Order
6 */
7
8 declare( strict_types=1 );
9
10 namespace Packetery\Module\Order;
11
12 use Packetery\Core;
13 use Packetery\Core\CoreHelper;
14 use Packetery\Latte\Engine;
15 use Packetery\Module\Carrier\CarrierOptionsFactory;
16 use Packetery\Module\ContextResolver;
17 use Packetery\Module\EntityFactory\SizeFactory;
18 use Packetery\Module\Exception\InvalidCarrierException;
19 use Packetery\Module\Framework\WpAdapter;
20 use Packetery\Module\Log\Purger;
21 use Packetery\Module\ModuleHelper;
22 use Packetery\Module\Plugin;
23 use Packetery\Nette\Http\Request;
24 use WC_Order;
25
26 use function esc_html;
27
28 /**
29 * Class GridExtender.
30 *
31 * @package Packetery\Order
32 */
33 class GridExtender {
34
35 private const TEMPLATE_GRID_COLUMN_WEIGHT = PACKETERY_PLUGIN_DIR . '/template/order/grid-column-weight.latte';
36
37 /**
38 * Generic CoreHelper.
39 *
40 * @var CoreHelper
41 */
42 private $coreHelper;
43
44 /**
45 * Latte Engine.
46 *
47 * @var Engine
48 */
49 private $latteEngine;
50
51 /**
52 * Http Request.
53 *
54 * @var Request
55 */
56 private $httpRequest;
57
58 /**
59 * Order repository.
60 *
61 * @var Repository
62 */
63 private $orderRepository;
64
65 /**
66 * Order Validator.
67 *
68 * @var Core\Validator\Order
69 */
70 private $orderValidator;
71
72 /**
73 * Context resolver.
74 *
75 * @var ContextResolver
76 */
77 private $contextResolver;
78
79 /**
80 * Carrier options factory.
81 *
82 * @var CarrierOptionsFactory
83 */
84 private $carrierOptionsFactory;
85
86 /**
87 * WordPress Adapter.
88 *
89 * @var WpAdapter
90 */
91 private $wpAdapter;
92
93 /**
94 * Module helper
95 *
96 * @var ModuleHelper
97 */
98 private $moduleHelper;
99
100 /**
101 * @var SizeFactory
102 */
103 private $sizeFactory;
104
105 /**
106 * @var PacketStatusResolver
107 */
108 private $packetStatusResolver;
109
110 /**
111 * GridExtender constructor.
112 *
113 * @param CoreHelper $coreHelper CoreHelper.
114 * @param Engine $latteEngine Latte Engine.
115 * @param Request $httpRequest Http Request.
116 * @param Repository $orderRepository Order repository.
117 * @param OrderValidatorFactory $orderValidatorFactory Order validator.
118 * @param ContextResolver $contextResolver Context resolver.
119 * @param CarrierOptionsFactory $carrierOptionsFactory Carrier options factory.
120 * @param WpAdapter $wpAdapter WordPress adapter.
121 * @param ModuleHelper $moduleHelper Module helper.
122 * @param SizeFactory $sizeFactory Size factory.
123 * @param PacketStatusResolver $packetStatusResolver Packet status resolver.
124 */
125 public function __construct(
126 CoreHelper $coreHelper,
127 Engine $latteEngine,
128 Request $httpRequest,
129 Repository $orderRepository,
130 OrderValidatorFactory $orderValidatorFactory,
131 ContextResolver $contextResolver,
132 CarrierOptionsFactory $carrierOptionsFactory,
133 WpAdapter $wpAdapter,
134 ModuleHelper $moduleHelper,
135 SizeFactory $sizeFactory,
136 PacketStatusResolver $packetStatusResolver
137 ) {
138 $this->coreHelper = $coreHelper;
139 $this->latteEngine = $latteEngine;
140 $this->httpRequest = $httpRequest;
141 $this->orderRepository = $orderRepository;
142 $this->orderValidator = $orderValidatorFactory->create();
143 $this->contextResolver = $contextResolver;
144 $this->carrierOptionsFactory = $carrierOptionsFactory;
145 $this->wpAdapter = $wpAdapter;
146 $this->moduleHelper = $moduleHelper;
147 $this->sizeFactory = $sizeFactory;
148 $this->packetStatusResolver = $packetStatusResolver;
149 }
150
151 /**
152 * Adds custom filtering links to order grid.
153 *
154 * @param string[] $htmlLinks Array of html links.
155 *
156 * @return string[]
157 */
158 public function addFilterLinks( array $htmlLinks ): array {
159 $linkConfig = new GridLinksConfig(
160 $this->wpAdapter->__( 'Packeta orders to submit', 'packeta' ),
161 $this->wpAdapter->__( 'Packeta orders to print', 'packeta' ),
162 $this->wpAdapter->__( 'Run Packeta wizard', 'packeta' )
163 );
164 $originalLinkConfig = clone $linkConfig;
165 $linkConfig = $this->wpAdapter->applyFilters( 'packeta_order_grid_links_settings', $linkConfig );
166 if ( ! $linkConfig instanceof GridLinksConfig ) {
167 $linkConfig = $originalLinkConfig;
168 }
169
170 if ( $linkConfig->isFilterOrdersToSubmitEnabled() === true ) {
171 $latteParams = [
172 'link' => ModuleHelper::getOrderGridUrl(
173 [
174 'filter_action' => 'packetery_filter_link',
175 'packetery_to_submit' => '1',
176 'packetery_to_print' => false,
177 ]
178 ),
179 'title' => $linkConfig->getFilterOrdersToSubmitTitle(),
180 'orderCount' => $this->orderRepository->countOrdersToSubmit(),
181 'active' => ( $this->httpRequest->getQuery( 'packetery_to_submit' ) === '1' ),
182 ];
183 $htmlLinks['js-wizard-packetery-filter-orders-to-submit'] = $this->latteEngine->renderToString(
184 PACKETERY_PLUGIN_DIR . '/template/order/filter-link.latte',
185 $latteParams
186 );
187 }
188
189 if ( $linkConfig->isFilterOrdersToPrintEnabled() === true ) {
190 $latteParams = [
191 'link' => ModuleHelper::getOrderGridUrl(
192 [
193 'filter_action' => 'packetery_filter_link',
194 'packetery_to_submit' => false,
195 'packetery_to_print' => '1',
196 ]
197 ),
198 'title' => $linkConfig->getFilterOrdersToPrintTitle(),
199 'orderCount' => $this->orderRepository->countOrdersToPrint(),
200 'active' => ( $this->httpRequest->getQuery( 'packetery_to_print' ) === '1' ),
201 ];
202 $htmlLinks['js-wizard-packetery-filter-orders-to-print'] = $this->latteEngine->renderToString(
203 PACKETERY_PLUGIN_DIR . '/template/order/filter-link.latte',
204 $latteParams
205 );
206 }
207
208 if ( $linkConfig->isOrderGridRunWizardEnabled() === true ) {
209 $latteParams = [
210 'link' => $this->wpAdapter->adminUrl( 'admin.php?page=wc-orders&wizard-enabled=true&wizard-order-grid-enabled=true' ),
211 'title' => $this->wpAdapter->__( 'Use this link to start interactive tutorial', 'packeta' ),
212 'escapedText' => '&#9654; ' . htmlspecialchars( $linkConfig->getOrderGridRunWizardTitle() ),
213 ];
214 $htmlLinks['js-wizard-packetery-order-grid-run'] = $this->latteEngine->renderToString(
215 PACKETERY_PLUGIN_DIR . '/template/order/unescaped-link.latte',
216 $latteParams
217 );
218 }
219
220 return $htmlLinks;
221 }
222
223 /**
224 * Adds select to order grid.
225 */
226 public function renderOrderTypeSelect(): void {
227 if ( $this->contextResolver->isOrderGridPage() === false ) {
228 return;
229 }
230
231 $linkFilters = [];
232
233 if ( $this->httpRequest->getQuery( 'packetery_to_submit' ) !== null ) {
234 $linkFilters['packetery_to_submit'] = '1';
235 }
236
237 if ( $this->httpRequest->getQuery( 'packetery_to_print' ) !== null ) {
238 $linkFilters['packetery_to_print'] = '1';
239 }
240
241 $this->latteEngine->render(
242 PACKETERY_PLUGIN_DIR . '/template/order/type-select.latte',
243 [
244 'packeteryOrderType' => $this->httpRequest->getQuery( 'packetery_order_type' ),
245 'linkFilters' => $linkFilters,
246 'translations' => [
247 'packetaMethodType' => __( 'Packeta shipping method', 'packeta' ),
248 'carrierPackets' => __( 'Carrier packets', 'packeta' ),
249 'packetaPickupPointPackets' => __( 'Packeta pickup points packets', 'packeta' ),
250 ],
251 ]
252 );
253 }
254
255 /**
256 * Gets weight cell content.
257 *
258 * @param Core\Entity\Order $order Order.
259 *
260 * @return string
261 */
262 public function getWeightCellContent( Core\Entity\Order $order ): string {
263 return $this->latteEngine->renderToString(
264 self::TEMPLATE_GRID_COLUMN_WEIGHT,
265 $this->getWeightCellContentParams( $order )
266 );
267 }
268
269 /**
270 * Gets weight cell content.
271 *
272 * @param Core\Entity\Order $order Order.
273 *
274 * @return array{orderNumber: null|string, weight: null|float}
275 */
276 private function getWeightCellContentParams( Core\Entity\Order $order ): array {
277 return [
278 'orderNumber' => $order->getNumber(),
279 'weight' => $order->getFinalWeight(),
280 ];
281 }
282
283 /**
284 * Get Order Entity from cache
285 *
286 * @param int $orderId Order ID.
287 *
288 * @return Core\Entity\Order|null
289 * @throws InvalidCarrierException InvalidCarrierException.
290 */
291 private function getOrderByIdCached( int $orderId ): ?Core\Entity\Order {
292 static $ordersCache;
293
294 if ( ! isset( $ordersCache[ $orderId ] ) ) {
295 $ordersCache[ $orderId ] = $this->orderRepository->getById( $orderId );
296 }
297
298 return $ordersCache[ $orderId ] ?? null;
299 }
300
301 /**
302 * Fills custom order list columns.
303 *
304 * @param string|mixed $column Current order column name.
305 * @param WC_Order|int|mixed $wcOrder WC Order.
306 */
307 public function fillCustomOrderListColumns( $column, $wcOrder ): void {
308 if ( is_string( $column ) === false ) {
309 return;
310 }
311
312 if ( $wcOrder instanceof WC_Order ) {
313 $orderId = $wcOrder->get_id();
314 } elseif ( is_numeric( $wcOrder ) ) {
315 $orderId = (int) $wcOrder;
316 } else {
317 return;
318 }
319
320 try {
321 $order = $this->getOrderByIdCached( $orderId );
322 } catch ( InvalidCarrierException $exception ) {
323 if ( $column === 'packetery' ) {
324 echo esc_html( $exception->getMessage() );
325 }
326
327 return;
328 }
329 if ( $order === null ) {
330 return;
331 }
332
333 switch ( $column ) {
334 case 'packetery_weight':
335 $this->latteEngine->render(
336 self::TEMPLATE_GRID_COLUMN_WEIGHT,
337 $this->getWeightCellContentParams( $order )
338 );
339
340 break;
341 case 'packetery_destination':
342 $pickupPoint = $order->getPickupPoint();
343 if ( $pickupPoint !== null ) {
344 $pointName = $pickupPoint->getName();
345 $pointId = $pickupPoint->getId();
346 if ( ! $order->isExternalCarrier() ) {
347 echo esc_html( "$pointName ($pointId)" );
348 } else {
349 echo esc_html( $pointName );
350 }
351
352 break;
353 }
354
355 $homeDeliveryCarrierOptions = $this->carrierOptionsFactory->createByCarrierId( $order->getCarrier()->getId() );
356 echo esc_html( $homeDeliveryCarrierOptions->getName() );
357
358 break;
359 case 'packetery_packet_id':
360 $packetId = $order->getPacketId();
361 $packetClaimId = $order->getPacketClaimId();
362 $latteParams = [
363 'order' => $order,
364 'packetIdTrackingUrl' => null,
365 'packetClaimIdTrackingUrl' => null,
366 'translations' => [
367 'packetClaimTracking' => __( 'Packet claim tracking', 'packeta' ),
368 ],
369 ];
370
371 if ( $packetId !== null ) {
372 $latteParams['packetIdTrackingUrl'] = $this->coreHelper->getTrackingUrl( $packetId );
373 }
374
375 if ( $packetClaimId !== null ) {
376 $latteParams['packetClaimIdTrackingUrl'] = $this->coreHelper->getTrackingUrl( $packetClaimId );
377 }
378
379 $this->latteEngine->render(
380 PACKETERY_PLUGIN_DIR . '/template/order/grid-column-tracking.latte',
381 $latteParams
382 );
383
384 break;
385 case 'packetery':
386 $orderGridParams = $this->httpRequest->getUrl()->getQueryParameters();
387 unset( $orderGridParams['wizard-enabled'], $orderGridParams['wizard-order-grid-enabled'] );
388 $encodedOrderGridParams = rawurlencode( http_build_query( $orderGridParams ) );
389 $packetSubmitUrl = add_query_arg(
390 [
391 PacketActionsCommonLogic::PARAM_ORDER_ID => $order->getNumber(),
392 Plugin::PARAM_PACKETERY_ACTION => PacketActionsCommonLogic::ACTION_SUBMIT_PACKET,
393 PacketActionsCommonLogic::PARAM_REDIRECT_TO => PacketActionsCommonLogic::REDIRECT_TO_ORDER_GRID,
394 Plugin::PARAM_NONCE => wp_create_nonce( PacketActionsCommonLogic::createNonceAction( PacketActionsCommonLogic::ACTION_SUBMIT_PACKET, $order->getNumber() ) ),
395 PacketActionsCommonLogic::PARAM_ORDER_GRID_PARAMS => $encodedOrderGridParams,
396 ],
397 admin_url( 'admin.php' )
398 );
399 $printLink = add_query_arg(
400 [
401 'page' => LabelPrint::MENU_SLUG,
402 LabelPrint::LABEL_TYPE_PARAM => ( $order->isExternalCarrier() ? LabelPrint::ACTION_CARRIER_LABELS : LabelPrint::ACTION_PACKETA_LABELS ),
403 'id' => $order->getNumber(),
404 'packet_id' => $order->getPacketId(),
405 'offset' => 0,
406 PacketActionsCommonLogic::PARAM_ORDER_GRID_PARAMS => $encodedOrderGridParams,
407 ],
408 admin_url( 'admin.php' )
409 );
410 $packetCancelLink = add_query_arg(
411 [
412 PacketActionsCommonLogic::PARAM_ORDER_ID => $order->getNumber(),
413 PacketActionsCommonLogic::PARAM_PACKET_ID => $order->getPacketId(),
414 Plugin::PARAM_PACKETERY_ACTION => PacketActionsCommonLogic::ACTION_CANCEL_PACKET,
415 PacketActionsCommonLogic::PARAM_REDIRECT_TO => PacketActionsCommonLogic::REDIRECT_TO_ORDER_GRID,
416 Plugin::PARAM_NONCE => wp_create_nonce( PacketActionsCommonLogic::createNonceAction( PacketActionsCommonLogic::ACTION_CANCEL_PACKET, $order->getNumber() ) ),
417 PacketActionsCommonLogic::PARAM_ORDER_GRID_PARAMS => $encodedOrderGridParams,
418 ],
419 admin_url( 'admin.php' )
420 );
421
422 $this->latteEngine->render(
423 PACKETERY_PLUGIN_DIR . '/template/order/grid-column-packetery.latte',
424 [
425 'order' => $order,
426 'dimensions' => $this->sizeFactory->createSizeInSetDimensionUnit( $order ),
427 'orderIsSubmittable' => $this->orderValidator->isValid( $order ),
428 'isPossibleExtendPacketPickUpDate' => $order->isPossibleExtendPacketPickUpDate(),
429 'storedUntil' => $this->coreHelper->getStringFromDateTime( $order->getStoredUntil(), CoreHelper::DATEPICKER_FORMAT ),
430 'orderWarningFields' => Form::getInvalidFieldsFromValidationResult( $this->orderValidator->validate( $order ) ),
431 'packetSubmitUrl' => $packetSubmitUrl,
432 'packetCancelLink' => $packetCancelLink,
433 'printLink' => $printLink,
434 'helper' => $this->coreHelper,
435 'datePickerFormat' => CoreHelper::DATEPICKER_FORMAT,
436 'logPurgerDatetimeModifier' => $this->wpAdapter->getOption( Purger::PURGER_OPTION_NAME, Purger::PURGER_MODIFIER_DEFAULT ),
437 'packetDeliverOn' => $this->coreHelper->getStringFromDateTime( $order->getDeliverOn(), CoreHelper::DATEPICKER_FORMAT ),
438 'translations' => [
439 'printLabel' => __( 'Print label', 'packeta' ),
440 'setAdditionalPacketInfo' => __( 'Set additional packet information', 'packeta' ),
441 'setStoredUntil' => __( 'Set the pickup date extension', 'packeta' ),
442 'packetSubmissionNotPossible' => __( 'It is not possible to submit the shipment because all the information required for this shipment is not filled.', 'packeta' ),
443 'submitToPacketa' => __( 'Submit to Packeta', 'packeta' ),
444 // translators: %s: Order number.
445 'reallyCancelPacketHeading' => sprintf( __( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
446 // translators: %s: Packet number.
447 'reallyCancelPacket' => sprintf( __( 'Do you really wish to cancel parcel number %s?', 'packeta' ), (string) $order->getPacketId() ),
448
449 'cancelPacket' => __( 'Cancel packet', 'packeta' ),
450 'lastErrorFromApi' => __( 'Last error from Packeta API', 'packeta' ),
451 ],
452 ]
453 );
454
455 break;
456 case 'packetery_packet_status':
457 echo esc_html( $this->packetStatusResolver->getTranslatedName( $order->getPacketStatus() ) );
458
459 break;
460 case 'packetery_packet_stored_until':
461 $this->latteEngine->render(
462 PACKETERY_PLUGIN_DIR . '/template/order/grid-column-stored-until.latte',
463 [
464 'orderNumber' => $order->getNumber(),
465 'storedUntil' => $this->moduleHelper->getTranslatedStringFromDateTime( $order->getStoredUntil() ) ?? '',
466 ]
467 );
468
469 break;
470 }
471 }
472
473 /**
474 * Add order list columns.
475 *
476 * @param string[] $columns Order list columns.
477 *
478 * @return string[] All columns.
479 */
480 public function addOrderListColumns( array $columns ): array {
481 $newColumns = array();
482
483 foreach ( $columns as $columnName => $columnInfo ) {
484 $newColumns[ $columnName ] = $columnInfo;
485
486 if ( $columnName === 'order_total' ) {
487 $newColumns['packetery_weight'] = __( 'Weight', 'packeta' );
488 $newColumns['packetery'] = __( 'Packeta', 'packeta' );
489 $newColumns['packetery_packet_id'] = __( 'Tracking No.', 'packeta' );
490 $newColumns['packetery_packet_status'] = __( 'Packeta packet status', 'packeta' );
491 $newColumns['packetery_packet_stored_until'] = __( 'Stored until', 'packeta' );
492 $newColumns['packetery_destination'] = __( 'Pickup point or carrier', 'packeta' );
493 }
494 }
495
496 return $newColumns;
497 }
498
499 /**
500 * Add order list sortable columns.
501 *
502 * @param string[] $columns Order list columns.
503 *
504 * @return string[] All columns.
505 */
506 public function makeOrderListSpecificColumnsSortable( array $columns ): array {
507 $metaKey = 'packetery_packet_stored_until';
508
509 return wp_parse_args( [ 'packetery_packet_stored_until' => $metaKey ], $columns );
510 }
511 }
512