custom/plugins/theme/src/Core/Content/Flow/Dispatching/Action/SendOrderDataAction.php line 64

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace DonCarneTheme\Core\Content\Flow\Dispatching\Action;
  3. use Monolog\Logger;
  4. use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
  5. use Shopware\Core\Content\Flow\Dispatching\Action\FlowAction;
  6. use Shopware\Core\Content\Media\MediaEntity;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  8. use Shopware\Core\Framework\Event\FlowEvent;
  9. use Shopware\Core\Framework\Event\OrderAware;
  10. use DonCarneTheme\Service\GraphQLClient;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  12. use DateTime;
  13. use Shopware\Core\Checkout\Order\OrderEntity;
  14. use Shopware\Core\Checkout\Order\OrderEvents;
  15. class SendOrderDataAction extends FlowAction
  16. {
  17.     const TRIGGER 'order_inProgress';
  18.     const FEMALE_SALUTATION_ID 'f3183bb9f683437e9f862cbe2b63237e';
  19.     private GraphQLClient $graphQLClient;
  20.     private EntityRepositoryInterface $productRepository;
  21.     private EntityRepositoryInterface $customerGroupRepository;
  22.     private EntityRepositoryInterface $orderAddressRepository;
  23.     private Logger $logger;
  24.     public function __construct(
  25.         GraphQLClient $graphQLClient,
  26.         EntityRepositoryInterface $productRepository,
  27.         EntityRepositoryInterface $customerGroupRepository,
  28.         EntityRepositoryInterface $orderAddressRepository,
  29.         Logger $logger
  30.     ) {
  31.         $this->graphQLClient $graphQLClient;
  32.         $this->productRepository $productRepository;
  33.         $this->customerGroupRepository $customerGroupRepository;
  34.         $this->orderAddressRepository $orderAddressRepository;
  35.         $this->logger $logger;
  36.     }
  37.     public static function getName(): string
  38.     {
  39.         return 'action.send.order.data';
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             self::getName() => 'handle',
  45.         ];
  46.     }
  47.     public function requirements(): array
  48.     {
  49.         return [OrderAware::class];
  50.     }
  51.     public function handle(FlowEvent $event): void
  52.     {
  53.         $orderEvent $event->getEvent();
  54.         if (!$orderEvent instanceof OrderAware) {
  55.             return;
  56.         }
  57.         $orderData = [];
  58.         /** @var OrderEntity $order */
  59.         $order $orderEvent->getOrder();
  60.         $customer $order->getOrderCustomer()->getCustomer();
  61.         $shipping $order->getDeliveries()->first();
  62.         $customFields $order->getCustomFields() ?? [];
  63.         $expectedDelivery $customFields['expected_delivery_date'] ?? date_format($shipping->getShippingDateEarliest(),"Y-m-d");
  64.         $orderData['email'] = $customer->getEmail();
  65.         $orderData['subscriberKey'] = $customer->getEmail();
  66.         $orderData['trigger'] = self::TRIGGER;
  67.         $orderData['order_date'] = date_format($order->getOrderDate(),"Y-m-d");
  68.         $orderData['delivery_date'] = $expectedDelivery;
  69.         $orderData['order_id'] = $order->getOrderNumber();
  70.         $orderData['gender'] = 'M';
  71.         // Billing data
  72.         $criteria = new Criteria([$order->getBillingAddressId()]);
  73.         $criteria->addAssociation('country');
  74.         $billingAddress $this->orderAddressRepository->search($criteria$event->getContext())->first();
  75.         //prior method did not work. Salutation was always empty. Salutation is not available here either, just the id is set
  76.         if($billingAddress->getSalutationId() == self::FEMALE_SALUTATION_ID) {
  77.             $orderData['gender'] = 'F';
  78.         }
  79.         $orderData['billing'] = $this->getBillingData($billingAddress);
  80.         // Shipping data
  81.         $orderData['shipping'] = $this->getShippingData($shipping);
  82.         $orderData['payment_method'] = $order->getTransactions()->first()->getPaymentMethod()->getName();
  83.         $orderData['positions'] = $this->getPositions($order$event)['positions'];
  84.         $orderData['order_sum'] = (string) round($this->getPositions($order$event)['totalPositionsPrice'],2);
  85.         $orderData['shipping_cost'] = (string) $shipping->getShippingCosts()->getTotalPrice();
  86.         $orderData['promotions'] = $this->getPromotions($order$event);
  87.         $orderData['total_order_sum'] = (string) $order->getAmountTotal();
  88.         $orderData['customer_group'] = $this->customerGroupRepository->search(new Criteria([$customer->getGroupId()]), $event->getContext())->first()->getName();
  89.         $orderData['voucher'] = '[]';
  90.         $response $this->graphQLClient->sendOrderData($orderData);
  91.     }
  92.     /* Get all billing infos */
  93.     private function getBillingData($billingAddress) {
  94.         $billingData = [];
  95.         $billingData['firstname'] = $billingAddress->getFirstName();
  96.         $billingData['lastname'] = $billingAddress->getLastName();
  97.         $billingData['company'] = $billingAddress->getCompany() ?: "";
  98.         $billingData['street'] = $billingAddress->getStreet();
  99.         $billingData['postalcode'] = $billingAddress->getZipcode();
  100.         $billingData['city'] = $billingAddress->getCity();
  101.         $billingData['country'] = $billingAddress->getCountry()->getIso();
  102.         return $billingData;
  103.     }
  104.     /* Get all shipping infos */
  105.     private function getShippingData($shipping) {
  106.         $shippingAddress $shipping->getShippingOrderAddress();
  107.         $shippingData = [];
  108.         $shippingData['shipping_firstname'] = $shippingAddress->getFirstName();
  109.         $shippingData['shipping_lastname'] = $shippingAddress->getLastName();
  110.         $shippingData['shipping_company'] = $shippingAddress->getCompany() ?: "";
  111.         $shippingData['shipping_street'] = $shippingAddress->getStreet();
  112.         $shippingData['shipping_postalcode'] = $shippingAddress->getZipcode();
  113.         $shippingData['shipping_city'] = $shippingAddress->getCity();
  114.         $shippingData['shipping_country'] = $shippingAddress->getCountry()->getIso();
  115.         $shippingData['delivery_date'] = date_format($shipping->getShippingDateEarliest(),"Y-m-d");
  116.         $shippingData['delivery_method'] = $shipping->getShippingMethod()->getName();
  117.         $shippingCustomFields $shipping->getShippingMethod()->getCustomFields();
  118.         /* If shipping method has a graphql id redo the delivery options request to retrieve the correct shipping method name and date */
  119.         if ($shippingCustomFields && isset($shippingCustomFields['custom_shipping_graphql_id'])) {
  120.             $availableShippingMethods $this->graphQLClient->getDeliveryOptions($shippingData['shipping_country'], $shippingData['shipping_postalcode']);
  121.             $deliveryGqlOptions json_decode($availableShippingMethods->getResponseBody())->data->deliveryOptions;
  122.             foreach ($deliveryGqlOptions as $deliveryGqlOption) {
  123.                 if ($deliveryGqlOption->id === $shippingCustomFields['custom_shipping_graphql_id']) {
  124.                     $shippingData['delivery_method'] = $deliveryGqlOption->name;
  125.                     $shippingData['delivery_date'] = $this->getNearestDeliveryDate($deliveryGqlOption->dates);
  126.                 }
  127.             }
  128.         }
  129.         return $shippingData;
  130.     }
  131.     /* Get all products data */
  132.     private function getPositions($order$event) {
  133.         $positions = [];
  134.         // We need this variable to calculate the order_sum value
  135.         $positionsPrice 0;
  136.         foreach ($order->getLineItems() as $lineItem) {
  137.             /**
  138.              * @var OrderLineItemEntity $lineItem
  139.              */
  140.             if ($lineItem->getType() === 'product') {
  141.                 $lineItemData = [];
  142.                 $criteria = new Criteria([$lineItem->getProductId()]);
  143.                 $criteria->addAssociation('properties.group');
  144.                 $criteria->addAssociation('media');
  145.                 $criteria->addAssociation('customFields');
  146.                 $product $this->productRepository->search($criteria$event->getContext())->first();
  147.                 $lineItemData['product_condition'] = "";
  148.                 if ($product->getProperties()) {
  149.                     foreach ($product->getProperties() as $property) {
  150.                         $propertyGroupCustomFields $property->getGroup()->getCustomFields();
  151.                         if ($propertyGroupCustomFields &&
  152.                             isset($propertyGroupCustomFields['custom_property_group_is_kuehlbedingung']) &&
  153.                             $propertyGroupCustomFields['custom_property_group_is_kuehlbedingung']
  154.                         ) {
  155.                             $lineItemData['product_condition'] = $property->getName();
  156.                         }
  157.                         if ($propertyGroupCustomFields &&
  158.                             isset($propertyGroupCustomFields['custom_property_group_is_kuehlbedingung']) &&
  159.                             $propertyGroupCustomFields['custom_property_group_is_kuehlbedingung']
  160.                         ) {
  161.                             $lineItemData['product_condition'] = $property->getName();
  162.                         }
  163.                     }
  164.                 }
  165.                 $lineItemData['product_imageurl'] = '';
  166.                 //Cover Image is not available. Therefore cycle through all images and use the one with position 0
  167.                 if($customFields $product->getCustomFields()) {
  168.                     if(!empty($customFields['mail_thumb'])) {
  169.                         $lineItemData['product_imageurl'] = 'https://doncarne.de' $customFields['mail_thumb'];
  170.                     }
  171.                 }
  172.                 if($lineItemData['product_imageurl'] == ''){
  173.                     if ($media $product->getMedia()) {
  174.                         foreach($media as $m) {
  175.                             if($m->getPosition() == 0) {
  176.                                 $lineItemData['product_imageurl'] = $m->getMedia()->getUrl();
  177.                             }
  178.                         }
  179.                         if(empty($lineItemData['product_imageurl'])) {
  180.                             $lineItemData['product_imageurl'] = $product->getMedia()->first()->getMedia()->getUrl();
  181.                         }
  182.                     }
  183.                 }
  184.                 $lineItemData['product_name'] = str_replace(["'",'"''\\'], '',$lineItem->getLabel());
  185.                 $lineItemData['product_weight'] = (string) $product->getWeight();
  186.                 $lineItemData['product_id'] = $product->getProductNumber();
  187.                 $lineItemData['order_amount'] = (string) $lineItem->getQuantity();
  188.                 $lineItemData['product_price_per_amount'] = (string) $lineItem->getUnitPrice();
  189.                 $lineItemData['product_price_total'] = (string) $lineItem->getTotalPrice();
  190.                 $positions[] = addslashes(json_encode($lineItemDataJSON_UNESCAPED_UNICODE));
  191.                 $positionsPrice += $lineItem->getTotalPrice();
  192.             }
  193.             if ($lineItem->getType() == 'easy-coupon') {
  194.                 $lineItemData = [];
  195.                 $lineItemData['product_imageurl'] = '';
  196.                 $lineItemData['product_name'] = 'Gutschein Einlösung';
  197.                 $lineItemData['product_condition'] = "";
  198.                 $lineItemData['product_weight'] = '';
  199.                 $lineItemData['product_id'] = 'voucher' $lineItem->getUnitPrice();
  200.                 $lineItemData['order_amount'] = (string) $lineItem->getQuantity();
  201.                 $lineItemData['product_price_per_amount'] = (string) $lineItem->getUnitPrice();
  202.                 $lineItemData['product_price_total'] = (string) $lineItem->getTotalPrice();
  203.                 $positions[] = addslashes(json_encode($lineItemDataJSON_UNESCAPED_UNICODE));
  204.                 $positionsPrice += $lineItem->getTotalPrice();
  205.             }
  206.             if ($lineItem->getType() == 'dvsn_pseudo_product') {
  207.                 $lineItemData = [];
  208.                 $lineItemData['product_imageurl'] = '';
  209.                 $lineItemData['product_name'] = str_replace(["'",'"''\\'], '',$lineItem->getLabel());
  210.                 $lineItemData['product_condition'] = "";
  211.                 $lineItemData['product_weight'] = '';
  212.                 $lineItemData['product_id'] = '';
  213.                 $lineItemData['order_amount'] = 1;
  214.                 $lineItemData['product_price_per_amount'] = (string) $lineItem->getUnitPrice();
  215.                 $lineItemData['product_price_total'] = (string) $lineItem->getTotalPrice();
  216.                 $positions[] = addslashes(json_encode($lineItemDataJSON_UNESCAPED_UNICODE));
  217.                 $positionsPrice += $lineItem->getTotalPrice();
  218.             }
  219.         }
  220.         $returnData = [
  221.             'positions' => implode(','$positions),
  222.             'totalPositionsPrice' => $positionsPrice
  223.         ];
  224.         return $returnData;
  225.     }
  226.     /* Get all the promotions */
  227.     private function getPromotions($order) {
  228.         $discounts = [];
  229.         foreach ($order->getLineItems() as $lineItem) {
  230.             if ($lineItem->getType() === 'promotion') {
  231.                 $lineItemData = [];
  232.                 $lineItemData['name'] = $lineItem->getLabel();
  233.                 $lineItemData['value'] = (string) (-$lineItem->getTotalPrice());
  234.                 $discounts[] = addslashes(json_encode($lineItemDataJSON_UNESCAPED_UNICODE));
  235.             }
  236.         }
  237.         return implode(','$discounts);
  238.     }
  239.     private function getNearestDeliveryDate($dates)
  240.     {
  241.         $nearestDate null;
  242.         foreach ($dates as $date) {
  243.             $currentDate $date->date;
  244.             if (!$nearestDate || $currentDate $nearestDate) {
  245.                 $nearestDate $currentDate;
  246.             }
  247.         }
  248.         $nearestDate DateTime::createFromFormat("Y-md-"strval($nearestDate));
  249.         return $nearestDate;
  250.     }
  251. }