custom/plugins/IwvDatevV6/src/Service/VariablesExporterService.php line 38

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Iwv\IwvDatevV6\Service;
  4. use Doctrine\DBAL\Connection;
  5. use Iwv\IwvDatevV6\Helper\ArrayHelper;
  6. use Iwv\IwvDatevV6\Service\VariablesExporterExt\VariablesExporterConfig;
  7. use Iwv\IwvVariablesHelper\Services\VariablesExporterServiceAbstract;
  8. use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionDefinition;
  9. use Shopware\Core\Checkout\Order\OrderEntity;
  10. use Shopware\Core\Framework\Context;
  11. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  17. class VariablesExporterService extends VariablesExporterServiceAbstract
  18. {
  19.     /** @var Connection */
  20.     protected $connection;
  21.     /** @var EntityRepositoryInterface */
  22.     protected $stateMachineHistoryRepository;
  23.     /** @var EntitySearchResult */
  24.     protected $loadedOrdersDB;
  25.     /** @var Context */
  26.     protected $context;
  27.     /** @var VariablesExporterConfig */
  28.     protected $variablesExporterConfig;
  29.     public function __construct(
  30.         Connection $connection,
  31.         EntityRepositoryInterface $orderRepository,
  32.         EntityRepositoryInterface $stateMachineHistoryRepository
  33.     ) {
  34.         $this->connection $connection;
  35.         $this->orderRepository $orderRepository;
  36.         $this->stateMachineHistoryRepository $stateMachineHistoryRepository;
  37.         parent::__construct($connection);
  38.     }
  39.     /**
  40.      * @param Criteria $criteria
  41.      * @param Context $context
  42.      * @return EntitySearchResult
  43.      */
  44.     public function loadLatestOrders(Criteria $criteriaVariablesExporterConfig $variablesExporterConfigContext $context): EntitySearchResult
  45.     {
  46.         $this->variablesExporterConfig $variablesExporterConfig;
  47.         $associations = [
  48.             'lineItems',
  49.             'transactions',
  50.             'transactions.paymentMethod',
  51.             'transactions.paymentMethod.translations',
  52.             'transactions.stateMachineState',
  53.             'orderCustomer.customer',
  54.             'orderCustomer.customer.group',
  55.             'deliveries',
  56.             'deliveries.stateMachineState',
  57.             'salesChannel.currency',
  58.         ];
  59.         if ($this->variablesExporterConfig->loadField('order_delivery_states')) {
  60.             $associations[] = 'deliveries.stateMachineState.toStateMachineHistoryEntries';
  61.         }
  62.         $criteria->addAssociations($associations);
  63.         if ($this->variablesExporterConfig->loadField('order_delivery_states')) {
  64.             $criteria->getAssociation('deliveries.stateMachineState.toStateMachineHistoryEntries')->setLimit(1)->addSorting(new FieldSorting('createdAt'FieldSorting::DESCENDING));
  65.         }
  66.         $criteria->getAssociation('transactions')->addSorting(new FieldSorting('createdAt'FieldSorting::DESCENDING));
  67.         $this->context $context;
  68.         $this->loadedOrdersDB $this->orderRepository->search($criteria$this->context);
  69.         return $this->loadedOrdersDB;
  70.     }
  71.     /**
  72.      * @param string $orderId
  73.      * @param array $settingsArray [paymentStates]
  74.      * @return array
  75.      * @throws \Exception
  76.      */
  77.     public function getLatestOrderVariables(string $orderId, array $settingsArray): array
  78.     {
  79.         $variablesArray = [];
  80.         /** @var OrderEntity $orderDB */
  81.         $orderDB $this->loadedOrdersDB->get($orderId);
  82.         if (!$orderDB) {
  83.             return $variablesArray;
  84.         }
  85.         $transactions $orderDB->getTransactions();
  86.         $hasTransactions $transactions && $transactions->first();
  87.         $paymentMethod $paymentMethodName '';
  88.         if ($hasTransactions) {
  89.             $customFields $transactions->first()->getCustomFields();
  90.             $paymentCodeArray explode("\\"$transactions->first()->getPaymentMethod()->getHandlerIdentifier());
  91.             $paymentMethod end($paymentCodeArray);
  92.             $paymentCustomFields $transactions->first()->getPaymentMethod()->getCustomFields();
  93.             if ($paymentCustomFields) {
  94.                 $variablesArray array_merge($variablesArrayArrayHelper::arrayFlat($paymentCustomFields'payment_method_cf''_'));
  95.             }
  96.             $paymentMethodName $transactions->first()->getPaymentMethod()->getTranslated() && isset($transactions->first()->getPaymentMethod()->getTranslated()['name']) ? $transactions->first()->getPaymentMethod()->getTranslated()['name'] : '';
  97.             if ($customFields) {
  98.                 $variablesArray array_merge($variablesArrayArrayHelper::arrayFlat($customFields'order_transaction_cf''.'$this->variablesExporterConfig->loadField('order_transaction_cf_export') === 'deep_load'));
  99.                 $variablesArray array_merge($variablesArrayArrayHelper::arrayFlat($customFields'order_transaction_cf''_'$this->variablesExporterConfig->loadField('order_transaction_cf_export') === 'deep_load'));
  100.             }
  101.             if (isset($settingsArray['paymentsErloes'][$transactions->first()->getPaymentMethod()->getId()])) {
  102.                 $variablesArray['{payment_datev_konto}'] = $settingsArray['paymentsErloes'][$transactions->first()->getPaymentMethod()->getId()]['counterAccount'];
  103.             } elseif (isset($settingsArray['paymentsErloes']['default'])) {
  104.                 $variablesArray['{payment_datev_konto}'] = $settingsArray['paymentsErloes']['default']['counterAccount'];
  105.             }
  106.         }
  107.         $variablesArray['{payment_method_cf_datev_gegenkonto}'] = $variablesArray['{payment_datev_konto}'] ?? '';
  108.         $variablesArray['{order_number}'] = $orderDB->getOrderNumber();
  109.         $variablesArray['{order_date}'] = $orderDB->getOrderDateTime()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d');
  110.         $variablesArray['{order_affiliate_code}'] = $orderDB->getAffiliateCode();
  111.         $variablesArray['{order_payment_status}'] = $hasTransactions && $orderDB->getTransactions()->first()->getStateMachineState() ? $orderDB->getTransactions()->first()->getStateMachineState()->getTechnicalName() : '';
  112.         $variablesArray['{order_status}'] = $orderDB->getStateMachineState() ? $orderDB->getStateMachineState()->getTechnicalName() : '';
  113.         $variablesArray['{order_delivery_status}'] = $orderDB->getDeliveries() && $orderDB->getDeliveries()->first() && $orderDB->getDeliveries()->first()->getStateMachineState() ? $orderDB->getDeliveries()->first()->getStateMachineState()->getTechnicalName() : '';
  114.         $variablesArray['{order_customer_comment}'] = $orderDB->getCustomerComment() ?: '';
  115.         $variablesArray['{payment_method}'] = $paymentMethod;
  116.         $variablesArray['{payment_method_name}'] = $paymentMethodName;
  117.         $variablesArray['{customer_number}'] = $orderDB->getOrderCustomer()->getCustomerNumber();
  118.         $variablesArray['{customer_email}'] = $orderDB->getOrderCustomer()->getEmail();
  119.         $customerGroupDB $orderDB->getOrderCustomer()->getCustomer() ? $orderDB->getOrderCustomer()->getCustomer()->getGroup() : '';
  120.         $variablesArray['{customer_group_id}'] = $customerGroupDB $customerGroupDB->getId() : '';
  121.         $variablesArray['{customer_group_name}'] = $customerGroupDB ? ($customerGroupDB->getTranslated()['name'] ?? $customerGroupDB->getName()) : '';
  122.         $variablesArray['{sales_channel_currency}'] = $orderDB->getSalesChannel()->getCurrency()->getIsoCode();
  123.         $variablesArray['{sales_channel_name}'] = $orderDB->getSalesChannel()->getName();;
  124.         $variablesArray['{sales_channel_id}'] = $orderDB->getSalesChannelId();
  125.         $variablesArray['{order_delivery_date}'] = $orderDB->getDeliveries() && $orderDB->getDeliveries()->last() ? $orderDB->getDeliveries()->last()->getShippingDateEarliest()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : '';
  126.         /* order custom fields */
  127.         if ($this->variablesExporterConfig->loadField('order_cf_export') && ($orderCustomFields $orderDB->getCustomFields())) {
  128.             foreach ($orderCustomFields as $pdcfKey => $pdcf) {
  129.                 if (is_string($pdcf) || is_numeric($pdcf)) {
  130.                     $variablesArray['{order_cf_' $pdcfKey '}'] = $pdcf;
  131.                 } elseif (is_bool($pdcf)) {
  132.                     $variablesArray['{order_cf_' $pdcfKey '}'] = $pdcf '1' '0';
  133.                 }
  134.             }
  135.             $variablesArray array_merge($variablesArrayArrayHelper::arrayFlat($orderCustomFields'order_cf''.'$this->variablesExporterConfig->loadField('order_cf_export') === 'deep_load'));
  136.         }
  137.         /* customer group custom fields */
  138.         if ($this->variablesExporterConfig->loadField('customer_group_cf_export') && ($customFields $customerGroupDB && $customerGroupDB->getCustomFields() ? $customerGroupDB->getCustomFields() : false)) {
  139.             foreach ($customFields as $pdcfKey => $pdcf) {
  140.                 if (is_string($pdcf) || is_numeric($pdcf)) {
  141.                     $variablesArray['{customer_group_cf_' $pdcfKey '}'] = $pdcf;
  142.                 } elseif (is_bool($pdcf)) {
  143.                     $variablesArray['{customer_group_cf_' $pdcfKey '}'] = $pdcf '1' '0';
  144.                 }
  145.             }
  146. //            $variablesArray = array_merge($variablesArray, ArrayHelper::arrayFlat($orderCustomFields, 'order_cf', '.', $this->variablesExporterConfig->loadField('order_cf_export') === 'deep_load'));
  147.         }
  148.         /* customer custom fields */
  149.         if ($orderDB->getOrderCustomer() && $orderDB->getOrderCustomer()->getCustomer() && ($customFields $orderDB->getOrderCustomer()->getCustomer()->getCustomFields())) {
  150.             foreach ($customFields as $pdcfKey => $pdcf) {
  151.                 if (is_string($pdcf) || is_numeric($pdcf)) {
  152.                     $variablesArray['{customer_cf_' $pdcfKey '}'] = $pdcf;
  153.                 } elseif (is_bool($pdcf)) {
  154.                     $variablesArray['{customer_cf_' $pdcfKey '}'] = $pdcf '1' '0';
  155.                 }
  156.             }
  157.         }
  158.         if ($this->variablesExporterConfig->loadField('payment_states_export') || isset($settingsArray['paymentRowLegacyExport'])) {
  159.             foreach (
  160.             ($orderDB->getTransactions() ? $this->stateMachineHistoryRepository->search((new Criteria)
  161.                 ->addFilter(new EqualsFilter('entityName'OrderTransactionDefinition::ENTITY_NAME))
  162.                 ->addFilter(new EqualsAnyFilter('entityId.id'$orderDB->getTransactions()->getIds()))
  163.                 ->addFilter(new EqualsAnyFilter('transitionActionName'$settingsArray['paymentStates']['selectStates']))
  164.                 ->addSorting(new FieldSorting('createdAt'FieldSorting::DESCENDING)), $this->context) : []) as $transactionDate
  165.             ) {
  166.                 if (isset($settingsArray['paymentStates']['paid'][$transactionDate->getTransitionActionName()]) && empty($variablesArray['{payment_date}'])) {
  167.                     $variablesArray['{payment_date}'] = $transactionDate->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d');
  168.                 }
  169.                 if (isset($settingsArray['paymentStates']['refunded'][$transactionDate->getTransitionActionName()]) && empty($variablesArray['{refunded_date}'])) {
  170.                     $variablesArray['{refunded_date}'] = $transactionDate->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d');
  171.                 }
  172.             }
  173.         }
  174.         /* delivery states */
  175.         if ($orderDB->getDeliveries() && $orderDB->getDeliveries()->first()) {
  176.             /** @var \Shopware\Core\Checkout\Order\Aggregate\OrderDelivery\OrderDeliveryEntity $deliveryDB */
  177.             $variablesArray['{order_delivery_state}'] = $orderDB->getDeliveries()->first()->getStateMachineState()->getTechnicalName();
  178.             foreach ($orderDB->getDeliveries() as $deliveryDB) {
  179.                 if (empty($variablesArray['{order_tracking_id}']) && ($trackingIds implode(', '$deliveryDB->getTrackingCodes()))) {
  180.                     $variablesArray['{order_tracking_id}'] = $trackingIds;
  181.                 }
  182.                 if ($this->variablesExporterConfig->loadField('order_delivery_states')) {
  183.                     if ($deliveryDB->getStateMachineState()->getTechnicalName() === 'shipped') {
  184.                         $variablesArray['{order_shipped_date}'] = $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries() && $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries()->first() ? $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries()->first()->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ($deliveryDB->getUpdatedAt() ? $deliveryDB->getUpdatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ($deliveryDB->getCreatedAt() ? $deliveryDB->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ''));
  185.                         break 1;
  186.                     } elseif ($deliveryDB->getStateMachineState()->getTechnicalName() === 'shipped_partially') {
  187.                         $variablesArray['{order_shipped_date}'] = $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries() && $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries()->first() ? $deliveryDB->getStateMachineState()->getToStateMachineHistoryEntries()->first()->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ($deliveryDB->getUpdatedAt() ? $deliveryDB->getUpdatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ($deliveryDB->getCreatedAt() ? $deliveryDB->getCreatedAt()->setTimezone(new \DateTimeZone($this->variablesExporterConfig->exportTimeZone))->format('Y-m-d') : ''));
  188.                     }
  189.                 }
  190.             }
  191.         }
  192.         /* sw635 compatibility fix */
  193.         $query 'SELECT platform,special FROM magnalister_orders WHERE current_orders_id = ?';
  194.         $params = [$orderDB->getId()];
  195.         if (isset($settingsArray['hasPluginMagnalister']) && $settingsArray['hasPluginMagnalister'] && ($q method_exists($this->connection'fetchAssociative') ? $this->connection->fetchAssociative($query$params) : $this->connection->fetchAssoc($query$params))) {
  196.             $variablesArray['{channel_name}'] = $q['platform'];
  197.             $variablesArray['{channel_order_number}'] = $q['special'];
  198.         }
  199.         $variablesArray['{currency_factor_order_total}'] = $this->formatPrice($orderDB->getAmountTotal() / $orderDB->getCurrencyFactor());
  200.         return array_merge($this->getOrderPluginVariables($orderDB)['entityVars'], $variablesArray);
  201.     }
  202.     /**
  203.      *
  204.      * @param float $price
  205.      * @return string
  206.      */
  207.     protected function formatPrice($price): string
  208.     {
  209.         return number_format($price2',''');
  210.     }
  211.     /**
  212.      * @param OrderEntity $orderDB
  213.      * @return array[]
  214.      */
  215.     public function getOrderPluginVariables(OrderEntity $orderDB): array
  216.     {
  217.         $entityVars = [];
  218.         foreach ($this->pluginVariables as $plugin) {
  219.             $entityVars array_merge($entityVars$plugin->getVariablesFromOrderDB($orderDB));
  220.         }
  221.         $entityVars['{order_transaction_id}'] = ($entityVars['{paypal_payment_id}'] ?? '') ?: ($entityVars['{payone_transaction_id}'] ?: ($entityVars['{mollie_third_party_payment_id}'] ?: ($entityVars['{klarna_order_id}'] ?: ($entityVars['{easycredit_transaction_id}'] ?: ($entityVars['{swag_amazon_pay_charge_id}'] ?: '')))));
  222.         return [
  223.             'entityVars' => $entityVars,
  224.         ];
  225.     }
  226. }