PluginProbe
Packeta / 1.4.2
Packeta v1.4.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 1.4.2, at src/Packetery/Module/Order/Metabox.php

409 lines 12.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Class Metabox
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\Helper;
14 use Packetery\Module\Checkout;
15 use Packetery\Module\FormFactory;
16 use Packetery\Module\Log;
17 use Packetery\Module\MessageManager;
18 use Packetery\Module\Options;
19 use Packetery\Module\Plugin;
20 use PacketeryLatte\Engine;
21 use PacketeryNette\Forms\Form;
22 use PacketeryNette\Http\Request;
23
24 /**
25 * Class Metabox
26 *
27 * @package Packetery\Order
28 */
29 class Metabox {
30
31 const FIELD_WEIGHT = 'packetery_weight';
32 const FIELD_ORIGINAL_WEIGHT = 'packetery_original_weight';
33 const FIELD_WIDTH = 'packetery_width';
34 const FIELD_LENGTH = 'packetery_length';
35 const FIELD_HEIGHT = 'packetery_height';
36 const FIELD_ADULT_CONTENT = 'packetery_adult_content';
37 const FIELD_COD = 'packetery_COD';
38 const FIELD_VALUE = 'packetery_value';
39
40 /**
41 * PacketeryLatte engine.
42 *
43 * @var Engine
44 */
45 private $latte_engine;
46
47 /**
48 * Message manager.
49 *
50 * @var MessageManager
51 */
52 private $message_manager;
53
54 /**
55 * Helper.
56 *
57 * @var Helper
58 */
59 private $helper;
60
61 /**
62 * Order form.
63 *
64 * @var Form
65 */
66 private $order_form;
67
68 /**
69 * HTTP request.
70 *
71 * @var Request
72 */
73 private $request;
74
75 /**
76 * Options provider.
77 *
78 * @var Options\Provider
79 */
80 private $optionsProvider;
81
82 /**
83 * Form factory.
84 *
85 * @var FormFactory
86 */
87 private $formFactory;
88
89 /**
90 * Order repository.
91 *
92 * @var Repository
93 */
94 private $orderRepository;
95
96 /**
97 * Log page.
98 *
99 * @var Log\Page
100 */
101 private $logPage;
102
103 /**
104 * Metabox constructor.
105 *
106 * @param Engine $latte_engine PacketeryLatte engine.
107 * @param MessageManager $message_manager Message manager.
108 * @param Helper $helper Helper.
109 * @param Request $request Http request.
110 * @param Options\Provider $optionsProvider Options provider.
111 * @param FormFactory $formFactory Form factory.
112 * @param Repository $orderRepository Order repository.
113 * @param Log\Page $logPage Log page.
114 */
115 public function __construct(
116 Engine $latte_engine,
117 MessageManager $message_manager,
118 Helper $helper,
119 Request $request,
120 Options\Provider $optionsProvider,
121 FormFactory $formFactory,
122 Repository $orderRepository,
123 Log\Page $logPage
124 ) {
125 $this->latte_engine = $latte_engine;
126 $this->message_manager = $message_manager;
127 $this->helper = $helper;
128 $this->request = $request;
129 $this->optionsProvider = $optionsProvider;
130 $this->formFactory = $formFactory;
131 $this->orderRepository = $orderRepository;
132 $this->logPage = $logPage;
133 }
134
135 /**
136 * Registers related hooks.
137 */
138 public function register(): void {
139 add_action(
140 'admin_init',
141 function () {
142 $this->order_form = $this->formFactory->create();
143 $this->add_fields();
144 }
145 );
146 add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
147 add_action( 'save_post', array( $this, 'save_fields' ) );
148 }
149
150 /**
151 * Add metaboxes
152 */
153 public function add_meta_boxes(): void {
154 global $post;
155
156 $order = $this->orderRepository->getById( (int) $post->ID );
157 if ( null === $order ) {
158 return;
159 }
160
161 add_meta_box(
162 'packetery_metabox',
163 __( 'Packeta', 'packeta' ),
164 array(
165 $this,
166 'render_metabox',
167 ),
168 'shop_order',
169 'side',
170 'high'
171 );
172 }
173
174 /**
175 * Adds packetery fields to order form.
176 */
177 public function add_fields(): void {
178 $this->order_form->addHidden( 'packetery_order_metabox_nonce' );
179 $this->order_form->addText( self::FIELD_WEIGHT, __( 'Weight (kg)', 'packeta' ) )
180 ->setRequired( false )
181 ->addRule( $this->order_form::FLOAT, __( 'Provide numeric value!', 'packeta' ) );
182 $this->order_form->addHidden( self::FIELD_ORIGINAL_WEIGHT );
183 $this->order_form->addText( self::FIELD_WIDTH, __( 'Width (mm)', 'packeta' ) )
184 ->setRequired( false )
185 ->addRule( $this->order_form::FLOAT, __( 'Provide numeric value!', 'packeta' ) );
186 $this->order_form->addText( self::FIELD_LENGTH, __( 'Length (mm)', 'packeta' ) )
187 ->setRequired( false )
188 ->addRule( $this->order_form::FLOAT, __( 'Provide numeric value!', 'packeta' ) );
189 $this->order_form->addText( self::FIELD_HEIGHT, __( 'Height (mm)', 'packeta' ) )
190 ->setRequired( false )
191 ->addRule( $this->order_form::FLOAT, __( 'Provide numeric value!', 'packeta' ) );
192 $this->order_form->addCheckbox( self::FIELD_ADULT_CONTENT, __( 'Adult content', 'packeta' ) )
193 ->setRequired( false );
194 $this->order_form->addText( self::FIELD_COD, __( 'Cash on delivery', 'packeta' ) )
195 ->setRequired( false )
196 ->addRule( $this->order_form::FLOAT );
197 $this->order_form->addText( self::FIELD_VALUE, __( 'Order value', 'packeta' ) )
198 ->setRequired( false )
199 ->addRule( $this->order_form::FLOAT );
200
201 foreach ( Checkout::$pickupPointAttrs as $attrs ) {
202 $this->order_form->addHidden( $attrs['name'] );
203 }
204 $this->order_form->addButton( 'packetery_pick_pickup_point', __( 'Choose pickup point', 'packeta' ) );
205 }
206
207 /**
208 * Renders metabox
209 */
210 public function render_metabox(): void {
211 global $post;
212
213 $order = $this->orderRepository->getById( (int) $post->ID );
214 if ( null === $order ) {
215 return;
216 }
217 $packetId = $order->getPacketId();
218
219 $showLogsLink = null;
220 if ( $this->logPage->hasAnyRows( (int) $order->getNumber() ) ) {
221 $showLogsLink = $this->logPage->createLogListUrl( (int) $order->getNumber() );
222 }
223
224 if ( $packetId ) {
225 $packetCancelLink = add_query_arg(
226 [
227 PacketCanceller::PARAM_ORDER_ID => $order->getNumber(),
228 PacketCanceller::PARAM_REDIRECT_TO => PacketCanceller::REDIRECT_TO_ORDER_DETAIL,
229 Plugin::PARAM_PACKETERY_ACTION => PacketCanceller::ACTION_CANCEL_PACKET,
230 Plugin::PARAM_NONCE => wp_create_nonce( PacketCanceller::createNonceAction( PacketCanceller::ACTION_CANCEL_PACKET, $order->getNumber() ) ),
231 ],
232 admin_url( 'admin.php' )
233 );
234
235 $this->latte_engine->render(
236 PACKETERY_PLUGIN_DIR . '/template/order/metabox-overview.latte',
237 [
238 'packetCancelLink' => $packetCancelLink,
239 'packet_id' => $packetId,
240 'packet_tracking_url' => $this->helper->get_tracking_url( $packetId ),
241 'showLogsLink' => $showLogsLink,
242 'translations' => [
243 'packetTrackingOnline' => __( 'Packet tracking online', 'packeta' ),
244 'showLogs' => __( 'Show logs', 'packeta' ),
245 // translators: %s: Order number.
246 'reallyCancelPacketHeading' => sprintf( __( 'Order #%s', 'packeta' ), $order->getCustomNumber() ),
247 // translators: %s: Packet number.
248 'reallyCancelPacket' => sprintf( __( 'Do you really wish to cancel parcel number %s?', 'packeta' ), $packetId ),
249 'cancelPacket' => __( 'Cancel packet', 'packeta' ),
250 ],
251 ]
252 );
253
254 return;
255 }
256
257 $this->order_form->setDefaults(
258 [
259 'packetery_order_metabox_nonce' => wp_create_nonce(),
260 self::FIELD_WEIGHT => $order->getFinalWeight(),
261 self::FIELD_ORIGINAL_WEIGHT => $order->getFinalWeight(),
262 self::FIELD_WIDTH => $order->getWidth(),
263 self::FIELD_LENGTH => $order->getLength(),
264 self::FIELD_HEIGHT => $order->getHeight(),
265 self::FIELD_ADULT_CONTENT => $order->containsAdultContent(),
266 self::FIELD_COD => $order->getCod(),
267 self::FIELD_VALUE => $order->getValue(),
268 ]
269 );
270
271 $prev_invalid_values = get_transient( 'packetery_metabox_nette_form_prev_invalid_values' );
272 if ( $prev_invalid_values ) {
273 $this->order_form->setValues( $prev_invalid_values );
274 $this->order_form->validate();
275 }
276 delete_transient( 'packetery_metabox_nette_form_prev_invalid_values' );
277
278 $widgetSettings = [
279 'packeteryApiKey' => $this->optionsProvider->get_api_key(),
280 'country' => ( $order->getShippingCountry() ? $order->getShippingCountry() : '' ),
281 'language' => substr( get_locale(), 0, 2 ),
282 'isAgeVerificationRequired' => $order->containsAdultContent(),
283 'appIdentity' => Plugin::getAppIdentity(),
284 'weight' => $order->getFinalWeight(),
285 'carriers' => Checkout::getWidgetCarriersParam( $order->isPickupPointDelivery(), $order->getCarrierId() ),
286 'pickupPointAttrs' => Checkout::$pickupPointAttrs,
287 ];
288
289 $this->latte_engine->render(
290 PACKETERY_PLUGIN_DIR . '/template/order/metabox-form.latte',
291 [
292 'form' => $this->order_form,
293 'order' => $order,
294 'orderCurrency' => get_woocommerce_currency_symbol( $order->getCurrency() ),
295 'widgetSettings' => $widgetSettings,
296 'logo' => plugin_dir_url( PACKETERY_PLUGIN_DIR . '/packeta.php' ) . 'public/packeta-symbol.png',
297 'showLogsLink' => $showLogsLink,
298 'hasOrderManualWeight' => $order->hasManualWeight(),
299 'translations' => [
300 'showLogs' => __( 'Show logs', 'packeta' ),
301 'weightIsManual' => __( 'Weight is manually set. To calculate weight remove the field content and save.', 'packeta' ),
302 ],
303 ]
304 );
305 }
306
307 /**
308 * Saves added packetery form fields to order metas.
309 *
310 * @param mixed $orderId Order id.
311 *
312 * @return mixed Order id.
313 * @throws \WC_Data_Exception When invalid data are passed during shipping address update.
314 */
315 public function save_fields( $orderId ) {
316 $order = $this->orderRepository->getById( $orderId );
317 if (
318 null === $order ||
319 ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ||
320 null === $this->request->getPost( 'packetery_order_metabox_nonce' )
321 ) {
322 return $orderId;
323 }
324
325 if ( false === $this->order_form->isValid() ) {
326 set_transient( 'packetery_metabox_nette_form_prev_invalid_values', $this->order_form->getValues( true ) );
327 $this->message_manager->flash_message( __( 'Packeta: entered data is not valid!', 'packeta' ), MessageManager::TYPE_ERROR );
328
329 return $orderId;
330 }
331
332 $values = $this->order_form->getValues( 'array' );
333
334 if ( ! wp_verify_nonce( $values['packetery_order_metabox_nonce'] ) ) {
335 $this->message_manager->flash_message( __( 'Session has expired! Please try again.', 'packeta' ), MessageManager::TYPE_ERROR );
336
337 return $orderId;
338 }
339
340 if ( ! current_user_can( 'edit_post', $orderId ) ) {
341 $this->message_manager->flash_message( __( 'You do not have sufficient rights to make changes!', 'packeta' ), MessageManager::TYPE_ERROR );
342
343 return $orderId;
344 }
345
346 $propsToSave = [
347 self::FIELD_WIDTH => ( is_numeric( $values[ self::FIELD_WIDTH ] ) ? (float) number_format( $values[ self::FIELD_WIDTH ], 0, '.', '' ) : null ),
348 self::FIELD_LENGTH => ( is_numeric( $values[ self::FIELD_LENGTH ] ) ? (float) number_format( $values[ self::FIELD_LENGTH ], 0, '.', '' ) : null ),
349 self::FIELD_HEIGHT => ( is_numeric( $values[ self::FIELD_HEIGHT ] ) ? (float) number_format( $values[ self::FIELD_HEIGHT ], 0, '.', '' ) : null ),
350 ];
351
352 if ( ! is_numeric( $values[ self::FIELD_WEIGHT ] ) ) {
353 $propsToSave[ self::FIELD_WEIGHT ] = null;
354 } elseif ( (float) $values[ self::FIELD_WEIGHT ] !== (float) $values[ self::FIELD_ORIGINAL_WEIGHT ] ) {
355 $propsToSave[ self::FIELD_WEIGHT ] = (float) $values[ self::FIELD_WEIGHT ];
356 }
357
358 if ( $values[ Checkout::ATTR_POINT_ID ] && $order->isPickupPointDelivery() ) {
359 $wcOrder = wc_get_order( $orderId ); // Can not be false due condition at the beginning of method.
360 foreach ( Checkout::$pickupPointAttrs as $pickupPointAttr ) {
361 $value = $values[ $pickupPointAttr['name'] ];
362
363 if ( Checkout::ATTR_CARRIER_ID === $pickupPointAttr['name'] ) {
364 $value = ( ! empty( $values[ Checkout::ATTR_CARRIER_ID ] ) ? $values[ Checkout::ATTR_CARRIER_ID ] : \Packetery\Module\Carrier\Repository::INTERNAL_PICKUP_POINTS_ID );
365 }
366
367 $propsToSave[ $pickupPointAttr['name'] ] = $value;
368
369 if ( $this->optionsProvider->replaceShippingAddressWithPickupPointAddress() ) {
370 Checkout::updateShippingAddressProperty( $wcOrder, $pickupPointAttr['name'], (string) $value );
371 }
372 }
373 $wcOrder->save();
374 }
375
376 $orderSize = $order->getSize();
377 if ( null === $orderSize ) {
378 $orderSize = new Core\Entity\Size();
379 }
380
381 foreach ( $propsToSave as $attrName => $attrValue ) {
382 switch ( $attrName ) {
383 case self::FIELD_WEIGHT:
384 $order->setWeight( $attrValue );
385 break;
386 case self::FIELD_WIDTH:
387 $orderSize->setWidth( $attrValue );
388 break;
389 case self::FIELD_LENGTH:
390 $orderSize->setLength( $attrValue );
391 break;
392 case self::FIELD_HEIGHT:
393 $orderSize->setHeight( $attrValue );
394 break;
395 }
396 }
397
398 $order->setAdultContent( $values[ self::FIELD_ADULT_CONTENT ] );
399 $order->setCod( is_numeric( $values[ self::FIELD_COD ] ) ? Helper::simplifyFloat( $values[ self::FIELD_COD ], 10 ) : null );
400 $order->setValue( is_numeric( $values[ self::FIELD_VALUE ] ) ? Helper::simplifyFloat( $values[ self::FIELD_VALUE ], 10 ) : null );
401
402 $order->setSize( $orderSize );
403 Checkout::updateOrderEntityFromPropsToSave( $order, $propsToSave );
404 $this->orderRepository->save( $order );
405
406 return $orderId;
407 }
408 }
409