-
-
- {|[NACHRICHT_BETREFF] |}
-
-
+
diff --git a/www/pages/content/uebersetzung_edit.tpl b/www/pages/content/uebersetzung_edit.tpl
new file mode 100644
index 00000000..663757a8
--- /dev/null
+++ b/www/pages/content/uebersetzung_edit.tpl
@@ -0,0 +1,90 @@
+
+
diff --git a/www/pages/content/uebersetzung_list.tpl b/www/pages/content/uebersetzung_list.tpl
new file mode 100644
index 00000000..7cd3c1a3
--- /dev/null
+++ b/www/pages/content/uebersetzung_list.tpl
@@ -0,0 +1,10 @@
+
+
+
+ [MESSAGE]
+ [TAB1]
+ [TAB1NEXT]
+
+
diff --git a/www/pages/content/upgrade.tpl b/www/pages/content/upgrade.tpl
new file mode 100644
index 00000000..3acd5379
--- /dev/null
+++ b/www/pages/content/upgrade.tpl
@@ -0,0 +1,108 @@
+
+
+
+
+ [MESSAGE]
+
+
+
+
+
+ {|OpenXE Upgrade-System|}
+Das Upgrade funktioniert in 2 Schritten: Dateien aktualisieren, Datenbank auffrischen. Wenn das Upgrade lange läuft, kann der Fortschritt in einem neuen Fenster mit "Anzeige auffrischen" angezeigt werden.
+Falls nach einem Abbruch oder schwerwiegenden Fehler kein Upgrade möglich ist, im Hauptordner den Ordner ".git" löschen und das Upgrade in der Konsole erneut durchführen.
+Dazu im Unterordner "upgrade" diesen Befehl starten: ./upgrade.sh -do
+
+
+
+
+
+
+ [FORMHANDLEREVENT]
+
+
+
+
+
+
+
+
+
+ {|Aktuelle Version|}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/www/pages/dateien.php b/www/pages/dateien.php
index ac4a3c5a..f4c96cbd 100644
--- a/www/pages/dateien.php
+++ b/www/pages/dateien.php
@@ -95,15 +95,15 @@ class Dateien {
$heading = array('ID','Titel', 'Beschreibung', 'Verknüpfung', 'Geloescht', 'Logdatei', 'Menü');
$width = array('10%'); // Fill out manually later
- $findcols = array('d.id','d.titel', 'd.beschreibung', 'd.nummer', 'd.geloescht', 'd.logdatei');
- $searchsql = array('d.titel', 'd.beschreibung', 'd.nummer', 'd.geloescht', 'd.logdatei');
+ $findcols = array('d.id','d.titel', 'd.beschreibung', 'ds.objekt', 'd.geloescht', 'd.logdatei');
+ $searchsql = array('d.titel', 'd.beschreibung', 'd.nummer', 'd.geloescht', 'd.logdatei','ds.objekt');
$defaultorder = 1;
$defaultorderdesc = 0;
$menu = "
";
- $sql = "SELECT SQL_CALC_FOUND_ROWS d.id, d.id, d.titel, d.beschreibung, GROUP_CONCAT(ds.objekt SEPARATOR ', '), d.geloescht, d.logdatei, d.id FROM datei d LEFT join datei_stichwoerter ds ON ds.datei = d.id";
+ $sql = "SELECT SQL_CALC_FOUND_ROWS d.id, d.id, d.titel, d.beschreibung, GROUP_CONCAT(ds.objekt SEPARATOR ', ') as verknuepfung, d.geloescht, d.logdatei, d.id FROM datei d LEFT join datei_stichwoerter ds ON ds.datei = d.id";
$where = "1";
$count = "SELECT count(DISTINCT id) FROM datei WHERE $where";
diff --git a/www/pages/firmendaten.php b/www/pages/firmendaten.php
index 0ece581b..e06eae2b 100644
--- a/www/pages/firmendaten.php
+++ b/www/pages/firmendaten.php
@@ -1016,7 +1016,7 @@ class Firmendaten {
,'zahlungszielskonto','kleinunternehmer','schnellanlegen','bestellvorschlaggroessernull','immernettorechnungen','rechnung_header','rechnung_footer',
'lieferschein_header','lieferschein_footer','auftrag_header','auftrag_footer','angebot_header','angebot_footer','gutschrift_header','gutschrift_footer','bestellung_header','bestellung_footer',
'arbeitsnachweis_header','arbeitsnachweis_footer','provisionsgutschrift_header','provisionsgutschrift_footer','proformarechnung_header','proformarechnung_footer','eu_lieferung_vermerk','export_lieferung_vermerk'
- ,'wareneingang_kamera_waage','layout_iconbar','passwort','host','port','mailssl','signatur','email','absendername','bcc1','bcc2'
+ ,'wareneingang_kamera_waage','layout_iconbar','passwort','host','port','mailssl','signatur','email','absendername','bcc1','bcc2','bcc3'
,'firmenfarbe','name','strasse','plz','ort','steuernummer','projekt','steuer_positionen_export','tabsnavigationfarbe','tabsnavigationfarbeschrift'
);
@@ -1719,6 +1719,7 @@ class Firmendaten {
$this->app->Tpl->Set('ABSENDERNAME' , $data[0]['absendername']);
$this->app->Tpl->Set('BCC1' , $data[0]['bcc1']);
$this->app->Tpl->Set('BCC2' , $data[0]['bcc2']);
+ $this->app->Tpl->Set('BCC3' , $data[0]['bcc3']);
$this->app->Tpl->Set('FIRMENFARBE' , $data[0]['firmenfarbe']);
$this->app->Tpl->Set('NAME' , $data[0]['name']);
$this->app->Tpl->Set('STRASSE' , $data[0]['strasse']);
@@ -2072,7 +2073,8 @@ class Firmendaten {
$this->app->Tpl->Set('EMAIL' , $data['email']);
$this->app->Tpl->Set('ABSENDERNAME' , $data['absendername']);
$this->app->Tpl->Set('BCC1' , $data['bcc1']);
- $this->app->Tpl->Set('BCC2' , $data['bcc2']);
+ $this->app->Tpl->Set('BCC2' , $data['bcc2']);
+ $this->app->Tpl->Set('BCC3' , $data['bcc3']);
$this->app->Tpl->Set('FIRMENFARBE' , $data['firmenfarbe']);
$this->app->Tpl->Set('NAME' , $data['name']);
$this->app->Tpl->Set('STRASSE' , $data['strasse']);
@@ -2224,6 +2226,7 @@ class Firmendaten {
$data['absendername'] = ($this->app->Secure->POST["absendername"]);
$data['bcc1'] = ($this->app->Secure->POST["bcc1"]);
$data['bcc2'] = ($this->app->Secure->POST["bcc2"]);
+ $data['bcc3'] = ($this->app->Secure->POST["bcc3"]);
$data['name'] = ($this->app->Secure->POST["name"]);
$data['firmenfarbe'] = ($this->app->Secure->POST["firmenfarbe"]);
$data['strasse'] = ($this->app->Secure->POST["strasse"]);
diff --git a/www/pages/importvorlage.php b/www/pages/importvorlage.php
index 18af7c73..fdc370aa 100644
--- a/www/pages/importvorlage.php
+++ b/www/pages/importvorlage.php
@@ -3739,7 +3739,7 @@ class Importvorlage extends GenImportvorlage {
}
$altervk = $this->app->DB->Select("SELECT preis FROM verkaufspreise WHERE artikel='$artikelid' AND ab_menge='".$tmp['verkaufspreis'.$verkaufspreisanzahl.'menge'][$i]."'
- AND (gueltig_bis='0000-00-00' OR gueltig_bis >=NOW() ) AND adresse <='$_kundenid' ".($gruppe?" AND gruppe = '".$gruppe."'":" AND (is_null(gruppe) or gruppe = '') ")." LIMIT 1");
+ AND (gueltig_bis='0000-00-00' OR gueltig_bis >=NOW() ) AND adresse <='$_kundenid' ".($gruppe?" AND gruppe = '".$gruppe."'":" AND ((gruppe IS NULL) or gruppe = '') ")." LIMIT 1");
if($altervk != str_replace(',','.',$tmp['verkaufspreis'.$verkaufspreisanzahl.'netto'][$i]) && str_replace(',','.',$tmp['verkaufspreis'.$verkaufspreisanzahl.'netto'][$i]))
{
@@ -3755,7 +3755,7 @@ class Importvorlage extends GenImportvorlage {
//verkaufspreis3internerkommentar'][$i]
$this->app->DB->Update("UPDATE verkaufspreise SET gueltig_bis=DATE_SUB(NOW(),INTERVAL 1 DAY)
- WHERE artikel='".$artikelid."' AND adresse='$_kundenid' ".($gruppe?" AND gruppe = '".$gruppe."'":" AND (is_null(gruppe) or gruppe = '') ")."
+ WHERE artikel='".$artikelid."' AND adresse='$_kundenid' ".($gruppe?" AND gruppe = '".$gruppe."'":" AND ((gruppe IS NULL) or gruppe = '') ")."
AND ab_menge='".$tmp['verkaufspreis'.$verkaufspreisanzahl.'menge'][$i]."' LIMIT 1");
$verkaufspreis1stueckdivisor = 1;
diff --git a/www/pages/lager.php b/www/pages/lager.php
index 0d252509..264fbfff 100644
--- a/www/pages/lager.php
+++ b/www/pages/lager.php
@@ -1346,17 +1346,17 @@ class Lager extends GenLager {
case "lager_reservierungen":
$allowed['lager'] = array('reservierungen');
- $heading = array('Kunde','Belegart','Belegnr','Status','Artikel','Menge','Projekt','Grund','Menü');
- $width = array('20%','20%','5%','10%','20%','1%');
- $findcols = array('t.kunde', 't.typ', 't.belegnr', 't.status', 't.Artikel', 't.menge', 't.projekt', 't.grund', 't.rid');
- $searchsql = array('t.kunde', 't.typ', 't.belegnr', 't.status', 't.Artikel', $app->erp->FormatMenge('t.menge'), 't.projekt', 't.grund');
+ $heading = array('Kunde','Belegart','Belegnr','Status','Artikelnummer','Artikel','Menge','Projekt','Grund','Menü');
+ $width = array('20%', '10%', '5%', '5%', '5%', '20%', '1%', '10%', '20%');
+ $findcols = array('t.kunde', 't.typ', 't.belegnr', 't.status','t.Artikelnummer', 't.Artikel', 't.menge', 't.projekt', 't.grund', 't.rid');
+ $searchsql = array('t.kunde', 't.typ', 't.belegnr', 't.status','t.Artikelnummer', 't.Artikel', $app->erp->FormatMenge('t.menge'), 't.projekt', 't.grund');
$defaultorder = 1; //Optional wenn andere Reihenfolge gewuenscht
$defaultorderdesc = 1;
//$sumcol = 9;
$menu = "
";
- $alignright = array(6);
- $numbercols = array(5);
+ $alignright = array(7);
+ $numbercols = array(6);
$menucol = 5;
//$moreinfo = true;
$sql = "
@@ -1366,6 +1366,7 @@ class Lager extends GenLager {
t.typ,
t.belegnr,
t.status,
+ t.Artikelnummer,
t.Artikel,
".$app->erp->FormatMenge('t.menge').",
t.projekt,
@@ -1375,43 +1376,43 @@ class Lager extends GenLager {
FROM
(
(
- SELECT r.id as rid, adr.name as kunde,'Auftrag' as typ,if(auf.belegnr = '','ENTWURF',auf.belegnr) as belegnr ,if(auf.status = '','angelegt',auf.status) as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Auftrag' as typ,if(auf.belegnr = '','ENTWURF',auf.belegnr) as belegnr ,if(auf.status = '','angelegt',auf.status) as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
INNER JOIN auftrag auf ON auf.id = r.parameter AND r.objekt = 'auftrag'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,'Lieferschein' as typ,if(l.belegnr = '','ENTWURF',l.belegnr) as belegnr ,if(l.status = '','angelegt',l.status) as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Lieferschein' as typ,if(l.belegnr = '','ENTWURF',l.belegnr) as belegnr ,if(l.status = '','angelegt',l.status) as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
INNER JOIN lieferschein l ON l.id = r.parameter AND r.objekt = 'lieferschein'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,'Produktion' as typ,if(l.belegnr = '','ENTWURF',l.belegnr) as belegnr ,if(l.status = '','angelegt',l.status) as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Produktion' as typ,if(l.belegnr = '','ENTWURF',l.belegnr) as belegnr ,if(l.status = '','angelegt',l.status) as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
INNER JOIN produktion l ON l.id = r.parameter AND r.objekt = 'produktion'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,'Auftrag' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Auftrag' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
LEFT JOIN auftrag auf ON auf.id = r.parameter AND r.objekt = 'auftrag' WHERE isnull(auf.id) AND r.objekt = 'auftrag'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,'Lieferschein' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Lieferschein' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
LEFT JOIN lieferschein l ON l.id = r.parameter AND r.objekt = 'lieferschein' WHERE isnull(l.id) AND r.objekt = 'lieferschein'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,'Produktion' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,'Produktion' as typ,'GELÖSCHT' as belegnr ,'GELÖSCHT' as status, a.nummer as Artikelnummer, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id
LEFT JOIN produktion l ON l.id = r.parameter AND r.objekt = 'produktion' WHERE isnull(l.id) AND r.objekt = 'produktion'
)
UNION ALL
(
- SELECT r.id as rid, adr.name as kunde,r.objekt as typ,'' as belegnr , '' as status, a.name_de as Artikel,r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
+ SELECT r.id as rid, adr.name as kunde,r.objekt as typ,'' as belegnr , '' as status, a.nummer as Artikelnummer, a.name_de as Artikel, r.menge,p.abkuerzung as projekt,r.grund, r.id FROM lager_reserviert r LEFT JOIN artikel a ON a.id=r.artikel LEFT JOIN projekt p ON
p.id=r.projekt LEFT JOIN adresse adr ON r.adresse=adr.id WHERE r.objekt <> 'auftrag' AND r.objekt <> 'lieferschein' AND r.objekt <> 'produktion'
)
diff --git a/www/pages/layoutvorlagen.php b/www/pages/layoutvorlagen.php
index 0b7a58c1..c7663c50 100644
--- a/www/pages/layoutvorlagen.php
+++ b/www/pages/layoutvorlagen.php
@@ -1,915 +1,915 @@
-app = $app;
- if($intern) {
- return;
- }
- $this->app->ActionHandlerInit($this);
- $this->app->ActionHandler("list", "LayoutvorlagenList");
- $this->app->ActionHandler("edit", "LayoutvorlagenEdit");
- $this->app->ActionHandler("create", "LayoutvorlagenCreate");
- $this->app->ActionHandler("copy", "LayoutvorlagenCopy");
- $this->app->ActionHandler("getposition", "LayoutvorlagenGetPosition");
- $this->app->ActionHandler("saveposition", "LayoutvorlagenSavePosition");
- $this->app->ActionHandler("createposition", "LayoutvorlagenCreatePosition");
- $this->app->ActionHandler("deleteposition", "LayoutvorlagenDeletePosition");
- $this->app->ActionHandler("delete", "LayoutvorlagenDelete");
- $this->app->ActionHandler("download", "LayoutvorlagenDownload");
- $this->app->ActionHandler("export", "LayoutvorlagenExport");
- //$this->app->ActionHandler("import", "LayoutvorlagenImport");
-
- $this->app->ActionHandler("imgvorschau", "LayoutvorlagenImgVorschau");
-
- $this->app->erp->Headlines('Layoutvorlagen');
-
- $this->app->ActionHandlerListen($app);
- }
-
- public function LayoutvorlagenCopy()
- {
- $id = (int)$this->app->Secure->GetGET('id');
- if($id)
- {
- $layoutvorlage = $this->app->DB->SelectArr("SELECT * FROM layoutvorlagen WHERE id = '$id'");
- if($layoutvorlage)
- {
- $this->app->DB->Insert("INSERT INTO layoutvorlagen (id) VALUES('')");
- $newvorlage = $this->app->DB->GetInsertID();
- $layoutvorlage[0]['name'] .= ' (Kopie)';
- $this->app->FormHandler->ArrayUpdateDatabase("layoutvorlagen",$newvorlage,$layoutvorlage[0],true);
- $positionen = $this->app->DB->SelectArr("SELECT * FROM layoutvorlagen_positionen WHERE layoutvorlage = '$id'");
- if($positionen)
- {
- foreach($positionen as $position)
- {
- $this->app->DB->Insert("INSERT INTO layoutvorlagen_positionen (id) VALUES('')");
- $newvorlagepos = $this->app->DB->GetInsertID();
- $position['layoutvorlage'] = $newvorlage;
- $this->app->FormHandler->ArrayUpdateDatabase("layoutvorlagen_positionen",$newvorlagepos,$position, true);
- }
- }
- }
- }
- header('Location: index.php?module=layoutvorlagen&action=list');
- exit;
- }
-
- public function LayoutvorlagenDownload($id = 0)
- {
- if(!$id)$id = $this->app->Secure->GetGET('id');
- // mit infos aus zertifikat und konkreten inhalten
- $projekt = "";
- $Brief = new LayoutvorlagenPDF($this->app, $projekt);
- $Brief->GetLayoutvorlage($id);
- $Brief->inlineDocument();
- }
-
-
- public function LayoutvorlagenMenu() {
- $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=list","Übersicht");
- }
-
- public function LayoutvorlagenList() {
-
- //$this->LayoutvorlagenMenu();
- $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=list","Übersicht");
- $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Neu");
-
- $layoutanlegen = $this->app->Secure->GetPOST('layoutanlegen');
-
-
- if ($layoutanlegen) {
-
- $row['name'] = $this->app->Secure->GetPOST('name');
- //$row['name'] = preg_replace('#[^-A-Za-z0-9]#', '-', $row['name']);
- $row['typ'] = $this->app->Secure->GetPOST('typ');
- $row['format'] = $this->app->Secure->GetPOST('format');
- $row['kategorie'] = $this->app->Secure->GetPOST('kategorie');
-
- if ($row['name']) {
-
- $this->app->DB->Insert('
- INSERT INTO
- layoutvorlagen
- SET
- name = "' . $row['name'] . '",
- typ = "' . $row['typ'] . '",
- format = "' . $row['format'] . '",
- kategorie = "' . $row['kategorie'] . '"
- ');
-
- $id = $this->app->DB->GetInsertID();
- if ($id) {
- header('location: index.php?module=layoutvorlagen&action=edit&id=' . $id);
- exit;
- }
- }
- }
- if($this->app->Secure->GetPOST('cmd') === 'import') {
- if (!empty($_FILES['importfile']['tmp_name'])) {
- $string = file_get_contents($_FILES['importfile']['tmp_name']);
- $ret = $this->importJson($string, $this->app->Secure->GetPOST('ueberschreiben'));
- if(!empty($ret['message'])) {
- $this->app->Tpl->Add('ERRORMSG', $ret['message']);
- }
- }
- else {
- $this->app->Tpl->Add('ERRORMSG', "Keine Datei ausgewält");
- }
- }
-
-
- $this->app->YUI->TableSearch('TABELLE', 'layoutvorlagen_list');
- $this->app->Tpl->Parse('PAGE',"layoutvorlagen_list.tpl");
-
- }
-
- /**
- * @param string $string
- * @param bool $overwrite
- *
- * @return array
- */
- public function importJson($string, $overwrite = false)
- {
- $ret = [];
- if(!(NULL !== $json = json_decode($string))) {
- return ['status' => 0, 'message' => 'Keine gültige Datei'];
- }
- if(empty($json->Layout) && empty($json->Layout->name)) {
- return ['status' => 0, 'message' => 'Keine gültige Datei Fehlendes Element: Layout'];
- }
-
- $altesLayout = $this->app->DB->SelectArr(
- sprintf(
- "select * from layoutvorlagen where name like '%s'",
- $this->app->DB->real_escape_string($json->Layout->name)
- )
- );
-
- if(!empty($altesLayout) && !$overwrite) {
- return ['status' => 0, 'message' => 'Es existiert bereis ein Layout mit dem Namen','id' => $altesLayout['id']];
- }
-
- if(isset($json->Layout->id)) {
- unset($json->Layout->id);
- }
- $columns = $this->app->DB->SelectArr('SHOW COLUMNS FROM layoutvorlagen');
- $error = false;
- foreach($json->Layout as $k => $v) {
- $found = false;
- foreach($columns as $k2 => $v2) {
- if($v2['Field'] == $k) {
- $found = true;
- }
- }
- if(!$found) {
- $error = true;
- }
- }
- $columnspos = $this->app->DB->SelectArr('SHOW COLUMNS FROM layoutvorlagen_positionen');
- if(!empty($json->Layoutpositionen)) {
- foreach($json->Layoutpositionen as $k => $pos) {
- if(isset($pos->id)) {
- unset($json->Layoutpositionen[$k]->id);
- }
- if(isset($pos->layoutvorlage)) {
- unset($json->Layoutpositionen[$k]->id);
- }
-
- foreach($pos as $kp => $vp) {
- $found = false;
- foreach($columnspos as $k2 => $v2) {
- if($v2['Field'] == $kp) {
- $found = true;
- }
- }
- if(!$found) {
- $error = true;
- }
- }
- }
- }
- if(!empty($error)) {
- return ['status' => 0, 'message' => 'Keine gültige Datei: falsche Elemente'];
- }
-
- $query = "insert into layoutvorlagen (";
- $i = 0;
- foreach($columns as $k => $v) {
- if($v['Field'] !== 'id') {
- $i++;
- if($i > 1) {
- $query .= ', ';
- }
- $query .= $v['Field'];
- }
- }
- $query .= ') values (';
- $i = 0;
- foreach($columns as $k => $v) {
- if($v['Field'] !== 'id') {
- $i++;
- if($i > 1) {
- $query .= ', ';
- }
- $query .= "'";
- $fieldName = $v['Field'];
- if(isset($json->Layout->$fieldName)) {
- $query .= $this->app->DB->real_escape_string($json->Layout->$fieldName);
- }
- $query .= "'";
- }
- }
- $query .= ')';
-
- //alte Löschen falls existiert
- if($altesLayout) {
- foreach($altesLayout as $l) {
- if($l['id']) {
- $this->app->DB->Delete("delete from layoutvorlagen_positionen where layoutvorlage = ".$l['id']);
- $this->app->DB->Delete("delete from layoutvorlagen where id = ".$l['id']);
- }
- }
- }
- //
- $this->app->DB->Insert($query);
- $newid = $this->app->DB->GetInsertID();
-
- if(empty($newid)) {
- return ['status' => 0, 'message' => 'Fehler beim Erstellen des Layouts'];
- }
-
- $j = 0;
- foreach ($json->Layoutpositionen as $kpos => $pos) {
-
- $querypos[$j] = "insert into layoutvorlagen_positionen (layoutvorlage";
- $i = 0;
- foreach($columnspos as $k => $v) {
- if($v['Field'] !== 'id' && $v['Field'] !== 'layoutvorlage') {
- $i++;
- $querypos[$j] .= ', ';
- $querypos[$j] .= $v['Field'];
- }
- }
-
- $querypos[$j] .= ") values ('".$newid."'";
- $i = 0;
- foreach($columnspos as $k => $v) {
- if($v['Field'] !== 'id' && $v['Field'] !== 'layoutvorlage') {
- $i++;
- $querypos[$j] .= ', ';
- $querypos[$j] .= "'";
- $fieldName = $v['Field'];
- if(isset($pos->$fieldName)) {
- $querypos[$j] .= $this->app->DB->real_escape_string($pos->$fieldName);
- }
- $querypos[$j] .= "'";
- }
- }
-
- $querypos[$j] .= ")";
- $j++;
- }
- if(isset($querypos)) {
- $fehler = false;
- foreach($querypos as $qp) {
- $this->app->DB->Insert($qp);
- if($this->app->DB->error()){
- $ret['error'] = $this->app->DB->error();
- $fehler = true;
- }
- }
- }
- if($fehler) {
- return [
- 'status' => 0,
- 'message' => (empty($ret['error'])?'':$ret['error'].' ')
- . 'Fehler beim Erstellen von einer oder mehreren Layoutposition(en)'
- ];
- }
-
- return [
- 'message' => 'Layout ' .$json->Layout->name. ' erfolgreich erstellt',
- 'status' => true, 'id' => $newid
- ];
- }
-
- public function LayoutvorlagenEdit() {
-
- $id = $this->app->Secure->GetGET('id');
- $cmd = $this->app->Secure->GetGET('cmd');
- $speichern = $this->app->Secure->GetPOST('layoutspeichern');
-
- if ($speichern) {
- $name = $this->app->Secure->GetPOST('name');
- $typ = $this->app->Secure->GetPOST('typ');
- $format = $this->app->Secure->GetPOST('format');
- $kategorie = $this->app->Secure->GetPOST('kategorie');
- $projekt = $this->app->Secure->GetPOST('layoutvorlagen_projekt');
- $delete_hintergrund = $this->app->Secure->GetPOST('delete_hintergrund')==''?false:true;
- $pdf_hintergrund = $_FILES['pdf_hintergrund'];
-
- if (isset($pdf_hintergrund['tmp_name']) && ($pdf_hintergrund['type'] == 'application/pdf' || $pdf_hintergrund['type'] == 'application/force-download' || $pdf_hintergrund['type'] =='binary/octet-stream' || $pdf_hintergrund['type'] == 'application/octetstream')) {
- $fp = fopen($pdf_hintergrund['tmp_name'], 'r');
- $imgContent = fread($fp, filesize($pdf_hintergrund['tmp_name']));
- fclose($fp);
- $sets[] = 'pdf_hintergrund = "' . base64_encode($imgContent) . '"';
- } elseif($delete_hintergrund) {
- $sets[] = 'pdf_hintergrund = ""';
- }
-
- $sets[] = 'name = "' . $name . '" ';
- $sets[] = 'typ = "' . $typ . '" ';
- $sets[] = 'format = "' . $format . '" ';
- $sets[] = 'kategorie = "' . $kategorie . '" ';
-
- if ($sets) {
- $this->app->DB->Insert('UPDATE layoutvorlagen SET ' . implode(', ', $sets) . ' WHERE id = ' . $id);
- }
-
- if($projekt != ''){
- $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung = '$projekt' LIMIT 1");
- }else{
- $projektid = 0;
- }
-
- $this->app->DB->Update("UPDATE layoutvorlagen SET projekt = '$projektid' WHERE id = '$id'");
-
- }
-
- $this->app->YUI->AutoComplete("kategorie","layoutvorlagenkategorie");
- $this->app->YUI->AutoComplete("layoutvorlagen_projekt", "projektname", 1);
- //$this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Neu");
- $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=edit&id=" . $id . "","Details");
-
- $vorlage = $this->app->DB->SelectArr('SELECT * FROM layoutvorlagen WHERE id = ' . $id);
- $vorlage = reset($vorlage);
-
- if ($cmd) {
- switch ($cmd) {
- case 'pdfvorschau':
- $pdf_hintergrund = $this->app->DB->Select('SELECT pdf_hintergrund FROM layoutvorlagen WHERE id = ' . $id);
- $pdf_hintergrund = base64_decode($pdf_hintergrund);
-
- header("Content-type: application/pdf");
- header('Content-disposition: attachment; filename="pdf_hintergrund.pdf"');
- print $pdf_hintergrund;
-
-
- break;
- default:
- break;
- }
- exit;
- }
-
- $this->app->User->SetParameter('layoutvorlagen_id', $id);
-
- $this->app->Tpl->Add('NAME', $vorlage['name']);
- $this->app->Tpl->Add('KATEGORIE', $vorlage['kategorie']);
-
- if($vorlage['projekt'] > 0){
- $projektname = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '".$vorlage['projekt']."' LIMIT 1");
- if($projektname != ""){
- $this->app->Tpl->Add('PROJEKT', $projektname);
- }
- }
-
- if ($vorlage['pdf_hintergrund']) {
- $this->app->Tpl->Add('PDFVORSCHAU', '
');
- }
- $this->app->Tpl->Add('TAB3', '
');
- /*
- $schriftarten = $this->app->erp->GetSchriftarten();
- //Test
- $schriftarten['times'] = "Times";
- $schriftarten['juliusc'] = 'juliusc';
- $schriftarten['bernard'] = 'Bernard';
- $schriftarten['HLBC____'] = 'HLBC____';
- */
- $schriftartena = $this->app->erp->GetFonts();
- foreach($schriftartena as $kk => $vv)
- {
- $schriftarten[$kk] = $vv['name'];
-
- }
- //Test End
- $schriftartenTpl = '';
- if ($schriftarten) {
- foreach ($schriftarten as $schriftartKey => $schriftart) {
- $schriftartenTpl .= '
' . $schriftart . ' ';
- }
- }
- $this->app->Tpl->Add(SCHRIFTARTEN, $schriftartenTpl);
-
- $rahmenbreiten = array(
- '0' => 'Kein Rahmen',
- '1' => '1',
- '2' => '2',
- '3' => '3',
- '4' => '4',
- '5' => '5',
- '6' => '6',
- '7' => '7',
- '8' => '8',
- '9' => '9',
- '10' => '10'
- );
- $rahmenTpl = '';
- if ($rahmenbreiten) {
- foreach ($rahmenbreiten as $rahmenbreiteKey => $rahmenbreite) {
- $rahmenTpl .= '
' . $rahmenbreite . ' ';
- }
- }
-
- $positionen = $this->app->DB->SelectArr('
- SELECT
- id,
- name,
- typ
- FROM
- layoutvorlagen_positionen
- WHERE
- layoutvorlage = "' . $id . '"
- ');
-
- $positionenTpl = '';
- $positionenTpl .= '
Keine ';
- if ($positionen) {
- foreach ($positionen as $position) {
- $positionenTpl .= '
' . $position['name'] . ' (' . $position['typ'] . ') ';
- }
- }
-
- $schriftausrichtungen = array('left' => 'Links', 'center' => 'Zentriert', 'right' => 'Rechts');
- $schriftausrichtungenTpl = '';
- if ($schriftausrichtungen) {
- foreach($schriftausrichtungen as $schriftausrichtungKey => $schriftausrichtung) {
- $schriftausrichtungenTpl .= '
' . $schriftausrichtung . ' ';
- }
- }
-
- $formate = array('A4' => 'DIN A4 Hoch', 'A4L' => 'DIN A4 Quer','A5' => 'DIN A5 Hoch', 'A5L' => 'DIN A5 Quer','A6' => 'DIN A6 Hoch', 'A6L' => 'DIN A6 Quer');
- $formatTpl = '';
- if ($formate) {
- foreach($formate as $formatKey => $formatBeschriftung) {
- $formatTpl .= '
' . $formatBeschriftung . ' ';
- }
- }
-
-
-
- $this->app->YUI->ColorPicker("schrift_farbe");
- $this->app->YUI->ColorPicker("hintergrund_farbe");
- $this->app->YUI->ColorPicker("rahmen_farbe");
-
- $this->app->Tpl->Add('SCHRIFTAUSRICHTUNGEN', $schriftausrichtungenTpl);
- $this->app->Tpl->Add('POSITIONPARENT', $positionenTpl);
-
- $this->app->Tpl->Add('FORMAT', $formatTpl);
- $this->app->Tpl->Add('RAHMEN', $rahmenTpl);
- $this->app->YUI->TableSearch('TABELLE', 'layoutvorlagen_edit');
- $this->app->Tpl->Parse('PAGE',"layoutvorlagen_edit.tpl");
-
- }
-
- public function LayoutvorlagenCreate() {
-
- $speichern = $this->app->Secure->GetPOST('layouterstellen');
-
- if ($speichern) {
-
-
- $felder = array('name', 'typ', 'format', 'kategorie');
- $sets = array();
- if ($felder) {
- foreach ($felder as $feld) {
- $sets[] = $feld . ' = "' . $this->app->Secure->GetPOST($feld) . '"';
- }
- }
-
- $projekt = $this->app->Secure->GetPOST('layoutvorlagen_projekt');
- if($projekt != ''){
- $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung = '$projekt' LIMIT 1");
- }else{
- $projektid = 0;
- }
-
- $query = ('INSERT INTO layoutvorlagen SET ' . implode(', ', $sets) . ' ');
- $this->app->DB->Insert($query);
-
-
- $layoutvorlagenId = $this->app->DB->GetInsertID();
-
- $this->app->DB->Update("UPDATE layoutvorlagen SET projekt = '$projektid' WHERE id = '$layoutvorlagenId'");
-
-
- $delete_hintergrund = $this->app->Secure->GetPOST('delete_hintergrund')==''?false:true;
- $pdf_hintergrund = $_FILES['pdf_hintergrund'];
- if (isset($pdf_hintergrund['tmp_name']) && ($pdf_hintergrund['type'] == 'application/pdf' || $pdf_hintergrund['type'] == 'application/force-download' || $pdf_hintergrund['type'] =='binary/octet-stream' || $pdf_hintergrund['type'] == 'application/octetstream')) {
- $fp = fopen($pdf_hintergrund['tmp_name'], 'r');
- $imgContent = fread($fp, filesize($pdf_hintergrund['tmp_name']));
- fclose($fp);
- $sets[] = 'pdf_hintergrund = "' . base64_encode($imgContent) . '"';
- } elseif($delete_hintergrund) {
- $sets[] = 'pdf_hintergrund = ""';
- }
-
- if ($sets) {
- $this->app->DB->Insert('UPDATE layoutvorlagen SET ' . implode(', ', $sets) . ' WHERE id = ' . $layoutvorlagenId);
- }
-
-
-
-
-
- if ($layoutvorlagenId) {
- header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlagenId);
- exit;
- }
-
- }
-
- $this->app->YUI->AutoComplete("kategorie","layoutvorlagenkategorie");
- $this->app->YUI->AutoComplete("layoutvorlagen_projekt", "projektname", 1);
-
- $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Erstellen");
- $this->app->Tpl->Parse('PAGE','layoutvorlagen_create.tpl');
-
- }
-
- public function LayoutvorlagenGetPosition() {
-
- $id = $this->app->Secure->GetPOST('id');
- $row = $this->app->DB->SelectRow('SELECT * FROM layoutvorlagen_positionen WHERE id = ' . $id);
-
- if ($row['bild_deutsch']) {
- $bilddata['bild_deutsch'] = '
VORSCHAU ';
- unset($row['bild_deutsch']);
- }
-
- if ($row['bild_englisch']) {
- $bilddata['bild_englisch'] = '
VORSCHAU ';
- unset($row['bild_englisch']);
- }
-
- echo json_encode(array(
- 'status' => 1,
- 'statusText' => '',
- 'row' => $row,
- 'bilddata' => $bilddata
- ));
- $this->app->ExitXentral();
- }
-
-
- public function LayoutvorlagenSavePosition() {
-
- $id = $this->app->Secure->GetPOST('id');
- $typ = $this->app->Secure->GetPOST('typ');
-
- $name = $this->app->Secure->GetPOST('name');
- $name = strtolower($name);
- $name = preg_replace('#[^-A-Za-z0-9]#', '-', $name);
-
- $beschreibung = $this->app->Secure->GetPOST('beschreibung');
- $position_typ = $this->app->Secure->GetPOST('position_typ');
- $position_x = $this->app->Secure->GetPOST('position_x');
- $position_y = $this->app->Secure->GetPOST('position_y');
- $position_parent = $this->app->Secure->GetPOST('position_parent');
- $breite = $this->app->Secure->GetPOST('breite');
- $hoehe = $this->app->Secure->GetPOST('hoehe');
- $schrift_art = $this->app->Secure->GetPOST('schrift_art');
- $schrift_groesse = $this->app->Secure->GetPOST('schrift_groesse');
- $zeilen_hoehe = $this->app->Secure->GetPOST('zeilen_hoehe');
- $schrift_align = $this->app->Secure->GetPOST('schrift_align');
- $schrift_farbe = $this->app->Secure->GetPOST('schrift_farbe');
- $hintergrund_farbe = $this->app->Secure->GetPOST('hintergrund_farbe');
- $rahmen = $this->app->Secure->GetPOST('rahmen');
- $rahmen_farbe = $this->app->Secure->GetPOST('rahmen_farbe');
- $sichtbar = ($this->app->Secure->GetPOST('sichtbar')=='')?'0':'1';
- $schrift_fett = ($this->app->Secure->GetPOST('schrift_fett')=='')?'0':'1';
- $schrift_kursiv = ($this->app->Secure->GetPOST('schrift_kursiv')=='')?'0':'1';
- $schrift_underline = ($this->app->Secure->GetPOST('schrift_underline')=='')?'0':'1';
- //$this->app->erp->LogFile("sichtbar: ".$sichtbar.".");
- $inhalt_deutsch = $this->app->Secure->GetPOST('inhalt_deutsch');
- $inhalt_englisch = $this->app->Secure->GetPOST('inhalt_englisch');
- $layoutvorlage = (int)$this->app->Secure->GetPOST('layoutvorlage');
- $sort = (int)$this->app->Secure->GetPOST('sort');
- $zeichenbegrenzung = (int)$this->app->Secure->GetPOST('zeichenbegrenzung');
- $zeichenbegrenzung_anzahl = (int)$this->app->Secure->GetPOST('zeichenbegrenzung_anzahl');
-
- $layoutvorlagenpos = $this->app->DB->SelectArr("select id, sort from layoutvorlagen_positionen where layoutvorlage = ".$layoutvorlage." and id <> ".$id." order by sort");
- $i = 0;
-
- if(isset($layoutvorlagenpos[0]))
- {
- foreach($layoutvorlagenpos as $key => $pos)
- {
- $i++;
- if($i < $sort && $i != $pos['sort'] )
- {
- $this->app->DB->Update("update layoutvorlagen_positionen set sort = ".$i." where id = ".$pos['id']);
- }
- if($i >= $sort && $i + 1 != $pos['sort'])
- {
- $this->app->DB->Update("update layoutvorlagen_positionen set sort = ".($i + 1)." where id = ".$pos['id']);
- }
- }
- }
- if($sort < 1)
- {
- $sort = 1;
- }
- if($sort > $i + 1)
- {
- $sort = $i + 1;
- }
-
- $sets = array();
- $sets[] = 'typ = "' . $typ . '"';
- $sets[] = 'name = "' . $name . '"';
- $sets[] = 'beschreibung = "' . $beschreibung . '"';
- $sets[] = 'position_typ = "' . $position_typ . '"';
- $sets[] = 'position_x = "' . $position_x . '"';
- $sets[] = 'position_y = "' . $position_y . '"';
- $sets[] = 'position_parent = "' . $position_parent . '"';
- $sets[] = 'breite = "' . $breite . '"';
- $sets[] = 'hoehe = "' . $hoehe . '"';
- $sets[] = 'schrift_art = "' . $schrift_art . '"';
- $sets[] = 'schrift_groesse = "' . $schrift_groesse . '"';
- $sets[] = 'zeilen_hoehe = "' . $zeilen_hoehe . '"';
- $sets[] = 'schrift_fett = "' . $schrift_fett . '"';
- $sets[] = 'schrift_kursiv = "' . $schrift_kursiv . '"';
- $sets[] = 'schrift_underline = "' . $schrift_underline . '"';
- $sets[] = 'schrift_align = "' . $schrift_align . '"';
- $sets[] = 'schrift_farbe = "' . $schrift_farbe . '"';
- $sets[] = 'hintergrund_farbe = "' . $hintergrund_farbe . '"';
- $sets[] = 'rahmen = "' . $rahmen . '"';
- $sets[] = 'rahmen_farbe = "' . $rahmen_farbe . '"';
- $sets[] = 'sichtbar = "' . $sichtbar . '"';
- $sets[] = 'inhalt_deutsch = "' . $inhalt_deutsch . '"';
- $sets[] = 'inhalt_englisch = "' . $inhalt_englisch . '"';
- $sets[] = 'layoutvorlage = "' . $layoutvorlage . '"';
- $sets[] = 'sort = "' . $sort . '"';
- $sets[] = 'zeichenbegrenzung = "' . $zeichenbegrenzung . '"';
- $sets[] = 'zeichenbegrenzung_anzahl = "' . $zeichenbegrenzung_anzahl . '"';
-
- if (isset($_FILES['bild_deutsch']['tmp_name'])) {
- if ($_FILES['bild_deutsch']['type'] == 'image/jpeg' || $_FILES['bild_deutsch']['type'] == 'image/png') {
-
- $imgtype = exif_imagetype($_FILES['bild_deutsch']['tmp_name']);
- $img_type = '';
- switch($imgtype)
- {
- case IMAGETYPE_GIF:
- $img_type = 'GIF';
- break;
- case IMAGETYPE_JPEG:
- $img_type = 'JPEG';
- break;
- case IMAGETYPE_PNG:
- $img_type = 'PNG';
- break;
- case IMAGETYPE_ICO:
- $img_type = 'ICO';
- break;
- case IMAGETYPE_BMP:
- $img_type = 'BMP';
- break;
-
- }
- $fp = fopen($_FILES['bild_deutsch']['tmp_name'], 'r');
- $sets[] = 'bild_deutsch_typ = "' . $img_type . '"';
- $imgContent = fread($fp, filesize($_FILES['bild_deutsch']['tmp_name']));
- fclose($fp);
- $sets[] = 'bild_deutsch = "' . base64_encode($imgContent) . '"';
- }
- }
-
- if (isset($_FILES['bild_englisch']['tmp_name'])) {
- if ($_FILES['bild_englisch']['type'] == 'image/jpeg' || $_FILES['bild_englisch']['type'] == 'image/png') {
-
- $imgtype = exif_imagetype($_FILES['bild_deutsch']['tmp_name']);
- $img_type = '';
- switch($imgtype)
- {
- case IMAGETYPE_GIF:
- $img_type = 'GIF';
- break;
- case IMAGETYPE_JPEG:
- $img_type = 'JPEG';
- break;
- case IMAGETYPE_PNG:
- $img_type = 'PNG';
- break;
- case IMAGETYPE_ICO:
- $img_type = 'ICO';
- break;
- case IMAGETYPE_BMP:
- $img_type = 'BMP';
- break;
-
- }
- $sets[] = 'bild_englisch_typ = "' . $img_type . '"';
- $fp = fopen($_FILES['bild_englisch']['tmp_name'], 'r');
- $imgContent = fread($fp, filesize($_FILES['bild_englisch']['tmp_name']));
- fclose($fp);
- $sets[] = 'bild_englisch = "' . base64_encode($imgContent) . '"';
- }
- }
-
-
-
- if($id) {
- $query = ('UPDATE layoutvorlagen_positionen SET ' . implode(',', $sets) . ' WHERE id = ' . $id);
- $saveType = 'UPDATE';
- } else {
-
-// $layoutvorlage = $this->app->DB->Select("SELECT layoutvorlage FROM layoutvorlagen_positionen WHERE id='$id'");
- $checkname = $this->app->DB->Select('
- SELECT id FROM layoutvorlagen_positionen WHERE name = "' . $name . '" AND layoutvorlage="'.$layoutvorlage.'"
- ');
-
- if ($checkname) {
- $msg = $this->app->erp->base64_url_encode("
Name bereits vergeben.
");
- header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlage . '&msg=' . $msg);
- exit;
- }
-
- $query = ('INSERT INTO layoutvorlagen_positionen SET ' . implode(' , ', $sets));
- $saveType = 'INSERT';
- }
-
- $this->app->DB->Insert($query);
-
- header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlage."#tabs-2");
- exit;
-
- }
-
- public function LayoutvorlagenDelete() {
-
- $id = (int)$this->app->Secure->GetGET('id');
-
- if($id > 0){
- $this->app->DB->Delete('DELETE FROM layoutvorlagen WHERE id = ' . $id);
- $this->app->DB->Delete('DELETE FROM layoutvorlagen_positionen WHERE layoutvorlage = ' . $id);
- }
-
- echo json_encode(array(
- 'status' => 1,
- 'statusText' => 'Gelöscht.'
- ));
-
- $this->app->ExitXentral();
- }
-
- public function LayoutvorlagenDeletePosition() {
-
- $id = (int)$this->app->Secure->GetGET('id');
- if($id <= 0){
- echo json_encode(array(
- 'status' => 0,
- 'statusText' => 'ID ungültig: nicht Gelöscht.'
- ));
- $this->app->ExitXentral();
- }
- $parent = $this->app->DB->SelectArr("SELECT sort, position_parent, layoutvorlage from layoutvorlagen_positionen where id = ".$id);
- if($parent[0]['position_parent'] !== false)
- {
- $this->app->DB->Update("UPDATE layoutvorlagen_positionen SET parent = ".$parent[0]['position_parent']." where parent = ".$id);
- }
- $this->app->DB->Delete('DELETE FROM layoutvorlagen_positionen WHERE id = ' . $id);
- $this->app->DB->Update('UPDATE layoutvorlagen_positionen set sort = sort - 1 where sort > '.$parent[0]['sort'].' and layoutvorlage = '.$parent[0]['layoutvorlage']);
-
- echo json_encode(array(
- 'status' => 1,
- 'statusText' => 'Gelöscht.'
- ));
-
- $this->app->ExitXentral();
- }
-
- public function LayoutvorlagenImgVorschau() {
-
- $id = $this->app->Secure->GetGET('id');
- $cmd = $this->app->Secure->GetGET('cmd');
-
- if ($cmd == 'de') {
- $bildA = $this->app->DB->SelectArr('SELECT bild_deutsch, bild_deutsch_typ FROM layoutvorlagen_positionen WHERE id = ' . $id);
- if(!isset($bildA[0]))
- {
- $this->app->ExitXentral();
- }
- $bild = $bildA[0]['bild_deutsch'];
- $type = $bildA[0]['bild_deutsch_typ'];
- } else if ($cmd == 'en') {
- $bildA = $this->app->DB->SelectArr('SELECT bild_englisch, bild_englisch_typ FROM layoutvorlagen_positionen WHERE id = ' . $id);
- if(!isset($bildA[0]))
- {
- $this->app->ExitXentral();
- }
- $bild = $bildA[0]['bild_englisch'];
- $type = $bildA[0]['bild_englisch_typ'];
-
- }
-
- $bild = base64_decode($bild);
-
- if ($bild) {
-
- $im = imagecreatefromstring($bild);
- if ($im !== false) {
- //$type = strtolower($type);
- $type = '';
- if($type == '')$type = $this->get_img_type($bild);
- if($type == 'jpg')
- {
- $type = 'jpeg';
- }
- header('Content-Type: image/'.$type);
- switch(strtolower($type)){
- case "png":
- imagepng($im); break;
- case "jpeg": case "jpg":
- imagejpeg($im); break;
- case "gif":
- imagegif($im); break;
- default:
-
- break;
- }
- imagedestroy($im);
- }
-
- }
-
- $this->app->ExitXentral();
- }
-
- function get_img_type($data) {
- $magics = array(
- 'ffd8ff' => 'jpg',
- '89504e470d0a1a0a' => 'png',
- );
-
- foreach ($magics as $str => $ext) {
- if (strtolower(bin2hex(substr($data, 0, strlen($str)/2))) == $str)
- {
- return $ext;
- }
- }
-
- return NULL;
- }
-
- public function LayoutvorlagenExport()
- {
- $id = (int)$this->app->Secure->GetGET('id');
- if($id > 0)
- {
- if($Layout = $this->app->DB->SelectArr("select * from layoutvorlagen where id = ".$id." limit 1"))
- {
- $Layout = reset($Layout);
- $Layoutpositionen = $this->app->DB->SelectArr("select * from layoutvorlagen_positionen where layoutvorlage = ".$id);
- header('Conent-Type: application/json');
- header("Content-Disposition: attachment; filename=\"Layout".$this->app->erp->Dateinamen((trim($Layout['name'])!= ''?'_'.$Layout['name']:(trim($Layout['beschreibung']) != ''?'_'.$Layout['beschreibung']:''))).".json\"");
- $Datei['Layout'] = $Layout;
- if(!empty($Layoutpositionen))
- {
- $Datei['Layoutpositionen'] = $Layoutpositionen;
- }
- echo json_encode($Datei);
- $this->app->ExitXentral();
- }
- }
- }
-
-}
+app = $app;
+ if($intern) {
+ return;
+ }
+ $this->app->ActionHandlerInit($this);
+ $this->app->ActionHandler("list", "LayoutvorlagenList");
+ $this->app->ActionHandler("edit", "LayoutvorlagenEdit");
+ $this->app->ActionHandler("create", "LayoutvorlagenCreate");
+ $this->app->ActionHandler("copy", "LayoutvorlagenCopy");
+ $this->app->ActionHandler("getposition", "LayoutvorlagenGetPosition");
+ $this->app->ActionHandler("saveposition", "LayoutvorlagenSavePosition");
+ $this->app->ActionHandler("createposition", "LayoutvorlagenCreatePosition");
+ $this->app->ActionHandler("deleteposition", "LayoutvorlagenDeletePosition");
+ $this->app->ActionHandler("delete", "LayoutvorlagenDelete");
+ $this->app->ActionHandler("download", "LayoutvorlagenDownload");
+ $this->app->ActionHandler("export", "LayoutvorlagenExport");
+ //$this->app->ActionHandler("import", "LayoutvorlagenImport");
+
+ $this->app->ActionHandler("imgvorschau", "LayoutvorlagenImgVorschau");
+
+ $this->app->erp->Headlines('Layoutvorlagen');
+
+ $this->app->ActionHandlerListen($app);
+ }
+
+ public function LayoutvorlagenCopy()
+ {
+ $id = (int)$this->app->Secure->GetGET('id');
+ if($id)
+ {
+ $layoutvorlage = $this->app->DB->SelectArr("SELECT * FROM layoutvorlagen WHERE id = '$id'");
+ if($layoutvorlage)
+ {
+ $this->app->DB->Insert("INSERT INTO layoutvorlagen (id) VALUES('')");
+ $newvorlage = $this->app->DB->GetInsertID();
+ $layoutvorlage[0]['name'] .= ' (Kopie)';
+ $this->app->FormHandler->ArrayUpdateDatabase("layoutvorlagen",$newvorlage,$layoutvorlage[0],true);
+ $positionen = $this->app->DB->SelectArr("SELECT * FROM layoutvorlagen_positionen WHERE layoutvorlage = '$id'");
+ if($positionen)
+ {
+ foreach($positionen as $position)
+ {
+ $this->app->DB->Insert("INSERT INTO layoutvorlagen_positionen (id) VALUES('')");
+ $newvorlagepos = $this->app->DB->GetInsertID();
+ $position['layoutvorlage'] = $newvorlage;
+ $this->app->FormHandler->ArrayUpdateDatabase("layoutvorlagen_positionen",$newvorlagepos,$position, true);
+ }
+ }
+ }
+ }
+ header('Location: index.php?module=layoutvorlagen&action=list');
+ exit;
+ }
+
+ public function LayoutvorlagenDownload($id = 0)
+ {
+ if(!$id)$id = $this->app->Secure->GetGET('id');
+ // mit infos aus zertifikat und konkreten inhalten
+ $projekt = "";
+ $Brief = new LayoutvorlagenPDF($this->app, $projekt);
+ $Brief->GetLayoutvorlage($id);
+ $Brief->inlineDocument();
+ }
+
+
+ public function LayoutvorlagenMenu() {
+ $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=list","Übersicht");
+ }
+
+ public function LayoutvorlagenList() {
+
+ //$this->LayoutvorlagenMenu();
+ $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=list","Übersicht");
+ $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Neu");
+
+ $layoutanlegen = $this->app->Secure->GetPOST('layoutanlegen');
+
+
+ if ($layoutanlegen) {
+
+ $row['name'] = $this->app->Secure->GetPOST('name');
+ //$row['name'] = preg_replace('#[^-A-Za-z0-9]#', '-', $row['name']);
+ $row['typ'] = $this->app->Secure->GetPOST('typ');
+ $row['format'] = $this->app->Secure->GetPOST('format');
+ $row['kategorie'] = $this->app->Secure->GetPOST('kategorie');
+
+ if ($row['name']) {
+
+ $this->app->DB->Insert('
+ INSERT INTO
+ layoutvorlagen
+ SET
+ name = "' . $row['name'] . '",
+ typ = "' . $row['typ'] . '",
+ format = "' . $row['format'] . '",
+ kategorie = "' . $row['kategorie'] . '"
+ ');
+
+ $id = $this->app->DB->GetInsertID();
+ if ($id) {
+ header('location: index.php?module=layoutvorlagen&action=edit&id=' . $id);
+ exit;
+ }
+ }
+ }
+ if($this->app->Secure->GetPOST('cmd') === 'import') {
+ if (!empty($_FILES['importfile']['tmp_name'])) {
+ $string = file_get_contents($_FILES['importfile']['tmp_name']);
+ $ret = $this->importJson($string, $this->app->Secure->GetPOST('ueberschreiben'));
+ if(!empty($ret['message'])) {
+ $this->app->Tpl->Add('ERRORMSG', $ret['message']);
+ }
+ }
+ else {
+ $this->app->Tpl->Add('ERRORMSG', "Keine Datei ausgewält");
+ }
+ }
+
+
+ $this->app->YUI->TableSearch('TABELLE', 'layoutvorlagen_list');
+ $this->app->Tpl->Parse('PAGE',"layoutvorlagen_list.tpl");
+
+ }
+
+ /**
+ * @param string $string
+ * @param bool $overwrite
+ *
+ * @return array
+ */
+ public function importJson($string, $overwrite = false)
+ {
+ $ret = [];
+ if(!(NULL !== $json = json_decode($string))) {
+ return ['status' => 0, 'message' => 'Keine gültige Datei'];
+ }
+ if(empty($json->Layout) && empty($json->Layout->name)) {
+ return ['status' => 0, 'message' => 'Keine gültige Datei Fehlendes Element: Layout'];
+ }
+
+ $altesLayout = $this->app->DB->SelectArr(
+ sprintf(
+ "select * from layoutvorlagen where name like '%s'",
+ $this->app->DB->real_escape_string($json->Layout->name)
+ )
+ );
+
+ if(!empty($altesLayout) && !$overwrite) {
+ return ['status' => 0, 'message' => 'Es existiert bereis ein Layout mit dem Namen','id' => $altesLayout['id']];
+ }
+
+ if(isset($json->Layout->id)) {
+ unset($json->Layout->id);
+ }
+ $columns = $this->app->DB->SelectArr('SHOW COLUMNS FROM layoutvorlagen');
+ $error = false;
+ foreach($json->Layout as $k => $v) {
+ $found = false;
+ foreach($columns as $k2 => $v2) {
+ if($v2['Field'] == $k) {
+ $found = true;
+ }
+ }
+ if(!$found) {
+ $error = true;
+ }
+ }
+ $columnspos = $this->app->DB->SelectArr('SHOW COLUMNS FROM layoutvorlagen_positionen');
+ if(!empty($json->Layoutpositionen)) {
+ foreach($json->Layoutpositionen as $k => $pos) {
+ if(isset($pos->id)) {
+ unset($json->Layoutpositionen[$k]->id);
+ }
+ if(isset($pos->layoutvorlage)) {
+ unset($json->Layoutpositionen[$k]->id);
+ }
+
+ foreach($pos as $kp => $vp) {
+ $found = false;
+ foreach($columnspos as $k2 => $v2) {
+ if($v2['Field'] == $kp) {
+ $found = true;
+ }
+ }
+ if(!$found) {
+ $error = true;
+ }
+ }
+ }
+ }
+ if(!empty($error)) {
+ return ['status' => 0, 'message' => 'Keine gültige Datei: falsche Elemente'];
+ }
+
+ $query = "insert into layoutvorlagen (";
+ $i = 0;
+ foreach($columns as $k => $v) {
+ if($v['Field'] !== 'id') {
+ $i++;
+ if($i > 1) {
+ $query .= ', ';
+ }
+ $query .= $v['Field'];
+ }
+ }
+ $query .= ') values (';
+ $i = 0;
+ foreach($columns as $k => $v) {
+ if($v['Field'] !== 'id') {
+ $i++;
+ if($i > 1) {
+ $query .= ', ';
+ }
+ $query .= "'";
+ $fieldName = $v['Field'];
+ if(isset($json->Layout->$fieldName)) {
+ $query .= $this->app->DB->real_escape_string($json->Layout->$fieldName);
+ }
+ $query .= "'";
+ }
+ }
+ $query .= ')';
+
+ //alte Löschen falls existiert
+ if($altesLayout) {
+ foreach($altesLayout as $l) {
+ if($l['id']) {
+ $this->app->DB->Delete("delete from layoutvorlagen_positionen where layoutvorlage = ".$l['id']);
+ $this->app->DB->Delete("delete from layoutvorlagen where id = ".$l['id']);
+ }
+ }
+ }
+ //
+ $this->app->DB->Insert($query);
+ $newid = $this->app->DB->GetInsertID();
+
+ if(empty($newid)) {
+ return ['status' => 0, 'message' => 'Fehler beim Erstellen des Layouts'];
+ }
+
+ $j = 0;
+ foreach ($json->Layoutpositionen as $kpos => $pos) {
+
+ $querypos[$j] = "insert into layoutvorlagen_positionen (layoutvorlage";
+ $i = 0;
+ foreach($columnspos as $k => $v) {
+ if($v['Field'] !== 'id' && $v['Field'] !== 'layoutvorlage') {
+ $i++;
+ $querypos[$j] .= ', ';
+ $querypos[$j] .= $v['Field'];
+ }
+ }
+
+ $querypos[$j] .= ") values ('".$newid."'";
+ $i = 0;
+ foreach($columnspos as $k => $v) {
+ if($v['Field'] !== 'id' && $v['Field'] !== 'layoutvorlage') {
+ $i++;
+ $querypos[$j] .= ', ';
+ $querypos[$j] .= "'";
+ $fieldName = $v['Field'];
+ if(isset($pos->$fieldName)) {
+ $querypos[$j] .= $this->app->DB->real_escape_string($pos->$fieldName);
+ }
+ $querypos[$j] .= "'";
+ }
+ }
+
+ $querypos[$j] .= ")";
+ $j++;
+ }
+ if(isset($querypos)) {
+ $fehler = false;
+ foreach($querypos as $qp) {
+ $this->app->DB->Insert($qp);
+ if($this->app->DB->error()){
+ $ret['error'] = $this->app->DB->error();
+ $fehler = true;
+ }
+ }
+ }
+ if($fehler) {
+ return [
+ 'status' => 0,
+ 'message' => (empty($ret['error'])?'':$ret['error'].' ')
+ . 'Fehler beim Erstellen von einer oder mehreren Layoutposition(en)'
+ ];
+ }
+
+ return [
+ 'message' => 'Layout ' .$json->Layout->name. ' erfolgreich erstellt',
+ 'status' => true, 'id' => $newid
+ ];
+ }
+
+ public function LayoutvorlagenEdit() {
+
+ $id = $this->app->Secure->GetGET('id');
+ $cmd = $this->app->Secure->GetGET('cmd');
+ $speichern = $this->app->Secure->GetPOST('layoutspeichern');
+
+ if ($speichern) {
+ $name = $this->app->Secure->GetPOST('name');
+ $typ = $this->app->Secure->GetPOST('typ');
+ $format = $this->app->Secure->GetPOST('format');
+ $kategorie = $this->app->Secure->GetPOST('kategorie');
+ $projekt = $this->app->Secure->GetPOST('layoutvorlagen_projekt');
+ $delete_hintergrund = $this->app->Secure->GetPOST('delete_hintergrund')==''?false:true;
+ $pdf_hintergrund = $_FILES['pdf_hintergrund'];
+
+ if (isset($pdf_hintergrund['tmp_name']) && ($pdf_hintergrund['type'] == 'application/pdf' || $pdf_hintergrund['type'] == 'application/force-download' || $pdf_hintergrund['type'] =='binary/octet-stream' || $pdf_hintergrund['type'] == 'application/octetstream')) {
+ $fp = fopen($pdf_hintergrund['tmp_name'], 'r');
+ $imgContent = fread($fp, filesize($pdf_hintergrund['tmp_name']));
+ fclose($fp);
+ $sets[] = 'pdf_hintergrund = "' . base64_encode($imgContent) . '"';
+ } elseif($delete_hintergrund) {
+ $sets[] = 'pdf_hintergrund = ""';
+ }
+
+ $sets[] = 'name = "' . $name . '" ';
+ $sets[] = 'typ = "' . $typ . '" ';
+ $sets[] = 'format = "' . $format . '" ';
+ $sets[] = 'kategorie = "' . $kategorie . '" ';
+
+ if ($sets) {
+ $this->app->DB->Insert('UPDATE layoutvorlagen SET ' . implode(', ', $sets) . ' WHERE id = ' . $id);
+ }
+
+ if($projekt != ''){
+ $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung = '$projekt' LIMIT 1");
+ }else{
+ $projektid = 0;
+ }
+
+ $this->app->DB->Update("UPDATE layoutvorlagen SET projekt = '$projektid' WHERE id = '$id'");
+
+ }
+
+ $this->app->YUI->AutoComplete("kategorie","layoutvorlagenkategorie");
+ $this->app->YUI->AutoComplete("layoutvorlagen_projekt", "projektname", 1);
+ //$this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Neu");
+ $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=edit&id=" . $id . "","Details");
+
+ $vorlage = $this->app->DB->SelectArr('SELECT * FROM layoutvorlagen WHERE id = ' . $id);
+ $vorlage = reset($vorlage);
+
+ if ($cmd) {
+ switch ($cmd) {
+ case 'pdfvorschau':
+ $pdf_hintergrund = $this->app->DB->Select('SELECT pdf_hintergrund FROM layoutvorlagen WHERE id = ' . $id);
+ $pdf_hintergrund = base64_decode($pdf_hintergrund);
+
+ header("Content-type: application/pdf");
+ header('Content-disposition: attachment; filename="pdf_hintergrund.pdf"');
+ print $pdf_hintergrund;
+
+
+ break;
+ default:
+ break;
+ }
+ exit;
+ }
+
+ $this->app->User->SetParameter('layoutvorlagen_id', $id);
+
+ $this->app->Tpl->Add('NAME', $vorlage['name']);
+ $this->app->Tpl->Add('KATEGORIE', $vorlage['kategorie']);
+
+ if($vorlage['projekt'] > 0){
+ $projektname = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '".$vorlage['projekt']."' LIMIT 1");
+ if($projektname != ""){
+ $this->app->Tpl->Add('PROJEKT', $projektname);
+ }
+ }
+
+ if ($vorlage['pdf_hintergrund']) {
+ $this->app->Tpl->Add('PDFVORSCHAU', '
');
+ }
+ $this->app->Tpl->Add('TAB3', '
');
+ /*
+ $schriftarten = $this->app->erp->GetSchriftarten();
+ //Test
+ $schriftarten['times'] = "Times";
+ $schriftarten['juliusc'] = 'juliusc';
+ $schriftarten['bernard'] = 'Bernard';
+ $schriftarten['HLBC____'] = 'HLBC____';
+ */
+ $schriftartena = $this->app->erp->GetFonts();
+ foreach($schriftartena as $kk => $vv)
+ {
+ $schriftarten[$kk] = $vv['name'];
+
+ }
+ //Test End
+ $schriftartenTpl = '';
+ if ($schriftarten) {
+ foreach ($schriftarten as $schriftartKey => $schriftart) {
+ $schriftartenTpl .= '
' . $schriftart . ' ';
+ }
+ }
+ $this->app->Tpl->Add('SCHRIFTARTEN', $schriftartenTpl);
+
+ $rahmenbreiten = array(
+ '0' => 'Kein Rahmen',
+ '1' => '1',
+ '2' => '2',
+ '3' => '3',
+ '4' => '4',
+ '5' => '5',
+ '6' => '6',
+ '7' => '7',
+ '8' => '8',
+ '9' => '9',
+ '10' => '10'
+ );
+ $rahmenTpl = '';
+ if ($rahmenbreiten) {
+ foreach ($rahmenbreiten as $rahmenbreiteKey => $rahmenbreite) {
+ $rahmenTpl .= '
' . $rahmenbreite . ' ';
+ }
+ }
+
+ $positionen = $this->app->DB->SelectArr('
+ SELECT
+ id,
+ name,
+ typ
+ FROM
+ layoutvorlagen_positionen
+ WHERE
+ layoutvorlage = "' . $id . '"
+ ');
+
+ $positionenTpl = '';
+ $positionenTpl .= '
Keine ';
+ if ($positionen) {
+ foreach ($positionen as $position) {
+ $positionenTpl .= '
' . $position['name'] . ' (' . $position['typ'] . ') ';
+ }
+ }
+
+ $schriftausrichtungen = array('left' => 'Links', 'center' => 'Zentriert', 'right' => 'Rechts');
+ $schriftausrichtungenTpl = '';
+ if ($schriftausrichtungen) {
+ foreach($schriftausrichtungen as $schriftausrichtungKey => $schriftausrichtung) {
+ $schriftausrichtungenTpl .= '
' . $schriftausrichtung . ' ';
+ }
+ }
+
+ $formate = array('A4' => 'DIN A4 Hoch', 'A4L' => 'DIN A4 Quer','A5' => 'DIN A5 Hoch', 'A5L' => 'DIN A5 Quer','A6' => 'DIN A6 Hoch', 'A6L' => 'DIN A6 Quer');
+ $formatTpl = '';
+ if ($formate) {
+ foreach($formate as $formatKey => $formatBeschriftung) {
+ $formatTpl .= '
' . $formatBeschriftung . ' ';
+ }
+ }
+
+
+
+ $this->app->YUI->ColorPicker("schrift_farbe");
+ $this->app->YUI->ColorPicker("hintergrund_farbe");
+ $this->app->YUI->ColorPicker("rahmen_farbe");
+
+ $this->app->Tpl->Add('SCHRIFTAUSRICHTUNGEN', $schriftausrichtungenTpl);
+ $this->app->Tpl->Add('POSITIONPARENT', $positionenTpl);
+
+ $this->app->Tpl->Add('FORMAT', $formatTpl);
+ $this->app->Tpl->Add('RAHMEN', $rahmenTpl);
+ $this->app->YUI->TableSearch('TABELLE', 'layoutvorlagen_edit');
+ $this->app->Tpl->Parse('PAGE',"layoutvorlagen_edit.tpl");
+
+ }
+
+ public function LayoutvorlagenCreate() {
+
+ $speichern = $this->app->Secure->GetPOST('layouterstellen');
+
+ if ($speichern) {
+
+
+ $felder = array('name', 'typ', 'format', 'kategorie');
+ $sets = array();
+ if ($felder) {
+ foreach ($felder as $feld) {
+ $sets[] = $feld . ' = "' . $this->app->Secure->GetPOST($feld) . '"';
+ }
+ }
+
+ $projekt = $this->app->Secure->GetPOST('layoutvorlagen_projekt');
+ if($projekt != ''){
+ $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung = '$projekt' LIMIT 1");
+ }else{
+ $projektid = 0;
+ }
+
+ $query = ('INSERT INTO layoutvorlagen SET ' . implode(', ', $sets) . ' ');
+ $this->app->DB->Insert($query);
+
+
+ $layoutvorlagenId = $this->app->DB->GetInsertID();
+
+ $this->app->DB->Update("UPDATE layoutvorlagen SET projekt = '$projektid' WHERE id = '$layoutvorlagenId'");
+
+
+ $delete_hintergrund = $this->app->Secure->GetPOST('delete_hintergrund')==''?false:true;
+ $pdf_hintergrund = $_FILES['pdf_hintergrund'];
+ if (isset($pdf_hintergrund['tmp_name']) && ($pdf_hintergrund['type'] == 'application/pdf' || $pdf_hintergrund['type'] == 'application/force-download' || $pdf_hintergrund['type'] =='binary/octet-stream' || $pdf_hintergrund['type'] == 'application/octetstream')) {
+ $fp = fopen($pdf_hintergrund['tmp_name'], 'r');
+ $imgContent = fread($fp, filesize($pdf_hintergrund['tmp_name']));
+ fclose($fp);
+ $sets[] = 'pdf_hintergrund = "' . base64_encode($imgContent) . '"';
+ } elseif($delete_hintergrund) {
+ $sets[] = 'pdf_hintergrund = ""';
+ }
+
+ if ($sets) {
+ $this->app->DB->Insert('UPDATE layoutvorlagen SET ' . implode(', ', $sets) . ' WHERE id = ' . $layoutvorlagenId);
+ }
+
+
+
+
+
+ if ($layoutvorlagenId) {
+ header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlagenId);
+ exit;
+ }
+
+ }
+
+ $this->app->YUI->AutoComplete("kategorie","layoutvorlagenkategorie");
+ $this->app->YUI->AutoComplete("layoutvorlagen_projekt", "projektname", 1);
+
+ $this->app->erp->MenuEintrag("index.php?module=layoutvorlagen&action=create","Erstellen");
+ $this->app->Tpl->Parse('PAGE','layoutvorlagen_create.tpl');
+
+ }
+
+ public function LayoutvorlagenGetPosition() {
+
+ $id = $this->app->Secure->GetPOST('id');
+ $row = $this->app->DB->SelectRow('SELECT * FROM layoutvorlagen_positionen WHERE id = ' . $id);
+
+ if ($row['bild_deutsch']) {
+ $bilddata['bild_deutsch'] = '
VORSCHAU ';
+ unset($row['bild_deutsch']);
+ }
+
+ if ($row['bild_englisch']) {
+ $bilddata['bild_englisch'] = '
VORSCHAU ';
+ unset($row['bild_englisch']);
+ }
+
+ echo json_encode(array(
+ 'status' => 1,
+ 'statusText' => '',
+ 'row' => $row,
+ 'bilddata' => $bilddata
+ ));
+ $this->app->ExitXentral();
+ }
+
+
+ public function LayoutvorlagenSavePosition() {
+
+ $id = $this->app->Secure->GetPOST('id');
+ $typ = $this->app->Secure->GetPOST('typ');
+
+ $name = $this->app->Secure->GetPOST('name');
+ $name = strtolower($name);
+ $name = preg_replace('#[^-A-Za-z0-9]#', '-', $name);
+
+ $beschreibung = $this->app->Secure->GetPOST('beschreibung');
+ $position_typ = $this->app->Secure->GetPOST('position_typ');
+ $position_x = $this->app->Secure->GetPOST('position_x');
+ $position_y = $this->app->Secure->GetPOST('position_y');
+ $position_parent = $this->app->Secure->GetPOST('position_parent');
+ $breite = $this->app->Secure->GetPOST('breite');
+ $hoehe = $this->app->Secure->GetPOST('hoehe');
+ $schrift_art = $this->app->Secure->GetPOST('schrift_art');
+ $schrift_groesse = $this->app->Secure->GetPOST('schrift_groesse');
+ $zeilen_hoehe = $this->app->Secure->GetPOST('zeilen_hoehe');
+ $schrift_align = $this->app->Secure->GetPOST('schrift_align');
+ $schrift_farbe = $this->app->Secure->GetPOST('schrift_farbe');
+ $hintergrund_farbe = $this->app->Secure->GetPOST('hintergrund_farbe');
+ $rahmen = $this->app->Secure->GetPOST('rahmen');
+ $rahmen_farbe = $this->app->Secure->GetPOST('rahmen_farbe');
+ $sichtbar = ($this->app->Secure->GetPOST('sichtbar')=='')?'0':'1';
+ $schrift_fett = ($this->app->Secure->GetPOST('schrift_fett')=='')?'0':'1';
+ $schrift_kursiv = ($this->app->Secure->GetPOST('schrift_kursiv')=='')?'0':'1';
+ $schrift_underline = ($this->app->Secure->GetPOST('schrift_underline')=='')?'0':'1';
+ //$this->app->erp->LogFile("sichtbar: ".$sichtbar.".");
+ $inhalt_deutsch = $this->app->Secure->GetPOST('inhalt_deutsch');
+ $inhalt_englisch = $this->app->Secure->GetPOST('inhalt_englisch');
+ $layoutvorlage = (int)$this->app->Secure->GetPOST('layoutvorlage');
+ $sort = (int)$this->app->Secure->GetPOST('sort');
+ $zeichenbegrenzung = (int)$this->app->Secure->GetPOST('zeichenbegrenzung');
+ $zeichenbegrenzung_anzahl = (int)$this->app->Secure->GetPOST('zeichenbegrenzung_anzahl');
+
+ $layoutvorlagenpos = $this->app->DB->SelectArr("select id, sort from layoutvorlagen_positionen where layoutvorlage = ".$layoutvorlage." and id <> ".$id." order by sort");
+ $i = 0;
+
+ if(isset($layoutvorlagenpos[0]))
+ {
+ foreach($layoutvorlagenpos as $key => $pos)
+ {
+ $i++;
+ if($i < $sort && $i != $pos['sort'] )
+ {
+ $this->app->DB->Update("update layoutvorlagen_positionen set sort = ".$i." where id = ".$pos['id']);
+ }
+ if($i >= $sort && $i + 1 != $pos['sort'])
+ {
+ $this->app->DB->Update("update layoutvorlagen_positionen set sort = ".($i + 1)." where id = ".$pos['id']);
+ }
+ }
+ }
+ if($sort < 1)
+ {
+ $sort = 1;
+ }
+ if($sort > $i + 1)
+ {
+ $sort = $i + 1;
+ }
+
+ $sets = array();
+ $sets[] = 'typ = "' . $typ . '"';
+ $sets[] = 'name = "' . $name . '"';
+ $sets[] = 'beschreibung = "' . $beschreibung . '"';
+ $sets[] = 'position_typ = "' . $position_typ . '"';
+ $sets[] = 'position_x = "' . $position_x . '"';
+ $sets[] = 'position_y = "' . $position_y . '"';
+ $sets[] = 'position_parent = "' . $position_parent . '"';
+ $sets[] = 'breite = "' . $breite . '"';
+ $sets[] = 'hoehe = "' . $hoehe . '"';
+ $sets[] = 'schrift_art = "' . $schrift_art . '"';
+ $sets[] = 'schrift_groesse = "' . $schrift_groesse . '"';
+ $sets[] = 'zeilen_hoehe = "' . $zeilen_hoehe . '"';
+ $sets[] = 'schrift_fett = "' . $schrift_fett . '"';
+ $sets[] = 'schrift_kursiv = "' . $schrift_kursiv . '"';
+ $sets[] = 'schrift_underline = "' . $schrift_underline . '"';
+ $sets[] = 'schrift_align = "' . $schrift_align . '"';
+ $sets[] = 'schrift_farbe = "' . $schrift_farbe . '"';
+ $sets[] = 'hintergrund_farbe = "' . $hintergrund_farbe . '"';
+ $sets[] = 'rahmen = "' . $rahmen . '"';
+ $sets[] = 'rahmen_farbe = "' . $rahmen_farbe . '"';
+ $sets[] = 'sichtbar = "' . $sichtbar . '"';
+ $sets[] = 'inhalt_deutsch = "' . $inhalt_deutsch . '"';
+ $sets[] = 'inhalt_englisch = "' . $inhalt_englisch . '"';
+ $sets[] = 'layoutvorlage = "' . $layoutvorlage . '"';
+ $sets[] = 'sort = "' . $sort . '"';
+ $sets[] = 'zeichenbegrenzung = "' . $zeichenbegrenzung . '"';
+ $sets[] = 'zeichenbegrenzung_anzahl = "' . $zeichenbegrenzung_anzahl . '"';
+
+ if (isset($_FILES['bild_deutsch']['tmp_name'])) {
+ if ($_FILES['bild_deutsch']['type'] == 'image/jpeg' || $_FILES['bild_deutsch']['type'] == 'image/png') {
+
+ $imgtype = exif_imagetype($_FILES['bild_deutsch']['tmp_name']);
+ $img_type = '';
+ switch($imgtype)
+ {
+ case IMAGETYPE_GIF:
+ $img_type = 'GIF';
+ break;
+ case IMAGETYPE_JPEG:
+ $img_type = 'JPEG';
+ break;
+ case IMAGETYPE_PNG:
+ $img_type = 'PNG';
+ break;
+ case IMAGETYPE_ICO:
+ $img_type = 'ICO';
+ break;
+ case IMAGETYPE_BMP:
+ $img_type = 'BMP';
+ break;
+
+ }
+ $fp = fopen($_FILES['bild_deutsch']['tmp_name'], 'r');
+ $sets[] = 'bild_deutsch_typ = "' . $img_type . '"';
+ $imgContent = fread($fp, filesize($_FILES['bild_deutsch']['tmp_name']));
+ fclose($fp);
+ $sets[] = 'bild_deutsch = "' . base64_encode($imgContent) . '"';
+ }
+ }
+
+ if (isset($_FILES['bild_englisch']['tmp_name'])) {
+ if ($_FILES['bild_englisch']['type'] == 'image/jpeg' || $_FILES['bild_englisch']['type'] == 'image/png') {
+
+ $imgtype = exif_imagetype($_FILES['bild_deutsch']['tmp_name']);
+ $img_type = '';
+ switch($imgtype)
+ {
+ case IMAGETYPE_GIF:
+ $img_type = 'GIF';
+ break;
+ case IMAGETYPE_JPEG:
+ $img_type = 'JPEG';
+ break;
+ case IMAGETYPE_PNG:
+ $img_type = 'PNG';
+ break;
+ case IMAGETYPE_ICO:
+ $img_type = 'ICO';
+ break;
+ case IMAGETYPE_BMP:
+ $img_type = 'BMP';
+ break;
+
+ }
+ $sets[] = 'bild_englisch_typ = "' . $img_type . '"';
+ $fp = fopen($_FILES['bild_englisch']['tmp_name'], 'r');
+ $imgContent = fread($fp, filesize($_FILES['bild_englisch']['tmp_name']));
+ fclose($fp);
+ $sets[] = 'bild_englisch = "' . base64_encode($imgContent) . '"';
+ }
+ }
+
+
+
+ if($id) {
+ $query = ('UPDATE layoutvorlagen_positionen SET ' . implode(',', $sets) . ' WHERE id = ' . $id);
+ $saveType = 'UPDATE';
+ } else {
+
+// $layoutvorlage = $this->app->DB->Select("SELECT layoutvorlage FROM layoutvorlagen_positionen WHERE id='$id'");
+ $checkname = $this->app->DB->Select('
+ SELECT id FROM layoutvorlagen_positionen WHERE name = "' . $name . '" AND layoutvorlage="'.$layoutvorlage.'"
+ ');
+
+ if ($checkname) {
+ $msg = $this->app->erp->base64_url_encode("
Name bereits vergeben.
");
+ header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlage . '&msg=' . $msg);
+ exit;
+ }
+
+ $query = ('INSERT INTO layoutvorlagen_positionen SET ' . implode(' , ', $sets));
+ $saveType = 'INSERT';
+ }
+
+ $this->app->DB->Insert($query);
+
+ header('location: index.php?module=layoutvorlagen&action=edit&id=' . $layoutvorlage."#tabs-2");
+ exit;
+
+ }
+
+ public function LayoutvorlagenDelete() {
+
+ $id = (int)$this->app->Secure->GetGET('id');
+
+ if($id > 0){
+ $this->app->DB->Delete('DELETE FROM layoutvorlagen WHERE id = ' . $id);
+ $this->app->DB->Delete('DELETE FROM layoutvorlagen_positionen WHERE layoutvorlage = ' . $id);
+ }
+
+ echo json_encode(array(
+ 'status' => 1,
+ 'statusText' => 'Gelöscht.'
+ ));
+
+ $this->app->ExitXentral();
+ }
+
+ public function LayoutvorlagenDeletePosition() {
+
+ $id = (int)$this->app->Secure->GetGET('id');
+ if($id <= 0){
+ echo json_encode(array(
+ 'status' => 0,
+ 'statusText' => 'ID ungültig: nicht Gelöscht.'
+ ));
+ $this->app->ExitXentral();
+ }
+ $parent = $this->app->DB->SelectArr("SELECT sort, position_parent, layoutvorlage from layoutvorlagen_positionen where id = ".$id);
+ if($parent[0]['position_parent'] !== false)
+ {
+ $this->app->DB->Update("UPDATE layoutvorlagen_positionen SET parent = ".$parent[0]['position_parent']." where parent = ".$id);
+ }
+ $this->app->DB->Delete('DELETE FROM layoutvorlagen_positionen WHERE id = ' . $id);
+ $this->app->DB->Update('UPDATE layoutvorlagen_positionen set sort = sort - 1 where sort > '.$parent[0]['sort'].' and layoutvorlage = '.$parent[0]['layoutvorlage']);
+
+ echo json_encode(array(
+ 'status' => 1,
+ 'statusText' => 'Gelöscht.'
+ ));
+
+ $this->app->ExitXentral();
+ }
+
+ public function LayoutvorlagenImgVorschau() {
+
+ $id = $this->app->Secure->GetGET('id');
+ $cmd = $this->app->Secure->GetGET('cmd');
+
+ if ($cmd == 'de') {
+ $bildA = $this->app->DB->SelectArr('SELECT bild_deutsch, bild_deutsch_typ FROM layoutvorlagen_positionen WHERE id = ' . $id);
+ if(!isset($bildA[0]))
+ {
+ $this->app->ExitXentral();
+ }
+ $bild = $bildA[0]['bild_deutsch'];
+ $type = $bildA[0]['bild_deutsch_typ'];
+ } else if ($cmd == 'en') {
+ $bildA = $this->app->DB->SelectArr('SELECT bild_englisch, bild_englisch_typ FROM layoutvorlagen_positionen WHERE id = ' . $id);
+ if(!isset($bildA[0]))
+ {
+ $this->app->ExitXentral();
+ }
+ $bild = $bildA[0]['bild_englisch'];
+ $type = $bildA[0]['bild_englisch_typ'];
+
+ }
+
+ $bild = base64_decode($bild);
+
+ if ($bild) {
+
+ $im = imagecreatefromstring($bild);
+ if ($im !== false) {
+ //$type = strtolower($type);
+ $type = '';
+ if($type == '')$type = $this->get_img_type($bild);
+ if($type == 'jpg')
+ {
+ $type = 'jpeg';
+ }
+ header('Content-Type: image/'.$type);
+ switch(strtolower($type)){
+ case "png":
+ imagepng($im); break;
+ case "jpeg": case "jpg":
+ imagejpeg($im); break;
+ case "gif":
+ imagegif($im); break;
+ default:
+
+ break;
+ }
+ imagedestroy($im);
+ }
+
+ }
+
+ $this->app->ExitXentral();
+ }
+
+ function get_img_type($data) {
+ $magics = array(
+ 'ffd8ff' => 'jpg',
+ '89504e470d0a1a0a' => 'png',
+ );
+
+ foreach ($magics as $str => $ext) {
+ if (strtolower(bin2hex(substr($data, 0, strlen($str)/2))) == $str)
+ {
+ return $ext;
+ }
+ }
+
+ return NULL;
+ }
+
+ public function LayoutvorlagenExport()
+ {
+ $id = (int)$this->app->Secure->GetGET('id');
+ if($id > 0)
+ {
+ if($Layout = $this->app->DB->SelectArr("select * from layoutvorlagen where id = ".$id." limit 1"))
+ {
+ $Layout = reset($Layout);
+ $Layoutpositionen = $this->app->DB->SelectArr("select * from layoutvorlagen_positionen where layoutvorlage = ".$id);
+ header('Conent-Type: application/json');
+ header("Content-Disposition: attachment; filename=\"Layout".$this->app->erp->Dateinamen((trim($Layout['name'])!= ''?'_'.$Layout['name']:(trim($Layout['beschreibung']) != ''?'_'.$Layout['beschreibung']:''))).".json\"");
+ $Datei['Layout'] = $Layout;
+ if(!empty($Layoutpositionen))
+ {
+ $Datei['Layoutpositionen'] = $Layoutpositionen;
+ }
+ echo json_encode($Datei);
+ $this->app->ExitXentral();
+ }
+ }
+ }
+
+}
diff --git a/www/pages/log.php b/www/pages/log.php
index 46d18563..6de8da11 100644
--- a/www/pages/log.php
+++ b/www/pages/log.php
@@ -82,7 +82,7 @@ class Log
'Nachricht',
'',
];
- $width = ['1%', '4%', '8%', '4%', '10%', '15%', '20%', '10%', '5%', '40%'];
+ $width = ['1%', '4%', '9%', '4%', '10%', '15%', '20%', '10%', '5%', '40%'];
$findcols = [
'open',
'l.id',
@@ -116,7 +116,7 @@ class Log
$sql = "SELECT l.id,
'
' AS `open`,
l.id,
- DATE_FORMAT(l.log_time,'%d.%m.%Y %H:%i:%s') AS `log_time`,
+ SUBSTRING(DATE_FORMAT(l.log_time,'%d.%m.%Y %H:%i:%s %f'),1,23) AS `log_time`,
l.level, l.origin_type, l.origin_detail, l.class, l.method, l.line, l.message, l.id
FROM `log` AS `l`";
$fastcount = 'SELECT COUNT(l.id) FROM `log` AS `l`';
diff --git a/www/pages/produktion.php b/www/pages/produktion.php
index 7b1878c1..5dab6f4c 100644
--- a/www/pages/produktion.php
+++ b/www/pages/produktion.php
@@ -8,6 +8,12 @@ use Xentral\Components\Database\Exception\QueryFailureException;
class Produktion {
+ // Botched helper function -> Should be replaced with a proper locale solution someday TODO
+ function FormatMenge ($value) {
+ return(number_format($value,0,',','.')); // DE
+// return(number_format($value,0,'.',',')); // EN
+ }
+
function __construct($app, $intern = false) {
$this->app = $app;
if ($intern)
@@ -17,42 +23,34 @@ class Produktion {
$this->app->ActionHandler("list", "produktion_list");
$this->app->ActionHandler("create", "produktion_edit"); // This automatically adds a "New" button
$this->app->ActionHandler("edit", "produktion_edit");
- $this->app->ActionHandler("delete", "produktion_delete");
+ $this->app->ActionHandler("copy", "produktion_copy");
+ $this->app->ActionHandler("minidetail", "produktion_minidetail");
+ $this->app->ActionHandler("delete", "produktion_delete");
$this->app->DefaultActionHandler("list");
$this->app->ActionHandlerListen($app);
+
+ $this->Install();
}
public function Install() {
- /* Fill out manually later */
+
+
}
- static function TableSearch(&$app, $name, $erlaubtevars) {
+ public function TableSearch(&$app, $name, $erlaubtevars) {
switch ($name) {
case "produktion_list":
$allowed['produktion_list'] = array('list');
-/*
-Produktion
-Kd-Nr.
-Kunde
-Vom
-Bezeichnung
-Soll
-Ist
-Zeit geplant
-Zeit gebucht
-Projekt
-Status
-Monitor
-Menü
-*/
// $heading = array('','','datum', 'art', 'projekt', 'belegnr', 'internet', 'bearbeiter', 'angebot', 'freitext', 'internebemerkung', 'status', 'adresse', 'name', 'abteilung', 'unterabteilung', 'strasse', 'adresszusatz', 'ansprechpartner', 'plz', 'ort', 'land', 'ustid', 'ust_befreit', 'ust_inner', 'email', 'telefon', 'telefax', 'betreff', 'kundennummer', 'versandart', 'vertrieb', 'zahlungsweise', 'zahlungszieltage', 'zahlungszieltageskonto', 'zahlungszielskonto', 'bank_inhaber', 'bank_institut', 'bank_blz', 'bank_konto', 'kreditkarte_typ', 'kreditkarte_inhaber', 'kreditkarte_nummer', 'kreditkarte_pruefnummer', 'kreditkarte_monat', 'kreditkarte_jahr', 'firma', 'versendet', 'versendet_am', 'versendet_per', 'versendet_durch', 'autoversand', 'keinporto', 'keinestornomail', 'abweichendelieferadresse', 'liefername', 'lieferabteilung', 'lieferunterabteilung', 'lieferland', 'lieferstrasse', 'lieferort', 'lieferplz', 'lieferadresszusatz', 'lieferansprechpartner', 'packstation_inhaber', 'packstation_station', 'packstation_ident', 'packstation_plz', 'packstation_ort', 'autofreigabe', 'freigabe', 'nachbesserung', 'gesamtsumme', 'inbearbeitung', 'abgeschlossen', 'nachlieferung', 'lager_ok', 'porto_ok', 'ust_ok', 'check_ok', 'vorkasse_ok', 'nachnahme_ok', 'reserviert_ok', 'bestellt_ok', 'zeit_ok', 'versand_ok', 'partnerid', 'folgebestaetigung', 'zahlungsmail', 'stornogrund', 'stornosonstiges', 'stornorueckzahlung', 'stornobetrag', 'stornobankinhaber', 'stornobankkonto', 'stornobankblz', 'stornobankbank', 'stornogutschrift', 'stornogutschriftbeleg', 'stornowareerhalten', 'stornomanuellebearbeitung', 'stornokommentar', 'stornobezahlt', 'stornobezahltam', 'stornobezahltvon', 'stornoabgeschlossen', 'stornorueckzahlungper', 'stornowareerhaltenretour', 'partnerausgezahlt', 'partnerausgezahltam', 'kennen', 'logdatei', 'bezeichnung', 'datumproduktion', 'anschreiben', 'usereditid', 'useredittimestamp', 'steuersatz_normal', 'steuersatz_zwischen', 'steuersatz_ermaessigt', 'steuersatz_starkermaessigt', 'steuersatz_dienstleistung', 'waehrung', 'schreibschutz', 'pdfarchiviert', 'pdfarchiviertversion', 'typ', 'reservierart', 'auslagerart', 'projektfiliale', 'datumauslieferung', 'datumbereitstellung', 'unterlistenexplodieren', 'charge', 'arbeitsschrittetextanzeigen', 'einlagern_ok', 'auslagern_ok', 'mhd', 'auftragmengenanpassen', 'internebezeichnung', 'mengeoriginal', 'teilproduktionvon', 'teilproduktionnummer', 'parent', 'parentnummer', 'bearbeiterid', 'mengeausschuss', 'mengeerfolgreich', 'abschlussbemerkung', 'auftragid', 'funktionstest', 'seriennummer_erstellen', 'unterseriennummern_erfassen', 'datumproduktionende', 'standardlager', 'Menü');
$heading = array('','','Produktion','Kd-Nr.','Kunde','Vom','Bezeichnung','Soll','Ist','Zeit geplant','Zeit gebucht','Projekt','Status','Monitor','Menü');
+ $alignright = array(8,9,10,11);
+
$width = array('1%','1%','10%'); // Fill out manually later
// $findcols = array('p.datum', 'p.art', 'p.projekt', 'p.belegnr', 'p.internet', 'p.bearbeiter', 'p.angebot', 'p.freitext', 'p.internebemerkung', 'p.status', 'p.adresse', 'p.name', 'p.abteilung', 'p.unterabteilung', 'p.strasse', 'p.adresszusatz', 'p.ansprechpartner', 'p.plz', 'p.ort', 'p.land', 'p.ustid', 'p.ust_befreit', 'p.ust_inner', 'p.email', 'p.telefon', 'p.telefax', 'p.betreff', 'p.kundennummer', 'p.versandart', 'p.vertrieb', 'p.zahlungsweise', 'p.zahlungszieltage', 'p.zahlungszieltageskonto', 'p.zahlungszielskonto', 'p.bank_inhaber', 'p.bank_institut', 'p.bank_blz', 'p.bank_konto', 'p.kreditkarte_typ', 'p.kreditkarte_inhaber', 'p.kreditkarte_nummer', 'p.kreditkarte_pruefnummer', 'p.kreditkarte_monat', 'p.kreditkarte_jahr', 'p.firma', 'p.versendet', 'p.versendet_am', 'p.versendet_per', 'p.versendet_durch', 'p.autoversand', 'p.keinporto', 'p.keinestornomail', 'p.abweichendelieferadresse', 'p.liefername', 'p.lieferabteilung', 'p.lieferunterabteilung', 'p.lieferland', 'p.lieferstrasse', 'p.lieferort', 'p.lieferplz', 'p.lieferadresszusatz', 'p.lieferansprechpartner', 'p.packstation_inhaber', 'p.packstation_station', 'p.packstation_ident', 'p.packstation_plz', 'p.packstation_ort', 'p.autofreigabe', 'p.freigabe', 'p.nachbesserung', 'p.gesamtsumme', 'p.inbearbeitung', 'p.abgeschlossen', 'p.nachlieferung', 'p.lager_ok', 'p.porto_ok', 'p.ust_ok', 'p.check_ok', 'p.vorkasse_ok', 'p.nachnahme_ok', 'p.reserviert_ok', 'p.bestellt_ok', 'p.zeit_ok', 'p.versand_ok', 'p.partnerid', 'p.folgebestaetigung', 'p.zahlungsmail', 'p.stornogrund', 'p.stornosonstiges', 'p.stornorueckzahlung', 'p.stornobetrag', 'p.stornobankinhaber', 'p.stornobankkonto', 'p.stornobankblz', 'p.stornobankbank', 'p.stornogutschrift', 'p.stornogutschriftbeleg', 'p.stornowareerhalten', 'p.stornomanuellebearbeitung', 'p.stornokommentar', 'p.stornobezahlt', 'p.stornobezahltam', 'p.stornobezahltvon', 'p.stornoabgeschlossen', 'p.stornorueckzahlungper', 'p.stornowareerhaltenretour', 'p.partnerausgezahlt', 'p.partnerausgezahltam', 'p.kennen', 'p.logdatei', 'p.bezeichnung', 'p.datumproduktion', 'p.anschreiben', 'p.usereditid', 'p.useredittimestamp', 'p.steuersatz_normal', 'p.steuersatz_zwischen', 'p.steuersatz_ermaessigt', 'p.steuersatz_starkermaessigt', 'p.steuersatz_dienstleistung', 'p.waehrung', 'p.schreibschutz', 'p.pdfarchiviert', 'p.pdfarchiviertversion', 'p.typ', 'p.reservierart', 'p.auslagerart', 'p.projektfiliale', 'p.datumauslieferung', 'p.datumbereitstellung', 'p.unterlistenexplodieren', 'p.charge', 'p.arbeitsschrittetextanzeigen', 'p.einlagern_ok', 'p.auslagern_ok', 'p.mhd', 'p.auftragmengenanpassen', 'p.internebezeichnung', 'p.mengeoriginal', 'p.teilproduktionvon', 'p.teilproduktionnummer', 'p.parent', 'p.parentnummer', 'p.bearbeiterid', 'p.mengeausschuss', 'p.mengeerfolgreich', 'p.abschlussbemerkung', 'p.auftragid', 'p.funktionstest', 'p.seriennummer_erstellen', 'p.unterseriennummern_erfassen', 'p.datumproduktionende', 'p.standardlager');
- $findcols = array('p.id','p.id','p.belegnr','p.kundennummer','p.name','p.datum');
+ $findcols = array('p.id','p.id','p.belegnr','p.kundennummer','p.name','p.datum','a.name_de','soll','ist', 'zeit_geplant','zeit_geplant', 'projekt','p.status','icons','id');
// $searchsql = array('p.datum', 'p.art', 'p.projekt', 'p.belegnr', 'p.internet', 'p.bearbeiter', 'p.angebot', 'p.freitext', 'p.internebemerkung', 'p.status', 'p.adresse', 'p.name', 'p.abteilung', 'p.unterabteilung', 'p.strasse', 'p.adresszusatz', 'p.ansprechpartner', 'p.plz', 'p.ort', 'p.land', 'p.ustid', 'p.ust_befreit', 'p.ust_inner', 'p.email', 'p.telefon', 'p.telefax', 'p.betreff', 'p.kundennummer', 'p.versandart', 'p.vertrieb', 'p.zahlungsweise', 'p.zahlungszieltage', 'p.zahlungszieltageskonto', 'p.zahlungszielskonto', 'p.bank_inhaber', 'p.bank_institut', 'p.bank_blz', 'p.bank_konto', 'p.kreditkarte_typ', 'p.kreditkarte_inhaber', 'p.kreditkarte_nummer', 'p.kreditkarte_pruefnummer', 'p.kreditkarte_monat', 'p.kreditkarte_jahr', 'p.firma', 'p.versendet', 'p.versendet_am', 'p.versendet_per', 'p.versendet_durch', 'p.autoversand', 'p.keinporto', 'p.keinestornomail', 'p.abweichendelieferadresse', 'p.liefername', 'p.lieferabteilung', 'p.lieferunterabteilung', 'p.lieferland', 'p.lieferstrasse', 'p.lieferort', 'p.lieferplz', 'p.lieferadresszusatz', 'p.lieferansprechpartner', 'p.packstation_inhaber', 'p.packstation_station', 'p.packstation_ident', 'p.packstation_plz', 'p.packstation_ort', 'p.autofreigabe', 'p.freigabe', 'p.nachbesserung', 'p.gesamtsumme', 'p.inbearbeitung', 'p.abgeschlossen', 'p.nachlieferung', 'p.lager_ok', 'p.porto_ok', 'p.ust_ok', 'p.check_ok', 'p.vorkasse_ok', 'p.nachnahme_ok', 'p.reserviert_ok', 'p.bestellt_ok', 'p.zeit_ok', 'p.versand_ok', 'p.partnerid', 'p.folgebestaetigung', 'p.zahlungsmail', 'p.stornogrund', 'p.stornosonstiges', 'p.stornorueckzahlung', 'p.stornobetrag', 'p.stornobankinhaber', 'p.stornobankkonto', 'p.stornobankblz', 'p.stornobankbank', 'p.stornogutschrift', 'p.stornogutschriftbeleg', 'p.stornowareerhalten', 'p.stornomanuellebearbeitung', 'p.stornokommentar', 'p.stornobezahlt', 'p.stornobezahltam', 'p.stornobezahltvon', 'p.stornoabgeschlossen', 'p.stornorueckzahlungper', 'p.stornowareerhaltenretour', 'p.partnerausgezahlt', 'p.partnerausgezahltam', 'p.kennen', 'p.logdatei', 'p.bezeichnung', 'p.datumproduktion', 'p.anschreiben', 'p.usereditid', 'p.useredittimestamp', 'p.steuersatz_normal', 'p.steuersatz_zwischen', 'p.steuersatz_ermaessigt', 'p.steuersatz_starkermaessigt', 'p.steuersatz_dienstleistung', 'p.waehrung', 'p.schreibschutz', 'p.pdfarchiviert', 'p.pdfarchiviertversion', 'p.typ', 'p.reservierart', 'p.auslagerart', 'p.projektfiliale', 'p.datumauslieferung', 'p.datumbereitstellung', 'p.unterlistenexplodieren', 'p.charge', 'p.arbeitsschrittetextanzeigen', 'p.einlagern_ok', 'p.auslagern_ok', 'p.mhd', 'p.auftragmengenanpassen', 'p.internebezeichnung', 'p.mengeoriginal', 'p.teilproduktionvon', 'p.teilproduktionnummer', 'p.parent', 'p.parentnummer', 'p.bearbeiterid', 'p.mengeausschuss', 'p.mengeerfolgreich', 'p.abschlussbemerkung', 'p.auftragid', 'p.funktionstest', 'p.seriennummer_erstellen', 'p.unterseriennummern_erfassen', 'p.datumproduktionende', 'p.standardlager');
$searchsql = array('p.datum', 'p.art', 'p.projekt', 'p.belegnr', 'p.internet', 'p.bearbeiter', 'p.angebot', 'p.freitext', 'p.internebemerkung', 'p.status', 'p.adresse', 'p.name', 'p.abteilung', 'p.unterabteilung', 'p.strasse', 'p.adresszusatz', 'p.ansprechpartner', 'p.plz', 'p.ort', 'p.land', 'p.ustid', 'p.ust_befreit', 'p.ust_inner', 'p.email', 'p.telefon', 'p.telefax', 'p.betreff', 'p.kundennummer', 'p.versandart', 'p.vertrieb', 'p.zahlungsweise', 'p.zahlungszieltage', 'p.zahlungszieltageskonto', 'p.zahlungszielskonto', 'p.bank_inhaber', 'p.bank_institut', 'p.bank_blz', 'p.bank_konto', 'p.kreditkarte_typ', 'p.kreditkarte_inhaber', 'p.kreditkarte_nummer', 'p.kreditkarte_pruefnummer', 'p.kreditkarte_monat', 'p.kreditkarte_jahr', 'p.firma', 'p.versendet', 'p.versendet_am', 'p.versendet_per', 'p.versendet_durch', 'p.autoversand', 'p.keinporto', 'p.keinestornomail', 'p.abweichendelieferadresse', 'p.liefername', 'p.lieferabteilung', 'p.lieferunterabteilung', 'p.lieferland', 'p.lieferstrasse', 'p.lieferort', 'p.lieferplz', 'p.lieferadresszusatz', 'p.lieferansprechpartner', 'p.packstation_inhaber', 'p.packstation_station', 'p.packstation_ident', 'p.packstation_plz', 'p.packstation_ort', 'p.autofreigabe', 'p.freigabe', 'p.nachbesserung', 'p.gesamtsumme', 'p.inbearbeitung', 'p.abgeschlossen', 'p.nachlieferung', 'p.lager_ok', 'p.porto_ok', 'p.ust_ok', 'p.check_ok', 'p.vorkasse_ok', 'p.nachnahme_ok', 'p.reserviert_ok', 'p.bestellt_ok', 'p.zeit_ok', 'p.versand_ok', 'p.partnerid', 'p.folgebestaetigung', 'p.zahlungsmail', 'p.stornogrund', 'p.stornosonstiges', 'p.stornorueckzahlung', 'p.stornobetrag', 'p.stornobankinhaber', 'p.stornobankkonto', 'p.stornobankblz', 'p.stornobankbank', 'p.stornogutschrift', 'p.stornogutschriftbeleg', 'p.stornowareerhalten', 'p.stornomanuellebearbeitung', 'p.stornokommentar', 'p.stornobezahlt', 'p.stornobezahltam', 'p.stornobezahltvon', 'p.stornoabgeschlossen', 'p.stornorueckzahlungper', 'p.stornowareerhaltenretour', 'p.partnerausgezahlt', 'p.partnerausgezahltam', 'p.kennen', 'p.logdatei', 'p.bezeichnung', 'p.datumproduktion', 'p.anschreiben', 'p.usereditid', 'p.useredittimestamp', 'p.steuersatz_normal', 'p.steuersatz_zwischen', 'p.steuersatz_ermaessigt', 'p.steuersatz_starkermaessigt', 'p.steuersatz_dienstleistung', 'p.waehrung', 'p.schreibschutz', 'p.pdfarchiviert', 'p.pdfarchiviertversion', 'p.typ', 'p.reservierart', 'p.auslagerart', 'p.projektfiliale', 'p.datumauslieferung', 'p.datumbereitstellung', 'p.unterlistenexplodieren', 'p.charge', 'p.arbeitsschrittetextanzeigen', 'p.einlagern_ok', 'p.auslagern_ok', 'p.mhd', 'p.auftragmengenanpassen', 'p.internebezeichnung', 'p.mengeoriginal', 'p.teilproduktionvon', 'p.teilproduktionnummer', 'p.parent', 'p.parentnummer', 'p.bearbeiterid', 'p.mengeausschuss', 'p.mengeerfolgreich', 'p.abschlussbemerkung', 'p.auftragid', 'p.funktionstest', 'p.seriennummer_erstellen', 'p.unterseriennummern_erfassen', 'p.datumproduktionende', 'p.standardlager');
@@ -60,34 +58,255 @@ Menü
$defaultorder = 1;
$defaultorderdesc = 0;
- $dropnbox = "'
' AS `open`, CONCAT('
') AS `auswahl`";
+ $dropnbox = "'
' AS `open`, CONCAT('
') AS `auswahl`";
- $menu = "
";
+ $menu = "
";
// $sql = "SELECT SQL_CALC_FOUND_ROWS p.id, $dropnbox, p.datum, p.art, p.projekt, p.belegnr, p.internet, p.bearbeiter, p.angebot, p.freitext, p.internebemerkung, p.status, p.adresse, p.name, p.abteilung, p.unterabteilung, p.strasse, p.adresszusatz, p.ansprechpartner, p.plz, p.ort, p.land, p.ustid, p.ust_befreit, p.ust_inner, p.email, p.telefon, p.telefax, p.betreff, p.kundennummer, p.versandart, p.vertrieb, p.zahlungsweise, p.zahlungszieltage, p.zahlungszieltageskonto, p.zahlungszielskonto, p.bank_inhaber, p.bank_institut, p.bank_blz, p.bank_konto, p.kreditkarte_typ, p.kreditkarte_inhaber, p.kreditkarte_nummer, p.kreditkarte_pruefnummer, p.kreditkarte_monat, p.kreditkarte_jahr, p.firma, p.versendet, p.versendet_am, p.versendet_per, p.versendet_durch, p.autoversand, p.keinporto, p.keinestornomail, p.abweichendelieferadresse, p.liefername, p.lieferabteilung, p.lieferunterabteilung, p.lieferland, p.lieferstrasse, p.lieferort, p.lieferplz, p.lieferadresszusatz, p.lieferansprechpartner, p.packstation_inhaber, p.packstation_station, p.packstation_ident, p.packstation_plz, p.packstation_ort, p.autofreigabe, p.freigabe, p.nachbesserung, p.gesamtsumme, p.inbearbeitung, p.abgeschlossen, p.nachlieferung, p.lager_ok, p.porto_ok, p.ust_ok, p.check_ok, p.vorkasse_ok, p.nachnahme_ok, p.reserviert_ok, p.bestellt_ok, p.zeit_ok, p.versand_ok, p.partnerid, p.folgebestaetigung, p.zahlungsmail, p.stornogrund, p.stornosonstiges, p.stornorueckzahlung, p.stornobetrag, p.stornobankinhaber, p.stornobankkonto, p.stornobankblz, p.stornobankbank, p.stornogutschrift, p.stornogutschriftbeleg, p.stornowareerhalten, p.stornomanuellebearbeitung, p.stornokommentar, p.stornobezahlt, p.stornobezahltam, p.stornobezahltvon, p.stornoabgeschlossen, p.stornorueckzahlungper, p.stornowareerhaltenretour, p.partnerausgezahlt, p.partnerausgezahltam, p.kennen, p.logdatei, p.bezeichnung, p.datumproduktion, p.anschreiben, p.usereditid, p.useredittimestamp, p.steuersatz_normal, p.steuersatz_zwischen, p.steuersatz_ermaessigt, p.steuersatz_starkermaessigt, p.steuersatz_dienstleistung, p.waehrung, p.schreibschutz, p.pdfarchiviert, p.pdfarchiviertversion, p.typ, p.reservierart, p.auslagerart, p.projektfiliale, p.datumauslieferung, p.datumbereitstellung, p.unterlistenexplodieren, p.charge, p.arbeitsschrittetextanzeigen, p.einlagern_ok, p.auslagern_ok, p.mhd, p.auftragmengenanpassen, p.internebezeichnung, p.mengeoriginal, p.teilproduktionvon, p.teilproduktionnummer, p.parent, p.parentnummer, p.bearbeiterid, p.mengeausschuss, p.mengeerfolgreich, p.abschlussbemerkung, p.auftragid, p.funktionstest, p.seriennummer_erstellen, p.unterseriennummern_erfassen, p.datumproduktionende, p.standardlager, p.id FROM produktion p";
// $sql = "SELECT SQL_CALC_FOUND_ROWS p.id, $dropnbox, p.belegnr, p.kundennummer, p.name, p.datum, \"SUBSELECT\", \"SUBSELECT\", p.mengeerfolgreich, \"-\", \"-\", p.projekt, p.status, p.status, p.id FROM produktion p";
$sql = "SELECT SQL_CALC_FOUND_ROWS
- p.id,
- $dropnbox,
- p.belegnr,
- p.kundennummer,
- p.name,
- p.datum,
- (SELECT pp.bezeichnung FROM produktion_position pp WHERE pp.produktion = p.id AND pp.stuecklistestufe = 1 LIMIT 1),
- FORMAT(p.mengeoriginal,0),
- FORMAT(p.mengeerfolgreich,0),
- \"-\",
- \"-\",
- (SELECT projekt.abkuerzung FROM projekt WHERE p.projekt = projekt.id LIMIT 1),
- p.status,
- (" . $app->YUI->IconsSQL_produktion('p') . ") AS `icons`,
- p.id
- FROM produktion p";
+ p.id,
+ $dropnbox,
+ p.belegnr,
+ p.kundennummer,
+ (SELECT name FROM adresse WHERE kundennummer = p.kundennummer AND p.kundennummer != 0 LIMIT 1) as name,
+ DATE_FORMAT(datum,'%d.%m.%Y') as datum,
+
+ CONCAT (
+ IFNULL((SELECT CONCAT(a.name_de,' (',a.nummer,')','
') FROM artikel a INNER JOIN produktion_position pp ON pp.artikel = a.id WHERE pp.stuecklistestufe = 1 AND pp.produktion = p.id LIMIT 1),''),
+ CONCAT('
',internebezeichnung,' ')
+ ) as bezeichnung,
- $where = "1";
- $count = "SELECT count(DISTINCT id) FROM produktion WHERE $where";
+ FORMAT((SELECT SUM(menge) FROM produktion_position pp WHERE pp.produktion = p.id AND pp.stuecklistestufe = 1),0,'de_DE') as soll,
+ FORMAT(p.mengeerfolgreich,0,'de_DE') as ist,
+ \"-\" as zeit_geplant,
+ \"-\" as zeit_erfasst,
+ (SELECT projekt.abkuerzung FROM projekt WHERE p.projekt = projekt.id LIMIT 1) as projekt,
+ p.status,
+ (" . $app->YUI->IconsSQL_produktion('p') . ") AS `icons`,
+ p.id
+ FROM produktion p
+ ";
+
+ $where = "0";
+
+ // Toggle filters
+ $this->app->Tpl->Add('JQUERYREADY', "$('#angelegte').click( function() { fnFilterColumn1( 0 ); } );");
+ $this->app->Tpl->Add('JQUERYREADY', "$('#offene').click( function() { fnFilterColumn2( 0 ); } );");
+ $this->app->Tpl->Add('JQUERYREADY', "$('#geschlossene').click( function() { fnFilterColumn3( 0 ); } );");
+ $this->app->Tpl->Add('JQUERYREADY', "$('#stornierte').click( function() { fnFilterColumn4( 0 ); } );");
+
+ for ($r = 1;$r <= 4;$r++) {
+ $this->app->Tpl->Add('JAVASCRIPT', '
+ function fnFilterColumn' . $r . ' ( i )
+ {
+ if(oMoreData' . $r . $name . '==1)
+ oMoreData' . $r . $name . ' = 0;
+ else
+ oMoreData' . $r . $name . ' = 1;
+
+ $(\'#' . $name . '\').dataTable().fnFilter(
+ \'\',
+ i,
+ 0,0
+ );
+ }
+ ');
+ }
+
+
+ $more_data1 = $this->app->Secure->GetGET("more_data1");
+ if ($more_data1 == 1) {
+ $where .= " OR p.status IN ('angelegt')";
+ } else {
+ }
+
+ $more_data2 = $this->app->Secure->GetGET("more_data2");
+ if ($more_data2 == 1) {
+ $where .= " OR p.status IN ('freigegeben','gestartet')";
+ }
+ else {
+ }
+
+ $more_data3 = $this->app->Secure->GetGET("more_data3");
+ if ($more_data3 == 1) {
+ $where .= " OR p.status IN ('abgeschlossen')";
+ }
+ else {
+ }
+
+ $more_data4 = $this->app->Secure->GetGET("more_data4");
+ if ($more_data4 == 1) {
+ $where .= " OR p.status IN ('storniert')";
+ }
+ else {
+ }
+ // END Toggle filters
+
+ $moreinfo = true; // Allow drop down details
+ $menucol = 14; // For moredata
+
+ if ($where=='0') {
+ $where = " p.status IN ('freigegeben','gestartet')";
+ }
+
+ $count = "SELECT count(DISTINCT p.id) FROM produktion p INNER JOIN produktion_position pp ON pp.produktion = pp.id WHERE $where";
// $groupby = "";
+ break;
+ case "produktion_position_source_list":
+ $id = $app->Secure->GetGET('id');
+
+ $sql = "SELECT standardlager FROM produktion WHERE id=$id";
+ $standardlager = $app->DB->SelectArr($sql)[0]['standardlager'];
+
+ $allowed['produktion_position_list'] = array('list');
+
+ $sql = "SELECT menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=1";
+ $produktionsmenge = $app->DB->SelectArr($sql)[0]['menge'];
+
+ // Get status to control UI element menu availability
+ $sql = "SELECT p.status from produktion p WHERE p.id = $id";
+ $result = $app->DB->SelectArr($sql)[0];
+ $status = $result['status'];
+
+ if (in_array($status,array('angelegt','freigegeben'))) {
+ $heading = array('','','Nummer', 'Artikel', 'Projekt', 'Planmenge pro Stück', 'Lager alle (verfügbar)', 'Lager (verfügbar)', 'Reserviert', 'Planmenge', 'Verbraucht', 'Menü');
+ $width = array( '1%','1%','5%', '30%', '5%', '1%', '1%', '1%' , '1%', '1%', '1%' ,'1%');
+ $menu = "
";
+ } else {
+ $heading = array('','','Nummer', 'Artikel', 'Projekt','Planmenge pro Stück', 'Lager alle (verfügbar)', 'Lager (verfügbar)', 'Reserviert', 'Planmenge', 'Verbraucht', '');
+ $width = array( '1%','1%','5%', '30%', '5%', '1%', '1%', '1%' , '1%', '1%', '1%' ,'1%');
+ $menu = "";
+ }
+
+ $alignright = array(6,7,8,9,10);
+
+ $findcols = array('','p.artikel','(SELECT a.nummer FROM artikel a WHERE a.id = p.artikel LIMIT 1)','(SELECT a.name_de FROM artikel a WHERE a.id = p.artikel LIMIT 1)','projekt','stueckmenge','lageralle','lager','reserviert','menge','geliefert_menge');
+ $searchsql = array('p.artikel','nummer','name','projekt','lager','menge','reserviert','geliefert_menge');
+
+ $defaultorder = 1;
+ $defaultorderdesc = 0;
+
+ $dropnbox = "'
' AS `open`, CONCAT('
') AS `auswahl`";
+
+ $sql = "SELECT SQL_CALC_FOUND_ROWS
+ p.id,
+ $dropnbox,
+ (SELECT a.nummer FROM artikel a WHERE a.id = p.artikel LIMIT 1) as nummer,
+ (SELECT a.name_de FROM artikel a WHERE a.id = p.artikel LIMIT 1) as name,
+ (SELECT projekt.abkuerzung FROM projekt INNER JOIN artikel a WHERE a.projekt = projekt.id AND a.id = p.artikel LIMIT 1) as projekt,
+ FORMAT(p.menge/$produktionsmenge,0,'de_DE') as stueckmenge,
+ IF ((SELECT lagerartikel FROM artikel a WHERE a.id = p.artikel LIMIT 1) != 0,
+ CONCAT (
+ FORMAT (IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.artikel = p.artikel),0),0,'de_DE'),
+ ' (',
+ FORMAT (
+ IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.artikel = p.artikel),0)-
+ IFNULL((SELECT SUM(menge) FROM lager_reserviert r WHERE r.artikel = p.artikel),0),
+ 0,
+ 'de_DE'
+ ),
+ ')'
+ ),'') as lageralle,
+ if (('$standardlager' != '0') && ((SELECT lagerartikel FROM artikel a WHERE a.id = p.artikel LIMIT 1) != 0),
+ CONCAT (
+ FORMAT (IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.lager_platz = $standardlager AND lpi.artikel = p.artikel),0),0,'de_DE'),
+ ' (',
+ FORMAT (
+ IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.lager_platz = $standardlager AND lpi.artikel = p.artikel),0)-
+ IFNULL((SELECT SUM(menge) FROM lager_reserviert r WHERE r.lager_platz = $standardlager AND r.artikel = p.artikel),0),
+ 0,
+ 'de_DE'
+ ),
+ ')'
+ )
+ ,''
+ ) as lager,
+ FORMAT ((SELECT SUM(menge) FROM lager_reserviert r WHERE r.lager_platz = $standardlager AND r.artikel = p.artikel AND r.objekt = 'produktion' AND r.parameter = $id AND r.posid = p.id),0,'de_DE') as Reserviert,
+ FORMAT(p.menge,0,'de_DE'),
+ FORMAT(p.geliefert_menge,0,'de_DE') as geliefert_menge,
+ p.id
+ FROM produktion_position p";
+
+ $where = " stuecklistestufe = 0 AND produktion = $id";
+
+ $count = "SELECT count(DISTINCT id) FROM produktion_position WHERE $where";
+// $groupby = "";
+
+ break;
+ case "produktion_source_list": // Aggregated per artikel
+ $id = $app->Secure->GetGET('id');
+
+ $sql = "SELECT menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=1";
+ $produktionsmenge = $app->DB->SelectArr($sql)[0]['menge'];
+
+ $sql = "SELECT standardlager FROM produktion WHERE id=$id";
+ $standardlager = $app->DB->SelectArr($sql)[0]['standardlager'];
+
+ $allowed['produktion_position_list'] = array('list');
+ $heading = array('','Nummer', 'Artikel', 'Projekt','Planmenge pro Stück', 'Lager alle (verfügbar)' ,'Lager (verfügbar)', 'Reserviert','Planmenge', 'Verbraucht','');
+ $width = array('1%','5%', '30%', '5%', '1%', '1%', '1%', '1%' , '1%', '1%' ,'1%');
+
+ $alignright = array(5,6,7,8,9);
+
+ $findcols = array('p.artikel','(SELECT a.nummer FROM artikel a WHERE a.id = p.artikel LIMIT 1)','(SELECT a.name_de FROM artikel a WHERE a.id = p.artikel LIMIT 1)','projekt','stueckmenge','lageralle','lager','reserviert','menge','geliefert_menge');
+
+ $searchsql = array('p.artikel','nummer','name','projekt','lager','menge','reserviert','geliefert_menge');
+
+ $defaultorder = 1;
+ $defaultorderdesc = 0;
+
+ $drop = "'
' AS `open`";
+
+ $sql = "SELECT SQL_CALC_FOUND_ROWS
+ p.artikel,
+ $drop,
+ (SELECT a.nummer FROM artikel a WHERE a.id = p.artikel LIMIT 1) as nummer,
+ (SELECT a.name_de FROM artikel a WHERE a.id = p.artikel LIMIT 1) as name,
+ (SELECT projekt.abkuerzung FROM projekt INNER JOIN artikel a WHERE a.projekt = projekt.id AND a.id = p.artikel LIMIT 1) as projekt,
+ FORMAT(SUM(p.menge)/$produktionsmenge,0,'de_DE') as stueckmenge,
+ IF ((SELECT lagerartikel FROM artikel a WHERE a.id = p.artikel LIMIT 1) != 0,
+ CONCAT (
+ FORMAT (IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.artikel = p.artikel),0),0,'de_DE'),
+ ' (',
+ FORMAT (
+ IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.artikel = p.artikel),0)-
+ IFNULL((SELECT SUM(menge) FROM lager_reserviert r WHERE r.artikel = p.artikel),0),
+ 0,
+ 'de_DE'
+ ),
+ ')'
+ ),'') as lageralle,
+ if (('$standardlager' != '0') && ((SELECT lagerartikel FROM artikel a WHERE a.id = p.artikel LIMIT 1) != 0),
+ CONCAT (
+ FORMAT (IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.lager_platz = $standardlager AND lpi.artikel = p.artikel),0),0,'de_DE'),
+ ' (',
+ FORMAT (
+ IFNULL((SELECT SUM(menge) FROM lager_platz_inhalt lpi WHERE lpi.lager_platz = $standardlager AND lpi.artikel = p.artikel),0)-
+ IFNULL((SELECT SUM(menge) FROM lager_reserviert r WHERE r.lager_platz = $standardlager AND r.artikel = p.artikel),0),
+ 0,
+ 'de_DE'
+ ),
+ ')'
+ )
+ ,''
+ ) as lager,
+ FORMAT ((SELECT SUM(menge) FROM lager_reserviert r WHERE r.lager_platz = $standardlager AND r.artikel = p.artikel AND r.objekt = 'produktion' AND r.parameter = $id),0,'de_DE') as reserviert,
+ FORMAT(SUM(p.menge),0,'de_DE') as menge,
+ FORMAT(p.geliefert_menge,0,'de_DE') as geliefert_menge,
+ p.id
+ FROM produktion_position p";
+
+ $where = " stuecklistestufe = 0 AND produktion = $id";
+
+ $count = "SELECT count(DISTINCT id) FROM produktion_position WHERE $where";
+ $groupby = " GROUP BY p.artikel ";
+
break;
}
@@ -107,6 +326,8 @@ Menü
$this->app->erp->MenuEintrag("index.php", "Zurück");
+ $this->StatusBerechnen(0); // all open ones
+
$this->app->YUI->TableSearch('TAB1', 'produktion_list', "show", "", "", basename(__FILE__), __CLASS__);
$this->app->Tpl->Parse('PAGE', "produktion_list.tpl");
}
@@ -114,8 +335,18 @@ Menü
public function produktion_delete() {
$id = (int) $this->app->Secure->GetGET('id');
- $this->app->DB->Delete("DELETE FROM `produktion` WHERE `id` = '{$id}'");
- $this->app->Tpl->Set('MESSAGE', "
Der Eintrag wurde gelöscht.
");
+ // Check if storno possible -> No partial production yet
+
+ $geliefert_menge = $this->app->DB->SelectArr("SELECT SUM(geliefert_menge) as menge FROM produktion_position pp WHERE pp.produktion = $id")[0]['menge'];
+
+ if ($geliefert_menge == 0) {
+
+ $sql = "UPDATE produktion SET status='storniert' WHERE id = '$id'";
+ $this->app->DB->Update($sql);
+ $this->app->Tpl->Set('MESSAGE', "
Der Eintrag wurde storniert.
");
+ } else {
+ $this->app->Tpl->Set('MESSAGE', "
Der Eintrag kann nicht storniert werden, da bereits Buchungen vorhanden sind.
");
+ }
$this->produktion_list();
}
@@ -125,410 +356,1357 @@ Menü
* If id is empty, create a new one
*/
- function produktion_edit() {
- $id = $this->app->Secure->GetGET('id');
-
+ function produktion_edit($id = NULL) {
+
+ if (empty($id)) {
+ $id = $this->app->Secure->GetGET('id');
+ }
+ if($this->app->erp->DisableModul('produktion',$id))
+ {
+ return;
+ }
+
+ $submit = $this->app->Secure->GetPOST('submit');
+
$this->app->Tpl->Set('ID', $id);
$this->app->erp->MenuEintrag("index.php?module=produktion&action=edit&id=$id", "Details");
$this->app->erp->MenuEintrag("index.php?module=produktion&action=list", "Zurück zur Übersicht");
- $id = $this->app->Secure->GetGET('id');
$input = $this->GetInput();
- $submit = $this->app->Secure->GetPOST('submit');
-
+ $msg = $this->app->erp->base64_url_decode($this->app->Secure->GetGET('msg'));
+
+ $sql = "SELECT status, belegnr, projekt, standardlager FROM produktion WHERE id = '$id'";
+ $from_db = $this->app->DB->SelectArr($sql)[0];
+ $global_status = $from_db['status'];
+ $global_produktionsnummer = $from_db['belegnr'];
+ $global_projekt = $from_db['projekt'];
+ $global_standardlager = $from_db['standardlager'];
+
+// foreach ($input as $key => $value) {
+// echo($key." -> ".$value."
\n");
+// }
+
+ $this->app->Tpl->Set('MESSAGE', "");
+
if (empty($id)) {
// New item
- $id = 'NULL';
- }
+ $id = 'NULL';
+
+ } else {
+ }
if ($submit != '')
{
- // Write to database
+ $msg = "";
+
+ switch ($submit) {
+ case 'speichern':
+ // Write to database
- // Add checks here
+ // Add checks here
- $columns = "id, ";
- $values = "$id, ";
- $update = "";
+ if (empty($input['datum'])) {
+ $input['datum'] = date("Y-m-d");
+ } else {
+ $input['datum'] = $this->app->erp->ReplaceDatum(true,$input['datum'],true);
+ }
+
+ if ($id == 'NULL') {
+ $input['status'] = 'angelegt';
+ }
+
+ $input['datumauslieferung'] = $this->app->erp->ReplaceDatum(true,$input['datumauslieferung'],true);
+ $input['datumbereitstellung'] = $this->app->erp->ReplaceDatum(true,$input['datumbereitstellung'],true);
+ $input['datumproduktion'] = $this->app->erp->ReplaceDatum(true,$input['datumproduktion'],true);
+ $input['datumproduktionende'] = $this->app->erp->ReplaceDatum(true,$input['datumproduktionende'],true);
+ $input['projekt'] = $this->app->erp->ReplaceProjekt(true,$input['projekt'],true);
+
+ $columns = "id, ";
+ $values = "$id, ";
+ $update = "";
+
+ $fix = "";
+
+ foreach ($input as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $update = $update.$fix.$key." = '$value'";
+ $fix = ", ";
+ }
+
+ $sql = "INSERT INTO produktion (".$columns.") VALUES (".$values.") ON DUPLICATE KEY UPDATE ".$update;
+ $this->app->DB->Update($sql);
+
+ if ($id == 'NULL') {
- $fix = "";
+ $id = $this->app->DB->GetInsertID();
- foreach ($input as $key => $value) {
- $columns = $columns.$fix.$key;
- $values = $values.$fix."'".$value."'";
- $update = $update.$fix.$key." = '$value'";
+ if (!empty($id)) {
+ $this->ProtokollSchreiben($id,'Produktion angelegt');
+ $msg = "
Das Element wurde erfolgreich angelegt.
"; // Overwrite old MSG
+ $msg = $this->app->erp->base64_url_encode($msg);
+ header("Location: index.php?module=produktion&action=edit&id=$id&msg=$msg");
+ }
+
+ } else {
+ $msg .= "
Die Einstellungen wurden erfolgreich übernommen.
";
+ }
+ break;
+ case 'planen':
+
+ // Check
+ // Parse positions
+ $sql = "SELECT artikel FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=1";
+ $produktionsartikel = $this->app->DB->SelectArr($sql);
- $fix = ", ";
- }
+ if (!empty($produktionsartikel)) {
+ $msg .= "
Bereits geplant.
";
+ break;
+ }
-// echo($columns."
");
-// echo($values."
");
-// echo($update."
");
+ $artikel_planen_id = $this->app->erp->ReplaceArtikel(true, $this->app->Secure->GetPOST('artikel_planen'),true); // Convert from form to artikel number
+ $artikel_planen_menge = $this->app->Secure->GetPOST('artikel_planen_menge');
- $sql = "INSERT INTO produktion (".$columns.") VALUES (".$values.") ON DUPLICATE KEY UPDATE ".$update;
+ if (!$artikel_planen_id) {
+ $msg .= "
Artikel ist keine Stückliste.
";
+ break;
+ }
-// echo($sql);
+ if ($artikel_planen_menge < 1) {
+ $msg .= "
Ungültige Planmenge.
";
+ break;
+ }
- $this->app->DB->Update($sql);
+ // Insert positions
- if ($id == 'NULL') {
- $msg = $this->app->erp->base64_url_encode("
Das Element wurde erfolgreich angelegt.
");
- header("Location: index.php?module=produktion&action=list&msg=$msg");
- } else {
- $this->app->Tpl->Set('MESSAGE', "
Die Einstellungen wurden erfolgreich übernommen.
");
- }
+ $position_array = array();
+
+ $sql = "SELECT '".$id."' as id, artikel, menge, '0' as stuecklistestufe FROM stueckliste WHERE stuecklistevonartikel = ".$artikel_planen_id;
+ $stueckliste = $this->app->DB->SelectArr($sql);
+
+ if (empty($stueckliste)) {
+ $msg .= "
Stückliste ist leer.
";
+ break;
+ }
+
+ foreach ($stueckliste as $key => $value) {
+ $value['menge'] = $value['menge'] * $artikel_planen_menge;
+ $position_values[] = '('.implode(",",$value).',\'\')';
+ }
+
+ $sql = "INSERT INTO produktion_position (produktion, artikel, menge, stuecklistestufe, projekt) VALUES ( $id, $artikel_planen_id, $artikel_planen_menge, 1, '$global_projekt'), ".implode(',',$position_values);
+ $this->app->DB->Update($sql);
+
+ $msg .= "
Planung angelegt.
";
+ $this->ProtokollSchreiben($id,"Produktion geplant ($artikel_planen_menge)");
+
+ break;
+ case 'freigeben':
+ $this->app->erp->BelegFreigabe("produktion",$id);
+ $this->ProtokollSchreiben($id,'Produktion freigegeben');
+ break;
+ case 'reservieren':
+
+ // Check quantities and reserve for every position
+
+ if($global_standardlager == 0) {
+ break;
+ }
+
+ $fortschritt = $this->MengeFortschritt($id,$global_standardlager);
+
+ if (empty($fortschritt)) {
+ break;
+ }
+
+ $sql = "SELECT pp.id, pp.artikel, a.name_de, a.nummer, pp.menge as menge, pp.geliefert_menge as geliefert_menge FROM produktion_position pp INNER JOIN artikel a ON a.id = pp.artikel WHERE pp.produktion=$id AND pp.stuecklistestufe=0";
+ $materialbedarf = $this->app->DB->SelectArr($sql);
+
+ // Try to reserve material
+ $reservierung_durchgefuehrt = false;
+ foreach ($materialbedarf as $materialbedarf_position) {
+
+ // Calculate new needed quantity if there is scrap
+ $materialbedarf_position['menge'] = $materialbedarf_position['menge']*($fortschritt['ausschuss']+$fortschritt['geplant'])/$fortschritt['geplant'];
+
+ $result = $this->ArtikelReservieren($materialbedarf_position['artikel'], $global_standardlager, $materialbedarf_position['menge']-$materialbedarf_position['geliefert_menge'], 0, 'produktion', $id, $materialbedarf_position['id'],"Produktion $global_produktionsnummer");
+ if ($result > 0) {
+ $reservierung_durchgefuehrt = true;
+ }
+ }
+
+ // Message output
+ if ($reservierung_durchgefuehrt) {
+ $msg .= "
Reservierung durchgeführt.
";
+ } else {
+ $msg .= "
Keine Reservierung durchgeführt!
";
+ }
+ break;
+ case 'produzieren':
+
+ // Check quanitites
+ // Parse positions
+ $sql = "SELECT artikel, menge, geliefert_menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=1";
+ $produktionsartikel_position = $this->app->DB->SelectArr($sql)[0];
+
+ if (empty($produktionsartikel_position)) {
+ $msg .= "
Keine Planung vorhanden.
";
+ break;
+ }
+
+ $menge_produzieren = $this->app->Secure->GetPOST('menge_produzieren');
+ if (empty($menge_produzieren)) {
+ $menge_produzieren = 0;
+ }
+ $menge_ausschuss = $this->app->Secure->GetPOST('menge_ausschuss_produzieren');
+ if (empty($menge_ausschuss)) {
+ $menge_ausschuss = 0;
+ }
+
+ $menge_plan = $produktionsartikel_position['menge'];
+ $menge_geliefert = $produktionsartikel_position['geliefert_menge'];
+
+ $menge_auslagern = $menge_produzieren+$menge_ausschuss;
+
+ if ($menge_auslagern < 1) {
+ $msg .= "
Ungültige Menge.
";
+ break;
+ }
+
+ $menge_moeglich = $this->LagerCheckProduktion($id, $global_standardlager, false);
+
+ if ($menge_auslagern > $menge_moeglich) {
+ $msg .= "
Lagermenge nicht ausreichend. ($menge_auslagern > $menge_moeglich)
";
+ break;
+ }
+
+ $sql = "UPDATE produktion SET status = 'gestartet' WHERE id=$id";
+ $this->app->DB->Update($sql);
+
+ $sql = "SELECT pp.id, pp.artikel, pp.menge, pp.geliefert_menge, pp.stuecklistestufe, a.lagerartikel FROM produktion_position pp INNER JOIN artikel a ON a.id = pp.artikel WHERE pp.produktion=$id";
+ $material = $this->app->DB->SelectArr($sql);
+
+ foreach ($material as $material_position) {
+
+ // Calculate quantity to be removed
+ $menge_artikel_auslagern = $material_position['menge']/$produktionsartikel_position['menge']*$menge_auslagern;
+
+ // Remove material from stock
+ if ($material_position['stuecklistestufe'] == 0 && $material_position['lagerartikel']) {
+ $result = $this->app->erp->LagerAuslagernRegal($material_position['artikel'],$global_standardlager,$menge_artikel_auslagern,$global_projekt,'Produktion '.$produktion_belegnr);
+ if ($result != 1) {
+ $msg .= "
Kritischer Fehler beim Ausbuchen! (Position ".$material_position['id'].", Menge ".$menge_artikel_auslagern.").
".
+ $error = true;
+ break;
+ }
+ // Adjust reservation
+ $result = $this->ArtikelReservieren($material_position['artikel'],$global_standardlager,-$menge_artikel_auslagern,0,'produktion',$id,$material_position['id'],"Produktion $global_produktionsnummer");
+ }
+
+ // Update position
+ $sql = "UPDATE produktion_position SET geliefert_menge = geliefert_menge + $menge_artikel_auslagern WHERE id = ".$material_position['id'];
+ $this->app->DB->Update($sql);
+ }
+
+ if ($error) {
+ break;
+ }
+
+ // Insert produced parts into stock
+ // Check target stock, if not existing, use default stock of article, if not given use production stock
+
+
+ $ziellager_from_form = $this->app->erp->ReplaceLagerPlatz(true,$this->app->Secure->GetPOST('ziellager'),true); // Parameters: Target db?, value, from form?
+
+ $use_artikel_lager = false;
+ $ziellager = $global_standardlager;
+
+ if (!empty($ziellager_from_form)) {
+ $sql = "SELECT id FROM lager_platz WHERE id = ".$ziellager_from_form;
+ $result = $this->app->DB->SelectArr($sql);
+ if (!empty($result)) {
+ $ziellager = $ziellager_from_form;
+ } else {
+ $use_artikel_lager = true;
+ }
+ } else {
+ $use_artikel_lager = true;
+ }
+
+ if ($use_artikel_lager) {
+ $sql = "SELECT lager_platz FROM artikel WHERE id = ".$produktionsartikel_position['artikel'];
+ $result = $this->app->DB->SelectArr($sql);
+ if (!empty($result) && !empty($result[0]['lager_platz'])) {
+ $ziellager = $result[0]['lager_platz'];
+ } else {
+
+ }
+ } else {
+
+ }
+ $sql = "SELECT kurzbezeichnung FROM lager_platz WHERE id = $ziellager";
+ $lagername = $this->app->DB->SelectArr($sql)[0]['kurzbezeichnung'];
+
+ // ERPAPI
+ // function LagerEinlagern($artikel,$menge,$regal,$projekt,$grund="",$importer="",$paketannahme="",$doctype = "", $doctypeid = 0, $vpeid = 0, $permanenteinventur = 0, $adresse = 0)
+ $this->app->erp->LagerEinlagern($produktionsartikel_position['artikel'],$menge_produzieren,$ziellager,$global_projekt,"Produktion $global_produktionsnummer");
+ // No error handling in LagerEinlagern...
+
+ $sql = "UPDATE produktion SET mengeerfolgreich = mengeerfolgreich + $menge_produzieren, mengeausschuss = mengeausschuss + $menge_ausschuss WHERE id = $id";
+ $this->app->DB->Update($sql);
+
+ if ($menge_produzieren > 0) {
+ $lagertext = ", eingelagert in $lagername";
+ }
+ $text = "Produktion durchgeführt ($menge_produzieren erfolgreich, $menge_ausschuss Ausschuss)$lagertext";
+ $msg .= "
$text.
";
+ $this->ProtokollSchreiben($id,$text);
+
+ break;
+ case 'teilen':
+
+ // Create partial production
+
+ $menge_abteilen = $this->app->Secure->GetPOST('menge_produzieren');
+
+ $fortschritt = $this->MengeFortschritt($id,$global_standardlager);
+
+ if (empty($fortschritt)) {
+ break;
+ }
+
+ if (($menge_abteilen < 1) || ($menge_abteilen > $fortschritt['offen'])) {
+ $msg .= "
Ungültige Teilmenge.
";
+ break;
+ }
+
+ $sql = "SELECT * from produktion WHERE id = $id";
+ $produktion_alt = $this->app->DB->SelectArr($sql)[0];
+
+ // Part production of part production -> select parent
+ $hauptproduktion_id = $produktion_alt['teilproduktionvon'];
+ if ($hauptproduktion_id != 0) {
+ $sql = "SELECT belegnr FROM produktion WHERE id = $hauptproduktion_id";
+ $hauptproduktion_belegnr = $this->app->DB->SelectArr($sql)[0]['belegnr'];
+ } else {
+ $hauptproduktion_id = $produktion_alt['id'];
+ $hauptproduktion_belegnr = $produktion_alt['belegnr'];
+ }
+
+ $sql = "SELECT MAX(teilproduktionnummer) as tpn FROM produktion WHERE teilproduktionvon = $hauptproduktion_id";
+ $teilproduktionnummer = $this->app->DB->SelectArr($sql)[0]['tpn'];
+ if (empty($teilproduktionnummer) || $teilproduktionnummer == 0) {
+ $teilproduktionnummer = '1';
+ } else {
+ $teilproduktionnummer++;
+ }
+
+ $produktion_neu = array();
+ $produktion_neu['status'] = 'angelegt';
+ $produktion_neu['datum'] = date("Y-m-d");
+ $produktion_neu['art'] = $produktion_alt['art'];
+ $produktion_neu['projekt'] = $produktion_alt['projekt'];
+ $produktion_neu['angebot'] = $produktion_alt['angebot'];
+ $produktion_neu['kundennummer'] = $produktion_alt['kundennummer'];
+ $produktion_neu['auftragid'] = $produktion_alt['auftragid'];
+ $produktion_neu['freitext'] = $produktion_alt['freitext'];
+ $produktion_neu['internebemerkung'] = $produktion_alt['internebemerkung'];
+ $produktion_neu['adresse'] = $produktion_alt['adresse'];
+ $produktion_neu['internebemerkung'] = $produktion_alt['internebemerkung'];
+ $produktion_neu['internebezeichnung '] = $produktion_alt['internebezeichnung'];
+ $produktion_neu['standardlager'] = $produktion_alt['standardlager'];
+ $produktion_neu['belegnr'] = $hauptproduktion_belegnr."-".$teilproduktionnummer;
+ $produktion_neu['teilproduktionvon'] = $hauptproduktion_id;
+ $produktion_neu['teilproduktionnummer'] = $teilproduktionnummer;
+
+ $columns = "";
+ $values = "";
+ $update = "";
+
+ $fix = "";
+
+ foreach ($produktion_neu as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $update = $update.$fix.$key." = '$value'";
+ $fix = ", ";
+ }
+
+ $sql = "INSERT INTO produktion (".$columns.") VALUES (".$values.")";
+ $this->app->DB->Update($sql);
+ $produktion_neu_id = $this->app->DB->GetInsertID();
+
+ // Now add the positions
+ $sql = "SELECT * FROM produktion_position WHERE produktion = $id";
+ $positionen = $this->app->DB->SelectArr($sql);
+
+ foreach ($positionen as $position) {
+
+ $columns = "";
+
+ // Preserve these values
+ $pos_id = $position['id'];
+ $geliefert_menge = $position['geliefert_menge'];
+ $menge = $position['menge'];
+ $produktion_alt_id = $position['produktion'];
+ $menge_pro_stueck = $menge/$fortschritt['geplant'];
+
+ // For the new positions
+ $position['id'] = 'NULL';
+ $position['geliefert_menge'] = 0;
+
+ $position['menge'] = $menge_abteilen*$menge_pro_stueck;
+ $position['produktion'] = $produktion_neu_id;
+
+ $values = "";
+ $fix = "";
+ foreach ($position as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $fix = ", ";
+ }
+ $sql = "INSERT INTO produktion_position (".$columns.") VALUES (".$values.")";
+ $this->app->DB->Update($sql);
+
+ // For the old positions
+ // Reduce positions in old production
+ $position['id'] = $pos_id;
+ $position['geliefert_menge'] = $geliefert_menge;
+ $position['menge'] = $menge - $position['menge']; // old quantity - partial quantity
+ $position['produktion'] = $produktion_alt_id;
+
+ $fix = "";
+ $update = "";
+ foreach ($position as $key => $value) {
+ $update = $update.$fix.$key." = '".($value)."'";
+ $fix = ", ";
+ }
+
+ $sql = "UPDATE produktion_position SET $update WHERE id = $pos_id";
+ $this->app->DB->Update($sql);
+
+ // Free surplus reservations
+ $restreservierung = $menge_pro_stueck * $fortschritt['offen']-$menge_abteilen;
+ $result = $this->ArtikelReservieren($position['artikel'],$global_standardlager,0,$restreservierung,'produktion',$id,$position['id'],"Produktion $global_produktionsnummer");
+
+ }
+
+ $this->ProtokollSchreiben($id,"Teilproduktion erstellt: ".$produktion_neu['belegnr']." (Menge $menge_abteilen)");
+ $msg = "
Das Element wurde erfolgreich angelegt.
"; // Overwrite old MSG
+ $msg = $this->app->erp->base64_url_encode($msg);
+ header("Location: index.php?module=produktion&action=edit&id=$produktion_neu_id&msg=$msg");
+
+ break;
+ case 'leeren':
+
+ if ($global_status == 'angelegt' || $global_status == 'freigegeben') {
+ $sql = "SELECT id, artikel, menge, geliefert_menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=0";
+ $material = $this->app->DB->SelectArr($sql);
+ foreach ($material as $material_position) {
+ // Remove reservation
+ $result = $this->ArtikelReservieren($material_position['artikel'],$global_standardlager,0,0,'produktion',$id,$material_position['id'],"Produktion $global_produktionsnummer");
+ }
+ $sql = "DELETE FROM produktion_position WHERE produktion = $id";
+ $this->app->DB->Update($sql);
+ $msg .= "
Planung geleert.
";
+ } else {
+ $msg .= "
Planung kann nicht geleert werden.
";
+ }
+
+ break;
+ case 'anpassen':
+
+ if ($global_status == 'angelegt' || $global_status == 'freigegeben' || $global_status == 'gestartet') {
+
+ $menge_anpassen = $this->app->Secure->GetPOST('menge_produzieren');
+
+ if (empty($menge_anpassen)) {
+ $msg .= "
Ungültige Planmenge.
";
+ break;
+ }
+
+ $fortschritt = $this->MengeFortschritt($id,$global_standardlager);
+
+ $result = $this->MengeAnpassen($id,$menge_anpassen,$global_standardlager);
+
+ if ($result == -1) {
+ $msg .= "
Ungültige Planmenge.
";
+ } else {
+ $msg .= "
Planmenge angepasst.
";
+ }
+ }
+
+ $this->ProtokollSchreiben($id,"Menge angepasst auf ".$this->FormatMenge($menge_anpassen));
+
+ break;
+ case 'abschliessen':
+ $sql = "UPDATE produktion SET status = 'abgeschlossen' WHERE id=$id";
+ $this->app->DB->Update($sql);
+
+ $sql = "SELECT id, artikel, menge, geliefert_menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=0";
+ $material = $this->app->DB->SelectArr($sql);
+
+ foreach ($material as $material_position) {
+ // Remove reservation
+ $result = $this->ArtikelReservieren($material_position['artikel'],$global_standardlager,0,0,'produktion',$id,$material_position['id'],"Produktion $global_produktionsnummer");
+ }
+
+ $this->ProtokollSchreiben($id,'Produktion abgeschlossen');
+
+ break;
+
+ }
}
// Load values again from database
+ // toDo: cleanup
- $sql = "SELECT SQL_CALC_FOUND_ROWS p.id, p.datum, p.art, p.projekt, p.belegnr, p.internet, p.bearbeiter, p.angebot, p.freitext, p.internebemerkung, p.status, p.adresse, p.name, p.abteilung, p.unterabteilung, p.strasse, p.adresszusatz, p.ansprechpartner, p.plz, p.ort, p.land, p.ustid, p.ust_befreit, p.ust_inner, p.email, p.telefon, p.telefax, p.betreff, p.kundennummer, p.versandart, p.vertrieb, p.zahlungsweise, p.zahlungszieltage, p.zahlungszieltageskonto, p.zahlungszielskonto, p.bank_inhaber, p.bank_institut, p.bank_blz, p.bank_konto, p.kreditkarte_typ, p.kreditkarte_inhaber, p.kreditkarte_nummer, p.kreditkarte_pruefnummer, p.kreditkarte_monat, p.kreditkarte_jahr, p.firma, p.versendet, p.versendet_am, p.versendet_per, p.versendet_durch, p.autoversand, p.keinporto, p.keinestornomail, p.abweichendelieferadresse, p.liefername, p.lieferabteilung, p.lieferunterabteilung, p.lieferland, p.lieferstrasse, p.lieferort, p.lieferplz, p.lieferadresszusatz, p.lieferansprechpartner, p.packstation_inhaber, p.packstation_station, p.packstation_ident, p.packstation_plz, p.packstation_ort, p.autofreigabe, p.freigabe, p.nachbesserung, p.gesamtsumme, p.inbearbeitung, p.abgeschlossen, p.nachlieferung, p.lager_ok, p.porto_ok, p.ust_ok, p.check_ok, p.vorkasse_ok, p.nachnahme_ok, p.reserviert_ok, p.bestellt_ok, p.zeit_ok, p.versand_ok, p.partnerid, p.folgebestaetigung, p.zahlungsmail, p.stornogrund, p.stornosonstiges, p.stornorueckzahlung, p.stornobetrag, p.stornobankinhaber, p.stornobankkonto, p.stornobankblz, p.stornobankbank, p.stornogutschrift, p.stornogutschriftbeleg, p.stornowareerhalten, p.stornomanuellebearbeitung, p.stornokommentar, p.stornobezahlt, p.stornobezahltam, p.stornobezahltvon, p.stornoabgeschlossen, p.stornorueckzahlungper, p.stornowareerhaltenretour, p.partnerausgezahlt, p.partnerausgezahltam, p.kennen, p.logdatei, p.bezeichnung, p.datumproduktion, p.anschreiben, p.usereditid, p.useredittimestamp, p.steuersatz_normal, p.steuersatz_zwischen, p.steuersatz_ermaessigt, p.steuersatz_starkermaessigt, p.steuersatz_dienstleistung, p.waehrung, p.schreibschutz, p.pdfarchiviert, p.pdfarchiviertversion, p.typ, p.reservierart, p.auslagerart, p.projektfiliale, p.datumauslieferung, p.datumbereitstellung, p.unterlistenexplodieren, p.charge, p.arbeitsschrittetextanzeigen, p.einlagern_ok, p.auslagern_ok, p.mhd, p.auftragmengenanpassen, p.internebezeichnung, p.mengeoriginal, p.teilproduktionvon, p.teilproduktionnummer, p.parent, p.parentnummer, p.bearbeiterid, p.mengeausschuss, p.mengeerfolgreich, p.abschlussbemerkung, p.auftragid, p.funktionstest, p.seriennummer_erstellen, p.unterseriennummern_erfassen, p.datumproduktionende, p.standardlager, p.id FROM produktion p"." WHERE id=$id";
-
- $result = $this->app->DB->SelectArr($sql);
+ $sql = "SELECT SQL_CALC_FOUND_ROWS
+ p.id,
+ (SELECT pp.bezeichnung FROM produktion_position pp WHERE pp.produktion = p.id AND pp.stuecklistestufe = 1 LIMIT 1) as artikelname,
+ p.datum,
+ p.art,
+ p.projekt,
+ p.belegnr,
+ p.internet,
+ p.bearbeiter,
+ p.angebot,
+ p.freitext,
+ p.internebemerkung,
+ p.status,
+ p.adresse,
+ p.name,
+ p.abteilung,
+ p.unterabteilung,
+ p.strasse,
+ p.adresszusatz,
+ p.ansprechpartner,
+ p.plz,
+ p.ort,
+ p.land,
+ p.ustid,
+ p.ust_befreit,
+ p.ust_inner,
+ p.email,
+ p.telefon,
+ p.telefax,
+ p.betreff,
+ p.kundennummer,
+ p.versandart,
+ p.vertrieb,
+ p.zahlungsweise,
+ p.zahlungszieltage,
+ p.zahlungszieltageskonto,
+ p.zahlungszielskonto,
+ p.bank_inhaber,
+ p.bank_institut,
+ p.bank_blz,
+ p.bank_konto,
+ p.kreditkarte_typ,
+ p.kreditkarte_inhaber,
+ p.kreditkarte_nummer,
+ p.kreditkarte_pruefnummer,
+ p.kreditkarte_monat,
+ p.kreditkarte_jahr,
+ p.firma,
+ p.versendet,
+ p.versendet_am,
+ p.versendet_per,
+ p.versendet_durch,
+ p.autoversand,
+ p.keinporto,
+ p.keinestornomail,
+ p.abweichendelieferadresse,
+ p.liefername,
+ p.lieferabteilung,
+ p.lieferunterabteilung,
+ p.lieferland,
+ p.lieferstrasse,
+ p.lieferort,
+ p.lieferplz,
+ p.lieferadresszusatz,
+ p.lieferansprechpartner,
+ p.packstation_inhaber,
+ p.packstation_station,
+ p.packstation_ident,
+ p.packstation_plz,
+ p.packstation_ort,
+ p.autofreigabe,
+ p.freigabe,
+ p.nachbesserung,
+ p.gesamtsumme,
+ p.inbearbeitung,
+ p.abgeschlossen,
+ p.nachlieferung,
+ p.lager_ok,
+ p.porto_ok,
+ p.ust_ok,
+ p.check_ok,
+ p.vorkasse_ok,
+ p.nachnahme_ok,
+ p.reserviert_ok,
+ p.bestellt_ok,
+ p.zeit_ok,
+ p.versand_ok,
+ p.partnerid,
+ p.folgebestaetigung,
+ p.zahlungsmail,
+ p.stornogrund,
+ p.stornosonstiges,
+ p.stornorueckzahlung,
+ p.stornobetrag,
+ p.stornobankinhaber,
+ p.stornobankkonto,
+ p.stornobankblz,
+ p.stornobankbank,
+ p.stornogutschrift,
+ p.stornogutschriftbeleg,
+ p.stornowareerhalten,
+ p.stornomanuellebearbeitung,
+ p.stornokommentar,
+ p.stornobezahlt,
+ p.stornobezahltam,
+ p.stornobezahltvon,
+ p.stornoabgeschlossen,
+ p.stornorueckzahlungper,
+ p.stornowareerhaltenretour,
+ p.partnerausgezahlt,
+ p.partnerausgezahltam,
+ p.kennen,
+ p.logdatei,
+ p.bezeichnung,
+ p.datumproduktion,
+ p.anschreiben,
+ p.usereditid,
+ p.useredittimestamp,
+ p.steuersatz_normal,
+ p.steuersatz_zwischen,
+ p.steuersatz_ermaessigt,
+ p.steuersatz_starkermaessigt,
+ p.steuersatz_dienstleistung,
+ p.waehrung,
+ p.schreibschutz,
+ p.pdfarchiviert,
+ p.pdfarchiviertversion,
+ p.typ,
+ p.reservierart,
+ p.auslagerart,
+ p.projektfiliale,
+ p.datumauslieferung,
+ p.datumbereitstellung,
+ p.unterlistenexplodieren,
+ p.charge,
+ p.arbeitsschrittetextanzeigen,
+ p.einlagern_ok,
+ p.auslagern_ok,
+ p.mhd,
+ p.auftragmengenanpassen,
+ p.internebezeichnung,
+ p.mengeoriginal,
+ p.teilproduktionvon,
+ p.teilproduktionnummer,
+ p.parent,
+ p.parentnummer,
+ p.bearbeiterid,
+ p.mengeausschuss,
+ p.mengeerfolgreich,
+ p.abschlussbemerkung,
+ p.auftragid,
+ p.funktionstest,
+ p.seriennummer_erstellen,
+ p.unterseriennummern_erfassen,
+ p.datumproduktionende,
+ p.standardlager,
+ p.id FROM produktion p"." WHERE id=$id";
- foreach ($result[0] as $key => $value) {
- $this->app->Tpl->Set(strtoupper($key), $value);
+ $produktion_from_db = $this->app->DB->SelectArr($sql)[0];
+
+ foreach ($produktion_from_db as $key => $value) {
+ $this->app->Tpl->Set(strtoupper($key), $value);
}
/*
* Add displayed items later
- *
+ */
- $this->app->Tpl->Add('KURZUEBERSCHRIFT2', $email);
- $this->app->Tpl->Add('EMAIL', $email);
- $this->app->Tpl->Add('ANGEZEIGTERNAME', $angezeigtername);
- */
+ $this->StatusBerechnen((int)$id);
-// $this->SetInput($input);
+ $sql = "SELECT " . $this->app->YUI->IconsSQL_produktion('p') . " AS `icons` FROM produktion p WHERE id=$id";
+ $icons = $this->app->DB->SelectArr($sql);
+ $this->app->Tpl->Add('STATUSICONS', $icons[0]['icons']);
+
+ if ($produktion_from_db['teilproduktionvon'] != 0) {
+ $sql = "SELECT belegnr FROM produktion WHERE id = ".$produktion_from_db['teilproduktionvon'];
+ $hauptproduktion_belegnr = $this->app->DB->SelectArr($sql)[0]['belegnr'];
+ $this->app->Tpl->Set('TEILPRODUKTIONINFO',"Teilproduktion von ".$hauptproduktion_belegnr);
+ }
+
+ $sql = "SELECT belegnr FROM produktion WHERE teilproduktionvon = $id";
+ $teilproduktionen = $this->app->DB->SelectArr($sql);
+
+ if (!empty($teilproduktionen)) {
+ $this->app->Tpl->Set('TEILPRODUKTIONINFO',"Zu dieser Produktion gehören die Teilproduktionen: ".implode(', ',array_column($teilproduktionen,'belegnr')));
+ }
+
+ if($produktion_from_db['standardlager'] == 0) {
+ $msg .= "
Kein Materiallager ausgewählt.
";
+ }
+
+ $this->app->Tpl->Set('PROJEKT',$this->app->erp->ReplaceProjekt(false,$produktion_from_db['projekt'],false));
+
+ $this->app->YUI->AutoComplete("projekt", "projektname", 1);
+ $this->app->YUI->AutoComplete("kundennummer", "kunde", 1);
+ $this->app->YUI->AutoComplete("auftragid", "auftrag", 1);
+
+ $this->app->YUI->AutoComplete("artikel_planen", "stuecklistenartikel");
+ $this->app->YUI->AutoComplete("artikel_hinzu", "artikelnummer");
+
+ $this->app->YUI->AutoComplete("standardlager", "lagerplatz");
+ $this->app->YUI->AutoComplete("ziellager", "lagerplatz");
+
+ $this->app->YUI->AutoComplete("artikel", "artikelnummer");
+
+ $this->app->Tpl->Set('STANDARDLAGER', $this->app->erp->ReplaceLagerPlatz(false,$produktion_from_db['standardlager'],false)); // Convert ID to form display
+
+ $this->app->YUI->DatePicker("datum");
+ $this->app->Tpl->Set('DATUM',$this->app->erp->ReplaceDatum(false,$produktion_from_db['datum'],true));
+
+ $this->app->YUI->DatePicker("datumauslieferung");
+ $this->app->Tpl->Set('DATUMAUSLIEFERUNG',$this->app->erp->ReplaceDatum(false,$produktion_from_db['datumauslieferung'],false));
+
+ $this->app->YUI->DatePicker("datumbereitstellung");
+ $this->app->Tpl->Set('DATUMBEREITSTELLUNG',$this->app->erp->ReplaceDatum(false,$produktion_from_db['datumbereitstellung'],false));
+
+ $this->app->YUI->DatePicker("datumproduktion");
+ $this->app->Tpl->Set('DATUMPRODUKTION',$this->app->erp->ReplaceDatum(false,$produktion_from_db['datumproduktion'],false));
+
+ $this->app->YUI->DatePicker("datumproduktionende");
+ $this->app->Tpl->Set('DATUMPRODUKTIONENDE',$this->app->erp->ReplaceDatum(false,$produktion_from_db['datumproduktionende'],false));
+
+ $this->app->YUI->CkEditor("freitext","internal", null, 'JQUERY');
+ $this->app->YUI->CkEditor("internebemerkung","internal", null, 'JQUERY');
+
+ /*
+ UI Elements
+
+ AKTION_SPEICHERN_DISABLED
+ AKTION_PLANEN_VISIBLE
+ AKTION_FREIGEBEN_VISIBLE
+ AKTION_RESERVIEREN_VISIBLE
+ AKTION_PRODUZIEREN_VISIBLE
+ AKTION_ABSCHLIESSEN_VISIBLE
+ POSITIONEN_TAB_VISIBLE
+ */
+
+ // Reparse positions
+ $sql = "SELECT id,artikel, menge, geliefert_menge FROM produktion_position pp WHERE produktion=$id AND stuecklistestufe=1";
+ $produktionsartikel_position = $this->app->DB->SelectArr($sql)[0];
+
+ // Not planned
+ if (empty($produktionsartikel_position)) {
+
+ $this->app->Tpl->Set('AKTION_FREIGEBEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('ARTIKEL_MENGE_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_PRODUZIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_LEEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_RESERVIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_TEILEN_VISIBLE','hidden');
+ } else {
+ // Planned
+
+ $fortschritt = $this->MengeFortschritt((int) $id, 0);
+
+ if (!empty($fortschritt)) {
+ $this->app->Tpl->Set('MENGE_GEPLANT',$this->FormatMenge($fortschritt['geplant']));
+ $this->app->Tpl->Set('MENGE_PRODUZIERT',$this->FormatMenge($fortschritt['produziert']));
+ $this->app->Tpl->Set('MENGE_OFFEN',$this->FormatMenge($fortschritt['offen']));
+ $this->app->Tpl->Set('MENGE_RESERVIERT',$this->FormatMenge($fortschritt['reserviert']));
+ $this->app->Tpl->Set('MENGE_PRODUZIERBAR',$this->FormatMenge($fortschritt['produzierbar']));
+ $this->app->Tpl->Set('MENGE_ERFOLGREICH',$this->FormatMenge($fortschritt['erfolgreich']));
+ $this->app->Tpl->Set('MENGE_AUSSCHUSS',$this->FormatMenge($fortschritt['ausschuss']));
+ }
+
+ if ($fortschritt['produziert'] > $fortschritt['geplant']) {
+ $msg .= "
Planmenge überschritten.
";
+ }
+
+ $this->app->Tpl->Set('AKTION_PLANEN_VISIBLE','hidden');
+ $this->app->YUI->TableSearch('PRODUKTION_POSITION_SOURCE_POSITION_TABELLE', 'produktion_position_source_list', "show", "", "", basename(__FILE__), __CLASS__);
+ $this->app->YUI->TableSearch('PRODUKTION_POSITION_SOURCE_TABELLE', 'produktion_source_list', "show", "", "", basename(__FILE__), __CLASS__);
+ $produktionsartikel_id = $produktionsartikel_position['artikel'];
+
+ $sql = "SELECT name_de,nummer FROM artikel WHERE id=".$produktionsartikel_id;
+ $produktionsartikel = $this->app->DB->SelectArr($sql)[0];
+ $produktionsartikel_name = $produktionsartikel['name_de'];
+ $produktionsartikel_nummer = $produktionsartikel['nummer'];
+ }
+
+ if (empty($produktion_from_db['belegnr'])) {
+ $this->app->Tpl->SetText('KURZUEBERSCHRIFT2', 'ENTWURF - '.$produktionsartikel_name." (".$produktionsartikel_nummer.")");
+ } else {
+ $this->app->Tpl->SetText('KURZUEBERSCHRIFT2', $produktion_from_db['belegnr']." ".$produktionsartikel_name." (".$produktionsartikel_nummer.")");
+ }
+
+ $this->app->Tpl->SetText('ARTIKELNAME', $produktionsartikel_name);
+
+ // Action menu
+ switch ($produktion_from_db['status']) {
+ case 'angelegt':
+ $this->app->Tpl->Set('AKTION_RESERVIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_PRODUZIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_ABSCHLIESSEN_VISIBLE','hidden');
+ break;
+ case 'freigegeben':
+ $this->app->Tpl->Set('AKTION_FREIGEBEN_VISIBLE','hidden');
+ break;
+ case 'gestartet':
+ $this->app->Tpl->Set('AKTION_FREIGEBEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_PLANEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_LEEREN_VISIBLE','hidden');
+ break;
+ case 'abgeschlossen':
+ case 'storniert':
+ $this->app->Tpl->Set('AKTION_SPEICHERN_DISABLED','disabled');
+ $this->app->Tpl->Set('AKTION_PLANEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_FREIGEBEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_RESERVIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_PRODUZIEREN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_TEILEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_ABSCHLIESSEN_VISIBLE','hidden');
+ $this->app->Tpl->Set('AKTION_LEEREN_VISIBLE','hidden');
+ break;
+ default: // new item
+ $this->app->Tpl->Set('POSITIONEN_TAB_VISIBLE','hidden="hidden"');
+ break;
+ }
+
+ $this->app->Tpl->Set('PRODUKTION_ID',$id);
+
+ $this->app->Tpl->Set('MESSAGE', $msg);
+ $this->produktion_minidetail('MINIDETAILINEDIT');
$this->app->Tpl->Parse('PAGE', "produktion_edit.tpl");
+
}
+ /*
+ Create a copy as draft
+ */
+
+ function produktion_copy() {
+ $id = (int) $this->app->Secure->GetGET('id');
+ if (empty($id)) {
+ return;
+ }
+ $result = $this->Copy($id,0);
+ if ($result <= 0) {
+ $msg .= "
Fehler beim Anlegen der Kopie.
";
+ $this->app->Tpl->Set('MESSAGE', $msg);
+ $this->produktion_list();
+ }
+ else {
+ $msg .= "
Kopie angelegt. $result new $id old
";
+ $this->app->Tpl->Set('MESSAGE', $msg);
+ $this->produktion_edit((int) $result);
+ }
+ }
+
+ public function produktion_minidetail($parsetarget='',$menu=true) {
+
+ $id = $this->app->Secure->GetGET('id');
+
+ $fortschritt = $this->MengeFortschritt((int) $id, 0);
+
+ if (!empty($fortschritt)) {
+ $this->app->Tpl->Set('MINI_MENGE_GEPLANT',$this->FormatMenge($fortschritt['geplant']));
+ $this->app->Tpl->Set('MINI_MENGE_PRODUZIERT',$this->FormatMenge($fortschritt['produziert']));
+ $this->app->Tpl->Set('MINI_MENGE_OFFEN',$this->FormatMenge($fortschritt['offen']));
+ $this->app->Tpl->Set('MINI_MENGE_RESERVIERT',$this->FormatMenge($fortschritt['reserviert']));
+ $this->app->Tpl->Set('MINI_MENGE_PRODUZIERBAR',$this->FormatMenge($fortschritt['produzierbar']));
+ $this->app->Tpl->Set('MINI_MENGEERFOLGREICH',$this->FormatMenge($fortschritt['erfolgreich']));
+ $this->app->Tpl->Set('MINI_MENGEAUSSCHUSS',$this->FormatMenge($fortschritt['ausschuss']));
+ }
+
+ $this->ProtokollTabelleErzeugen($id, 'PROTOKOLL');
+
+ if($parsetarget=='')
+ {
+ $this->app->Tpl->Output('produktion_minidetail.tpl');
+ $this->app->ExitXentral();
+ }
+
+ $this->app->Tpl->Parse($parsetarget,'produktion_minidetail.tpl');
+ }
+
+
/**
* Get all paramters from html form and save into $input
*/
public function GetInput(): array {
$input = array();
- //$input['EMAIL'] = $this->app->Secure->GetPOST('email');
-
+
+ $input['kundennummer'] = $this->app->Secure->GetPOST('kundennummer');
+ $input['projekt'] = $this->app->Secure->GetPOST('projekt');
+ $input['auftragid'] = $this->app->Secure->GetPOST('auftragid');
+ $input['internebezeichnung'] = $this->app->Secure->GetPOST('internebezeichnung');
+
$input['datum'] = $this->app->Secure->GetPOST('datum');
- $input['art'] = $this->app->Secure->GetPOST('art');
- $input['projekt'] = $this->app->Secure->GetPOST('projekt');
- $input['belegnr'] = $this->app->Secure->GetPOST('belegnr');
- $input['internet'] = $this->app->Secure->GetPOST('internet');
- $input['bearbeiter'] = $this->app->Secure->GetPOST('bearbeiter');
- $input['angebot'] = $this->app->Secure->GetPOST('angebot');
- $input['freitext'] = $this->app->Secure->GetPOST('freitext');
- $input['internebemerkung'] = $this->app->Secure->GetPOST('internebemerkung');
- $input['status'] = $this->app->Secure->GetPOST('status');
- $input['adresse'] = $this->app->Secure->GetPOST('adresse');
- $input['name'] = $this->app->Secure->GetPOST('name');
- $input['abteilung'] = $this->app->Secure->GetPOST('abteilung');
- $input['unterabteilung'] = $this->app->Secure->GetPOST('unterabteilung');
- $input['strasse'] = $this->app->Secure->GetPOST('strasse');
- $input['adresszusatz'] = $this->app->Secure->GetPOST('adresszusatz');
- $input['ansprechpartner'] = $this->app->Secure->GetPOST('ansprechpartner');
- $input['plz'] = $this->app->Secure->GetPOST('plz');
- $input['ort'] = $this->app->Secure->GetPOST('ort');
- $input['land'] = $this->app->Secure->GetPOST('land');
- $input['ustid'] = $this->app->Secure->GetPOST('ustid');
- $input['ust_befreit'] = $this->app->Secure->GetPOST('ust_befreit');
- $input['ust_inner'] = $this->app->Secure->GetPOST('ust_inner');
- $input['email'] = $this->app->Secure->GetPOST('email');
- $input['telefon'] = $this->app->Secure->GetPOST('telefon');
- $input['telefax'] = $this->app->Secure->GetPOST('telefax');
- $input['betreff'] = $this->app->Secure->GetPOST('betreff');
- $input['kundennummer'] = $this->app->Secure->GetPOST('kundennummer');
- $input['versandart'] = $this->app->Secure->GetPOST('versandart');
- $input['vertrieb'] = $this->app->Secure->GetPOST('vertrieb');
- $input['zahlungsweise'] = $this->app->Secure->GetPOST('zahlungsweise');
- $input['zahlungszieltage'] = $this->app->Secure->GetPOST('zahlungszieltage');
- $input['zahlungszieltageskonto'] = $this->app->Secure->GetPOST('zahlungszieltageskonto');
- $input['zahlungszielskonto'] = $this->app->Secure->GetPOST('zahlungszielskonto');
- $input['bank_inhaber'] = $this->app->Secure->GetPOST('bank_inhaber');
- $input['bank_institut'] = $this->app->Secure->GetPOST('bank_institut');
- $input['bank_blz'] = $this->app->Secure->GetPOST('bank_blz');
- $input['bank_konto'] = $this->app->Secure->GetPOST('bank_konto');
- $input['kreditkarte_typ'] = $this->app->Secure->GetPOST('kreditkarte_typ');
- $input['kreditkarte_inhaber'] = $this->app->Secure->GetPOST('kreditkarte_inhaber');
- $input['kreditkarte_nummer'] = $this->app->Secure->GetPOST('kreditkarte_nummer');
- $input['kreditkarte_pruefnummer'] = $this->app->Secure->GetPOST('kreditkarte_pruefnummer');
- $input['kreditkarte_monat'] = $this->app->Secure->GetPOST('kreditkarte_monat');
- $input['kreditkarte_jahr'] = $this->app->Secure->GetPOST('kreditkarte_jahr');
- $input['firma'] = $this->app->Secure->GetPOST('firma');
- $input['versendet'] = $this->app->Secure->GetPOST('versendet');
- $input['versendet_am'] = $this->app->Secure->GetPOST('versendet_am');
- $input['versendet_per'] = $this->app->Secure->GetPOST('versendet_per');
- $input['versendet_durch'] = $this->app->Secure->GetPOST('versendet_durch');
- $input['autoversand'] = $this->app->Secure->GetPOST('autoversand');
- $input['keinporto'] = $this->app->Secure->GetPOST('keinporto');
- $input['keinestornomail'] = $this->app->Secure->GetPOST('keinestornomail');
- $input['abweichendelieferadresse'] = $this->app->Secure->GetPOST('abweichendelieferadresse');
- $input['liefername'] = $this->app->Secure->GetPOST('liefername');
- $input['lieferabteilung'] = $this->app->Secure->GetPOST('lieferabteilung');
- $input['lieferunterabteilung'] = $this->app->Secure->GetPOST('lieferunterabteilung');
- $input['lieferland'] = $this->app->Secure->GetPOST('lieferland');
- $input['lieferstrasse'] = $this->app->Secure->GetPOST('lieferstrasse');
- $input['lieferort'] = $this->app->Secure->GetPOST('lieferort');
- $input['lieferplz'] = $this->app->Secure->GetPOST('lieferplz');
- $input['lieferadresszusatz'] = $this->app->Secure->GetPOST('lieferadresszusatz');
- $input['lieferansprechpartner'] = $this->app->Secure->GetPOST('lieferansprechpartner');
- $input['packstation_inhaber'] = $this->app->Secure->GetPOST('packstation_inhaber');
- $input['packstation_station'] = $this->app->Secure->GetPOST('packstation_station');
- $input['packstation_ident'] = $this->app->Secure->GetPOST('packstation_ident');
- $input['packstation_plz'] = $this->app->Secure->GetPOST('packstation_plz');
- $input['packstation_ort'] = $this->app->Secure->GetPOST('packstation_ort');
- $input['autofreigabe'] = $this->app->Secure->GetPOST('autofreigabe');
- $input['freigabe'] = $this->app->Secure->GetPOST('freigabe');
- $input['nachbesserung'] = $this->app->Secure->GetPOST('nachbesserung');
- $input['gesamtsumme'] = $this->app->Secure->GetPOST('gesamtsumme');
- $input['inbearbeitung'] = $this->app->Secure->GetPOST('inbearbeitung');
- $input['abgeschlossen'] = $this->app->Secure->GetPOST('abgeschlossen');
- $input['nachlieferung'] = $this->app->Secure->GetPOST('nachlieferung');
- $input['lager_ok'] = $this->app->Secure->GetPOST('lager_ok');
- $input['porto_ok'] = $this->app->Secure->GetPOST('porto_ok');
- $input['ust_ok'] = $this->app->Secure->GetPOST('ust_ok');
- $input['check_ok'] = $this->app->Secure->GetPOST('check_ok');
- $input['vorkasse_ok'] = $this->app->Secure->GetPOST('vorkasse_ok');
- $input['nachnahme_ok'] = $this->app->Secure->GetPOST('nachnahme_ok');
- $input['reserviert_ok'] = $this->app->Secure->GetPOST('reserviert_ok');
- $input['bestellt_ok'] = $this->app->Secure->GetPOST('bestellt_ok');
- $input['zeit_ok'] = $this->app->Secure->GetPOST('zeit_ok');
- $input['versand_ok'] = $this->app->Secure->GetPOST('versand_ok');
- $input['partnerid'] = $this->app->Secure->GetPOST('partnerid');
- $input['folgebestaetigung'] = $this->app->Secure->GetPOST('folgebestaetigung');
- $input['zahlungsmail'] = $this->app->Secure->GetPOST('zahlungsmail');
- $input['stornogrund'] = $this->app->Secure->GetPOST('stornogrund');
- $input['stornosonstiges'] = $this->app->Secure->GetPOST('stornosonstiges');
- $input['stornorueckzahlung'] = $this->app->Secure->GetPOST('stornorueckzahlung');
- $input['stornobetrag'] = $this->app->Secure->GetPOST('stornobetrag');
- $input['stornobankinhaber'] = $this->app->Secure->GetPOST('stornobankinhaber');
- $input['stornobankkonto'] = $this->app->Secure->GetPOST('stornobankkonto');
- $input['stornobankblz'] = $this->app->Secure->GetPOST('stornobankblz');
- $input['stornobankbank'] = $this->app->Secure->GetPOST('stornobankbank');
- $input['stornogutschrift'] = $this->app->Secure->GetPOST('stornogutschrift');
- $input['stornogutschriftbeleg'] = $this->app->Secure->GetPOST('stornogutschriftbeleg');
- $input['stornowareerhalten'] = $this->app->Secure->GetPOST('stornowareerhalten');
- $input['stornomanuellebearbeitung'] = $this->app->Secure->GetPOST('stornomanuellebearbeitung');
- $input['stornokommentar'] = $this->app->Secure->GetPOST('stornokommentar');
- $input['stornobezahlt'] = $this->app->Secure->GetPOST('stornobezahlt');
- $input['stornobezahltam'] = $this->app->Secure->GetPOST('stornobezahltam');
- $input['stornobezahltvon'] = $this->app->Secure->GetPOST('stornobezahltvon');
- $input['stornoabgeschlossen'] = $this->app->Secure->GetPOST('stornoabgeschlossen');
- $input['stornorueckzahlungper'] = $this->app->Secure->GetPOST('stornorueckzahlungper');
- $input['stornowareerhaltenretour'] = $this->app->Secure->GetPOST('stornowareerhaltenretour');
- $input['partnerausgezahlt'] = $this->app->Secure->GetPOST('partnerausgezahlt');
- $input['partnerausgezahltam'] = $this->app->Secure->GetPOST('partnerausgezahltam');
- $input['kennen'] = $this->app->Secure->GetPOST('kennen');
- $input['logdatei'] = $this->app->Secure->GetPOST('logdatei');
- $input['bezeichnung'] = $this->app->Secure->GetPOST('bezeichnung');
- $input['datumproduktion'] = $this->app->Secure->GetPOST('datumproduktion');
- $input['anschreiben'] = $this->app->Secure->GetPOST('anschreiben');
- $input['usereditid'] = $this->app->Secure->GetPOST('usereditid');
- $input['useredittimestamp'] = $this->app->Secure->GetPOST('useredittimestamp');
- $input['steuersatz_normal'] = $this->app->Secure->GetPOST('steuersatz_normal');
- $input['steuersatz_zwischen'] = $this->app->Secure->GetPOST('steuersatz_zwischen');
- $input['steuersatz_ermaessigt'] = $this->app->Secure->GetPOST('steuersatz_ermaessigt');
- $input['steuersatz_starkermaessigt'] = $this->app->Secure->GetPOST('steuersatz_starkermaessigt');
- $input['steuersatz_dienstleistung'] = $this->app->Secure->GetPOST('steuersatz_dienstleistung');
- $input['waehrung'] = $this->app->Secure->GetPOST('waehrung');
- $input['schreibschutz'] = $this->app->Secure->GetPOST('schreibschutz');
- $input['pdfarchiviert'] = $this->app->Secure->GetPOST('pdfarchiviert');
- $input['pdfarchiviertversion'] = $this->app->Secure->GetPOST('pdfarchiviertversion');
- $input['typ'] = $this->app->Secure->GetPOST('typ');
- $input['reservierart'] = $this->app->Secure->GetPOST('reservierart');
- $input['auslagerart'] = $this->app->Secure->GetPOST('auslagerart');
- $input['projektfiliale'] = $this->app->Secure->GetPOST('projektfiliale');
- $input['datumauslieferung'] = $this->app->Secure->GetPOST('datumauslieferung');
- $input['datumbereitstellung'] = $this->app->Secure->GetPOST('datumbereitstellung');
- $input['unterlistenexplodieren'] = $this->app->Secure->GetPOST('unterlistenexplodieren');
- $input['charge'] = $this->app->Secure->GetPOST('charge');
- $input['arbeitsschrittetextanzeigen'] = $this->app->Secure->GetPOST('arbeitsschrittetextanzeigen');
- $input['einlagern_ok'] = $this->app->Secure->GetPOST('einlagern_ok');
- $input['auslagern_ok'] = $this->app->Secure->GetPOST('auslagern_ok');
- $input['mhd'] = $this->app->Secure->GetPOST('mhd');
- $input['auftragmengenanpassen'] = $this->app->Secure->GetPOST('auftragmengenanpassen');
- $input['internebezeichnung'] = $this->app->Secure->GetPOST('internebezeichnung');
- $input['mengeoriginal'] = $this->app->Secure->GetPOST('mengeoriginal');
- $input['teilproduktionvon'] = $this->app->Secure->GetPOST('teilproduktionvon');
- $input['teilproduktionnummer'] = $this->app->Secure->GetPOST('teilproduktionnummer');
- $input['parent'] = $this->app->Secure->GetPOST('parent');
- $input['parentnummer'] = $this->app->Secure->GetPOST('parentnummer');
- $input['bearbeiterid'] = $this->app->Secure->GetPOST('bearbeiterid');
- $input['mengeausschuss'] = $this->app->Secure->GetPOST('mengeausschuss');
- $input['mengeerfolgreich'] = $this->app->Secure->GetPOST('mengeerfolgreich');
- $input['abschlussbemerkung'] = $this->app->Secure->GetPOST('abschlussbemerkung');
- $input['auftragid'] = $this->app->Secure->GetPOST('auftragid');
- $input['funktionstest'] = $this->app->Secure->GetPOST('funktionstest');
- $input['seriennummer_erstellen'] = $this->app->Secure->GetPOST('seriennummer_erstellen');
- $input['unterseriennummern_erfassen'] = $this->app->Secure->GetPOST('unterseriennummern_erfassen');
- $input['datumproduktionende'] = $this->app->Secure->GetPOST('datumproduktionende');
- $input['standardlager'] = $this->app->Secure->GetPOST('standardlager');
-
+ $input['standardlager'] = $this->app->Secure->GetPOST('standardlager');
+ $input['standardlager'] = $this->app->erp->ReplaceLagerPlatz(true,$input['standardlager'],true); // Parameters: Target db?, value, from form?
+
+ $input['reservierart'] = $this->app->Secure->GetPOST('reservierart');
+ $input['auslagerart'] = $this->app->Secure->GetPOST('auslagerart');
+ $input['unterlistenexplodieren'] = $this->app->Secure->GetPOST('unterlistenexplodieren');
+ $input['funktionstest'] = $this->app->Secure->GetPOST('funktionstest');
+ $input['arbeitsschrittetextanzeigen'] = $this->app->Secure->GetPOST('arbeitsschrittetextanzeigen');
+ $input['seriennummer_erstellen'] = $this->app->Secure->GetPOST('seriennummer_erstellen');
+
+ $input['datumauslieferung'] = $this->app->Secure->GetPOST('datumauslieferung');
+ $input['datumbereitstellung'] = $this->app->Secure->GetPOST('datumbereitstellung');
+ $input['datumproduktion'] = $this->app->Secure->GetPOST('datumproduktion');
+ $input['datumproduktionende'] = $this->app->Secure->GetPOST('datumproduktionende');
+
+ $input['freitext'] = $this->app->Secure->GetPOST('freitext');
+ $input['internebemerkung'] = $this->app->Secure->GetPOST('internebemerkung');
return $input;
}
+ // Check stock situation and reservation
+ // Return possible production quantity for all stock or just the reserved
+ function LagerCheckProduktion(int $produktion_id, int $lager, bool $only_reservations) : int {
+
+ $menge_moeglich = PHP_INT_MAX;
+
+ $sql = "SELECT pp.id, artikel, SUM(menge) as menge, geliefert_menge FROM produktion_position pp INNER JOIN artikel a ON pp.artikel = a.id WHERE pp.produktion=$produktion_id AND pp.stuecklistestufe=0 AND a.lagerartikel != 0 GROUP BY artikel";
+ $materialbedarf_gesamt = $this->app->DB->SelectArr($sql);
+
+ $sql = "SELECT id, artikel, SUM(menge) as menge, geliefert_menge as geliefert_menge FROM produktion_position pp WHERE produktion=$produktion_id AND stuecklistestufe=1 GROUP BY artikel";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $menge_plan_gesamt = $result['menge'];
+
+ if ($menge_plan_gesamt == 0) {
+ return(0);
+ }
+
+ $sql = "SELECT SUM(mengeerfolgreich) as menge FROM produktion WHERE id=$produktion_id";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $menge_geliefert_gesamt = $result['menge'];
+
+ foreach ($materialbedarf_gesamt as $materialbedarf_artikel) {
+
+ $artikel = $materialbedarf_artikel['artikel'];
+ $position = $materialbedarf_artikel['id'];
+ $menge_plan_artikel = $materialbedarf_artikel['menge'];
+ $menge_geliefert = $materialbedarf_artikel['menge_geliefert'];
+
+ $sql = "SELECT SUM(menge) as menge FROM lager_reserviert r WHERE lager_platz=$lager AND artikel = $artikel AND r.objekt = 'produktion' AND r.parameter = $produktion_id";
+ $menge_reserviert_diese = $this->app->DB->SelectArr($sql)[0]['menge'];
+
+ if ($only_reservations) {
+ $menge_verfuegbar = $menge_reserviert_diese;
+ } else {
+ $sql = "SELECT SUM(menge) as menge FROM lager_platz_inhalt WHERE lager_platz=$lager AND artikel = $artikel";
+ $menge_lager = $this->app->DB->SelectArr($sql)[0]['menge'];
+
+ $sql = "SELECT SUM(menge) as menge FROM lager_reserviert r WHERE lager_platz=$lager AND artikel = $artikel";
+ $menge_reserviert_lager = $this->app->DB->SelectArr($sql)[0]['menge'];
+
+ $sql = "SELECT SUM(menge) as menge FROM lager_reserviert r WHERE artikel = $artikel";
+ $menge_reserviert_gesamt = $this->app->DB->SelectArr($sql)[0]['menge'];
+
+ $menge_verfuegbar = $menge_lager-$menge_reserviert_lager+$menge_reserviert_diese;
+ }
+
+ $menge_moeglich_artikel = round($menge_verfuegbar / ($menge_plan_artikel/$menge_plan_gesamt), 0, PHP_ROUND_HALF_DOWN);
+
+ if ($menge_moeglich_artikel < $menge_moeglich) {
+ $menge_moeglich = $menge_moeglich_artikel;
+ }
+
+// echo("------------------------Lager $lager a $artikel menge_plan_artikel $menge_plan_artikel menge_geliefert $menge_geliefert menge_lager $menge_lager menge_reserviert_diese $menge_reserviert_diese menge_reserviert_gesamt $menge_reserviert_gesamt menge_verfuegbar $menge_verfuegbar menge_moeglich_artikel $menge_moeglich_artikel menge_moeglich $menge_moeglich
");
+
+ }
+
+ if ($menge_moeglich < 0) {
+ $menge_moeglich = 0;
+ }
+
+
+ return($menge_moeglich);
+ }
+
+ // Modify or add reservation
+ // If quantity is negative, the existing reservation will be reduced
+ // If current quantity is higher as menge_reservieren_limit, current quantity will be reduced
+ // Returns amount that is reserved
+ function ArtikelReservieren(int $artikel, $lager, int $menge_reservieren, int $menge_reservieren_limit, string $objekt, int $objekt_id, int $position_id, string $text) : int {
+
+ if($lager <= 0 || $artikel <= 0 || $position_id <= 0) {
+ return 0;
+ }
+
+ $sql = "SELECT menge FROM lager_reserviert WHERE objekt='$objekt' AND parameter = $objekt_id AND artikel = $artikel AND lager_platz = $lager AND posid = $position_id";
+ $menge_reserviert_diese = $this->app->DB->SelectArr($sql)[0]['menge'];
+ if ($menge_reserviert_diese == null) {
+ $menge_reserviert_diese = 0;
+ }
+
+ $sql = "SELECT menge FROM lager_reserviert WHERE artikel = $artikel AND lager_platz = $lager";
+ $menge_reserviert_lager_platz = $this->app->DB->SelectArr($sql)[0]['menge'];
+ if ($menge_reserviert_lager_platz == null) {
+ $menge_reserviert_lager_platz = 0;
+ }
+
+ $sql = "SELECT menge FROM lager_platz_inhalt WHERE artikel = $artikel AND lager_platz = $lager";
+ $menge_lager = $this->app->DB->SelectArr($sql)[0]['menge'];
+ if ($menge_lager == null) {
+ $menge_lager = 0;
+ }
+
+ if ($menge_reservieren < 0) { // Relative reduction
+ $menge_reservieren = $menge_reserviert_diese+$menge_reservieren;
+
+ if ($menge_reservieren < 0) {
+ $menge_reservieren = 0;
+ }
+ }
+
+ if (($menge_reservieren == 0) && ($menge_reservieren_limit <= 0)) {
+ $sql = "DELETE FROM lager_reserviert WHERE objekt = '$objekt' AND parameter = $objekt_id AND artikel = $artikel AND posid = $position_id";
+ $this->app->DB->Update($sql);
+ return(0);
+ }
+
+ $menge_lager_reservierbar = $menge_lager - $menge_reserviert_lager_platz + $menge_reserviert_diese;
+
+ if ($menge_reservieren_limit > 0) {
+ if ($menge_reserviert_diese > $menge_reservieren_limit) {
+ $menge_reservieren = $menge_reservieren_limit;
+ } else {
+ // Nothing to do
+ return($menge_reserviert_diese);
+ }
+ }
+
+ if ($menge_lager_reservierbar > 0) {
+ if ($menge_reserviert_diese > 0) {
+ // Modify given entry
+ if ($menge_reservieren > $menge_lager_reservierbar) {
+ $menge_reservieren = $menge_lager_reservierbar; // Take all that is there
+ }
+ $sql = "UPDATE lager_reserviert SET menge = $menge_reservieren WHERE objekt = '$objekt' AND parameter = $objekt_id AND artikel = $artikel AND posid = $position_id";
+ $this->app->DB->Update($sql);
+ } else {
+ // Create new entry
+ if ($menge_reservieren > $menge_lager_reservierbar) {
+ $menge_reservieren = $menge_lager_reservierbar; // Take all that is there
+ }
+ $sql = "INSERT INTO lager_reserviert (menge,objekt,parameter,artikel,posid,lager_platz,grund) VALUES (".
+ $menge_reservieren.",".
+ "'$objekt',".
+ $objekt_id.",".
+ $artikel.",".
+ $position_id.",".
+ $lager.",".
+ "'$text'".
+ ")";
+ $this->app->DB->Update($sql);
+ }
+ } else {
+ $menge_reservieren = 0;
+ }
+
+ return ($menge_reservieren);
+
+ }
+
+
/*
- * Set all fields in the page corresponding to $input
- */
- function SetInput($input) {
- // $this->app->Tpl->Set('EMAIL', $input['email']);
-
- $this->app->Tpl->Set('DATUM', $input['datum']);
- $this->app->Tpl->Set('ART', $input['art']);
- $this->app->Tpl->Set('PROJEKT', $input['projekt']);
- $this->app->Tpl->Set('BELEGNR', $input['belegnr']);
- $this->app->Tpl->Set('INTERNET', $input['internet']);
- $this->app->Tpl->Set('BEARBEITER', $input['bearbeiter']);
- $this->app->Tpl->Set('ANGEBOT', $input['angebot']);
- $this->app->Tpl->Set('FREITEXT', $input['freitext']);
- $this->app->Tpl->Set('INTERNEBEMERKUNG', $input['internebemerkung']);
- $this->app->Tpl->Set('STATUS', $input['status']);
- $this->app->Tpl->Set('ADRESSE', $input['adresse']);
- $this->app->Tpl->Set('NAME', $input['name']);
- $this->app->Tpl->Set('ABTEILUNG', $input['abteilung']);
- $this->app->Tpl->Set('UNTERABTEILUNG', $input['unterabteilung']);
- $this->app->Tpl->Set('STRASSE', $input['strasse']);
- $this->app->Tpl->Set('ADRESSZUSATZ', $input['adresszusatz']);
- $this->app->Tpl->Set('ANSPRECHPARTNER', $input['ansprechpartner']);
- $this->app->Tpl->Set('PLZ', $input['plz']);
- $this->app->Tpl->Set('ORT', $input['ort']);
- $this->app->Tpl->Set('LAND', $input['land']);
- $this->app->Tpl->Set('USTID', $input['ustid']);
- $this->app->Tpl->Set('UST_BEFREIT', $input['ust_befreit']);
- $this->app->Tpl->Set('UST_INNER', $input['ust_inner']);
- $this->app->Tpl->Set('EMAIL', $input['email']);
- $this->app->Tpl->Set('TELEFON', $input['telefon']);
- $this->app->Tpl->Set('TELEFAX', $input['telefax']);
- $this->app->Tpl->Set('BETREFF', $input['betreff']);
- $this->app->Tpl->Set('KUNDENNUMMER', $input['kundennummer']);
- $this->app->Tpl->Set('VERSANDART', $input['versandart']);
- $this->app->Tpl->Set('VERTRIEB', $input['vertrieb']);
- $this->app->Tpl->Set('ZAHLUNGSWEISE', $input['zahlungsweise']);
- $this->app->Tpl->Set('ZAHLUNGSZIELTAGE', $input['zahlungszieltage']);
- $this->app->Tpl->Set('ZAHLUNGSZIELTAGESKONTO', $input['zahlungszieltageskonto']);
- $this->app->Tpl->Set('ZAHLUNGSZIELSKONTO', $input['zahlungszielskonto']);
- $this->app->Tpl->Set('BANK_INHABER', $input['bank_inhaber']);
- $this->app->Tpl->Set('BANK_INSTITUT', $input['bank_institut']);
- $this->app->Tpl->Set('BANK_BLZ', $input['bank_blz']);
- $this->app->Tpl->Set('BANK_KONTO', $input['bank_konto']);
- $this->app->Tpl->Set('KREDITKARTE_TYP', $input['kreditkarte_typ']);
- $this->app->Tpl->Set('KREDITKARTE_INHABER', $input['kreditkarte_inhaber']);
- $this->app->Tpl->Set('KREDITKARTE_NUMMER', $input['kreditkarte_nummer']);
- $this->app->Tpl->Set('KREDITKARTE_PRUEFNUMMER', $input['kreditkarte_pruefnummer']);
- $this->app->Tpl->Set('KREDITKARTE_MONAT', $input['kreditkarte_monat']);
- $this->app->Tpl->Set('KREDITKARTE_JAHR', $input['kreditkarte_jahr']);
- $this->app->Tpl->Set('FIRMA', $input['firma']);
- $this->app->Tpl->Set('VERSENDET', $input['versendet']);
- $this->app->Tpl->Set('VERSENDET_AM', $input['versendet_am']);
- $this->app->Tpl->Set('VERSENDET_PER', $input['versendet_per']);
- $this->app->Tpl->Set('VERSENDET_DURCH', $input['versendet_durch']);
- $this->app->Tpl->Set('AUTOVERSAND', $input['autoversand']);
- $this->app->Tpl->Set('KEINPORTO', $input['keinporto']);
- $this->app->Tpl->Set('KEINESTORNOMAIL', $input['keinestornomail']);
- $this->app->Tpl->Set('ABWEICHENDELIEFERADRESSE', $input['abweichendelieferadresse']);
- $this->app->Tpl->Set('LIEFERNAME', $input['liefername']);
- $this->app->Tpl->Set('LIEFERABTEILUNG', $input['lieferabteilung']);
- $this->app->Tpl->Set('LIEFERUNTERABTEILUNG', $input['lieferunterabteilung']);
- $this->app->Tpl->Set('LIEFERLAND', $input['lieferland']);
- $this->app->Tpl->Set('LIEFERSTRASSE', $input['lieferstrasse']);
- $this->app->Tpl->Set('LIEFERORT', $input['lieferort']);
- $this->app->Tpl->Set('LIEFERPLZ', $input['lieferplz']);
- $this->app->Tpl->Set('LIEFERADRESSZUSATZ', $input['lieferadresszusatz']);
- $this->app->Tpl->Set('LIEFERANSPRECHPARTNER', $input['lieferansprechpartner']);
- $this->app->Tpl->Set('PACKSTATION_INHABER', $input['packstation_inhaber']);
- $this->app->Tpl->Set('PACKSTATION_STATION', $input['packstation_station']);
- $this->app->Tpl->Set('PACKSTATION_IDENT', $input['packstation_ident']);
- $this->app->Tpl->Set('PACKSTATION_PLZ', $input['packstation_plz']);
- $this->app->Tpl->Set('PACKSTATION_ORT', $input['packstation_ort']);
- $this->app->Tpl->Set('AUTOFREIGABE', $input['autofreigabe']);
- $this->app->Tpl->Set('FREIGABE', $input['freigabe']);
- $this->app->Tpl->Set('NACHBESSERUNG', $input['nachbesserung']);
- $this->app->Tpl->Set('GESAMTSUMME', $input['gesamtsumme']);
- $this->app->Tpl->Set('INBEARBEITUNG', $input['inbearbeitung']);
- $this->app->Tpl->Set('ABGESCHLOSSEN', $input['abgeschlossen']);
- $this->app->Tpl->Set('NACHLIEFERUNG', $input['nachlieferung']);
- $this->app->Tpl->Set('LAGER_OK', $input['lager_ok']);
- $this->app->Tpl->Set('PORTO_OK', $input['porto_ok']);
- $this->app->Tpl->Set('UST_OK', $input['ust_ok']);
- $this->app->Tpl->Set('CHECK_OK', $input['check_ok']);
- $this->app->Tpl->Set('VORKASSE_OK', $input['vorkasse_ok']);
- $this->app->Tpl->Set('NACHNAHME_OK', $input['nachnahme_ok']);
- $this->app->Tpl->Set('RESERVIERT_OK', $input['reserviert_ok']);
- $this->app->Tpl->Set('BESTELLT_OK', $input['bestellt_ok']);
- $this->app->Tpl->Set('ZEIT_OK', $input['zeit_ok']);
- $this->app->Tpl->Set('VERSAND_OK', $input['versand_ok']);
- $this->app->Tpl->Set('PARTNERID', $input['partnerid']);
- $this->app->Tpl->Set('FOLGEBESTAETIGUNG', $input['folgebestaetigung']);
- $this->app->Tpl->Set('ZAHLUNGSMAIL', $input['zahlungsmail']);
- $this->app->Tpl->Set('STORNOGRUND', $input['stornogrund']);
- $this->app->Tpl->Set('STORNOSONSTIGES', $input['stornosonstiges']);
- $this->app->Tpl->Set('STORNORUECKZAHLUNG', $input['stornorueckzahlung']);
- $this->app->Tpl->Set('STORNOBETRAG', $input['stornobetrag']);
- $this->app->Tpl->Set('STORNOBANKINHABER', $input['stornobankinhaber']);
- $this->app->Tpl->Set('STORNOBANKKONTO', $input['stornobankkonto']);
- $this->app->Tpl->Set('STORNOBANKBLZ', $input['stornobankblz']);
- $this->app->Tpl->Set('STORNOBANKBANK', $input['stornobankbank']);
- $this->app->Tpl->Set('STORNOGUTSCHRIFT', $input['stornogutschrift']);
- $this->app->Tpl->Set('STORNOGUTSCHRIFTBELEG', $input['stornogutschriftbeleg']);
- $this->app->Tpl->Set('STORNOWAREERHALTEN', $input['stornowareerhalten']);
- $this->app->Tpl->Set('STORNOMANUELLEBEARBEITUNG', $input['stornomanuellebearbeitung']);
- $this->app->Tpl->Set('STORNOKOMMENTAR', $input['stornokommentar']);
- $this->app->Tpl->Set('STORNOBEZAHLT', $input['stornobezahlt']);
- $this->app->Tpl->Set('STORNOBEZAHLTAM', $input['stornobezahltam']);
- $this->app->Tpl->Set('STORNOBEZAHLTVON', $input['stornobezahltvon']);
- $this->app->Tpl->Set('STORNOABGESCHLOSSEN', $input['stornoabgeschlossen']);
- $this->app->Tpl->Set('STORNORUECKZAHLUNGPER', $input['stornorueckzahlungper']);
- $this->app->Tpl->Set('STORNOWAREERHALTENRETOUR', $input['stornowareerhaltenretour']);
- $this->app->Tpl->Set('PARTNERAUSGEZAHLT', $input['partnerausgezahlt']);
- $this->app->Tpl->Set('PARTNERAUSGEZAHLTAM', $input['partnerausgezahltam']);
- $this->app->Tpl->Set('KENNEN', $input['kennen']);
- $this->app->Tpl->Set('LOGDATEI', $input['logdatei']);
- $this->app->Tpl->Set('BEZEICHNUNG', $input['bezeichnung']);
- $this->app->Tpl->Set('DATUMPRODUKTION', $input['datumproduktion']);
- $this->app->Tpl->Set('ANSCHREIBEN', $input['anschreiben']);
- $this->app->Tpl->Set('USEREDITID', $input['usereditid']);
- $this->app->Tpl->Set('USEREDITTIMESTAMP', $input['useredittimestamp']);
- $this->app->Tpl->Set('STEUERSATZ_NORMAL', $input['steuersatz_normal']);
- $this->app->Tpl->Set('STEUERSATZ_ZWISCHEN', $input['steuersatz_zwischen']);
- $this->app->Tpl->Set('STEUERSATZ_ERMAESSIGT', $input['steuersatz_ermaessigt']);
- $this->app->Tpl->Set('STEUERSATZ_STARKERMAESSIGT', $input['steuersatz_starkermaessigt']);
- $this->app->Tpl->Set('STEUERSATZ_DIENSTLEISTUNG', $input['steuersatz_dienstleistung']);
- $this->app->Tpl->Set('WAEHRUNG', $input['waehrung']);
- $this->app->Tpl->Set('SCHREIBSCHUTZ', $input['schreibschutz']);
- $this->app->Tpl->Set('PDFARCHIVIERT', $input['pdfarchiviert']);
- $this->app->Tpl->Set('PDFARCHIVIERTVERSION', $input['pdfarchiviertversion']);
- $this->app->Tpl->Set('TYP', $input['typ']);
- $this->app->Tpl->Set('RESERVIERART', $input['reservierart']);
- $this->app->Tpl->Set('AUSLAGERART', $input['auslagerart']);
- $this->app->Tpl->Set('PROJEKTFILIALE', $input['projektfiliale']);
- $this->app->Tpl->Set('DATUMAUSLIEFERUNG', $input['datumauslieferung']);
- $this->app->Tpl->Set('DATUMBEREITSTELLUNG', $input['datumbereitstellung']);
- $this->app->Tpl->Set('UNTERLISTENEXPLODIEREN', $input['unterlistenexplodieren']);
- $this->app->Tpl->Set('CHARGE', $input['charge']);
- $this->app->Tpl->Set('ARBEITSSCHRITTETEXTANZEIGEN', $input['arbeitsschrittetextanzeigen']);
- $this->app->Tpl->Set('EINLAGERN_OK', $input['einlagern_ok']);
- $this->app->Tpl->Set('AUSLAGERN_OK', $input['auslagern_ok']);
- $this->app->Tpl->Set('MHD', $input['mhd']);
- $this->app->Tpl->Set('AUFTRAGMENGENANPASSEN', $input['auftragmengenanpassen']);
- $this->app->Tpl->Set('INTERNEBEZEICHNUNG', $input['internebezeichnung']);
- $this->app->Tpl->Set('MENGEORIGINAL', $input['mengeoriginal']);
- $this->app->Tpl->Set('TEILPRODUKTIONVON', $input['teilproduktionvon']);
- $this->app->Tpl->Set('TEILPRODUKTIONNUMMER', $input['teilproduktionnummer']);
- $this->app->Tpl->Set('PARENT', $input['parent']);
- $this->app->Tpl->Set('PARENTNUMMER', $input['parentnummer']);
- $this->app->Tpl->Set('BEARBEITERID', $input['bearbeiterid']);
- $this->app->Tpl->Set('MENGEAUSSCHUSS', $input['mengeausschuss']);
- $this->app->Tpl->Set('MENGEERFOLGREICH', $input['mengeerfolgreich']);
- $this->app->Tpl->Set('ABSCHLUSSBEMERKUNG', $input['abschlussbemerkung']);
- $this->app->Tpl->Set('AUFTRAGID', $input['auftragid']);
- $this->app->Tpl->Set('FUNKTIONSTEST', $input['funktionstest']);
- $this->app->Tpl->Set('SERIENNUMMER_ERSTELLEN', $input['seriennummer_erstellen']);
- $this->app->Tpl->Set('UNTERSERIENNUMMERN_ERFASSEN', $input['unterseriennummern_erfassen']);
- $this->app->Tpl->Set('DATUMPRODUKTIONENDE', $input['datumproduktionende']);
- $this->app->Tpl->Set('STANDARDLAGER', $input['standardlager']);
-
+ Adjust the planned quantity of a produktion
+ Lower limit is the already produced quantity
+ Return -1 if not possible, else 1
+ */
+ function MengeAnpassen(int $produktion_id, int $menge_neu, int $lager) : int {
+
+ $fortschritt = $this->MengeFortschritt($produktion_id,$lager);
+
+ $sql = "SELECT menge,geliefert_menge FROM produktion_position WHERE produktion = $produktion_id AND stuecklistestufe = 1";
+ $produktionsmengen_alt = $this->app->DB->SelectArr($sql)[0];
+
+ if (empty($produktionsmengen_alt)) {
+ return(-1);
+ }
+ if ($menge_neu < $produktionsmengen_alt['geliefert_menge']) {
+ return(-1);
+ }
+
+ $sql = "SELECT * from produktion WHERE id = $produktion_id";
+ $produktion_alt = $this->app->DB->SelectArr($sql)[0];
+
+ // Process positions
+ $sql = "SELECT * FROM produktion_position WHERE produktion = $produktion_id";
+ $positionen = $this->app->DB->SelectArr($sql);
+
+ foreach ($positionen as $position) {
+ $menge_pro_stueck = $position['menge']/$produktionsmengen_alt['menge'];
+ $position_menge_neu = $menge_neu*$menge_pro_stueck;
+ $sql = "UPDATE produktion_position SET menge=".$position_menge_neu." WHERE id =".$position['id'];
+ $this->app->DB->Update($sql);
+
+ // Free surplus reservations
+ $restreservierung = $menge_pro_stueck * ($menge_neu+$fortschritt['ausschuss']-$fortschritt['produziert']);
+
+ $result = $this->ArtikelReservieren($position['artikel'],$lager,0,$restreservierung,'produktion',$produktion_id,$position['id'],"Produktion ".$produktion_alt['belegnr']);
+ }
+ return(1);
}
+ /*
+ Output progress information
+ ['geplant']
+ ['produziert']
+ ['erfolgreich']
+ ['ausschuss']
+ ['offen']
+ ['reserviert']
+ ['produzierbar']
+
+ If lager <= 0 -> use lager from database
+
+ */
+ function MengeFortschritt(int $produktion_id, int $lager) : array {
+ $result = array();
+
+ if ($lager <= 0) {
+ $sql = "SELECT standardlager FROM produktion WHERE id = $produktion_id";
+ $lager = $this->app->DB->SelectArr($sql)[0]['standardlager'];
+ }
+
+ $sql = "SELECT menge as geplant, geliefert_menge as produziert FROM produktion_position WHERE produktion = $produktion_id AND stuecklistestufe = 1";
+ $position_values = $this->app->DB->SelectArr($sql)[0];
+
+ if (empty($position_values)) {
+ return($result);
+ }
+
+ $sql = "SELECT mengeerfolgreich as erfolgreich, mengeausschuss as ausschuss FROM produktion WHERE id = $produktion_id";
+ $produktion_values = $this->app->DB->SelectArr($sql)[0];
+
+ if (empty($produktion_values)) {
+ return($result);
+ }
+
+ $result['geplant'] = $position_values['geplant'];
+ $result['produziert'] = $position_values['produziert'];
+
+ $result['erfolgreich'] = $produktion_values['erfolgreich'];
+ $result['ausschuss'] = $produktion_values['ausschuss'];
+
+ $result['offen'] = $result['geplant']-$result['erfolgreich'];
+
+ if (empty($lager)) {
+ $result['reserviert'] = 0;
+ $result['produzierbar'] = 0;
+ } else {
+ $result['reserviert'] = $this->LagerCheckProduktion($produktion_id, $lager, true);
+ $result['produzierbar'] = $this->LagerCheckProduktion($produktion_id, $lager, false);
+ }
+
+ return($result);
+ }
+
+ // Do calculations for the status icon display
+ // id = 0 for all open ones
+ function StatusBerechnen(int $produktion_id) {
+
+ $where = "WHERE status IN ('freigegeben','gestartet') ";
+
+ if ($produktion_id > 0) {
+ $where .= "AND id = $produktion_id";
+ }
+
+ $sql = "SELECT id, lager_ok, reserviert_ok, auslagern_ok, einlagern_ok, zeit_ok, versand_ok FROM produktion ".$where;
+ $produktionen = $this->app->DB->SelectArr($sql);
+
+ foreach ($produktionen as $produktion) {
+
+ $produktion_id = $produktion['id'];
+
+ $fortschritt = $this->MengeFortschritt($produktion_id,-1);
+
+ if (empty($fortschritt)) {
+ continue;
+ }
+
+ // lager_ok
+ if ($fortschritt['produzierbar'] >= $fortschritt['offen']) {
+ $values['lager_ok'] = 1;
+ // } else if ($fortschritt['produzierbar'] > 0) {
+ // $values['lager_ok'] = 2;
+ } else {
+ $values['lager_ok'] = 0;
+ }
+
+ // reserviert_ok
+ if ($fortschritt['reserviert'] >= $fortschritt['offen']) {
+ $values['reserviert_ok'] = 1;
+ // } else if ($fortschritt['reserviert'] > 0) {
+ // $values['reserviert_ok'] = 2;
+ } else {
+ $values['reserviert_ok'] = 0;
+ }
+
+ // auslagern_ok
+ if ($fortschritt['produziert'] >= $fortschritt['geplant']) {
+ $values['auslagern_ok'] = 1;
+ // } else if ($fortschritt['produziert'] > 0) {
+ // $values['auslagern_ok'] = 2;
+ } else {
+ $values['auslagern_ok'] = 0;
+ }
+
+ // einlagern_ok
+ if ($fortschritt['erfolgreich'] >= $fortschritt['geplant']) {
+ $values['einlagern_ok'] = 1;
+ // } else if ($fortschritt['erfolgreich'] > 0) {
+ // $values['einlagern_ok'] = 2;
+ } else {
+ $values['einlagern_ok'] = 0;
+ }
+
+ // reserviert_ok
+ if ($fortschritt['produziert'] >= $fortschritt['geplant']) {
+ $values['auslagern_ok'] = 1;
+ // } else if ($fortschritt['produziert'] > 0) {
+ // $values['auslagern_ok'] = 2;
+ } else {
+ $values['auslagern_ok'] = 0;
+ }
+
+ $fix = "";
+ $update = "";
+ foreach ($values as $key => $value) {
+ $update = $update.$fix.$key." = '".($value)."'";
+ $fix = ", ";
+ }
+
+ $sql = "UPDATE produktion SET $update WHERE id = $produktion_id";
+ $this->app->DB->Update($sql);
+ }
+ }
+
+ // Copy an existing produktion as draft, with option to adjust the quantity
+ // return id on sucess, else negative number
+
+ function Copy($produktion_id, $menge_abteilen) : int {
+
+ if (empty($produktion_id)) {
+ return(-1);
+ }
+
+ $fortschritt = $this->MengeFortschritt($produktion_id,0);
+ if (empty($fortschritt)) {
+ return(-2);
+ }
+
+ if ($menge_abteilen < 1) {
+ $menge_abteilen = $fortschritt['geplant'];
+ }
+
+ $sql = "SELECT * from produktion WHERE id = $produktion_id";
+ $produktion_alt = $this->app->DB->SelectArr($sql)[0];
+
+ if (empty($produktion_alt)) {
+ return (-3);
+ }
+
+ $menge_pro_stueck = $menge_abteilen/$fortschritt['geplant'];
+
+ $produktion_neu = array();
+ $produktion_neu['status'] = 'angelegt';
+ $produktion_neu['datum'] = date("Y-m-d");
+ $produktion_neu['art'] = $produktion_alt['art'];
+ $produktion_neu['projekt'] = $produktion_alt['projekt'];
+ $produktion_neu['angebot'] = $produktion_alt['angebot'];
+ $produktion_neu['kundennummer'] = $produktion_alt['kundennummer'];
+ $produktion_neu['auftragid'] = $produktion_alt['auftragid'];
+ $produktion_neu['freitext'] = $produktion_alt['freitext'];
+ $produktion_neu['internebemerkung'] = $produktion_alt['internebemerkung'];
+ $produktion_neu['adresse'] = $produktion_alt['adresse'];
+
+ if ($produktion_alt['belegnr'] != '') {
+ $produktion_neu['internebezeichnung '] = "Kopie von ".$produktion_alt['belegnr']." ".$produktion_alt['internebezeichnung'];
+ } else {
+ $produktion_neu['internebezeichnung '] = $produktion_alt['internebezeichnung'];
+ }
+
+ $produktion_neu['standardlager'] = $produktion_alt['standardlager'];
+
+
+ $columns = "";
+ $values = "";
+ $update = "";
+
+ $fix = "";
+
+ foreach ($produktion_neu as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $update = $update.$fix.$key." = '$value'";
+ $fix = ", ";
+ }
+
+ $sql = "INSERT INTO produktion (".$columns.") VALUES (".$values.")";
+ $this->app->DB->Update($sql);
+ $produktion_neu_id = $this->app->DB->GetInsertID();
+
+ // Now add the positions
+ $sql = "SELECT * FROM produktion_position WHERE produktion = $produktion_id";
+ $positionen = $this->app->DB->SelectArr($sql);
+
+ foreach ($positionen as $position) {
+
+ $columns = "";
+
+ // For the new positions
+ $position['id'] = 'NULL';
+ $position['geliefert_menge'] = 0;
+
+ $position['menge'] = $menge_abteilen*$menge_pro_stueck;
+ $position['produktion'] = $produktion_neu_id;
+
+ $values = "";
+ $fix = "";
+ foreach ($position as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $fix = ", ";
+ }
+ $sql = "INSERT INTO produktion_position (".$columns.") VALUES (".$values.")";
+ $this->app->DB->Update($sql);
+
+ }
+
+ return($produktion_neu_id);
+ }
+
+ /*
+ Write something into the log
+ */
+ function ProtokollSchreiben(int $produktion_id, string $text) {
+ $sql = "INSERT INTO produktion_protokoll (produktion, zeit, bearbeiter, grund) VALUES ($produktion_id, NOW(), '".$this->app->DB->real_escape_string($this->app->User->GetName())."','".$this->app->DB->real_escape_string($text)."')";
+ $this->app->DB->Insert($sql);
+ }
+
+ function ProtokollTabelleErzeugen($produktion_id, $parsetarget)
+ {
+ $tmp = new EasyTable($this->app);
+ $tmp->Query("SELECT zeit,bearbeiter,grund FROM produktion_protokoll WHERE produktion='$produktion_id' ORDER by zeit DESC");
+ $tmp->DisplayNew($parsetarget,'Protokoll','noAction');
+ }
+
+
}
+
diff --git a/www/pages/produktion_position.php b/www/pages/produktion_position.php
new file mode 100644
index 00000000..91de8f31
--- /dev/null
+++ b/www/pages/produktion_position.php
@@ -0,0 +1,258 @@
+app = $app;
+ if ($intern)
+ return;
+
+ $this->app->ActionHandlerInit($this);
+ $this->app->ActionHandler("list", "produktion_position_list");
+ $this->app->ActionHandler("create", "produktion_position_edit"); // This automatically adds a "New" button
+ $this->app->ActionHandler("edit", "produktion_position_edit");
+ $this->app->ActionHandler("delete", "produktion_position_delete");
+ $this->app->DefaultActionHandler("list");
+ $this->app->ActionHandlerListen($app);
+ }
+
+ public function Install() {
+ /* Fill out manually later */
+ }
+
+ static function TableSearch(&$app, $name, $erlaubtevars) {
+ switch ($name) {
+ case "produktion_position_list":
+ $allowed['produktion_position_list'] = array('list');
+ $heading = array('','','produktion', 'artikel', 'projekt', 'bezeichnung', 'beschreibung', 'internerkommentar', 'nummer', 'menge', 'preis', 'waehrung', 'lieferdatum', 'vpe', 'sort', 'status', 'umsatzsteuer', 'bemerkung', 'geliefert', 'geliefert_menge', 'explodiert', 'explodiert_parent', 'logdatei', 'nachbestelltexternereinkauf', 'beistellung', 'externeproduktion', 'einheit', 'steuersatz', 'steuertext', 'erloese', 'erloesefestschreiben', 'freifeld1', 'freifeld2', 'freifeld3', 'freifeld4', 'freifeld5', 'freifeld6', 'freifeld7', 'freifeld8', 'freifeld9', 'freifeld10', 'freifeld11', 'freifeld12', 'freifeld13', 'freifeld14', 'freifeld15', 'freifeld16', 'freifeld17', 'freifeld18', 'freifeld19', 'freifeld20', 'freifeld21', 'freifeld22', 'freifeld23', 'freifeld24', 'freifeld25', 'freifeld26', 'freifeld27', 'freifeld28', 'freifeld29', 'freifeld30', 'freifeld31', 'freifeld32', 'freifeld33', 'freifeld34', 'freifeld35', 'freifeld36', 'freifeld37', 'freifeld38', 'freifeld39', 'freifeld40', 'stuecklistestufe', 'teilprojekt', 'Menü');
+ $width = array('1%','1%','10%'); // Fill out manually later
+
+ $findcols = array('p.produktion', 'p.artikel', 'p.projekt', 'p.bezeichnung', 'p.beschreibung', 'p.internerkommentar', 'p.nummer', 'p.menge', 'p.preis', 'p.waehrung', 'p.lieferdatum', 'p.vpe', 'p.sort', 'p.status', 'p.umsatzsteuer', 'p.bemerkung', 'p.geliefert', 'p.geliefert_menge', 'p.explodiert', 'p.explodiert_parent', 'p.logdatei', 'p.nachbestelltexternereinkauf', 'p.beistellung', 'p.externeproduktion', 'p.einheit', 'p.steuersatz', 'p.steuertext', 'p.erloese', 'p.erloesefestschreiben', 'p.freifeld1', 'p.freifeld2', 'p.freifeld3', 'p.freifeld4', 'p.freifeld5', 'p.freifeld6', 'p.freifeld7', 'p.freifeld8', 'p.freifeld9', 'p.freifeld10', 'p.freifeld11', 'p.freifeld12', 'p.freifeld13', 'p.freifeld14', 'p.freifeld15', 'p.freifeld16', 'p.freifeld17', 'p.freifeld18', 'p.freifeld19', 'p.freifeld20', 'p.freifeld21', 'p.freifeld22', 'p.freifeld23', 'p.freifeld24', 'p.freifeld25', 'p.freifeld26', 'p.freifeld27', 'p.freifeld28', 'p.freifeld29', 'p.freifeld30', 'p.freifeld31', 'p.freifeld32', 'p.freifeld33', 'p.freifeld34', 'p.freifeld35', 'p.freifeld36', 'p.freifeld37', 'p.freifeld38', 'p.freifeld39', 'p.freifeld40', 'p.stuecklistestufe', 'p.teilprojekt');
+ $searchsql = array('p.produktion', 'p.artikel', 'p.projekt', 'p.bezeichnung', 'p.beschreibung', 'p.internerkommentar', 'p.nummer', 'p.menge', 'p.preis', 'p.waehrung', 'p.lieferdatum', 'p.vpe', 'p.sort', 'p.status', 'p.umsatzsteuer', 'p.bemerkung', 'p.geliefert', 'p.geliefert_menge', 'p.explodiert', 'p.explodiert_parent', 'p.logdatei', 'p.nachbestelltexternereinkauf', 'p.beistellung', 'p.externeproduktion', 'p.einheit', 'p.steuersatz', 'p.steuertext', 'p.erloese', 'p.erloesefestschreiben', 'p.freifeld1', 'p.freifeld2', 'p.freifeld3', 'p.freifeld4', 'p.freifeld5', 'p.freifeld6', 'p.freifeld7', 'p.freifeld8', 'p.freifeld9', 'p.freifeld10', 'p.freifeld11', 'p.freifeld12', 'p.freifeld13', 'p.freifeld14', 'p.freifeld15', 'p.freifeld16', 'p.freifeld17', 'p.freifeld18', 'p.freifeld19', 'p.freifeld20', 'p.freifeld21', 'p.freifeld22', 'p.freifeld23', 'p.freifeld24', 'p.freifeld25', 'p.freifeld26', 'p.freifeld27', 'p.freifeld28', 'p.freifeld29', 'p.freifeld30', 'p.freifeld31', 'p.freifeld32', 'p.freifeld33', 'p.freifeld34', 'p.freifeld35', 'p.freifeld36', 'p.freifeld37', 'p.freifeld38', 'p.freifeld39', 'p.freifeld40', 'p.stuecklistestufe', 'p.teilprojekt');
+
+ $defaultorder = 1;
+ $defaultorderdesc = 0;
+
+ $dropnbox = "'
' AS `open`, CONCAT('
') AS `auswahl`";
+
+ $menu = "
";
+
+ $sql = "SELECT SQL_CALC_FOUND_ROWS p.id, $dropnbox, p.produktion, p.artikel, p.projekt, p.bezeichnung, p.beschreibung, p.internerkommentar, p.nummer, p.menge, p.preis, p.waehrung, p.lieferdatum, p.vpe, p.sort, p.status, p.umsatzsteuer, p.bemerkung, p.geliefert, p.geliefert_menge, p.explodiert, p.explodiert_parent, p.logdatei, p.nachbestelltexternereinkauf, p.beistellung, p.externeproduktion, p.einheit, p.steuersatz, p.steuertext, p.erloese, p.erloesefestschreiben, p.freifeld1, p.freifeld2, p.freifeld3, p.freifeld4, p.freifeld5, p.freifeld6, p.freifeld7, p.freifeld8, p.freifeld9, p.freifeld10, p.freifeld11, p.freifeld12, p.freifeld13, p.freifeld14, p.freifeld15, p.freifeld16, p.freifeld17, p.freifeld18, p.freifeld19, p.freifeld20, p.freifeld21, p.freifeld22, p.freifeld23, p.freifeld24, p.freifeld25, p.freifeld26, p.freifeld27, p.freifeld28, p.freifeld29, p.freifeld30, p.freifeld31, p.freifeld32, p.freifeld33, p.freifeld34, p.freifeld35, p.freifeld36, p.freifeld37, p.freifeld38, p.freifeld39, p.freifeld40, p.stuecklistestufe, p.teilprojekt, p.id FROM produktion_position p";
+
+ $where = "1";
+ $count = "SELECT count(DISTINCT id) FROM produktion_position WHERE $where";
+// $groupby = "";
+
+ break;
+ }
+
+ $erg = false;
+
+ foreach ($erlaubtevars as $k => $v) {
+ if (isset($$v)) {
+ $erg[$v] = $$v;
+ }
+ }
+ return $erg;
+ }
+
+ function produktion_position_list() {
+/* $this->app->erp->MenuEintrag("index.php?module=produktion_position&action=list", "Übersicht");
+ $this->app->erp->MenuEintrag("index.php?module=produktion_position&action=create", "Neu anlegen");
+
+ $this->app->erp->MenuEintrag("index.php", "Zurück");
+
+ $this->app->YUI->TableSearch('TAB1', 'produktion_position_list', "show", "", "", basename(__FILE__), __CLASS__);
+ $this->app->Tpl->Parse('PAGE', "produktion_position_list.tpl");*/
+
+ header("Location: index.php?module=produktion&action=list");
+ }
+
+
+ // End edit process and return to previous page
+ // Give pid in case of delete because position.id is already gone
+ function produktion_position_edit_end(string $msg, bool $error, bool $go_to_production, int $pid = 0) {
+
+ if ($error) {
+ $msg = $this->app->erp->base64_url_encode("
".$msg."
");
+ } else {
+ $msg = $this->app->erp->base64_url_encode("
".$msg."
");
+ }
+
+ if ($go_to_production) {
+ if ($pid == 0) {
+ $id = (int) $this->app->Secure->GetGET('id');
+ $sql = "SELECT p.status, p.id from produktion p INNER JOIN produktion_position pp ON pp.produktion = p.id WHERE pp.id = $id";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $pid = $result['id'];
+ }
+ header("Location: index.php?module=produktion&action=edit&id=$pid&msg=$msg#tabs-3");
+ } else {
+ header("Location: index.php?module=produktion_position&action=list&msg=$msg");
+ }
+ exit();
+ }
+
+
+ public function produktion_position_delete() {
+ $id = (int) $this->app->Secure->GetGET('id');
+
+ $sql = "SELECT p.status, p.id from produktion p INNER JOIN produktion_position pp ON pp.produktion = p.id WHERE pp.id = $id";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $status = $result['status'];
+ $pid = $result['id'];
+ if (!in_array($status,array('angelegt','freigegeben'))) {
+ $this->produktion_position_edit_end("Bearbeiten nicht möglich, Produktionsstatus ist '$status'",true, true);
+ }
+
+ $this->app->DB->Delete("DELETE FROM `produktion_position` WHERE `id` = '{$id}'");
+
+ // Remove reserved items
+
+ $this->produktion_position_edit_end("Der Eintrag wurde gelöscht.", true, true, $pid);
+ }
+
+ /*
+ * Edit produktion_position item
+ * If id is empty, create a new one
+ */
+
+ function produktion_position_edit() {
+ $id = $this->app->Secure->GetGET('id');
+
+ $this->app->Tpl->Set('ID', $id);
+
+ $this->app->erp->MenuEintrag("index.php?module=produktion_position&action=edit&id=$id", "Details");
+ $this->app->erp->MenuEintrag("index.php?module=produktion&action=edit%id=$pid", "Zurück zur Übersicht");
+ $id = $this->app->Secure->GetGET('id');
+ $input = $this->GetInput();
+ $submit = $this->app->Secure->GetPOST('submit');
+
+ if (empty($id)) {
+ // New item
+ $id = 'NULL';
+ $produktion_id = $this->app->Secure->GetGET('produktion');
+ $sql = "SELECT p.status from produktion p WHERE p.id = $produktion_id";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $status = $result['status'];
+ } else {
+ $sql = "SELECT p.status, p.id from produktion p INNER JOIN produktion_position pp ON pp.produktion = p.id WHERE pp.id = $id";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $status = $result['status'];
+ $produktion_id = $result['id'];
+ }
+
+ $input['produktion'] = $produktion_id;
+
+ $sql = "SELECT FORMAT(menge,0) as menge FROM produktion_position WHERE produktion = $produktion_id AND stuecklistestufe = 1";
+ $result = $this->app->DB->SelectArr($sql)[0];
+ $planmenge = $result['menge'];
+
+ if ($planmenge == 0) {
+ $this->produktion_position_edit_end("Keine Planung vorhanden.",true, true, $produktion_id);
+ }
+
+ if ($submit != '')
+ {
+
+ // Write to database
+
+ // Add checks here
+ $input['artikel'] = $this->app->erp->ReplaceArtikel(true, $input['artikel'],true); // Convert from form to db
+
+ // Only allowed when produktion is 'freigegeben or angelegt'
+ if (!in_array($status,array('angelegt','freigegeben'))) {
+ $this->produktion_position_edit_end("Bearbeiten nicht möglich, Produktionsstatus ist '$status'",true, true);
+ }
+
+ if ($input['menge'] < 0) {
+ $this->produktion_position_edit_end("Ungültige Menge.",true, true);
+ }
+
+ // Only allow quantities that are a multiple of the target quantity
+ if ($input['menge'] % $planmenge != 0) {
+ $this->produktion_position_edit_end("Positionsmenge muss Vielfaches von $planmenge sein.",true, true, $produktion_id);
+ }
+
+ $columns = "id, ";
+ $values = "$id, ";
+ $update = "";
+
+ $fix = "";
+
+ foreach ($input as $key => $value) {
+ $columns = $columns.$fix.$key;
+ $values = $values.$fix."'".$value."'";
+ $update = $update.$fix.$key." = '$value'";
+
+ $fix = ", ";
+ }
+
+// echo($columns."
");
+// echo($values."
");
+// echo($update."
");
+
+ $sql = "INSERT INTO produktion_position (".$columns.") VALUES (".$values.") ON DUPLICATE KEY UPDATE ".$update;
+
+// echo($sql);
+
+ $this->app->DB->Update($sql);
+
+ if ($id == 'NULL') {
+ $msg = "Das Element wurde erfolgreich angelegt.";
+ } else {
+ $msg = "Die Einstellungen wurden erfolgreich übernommen.";
+ }
+ $this->produktion_position_edit_end($msg,false,true,$produktion_id);
+
+ }
+
+
+ // Load values again from database
+
+ $result = $this->app->DB->SelectArr("SELECT SQL_CALC_FOUND_ROWS pp.id, pp.produktion, p.belegnr, pp.artikel, FORMAT(pp.menge,0) as menge, pp.id FROM produktion_position pp INNER JOIN produktion p ON pp.produktion = p.id "." WHERE pp.id=$id");
+
+ foreach ($result[0] as $key => $value) {
+ $this->app->Tpl->Set(strtoupper($key), $value);
+ }
+
+ /*
+ * Add displayed items later
+ *
+
+ $this->app->Tpl->Add('KURZUEBERSCHRIFT2', $email);
+ $this->app->Tpl->Add('EMAIL', $email);
+ $this->app->Tpl->Add('ANGEZEIGTERNAME', $angezeigtername);
+ */
+
+ $this->app->YUI->AutoComplete("artikel", "artikelnummer");
+ //$this->app->YUI->AutoComplete("artikel", "lagerartikelnummer");
+ $this->app->Tpl->Set('ARTIKEL',$this->app->erp->ReplaceArtikel(false, $result[0]['artikel'], false)); // Convert from form to db
+
+ $this->app->Tpl->Set('PRODUKTIONID',$result[0]['produktion']);
+ $this->app->Tpl->Set('PRODUKTIONBELEGNR',$result[0]['belegnr']);
+
+ $this->app->Tpl->Add('MESSAGE',"
Positionsmenge muss Vielfaches von $planmenge sein.
");
+
+ $this->app->Tpl->Parse('PAGE', "produktion_position_edit.tpl");
+ }
+
+ /**
+ * Get all paramters from html form and save into $input
+ */
+ public function GetInput(): array {
+ $input = array();
+
+ $input['artikel'] = $this->app->Secure->GetPOST('artikel');
+ $input['menge'] = $this->app->Secure->GetPOST('menge');
+
+ return($input);
+ }
+
+}
diff --git a/www/pages/shopimporter_shopware6.php b/www/pages/shopimporter_shopware6.php
index 3189b694..87f8ed0c 100644
--- a/www/pages/shopimporter_shopware6.php
+++ b/www/pages/shopimporter_shopware6.php
@@ -1,3820 +1,3820 @@
-app = $app;
- $this->intern = true;
- if ($intern) {
- return;
- }
- $this->app->ActionHandlerInit($this);
-
- $this->app->ActionHandler('list', 'Shopimporter_Shopware6List');
- $this->app->ActionHandler('auth', 'ImportAuth');
- $this->app->ActionHandler('sendlistlager', 'ImportSendListLager');
- $this->app->ActionHandler('getauftraegeanzahl', 'ImportGetAuftraegeAnzahl');
- $this->app->ActionHandler('getauftrag', 'ImportGetAuftrag');
- $this->app->ActionHandler('deleteauftrag', 'ImportDeleteAuftrag');
- $this->app->ActionHandler('updateauftrag', 'ImportUpdateAuftrag');
- $this->app->ActionHandler('storniereauftrag','ImportStorniereAuftrag');
- $this->app->ActionHandler('getarticle','ImportGetArticle');
- $this->app->ActionHandler('getarticlelist','ImportGetArticleList');
- $this->app->ActionHandler("updatezahlungsstatus","ImportUpdateZahlungsstatus");
- $this->app->DefaultActionHandler('list');
-
- $this->app->ActionHandlerListen($app);
- }
-
- /**
- * @param string $productId
- *
- * @return mixed
- */
- public function addSyncCustomFieldToProduct(string $productId)
- {
- $customField = [
- 'customFields' => [
- 'wawision_shopimporter_syncstate' => 1
- ]
- ];
-
- return $this->shopwareRequest('PATCH', "product/{$productId}", $customField);
- }
-
- /**
- * @param string $orderId
- *
- * @return mixed
- */
- public function addCustomFieldToOrder(string $orderId)
- {
- $customField = [
- 'customFields' => [
- 'wawision_shopimporter_syncstate' => 1
- ]
- ];
-
- return $this->shopwareRequest('PATCH', "order/{$orderId}", $customField);
- }
-
- public function ImportGetArticleList()
- {
- $page = 1;
- $limit = 500;
-
- do {
- $productIdsToAdd = [];
- $searchdata = [
- 'limit' => $limit,
- 'page' => $page,
- 'filter' => [
- [
- 'field' => 'product.parentId',
- 'type' => 'equals',
- 'value' => null
- ]
- ]
- ];
-
- $productsInShop = $this->shopwareRequest('POST', 'search/product', $searchdata);
- if (!empty($productsInShop['data'])) {
- foreach ($productsInShop['data'] as $productInShop) {
- $productIdsToAdd[] = $productInShop['id'];
- }
- }
-
- foreach ($productIdsToAdd as $productId) {
- $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$this->shopid', '" . $this->app->DB->real_escape_string($productId) . "')");
- }
- $page++;
- } while (count($productsInShop['data']) === $limit);
-
-
- $anzahl = $this->app->DB->Select("SELECT COUNT(id) FROM shopexport_getarticles WHERE shop=$this->shopid");
- $this->app->erp->SetKonfigurationValue('artikelimportanzahl_' . $this->shopid, $anzahl);
-
- }
-
- /**
- * @param string $method
- * @param string $endpoint
- * @param string $data
- *
- * @param array $headerInformation
- * @return mixed
- */
- public function shopwareRequest($method, $endpoint, $data = '', $headerInformation = [])
- {
- $accessToken = $this->shopwareToken();
- $url = $this->ShopUrl;
- $url .= 'v2/' . $endpoint;
-
- $ch = curl_init();
- $headerInformation[] = 'Content-Type:application/json';
- $headerInformation[] = 'Authorization:Bearer ' . $accessToken['token'];
- curl_setopt($ch, CURLOPT_URL, $url);
- if (!empty($data)) {
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- }
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headerInformation);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $response = curl_exec($ch);
- if (curl_error($ch)) {
- $this->error[] = curl_error($ch);
- }
- curl_close($ch);
-
- return json_decode($response, true);
- }
-
- /**
- * @return array
- */
- protected function shopwareToken()
- {
- $result = [];
-
- $result['success'] = true;
- $result['token'] = $this->accessToken;
- $result['message'] = 'Keine Antwort von API erhalten.';
-
- if (!empty($result['token'])) {
- return $result;
- }
-
- $result['success'] = false;
-
- $data = [
- 'username' => $this->UserName,
- 'password' => $this->Password,
- 'grant_type' => 'password',
- 'scopes' => 'write',
- 'client_id' => 'administration',
- ];
-
- $ch = curl_init($this->ShopUrl . 'oauth/token');
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Accept: application/json',
- 'Content-Type: application/json',
- 'Cache-Control: no-cache',
- ]
- );
- $response = json_decode(curl_exec($ch), true);
-
- if (!empty((string)$response['title'])) {
- $result['message'] = $response['title'];
- }
-
- if (!empty($response['access_token'])) {
- $result['success'] = true;
- $this->accessToken = $response['access_token'];
- $result['token'] = $response['access_token'];
- }
-
- return $result;
- }
-
- public function ImportGetArticle()
- {
- $tmp = $this->CatchRemoteCommand('data');
-
- if (isset($tmp['nummerintern'])) {
- $nummer = $tmp['nummerintern'];
- $response = $this->shopwareRequest('GET', 'product/' . $nummer);
- if (empty($response['data'])) {
- $this->error[] = 'Artikel in der Shop Datenbank nicht gefunden!';
- return;
- }
- $nummer = $response['data']['attributes']['productNumber'];
- } else {
- $nummer = $tmp['nummer'];
- }
- $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer .
- '&associations[manufacturer][]&associations[properties][]');
- if (empty($articleInfo['data'][0])) {
- $this->error[] = 'Artikel in der Shop Datenbank nicht gefunden!';
- return;
- }
- $articleIdInShop = $articleInfo['data'][0]['id'];
- if(empty($articleInfo['data'][0]['customFields'])
- || empty($articleInfo['data'][0]['customFields']['wawision_shopimporter_syncstate'])){
- $this->addSyncCustomFieldToProduct((string)$articleIdInShop);
- }
-
- $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer .
- '&associations[manufacturer][]&associations[properties][]');
- $associatedInformation = [];
- $properties = [];
- foreach ($articleInfo['included'] as $includedInformation) {
- if ($includedInformation['type'] === 'property_group_option') {
- $properties[$includedInformation['id']] = $includedInformation['attributes'];
- } else {
- $associatedInformation[$includedInformation['id']] = $includedInformation['attributes'];
- }
- }
- $groups = [];
- if (!empty($properties)) {
- $groupsInShop = $this->shopwareRequest('GET', 'property-group');
- foreach ($groupsInShop['data'] as $groupInShop) {
- $groups[$groupInShop['id']] = $groupInShop['attributes']['name'];
- }
- }
- $media = $this->shopwareRequest('GET', 'product/' . $articleIdInShop . '/media');
- $imagesToAdd = [];
- if (!empty($media['included'])) {
- foreach ($media['included'] as $mediaInfo) {
- if ($mediaInfo['type'] === 'media') {
- $imagesToAdd[] = [
- 'content' => base64_encode(@file_get_contents($mediaInfo['attributes']['url'])),
- 'path' => $mediaInfo['attributes']['url'],
- 'id' => $mediaInfo['id']
- ];
- }
- }
- }
- $articleInfo = $articleInfo['data'][0]['attributes'];
-
- $data = [];
- $data['name'] = $articleInfo['name'];
- if (isset($tmp['nummerintern'])) {
- $data['nummer'] = $articleInfo['productNumber'];
- }
-
-
- $data['artikelnummerausshop'] = $articleInfo['productNumber'];
- $data['restmenge'] = $articleInfo['stock'];
- $data['uebersicht_de'] = $articleInfo['description'];
- $data['preis_netto'] = $articleInfo['price'][0]['net'];
- if (!empty($articleInfo['price'][0]['listPrice'])) {
- $data['pseudopreis'] = $articleInfo['price'][0]['listPrice'];
- }
- $data['aktiv'] = $articleInfo['active'];
- if (!empty($articleInfo['weight'])) {
- $data['gewicht'] = $articleInfo['weight'];
- }
- if (!empty($articleInfo['manufacturerNumber'])) {
- $data['herstellernummer'] = $articleInfo['manufacturerNumber'];
- }
- if (!empty($articleInfo['ean'])) {
- $data['ean'] = $articleInfo['ean'];
- }
- if (!empty($articleInfo['manufacturerId'])) {
- $data['hersteller'] = $associatedInformation[$articleInfo['manufacturerId']]['name'];
- }
- if (!empty($articleInfo['taxId'])) {
- $data['umsatzsteuer'] = $associatedInformation[$articleInfo['taxId']]['taxRate'];
- }
- if (!empty($properties)) {
- foreach ($properties as $property) {
- if ($this->propertyOption === 'toProperties') {
- $data['eigenschaften'][] = [
- 'name' => $groups[$property['groupId']],
- 'values' => $property['name'],
- ];
- }
- if ($this->propertyOption === 'toCustomFields') {
- $data['freifeld_' . $groups[$property['groupId']]] = $property['name'];
- }
- }
- }
- if (!empty($articleInfo['customFields'])) {
- foreach ($articleInfo['customFields'] as $customFieldName => $customFieldValue) {
- if ($this->freeFieldOption === 'toProperties') {
- $data['eigenschaften'][] = [
- 'name' => $customFieldName,
- 'values' => $customFieldValue
- ];
- }
- if ($this->freeFieldOption === 'toCustomFields') {
- $data['freifeld_' . $customFieldName] = $customFieldValue;
- }
- }
- }
- if (!empty($imagesToAdd)) {
- $data['bilder'] = $imagesToAdd;
- }
-
-
- if ($articleInfo['childCount'] > 0) {
- $data = [$data];
-
- $limit = 50;
- $page = 1;
- $optionInfo = [];
- $optionGroupInfo = [];
- do {
-
- $searchdata = [
- 'limit' => $limit,
- 'page' => $page,
- 'filter' => [
- [
- 'field' => 'product.parentId',
- 'type' => 'equals',
- 'value' => $articleIdInShop
- ]
- ],
- 'sort' => [
- [
- 'field' => 'product.options.groupId',
- 'naturalSorting' => false,
- 'order' => 'ASC'
- ],
- [
- 'field' => 'product.options.id',
- 'naturalSorting' => false,
- 'order' => 'ASC'
- ]
- ],
- 'associations' => [
- 'options' => [
- 'sort' => [
- [
- 'field' => 'groupId',
- 'naturalSorting' => false,
- 'order' => 'ASC'
- ],
- [
- 'field' => 'id',
- 'naturalSorting' => false,
- 'order' => 'ASC'
- ]
- ]
- ]
- ]
- ];
- $variantsInShop = $this->shopwareRequest('POST', 'search/product', $searchdata);
- foreach ($variantsInShop['included'] as $includedInfo) {
- if ($includedInfo['type'] === 'property_group_option') {
- $optionInfo[$includedInfo['id']] = $includedInfo['attributes'];
- if (empty($optionGroupInfo[$includedInfo['attributes']['groupId']])) {
- $optionGroupInfo[$includedInfo['attributes']['groupId']] = (!empty($optionGroupInfo)?count($optionGroupInfo):0) + 1;
- }
- }
- }
-
- foreach ($variantsInShop['data'] as $variantInShop) {
- $variantData = [];
- $variantName = $data[0]['name'];
- foreach ($variantInShop['attributes']['optionIds'] as $optionId) {
- $variantData['matrixprodukt_wert' . $optionGroupInfo[$optionInfo[$optionId]['groupId']]] =
- $optionInfo[$optionId]['name'];
- $variantName .= ' - ' . $optionInfo[$optionId]['name'];
- }
-
- $variantData['name'] = $variantName;
- $variantData['nummer'] = $variantInShop['attributes']['productNumber'];
- $variantData['artikelnummerausshop'] = $variantInShop['attributes']['productNumber'];
- $variantData['restmenge'] = $variantInShop['attributes']['stock'];
- $variantData['uebersicht_de'] = $variantInShop['attributes']['description'];
- if (empty($variantInShop['attributes']['price'][0]['net'])) {
- $variantData['preis_netto'] = $data[0]['preis_netto'];
- } else {
- $variantData['preis_netto'] = $variantInShop['attributes']['price'][0]['net'];
- }
- if (!empty($variantInShop['attributes']['price'][0]['listPrice'])) {
- $variantData['pseudopreis'] = $variantInShop['attributes']['price'][0]['listPrice'];
- }
- $variantData['aktiv'] = $variantInShop['attributes']['active'];
- if (!empty($variantInShop['attributes']['weight'])) {
- $variantData['gewicht'] = $variantInShop['attributes']['weight'];
- }
- if (!empty($variantInShop['attributes']['manufacturerNumber'])) {
- $variantData['herstellernummer'] = $variantInShop['attributes']['manufacturerNumber'];
- }
- if (!empty($variantInShop['attributes']['ean'])) {
- $variantData['ean'] = $variantInShop['attributes']['ean'];
- }
- if (!empty($data[0]['umsatzsteuer'])) {
- $variantData['umsatzsteuer'] = $data[0]['umsatzsteuer'];
- }
-
- $data[] = $variantData;
- }
-
- $page++;
- } while (count($variantsInShop['data']) > $limit);
-
- foreach ($optionGroupInfo as $groupId => $sorting) {
- $data[0]['matrixprodukt_gruppe' . $sorting] = $groups[$groupId];
- }
- foreach ($optionInfo as $optionData) {
- $data[0]['matrixprodukt_optionen' . $optionGroupInfo[$optionData['groupId']]][] = $optionData['name'];
- }
- }
-
- //TODO Staffelpreise
- //TODO Kategorien
- //TODO Freifelder
- //TODO Crossselling
-
- return $data;
- }
-
- /**
- * @param array $data
- *
- * @return array
- */
- public function checkApiApp($data)
- {
- foreach (['shopwareUserName', 'shopwarePassword', 'shopwareUrl'] as $field) {
- if (empty($data['data'][$field])) {
- return ['success' => false, 'error' => sprintf('%s is empty', $field)];
- }
- }
-
- $shops = $this->app->DB->SelectArr(
- sprintf(
- "SELECT `einstellungen_json`, `bezeichnung`,`id`
- FROM `shopexport`
- WHERE `modulename` = 'shopimporter_shopware6'
- AND `einstellungen_json` IS NOT NULL AND `einstellungen_json` <> ''"
- )
- );
- if (empty($shops)) {
- return [
- 'info' => [
- 'Shop' => 'Shopware',
- 'info' => 'Url ' . $data['data']['shopwareUrl'],
- ]
- ];
- }
- foreach ($shops as $shop) {
- if (empty($shop['einstellungen_json'])) {
- continue;
- }
- $json = @json_decode($shop['einstellungen_json'], true);
- if (empty($json['felder']) || empty($json['felder']['shopwareUrl'])) {
- continue;
- }
- if ($json['felder']['shopwareUrl'] === $data['data']['shopwareUrl']) {
- return [
- 'success' => false,
- 'error' => sprintf('Shop with url %s allready exists', $data['data']['shopwareUrl'])
- ];
- }
- }
-
- return [
- 'info' => [
- 'Shop' => 'Shopware',
- 'info' => 'Url ' . $data['data']['shopwareUrl'],
- ]
- ];
- }
-
- /**
- *
- */
- public function Shopimporter_Shopware6List()
- {
- $msg = $this->app->erp->base64_url_encode('
Sie können hier die Shops einstellen
');
- header('Location: index.php?module=onlineshops&action=list&msg=' . $msg);
- exit;
- }
-
- /**
- * @param $shopid
- * @param $data
- */
- public function getKonfig($shopid, $data)
- {
- $this->shopid = $shopid;
- $this->data = $data;
- $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json`, `kategorienuebertragen` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1");
- $importerSettings = reset($importerSettings);
-
- $this->exportCategories = (bool) $importerSettings['kategorienuebertragen'];
-
- $einstellungen = [];
- if (!empty($importerSettings['einstellungen_json'])) {
- $einstellungen = json_decode($importerSettings['einstellungen_json'], true);
- }
- $this->protocol = $einstellungen['felder']['protocol'];
- $this->UserName = $einstellungen['felder']['shopwareUserName'];
- $this->Password = $einstellungen['felder']['shopwarePassword'];
- $this->ShopUrl = rtrim($einstellungen['felder']['shopwareUrl'], '/') . '/';
- $this->createManufacturerAllowed = false;
- if ($einstellungen['felder']['shopwareAllowCreateManufacturer'] === '1') {
- $this->createManufacturerAllowed = true;
- }
- $this->defaultManufacturer = $einstellungen['felder']['shopwareDefaultManufacturer'];
- $this->defaultRuleName = $einstellungen['felder']['shopwareDefaultRuleName'];
- $this->statesToFetch = $einstellungen['felder']['statesToFetch'];
- $this->deliveryStatesToFetch = $einstellungen['felder']['deliveryStatesToFetch'];
- $this->transactionStatesToFetch = $einstellungen['felder']['transactionStatesToFetch'];
- $this->salesChannelToFetch = $einstellungen['felder']['salesChannelToFetch'];
- $this->orderSearchLimit = $einstellungen['felder']['orderSearchLimit'];
- $this->freeFieldOption = $einstellungen['felder']['shopwareFreeFieldOption'];
- $this->propertyOption = $einstellungen['felder']['shopwarePropertyOption'];
- $this->shopwareDefaultSalesChannel = $einstellungen['felder']['shopwareDefaultSalesChannel'];
- $this->shopwareMediaFolder = $einstellungen['felder']['shopwareMediaFolder'];
- $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid);
- $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query));
-
- $this->client = $this->app->Container->get('Shopware6Client');
- $this->client->setCredentials(
- $this->UserName,
- $this->Password,
- $this->ShopUrl
- );
- }
-
- /**
- * @return array
- */
- public function EinstellungenStruktur()
- {
- return
- [
- 'ausblenden' => ['abholmodus' => ['ab_nummer']],
- 'functions' => ['exportartikelbaum','getarticlelist','updatezahlungsstatus'],
- 'felder' => [
- 'protocol' => [
- 'typ' => 'checkbox',
- 'bezeichnung' => '{|Protokollierung im Logfile|}:',
- ],
- 'shopwareUserName' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Benutzername|}:',
- 'size' => 40,
- ],
- 'shopwarePassword' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Passwort|}:',
- 'size' => 40,
- ],
- 'shopwareUrl' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Shop API URL|}:',
- 'size' => 40,
- ],
- 'shopwareDefaultManufacturer' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Standard Hersteller|}:',
- 'size' => 40,
- 'default' => 'Keine Herstellerinformation',
- ],
- 'shopwareAllowCreateManufacturer' => [
- 'typ' => 'checkbox',
- 'bezeichnung' => '{|Bei Artikelexport Hersteller anlegen|}:',
- ],
- 'shopwareDefaultRuleName' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Name der Standardpreisgruppe|}:',
- 'size' => 40,
- 'default' => 'All customers',
- ],
- 'shopwarePropertyOption' => [
- 'heading' => '{|Eigenschaften / Freifeld Zuordnung|}',
- 'typ' => 'select',
- 'bezeichnung' => '{|Xentral Artikel Eigenschaften|}:',
- 'size' => 40,
- 'default' => 'toProperties',
- 'optionen' => ['toProperties' => '{|Shopware Eigenschaften|}', 'toCustomFields' => '{|Shopware Zusatzfelder|}', 'doNotExport' => '{|Nicht übertragen|}']
- ],
- 'shopwareFreeFieldOption' => [
- 'typ' => 'select',
- 'bezeichnung' => '{|Xentral Artikel Freifelder|}:',
- 'size' => 40,
- 'default' => 'toCustomFields',
- 'optionen' => ['toProperties' => '{|Shopware Eigenschaften|}', 'toCustomFields' => '{|Shopware Zusatzfelder|}', 'doNotExport' => '{|Nicht übertragen|}']
- ],
- 'shopwareDefaultSalesChannel' => [
- 'heading' => '{|Artikelexport Standardeinstellungen|}',
- 'typ' => 'text',
- 'bezeichnung' => '{|Standard Sichtbarkeit|}:',
- 'size' => 40
- ],
- 'shopwareMediaFolder' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Media Folder für Artikelbilder|}:',
- 'size' => 40,
- 'default' => 'Product Media'
- ],
- 'statesToFetch' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Abzuholender Bestellstatus|}:',
- 'size' => 40,
- 'default' => 'open',
- 'col' => 2,
- 'info' => '
Erlaubte Werte: open;in_progress;completed;cancelled'
- ],
- 'deliveryStatesToFetch' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Eingrenzen auf Lieferstatus|}:',
- 'size' => 40,
- 'default' => '',
- 'col' => 2,
- 'info' => '
Erlaubte Werte: open;shipped_partially;shipped;returned;returned_partially;cancelled'
- ],
- 'transactionStatesToFetch' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Eingrenzen auf Bezahlstatus|}:',
- 'size' => 40,
- 'default' => '',
- 'col' => 2,
- 'info' => '
Erlaubte Werte: open;paid;authorized;paid_partially;refunded;refunded_partially;reminded;cancelled'
- ],
- 'salesChannelToFetch' => [
- 'typ' => 'text',
- 'bezeichnung' => '{|Eingrenzen auf Sales Channel|}:',
- 'size' => 40,
- 'default' => '',
- 'col' => 2,
- 'info' => '
Klicke auf "Verbindung prüfen" um die verfügbaren Channels (bitte die Id verwenden) anzuzeigen.'
- ],
- 'orderSearchLimit' => [
- 'typ' => 'select',
- 'bezeichnung' => '{|Anzahl Aufträge abholen|}:',
- 'optionen' => [
- '25' => '25',
- '50' => '50',
- '75' => '75',
- '100' => '100',
- ],
- 'default' => '25',
- 'col' => 2
- ],
- ],
- ];
- }
-
- public function ImportUpdateZahlungsstatus()
- {
- $tmp = $this->CatchRemoteCommand('data');
- $auftrag = $tmp['auftrag'];
-
- $transactions = $this->shopwareRequest('GET', 'order/'.$auftrag.'/transactions');
- $transactionId = $transactions['data'][0]['id'];
-
- if(empty($transactionId)){
- return;
- }
-
- $response = $this->shopwareRequest('POST', '_action/order_transaction/'.$transactionId.'/state/paid');
- if (!empty($response['id'])) {
- return 'ok';
- }
- }
-
- public function ImportSendArtikelbaum(){
- $xentralCategoryTree = [];
- $this->app->erp->GetKategorienbaum($xentralCategoryTree, 0, 0, $this->shopid);
-
- $xentralCategoryIdToParentId = [];
- foreach ($xentralCategoryTree as $key => $value) {
- $xentralCategoryTree[$key]['erledigt'] = false;
- $xentralCategoryTree[$key]['shopid'] = '';
- $xentralCategoryTree[$key]['aktiv'] = false;
- $xentralCategoryIdToParentId[$value['id']] = $key;
- }
-
- $parentCategoryId = null;
- foreach ($xentralCategoryTree as $index => $categoryData) {
- $this->createCategoryTree($index, $xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId);
- }
- }
-
- protected function createCategoryTree($id, &$xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId)
- {
- $parentId = $parentCategoryId;
- if ($xentralCategoryTree[$id]['parent']) {
- $parentId = $xentralCategoryTree[$xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']]]['shopid'];
- }
- if ($xentralCategoryTree[$id]['parent'] && !$xentralCategoryTree[$xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']]]['erledigt']) {
- $this->createCategoryTree($xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']], $xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId);
- }
- $xentralCategoryTree[$id]['erledigt'] = true;
-
- $categoryName = $xentralCategoryTree[$id]['bezeichnung'];
- $searchdata = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'category.name',
- 'type' => 'equals',
- 'value' => $categoryName
- ],
- [
- 'field' => 'category.parentId',
- 'type' => 'equals',
- 'value' => $parentId
- ]
- ]
- ];
-
- $categoriesInShop = $this->shopwareRequest('POST', 'search/category', $searchdata);
-
- $categoryId = '';
- if (!empty($categoriesInShop['data'])) {
- $categoryId = $categoriesInShop['data'][0]['id'];
- }
-
- if (!$categoryId) {
- $categoryData = [
- 'parentId' => $parentId,
- 'name' => $categoryName
- ];
- $result = $this->shopwareRequest('POST', 'category?_response=true', $categoryData);
- if ($result['data']['id']) {
- $categoryId = $result['data']['id'];
- }
- }
-
- if ($categoryId) {
- $xentralCategoryTree[$id]['shopid'] = $categoryId;
- }
- }
-
- /**
- * @return int
- */
- public function ImportSendListLager()
- {
- $tmp = $this->CatchRemoteCommand('data');
-
- $count = 0;
- foreach ($tmp as $article) {
- $artikel = $article['artikel'];
- if ($artikel === 'ignore') {
- continue;
- }
- $nummer = $article['nummer'];
- $fremdnummer = $article['fremdnummer'];
- if (!empty($fremdnummer)) {
- $nummer = $fremdnummer;
- }
- $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer);
-
- if (empty($articleInfo['data'][0]['id'])) {
- $this->Shopware6Log('Artikel wurde nicht im Shop gefunden: ' . $nummer, $articleInfo);
- continue;
- }
- if(empty($articleInfo['data'][0]['customFields'])
- || empty($articleInfo['data'][0]['customFields']['wawision_shopimporter_syncstate'])){
- $this->addSyncCustomFieldToProduct((string)$articleInfo['data'][0]['id']);
- }
-
- $active = true;
- if ($article['inaktiv']) {
- $active = false;
- }
-
- $stock = $article['anzahl_lager'];
- if (!empty($article['pseudolager'])) {
- $stock = $article['pseudolager'];
- }
- $stock = $this->getCorrectedStockFromAvailable($active, (int)$stock, $articleInfo);
- $data = [
- 'stock' => $stock,
- 'active' => $active,
- ];
- $response = $this->shopwareRequest('PATCH', 'product/' . $articleInfo['data'][0]['id'], $data);
- $this->Shopware6Log('Lagerbestand konnte nicht uebertragen werden fuer Artikel: ' . $nummer, $response);
- $count++;
- }
-
- return $count;
- }
-
- /**
- * @param bool $isStockActive
- * @param int $stock
- * @param array|null $articleInfo
- *
- * @return int
- */
- public function getCorrectedStockFromAvailable(bool $isStockActive, int $stock, ?array $articleInfo): int
- {
- if(!$isStockActive) {
- return $stock;
- }
- if(empty($articleInfo)) {
- return $stock;
- }
- if(!isset($articleInfo['data'][0]['attributes']['availableStock'])) {
- return $stock;
- }
- if(!isset($articleInfo['data'][0]['attributes']['availableStock'])) {
- return $stock;
- }
- $reserved = (int)$articleInfo['data'][0]['attributes']['stock']
- - (int)$articleInfo['data'][0]['attributes']['availableStock'];
- if($reserved <= 0) {
- return $stock;
- }
-
- return $stock + $reserved;
- }
-
- /**
- * @param string $message
- * @param mixed $dump
- */
- public function Shopware6Log($message, $dump = '')
- {
- if ($this->protocol) {
- $this->app->erp->Logfile($message, print_r($dump, true));
- }
- }
-
- /**
- * @return int
- */
- public function ImportSendList()
- {
- $articleList = $this->CatchRemoteCommand('data');
-
- $successCounter = 0;
- foreach ($articleList as $article) {
- $number = $article['nummer'];
- $articleInfo = $this->shopwareRequest(
- 'GET',
- sprintf('product?filter[product.productNumber]=%s', $number)
- );
- $articleIdShopware = '';
- if (!empty($articleInfo['data'][0]['id'])) {
- $articleIdShopware = $articleInfo['data'][0]['id'];
- }
-
- $quantity = $article['anzahl_lager'];
- if (!empty($article['pseudolager'])) {
- $quantity = $article['pseudolager'];
- }
- $inaktiv = $article['inaktiv'];
- $active = true;
- if (!empty($inaktiv)) {
- $active = false;
- }
- $quantity = $this->getCorrectedStockFromAvailable($active, (int)$quantity, $articleInfo);
- $taxRate = (float)$article['steuersatz'];
-
- $taxId = $this->getTaxIdByRate($taxRate);
-
- $mediaToAdd = $this->mediaToExport($article, $articleIdShopware);
-
- $categoriesToAdd = [];
- if($this->exportCategories){
- $categoriesToAdd = $this->categoriesToExport($article, $articleIdShopware);
- }
-
- $propertiesToAdd = $this->propertiesToExport($article, $articleIdShopware);
-
- $crosselingToAdd = $this->crosssellingToExport($article, $articleIdShopware);
-
- $systemFieldsToAdd = $this->systemFieldsToExport($article, $articleIdShopware);
-
- $deliveryTimeId = null;
- if(!empty($article['lieferzeitmanuell'])){
- $deliveryTimeId = $this->getDeliveryTimeId($article['lieferzeitmanuell']);
- }
-
- if (empty($systemFieldsToAdd['visibilities']) && !empty($this->shopwareDefaultSalesChannel)) {
- $systemFieldsToAdd['visibilities'] = $this->modifySalesChannel(explode(',', $this->shopwareDefaultSalesChannel), $articleIdShopware);
- }
-
- if(empty($systemFieldsToAdd['unitId']) && !empty($article['einheit']) ){
- $systemFieldsToAdd['unitId'] = $this->unitToAdd($article['einheit']);
- }
-
-
- //Hersteller in Shopware suchen bzw. Anlegen
- $manufacturerName = $article['hersteller'];
- $manufacturerId = $this->getManufacturerIdByName($manufacturerName);
-
- if ($manufacturerId === null && $this->createManufacturerAllowed === true) {
- $manufacturerId = $this->createManufacturer($manufacturerName);
- }
-
- if (empty($manufacturerId)) {
- return 'error: Für den Artikelexport ist die Herstellerinformation zwingend erforderlich';
- }
-
- $isCloseOut = false;
- if(!empty($article['restmenge'])){
- $isCloseOut = true;
- }
-
- $description = $this->prepareDescription($article['uebersicht_de']);
- $ean = $article['ean'];
- $metaTitle = $article['metatitle_de'];
- $metaDescription = $article['metadescription_de'];
- $metaKeywords = $article['metakeywords_de'];
-
- $manufacturerNumber = $article['herstellernummer'];
- if (empty($manufacturerNumber)) {
- $manufacturerNumber = '';
- }
-
- $weight = (float)$article['gewicht'];
- $length = (float)$article['laenge'] * 10;
- $height = (float)$article['hoehe'] * 10;
- $width = (float)$article['breite'] * 10;
-
- $purchasePrice = (float)$article['einkaufspreis'];
-
- $currencyId = $this->findCurrencyId($article['waehrung']);
- $price = [
- 'net' => $article['preis'],
- 'gross' => $article['bruttopreis'],
- 'currencyId' => $currencyId,
- 'linked' => true];
-
- if (!empty($article['pseudopreis'])) {
- $price['listPrice'] = [
- 'currencyId' => $currencyId,
- 'gross' => $article['pseudopreis'],
- 'linked' => true,
- 'net' => $article['pseudopreis']/(1+$taxRate/100)
- ];
- }
-
- $data = [
- 'name' => $article['name_de'],
- 'isCloseout' => $isCloseOut,
- 'productNumber' => $number,
- 'manufacturerId' => $manufacturerId,
- 'stock' => (int)$quantity,
- 'taxId' => $taxId,
- 'active' => $active,
- 'description' => $description,
- 'ean' => $ean,
- 'metaTitle' => $metaTitle,
- 'metaDescription' => $metaDescription,
- 'keywords' => $metaKeywords,
- 'manufacturerNumber' => $manufacturerNumber,
- 'length' => $length,
- 'width' => $width,
- 'height' => $height,
- 'weight' => $weight,
- 'purchasePrice' => $purchasePrice,
- 'price' => [$price],
- 'categories' => $categoriesToAdd,
- 'properties' => $propertiesToAdd,
- 'crossSellings' => $crosselingToAdd,
- 'media' => $mediaToAdd,
- 'deliveryTimeId' => $deliveryTimeId
- ];
-
- $data = array_merge($data, $systemFieldsToAdd);
- if(empty($data['customFields'])
- || empty($data['customFields']['wawision_shopimporter_syncstate'])){
- $data['customFields']['wawision_shopimporter_syncstate'] = 1;
- }
-
- if (empty($articleIdShopware)) {
- $result = $this->shopwareRequest('POST',
- 'product?_response=true', $data);
- if (!empty($result['data']['id'])) {
- $articleIdShopware = $result['data']['id'];
- $articleInfo['data'][0] = $result['data'];
- }
- } else {
- $headerInformation = [];
- $languageId = $this->getLanguageIdByCountryIso('DE');
- if (!empty($languageId)) {
- $headerInformation[] = 'sw-language-id: ' . $languageId;
- }
- $result = $this->shopwareRequest('PATCH',
- sprintf('product/%s?_response=true', $articleIdShopware), $data, $headerInformation);
- }
-
- if(!empty($articleIdShopware)){
- $this->exportTranslationsForArticle($article, $articleIdShopware);
- }
-
- $this->addCoverImage($article, $articleIdShopware);
-
- if (empty($result['data']) || is_array($result['errors'])) {
- $this->Shopware6Log('Artikelexport fehlgeschlagen', ['data:' => $data, 'response' => $result]);
- continue;
- }
-
- $this->exportSeoUrls($article, $articleIdShopware);
-
- $this->exportVariants($article, $articleIdShopware, $currencyId);
-
- if (empty($result['data']) || is_array($result['errors'])) {
- $this->Shopware6Log('Artikelexport bei Bildübertragung fehlgeschlagen', ['data:' => $data, 'response' => $result]);
- continue;
- }
-
- $defaultPrices = $this->getPricesFromArray($article['staffelpreise_standard'] ?? []);
- $groupPrices = $this->getPricesFromArray($article['staffelpreise_gruppen'] ?? []);
-
- if (!empty($defaultPrices) || !empty($groupPrices)) {
- $this->deleteOldBulkPrices($articleIdShopware);
- }
- if (!empty($defaultPrices)) {
- foreach ($defaultPrices as $priceData) {
- $this->exportBulkPriceForGroup($articleIdShopware, $this->defaultRuleName, $priceData);
- }
- }
- if (!empty($groupPrices)) {
- foreach ($groupPrices as $priceData) {
- $this->exportBulkPriceForGroup($articleIdShopware, $priceData->getGroupName(), $priceData);
- }
- }
-
- $successCounter++;
- }
-
- return $successCounter;
- }
-
- protected function exportBulkPriceForGroup(string $productId, string $groupName, PriceData $priceData): void
- {
- $currencyId = $this->findCurrencyId($priceData->getCurrency());
-
- $groupRuleId = $this->client->getGroupRuleId($groupName);
- if (empty($groupRuleId)) {
- $this->Shopware6Log("Fehler: Gruppe {$groupName} konnte im Shop nicht gefunden werden");
- return;
- }
-
- $result = $this->client->saveBulkPrice($productId, $groupRuleId, $currencyId, $priceData);
- if (empty($result['data'])) {
- $this->Shopware6Log("Fehler: Staffelpreis für Gruppe {$groupName} konnte nicht exportiert werden", $result);
- }
- }
-
- /**
- * @param string $deliveryTimeText
- *
- * @return string|null
- */
- protected function getDeliveryTimeId(string $deliveryTimeText): ?string
- {
- $searchCommand = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'name',
- 'type' => 'equals',
- 'value' => $deliveryTimeText
- ]
- ]
- ];
- $result = $this->shopwareRequest('POST', 'search/delivery-time', $searchCommand);
-
- if (empty($result['data'][0]['id'])) {
- return null;
- }
-
- return $result['data'][0]['id'];
- }
-
- /**
- * @param string $description
- * @return string
- */
- protected function prepareDescription($description): string
- {
- $markupSubstitute = [
- '/"/' => '"',
- '/<([^&]+)>/' => '<\1>',
- '/\\
/' => '',
- '/\\<\/strong>/' => ' ',
- '/\\/' => '',
- '/\\<\/em>/' => ' ',
- '/&/' => '&',
- ];
-
- return (string)preg_replace(array_keys($markupSubstitute), array_values($markupSubstitute), $description);
- }
-
- /**
- * @param array $article
- * @param string $articleIdShopware
- */
- protected function exportTranslationsForArticle(array $article, string $articleIdShopware): void
- {
- $customFieldsToAdd = $this->customFieldsToExport($article, $articleIdShopware);
-
- $preparedTranslations = [];
- $preparedTranslations['DE'] = [
- 'name' => $article['name_de'],
- 'description' => $this->prepareDescription($article['uebersicht_de']),
- 'metaTitle' => $article['metatitle_de'],
- 'metaDescription' => $article['metadescription_de'],
- 'keywords' => $article['metakeywords_de'],
- 'customFields' => []
- ];
- if(!empty($customFieldsToAdd['DE'])){
- $preparedTranslations['DE']['customFields'] = $customFieldsToAdd['DE'];
- }
- $preparedTranslations['GB'] = [
- 'name' => $article['name_en'],
- 'description' => $this->prepareDescription($article['uebersicht_en']),
- 'metaTitle' => $article['metatitle_en'],
- 'metaDescription' => $article['metadescription_en'],
- 'keywords' => $article['metakeywords_en'],
- 'customFields' => [],
- ];
- if(!empty($customFieldsToAdd['GB'])){
- $preparedTranslations['GB']['customFields'] = $customFieldsToAdd['GB'];
- }
- foreach ($article['texte'] as $translation) {
- if ($translation['sprache'] === 'EN') {
- $translation['sprache'] = 'GB';
- }
- $preparedTranslations[$translation['sprache']] = [
- 'name' => $translation['name'],
- 'description' => $this->prepareDescription($translation['beschreibung_online']),
- 'metaTitle' => $translation['meta_title'],
- 'metaDescription' => $translation['meta_description'],
- 'keywords' => $translation['meta_keywords'],
- ];
- if(!empty($customFieldsToAdd[$translation['sprache']])){
- $preparedTranslations[$translation['sprache']]['customFields'] = $customFieldsToAdd[$translation['sprache']];
- }
- }
-
- foreach ($preparedTranslations as $countryIsoCode => $translation) {
- $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
- if (empty($languageId)) {
- $this->Shopware6Log('Language Id not found for country: ' . $countryIsoCode);
- continue;
- }
-
- $headerInformation = ['sw-language-id: ' . $languageId];
- $this->shopwareRequest(
- 'PATCH',
- sprintf('product/%s', $articleIdShopware),
- $translation, $headerInformation
- );
- }
- }
-
- /**
- * @param string $countryIso
- *
- * @return string|null
- */
- protected function getLanguageIdByCountryIso(string $countryIso): ?string
- {
- if(array_key_exists($countryIso, $this->knownShopLanguageIds)){
- return $this->knownShopLanguageIds[$countryIso];
- }
-
- $searchCommand = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'country.iso',
- 'type' => 'equals',
- 'value' => $countryIso
- ]
- ]
- ];
- $countryInformation = $this->shopwareRequest('POST', 'search/country', $searchCommand);
-
- foreach ($countryInformation['data'] as $country){
- $searchCommand = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'locale.territory',
- 'type' => 'equals',
- 'value' => $country['attributes']['name']
- ]
- ]
- ];
- $localeInformation = $this->shopwareRequest('POST', 'search/locale', $searchCommand);
- foreach ($localeInformation['data'] as $locale) {
- $searchCommand = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'language.localeId',
- 'type' => 'equals',
- 'value' => $locale['id']
- ]
- ]
- ];
- $languageInformation = $this->shopwareRequest('POST', 'search/language', $searchCommand);
- if (!empty($languageInformation['data'][0]['id'])) {
- $this->knownShopLanguageIds[$countryIso] = $languageInformation['data'][0]['id'];
- return $languageInformation['data'][0]['id'];
- }
- }
- }
- $this->knownShopLanguageIds[$countryIso] = null;
-
- return null;
- }
-
- /**
- * @param string $manufacturerName
- *
- * @return null|string
- */
- protected function createManufacturer(string $manufacturerName): ?string
- {
- $data = ['name' => $manufacturerName];
- $response = $this->shopwareRequest('POST', 'product-manufacturer?_response=true', $data);
-
- $manufacturerId = null;
- if(!empty($response['data']['id'])){
- $manufacturerId = $response['data']['id'];
- $this->knownManufacturerIds[$manufacturerName] = $manufacturerId;
- }
-
- return $manufacturerId;
- }
-
- /**
- * @param string $manufacturerName
- *
- * @return null|string
- */
- protected function getManufacturerIdByName(string $manufacturerName): ?string
- {
- if (!empty($this->knownManufacturerIds[$manufacturerName])) {
- return $this->knownManufacturerIds[$manufacturerName];
- }
-
- $manufacturerId = null;
- if (empty($manufacturerName)) {
- $manufacturerName = $this->defaultManufacturer;
- }
- $manufacturer = $this->shopwareRequest(
- 'GET',
- 'product-manufacturer?filter[product_manufacturer.name]=' . urlencode($manufacturerName)
- );
- $manufacturerId = $manufacturer['data'][0]['id'];
- $this->knownManufacturerIds[$manufacturerName] = $manufacturerId;
-
- return $manufacturerId;
- }
-
- /**
- * @param float $taxRate
- *
- * @return string
- */
- protected function getTaxIdByRate(float $taxRate): string{
- if(empty($this->taxesInShop)){
- $this->taxesInShop = $this->shopwareRequest('GET', 'tax');
- }
- foreach ($this->taxesInShop['data'] as $taxData) {
- if (abs(($taxData['attributes']['taxRate']-$taxRate)) < 0.0001 ) {
- return $taxData['id'];
- }
- }
-
- return $this->taxesInShop['data'][0]['id'];
- }
-
- /**
- * @param array $internalArticleData
- * @param string $articleIdShopware
- *
- * @return array
- */
- protected function mediaToExport($internalArticleData, $articleIdShopware)
- {
- $mediaToAdd = [
- ];
-
- if (empty($internalArticleData['Dateien'])) {
- return $mediaToAdd;
- }
- $internalMediaIds = [];
-
- $searchdata = [
- 'limit' => 1,
- 'filter' => [
- [
- 'field' => 'name',
- 'type' => 'equals',
- 'value' => $this->shopwareMediaFolder
- ]
- ]
- ];
- $mediaFolderData = $this->shopwareRequest('POST', 'search/media-folder', $searchdata);
- if(empty($mediaFolderData['data'][0]['id'])){
- $this->Shopware6ErrorLog('Kein Media Folder gefunden für: ', $this->shopwareMediaFolder);
- return [];
- }
-
- $mediaFolderId = $mediaFolderData['data'][0]['id'];
-
- foreach ($internalArticleData['Dateien'] as $internalFile) {
- $filename = explode('.', $internalFile['filename']);
- unset($filename[(!empty($filename)?count($filename):0) - 1]);
- $filename = $internalFile['id'].'_'.implode($filename);
- $extension = $internalFile['extension'];
- $imageTitle = (string)$internalFile['titel'];
- $imageAltText = (string)$internalFile['beschreibung'];
- $accessToken = $this->shopwareToken();
-
- $searchdata = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'media.fileName',
- 'type' => 'equals',
- 'value' => $filename
- ]
- ]
- ];
- $mediaData = $this->shopwareRequest('POST', 'search/media', $searchdata);
- if (!empty($mediaData['data'][0]['id'])) {
- $internalMediaIds[] = $mediaData['data'][0]['id'];
- if($mediaData['data'][0]['attributes']['title'] !== $imageTitle
- || $mediaData['data'][0]['attributes']['alt'] !== $imageAltText){
- $this->setMediaTitleAndAltText($mediaData['data'][0]['id'], $imageTitle, $imageAltText);
- }
- continue;
- }
-
- $mediaData = $this->shopwareRequest('POST', 'media?_response=true', []);
- if(empty($mediaData['data']['id'])){
- $this->Shopware6Log('Error when creating media for sku: ' . $internalArticleData['nummer'],
- ['mediaData' => $mediaData, 'title' => $imageTitle, 'text' => $imageAltText]);
- continue;
- }
- $mediaId = $mediaData['data']['id'];
- $this->setMediaTitleAndAltText($mediaId, $imageTitle, $imageAltText);
-
- $mediaAssociationData = [
- [
- 'action' => 'upsert',
- 'entity' => 'media',
- 'payload' => [
- [
- 'id' => $mediaId,
- 'mediaFolderId' => $mediaFolderId
- ]
- ]
- ]
- ];
- $this->shopwareRequest('POST', '_action/sync?_response=true', $mediaAssociationData);
-
- $url = $this->ShopUrl . 'v2/_action/media/' . $mediaId . '/upload?extension=' . $extension . '&fileName=' . $filename;
- $ch = curl_init();
- $setHeaders = [
- 'Content-Type:image/' . $extension,
- 'Authorization:Bearer ' . $accessToken['token']
- ];
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POSTFIELDS, base64_decode($internalFile['datei']));
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
- curl_setopt($ch, CURLOPT_HTTPHEADER, $setHeaders);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_exec($ch);
-
- $internalMediaIds[] = $mediaId;
- }
-
- $existingMediaConnection = [];
- if (!empty($articleIdShopware)) {
- $existingMediaConnection = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/media?limit=100');
- foreach ($existingMediaConnection['data'] as $existingConnection) {
- if (!in_array($existingConnection['attributes']['mediaId'], $internalMediaIds, false)) {
- $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/media/' . $existingConnection['id']);
- }
- }
- }
-
- $alreadyAddedMediaIDs = [];
- if (!empty($existingMediaConnection)) {
- foreach ($existingMediaConnection['data'] as $existingConnection) {
- $alreadyAddedMediaIDs[$existingConnection['attributes']['mediaId']] = $existingConnection['id'];
- }
- }
- $position = 0;
- foreach ($internalMediaIds as $mediaId) {
- $mediaDataSet = [
- 'mediaId' => $mediaId,
- 'position' => $position
- ];
- if (array_key_exists($mediaId, $alreadyAddedMediaIDs)) {
- $mediaDataSet['id'] = $alreadyAddedMediaIDs[$mediaId];
- }
- $mediaToAdd[] = $mediaDataSet;
- $position++;
- }
-
- return $mediaToAdd;
- }
-
- /**
- * @param string $mediaId
- * @param string $title
- * @param string $altText
- */
- protected function setMediaTitleAndAltText(string $mediaId, string $title, string $altText): void
- {
- $this->shopwareRequest('PATCH', 'media/' . $mediaId,
- ['title' => $title,
- 'alt' => $altText
- ]
- );
- }
-
- /**
- * @param array $articleInXentral
- * @param string $articleIdShopware
- */
- protected function addCoverImage($articleInXentral, $articleIdShopware){
- if(empty($articleIdShopware)){
- return;
- }
- if(empty($articleInXentral['Dateien'])){
- return;
- }
- $existingMediaConnection = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/media?limit=100');
- if(empty($existingMediaConnection['data'])){
- return;
- }
- foreach ($articleInXentral['Dateien'] as $xentralFile) {
- $filename = explode('.', $xentralFile['filename']);
- unset($filename[(!empty($filename)?count($filename):0) - 1]);
- $filename = $xentralFile['id'].'_'.implode($filename);
-
- $searchdata = [
- 'limit' => 5,
- 'filter' => [
- [
- 'field' => 'media.fileName',
- 'type' => 'equals',
- 'value' => $filename
- ]
- ]
- ];
- $mediaData = $this->shopwareRequest('POST', 'search/media', $searchdata);
- $mediaId = $mediaData['data'][0]['id'];
-
- foreach ($existingMediaConnection['data'] as $mediaConnection){
- if($mediaId === $mediaConnection['attributes']['mediaId']){
-
- $this->shopwareRequest('PATCH',
- sprintf('product/%s?_response=true', $articleIdShopware),['coverId' => $mediaConnection['id']]);
- return;
- }
- }
- }
- }
-
- /**
- * @param array $articleInXentral
- * @param string $articleIdShopware
- * @return array
- */
- protected function categoriesToExport($articleInXentral, $articleIdShopware)
- {
- $categoryName = $articleInXentral['kategoriename'];
- $categoryTree = $articleInXentral['kategorien'];
-
- $categoriesToAdd = [];
- if (empty($categoryName) && empty($categoryTree)) {
- return $categoriesToAdd;
- }
-
- $categoriesInXentral = [];
- if (!empty($categoryTree)) {
- $rootcategory = null;
- $categoryTreeid = [];
- foreach ($categoryTree as $categoryData) {
- $categoryData['shopwareparent'] = 0;
- if (!$categoryData['parent']) {
- $categoryData['shopwareid'] = $rootcategory;
- }
- $categoryTreeid[$categoryData['id']] = $categoryData;
- }
-
- foreach ($categoryTree as $categoryData) {
- $parentid = $rootcategory;
- if (!empty($categoryData['parent'])) {
- $parentid = $this->getCategoryParentId($categoryData, $categoryTreeid);
- }
-
- $searchdata = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'category.name',
- 'type' => 'equals',
- 'value' => $categoryData['name']
- ]
- ]
- ];
- if (!empty($parentid)) {
- $searchdata['filter'][] = [
- 'field' => 'category.parentId',
- 'type' => 'equals',
- 'value' => $parentid
- ];
- }
- $result = $this->shopwareRequest('POST', 'search/category', $searchdata);
-
-
- if (!empty($result['data'][0]['id'])) {
- $categoryTreeid[$categoryData['id']]['shopwareid'] = $result['data'][0]['id'];
- $categoriesInXentral[] = $result['data'][0]['id'];
- }
- }
- } else if (!empty($categoryName)) {
- $searchdata = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'category.name',
- 'type' => 'equals',
- 'value' => $categoryName
- ]
- ]
- ];
-
- $result = $this->shopwareRequest('POST', 'search/category', $searchdata);
-
- if (!empty($result['data'][0]['id'])) {
- $categoriesInXentral[] = $result['data'][0]['id'];
- }
- }
-
- if (!empty($articleIdShopware)) {
- $existingCategories = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/categories?limit=50');
- foreach ($existingCategories['data'] as $existingCategory) {
- if (!in_array($existingCategory['id'], $categoriesInXentral, false)) {
- $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/categories/' . $existingCategory['id']);
- }
- }
- }
- foreach ($categoriesInXentral as $categoryId) {
- $categoriesToAdd[] = ['id' => $categoryId];
- }
-
-
- return $categoriesToAdd;
- }
-
- /**
- * @param $categoryData
- * @param $categoryTreeId
- * @return string|null
- */
- protected function getCategoryParentId($categoryData, &$categoryTreeId)
- {
- $parentId = $categoryTreeId[$categoryData['parent']]['shopwareid'];
- if (!empty($parentId)) {
- return $parentId;
- }
-
- $parentCategoryData = $this->app->DB->SelectRow("SELECT id,parent,bezeichnung AS name FROM artikelkategorien WHERE id<>'' AND id<>'0' AND id='" . $categoryData['parent'] . "' LIMIT 1");
- if (empty($parentCategoryData)) {
- return null;
- }
-
- $searchData = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'category.name',
- 'type' => 'equals',
- 'value' => $parentCategoryData['name']
- ]
- ]
- ];
- $result = $this->shopwareRequest('POST', 'search/category', $searchData);
-
- if (count($result['data']) < 1) {
- return null;
- }
-
- if (count($result['data']) === 1) {
- $parentCategoryData['shopwareid'] = $result['data'][0]['id'];
- $categoryTreeId[$parentCategoryData['id']] = $parentCategoryData;
- return $result['data'][0]['id'];
- }
-
- $grandparentId = $this->getCategoryParentId($parentCategoryData, $categoryTreeId);
-
- $searchData = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'category.name',
- 'type' => 'equals',
- 'value' => $parentCategoryData['name']
- ],
- [
- 'field' => 'category.parentId',
- 'type' => 'equals',
- 'value' => $grandparentId
- ]
- ]
- ];
- $result = $this->shopwareRequest('POST', 'search/category', $searchData);
-
-
- if (count($result['data']) === 1) {
- $parentCategoryData['shopwareid'] = $result['data'][0]['id'];
- $categoryTreeId[$parentCategoryData['id']] = $parentCategoryData;
- return $result['data'][0]['id'];
- }
- return null;
- }
-
- /**
- * @param string $propertyName
- *
- * @return string|null
- */
- protected function getPropertyGroupId($propertyName): ?string
- {
- if(array_key_exists($propertyName, $this->knownPropertyGroupIds)){
- return $this->knownPropertyGroupIds[$propertyName];
- }
-
- $searchData = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'property_group.name',
- 'type' => 'equals',
- 'value' => $propertyName
- ]
- ]
- ];
-
- $germanLanguageId = $this->getLanguageIdByCountryIso('DE');
- $headerInformation = ['sw-language-id: ' . $germanLanguageId];
- $propertyData = $this->shopwareRequest(
- 'POST',
- 'search/property-group',
- $searchData,
- $headerInformation);
- if (empty($propertyData['data'][0]['id'])) {
- return null;
- }
-
- $this->knownPropertyGroupIds[$propertyName] = $propertyData['data'][0]['id'];
-
- return $propertyData['data'][0]['id'];
- }
-
- /**
- * @param string $propertyName
- * @return null|string
- */
- protected function createPropertyGroup($propertyName): ?string
- {
- $propertyGroupData = [
- 'displayType' => 'text',
- 'name' => $propertyName,
- 'sortingType' => 'alphanumeric'
- ];
- $propertyGroup = $this->shopwareRequest(
- 'POST',
- 'property-group?_response=true',
- $propertyGroupData);
-
- $this->knownPropertyGroupIds[$propertyName] = $propertyGroup['data']['id'];
-
- if (empty($propertyGroup['data']['id'])) {
- return null;
- }
-
- return $propertyGroup['data']['id'];
- }
-
- /**
- * @param string $propertyGroupId
- * @param string $propertyName
- * @param string $countryIsoCode
- */
- protected function createTranslationForPropertyGroup($propertyGroupId, $propertyName, $countryIsoCode): void
- {
- $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
- if (empty($languageId)) {
- return;
- }
-
- $headerInformation = ['sw-language-id: ' . $languageId];
-
- $translation = [
- 'name' => $propertyName,
- ];
-
- $this->shopwareRequest(
- 'PATCH',
- sprintf('property-group/%s', $propertyGroupId),
- $translation,
- $headerInformation);
- }
-
- /**
- * @param string $propertyGroupId
- * @param string $propertyOptionName
- * @param string $countryIsoCode
- * @return mixed|null
- */
- protected function getPropertyOptionId($propertyGroupId, $propertyOptionName, $countryIsoCode = 'DE'): ?string
- {
- $searchData = [
- 'limit' => 25,
- 'filter' => [
- [
- 'field' => 'property_group_option.name',
- 'type' => 'equals',
- 'value' => $propertyOptionName
- ]
- ]
- ];
- $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
- $headerInformation = ['sw-language-id: ' . $languageId];
- $optionData = $this->shopwareRequest(
- 'POST',
- 'search/property-group/' . $propertyGroupId . '/options',
- $searchData,
- $headerInformation);
-
- if (empty($optionData['data'][0]['id'])) {
- return null;
- }
-
- return $optionData['data'][0]['id'];
- }
-
- /**
- * @param string $propertyGroupId
- * @param string $propertyOptionName
- * @return null|string
- */
- protected function createPropertyOption($propertyGroupId, $propertyOptionName): ?string
- {
- $propertyOptionData = [
- 'id' => '',
- 'name' => $propertyOptionName
- ];
- $createdPropertyOption = $this->shopwareRequest(
- 'POST',
- 'property-group/' . $propertyGroupId . '/options?_response=true',
- $propertyOptionData);
-
- if (empty($createdPropertyOption['data']['id'])) {
- return null;
- }
-
- return $createdPropertyOption['data']['id'];
- }
-
- /**
- * @param string $optionId
- * @param string $optionName
- * @param string $countryIsoCode
- */
- protected function createTranslationForPropertyOption($optionId, $optionName, $countryIsoCode): void
- {
- $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
- if (empty($languageId)) {
- return;
- }
- $headerInformation = ['sw-language-id: ' . $languageId];
- $translation = [
- 'name' => $optionName,
- ];
-
- $this->shopwareRequest(
- 'PATCH',
- sprintf('property-group-option/%s', $optionId),
- $translation,
- $headerInformation);
- }
-
- /**
- * @param array $internalArticle
- * @param string $articleIdShopware
- * @return array
- */
- protected function propertiesToExport($internalArticle, $articleIdShopware): array
- {
- $propertiesToAdd = $this->getPropertiesFromArticle($internalArticle);
- if (empty($propertiesToAdd)) {
- return [];
- }
- $assignedProperties = [];
-
- foreach ($propertiesToAdd as $propertyDefaultName => $countryIsoToPropertyTranslation) {
- if (empty($countryIsoToPropertyTranslation['DE'])) {
- continue;
- }
- $propertyGroupId = '';
- if (array_key_exists($propertyDefaultName, $this->knownPropertyGroupIds)) {
- $propertyGroupId = $this->knownPropertyGroupIds[$propertyDefaultName];
- }
- if (empty($propertyGroupId)) {
- $propertyGroupId = $this->getPropertyGroupId($propertyDefaultName);
- }
- if (empty($propertyGroupId)) {
- $propertyGroupId = $this->createPropertyGroup($propertyDefaultName);
- }
- if (empty($propertyGroupId)) {
- $this->Shopware6Log('PropertyGroup kann nicht erstellt werden: ' . $propertyDefaultName);
- continue;
- }
-
- foreach ($countryIsoToPropertyTranslation as $countryIsoCode => $translation) {
- $this->createTranslationForPropertyGroup($propertyGroupId, $translation['name'], $countryIsoCode);
- }
-
-
- $optionId = $this->getPropertyOptionId($propertyGroupId, $countryIsoToPropertyTranslation['DE']['value'], 'DE');
- if (empty($optionId)) {
- $optionId = $this->createPropertyOption($propertyGroupId, $countryIsoToPropertyTranslation['DE']['value']);
- }
- if (empty($optionId)) {
- $this->Shopware6Log('Option kann nicht erstellt werden: ' . $countryIsoToPropertyTranslation['DE']['value']);
- continue;
- }
-
- $assignedProperties[] = $optionId;
-
- foreach ($countryIsoToPropertyTranslation as $countryIsoCode => $translation) {
- $this->createTranslationForPropertyOption($optionId, $translation['value'], $countryIsoCode);
- }
- }
-
- if (!empty($articleIdShopware)) {
- $existingProperties = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/properties?limit=100');
- foreach ($existingProperties['data'] as $existingProperty) {
- if (!in_array($existingProperty['id'], $assignedProperties, false)) {
- $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/properties/' . $existingProperty['id']);
- }
- }
- }
-
- $propertiesToAdd = [];
- foreach ($assignedProperties as $propertyOptionId) {
- $propertiesToAdd[] = ['id' => $propertyOptionId];
- }
-
- return $propertiesToAdd;
- }
-
- /**
- * @param string $name
- * @param string $value
- * @return bool
- */
- protected function propertyMustBeIgnored(string $name, string $value): bool
- {
- return empty($value) ||
- strpos($name, 'customField_') === 0 ||
- stripos($name, 'shopware6_') !== false;
- }
-
- /**
- * @param array $internalArticleData
- * @return array
- */
- protected function getPropertiesFromArticle($internalArticleData): array
- {
- //'Farbe' => [['DE' => ['name' => 'Farbe, 'value' => 'Gelb']],
- // ['EN' => ['name' => 'Colour, 'value' => 'Yellow']]]
- $propertiesToAdd = [];
- if (!empty($internalArticleData['eigenschaften'])) {
- foreach ($internalArticleData['eigenschaften'] as $property) {
- if ($this->propertyMustBeIgnored($property['name'], $property['values'])) {
- continue;
- }
- if (strpos($property['name'], 'property_') === 0) {
- $propertyName = substr($property['name'], 9);
- $propertiesToAdd[$propertyName]['DE'] = [
- 'name' => $propertyName,
- 'value' => $property['values']];
- continue;
- }
- if ($this->propertyOption === 'toProperties') {
- $propertiesToAdd[$property['name']]['DE'] = [
- 'name' => $property['name'],
- 'value' => $property['values']];
- }
- }
- }
-
- if (!empty($internalArticleData['eigenschaftenuebersetzungen'])) {
- foreach ($internalArticleData['eigenschaftenuebersetzungen'] as $translatedProperty) {
- if ($translatedProperty['language_to'] === 'EN') {
- $translatedProperty['language_to'] = 'GB';
- }
- if ($this->propertyMustBeIgnored($translatedProperty['property_to'], $translatedProperty['property_value_to'])) {
- continue;
- }
- if (strpos($translatedProperty['property_to'], 'property_') === 0) {
- $propertiesToAdd[$translatedProperty['property_from']][$translatedProperty['language_to']] = [
- 'name' => substr($translatedProperty['property_to'], 9),
- 'value' => $translatedProperty['property_value_to']];
- continue;
- }
- if ($this->propertyOption === 'toProperties') {
- $propertiesToAdd[$translatedProperty['property_from']][$translatedProperty['language_to']] = [
- 'name' => $translatedProperty['property_to'],
- 'value' => $translatedProperty['property_value_to']];
- }
- }
- }
-
- if (!empty($internalArticleData['freifelder'])) {
- foreach ($internalArticleData['freifelder']['DE'] as $freeFieldKey => $freeFieldValue) {
- if ($this->propertyMustBeIgnored($freeFieldKey, $freeFieldValue)) {
- continue;
- }
- if (strpos($freeFieldKey, 'property_') === 0) {
- $propertyName = substr($freeFieldKey, 9);
- $propertiesToAdd[$propertyName]['DE'] = [
- 'name' => $propertyName,
- 'value' => $freeFieldValue
- ];
- continue;
- }
- if ($this->freeFieldOption === 'toProperties') {
- $propertiesToAdd[$freeFieldKey]['DE'] = [
- 'name' => $freeFieldKey,
- 'value' => $freeFieldValue
- ];
- }
- }
-
- foreach ($internalArticleData['freifelder'] as $languageIso => $freeFields) {
- if ($languageIso === 'DE') {
- continue;
- }
- if ($languageIso === 'EN') {
- $languageIso = 'GB';
- }
- foreach ($freeFields as $freeFieldData) {
- if ($this->propertyMustBeIgnored($freeFieldData['mapping'], $freeFieldData['wert'])) {
- continue;
- }
- if (strpos($freeFieldData['mapping'], 'property_') === 0) {
- $propertyName = substr($freeFieldData['mapping'], 9);
- $propertiesToAdd[$propertyName][$languageIso] = [
- 'name' => $propertyName,
- 'value' => $freeFieldData['wert']
- ];
- continue;
- }
- if ($this->freeFieldOption === 'toProperties') {
- $propertiesToAdd[$freeFieldData['mapping']][$languageIso] = [
- 'name' => $freeFieldData['mapping'],
- 'value' => $freeFieldData['wert']
- ];
- }
- }
- }
- }
-
- return $propertiesToAdd;
- }
-
- /**
- * @param array $articleInXentral
- * @param string $articleIdShopware
- *
- * @return array
- */
- protected function customFieldsToExport($articleInXentral, $articleIdShopware): array
- {
- $customFieldsToAdd = $this->getCustomFieldsFromArticle($articleInXentral);
- if (empty($customFieldsToAdd)) {
- return [];
- }
- $languageId = $this->getLanguageIdByCountryIso('DE');
- $headerInformation = ['sw-language-id: ' . $languageId];
-
- $customFields = [];
- if (!empty($articleIdShopware)) {
- $articleInfo = $this->shopwareRequest(
- 'GET', 'product/' . $articleIdShopware,
- [],
- $headerInformation);
- $customFields['DE'] = $articleInfo['data'][0]['attributes']['customFields'];
- if ($customFields === null) {
- $customFields = [];
- }
- }
-
- foreach ($customFieldsToAdd as $defaultFieldName => $countryIsoCodeToCustomFieldData) {
- $customFieldDefinition = $this->shopwareRequest(
- 'GET',
- sprintf('custom-field?filter[custom_field.name]=%s', $defaultFieldName),
- [],
- $headerInformation
- );
- if (empty($customFieldDefinition)) {
- $this->Shopware6Log('Freifeld entspricht keinem shopware Freifeld', $defaultFieldName);
- continue;
- }
-
- foreach ($countryIsoCodeToCustomFieldData as $countryIsoCode => $customFieldData) {
- $name = $customFieldData['name'];
- $value = $customFieldData['value'];
- if ($value === '') {
- continue;
- }
- if($countryIsoCode === 'EN'){
- $countryIsoCode = 'GB';
- }
- $fieldType = $customFieldDefinition['data'][0]['attributes']['type'];
- $controlType = $customFieldDefinition['data'][0]['attributes']['config']['componentName'];
-
- switch ($fieldType) {
- case 'text':
- case 'html':
- if ($controlType === 'sw-media-field') {
- $this->Shopware6Log(
- 'Warnung: Freifelder vom Type "medium" werden nicht unterstützt.'
- );
- } else {
- $customFields[$countryIsoCode][$name] = (string)$value;
- }
- break;
- case 'bool':
- $customFields[$countryIsoCode][$name] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
- break;
- case 'int':
- $customFields[$countryIsoCode][$name] = (int)$value;
- break;
- case 'float':
- $customFields[$countryIsoCode][$name] = (float)$value;
- break;
- case 'select':
- $options = $customFieldDefinition['data'][0]['attributes']['config']['options'];
- $allowedValues = [];
- foreach ($options as $option) {
- $allowedValues[] = $option['value'];
- }
- if ($controlType === 'sw-single-select') {
- if (in_array($value, $allowedValues, true)) {
- $customFields[$countryIsoCode][$name] = $value;
- } else {
- $this->Shopware6Log(
- sprintf('Warnung: Freifeld "%s"="%s"; ungültiger Wert', $name, $value),
- ['allowed values' => $allowedValues]
- );
- }
- }
- if ($controlType === 'sw-multi-select') {
- $value = explode(',', $value);
- foreach ($value as &$item) {
- $item = trim($item);
- }
- unset($item);
- if (array_intersect($value, $allowedValues) === $value) {
- $customFields[$countryIsoCode][$name] = $value;
- } else {
- $this->Shopware6Log(
- sprintf('Warnung: Freifeld "%s"; ungültiger Wert', $name),
- ['values' => $value, 'allowed values' => $allowedValues]
- );
- }
- }
- break;
- default:
- $this->Shopware6Log(
- 'Warnung: Freifeld enthält falschen Typ.',
- ['freifeld' => $name, 'wert' => $value]
- );
- continue 2;
- }
- }
- }
-
-
- return $customFields;
- }
-
- /**
- * @param string $name
- * @param string $value
- * @return bool
- */
- protected function customFieldMustBeIgnored(string $name, string $value): bool
- {
- return empty($value) ||
- strpos($name, 'property_') === 0 ||
- stripos($name, 'shopware6_') !== false;
- }
-
- /**
- * @param array $articleInXentral
- * @return array
- */
- protected function getCustomFieldsFromArticle($articleInXentral): array
- {
- $customFieldsToAdd = [];
- if (!empty($articleInXentral['eigenschaften'])) {
- foreach ($articleInXentral['eigenschaften'] as $propertyInXentral) {
- if ($this->customFieldMustBeIgnored($propertyInXentral['name'], $propertyInXentral['values'])) {
- continue;
- }
- if (strpos($propertyInXentral['name'], 'customField_') === 0) {
- $customFieldName = substr($propertyInXentral['name'], 12);
- $customFieldsToAdd[$customFieldName]['DE'] = [
- 'name' => $customFieldName,
- 'value' => $propertyInXentral['values']
- ];
- continue;
- }
- if ($this->propertyOption === 'toCustomFields') {
- $customFieldsToAdd[$propertyInXentral['name']]['DE'] = [
- 'name' => $propertyInXentral['name'],
- 'value' => $propertyInXentral['values']
- ];
- }
- }
- }
- if (!empty($articleInXentral['eigenschaftenuebersetzungen'])) {
- foreach ($articleInXentral['eigenschaftenuebersetzungen'] as $translatedProperty) {
- if ($this->customFieldMustBeIgnored($translatedProperty['property_to'], $translatedProperty['property_value_to'])) {
- continue;
- }
- if (strpos($translatedProperty['property_to'], 'customField_') === 0) {
- $customFieldName = substr($translatedProperty['property_to'], 12);
- $customFieldsToAdd[$customFieldName][$translatedProperty['language_to']] = [
- 'name' => $customFieldName,
- 'value' => $translatedProperty['property_value_to']
- ];
- continue;
- }
- if ($this->propertyOption === 'toCustomFields') {
- $customFieldsToAdd[$translatedProperty['property_to']][$translatedProperty['language_to']] = [
- 'name' => $translatedProperty['property_to'],
- 'value' => $translatedProperty['property_value_to']
- ];
- }
- }
- }
-
- if (!empty($articleInXentral['freifelder'])) {
- foreach ($articleInXentral['freifelder']['DE'] as $freeFieldKey => $freeFieldValue) {
- if ($this->customFieldMustBeIgnored($freeFieldKey, $freeFieldValue)) {
- continue;
- }
- if (strpos($freeFieldKey, 'customField_') === 0) {
- $customFieldName = substr($freeFieldKey, 12);
- $customFieldsToAdd[$customFieldName]['DE'] = [
- 'name' => $customFieldName,
- 'value' => $freeFieldValue
- ];
- continue;
- }
- if ($this->freeFieldOption === 'toCustomFields') {
- $customFieldsToAdd[$freeFieldKey]['DE'] = [
- 'name' => $freeFieldKey,
- 'value' => $freeFieldValue
- ];
- }
- }
-
- foreach ($articleInXentral['freifelder'] as $countryIsoCode => $freeFieldTranslations) {
- if ($countryIsoCode === 'DE') {
- continue;
- }
- foreach ($freeFieldTranslations as $freeFieldTranslation){
- if ($this->customFieldMustBeIgnored($freeFieldTranslation['mapping'], $freeFieldTranslation['wert'])) {
- continue;
- }
- if ($countryIsoCode === 'EN') {
- $countryIsoCode = 'GB';
- }
- if (strpos($freeFieldTranslation['mapping'], 'customField_') === 0) {
- $customFieldName = substr($freeFieldTranslation['mapping'], 12);
- $customFieldsToAdd[$customFieldName][$countryIsoCode] = [
- 'name' => $customFieldName,
- 'value' => $freeFieldTranslation['wert']
- ];
- continue;
- }
- if ($this->freeFieldOption === 'toCustomFields') {
- $customFieldsToAdd[$freeFieldTranslation['mapping']][$countryIsoCode] = [
- 'name' => $freeFieldTranslation['mapping'],
- 'value' => $freeFieldTranslation['wert']
- ];
- }
- }
- }
- }
-
- return $customFieldsToAdd;
- }
-
- /**
- * @param array $articleInXentral
- * @param int $articleIdShopware
- *
- * @return array
- */
- protected function crosssellingToExport($articleInXentral, $articleIdShopware){
- if (empty($articleInXentral['crosssellingartikel'])) {
- return [];
- }
-
- $crosssellingArticles = [];
- foreach ($articleInXentral['crosssellingartikel'] as $crosssellingArticle){
- $type = 'Ähnlich';
- if($crosssellingArticle['art'] == 2){
- $type = 'Zubehör';
- }
- $crosssellingArticles[$type][] = $crosssellingArticle['nummer'];
- }
- $crossselingInformation = [];
- foreach ($crosssellingArticles as $type => $articles){
- if(!empty($articleIdShopware)){
- $existingCrossSellings = $this->shopwareRequest('GET', sprintf('product/%s/cross-sellings/',
- $articleIdShopware));
- if(!empty($existingCrossSellings['data'])){
- foreach ($existingCrossSellings['data'] as $existingCrossSelling){
- if($existingCrossSelling['attributes']['name'] === $type){
- $this->shopwareRequest('DELETE', sprintf('product/%s/cross-sellings/%s/',
- $articleIdShopware, $existingCrossSelling['id']));
- }
- }
- }
- }
-
- $crosselingToAdd = [];
- foreach ($articles as $articleNumber) {
- $articleInfo = $this->shopwareRequest(
- 'GET',
- sprintf('product?filter[product.productNumber]=%s', $articleNumber)
- );
-
- if(empty($articleInfo['data'][0]['id'])){
- continue;
- }
- $crosselingToAdd[] = $articleInfo['data'][0]['id'];
- }
- if(empty($crosselingToAdd)){
- continue;
- }
- $crossselingInformationForType = [
- 'active' => true,
- 'name' => $type,
- 'assignedProducts' => [],
- 'type' => 'productList',
- 'sortBy' => 'name',
- 'limit' => 24,
- 'position' => 1
- ];
- $position = 1;
- foreach ($crosselingToAdd as $articleId){
- $crossselingInformationForType['assignedProducts'][] = [
- 'productId' => $articleId,
- 'position' => $position,
- ];
- $position++;
- }
- $crossselingInformation[] = $crossselingInformationForType;
- }
-
-
- return $crossselingInformation;
- }
-
- /**
- * @param string $unitShortCode
- *
- * @return string
- */
- protected function unitToAdd(string $unitShortCode): string{
- $searchData = [
- 'limit' => 25,
- 'source' => [
- 'id'
- ],
- 'filter' => [
- [
- 'field' => 'unit.shortCode',
- 'type' => 'equals',
- 'value' => $unitShortCode
- ]
- ]
- ];
- $unitInShopware = $this->shopwareRequest(
- 'POST',
- 'search/unit',
- $searchData);
-
- if(!empty($unitInShopware['data'][0]['id'])){
- return $unitInShopware['data'][0]['id'];
- }
-
- $query = sprintf("SELECT `internebemerkung` FROM `artikeleinheit` WHERE `einheit_de` = '%s' LIMIT 1",
- $unitShortCode);
- $unitName = $this->app->DB->Select($query);
- if(empty($unitName)){
- $unitName = $unitShortCode;
- }
-
- $unitInformation = [
- 'name' => $unitName,
- 'shortCode' => $unitShortCode
- ];
- $result = $this->shopwareRequest('POST', 'unit?_response=true', $unitInformation);
-
- if(empty($result['data']['id'])){
- return '';
- }
-
- return $result['data']['id'];
- }
-
- /**
- * @param array $internArticle
- * @param int $articleIdShopware
- *
- * @return array
- */
- protected function systemFieldsToExport($internArticle, $articleIdShopware): array
- {
- $internalSpecialFields = [];
- foreach ($internArticle['freifelder']['DE'] as $freeFieldName => $freeFieldValue) {
- if (stripos($freeFieldName, 'shopware6_') !== false) {
- $internalSpecialFields[$freeFieldName] = $freeFieldValue;
- }
- }
- foreach ($internArticle['eigenschaften'] as $property) {
- if (stripos($property['name'], 'shopware6_') !== false) {
- $internalSpecialFields[$property['name']] = $property['values'];
- }
- }
-
- $systemFields = [];
- foreach ($internalSpecialFields as $fieldName => $fieldValue) {
- switch (strtolower($fieldName)) {
- case 'shopware6_sales_channel':
- $systemFields['visibilities'] = $this->modifySalesChannel(explode(',', $fieldValue), $articleIdShopware);
- break;
- case 'shopware6_purchase_unit':
- $systemFields['purchaseUnit'] = (float)str_replace(',', '.', $fieldValue);
- break;
- case 'shopware6_reference_unit':
- $systemFields['referenceUnit'] = (float)str_replace(',', '.', $fieldValue);
- break;
- case 'shopware6_unit':
- $systemFields['unitId'] = $this->unitToAdd($fieldValue);
- break;
- case 'shopware6_pack_unit':
- $systemFields['packUnit'] = (string)$fieldValue;
- break;
- case 'shopware6_restock_time':
- $systemFields['restockTime'] = (int)$fieldValue;
- break;
- case 'shopware6_pack_unit_plural':
- $systemFields['packUnitPlural'] = (string)$fieldValue;
- break;
- }
- }
-
- return $systemFields;
- }
-
- /**
- * @param array $salesChannelNames
- * @param string $articleIdInShopware
- *
- * @return array
- */
- protected function modifySalesChannel($salesChannelNames, $articleIdInShopware)
- {
- $salesChannelInXentralIds = [];
- foreach ($salesChannelNames as $salesChannelName) {
- $salesChannelInfo = $this->shopwareRequest('GET',
- sprintf('sales-channel?filter[sales_channel.name]=%s', urlencode(trim($salesChannelName)))
- );
- if (!empty($salesChannelInfo['data'][0]['id'])) {
- $salesChannelInXentralIds[] = $salesChannelInfo['data'][0]['id'];
- }
- }
-
- $existingVisibilities = $this->shopwareRequest(
- 'GET',
- sprintf('product/%s/visibilities', $articleIdInShopware)
- );
-
- $existingSalesChannelIds = [];
- if (!empty($existingVisibilities['data'])) {
- foreach ($existingVisibilities['data'] as $visibility) {
- $existingSalesChannelIds[$visibility['id']] = $visibility['attributes']['salesChannelId'];
- }
- }
-
- foreach ($existingSalesChannelIds as $associationId => $existingSalesChannelId){
- if (!in_array($existingSalesChannelId, $salesChannelInXentralIds,true)) {
- $this->shopwareRequest('DELETE', sprintf('product/%s/visibilities/%s/',
- $articleIdInShopware, $associationId));
- }
- }
-
- $salesChannelsToAdd = [];
- foreach ($salesChannelInXentralIds as $salesChannelInXentralId){
- if (!in_array($salesChannelInXentralId, $existingSalesChannelIds,true)) {
- $salesChannelsToAdd[] = $salesChannelInXentralId;
- }
- }
-
- $visibilities = [];
- foreach ($salesChannelsToAdd as $salesChannelIdToAdd) {
- $visibilities[] = [
- 'salesChannelId' => $salesChannelIdToAdd,
- 'visibility' => 30
- ];
- }
-
- return $visibilities;
- }
-
- /**
- * @param string $isoCode
- *
- * @return string
- */
- protected function findCurrencyId($isoCode)
- {
-
- $this->requestCurrencyMappingLazy();
- if (isset($this->currencyMapping[strtoupper($isoCode)])) {
- return $this->currencyMapping[strtoupper($isoCode)];
- }
- $this->Shopware6Log(
- sprintf('Warnung: Kein Mapping für Waehrung "%s" gefunden.', $isoCode),
- $this->currencyMapping
- );
-
- return null;
- }
-
- /**
- * request currency mapping only once
- */
- protected function requestCurrencyMappingLazy()
- {
-
- if ($this->currencyMapping !== null) {
- return;
- }
- $currencies = $this->shopwareRequest('GET', 'currency');
- if (!isset($currencies['data'])) {
- $this->Shopware6Log('Kann Währungsmapping nicht abrufen', $currencies);
- }
- foreach ($currencies['data'] as $currency) {
- $isoCode = strtoupper($currency['attributes']['isoCode']);
- $this->currencyMapping[$isoCode] = $currency['id'];
- }
- }
-
- /**
- * @param array $internalArticleData
- * @param string $articleIdInShopware
- * @return bool
- */
- public function exportSeoUrls(array $internalArticleData, string $articleIdInShopware): bool
- {
- if (empty($articleIdInShopware)) {
- return false;
- }
-
- $preparedSeoInformation = [];
- foreach ($internalArticleData['freifelder'] as $countryIsoCode => $freeFieldInformation) {
- if($countryIsoCode === 'EN'){
- $countryIsoCode = 'GB';
- }
- if($countryIsoCode === 'DE'){
- foreach ($freeFieldInformation as $freeFieldName => $freeFieldValue) {
- if (stripos($freeFieldName, 'shopware6_seo_url') !== false) {
- $preparedSeoInformation[$countryIsoCode][$freeFieldName] = $freeFieldValue;
- }
- }
- }else{
- foreach ($freeFieldInformation as $freeFieldData) {
- if (stripos($freeFieldData['mapping'], 'shopware6_seo_url') !== false) {
- $preparedSeoInformation[$countryIsoCode][$freeFieldData['mapping']] = $freeFieldData['wert'];
- }
- }
- }
- }
- foreach ($internalArticleData['eigenschaften'] as $property) {
- if (stripos($property['name'], 'shopware6_seo_url') !== false) {
- $preparedSeoInformation['DE'][$property['name']] = $property['values'];
- }
- }
- foreach ($internalArticleData['eigenschaftenuebersetzungen'] as $propertyTranslation) {
- if($propertyTranslation['language_to'] === 'EN'){
- $propertyTranslation['language_to'] = 'GB';
- }
- if (stripos($propertyTranslation['property_to'], 'shopware6_seo_url') !== false) {
- $preparedSeoInformation[$propertyTranslation['language_to']][$propertyTranslation['property_to']] = $propertyTranslation['property_value_to'];
- }
- }
-
- $specificSalesChannelSeoUrls = [];
- $defaultSeoUrls = [];
- foreach ($preparedSeoInformation as $countryIsoCode => $channelAssociations) {
- foreach ($channelAssociations as $fieldName => $fieldValue){
- if(strtolower($fieldName) === 'shopware6_seo_url'){
- $defaultSeoUrls[$countryIsoCode] = $fieldValue;
- }else{
- $seoInformation = explode('|', $fieldName);
- $specificSalesChannelSeoUrls[$countryIsoCode][array_pop($seoInformation)] = $fieldValue;
- }
- }
- }
-
- if (empty($specificSalesChannelSeoUrls) && empty($defaultSeoUrls)) {
- return false;
- }
-
- $salesChannelsIdToName = [];
- $salesChannels = $this->shopwareRequest('GET','sales-channel');
- foreach ($salesChannels['data'] as $salesChannel) {
- $salesChannelsIdToName[$salesChannel['id']] = $salesChannel['attributes']['name'];
- }
-
- foreach ($preparedSeoInformation as $countryIsoCode => $x){
- $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
- if (empty($languageId)) {
- $this->Shopware6Log('Language Id not found for country: ' . $countryIsoCode);
- continue;
- }
-
- $headerInformation = ['sw-language-id: ' . $languageId];
- foreach ($salesChannelsIdToName as $salesChannelId => $salesChannelName) {
- $seoUrlToUse = $defaultSeoUrls[$countryIsoCode];
- if (!empty($specificSalesChannelSeoUrls[$countryIsoCode][$salesChannelName])) {
- $seoUrlToUse = $specificSalesChannelSeoUrls[$countryIsoCode][$salesChannelsIdToName[$salesChannelName]];
- }
- if (empty($seoUrlToUse)) {
- continue;
- }
- $seoDataToSend = [
- 'seoPathInfo' => $seoUrlToUse,
- '_isNew' => true,
- 'isModified' => true,
- 'isCanonical' => true,
- 'isDeleted' => false,
- 'routeName' => 'frontend.detail.page',
- 'foreignKey' => $articleIdInShopware,
- 'pathInfo' => '/detail/'.$articleIdInShopware,
- 'languageId' => $languageId,
- 'salesChannelId' => $salesChannelId];
- $this->shopwareRequest('PATCH', '_action/seo-url/canonical', $seoDataToSend, $headerInformation);
- }
- }
-
- return true;
- }
-
- /**
- * @param array $article
- * @param string $articleIdShopware
- * @param string $currencyId
- *
- * @return bool
- */
- protected function exportVariants($article, $articleIdShopware, $currencyId): bool
- {
- $languageId = $this->getLanguageIdByCountryIso('DE');
- if (empty($languageId)) {
- return false;
- }
- if (empty($article['matrix_varianten']) || empty($articleIdShopware)) {
- return false;
- }
- $internalGroupPropertiesToShopwareId = [];
- foreach ($article['matrix_varianten']['gruppen'] as $propertyGroupName => $internalPropertyGroupValues) {
- $propertyGroupId = '';
- if (array_key_exists($propertyGroupName, $this->knownPropertyGroupIds)) {
- $propertyGroupId = $this->knownPropertyGroupIds[$propertyGroupName];
- }
- if (empty($propertyGroupId)) {
- $propertyGroupId = $this->getPropertyGroupId($propertyGroupName);
- }
- if (empty($propertyGroupId)) {
- $propertyGroupId = $this->createPropertyGroup($propertyGroupName);
- }
- if (empty($propertyGroupId)) {
- $this->Shopware6Log('PropertyGroup kann nicht erstellt werden: ' . $propertyGroupName);
- return false;
- }
-
- if (!empty($article['matrix_varianten']['texte'])) {
- $this->createTranslationForPropertyGroup($propertyGroupId, $propertyGroupName, 'DE');
-
- foreach ($article['matrix_varianten']['texte']['gruppen'] as $countryIsoCode => $matrixGroupTranslation) {
- if ($countryIsoCode === 'EN') {
- $countryIsoCode = 'GB';
- }
-
- $this->createTranslationForPropertyGroup($propertyGroupId, $matrixGroupTranslation[$propertyGroupName], $countryIsoCode);
- }
- }
-
- $languageId = $this->getLanguageIdByCountryIso('DE');
- $headerInformation = ['sw-language-id: ' . $languageId];
- $shopwarePropertyGroupOptions = $this->shopwareRequest(
- 'GET',
- 'property-group/' . $propertyGroupId . '/options?limit=100',
- $headerInformation);
- foreach ($shopwarePropertyGroupOptions['data'] as $shopwarePropertyGroupOption) {
- $propertyValue = $shopwarePropertyGroupOption['attributes']['name'];
- $internalGroupPropertiesToShopwareId[$propertyGroupName][$propertyValue] = $shopwarePropertyGroupOption['id'];
- }
-
- foreach ($internalPropertyGroupValues as $internalPropertyGroupValue => $valueNotNeeded) {
- if (!array_key_exists($internalPropertyGroupValue, $internalGroupPropertiesToShopwareId[$propertyGroupName])) {
- $newOptionData = [
- 'name' => (string)$internalPropertyGroupValue
- ];
- $optionData = $this->shopwareRequest(
- 'POST',
- 'property-group/' . $propertyGroupId . '/options?_response=true',
- $newOptionData);
- $internalGroupPropertiesToShopwareId[$propertyGroupName][$internalPropertyGroupValue] = $optionData['data']['id'];
- }
- }
-
- if (!empty($article['matrix_varianten']['texte'])) {
- foreach ($internalPropertyGroupValues as $optionValue => $valueNotNeeded) {
- $optionId = $internalGroupPropertiesToShopwareId[$propertyGroupName][$optionValue];
- $this->createTranslationForPropertyOption(
- $optionId,
- $optionValue,
- 'DE');
- foreach ($article['matrix_varianten']['texte']['werte'] as $countryIsoCode => $matrixOptionTranslations) {
- if ($countryIsoCode === 'EN') {
- $countryIsoCode = 'GB';
- }
- if (array_key_exists($optionValue, $matrixOptionTranslations)) {
- $this->createTranslationForPropertyOption(
- $optionId,
- $matrixOptionTranslations[$optionValue],
- $countryIsoCode);
- }
- }
- }
- }
- }
-
- $existingCombinations = $this->shopwareRequest(
- 'GET',
- '_action/product/' . $articleIdShopware . '/combinations');
- $existingCombinationsByNumber = [];
-
- foreach ($existingCombinations as $combinationId => $combinationInfo) {
- $existingCombinationsByNumber[$combinationInfo['productNumber']] = [
- 'id' => $combinationId,
- 'options' => [],
- ];
- foreach ($combinationInfo['options'] as $combinationOption) {
- $existingCombinationsByNumber[$combinationInfo['productNumber']]['options'][$combinationOption] = $combinationOption;
- }
- }
-
-
- foreach ($article['artikel_varianten'] as $variant) {
- $internalVariantMatrixData = $article['matrix_varianten']['artikel'][$variant['artikel']];
- $productNumber = $internalVariantMatrixData[0]['nummer'];
- $name = $variant['name_de'];
- $stock = $variant['lag'];
- $ean = $variant['ean'];
- $weight = (float)$variant['gewicht'];
- $pseudoPrice = $variant['pseudopreis'];
- if (empty($pseudoPrice)) {
- $pseudoPrice = 0;
- }
- if (!empty($variant['pseudolager'])) {
- $stock = $variant['pseudolager'];
- }
- $active = true;
- if (!empty($variant['inaktiv'])) {
- $active = false;
- }
- $isCloseOut = false;
- if (!empty($variant['restmenge'])) {
- $isCloseOut = true;
- }
-
- $variantProductData = [
- 'active' => $active,
- 'isCloseout' => $isCloseOut,
- 'name' => $name,
- 'description' => null,
- 'weight' => null,
- 'price' => [
- [
- 'currencyId' => $currencyId,
- 'gross' => $variant['bruttopreis'],
- 'net' => $variant['preis'],
- 'linked' => true,
- 'listPrice' => [
- 'currencyId' => $currencyId,
- 'gross' => $pseudoPrice,
- 'linked' => true,
- 'net' => $pseudoPrice / (1 + $variant['steuersatz'] / 100)
- ]
- ]
- ],
- 'stock' => (int)$stock,
- 'ean' => null,
- 'taxId' => $this->getTaxIdByRate($variant['steuersatz']),
- ];
- if(!empty($weight)){
- $variantProductData['weight'] = $weight;
- }
- if(!empty($ean)){
- $variantProductData['ean'] = $ean;
- }
- if (!empty($variant['uebersicht_de'])) {
- $variantProductData['description'] = $variant['uebersicht_de'];
- }
-
- $renewVariant = false;
- $options = [];
- foreach ($internalVariantMatrixData as $expression) {
- if (!in_array(
- $internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']],
- $existingCombinationsByNumber[$productNumber]['options'],
- false)) {
- $renewVariant = true;
- } else {
- unset($existingCombinationsByNumber[$productNumber]['options'][$internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']]]);
- }
- $options[] = ['id' => $internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']]];
- }
-
- if (!empty($existingCombinationsByNumber[$productNumber]['options'])) {
- $renewVariant = true;
- }
-
- $variantImageData = [
- 'Dateien' => []
- ];
- $variantProductId = '';
- if (!empty($existingCombinationsByNumber[$productNumber]['id']) && !$renewVariant) {
- $variantProductId = $existingCombinationsByNumber[$productNumber]['id'];
- }
- if (!empty($variant['Dateien']['id'])) {
- foreach ($variant['Dateien']['id'] as $index => $fileId) {
- $variantImageData['Dateien'][] = [
- 'filename' => $variant['Dateien']['filename'][$index],
- 'extension' => $variant['Dateien']['extension'][$index],
- 'datei' => $variant['Dateien']['datei'][$index],
- 'beschreibung' => $variant['Dateien']['beschreibung'][$index],
- 'titel' => $variant['Dateien']['titel'][$index],
- 'id' => $fileId,
- ];
- }
- }
- $mediaToAdd = $this->mediaToExport($variantImageData, $variantProductId);
- $variantProductData['media'] = $mediaToAdd;
-
- if ($renewVariant) {
- if (!empty($existingCombinationsByNumber[$productNumber]['id'])) {
- $this->shopwareRequest('DELETE', 'product/' . $existingCombinationsByNumber[$productNumber]['id']);
- }
- $variantProductData['productNumber'] = $productNumber;
- $variantProductData['parentId'] = $articleIdShopware;
- $variantProductData['options'] = $options;
-
- $result = $this->shopwareRequest('POST', 'product?_response=true', $variantProductData);
- $variantProductId = $result['data']['id'];
- } else {
- $variantProductId = $existingCombinationsByNumber[$productNumber]['id'];
- $this->shopwareRequest('PATCH', 'product/' . $variantProductId, $variantProductData);
- }
-
- $defaultPrices = $this->getPricesFromArray($variant['staffelpreise_standard'] ?? []);
- $groupPrices = $this->getPricesFromArray($variant['staffelpreise_gruppen'] ?? []);
-
- $this->deleteOldBulkPrices($variantProductId);
- if (!empty($defaultPrices)) {
- foreach ($defaultPrices as $priceData) {
- $this->exportBulkPriceForGroup($variantProductId, $this->defaultRuleName, $priceData);
- }
- }
- if (!empty($groupPrices)) {
- foreach ($groupPrices as $priceData) {
- $this->exportBulkPriceForGroup($variantProductId, $priceData->getGroupName(), $priceData);
- }
- }
-
- $this->addCoverImage($variantImageData, $variantProductId);
- }
-
- $existingConfigurations = $this->shopwareRequest(
- 'GET', 'product/' . $articleIdShopware . '/configuratorSettings');
- $optionIdsToAdd = [];
- foreach ($article['artikel_varianten'] as $variant) {
- foreach ($article['matrix_varianten']['artikel'][$variant['artikel']] as $matrixInfo) {
- $configurationExists = false;
- foreach ($existingConfigurations['data'] as $configuration) {
- if ($configuration['attributes']['optionId'] === $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']]) {
- $configurationExists = true;
- break;
- }
- }
- if (!$configurationExists) {
- $optionIdsToAdd[] = $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']];
- }
- }
- }
- if (!empty($optionIdsToAdd)) {
- $optionIdsToAdd = array_flip(array_flip($optionIdsToAdd));
- $configurationData = [
- 'configuratorSettings' => []
- ];
- foreach ($optionIdsToAdd as $id) {
- $configurationData['configuratorSettings'][] = ['optionId' => $id];
- }
-
- $this->shopwareRequest(
- 'PATCH',
- sprintf('product/%s', $articleIdShopware),
- $configurationData
- );
-
- $existingConfigurations = $this->shopwareRequest(
- 'GET', 'product/' . $articleIdShopware . '/configuratorSettings');
- $optionsToSort = [];
- foreach ($article['artikel_varianten'] as $variant) {
- foreach ($article['matrix_varianten']['artikel'][$variant['artikel']] as $matrixInfo) {
- foreach ($existingConfigurations['data'] as $configuration) {
- if ($configuration['attributes']['optionId'] === $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']]) {
- $optionsToSort[] = $configuration['id'];
- break;
- }
- }
- }
- }
- if (!empty($optionsToSort)) {
- $optionsToSort = array_flip(array_flip($optionsToSort));
- $configurationData = [
- 'configuratorSettings' => []
- ];
- $position = 1;
-
- foreach ($optionsToSort as $id) {
- $configurationData['configuratorSettings'][] = [
- 'id' => $id,
- 'position' => $position];
- $position++;
- }
-
- $this->shopwareRequest(
- 'PATCH',
- sprintf('product/%s', $articleIdShopware),
- $configurationData
- );
- }
- }
-
- return true;
- }
-
- /**
- * @param $priceArray
- * @return PriceData[]
- */
- protected function getPricesFromArray($priceArray): array{
- return array_map(static function($price){
- return new PriceData(
- (int)$price['ab_menge'],
- (float)$price['preis'],
- (float)$price['bruttopreis'],
- $price['waehrung'],
- $price['gruppeextern'] ?? '') ;
- },$priceArray);
- }
-
- /**
- * delete all old price entries for a product
- *
- * @param string $productId
- */
- protected function deleteOldBulkPrices($productId)
- {
- //TODO Instead of deleting all old prices we should rather check first whether they are still in order
- $oldPrices = $this->shopwareRequest(
- 'GET',
- sprintf('product-price?filter[product_price.productId]=%s', $productId)
- );
- if (is_array($oldPrices)) {
- foreach ($oldPrices['data'] as $deletePrice) {
- $this->shopwareRequest('DELETE', 'product-price/' . $deletePrice['id']);
- }
- } else {
- $this->Shopware6Log('Fehler: Alte Preise wurden nicht gelöscht', $productId);
- }
- }
-
- /**
- * @return int
- */
- public function getOrderSearchLimit(): int
- {
- if(in_array($this->orderSearchLimit, ['50', '75', '100'])) {
- return (int)$this->orderSearchLimit;
- }
-
- return 25;
- }
-
- /**
- * @return int
- */
- public function ImportGetAuftraegeAnzahl()
- {
- $order = null;
- $dataToGet = $this->CatchRemoteCommand('data');
-
- if (empty($this->statesToFetch)) {
- return false;
- }
-
- $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit());
-
- return count($ordersToProcess['data']);
- }
-
- /**
- * @param string $parameter1
- * @param string $parameter2
- */
- public function Shopware6ErrorLog($parameter1, $parameter2 = '')
- {
- $this->app->DB->Insert(
- sprintf(
- "INSERT INTO `shopexport_log`
- (shopid, typ, parameter1, parameter2, bearbeiter, zeitstempel)
- VALUES (%d, 'fehler', '%s','%s','%s',NOW())",
- $this->shopid,
- $this->app->DB->real_escape_string($parameter1),
- $this->app->DB->real_escape_string($parameter2),
- $this->app->DB->real_escape_string($this->app->User->GetName())
- )
- );
- }
-
- /**
- * @param array $stateMachinesIds
- * @return array
- */
- protected function getTransactionStateIdsToFetch($stateMachinesIds): array
- {
- $transactionStateIdsToFetch = [];
- if (!empty($this->transactionStatesToFetch)) {
- $transactionStatesToFetch = explode(';', $this->transactionStatesToFetch);
- foreach ($transactionStatesToFetch as $transactionStateToFetch) {
- $stateInformation = $this->shopwareRequest('GET', 'state-machine-state?filter[technicalName]=' .
- trim($transactionStateToFetch) . '&filter[stateMachineId]=' . $stateMachinesIds['order_transaction.state']);
- if (empty($stateInformation['data'])) {
- $this->Shopware6ErrorLog('Zahlungsstatus für Abholung nicht gefunden', $transactionStateToFetch);
- return false;
- }
- foreach ($stateInformation['data'] as $state) {
- $transactionStateIdsToFetch[] = $state['id'];
- }
- }
- }
-
- return $transactionStateIdsToFetch;
- }
-
- /**
- * @param int $limit
- *
- * @return mixed
- */
- protected function getOrdersToProcess(int $limit)
- {
- $searchData = [
- 'limit' => $limit,
- 'includes' => [
- 'order' => ['id']
- ],
- 'sort' => [
- [
- 'field' => 'order.createdAt',
- 'direction' => 'DESC'
- ]
- ],
- 'filter' => []
- ];
-
- $searchData['filter'][] = [
- 'field' => 'stateMachineState.technicalName',
- 'type' => 'equalsAny',
- 'value' => explode(';', $this->statesToFetch)
- ];
-
- if (!empty($this->deliveryStatesToFetch)) {
- $searchData['filter'][] = [
- 'field' => 'deliveries.stateMachineState.technicalName',
- 'type' => 'equalsAny',
- 'value' => explode(';', $this->deliveryStatesToFetch)
- ];
- }
- if (!empty($this->transactionStatesToFetch)) {
- $searchData['filter'][] = [
- 'field' => 'transactions.stateMachineState.technicalName',
- 'type' => 'equalsAny',
- 'value' => explode(';', $this->transactionStatesToFetch)
- ];
- }
-
- if (!empty($this->salesChannelToFetch)) {
- $searchData['filter'][] = [
- 'field' => 'order.salesChannelId',
- 'type' => 'equals',
- 'value' => $this->salesChannelToFetch
- ];
- }
-
- return $this->shopwareRequest('POST', 'search/order', $searchData);
- }
-
- /**
- * @return int|mixed
- */
- public function ImportGetAuftrag()
- {
- $voucherArticleId = $this->app->DB->Select("SELECT s.artikelrabatt FROM `shopexport` AS `s` WHERE s.id='$this->shopid' LIMIT 1");
- $voucherArticleNumber = $this->app->DB->Select("SELECT a.nummer FROM `artikel` AS `a` WHERE a.id='$voucherArticleId' LIMIT 1");
-
- $dataToGet = $this->CatchRemoteCommand('data');
- if (empty($this->statesToFetch)) {
- return false;
- }
- $expectOrderArray = !empty($dataToGet['anzgleichzeitig']) && (int)$dataToGet['anzgleichzeitig'] > 1;
- $expectNumber = !empty($dataToGet['nummer']);
- $order = null;
- if($expectNumber) {
- $order = $this->shopwareRequest('GET', 'order/' . $dataToGet['nummer'] . '?associations[currency][]');
- if(empty($order['data'])) {
- return false;
- }
- $ordersToProcess = ['data' => [ ['id' => $dataToGet['nummer']] ]];
- $orderIncludedData = $order['included'];
- $order = $order['data'];
- }
- elseif(!$expectOrderArray) {
- $ordersToProcess = $this->getOrdersToProcess(1);
- }
- elseif(!$expectNumber) {
- $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit());
- }
- if (empty($ordersToProcess['data'])) {
- return false;
- }
-
- $fetchedOrders = [];
- if (isset($ordersToFetch['data']['id']) && !isset($ordersToFetch['data'][0])) {
- $ordersToFetch['data'] = [$ordersToFetch['data']];
- }
- foreach ($ordersToProcess['data'] as $currentlyOpenOrder) {
- $orderIdToFetch = $currentlyOpenOrder['id'];
-
- if (empty($dataToGet['nummer']) || empty($order)) {
- $order = $this->shopwareRequest('GET', 'order/' . $orderIdToFetch.'?associations[currency][]');
- $orderIncludedData = $order['included'];
- $order = $order['data'];
- }
- $cart = [];
- try {
- $timestamp = date_create_from_format('Y-m-d\TH:i:s+', $order['attributes']['createdAt']);
- $cart['zeitstempel'] = $timestamp->format('Y-m-d H:i:s');
- } catch (Exception $ex) {
-
- }
- $cart['auftrag'] = $order['id'];
- $cart['subshop'] = $order['attributes']['salesChannelId'];
- $cart['order'] = $order;
- $cart['onlinebestellnummer'] = $order['attributes']['orderNumber'];
- $cart['gesamtsumme'] = $order['attributes']['amountTotal'];
- $cart['versandkostenbrutto'] = $order['attributes']['shippingTotal'];
- $cart['bestelldatum'] = substr($order['attributes']['orderDate'], 0, 10);
- if (!empty($order['attributes']['customerComment'])) {
- $cart['freitext'] = $order['attributes']['customerComment'];
- }
-
- foreach ($orderIncludedData as $includedDataSet){
- if($includedDataSet['type'] === 'currency'){
- $cart['waehrung'] = $includedDataSet['attributes']['isoCode'];
- }
- }
-
- $deliveryInfo = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/deliveries');
- $shippingMethod = $this->shopwareRequest('GET',
- 'order-delivery/' . $deliveryInfo['data'][0]['id'] . '/shipping-method');
- $order['shippingMethod'] = $shippingMethod;
- $cart['lieferung'] = $shippingMethod['data'][0]['attributes']['name'];
-
- $customer = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/order-customer');
- $order['customer'] = $customer;
- $cart['email'] = $customer['data']['0']['attributes']['email'];
-
- $addresses = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/addresses?associations[salutation][]&associations[country][]');
- $order['addresses'] = $addresses;
- $deliveryCountryId = '';
- $billingCountryId = '';
- $billingSalutationId = '';
- foreach ($addresses['data'] as $address) {
- if ($address['id'] === $order['attributes']['billingAddressId']) {
- if (!empty($address['attributes']['vatId'])) {
- $cart['ustid'] = $address['attributes']['vatId'];
- }
- $cart['name'] = $address['attributes']['firstName'] . ' ' . $address['attributes']['lastName'];
- if (!empty($address['attributes']['company'])) {
- $cart['ansprechpartner'] = $cart['name'];
- $cart['name'] = $address['attributes']['company'];
- }
- $cart['strasse'] = $address['attributes']['street'];
- $cart['abteilung'] = $address['attributes']['department'];
- $cart['adresszusatz'] = trim($address['attributes']['additionalAddressLine1'].' '.
- $address['attributes']['additionalAddressLine2']);
- $cart['telefon'] = $address['attributes']['phoneNumber'];
- $cart['plz'] = $address['attributes']['zipcode'];
- $cart['ort'] = $address['attributes']['city'];
- $billingCountryId = $address['attributes']['countryId'];
- $billingSalutationId = $address['attributes']['salutationId'];
- }
- if ($address['id'] !== $order['attributes']['billingAddressId']) {
- $cart['abweichendelieferadresse'] = 1;
- if (!empty($address['attributes']['vatId'])) {
- $cart['lieferadresse_ustid'] = $address['attributes']['vatId'];
- }
- $cart['lieferadresse_name'] = $address['attributes']['firstName'] . ' ' . $address['attributes']['lastName'];
- if (!empty($address['attributes']['company'])) {
- $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name'];
- $cart['lieferadresse_name'] = $address['attributes']['company'];
- }
- $cart['lieferadresse_strasse'] = $address['attributes']['street'];
- $cart['lieferadresse_abteilung'] = $address['attributes']['department'];
- $cart['lieferadresse_adresszusatz'] = trim($address['attributes']['additionalAddressLine1'].' '.
- $address['attributes']['additionalAddressLine2']);
- $cart['lieferadresse_plz'] = $address['attributes']['zipcode'];
- $cart['lieferadresse_ort'] = $address['attributes']['city'];
- $deliveryCountryId = $address['attributes']['countryId'];
- }
- }
-
- $anrede = 'herr';
- $land = 'DE';
- $lieferadresseLand = 'DE';
- foreach ($addresses['included'] as $includedInfo) {
- if ($includedInfo['id'] === $billingCountryId) {
- $land = $includedInfo['attributes']['iso'];
- }
- if ($includedInfo['id'] === $deliveryCountryId) {
- $lieferadresseLand = $includedInfo['attributes']['iso'];
- }
- if ($includedInfo['id'] === $billingSalutationId) {
- $salutation = $includedInfo['attributes']['salutationKey'];
- if ($salutation === 'ms' || $salutation === 'mrs') {
- $anrede = 'frau';
- }
- }
- }
-
- $cart['anrede'] = $anrede;
- $cart['land'] = $land;
- if (!empty($cart['abweichendelieferadresse'])) {
- $cart['lieferadresse_land'] = $lieferadresseLand;
- }
-
- $transactionData = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/transactions');
- $cart['transacion_data'] = $transactionData;
- if (!empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_pui_payment_instruction']['reference_number'])) {
- $cart['transaktionsnummer'] = $transactionData['data'][0]['attributes']['customFields']['swag_paypal_pui_payment_instruction']['reference_number'];
- }
- if (empty($cart['transaktionsnummer'] && !empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_order_id']))) {
- $cart['transaktionsnummer'] = (string)$transactionData['data'][0]['attributes']['customFields']['swag_paypal_order_id'];
- }
- if (empty($cart['transaktionsnummer'] && !empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_transaction_id']))) {
- $livePayPalData = $this->shopwareRequest('GET', 'paypal/payment-details/' . $order['id'] . '/' . $transactionData['data'][0]['attributes']['customFields']['swag_paypal_transaction_id']);
- if (!empty($livePayPalData['transactions'])) {
- foreach ($livePayPalData['transactions'] as $payPalData) {
- foreach ($payPalData['related_resources'] as $ressources) {
- if ($ressources['sale']['state'] === 'completed') {
- $cart['transaktionsnummer'] = $ressources['sale']['id'];
- break 2;
- }
- }
- }
- }
- }
- if(
- empty($cart['transaktionsnummer'])
- && isset($transactionData['data'][0]['attributes']['customFields']['stripe_payment_context']['payment']['payment_intent_id'])
- ){
- $cart['transaktionsnummer'] = $transactionData['data'][0]['attributes']['customFields']['stripe_payment_context']['payment']['payment_intent_id'];
- }
-
- $paymentMethodId = $transactionData['data'][0]['attributes']['paymentMethodId'];
- $paymentMethod = $this->shopwareRequest('GET', 'payment-method/' . $paymentMethodId);
- $cart['zahlungsweise'] = $paymentMethod['data']['attributes']['name'];
-
- $taxedCountry = $land;
- if($this->taxationByDestinationCountry){
- $taxedCountry = $lieferadresseLand;
- }
- if($order['attributes']['amountTotal'] === $order['attributes']['amountNet']){
- if($this->app->erp->IstEU($taxedCountry)){
- $cart['ust_befreit'] = 1;
- }elseif($this->app->erp->Export($taxedCountry)){
- $cart['ust_befreit'] = 2;
- }else{
- $cart['ust_befreit'] = 3;
- }
- }
-
- $lineItems = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/line-items');
- $order['lineItems'] = $lineItems;
- $cart['articlelist'] = [];
-
- $taxRate = 0;
- foreach ($lineItems['data'] as $lineItem) {
- if ($lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'] > $taxRate) {
- $taxRate = $lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'];
- }
- }
-
- $orderPriceType = 'price';
- if(in_array($order['attributes']['taxStatus'], ['net', 'tax-free'])) {
- $orderPriceType = 'price_netto';
- $cart['versandkostennetto'] = $cart['versandkostenbrutto'];
- unset($cart['versandkostenbrutto']);
- }
-
- foreach ($lineItems['data'] as $lineItem) {
- $productPriceType = $orderPriceType;
- if(empty($lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'])){
- $productPriceType = 'price_netto';
- }
- $articleId = null;
- if($lineItem['attributes']['price']['unitPrice'] < 0) {
- $articleId = $voucherArticleNumber;
- }
- elseif(isset($lineItem['attributes']['payload']['productNumber'])){
- $articleId = $lineItem['attributes']['payload']['productNumber'];
- }
- $product = [
- 'articleid' => $articleId,
- 'name' => $lineItem['attributes']['label'],
- 'quantity' => $lineItem['attributes']['quantity'],
- $productPriceType => $lineItem['attributes']['price']['unitPrice'],
- 'steuersatz' => $lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'],
- ];
- $cart['articlelist'][] = $product;
- }
-
- $cart['order'] = $order;
- $fetchedOrders[] = [
- 'id' => $cart['auftrag'],
- 'sessionid' => '',
- 'logdatei' => '',
- 'warenkorb' => base64_encode(serialize($cart)),
- 'warenkorbjson' => base64_encode(json_encode($cart)),
- ];
- $this->Shopware6Log('Ergebnis: Auftrag', $order);
- $this->Shopware6Log('Ergebnis: Adresse', $addresses);
- $this->Shopware6Log('Ergebnis: Positionen', $lineItems);
- }
-
- return $fetchedOrders;
- }
-
- /**
- * @return void
- */
- public function ImportDeleteAuftrag()
- {
- $tmp = $this->CatchRemoteCommand('data');
- $auftrag = $tmp['auftrag'];
-
- $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/process');
- $this->addCustomFieldToOrder((string)$auftrag);
- }
-
- /**
- * @return void
- */
- public function ImportUpdateAuftrag()
- {
- $tmp = $this->CatchRemoteCommand('data');
- $auftrag = $tmp['auftrag'];
- $tracking = $tmp['tracking'];
-
- $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/complete');
-
- $deliveries = $this->shopwareRequest('GET', 'order/'.$auftrag.'/deliveries');
- $deliveryId = $deliveries['data'][0]['id'];
-
- if(!empty($deliveryId)){
- $this->shopwareRequest('POST', '_action/order_delivery/'.$deliveryId.'/state/ship');
-
- $deliveryData = [
- 'trackingCodes' => [$tracking]
- ];
- $this->shopwareRequest('PATCH', 'order-delivery/'.$deliveryId,$deliveryData);
- }
-
- $this->sendInvoce($auftrag);
- $this->addCustomFieldToOrder((string)$auftrag);
- if(empty($tmp['orderId'])) {
- return;
- }
- $this->updateStorageForOrderIntId((int)$tmp['orderId']);
- }
-
- public function ImportStorniereAuftrag()
- {
- $tmp = $this->CatchRemoteCommand('data');
- $auftrag = $tmp['auftrag'];
-
- $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/cancel');
- $this->addCustomFieldToOrder((string)$auftrag);
- }
-
- /**
- * @param string $extOrderId
- */
- protected function sendInvoce($extOrderId)
- {
- $order = $this->app->DB->SelectRow(
- sprintf(
- "SELECT `rechnungid`, `id` FROM `auftrag` WHERE shopextid='%s'",
- $extOrderId
- )
- );
- $invoiceId = 0;
- if (!empty($order['rechnungid'])) {
- $invoiceId = $order['rechnungid'];
- $sql = sprintf("SELECT projekt, belegnr FROM rechnung WHERE id='%s'", $invoiceId);
- $invoiceData = $this->app->DB->SelectRow($sql);
- }
- if (empty($invoiceId) && !empty($order['id'])) {
- $invoiceData = $this->app->DB->SelectRow(
- sprintf(
- "SELECT `id`, `projekt`, `belegnr`
- FROM `rechnung`
- WHERE `auftragid` = %d AND `status` <> 'storniert' AND `status` <> 'angelegt'
- LIMIT 1",
- $order['id']
- )
- );
- if (!empty($invoiceData)) {
- $invoiceId = $invoiceData['id'];
- }
- }
-
- if (!empty($invoiceData['belegnr'])) {
- $projekt = $invoiceData['projekt'];
- if (class_exists('RechnungPDFCustom')) {
- $Brief = new RechnungPDFCustom($this->app, $projekt);
- } else {
- $Brief = new RechnungPDF($this->app, $projekt);
- }
-
- $Brief->GetRechnung($invoiceId);
- $filePath = $Brief->displayTMP(true);
-
- $documentNumber = $invoiceData['belegnr'];
- $invoiceDocumentData = [
- 'config' => [
- 'custom' => [
- 'invoiceNumber' => $documentNumber,
- ],
- 'documentComment' => 'Aus Xentral heraus erstellte Rechnung',
- 'documentNumber' => $documentNumber,
- ],
- 'referenced_document_id' => null,
- 'static' => true
- ];
-
- $documentData = $this->shopwareRequest('POST', '_action/order/' . $extOrderId . '/document/invoice', $invoiceDocumentData);
- $documentId = $documentData['documentId'];
-
- $accessToken = $this->shopwareToken();
- $url = $this->ShopUrl . 'v2/_action/document/' . $documentId . '/upload?_response=true&extension=pdf&fileName=' . $documentNumber;
-
- $ch = curl_init();
- $setHeaders = [
- 'Content-Type:application/pdf',
- 'Authorization:Bearer ' . $accessToken['token']
- ];
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filePath));
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
- curl_setopt($ch, CURLOPT_HTTPHEADER, $setHeaders);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $response = json_decode(curl_exec($ch), true);
- curl_close($ch);
- if (!empty($response['errors'])) {
- $this->Shopware6Log(
- 'Fehler bei Rechnugnsübertragung für ' . $documentNumber, $response['errors']
- );
- }
- }
- }
-
- /**
- * @return string
- */
- public function ImportAuth()
- {
- $tokeninfo = $this->shopwareToken();
-
-
- if (!$tokeninfo['success']) {
- return 'failed: ' . $tokeninfo['message'];
- }
- if($this->data === 'info'){
- $salesChannelsInShopware = $this->client->getAllSalesChannels();
- $salesChannelsToShow = ['subshops' => []];
- foreach ($salesChannelsInShopware['data'] as $salesChannelInShopware){
- $salesChannelsToShow['subshops'][] = [
- 'id'=>$salesChannelInShopware['id'],
- 'name'=>$salesChannelInShopware['name'],
- 'aktiv'=>$salesChannelInShopware['active']
- ];
- }
- return $salesChannelsToShow;
- }
-
- return 'success';
- }
-
- /**
- * Build category tree as displayed in article info
- * May be useful for setting category in the future
- * but probably obsolete
- *
- * @param string $categoryName
- * @param array $categoryTree
- *
- * @return array
- */
- protected function appendCategoryTree($categoryName, $categoryTree = [])
- {
- $shopwareCategory = $this->shopwareRequest(
- 'GET',
- 'category?filter[category.name]=' . urlencode($categoryName)
- );
- if (!isset($shopwareCategory['data'][0]['id'])) {
- return $categoryTree;
- }
- $categoryInfo = $shopwareCategory['data'][0]['attributes'];
- $categories[] = [(int)$categoryInfo['level'], $shopwareCategory['data'][0]['id']];
- $path = $categoryInfo['path'];
- if (!empty($path)) {
- $pathArray = explode('|', $path);
- foreach ($pathArray as $nodeId) {
- if ($nodeId === '') {
- continue;
- }
- $nodeCategory = $this->shopwareRequest('GET', 'category/' . $nodeId);
- if (isset($nodeCategory['data']['id'])) {
- $categories[] = [(int)$nodeCategory['data']['attributes']['level'], $nodeId];
- unset($nodeCategory);
- }
- }
- }
- foreach ($categories as $category) {
- $level = $category[0];
- if (!isset($categoryTree[$level])) {
- $categoryTree[$level] = [];
- }
- if (!in_array($category, $categoryTree[$level], true)) {
- $categoryTree[$level][] = $category[1];
- }
- }
- ksort($categoryTree);
-
- return $categoryTree;
- }
-
- /**
- * @param array $postData
- *
- * @return array
- */
- public function updatePostDataForAssistent($postData)
- {
- if(!empty($this->ShopUrl)) {
- $postData['shopwareUrl'] = $this->ShopUrl;
- }
- return $postData;
- }
-
- /**
- * @param array $shopArr
- * @param array $postData
- *
- * @return array
- */
- public function updateShopexportArr($shopArr, $postData)
- {
- $shopArr['stornoabgleich'] = 1;
- $shopArr['demomodus'] = 0;
-
- return $shopArr;
- }
-
- /**
- * @return JsonResponse|null
- */
- public function AuthByAssistent()
- {
- $shopwareUrl = $this->app->Secure->GetPOST('shopwareUrl');
- $shopwareUserName = $this->app->Secure->GetPOST('shopwareUserName');
- $shopwarePassword = $this->app->Secure->GetPOST('shopwarePassword');
- $step = (int)$this->app->Secure->GetPOST('step');
-
- if($step <= 1){
- if(empty($shopwareUrl)){
- return new JsonResponse(['error' => 'Bitte die URL des Shops angeben.'], JsonResponse::HTTP_BAD_REQUEST);
- }
- if(empty($shopwareUserName)){
- return new JsonResponse(['error' => 'Bitte den Benutzernamen angeben'], JsonResponse::HTTP_BAD_REQUEST);
- }
- if(empty($shopwarePassword)){
- return new JsonResponse(['error' => 'Bitte das Passwort angeben'], JsonResponse::HTTP_BAD_REQUEST);
- }
-
- $this->UserName = $shopwareUserName;
- $this->Password = $shopwarePassword;
- $shopwareUrl = rtrim($shopwareUrl, '/') . '/';
- $testUrls = [];
- $hasNoHttp = strpos($shopwareUrl,'http') !== 0;
- if(substr($shopwareUrl, -5) !== '/api/') {
- if($hasNoHttp) {
- $testUrls[] = 'https://'.$shopwareUrl.'api/';
- $testUrls[] = 'http://'.$shopwareUrl.'api/';
- }
- $testUrls[] = $shopwareUrl.'api/';
- }
- elseif($hasNoHttp) {
- $testUrls[] = 'https://'.$shopwareUrl;
- $testUrls[] = 'http://'.$shopwareUrl;
- }
- else {
- $testUrls[] = $shopwareUrl;
- }
- foreach($testUrls as $testUrl) {
- $this->ShopUrl = $testUrl;
- $tokeninfo = $this->shopwareToken();
- if(!empty($tokeninfo['success'])) {
- break;
- }
- }
-
- if(!$tokeninfo['success']){
- return new JsonResponse(['error' => $tokeninfo['message']], JsonResponse::HTTP_BAD_REQUEST);
- }
- }
-
- return null;
- }
-
- /**
- * @return string
- */
- public function getClickByClickHeadline()
- {
- return 'Bitte im Shopware Backend einen eigenen Benutzer für Xentral anlegen und diese
- Zugangsdaten hier eintragen.';
- }
-
- /**
- * @return array
- */
- public function getStructureDataForClickByClickSave()
- {
- return [
- 'shopwareAllowCreateManufacturer' => 1,
- ];
- }
-
- /**
- * @return array[]
- */
- public function getCreateForm()
- {
- return [
- [
- 'id' => 0,
- 'name' => 'urls',
- 'inputs' => [
- [
- 'label' => 'URL des Shops',
- 'type' => 'text',
- 'name' => 'shopwareUrl',
- 'validation' => true,
- ],
- ],
- ],
- [
- 'id' => 1,
- 'name' => 'username',
- 'inputs' => [
- [
- 'label' => 'Benutzername aus Shopware',
- 'type' => 'text',
- 'name' => 'shopwareUserName',
- 'validation' => true,
- ],
- ],
- ],
- [
- 'id' => 2,
- 'name' => 'password',
- 'inputs' => [
- [
- 'label' => 'Passwort aus Shopware',
- 'type' => 'password',
- 'name' => 'shopwarePassword',
- 'validation' => true,
- ],
- ],
- ],
- ];
- }
-
- public function getBoosterHeadline(): string
- {
- return 'Shopware 6 Business Booster App';
- }
-
- public function getBoosterSubHeadline(): string
- {
- return 'Bitte gehe auf Shopware 6 und installiere dort das Plugin Xentral Business Booster App.
- Dort kann man sich dann mit ein paar Klicks mit Xentral verbinden.';
- }
-
- /**
- * @param int $intOrderId
- *
- * @return array
- */
- protected function getArticleShopLinks(int $intOrderId): array
- {
- return $this->app->DB->SelectPairs(
- "SELECT DISTINCT ao.artikel, a.nummer
- FROM `auftrag_position` AS `ap`
- INNER JOIN `auftrag` AS `ab` ON ap.auftrag = ab.id
- INNER JOIN `artikel` AS `a` ON ap.artikel = a.id
- INNER JOIN `artikel_onlineshops` AS `ao` ON ab.shop = ao.shop AND a.id = ao.artikel
- WHERE ab.id = {$intOrderId} AND ao.aktiv = 1"
- );
- }
-
- /**
- * @param array $articleIds
- */
- protected function updateArticleCacheToSync(array $articleIds): void
- {
- if(empty($articleIds)) {
- return;
- }
- $articleIdsString = implode(', ', $articleIds);
- $this->app->DB->Update(
- "UPDATE `artikel`
- SET `laststorage_changed` = DATE_ADD(NOW(), INTERVAL 1 SECOND)
- WHERE `id` IN ({$articleIdsString})"
- );
- }
-
- /**
- * @param array $articleIds
- */
- protected function updateArticleOnlineShopCache(array $articleIds): void
- {
- if(empty($articleIds)) {
- return;
- }
- $articleIdsString = implode(', ', $articleIds);
- $this->app->DB->Update(
- "UPDATE `artikel_onlineshops`
- SET `storage_cache` = -999, `pseudostorage_cache` = -999
- WHERE `artikel` IN ({$articleIdsString}) AND `aktiv` = 1 AND `shop` = {$this->shopid}"
- );
- }
-
- /**
- * @param int $intOrderId
- */
- protected function updateStorageForOrderIntId(int $intOrderId): void
- {
- $articles = $this->getArticleShopLinks($intOrderId);
- if(empty($articles)) {
- return;
- }
- $articleIds = array_keys($articles);
- $this->updateArticleCacheToSync($articleIds);
- $this->updateArticleOnlineShopCache($articleIds);
-
- $isStorageSyncCronjobActive = (int)$this->app->DB->Select(
- "SELECT COUNT(`id`) FROM `prozessstarter` WHERE `aktiv` = 1 AND `parameter` = 'lagerzahlen'"
- ) > 0;
- if(!$isStorageSyncCronjobActive) {
- return;
- }
- foreach($articleIds as $articleId) {
- try {
- $this->app->erp->LagerSync($articleId, false, [$this->shopid]);
- }
- catch (Exception $e) {
- $articleNumber = $articles[$articleId];
- $this->Shopware6ErrorLog('LagerSync konnte nicht ausgeführt werden', $articleNumber);
- }
- }
-
- $this->updateArticleCacheToSync($articleIds);
- }
-}
+app = $app;
+ $this->intern = true;
+ if ($intern) {
+ return;
+ }
+ $this->app->ActionHandlerInit($this);
+
+ $this->app->ActionHandler('list', 'Shopimporter_Shopware6List');
+ $this->app->ActionHandler('auth', 'ImportAuth');
+ $this->app->ActionHandler('sendlistlager', 'ImportSendListLager');
+ $this->app->ActionHandler('getauftraegeanzahl', 'ImportGetAuftraegeAnzahl');
+ $this->app->ActionHandler('getauftrag', 'ImportGetAuftrag');
+ $this->app->ActionHandler('deleteauftrag', 'ImportDeleteAuftrag');
+ $this->app->ActionHandler('updateauftrag', 'ImportUpdateAuftrag');
+ $this->app->ActionHandler('storniereauftrag','ImportStorniereAuftrag');
+ $this->app->ActionHandler('getarticle','ImportGetArticle');
+ $this->app->ActionHandler('getarticlelist','ImportGetArticleList');
+ $this->app->ActionHandler("updatezahlungsstatus","ImportUpdateZahlungsstatus");
+ $this->app->DefaultActionHandler('list');
+
+ $this->app->ActionHandlerListen($app);
+ }
+
+ /**
+ * @param string $productId
+ *
+ * @return mixed
+ */
+ public function addSyncCustomFieldToProduct(string $productId)
+ {
+ $customField = [
+ 'customFields' => [
+ 'wawision_shopimporter_syncstate' => 1
+ ]
+ ];
+
+ return $this->shopwareRequest('PATCH', "product/{$productId}", $customField);
+ }
+
+ /**
+ * @param string $orderId
+ *
+ * @return mixed
+ */
+ public function addCustomFieldToOrder(string $orderId)
+ {
+ $customField = [
+ 'customFields' => [
+ 'wawision_shopimporter_syncstate' => 1
+ ]
+ ];
+
+ return $this->shopwareRequest('PATCH', "order/{$orderId}", $customField);
+ }
+
+ public function ImportGetArticleList()
+ {
+ $page = 1;
+ $limit = 500;
+
+ do {
+ $productIdsToAdd = [];
+ $searchdata = [
+ 'limit' => $limit,
+ 'page' => $page,
+ 'filter' => [
+ [
+ 'field' => 'product.parentId',
+ 'type' => 'equals',
+ 'value' => null
+ ]
+ ]
+ ];
+
+ $productsInShop = $this->shopwareRequest('POST', 'search/product', $searchdata);
+ if (!empty($productsInShop['data'])) {
+ foreach ($productsInShop['data'] as $productInShop) {
+ $productIdsToAdd[] = $productInShop['id'];
+ }
+ }
+
+ foreach ($productIdsToAdd as $productId) {
+ $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$this->shopid', '" . $this->app->DB->real_escape_string($productId) . "')");
+ }
+ $page++;
+ } while (count($productsInShop['data']) === $limit);
+
+
+ $anzahl = $this->app->DB->Select("SELECT COUNT(id) FROM shopexport_getarticles WHERE shop=$this->shopid");
+ $this->app->erp->SetKonfigurationValue('artikelimportanzahl_' . $this->shopid, $anzahl);
+
+ }
+
+ /**
+ * @param string $method
+ * @param string $endpoint
+ * @param string $data
+ *
+ * @param array $headerInformation
+ * @return mixed
+ */
+ public function shopwareRequest($method, $endpoint, $data = '', $headerInformation = [])
+ {
+ $accessToken = $this->shopwareToken();
+ $url = $this->ShopUrl;
+ $url .= $endpoint;
+
+ $ch = curl_init();
+ $headerInformation[] = 'Content-Type:application/json';
+ $headerInformation[] = 'Authorization:Bearer ' . $accessToken['token'];
+ curl_setopt($ch, CURLOPT_URL, $url);
+ if (!empty($data)) {
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+ }
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headerInformation);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $response = curl_exec($ch);
+ if (curl_error($ch)) {
+ $this->error[] = curl_error($ch);
+ }
+ curl_close($ch);
+
+ return json_decode($response, true);
+ }
+
+ /**
+ * @return array
+ */
+ protected function shopwareToken()
+ {
+ $result = [];
+
+ $result['success'] = true;
+ $result['token'] = $this->accessToken;
+ $result['message'] = 'Keine Antwort von API erhalten.';
+
+ if (!empty($result['token'])) {
+ return $result;
+ }
+
+ $result['success'] = false;
+
+ $data = [
+ 'username' => $this->UserName,
+ 'password' => $this->Password,
+ 'grant_type' => 'password',
+ 'scopes' => 'write',
+ 'client_id' => 'administration',
+ ];
+
+ $ch = curl_init($this->ShopUrl . 'oauth/token');
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Accept: application/json',
+ 'Content-Type: application/json',
+ 'Cache-Control: no-cache',
+ ]
+ );
+ $response = json_decode(curl_exec($ch), true);
+
+ if (!empty((string)$response['title'])) {
+ $result['message'] = $response['title'];
+ }
+
+ if (!empty($response['access_token'])) {
+ $result['success'] = true;
+ $this->accessToken = $response['access_token'];
+ $result['token'] = $response['access_token'];
+ }
+
+ return $result;
+ }
+
+ public function ImportGetArticle()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+
+ if (isset($tmp['nummerintern'])) {
+ $nummer = $tmp['nummerintern'];
+ $response = $this->shopwareRequest('GET', 'product/' . $nummer);
+ if (empty($response['data'])) {
+ $this->error[] = 'Artikel in der Shop Datenbank nicht gefunden!';
+ return;
+ }
+ $nummer = $response['data']['attributes']['productNumber'];
+ } else {
+ $nummer = $tmp['nummer'];
+ }
+ $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer .
+ '&associations[manufacturer][]&associations[properties][]');
+ if (empty($articleInfo['data'][0])) {
+ $this->error[] = 'Artikel in der Shop Datenbank nicht gefunden!';
+ return;
+ }
+ $articleIdInShop = $articleInfo['data'][0]['id'];
+ if(empty($articleInfo['data'][0]['customFields'])
+ || empty($articleInfo['data'][0]['customFields']['wawision_shopimporter_syncstate'])){
+ $this->addSyncCustomFieldToProduct((string)$articleIdInShop);
+ }
+
+ $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer .
+ '&associations[manufacturer][]&associations[properties][]');
+ $associatedInformation = [];
+ $properties = [];
+ foreach ($articleInfo['included'] as $includedInformation) {
+ if ($includedInformation['type'] === 'property_group_option') {
+ $properties[$includedInformation['id']] = $includedInformation['attributes'];
+ } else {
+ $associatedInformation[$includedInformation['id']] = $includedInformation['attributes'];
+ }
+ }
+ $groups = [];
+ if (!empty($properties)) {
+ $groupsInShop = $this->shopwareRequest('GET', 'property-group');
+ foreach ($groupsInShop['data'] as $groupInShop) {
+ $groups[$groupInShop['id']] = $groupInShop['attributes']['name'];
+ }
+ }
+ $media = $this->shopwareRequest('GET', 'product/' . $articleIdInShop . '/media');
+ $imagesToAdd = [];
+ if (!empty($media['included'])) {
+ foreach ($media['included'] as $mediaInfo) {
+ if ($mediaInfo['type'] === 'media') {
+ $imagesToAdd[] = [
+ 'content' => base64_encode(@file_get_contents($mediaInfo['attributes']['url'])),
+ 'path' => $mediaInfo['attributes']['url'],
+ 'id' => $mediaInfo['id']
+ ];
+ }
+ }
+ }
+ $articleInfo = $articleInfo['data'][0]['attributes'];
+
+ $data = [];
+ $data['name'] = $articleInfo['name'];
+ if (isset($tmp['nummerintern'])) {
+ $data['nummer'] = $articleInfo['productNumber'];
+ }
+
+
+ $data['artikelnummerausshop'] = $articleInfo['productNumber'];
+ $data['restmenge'] = $articleInfo['stock'];
+ $data['uebersicht_de'] = $articleInfo['description'];
+ $data['preis_netto'] = $articleInfo['price'][0]['net'];
+ if (!empty($articleInfo['price'][0]['listPrice'])) {
+ $data['pseudopreis'] = $articleInfo['price'][0]['listPrice'];
+ }
+ $data['aktiv'] = $articleInfo['active'];
+ if (!empty($articleInfo['weight'])) {
+ $data['gewicht'] = $articleInfo['weight'];
+ }
+ if (!empty($articleInfo['manufacturerNumber'])) {
+ $data['herstellernummer'] = $articleInfo['manufacturerNumber'];
+ }
+ if (!empty($articleInfo['ean'])) {
+ $data['ean'] = $articleInfo['ean'];
+ }
+ if (!empty($articleInfo['manufacturerId'])) {
+ $data['hersteller'] = $associatedInformation[$articleInfo['manufacturerId']]['name'];
+ }
+ if (!empty($articleInfo['taxId'])) {
+ $data['umsatzsteuer'] = $associatedInformation[$articleInfo['taxId']]['taxRate'];
+ }
+ if (!empty($properties)) {
+ foreach ($properties as $property) {
+ if ($this->propertyOption === 'toProperties') {
+ $data['eigenschaften'][] = [
+ 'name' => $groups[$property['groupId']],
+ 'values' => $property['name'],
+ ];
+ }
+ if ($this->propertyOption === 'toCustomFields') {
+ $data['freifeld_' . $groups[$property['groupId']]] = $property['name'];
+ }
+ }
+ }
+ if (!empty($articleInfo['customFields'])) {
+ foreach ($articleInfo['customFields'] as $customFieldName => $customFieldValue) {
+ if ($this->freeFieldOption === 'toProperties') {
+ $data['eigenschaften'][] = [
+ 'name' => $customFieldName,
+ 'values' => $customFieldValue
+ ];
+ }
+ if ($this->freeFieldOption === 'toCustomFields') {
+ $data['freifeld_' . $customFieldName] = $customFieldValue;
+ }
+ }
+ }
+ if (!empty($imagesToAdd)) {
+ $data['bilder'] = $imagesToAdd;
+ }
+
+
+ if ($articleInfo['childCount'] > 0) {
+ $data = [$data];
+
+ $limit = 50;
+ $page = 1;
+ $optionInfo = [];
+ $optionGroupInfo = [];
+ do {
+
+ $searchdata = [
+ 'limit' => $limit,
+ 'page' => $page,
+ 'filter' => [
+ [
+ 'field' => 'product.parentId',
+ 'type' => 'equals',
+ 'value' => $articleIdInShop
+ ]
+ ],
+ 'sort' => [
+ [
+ 'field' => 'product.options.groupId',
+ 'naturalSorting' => false,
+ 'order' => 'ASC'
+ ],
+ [
+ 'field' => 'product.options.id',
+ 'naturalSorting' => false,
+ 'order' => 'ASC'
+ ]
+ ],
+ 'associations' => [
+ 'options' => [
+ 'sort' => [
+ [
+ 'field' => 'groupId',
+ 'naturalSorting' => false,
+ 'order' => 'ASC'
+ ],
+ [
+ 'field' => 'id',
+ 'naturalSorting' => false,
+ 'order' => 'ASC'
+ ]
+ ]
+ ]
+ ]
+ ];
+ $variantsInShop = $this->shopwareRequest('POST', 'search/product', $searchdata);
+ foreach ($variantsInShop['included'] as $includedInfo) {
+ if ($includedInfo['type'] === 'property_group_option') {
+ $optionInfo[$includedInfo['id']] = $includedInfo['attributes'];
+ if (empty($optionGroupInfo[$includedInfo['attributes']['groupId']])) {
+ $optionGroupInfo[$includedInfo['attributes']['groupId']] = (!empty($optionGroupInfo)?count($optionGroupInfo):0) + 1;
+ }
+ }
+ }
+
+ foreach ($variantsInShop['data'] as $variantInShop) {
+ $variantData = [];
+ $variantName = $data[0]['name'];
+ foreach ($variantInShop['attributes']['optionIds'] as $optionId) {
+ $variantData['matrixprodukt_wert' . $optionGroupInfo[$optionInfo[$optionId]['groupId']]] =
+ $optionInfo[$optionId]['name'];
+ $variantName .= ' - ' . $optionInfo[$optionId]['name'];
+ }
+
+ $variantData['name'] = $variantName;
+ $variantData['nummer'] = $variantInShop['attributes']['productNumber'];
+ $variantData['artikelnummerausshop'] = $variantInShop['attributes']['productNumber'];
+ $variantData['restmenge'] = $variantInShop['attributes']['stock'];
+ $variantData['uebersicht_de'] = $variantInShop['attributes']['description'];
+ if (empty($variantInShop['attributes']['price'][0]['net'])) {
+ $variantData['preis_netto'] = $data[0]['preis_netto'];
+ } else {
+ $variantData['preis_netto'] = $variantInShop['attributes']['price'][0]['net'];
+ }
+ if (!empty($variantInShop['attributes']['price'][0]['listPrice'])) {
+ $variantData['pseudopreis'] = $variantInShop['attributes']['price'][0]['listPrice'];
+ }
+ $variantData['aktiv'] = $variantInShop['attributes']['active'];
+ if (!empty($variantInShop['attributes']['weight'])) {
+ $variantData['gewicht'] = $variantInShop['attributes']['weight'];
+ }
+ if (!empty($variantInShop['attributes']['manufacturerNumber'])) {
+ $variantData['herstellernummer'] = $variantInShop['attributes']['manufacturerNumber'];
+ }
+ if (!empty($variantInShop['attributes']['ean'])) {
+ $variantData['ean'] = $variantInShop['attributes']['ean'];
+ }
+ if (!empty($data[0]['umsatzsteuer'])) {
+ $variantData['umsatzsteuer'] = $data[0]['umsatzsteuer'];
+ }
+
+ $data[] = $variantData;
+ }
+
+ $page++;
+ } while (count($variantsInShop['data']) > $limit);
+
+ foreach ($optionGroupInfo as $groupId => $sorting) {
+ $data[0]['matrixprodukt_gruppe' . $sorting] = $groups[$groupId];
+ }
+ foreach ($optionInfo as $optionData) {
+ $data[0]['matrixprodukt_optionen' . $optionGroupInfo[$optionData['groupId']]][] = $optionData['name'];
+ }
+ }
+
+ //TODO Staffelpreise
+ //TODO Kategorien
+ //TODO Freifelder
+ //TODO Crossselling
+
+ return $data;
+ }
+
+ /**
+ * @param array $data
+ *
+ * @return array
+ */
+ public function checkApiApp($data)
+ {
+ foreach (['shopwareUserName', 'shopwarePassword', 'shopwareUrl'] as $field) {
+ if (empty($data['data'][$field])) {
+ return ['success' => false, 'error' => sprintf('%s is empty', $field)];
+ }
+ }
+
+ $shops = $this->app->DB->SelectArr(
+ sprintf(
+ "SELECT `einstellungen_json`, `bezeichnung`,`id`
+ FROM `shopexport`
+ WHERE `modulename` = 'shopimporter_shopware6'
+ AND `einstellungen_json` IS NOT NULL AND `einstellungen_json` <> ''"
+ )
+ );
+ if (empty($shops)) {
+ return [
+ 'info' => [
+ 'Shop' => 'Shopware',
+ 'info' => 'Url ' . $data['data']['shopwareUrl'],
+ ]
+ ];
+ }
+ foreach ($shops as $shop) {
+ if (empty($shop['einstellungen_json'])) {
+ continue;
+ }
+ $json = @json_decode($shop['einstellungen_json'], true);
+ if (empty($json['felder']) || empty($json['felder']['shopwareUrl'])) {
+ continue;
+ }
+ if ($json['felder']['shopwareUrl'] === $data['data']['shopwareUrl']) {
+ return [
+ 'success' => false,
+ 'error' => sprintf('Shop with url %s allready exists', $data['data']['shopwareUrl'])
+ ];
+ }
+ }
+
+ return [
+ 'info' => [
+ 'Shop' => 'Shopware',
+ 'info' => 'Url ' . $data['data']['shopwareUrl'],
+ ]
+ ];
+ }
+
+ /**
+ *
+ */
+ public function Shopimporter_Shopware6List()
+ {
+ $msg = $this->app->erp->base64_url_encode('Sie können hier die Shops einstellen
');
+ header('Location: index.php?module=onlineshops&action=list&msg=' . $msg);
+ exit;
+ }
+
+ /**
+ * @param $shopid
+ * @param $data
+ */
+ public function getKonfig($shopid, $data)
+ {
+ $this->shopid = $shopid;
+ $this->data = $data;
+ $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json`, `kategorienuebertragen` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1");
+ $importerSettings = reset($importerSettings);
+
+ $this->exportCategories = (bool) $importerSettings['kategorienuebertragen'];
+
+ $einstellungen = [];
+ if (!empty($importerSettings['einstellungen_json'])) {
+ $einstellungen = json_decode($importerSettings['einstellungen_json'], true);
+ }
+ $this->protocol = $einstellungen['felder']['protocol'];
+ $this->UserName = $einstellungen['felder']['shopwareUserName'];
+ $this->Password = $einstellungen['felder']['shopwarePassword'];
+ $this->ShopUrl = rtrim($einstellungen['felder']['shopwareUrl'], '/') . '/';
+ $this->createManufacturerAllowed = false;
+ if ($einstellungen['felder']['shopwareAllowCreateManufacturer'] === '1') {
+ $this->createManufacturerAllowed = true;
+ }
+ $this->defaultManufacturer = $einstellungen['felder']['shopwareDefaultManufacturer'];
+ $this->defaultRuleName = $einstellungen['felder']['shopwareDefaultRuleName'];
+ $this->statesToFetch = $einstellungen['felder']['statesToFetch'];
+ $this->deliveryStatesToFetch = $einstellungen['felder']['deliveryStatesToFetch'];
+ $this->transactionStatesToFetch = $einstellungen['felder']['transactionStatesToFetch'];
+ $this->salesChannelToFetch = $einstellungen['felder']['salesChannelToFetch'];
+ $this->orderSearchLimit = $einstellungen['felder']['orderSearchLimit'];
+ $this->freeFieldOption = $einstellungen['felder']['shopwareFreeFieldOption'];
+ $this->propertyOption = $einstellungen['felder']['shopwarePropertyOption'];
+ $this->shopwareDefaultSalesChannel = $einstellungen['felder']['shopwareDefaultSalesChannel'];
+ $this->shopwareMediaFolder = $einstellungen['felder']['shopwareMediaFolder'];
+ $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid);
+ $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query));
+
+ $this->client = $this->app->Container->get('Shopware6Client');
+ $this->client->setCredentials(
+ $this->UserName,
+ $this->Password,
+ $this->ShopUrl
+ );
+ }
+
+ /**
+ * @return array
+ */
+ public function EinstellungenStruktur()
+ {
+ return
+ [
+ 'ausblenden' => ['abholmodus' => ['ab_nummer']],
+ 'functions' => ['exportartikelbaum','getarticlelist','updatezahlungsstatus'],
+ 'felder' => [
+ 'protocol' => [
+ 'typ' => 'checkbox',
+ 'bezeichnung' => '{|Protokollierung im Logfile|}:',
+ ],
+ 'shopwareUserName' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Benutzername|}:',
+ 'size' => 40,
+ ],
+ 'shopwarePassword' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Passwort|}:',
+ 'size' => 40,
+ ],
+ 'shopwareUrl' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Shop API URL|}:',
+ 'size' => 40,
+ ],
+ 'shopwareDefaultManufacturer' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Standard Hersteller|}:',
+ 'size' => 40,
+ 'default' => 'Keine Herstellerinformation',
+ ],
+ 'shopwareAllowCreateManufacturer' => [
+ 'typ' => 'checkbox',
+ 'bezeichnung' => '{|Bei Artikelexport Hersteller anlegen|}:',
+ ],
+ 'shopwareDefaultRuleName' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Name der Standardpreisgruppe|}:',
+ 'size' => 40,
+ 'default' => 'All customers',
+ ],
+ 'shopwarePropertyOption' => [
+ 'heading' => '{|Eigenschaften / Freifeld Zuordnung|}',
+ 'typ' => 'select',
+ 'bezeichnung' => '{|Xentral Artikel Eigenschaften|}:',
+ 'size' => 40,
+ 'default' => 'toProperties',
+ 'optionen' => ['toProperties' => '{|Shopware Eigenschaften|}', 'toCustomFields' => '{|Shopware Zusatzfelder|}', 'doNotExport' => '{|Nicht übertragen|}']
+ ],
+ 'shopwareFreeFieldOption' => [
+ 'typ' => 'select',
+ 'bezeichnung' => '{|Xentral Artikel Freifelder|}:',
+ 'size' => 40,
+ 'default' => 'toCustomFields',
+ 'optionen' => ['toProperties' => '{|Shopware Eigenschaften|}', 'toCustomFields' => '{|Shopware Zusatzfelder|}', 'doNotExport' => '{|Nicht übertragen|}']
+ ],
+ 'shopwareDefaultSalesChannel' => [
+ 'heading' => '{|Artikelexport Standardeinstellungen|}',
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Standard Sichtbarkeit|}:',
+ 'size' => 40
+ ],
+ 'shopwareMediaFolder' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Media Folder für Artikelbilder|}:',
+ 'size' => 40,
+ 'default' => 'Product Media'
+ ],
+ 'statesToFetch' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Abzuholender Bestellstatus|}:',
+ 'size' => 40,
+ 'default' => 'open',
+ 'col' => 2,
+ 'info' => ' Erlaubte Werte: open;in_progress;completed;cancelled'
+ ],
+ 'deliveryStatesToFetch' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Eingrenzen auf Lieferstatus|}:',
+ 'size' => 40,
+ 'default' => '',
+ 'col' => 2,
+ 'info' => ' Erlaubte Werte: open;shipped_partially;shipped;returned;returned_partially;cancelled'
+ ],
+ 'transactionStatesToFetch' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Eingrenzen auf Bezahlstatus|}:',
+ 'size' => 40,
+ 'default' => '',
+ 'col' => 2,
+ 'info' => ' Erlaubte Werte: open;paid;authorized;paid_partially;refunded;refunded_partially;reminded;cancelled'
+ ],
+ 'salesChannelToFetch' => [
+ 'typ' => 'text',
+ 'bezeichnung' => '{|Eingrenzen auf Sales Channel|}:',
+ 'size' => 40,
+ 'default' => '',
+ 'col' => 2,
+ 'info' => ' Klicke auf "Verbindung prüfen" um die verfügbaren Channels (bitte die Id verwenden) anzuzeigen.'
+ ],
+ 'orderSearchLimit' => [
+ 'typ' => 'select',
+ 'bezeichnung' => '{|Anzahl Aufträge abholen|}:',
+ 'optionen' => [
+ '25' => '25',
+ '50' => '50',
+ '75' => '75',
+ '100' => '100',
+ ],
+ 'default' => '25',
+ 'col' => 2
+ ],
+ ],
+ ];
+ }
+
+ public function ImportUpdateZahlungsstatus()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+ $auftrag = $tmp['auftrag'];
+
+ $transactions = $this->shopwareRequest('GET', 'order/'.$auftrag.'/transactions');
+ $transactionId = $transactions['data'][0]['id'];
+
+ if(empty($transactionId)){
+ return;
+ }
+
+ $response = $this->shopwareRequest('POST', '_action/order_transaction/'.$transactionId.'/state/paid');
+ if (!empty($response['id'])) {
+ return 'ok';
+ }
+ }
+
+ public function ImportSendArtikelbaum(){
+ $xentralCategoryTree = [];
+ $this->app->erp->GetKategorienbaum($xentralCategoryTree, 0, 0, $this->shopid);
+
+ $xentralCategoryIdToParentId = [];
+ foreach ($xentralCategoryTree as $key => $value) {
+ $xentralCategoryTree[$key]['erledigt'] = false;
+ $xentralCategoryTree[$key]['shopid'] = '';
+ $xentralCategoryTree[$key]['aktiv'] = false;
+ $xentralCategoryIdToParentId[$value['id']] = $key;
+ }
+
+ $parentCategoryId = null;
+ foreach ($xentralCategoryTree as $index => $categoryData) {
+ $this->createCategoryTree($index, $xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId);
+ }
+ }
+
+ protected function createCategoryTree($id, &$xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId)
+ {
+ $parentId = $parentCategoryId;
+ if ($xentralCategoryTree[$id]['parent']) {
+ $parentId = $xentralCategoryTree[$xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']]]['shopid'];
+ }
+ if ($xentralCategoryTree[$id]['parent'] && !$xentralCategoryTree[$xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']]]['erledigt']) {
+ $this->createCategoryTree($xentralCategoryIdToParentId[$xentralCategoryTree[$id]['parent']], $xentralCategoryTree, $xentralCategoryIdToParentId, $parentCategoryId);
+ }
+ $xentralCategoryTree[$id]['erledigt'] = true;
+
+ $categoryName = $xentralCategoryTree[$id]['bezeichnung'];
+ $searchdata = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'category.name',
+ 'type' => 'equals',
+ 'value' => $categoryName
+ ],
+ [
+ 'field' => 'category.parentId',
+ 'type' => 'equals',
+ 'value' => $parentId
+ ]
+ ]
+ ];
+
+ $categoriesInShop = $this->shopwareRequest('POST', 'search/category', $searchdata);
+
+ $categoryId = '';
+ if (!empty($categoriesInShop['data'])) {
+ $categoryId = $categoriesInShop['data'][0]['id'];
+ }
+
+ if (!$categoryId) {
+ $categoryData = [
+ 'parentId' => $parentId,
+ 'name' => $categoryName
+ ];
+ $result = $this->shopwareRequest('POST', 'category?_response=true', $categoryData);
+ if ($result['data']['id']) {
+ $categoryId = $result['data']['id'];
+ }
+ }
+
+ if ($categoryId) {
+ $xentralCategoryTree[$id]['shopid'] = $categoryId;
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function ImportSendListLager()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+
+ $count = 0;
+ foreach ($tmp as $article) {
+ $artikel = $article['artikel'];
+ if ($artikel === 'ignore') {
+ continue;
+ }
+ $nummer = $article['nummer'];
+ $fremdnummer = $article['fremdnummer'];
+ if (!empty($fremdnummer)) {
+ $nummer = $fremdnummer;
+ }
+ $articleInfo = $this->shopwareRequest('GET', 'product?filter[product.productNumber]=' . $nummer);
+
+ if (empty($articleInfo['data'][0]['id'])) {
+ $this->Shopware6Log('Artikel wurde nicht im Shop gefunden: ' . $nummer, $articleInfo);
+ continue;
+ }
+ if(empty($articleInfo['data'][0]['customFields'])
+ || empty($articleInfo['data'][0]['customFields']['wawision_shopimporter_syncstate'])){
+ $this->addSyncCustomFieldToProduct((string)$articleInfo['data'][0]['id']);
+ }
+
+ $active = true;
+ if ($article['inaktiv']) {
+ $active = false;
+ }
+
+ $stock = $article['anzahl_lager'];
+ if (!empty($article['pseudolager'])) {
+ $stock = $article['pseudolager'];
+ }
+ $stock = $this->getCorrectedStockFromAvailable($active, (int)$stock, $articleInfo);
+ $data = [
+ 'stock' => $stock,
+ 'active' => $active,
+ ];
+ $response = $this->shopwareRequest('PATCH', 'product/' . $articleInfo['data'][0]['id'], $data);
+ $this->Shopware6Log('Lagerbestand konnte nicht uebertragen werden fuer Artikel: ' . $nummer, $response);
+ $count++;
+ }
+
+ return $count;
+ }
+
+ /**
+ * @param bool $isStockActive
+ * @param int $stock
+ * @param array|null $articleInfo
+ *
+ * @return int
+ */
+ public function getCorrectedStockFromAvailable(bool $isStockActive, int $stock, ?array $articleInfo): int
+ {
+ if(!$isStockActive) {
+ return $stock;
+ }
+ if(empty($articleInfo)) {
+ return $stock;
+ }
+ if(!isset($articleInfo['data'][0]['attributes']['availableStock'])) {
+ return $stock;
+ }
+ if(!isset($articleInfo['data'][0]['attributes']['availableStock'])) {
+ return $stock;
+ }
+ $reserved = (int)$articleInfo['data'][0]['attributes']['stock']
+ - (int)$articleInfo['data'][0]['attributes']['availableStock'];
+ if($reserved <= 0) {
+ return $stock;
+ }
+
+ return $stock + $reserved;
+ }
+
+ /**
+ * @param string $message
+ * @param mixed $dump
+ */
+ public function Shopware6Log($message, $dump = '')
+ {
+ if ($this->protocol) {
+ $this->app->erp->Logfile($message, print_r($dump, true));
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function ImportSendList()
+ {
+ $articleList = $this->CatchRemoteCommand('data');
+
+ $successCounter = 0;
+ foreach ($articleList as $article) {
+ $number = $article['nummer'];
+ $articleInfo = $this->shopwareRequest(
+ 'GET',
+ sprintf('product?filter[product.productNumber]=%s', $number)
+ );
+ $articleIdShopware = '';
+ if (!empty($articleInfo['data'][0]['id'])) {
+ $articleIdShopware = $articleInfo['data'][0]['id'];
+ }
+
+ $quantity = $article['anzahl_lager'];
+ if (!empty($article['pseudolager'])) {
+ $quantity = $article['pseudolager'];
+ }
+ $inaktiv = $article['inaktiv'];
+ $active = true;
+ if (!empty($inaktiv)) {
+ $active = false;
+ }
+ $quantity = $this->getCorrectedStockFromAvailable($active, (int)$quantity, $articleInfo);
+ $taxRate = (float)$article['steuersatz'];
+
+ $taxId = $this->getTaxIdByRate($taxRate);
+
+ $mediaToAdd = $this->mediaToExport($article, $articleIdShopware);
+
+ $categoriesToAdd = [];
+ if($this->exportCategories){
+ $categoriesToAdd = $this->categoriesToExport($article, $articleIdShopware);
+ }
+
+ $propertiesToAdd = $this->propertiesToExport($article, $articleIdShopware);
+
+ $crosselingToAdd = $this->crosssellingToExport($article, $articleIdShopware);
+
+ $systemFieldsToAdd = $this->systemFieldsToExport($article, $articleIdShopware);
+
+ $deliveryTimeId = null;
+ if(!empty($article['lieferzeitmanuell'])){
+ $deliveryTimeId = $this->getDeliveryTimeId($article['lieferzeitmanuell']);
+ }
+
+ if (empty($systemFieldsToAdd['visibilities']) && !empty($this->shopwareDefaultSalesChannel)) {
+ $systemFieldsToAdd['visibilities'] = $this->modifySalesChannel(explode(',', $this->shopwareDefaultSalesChannel), $articleIdShopware);
+ }
+
+ if(empty($systemFieldsToAdd['unitId']) && !empty($article['einheit']) ){
+ $systemFieldsToAdd['unitId'] = $this->unitToAdd($article['einheit']);
+ }
+
+
+ //Hersteller in Shopware suchen bzw. Anlegen
+ $manufacturerName = $article['hersteller'];
+ $manufacturerId = $this->getManufacturerIdByName($manufacturerName);
+
+ if ($manufacturerId === null && $this->createManufacturerAllowed === true) {
+ $manufacturerId = $this->createManufacturer($manufacturerName);
+ }
+
+ if (empty($manufacturerId)) {
+ return 'error: Für den Artikelexport ist die Herstellerinformation zwingend erforderlich';
+ }
+
+ $isCloseOut = false;
+ if(!empty($article['restmenge'])){
+ $isCloseOut = true;
+ }
+
+ $description = $this->prepareDescription($article['uebersicht_de']);
+ $ean = $article['ean'];
+ $metaTitle = $article['metatitle_de'];
+ $metaDescription = $article['metadescription_de'];
+ $metaKeywords = $article['metakeywords_de'];
+
+ $manufacturerNumber = $article['herstellernummer'];
+ if (empty($manufacturerNumber)) {
+ $manufacturerNumber = '';
+ }
+
+ $weight = (float)$article['gewicht'];
+ $length = (float)$article['laenge'] * 10;
+ $height = (float)$article['hoehe'] * 10;
+ $width = (float)$article['breite'] * 10;
+
+ $purchasePrice = (float)$article['einkaufspreis'];
+
+ $currencyId = $this->findCurrencyId($article['waehrung']);
+ $price = [
+ 'net' => $article['preis'],
+ 'gross' => $article['bruttopreis'],
+ 'currencyId' => $currencyId,
+ 'linked' => true];
+
+ if (!empty($article['pseudopreis'])) {
+ $price['listPrice'] = [
+ 'currencyId' => $currencyId,
+ 'gross' => $article['pseudopreis'],
+ 'linked' => true,
+ 'net' => $article['pseudopreis']/(1+$taxRate/100)
+ ];
+ }
+
+ $data = [
+ 'name' => $article['name_de'],
+ 'isCloseout' => $isCloseOut,
+ 'productNumber' => $number,
+ 'manufacturerId' => $manufacturerId,
+ 'stock' => (int)$quantity,
+ 'taxId' => $taxId,
+ 'active' => $active,
+ 'description' => $description,
+ 'ean' => $ean,
+ 'metaTitle' => $metaTitle,
+ 'metaDescription' => $metaDescription,
+ 'keywords' => $metaKeywords,
+ 'manufacturerNumber' => $manufacturerNumber,
+ 'length' => $length,
+ 'width' => $width,
+ 'height' => $height,
+ 'weight' => $weight,
+ 'purchasePrice' => $purchasePrice,
+ 'price' => [$price],
+ 'categories' => $categoriesToAdd,
+ 'properties' => $propertiesToAdd,
+ 'crossSellings' => $crosselingToAdd,
+ 'media' => $mediaToAdd,
+ 'deliveryTimeId' => $deliveryTimeId
+ ];
+
+ $data = array_merge($data, $systemFieldsToAdd);
+ if(empty($data['customFields'])
+ || empty($data['customFields']['wawision_shopimporter_syncstate'])){
+ $data['customFields']['wawision_shopimporter_syncstate'] = 1;
+ }
+
+ if (empty($articleIdShopware)) {
+ $result = $this->shopwareRequest('POST',
+ 'product?_response=true', $data);
+ if (!empty($result['data']['id'])) {
+ $articleIdShopware = $result['data']['id'];
+ $articleInfo['data'][0] = $result['data'];
+ }
+ } else {
+ $headerInformation = [];
+ $languageId = $this->getLanguageIdByCountryIso('DE');
+ if (!empty($languageId)) {
+ $headerInformation[] = 'sw-language-id: ' . $languageId;
+ }
+ $result = $this->shopwareRequest('PATCH',
+ sprintf('product/%s?_response=true', $articleIdShopware), $data, $headerInformation);
+ }
+
+ if(!empty($articleIdShopware)){
+ $this->exportTranslationsForArticle($article, $articleIdShopware);
+ }
+
+ $this->addCoverImage($article, $articleIdShopware);
+
+ if (empty($result['data']) || is_array($result['errors'])) {
+ $this->Shopware6Log('Artikelexport fehlgeschlagen', ['data:' => $data, 'response' => $result]);
+ continue;
+ }
+
+ $this->exportSeoUrls($article, $articleIdShopware);
+
+ $this->exportVariants($article, $articleIdShopware, $currencyId);
+
+ if (empty($result['data']) || is_array($result['errors'])) {
+ $this->Shopware6Log('Artikelexport bei Bildübertragung fehlgeschlagen', ['data:' => $data, 'response' => $result]);
+ continue;
+ }
+
+ $defaultPrices = $this->getPricesFromArray($article['staffelpreise_standard'] ?? []);
+ $groupPrices = $this->getPricesFromArray($article['staffelpreise_gruppen'] ?? []);
+
+ if (!empty($defaultPrices) || !empty($groupPrices)) {
+ $this->deleteOldBulkPrices($articleIdShopware);
+ }
+ if (!empty($defaultPrices)) {
+ foreach ($defaultPrices as $priceData) {
+ $this->exportBulkPriceForGroup($articleIdShopware, $this->defaultRuleName, $priceData);
+ }
+ }
+ if (!empty($groupPrices)) {
+ foreach ($groupPrices as $priceData) {
+ $this->exportBulkPriceForGroup($articleIdShopware, $priceData->getGroupName(), $priceData);
+ }
+ }
+
+ $successCounter++;
+ }
+
+ return $successCounter;
+ }
+
+ protected function exportBulkPriceForGroup(string $productId, string $groupName, PriceData $priceData): void
+ {
+ $currencyId = $this->findCurrencyId($priceData->getCurrency());
+
+ $groupRuleId = $this->client->getGroupRuleId($groupName);
+ if (empty($groupRuleId)) {
+ $this->Shopware6Log("Fehler: Gruppe {$groupName} konnte im Shop nicht gefunden werden");
+ return;
+ }
+
+ $result = $this->client->saveBulkPrice($productId, $groupRuleId, $currencyId, $priceData);
+ if (empty($result['data'])) {
+ $this->Shopware6Log("Fehler: Staffelpreis für Gruppe {$groupName} konnte nicht exportiert werden", $result);
+ }
+ }
+
+ /**
+ * @param string $deliveryTimeText
+ *
+ * @return string|null
+ */
+ protected function getDeliveryTimeId(string $deliveryTimeText): ?string
+ {
+ $searchCommand = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'name',
+ 'type' => 'equals',
+ 'value' => $deliveryTimeText
+ ]
+ ]
+ ];
+ $result = $this->shopwareRequest('POST', 'search/delivery-time', $searchCommand);
+
+ if (empty($result['data'][0]['id'])) {
+ return null;
+ }
+
+ return $result['data'][0]['id'];
+ }
+
+ /**
+ * @param string $description
+ * @return string
+ */
+ protected function prepareDescription($description): string
+ {
+ $markupSubstitute = [
+ '/"/' => '"',
+ '/<([^&]+)>/' => '<\1>',
+ '/\\/' => '',
+ '/\\<\/strong>/' => ' ',
+ '/\\/' => '',
+ '/\\<\/em>/' => ' ',
+ '/&/' => '&',
+ ];
+
+ return (string)preg_replace(array_keys($markupSubstitute), array_values($markupSubstitute), $description);
+ }
+
+ /**
+ * @param array $article
+ * @param string $articleIdShopware
+ */
+ protected function exportTranslationsForArticle(array $article, string $articleIdShopware): void
+ {
+ $customFieldsToAdd = $this->customFieldsToExport($article, $articleIdShopware);
+
+ $preparedTranslations = [];
+ $preparedTranslations['DE'] = [
+ 'name' => $article['name_de'],
+ 'description' => $this->prepareDescription($article['uebersicht_de']),
+ 'metaTitle' => $article['metatitle_de'],
+ 'metaDescription' => $article['metadescription_de'],
+ 'keywords' => $article['metakeywords_de'],
+ 'customFields' => []
+ ];
+ if(!empty($customFieldsToAdd['DE'])){
+ $preparedTranslations['DE']['customFields'] = $customFieldsToAdd['DE'];
+ }
+ $preparedTranslations['GB'] = [
+ 'name' => $article['name_en'],
+ 'description' => $this->prepareDescription($article['uebersicht_en']),
+ 'metaTitle' => $article['metatitle_en'],
+ 'metaDescription' => $article['metadescription_en'],
+ 'keywords' => $article['metakeywords_en'],
+ 'customFields' => [],
+ ];
+ if(!empty($customFieldsToAdd['GB'])){
+ $preparedTranslations['GB']['customFields'] = $customFieldsToAdd['GB'];
+ }
+ foreach ($article['texte'] as $translation) {
+ if ($translation['sprache'] === 'EN') {
+ $translation['sprache'] = 'GB';
+ }
+ $preparedTranslations[$translation['sprache']] = [
+ 'name' => $translation['name'],
+ 'description' => $this->prepareDescription($translation['beschreibung_online']),
+ 'metaTitle' => $translation['meta_title'],
+ 'metaDescription' => $translation['meta_description'],
+ 'keywords' => $translation['meta_keywords'],
+ ];
+ if(!empty($customFieldsToAdd[$translation['sprache']])){
+ $preparedTranslations[$translation['sprache']]['customFields'] = $customFieldsToAdd[$translation['sprache']];
+ }
+ }
+
+ foreach ($preparedTranslations as $countryIsoCode => $translation) {
+ $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
+ if (empty($languageId)) {
+ $this->Shopware6Log('Language Id not found for country: ' . $countryIsoCode);
+ continue;
+ }
+
+ $headerInformation = ['sw-language-id: ' . $languageId];
+ $this->shopwareRequest(
+ 'PATCH',
+ sprintf('product/%s', $articleIdShopware),
+ $translation, $headerInformation
+ );
+ }
+ }
+
+ /**
+ * @param string $countryIso
+ *
+ * @return string|null
+ */
+ protected function getLanguageIdByCountryIso(string $countryIso): ?string
+ {
+ if(array_key_exists($countryIso, $this->knownShopLanguageIds)){
+ return $this->knownShopLanguageIds[$countryIso];
+ }
+
+ $searchCommand = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'country.iso',
+ 'type' => 'equals',
+ 'value' => $countryIso
+ ]
+ ]
+ ];
+ $countryInformation = $this->shopwareRequest('POST', 'search/country', $searchCommand);
+
+ foreach ($countryInformation['data'] as $country){
+ $searchCommand = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'locale.territory',
+ 'type' => 'equals',
+ 'value' => $country['attributes']['name']
+ ]
+ ]
+ ];
+ $localeInformation = $this->shopwareRequest('POST', 'search/locale', $searchCommand);
+ foreach ($localeInformation['data'] as $locale) {
+ $searchCommand = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'language.localeId',
+ 'type' => 'equals',
+ 'value' => $locale['id']
+ ]
+ ]
+ ];
+ $languageInformation = $this->shopwareRequest('POST', 'search/language', $searchCommand);
+ if (!empty($languageInformation['data'][0]['id'])) {
+ $this->knownShopLanguageIds[$countryIso] = $languageInformation['data'][0]['id'];
+ return $languageInformation['data'][0]['id'];
+ }
+ }
+ }
+ $this->knownShopLanguageIds[$countryIso] = null;
+
+ return null;
+ }
+
+ /**
+ * @param string $manufacturerName
+ *
+ * @return null|string
+ */
+ protected function createManufacturer(string $manufacturerName): ?string
+ {
+ $data = ['name' => $manufacturerName];
+ $response = $this->shopwareRequest('POST', 'product-manufacturer?_response=true', $data);
+
+ $manufacturerId = null;
+ if(!empty($response['data']['id'])){
+ $manufacturerId = $response['data']['id'];
+ $this->knownManufacturerIds[$manufacturerName] = $manufacturerId;
+ }
+
+ return $manufacturerId;
+ }
+
+ /**
+ * @param string $manufacturerName
+ *
+ * @return null|string
+ */
+ protected function getManufacturerIdByName(string $manufacturerName): ?string
+ {
+ if (!empty($this->knownManufacturerIds[$manufacturerName])) {
+ return $this->knownManufacturerIds[$manufacturerName];
+ }
+
+ $manufacturerId = null;
+ if (empty($manufacturerName)) {
+ $manufacturerName = $this->defaultManufacturer;
+ }
+ $manufacturer = $this->shopwareRequest(
+ 'GET',
+ 'product-manufacturer?filter[product_manufacturer.name]=' . urlencode($manufacturerName)
+ );
+ $manufacturerId = $manufacturer['data'][0]['id'];
+ $this->knownManufacturerIds[$manufacturerName] = $manufacturerId;
+
+ return $manufacturerId;
+ }
+
+ /**
+ * @param float $taxRate
+ *
+ * @return string
+ */
+ protected function getTaxIdByRate(float $taxRate): string{
+ if(empty($this->taxesInShop)){
+ $this->taxesInShop = $this->shopwareRequest('GET', 'tax');
+ }
+ foreach ($this->taxesInShop['data'] as $taxData) {
+ if (abs(($taxData['attributes']['taxRate']-$taxRate)) < 0.0001 ) {
+ return $taxData['id'];
+ }
+ }
+
+ return $this->taxesInShop['data'][0]['id'];
+ }
+
+ /**
+ * @param array $internalArticleData
+ * @param string $articleIdShopware
+ *
+ * @return array
+ */
+ protected function mediaToExport($internalArticleData, $articleIdShopware)
+ {
+ $mediaToAdd = [
+ ];
+
+ if (empty($internalArticleData['Dateien'])) {
+ return $mediaToAdd;
+ }
+ $internalMediaIds = [];
+
+ $searchdata = [
+ 'limit' => 1,
+ 'filter' => [
+ [
+ 'field' => 'name',
+ 'type' => 'equals',
+ 'value' => $this->shopwareMediaFolder
+ ]
+ ]
+ ];
+ $mediaFolderData = $this->shopwareRequest('POST', 'search/media-folder', $searchdata);
+ if(empty($mediaFolderData['data'][0]['id'])){
+ $this->Shopware6ErrorLog('Kein Media Folder gefunden für: ', $this->shopwareMediaFolder);
+ return [];
+ }
+
+ $mediaFolderId = $mediaFolderData['data'][0]['id'];
+
+ foreach ($internalArticleData['Dateien'] as $internalFile) {
+ $filename = explode('.', $internalFile['filename']);
+ unset($filename[(!empty($filename)?count($filename):0) - 1]);
+ $filename = $internalFile['id'].'_'.implode($filename);
+ $extension = $internalFile['extension'];
+ $imageTitle = (string)$internalFile['titel'];
+ $imageAltText = (string)$internalFile['beschreibung'];
+ $accessToken = $this->shopwareToken();
+
+ $searchdata = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'media.fileName',
+ 'type' => 'equals',
+ 'value' => $filename
+ ]
+ ]
+ ];
+ $mediaData = $this->shopwareRequest('POST', 'search/media', $searchdata);
+ if (!empty($mediaData['data'][0]['id'])) {
+ $internalMediaIds[] = $mediaData['data'][0]['id'];
+ if($mediaData['data'][0]['attributes']['title'] !== $imageTitle
+ || $mediaData['data'][0]['attributes']['alt'] !== $imageAltText){
+ $this->setMediaTitleAndAltText($mediaData['data'][0]['id'], $imageTitle, $imageAltText);
+ }
+ continue;
+ }
+
+ $mediaData = $this->shopwareRequest('POST', 'media?_response=true', []);
+ if(empty($mediaData['data']['id'])){
+ $this->Shopware6Log('Error when creating media for sku: ' . $internalArticleData['nummer'],
+ ['mediaData' => $mediaData, 'title' => $imageTitle, 'text' => $imageAltText]);
+ continue;
+ }
+ $mediaId = $mediaData['data']['id'];
+ $this->setMediaTitleAndAltText($mediaId, $imageTitle, $imageAltText);
+
+ $mediaAssociationData = [
+ [
+ 'action' => 'upsert',
+ 'entity' => 'media',
+ 'payload' => [
+ [
+ 'id' => $mediaId,
+ 'mediaFolderId' => $mediaFolderId
+ ]
+ ]
+ ]
+ ];
+ $this->shopwareRequest('POST', '_action/sync?_response=true', $mediaAssociationData);
+
+ $url = $this->ShopUrl . '_action/media/' . $mediaId . '/upload?extension=' . $extension . '&fileName=' . $filename;
+ $ch = curl_init();
+ $setHeaders = [
+ 'Content-Type:image/' . $extension,
+ 'Authorization:Bearer ' . $accessToken['token']
+ ];
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, base64_decode($internalFile['datei']));
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $setHeaders);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_exec($ch);
+
+ $internalMediaIds[] = $mediaId;
+ }
+
+ $existingMediaConnection = [];
+ if (!empty($articleIdShopware)) {
+ $existingMediaConnection = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/media?limit=100');
+ foreach ($existingMediaConnection['data'] as $existingConnection) {
+ if (!in_array($existingConnection['attributes']['mediaId'], $internalMediaIds, false)) {
+ $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/media/' . $existingConnection['id']);
+ }
+ }
+ }
+
+ $alreadyAddedMediaIDs = [];
+ if (!empty($existingMediaConnection)) {
+ foreach ($existingMediaConnection['data'] as $existingConnection) {
+ $alreadyAddedMediaIDs[$existingConnection['attributes']['mediaId']] = $existingConnection['id'];
+ }
+ }
+ $position = 0;
+ foreach ($internalMediaIds as $mediaId) {
+ $mediaDataSet = [
+ 'mediaId' => $mediaId,
+ 'position' => $position
+ ];
+ if (array_key_exists($mediaId, $alreadyAddedMediaIDs)) {
+ $mediaDataSet['id'] = $alreadyAddedMediaIDs[$mediaId];
+ }
+ $mediaToAdd[] = $mediaDataSet;
+ $position++;
+ }
+
+ return $mediaToAdd;
+ }
+
+ /**
+ * @param string $mediaId
+ * @param string $title
+ * @param string $altText
+ */
+ protected function setMediaTitleAndAltText(string $mediaId, string $title, string $altText): void
+ {
+ $this->shopwareRequest('PATCH', 'media/' . $mediaId,
+ ['title' => $title,
+ 'alt' => $altText
+ ]
+ );
+ }
+
+ /**
+ * @param array $articleInXentral
+ * @param string $articleIdShopware
+ */
+ protected function addCoverImage($articleInXentral, $articleIdShopware){
+ if(empty($articleIdShopware)){
+ return;
+ }
+ if(empty($articleInXentral['Dateien'])){
+ return;
+ }
+ $existingMediaConnection = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/media?limit=100');
+ if(empty($existingMediaConnection['data'])){
+ return;
+ }
+ foreach ($articleInXentral['Dateien'] as $xentralFile) {
+ $filename = explode('.', $xentralFile['filename']);
+ unset($filename[(!empty($filename)?count($filename):0) - 1]);
+ $filename = $xentralFile['id'].'_'.implode($filename);
+
+ $searchdata = [
+ 'limit' => 5,
+ 'filter' => [
+ [
+ 'field' => 'media.fileName',
+ 'type' => 'equals',
+ 'value' => $filename
+ ]
+ ]
+ ];
+ $mediaData = $this->shopwareRequest('POST', 'search/media', $searchdata);
+ $mediaId = $mediaData['data'][0]['id'];
+
+ foreach ($existingMediaConnection['data'] as $mediaConnection){
+ if($mediaId === $mediaConnection['attributes']['mediaId']){
+
+ $this->shopwareRequest('PATCH',
+ sprintf('product/%s?_response=true', $articleIdShopware),['coverId' => $mediaConnection['id']]);
+ return;
+ }
+ }
+ }
+ }
+
+ /**
+ * @param array $articleInXentral
+ * @param string $articleIdShopware
+ * @return array
+ */
+ protected function categoriesToExport($articleInXentral, $articleIdShopware)
+ {
+ $categoryName = $articleInXentral['kategoriename'];
+ $categoryTree = $articleInXentral['kategorien'];
+
+ $categoriesToAdd = [];
+ if (empty($categoryName) && empty($categoryTree)) {
+ return $categoriesToAdd;
+ }
+
+ $categoriesInXentral = [];
+ if (!empty($categoryTree)) {
+ $rootcategory = null;
+ $categoryTreeid = [];
+ foreach ($categoryTree as $categoryData) {
+ $categoryData['shopwareparent'] = 0;
+ if (!$categoryData['parent']) {
+ $categoryData['shopwareid'] = $rootcategory;
+ }
+ $categoryTreeid[$categoryData['id']] = $categoryData;
+ }
+
+ foreach ($categoryTree as $categoryData) {
+ $parentid = $rootcategory;
+ if (!empty($categoryData['parent'])) {
+ $parentid = $this->getCategoryParentId($categoryData, $categoryTreeid);
+ }
+
+ $searchdata = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'category.name',
+ 'type' => 'equals',
+ 'value' => $categoryData['name']
+ ]
+ ]
+ ];
+ if (!empty($parentid)) {
+ $searchdata['filter'][] = [
+ 'field' => 'category.parentId',
+ 'type' => 'equals',
+ 'value' => $parentid
+ ];
+ }
+ $result = $this->shopwareRequest('POST', 'search/category', $searchdata);
+
+
+ if (!empty($result['data'][0]['id'])) {
+ $categoryTreeid[$categoryData['id']]['shopwareid'] = $result['data'][0]['id'];
+ $categoriesInXentral[] = $result['data'][0]['id'];
+ }
+ }
+ } else if (!empty($categoryName)) {
+ $searchdata = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'category.name',
+ 'type' => 'equals',
+ 'value' => $categoryName
+ ]
+ ]
+ ];
+
+ $result = $this->shopwareRequest('POST', 'search/category', $searchdata);
+
+ if (!empty($result['data'][0]['id'])) {
+ $categoriesInXentral[] = $result['data'][0]['id'];
+ }
+ }
+
+ if (!empty($articleIdShopware)) {
+ $existingCategories = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/categories?limit=50');
+ foreach ($existingCategories['data'] as $existingCategory) {
+ if (!in_array($existingCategory['id'], $categoriesInXentral, false)) {
+ $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/categories/' . $existingCategory['id']);
+ }
+ }
+ }
+ foreach ($categoriesInXentral as $categoryId) {
+ $categoriesToAdd[] = ['id' => $categoryId];
+ }
+
+
+ return $categoriesToAdd;
+ }
+
+ /**
+ * @param $categoryData
+ * @param $categoryTreeId
+ * @return string|null
+ */
+ protected function getCategoryParentId($categoryData, &$categoryTreeId)
+ {
+ $parentId = $categoryTreeId[$categoryData['parent']]['shopwareid'];
+ if (!empty($parentId)) {
+ return $parentId;
+ }
+
+ $parentCategoryData = $this->app->DB->SelectRow("SELECT id,parent,bezeichnung AS name FROM artikelkategorien WHERE id<>'' AND id<>'0' AND id='" . $categoryData['parent'] . "' LIMIT 1");
+ if (empty($parentCategoryData)) {
+ return null;
+ }
+
+ $searchData = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'category.name',
+ 'type' => 'equals',
+ 'value' => $parentCategoryData['name']
+ ]
+ ]
+ ];
+ $result = $this->shopwareRequest('POST', 'search/category', $searchData);
+
+ if (count($result['data']) < 1) {
+ return null;
+ }
+
+ if (count($result['data']) === 1) {
+ $parentCategoryData['shopwareid'] = $result['data'][0]['id'];
+ $categoryTreeId[$parentCategoryData['id']] = $parentCategoryData;
+ return $result['data'][0]['id'];
+ }
+
+ $grandparentId = $this->getCategoryParentId($parentCategoryData, $categoryTreeId);
+
+ $searchData = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'category.name',
+ 'type' => 'equals',
+ 'value' => $parentCategoryData['name']
+ ],
+ [
+ 'field' => 'category.parentId',
+ 'type' => 'equals',
+ 'value' => $grandparentId
+ ]
+ ]
+ ];
+ $result = $this->shopwareRequest('POST', 'search/category', $searchData);
+
+
+ if (count($result['data']) === 1) {
+ $parentCategoryData['shopwareid'] = $result['data'][0]['id'];
+ $categoryTreeId[$parentCategoryData['id']] = $parentCategoryData;
+ return $result['data'][0]['id'];
+ }
+ return null;
+ }
+
+ /**
+ * @param string $propertyName
+ *
+ * @return string|null
+ */
+ protected function getPropertyGroupId($propertyName): ?string
+ {
+ if(array_key_exists($propertyName, $this->knownPropertyGroupIds)){
+ return $this->knownPropertyGroupIds[$propertyName];
+ }
+
+ $searchData = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'property_group.name',
+ 'type' => 'equals',
+ 'value' => $propertyName
+ ]
+ ]
+ ];
+
+ $germanLanguageId = $this->getLanguageIdByCountryIso('DE');
+ $headerInformation = ['sw-language-id: ' . $germanLanguageId];
+ $propertyData = $this->shopwareRequest(
+ 'POST',
+ 'search/property-group',
+ $searchData,
+ $headerInformation);
+ if (empty($propertyData['data'][0]['id'])) {
+ return null;
+ }
+
+ $this->knownPropertyGroupIds[$propertyName] = $propertyData['data'][0]['id'];
+
+ return $propertyData['data'][0]['id'];
+ }
+
+ /**
+ * @param string $propertyName
+ * @return null|string
+ */
+ protected function createPropertyGroup($propertyName): ?string
+ {
+ $propertyGroupData = [
+ 'displayType' => 'text',
+ 'name' => $propertyName,
+ 'sortingType' => 'alphanumeric'
+ ];
+ $propertyGroup = $this->shopwareRequest(
+ 'POST',
+ 'property-group?_response=true',
+ $propertyGroupData);
+
+ $this->knownPropertyGroupIds[$propertyName] = $propertyGroup['data']['id'];
+
+ if (empty($propertyGroup['data']['id'])) {
+ return null;
+ }
+
+ return $propertyGroup['data']['id'];
+ }
+
+ /**
+ * @param string $propertyGroupId
+ * @param string $propertyName
+ * @param string $countryIsoCode
+ */
+ protected function createTranslationForPropertyGroup($propertyGroupId, $propertyName, $countryIsoCode): void
+ {
+ $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
+ if (empty($languageId)) {
+ return;
+ }
+
+ $headerInformation = ['sw-language-id: ' . $languageId];
+
+ $translation = [
+ 'name' => $propertyName,
+ ];
+
+ $this->shopwareRequest(
+ 'PATCH',
+ sprintf('property-group/%s', $propertyGroupId),
+ $translation,
+ $headerInformation);
+ }
+
+ /**
+ * @param string $propertyGroupId
+ * @param string $propertyOptionName
+ * @param string $countryIsoCode
+ * @return mixed|null
+ */
+ protected function getPropertyOptionId($propertyGroupId, $propertyOptionName, $countryIsoCode = 'DE'): ?string
+ {
+ $searchData = [
+ 'limit' => 25,
+ 'filter' => [
+ [
+ 'field' => 'property_group_option.name',
+ 'type' => 'equals',
+ 'value' => $propertyOptionName
+ ]
+ ]
+ ];
+ $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
+ $headerInformation = ['sw-language-id: ' . $languageId];
+ $optionData = $this->shopwareRequest(
+ 'POST',
+ 'search/property-group/' . $propertyGroupId . '/options',
+ $searchData,
+ $headerInformation);
+
+ if (empty($optionData['data'][0]['id'])) {
+ return null;
+ }
+
+ return $optionData['data'][0]['id'];
+ }
+
+ /**
+ * @param string $propertyGroupId
+ * @param string $propertyOptionName
+ * @return null|string
+ */
+ protected function createPropertyOption($propertyGroupId, $propertyOptionName): ?string
+ {
+ $propertyOptionData = [
+ 'id' => '',
+ 'name' => $propertyOptionName
+ ];
+ $createdPropertyOption = $this->shopwareRequest(
+ 'POST',
+ 'property-group/' . $propertyGroupId . '/options?_response=true',
+ $propertyOptionData);
+
+ if (empty($createdPropertyOption['data']['id'])) {
+ return null;
+ }
+
+ return $createdPropertyOption['data']['id'];
+ }
+
+ /**
+ * @param string $optionId
+ * @param string $optionName
+ * @param string $countryIsoCode
+ */
+ protected function createTranslationForPropertyOption($optionId, $optionName, $countryIsoCode): void
+ {
+ $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
+ if (empty($languageId)) {
+ return;
+ }
+ $headerInformation = ['sw-language-id: ' . $languageId];
+ $translation = [
+ 'name' => $optionName,
+ ];
+
+ $this->shopwareRequest(
+ 'PATCH',
+ sprintf('property-group-option/%s', $optionId),
+ $translation,
+ $headerInformation);
+ }
+
+ /**
+ * @param array $internalArticle
+ * @param string $articleIdShopware
+ * @return array
+ */
+ protected function propertiesToExport($internalArticle, $articleIdShopware): array
+ {
+ $propertiesToAdd = $this->getPropertiesFromArticle($internalArticle);
+ if (empty($propertiesToAdd)) {
+ return [];
+ }
+ $assignedProperties = [];
+
+ foreach ($propertiesToAdd as $propertyDefaultName => $countryIsoToPropertyTranslation) {
+ if (empty($countryIsoToPropertyTranslation['DE'])) {
+ continue;
+ }
+ $propertyGroupId = '';
+ if (array_key_exists($propertyDefaultName, $this->knownPropertyGroupIds)) {
+ $propertyGroupId = $this->knownPropertyGroupIds[$propertyDefaultName];
+ }
+ if (empty($propertyGroupId)) {
+ $propertyGroupId = $this->getPropertyGroupId($propertyDefaultName);
+ }
+ if (empty($propertyGroupId)) {
+ $propertyGroupId = $this->createPropertyGroup($propertyDefaultName);
+ }
+ if (empty($propertyGroupId)) {
+ $this->Shopware6Log('PropertyGroup kann nicht erstellt werden: ' . $propertyDefaultName);
+ continue;
+ }
+
+ foreach ($countryIsoToPropertyTranslation as $countryIsoCode => $translation) {
+ $this->createTranslationForPropertyGroup($propertyGroupId, $translation['name'], $countryIsoCode);
+ }
+
+
+ $optionId = $this->getPropertyOptionId($propertyGroupId, $countryIsoToPropertyTranslation['DE']['value'], 'DE');
+ if (empty($optionId)) {
+ $optionId = $this->createPropertyOption($propertyGroupId, $countryIsoToPropertyTranslation['DE']['value']);
+ }
+ if (empty($optionId)) {
+ $this->Shopware6Log('Option kann nicht erstellt werden: ' . $countryIsoToPropertyTranslation['DE']['value']);
+ continue;
+ }
+
+ $assignedProperties[] = $optionId;
+
+ foreach ($countryIsoToPropertyTranslation as $countryIsoCode => $translation) {
+ $this->createTranslationForPropertyOption($optionId, $translation['value'], $countryIsoCode);
+ }
+ }
+
+ if (!empty($articleIdShopware)) {
+ $existingProperties = $this->shopwareRequest('GET', 'product/' . $articleIdShopware . '/properties?limit=100');
+ foreach ($existingProperties['data'] as $existingProperty) {
+ if (!in_array($existingProperty['id'], $assignedProperties, false)) {
+ $this->shopwareRequest('DELETE', 'product/' . $articleIdShopware . '/properties/' . $existingProperty['id']);
+ }
+ }
+ }
+
+ $propertiesToAdd = [];
+ foreach ($assignedProperties as $propertyOptionId) {
+ $propertiesToAdd[] = ['id' => $propertyOptionId];
+ }
+
+ return $propertiesToAdd;
+ }
+
+ /**
+ * @param string $name
+ * @param string $value
+ * @return bool
+ */
+ protected function propertyMustBeIgnored(string $name, string $value): bool
+ {
+ return empty($value) ||
+ strpos($name, 'customField_') === 0 ||
+ stripos($name, 'shopware6_') !== false;
+ }
+
+ /**
+ * @param array $internalArticleData
+ * @return array
+ */
+ protected function getPropertiesFromArticle($internalArticleData): array
+ {
+ //'Farbe' => [['DE' => ['name' => 'Farbe, 'value' => 'Gelb']],
+ // ['EN' => ['name' => 'Colour, 'value' => 'Yellow']]]
+ $propertiesToAdd = [];
+ if (!empty($internalArticleData['eigenschaften'])) {
+ foreach ($internalArticleData['eigenschaften'] as $property) {
+ if ($this->propertyMustBeIgnored($property['name'], $property['values'])) {
+ continue;
+ }
+ if (strpos($property['name'], 'property_') === 0) {
+ $propertyName = substr($property['name'], 9);
+ $propertiesToAdd[$propertyName]['DE'] = [
+ 'name' => $propertyName,
+ 'value' => $property['values']];
+ continue;
+ }
+ if ($this->propertyOption === 'toProperties') {
+ $propertiesToAdd[$property['name']]['DE'] = [
+ 'name' => $property['name'],
+ 'value' => $property['values']];
+ }
+ }
+ }
+
+ if (!empty($internalArticleData['eigenschaftenuebersetzungen'])) {
+ foreach ($internalArticleData['eigenschaftenuebersetzungen'] as $translatedProperty) {
+ if ($translatedProperty['language_to'] === 'EN') {
+ $translatedProperty['language_to'] = 'GB';
+ }
+ if ($this->propertyMustBeIgnored($translatedProperty['property_to'], $translatedProperty['property_value_to'])) {
+ continue;
+ }
+ if (strpos($translatedProperty['property_to'], 'property_') === 0) {
+ $propertiesToAdd[$translatedProperty['property_from']][$translatedProperty['language_to']] = [
+ 'name' => substr($translatedProperty['property_to'], 9),
+ 'value' => $translatedProperty['property_value_to']];
+ continue;
+ }
+ if ($this->propertyOption === 'toProperties') {
+ $propertiesToAdd[$translatedProperty['property_from']][$translatedProperty['language_to']] = [
+ 'name' => $translatedProperty['property_to'],
+ 'value' => $translatedProperty['property_value_to']];
+ }
+ }
+ }
+
+ if (!empty($internalArticleData['freifelder'])) {
+ foreach ($internalArticleData['freifelder']['DE'] as $freeFieldKey => $freeFieldValue) {
+ if ($this->propertyMustBeIgnored($freeFieldKey, $freeFieldValue)) {
+ continue;
+ }
+ if (strpos($freeFieldKey, 'property_') === 0) {
+ $propertyName = substr($freeFieldKey, 9);
+ $propertiesToAdd[$propertyName]['DE'] = [
+ 'name' => $propertyName,
+ 'value' => $freeFieldValue
+ ];
+ continue;
+ }
+ if ($this->freeFieldOption === 'toProperties') {
+ $propertiesToAdd[$freeFieldKey]['DE'] = [
+ 'name' => $freeFieldKey,
+ 'value' => $freeFieldValue
+ ];
+ }
+ }
+
+ foreach ($internalArticleData['freifelder'] as $languageIso => $freeFields) {
+ if ($languageIso === 'DE') {
+ continue;
+ }
+ if ($languageIso === 'EN') {
+ $languageIso = 'GB';
+ }
+ foreach ($freeFields as $freeFieldData) {
+ if ($this->propertyMustBeIgnored($freeFieldData['mapping'], $freeFieldData['wert'])) {
+ continue;
+ }
+ if (strpos($freeFieldData['mapping'], 'property_') === 0) {
+ $propertyName = substr($freeFieldData['mapping'], 9);
+ $propertiesToAdd[$propertyName][$languageIso] = [
+ 'name' => $propertyName,
+ 'value' => $freeFieldData['wert']
+ ];
+ continue;
+ }
+ if ($this->freeFieldOption === 'toProperties') {
+ $propertiesToAdd[$freeFieldData['mapping']][$languageIso] = [
+ 'name' => $freeFieldData['mapping'],
+ 'value' => $freeFieldData['wert']
+ ];
+ }
+ }
+ }
+ }
+
+ return $propertiesToAdd;
+ }
+
+ /**
+ * @param array $articleInXentral
+ * @param string $articleIdShopware
+ *
+ * @return array
+ */
+ protected function customFieldsToExport($articleInXentral, $articleIdShopware): array
+ {
+ $customFieldsToAdd = $this->getCustomFieldsFromArticle($articleInXentral);
+ if (empty($customFieldsToAdd)) {
+ return [];
+ }
+ $languageId = $this->getLanguageIdByCountryIso('DE');
+ $headerInformation = ['sw-language-id: ' . $languageId];
+
+ $customFields = [];
+ if (!empty($articleIdShopware)) {
+ $articleInfo = $this->shopwareRequest(
+ 'GET', 'product/' . $articleIdShopware,
+ [],
+ $headerInformation);
+ $customFields['DE'] = $articleInfo['data'][0]['attributes']['customFields'];
+ if ($customFields === null) {
+ $customFields = [];
+ }
+ }
+
+ foreach ($customFieldsToAdd as $defaultFieldName => $countryIsoCodeToCustomFieldData) {
+ $customFieldDefinition = $this->shopwareRequest(
+ 'GET',
+ sprintf('custom-field?filter[custom_field.name]=%s', $defaultFieldName),
+ [],
+ $headerInformation
+ );
+ if (empty($customFieldDefinition)) {
+ $this->Shopware6Log('Freifeld entspricht keinem shopware Freifeld', $defaultFieldName);
+ continue;
+ }
+
+ foreach ($countryIsoCodeToCustomFieldData as $countryIsoCode => $customFieldData) {
+ $name = $customFieldData['name'];
+ $value = $customFieldData['value'];
+ if ($value === '') {
+ continue;
+ }
+ if($countryIsoCode === 'EN'){
+ $countryIsoCode = 'GB';
+ }
+ $fieldType = $customFieldDefinition['data'][0]['attributes']['type'];
+ $controlType = $customFieldDefinition['data'][0]['attributes']['config']['componentName'];
+
+ switch ($fieldType) {
+ case 'text':
+ case 'html':
+ if ($controlType === 'sw-media-field') {
+ $this->Shopware6Log(
+ 'Warnung: Freifelder vom Type "medium" werden nicht unterstützt.'
+ );
+ } else {
+ $customFields[$countryIsoCode][$name] = (string)$value;
+ }
+ break;
+ case 'bool':
+ $customFields[$countryIsoCode][$name] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
+ break;
+ case 'int':
+ $customFields[$countryIsoCode][$name] = (int)$value;
+ break;
+ case 'float':
+ $customFields[$countryIsoCode][$name] = (float)$value;
+ break;
+ case 'select':
+ $options = $customFieldDefinition['data'][0]['attributes']['config']['options'];
+ $allowedValues = [];
+ foreach ($options as $option) {
+ $allowedValues[] = $option['value'];
+ }
+ if ($controlType === 'sw-single-select') {
+ if (in_array($value, $allowedValues, true)) {
+ $customFields[$countryIsoCode][$name] = $value;
+ } else {
+ $this->Shopware6Log(
+ sprintf('Warnung: Freifeld "%s"="%s"; ungültiger Wert', $name, $value),
+ ['allowed values' => $allowedValues]
+ );
+ }
+ }
+ if ($controlType === 'sw-multi-select') {
+ $value = explode(',', $value);
+ foreach ($value as &$item) {
+ $item = trim($item);
+ }
+ unset($item);
+ if (array_intersect($value, $allowedValues) === $value) {
+ $customFields[$countryIsoCode][$name] = $value;
+ } else {
+ $this->Shopware6Log(
+ sprintf('Warnung: Freifeld "%s"; ungültiger Wert', $name),
+ ['values' => $value, 'allowed values' => $allowedValues]
+ );
+ }
+ }
+ break;
+ default:
+ $this->Shopware6Log(
+ 'Warnung: Freifeld enthält falschen Typ.',
+ ['freifeld' => $name, 'wert' => $value]
+ );
+ continue 2;
+ }
+ }
+ }
+
+
+ return $customFields;
+ }
+
+ /**
+ * @param string $name
+ * @param string $value
+ * @return bool
+ */
+ protected function customFieldMustBeIgnored(string $name, string $value): bool
+ {
+ return empty($value) ||
+ strpos($name, 'property_') === 0 ||
+ stripos($name, 'shopware6_') !== false;
+ }
+
+ /**
+ * @param array $articleInXentral
+ * @return array
+ */
+ protected function getCustomFieldsFromArticle($articleInXentral): array
+ {
+ $customFieldsToAdd = [];
+ if (!empty($articleInXentral['eigenschaften'])) {
+ foreach ($articleInXentral['eigenschaften'] as $propertyInXentral) {
+ if ($this->customFieldMustBeIgnored($propertyInXentral['name'], $propertyInXentral['values'])) {
+ continue;
+ }
+ if (strpos($propertyInXentral['name'], 'customField_') === 0) {
+ $customFieldName = substr($propertyInXentral['name'], 12);
+ $customFieldsToAdd[$customFieldName]['DE'] = [
+ 'name' => $customFieldName,
+ 'value' => $propertyInXentral['values']
+ ];
+ continue;
+ }
+ if ($this->propertyOption === 'toCustomFields') {
+ $customFieldsToAdd[$propertyInXentral['name']]['DE'] = [
+ 'name' => $propertyInXentral['name'],
+ 'value' => $propertyInXentral['values']
+ ];
+ }
+ }
+ }
+ if (!empty($articleInXentral['eigenschaftenuebersetzungen'])) {
+ foreach ($articleInXentral['eigenschaftenuebersetzungen'] as $translatedProperty) {
+ if ($this->customFieldMustBeIgnored($translatedProperty['property_to'], $translatedProperty['property_value_to'])) {
+ continue;
+ }
+ if (strpos($translatedProperty['property_to'], 'customField_') === 0) {
+ $customFieldName = substr($translatedProperty['property_to'], 12);
+ $customFieldsToAdd[$customFieldName][$translatedProperty['language_to']] = [
+ 'name' => $customFieldName,
+ 'value' => $translatedProperty['property_value_to']
+ ];
+ continue;
+ }
+ if ($this->propertyOption === 'toCustomFields') {
+ $customFieldsToAdd[$translatedProperty['property_to']][$translatedProperty['language_to']] = [
+ 'name' => $translatedProperty['property_to'],
+ 'value' => $translatedProperty['property_value_to']
+ ];
+ }
+ }
+ }
+
+ if (!empty($articleInXentral['freifelder'])) {
+ foreach ($articleInXentral['freifelder']['DE'] as $freeFieldKey => $freeFieldValue) {
+ if ($this->customFieldMustBeIgnored($freeFieldKey, $freeFieldValue)) {
+ continue;
+ }
+ if (strpos($freeFieldKey, 'customField_') === 0) {
+ $customFieldName = substr($freeFieldKey, 12);
+ $customFieldsToAdd[$customFieldName]['DE'] = [
+ 'name' => $customFieldName,
+ 'value' => $freeFieldValue
+ ];
+ continue;
+ }
+ if ($this->freeFieldOption === 'toCustomFields') {
+ $customFieldsToAdd[$freeFieldKey]['DE'] = [
+ 'name' => $freeFieldKey,
+ 'value' => $freeFieldValue
+ ];
+ }
+ }
+
+ foreach ($articleInXentral['freifelder'] as $countryIsoCode => $freeFieldTranslations) {
+ if ($countryIsoCode === 'DE') {
+ continue;
+ }
+ foreach ($freeFieldTranslations as $freeFieldTranslation){
+ if ($this->customFieldMustBeIgnored($freeFieldTranslation['mapping'], $freeFieldTranslation['wert'])) {
+ continue;
+ }
+ if ($countryIsoCode === 'EN') {
+ $countryIsoCode = 'GB';
+ }
+ if (strpos($freeFieldTranslation['mapping'], 'customField_') === 0) {
+ $customFieldName = substr($freeFieldTranslation['mapping'], 12);
+ $customFieldsToAdd[$customFieldName][$countryIsoCode] = [
+ 'name' => $customFieldName,
+ 'value' => $freeFieldTranslation['wert']
+ ];
+ continue;
+ }
+ if ($this->freeFieldOption === 'toCustomFields') {
+ $customFieldsToAdd[$freeFieldTranslation['mapping']][$countryIsoCode] = [
+ 'name' => $freeFieldTranslation['mapping'],
+ 'value' => $freeFieldTranslation['wert']
+ ];
+ }
+ }
+ }
+ }
+
+ return $customFieldsToAdd;
+ }
+
+ /**
+ * @param array $articleInXentral
+ * @param int $articleIdShopware
+ *
+ * @return array
+ */
+ protected function crosssellingToExport($articleInXentral, $articleIdShopware){
+ if (empty($articleInXentral['crosssellingartikel'])) {
+ return [];
+ }
+
+ $crosssellingArticles = [];
+ foreach ($articleInXentral['crosssellingartikel'] as $crosssellingArticle){
+ $type = 'Ähnlich';
+ if($crosssellingArticle['art'] == 2){
+ $type = 'Zubehör';
+ }
+ $crosssellingArticles[$type][] = $crosssellingArticle['nummer'];
+ }
+ $crossselingInformation = [];
+ foreach ($crosssellingArticles as $type => $articles){
+ if(!empty($articleIdShopware)){
+ $existingCrossSellings = $this->shopwareRequest('GET', sprintf('product/%s/cross-sellings/',
+ $articleIdShopware));
+ if(!empty($existingCrossSellings['data'])){
+ foreach ($existingCrossSellings['data'] as $existingCrossSelling){
+ if($existingCrossSelling['attributes']['name'] === $type){
+ $this->shopwareRequest('DELETE', sprintf('product/%s/cross-sellings/%s/',
+ $articleIdShopware, $existingCrossSelling['id']));
+ }
+ }
+ }
+ }
+
+ $crosselingToAdd = [];
+ foreach ($articles as $articleNumber) {
+ $articleInfo = $this->shopwareRequest(
+ 'GET',
+ sprintf('product?filter[product.productNumber]=%s', $articleNumber)
+ );
+
+ if(empty($articleInfo['data'][0]['id'])){
+ continue;
+ }
+ $crosselingToAdd[] = $articleInfo['data'][0]['id'];
+ }
+ if(empty($crosselingToAdd)){
+ continue;
+ }
+ $crossselingInformationForType = [
+ 'active' => true,
+ 'name' => $type,
+ 'assignedProducts' => [],
+ 'type' => 'productList',
+ 'sortBy' => 'name',
+ 'limit' => 24,
+ 'position' => 1
+ ];
+ $position = 1;
+ foreach ($crosselingToAdd as $articleId){
+ $crossselingInformationForType['assignedProducts'][] = [
+ 'productId' => $articleId,
+ 'position' => $position,
+ ];
+ $position++;
+ }
+ $crossselingInformation[] = $crossselingInformationForType;
+ }
+
+
+ return $crossselingInformation;
+ }
+
+ /**
+ * @param string $unitShortCode
+ *
+ * @return string
+ */
+ protected function unitToAdd(string $unitShortCode): string{
+ $searchData = [
+ 'limit' => 25,
+ 'source' => [
+ 'id'
+ ],
+ 'filter' => [
+ [
+ 'field' => 'unit.shortCode',
+ 'type' => 'equals',
+ 'value' => $unitShortCode
+ ]
+ ]
+ ];
+ $unitInShopware = $this->shopwareRequest(
+ 'POST',
+ 'search/unit',
+ $searchData);
+
+ if(!empty($unitInShopware['data'][0]['id'])){
+ return $unitInShopware['data'][0]['id'];
+ }
+
+ $query = sprintf("SELECT `internebemerkung` FROM `artikeleinheit` WHERE `einheit_de` = '%s' LIMIT 1",
+ $unitShortCode);
+ $unitName = $this->app->DB->Select($query);
+ if(empty($unitName)){
+ $unitName = $unitShortCode;
+ }
+
+ $unitInformation = [
+ 'name' => $unitName,
+ 'shortCode' => $unitShortCode
+ ];
+ $result = $this->shopwareRequest('POST', 'unit?_response=true', $unitInformation);
+
+ if(empty($result['data']['id'])){
+ return '';
+ }
+
+ return $result['data']['id'];
+ }
+
+ /**
+ * @param array $internArticle
+ * @param int $articleIdShopware
+ *
+ * @return array
+ */
+ protected function systemFieldsToExport($internArticle, $articleIdShopware): array
+ {
+ $internalSpecialFields = [];
+ foreach ($internArticle['freifelder']['DE'] as $freeFieldName => $freeFieldValue) {
+ if (stripos($freeFieldName, 'shopware6_') !== false) {
+ $internalSpecialFields[$freeFieldName] = $freeFieldValue;
+ }
+ }
+ foreach ($internArticle['eigenschaften'] as $property) {
+ if (stripos($property['name'], 'shopware6_') !== false) {
+ $internalSpecialFields[$property['name']] = $property['values'];
+ }
+ }
+
+ $systemFields = [];
+ foreach ($internalSpecialFields as $fieldName => $fieldValue) {
+ switch (strtolower($fieldName)) {
+ case 'shopware6_sales_channel':
+ $systemFields['visibilities'] = $this->modifySalesChannel(explode(',', $fieldValue), $articleIdShopware);
+ break;
+ case 'shopware6_purchase_unit':
+ $systemFields['purchaseUnit'] = (float)str_replace(',', '.', $fieldValue);
+ break;
+ case 'shopware6_reference_unit':
+ $systemFields['referenceUnit'] = (float)str_replace(',', '.', $fieldValue);
+ break;
+ case 'shopware6_unit':
+ $systemFields['unitId'] = $this->unitToAdd($fieldValue);
+ break;
+ case 'shopware6_pack_unit':
+ $systemFields['packUnit'] = (string)$fieldValue;
+ break;
+ case 'shopware6_restock_time':
+ $systemFields['restockTime'] = (int)$fieldValue;
+ break;
+ case 'shopware6_pack_unit_plural':
+ $systemFields['packUnitPlural'] = (string)$fieldValue;
+ break;
+ }
+ }
+
+ return $systemFields;
+ }
+
+ /**
+ * @param array $salesChannelNames
+ * @param string $articleIdInShopware
+ *
+ * @return array
+ */
+ protected function modifySalesChannel($salesChannelNames, $articleIdInShopware)
+ {
+ $salesChannelInXentralIds = [];
+ foreach ($salesChannelNames as $salesChannelName) {
+ $salesChannelInfo = $this->shopwareRequest('GET',
+ sprintf('sales-channel?filter[sales_channel.name]=%s', urlencode(trim($salesChannelName)))
+ );
+ if (!empty($salesChannelInfo['data'][0]['id'])) {
+ $salesChannelInXentralIds[] = $salesChannelInfo['data'][0]['id'];
+ }
+ }
+
+ $existingVisibilities = $this->shopwareRequest(
+ 'GET',
+ sprintf('product/%s/visibilities', $articleIdInShopware)
+ );
+
+ $existingSalesChannelIds = [];
+ if (!empty($existingVisibilities['data'])) {
+ foreach ($existingVisibilities['data'] as $visibility) {
+ $existingSalesChannelIds[$visibility['id']] = $visibility['attributes']['salesChannelId'];
+ }
+ }
+
+ foreach ($existingSalesChannelIds as $associationId => $existingSalesChannelId){
+ if (!in_array($existingSalesChannelId, $salesChannelInXentralIds,true)) {
+ $this->shopwareRequest('DELETE', sprintf('product/%s/visibilities/%s/',
+ $articleIdInShopware, $associationId));
+ }
+ }
+
+ $salesChannelsToAdd = [];
+ foreach ($salesChannelInXentralIds as $salesChannelInXentralId){
+ if (!in_array($salesChannelInXentralId, $existingSalesChannelIds,true)) {
+ $salesChannelsToAdd[] = $salesChannelInXentralId;
+ }
+ }
+
+ $visibilities = [];
+ foreach ($salesChannelsToAdd as $salesChannelIdToAdd) {
+ $visibilities[] = [
+ 'salesChannelId' => $salesChannelIdToAdd,
+ 'visibility' => 30
+ ];
+ }
+
+ return $visibilities;
+ }
+
+ /**
+ * @param string $isoCode
+ *
+ * @return string
+ */
+ protected function findCurrencyId($isoCode)
+ {
+
+ $this->requestCurrencyMappingLazy();
+ if (isset($this->currencyMapping[strtoupper($isoCode)])) {
+ return $this->currencyMapping[strtoupper($isoCode)];
+ }
+ $this->Shopware6Log(
+ sprintf('Warnung: Kein Mapping für Waehrung "%s" gefunden.', $isoCode),
+ $this->currencyMapping
+ );
+
+ return null;
+ }
+
+ /**
+ * request currency mapping only once
+ */
+ protected function requestCurrencyMappingLazy()
+ {
+
+ if ($this->currencyMapping !== null) {
+ return;
+ }
+ $currencies = $this->shopwareRequest('GET', 'currency');
+ if (!isset($currencies['data'])) {
+ $this->Shopware6Log('Kann Währungsmapping nicht abrufen', $currencies);
+ }
+ foreach ($currencies['data'] as $currency) {
+ $isoCode = strtoupper($currency['attributes']['isoCode']);
+ $this->currencyMapping[$isoCode] = $currency['id'];
+ }
+ }
+
+ /**
+ * @param array $internalArticleData
+ * @param string $articleIdInShopware
+ * @return bool
+ */
+ public function exportSeoUrls(array $internalArticleData, string $articleIdInShopware): bool
+ {
+ if (empty($articleIdInShopware)) {
+ return false;
+ }
+
+ $preparedSeoInformation = [];
+ foreach ($internalArticleData['freifelder'] as $countryIsoCode => $freeFieldInformation) {
+ if($countryIsoCode === 'EN'){
+ $countryIsoCode = 'GB';
+ }
+ if($countryIsoCode === 'DE'){
+ foreach ($freeFieldInformation as $freeFieldName => $freeFieldValue) {
+ if (stripos($freeFieldName, 'shopware6_seo_url') !== false) {
+ $preparedSeoInformation[$countryIsoCode][$freeFieldName] = $freeFieldValue;
+ }
+ }
+ }else{
+ foreach ($freeFieldInformation as $freeFieldData) {
+ if (stripos($freeFieldData['mapping'], 'shopware6_seo_url') !== false) {
+ $preparedSeoInformation[$countryIsoCode][$freeFieldData['mapping']] = $freeFieldData['wert'];
+ }
+ }
+ }
+ }
+ foreach ($internalArticleData['eigenschaften'] as $property) {
+ if (stripos($property['name'], 'shopware6_seo_url') !== false) {
+ $preparedSeoInformation['DE'][$property['name']] = $property['values'];
+ }
+ }
+ foreach ($internalArticleData['eigenschaftenuebersetzungen'] as $propertyTranslation) {
+ if($propertyTranslation['language_to'] === 'EN'){
+ $propertyTranslation['language_to'] = 'GB';
+ }
+ if (stripos($propertyTranslation['property_to'], 'shopware6_seo_url') !== false) {
+ $preparedSeoInformation[$propertyTranslation['language_to']][$propertyTranslation['property_to']] = $propertyTranslation['property_value_to'];
+ }
+ }
+
+ $specificSalesChannelSeoUrls = [];
+ $defaultSeoUrls = [];
+ foreach ($preparedSeoInformation as $countryIsoCode => $channelAssociations) {
+ foreach ($channelAssociations as $fieldName => $fieldValue){
+ if(strtolower($fieldName) === 'shopware6_seo_url'){
+ $defaultSeoUrls[$countryIsoCode] = $fieldValue;
+ }else{
+ $seoInformation = explode('|', $fieldName);
+ $specificSalesChannelSeoUrls[$countryIsoCode][array_pop($seoInformation)] = $fieldValue;
+ }
+ }
+ }
+
+ if (empty($specificSalesChannelSeoUrls) && empty($defaultSeoUrls)) {
+ return false;
+ }
+
+ $salesChannelsIdToName = [];
+ $salesChannels = $this->shopwareRequest('GET','sales-channel');
+ foreach ($salesChannels['data'] as $salesChannel) {
+ $salesChannelsIdToName[$salesChannel['id']] = $salesChannel['attributes']['name'];
+ }
+
+ foreach ($preparedSeoInformation as $countryIsoCode => $x){
+ $languageId = $this->getLanguageIdByCountryIso($countryIsoCode);
+ if (empty($languageId)) {
+ $this->Shopware6Log('Language Id not found for country: ' . $countryIsoCode);
+ continue;
+ }
+
+ $headerInformation = ['sw-language-id: ' . $languageId];
+ foreach ($salesChannelsIdToName as $salesChannelId => $salesChannelName) {
+ $seoUrlToUse = $defaultSeoUrls[$countryIsoCode];
+ if (!empty($specificSalesChannelSeoUrls[$countryIsoCode][$salesChannelName])) {
+ $seoUrlToUse = $specificSalesChannelSeoUrls[$countryIsoCode][$salesChannelsIdToName[$salesChannelName]];
+ }
+ if (empty($seoUrlToUse)) {
+ continue;
+ }
+ $seoDataToSend = [
+ 'seoPathInfo' => $seoUrlToUse,
+ '_isNew' => true,
+ 'isModified' => true,
+ 'isCanonical' => true,
+ 'isDeleted' => false,
+ 'routeName' => 'frontend.detail.page',
+ 'foreignKey' => $articleIdInShopware,
+ 'pathInfo' => '/detail/'.$articleIdInShopware,
+ 'languageId' => $languageId,
+ 'salesChannelId' => $salesChannelId];
+ $this->shopwareRequest('PATCH', '_action/seo-url/canonical', $seoDataToSend, $headerInformation);
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @param array $article
+ * @param string $articleIdShopware
+ * @param string $currencyId
+ *
+ * @return bool
+ */
+ protected function exportVariants($article, $articleIdShopware, $currencyId): bool
+ {
+ $languageId = $this->getLanguageIdByCountryIso('DE');
+ if (empty($languageId)) {
+ return false;
+ }
+ if (empty($article['matrix_varianten']) || empty($articleIdShopware)) {
+ return false;
+ }
+ $internalGroupPropertiesToShopwareId = [];
+ foreach ($article['matrix_varianten']['gruppen'] as $propertyGroupName => $internalPropertyGroupValues) {
+ $propertyGroupId = '';
+ if (array_key_exists($propertyGroupName, $this->knownPropertyGroupIds)) {
+ $propertyGroupId = $this->knownPropertyGroupIds[$propertyGroupName];
+ }
+ if (empty($propertyGroupId)) {
+ $propertyGroupId = $this->getPropertyGroupId($propertyGroupName);
+ }
+ if (empty($propertyGroupId)) {
+ $propertyGroupId = $this->createPropertyGroup($propertyGroupName);
+ }
+ if (empty($propertyGroupId)) {
+ $this->Shopware6Log('PropertyGroup kann nicht erstellt werden: ' . $propertyGroupName);
+ return false;
+ }
+
+ if (!empty($article['matrix_varianten']['texte'])) {
+ $this->createTranslationForPropertyGroup($propertyGroupId, $propertyGroupName, 'DE');
+
+ foreach ($article['matrix_varianten']['texte']['gruppen'] as $countryIsoCode => $matrixGroupTranslation) {
+ if ($countryIsoCode === 'EN') {
+ $countryIsoCode = 'GB';
+ }
+
+ $this->createTranslationForPropertyGroup($propertyGroupId, $matrixGroupTranslation[$propertyGroupName], $countryIsoCode);
+ }
+ }
+
+ $languageId = $this->getLanguageIdByCountryIso('DE');
+ $headerInformation = ['sw-language-id: ' . $languageId];
+ $shopwarePropertyGroupOptions = $this->shopwareRequest(
+ 'GET',
+ 'property-group/' . $propertyGroupId . '/options?limit=100',
+ $headerInformation);
+ foreach ($shopwarePropertyGroupOptions['data'] as $shopwarePropertyGroupOption) {
+ $propertyValue = $shopwarePropertyGroupOption['attributes']['name'];
+ $internalGroupPropertiesToShopwareId[$propertyGroupName][$propertyValue] = $shopwarePropertyGroupOption['id'];
+ }
+
+ foreach ($internalPropertyGroupValues as $internalPropertyGroupValue => $valueNotNeeded) {
+ if (!array_key_exists($internalPropertyGroupValue, $internalGroupPropertiesToShopwareId[$propertyGroupName])) {
+ $newOptionData = [
+ 'name' => (string)$internalPropertyGroupValue
+ ];
+ $optionData = $this->shopwareRequest(
+ 'POST',
+ 'property-group/' . $propertyGroupId . '/options?_response=true',
+ $newOptionData);
+ $internalGroupPropertiesToShopwareId[$propertyGroupName][$internalPropertyGroupValue] = $optionData['data']['id'];
+ }
+ }
+
+ if (!empty($article['matrix_varianten']['texte'])) {
+ foreach ($internalPropertyGroupValues as $optionValue => $valueNotNeeded) {
+ $optionId = $internalGroupPropertiesToShopwareId[$propertyGroupName][$optionValue];
+ $this->createTranslationForPropertyOption(
+ $optionId,
+ $optionValue,
+ 'DE');
+ foreach ($article['matrix_varianten']['texte']['werte'] as $countryIsoCode => $matrixOptionTranslations) {
+ if ($countryIsoCode === 'EN') {
+ $countryIsoCode = 'GB';
+ }
+ if (array_key_exists($optionValue, $matrixOptionTranslations)) {
+ $this->createTranslationForPropertyOption(
+ $optionId,
+ $matrixOptionTranslations[$optionValue],
+ $countryIsoCode);
+ }
+ }
+ }
+ }
+ }
+
+ $existingCombinations = $this->shopwareRequest(
+ 'GET',
+ '_action/product/' . $articleIdShopware . '/combinations');
+ $existingCombinationsByNumber = [];
+
+ foreach ($existingCombinations as $combinationId => $combinationInfo) {
+ $existingCombinationsByNumber[$combinationInfo['productNumber']] = [
+ 'id' => $combinationId,
+ 'options' => [],
+ ];
+ foreach ($combinationInfo['options'] as $combinationOption) {
+ $existingCombinationsByNumber[$combinationInfo['productNumber']]['options'][$combinationOption] = $combinationOption;
+ }
+ }
+
+
+ foreach ($article['artikel_varianten'] as $variant) {
+ $internalVariantMatrixData = $article['matrix_varianten']['artikel'][$variant['artikel']];
+ $productNumber = $internalVariantMatrixData[0]['nummer'];
+ $name = $variant['name_de'];
+ $stock = $variant['lag'];
+ $ean = $variant['ean'];
+ $weight = (float)$variant['gewicht'];
+ $pseudoPrice = $variant['pseudopreis'];
+ if (empty($pseudoPrice)) {
+ $pseudoPrice = 0;
+ }
+ if (!empty($variant['pseudolager'])) {
+ $stock = $variant['pseudolager'];
+ }
+ $active = true;
+ if (!empty($variant['inaktiv'])) {
+ $active = false;
+ }
+ $isCloseOut = false;
+ if (!empty($variant['restmenge'])) {
+ $isCloseOut = true;
+ }
+
+ $variantProductData = [
+ 'active' => $active,
+ 'isCloseout' => $isCloseOut,
+ 'name' => $name,
+ 'description' => null,
+ 'weight' => null,
+ 'price' => [
+ [
+ 'currencyId' => $currencyId,
+ 'gross' => $variant['bruttopreis'],
+ 'net' => $variant['preis'],
+ 'linked' => true,
+ 'listPrice' => [
+ 'currencyId' => $currencyId,
+ 'gross' => $pseudoPrice,
+ 'linked' => true,
+ 'net' => $pseudoPrice / (1 + $variant['steuersatz'] / 100)
+ ]
+ ]
+ ],
+ 'stock' => (int)$stock,
+ 'ean' => null,
+ 'taxId' => $this->getTaxIdByRate($variant['steuersatz']),
+ ];
+ if(!empty($weight)){
+ $variantProductData['weight'] = $weight;
+ }
+ if(!empty($ean)){
+ $variantProductData['ean'] = $ean;
+ }
+ if (!empty($variant['uebersicht_de'])) {
+ $variantProductData['description'] = $variant['uebersicht_de'];
+ }
+
+ $renewVariant = false;
+ $options = [];
+ foreach ($internalVariantMatrixData as $expression) {
+ if (!in_array(
+ $internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']],
+ $existingCombinationsByNumber[$productNumber]['options'],
+ false)) {
+ $renewVariant = true;
+ } else {
+ unset($existingCombinationsByNumber[$productNumber]['options'][$internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']]]);
+ }
+ $options[] = ['id' => $internalGroupPropertiesToShopwareId[$expression['name']][$expression['values']]];
+ }
+
+ if (!empty($existingCombinationsByNumber[$productNumber]['options'])) {
+ $renewVariant = true;
+ }
+
+ $variantImageData = [
+ 'Dateien' => []
+ ];
+ $variantProductId = '';
+ if (!empty($existingCombinationsByNumber[$productNumber]['id']) && !$renewVariant) {
+ $variantProductId = $existingCombinationsByNumber[$productNumber]['id'];
+ }
+ if (!empty($variant['Dateien']['id'])) {
+ foreach ($variant['Dateien']['id'] as $index => $fileId) {
+ $variantImageData['Dateien'][] = [
+ 'filename' => $variant['Dateien']['filename'][$index],
+ 'extension' => $variant['Dateien']['extension'][$index],
+ 'datei' => $variant['Dateien']['datei'][$index],
+ 'beschreibung' => $variant['Dateien']['beschreibung'][$index],
+ 'titel' => $variant['Dateien']['titel'][$index],
+ 'id' => $fileId,
+ ];
+ }
+ }
+ $mediaToAdd = $this->mediaToExport($variantImageData, $variantProductId);
+ $variantProductData['media'] = $mediaToAdd;
+
+ if ($renewVariant) {
+ if (!empty($existingCombinationsByNumber[$productNumber]['id'])) {
+ $this->shopwareRequest('DELETE', 'product/' . $existingCombinationsByNumber[$productNumber]['id']);
+ }
+ $variantProductData['productNumber'] = $productNumber;
+ $variantProductData['parentId'] = $articleIdShopware;
+ $variantProductData['options'] = $options;
+
+ $result = $this->shopwareRequest('POST', 'product?_response=true', $variantProductData);
+ $variantProductId = $result['data']['id'];
+ } else {
+ $variantProductId = $existingCombinationsByNumber[$productNumber]['id'];
+ $this->shopwareRequest('PATCH', 'product/' . $variantProductId, $variantProductData);
+ }
+
+ $defaultPrices = $this->getPricesFromArray($variant['staffelpreise_standard'] ?? []);
+ $groupPrices = $this->getPricesFromArray($variant['staffelpreise_gruppen'] ?? []);
+
+ $this->deleteOldBulkPrices($variantProductId);
+ if (!empty($defaultPrices)) {
+ foreach ($defaultPrices as $priceData) {
+ $this->exportBulkPriceForGroup($variantProductId, $this->defaultRuleName, $priceData);
+ }
+ }
+ if (!empty($groupPrices)) {
+ foreach ($groupPrices as $priceData) {
+ $this->exportBulkPriceForGroup($variantProductId, $priceData->getGroupName(), $priceData);
+ }
+ }
+
+ $this->addCoverImage($variantImageData, $variantProductId);
+ }
+
+ $existingConfigurations = $this->shopwareRequest(
+ 'GET', 'product/' . $articleIdShopware . '/configuratorSettings');
+ $optionIdsToAdd = [];
+ foreach ($article['artikel_varianten'] as $variant) {
+ foreach ($article['matrix_varianten']['artikel'][$variant['artikel']] as $matrixInfo) {
+ $configurationExists = false;
+ foreach ($existingConfigurations['data'] as $configuration) {
+ if ($configuration['attributes']['optionId'] === $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']]) {
+ $configurationExists = true;
+ break;
+ }
+ }
+ if (!$configurationExists) {
+ $optionIdsToAdd[] = $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']];
+ }
+ }
+ }
+ if (!empty($optionIdsToAdd)) {
+ $optionIdsToAdd = array_flip(array_flip($optionIdsToAdd));
+ $configurationData = [
+ 'configuratorSettings' => []
+ ];
+ foreach ($optionIdsToAdd as $id) {
+ $configurationData['configuratorSettings'][] = ['optionId' => $id];
+ }
+
+ $this->shopwareRequest(
+ 'PATCH',
+ sprintf('product/%s', $articleIdShopware),
+ $configurationData
+ );
+
+ $existingConfigurations = $this->shopwareRequest(
+ 'GET', 'product/' . $articleIdShopware . '/configuratorSettings');
+ $optionsToSort = [];
+ foreach ($article['artikel_varianten'] as $variant) {
+ foreach ($article['matrix_varianten']['artikel'][$variant['artikel']] as $matrixInfo) {
+ foreach ($existingConfigurations['data'] as $configuration) {
+ if ($configuration['attributes']['optionId'] === $internalGroupPropertiesToShopwareId[$matrixInfo['name']][$matrixInfo['values']]) {
+ $optionsToSort[] = $configuration['id'];
+ break;
+ }
+ }
+ }
+ }
+ if (!empty($optionsToSort)) {
+ $optionsToSort = array_flip(array_flip($optionsToSort));
+ $configurationData = [
+ 'configuratorSettings' => []
+ ];
+ $position = 1;
+
+ foreach ($optionsToSort as $id) {
+ $configurationData['configuratorSettings'][] = [
+ 'id' => $id,
+ 'position' => $position];
+ $position++;
+ }
+
+ $this->shopwareRequest(
+ 'PATCH',
+ sprintf('product/%s', $articleIdShopware),
+ $configurationData
+ );
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @param $priceArray
+ * @return PriceData[]
+ */
+ protected function getPricesFromArray($priceArray): array{
+ return array_map(static function($price){
+ return new PriceData(
+ (int)$price['ab_menge'],
+ (float)$price['preis'],
+ (float)$price['bruttopreis'],
+ $price['waehrung'],
+ $price['gruppeextern'] ?? '') ;
+ },$priceArray);
+ }
+
+ /**
+ * delete all old price entries for a product
+ *
+ * @param string $productId
+ */
+ protected function deleteOldBulkPrices($productId)
+ {
+ //TODO Instead of deleting all old prices we should rather check first whether they are still in order
+ $oldPrices = $this->shopwareRequest(
+ 'GET',
+ sprintf('product-price?filter[product_price.productId]=%s', $productId)
+ );
+ if (is_array($oldPrices)) {
+ foreach ($oldPrices['data'] as $deletePrice) {
+ $this->shopwareRequest('DELETE', 'product-price/' . $deletePrice['id']);
+ }
+ } else {
+ $this->Shopware6Log('Fehler: Alte Preise wurden nicht gelöscht', $productId);
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getOrderSearchLimit(): int
+ {
+ if(in_array($this->orderSearchLimit, ['50', '75', '100'])) {
+ return (int)$this->orderSearchLimit;
+ }
+
+ return 25;
+ }
+
+ /**
+ * @return int
+ */
+ public function ImportGetAuftraegeAnzahl()
+ {
+ $order = null;
+ $dataToGet = $this->CatchRemoteCommand('data');
+
+ if (empty($this->statesToFetch)) {
+ return false;
+ }
+
+ $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit());
+
+ return (!empty(count($ordersToProcess['data'])?count($ordersToProcess['data']):0));
+ }
+
+ /**
+ * @param string $parameter1
+ * @param string $parameter2
+ */
+ public function Shopware6ErrorLog($parameter1, $parameter2 = '')
+ {
+ $this->app->DB->Insert(
+ sprintf(
+ "INSERT INTO `shopexport_log`
+ (shopid, typ, parameter1, parameter2, bearbeiter, zeitstempel)
+ VALUES (%d, 'fehler', '%s','%s','%s',NOW())",
+ $this->shopid,
+ $this->app->DB->real_escape_string($parameter1),
+ $this->app->DB->real_escape_string($parameter2),
+ $this->app->DB->real_escape_string($this->app->User->GetName())
+ )
+ );
+ }
+
+ /**
+ * @param array $stateMachinesIds
+ * @return array
+ */
+ protected function getTransactionStateIdsToFetch($stateMachinesIds): array
+ {
+ $transactionStateIdsToFetch = [];
+ if (!empty($this->transactionStatesToFetch)) {
+ $transactionStatesToFetch = explode(';', $this->transactionStatesToFetch);
+ foreach ($transactionStatesToFetch as $transactionStateToFetch) {
+ $stateInformation = $this->shopwareRequest('GET', 'state-machine-state?filter[technicalName]=' .
+ trim($transactionStateToFetch) . '&filter[stateMachineId]=' . $stateMachinesIds['order_transaction.state']);
+ if (empty($stateInformation['data'])) {
+ $this->Shopware6ErrorLog('Zahlungsstatus für Abholung nicht gefunden', $transactionStateToFetch);
+ return false;
+ }
+ foreach ($stateInformation['data'] as $state) {
+ $transactionStateIdsToFetch[] = $state['id'];
+ }
+ }
+ }
+
+ return $transactionStateIdsToFetch;
+ }
+
+ /**
+ * @param int $limit
+ *
+ * @return mixed
+ */
+ protected function getOrdersToProcess(int $limit)
+ {
+ $searchData = [
+ 'limit' => $limit,
+ 'includes' => [
+ 'order' => ['id']
+ ],
+ 'sort' => [
+ [
+ 'field' => 'order.createdAt',
+ 'direction' => 'DESC'
+ ]
+ ],
+ 'filter' => []
+ ];
+
+ $searchData['filter'][] = [
+ 'field' => 'stateMachineState.technicalName',
+ 'type' => 'equalsAny',
+ 'value' => explode(';', $this->statesToFetch)
+ ];
+
+ if (!empty($this->deliveryStatesToFetch)) {
+ $searchData['filter'][] = [
+ 'field' => 'deliveries.stateMachineState.technicalName',
+ 'type' => 'equalsAny',
+ 'value' => explode(';', $this->deliveryStatesToFetch)
+ ];
+ }
+ if (!empty($this->transactionStatesToFetch)) {
+ $searchData['filter'][] = [
+ 'field' => 'transactions.stateMachineState.technicalName',
+ 'type' => 'equalsAny',
+ 'value' => explode(';', $this->transactionStatesToFetch)
+ ];
+ }
+
+ if (!empty($this->salesChannelToFetch)) {
+ $searchData['filter'][] = [
+ 'field' => 'order.salesChannelId',
+ 'type' => 'equals',
+ 'value' => $this->salesChannelToFetch
+ ];
+ }
+
+ return $this->shopwareRequest('POST', 'search/order', $searchData);
+ }
+
+ /**
+ * @return int|mixed
+ */
+ public function ImportGetAuftrag()
+ {
+ $voucherArticleId = $this->app->DB->Select("SELECT s.artikelrabatt FROM `shopexport` AS `s` WHERE s.id='$this->shopid' LIMIT 1");
+ $voucherArticleNumber = $this->app->DB->Select("SELECT a.nummer FROM `artikel` AS `a` WHERE a.id='$voucherArticleId' LIMIT 1");
+
+ $dataToGet = $this->CatchRemoteCommand('data');
+ if (empty($this->statesToFetch)) {
+ return false;
+ }
+ $expectOrderArray = !empty($dataToGet['anzgleichzeitig']) && (int)$dataToGet['anzgleichzeitig'] > 1;
+ $expectNumber = !empty($dataToGet['nummer']);
+ $order = null;
+ if($expectNumber) {
+ $order = $this->shopwareRequest('GET', 'order/' . $dataToGet['nummer'] . '?associations[currency][]');
+ if(empty($order['data'])) {
+ return false;
+ }
+ $ordersToProcess = ['data' => [ ['id' => $dataToGet['nummer']] ]];
+ $orderIncludedData = $order['included'];
+ $order = $order['data'];
+ }
+ elseif(!$expectOrderArray) {
+ $ordersToProcess = $this->getOrdersToProcess(1);
+ }
+ elseif(!$expectNumber) {
+ $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit());
+ }
+ if (empty($ordersToProcess['data'])) {
+ return false;
+ }
+
+ $fetchedOrders = [];
+ if (isset($ordersToFetch['data']['id']) && !isset($ordersToFetch['data'][0])) {
+ $ordersToFetch['data'] = [$ordersToFetch['data']];
+ }
+ foreach ($ordersToProcess['data'] as $currentlyOpenOrder) {
+ $orderIdToFetch = $currentlyOpenOrder['id'];
+
+ if (empty($dataToGet['nummer']) || empty($order)) {
+ $order = $this->shopwareRequest('GET', 'order/' . $orderIdToFetch.'?associations[currency][]');
+ $orderIncludedData = $order['included'];
+ $order = $order['data'];
+ }
+ $cart = [];
+ try {
+ $timestamp = date_create_from_format('Y-m-d\TH:i:s+', $order['attributes']['createdAt']);
+ $cart['zeitstempel'] = $timestamp->format('Y-m-d H:i:s');
+ } catch (Exception $ex) {
+
+ }
+ $cart['auftrag'] = $order['id'];
+ $cart['subshop'] = $order['attributes']['salesChannelId'];
+ $cart['order'] = $order;
+ $cart['onlinebestellnummer'] = $order['attributes']['orderNumber'];
+ $cart['gesamtsumme'] = $order['attributes']['amountTotal'];
+ $cart['versandkostenbrutto'] = $order['attributes']['shippingTotal'];
+ $cart['bestelldatum'] = substr($order['attributes']['orderDate'], 0, 10);
+ if (!empty($order['attributes']['customerComment'])) {
+ $cart['freitext'] = $order['attributes']['customerComment'];
+ }
+
+ foreach ($orderIncludedData as $includedDataSet){
+ if($includedDataSet['type'] === 'currency'){
+ $cart['waehrung'] = $includedDataSet['attributes']['isoCode'];
+ }
+ }
+
+ $deliveryInfo = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/deliveries');
+ $shippingMethod = $this->shopwareRequest('GET',
+ 'order-delivery/' . $deliveryInfo['data'][0]['id'] . '/shipping-method');
+ $order['shippingMethod'] = $shippingMethod;
+ $cart['lieferung'] = $shippingMethod['data'][0]['attributes']['name'];
+
+ $customer = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/order-customer');
+ $order['customer'] = $customer;
+ $cart['email'] = $customer['data']['0']['attributes']['email'];
+
+ $addresses = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/addresses?associations[salutation][]&associations[country][]');
+ $order['addresses'] = $addresses;
+ $deliveryCountryId = '';
+ $billingCountryId = '';
+ $billingSalutationId = '';
+ foreach ($addresses['data'] as $address) {
+ if ($address['id'] === $order['attributes']['billingAddressId']) {
+ if (!empty($address['attributes']['vatId'])) {
+ $cart['ustid'] = $address['attributes']['vatId'];
+ }
+ $cart['name'] = $address['attributes']['firstName'] . ' ' . $address['attributes']['lastName'];
+ if (!empty($address['attributes']['company'])) {
+ $cart['ansprechpartner'] = $cart['name'];
+ $cart['name'] = $address['attributes']['company'];
+ }
+ $cart['strasse'] = $address['attributes']['street'];
+ $cart['abteilung'] = $address['attributes']['department'];
+ $cart['adresszusatz'] = trim($address['attributes']['additionalAddressLine1'].' '.
+ $address['attributes']['additionalAddressLine2']);
+ $cart['telefon'] = $address['attributes']['phoneNumber'];
+ $cart['plz'] = $address['attributes']['zipcode'];
+ $cart['ort'] = $address['attributes']['city'];
+ $billingCountryId = $address['attributes']['countryId'];
+ $billingSalutationId = $address['attributes']['salutationId'];
+ }
+ if ($address['id'] !== $order['attributes']['billingAddressId']) {
+ $cart['abweichendelieferadresse'] = 1;
+ if (!empty($address['attributes']['vatId'])) {
+ $cart['lieferadresse_ustid'] = $address['attributes']['vatId'];
+ }
+ $cart['lieferadresse_name'] = $address['attributes']['firstName'] . ' ' . $address['attributes']['lastName'];
+ if (!empty($address['attributes']['company'])) {
+ $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name'];
+ $cart['lieferadresse_name'] = $address['attributes']['company'];
+ }
+ $cart['lieferadresse_strasse'] = $address['attributes']['street'];
+ $cart['lieferadresse_abteilung'] = $address['attributes']['department'];
+ $cart['lieferadresse_adresszusatz'] = trim($address['attributes']['additionalAddressLine1'].' '.
+ $address['attributes']['additionalAddressLine2']);
+ $cart['lieferadresse_plz'] = $address['attributes']['zipcode'];
+ $cart['lieferadresse_ort'] = $address['attributes']['city'];
+ $deliveryCountryId = $address['attributes']['countryId'];
+ }
+ }
+
+ $anrede = 'herr';
+ $land = 'DE';
+ $lieferadresseLand = 'DE';
+ foreach ($addresses['included'] as $includedInfo) {
+ if ($includedInfo['id'] === $billingCountryId) {
+ $land = $includedInfo['attributes']['iso'];
+ }
+ if ($includedInfo['id'] === $deliveryCountryId) {
+ $lieferadresseLand = $includedInfo['attributes']['iso'];
+ }
+ if ($includedInfo['id'] === $billingSalutationId) {
+ $salutation = $includedInfo['attributes']['salutationKey'];
+ if ($salutation === 'ms' || $salutation === 'mrs') {
+ $anrede = 'frau';
+ }
+ }
+ }
+
+ $cart['anrede'] = $anrede;
+ $cart['land'] = $land;
+ if (!empty($cart['abweichendelieferadresse'])) {
+ $cart['lieferadresse_land'] = $lieferadresseLand;
+ }
+
+ $transactionData = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/transactions');
+ $cart['transacion_data'] = $transactionData;
+ if (!empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_pui_payment_instruction']['reference_number'])) {
+ $cart['transaktionsnummer'] = $transactionData['data'][0]['attributes']['customFields']['swag_paypal_pui_payment_instruction']['reference_number'];
+ }
+ if (empty($cart['transaktionsnummer'] && !empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_order_id']))) {
+ $cart['transaktionsnummer'] = (string)$transactionData['data'][0]['attributes']['customFields']['swag_paypal_order_id'];
+ }
+ if (empty($cart['transaktionsnummer'] && !empty($transactionData['data'][0]['attributes']['customFields']['swag_paypal_transaction_id']))) {
+ $livePayPalData = $this->shopwareRequest('GET', 'paypal/payment-details/' . $order['id'] . '/' . $transactionData['data'][0]['attributes']['customFields']['swag_paypal_transaction_id']);
+ if (!empty($livePayPalData['transactions'])) {
+ foreach ($livePayPalData['transactions'] as $payPalData) {
+ foreach ($payPalData['related_resources'] as $ressources) {
+ if ($ressources['sale']['state'] === 'completed') {
+ $cart['transaktionsnummer'] = $ressources['sale']['id'];
+ break 2;
+ }
+ }
+ }
+ }
+ }
+ if(
+ empty($cart['transaktionsnummer'])
+ && isset($transactionData['data'][0]['attributes']['customFields']['stripe_payment_context']['payment']['payment_intent_id'])
+ ){
+ $cart['transaktionsnummer'] = $transactionData['data'][0]['attributes']['customFields']['stripe_payment_context']['payment']['payment_intent_id'];
+ }
+
+ $paymentMethodId = $transactionData['data'][0]['attributes']['paymentMethodId'];
+ $paymentMethod = $this->shopwareRequest('GET', 'payment-method/' . $paymentMethodId);
+ $cart['zahlungsweise'] = $paymentMethod['data']['attributes']['name'];
+
+ $taxedCountry = $land;
+ if($this->taxationByDestinationCountry){
+ $taxedCountry = $lieferadresseLand;
+ }
+ if($order['attributes']['amountTotal'] === $order['attributes']['amountNet']){
+ if($this->app->erp->IstEU($taxedCountry)){
+ $cart['ust_befreit'] = 1;
+ }elseif($this->app->erp->Export($taxedCountry)){
+ $cart['ust_befreit'] = 2;
+ }else{
+ $cart['ust_befreit'] = 3;
+ }
+ }
+
+ $lineItems = $this->shopwareRequest('GET', 'order/' . $order['id'] . '/line-items');
+ $order['lineItems'] = $lineItems;
+ $cart['articlelist'] = [];
+
+ $taxRate = 0;
+ foreach ($lineItems['data'] as $lineItem) {
+ if ($lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'] > $taxRate) {
+ $taxRate = $lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'];
+ }
+ }
+
+ $orderPriceType = 'price';
+ if(in_array($order['attributes']['taxStatus'], ['net', 'tax-free'])) {
+ $orderPriceType = 'price_netto';
+ $cart['versandkostennetto'] = $cart['versandkostenbrutto'];
+ unset($cart['versandkostenbrutto']);
+ }
+
+ foreach ($lineItems['data'] as $lineItem) {
+ $productPriceType = $orderPriceType;
+ if(empty($lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'])){
+ $productPriceType = 'price_netto';
+ }
+ $articleId = null;
+ if($lineItem['attributes']['price']['unitPrice'] < 0) {
+ $articleId = $voucherArticleNumber;
+ }
+ elseif(isset($lineItem['attributes']['payload']['productNumber'])){
+ $articleId = $lineItem['attributes']['payload']['productNumber'];
+ }
+ $product = [
+ 'articleid' => $articleId,
+ 'name' => $lineItem['attributes']['label'],
+ 'quantity' => $lineItem['attributes']['quantity'],
+ $productPriceType => $lineItem['attributes']['price']['unitPrice'],
+ 'steuersatz' => $lineItem['attributes']['price']['calculatedTaxes'][0]['taxRate'],
+ ];
+ $cart['articlelist'][] = $product;
+ }
+
+ $cart['order'] = $order;
+ $fetchedOrders[] = [
+ 'id' => $cart['auftrag'],
+ 'sessionid' => '',
+ 'logdatei' => '',
+ 'warenkorb' => base64_encode(serialize($cart)),
+ 'warenkorbjson' => base64_encode(json_encode($cart)),
+ ];
+ $this->Shopware6Log('Ergebnis: Auftrag', $order);
+ $this->Shopware6Log('Ergebnis: Adresse', $addresses);
+ $this->Shopware6Log('Ergebnis: Positionen', $lineItems);
+ }
+
+ return $fetchedOrders;
+ }
+
+ /**
+ * @return void
+ */
+ public function ImportDeleteAuftrag()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+ $auftrag = $tmp['auftrag'];
+
+ $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/process');
+ $this->addCustomFieldToOrder((string)$auftrag);
+ }
+
+ /**
+ * @return void
+ */
+ public function ImportUpdateAuftrag()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+ $auftrag = $tmp['auftrag'];
+ $tracking = $tmp['tracking'];
+
+ $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/complete');
+
+ $deliveries = $this->shopwareRequest('GET', 'order/'.$auftrag.'/deliveries');
+ $deliveryId = $deliveries['data'][0]['id'];
+
+ if(!empty($deliveryId)){
+ $this->shopwareRequest('POST', '_action/order_delivery/'.$deliveryId.'/state/ship');
+
+ $deliveryData = [
+ 'trackingCodes' => [$tracking]
+ ];
+ $this->shopwareRequest('PATCH', 'order-delivery/'.$deliveryId,$deliveryData);
+ }
+
+ $this->sendInvoce($auftrag);
+ $this->addCustomFieldToOrder((string)$auftrag);
+ if(empty($tmp['orderId'])) {
+ return;
+ }
+ $this->updateStorageForOrderIntId((int)$tmp['orderId']);
+ }
+
+ public function ImportStorniereAuftrag()
+ {
+ $tmp = $this->CatchRemoteCommand('data');
+ $auftrag = $tmp['auftrag'];
+
+ $this->shopwareRequest('POST', '_action/order/'.$auftrag.'/state/cancel');
+ $this->addCustomFieldToOrder((string)$auftrag);
+ }
+
+ /**
+ * @param string $extOrderId
+ */
+ protected function sendInvoce($extOrderId)
+ {
+ $order = $this->app->DB->SelectRow(
+ sprintf(
+ "SELECT `rechnungid`, `id` FROM `auftrag` WHERE shopextid='%s'",
+ $extOrderId
+ )
+ );
+ $invoiceId = 0;
+ if (!empty($order['rechnungid'])) {
+ $invoiceId = $order['rechnungid'];
+ $sql = sprintf("SELECT projekt, belegnr FROM rechnung WHERE id='%s'", $invoiceId);
+ $invoiceData = $this->app->DB->SelectRow($sql);
+ }
+ if (empty($invoiceId) && !empty($order['id'])) {
+ $invoiceData = $this->app->DB->SelectRow(
+ sprintf(
+ "SELECT `id`, `projekt`, `belegnr`
+ FROM `rechnung`
+ WHERE `auftragid` = %d AND `status` <> 'storniert' AND `status` <> 'angelegt'
+ LIMIT 1",
+ $order['id']
+ )
+ );
+ if (!empty($invoiceData)) {
+ $invoiceId = $invoiceData['id'];
+ }
+ }
+
+ if (!empty($invoiceData['belegnr'])) {
+ $projekt = $invoiceData['projekt'];
+ if (class_exists('RechnungPDFCustom')) {
+ $Brief = new RechnungPDFCustom($this->app, $projekt);
+ } else {
+ $Brief = new RechnungPDF($this->app, $projekt);
+ }
+
+ $Brief->GetRechnung($invoiceId);
+ $filePath = $Brief->displayTMP(true);
+
+ $documentNumber = $invoiceData['belegnr'];
+ $invoiceDocumentData = [
+ 'config' => [
+ 'custom' => [
+ 'invoiceNumber' => $documentNumber,
+ ],
+ 'documentComment' => 'Aus Xentral heraus erstellte Rechnung',
+ 'documentNumber' => $documentNumber,
+ ],
+ 'referenced_document_id' => null,
+ 'static' => true
+ ];
+
+ $documentData = $this->shopwareRequest('POST', '_action/order/' . $extOrderId . '/document/invoice', $invoiceDocumentData);
+ $documentId = $documentData['documentId'];
+
+ $accessToken = $this->shopwareToken();
+ $url = $this->ShopUrl . '_action/document/' . $documentId . '/upload?_response=true&extension=pdf&fileName=' . $documentNumber;
+
+ $ch = curl_init();
+ $setHeaders = [
+ 'Content-Type:application/pdf',
+ 'Authorization:Bearer ' . $accessToken['token']
+ ];
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filePath));
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $setHeaders);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $response = json_decode(curl_exec($ch), true);
+ curl_close($ch);
+ if (!empty($response['errors'])) {
+ $this->Shopware6Log(
+ 'Fehler bei Rechnugnsübertragung für ' . $documentNumber, $response['errors']
+ );
+ }
+ }
+ }
+
+ /**
+ * @return string
+ */
+ public function ImportAuth()
+ {
+ $tokeninfo = $this->shopwareToken();
+
+
+ if (!$tokeninfo['success']) {
+ return 'failed: ' . $tokeninfo['message'];
+ }
+ if($this->data === 'info'){
+ $salesChannelsInShopware = $this->client->getAllSalesChannels();
+ $salesChannelsToShow = ['subshops' => []];
+ foreach ($salesChannelsInShopware['data'] as $salesChannelInShopware){
+ $salesChannelsToShow['subshops'][] = [
+ 'id'=>$salesChannelInShopware['id'],
+ 'name'=>$salesChannelInShopware['name'],
+ 'aktiv'=>$salesChannelInShopware['active']
+ ];
+ }
+ return $salesChannelsToShow;
+ }
+
+ return 'success';
+ }
+
+ /**
+ * Build category tree as displayed in article info
+ * May be useful for setting category in the future
+ * but probably obsolete
+ *
+ * @param string $categoryName
+ * @param array $categoryTree
+ *
+ * @return array
+ */
+ protected function appendCategoryTree($categoryName, $categoryTree = [])
+ {
+ $shopwareCategory = $this->shopwareRequest(
+ 'GET',
+ 'category?filter[category.name]=' . urlencode($categoryName)
+ );
+ if (!isset($shopwareCategory['data'][0]['id'])) {
+ return $categoryTree;
+ }
+ $categoryInfo = $shopwareCategory['data'][0]['attributes'];
+ $categories[] = [(int)$categoryInfo['level'], $shopwareCategory['data'][0]['id']];
+ $path = $categoryInfo['path'];
+ if (!empty($path)) {
+ $pathArray = explode('|', $path);
+ foreach ($pathArray as $nodeId) {
+ if ($nodeId === '') {
+ continue;
+ }
+ $nodeCategory = $this->shopwareRequest('GET', 'category/' . $nodeId);
+ if (isset($nodeCategory['data']['id'])) {
+ $categories[] = [(int)$nodeCategory['data']['attributes']['level'], $nodeId];
+ unset($nodeCategory);
+ }
+ }
+ }
+ foreach ($categories as $category) {
+ $level = $category[0];
+ if (!isset($categoryTree[$level])) {
+ $categoryTree[$level] = [];
+ }
+ if (!in_array($category, $categoryTree[$level], true)) {
+ $categoryTree[$level][] = $category[1];
+ }
+ }
+ ksort($categoryTree);
+
+ return $categoryTree;
+ }
+
+ /**
+ * @param array $postData
+ *
+ * @return array
+ */
+ public function updatePostDataForAssistent($postData)
+ {
+ if(!empty($this->ShopUrl)) {
+ $postData['shopwareUrl'] = $this->ShopUrl;
+ }
+ return $postData;
+ }
+
+ /**
+ * @param array $shopArr
+ * @param array $postData
+ *
+ * @return array
+ */
+ public function updateShopexportArr($shopArr, $postData)
+ {
+ $shopArr['stornoabgleich'] = 1;
+ $shopArr['demomodus'] = 0;
+
+ return $shopArr;
+ }
+
+ /**
+ * @return JsonResponse|null
+ */
+ public function AuthByAssistent()
+ {
+ $shopwareUrl = $this->app->Secure->GetPOST('shopwareUrl');
+ $shopwareUserName = $this->app->Secure->GetPOST('shopwareUserName');
+ $shopwarePassword = $this->app->Secure->GetPOST('shopwarePassword');
+ $step = (int)$this->app->Secure->GetPOST('step');
+
+ if($step <= 1){
+ if(empty($shopwareUrl)){
+ return new JsonResponse(['error' => 'Bitte die URL des Shops angeben.'], JsonResponse::HTTP_BAD_REQUEST);
+ }
+ if(empty($shopwareUserName)){
+ return new JsonResponse(['error' => 'Bitte den Benutzernamen angeben'], JsonResponse::HTTP_BAD_REQUEST);
+ }
+ if(empty($shopwarePassword)){
+ return new JsonResponse(['error' => 'Bitte das Passwort angeben'], JsonResponse::HTTP_BAD_REQUEST);
+ }
+
+ $this->UserName = $shopwareUserName;
+ $this->Password = $shopwarePassword;
+ $shopwareUrl = rtrim($shopwareUrl, '/') . '/';
+ $testUrls = [];
+ $hasNoHttp = strpos($shopwareUrl,'http') !== 0;
+ if(substr($shopwareUrl, -5) !== '/api/') {
+ if($hasNoHttp) {
+ $testUrls[] = 'https://'.$shopwareUrl.'api/';
+ $testUrls[] = 'http://'.$shopwareUrl.'api/';
+ }
+ $testUrls[] = $shopwareUrl.'api/';
+ }
+ elseif($hasNoHttp) {
+ $testUrls[] = 'https://'.$shopwareUrl;
+ $testUrls[] = 'http://'.$shopwareUrl;
+ }
+ else {
+ $testUrls[] = $shopwareUrl;
+ }
+ foreach($testUrls as $testUrl) {
+ $this->ShopUrl = $testUrl;
+ $tokeninfo = $this->shopwareToken();
+ if(!empty($tokeninfo['success'])) {
+ break;
+ }
+ }
+
+ if(!$tokeninfo['success']){
+ return new JsonResponse(['error' => $tokeninfo['message']], JsonResponse::HTTP_BAD_REQUEST);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * @return string
+ */
+ public function getClickByClickHeadline()
+ {
+ return 'Bitte im Shopware Backend einen eigenen Benutzer für Xentral anlegen und diese
+ Zugangsdaten hier eintragen.';
+ }
+
+ /**
+ * @return array
+ */
+ public function getStructureDataForClickByClickSave()
+ {
+ return [
+ 'shopwareAllowCreateManufacturer' => 1,
+ ];
+ }
+
+ /**
+ * @return array[]
+ */
+ public function getCreateForm()
+ {
+ return [
+ [
+ 'id' => 0,
+ 'name' => 'urls',
+ 'inputs' => [
+ [
+ 'label' => 'URL des Shops',
+ 'type' => 'text',
+ 'name' => 'shopwareUrl',
+ 'validation' => true,
+ ],
+ ],
+ ],
+ [
+ 'id' => 1,
+ 'name' => 'username',
+ 'inputs' => [
+ [
+ 'label' => 'Benutzername aus Shopware',
+ 'type' => 'text',
+ 'name' => 'shopwareUserName',
+ 'validation' => true,
+ ],
+ ],
+ ],
+ [
+ 'id' => 2,
+ 'name' => 'password',
+ 'inputs' => [
+ [
+ 'label' => 'Passwort aus Shopware',
+ 'type' => 'password',
+ 'name' => 'shopwarePassword',
+ 'validation' => true,
+ ],
+ ],
+ ],
+ ];
+ }
+
+ public function getBoosterHeadline(): string
+ {
+ return 'Shopware 6 Business Booster App';
+ }
+
+ public function getBoosterSubHeadline(): string
+ {
+ return 'Bitte gehe auf Shopware 6 und installiere dort das Plugin Xentral Business Booster App.
+ Dort kann man sich dann mit ein paar Klicks mit Xentral verbinden.';
+ }
+
+ /**
+ * @param int $intOrderId
+ *
+ * @return array
+ */
+ protected function getArticleShopLinks(int $intOrderId): array
+ {
+ return $this->app->DB->SelectPairs(
+ "SELECT DISTINCT ao.artikel, a.nummer
+ FROM `auftrag_position` AS `ap`
+ INNER JOIN `auftrag` AS `ab` ON ap.auftrag = ab.id
+ INNER JOIN `artikel` AS `a` ON ap.artikel = a.id
+ INNER JOIN `artikel_onlineshops` AS `ao` ON ab.shop = ao.shop AND a.id = ao.artikel
+ WHERE ab.id = {$intOrderId} AND ao.aktiv = 1"
+ );
+ }
+
+ /**
+ * @param array $articleIds
+ */
+ protected function updateArticleCacheToSync(array $articleIds): void
+ {
+ if(empty($articleIds)) {
+ return;
+ }
+ $articleIdsString = implode(', ', $articleIds);
+ $this->app->DB->Update(
+ "UPDATE `artikel`
+ SET `laststorage_changed` = DATE_ADD(NOW(), INTERVAL 1 SECOND)
+ WHERE `id` IN ({$articleIdsString})"
+ );
+ }
+
+ /**
+ * @param array $articleIds
+ */
+ protected function updateArticleOnlineShopCache(array $articleIds): void
+ {
+ if(empty($articleIds)) {
+ return;
+ }
+ $articleIdsString = implode(', ', $articleIds);
+ $this->app->DB->Update(
+ "UPDATE `artikel_onlineshops`
+ SET `storage_cache` = -999, `pseudostorage_cache` = -999
+ WHERE `artikel` IN ({$articleIdsString}) AND `aktiv` = 1 AND `shop` = {$this->shopid}"
+ );
+ }
+
+ /**
+ * @param int $intOrderId
+ */
+ protected function updateStorageForOrderIntId(int $intOrderId): void
+ {
+ $articles = $this->getArticleShopLinks($intOrderId);
+ if(empty($articles)) {
+ return;
+ }
+ $articleIds = array_keys($articles);
+ $this->updateArticleCacheToSync($articleIds);
+ $this->updateArticleOnlineShopCache($articleIds);
+
+ $isStorageSyncCronjobActive = (int)$this->app->DB->Select(
+ "SELECT COUNT(`id`) FROM `prozessstarter` WHERE `aktiv` = 1 AND `parameter` = 'lagerzahlen'"
+ ) > 0;
+ if(!$isStorageSyncCronjobActive) {
+ return;
+ }
+ foreach($articleIds as $articleId) {
+ try {
+ $this->app->erp->LagerSync($articleId, false, [$this->shopid]);
+ }
+ catch (Exception $e) {
+ $articleNumber = $articles[$articleId];
+ $this->Shopware6ErrorLog('LagerSync konnte nicht ausgeführt werden', $articleNumber);
+ }
+ }
+
+ $this->updateArticleCacheToSync($articleIds);
+ }
+}
diff --git a/www/pages/ticket.php b/www/pages/ticket.php
index 936da277..28828244 100644
--- a/www/pages/ticket.php
+++ b/www/pages/ticket.php
@@ -48,11 +48,11 @@ class Ticket {
case "ticket_list":
$allowed['ticket_list'] = array('list');
- $heading = array('','','Ticket #', 'Letzte Aktion', 'Adresse', 'Betreff', 'Tags', 'Verant.', 'Nachr.', 'Status', 'Alter', 'Projekt', 'Menü');
- $width = array('1%','1%','5%', '5%', '5%', '30%', '1%', '5%', '1%', '1%', '1%', '1%', '1%');
+ $heading = array('','','Ticket #', 'Aktion','Adresse', 'Betreff', 'Tags', 'Verant.', 'Nachr.', 'Status', 'Projekt', 'Menü');
+ $width = array('1%','1%','5%', '5%', '5%', '30%', '1%', '5%', '1%', '1%', '1%', '1%');
- $findcols = array('t.id','t.zeit','t.schluessel', 't.zeit', 'a.name', 't.betreff', 't.tags', 'w.warteschlange', 'nachrichten_anz', 't.status','t.zeit', 't.projekt');
- $searchsql = array( 't.schluessel', 't.zeit', 'a.name', 't.betreff','t.notiz', 't.tags', 'w.warteschlange', 't.status', 't.projekt');
+ $findcols = array('t.id','t.id','t.schluessel', 't.zeit', 'a.name', 't.betreff', 't.tags', 'w.warteschlange', 'nachrichten_anz', 't.status', 'p.abkuerzung');
+ $searchsql = array( 't.schluessel', 't.zeit', 'a.name', 't.betreff','t.notiz', 't.tags', 'w.warteschlange', 't.status', 'p.abkuerzung','(SELECT mail FROM ticket_nachricht tn WHERE tn.ticket = t.schluessel AND tn.versendet <> 1 LIMIT 1)');
$defaultorder = 1;
$defaultorderdesc = 0;
@@ -65,27 +65,29 @@ class Ticket {
CONCAT(TIMESTAMPDIFF(hour, t.zeit, NOW()),'h'),
CONCAT(TIMESTAMPDIFF(day, t.zeit, NOW()), 'd ',MOD(TIMESTAMPDIFF(hour, t.zeit, NOW()),24),'h'))";
- $dropnbox = "' ' AS `open`, CONCAT(' ') AS `auswahl`";
+ $dropnbox = "' ' AS `open`,
+ CONCAT(' ') AS `auswahl`";
$priobetreff = "if(t.prio!=1,t.betreff,CONCAT('',t.betreff,' '))";
$anzahlnachrichten = "(SELECT COUNT(n.id) FROM ticket_nachricht n WHERE n.ticket = t.schluessel)";
+ $letztemail = $app->erp->FormatDateTimeShort("(SELECT MAX(n.zeit) FROM ticket_nachricht n WHERE n.ticket = t.schluessel AND n.zeit IS NOT NULL)");
+
$tagstart = "";
$tagend = " ";
$sql = "SELECT SQL_CALC_FOUND_ROWS
t.id,
".$dropnbox.",
- CONCAT('',t.schluessel,' '),
- t.zeit,
- a.name,
+ CONCAT('',t.schluessel,' '),".
+ $app->erp->FormatDateTimeShort('zeit')." as aktion,
+ CONCAT(COALESCE(CONCAT(a.name,' '),''),COALESCE((SELECT mail FROM ticket_nachricht tn WHERE tn.ticket = t.schluessel AND tn.versendet <> 1 LIMIT 1),'')) as combiadresse,
CONCAT('',".$priobetreff.",' ',replace(substring(ifnull(t.notiz,''),1,500),'\n',' '),' '),
CONCAT(''\n,'".$tagstart."',replace(t.tags,',','".$tagend."
".$tagstart."'),'".$tagend."',' '),
w.warteschlange,
- ".$anzahlnachrichten." as nachrichten_anz,
+ ".$anzahlnachrichten." as `nachrichten_anz`,
".ticket_iconssql().",
- ".$timedifference.",
p.abkuerzung,
t.id
FROM ticket t
@@ -149,7 +151,7 @@ class Ticket {
// END Toggle filters
$moreinfo = true; // Allow drop down details
- $menucol = 12; // For moredata
+ $menucol = 11; // For moredata
$count = "SELECT count(DISTINCT id) FROM ticket t WHERE $where";
@@ -170,6 +172,16 @@ class Ticket {
return $erg;
}
+ // Ensure status 'offen' on self-assigned tickets
+ function ticket_set_self_assigned_status(array $ids) {
+ $sql = "UPDATE ticket SET status = 'offen'
+ WHERE
+ status = 'neu'
+ AND id IN (".implode(',',$ids).")
+ AND warteschlange IN (SELECT label FROM warteschlangen WHERE adresse = '".$this->app->User->GetAdresse()."')";
+ $this->app->DB->Update($sql);
+ }
+
function ticket_list() {
// Process multi action
@@ -181,7 +193,7 @@ class Ticket {
if($selectedId > 0) {
$selectedIds[] = $selectedId;
}
- }
+ }
$status = $this->app->Secure->GetPOST('status');
$warteschlange = $this->app->Secure->GetPOST('warteschlange');
@@ -192,9 +204,10 @@ class Ticket {
}
$sql .= " WHERE id IN (".implode(",",$selectedIds).")";
-
$this->app->DB->Update($sql);
+ $this->ticket_set_self_assigned_status($selectedIds);
+
}
// List
@@ -239,8 +252,8 @@ class Ticket {
n.verfasser,
n.mail,
t.quelle,
- n.zeit,
- n.zeitausgang,
+ ".$this->app->erp->FormatDateTimeShort('n.zeit','zeit').",
+ ".$this->app->erp->FormatDateTimeShort('n.zeitausgang','zeitausgang').",
n.versendet,
n.text,
n.textausgang,
@@ -307,6 +320,7 @@ class Ticket {
$this->app->Tpl->Set("NACHRICHT_BETREFF",''.htmlentities($message['betreff']).' ');
$this->app->Tpl->Set("NACHRICHT_ZEIT",$message['zeitausgang']);
$this->app->Tpl->Set("NACHRICHT_FLOAT","right");
+ $this->app->Tpl->Set("META_FLOAT","left");
$this->app->Tpl->Set("NACHRICHT_TEXT",$message['textausgang']);
$this->app->Tpl->Set("NACHRICHT_SENDER",htmlentities($message['bearbeiter']));
$this->app->Tpl->Set("NACHRICHT_RECIPIENTS",htmlentities($message['verfasser']." <".$message['mail'].">"));
@@ -327,12 +341,13 @@ class Ticket {
}
$this->app->Tpl->Set("NACHRICHT_BETREFF",htmlentities($message['betreff']." (Entwurf)"));
} else {
- $this->app->Tpl->Set("NACHRICHT_BETREFF",htmlentities($message['betreff']));
+ $this->app->Tpl->Set("NACHRICHT_BETREFF",''.htmlentities($message['betreff']).' ');
}
$this->app->Tpl->Set("NACHRICHT_SENDER",htmlentities($message['verfasser']." <".$message['mail_replyto'].">"));
$this->app->Tpl->Set("NACHRICHT_RECIPIENTS",htmlentities($message['mail']));
$this->app->Tpl->Set("NACHRICHT_CC_RECIPIENTS",htmlentities($message['mail_cc']));
$this->app->Tpl->Set("NACHRICHT_FLOAT","right");
+ $this->app->Tpl->Set("META_FLOAT","left");
$this->app->Tpl->Set("NACHRICHT_ZEIT",$message['zeitausgang']);
$this->app->Tpl->Set("NACHRICHT_NAME",htmlentities($message['verfasser']));
} else {
@@ -349,8 +364,9 @@ class Ticket {
$this->app->Tpl->Set("NACHRICHT_RECIPIENTS",htmlentities($message['quelle']));
}
$this->app->Tpl->Set("NACHRICHT_CC_RECIPIENTS",htmlentities($message['mail_cc_recipients']));
- $this->app->Tpl->Set("NACHRICHT_BETREFF",''.htmlentities($message['betreff']).' ');
+ $this->app->Tpl->Set("NACHRICHT_BETREFF",''.htmlentities($message['betreff']).' ');
$this->app->Tpl->Set("NACHRICHT_FLOAT","left");
+ $this->app->Tpl->Set("META_FLOAT","right");
$this->app->Tpl->Set("NACHRICHT_ZEIT",$message['zeit']);
}
@@ -365,9 +381,21 @@ class Ticket {
}
}
+ function ticket_text() {
+
+ $secure_html_tags = array(
+ ' ',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '
-[CSSLINKS]
-
-
-[JAVASCRIPT]
-
-
-[ADDITIONALJAVASCRIPT]
-
-
-
-[SPERRMELDUNGNACHRICHT]
-
-
-
-
-[ICONBAR]
-
-
-
-
-
OpenXE Update
-
-
-[PAGE]
-
-
-
Download:
-
-
Installieren:
-
-
Datenbank Update:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-[JSSCRIPTS]
-
-
-[BODYENDE]
-
-
-
-