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

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