<?php declare(strict_types=1);
namespace Schoettler\SteincoProducts\Subscriber;
use Schoettler\SteincoProducts\SharedFunctions;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use DateTimeImmutable;
use DateTimeInterface;
// Rechnung immer zuerst
class OrderEventsSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() : array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'onOrderWritten',
'document.written' => 'onDocumentWritten'
];
}
Private $DOK_RECHNUNG = "IRGVK";
Private $DOK_LIEFERSCHEIN = "ILSVK";
Private $DOK_GUTSCHRIFT = "IGUVK";
Private $DOK_RECHNUNGSSTORNO = "IGUVK";
Private $DOK_GUTSCHRIFTSTORNO = "IGUST";
Private $DOK_AUFTRAGBESTAETIGUNG = "IABVK";
Private $LINEBREAK = "\r\n";
private $context;
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var EntityRepository
*/
private $customerRepository;
/**
* @var EntityRepository
*/
private $orderRepository;
/**
* @var EntityRepository
*/
private $documentRepository;
/**
* @var EntityRepository
*/
private $propertyOptionRepository;
/**
* @var EntityRepository
*/
private $propertyRepository;
/**
* @var DocumentService
*/
protected $documentService;
/**
* @var EntityRepository
*/
private $mediaRepository;
public function __construct(SystemConfigService $systemConfigService,
EntityRepository $customerRepository, EntityRepository $orderRepository,
EntityRepository $documentRepository, EntityRepository $propertyOptionRepository,
EntityRepository $propertyRepository, $docService, $mediaRepository)
{
$this->systemConfigService = $systemConfigService;
$this->customerRepository = $customerRepository;
$this->orderRepository = $orderRepository;
$this->documentRepository = $documentRepository;
$this->propertyOptionRepository = $propertyOptionRepository;
$this->propertyRepository = $propertyRepository;
$this->documentService = $docService;
$this->mediaRepository = $mediaRepository;
//$this->urlGenerator = $urlGenerator;
}
public function onOrderWritten(EntityWrittenEvent $event)
{
//Database
$dbHost = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
$dbUser = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
$dbPass = $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
$dbName = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseName');
$mysqli = new \mysqli($dbHost, $dbUser, $dbPass, $dbName);
if($mysqli->connect_errno ) {
// Log the error somehow
//dump($mysqli->connect_errno);
}
$orderUUID = $event->getWriteResults()[0]->getPrimaryKey();
$myContext = $event->getContext();
$this->context = $myContext ?? \Shopware\Core\Framework\Context::createDefaultContext();
$orderCriteria = new Criteria([]);
$orderCriteria->addAssociation('currency')->addAssociation('billingAddress')->addFilter(new EqualsFilter('id', $orderUUID));
$order_searchresult = $this->orderRepository->search(
$orderCriteria,
\Shopware\Core\Framework\Context::createDefaultContext());
$order = $order_searchresult->getEntities()->getElements()[$orderUUID];
// TODO: if order is empty
$order_number = $order->getOrderNumber();
$customer_number = $order->getOrderCustomer()->getCustomerNumber();
//dump($order_searchresult, $order);
// check if the order is already present in the Shop2DWH_Erstbesteller table
$check_erstbesteller_sql = 'SELECT NOT EXISTS (SELECT * FROM Shop2DWH_Erstbesteller WHERE Kundennummer = "'
.$customer_number .'" ) AS firstorder';
if($check_erstbesteller_query = $mysqli->query($check_erstbesteller_sql)) {
$row = mysqli_fetch_array($check_erstbesteller_query);
$no_entry_exists = $row['firstorder'];
$check_erstbesteller_query->close();
$firstorderDate = $order->getCreatedAt();
$erstbestelldatum = $firstorderDate->format('Y-m-d H:i:s');
if($no_entry_exists == 1) {
// first order by this Customer, write to Shop2DWH_Erstbesteller
$sql = 'INSERT INTO Shop2DWH_Erstbesteller (Kundennummer, order_id, Erstbestelldatum)'
.' VALUES ("' .$customer_number .'", "' .$order_number .'", "' .$erstbestelldatum .'" )';
if(! $mysqli->query($sql)){
//dump(mysqli_error($mysqli), $sql, $customer);
}
}
} else {
//TODO: query failed
}
}
public function onDocumentWritten(EntityWrittenEvent $event){
SharedFunctions::dumpToLog("onDocumentWritten()");
//get DB-related data
$dbHost = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
$dbUser = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
$dbPass = $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
$dbName = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseName');
// each document should only be written once, so all data must be present at this event
$myContext = $event->getContext();
$this->context = $myContext ?? \Shopware\Core\Framework\Context::createDefaultContext();
$writeResult = $event->getWriteResults();
$writeResult = reset($writeResult);
$writeResult = $writeResult->getPayload();
// SharedFunctions::dumpToLog($writeResult);
$orderUUID = $writeResult['orderId'];
$orderVersionUUID = $writeResult['orderVersionId']; // probably not needed
$documentUUID = $writeResult['id'];
// get the document including type
$documentCritera = new Criteria([]);
$documentCritera->addAssociation("documentType")->addFilter(New EqualsFilter('id', $documentUUID));
$document_searchresult = $this->documentRepository->search(
$documentCritera,
$myContext
);
$document = $document_searchresult->getEntities()->getElements()[$documentUUID];
//dump($document_searchresult->getEntities()->getElements()[$documentUUID],$documentUUID,$document_searchresult->getEntities()->getElements());
// we only want Rechnung, Storno, Gutschrift for the bulk of data
$documentTechnicalName = $document->getDocumentType()->getTechnicalName();
$invoice_types = ['invoice'];
$creditNote_types = ['credit_note', 'storno'];
// if the document is just created, we need to create a copy of the pdf and create a jpl-file
// pass document and order
//dump("copying document");
if(!empty($orderUUID)){
$this->writeFilesToExchangeFolder($orderUUID, $document);
//dump("copied document");
// delivery_note => Lieferschein
if ($documentTechnicalName == 'delivery_note'){
// delivery_note is created after invoice by design,
// we just use it to update the Lieferschein field in existing entries
// UPDATE Shop2DWH_BelegPosition Set Lieferschein = $belegnummer WHERE BelegkopfId = $belegkopfId
// To retrieve BelegkopfId we need the invoice, which we can get using Bestellnr
$order = $this->getOrder($orderUUID);
$orderNumber = $order->getOrderNumber();
$documentCriteria = new Criteria();
$documentCriteria->addFilter(new EqualsFilter('orderId', $orderUUID));
$documents = $this->documentRepository->search($documentCriteria, $this->context);
// loop over the docs and update Belegpositionen
$documentEntities = $documents->getEntities()->getElements();
$whereClause = ' WHERE LieferscheinNr ';
$numberOfElemets = sizeof($documentEntities);
//dump("trying to update delivery-note");
If($numberOfElemets > 0){
If ($numberOfElemets == 1) {
$doc = reset($documentEntities);
$whereClause .= '= "' .$doc->getConfig()['documentNumber'] .'" ';
} elseif ($numberOfElemets > 1) {
$whereClause .= 'IN(';
foreach ($documentEntities as $oldDocuments) {
$whereClause .= '"' .$oldDocuments->getConfig()['documentNumber'] .'", ';
}
$whereClause = substr($whereClause, 0, strlen($whereClause) - 2);
$whereClause .= ') ';
}
$updateSQL = 'UPDATE Shop2DWH_Belegposition SET LieferscheinNr = "' .$writeResult['config']['documentNumber'] .'" ' .$whereClause;
$mysqli = new \mysqli($dbHost, $dbUser, $dbPass, $dbName);
if($mysqli->connect_errno ) {
// Log the error somehow
//dump($mysqli->connect_errno);
}
if(! $mysqli->query($updateSQL)){
//dump(mysqli_error($mysqli), $updateSQL);
}
}
}
if(in_array($documentTechnicalName, $invoice_types) || in_array($documentTechnicalName, $creditNote_types))
{
SharedFunctions::dumpToLog("Creating BelegkopfSQL");
// get the order including currency and billing-address and shipping-address
$order = $this->getOrder($orderUUID);
$zahlungsart = $this->getZahlungsart($orderUUID, $orderVersionUUID, $order->getLanguageId());
$dummy_time = strtotime('2999-12-31');
$dummy_date = date('Y-m-d H:i:s', $dummy_time);
$bestellnummer = $order->getOrderNumber();
$belegwaehrung = $order->getCurrency()->getIsoCode();
$billing_address_country = $order->getBillingAddress()->getCountry()->getIso3();
// get necessary Data for Belegkopf and write to external DB
$belegart = in_array($documentTechnicalName, $creditNote_types)? 'GAS' : 'RAS'; //"RAS"; // possible values: RAS, GAS (Rechnungs/Gutschriftsausgang)
$belegnummer = $writeResult['config']['documentNumber'];
$belegdatum = strtotime($writeResult['config']['documentDate']);
$belegdatum = date('Y-m-d H:i:s', $belegdatum);
$leistungsdatum = $belegdatum;
$erzeugungsdatum = $writeResult['createdAt'];
// This is a DateTimeImmutable Object
$erzeugungsdatum = $erzeugungsdatum->format('Y-m-d H:i:s');
$referenznummer = $writeResult['config']['referencedDocumentId']?? ' '; // z.B. bei Storno: Nummer der stornierten Rechnung
$personenkonto = $order->getOrderCustomer()->getCustomerNumber();
$zahlungsdienstleister_OP_ID = '';// $order->getOrderTransactions()->getCustomFileds()['swag_paypal_order_id'];//''; // Paypal Transaktions ID; bei Rechnung: Rechnungsnummer, nullable $order->getOrderTransactions()->getCustomFileds()['swag_paypal_order_id']
$transactions = $order->getTransactions()->getElements();
//we use the first
$first_transaction = reset($transactions);
if($first_transaction) {
$custom_transactionfields = $first_transaction->getCustomFields() ?? [];
$zahlungsdienstleister_OP_ID = array_key_exists('swag_paypal_order_id', $custom_transactionfields) ? $custom_transactionfields['swag_paypal_order_id'] : '';
}
$valutadatum = $leistungsdatum;
$ziel1 = $dummy_date;
$skonto1Betrag = $order->getAmountTotal(); //
$skonto1Prozent = "0";
$faelligAm = $belegdatum;
$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
$land_Rechnungsadresse_ISO3 = $billing_address_country;
$ust_id = $order->getOrderCustomer()->getVatIds()[0]?? "";
$ust_id = preg_replace('/[^a-zA-Z0-9]/', "", $ust_id); // remove white space and non-alphanumeric characters
$endbetrag = $order->getAmountTotal();
$taxes = $order->getPrice()->getCalculatedTaxes()->getElements();
// HALLO: muss es hier fix 7 und 19 sein?
$endbetrag_Steuerschluessel1 = array_key_exists(19, $taxes) ? $taxes[19]->getTax() : 0;
$endbetrag_Steuerschluessel2 = array_key_exists(7, $taxes) ? $taxes[7]->getTax() : 0;
// Credit-note type should have negative values for money-related entries
if(in_array($documentTechnicalName, $creditNote_types)){
$skonto1Betrag *= -1;
$endbetrag *= -1;
$endbetrag_Steuerschluessel1 *= -1;
$endbetrag_Steuerschluessel2 *= -1;
}
$sql_belegkopf = 'INSERT INTO Shop2DWH_Belegkopf ('
.'`Belegart`, '
.'`Belegnummer`, '
.'`BestellNr`, '
.'`Belegwaehrung`, '
.'`Belegdatum`, '
.'`Leistungsdatum`, '
.'`Erzeugungsdatum`, '
.'`Referenznr`, '
.'`Personenkonto`, '
.'`ZahlungsDienstleister_OP_ID`, '
.'`Valutadatum`, '
.'`Ziel1`, '
.'`Skonto1Betrag`, '
.'`Skonto1Prozent`, '
.'`FaelligAm`, '
.'`Land_Lieferadresse_ISO3`, '
.'`Land_Rechnungsadresse_ISO3`, '
.'`UST-ID`, '
.'`Endbetrag`, '
.'`Endbetrag_Steuerschluessel1`, '
.'`Endbetrag_Steuerschluessel2`, '
.'`Zahlungsart`'
.' )'
.' VALUES ( '
.'"' .$belegart .'", '
.'"' .$belegnummer .'", '
.'"' .$bestellnummer .'", '
.'"' .$belegwaehrung .'", '
.'"' .$belegdatum .'", '
.'"' .$leistungsdatum .'", '
.'"' .$erzeugungsdatum .'", '
.'"' .$referenznummer.'", '
.'"' .$personenkonto .'", '
.'"' .$zahlungsdienstleister_OP_ID .'", '
.'"' .$valutadatum .'", '
.'"' .$ziel1 .'", '
.'"' .$skonto1Betrag .'", '
.'"' .$skonto1Prozent .'", '
.'"' .$faelligAm .'", '
.'"' .$land_Lieferadresse_ISO3 .'", '
.'"' .$land_Rechnungsadresse_ISO3 .'", '
.'"' .$ust_id .'", '
.'"' .$endbetrag .'", '
.'"' .$endbetrag_Steuerschluessel1 .'", '
.'"' .$endbetrag_Steuerschluessel2 .'", '
.'"' .$zahlungsart .'"'
.' )';
//dump($sql_belegkopf);
$mysqli = new \mysqli($dbHost, $dbUser, $dbPass, $dbName);
if($mysqli->connect_errno ) {
// Log the error somehow
//dump($mysqli->connect_errno);
}
if(! $mysqli->query($sql_belegkopf)){
//dump(mysqli_error($mysqli), $sql_belegkopf);
}
//dump("Belegkopf persisted");
// retrieve the belegkopfId
$belegkopfId = '';
$sql_getBelegkopf = 'SELECT BelegkopfID AS kopfid FROM Shop2DWH_Belegkopf WHERE Belegnummer = "' .$belegnummer .'" ';
if($get_belegkopfid_query = $mysqli->query($sql_getBelegkopf)) {
$row = mysqli_fetch_array($get_belegkopfid_query);
// dump($row);
$belegkopfId = $row['kopfid'];
$get_belegkopfid_query->close();
}
$optionSearchResult = $this->getPropertyOptions_by_name_and_propertydescription('1', 'istHandelwareWebshop');
$handelswareOption = reset($optionSearchResult);
if ($handelswareOption !== false) {
$handelswareId = $handelswareOption->getId();
} else {
// Umgang mit dem Fall, dass keine Option gefunden wurde
SharedFunctions::dumpToLog('Keine Handelsware-Option gefunden.');
$handelswareId = '<->'; // oder ein anderer sinnvoller Wert
}
// get neccessary Data for Belegposition and write to external DB
//dump("create Belegpositionquery");
$order_linteitems = $order->getLineItems()->getElements();
foreach($order_linteitems as $lineItem){
$positionsnummer = $lineItem->getPosition();
$betragNetto = $lineItem->getPrice()->getTotalPrice();
$betragSteuer = $lineItem->getPrice()->getCalculatedTaxes()->getElements()[19]->getTax();
$steuerschluessel = '9';
$steuerProzent = $lineItem->getPrice()->getCalculatedTaxes()->getElements()[19]->getTaxRate();
$positionstext = $lineItem->getDescription() ?? "";
$lieferscheinNr = $belegnummer;
$payload = $lineItem->getPayload();
$artikelNr = array_key_exists('productNumber', $payload) ? $payload['productNumber'] : 'ohne';
$menge = $lineItem->getQuantity();
$me = 'StĂĽck';
$produktart = 'Eigenfertigung';
if ($lineItem->getProduct()) {
$propertyIds = $lineItem->getProduct()->getPropertyIds();
if(in_array($handelswareId, $propertyIds)){
$produktart = 'Handelsware';
}
} else {
$produktart = 'Rabatt';
}
/*
Get all info about order and write to Shop2DWH_Belegkopf and Shop2DWH_Belegposition
Belegkopf:
Belegart, Belegnummer, BestellNr, Belegdatum, Leistungsdatum, Erzeugungsdatum, (Referenznummer), Personenkonto,
Zahlungsdienstleister_OP_ID, Valutadatum, Ziel1, Skonto1Betrag, Skonto1Prozent, FaelligAm, Land_Lieferadresse_ISO3,
Land_Rechnungsadresse_ISO3, UST-ID, Endbetrag, Endbetrag_Steuerschluessel1, Endbetrag_Steuerschluessel2,
Belegposition:
*BelegkopfID int11
PositionsNr int11
BetragNetto decimal
BetragSteuer decimal
Steuerschluessel varchar: 9=> 19%, 5:0%
SteuerProzent decimal(4,2) (???)
PositionsText
LieferscheinNr varchar15
Leistungsdatum date
ArtikelNr
Menge int
ME varchar(15) ???
Produktart varchar(15) ???
*/
// Credit-note type should have negative values for money-related entries
if(in_array($documentTechnicalName, $creditNote_types)){
$betragNetto *= -1;
$betragSteuer *= -1;
}
$sql_belegposition = 'INSERT INTO Shop2DWH_Belegposition ('
.' BelegkopfID , PositionsNr, BetragNetto, BetragSteuer, Steuerschluessel, '
.'SteuerProzent, PositionsText, LieferscheinNr, Leistungsdatum, '
.'ArtikelNr, Menge, ME, Produktart ) VALUES ( '
.$belegkopfId .', '
.$positionsnummer .', '
.$betragNetto .', '
.$betragSteuer .', '
.'"' .$steuerschluessel .'", '
.$steuerProzent .', '
.'"' .$positionstext .'", '
.'"' .$lieferscheinNr .'", '
.'"' .$leistungsdatum .'", '
.'"' .$artikelNr .'", '
.$menge .', '
.'"' .$me .'", '
.'"' .$produktart .'" )';
//dump($sql_belegposition);
if(! $mysqli->query($sql_belegposition)){
//dump(mysqli_error($mysqli), $sql_belegposition);
}
}
// add another position for shipment
$shipping_costs = $order->getShippingCosts();
$betragNetto = $shipping_costs->getTotalPrice();
$betragSteuer = $shipping_costs->getCalculatedTaxes()->getElements()[19]->getTax();
$steuerschluessel = '9';
$steuerProzent = $shipping_costs->getCalculatedTaxes()->getElements()[19]->getTaxRate();
$positionstext = 'Versandkosten';
$lieferscheinNr = $belegnummer;
$artikelNr = 'ohne';
$menge = 1;
$me = 'StĂĽck';
$produktart = 'Versandkosten';
if(in_array($documentTechnicalName, $creditNote_types)){
$betragNetto *= -1;
$betragSteuer *= -1;
}
$sql_shipmentPosition = 'INSERT INTO Shop2DWH_Belegposition ('
.' BelegkopfID , PositionsNr, BetragNetto, BetragSteuer, Steuerschluessel, '
.'SteuerProzent, PositionsText, LieferscheinNr, Leistungsdatum, '
.'ArtikelNr, Menge, ME, Produktart ) VALUES ( '
.$belegkopfId .', '
.'99998' .', '
.$betragNetto .', '
.$betragSteuer .', '
.'"' .$steuerschluessel .'", '
.$steuerProzent .', '
.'"' .$positionstext .'", '
.'"' .$lieferscheinNr .'", '
.'"' .$leistungsdatum .'", '
.'"' .$artikelNr .'", '
.$menge .', '
.'"' .$me .'", '
.'"' .$produktart .'" )';
if(! $mysqli->query($sql_shipmentPosition)){
// TODO sql-query failed
}
//dump("added shipment");
}
//dump("finished");
} else {
//no-op
}
}
private function getZahlungsart($orderUUID, $orderVersionUUID, $languageUUID) {
// get the payment method as "Name"
SharedFunctions::dumpToLog("getZahlungsart()");
$dbHost = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseHost');
$dbUser = $this->systemConfigService->get('SteincoProductsController.config.externalDatabaseUser');
$dbPass = $this->systemConfigService->get('SteincoProductsController.config.externalDatabasePassword');
$dbName = $this->systemConfigService->get('SteincoProductsController.config.shopDatabaseName');
$mySql = new \mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($mySql->connect_errno) {
SharedFunctions::dumpToLog('Could not connect to MySQL: ' . $mySql->connect_error);
return "";
}
$zahlungsart = "";
try {
$sql = "
SELECT
COALESCE(pmt.distinguishable_name, pmt.name) AS payment_method
FROM
order_transaction ot
JOIN
payment_method pm ON ot.payment_method_id = pm.id
JOIN
payment_method_translation pmt ON pm.id = pmt.payment_method_id
WHERE
ot.order_id = UNHEX('" . $orderUUID . "')
AND ot.order_version_id = UNHEX('" . $orderVersionUUID . "')
AND pmt.language_id = UNHEX('" . $languageUUID . "')
LIMIT 1
";
$result = $mySql->query($sql);
if ($result) {
$row = $result->fetch_assoc();
if ($row) {
$zahlungsart = $row['payment_method'];
SharedFunctions::dumpToLog($result);
} else {
SharedFunctions::dumpToLog('Keine Daten gefunden. SQL: ' . $sql);
}
} else {
SharedFunctions::dumpToLog('Error executing: ' . $sql);
SharedFunctions::dumpToLog('SQL-Error: ' . $mySql->error);
}
} catch (\Exception $e) {
// Logge die Fehlermeldung in eine Datei oder verarbeite den Fehler entsprechend
SharedFunctions::dumpToLog('Abfrage der Zahlungsart fehlgeschlagen: .', $sql);
SharedFunctions::dumpToLog($e->getMessage());
}
return $zahlungsart;
}
private function getPropertyOptions_by_name_and_propertydescription($propertyoptionname, $propertydescription)
{
SharedFunctions::dumpToLog("getPropertyOptions_by_name_and_propertydescription(): [" . $propertyoptionname . "], [" . $propertydescription . "]");
$property_uuid = $this->getPropertyUUID_by_description($propertydescription);
$property_filter = new EqualsFilter('groupId', $property_uuid);
$propertyoption_filter = new EqualsFilter('name', $propertyoptionname);
$search_criteria = new Criteria([]);
$search_criteria->addFilter($property_filter);
$search_criteria->addFilter($propertyoption_filter);
$search_results = $this->propertyOptionRepository->search($search_criteria,
$this->context)->getElements();
SharedFunctions::dumpToLog($search_results);
return $search_results;
}
private function getPropertyUUID_by_description($name) {
$filter = new EqualsFilter("description", $name);
$entity = $this->propertyRepository->search((new Criteria())->addFilter($filter),
$this->context)->first();
if($entity) {
return $entity->getId();
}
return null;
}
private function getOrder($orderUUID){
$orderCriteria = new Criteria([]);
$orderCriteria->addAssociation('currency')
->addAssociation('billingAddress')
->addAssociation('lineItems')
->addAssociation('lineItems.product')
->addAssociation('lineItems.product.properties')
->addAssociation('transactions')
->addAssociation('transactions.paymentMethod')
->addAssociation('paymentMethod')
->addAssociation('billingAddress.country')
->addFilter(new EqualsFilter('id', $orderUUID));
$order_searchresult = $this->orderRepository->search(
$orderCriteria,
\Shopware\Core\Framework\Context::createDefaultContext());
$order = $order_searchresult->getEntities()->getElements()[$orderUUID];
return $order;
}
// file stuff
//TODO: what data do we need?: $orderID, $config? $documentTypeName?
private function writeFilesToExchangeFolder($orderId, $document){
$orderCriteria = new Criteria([]);
$orderCriteria->addAssociation('currency')->addAssociation('billingAddress')->addAssociation('salesChannel')->addAssociation('documents')->addAssociation('createdBy')->addFilter(new EqualsFilter('id', $orderId));
$order_searchresult = $this->orderRepository->search(
$orderCriteria,
\Shopware\Core\Framework\Context::createDefaultContext());
$order = $order_searchresult->getEntities()->getElements()[$orderId];
$this->createJPLFile($order, $document->getConfig(), $document->getConfig()['name']);
// find the file and copy to the selected directory
$this->copyCreatedFileToFileExchangeDirectory($document->getId(), $this->context);
}
// taken from SchoettlerDocumentService
Private function copyCreatedFileToFileExchangeDirectory($documentId, $context) {
$outputdirectory = $this->systemConfigService->get('SteincoProductsController.config.fileOutputPath');
$archivedirectory = $this->systemConfigService->get('SteincoProductsController.config.archivefileOutputPath');
// find the source file
//dump($documentId);
$criteria = new Criteria([$documentId]);
$criteria->addAssociation('documentMediaFile');
$criteria->addAssociation('documentType');
/** @var DocumentEntity $document */
$document = $this->documentRepository->search($criteria, $context)->get($documentId);
$generatedDocument = $this->documentService->getDocument($document, $context);
if ((!$outputdirectory == NULL) and ($outputdirectory != "") and ($generatedDocument) and $generatedDocument->getFilename()) {
if((!$archivedirectory == NULL) and ($archivedirectory != "")) {
$archivefilename = $archivedirectory .$generatedDocument->getFilename();
$archivefile = fopen($archivefilename, "w");
fwrite($archivefile, $generatedDocument->getFileBlob());
fclose($archivefile);
}
$filename = $outputdirectory .$generatedDocument->getFilename();
$file = fopen($filename, "w");
fwrite($file, $generatedDocument->getFileBlob());
fclose($file);
}
}
Private function createJPLFile($order, $config, $documentTypeName) {
$myDocType = "unbekannt";
//$shopname = $context
$outputContent = null;
switch ($documentTypeName) {
case ("invoice"):
$myDocType = $this->DOK_RECHNUNG;
$outputContent = $this->getInvoiceOutputContent($order, $config);
break;
case ("credit_note"):
$myDocType= $this->DOK_GUTSCHRIFT;
$outputContent = $this->getCreditNoteOutput($order, $config);
break;
case ("delivery_note"):
$myDocType = $this->DOK_LIEFERSCHEIN;
$outputContent = $this->getDeliveryNoteOutput($order, $config);
break;
case ("storno"):
$myDocType = $this->DOK_RECHNUNGSSTORNO;
$outputContent = $this->getStornoBillOutput($order, $config);
break;
// No types for Gutschriftstorno, Auftragbestätigung implemented (yet)
}
if (!$outputContent) {
$outputContent = "Error while creating content of this file.";
}
$archivedirectory = $this->systemConfigService->get('SteincoProductsController.config.archivefileOutputPath');
$outputdirectory = $this->systemConfigService->get('SteincoProductsController.config.fileOutputPath');
if (!empty($outputdirectory)) {
if (!empty($archivedirectory)) {
$archivefilename = $archivedirectory .$documentTypeName ."_" .$config['documentNumber'] .".jpl";
$archivefile = fopen($archivefilename, "a");
fwrite($archivefile, $outputContent);
fclose($archivefile);
}
$filename = $outputdirectory .$documentTypeName ."_" .$config['documentNumber'] .".jpl";
$file = fopen($filename, "a");
fwrite($file, $outputContent);
fclose($file);
}
// some error: could not create file because of missing outputpath
}
private function getInvoiceOutputContent($order, $config)
{
// $shopname -should be in context
//
$customerName = $order->getOrderCustomer()->getCompany();
if (!$customerName) {
$customerName = $order->getOrderCustomer()->getLastName() .", ". $order->getOrderCustomer()->getFirstName();
}
$bearbeiter = "shopware";
$result = 'zeich_nr= "Shop' .$this->DOK_RECHNUNG .$config['documentNumber'] .'"' .$this->LINEBREAK
.'dokuart= "' .$this->DOK_RECHNUNG .'"'.$this->LINEBREAK
.'logi_verzeichnis = "Fr"'.$this->LINEBREAK
.'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
.'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
.'dok_dat_feld[14] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
.'dok_dat_feld[38] = "' .$bearbeiter .'"'.$this->LINEBREAK
.'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
.'dok_dat_feld[51] = "' . date("d.m.Y") .'"'.$this->LINEBREAK;
$result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
return $result;
}
Private function getCreditNoteOutput($order, $config)
{
$bearbeiter = "shopware";
$customerName = $order->getOrderCustomer()->getCompany();
if (!$customerName) {
$customerName = $order->getOrderCustomer()->getLastName() .", ". $order->getOrderCustomer()->getFirstName();
}
$result = 'zeich_nr = "Shop' .$this->DOK_GUTSCHRIFT .$config['documentNumber'] ."'" .$this->LINEBREAK
.'dokuart = "' .$this->DOK_GUTSCHRIFT .'"' .$this->LINEBREAK
.'var_nr = 1'.$this->LINEBREAK
.'logi_verzeichnis = "Fr"' .$this->LINEBREAK
.'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
.'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
.'dok_dat_feld[15] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
.'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
.'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
.'dok_dat_feld[51] = "' . date("d.m.Y") .'"'.$this->LINEBREAK;
// multiple Orders?
$result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
return $result;
}
Private function getDeliveryNoteOutput($order, $config)
{
/* zeich_nr = "RollenILSVK823000817" Dokument ID: "Shop", Dokumentart, Dokument Nr
dokuart = "ILSVK" Dokumentart
var_nr = "1" Konstante
logi_verzeichnis = "Fr" Konstante
dok_dat_feld[1] = "1209331" KundenNr
dok_dat_feld[2] = "PASOTEC GmbH" KundenName
dok_dat_feld[13] = "823000817" Dokument Nr
dok_dat_feld[38] = "PURSCHKES" Bearbeiter
dok_dat_feld[39] = "Rollen" Shop (=Konstante)
dok_dat_feld[51] = "12.10.2021" Datum
dok_dat_feld_60[1] = "KA53131" Auftrag
*/
$bearbeiter = "shopware";
$customerName = $order->getOrderCustomer()->getCompany();
if (!$customerName) {
$customerName = $order->getOrderCustomer()->getLastName() .", ". $order->getOrderCustomer()->getFirstName();
}
$result = 'zeich_nr = "Shop' .$this->DOK_LIEFERSCHEIN .$config['documentNumber'] .'"' .$this->LINEBREAK
.'dokuart = "' .$this->DOK_LIEFERSCHEIN .'"' .$this->LINEBREAK
.'var_nr = 1'.$this->LINEBREAK
.'logi_verzeichnis = "Fr"' .$this->LINEBREAK
.'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
.'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
.'dok_dat_feld[13] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
.'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
.'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
.'dok_dat_feld[51] = "' . date("d.m.Y") .'"'.$this->LINEBREAK;
$result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK;
return $result;
}
Private function getStornoBillOutput($order, $config)
{
/* zeich_nr = "RollenIGUVK32001379" Dokument ID: "Shop", Dokumentart, Dokument Nr
dokuart = "IGUVK" Dokumentart
var_nr = "1" Konstante
logi_verzeichnis = "Fr" Konstante
dok_dat_feld[1] = "1201307" KundenNr
dok_dat_feld[2] = "Universitätsklinikum Dresden" KundenName
dok_dat_feld[15] = "32001379" Dokument Nr
dok_dat_feld[38] = "LINDHORSTJ" Bearbeiter
dok_dat_feld[39] = "Rollen" SHOP (=Konstante)
dok_dat_feld[51] = "12.10.2021" Datum
dok_dat_feld_60[1] = "KA54091" Auftrag
dok_dat_feld_60[2] = "KA54091" Auftrag
dok_dat_feld_61[1] = "00050066" Lieferschein
dok_dat_feld_61[2] = "00050066" Lieferschein
*/
$bearbeiter = "shopware";
$customerName = $order->getOrderCustomer()->getCompany();
if (!$customerName) {
$customerName = $order->getOrderCustomer()->getLastName() .", ". $order->getOrderCustomer()->getFirstName();
}
$result = 'zeich_nr = "Shop' .$this->DOK_RECHNUNGSSTORNO .$config['documentNumber'] .'"' .$this->LINEBREAK
.'dokuart = "' .$this->DOK_RECHNUNGSSTORNO .'"' .$this->LINEBREAK
.'var_nr = 1'.$this->LINEBREAK
.'logi_verzeichnis = "Fr"' .$this->LINEBREAK
.'dok_dat_feld[1] = "' .$order->getOrderCustomer()->getCustomerNumber() .'"'.$this->LINEBREAK
.'dok_dat_feld[2] = "' .$customerName .'"'.$this->LINEBREAK
.'dok_dat_feld[15] = "' .$config['documentNumber'] .'"'.$this->LINEBREAK
.'dok_dat_feld[38] = "' .$bearbeiter .'"' .$this->LINEBREAK
.'dok_dat_feld[39] = "Shop"'.$this->LINEBREAK
.'dok_dat_feld[51] = "' . date("d.m.Y") .'"'.$this->LINEBREAK;
// in shopware, a storno bill references a single invoice and thus a single order
$invoiceNr = $config['custom']['invoiceNumber'] ?? '';
$result .= 'dok_dat_feld_60[1] = "' .$order->getOrderNumber() .'"' .$this->LINEBREAK
.'dok_dat_feld_61[1] = "' .$invoiceNr .'"' .$this->LINEBREAK;
return $result;
}
}