custom/plugins/DreiwmBrandstetterPlugin/src/Subscriber/ShippingMethodSubscriber.php line 62

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace DreiwmBrandstetterPlugin\Subscriber;
  3. use DateTime;
  4. use DreiwmBrandstetterPlugin\Service\DateValidator;
  5. use DreiwmBrandstetterPlugin\Service\RadbotenService;
  6. use Exception;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  9. use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressEntity;
  10. use Shopware\Core\Checkout\Order\Aggregate\OrderCustomer\OrderCustomerEntity;
  11. use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection;
  12. use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
  13. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. class ShippingMethodSubscriber implements EventSubscriberInterface
  18. {
  19.     private $flashBag;
  20.     private $cartService;
  21.     private DateValidator $dateValidator;
  22.     private EntityRepository $orderTransactionRepository;
  23.     private RadbotenService $radbotenService;
  24.     private EntityRepository $productRepository;
  25.     public function __construct(
  26.         $flashBag,
  27.         CartService $cartService,
  28.         DateValidator $dateValidator,
  29.         EntityRepository $orderTransactionRepository,
  30.         RadbotenService $radbotenService,
  31.         EntityRepository $productRepository
  32.     ) {
  33.         $this->flashBag $flashBag;
  34.         $this->cartService $cartService;
  35.         $this->dateValidator $dateValidator;
  36.         $this->orderTransactionRepository $orderTransactionRepository;
  37.         $this->radbotenService $radbotenService;
  38.         $this->productRepository $productRepository;
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             // wenn sich der Zahlungsstatus ändert
  44.             'state_machine.order_transaction.state_changed' => 'onOrderTransactionPaid',
  45.         ];
  46.     }
  47.     /**
  48.      * Wird aufgerufen, wenn sich der Zahlungsstatus einer Bestellung ändert
  49.      * Wird gebraucht um die Bestellung an EasyTrans (Radboten) zu senden
  50.      * @param StateMachineStateChangeEvent $event
  51.      * @return void
  52.      * @throws GuzzleException
  53.      */
  54.     public function onOrderTransactionPaid(StateMachineStateChangeEvent $event): void
  55.     {
  56.         if ($event->getStateEventName() === 'state_enter.order_transaction.state.paid') {
  57.             // Lade die Transaktion, um auf die Bestellinformationen zuzugreifen
  58.             $transactionId $event->getTransition()->getEntityId();
  59.             $context $event->getContext();
  60.             $criteria = new Criteria([$transactionId]);
  61.             $criteria->addAssociation('order');
  62.             $criteria->addAssociation('order.addresses');
  63.             $criteria->addAssociation('order.lineItems');
  64.             $criteria->addAssociation('order.deliveries.shippingMethod');
  65.             /**@var OrderTransactionEntity $transaction */
  66.             $transaction $this->orderTransactionRepository->search($criteria$context)->first();
  67.             if (!$transaction || !$transaction->getOrder()) {
  68.                 return;
  69.             }
  70.             // Zugriff auf die Bestellung
  71.             $order $transaction->getOrder();
  72.             // nur Bestellungen mit Radboten-Versandart
  73.             $shippingMethod $order->getDeliveries()->first()->getShippingMethod()->getId();
  74.             if (!$this->dateValidator->isRadbotenShippingMethod($shippingMethod)) {
  75.                 return;
  76.             }
  77.             //hole den Kunden
  78.             /**@var OrderCustomerEntity $customer */
  79.             $customer $order->getOrderCustomer();
  80.             /**@var OrderAddressEntity $customerAddress */
  81.             $customerAddress $order->getDeliveries()->getShippingAddress()->first();
  82.             // hole das Gewicht des Warenkorbs
  83.             $lineItems $order->getLineItems();
  84.             $ls_desiredRadbotenTimeRange $order->getCustomFields()['brandstetter_orders_desired_delivery_timeRange_radboten'];
  85.             // Verwende die Methode calculateTotalWeightAndPackstationMultiplier, um das Gewicht zu berechnen
  86.             $calculatedValues $this->calculateTotalWeightAndPackstationMultiplier($lineItems$context);
  87.             $weight $calculatedValues['totalWeight'];
  88.             // Hole das gewünschte Lieferdatum und das Lieferzeitfenster aus den Custom Fields der Bestellung
  89.             $customFields $order->getCustomFields();
  90.             // Der ursprüngliche Wert von $desiredDeliveryDate
  91.             $originalValue $customFields['brandstetter_orders_desired_delivery_date'] ?? null;
  92.             // Überprüfen, ob ein Wert vorhanden ist
  93.             if ($originalValue !== null) {
  94.                 try {
  95.                     // Erstellen eines DateTime-Objekts aus dem ursprünglichen Wert
  96.                     $date = new DateTime($originalValue);
  97.                     // Formatieren des Datums in das gewünschte Format 'Y-m-d H:i'
  98.                     $formattedDate $date->format('Y-m-d');
  99.                     // Zuweisen des formatierten Datums zu $desiredDeliveryDate
  100.                     $ls_desiredDeliveryDate $formattedDate;
  101.                 } catch (Exception $e) {
  102.                     // @todo Loggen des Fehlers und abbrechen der Bestellung
  103.                     echo "Fehler bei der Datumsumwandlung: " $e->getMessage();
  104.                     $ls_desiredDeliveryDate null;
  105.                 }
  106.             } else {
  107.                 // Kein Wert vorhanden, $desiredDeliveryDate bleibt null
  108.                 $ls_desiredDeliveryDate null;
  109.             }
  110.             // Abstellort
  111.             $pickupLocation $order->getCustomFields()['brandstetter_orders_desired_dropoff_location'];
  112.             if ($pickupLocation !== null) {
  113.                 $pickupLocation ' Abstellort: ' $order->getCustomFields()['brandstetter_orders_desired_dropoff_location'];
  114.             }
  115.             $orderContent = [
  116.                 [
  117.                     'date' => $ls_desiredDeliveryDate,
  118.                     'status' => 'submit',
  119.                     'productno' => $this->calculateProductNumberForRadbotenOrder($ls_desiredDeliveryDate),
  120.                     'email_receiver' => $customer->getEmail(),
  121.                     'order_destinations' => [
  122.                         [
  123.                             "company_name" => "Marktcafé Brandstetter GmbH & Co. KG",
  124.                             "address" => "Marktgasse",
  125.                             "houseno" => "3",
  126.                             "postal_code" => "97070",
  127.                             "city" => "Würzburg",
  128.                         ],
  129.                         [
  130.                             'company_name' => $customerAddress->getCompany(),
  131.                             'contact' => $customerAddress->getFirstName() . ' ' $customerAddress->getLastName(),
  132.                             'address' => $customerAddress->getStreet(),
  133.                             'postal_code' => $customerAddress->getZipcode(),
  134.                             'city' => $customerAddress->getCity(),
  135.                             'delivery_date' => $ls_desiredDeliveryDate,
  136.                             'delivery_time' => explode(' - '$ls_desiredRadbotenTimeRange)[1],
  137.                             'delivery_time_from' => explode(' - '$ls_desiredRadbotenTimeRange)[0],
  138.                             "customer_reference" => 'Ihre Bestellung ' $order->getOrderNumber(),
  139.                             "destination_remark" => $pickupLocation,
  140.                         ],
  141.                     ],
  142.                     'order_packages' => [
  143.                         [
  144.                             'amount' => 1,
  145.                             'weight' => $weight,
  146.                         ]
  147.                     ]
  148.                 ]
  149.             ];
  150.             $this->radbotenService->sendOrderToEasyTrans($orderContent);
  151.         }
  152.     }
  153.     /**
  154.      * Prüfe, ob Packstation ein freies Fach hat
  155.      */
  156.     public
  157.     function checkFreeLockerInPackstation()
  158.     {
  159.         $data = array(
  160.             "api_id" => "6e4k3xhzzrcm067p986891mtwlq54n",
  161.             "api_key" => "f21z374c75730881k2q09mx2qtmt7y",
  162.             "pkkid" => "9323466505932151"
  163.         );
  164.         $ch curl_init('https://api.paketin.de/v1/find/locker/');
  165.         curl_setopt($chCURLOPT_POST1);
  166.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  167.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  168.         curl_setopt($chCURLOPT_CONNECTTIMEOUT30);
  169.         curl_setopt($chCURLOPT_TIMEOUT30); //timeout in seconds
  170.         curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type:application/json'));
  171.         $curl_result curl_exec($ch);
  172.         $result json_decode($curl_result);
  173.         dd($result);
  174.     }
  175.     /**
  176.      * prüft jedes Mal, wenn ein LineItem hinzugefügt oder entfernt wird, ob die Packstation noch ein freies Fach hat
  177.      *
  178.      */
  179.     public
  180.     function checkFreeLockerInPackstationOnCartChange()
  181.     {
  182.         $data = array(
  183.             "api_id" => "6e4k3xhzzrcm067p986891mtwlq54n",
  184.             "api_key" => "f21z374c75730881k2q09mx2qtmt7y",
  185.             "pkkid" => "9323 4665 0593 21519323 4665 0593 2151",
  186.             "boxgroup_id" => "418",
  187.         );
  188.     }
  189.     /**
  190.      * Berechnet die Produkt-Nummer (EayseTrnas) für eine Radboten-Bestellung
  191.      * Wird benötigt, um die Bestellung an EasyTrans zu senden
  192.      * @param $desiredDeliveryDate
  193.      * @return int
  194.      * @throws Exception
  195.      */
  196.     private function calculateProductNumberForRadbotenOrder($desiredDeliveryDate): int
  197.     {
  198.         // ist das Bestelldatum das Lieferdatum? ja: Produkt-Nummer 34, nein: Produkt-Nummer 33
  199.         if ($this->dateValidator->isDeliveryDateToday($desiredDeliveryDate)) {
  200.             return 34;
  201.         } else {
  202.             return 33;
  203.         }
  204.     }
  205.     private function calculateTotalWeightAndPackstationMultiplier(?OrderLineItemCollection $lineItems$context): array
  206.     {
  207.         $totalWeight 0.0;
  208.         $packstationMultiplierSum 0;
  209.         foreach ($lineItems as $lineItem) {
  210.             // Berechnung des Gewichts
  211.             if ($lineItem->getType() === 'product' && $lineItem->getProductId()) {
  212.                 $criteria = new Criteria([$lineItem->getProductId()]);
  213.                 $product $this->productRepository->search($criteria$context)->first();
  214.                 $productWeight 0.0;
  215.                 if ($product) {
  216.                     $productWeight $product->getWeight() ?? 0;
  217.                     // Wenn das Produkt eine Variante ist und kein Gewicht hat, versuche das Gewicht vom Parent zu bekommen
  218.                     if ($product->getParentId() && $productWeight === 0) {
  219.                         $parentCriteria = new Criteria([$product->getParentId()]);
  220.                         $parentProduct $this->productRepository->search($parentCriteria$context)->first();
  221.                         $productWeight $parentProduct $parentProduct->getWeight() ?? 0;
  222.                     }
  223.                 }
  224.                 $lineItemWeight $productWeight $lineItem->getQuantity();
  225.                 $totalWeight += $lineItemWeight;
  226.             }
  227.             // Berechnung des packstationMultipliers aus den Custom Fields
  228. //            $customFields = $lineItem->getPayload()['customFields'] ?? [];
  229. //            if (isset($customFields['packstationMultiplier'])) {
  230. //                $multiplier = $customFields['packstationMultiplier'];
  231. //                $packstationMultiplierSum += $multiplier * $lineItem->getQuantity();
  232. //            }
  233.         }
  234.         // Rückgabe beider Werte in einem Array
  235.         return [
  236.             'totalWeight' => $totalWeight,
  237.             'packstationMultiplierSum' => $packstationMultiplierSum,
  238.         ];
  239.     }
  240. }