custom/plugins/MasterFFLCheckout/src/Subscriber/DeleteFflAddressSubscriber.php line 25

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace MasterFFL\Checkout\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Psr\Log\LoggerInterface;
  9. class DeleteFflAddressSubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         private readonly EntityRepository $customerAddressRepository,
  13.         private readonly EntityRepository $customerRepository,
  14.         private readonly LoggerInterface  $logger
  15.     ) {}
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced'];
  19.     }
  20.     public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
  21.     {
  22.         $order      $event->getOrder();
  23.         $context    $event->getContext();
  24.         $customerId $order->getOrderCustomer()?->getCustomerId();
  25.         // Get shipping address
  26.         $shippingAddress $order->getDeliveries()->first()?->getShippingOrderAddress();
  27.         if (!$shippingAddress) {
  28.             $this->logger->info('[FFL] No shipping address found in order');
  29.             return;
  30.         }
  31.         // Check if this is an FFL address - FIXED LOGIC
  32.         $customFields $shippingAddress->getCustomFields() ?? [];
  33.         $isFflAddress $customFields['is_ffl_address'] ?? false;
  34.         // Log for debugging
  35.         $this->logger->info('[FFL] Order placed - checking address type', [
  36.             'order_id' => $order->getId(),
  37.             'custom_fields' => $customFields,
  38.             'is_ffl_address' => $isFflAddress
  39.         ]);
  40.         // If NOT an FFL address, skip processing
  41.         if (!$isFflAddress || $isFflAddress !== true) {
  42.             $this->logger->info('[FFL] Not an FFL address, skipping cleanup', [
  43.                 'order_id' => $order->getId(),
  44.                 'is_ffl_address' => $isFflAddress
  45.             ]);
  46.             return;
  47.         }
  48.         if ($customerId === null) {
  49.             $this->logger->warning('[FFL] No customer ID found in order');
  50.             return;
  51.         }
  52.         $this->processFflAddressCleanup($customerId$order->getId(), $context);
  53.     }
  54.     private function processFflAddressCleanup(string $customerIdstring $orderId$context): void
  55.     {
  56.         try {
  57.             // Get all customer addresses
  58.             $addresses $this->customerAddressRepository->search(
  59.                 (new Criteria())->addFilter(new EqualsFilter('customerId'$customerId)),
  60.                 $context
  61.             )->getEntities();
  62.             $fflAddressIds = [];
  63.             $regularAddressIds = [];
  64.             // Separate FFL and regular addresses
  65.             foreach ($addresses as $address) {
  66.                 $customFields $address->getCustomFields() ?? [];
  67.                 $isFflAddress $customFields['is_ffl_address'] ?? false;
  68.                 
  69.                 if ($isFflAddress === true || $isFflAddress === || $isFflAddress === '1') {
  70.                     $fflAddressIds[] = $address->getId();
  71.                 } else {
  72.                     $regularAddressIds[] = $address->getId();
  73.                 }
  74.             }
  75.             $this->logger->info('[FFL] Address analysis', [
  76.                 'customer_id' => $customerId,
  77.                 'order_id' => $orderId,
  78.                 'ffl_addresses' => count($fflAddressIds),
  79.                 'regular_addresses' => count($regularAddressIds)
  80.             ]);
  81.             // If no FFL addresses to clean up, return
  82.             if (empty($fflAddressIds)) {
  83.                 $this->logger->info('[FFL] No FFL addresses found to cleanup');
  84.                 return;
  85.             }
  86.             // If customer has regular addresses, delete FFL addresses and set new default
  87.             if (!empty($regularAddressIds)) {
  88.                 $this->safeDeleteFflAddresses($fflAddressIds$regularAddressIds[0], $customerId$context);
  89.                 
  90.                 $this->logger->info('[FFL] FFL addresses cleaned up successfully', [
  91.                     'customer_id' => $customerId,
  92.                     'order_id' => $orderId,
  93.                     'deleted_ffl_addresses' => $fflAddressIds,
  94.                     'new_default_address' => $regularAddressIds[0]
  95.                 ]);
  96.             } else {
  97.                 // Customer only has FFL addresses - keep one and mark it as regular
  98.                 $this->convertFflAddressToRegular($fflAddressIds[0], $context);
  99.                 
  100.                 $this->logger->warning('[FFL] Customer only had FFL addresses, converted one to regular', [
  101.                     'customer_id' => $customerId,
  102.                     'order_id' => $orderId,
  103.                     'converted_address' => $fflAddressIds[0]
  104.                 ]);
  105.             }
  106.         } catch (\Exception $e) {
  107.             $this->logger->error('[FFL] Error during FFL address cleanup', [
  108.                 'customer_id' => $customerId,
  109.                 'order_id' => $orderId,
  110.                 'error' => $e->getMessage()
  111.             ]);
  112.         }
  113.     }
  114.     private function safeDeleteFflAddresses(array $fflAddressIdsstring $newDefaultIdstring $customerId$context): void
  115.     {
  116.         // Update customer default addresses first
  117.         $this->customerRepository->update([[
  118.             'id' => $customerId,
  119.             'defaultShippingAddressId' => $newDefaultId,
  120.             'defaultBillingAddressId' => $newDefaultId,
  121.         ]], $context);
  122.         // Delete FFL addresses
  123.         $payload array_map(fn ($id) => ['id' => $id], $fflAddressIds);
  124.         $this->customerAddressRepository->delete($payload$context);
  125.     }
  126.     private function convertFflAddressToRegular(string $addressId$context): void
  127.     {
  128.         // Remove FFL flag from address
  129.         $this->customerAddressRepository->update([[
  130.             'id' => $addressId,
  131.             'customFields' => [
  132.                 'is_ffl_address' => false,
  133.                 'converted_from_ffl' => true,
  134.                 'converted_at' => date('Y-m-d H:i:s')
  135.             ]
  136.         ]], $context);
  137.     }
  138. }