custom/plugins/MyCustomFieldNotifier/src/Subscriber/OrderCustomFieldChangeSubscriber.php line 641

Open in your IDE?
  1. <?php
  2. namespace MyCustomFieldNotifier\Subscriber;
  3. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Mailer\MailerInterface;
  6. use Symfony\Component\Mime\Email;
  7. use Psr\Log\LoggerInterface;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  9. use Shopware\Core\Framework\Context;
  10. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  12. use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\Routing\RouterInterface;
  15. use Shopware\Storefront\Page\GenericPageLoadedEvent;
  16. use Shopware\Core\System\SystemConfig\SystemConfigService;
  17. use Shopware\Core\Framework\Struct\ArrayStruct;
  18. use Shopware\Core\Framework\Api\Event\SearchCriteriaEvent;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  20. use src\Core\Content\Cms\CmsPageEvents;
  21. use src\Core\Content\Cms\Events\CmsPageLoadedEvent;
  22. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchedEvent;
  23. use Shopware\Core\Checkout\Order\OrderDefinition;
  24. use Shopware\Core\Framework\Api\Context\AdminApiSource;
  25. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchRequestEvent;
  26. use Shopware\Core\System\Tag\Aggregate\TagEntity;
  27. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  28. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  29. class OrderCustomFieldChangeSubscriber implements EventSubscriberInterface
  30. {
  31.     private MailerInterface $mailer;
  32.     private LoggerInterface $logger;
  33.     private EntityRepositoryInterface $orderRepository;
  34.     private RequestStack $requestStack;
  35.     private SystemConfigService $configService;
  36.     private EntityRepository $userRepository;
  37.     public function __construct(
  38.         MailerInterface $mailer,
  39.         LoggerInterface $logger,
  40.         EntityRepositoryInterface $orderRepository,
  41.         RequestStack $requestStack,
  42.         RouterInterface $router,
  43.         SystemConfigService $configService,
  44.         EntityRepository $userRepository
  45.     ) {
  46.         $this->mailer $mailer;
  47.         $this->logger $logger;
  48.         $this->orderRepository $orderRepository;
  49.         $this->requestStack $requestStack;
  50.         $this->router $router;
  51.         $this->configService $configService;
  52.         $this->userRepository $userRepository;
  53.     }
  54.     public static function getSubscribedEvents(): array
  55.     {
  56.         return [
  57.             'order.written' => 'onOrderWritten',
  58.             CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced',
  59.             CartConvertedEvent::class => 'addCustomFieldsToOrder',
  60.             GenericPageLoadedEvent::class => 'onGenericPageLoaded',
  61.             SearchCriteriaEvent::class => 'onSearchCriteria',
  62.             'cms_page.loaded' => 'onCMSPageLoaded',
  63.             EntitySearchedEvent::class => 'onEntitySearched',
  64.             'order.search.request' => 'onOrderSearchRequest',
  65.         ];
  66.     }
  67. // NEW START
  68. //     public function onOrderWritten(EntityWrittenEvent $event): void
  69. //     {
  70. //         $this->logger->info('TEST23 ENTERED onOrderWritten()');
  71. //         foreach ($event->getWriteResults() as $writeResult) {
  72. //             $payload = $writeResult->getPayload();
  73. //             $this->logger->info('TEST23 ENTERED foreach ($event->getWriteResults()');
  74. //             $payloadString = print_r($payload, true);
  75. //             $this->logger->info('TEST234 $writeResult->getPayload() {payloadString}', [
  76. //                 'payloadString' => $payloadString,
  77. //             ]);
  78.             
  79. //             if ($writeResult->getChangeSet()) {
  80. //                 $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSetString}', [
  81. //                     'changeSetString' => $writeResult->getChangeSet(),
  82. //                 ]);
  83. //             } else {
  84. //                 $this->logger->info('TEST234 ChangeSet IS EMPTY');
  85. //             }
  86. //             // Check if the custom field is present in the payload
  87. //             if (isset($payload['customFields']['custom_downloads_testfield'])) {
  88. //                 $newValue = $payload['customFields']['custom_downloads_testfield'];
  89. //                 // Get the changeset to compare old and new values
  90. //                 $changeSet = $writeResult->getChangeSet();
  91. //                 // if ( !$changeSet ) {$this->logger->info('TEST234 CHANGESET is EMPTY');}
  92.                 
  93. //                 $changeSetString = print_r($changeSet, true);
  94. //                 $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSetString}', [
  95. //                     'changeSetString' => $changeSetString,
  96. //                 ]);
  97. //                 $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSet}', [
  98. //                     'changeSet' => $changeSet,
  99. //                 ]);
  100. //                 if ($changeSet) {
  101. //                     $this->logger->info('ChangeSet detected');
  102. //                     $oldValue = $changeSet->getBefore('customFields')['custom_downloads_testfield'] ?? null;
  103. //                     if ($oldValue !== $newValue) {
  104. //                         // Custom field value has actually changed
  105. //                         $this->logger->info('TEST23 Custom field updated', [
  106. //                             'oldValue' => $oldValue,
  107. //                             'newValue' => $newValue,
  108. //                         ]);
  109. //                         // Send an email to the customer (for demonstration purposes, using dummy email)
  110. //                         $email = (new Email())
  111. //                             ->from('noreply@comentire.de')
  112. //                             ->to('szymanski@comentire.de')  // Replace with actual customer email
  113. //                             ->subject('Your order has been updated')
  114. //                             ->text(sprintf(
  115. //                                 'Dear customer,
  116. // Your order custom field "custom_downloads_testfield" has been updated.
  117. // Old Value: %s
  118. // New Value: %s
  119. // Thank you for your business!
  120. // Best regards,
  121. // Your Company',
  122. //                                 $oldValue,
  123. //                                 $newValue
  124. //                             ));
  125. //                         $this->mailer->send($email);
  126. //                     }
  127. //                 }
  128. //             }
  129. //         }
  130. //     }    
  131. // NEW END    
  132. // OLD START
  133.     public function onOrderWritten(EntityWrittenEvent $event): void
  134.     {
  135.         $this->logger->info('TEST23 ENTERED onOrderWritten() TEST24TEST24TEST24TEST24TEST24TEST24');
  136.         $this->logger->info('TEST23 ENTERED onOrderWritten()');
  137.         foreach ($event->getPayloads() as $payload) {
  138.             if ((isset($payload['customFields']['custom_downloads_download_1']) || isset($payload['customFields']['custom_downloads_download_2'])) && isset($payload['updatedById'])) {
  139.                 $orderId $payload['id'];
  140.                 // $this->logger->info('TEST23 Order custom field change detected', [
  141.                 //     'customFieldName' => 'custom_downloads_testfield',
  142.                 //     'newValue' => $payload['customFields']['custom_downloads_testfield'],
  143.                 //     'orderId' => $orderId,
  144.                 // ]);
  145.                 // Fetch the order to get customer data
  146.                 $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
  147.                 $criteria->addAssociation('orderCustomer'); // Load customer data
  148.                 $order $this->orderRepository->search($criteriaContext::createDefaultContext())->first();
  149.                 if ($order) {
  150.                     $customerEmail $order->getOrderCustomer()->getEmail();
  151.                     $orderNumber $order->getOrderNumber(); // Retrieve the order number
  152.                     // $url = $this->router->generate('frontend.account.order.page', ['orderNumber' => $orderNumber], RouterInterface::ABSOLUTE_URL);
  153.                     $this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
  154.                     $deepLinkCode $order->getDeepLinkCode();
  155.                     $url $this->router->generate(
  156.                         'frontend.account.order.page',
  157.                         [],
  158.                         RouterInterface::ABSOLUTE_URL
  159.                     );
  160.                     $url .= "/" $deepLinkCode;
  161.                     $email = (new Email())
  162.                         ->from('noreply@sw6afg.ce1.eu')
  163.                         ->to($customerEmail)
  164.                         ->subject('New document available')
  165.                         ->text(sprintf(
  166.                             'Hello %s %s,
  167. New documents have been added to your orders / ordered products.
  168. The download section in your order (Order Number: %s) was changed.
  169. Please log in to retrieve them:
  170. %s
  171. You can check your order status at any time in your account under “Orders”.
  172. If you have any questions, please do not hesitate to contact us.
  173. With kind regards,
  174. Your AUTOFLUG FLYWEIGHT® Team',
  175.                             $order->getOrderCustomer()->getFirstName(),
  176.                             $order->getOrderCustomer()->getLastName(),
  177.                             $orderNumber,
  178.                             $url,
  179.                         ));
  180.                     // Convert payload to a readable format
  181.                     $payloadString print_r($payloadtrue);
  182.                     $this->mailer->send($email);
  183.                     $email = (new Email())
  184.                         ->from('noreply@comentire.de')
  185.                         ->addTo('szymanski@comentire.de')
  186.                         ->subject('Order Custom Field Updated')
  187.                         ->text(sprintf(
  188.                             'FOR USER: %s ORDER NUMBER: %s A custom field in your order was updated. PAYLOAD: %s',
  189.                             $customerEmail,
  190.                             $orderNumber,
  191.                             $payloadString
  192.                         ));
  193.                     $this->mailer->send($email);
  194.                 } else {
  195.                     $this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
  196.                 }
  197.             }
  198.             // if (isset($payload['customFields']['custom_downloads_download_1']) && isset($payload['updatedById'])) {
  199.             //     $orderId = $payload['id'];
  200.             //     $this->logger->info('TEST23 Order custom field change detected', [
  201.             //         'customFieldName' => 'custom_downloads_testfield',
  202.             //         'newValue' => $payload['customFields']['custom_downloads_download_1'],
  203.             //         'orderId' => $orderId,
  204.             //     ]);
  205.             //     // Fetch the order to get customer data
  206.             //     $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
  207.             //     $criteria->addAssociation('orderCustomer'); // Load customer data
  208.             //     $order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();
  209.             //     if ($order) {
  210.             //         $customerEmail = $order->getOrderCustomer()->getEmail();
  211.             //         $orderNumber = $order->getOrderNumber(); // Retrieve the order number
  212.             //         $this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
  213.             //         $email = (new Email())
  214.             //             ->from('noreply@comentire.de')
  215.             //             ->to($customerEmail)
  216.             //             ->subject('Order Custom Field Updated')
  217.             //             ->text(sprintf(
  218.             //                 'Dear customer,',
  219.             //                 $orderNumber,
  220.             //                 'custom_downloads_download_1',
  221.             //                 $payload['customFields']['custom_downloads_download_1']
  222.             //             ));
  223.             //         // Convert payload to a readable format
  224.             //         $payloadString = print_r($payload, true);
  225.             //         $this->mailer->send($email);
  226.             //         $email = (new Email())
  227.             //             ->from('noreply@comentire.de')
  228.             //             ->addTo('szymanski@comentire.de')
  229.             //             ->subject('Order Custom Field Updated')
  230.             //             ->text(sprintf(
  231.             //                 'FOR USER: %s ORDER NUMBER: %s The custom field "%s" in your order was updated. New value: %s PAYLOAD: %s',
  232.             //                 $customerEmail,
  233.             //                 $orderNumber,
  234.             //                 'custom_downloads_download_1',
  235.             //                 $payload['customFields']['custom_downloads_download_1'],
  236.             //                 $payloadString
  237.             //             ));
  238.             //         $this->mailer->send($email);
  239.             //     } else {
  240.             //         $this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
  241.             //     }
  242.             // }
  243.             // if (isset($payload['customFields']['custom_downloads_download_2']) && isset($payload['updatedById'])) {
  244.             //     $orderId = $payload['id'];
  245.             //     $this->logger->info('TEST23 Order custom field change detected', [
  246.             //         'customFieldName' => 'custom_downloads_download_2',
  247.             //         'newValue' => $payload['customFields']['custom_downloads_download_2'],
  248.             //         'orderId' => $orderId,
  249.             //     ]);
  250.             //     // Fetch the order to get customer data
  251.             //     $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
  252.             //     $criteria->addAssociation('orderCustomer'); // Load customer data
  253.             //     $order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();
  254.             //     if ($order) {
  255.             //         $customerEmail = $order->getOrderCustomer()->getEmail();
  256.             //         $orderNumber = $order->getOrderNumber(); // Retrieve the order number
  257.             //         $this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
  258.             //         $email = (new Email())
  259.             //             ->from('noreply@comentire.de')
  260.             //             ->to($customerEmail)
  261.             //             ->subject('Order Custom Field Updated')
  262.             //             ->text(sprintf(
  263.             //                 'Dear customer,',
  264.             //                 $orderNumber,
  265.             //                 'custom_downloads_download_2',
  266.             //                 $payload['customFields']['custom_downloads_download_2']
  267.             //             ));
  268.             //         // Convert payload to a readable format
  269.             //         $payloadString = print_r($payload, true);
  270.             //         $this->mailer->send($email);
  271.             //         $email = (new Email())
  272.             //             ->from('noreply@comentire.de')
  273.             //             ->addTo('szymanski@comentire.de')
  274.             //             ->subject('Order Custom Field Updated')
  275.             //             ->text(sprintf(
  276.             //                 'FOR USER: %s ORDER NUMBER: %s The custom field "%s" in your order was updated. New value: %s PAYLOAD: %s',
  277.             //                 $customerEmail,
  278.             //                 $orderNumber,
  279.             //                 'custom_downloads_download_2',
  280.             //                 $payload['customFields']['custom_downloads_download_2'],
  281.             //                 $payloadString
  282.             //             ));
  283.             //         $this->mailer->send($email);
  284.             //     } else {
  285.             //         $this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
  286.             //     }
  287.             // }
  288.         }
  289.     }
  290. // OLD END
  291.     public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
  292.     {
  293.         $this->logger->info('TEST233 ENTERED onCheckoutOrderPlaced()');
  294.         // FIRST TRY START //
  295.         // $order = $event->getOrder();
  296.         // $customFields = $event->getContext()->getRequestDataBag()->get('customFields');
  297.         // if (!empty($customFields['custom_order_fields_customer_reference_ID'])) {
  298.         //     $this->orderRepository->update([
  299.         //         [
  300.         //             'id' => $order->getId(),
  301.         //             'customFields' => [
  302.         //                 'custom_order_fields_customer_reference_ID' => $customFields['custom_order_fields_customer_reference_ID']
  303.         //             ],
  304.         //         ],
  305.         //     ], $event->getContext());
  306.         // }
  307.         // FIRST TRY END //
  308.         // SECOND TRY START //
  309.         // $orderId = $event->getOrderId();
  310.         // $context = $event->getContext();
  311.         // // Fetch the order using its ID
  312.         // $criteria = new Criteria([$orderId]);
  313.         // $order = $this->orderRepository->search($criteria, $context)->first();
  314.         // if (!$order) {
  315.         //     return;
  316.         // }
  317.         // // Get custom field data from request
  318.         // $customFields = $event->getContext()->getRequestDataBag()->get('customFields');
  319.         // if (!empty($customFields['custom_order_fields_customer_reference_ID'])) {
  320.         //     $this->orderRepository->update([
  321.         //         [
  322.         //             'id' => $orderId,
  323.         //             'customFields' => array_merge($order->getCustomFields() ?? [], [
  324.         //                 'custom_order_fields_customer_reference_ID' => $customFields['custom_order_fields_customer_reference_ID']
  325.         //             ]),
  326.         //         ],
  327.         //     ], $context);
  328.         // }   
  329.         // SECOND TRY END //
  330.         $orderId $event->getOrderId();
  331.         $context $event->getContext();
  332.         // Fetch the order using its ID
  333.         $criteria = new Criteria([$orderId]);
  334.         $criteria->addAssociation('orderCustomer'); // Ensure order data is fully loaded
  335.         $order $this->orderRepository->search($criteria$context)->first();
  336.         if (!$order) {
  337.             return;
  338.         }
  339.         // Retrieve existing custom fields
  340.         $existingCustomFields $order->getCustomFields() ?? [];
  341.         if ($order->getCustomFields()) {
  342.             $this->logger->info('TEST233 FOUND $order->getCustomFields()', ['$order->getCustomFields()' => $order->getCustomFields()]);
  343.             //$this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
  344.         }
  345.         else {
  346.             $this->logger->info('TEST233 NOT FOUND $order->getCustomFields()');
  347.         }
  348.         if ($order) {
  349.             $this->logger->info('TEST233 FOUND $order', ['$order' => $order]);
  350.         }
  351.         else {
  352.             $this->logger->info('TEST233 NOT FOUND $order');
  353.         }        
  354.         // Ensure the field exists before modifying
  355.         // if (!isset($existingCustomFields['custom_order_fields_customer_reference_ID'])) {
  356.         //     return;
  357.         // }
  358.         // else {
  359.         //     $this->logger->info('TEST23 FOUND custom_order_fields_customer_reference_ID found');
  360.         // }
  361.         // // Example: Modify the custom field (if needed)
  362.         // $existingCustomFields['custom_order_fields_customer_reference_ID'] .= ' - Processed';
  363.         //TODO DELETE THIS START
  364.         // foreach ($event->getPayloads() as $payload) {
  365.         //     if ( isset($payload['customFields']['custom_order_fields_customer_reference_ID']) ) {
  366.         //         $this->logger->info('TEST233 FOUND custom_order_fields_customer_reference_ID');
  367.         //     }
  368.         // }
  369.         $this->logger->info('TEST233 EVENT: ', ['$event->getOrder()' => $event->getOrder()] );
  370.         $this->logger->info('TEST233 EVENT: ', ['$event->getAvailableData()' => $event->getAvailableData()] );
  371.         $this->logger->info('TEST233 EVENT: ', ['$event->getContext()' => $event->getContext()] );
  372.         $existingCustomFields = [
  373.             "foo" => "bar",
  374.             "bar" => "foo",
  375.             "custom_order_fields_customer_reference_ID" => "#TEST@@@2324",
  376.         ];
  377.         //TODO DELETE THIS END
  378.         // // Update the order with the modified custom field
  379.         // $this->orderRepository->update([
  380.         //     [
  381.         //         'id' => $orderId,
  382.         //         'customFields' => $existingCustomFields,
  383.         //     ],
  384.         // ], $context);
  385.         $this->logger->info('TEST233 FOUND $order', ['$order' => $order]);
  386.         $this->logger->info('TEST233 FOUND $order', ['$order' => $this->orderRepository->search($criteria$context)->first()]);
  387.     }
  388.     public function addCustomFieldsToOrder(CartConvertedEvent $event): void
  389.     {
  390.         $this->logger->info('Subscriber triggered: ');
  391.         dump('Subscriber triggered: ');
  392.         $orderData $event->getConvertedCart();
  393.         $orderCustomFields $orderData['customFields'] ?? [];
  394.        $customerReferenceID $this->requestStack->getCurrentRequest()->request->get('custom_order_fields_customer_reference_ID');
  395.         if ($customerReferenceID) {
  396.             $orderCustomFields['custom_order_fields_customer_reference_ID'] = $customerReferenceID;
  397.         }
  398.         $orderData['customFields'] = $orderCustomFields;
  399.        // $customerReferenceID = $this->requestStack->getCurrentRequest()->request->get('custom_order_fields_comment');
  400.        //  if ($customerReferenceID) {
  401.        //      $orderCustomFields['custom_order_fields_test_textarea'] = $customerReferenceID;
  402.        //  }
  403.        //  $orderData['customFields'] = $orderCustomFields;
  404.         $event->setConvertedCart($orderData);
  405.     }
  406.     // make basicInformation.email accessible in the frontend
  407.     public function onGenericPageLoaded(GenericPageLoadedEvent $event): void
  408.     {
  409.         $this->logger->info'Subscriber triggered: onGenericPageLoaded() ');
  410.         $salesChannelId $event->getSalesChannelContext()->getSalesChannelId();
  411.         $email $this->configService->get('core.basicInformation.email'$salesChannelId);
  412.         $event->getPage()->addExtension('shopEmail', new ArrayStruct([
  413.             'email' => $email
  414.         ]));
  415.     }
  416.     public function onOrderSearchRequest(EntitySearchRequestEvent $event): void
  417.     {
  418.         $this->logger->info'Subscriber triggered: onOrderSearchRequest() ');
  419.         $request $this->requestStack->getCurrentRequest();
  420.         $context $request->attributes->get('sw-context');
  421.         $source $context->getSource();
  422.         if (!$source || $source->getType() !== 'admin') {
  423.             return;
  424.         }
  425.         $user $source->getUser();
  426.         if (!$user) {
  427.             return;
  428.         }
  429.         // Check for a specific ACL role
  430.         $hasRole false;
  431.         foreach ($user->getAclRoles()->getElements() ?? [] as $role) {
  432.             if ($role->getName() === 'testFirma-MRO') {
  433.                 $hasRole true;
  434.                 break;
  435.             }
  436.         }
  437.         if (!$hasRole) {
  438.             return;
  439.         }
  440.         // Apply filter: orders where customer has tag "VIP"
  441.         $criteria $event->getCriteria();
  442.         // Add customer and tags associations
  443.         $criteria->addAssociation('orderCustomer.customer.tags');
  444.         // Filter by customer tag name (make sure it matches exactly)
  445.         $criteria->addFilter(
  446.             new EqualsFilter('orderCustomer.customer.tags.name''testFirma-mro-visible')
  447.         );
  448.     }    
  449.     public function onSearchCriteria(SearchCriteriaEvent $event): void
  450.     {
  451.         $this->logger->info'Subscriber triggered: onSearchCriteria() ');
  452.         // Only act on the "order" entity
  453.         if ($event->getDefinition()->getEntityName() !== 'order') {
  454.             return;
  455.         }
  456.         $context $event->getContext();
  457.         $source $context->getSource();
  458.         if ($source->getType() !== 'admin') {
  459.             return;
  460.         }
  461.         $user $source->getUser();
  462.         if (!$user) {
  463.             return;
  464.         }
  465.         // Check if the user has the specific role
  466.         $hasRole false;
  467.         $aclRoles $user->getAclRoles();
  468.         if ($aclRoles !== null) {
  469.             foreach ($aclRoles->getElements() as $role) {
  470.                 if ($role->getName() === 'order_view_customer_tag_vip') {
  471.                     $hasRole true;
  472.                     break;
  473.                 }
  474.             }
  475.         }
  476.         if (!$hasRole) {
  477.             return;
  478.         }
  479.         // Apply filter: only show orders where customer has tag "VIP"
  480.         $criteria $event->getCriteria();
  481.         // Include the customer tag association
  482.         $criteria->addAssociation('orderCustomer.customer.tags');
  483.         // Filter orders by customer tag
  484.         $criteria->addFilter(
  485.             new EqualsFilter('orderCustomer.customer.tags.name''VIP')
  486.         );
  487.     }
  488.     public function onCMSPageLoaded(): void
  489.     {
  490.         $this->logger->info'Subscriber triggered: onCMSPageLoaded() ');
  491.     }
  492.     public function onEntitySearched(EntitySearchedEvent $event): void
  493.     {
  494.         $this->logger->info'Subscriber triggered: onEntitySearched() ');
  495.         // Only act on orders
  496.         if (!$event->getDefinition() instanceof OrderDefinition) {
  497.             return;
  498.         }
  499.         $context $event->getContext();
  500.         $source $context->getSource();
  501.         // Only apply in Admin API
  502.         if (!$source instanceof AdminApiSource) {
  503.             return;
  504.         }
  505.         $userId $source->getUserId();
  506.         if (!$userId) {
  507.             return;
  508.         }
  509.         // Load user with ACL roles
  510.         $criteria = new Criteria([$userId]);
  511.         $criteria->addAssociation('aclRoles');
  512.         /** @var \Shopware\Core\System\User\UserEntity|null $user */
  513.         $user $this->userRepository->search($criteria$context)->first();
  514.         if (!$user) {
  515.             return;
  516.         }
  517.         // // Check for specific role
  518.         // $hasRole = false;
  519.         // $aclRoles = $user->getAclRoles();
  520.         // if ($aclRoles !== null) {
  521.         //     foreach ($aclRoles->getElements() as $role) {
  522.         //         if ($role->getName() === 'testFirma-MRO') {
  523.         //             $hasRole = true;
  524.         //             break;
  525.         //         }
  526.         //     }
  527.         // }
  528.         // if (!$hasRole) {
  529.         //     return;
  530.         // }
  531.         // // Correct way: add filter to criteria!
  532.         // $criteria = $event->getCriteria();
  533.         // // Example filter: orders whose customers have tag 'VIP'
  534.         // // Here you would need to filter by customer tag, but customer tags are in a related entity
  535.         // // so you'll need an association filter (multi-level filter), something like this:
  536.         // $criteria->addAssociation('orderCustomer.customer.tags');
  537.         // $criteria->addFilter(
  538.         //     new EqualsFilter('orderCustomer.customer.tags.name', 'testFirma-mro-visible')
  539.         // );
  540.         $aclRoles $user->getAclRoles();
  541.         if (!$aclRoles) {
  542.             return;
  543.         }
  544.         $hasMroRole false;
  545.         $tagNamesToShare = [];
  546.         foreach ($aclRoles->getElements() as $role) {
  547.             $roleName $role->getName();
  548.             if ($roleName === 'MRO') {
  549.                 $hasMroRole true;
  550.             }
  551.             if (str_starts_with($roleName'share-tag-')) {
  552.                 // Extract tag name and add to list
  553.                 $tagName substr($roleNamestrlen('share-tag-'));
  554.                 $tagNamesToShare[] = $tagName;
  555.             }
  556.         }
  557.         $this->logger->info('TEST233 FOUND $tagNamesToShare[] = ', ['$tagNamesToShare' => $tagNamesToShare]);
  558.         // Must have both: MRO role and at least one share-tag role
  559.         if (!$hasMroRole || empty($tagNamesToShare)) {
  560.             return;
  561.         }
  562.         // ✅ Filter orders: customer must have any of the tags in $tagNamesToShare
  563.         $criteria $event->getCriteria();
  564.         // Make sure we load customer tags in this search
  565.         $criteria->addAssociation('orderCustomer.customer.tags');
  566.         // Add filter: orders where customer has any of the allowed tags
  567.         $criteria->addFilter(
  568.             new EqualsAnyFilter('orderCustomer.customer.tags.name'$tagNamesToShare)
  569.         );
  570.         // OLD 2
  571.         // // Filter orders: Only include orders where customer has tag "VIP"
  572.         // $filtered = $event->getEntities()->filter(function ($order) {
  573.         //     $orderCustomer = $order->getOrderCustomer();
  574.         //     if (!$orderCustomer) {
  575.         //         return false;
  576.         //     }
  577.         //     $customer = $orderCustomer->getCustomer();
  578.         //     if (!$customer) {
  579.         //         return false;
  580.         //     }
  581.         //     $tags = $customer->getTags();
  582.         //     if (!$tags) {
  583.         //         return false;
  584.         //     }
  585.         //     foreach ($tags as $tag) {
  586.         //         if ($tag->getName() === 'VIP') {
  587.         //             return true;
  588.         //         }
  589.         //     }
  590.         //     return false;
  591.         // });
  592.         // // Overwrite entities with filtered ones
  593.         // $event->getEntities()->clear();
  594.         // foreach ($filtered as $entity) {
  595.         //     $event->getEntities()->add($entity);
  596.         // }
  597.         // OLD
  598.         // // Only act on the "order" entity
  599.         // if (!$event->getDefinition() instanceof OrderDefinition) {
  600.         //     return;
  601.         // }
  602.         // $context = $event->getContext();
  603.         // $source = $context->getSource();
  604.         // if (!$source instanceof AdminApiSource) {
  605.         //     return;
  606.         // }
  607.         // $userId = $source->getUserId();
  608.         // if (!$userId) {
  609.         //     return;
  610.         // }
  611.         //
  612.         //     // Load user with roles
  613.         //     $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$userId]);
  614.         //     $criteria->addAssociation('aclRoles');
  615.         //     /** @var \Shopware\Core\System\User\UserEntity|null $user */
  616.         //     $user = $this->userRepository->search($criteria, $event->getContext())->first();
  617.         //     if (!$user) {
  618.         //         return;
  619.         //     }
  620.         //     // Now you can check roles safely
  621.         //     $hasRole = false;
  622.         //     $aclRoles = $user->getAclRoles();
  623.         //     if ($aclRoles !== null) {
  624.         //         foreach ($aclRoles->getElements() as $role) {
  625.         //             if ($role->getName() === 'order_view_customer_tag_vip') {
  626.         //                 $hasRole = true;
  627.         //                 break;
  628.         //             }
  629.         //         }
  630.         //     }
  631.         //     if (!$hasRole) {
  632.         //         return;
  633.         //     }
  634.         //     // Filter out orders where the customer does NOT have tag "VIP"
  635.         //     $filtered = $event->getEntities()->filter(function ($order) {
  636.         //         $orderCustomer = $order->getOrderCustomer();
  637.         //         if (!$orderCustomer) {
  638.         //             return false;
  639.         //         }
  640.         //         $customer = $orderCustomer->getCustomer();
  641.         //         if (!$customer) {
  642.         //             return false;
  643.         //         }
  644.         //         $tags = $customer->getTags();
  645.         //         foreach ($tags as $tag) {
  646.         //             if ($tag->getName() === 'VIP') {
  647.         //                 return true;
  648.         //             }
  649.         //         }
  650.         //         // If no matching tag, exclude the order
  651.         //         return false;
  652.         //     });
  653.         //     // Override the entity result with the filtered list
  654.         //     $event->getEntities()->clear();
  655.         //     foreach ($filtered as $entity) {
  656.         //         $event->getEntities()->add($entity);
  657.         //     }
  658.     }    
  659. }