src/Core/Checkout/Customer/Subscriber/CustomerMetaFieldSubscriber.php line 55

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Checkout\Customer\Subscriber;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Checkout\Order\OrderDefinition;
  5. use Shopware\Core\Checkout\Order\OrderStates;
  6. use Shopware\Core\Defaults;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\RetryableQuery;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\DeleteCommand;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
  10. use Shopware\Core\Framework\Log\Package;
  11. use Shopware\Core\Framework\Uuid\Uuid;
  12. use Shopware\Core\System\StateMachine\Event\StateMachineTransitionEvent;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. /**
  15.  * @internal
  16.  */
  17. #[Package('customer-order')]
  18. class CustomerMetaFieldSubscriber implements EventSubscriberInterface
  19. {
  20.     /**
  21.      * @internal
  22.      */
  23.     public function __construct(private readonly Connection $connection)
  24.     {
  25.     }
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             StateMachineTransitionEvent::class => 'fillCustomerMetaDataFields',
  30.             PreWriteValidationEvent::class => 'deleteOrder',
  31.         ];
  32.     }
  33.     public function fillCustomerMetaDataFields(StateMachineTransitionEvent $event): void
  34.     {
  35.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  36.             return;
  37.         }
  38.         if ($event->getEntityName() !== 'order') {
  39.             return;
  40.         }
  41.         if ($event->getToPlace()->getTechnicalName() !== OrderStates::STATE_COMPLETED && $event->getFromPlace()->getTechnicalName() !== OrderStates::STATE_COMPLETED) {
  42.             return;
  43.         }
  44.         $this->updateCustomer([$event->getEntityId()]);
  45.     }
  46.     public function deleteOrder(PreWriteValidationEvent $event): void
  47.     {
  48.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  49.             return;
  50.         }
  51.         $orderIds = [];
  52.         foreach ($event->getCommands() as $command) {
  53.             if ($command->getDefinition()->getClass() === OrderDefinition::class
  54.                 && $command instanceof DeleteCommand
  55.             ) {
  56.                 $orderIds[] = Uuid::fromBytesToHex($command->getPrimaryKey()['id']);
  57.             }
  58.         }
  59.         $this->updateCustomer($orderIdstrue);
  60.     }
  61.     /**
  62.      * @param array<string> $orderIds
  63.      */
  64.     private function updateCustomer(array $orderIdsbool $isDelete false): void
  65.     {
  66.         if (empty($orderIds)) {
  67.             return;
  68.         }
  69.         $customerIds $this->connection->fetchFirstColumn(
  70.             'SELECT DISTINCT LOWER(HEX(customer_id)) FROM `order_customer` WHERE order_id IN (:ids) AND order_version_id = :version AND customer_id IS NOT NULL',
  71.             ['ids' => Uuid::fromHexToBytesList($orderIds), 'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION)],
  72.             ['ids' => Connection::PARAM_STR_ARRAY]
  73.         );
  74.         if (empty($customerIds)) {
  75.             return;
  76.         }
  77.         $parameters = [
  78.             'customerIds' => Uuid::fromHexToBytesList($customerIds),
  79.             'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION),
  80.             'state' => OrderStates::STATE_COMPLETED,
  81.         ];
  82.         $types = [
  83.             'customerIds' => Connection::PARAM_STR_ARRAY,
  84.         ];
  85.         $whereOrder '';
  86.         if ($isDelete) {
  87.             $whereOrder 'AND `order`.id NOT IN (:exceptOrderIds)';
  88.             $parameters['exceptOrderIds'] = Uuid::fromHexToBytesList($orderIds);
  89.             $types['exceptOrderIds'] = Connection::PARAM_STR_ARRAY;
  90.         }
  91.         $select '
  92.             SELECT `order_customer`.customer_id as id,
  93.                    COUNT(`order`.id) as order_count,
  94.                    SUM(`order`.amount_total) as order_total_amount,
  95.                    MAX(`order`.order_date_time) as last_order_date
  96.             FROM `order_customer`
  97.             INNER JOIN `order`
  98.                 ON `order`.id = `order_customer`.order_id
  99.                 AND `order`.version_id = `order_customer`.order_version_id
  100.                 AND `order`.version_id = :version
  101.                 ' $whereOrder '
  102.             INNER JOIN `state_machine_state`
  103.                 ON `state_machine_state`.id = `order`.state_id
  104.                 AND `state_machine_state`.technical_name = :state
  105.             WHERE `order_customer`.customer_id IN (:customerIds)
  106.             GROUP BY `order_customer`.customer_id
  107.         ';
  108.         $data $this->connection->fetchAllAssociative($select$parameters$types);
  109.         if (empty($data)) {
  110.             foreach ($customerIds as $customerId) {
  111.                 $data[] = [
  112.                     'id' => Uuid::fromHexToBytes($customerId),
  113.                     'order_count' => 0,
  114.                     'order_total_amount' => 0,
  115.                     'last_order_date' => null,
  116.                 ];
  117.             }
  118.         }
  119.         $update = new RetryableQuery(
  120.             $this->connection,
  121.             $this->connection->prepare('UPDATE `customer` SET order_count = :order_count, order_total_amount = :order_total_amount, last_order_date = :last_order_date WHERE id = :id')
  122.         );
  123.         foreach ($data as $record) {
  124.             $update->execute($record);
  125.         }
  126.     }
  127. }