custom/plugins/SteincoProducts/src/Subscriber/OrderEventsSubscriber.php line 100

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Schoettler\SteincoProducts\Subscriber;
  3. use Schoettler\SteincoProducts\SharedFunctions;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  6. use Shopware\Core\Checkout\Order\OrderEvents;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  8. use Shopware\Core\System\SystemConfig\SystemConfigService;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  12. use DateTimeImmutable;
  13. use DateTimeInterface;
  14. // Rechnung immer zuerst
  15. class OrderEventsSubscriber implements EventSubscriberInterface {
  16.     public static function getSubscribedEvents() : array 
  17.     {
  18.         // Return the events to listen to as array like this:  <event to listen to> => <method to execute>
  19.         return [
  20.             OrderEvents::ORDER_WRITTEN_EVENT => 'onOrderWritten',
  21.             'document.written' => 'onDocumentWritten'
  22.         ];
  23.     }
  24.     Private $DOK_RECHNUNG "IRGVK";
  25.     Private $DOK_LIEFERSCHEIN "ILSVK";
  26.     Private $DOK_GUTSCHRIFT "IGUVK";
  27.     Private $DOK_RECHNUNGSSTORNO "IGUVK";
  28.     Private $DOK_GUTSCHRIFTSTORNO "IGUST";
  29.     Private $DOK_AUFTRAGBESTAETIGUNG "IABVK";
  30.     Private $LINEBREAK "\r\n";
  31.     private $context;
  32.     /**
  33.      * @var SystemConfigService
  34.      */
  35.     private $systemConfigService;
  36.     /**
  37.      * @var EntityRepository
  38.      */
  39.     private $customerRepository;
  40.     /**
  41.      * @var EntityRepository
  42.      */
  43.     private $orderRepository;
  44.     /**
  45.      * @var EntityRepository
  46.      */
  47.     private $documentRepository;
  48.     /**
  49.      * @var EntityRepository
  50.      */
  51.     private $propertyOptionRepository;
  52.     
  53.     /**
  54.      * @var EntityRepository
  55.      */
  56.     private $propertyRepository;
  57.     /**
  58.      * @var DocumentService
  59.      */
  60.     protected $documentService;
  61.      /**
  62.      * @var EntityRepository
  63.      */
  64.     private  $mediaRepository;
  65.     public function __construct(SystemConfigService $systemConfigService,
  66.     EntityRepository $customerRepositoryEntityRepository $orderRepository,
  67.      EntityRepository $documentRepositoryEntityRepository $propertyOptionRepository,
  68.      EntityRepository $propertyRepository$docService$mediaRepository)
  69.     {
  70.         $this->systemConfigService $systemConfigService;
  71.         $this->customerRepository $customerRepository;
  72.         $this->orderRepository $orderRepository;
  73.         $this->documentRepository $documentRepository;
  74.         $this->propertyOptionRepository $propertyOptionRepository;
  75.         $this->propertyRepository $propertyRepository;
  76.         $this->documentService $docService;
  77.         $this->mediaRepository $mediaRepository;
  78.         //$this->urlGenerator = $urlGenerator;
  79.     }
  80.     public function onOrderWritten(EntityWrittenEvent $event
  81.     {
  82.         //Database
  83.         $dbHost $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
  84.         $dbUser $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
  85.         $dbPass $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
  86.         $dbName $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseName');
  87.         $mysqli = new \mysqli($dbHost$dbUser$dbPass$dbName);
  88.         if($mysqli->connect_errno ) {
  89.             // Log the error somehow
  90.             //dump($mysqli->connect_errno);
  91.         }  
  92.         $orderUUID $event->getWriteResults()[0]->getPrimaryKey();
  93.         $myContext $event->getContext();
  94.         $this->context $myContext ?? \Shopware\Core\Framework\Context::createDefaultContext();
  95.         $orderCriteria = new Criteria([]);
  96.         $orderCriteria->addAssociation('currency')->addAssociation('billingAddress')->addFilter(new EqualsFilter('id'$orderUUID));
  97.        
  98.         $order_searchresult $this->orderRepository->search(
  99.             $orderCriteria,
  100.            \Shopware\Core\Framework\Context::createDefaultContext());
  101.         
  102.         $order $order_searchresult->getEntities()->getElements()[$orderUUID];
  103.         // TODO: if order is empty
  104.         $order_number $order->getOrderNumber();
  105.         $customer_number $order->getOrderCustomer()->getCustomerNumber();
  106.     //dump($order_searchresult, $order);
  107.         // check if the order is already present in the Shop2DWH_Erstbesteller table
  108.         $check_erstbesteller_sql 'SELECT NOT EXISTS (SELECT * FROM Shop2DWH_Erstbesteller WHERE Kundennummer = "' 
  109.         .$customer_number .'" ) AS firstorder';
  110.         if($check_erstbesteller_query $mysqli->query($check_erstbesteller_sql)) {
  111.             $row mysqli_fetch_array($check_erstbesteller_query);
  112.             $no_entry_exists $row['firstorder'];
  113.             $check_erstbesteller_query->close();
  114.             $firstorderDate $order->getCreatedAt();
  115.             $erstbestelldatum $firstorderDate->format('Y-m-d H:i:s');
  116.             if($no_entry_exists == 1) {
  117.                 // first order by this Customer, write to Shop2DWH_Erstbesteller
  118.                 $sql 'INSERT INTO Shop2DWH_Erstbesteller (Kundennummer, order_id, Erstbestelldatum)' 
  119.                 .' VALUES ("' .$customer_number .'", "' .$order_number .'", "' .$erstbestelldatum .'" )';
  120.                 if(! $mysqli->query($sql)){
  121.                     //dump(mysqli_error($mysqli), $sql, $customer);
  122.                 }
  123.             }
  124.         } else {
  125.             //TODO: query failed
  126.         }
  127.     }
  128.     public function onDocumentWritten(EntityWrittenEvent $event){
  129.         SharedFunctions::dumpToLog("onDocumentWritten()");
  130.         //get DB-related data
  131.         $dbHost $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
  132.         $dbUser $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
  133.         $dbPass $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
  134.         $dbName $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseName');
  135.        
  136.         // each document should only be written once, so all data must be present at this event
  137.         $myContext $event->getContext();
  138.         $this->context $myContext ?? \Shopware\Core\Framework\Context::createDefaultContext();
  139.         $writeResult $event->getWriteResults();
  140.         $writeResult reset($writeResult);
  141.         $writeResult $writeResult->getPayload(); 
  142.         // SharedFunctions::dumpToLog($writeResult);
  143.         $orderUUID $writeResult['orderId'];
  144.         $orderVersionUUID $writeResult['orderVersionId']; // probably not needed
  145.         $documentUUID $writeResult['id'];
  146.         // get the document including type
  147.         $documentCritera = new Criteria([]);
  148.         $documentCritera->addAssociation("documentType")->addFilter(New EqualsFilter('id'$documentUUID));
  149.         $document_searchresult $this->documentRepository->search(
  150.             $documentCritera,
  151.             $myContext
  152.         );
  153.         $document $document_searchresult->getEntities()->getElements()[$documentUUID];
  154. //dump($document_searchresult->getEntities()->getElements()[$documentUUID],$documentUUID,$document_searchresult->getEntities()->getElements());
  155.         // we only want Rechnung, Storno, Gutschrift for the bulk of data
  156.         $documentTechnicalName $document->getDocumentType()->getTechnicalName();
  157.         $invoice_types = ['invoice'];
  158.         $creditNote_types = ['credit_note''storno'];
  159.         // if the document is just created, we need to create a copy of the pdf and create a jpl-file
  160.         // pass document and order
  161. //dump("copying document");
  162.         if(!empty($orderUUID)){
  163.         $this->writeFilesToExchangeFolder($orderUUID$document);
  164. //dump("copied document");
  165.         // delivery_note => Lieferschein
  166.         if ($documentTechnicalName == 'delivery_note'){
  167.             // delivery_note is created after invoice by design, 
  168.             // we just use it to update the Lieferschein field in existing entries
  169.             // UPDATE Shop2DWH_BelegPosition Set Lieferschein = $belegnummer WHERE BelegkopfId = $belegkopfId
  170.             // To retrieve BelegkopfId we need the invoice, which we can get using Bestellnr
  171.             $order $this->getOrder($orderUUID);
  172.             $orderNumber $order->getOrderNumber();
  173.             $documentCriteria = new Criteria();
  174.             $documentCriteria->addFilter(new EqualsFilter('orderId'$orderUUID));
  175.             
  176.             $documents $this->documentRepository->search($documentCriteria$this->context);
  177.             // loop over the docs and update Belegpositionen
  178.             $documentEntities $documents->getEntities()->getElements();
  179.             $whereClause ' WHERE LieferscheinNr ';
  180.             $numberOfElemets sizeof($documentEntities);
  181. //dump("trying to update delivery-note");
  182.             If($numberOfElemets 0){
  183.                 If ($numberOfElemets == 1) {
  184.                     $doc reset($documentEntities);
  185.                     $whereClause .= '= "' .$doc->getConfig()['documentNumber'] .'" ';
  186.                 } elseif ($numberOfElemets 1) {
  187.                     $whereClause .= 'IN(';
  188.                     foreach ($documentEntities as $oldDocuments) {
  189.                         $whereClause .= '"' .$oldDocuments->getConfig()['documentNumber'] .'", ';
  190.                     }
  191.                     $whereClause substr($whereClause0strlen($whereClause) - 2);
  192.                     $whereClause .= ') ';
  193.                 }
  194.                 $updateSQL 'UPDATE Shop2DWH_Belegposition SET LieferscheinNr = "' .$writeResult['config']['documentNumber'] .'" ' .$whereClause;
  195.                 
  196.                 $mysqli = new \mysqli($dbHost$dbUser$dbPass$dbName);
  197.                 if($mysqli->connect_errno ) {
  198.                     // Log the error somehow
  199.                     //dump($mysqli->connect_errno);
  200.                 }
  201.                 if(! $mysqli->query($updateSQL)){
  202.                  //dump(mysqli_error($mysqli), $updateSQL);
  203.                 }
  204.             }
  205.         }
  206.         if(in_array($documentTechnicalName$invoice_types) || in_array($documentTechnicalName$creditNote_types))
  207.         {
  208.             SharedFunctions::dumpToLog("Creating BelegkopfSQL");
  209.             // get the order including currency and billing-address and shipping-address
  210.             $order $this->getOrder($orderUUID);
  211.             $zahlungsart $this->getZahlungsart($orderUUID$orderVersionUUID$order->getLanguageId());
  212.             
  213.             $dummy_time strtotime('2999-12-31');
  214.             $dummy_date date('Y-m-d H:i:s'$dummy_time);
  215.             $bestellnummer $order->getOrderNumber();
  216.             $belegwaehrung $order->getCurrency()->getIsoCode();
  217.             $billing_address_country $order->getBillingAddress()->getCountry()->getIso3();
  218.             // get necessary Data for Belegkopf and write to external DB
  219.             $belegart in_array($documentTechnicalName$creditNote_types)? 'GAS' 'RAS'//"RAS"; // possible values: RAS, GAS (Rechnungs/Gutschriftsausgang)
  220.             $belegnummer $writeResult['config']['documentNumber'];
  221.             $belegdatum strtotime($writeResult['config']['documentDate']);
  222.             $belegdatum date('Y-m-d H:i:s'$belegdatum);
  223.             $leistungsdatum $belegdatum;
  224.             $erzeugungsdatum $writeResult['createdAt']; 
  225.             // This is a DateTimeImmutable Object
  226.             $erzeugungsdatum $erzeugungsdatum->format('Y-m-d H:i:s');
  227.             $referenznummer $writeResult['config']['referencedDocumentId']?? ' '// z.B. bei Storno: Nummer der stornierten Rechnung
  228.             $personenkonto $order->getOrderCustomer()->getCustomerNumber();
  229.             $zahlungsdienstleister_OP_ID '';// $order->getOrderTransactions()->getCustomFileds()['swag_paypal_order_id'];//''; // Paypal Transaktions ID; bei Rechnung: Rechnungsnummer, nullable $order->getOrderTransactions()->getCustomFileds()['swag_paypal_order_id']
  230.             $transactions $order->getTransactions()->getElements();
  231.             //we use the first
  232.             $first_transaction reset($transactions);
  233.             if($first_transaction) {
  234.                 $custom_transactionfields $first_transaction->getCustomFields() ?? [];
  235.                 $zahlungsdienstleister_OP_ID array_key_exists('swag_paypal_order_id'$custom_transactionfields) ? $custom_transactionfields['swag_paypal_order_id'] : '';
  236.             }
  237.             $valutadatum $leistungsdatum;
  238.             $ziel1 $dummy_date;
  239.             $skonto1Betrag $order->getAmountTotal(); //
  240.             $skonto1Prozent "0";
  241.             $faelligAm $belegdatum;
  242.             $land_Lieferadresse_ISO3 $billing_address_country// no shipping Address in Order or Document! -> because there is only one address per customer ATM, just take the billing address
  243.             $land_Rechnungsadresse_ISO3 $billing_address_country;
  244.             $ust_id $order->getOrderCustomer()->getVatIds()[0]?? "";
  245.             $ust_id preg_replace('/[^a-zA-Z0-9]/'""$ust_id); // remove white space and non-alphanumeric characters
  246.             $endbetrag $order->getAmountTotal();
  247.             $taxes $order->getPrice()->getCalculatedTaxes()->getElements();
  248.             SharedFunctions::dumpToLog("Taxes");
  249.             SharedFunctions::dumpToLog($taxes);
  250.             $endbetrag_Steuerschluessel1 = !empty($taxes) ? reset($taxes)->getTax() : 0;
  251.             SharedFunctions::dumpToLog($endbetrag_Steuerschluessel1);
  252.             $endbetrag_Steuerschluessel2 0;
  253.             SharedFunctions::dumpToLog($endbetrag_Steuerschluessel2);
  254.             SharedFunctions::dumpToLog("Taxes done");
  255.             // Credit-note type should have negative values for money-related entries
  256.             if(in_array($documentTechnicalName$creditNote_types)){
  257.               $skonto1Betrag *= -1;
  258.               $endbetrag *= -1;
  259.               $endbetrag_Steuerschluessel1 *= -1;
  260.               $endbetrag_Steuerschluessel2 *= -1;
  261.             }
  262.             $sql_belegkopf 'INSERT INTO Shop2DWH_Belegkopf (' 
  263.             .'`Belegart`, ' 
  264.             .'`Belegnummer`, '
  265.             .'`BestellNr`, ' 
  266.             .'`Belegwaehrung`, ' 
  267.             .'`Belegdatum`, ' 
  268.             .'`Leistungsdatum`, ' 
  269.             .'`Erzeugungsdatum`, ' 
  270.             .'`Referenznr`, '
  271.             .'`Personenkonto`, ' 
  272.             .'`ZahlungsDienstleister_OP_ID`, ' 
  273.             .'`Valutadatum`, ' 
  274.             .'`Ziel1`, ' 
  275.             .'`Skonto1Betrag`, ' 
  276.             .'`Skonto1Prozent`, ' 
  277.             .'`FaelligAm`, ' 
  278.             .'`Land_Lieferadresse_ISO3`, '
  279.             .'`Land_Rechnungsadresse_ISO3`, '
  280.             .'`UST-ID`, '
  281.             .'`Endbetrag`, '
  282.             .'`Endbetrag_Steuerschluessel1`, '
  283.             .'`Endbetrag_Steuerschluessel2`, '
  284.             .'`Zahlungsart`'
  285.              .' )'
  286.             .' VALUES ( '
  287.             .'"' .$belegart .'", '
  288.             .'"' .$belegnummer .'", '
  289.             .'"' .$bestellnummer .'", '
  290.             .'"' .$belegwaehrung .'", '
  291.             .'"' .$belegdatum .'", '
  292.             .'"' .$leistungsdatum .'", '
  293.             .'"' .$erzeugungsdatum .'", '
  294.             .'"' .$referenznummer.'", '
  295.             .'"' .$personenkonto .'", '
  296.             .'"' .$zahlungsdienstleister_OP_ID .'", '
  297.             .'"' .$valutadatum .'", '
  298.             .'"' .$ziel1 .'", '
  299.             .'"' .$skonto1Betrag .'", '
  300.             .'"' .$skonto1Prozent .'", '
  301.             .'"' .$faelligAm .'", '
  302.             .'"' .$land_Lieferadresse_ISO3 .'", '
  303.             .'"' .$land_Rechnungsadresse_ISO3 .'", '
  304.             .'"' .$ust_id .'", '
  305.             .'"' .$endbetrag .'", '
  306.             .'"' .$endbetrag_Steuerschluessel1 .'", '
  307.             .'"' .$endbetrag_Steuerschluessel2 .'", '
  308.             .'"' .$zahlungsart .'"'
  309.             .' )';
  310.             
  311.             //dump($sql_belegkopf);
  312.             $mysqli = new \mysqli($dbHost$dbUser$dbPass$dbName);
  313.             if($mysqli->connect_errno ) {
  314.                 // Log the error somehow
  315.                 //dump($mysqli->connect_errno);
  316.             }
  317.             
  318.             if(! $mysqli->query($sql_belegkopf)){
  319.                //dump(mysqli_error($mysqli), $sql_belegkopf);
  320.             }
  321. //dump("Belegkopf persisted");
  322.             // retrieve the belegkopfId
  323.             $belegkopfId '';
  324.             $sql_getBelegkopf 'SELECT BelegkopfID AS kopfid FROM Shop2DWH_Belegkopf WHERE Belegnummer = "' .$belegnummer .'" ';
  325.             if($get_belegkopfid_query $mysqli->query($sql_getBelegkopf)) {
  326.                 $row mysqli_fetch_array($get_belegkopfid_query);
  327.                 // dump($row);
  328.                 $belegkopfId $row['kopfid'];
  329.                 $get_belegkopfid_query->close();
  330.             }
  331.             $optionSearchResult $this->getPropertyOptions_by_name_and_propertydescription('1''istHandelwareWebshop');
  332.             $handelswareOption reset($optionSearchResult);
  333.             if ($handelswareOption !== false) {
  334.                 $handelswareId $handelswareOption->getId();
  335.             } else {
  336.                 // Umgang mit dem Fall, dass keine Option gefunden wurde
  337.                 SharedFunctions::dumpToLog('Keine Handelsware-Option gefunden.');
  338.                 $handelswareId '<->'// oder ein anderer sinnvoller Wert
  339.             }
  340.             // get necessary Data for Belegposition and write to external DB
  341.             $order_linteitems $order->getLineItems()->getElements();
  342.             foreach($order_linteitems as $lineItem){
  343.                 $positionsnummer $lineItem->getPosition();
  344.                 $betragNetto $lineItem->getPrice()->getTotalPrice();
  345.                 $taxes $order->getPrice()->getCalculatedTaxes()->getElements();
  346.                 SharedFunctions::dumpToLog("=================== 1 =======================");
  347.                 SharedFunctions::dumpToLog($taxes);
  348.                 $betragSteuer = !empty($taxes) ? reset($taxes)->getTax() : 0;
  349.                 $steuerschluessel '9';
  350.                 $steuerProzent = !empty($taxes) ? reset($taxes)->getTaxRate() : 0;
  351. ;
  352.                 $positionstext $lineItem->getDescription() ?? "";
  353.                 $lieferscheinNr $belegnummer;
  354.                 $payload $lineItem->getPayload();
  355.                 $artikelNr array_key_exists('productNumber'$payload) ? $payload['productNumber'] : 'ohne';
  356.                 $menge $lineItem->getQuantity();
  357.                 $me 'StĂĽck';
  358.                 
  359.                 $produktart 'Eigenfertigung';
  360.                 if ($lineItem->getProduct()) {
  361.                     $propertyIds $lineItem->getProduct()->getPropertyIds();
  362.                     if(in_array($handelswareId$propertyIds)){
  363.                         $produktart 'Handelsware';
  364.                     }
  365.                 } else {
  366.                     $produktart 'Rabatt';
  367.                 }
  368.             /*
  369.                 Get all info about order and write to Shop2DWH_Belegkopf and Shop2DWH_Belegposition
  370.                 Belegkopf:
  371.                 Belegart, Belegnummer, BestellNr, Belegdatum, Leistungsdatum, Erzeugungsdatum, (Referenznummer), Personenkonto,
  372.                 Zahlungsdienstleister_OP_ID, Valutadatum, Ziel1, Skonto1Betrag, Skonto1Prozent, FaelligAm, Land_Lieferadresse_ISO3,
  373.                 Land_Rechnungsadresse_ISO3, UST-ID, Endbetrag, Endbetrag_Steuerschluessel1, Endbetrag_Steuerschluessel2, 
  374.                 
  375.                 Belegposition:
  376.                 *BelegkopfID int11
  377.                 PositionsNr int11
  378.                 BetragNetto decimal
  379.                 BetragSteuer decimal
  380.                 Steuerschluessel varchar: 9=> 19%, 5:0%
  381.                 SteuerProzent decimal(4,2) (???)
  382.                 PositionsText
  383.                 LieferscheinNr varchar15
  384.                 Leistungsdatum date
  385.                 ArtikelNr
  386.                 Menge int
  387.                 ME varchar(15) ???
  388.                 Produktart varchar(15) ???
  389.                  */
  390.                 // Credit-note type should have negative values for money-related entries
  391.                 if(in_array($documentTechnicalName$creditNote_types)){
  392.                   $betragNetto *= -1;
  393.                   $betragSteuer *= -1;
  394.                 }
  395.                  $sql_belegposition 'INSERT INTO Shop2DWH_Belegposition ('
  396.                  .' BelegkopfID , PositionsNr, BetragNetto, BetragSteuer, Steuerschluessel, '
  397.                  .'SteuerProzent, PositionsText, LieferscheinNr, Leistungsdatum, '
  398.                  .'ArtikelNr, Menge, ME, Produktart ) VALUES ( '
  399.                  .$belegkopfId .', '
  400.                  .$positionsnummer .', '
  401.                  .$betragNetto .', '
  402.                  .$betragSteuer .', '
  403.                  .'"' .$steuerschluessel .'", '
  404.                  .$steuerProzent .', '
  405.                  .'"' .$positionstext .'", '
  406.                  .'"' .$lieferscheinNr .'", '
  407.                  .'"' .$leistungsdatum .'", '
  408.                  .'"' .$artikelNr .'", '
  409.                  .$menge .', '
  410.                 .'"' .$me .'", '
  411.                 .'"' .$produktart .'" )';
  412. //dump($sql_belegposition);
  413.                 if(! $mysqli->query($sql_belegposition)){
  414.                     //dump(mysqli_error($mysqli), $sql_belegposition);
  415.                 }
  416.             
  417.             }
  418.             // add another position for shipment
  419.             $shipping_costs $order->getShippingCosts();
  420.             $betragNetto $shipping_costs->getTotalPrice();
  421.             $taxes $shipping_costs->getCalculatedTaxes()->getElements();
  422.             SharedFunctions::dumpToLog("=================== 2 =======================");
  423.             SharedFunctions::dumpToLog($taxes);
  424.             $betragSteuer = !empty($taxes) ? reset($taxes)->getTax() : 0;
  425.             $steuerProzent = !empty($taxes) ? reset($taxes)->getTaxRate() : 0;
  426.             $steuerschluessel '9';
  427.             $positionstext 'Versandkosten';
  428.             $lieferscheinNr $belegnummer;
  429.             $artikelNr 'ohne';
  430.             $menge 1;
  431.             $me 'StĂĽck';
  432.                 
  433.             $produktart 'Versandkosten';
  434.             
  435.             if(in_array($documentTechnicalName$creditNote_types)){
  436.                   $betragNetto *= -1;
  437.                   $betragSteuer *= -1;
  438.             }
  439.             
  440.             $sql_shipmentPosition 'INSERT INTO Shop2DWH_Belegposition ('
  441.             .' BelegkopfID , PositionsNr, BetragNetto, BetragSteuer, Steuerschluessel, '
  442.             .'SteuerProzent, PositionsText, LieferscheinNr, Leistungsdatum, '
  443.             .'ArtikelNr, Menge, ME, Produktart ) VALUES ( '
  444.             .$belegkopfId .', '
  445.             .'99998' .', '
  446.             .$betragNetto .', '
  447.             .$betragSteuer .', '
  448.             .'"' .$steuerschluessel .'", '
  449.             .$steuerProzent .', '
  450.             .'"' .$positionstext .'", '
  451.             .'"' .$lieferscheinNr .'", '
  452.             .'"' .$leistungsdatum .'", '
  453.             .'"' .$artikelNr .'", '
  454.             .$menge .', '
  455.             .'"' .$me .'", '
  456.             .'"' .$produktart .'" )';
  457.             
  458.             if(! $mysqli->query($sql_shipmentPosition)){
  459.                 // TODO sql-query failed
  460.             }
  461.             //dump("added shipment");
  462.         
  463.         //dump("finished");
  464.         } else {
  465.             //no-op
  466.         }
  467.     }
  468.     private function getZahlungsart($orderUUID$orderVersionUUID$languageUUID) {
  469.         // get the payment method as "Name"
  470.         SharedFunctions::dumpToLog("getZahlungsart()");
  471.         $dbHost $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
  472.         $dbUser $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
  473.         $dbPass $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
  474.         $dbName $this->systemConfigService->get('SteincoProductsController.config.shopDatabaseName');
  475.         $mySql = new \mysqli($dbHost$dbUser$dbPass$dbName);
  476.         if ($mySql->connect_errno) {
  477.             SharedFunctions::dumpToLog('Could not connect to MySQL: ' $mySql->connect_error);
  478.             return "";
  479.         }
  480.         $zahlungsart "";
  481.         try {
  482.             $sql "
  483.                 SELECT 
  484.                     COALESCE(pmt.distinguishable_name, pmt.name) AS payment_method 
  485.                 FROM 
  486.                     order_transaction ot 
  487.                 JOIN 
  488.                     payment_method pm ON ot.payment_method_id = pm.id 
  489.                 JOIN 
  490.                     payment_method_translation pmt ON pm.id = pmt.payment_method_id 
  491.                 WHERE 
  492.                     ot.order_id = UNHEX('" $orderUUID "') 
  493.                     AND ot.order_version_id = UNHEX('" $orderVersionUUID "') 
  494.                     AND pmt.language_id = UNHEX('" $languageUUID "') 
  495.                 LIMIT 1
  496.             ";
  497.             $result $mySql->query($sql);
  498.             if ($result) {
  499.                 $row $result->fetch_assoc();
  500.                 if ($row) {
  501.                     $zahlungsart $row['payment_method'];
  502.                     SharedFunctions::dumpToLog($result);
  503.                 } else {
  504.                     SharedFunctions::dumpToLog('Keine Daten gefunden. SQL: ' $sql);
  505.                 }
  506.             } else {
  507.                 SharedFunctions::dumpToLog('Error executing: ' $sql);
  508.                 SharedFunctions::dumpToLog('SQL-Error: ' $mySql->error);
  509.             }
  510.         } catch (\Exception $e) {
  511.             // Logge die Fehlermeldung in eine Datei oder verarbeite den Fehler entsprechend
  512.             SharedFunctions::dumpToLog('Abfrage der Zahlungsart fehlgeschlagen: .'$sql);
  513.             SharedFunctions::dumpToLog($e->getMessage());
  514.         }
  515.         return $zahlungsart;
  516.     }
  517.     private function getPropertyOptions_by_name_and_propertydescription($propertyoptionname$propertydescription)
  518.     {
  519.         SharedFunctions::dumpToLog("getPropertyOptions_by_name_and_propertydescription(): [" $propertyoptionname "], [" $propertydescription "]");
  520.         $property_uuid $this->getPropertyUUID_by_description($propertydescription);
  521.         $property_filter = new EqualsFilter('groupId'$property_uuid);
  522.         $propertyoption_filter = new EqualsFilter('name'$propertyoptionname);
  523.         $search_criteria = new Criteria([]);
  524.         $search_criteria->addFilter($property_filter);
  525.         $search_criteria->addFilter($propertyoption_filter);
  526.         $search_results $this->propertyOptionRepository->search($search_criteria,
  527.             $this->context)->getElements();
  528.         SharedFunctions::dumpToLog($search_results);
  529.         return $search_results;
  530.     }
  531.     private function getPropertyUUID_by_description($name) {
  532.         $filter = new EqualsFilter("description"$name);
  533.         $entity $this->propertyRepository->search((new Criteria())->addFilter($filter), 
  534.         $this->context)->first();
  535.         if($entity) {
  536.             return $entity->getId();
  537.         }
  538.         return null;
  539.     }
  540.     private function getOrder($orderUUID){
  541.         $orderCriteria = new Criteria([]);
  542.         $orderCriteria->addAssociation('currency')
  543.         ->addAssociation('billingAddress')
  544.         ->addAssociation('lineItems')
  545.         ->addAssociation('lineItems.product')
  546.         ->addAssociation('lineItems.product.properties')
  547.         ->addAssociation('transactions')
  548.         ->addAssociation('transactions.paymentMethod')
  549.         ->addAssociation('paymentMethod')
  550.         ->addAssociation('billingAddress.country')
  551.         ->addFilter(new EqualsFilter('id'$orderUUID));
  552.         $order_searchresult $this->orderRepository->search(
  553.             $orderCriteria,
  554.         \Shopware\Core\Framework\Context::createDefaultContext());
  555.         
  556.         $order $order_searchresult->getEntities()->getElements()[$orderUUID];
  557.         return $order;
  558.     }
  559.     // file stuff
  560.     //TODO: what data do we need?: $orderID, $config? $documentTypeName?
  561.     private function writeFilesToExchangeFolder($orderId$document){
  562.         $orderCriteria = new Criteria([]);
  563.         $orderCriteria->addAssociation('currency')->addAssociation('billingAddress')->addAssociation('salesChannel')->addAssociation('documents')->addAssociation('createdBy')->addFilter(new EqualsFilter('id'$orderId));
  564.         $order_searchresult $this->orderRepository->search(
  565.             $orderCriteria,
  566.            \Shopware\Core\Framework\Context::createDefaultContext());
  567.         
  568.         $order $order_searchresult->getEntities()->getElements()[$orderId];
  569.         $this->createJPLFile($order$document->getConfig(), $document->getConfig()['name']);
  570.         // find the file and copy to the selected directory
  571.         $this->copyCreatedFileToFileExchangeDirectory($document->getId(), $this->context);
  572.     }
  573.     // taken from SchoettlerDocumentService
  574.     Private function copyCreatedFileToFileExchangeDirectory($documentId$context) {
  575.         $outputdirectory $this->systemConfigService->get('SteincoProductsController.config.fileOutputPath');
  576.         $archivedirectory $this->systemConfigService->get('SteincoProductsController.config.archivefileOutputPath');
  577.         // find the source file
  578.         //dump($documentId);
  579.         $criteria = new Criteria([$documentId]);
  580.         $criteria->addAssociation('documentMediaFile');
  581.         $criteria->addAssociation('documentType');
  582.         /** @var DocumentEntity $document */
  583.         $document $this->documentRepository->search($criteria$context)->get($documentId);
  584.         $generatedDocument $this->documentService->getDocument($document$context);
  585.         if ((!$outputdirectory == NULL) and ($outputdirectory != "") and ($generatedDocument) and $generatedDocument->getFilename())  {
  586.             if((!$archivedirectory == NULL) and ($archivedirectory != "")) {
  587.                 $archivefilename $archivedirectory .$generatedDocument->getFilename();
  588.                 $archivefile fopen($archivefilename"w");
  589.                 fwrite($archivefile$generatedDocument->getFileBlob());
  590.                 fclose($archivefile);
  591.             }
  592.             $filename $outputdirectory .$generatedDocument->getFilename();
  593.             $file fopen($filename"w");
  594.             fwrite($file$generatedDocument->getFileBlob());
  595.             fclose($file);
  596.         }
  597.     }
  598.     Private function createJPLFile($order$config$documentTypeName) {
  599.         $myDocType "unbekannt";
  600.         //$shopname = $context
  601.         $outputContent null;
  602.         switch ($documentTypeName) {
  603.         case ("invoice"):
  604.             $myDocType $this->DOK_RECHNUNG;
  605.             $outputContent $this->getInvoiceOutputContent($order$config);
  606.             break;
  607.         case ("credit_note"):
  608.             $myDocType$this->DOK_GUTSCHRIFT;
  609.             $outputContent $this->getCreditNoteOutput($order$config);
  610.             break;
  611.         case ("delivery_note"):
  612.             $myDocType $this->DOK_LIEFERSCHEIN;
  613.             $outputContent $this->getDeliveryNoteOutput($order$config);
  614.             break;
  615.         case ("storno"):
  616.             $myDocType $this->DOK_RECHNUNGSSTORNO;
  617.             $outputContent $this->getStornoBillOutput($order$config);
  618.             break;
  619.             // No types for Gutschriftstorno, Auftragbestätigung implemented (yet)
  620.         }
  621.         if (!$outputContent) {
  622.             $outputContent "Error while creating content of this file.";
  623.         }
  624.         $archivedirectory $this->systemConfigService->get('SteincoProductsController.config.archivefileOutputPath');
  625.         $outputdirectory $this->systemConfigService->get('SteincoProductsController.config.fileOutputPath');
  626.         if (!empty($outputdirectory)) {
  627.             if (!empty($archivedirectory)) {
  628.                 $archivefilename $archivedirectory .$documentTypeName ."_" .$config['documentNumber'] .".jpl";
  629.                 $archivefile fopen($archivefilename"a");
  630.                 fwrite($archivefile$outputContent);
  631.                 fclose($archivefile);
  632.             }
  633.             $filename $outputdirectory .$documentTypeName ."_" .$config['documentNumber'] .".jpl";
  634.             $file fopen($filename"a");
  635.             fwrite($file$outputContent);
  636.             fclose($file);
  637.         }
  638.         // some error: could not create file because of missing outputpath
  639.     }
  640.     private function getInvoiceOutputContent($order$config
  641.     {
  642.         // $shopname -should be in context
  643.         // 
  644.         $customerName $order->getOrderCustomer()->getCompany();
  645.         if (!$customerName) {
  646.             $customerName $order->getOrderCustomer()->getLastName() .", "$order->getOrderCustomer()->getFirstName();
  647.         } 
  648.         $bearbeiter "shopware";
  649.         $result 'zeich_nr= "Shop' .$this->DOK_RECHNUNG .$config['documentNumber'] .'"' .$this->LINEBREAK
  650.             .'dokuart= "' .$this->DOK_RECHNUNG .'"'.$this->LINEBREAK
  651.             .'logi_verzeichnis = "Fr"'.$this->LINEBREAK
  652.             .'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
  653.             .'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
  654.             .'dok_dat_feld[14] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
  655.             .'dok_dat_feld[38] = "' .$bearbeiter .'"'.$this->LINEBREAK
  656.             .'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
  657.             .'dok_dat_feld[51] = "' date("d.m.Y") .'"'.$this->LINEBREAK;
  658.            
  659.             $result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
  660.         return $result;
  661.     }
  662.     Private function getCreditNoteOutput($order$config)
  663.     {
  664.         $bearbeiter "shopware";
  665.         $customerName $order->getOrderCustomer()->getCompany();
  666.         if (!$customerName) {
  667.             $customerName $order->getOrderCustomer()->getLastName() .", "$order->getOrderCustomer()->getFirstName();
  668.         } 
  669.         $result 'zeich_nr = "Shop' .$this->DOK_GUTSCHRIFT .$config['documentNumber'] ."'" .$this->LINEBREAK
  670.             .'dokuart = "' .$this->DOK_GUTSCHRIFT .'"' .$this->LINEBREAK
  671.             .'var_nr = 1'.$this->LINEBREAK
  672.             .'logi_verzeichnis = "Fr"' .$this->LINEBREAK
  673.             .'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
  674.             .'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
  675.             .'dok_dat_feld[15] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
  676.             .'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
  677.             .'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
  678.             .'dok_dat_feld[51] = "' date("d.m.Y") .'"'.$this->LINEBREAK;
  679.             // multiple Orders?
  680.         $result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
  681.         return $result;
  682.     }
  683.     Private function getDeliveryNoteOutput($order$config
  684.     {
  685.        /*  zeich_nr = "RollenILSVK823000817"                Dokument ID: "Shop", Dokumentart, Dokument Nr
  686.         dokuart = "ILSVK"                        Dokumentart
  687.         var_nr = "1"                            Konstante
  688.         logi_verzeichnis = "Fr"                        Konstante
  689.         dok_dat_feld[1] = "1209331"                    KundenNr
  690.         dok_dat_feld[2] = "PASOTEC GmbH"                KundenName
  691.         dok_dat_feld[13] = "823000817"                    Dokument Nr
  692.         dok_dat_feld[38] = "PURSCHKES"                    Bearbeiter
  693.         dok_dat_feld[39] = "Rollen"                    Shop (=Konstante) 
  694.         dok_dat_feld[51] = "12.10.2021"                    Datum
  695.         dok_dat_feld_60[1] = "KA53131"                    Auftrag
  696.          */
  697.         $bearbeiter "shopware";
  698.         $customerName $order->getOrderCustomer()->getCompany();
  699.         if (!$customerName) {
  700.             $customerName $order->getOrderCustomer()->getLastName() .", "$order->getOrderCustomer()->getFirstName();
  701.         } 
  702.         $result 'zeich_nr = "Shop' .$this->DOK_LIEFERSCHEIN .$config['documentNumber'] .'"' .$this->LINEBREAK
  703.         .'dokuart = "' .$this->DOK_LIEFERSCHEIN .'"' .$this->LINEBREAK
  704.         .'var_nr = 1'.$this->LINEBREAK
  705.         .'logi_verzeichnis = "Fr"' .$this->LINEBREAK
  706.         .'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
  707.         .'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
  708.         .'dok_dat_feld[13] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
  709.         .'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
  710.         .'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
  711.         .'dok_dat_feld[51] = "' date("d.m.Y") .'"'.$this->LINEBREAK;
  712.         $result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
  713.         return $result;
  714.     }
  715.     Private function getStornoBillOutput($order$config)
  716.     {
  717.        /*  zeich_nr = "RollenIGUVK32001379"                Dokument ID: "Shop", Dokumentart, Dokument Nr
  718.           dokuart = "IGUVK"                        Dokumentart
  719.           var_nr = "1"                            Konstante
  720.           logi_verzeichnis = "Fr"                        Konstante
  721.           dok_dat_feld[1] = "1201307"                    KundenNr
  722.           dok_dat_feld[2] = "Universitätsklinikum Dresden"        KundenName    
  723.           dok_dat_feld[15] = "32001379"                    Dokument Nr
  724.            dok_dat_feld[38] = "LINDHORSTJ"                    Bearbeiter
  725.            dok_dat_feld[39] = "Rollen"                    SHOP (=Konstante) 
  726.            dok_dat_feld[51] = "12.10.2021"                    Datum
  727.            dok_dat_feld_60[1] = "KA54091"                    Auftrag
  728.             dok_dat_feld_60[2] = "KA54091"                    Auftrag
  729.            dok_dat_feld_61[1] = "00050066"                    Lieferschein
  730.            dok_dat_feld_61[2] = "00050066"                    Lieferschein
  731.  */
  732.         $bearbeiter "shopware";
  733.         $customerName $order->getOrderCustomer()->getCompany();
  734.         if (!$customerName) {
  735.             $customerName $order->getOrderCustomer()->getLastName() .", "$order->getOrderCustomer()->getFirstName();
  736.         } 
  737.         $result 'zeich_nr = "Shop' .$this->DOK_RECHNUNGSSTORNO .$config['documentNumber'] .'"' .$this->LINEBREAK
  738.         .'dokuart = "' .$this->DOK_RECHNUNGSSTORNO .'"' .$this->LINEBREAK
  739.         .'var_nr = 1'.$this->LINEBREAK
  740.         .'logi_verzeichnis = "Fr"' .$this->LINEBREAK
  741.         .'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
  742.         .'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
  743.         .'dok_dat_feld[15] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
  744.         .'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
  745.         .'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
  746.         .'dok_dat_feld[51] = "' date("d.m.Y") .'"'.$this->LINEBREAK;
  747.         // in shopware, a storno bill references a single invoice and thus a single order
  748.         $invoiceNr $config['custom']['invoiceNumber'] ?? '';
  749.         $result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK
  750.             .'dok_dat_feld_61[1] = "' .$invoiceNr .'"' .$this->LINEBREAK;
  751.         return $result;
  752.     }
  753. }