diff --git a/src/Hooks/HasPdkCheckoutHooks.php b/src/Hooks/HasPdkCheckoutHooks.php index ec4466e1..9e00b134 100644 --- a/src/Hooks/HasPdkCheckoutHooks.php +++ b/src/Hooks/HasPdkCheckoutHooks.php @@ -4,9 +4,11 @@ namespace MyParcelNL\PrestaShop\Hooks; -use MyParcelNL\Pdk\App\Order\Model\PdkOrder; +use Cart; use MyParcelNL\Pdk\Facade\Logger; use MyParcelNL\Pdk\Facade\Pdk; +use MyParcelNL\Pdk\Shipment\Model\DeliveryOptions; +use MyParcelNL\PrestaShop\Facade\EntityManager; use MyParcelNL\PrestaShop\Repository\PsCartDeliveryOptionsRepository; use Throwable; use Tools; @@ -24,57 +26,51 @@ trait HasPdkCheckoutHooks */ public function hookActionCarrierProcess(array $params): void { - $action = Tools::getValue('action'); + $action = Tools::getValue('action'); $carrierId = Tools::getValue('delivery_option'); if (('selectDeliveryOption' !== $action || empty($carrierId)) && ! Tools::isSubmit('confirmDeliveryOption')) { return; } + $this->saveDeliveryOptionsToCart($params['cart']); + } + + /** + * @param \Cart $cart + * + * @return void + */ + private function saveDeliveryOptionsToCart(Cart $cart): void + { $options = Tools::getValue(Pdk::get('checkoutHiddenInputName')); if (! $options || '[]' === $options) { return; } - $cartId = $params['cart']->id ?? null; + /** @var PsCartDeliveryOptionsRepository $cartDeliveryOptionsRepository */ + $cartDeliveryOptionsRepository = Pdk::get(PsCartDeliveryOptionsRepository::class); try { - $pdkOrder = new PdkOrder(['deliveryOptions' => json_decode($options, true)]); + $deliveryOptions = new DeliveryOptions(json_decode($options, true)); - $this->saveOrderData($cartId, $pdkOrder); - } catch (Throwable $e) { - Logger::error( - 'Failed to save order data', + $cartDeliveryOptionsRepository->updateOrCreate( + [ + 'cartId' => $cart->id, + ], [ - 'exception' => $e, - 'options' => $options, - 'cartId' => $cartId, + 'data' => json_encode($deliveryOptions->toStorableArray()), ] ); - } - } - /** - * @param int $cartId - * @param \MyParcelNL\Pdk\App\Order\Model\PdkOrder $order - * - * @return void - * @throws \Doctrine\ORM\ORMException - * @throws \MyParcelNL\Pdk\Base\Exception\InvalidCastException - */ - private function saveOrderData(int $cartId, PdkOrder $order): void - { - /** @var PsCartDeliveryOptionsRepository $cartDeliveryOptionsRepository */ - $cartDeliveryOptionsRepository = Pdk::get(PsCartDeliveryOptionsRepository::class); - - $cartDeliveryOptionsRepository->updateOrCreate( - [ - 'cartId' => $cartId, - ], - [ - 'data' => json_encode($order->toStorableArray()), - ] - ); + EntityManager::flush(); + } catch (Throwable $e) { + Logger::error('Failed to save delivery options to cart', [ + 'exception' => $e, + 'options' => $options, + 'cartId' => $cart->id, + ]); + } } }