custom/plugins/IwvDatevV6/src/Subscriber/OrderPaymentStateChangeListener.php line 60

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Iwv\IwvDatevV6\Subscriber;
  3. use Iwv\IwvDatevV6\Core\Content\IwvDatevPayment\IwvDatevPaymentDefinition;
  4. use Iwv\IwvDatevV6\Service\VariablesExporterExt\VariablesExporterConfig;
  5. use Iwv\IwvDatevV6\Service\VariablesExporterService;
  6. use Psr\Log\LoggerInterface;
  7. use Shopware\Core\Framework\Context;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  11. use Shopware\Core\Framework\Uuid\Uuid;
  12. use Shopware\Core\System\StateMachine\Event\StateMachineStateChangeEvent;
  13. use Shopware\Core\System\SystemConfig\SystemConfigService;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. class OrderPaymentStateChangeListener implements EventSubscriberInterface
  16. {
  17.     /** @var EntityRepositoryInterface */
  18.     private $datevPaymentsRepository;
  19.     /** @var EntityRepositoryInterface */
  20.     private $transactionRepository;
  21.     /** @var VariablesExporterService */
  22.     private $variablesExporterService;
  23.     /** @var SystemConfigService */
  24.     private $systemConfigService;
  25.     /**  @var LoggerInterface $logger */
  26.     private $logger;
  27.     public function __construct(
  28.         EntityRepositoryInterface $datevPaymentsRepository,
  29.         EntityRepositoryInterface $transactionRepository,
  30.         VariablesExporterService $variablesExporterService,
  31.         SystemConfigService $systemConfigService,
  32.         LoggerInterface $logger
  33.     ) {
  34.         $this->datevPaymentsRepository $datevPaymentsRepository;
  35.         $this->transactionRepository $transactionRepository;
  36.         $this->variablesExporterService $variablesExporterService;
  37.         $this->systemConfigService $systemConfigService;
  38.         $this->logger $logger;
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             'state_machine.order_transaction.state_changed' => 'onOrderPaymentStateChange',
  44.         ];
  45.     }
  46.     /**
  47.      * @param StateMachineStateChangeEvent $event
  48.      * @return void
  49.      */
  50.     public function onOrderPaymentStateChange(StateMachineStateChangeEvent $event): void
  51.     {
  52.         if ($event->getTransitionSide() !== 'state_enter' || !in_array($event->getStateName(), ['paid''paid_partially''refunded''refunded_partially'])) {
  53.             return;
  54.         }
  55.         try {
  56.             $orderTransactionId $event->getTransition()->getEntityId();
  57.             $criteria = new Criteria([$orderTransactionId]);
  58.             $criteria->addAssociation('order.documents.documentType');
  59.             $criteria->getAssociation('order.documents')->addSorting(new FieldSorting('createdAt'FieldSorting::DESCENDING));
  60.             /** @var \Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity $orderTransactionDB */
  61.             $orderTransactionDB $this->transactionRepository
  62.                 ->search($criteria$event->getContext())
  63.                 ->first();
  64.             /** @var \Shopware\Core\Checkout\Order\OrderEntity $orderDB */
  65.             $orderDB $orderTransactionDB->getOrder();
  66.             if ($orderDB) {
  67.                 $this->variablesExporterService->loadLatestOrders(new Criteria([$orderDB->getId()]), new VariablesExporterConfig(), $event->getContext());
  68.                 $variables $this->variablesExporterService->getLatestOrderVariables($orderDB->getId(), []);
  69.                 $timezone $this->systemConfigService->get('IwvDatevV6.config.exportTimezone'$orderDB->getCurrencyId()) ?: 'Europe/Berlin';
  70.                 $paymentEntryData = [
  71.                     'id' => Uuid::randomHex(),
  72.                     'orderId' => $orderDB->getId(),
  73.                     'orderVersionId' => $orderDB->getVersionId(),
  74.                     'paymentDate' => (new \DateTime)->setTimezone(new \DateTimeZone($timezone))->format('Y-m-d'),
  75.                     'amount' => $orderDB->getAmountTotal() * (in_array($event->getStateName(), ['refunded''refunded_partially']) ? -1),
  76.                     'currencyId' => $orderDB->getCurrencyId(),
  77.                     'paymentMethodId' => $orderTransactionDB->getPaymentMethodId(),
  78.                     'paymentReference' => $variables['{order_transaction_id}'],
  79.                     'isSystem' => true
  80.                 ];
  81.                 $profiles = (array)$this->systemConfigService->get('IwvDatevV6.config.' . ($paymentEntryData['amount'] < 'creditNoteProfileDocuments' 'invoiceProfileDocuments'));
  82.                 if (isset($profiles[0]) && $profiles[0] === 'credit_note,storno') {
  83.                     $profiles = ['credit_note''storno'];
  84.                 }
  85.                 foreach ($orderDB->getDocuments() as $documentDB) {
  86.                     if (in_array($documentDB->getDocumentType()->getTechnicalName(), $profiles)) {
  87.                         $paymentEntryData['documentId'] = $documentDB->getId();
  88.                         break 1;
  89.                     }
  90.                 }
  91.                 $event->getContext()->scope(Context::SYSTEM_SCOPE, function (Context $context) use ($paymentEntryData): void {
  92.                     $this->datevPaymentsRepository->create([$paymentEntryData], $context);
  93.                 });
  94.             }
  95.         } catch (\Throwable $ex) {
  96.             $this->logger->error('Error on creating DATEV Payment: ' $ex->getMessage() . ' ' basename($ex->getFile()) . ':' $ex->getLine());
  97.         }
  98.     }
  99. }