From 9d547c6e5227d2c2ec52a12cabd4e0c4462ab0c8 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 13 May 2024 14:43:33 +0200 Subject: [PATCH 01/52] Shop Mirakl initial copied from Presta --- www/lib/ShopimporterBase.php | 52 ++++ www/pages/appstore.php | 5 +- www/pages/shopimporter_mirakl.php | 483 ++++++++++++++++++++++++++++++ 3 files changed, 539 insertions(+), 1 deletion(-) create mode 100644 www/pages/shopimporter_mirakl.php diff --git a/www/lib/ShopimporterBase.php b/www/lib/ShopimporterBase.php index 0e3795a7..2d92213d 100644 --- a/www/lib/ShopimporterBase.php +++ b/www/lib/ShopimporterBase.php @@ -632,6 +632,18 @@ Class ShopimporterBase{ 'variants', 'free_fields', ], + 'shopimporter_mirakl' => [ + 'article_descriptions', + 'translations', + 'categories', + 'properties', + 'pictures', + 'cross_selling', + 'bulk_prices', + 'standard_price', + 'variants', + 'free_fields', + ], 'shopimporter_shopify' => [ 'article_descriptions', 'translations', @@ -1329,6 +1341,46 @@ Class ShopimporterBase{ 'metabeschreibung' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], 'metakeywords' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], 'freifelder' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + ], + 'shopimporter_mirakl' => [ + 'auftrag' => ['createarticle' => self::UNDEFINED, 'updatearticle' => self::UNDEFINED, 'importarticle' => self::UNDEFINED, 'importorder' => self::UNDEFINED], + 'artikelname' => ['createarticle' => self::MUST, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CAN], + 'artikelnummer' => ['createarticle' => self::MUST, 'updatearticle' => self::MUST, 'importarticle' => self::CANNOT, 'importorder' => self::CAN], + 'aktiv' => ['createarticle' => self::MUST, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'restmenge' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'beschreibung' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CAN], + 'ean' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'hersteller' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'herstellerlink' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'herstellernummer' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'zolltarifnummer' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'gewicht' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'einheit' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'laenge' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'hoehe' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'breite' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'verkaufspreis' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CAN], + 'pseudopreis' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'lagerzahlen' => ['createarticle' => self::MUST, 'updatearticle' => self::MUST, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'pseudolager' => ['createarticle' => self::MUST, 'updatearticle' => self::MUST, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'staffelpreise' => ['createarticle' => self::MUST, 'updatearticle' => self::MUST, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'gruppenpreise' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'fremdsprachen' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'kategorie' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'kategoriebaum' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'bilder' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'varianten' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'matrixeigenschaften' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'über 5000 Varianten' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'eigenschaften' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'crossselling' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'kurztext' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'herkunftsland' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'umsatzsteuer' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'metatitel' => ['createarticle' => self::CANNOT, 'updatearticle' => self::CANNOT, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'metabeschreibung' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'metakeywords' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], + 'freifelder' => ['createarticle' => self::CAN, 'updatearticle' => self::CAN, 'importarticle' => self::CANNOT, 'importorder' => self::CANNOT], ], 'shopimporter_modified' => [ 'auftrag' => ['createarticle' => self::UNDEFINED, 'updatearticle' => self::UNDEFINED, 'importarticle' => self::UNDEFINED, 'importorder' => self::UNDEFINED], diff --git a/www/pages/appstore.php b/www/pages/appstore.php index 6c9c7c89..c118ecaf 100644 --- a/www/pages/appstore.php +++ b/www/pages/appstore.php @@ -2628,6 +2628,10 @@ class Appstore { 'Link'=>'index.php?module=onlineshops&action=create&cmd=shopimporter_presta', 'Icon'=>'Icons_dunkel_1.gif', 'Versionen'=>'ALL','install'=>true, 'beta' => false,'kategorie'=>'{|Shop Schnittstelle|}') + ,'shopimporter_mirakl'=>array('Bezeichnung'=>'Mirakl', + 'Link'=>'index.php?module=onlineshops&action=create&cmd=shopimporter_mirakl', + 'Icon'=>'Icons_dunkel_1.gif', + 'Versionen'=>'ALL','install'=>true, 'beta' => false,'kategorie'=>'{|Shop Schnittstelle|}') ,'shopimporter_shopify'=>array( 'Bezeichnung'=>'Shopify API Advanced', 'Link'=>'index.php?module=onlineshops&action=create&cmd=shopimporter_shopify', @@ -3967,7 +3971,6 @@ class Appstore { } } - if(isset($module['installiert'])) { foreach($module['installiert'] as $k => $v) { $moduleInstallKey = $module['installiert'][$k]['key']; diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php new file mode 100644 index 00000000..e7b6b6e2 --- /dev/null +++ b/www/pages/shopimporter_mirakl.php @@ -0,0 +1,483 @@ + 'de', 1 => 'en']; + private $taxationByDestinationCountry; + private $orderSearchLimit; + + + public function __construct($app, $intern = false) + { + $this->app = $app; + $this->intern = $intern; + if ($intern) + return; + + } + + public function EinstellungenStruktur() + { + return [ + 'ausblenden' => ['abholmodus' => ['ab_nummer', 'zeitbereich']], + 'functions' => ['getarticlelist'], + 'felder' => [ + 'protokoll' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Protokollierung im Logfile|}:' + ], + 'textekuerzen' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' + ], + 'useKeyAsParameter' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' + ], + 'apikey' => [ + 'typ' => 'text', + 'bezeichnung' => '{|API Key|}:', + 'size' => 40, + ], + 'shopurl' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Shop URL|}:', + 'size' => 40, + ], + 'shopidmirakl' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Shop ID des Shops|}:', + 'size' => 40, + ], + 'steuergruppen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Steuergruppenmapping|}:', + 'size' => 40, + ], + 'zustand' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Freifeld Zustand|}:', + 'size' => 40, + ], + 'abholen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'Abholen\' Status IDs|}:', + 'size' => 40, + ], + 'bearbeitung' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'In Bearbeitung\' Status IDs|}:', + 'size' => 40, + ], + 'abgeschlossen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'Abgeschlossen\' Status IDs|}:', + 'size' => 40, + ], + 'autoerstellehersteller' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Fehlende Hersteller automatisch anlegen|}:', + 'col' => 2 + ], + 'zeigezustand' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Artikelzustand im Shop anzeigen|}:', + 'col' => 2 + ], + 'zeigepreis' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', + 'col' => 2 + ], + ] + ]; + } + + public function getKonfig($shopid, $data) + { + $this->shopid = $shopid; + $this->data = $data; + $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1"); + $importerSettings = reset($importerSettings); + + $einstellungen = []; + if (!empty($importerSettings['einstellungen_json'])) { + $einstellungen = json_decode($importerSettings['einstellungen_json'], true); + } + $this->protocol = $einstellungen['felder']['protokoll']; + $this->apiKey = $einstellungen['felder']['apikey']; + $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; + if ($einstellungen['felder']['autoerstellehersteller'] === '1') { + $this->createManufacturerAllowed = true; + } + $this->idsabholen = $einstellungen['felder']['abholen']; + $this->idbearbeitung = $einstellungen['felder']['bearbeitung']; + $this->idabgeschlossen = $einstellungen['felder']['abgeschlossen']; + $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid); + $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); + } + + public function ImportAuth() { + $ch = curl_init($this->shopUrl); + curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec($ch); + $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + if ($code == 200) + return 'success'; + + return $response; + } + + public function ImportDeleteAuftrag() + { + $auftrag = $this->data['auftrag']; + + $obj = $this->miraklRequest('GET', 'order_histories?schema=blank'); + $obj->order_history->id_order = $auftrag; + $obj->order_history->id_order_state = $this->idbearbeitung; + + $this->miraklRequest('POST', 'order_histories', $obj->asXML()); + } + + public function ImportUpdateAuftrag() + { + $auftrag = $this->data['auftrag']; + + $obj = $this->miraklRequest('GET', 'order_histories?schema=blank'); + $obj->order_history->id_order = $auftrag; + $obj->order_history->id_order_state = $this->idabgeschlossen; + + $this->miraklRequest('POST', 'order_histories', $obj->asXML()); + + $req = $this->miraklRequest('GET', "order_carriers?filter[id_order]=$auftrag&display=[id]"); + $orderCarrierId = strval($req->order_carriers->order_carrier[0]->id); + $req = $this->miraklRequest('GET', "order_carriers/$orderCarrierId"); + $req->order_carrier->tracking_number = $this->data['tracking']; + $this->miraklRequest('PUT', "order_carriers/$orderCarrierId", $req->asXML()); + } + + public function ImportGetAuftraegeAnzahl() + { + $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit()); + return count($ordersToProcess); + } + + 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"); + + if (empty($this->idsabholen)) { + return false; + } + $expectOrderArray = !empty($this->data['anzgleichzeitig']) && (int)$this->data['anzgleichzeitig'] > 1; + $expectNumber = !empty($this->data['nummer']); + if ($expectNumber) { + $ordersToProcess = [$this->data['nummer']]; + } elseif (!$expectOrderArray) { + $ordersToProcess = $this->getOrdersToProcess(1); + } else { + $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit()); + } + + $fetchedOrders = []; + foreach ($ordersToProcess as $currentOrderId) { + $order = $this->miraklRequest('GET', "orders/$currentOrderId"); + $order = $order->order; + $cart = []; + $cart['zeitstempel'] = strval($order->date_add); + $cart['auftrag'] = strval($order->id); + $cart['onlinebestellnummer'] = strval($order->reference); + $cart['gesamtsumme'] = strval($order->total_paid); + $cart['versandkostennetto'] = strval($order->total_shipping_tax_excl); + $cart['bestelldatum'] = strval($order->date_add); + + $carrier = $this->miraklRequest('GET', "carriers/$order->id_carrier"); + $cart['lieferung'] = strval($carrier->carrier->name); + + $customer = $this->miraklRequest('GET', "customers/$order->id_customer"); + $cart['email'] = strval($customer->customer->email); + + $language = $this->miraklRequest('GET', "languages/{$customer->customer->id_lang}"); + if ($language->language->iso_code == "en") { + $cart['kunde_sprache'] = 'englisch'; + } + + $invoiceAddress = $this->miraklRequest('GET', "addresses/$order->id_address_invoice"); + $invoiceAddress = $invoiceAddress->address; + $invoiceCountry = $this->miraklRequest('GET', "countries/$invoiceAddress->id_country"); + $invoiceCountry = $invoiceCountry->country; + $cart['name'] = "$invoiceAddress->firstname $invoiceAddress->lastname"; + if (!empty(strval($invoiceAddress->company))) { + $cart['ansprechpartner'] = $cart['name']; + $cart['name'] = strval($invoiceAddress->company); + } + $cart['strasse'] = strval($invoiceAddress->address1); + $cart['adresszusatz'] = strval($invoiceAddress->address2); + $cart['telefon'] = strval($invoiceAddress->phone_mobile); + if (empty($cart['telefon'])) + $cart['telefon'] = strval($invoiceAddress->phone); + $cart['plz'] = strval($invoiceAddress->postcode); + $cart['ort'] = strval($invoiceAddress->city); + $cart['ustid'] = strval($invoiceAddress->vat_number); + $cart['land'] = strval($invoiceCountry->iso_code); + + if (strval($order->id_address_invoice) != strval($order->id_address_delivery)) { + $deliveryAddress = $this->miraklRequest('GET', "addresses/$order->id_address_delivery"); + $deliveryAddress = $deliveryAddress->address; + $deliveryCountry = $this->miraklRequest('GET', "countries/$deliveryAddress->id_country"); + $deliveryCountry = $deliveryCountry->country; + $cart['abweichendelieferadresse'] = 1; + $cart['lieferadresse_name'] = "$deliveryAddress->firstname $deliveryAddress->lastname"; + if (!empty(strval($deliveryAddress->company))) { + $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; + $cart['lieferadresse_name'] = strval($deliveryAddress->company); + } + $cart['lieferadresse_strasse'] = strval($deliveryAddress->address1); + $cart['lieferadresse_adresszusatz'] = strval($deliveryAddress->address2); + $cart['lieferadresse_plz'] = strval($deliveryAddress->postcode); + $cart['lieferadresse_ort'] = strval($deliveryAddress->city); + $cart['lieferadresse_land'] = strval($deliveryCountry->iso_code); + } + + //TODO + //$cart['transaktionsnummer'] + $cart['zahlungsweise'] = strval($order->payment); + + $taxedCountry = $cart['land']; + if (!empty($cart['lieferadresse_land']) && $this->taxationByDestinationCountry) { + $taxedCountry = $cart['lieferadresse_land']; + } + $lieferschwelle = $this->app->DB->SelectArr("SELECT * FROM lieferschwelle WHERE empfaengerland='$taxedCountry' LIMIT 1"); + if ($this->app->erp->IstEU($taxedCountry) || !empty($lieferschwelle['ueberschreitungsdatum'])) { + $cart['ust_befreit'] = 1; + } elseif ($this->app->erp->Export($taxedCountry)) { + $cart['ust_befreit'] = 2; + } + + $taxes = []; + $this->app->erp->RunHook('getTaxRatesFromShopOrder', 2, $taxedCountry, $taxes); + + if (isset($taxes['normal']) && $taxes['normal'] > 0) + $cart['steuersatz_normal'] = $taxes['normal']; + if (isset($taxes['ermaessigt']) && $taxes['ermaessigt'] > 0) + $cart['steuersatz_ermaessigt'] = $taxes['ermaessigt']; + + $cart['articlelist'] = []; + foreach ($order->associations->order_rows->order_row as $order_row) { + $article = [ + 'articleid' => strval($order_row->product_reference), + 'name' => strval($order_row->product_name), + 'quantity' => strval($order_row->product_quantity), + 'price_netto' => strval($order_row->unit_price_tax_excl), + ]; + + if ($order_row->unit_price_tax_excl > 0) { + $steuersatz = (strval($order_row->unit_price_tax_incl) / strval($order_row->unit_price_tax_excl)) - 1; + $steuersatz = round($steuersatz, 1); + $article['steuersatz'] = $steuersatz; + } + + $cart['articlelist'][] = $article; + } + + $fetchedOrders[] = [ + 'id' => $cart['auftrag'], + 'sessionid' => '', + 'logdatei' => '', + 'warenkorb' => base64_encode(serialize($cart)), + 'warenkorbjson' => base64_encode(json_encode($cart)), + ]; + } + $this->Log('Precessed order from mirakl', $fetchedOrders); + + return $fetchedOrders; + } + + public function ImportGetArticleList() + { + $result = []; + $response = $this->miraklRequest('GET', 'products?display=[reference]'); + foreach ($response->products->product as $product) { + $result[] = $product->reference; + } + + array_unique($result); + return $result; + } + + public function ImportGetArticle() + { + $nummer = $this->data['nummer']; + if (isset($this->data['nummerintern'])) { + $nummer = $this->data['nummerintern']; + } + $nummer = trim($nummer); + + if (empty($nummer)) + return; + + $productsresult = $this->miraklRequest('GET', 'products?filter[reference]='.$nummer); + $combinationsresult = $this->miraklRequest('GET', 'combinations?filter[reference]='.$nummer); + $numberOfCombinations = count($combinationsresult->combinations->combination); + $numberOfProducts = count($productsresult->products->product); + $numberOfResults = $numberOfProducts + $numberOfCombinations; + if ($numberOfResults > 1) { + $this->Log('Got multiple results from Shop', $this->data); + return; + } + elseif ($numberOfResults < 1) { + $this->Log('No product found in Shop', $this->data); + return; + } + + $isCombination = $numberOfCombinations > 0; + if ($isCombination) { + $combinationId = intval($combinationsresult->combinations->combination->attributes()->id); + $combination = $this->miraklRequest('GET', "combinations/$combinationId"); + $productId = intval($combination->combination->id_product); + } else { + $productId = intval($productsresult->products->product->attributes()->id); + } + $product = $this->miraklRequest('GET', "products/$productId"); + $res = []; + if ($isCombination) { + $res['nummer'] = strval($combination->combination->reference); + $res['artikelnummerausshop'] = strval($combination->combination->reference); + $res['ean'] = strval($combination->combination->ean13); + $res['preis_netto'] = floatval($product->product->price) + floatval($combination->combination->price); + } else { + $res['nummer'] = strval($product->product->reference); + $res['artikelnummerausshop'] = strval($product->product->reference); + $res['ean'] = strval($product->product->ean13); + $res['preis_netto'] = floatval($product->product->price); + } + $names = $this->toMultilangArray($product->product->name->language); + $descriptions = $this->toMultilangArray($product->product->description->language); + $shortdescriptions = $this->toMultilangArray($product->product->description_short->language); + $metadescriptions = $this->toMultilangArray($product->product->meta_description->language); + $metakeywords = $this->toMultilangArray($product->product->meta_keywords->language); + $metatitles = $this->toMultilangArray($product->product->meta_title->language); + $res['name'] = $names['de']; + $res['name_en'] = $names['en']; + $res['uebersicht_de'] = $descriptions['de']; + $res['uebersicht_en'] = $descriptions['en']; + $res['kurztext_de'] = strip_tags($shortdescriptions['de']); + $res['kurztext_en'] = strip_tags($shortdescriptions['en']); + $res['hersteller'] = strval($product->product->manufacturer_name); + $res['metatitle_de'] = $metatitles['de']; + $res['metatitle_en'] = $metatitles['en']; + $res['metadescription_de'] = $metadescriptions['de']; + $res['metadescription_en'] = $metadescriptions['en']; + + $tags = $product->product->associations->tags->tag; + $keywords = []; + foreach ($tags as $tag) { + $tagid = intval($tag->id); + $endpoint = "tags/{$tagid}"; + $tagdata = $this->miraklRequest('GET', $endpoint); + $tagiso = $this->langidToIso[intval($tagdata->tag->id_lang)]; + $tagvalue = strval($tagdata->tag->name); + if (!array_key_exists($tagiso, $keywords)) + $keywords[$tagiso] = []; + $keywords[$tagiso][] = $tagvalue; + } + $res['metakeywords_de'] = join(',', $keywords['de'] ?? []); + $res['metakeywords_en'] = join(',', $keywords['en'] ?? []); + + $images = []; + foreach ($product->product->associations->images->image as $img) { + $endpoint = "images/products/$productId/$img->id"; + $imgdata = $this->miraklRequest('GET', $endpoint, '', true); + $images[] = [ + 'content' => base64_encode($imgdata), + 'path' => "$img->id.jpg", + 'id' => $img->id + ]; + } + $res['bilder'] = $images; + return $res; + } + + private function toMultilangArray($xmlnode) { + $res = []; + foreach ($xmlnode as $item) { + $iso = $this->langidToIso[strval($item->attributes()->id)]; + $res[$iso] = strval($item); + } + return $res; + } + + private function getOrdersToProcess(int $limit) + { + $states = implode('|', explode(',', $this->idsabholen)); + $response = $this->miraklRequest('GET', "orders?display=[id]&limit=$limit&filter[current_state]=[$states]"); + $result = []; + foreach ($response->orders->order as $order) { + $result[] = strval($order->id); + } + return $result; + } + + public function getOrderSearchLimit(): int + { + if(in_array($this->orderSearchLimit, ['50', '75', '100'])) { + return (int)$this->orderSearchLimit; + } + + return 25; + } + + private function Log($message, $dump = '') + { + if ($this->protocol) { + $this->app->erp->Logfile($message, print_r($dump, true)); + } + } + + private function miraklRequest($method, $endpoint, $data = '', $raw = false) + { + $url = $this->shopUrl . $endpoint; + $url = str_replace('[', '%5b', $url); + $url = str_replace(']', '%5d', $url); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + if (!empty($data)) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + } + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec($ch); + if (curl_error($ch)) { + $this->error[] = curl_error($ch); + } + curl_close($ch); + + if ($raw) + return $response; + + return simplexml_load_string($response); + } +} From 9d71d9812f3a02b6c543a0069a8812bf13c1113b Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 14 May 2024 11:00:56 +0200 Subject: [PATCH 02/52] mirakl Zwischenstand --- www/eproosystem.php | 2 +- www/pages/onlineshops.php | 2 +- www/pages/shopimporter_mirakl.php | 79 ++++++++++++----------- www/widgets/templates/_gen/shopexport.tpl | 2 +- 4 files changed, 44 insertions(+), 41 deletions(-) diff --git a/www/eproosystem.php b/www/eproosystem.php index 560f7a59..4e96c6bd 100644 --- a/www/eproosystem.php +++ b/www/eproosystem.php @@ -1111,7 +1111,7 @@ if (typeof document.hidden !== \"undefined\") { // Opera 12.10 and Firefox 18 an } // userd edit ajax call - $poll = true; +// $poll = true; if($poll) { $this->addPollJs($module, $action, $id); } diff --git a/www/pages/onlineshops.php b/www/pages/onlineshops.php index a1eea6e4..7e1f015e 100644 --- a/www/pages/onlineshops.php +++ b/www/pages/onlineshops.php @@ -3339,7 +3339,7 @@ INNER JOIN shopexport s ON } if($this->app->Secure->GetPOST('pruefen')) { - + $className = 'Remote'; $methodName = 'RemoteConnection'; $r = new ReflectionMethod($className, $methodName); diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index e7b6b6e2..5a4cb70d 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -45,14 +45,14 @@ class Shopimporter_Mirakl extends ShopimporterBase 'typ' => 'checkbox', 'bezeichnung' => '{|Protokollierung im Logfile|}:' ], - 'textekuerzen' => [ +/* 'textekuerzen' => [ 'typ' => 'checkbox', 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' ], 'useKeyAsParameter' => [ 'typ' => 'checkbox', 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' - ], + ],*/ 'apikey' => [ 'typ' => 'text', 'bezeichnung' => '{|API Key|}:', @@ -65,9 +65,9 @@ class Shopimporter_Mirakl extends ShopimporterBase ], 'shopidmirakl' => [ 'typ' => 'text', - 'bezeichnung' => '{|Shop ID des Shops|}:', + 'bezeichnung' => '{|Shop ID des Shops (optional, int64)|}:', 'size' => 40, - ], + ],/* 'steuergruppen' => [ 'typ' => 'text', 'bezeichnung' => '{|Steuergruppenmapping|}:', @@ -107,7 +107,7 @@ class Shopimporter_Mirakl extends ShopimporterBase 'typ' => 'checkbox', 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', 'col' => 2 - ], + ],*/ ] ]; } @@ -136,15 +136,39 @@ class Shopimporter_Mirakl extends ShopimporterBase $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); } + private function miraklRequest(string $endpoint, array $postdata = null, bool $raw = false) + { + $ch = curl_init($this->shopUrl.$endpoint); + curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: ".$this->apiKey)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + if (!empty($postdata)) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + } + + $response = curl_exec($ch); + if (curl_error($ch)) { + $this->error[] = curl_error($ch); + } + curl_close($ch); + + if ($raw) + return $response; + + return simplexml_load_string($response); + } + + public function ImportAuth() { - $ch = curl_init($this->shopUrl); - curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); + $ch = curl_init($this->shopUrl."version"); + curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: ".$this->apiKey)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); - if ($code == 200) - return 'success'; - + $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + if ($code == 200) { + return 'success '.print_r($response,true); + } return $response; } @@ -317,7 +341,11 @@ class Shopimporter_Mirakl extends ShopimporterBase public function ImportGetArticleList() { $result = []; - $response = $this->miraklRequest('GET', 'products?display=[reference]'); + $response = $this->miraklRequest('offers'); + + print_r($response); + exit(); + foreach ($response->products->product as $product) { $result[] = $product->reference; } @@ -454,30 +482,5 @@ class Shopimporter_Mirakl extends ShopimporterBase $this->app->erp->Logfile($message, print_r($dump, true)); } } - - private function miraklRequest($method, $endpoint, $data = '', $raw = false) - { - $url = $this->shopUrl . $endpoint; - $url = str_replace('[', '%5b', $url); - $url = str_replace(']', '%5d', $url); - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - if (!empty($data)) { - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - } - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $response = curl_exec($ch); - if (curl_error($ch)) { - $this->error[] = curl_error($ch); - } - curl_close($ch); - - if ($raw) - return $response; - - return simplexml_load_string($response); - } + } diff --git a/www/widgets/templates/_gen/shopexport.tpl b/www/widgets/templates/_gen/shopexport.tpl index c0241d10..4255bffd 100644 --- a/www/widgets/templates/_gen/shopexport.tpl +++ b/www/widgets/templates/_gen/shopexport.tpl @@ -98,7 +98,7 @@
{|Aktion|} - + [AKTIONBUTTONS]
From 55e7934fe4dc7925e39f1ff072e7573fff03a4b9 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 14 May 2024 11:00:56 +0200 Subject: [PATCH 03/52] mirakl Zwischenstand --- www/eproosystem.php | 2 +- www/lib/class.remote.php | 8 +- www/pages/artikel.php | 1 + www/pages/onlineshops.php | 2 +- www/pages/shopimporter_mirakl.php | 326 +++++++++++++--------- www/pages/verbindlichkeit.php | 40 +-- www/widgets/templates/_gen/shopexport.tpl | 2 +- 7 files changed, 221 insertions(+), 160 deletions(-) diff --git a/www/eproosystem.php b/www/eproosystem.php index 560f7a59..4e96c6bd 100644 --- a/www/eproosystem.php +++ b/www/eproosystem.php @@ -1111,7 +1111,7 @@ if (typeof document.hidden !== \"undefined\") { // Opera 12.10 and Firefox 18 an } // userd edit ajax call - $poll = true; +// $poll = true; if($poll) { $this->addPollJs($module, $action, $id); } diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 0eb67ede..ef8cabb8 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -2775,6 +2775,7 @@ class Remote } return ''; } + if($shoptyp === 'intern') { if($modulename != '') @@ -2788,15 +2789,16 @@ class Remote $obj->getKonfig($id, $data); } $method = 'Import'.$action; + if(method_exists($obj,$method)) { try { $ret = $obj->$method(); } catch(Exception $e) { if($isActionAuth) { + return 'Fehler Auth: '.$e->getMessage(); + } return 'Fehler: '.$e->getMessage(); - } - return ''; } if(!empty($this->app->stringcleaner)){ @@ -2804,6 +2806,8 @@ class Remote } $this->parseReturn($ret, $id, $action); return $ret; + } else { + return 'Fehler: Funktion nicht implementiert: '.$method; } }elseif($isActionAuth) { diff --git a/www/pages/artikel.php b/www/pages/artikel.php index 34af81c7..129f3592 100644 --- a/www/pages/artikel.php +++ b/www/pages/artikel.php @@ -2867,6 +2867,7 @@ class Artikel extends GenArtikel { } $pageContents = $this->app->remote->RemoteSendArticleList($shop,$artikel,$extartikelnummer); + $check = strpos($pageContents ,'error:'); $msg = ''; if(!empty($pageContents) && is_array($pageContents)) { diff --git a/www/pages/onlineshops.php b/www/pages/onlineshops.php index a1eea6e4..7e1f015e 100644 --- a/www/pages/onlineshops.php +++ b/www/pages/onlineshops.php @@ -3339,7 +3339,7 @@ INNER JOIN shopexport s ON } if($this->app->Secure->GetPOST('pruefen')) { - + $className = 'Remote'; $methodName = 'RemoteConnection'; $r = new ReflectionMethod($className, $methodName); diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index e7b6b6e2..8352e5d0 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -11,7 +11,6 @@ class Shopimporter_Mirakl extends ShopimporterBase private $app; private $intern; private $shopid; - private $data; private $protocol; private $apiKey; private $shopUrl; @@ -20,6 +19,8 @@ class Shopimporter_Mirakl extends ShopimporterBase private $idbearbeitung; private $idabgeschlossen; + public $data; + // TODO private $langidToIso = [3 => 'de', 1 => 'en']; private $taxationByDestinationCountry; @@ -45,14 +46,14 @@ class Shopimporter_Mirakl extends ShopimporterBase 'typ' => 'checkbox', 'bezeichnung' => '{|Protokollierung im Logfile|}:' ], - 'textekuerzen' => [ +/* 'textekuerzen' => [ 'typ' => 'checkbox', 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' ], 'useKeyAsParameter' => [ 'typ' => 'checkbox', 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' - ], + ],*/ 'apikey' => [ 'typ' => 'text', 'bezeichnung' => '{|API Key|}:', @@ -65,9 +66,9 @@ class Shopimporter_Mirakl extends ShopimporterBase ], 'shopidmirakl' => [ 'typ' => 'text', - 'bezeichnung' => '{|Shop ID des Shops|}:', + 'bezeichnung' => '{|Shop ID des Shops (optional, int64)|}:', 'size' => 40, - ], + ],/* 'steuergruppen' => [ 'typ' => 'text', 'bezeichnung' => '{|Steuergruppenmapping|}:', @@ -107,7 +108,7 @@ class Shopimporter_Mirakl extends ShopimporterBase 'typ' => 'checkbox', 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', 'col' => 2 - ], + ],*/ ] ]; } @@ -136,15 +137,44 @@ class Shopimporter_Mirakl extends ShopimporterBase $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); } + private function miraklRequest(string $endpoint, string $postdata = null, bool $raw = false) + { + $ch = curl_init($this->shopUrl.$endpoint); + + $headers = array("Authorization: ".$this->apiKey); + + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + if (!empty($postdata)) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); + $headers[] = 'Content-Type: application/json'; + } + + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + $response = curl_exec($ch); + if (curl_error($ch)) { + $this->error[] = curl_error($ch); + } + curl_close($ch); + + if ($raw) + return $response; + + return simplexml_load_string($response); + } + + public function ImportAuth() { - $ch = curl_init($this->shopUrl); - curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); + $ch = curl_init($this->shopUrl."version"); + curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: ".$this->apiKey)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); - if ($code == 200) - return 'success'; - + $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + if ($code == 200) { + return 'success '.print_r($response,true); + } return $response; } @@ -314,109 +344,180 @@ class Shopimporter_Mirakl extends ShopimporterBase return $fetchedOrders; } + /* + * Fetches article list from the shop, puts them into table shopexport_getarticles, starts the prozessstarter getarticles which fetches details for each article via ImportGetArticle() + */ public function ImportGetArticleList() { $result = []; - $response = $this->miraklRequest('GET', 'products?display=[reference]'); - foreach ($response->products->product as $product) { - $result[] = $product->reference; + $response = $this->miraklRequest('offers', raw: true); + + $result_array = json_decode($response); + + foreach ($result_array->offers as $offer) { + $result[] = $offer->shop_sku; } array_unique($result); return $result; } + /* + * Fetches article details from the shop + */ public function ImportGetArticle() { - $nummer = $this->data['nummer']; - if (isset($this->data['nummerintern'])) { - $nummer = $this->data['nummerintern']; - } - $nummer = trim($nummer); + throw new Exception("Not implemented"); + } - if (empty($nummer)) - return; + /* + * Send articles to shop + */ - $productsresult = $this->miraklRequest('GET', 'products?filter[reference]='.$nummer); - $combinationsresult = $this->miraklRequest('GET', 'combinations?filter[reference]='.$nummer); - $numberOfCombinations = count($combinationsresult->combinations->combination); - $numberOfProducts = count($productsresult->products->product); - $numberOfResults = $numberOfProducts + $numberOfCombinations; - if ($numberOfResults > 1) { - $this->Log('Got multiple results from Shop', $this->data); - return; - } - elseif ($numberOfResults < 1) { - $this->Log('No product found in Shop', $this->data); - return; - } + public function ImportSendList() + { + $articleList = $this->CatchRemoteCommand('data'); + + //print_r($articleList); + + /* + Array +( + [0] => Array + ( + [artikel] => 1 + [artikelid] => 1 + [nummer] => 700001 + [inaktiv] => + [name_de] => Schraube M10x20 + [name_en] => + [einheit] => + [hersteller] => + [herstellernummer] => + [ean] => + [artikelnummer_fremdnummern] => + [kurztext_de] => + [kurztext_en] => + [anabregs_text] => + [anabregs_text_en] => + [beschreibung_de] => + [beschreibung_en] => + [uebersicht_de] => + [uebersicht_en] => + [herkunftsland] => DE + [texteuebertragen] => 1 + [metadescription_de] => + [metadescription_en] => + [metakeywords_de] => + [metakeywords_en] => + [metatitle_de] => + [metatitle_en] => + [links_de] => + [altersfreigabe] => + [links_en] => + [startseite_de] => + [startseite_en] => + [restmenge] => 0 + [startseite] => 0 + [standardbild] => + [herstellerlink] => + [lieferzeit] => + [lieferzeitmanuell] => + [gewicht] => + [laenge] => 0.00 + [breite] => 0.00 + [hoehe] => 0.00 + [wichtig] => 0 + [porto] => 0 + [gesperrt] => 0 + [sperrgrund] => + [gueltigbis] => 0000-00-00 + [umsatzsteuer] => normal + [ausverkauft] => 0 + [variante] => 0 + [variante_von_id] => 0 + [variantevon] => + [pseudopreis] => 0.00 + [keinrabatterlaubt] => 0 + [einkaufspreis] => 0.12000000 + [pseudolager] => + [downloadartikel] => 0 + [zolltarifnummer] => + [typ] => 1_kat + [kategoriename] => Handelsware (100000) + [steuer_art_produkt] => 0 + [steuer_art_produkt_download] => 0 + [anzahl_bilder] => 0 + [anzahl_lager] => + [lagerkorrekturwert] => -0 + [autolagerlampe] => 0 + [crosssellingartikel] => Array + ( + ) - $isCombination = $numberOfCombinations > 0; - if ($isCombination) { - $combinationId = intval($combinationsresult->combinations->combination->attributes()->id); - $combination = $this->miraklRequest('GET', "combinations/$combinationId"); - $productId = intval($combination->combination->id_product); - } else { - $productId = intval($productsresult->products->product->attributes()->id); - } - $product = $this->miraklRequest('GET', "products/$productId"); - $res = []; - if ($isCombination) { - $res['nummer'] = strval($combination->combination->reference); - $res['artikelnummerausshop'] = strval($combination->combination->reference); - $res['ean'] = strval($combination->combination->ean13); - $res['preis_netto'] = floatval($product->product->price) + floatval($combination->combination->price); - } else { - $res['nummer'] = strval($product->product->reference); - $res['artikelnummerausshop'] = strval($product->product->reference); - $res['ean'] = strval($product->product->ean13); - $res['preis_netto'] = floatval($product->product->price); - } - $names = $this->toMultilangArray($product->product->name->language); - $descriptions = $this->toMultilangArray($product->product->description->language); - $shortdescriptions = $this->toMultilangArray($product->product->description_short->language); - $metadescriptions = $this->toMultilangArray($product->product->meta_description->language); - $metakeywords = $this->toMultilangArray($product->product->meta_keywords->language); - $metatitles = $this->toMultilangArray($product->product->meta_title->language); - $res['name'] = $names['de']; - $res['name_en'] = $names['en']; - $res['uebersicht_de'] = $descriptions['de']; - $res['uebersicht_en'] = $descriptions['en']; - $res['kurztext_de'] = strip_tags($shortdescriptions['de']); - $res['kurztext_en'] = strip_tags($shortdescriptions['en']); - $res['hersteller'] = strval($product->product->manufacturer_name); - $res['metatitle_de'] = $metatitles['de']; - $res['metatitle_en'] = $metatitles['en']; - $res['metadescription_de'] = $metadescriptions['de']; - $res['metadescription_en'] = $metadescriptions['en']; + [waehrung] => EUR + [preis] => 0.16000000 + [steuersatz] => 19 + [staffelpreise_standard] => Array + ( + [0] => Array + ( + [ab_menge] => 1.0000 + [preis] => 0.16000000 + [bruttopreis] => 0.1904 + [waehrung] => EUR + ) - $tags = $product->product->associations->tags->tag; - $keywords = []; - foreach ($tags as $tag) { - $tagid = intval($tag->id); - $endpoint = "tags/{$tagid}"; - $tagdata = $this->miraklRequest('GET', $endpoint); - $tagiso = $this->langidToIso[intval($tagdata->tag->id_lang)]; - $tagvalue = strval($tagdata->tag->name); - if (!array_key_exists($tagiso, $keywords)) - $keywords[$tagiso] = []; - $keywords[$tagiso][] = $tagvalue; - } - $res['metakeywords_de'] = join(',', $keywords['de'] ?? []); - $res['metakeywords_en'] = join(',', $keywords['en'] ?? []); + ) - $images = []; - foreach ($product->product->associations->images->image as $img) { - $endpoint = "images/products/$productId/$img->id"; - $imgdata = $this->miraklRequest('GET', $endpoint, '', true); - $images[] = [ - 'content' => base64_encode($imgdata), - 'path' => "$img->id.jpg", - 'id' => $img->id - ]; - } - $res['bilder'] = $images; - return $res; + [staffelpreise] => Array + ( + [0] => Array + ( + [ab_menge] => 1.0000 + [preis] => 0.16000000 + [bruttopreis] => 0.1904 + [waehrung] => EUR + ) + + ) + + [bruttopreis] => 0.1904 + [checksum] => + [variantevorhanden] => 0 + ) + +) + + */ + + $offers_for_mirakl = array(); + + foreach ($articleList as $article) { + $offers_for_mirakl[] = array( + 'product_id_type' => 'sku', // ?!?! + 'price' => $article['preis'], +// 'pricing_unit' => $article['waehrung'], + 'product_id' => $article['nummer'], + 'shop_sku' => $article['nummer'], + 'state_code' => '11', // ?!?! + 'update_delete' => 'update' // update or delete + ); + } + + $data_for_mirakl = array(); + $data_for_mirakl['offers'] = $offers_for_mirakl; + + $json_for_mirakl = json_encode($data_for_mirakl); + + $result = []; + $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, raw: true); + + $result_array = json_decode($response); + + + print_r($result_array); // stdClass Object ( [import_id] => 69751 ) + exit(); } private function toMultilangArray($xmlnode) { @@ -454,30 +555,5 @@ class Shopimporter_Mirakl extends ShopimporterBase $this->app->erp->Logfile($message, print_r($dump, true)); } } - - private function miraklRequest($method, $endpoint, $data = '', $raw = false) - { - $url = $this->shopUrl . $endpoint; - $url = str_replace('[', '%5b', $url); - $url = str_replace(']', '%5d', $url); - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - if (!empty($data)) { - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - } - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - curl_setopt($ch, CURLOPT_USERNAME, $this->apiKey); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $response = curl_exec($ch); - if (curl_error($ch)) { - $this->error[] = curl_error($ch); - } - curl_close($ch); - - if ($raw) - return $response; - - return simplexml_load_string($response); - } + } diff --git a/www/pages/verbindlichkeit.php b/www/pages/verbindlichkeit.php index 374db9cb..99a1d0a4 100644 --- a/www/pages/verbindlichkeit.php +++ b/www/pages/verbindlichkeit.php @@ -228,11 +228,7 @@ class Verbindlichkeit { $defaultorder = 1; $defaultorderdesc = 0; - $offen_menge = "TRIM(IF( - pd.menge > COALESCE(vp.menge,0), - pd.menge - COALESCE(vp.menge,0), - 0 - ))+0"; + $offen_menge = ""; $auswahl = array ( '' ); @@ -303,7 +297,7 @@ class Verbindlichkeit { // END Toggle filters $sql = " - SELECT SQL_CALC_FOUND_ROWS * FROM ( + SELECT * FROM ( SELECT pa.id pa_id, ".$this->app->erp->ConcatSQL($auswahl)." AS auswahl, @@ -316,11 +310,7 @@ class Verbindlichkeit { art.name_de, pd.bemerkung, pd.menge, - IF( - pd.menge > COALESCE(vp.menge,0), - pd.menge - COALESCE(vp.menge,0), - 0 - ) offen_menge, + 0 offen_menge, ".$this->app->erp->ConcatSQL($werte).", ".$this->app->erp->ConcatSQL($preise)." AS preis, if(art.umsatzsteuer = '',art.steuersatz,art.umsatzsteuer) steuer, @@ -329,38 +319,28 @@ class Verbindlichkeit { CONCAT(skadr.sachkonto,' ',skadr.beschriftung) ) AS sachkonto FROM - paketannahme pa - INNER JOIN paketdistribution pd ON + paketdistribution pd + LEFT JOIN paketannahme pa ON pd.paketannahme = pa.id - INNER JOIN artikel art ON + LEFT JOIN artikel art ON art.id = pd.artikel LEFT JOIN adresse adr ON adr.id = pa.adresse LEFT JOIN bestellung_position bp ON bp.id = pd.bestellung_position LEFT JOIN bestellung b ON - b.id = bp.bestellung - LEFT JOIN( - SELECT - paketdistribution, - SUM(menge) AS menge - FROM - verbindlichkeit_position vp - GROUP BY - paketdistribution - ) vp - ON - vp.paketdistribution = pd.id + b.id = bp.bestellung LEFT JOIN kontorahmen skart ON skart.id = art.kontorahmen LEFT JOIN kontorahmen skadr ON skadr.id = adr.kontorahmen - WHERE pa.adresse = ".$lieferant." AND pd.vorlaeufig IS NULL".$innerwhere." + WHERE pa.adresse = '".$lieferant."' + GROUP BY pd.id ) temp "; $count = ""; -// $groupby = ""; + $groupby = ""; break; case 'verbindlichkeit_positionen': diff --git a/www/widgets/templates/_gen/shopexport.tpl b/www/widgets/templates/_gen/shopexport.tpl index c0241d10..4255bffd 100644 --- a/www/widgets/templates/_gen/shopexport.tpl +++ b/www/widgets/templates/_gen/shopexport.tpl @@ -98,7 +98,7 @@
{|Aktion|} - + [AKTIONBUTTONS]
From 823f35e44dc420b19aab8253ac7f9dad044d451c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 22 May 2024 11:23:49 +0200 Subject: [PATCH 04/52] Bugfix shop error message --- www/pages/artikel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/pages/artikel.php b/www/pages/artikel.php index 129f3592..4f583554 100644 --- a/www/pages/artikel.php +++ b/www/pages/artikel.php @@ -2868,7 +2868,7 @@ class Artikel extends GenArtikel { $pageContents = $this->app->remote->RemoteSendArticleList($shop,$artikel,$extartikelnummer); - $check = strpos($pageContents ,'error:'); + $check = strpos((string) $pageContents ,'error:'); $msg = ''; if(!empty($pageContents) && is_array($pageContents)) { if(!empty($pageContents['status']) && !empty($pageContents['message'])) { From 5c96cff8c336e4cb74f444aac7ecda71e7b9c118 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 22 May 2024 11:25:13 +0200 Subject: [PATCH 05/52] onlineshops changed options layout --- www/widgets/templates/_gen/shopexport.tpl | 28 ++++++++++++++++++----- www/widgets/widget.shopexport.php | 4 ++-- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/www/widgets/templates/_gen/shopexport.tpl b/www/widgets/templates/_gen/shopexport.tpl index 4255bffd..fab71180 100644 --- a/www/widgets/templates/_gen/shopexport.tpl +++ b/www/widgets/templates/_gen/shopexport.tpl @@ -53,20 +53,36 @@ [BEZEICHNUNG][MSGBEZEICHNUNG] - [SELMODUS] [AKTIV][MSGAKTIV] - - [EINZELSYNC][MSGEINZELSYNC] [PROJEKT][MSGPROJEKT] - [WARTESCHLANGE] {|Freigabe erfolgt manuell|} - - [SELABHOLMODUS]{|Anzahl abholen begrenzen|}:[MAXMANUELL][MSGMAXMANUELL] {|0 bedeutet Begrenzung auf 100|} + + + [SELABHOLMODUS] + + + {|Anzahl abholen begrenzen|}: + [MAXMANUELL][MSGMAXMANUELL] + {|0 bedeutet Begrenzung auf 100|} + + + [SELMODUS] + + + + [EINZELSYNC][MSGEINZELSYNC] + + + + [WARTESCHLANGE] + {|Freigabe erfolgt manuell|} + + diff --git a/www/widgets/widget.shopexport.php b/www/widgets/widget.shopexport.php index 3ff7c20e..0e6b8ed1 100644 --- a/www/widgets/widget.shopexport.php +++ b/www/widgets/widget.shopexport.php @@ -861,7 +861,7 @@ class WidgetShopexport extends WidgetGenShopexport switch($typ) { case 'textarea': - $aktcol .= ''; + $aktcol .= ''; break; case 'checkbox': $aktcol .= ''; @@ -912,7 +912,7 @@ class WidgetShopexport extends WidgetGenShopexport $aktcol .= ' '; } if(isset($val['info']) && $val['info']){ - $aktcol .= ' '.$val['info'].''; + $aktcol .= ' '.$val['info'].''; } if(isset($val['col']) && $val['col'] == 2) { From f479a12c848a1aa625ae706e0653f21ba5d986c0 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 22 May 2024 11:25:35 +0200 Subject: [PATCH 06/52] mirakl offer export --- www/pages/shopimporter_mirakl.php | 1030 ++++++++++++----------------- 1 file changed, 425 insertions(+), 605 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 864b6a75..d64f21bd 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -6,623 +6,443 @@ * SPDX-License-Identifier: LicenseRef-EGPL-3.1 */ -class Shopimporter_Mirakl extends ShopimporterBase -{ - private $app; - private $intern; - private $shopid; - private $protocol; - private $apiKey; - private $shopUrl; - private $createManufacturerAllowed = false; - private $idsabholen; - private $idbearbeitung; - private $idabgeschlossen; +class Shopimporter_Mirakl extends ShopimporterBase { - public $data; + private $app; + private $intern; + private $shopid; + private $protocol; + private $apiKey; + private $shopUrl; + private $createManufacturerAllowed = false; + private $idsabholen; + private $idbearbeitung; + private $idabgeschlossen; + public $data; + // TODO + private $langidToIso = [3 => 'de', 1 => 'en']; + private $taxationByDestinationCountry; + private $orderSearchLimit; - // TODO - private $langidToIso = [3 => 'de', 1 => 'en']; - private $taxationByDestinationCountry; - private $orderSearchLimit; + private $category_identifier_source; + private $category_identifier_source_field; + private $product_identifier_type; + private $product_identifier_source; + private $product_identifier_source_field; + private $product_field_map; + private $offer_field_map; - - public function __construct($app, $intern = false) - { - $this->app = $app; - $this->intern = $intern; - if ($intern) - return; - - } - - public function EinstellungenStruktur() - { - return [ - 'ausblenden' => ['abholmodus' => ['ab_nummer', 'zeitbereich']], - 'functions' => ['getarticlelist'], - 'felder' => [ - 'protokoll' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Protokollierung im Logfile|}:' - ], -/* 'textekuerzen' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' - ], - 'useKeyAsParameter' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' - ],*/ - 'apikey' => [ - 'typ' => 'text', - 'bezeichnung' => '{|API Key|}:', - 'size' => 40, - ], - 'shopurl' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Shop URL|}:', - 'size' => 40, - ], - 'shopidmirakl' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Shop ID des Shops (optional, int64)|}:', - 'size' => 40, - ],/* - 'steuergruppen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Steuergruppenmapping|}:', - 'size' => 40, - ], - 'zustand' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Freifeld Zustand|}:', - 'size' => 40, - ], - 'abholen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'Abholen\' Status IDs|}:', - 'size' => 40, - ], - 'bearbeitung' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'In Bearbeitung\' Status IDs|}:', - 'size' => 40, - ], - 'abgeschlossen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'Abgeschlossen\' Status IDs|}:', - 'size' => 40, - ], - 'autoerstellehersteller' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Fehlende Hersteller automatisch anlegen|}:', - 'col' => 2 - ], - 'zeigezustand' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Artikelzustand im Shop anzeigen|}:', - 'col' => 2 - ], - 'zeigepreis' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', - 'col' => 2 - ],*/ - ] - ]; - } - - public function getKonfig($shopid, $data) - { - $this->shopid = $shopid; - $this->data = $data; - $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1"); - $importerSettings = reset($importerSettings); - - $einstellungen = []; - if (!empty($importerSettings['einstellungen_json'])) { - $einstellungen = json_decode($importerSettings['einstellungen_json'], true); - } - $this->protocol = $einstellungen['felder']['protokoll']; - $this->apiKey = $einstellungen['felder']['apikey']; - $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; - if ($einstellungen['felder']['autoerstellehersteller'] === '1') { - $this->createManufacturerAllowed = true; - } - $this->idsabholen = $einstellungen['felder']['abholen']; - $this->idbearbeitung = $einstellungen['felder']['bearbeitung']; - $this->idabgeschlossen = $einstellungen['felder']['abgeschlossen']; - $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid); - $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); - } - - private function miraklRequest(string $endpoint, array $postdata = null, string $content_type = null, bool $raw = false) - { - $ch = curl_init($this->shopUrl.$endpoint); - - $headers = array("Authorization: ".$this->apiKey); - - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - - if (!empty($postdata)) { - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); - curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); - $headers[] = 'Content-Type: '.$content_type; + public function __construct($app, $intern = false) { + $this->app = $app; + $this->intern = $intern; + if ($intern) + return; } - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLINFO_HEADER_OUT, true); - curl_setopt($ch, CURLOPT_VERBOSE,true); - - $response = curl_exec($ch); - if (curl_error($ch)) { - $this->error[] = curl_error($ch); - } - curl_close($ch); + /* + * See widget.shopexport.php + */ - $information = curl_getinfo($ch); - print_r($information); - - if ($raw) - return $response; - - return simplexml_load_string($response); - } - - - public function ImportAuth() { - $ch = curl_init($this->shopUrl."version"); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: ".$this->apiKey)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $response = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); - if ($code == 200) { - return 'success '.print_r($response,true); - } - return $response; - } - - /* - * Fetches article list from the shop, puts them into table shopexport_getarticles, starts the prozessstarter getarticles which fetches details for each article via ImportGetArticle() - */ - public function ImportGetArticleList() - { - $result = []; - - $response = $this->miraklRequest('offers', raw: true); - - $result_array = json_decode($response); - - foreach ($result_array->offers as $offer) { - $result[] = $offer->shop_sku; - } - - array_unique($result); - return $result; - } - - /* - * Fetches article details from the shop - */ - public function ImportGetArticle() - { - throw new Exception("Not implemented"); - } - - /* - * Send articles to shop - */ - - public function ImportSendList() - { - $articleList = $this->CatchRemoteCommand('data'); - - //print_r($articleList); - - /* - Array -( - [0] => Array - ( - [artikel] => 1 - [artikelid] => 1 - [nummer] => 700001 - [inaktiv] => - [name_de] => Schraube M10x20 - [name_en] => - [einheit] => - [hersteller] => - [herstellernummer] => - [ean] => - [artikelnummer_fremdnummern] => - [kurztext_de] => - [kurztext_en] => - [anabregs_text] => - [anabregs_text_en] => - [beschreibung_de] => - [beschreibung_en] => - [uebersicht_de] => - [uebersicht_en] => - [herkunftsland] => DE - [texteuebertragen] => 1 - [metadescription_de] => - [metadescription_en] => - [metakeywords_de] => - [metakeywords_en] => - [metatitle_de] => - [metatitle_en] => - [links_de] => - [altersfreigabe] => - [links_en] => - [startseite_de] => - [startseite_en] => - [restmenge] => 0 - [startseite] => 0 - [standardbild] => - [herstellerlink] => - [lieferzeit] => - [lieferzeitmanuell] => - [gewicht] => - [laenge] => 0.00 - [breite] => 0.00 - [hoehe] => 0.00 - [wichtig] => 0 - [porto] => 0 - [gesperrt] => 0 - [sperrgrund] => - [gueltigbis] => 0000-00-00 - [umsatzsteuer] => normal - [ausverkauft] => 0 - [variante] => 0 - [variante_von_id] => 0 - [variantevon] => - [pseudopreis] => 0.00 - [keinrabatterlaubt] => 0 - [einkaufspreis] => 0.12000000 - [pseudolager] => - [downloadartikel] => 0 - [zolltarifnummer] => - [typ] => 1_kat - [kategoriename] => Handelsware (100000) - [steuer_art_produkt] => 0 - [steuer_art_produkt_download] => 0 - [anzahl_bilder] => 0 - [anzahl_lager] => - [lagerkorrekturwert] => -0 - [autolagerlampe] => 0 - [crosssellingartikel] => Array - ( - ) - - [waehrung] => EUR - [preis] => 0.16000000 - [steuersatz] => 19 - [staffelpreise_standard] => Array - ( - [0] => Array - ( - [ab_menge] => 1.0000 - [preis] => 0.16000000 - [bruttopreis] => 0.1904 - [waehrung] => EUR - ) - - ) - - [staffelpreise] => Array - ( - [0] => Array - ( - [ab_menge] => 1.0000 - [preis] => 0.16000000 - [bruttopreis] => 0.1904 - [waehrung] => EUR - ) - - ) - - [bruttopreis] => 0.1904 - [checksum] => - [variantevorhanden] => 0 - ) - -) - - */ - - - foreach ($articleList as $article) { - - /* - * Export product - POST P41 - Import products to the operator information system - Url - /api/products/imports - Description - - Import products to the operator information system - - Returns the import identifier to track the status of the import - Call frequencies - - Recommended: Every hour, for each seller - Maximum: Every 15 minutes, for each seller - - Query parameters - - shop_id - optional - integer - int64 - Use this parameter when your user has access to several shops. If not specified, the shop_id from your default shop will be used. - - HTTP Return Codes - - 201 - Created - Response Headers - - Location - Pre-calculated URL to call to get the import status - Input (body) - - file - required - string - binary - Import file (CSV or XML or XLSX) to upload. Use multipart/form-data with name file - - operator_format - optional - boolean - Force the use of the operator product format - Default to:false - Output (response) - - import_id - required - integer - int64 - */ - - $file_contents = 'category;Product.SellerProductID;SHOP.PRODUCT.TITLE;Product.EAN.Main_MP;ATT.GLOBAL.Brandname;ATT.GLOBAL.ManufacturerAID;ATT.GLOBAL.ManufacturerTypeDesc;Product.BaseUnit;ATT.GLOBAL.NoCUperOU;ATT.GLOBAL.NoCUperOU__UNIT;Product.DetailpageVariantValue_MP;Product.RoHS.Compliant;ATT.Text.ProductHeadline;ATT.Text.ProductFeatures;ATT.Text.ProductTextLong;ATT.Text.ProductFacts;ATT.TXT.ProductSpecifications_MP;ATT.Text.ProductDelivery;ATT.Text.ProductSysReq;ATT.Text.ProductSpecialAdd;ATT.CPCS.ArticleKeywords;Product.PrimaryImageURL_MP;Product.Image02URL_MP;Product.Image03URL_MP;Product.Image04URL_MP;Product.Image05URL_MP;Product.ImageIllustration01URL_MP;Product.ImageIllustration02URL_MP;Product.ImageSymbol01URL_MP;Product.ImageSymbol02URL_MP;Product.ImageSymbol03URL_MP;Product.ImageSymbol04URL_MP;Product.ImageSymbol05URL_MP;Product.ImageAward01URL_MP;Product.ImageAward02URL_MP;Product.ImageEnergyEfficiencyLabelURL_MP;Product.DocumentEnergyEfficiencyFicheURL_MP;Product.DocumentDatasheet01URL_MP;Product.DocumentManual01URL_MP;Product.DocumentSecurityAdvisory01URL_MP;Product.DocumentCertificate01URL_MP;Product.DocumentCertificate02URL_MP;Product.DocumentCertificate03URL_MP;Product.Video01URL_MP;Product.Video02URL_MP;Product.TaxIndicator;Product.InvalidationFlag;Product.Disposal.EPR.Category@FR;Product.Disposal.ElektroG.Code@DE;Product.Disposal.ElektroG.Brand@DE;Product.CO2.Footprint;Product.CO2.Footprint__UNIT;Product.Order-Based-Production;ATT.PRODPSEC.SOURCEVOLTAGEMIN;ATT.LOV.MEASUREMENT-CATEGORY;ATT.LOV.MOUNTING_MEASUREMENT_FEATURES;ATT.INSTALLATION_WIDTH;ATT.NUM.SOURCE_VOLTAGE;ATT.PRODSPEC.SOURCEVOLTAGEMAX__UNIT;ATT.WEIGHT.VALUE;ATT.IP;ATT.DIMENSION.LENGTH;ATT.NUM.SOURCE_VOLTAGE__UNIT;ATT.DIMENSION.WIDTH;ATT.NUM.MEASURING_RANGE_UNIVERSAL_MAX;ATT.DIMENSION.DIAMETER;ATT.NUM.INSTALLATION_HEIGHT;ATT.PRODSPEC.SOURCEVOLTAGEMAX;ATT.FRAME-HEIGHT__UNIT;ATT.FRAME-HEIGHT;ATT.LOV.MEASURING_FUNCTION;ATT.NUM.FRAME_WIDTH__UNIT;ATT.MOUNTING_DEPTH__UNIT;ATT.LOV.DISPLAY_LIGHTING;ATT.INSTALLATION_WIDTH__UNIT;ATT.NUM.DISPLAY_COUNTS;ATT.WEIGHT.VALUE__UNIT;ATT.DIGIT_HEIGHT__UNIT;ATT.DIMENSION.LENGTH__UNIT;ATT.DIMENSION.WIDTH__UNIT;ATT.NUM.MEASURING_RANGE_UNIVERSAL_MIN__UNIT;Product.Disposal.ElektroG.Pickup;ATT.DIMENSION.DIAMETER__UNIT;ATT.NUM.INSTALLATION_HEIGHT__UNIT;ATT.CALIBRATION_POSSIBLE;ATT.MOUNTING_DEPTH;ATT.NUM.MEASURING_RANGE_UNIVERSAL_MIN;ATT.DISPLAY_TYPE;ATT.DIMENSION.HEIGHT;ATT.KAT.MOUNTING_MEASUREMENT_TYPE;ATT.PRODPSEC.SOURCEVOLTAGEMIN__UNIT;ATT.COLOR;ATT.DIGIT_HEIGHT;ATT.DIMENSION.HEIGHT__UNIT;ATT.INTERFACE;ATT.NUM.FRAME_WIDTH;ATT.LOV.INTERFACES_COMPONENTS;ATT.INT.RACK_UNIT;ATT.NUM.MEASURING_RANGE_UNIVERSAL_MAX__UNIT;ATT.INT.RACK_UNIT__UNIT;ATT.LOV.CALIBRATION_TO;Product.DetailpageVariantGroup_MP -1105510;700002;"OpenXE Schraube M10x20";;Brand.5105083;OpenXE Schraube M10x20 vom Hersteller;;ST;1;unece.unit.C62;;ROHS-2;;;;;;;;;;https://conradb2b-prod.mirakl.net/mmp/media/product-media/28071/CIRCUTOR_DHC_CPM_1.png;;;;;;;;;;;;;;;;https://tde-instruments.de/wp-content/uploads/CIRCUTOR_DHC-96_CPM-HS_Datenblatt_Englisch.pdf;https://tde-instruments.de/wp-content/uploads/CIRCUTOR_DHC-96_CPM_Anleitung_Englisch.pdf;;;;;;;1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'; - - $postdata = array('file' => new CURLStringFile($file_contents,'file.csv')); - - $response = $this->miraklRequest('products/imports', postdata: $postdata, content_type: 'multipart/form-data', raw: true); - - print_r($response); - exit(); - - /* - * Export offer - */ - $offers_for_mirakl[] = array( - 'product_id_type' => 'SHOP_SKU', // ?!?! - 'price' => $article['preis'], -// 'pricing_unit' => $article['waehrung'], - 'product_id' => $article['nummer'], - 'shop_sku' => $article['nummer'], - 'state_code' => '11', // ?!?! - 'update_delete' => 'update' // update or delete - ); - } - - json_decode(null); - - $data_for_mirakl = array(); - $data_for_mirakl['offers'] = $offers_for_mirakl; - - $json_for_mirakl = json_encode($data_for_mirakl); - - $result = []; - $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); - - $result_array = json_decode($response); - - - print_r($result_array); // stdClass Object ( [import_id] => 69751 ) - exit(); - } - - private function toMultilangArray($xmlnode) { - $res = []; - foreach ($xmlnode as $item) { - $iso = $this->langidToIso[strval($item->attributes()->id)]; - $res[$iso] = strval($item); - } - return $res; - } - - private function getOrdersToProcess(int $limit) - { - $states = implode('|', explode(',', $this->idsabholen)); - $response = $this->miraklRequest('GET', "orders?display=[id]&limit=$limit&filter[current_state]=[$states]"); - $result = []; - foreach ($response->orders->order as $order) { - $result[] = strval($order->id); - } - return $result; - } - - public function getOrderSearchLimit(): int - { - if(in_array($this->orderSearchLimit, ['50', '75', '100'])) { - return (int)$this->orderSearchLimit; - } - - return 25; - } - - private function Log($message, $dump = '') - { - if ($this->protocol) { - $this->app->erp->Logfile($message, print_r($dump, true)); - } - } - - public function ImportDeleteAuftrag() - { - $auftrag = $this->data['auftrag']; - - $obj = $this->miraklRequest('GET', 'order_histories?schema=blank'); - $obj->order_history->id_order = $auftrag; - $obj->order_history->id_order_state = $this->idbearbeitung; - - $this->miraklRequest('POST', 'order_histories', $obj->asXML()); - } - - public function ImportUpdateAuftrag() - { - $auftrag = $this->data['auftrag']; - - $obj = $this->miraklRequest('GET', 'order_histories?schema=blank'); - $obj->order_history->id_order = $auftrag; - $obj->order_history->id_order_state = $this->idabgeschlossen; - - $this->miraklRequest('POST', 'order_histories', $obj->asXML()); - - $req = $this->miraklRequest('GET', "order_carriers?filter[id_order]=$auftrag&display=[id]"); - $orderCarrierId = strval($req->order_carriers->order_carrier[0]->id); - $req = $this->miraklRequest('GET', "order_carriers/$orderCarrierId"); - $req->order_carrier->tracking_number = $this->data['tracking']; - $this->miraklRequest('PUT', "order_carriers/$orderCarrierId", $req->asXML()); - } - - public function ImportGetAuftraegeAnzahl() - { - $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit()); - return count($ordersToProcess); - } - - 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"); - - if (empty($this->idsabholen)) { - return false; - } - $expectOrderArray = !empty($this->data['anzgleichzeitig']) && (int)$this->data['anzgleichzeitig'] > 1; - $expectNumber = !empty($this->data['nummer']); - if ($expectNumber) { - $ordersToProcess = [$this->data['nummer']]; - } elseif (!$expectOrderArray) { - $ordersToProcess = $this->getOrdersToProcess(1); - } else { - $ordersToProcess = $this->getOrdersToProcess($this->getOrderSearchLimit()); - } - - $fetchedOrders = []; - foreach ($ordersToProcess as $currentOrderId) { - $order = $this->miraklRequest('GET', "orders/$currentOrderId"); - $order = $order->order; - $cart = []; - $cart['zeitstempel'] = strval($order->date_add); - $cart['auftrag'] = strval($order->id); - $cart['onlinebestellnummer'] = strval($order->reference); - $cart['gesamtsumme'] = strval($order->total_paid); - $cart['versandkostennetto'] = strval($order->total_shipping_tax_excl); - $cart['bestelldatum'] = strval($order->date_add); - - $carrier = $this->miraklRequest('GET', "carriers/$order->id_carrier"); - $cart['lieferung'] = strval($carrier->carrier->name); - - $customer = $this->miraklRequest('GET', "customers/$order->id_customer"); - $cart['email'] = strval($customer->customer->email); - - $language = $this->miraklRequest('GET', "languages/{$customer->customer->id_lang}"); - if ($language->language->iso_code == "en") { - $cart['kunde_sprache'] = 'englisch'; - } - - $invoiceAddress = $this->miraklRequest('GET', "addresses/$order->id_address_invoice"); - $invoiceAddress = $invoiceAddress->address; - $invoiceCountry = $this->miraklRequest('GET', "countries/$invoiceAddress->id_country"); - $invoiceCountry = $invoiceCountry->country; - $cart['name'] = "$invoiceAddress->firstname $invoiceAddress->lastname"; - if (!empty(strval($invoiceAddress->company))) { - $cart['ansprechpartner'] = $cart['name']; - $cart['name'] = strval($invoiceAddress->company); - } - $cart['strasse'] = strval($invoiceAddress->address1); - $cart['adresszusatz'] = strval($invoiceAddress->address2); - $cart['telefon'] = strval($invoiceAddress->phone_mobile); - if (empty($cart['telefon'])) - $cart['telefon'] = strval($invoiceAddress->phone); - $cart['plz'] = strval($invoiceAddress->postcode); - $cart['ort'] = strval($invoiceAddress->city); - $cart['ustid'] = strval($invoiceAddress->vat_number); - $cart['land'] = strval($invoiceCountry->iso_code); - - if (strval($order->id_address_invoice) != strval($order->id_address_delivery)) { - $deliveryAddress = $this->miraklRequest('GET', "addresses/$order->id_address_delivery"); - $deliveryAddress = $deliveryAddress->address; - $deliveryCountry = $this->miraklRequest('GET', "countries/$deliveryAddress->id_country"); - $deliveryCountry = $deliveryCountry->country; - $cart['abweichendelieferadresse'] = 1; - $cart['lieferadresse_name'] = "$deliveryAddress->firstname $deliveryAddress->lastname"; - if (!empty(strval($deliveryAddress->company))) { - $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; - $cart['lieferadresse_name'] = strval($deliveryAddress->company); - } - $cart['lieferadresse_strasse'] = strval($deliveryAddress->address1); - $cart['lieferadresse_adresszusatz'] = strval($deliveryAddress->address2); - $cart['lieferadresse_plz'] = strval($deliveryAddress->postcode); - $cart['lieferadresse_ort'] = strval($deliveryAddress->city); - $cart['lieferadresse_land'] = strval($deliveryCountry->iso_code); - } - - //TODO - //$cart['transaktionsnummer'] - $cart['zahlungsweise'] = strval($order->payment); - - $taxedCountry = $cart['land']; - if (!empty($cart['lieferadresse_land']) && $this->taxationByDestinationCountry) { - $taxedCountry = $cart['lieferadresse_land']; - } - $lieferschwelle = $this->app->DB->SelectArr("SELECT * FROM lieferschwelle WHERE empfaengerland='$taxedCountry' LIMIT 1"); - if ($this->app->erp->IstEU($taxedCountry) || !empty($lieferschwelle['ueberschreitungsdatum'])) { - $cart['ust_befreit'] = 1; - } elseif ($this->app->erp->Export($taxedCountry)) { - $cart['ust_befreit'] = 2; - } - - $taxes = []; - $this->app->erp->RunHook('getTaxRatesFromShopOrder', 2, $taxedCountry, $taxes); - - if (isset($taxes['normal']) && $taxes['normal'] > 0) - $cart['steuersatz_normal'] = $taxes['normal']; - if (isset($taxes['ermaessigt']) && $taxes['ermaessigt'] > 0) - $cart['steuersatz_ermaessigt'] = $taxes['ermaessigt']; - - $cart['articlelist'] = []; - foreach ($order->associations->order_rows->order_row as $order_row) { - $article = [ - 'articleid' => strval($order_row->product_reference), - 'name' => strval($order_row->product_name), - 'quantity' => strval($order_row->product_quantity), - 'price_netto' => strval($order_row->unit_price_tax_excl), + public function EinstellungenStruktur() { + return [ + 'ausblenden' => ['abholmodus' => ['ab_nummer', 'zeitbereich']], + 'functions' => ['getarticlelist'], + 'felder' => [ + 'protokoll' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Protokollierung im Logfile|}:' + ], + /* 'textekuerzen' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' + ], + 'useKeyAsParameter' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' + ], */ + 'apikey' => [ + 'typ' => 'text', + 'bezeichnung' => '{|API Key|}:', + 'size' => 40, + ], + 'shopurl' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Shop URL|}:', + 'size' => 40, + ], + 'shopid' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Shop ID des Shops|}:', + 'size' => 40, + 'info' => 'optional, int64' + ], + 'category_identifier_source' => [ + 'typ' => 'select', + 'bezeichnung' => '{|Kategorie-Identifizierer|}:', + 'size' => 40, + 'optionen' => ['Kategorie' => '{|Kategorie|}', 'Freifeld' => '{|Freifeld|}', 'Eigenschaft' => '{|Eigenschaft|}'], + 'info' => 'Feld in OpenXE für die Zuordnung der Artikel zu den Katalogkategorien in Mirakl' + ], + 'category_identifier_source_field' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Kategorie-Identifizierer Freifeld oder Eigenschaft|}:', + 'size' => 40, + 'info' => 'Wenn oben Freifeld oder Eigenschaft gewählt wurde' + ], + 'product_identifier_type' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Produkt-Identifizierertyp in Mirakl|}:', + 'size' => 40, + 'info' => 'Z.B. EAN' + ], + 'product_identifier_source' => [ + 'typ' => 'select', + 'bezeichnung' => '{|Produkt-Identifizierer|}:', + 'size' => 40, + 'optionen' => ['Artikelnummer' => '{|Artikelnummer|}', 'Herstellernummer' => '{|Herstellernummer|}', 'EAN' => '{|EAN|}', 'Freifeld' => 'Freifeld', 'Eigenschaft' => 'Eigenschaft'], + 'info' => 'Feld in OpenXE für die Zuordnung der Artikel zu den Katalogprodukten in Mirakl' + ], + 'product_identifier_source_field' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Produkt-Identifizierer Freifeld oder Eigenschaft|}:', + 'size' => 40, + 'info' => 'Wenn oben Freifeld oder Eigenschaft gewählt wurde' + ], + 'product_field_map' => [ + 'typ' => 'textarea', + 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: Artikelnummer, Artikelname, Einheit, Hersteller, Herstellernummer, EAN oder eine konkrete Artikeleigenschaft' + ], + 'offer_field_map' => [ + 'typ' => 'textarea', + 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: nummer, name_de, einheit, hersteller, herstellernummer, ean u.v.m. Freifelder: {"freifeld": "Freifeld1-40"}, Eigenschaften: {"eigenschaft": "Eigenschaftenname xyz"}, Fester Wert: {"wert": "xyz"}, Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. {"freifeld": "Freifeld1", "zusatzfeld": true}' + ], + /* + 'steuergruppen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Steuergruppenmapping|}:', + 'size' => 40, + ], + 'zustand' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Freifeld Zustand|}:', + 'size' => 40, + ], + 'abholen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'Abholen\' Status IDs|}:', + 'size' => 40, + ], + 'bearbeitung' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'In Bearbeitung\' Status IDs|}:', + 'size' => 40, + ], + 'abgeschlossen' => [ + 'typ' => 'text', + 'bezeichnung' => '{|\'Abgeschlossen\' Status IDs|}:', + 'size' => 40, + ], + 'autoerstellehersteller' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Fehlende Hersteller automatisch anlegen|}:', + 'col' => 2 + ], + 'zeigezustand' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Artikelzustand im Shop anzeigen|}:', + 'col' => 2 + ], + 'zeigepreis' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', + 'col' => 2 + ], */ + ] ]; + } - if ($order_row->unit_price_tax_excl > 0) { - $steuersatz = (strval($order_row->unit_price_tax_incl) / strval($order_row->unit_price_tax_excl)) - 1; - $steuersatz = round($steuersatz, 1); - $article['steuersatz'] = $steuersatz; + public function getKonfig($shopid, $data) { + $this->shopid = $shopid; + $this->data = $data; + $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1"); + $importerSettings = reset($importerSettings); + + $einstellungen = []; + if (!empty($importerSettings['einstellungen_json'])) { + $einstellungen = json_decode($importerSettings['einstellungen_json'], true); + } + $this->protocol = $einstellungen['felder']['protokoll']; + $this->apiKey = $einstellungen['felder']['apikey']; + $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; + if ($einstellungen['felder']['autoerstellehersteller'] === '1') { + $this->createManufacturerAllowed = true; + } + $this->idsabholen = $einstellungen['felder']['abholen']; + $this->idbearbeitung = $einstellungen['felder']['bearbeitung']; + $this->idabgeschlossen = $einstellungen['felder']['abgeschlossen']; + $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid); + $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); + + $this->category_identifier_source = $einstellungen['felder']['category_identifier_source']; + $this->category_identifier_source_field = $einstellungen['felder']['category_identifier_source_field']; + $this->product_identifier_type = $einstellungen['felder']['product_identifier_type']; + $this->product_identifier_source = $einstellungen['felder']['product_identifier_source']; + $this->product_identifier_source_field = $einstellungen['felder']['product_identifier_source_field']; + $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true); + $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true); + } + + private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false) { + $ch = curl_init(); + $url_addition = ""; + + $headers = array("Authorization: " . $this->apiKey); + + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + if (!empty($getdata)) { + $url_addition = "?"; + $ampersand = ""; + foreach ($getdata as $key => $value) { + $url_addition .= $ampersand . $key . "=" . $value; + $ampersand = "&"; + } + } else if (!empty($postdata)) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); + $headers[] = 'Content-Type: ' . $content_type; } - $cart['articlelist'][] = $article; - } + curl_setopt($ch, CURLOPT_URL, $this->shopUrl . $endpoint . $url_addition); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLINFO_HEADER_OUT, true); + curl_setopt($ch, CURLOPT_VERBOSE, true); - $fetchedOrders[] = [ - 'id' => $cart['auftrag'], - 'sessionid' => '', - 'logdatei' => '', - 'warenkorb' => base64_encode(serialize($cart)), - 'warenkorbjson' => base64_encode(json_encode($cart)), - ]; + $response = curl_exec($ch); + if (curl_error($ch)) { + $this->error[] = curl_error($ch); + } + curl_close($ch); + + $information = curl_getinfo($ch); +// print_r($information); +// print_r($postdata); +// print_r($response); +// exit(); + + if ($raw) + return $response; + + return simplexml_load_string($response); } - $this->Log('Precessed order from mirakl', $fetchedOrders); - return $fetchedOrders; - } + public function ImportAuth() { + $ch = curl_init($this->shopUrl . "version"); + curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $this->apiKey)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec($ch); + $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + if ($code == 200) { + return 'success ' . print_r($response, true); + } + return $response; + } - + /* + * Fetches article list from the shop, puts them into table shopexport_getarticles, starts the prozessstarter getarticles which fetches details for each article via ImportGetArticle() + */ + + public function ImportGetArticleList() { + $result = []; + + $response = $this->miraklRequest('offers', raw: true); + + $result_array = json_decode($response); + + foreach ($result_array->offers as $offer) { + $result[] = $offer->shop_sku; + } + + array_unique($result); + return $result; + } + + /* + * Fetches article details from the shop + */ + + public function ImportGetArticle() { + + $articleList = $this->CatchRemoteCommand('data'); + + $parameters = array('product_references' => 'productID', 'product_'); + + $response = $this->miraklRequest('products?', raw: true); + + throw new Exception("Not implemented"); + } + + /* + * Send articles to shop + */ + + public function ImportSendList() { + $articleList = $this->CatchRemoteCommand('data'); + + // First gather all articles as offers and send them + // Wait for import to finish + // Evaluate import + + // Unimplemented (needed?) + // Select offers with no product + // Create products and send + // Wait for import to finish + // Evaluate import + + foreach ($articleList as $article) { + + /* + * Export offer + */ + + $additional_fields = array(); + + // Required attributes + $offer_for_mirakl = array( + 'product_id_type' => $this->product_identifier_type, + 'product_id' => $article['nummer'], // TBD + 'shop_sku' => $article['nummer'], // TBD + 'price' => $article['preis'], + 'state_code' => '11', // ?!?! + 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". + ); + + foreach ($this->offer_field_map as $offer_field => $offer_field_source) { + + $offer_field_value = null; + + print_r($this->offer_field_map); + + if (!is_array($offer_field_source)) { + if (!isset($article[$offer_field_source])) { + throw new Exception("Artikelfeld \"".$offer_field_source."\" nicht vorhanden."); + } + $offer_field_value = $article[$offer_field_source]; + } else { + + $is_additional_field = false; + + foreach ($offer_field_source as $key => $value) { + switch ($key) { + case 'freifeld': + // TBD + break; + case 'eigenschaft': + // TBD + break; + case 'wert': + $offer_field_value = $value; + break; + case 'zusatzfeld': + $is_additional_field = $value; + break; + } + } + } + + if ($is_additional_field) { + $additional_field = array ( + "code" => $offer_field, + "value" => $offer_field_value + ); + $additional_fields[] = $additional_field; + } else { + $offer_for_mirakl[$offer_field] = $offer_field_value; + } + } + + if (!empty($additional_fields)) { + $offer_for_mirakl['offer_additional_fields'] = $additional_fields; + } + + $offers_for_mirakl[] = $offer_for_mirakl; + } + + $data_for_mirakl = array(); + $data_for_mirakl['offers'] = $offers_for_mirakl; + + $json_for_mirakl = json_encode($data_for_mirakl); + +// print_r($json_for_mirakl); +// exit(); + + $result = []; + $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); + + $result = json_decode($response); + + if (!isset($result->import_id)) { + return(array('status' => false, 'message' => "Offer import in Mirakl not accepted: ".print_r($response,true))); + } + + $import_id = $result->import_id; + + // Wait for import to finish + + $status = null; + + /* + WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED + */ + + while ($status != 'COMPLETE' && $status != 'FAILED') { + sleep(5); + $response = $this->miraklRequest('offers/imports/'.$import_id, raw: true); + $result = json_decode($response); + $status = $result->status; + } + + if ($status == 'FAILED') { + return(array('status' => false, 'message' => "Offer import in Mirakl failed: ".print_r($response,true))); + } + + if ($result->lines_in_error == 0) { + return($result->lines_in_success); + } + + // Check errors + $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); + + return(array('status' => false, 'message' => "Offer import in Mirakl has errors: ".print_r($response,true))); + + } + + private function getOrdersToProcess(int $limit) { + + } + + private function Log($message, $dump = '') { + if ($this->protocol) { + $this->app->erp->Logfile($message, print_r($dump, true)); + } + } + + public function ImportDeleteAuftrag() { + + } + + public function ImportUpdateAuftrag() { + + } + + public function ImportGetAuftraegeAnzahl() { + + } + + public function ImportGetAuftrag() { + + } } + From 365b87f73407d89c5c9b8648a082f95ba2ff51d6 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 22 May 2024 13:37:30 +0200 Subject: [PATCH 07/52] mirakl required fields --- www/pages/shopimporter_mirakl.php | 97 ++++++++++++++----------------- 1 file changed, 45 insertions(+), 52 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index d64f21bd..1a59d3f8 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -76,7 +76,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'size' => 40, 'info' => 'optional, int64' ], - 'category_identifier_source' => [ +/* 'category_identifier_source' => [ 'typ' => 'select', 'bezeichnung' => '{|Kategorie-Identifizierer|}:', 'size' => 40, @@ -89,34 +89,15 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'size' => 40, 'info' => 'Wenn oben Freifeld oder Eigenschaft gewählt wurde' ], - 'product_identifier_type' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Produkt-Identifizierertyp in Mirakl|}:', - 'size' => 40, - 'info' => 'Z.B. EAN' - ], - 'product_identifier_source' => [ - 'typ' => 'select', - 'bezeichnung' => '{|Produkt-Identifizierer|}:', - 'size' => 40, - 'optionen' => ['Artikelnummer' => '{|Artikelnummer|}', 'Herstellernummer' => '{|Herstellernummer|}', 'EAN' => '{|EAN|}', 'Freifeld' => 'Freifeld', 'Eigenschaft' => 'Eigenschaft'], - 'info' => 'Feld in OpenXE für die Zuordnung der Artikel zu den Katalogprodukten in Mirakl' - ], - 'product_identifier_source_field' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Produkt-Identifizierer Freifeld oder Eigenschaft|}:', - 'size' => 40, - 'info' => 'Wenn oben Freifeld oder Eigenschaft gewählt wurde' - ], 'product_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: Artikelnummer, Artikelname, Einheit, Hersteller, Herstellernummer, EAN oder eine konkrete Artikeleigenschaft' - ], + ],*/ 'offer_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', - 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: nummer, name_de, einheit, hersteller, herstellernummer, ean u.v.m. Freifelder: {"freifeld": "Freifeld1-40"}, Eigenschaften: {"eigenschaft": "Eigenschaftenname xyz"}, Fester Wert: {"wert": "xyz"}, Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. {"freifeld": "Freifeld1", "zusatzfeld": true}' + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Zuordnung über "Mirakl-xyz": {"feld": "xyz"} oder kurz "Mirakl-xyz": "xyz" Mögliche Zuordnungen aus OpenXE sind: nummer, name_de, einheit, hersteller, herstellernummer, ean u.v.m. Freifelder wie im Reiter Freifelder mit Präfix \'freifeld_\', Eigenschaften: {"eigenschaft": "Eigenschaftenname xyz"}, Fester Wert: {"wert": "xyz"}, Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. {"feld": "name_de", "zusatzfeld": true}' ], /* 'steuergruppen' => [ @@ -310,46 +291,58 @@ class Shopimporter_Mirakl extends ShopimporterBase { $additional_fields = array(); // Required attributes + + $required = [ + 'product_id_type', + 'product_id', + 'shop_sku', + 'price' + ]; + + $missing = null; + + foreach ($required as $key) { + if (!isset($this->offer_field_map[$key])) { + $missing[] = $key; + } + } + + if ($missing) { + return(array('status' => false, 'message' => "Missing required field: ".implode(', ',$missing))); + } + $offer_for_mirakl = array( - 'product_id_type' => $this->product_identifier_type, - 'product_id' => $article['nummer'], // TBD - 'shop_sku' => $article['nummer'], // TBD - 'price' => $article['preis'], 'state_code' => '11', // ?!?! 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); +// print_r($this->offer_field_map); + foreach ($this->offer_field_map as $offer_field => $offer_field_source) { - $offer_field_value = null; - - print_r($this->offer_field_map); - if (!is_array($offer_field_source)) { - if (!isset($article[$offer_field_source])) { - throw new Exception("Artikelfeld \"".$offer_field_source."\" nicht vorhanden."); - } - $offer_field_value = $article[$offer_field_source]; - } else { + $offer_field_source = array('feld' => $offer_field_source); + } - $is_additional_field = false; + $offer_field_value = null; + $is_additional_field = false; - foreach ($offer_field_source as $key => $value) { - switch ($key) { - case 'freifeld': - // TBD - break; - case 'eigenschaft': - // TBD - break; - case 'wert': - $offer_field_value = $value; - break; - case 'zusatzfeld': - $is_additional_field = $value; - break; - } - } + foreach ($offer_field_source as $key => $value) { + switch ($key) { + case 'feld': + $offer_field_value = $article[$value]; + break; + case 'eigenschaft': + $sql = "SELECT wert FROM artikeleigenschaften ae INNER JOIN artikeleigenschaftenwerte aew ON aew.artikeleigenschaften = ae.id WHERE aew.artikel = '".$article['artikelid']."' AND ae.name = '".$value."' LIMIT 1"; + $offer_field_value = $this->app->DB->Select($sql); + break; + case 'wert': + $offer_field_value = $value; + break; + case 'zusatzfeld': + $is_additional_field = $value; + break; + } } if ($is_additional_field) { From 35e2feee2e39f628a42a4bd01292b5a626c1d0d1 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 23 May 2024 20:12:05 +0200 Subject: [PATCH 08/52] mirakl field mapping for multiple categories --- www/pages/shopimporter_mirakl.php | 141 ++++++++++++++++-------------- 1 file changed, 77 insertions(+), 64 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 1a59d3f8..839f51ec 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -30,7 +30,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $product_identifier_source; private $product_identifier_source_field; private $product_field_map; - private $offer_field_map; + private $field_map; public function __construct($app, $intern = false) { $this->app = $app; @@ -94,7 +94,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: Artikelnummer, Artikelname, Einheit, Hersteller, Herstellernummer, EAN oder eine konkrete Artikeleigenschaft' ],*/ - 'offer_field_map' => [ + 'field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Zuordnung über "Mirakl-xyz": {"feld": "xyz"} oder kurz "Mirakl-xyz": "xyz" Mögliche Zuordnungen aus OpenXE sind: nummer, name_de, einheit, hersteller, herstellernummer, ean u.v.m. Freifelder wie im Reiter Freifelder mit Präfix \'freifeld_\', Eigenschaften: {"eigenschaft": "Eigenschaftenname xyz"}, Fester Wert: {"wert": "xyz"}, Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. {"feld": "name_de", "zusatzfeld": true}' @@ -172,7 +172,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->product_identifier_source = $einstellungen['felder']['product_identifier_source']; $this->product_identifier_source_field = $einstellungen['felder']['product_identifier_source_field']; $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true); - $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true); + $this->field_map = json_decode($einstellungen['felder']['field_map'], true); } private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false) { @@ -265,13 +265,35 @@ class Shopimporter_Mirakl extends ShopimporterBase { throw new Exception("Not implemented"); } + /* + * Gets a flexible mapped fieldvalue from feld, wert or eigenschaft + */ + public function GetFieldValue($article, $field_map_entry) { + foreach ($field_map_entry as $key => $value) { + switch ($key) { + case 'feld': + return($article[$value]); + break; + case 'eigenschaft': + $sql = "SELECT wert FROM artikeleigenschaften ae INNER JOIN artikeleigenschaftenwerte aew ON aew.artikeleigenschaften = ae.id WHERE aew.artikel = '".$article['artikelid']."' AND ae.name = '".$value."' LIMIT 1"; + return($this->app->DB->Select($sql)); + break; + case 'wert': + return($value); + break; + } + } + return(null); + } + /* * Send articles to shop */ public function ImportSendList() { + $articleList = $this->CatchRemoteCommand('data'); - + // First gather all articles as offers and send them // Wait for import to finish // Evaluate import @@ -287,73 +309,64 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Export offer */ - + $processed = false; $additional_fields = array(); - // Required attributes - - $required = [ - 'product_id_type', - 'product_id', - 'shop_sku', - 'price' - ]; - - $missing = null; - - foreach ($required as $key) { - if (!isset($this->offer_field_map[$key])) { - $missing[] = $key; - } - } - - if ($missing) { - return(array('status' => false, 'message' => "Missing required field: ".implode(', ',$missing))); - } - $offer_for_mirakl = array( 'state_code' => '11', // ?!?! 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); -// print_r($this->offer_field_map); + foreach ($this->field_map['angebotskonfiguration'] as $offer_field_entry) { - foreach ($this->offer_field_map as $offer_field => $offer_field_source) { - - if (!is_array($offer_field_source)) { - $offer_field_source = array('feld' => $offer_field_source); + $kategorie = $this->GetFieldValue($article, $this->field_map['katalogkonfiguration']['kategorie']); + if ($offer_field_entry['kategorie'] != $kategorie && $offer_field_entry['kategorie'] != null) { + continue; + }; + + // Check Required attributes + $required = [ + 'product_id_type', + 'product_id', + 'shop_sku', + 'price' + ]; + $missing = null; + foreach ($required as $key) { + if (!isset($offer_field_entry['felder'][$key])) { + $missing[] = $key; + } + } + if ($missing) { + return(array('status' => false, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration von Kategorie \"".$offer_field_entry['kategorie']."\": ".implode(', ',$missing))); } + // Check Required attributes + + foreach ($offer_field_entry['felder'] as $offer_field => $offer_field_source) { + if (!is_array($offer_field_source)) { + $offer_field_source = array('feld' => $offer_field_source); + } + $offer_field_value = null; + $is_additional_field = false; + $offer_field_value = $this->GetFieldValue($article, $offer_field_source); + if (in_array('zusatzfeld', $offer_field_source)) { + $is_additional_field = true; + } + if ($is_additional_field) { + $additional_field = array ( + "code" => $offer_field, + "value" => $offer_field_value + ); + $additional_fields[] = $additional_field; + } else { + $offer_for_mirakl[$offer_field] = $offer_field_value; + } + } + $processed = true; + } - $offer_field_value = null; - $is_additional_field = false; - - foreach ($offer_field_source as $key => $value) { - switch ($key) { - case 'feld': - $offer_field_value = $article[$value]; - break; - case 'eigenschaft': - $sql = "SELECT wert FROM artikeleigenschaften ae INNER JOIN artikeleigenschaftenwerte aew ON aew.artikeleigenschaften = ae.id WHERE aew.artikel = '".$article['artikelid']."' AND ae.name = '".$value."' LIMIT 1"; - $offer_field_value = $this->app->DB->Select($sql); - break; - case 'wert': - $offer_field_value = $value; - break; - case 'zusatzfeld': - $is_additional_field = $value; - break; - } - } - - if ($is_additional_field) { - $additional_field = array ( - "code" => $offer_field, - "value" => $offer_field_value - ); - $additional_fields[] = $additional_field; - } else { - $offer_for_mirakl[$offer_field] = $offer_field_value; - } + if (!$processed) { + return(array('status' => false, 'message' => "Angebotskonfiguration für Kategorie \"".$kategorie."\" nicht gefunden")); } if (!empty($additional_fields)) { @@ -377,7 +390,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $result = json_decode($response); if (!isset($result->import_id)) { - return(array('status' => false, 'message' => "Offer import in Mirakl not accepted: ".print_r($response,true))); + return(array('status' => false, 'message' => "Angebotsimport in Mirakl abgelehnt: ".print_r($response,true))); } $import_id = $result->import_id; @@ -398,7 +411,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { - return(array('status' => false, 'message' => "Offer import in Mirakl failed: ".print_r($response,true))); + return(array('status' => false, 'message' => "Angebotsimport in Mirakl fehlgeschlagen: ".print_r($response,true))); } if ($result->lines_in_error == 0) { @@ -408,7 +421,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { // Check errors $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); - return(array('status' => false, 'message' => "Offer import in Mirakl has errors: ".print_r($response,true))); + return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler: ".print_r($response,true))); } From e71da793a38f178001da117d35135388e2e991ce Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 10:10:59 +0200 Subject: [PATCH 09/52] mirakl angebotskonfiguration multiple categories --- www/pages/shopimporter_mirakl.php | 37 ++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 839f51ec..e151fe8e 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -2,10 +2,39 @@ /* * SPDX-FileCopyrightText: 2022 Andreas Palm + * SPDX-FileCopyrightText: 2024 OpenXE project * * SPDX-License-Identifier: LicenseRef-EGPL-3.1 */ + +/* + +JSON example for field_map + +{ + "katalogkonfiguration": { + "kategorie": {"feld": "freifeld_Kategorie"} + }, + "angebotskonfiguration": + [ + { + "kategorien": ["Schrauben"], + "felder": { + "product_id_type": {"wert": "SHOP_SKU"}, + "product_id": {"feld": "nummer"}, + "shop_sku": {"feld": "nummer"}, + "price": {"feld": "preis"}, + "description": "freifeld_Kategorie", + "internal_description": {"eigenschaft": "Mirakl Steuertext"}, + "reversecharge": {"wert": "false","zusatzfeld": true}, + "warehouse": {"wert": "1","zusatzfeld": true} + } + } + ] +} +*/ + class Shopimporter_Mirakl extends ShopimporterBase { private $app; @@ -320,9 +349,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { foreach ($this->field_map['angebotskonfiguration'] as $offer_field_entry) { $kategorie = $this->GetFieldValue($article, $this->field_map['katalogkonfiguration']['kategorie']); - if ($offer_field_entry['kategorie'] != $kategorie && $offer_field_entry['kategorie'] != null) { - continue; - }; + if ($offer_field_entry['kategorien'] != null) { + if (!in_array($kategorie,$offer_field_entry['kategorien'])) { + continue; + } + } // Check Required attributes $required = [ From 7f61cad921e4fa9700813e10b77807450cb28b28 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 10:18:26 +0200 Subject: [PATCH 10/52] 3540153c417eb2f99f83aa250f3e9516fed61122 --- www/eproosystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/eproosystem.php b/www/eproosystem.php index 4e96c6bd..560f7a59 100644 --- a/www/eproosystem.php +++ b/www/eproosystem.php @@ -1111,7 +1111,7 @@ if (typeof document.hidden !== \"undefined\") { // Opera 12.10 and Firefox 18 an } // userd edit ajax call -// $poll = true; + $poll = true; if($poll) { $this->addPollJs($module, $action, $id); } From 4f106028c9fe7671186051ba10494ab38249538c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 10:53:49 +0200 Subject: [PATCH 11/52] mirakl send shop_id --- www/pages/shopimporter_mirakl.php | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index e151fe8e..7a837079 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -43,6 +43,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $protocol; private $apiKey; private $shopUrl; + private $mirakl_shopid; private $createManufacturerAllowed = false; private $idsabholen; private $idbearbeitung; @@ -99,7 +100,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'bezeichnung' => '{|Shop URL|}:', 'size' => 40, ], - 'shopid' => [ + 'mirakl_shopid' => [ 'typ' => 'text', 'bezeichnung' => '{|Shop ID des Shops|}:', 'size' => 40, @@ -178,7 +179,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->data = $data; $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1"); $importerSettings = reset($importerSettings); - $einstellungen = []; if (!empty($importerSettings['einstellungen_json'])) { $einstellungen = json_decode($importerSettings['einstellungen_json'], true); @@ -186,6 +186,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->protocol = $einstellungen['felder']['protokoll']; $this->apiKey = $einstellungen['felder']['apikey']; $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; + $this->mirakl_shopid = $einstellungen['felder']['mirakl_shopid']; + if ($einstellungen['felder']['autoerstellehersteller'] === '1') { $this->createManufacturerAllowed = true; } @@ -212,6 +214,10 @@ class Shopimporter_Mirakl extends ShopimporterBase { curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + if (!empty($this->mirakl_shopid)) { + $getdata['shop_id'] = $this->mirakl_shopid; + } + if (!empty($getdata)) { $url_addition = "?"; $ampersand = ""; @@ -219,7 +225,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { $url_addition .= $ampersand . $key . "=" . $value; $ampersand = "&"; } - } else if (!empty($postdata)) { + } + if (!empty($postdata)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); $headers[] = 'Content-Type: ' . $content_type; @@ -237,10 +244,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { curl_close($ch); $information = curl_getinfo($ch); -// print_r($information); -// print_r($postdata); -// print_r($response); -// exit(); + +/* print_r($information); + print_r($postdata); + print_r($response); + exit(); +*/ if ($raw) return $response; From d20bbe79b34b35b029eb3bf2d2896430f0ccf555 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 18:57:37 +0200 Subject: [PATCH 12/52] mirakl lagersync removed storageNotNeededElements --- www/lib/ShopimporterBase.php | 12 ------------ www/pages/shopimporter_mirakl.php | 15 +++++++-------- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/www/lib/ShopimporterBase.php b/www/lib/ShopimporterBase.php index 2d92213d..716b1469 100644 --- a/www/lib/ShopimporterBase.php +++ b/www/lib/ShopimporterBase.php @@ -632,18 +632,6 @@ Class ShopimporterBase{ 'variants', 'free_fields', ], - 'shopimporter_mirakl' => [ - 'article_descriptions', - 'translations', - 'categories', - 'properties', - 'pictures', - 'cross_selling', - 'bulk_prices', - 'standard_price', - 'variants', - 'free_fields', - ], 'shopimporter_shopify' => [ 'article_descriptions', 'translations', diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 7a837079..5d5ddadf 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -19,7 +19,6 @@ JSON example for field_map "angebotskonfiguration": [ { - "kategorien": ["Schrauben"], "felder": { "product_id_type": {"wert": "SHOP_SKU"}, "product_id": {"feld": "nummer"}, @@ -28,7 +27,8 @@ JSON example for field_map "description": "freifeld_Kategorie", "internal_description": {"eigenschaft": "Mirakl Steuertext"}, "reversecharge": {"wert": "false","zusatzfeld": true}, - "warehouse": {"wert": "1","zusatzfeld": true} + "warehouse": {"wert": "1","zusatzfeld": true}, + "quantity": {"feld": "anzahl_lager"} } } ] @@ -324,10 +324,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { return(null); } + public function ImportSendListLager() { + return($this->ImportSendList()); + } + /* * Send articles to shop */ - public function ImportSendList() { $articleList = $this->CatchRemoteCommand('data'); @@ -421,9 +424,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { $json_for_mirakl = json_encode($data_for_mirakl); -// print_r($json_for_mirakl); -// exit(); - $result = []; $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); @@ -459,8 +459,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } // Check errors - $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); - + $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler: ".print_r($response,true))); } From 57a9aa23fff9b9d73e8256c1bc128ec5a414878d Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 18:58:32 +0200 Subject: [PATCH 13/52] class.remote sendlistlager condensed --- www/lib/class.remote.php | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index ef8cabb8..0ba1f2a5 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -2218,7 +2218,7 @@ class Remote $data2 = $data; foreach ($data2 as $key => $value){ $data2[$key]['artikel'] = $value['artikelid']; - } + } $result = $this->RemoteCommand($id,'sendlistlager',$data2); $this->app->DB->Update( sprintf( @@ -2286,17 +2286,7 @@ class Remote }//Altes Verhalten } if(!$isLagerExported){ - $data2 = $data; - foreach ($data2 as $key => $value){ - $data2[$key]['artikel'] = $value['artikelid']; - } - $this->RemoteCommand($id,'sendlistlager',$data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); + $this->sendlistlager($i,$id,$data); } return $result; } From 5b9a04031ab0a22b3aa624c14e6a7cd26cbd5937 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 24 May 2024 18:59:43 +0200 Subject: [PATCH 14/52] cronjob lagerzahlen added information --- cronjobs/lagerzahlen.php | 207 +++++++++++++++++++-------------------- 1 file changed, 100 insertions(+), 107 deletions(-) diff --git a/cronjobs/lagerzahlen.php b/cronjobs/lagerzahlen.php index 4466331e..a1ef1e0b 100644 --- a/cronjobs/lagerzahlen.php +++ b/cronjobs/lagerzahlen.php @@ -1,38 +1,37 @@ Conf)) { - $conf = new Config(); - $app->Conf = $conf; +if (empty($app->Conf)) { + $conf = new Config(); + $app->Conf = $conf; } -if(empty($app->DB)) { - $app->DB = new DB($app->Conf->WFdbhost,$app->Conf->WFdbname,$app->Conf->WFdbuser,$app->Conf->WFdbpass,null,$app->Conf->WFdbport); +if (empty($app->DB)) { + $app->DB = new DB($app->Conf->WFdbhost, $app->Conf->WFdbname, $app->Conf->WFdbuser, $app->Conf->WFdbpass, null, $app->Conf->WFdbport); } -if(empty($app->erp)) { - if(class_exists('erpAPICustom')) { - $erp = new erpAPICustom($app); - } - else { - $erp = new erpAPI($app); - } - $app->erp = $erp; -} -if(empty($app->remote)) { - if(is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')){ - if(!class_exists('RemoteCustom')) { - require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; +if (empty($app->erp)) { + if (class_exists('erpAPICustom')) { + $erp = new erpAPICustom($app); + } else { + $erp = new erpAPI($app); + } + $app->erp = $erp; +} +if (empty($app->remote)) { + if (is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')) { + if (!class_exists('RemoteCustom')) { + require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; + } + $app->remote = new RemoteCustom($app); + } else { + $app->remote = new Remote($app); } - $app->remote = new RemoteCustom($app); - } - else { - $app->remote = new Remote($app); - } } $app->erp->LogFile("Lagerzahlen-Synchronisation Start"); @@ -40,34 +39,33 @@ $app->erp->LogFile("Lagerzahlen-Synchronisation Start"); $firmendatenid = $app->DB->Select("SELECT MAX(id) FROM firmendaten LIMIT 1"); - $app->DB->Update( +$app->DB->Update( "UPDATE `prozessstarter` SET `mutexcounter` = `mutexcounter` + 1 WHERE `mutex` = 1 AND `parameter` = 'lagerzahlen' AND `aktiv` = 1" - ); - if(!$app->DB->Select( +); +if (!$app->DB->Select( "SELECT `id` FROM `prozessstarter` WHERE `mutex` = 0 AND `parameter` = 'lagerzahlen' AND `aktiv` = 1" - )) { +)) { + $app->erp->LogFile("Lagerzahlen-Synchronisation Ende: Prozessstarter-Mutex nicht bereit"); return; - } - - $shops = $app->DB->SelectArr('SELECT * FROM `shopexport` WHERE `aktiv` = 1'); - if(empty($shops)) { +} +$shops = $app->DB->SelectArr('SELECT * FROM `shopexport` WHERE `aktiv` = 1'); +if (empty($shops)) { $app->erp->LogFile("Lagerzahlen-Synchronisation Ende: Keine aktiven Shops"); - return; - } - $shopByIds = []; - foreach($shops as $shop) { +} +$shopByIds = []; +foreach ($shops as $shop) { $shopByIds[$shop['id']] = $shop; - } - $shopIds = array_keys($shopByIds); - $shopIdsStr = implode(',', $shopIds); - $hours = 12; - $hoursShop = 48; - $lagerartikel = $app->DB->SelectFirstCols( - "SELECT a.id +} +$shopIds = array_keys($shopByIds); +$shopIdsStr = implode(',', $shopIds); +$hours = 12; +$hoursShop = 48; +$lagerartikel = $app->DB->SelectFirstCols( + "SELECT a.id FROM `artikel` AS `a` LEFT JOIN ( SELECT ao2.artikel, 1 AS `autolagerlampe`, @@ -97,91 +95,86 @@ $firmendatenid = $app->DB->Select("SELECT MAX(id) FROM firmendaten LIMIT 1"); ORDER BY a.cache_lagerplatzinhaltmenge = -999 DESC, ao.cache_reseted DESC, a.laststorage_sync" - ); - - if(empty($lagerartikel)) { +); +if (empty($lagerartikel)) { $app->erp->LogFile("Lagerzahlen-Synchronisation Ende: Keine fälligen Artikel"); - return; - } +} - try { +try { $r = new ReflectionMethod($app->erp, 'LagerSync'); $params = $r->getParameters(); $anzargs = count($params); - } - catch(Exception $e) { +} catch (Exception $e) { $anzargs = 2; - } +} - $clagerartikel = $lagerartikel?count($lagerartikel):0; - $app->erp->LogFile('Lagerzahlen-Synchronisation, Artikel gesamt: '.$clagerartikel); - foreach($lagerartikel as $ij => $articleId) { +$clagerartikel = $lagerartikel ? count($lagerartikel) : 0; +$app->erp->LogFile('Lagerzahlen-Synchronisation, Artikel gesamt: ' . $clagerartikel); +foreach ($lagerartikel as $articleCounter => $articleId) { $app->DB->Update( - "UPDATE `prozessstarter` + "UPDATE `prozessstarter` SET `mutex` = 1 , `mutexcounter` = 0, `letzteausfuerhung` = NOW() WHERE `parameter` = 'lagerzahlen' AND `aktiv` = 1" ); try { - if($anzargs > 2){ - $message .= $app->erp->LagerSync($articleId, false, $shopByIds); // 2nd parameter is print_echo -> prints via echo to logfile (big print_r) - }else{ - $message .= $app->erp->LagerSync($articleId, false); - } + if ($anzargs > 2) { + $message .= $app->erp->LagerSync($articleId, false, $shopByIds); // 2nd parameter is print_echo -> prints via echo to logfile (big print_r) + } else { + $message .= $app->erp->LagerSync($articleId, false); + } + } catch (Exception $exception) { + $message .= '
' . $exception->getMessage(); } - catch (Exception $exception) { - $message .= '
' . $exception->getMessage(); + if ($message != '') { + $message .= '
'; } - if($message!='') { - $message .='
'; - } - if($ij % 10 === 0 && method_exists($app->erp, 'canRunCronjob') - && !$app->erp->canRunCronjob(['lagerzahlen'])) { - $app->DB->Update( - "UPDATE `prozessstarter` - SET `mutex` = 0 , `mutexcounter` = 0, `letzteausfuerhung` = NOW() - WHERE `parameter` = 'lagerzahlen' AND `aktiv` = 1" - ); - return; + if ($articleCounter % 10 === 0 && method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['lagerzahlen'])) { + $app->DB->Update( + "UPDATE `prozessstarter` + SET `mutex` = 0 , `mutexcounter` = 0, `letzteausfuerhung` = NOW() + WHERE `parameter` = 'lagerzahlen' AND `aktiv` = 1" + ); + $app->erp->LogFile("Lagerzahlen-Synchronisation Ende: lagerzahlen-Job kann nicht geladen werden"); + return; } + $app->erp->LogFile("Lagerzahlen-Synchronisation: Warte 10 Sekunden"); usleep(10000); - } - $app->DB->Update( +} +$app->DB->Update( "UPDATE `prozessstarter` SET `mutex` = 0 , `mutexcounter` = 0, `letzteausfuerhung` = NOW() WHERE `parameter` = 'lagerzahlen' AND `aktiv` = 1" - ); - if($message !='' && $erp->Firmendaten('systemmailsabschalten') == 0 && $erp->GetFirmaMail()!='') { +); +if ($message != '' && $erp->Firmendaten('systemmailsabschalten') == 0 && $erp->GetFirmaMail() != '') { try { - if($erp->Firmendaten('systemmailsempfaenger') != ''){ - $erp->MailSend( - $erp->GetFirmaMail(), - $erp->GetFirmaName(), - $erp->Firmendaten('systemmailsempfaenger'), - 'Lagerverwaltung', - 'Systemmeldung: Auto Update Lagerlampen', - $message - ); - - }else{ - if($erp->GetFirmaBCC1() != ''){ - $erp->MailSend( - $erp->GetFirmaMail(), - $erp->GetFirmaName(), - $erp->GetFirmaBCC1(), - 'Lagerverwaltung', - 'Systemmeldung: Auto Update Lagerlampen', - $message - ); + if ($erp->Firmendaten('systemmailsempfaenger') != '') { + $erp->MailSend( + $erp->GetFirmaMail(), + $erp->GetFirmaName(), + $erp->Firmendaten('systemmailsempfaenger'), + 'Lagerverwaltung', + 'Systemmeldung: Auto Update Lagerlampen', + $message + ); + } else { + if ($erp->GetFirmaBCC1() != '') { + $erp->MailSend( + $erp->GetFirmaMail(), + $erp->GetFirmaName(), + $erp->GetFirmaBCC1(), + 'Lagerverwaltung', + 'Systemmeldung: Auto Update Lagerlampen', + $message + ); + } } - } + } catch (Exception $exception) { + $app->erp->LogFile("Lagerzahlen-Synchronisation Exception:" . $app->DB->real_escape_string($exception->getMessage())); } - catch (Exception $exception) { - $app->erp->LogFile("Lagerzahlen-Synchronisation Exception:".$app->DB->real_escape_string($exception->getMessage())); - } - } +} - $app->erp->LogFile("Lagerzahlen-Synchronisation Ende"); +$app->erp->LogFile("Lagerzahlen-Synchronisation Ende"); From f95918647a37595203d7ed3fc78119f28003a7bf Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 13 Jun 2024 15:51:30 +0200 Subject: [PATCH 15/52] reworked shop configuration fields and mapping --- www/pages/shopimporter_mirakl.php | 192 ++++++++++++------------------ www/widgets/widget.shopexport.php | 5 +- 2 files changed, 77 insertions(+), 120 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 5d5ddadf..48537af5 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -7,34 +7,6 @@ * SPDX-License-Identifier: LicenseRef-EGPL-3.1 */ - -/* - -JSON example for field_map - -{ - "katalogkonfiguration": { - "kategorie": {"feld": "freifeld_Kategorie"} - }, - "angebotskonfiguration": - [ - { - "felder": { - "product_id_type": {"wert": "SHOP_SKU"}, - "product_id": {"feld": "nummer"}, - "shop_sku": {"feld": "nummer"}, - "price": {"feld": "preis"}, - "description": "freifeld_Kategorie", - "internal_description": {"eigenschaft": "Mirakl Steuertext"}, - "reversecharge": {"wert": "false","zusatzfeld": true}, - "warehouse": {"wert": "1","zusatzfeld": true}, - "quantity": {"feld": "anzahl_lager"} - } - } - ] -} -*/ - class Shopimporter_Mirakl extends ShopimporterBase { private $app; @@ -54,13 +26,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $taxationByDestinationCountry; private $orderSearchLimit; - private $category_identifier_source; - private $category_identifier_source_field; - private $product_identifier_type; - private $product_identifier_source; - private $product_identifier_source_field; - private $product_field_map; - private $field_map; + private $category_identifier; + + private $offer_field_map; public function __construct($app, $intern = false) { $this->app = $app; @@ -70,11 +38,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { } /* - * See widget.shopexport.php + * See widget.shopexport.php, ShowExtraeinstellungen() */ public function EinstellungenStruktur() { - return [ + $einstellungen = [ 'ausblenden' => ['abholmodus' => ['ab_nummer', 'zeitbereich']], 'functions' => ['getarticlelist'], 'felder' => [ @@ -82,14 +50,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'typ' => 'checkbox', 'bezeichnung' => '{|Protokollierung im Logfile|}:' ], - /* 'textekuerzen' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Texte bei Artikelexport auf Maximallänge kürzen|}:' - ], - 'useKeyAsParameter' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Shop Version ist mindestens 1.6.1.1|}:' - ], */ 'apikey' => [ 'typ' => 'text', 'bezeichnung' => '{|API Key|}:', @@ -106,75 +66,61 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'size' => 40, 'info' => 'optional, int64' ], -/* 'category_identifier_source' => [ + 'category_identifier_source' => [ 'typ' => 'select', - 'bezeichnung' => '{|Kategorie-Identifizierer|}:', + 'bezeichnung' => '{|Katalogkategorie-Typ|}:', 'size' => 40, - 'optionen' => ['Kategorie' => '{|Kategorie|}', 'Freifeld' => '{|Freifeld|}', 'Eigenschaft' => '{|Eigenschaft|}'], - 'info' => 'Feld in OpenXE für die Zuordnung der Artikel zu den Katalogkategorien in Mirakl' + 'info' => 'Woher soll die Katalogkategorie des jeweiligen Artikels bezogen werden?', + 'default' => 'feld', + 'optionen' => ['feld' => '{|Feld|}', 'freifeld' => '{|Freifeld|}', 'eigenschaft' => '{|Eigenschaft|}', 'wert' => '{|Fester Wert|}'] ], - 'category_identifier_source_field' => [ + 'category_identifier_source_value' => [ 'typ' => 'text', - 'bezeichnung' => '{|Kategorie-Identifizierer Freifeld oder Eigenschaft|}:', + 'bezeichnung' => '{|Katalogkategorie-Wert|}:', 'size' => 40, - 'info' => 'Wenn oben Freifeld oder Eigenschaft gewählt wurde' + 'info' => '', + 'default' => 'kategoriename' ], - 'product_field_map' => [ - 'typ' => 'textarea', - 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', - 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Mögliche Zuordnungen aus OpenXE sind: Artikelnummer, Artikelname, Einheit, Hersteller, Herstellernummer, EAN oder eine konkrete Artikeleigenschaft' - ],*/ - 'field_map' => [ + 'offer_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', - 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Zuordnung über "Mirakl-xyz": {"feld": "xyz"} oder kurz "Mirakl-xyz": "xyz" Mögliche Zuordnungen aus OpenXE sind: nummer, name_de, einheit, hersteller, herstellernummer, ean u.v.m. Freifelder wie im Reiter Freifelder mit Präfix \'freifeld_\', Eigenschaften: {"eigenschaft": "Eigenschaftenname xyz"}, Fester Wert: {"wert": "xyz"}, Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. {"feld": "name_de", "zusatzfeld": true}' + 'cols' => 80, + 'rows' => 20, + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Ist keine Kategorie definiert, gilt der Eintrag für alle Artikel. Jedes Feld kann wie folgt zugeordnet werden:
Artikelfeld: "Mirakel-Feldname": {"feld": "xyz"} oder kurz "Mirakel-Feldname": "xyz",
Freifeld: "Mirakel-Feldname": {"freifeld": "Bezeichnung in Shop"} (Siehe Reiter "Freifelder"),
Eigenschaft: "Mirakel-Feldname": {"eigenschaft": "Eigenschaftenname xyz"},
Fester Wert: "Mirakel-Feldname": {"wert": "xyz"}

Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. "Mirakel-Feldname": {"feld": "name_de", "zusatzfeld": true}', + 'placeholder' => '[ + { + "kategorien": [ + "Schuhe", "Hosen" + ], + "felder": { + "product_id_type": {"wert": "SHOP_SKU"}, + "product_id": {"feld": "nummer"}, + "shop_sku": {"feld": "nummer"}, + "price": {"feld": "preis"}, + "description": {"freifeld": "Kategorie"}, + "internal_description": {"eigenschaft": "Mirakl Steuertext"}, + "reversecharge": {"wert": "false","zusatzfeld": true}, + "warehouse": {"wert": "1","zusatzfeld": true}, + "quantity": {"feld": "anzahl_lager"} + } + } +]' ], - /* - 'steuergruppen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Steuergruppenmapping|}:', - 'size' => 40, - ], - 'zustand' => [ - 'typ' => 'text', - 'bezeichnung' => '{|Freifeld Zustand|}:', - 'size' => 40, - ], - 'abholen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'Abholen\' Status IDs|}:', - 'size' => 40, - ], - 'bearbeitung' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'In Bearbeitung\' Status IDs|}:', - 'size' => 40, - ], - 'abgeschlossen' => [ - 'typ' => 'text', - 'bezeichnung' => '{|\'Abgeschlossen\' Status IDs|}:', - 'size' => 40, - ], - 'autoerstellehersteller' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Fehlende Hersteller automatisch anlegen|}:', - 'col' => 2 - ], - 'zeigezustand' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Artikelzustand im Shop anzeigen|}:', - 'col' => 2 - ], - 'zeigepreis' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Artikelpreis im Shop anzeigen|}:', - 'col' => 2 - ], */ + 'Artikelfelder' => [ + 'heading' => 'Zusatzinformationen', + 'typ' => 'info', + 'text' => 'Folgende Artikelfelder stehen zur Verfügung:', + 'bezeichnung' => null, + 'info' => 'artikel, artikelid, nummer, inaktiv, name_de, name_en, einheit, hersteller, herstellernummer, ean, artikelnummer_fremdnummern, kurztext_de, kurztext_en, anabregs_text, anabregs_text_en, beschreibung_de, beschreibung_en, uebersicht_de, uebersicht_en, herkunftsland, texteuebertragen, metadescription_de, metadescription_en, metakeywords_de, metakeywords_en, metatitle_de, metatitle_en, links_de, altersfreigabe, links_en, startseite_de, startseite_en, restmenge, startseite, standardbild, herstellerlink, lieferzeit, lieferzeitmanuell, gewicht, laenge, breite, hoehe, wichtig, porto, gesperrt, sperrgrund, gueltigbis, umsatzsteuer, ausverkauft, variante, variante_von_id, variantevon, pseudopreis, keinrabatterlaubt, einkaufspreis, pseudolager, downloadartikel, zolltarifnummer, freifeld_Kategorie, typ, kategoriename, steuer_art_produkt, steuer_art_produkt_download, anzahl_bilder, anzahl_lager, lagerkorrekturwert, autolagerlampe, waehrung, preis, steuersatz, bruttopreis, checksum, variantevorhanden' + ] ] ]; + + return($einstellungen); } public function getKonfig($shopid, $data) { + $this->shopid = $shopid; $this->data = $data; $importerSettings = $this->app->DB->SelectArr("SELECT `einstellungen_json` FROM `shopexport` WHERE `id` = '$shopid' LIMIT 1"); @@ -197,13 +143,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid); $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); - $this->category_identifier_source = $einstellungen['felder']['category_identifier_source']; - $this->category_identifier_source_field = $einstellungen['felder']['category_identifier_source_field']; - $this->product_identifier_type = $einstellungen['felder']['product_identifier_type']; - $this->product_identifier_source = $einstellungen['felder']['product_identifier_source']; - $this->product_identifier_source_field = $einstellungen['felder']['product_identifier_source_field']; - $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true); - $this->field_map = json_decode($einstellungen['felder']['field_map'], true); + $this->category_identifier = array($einstellungen['felder']['category_identifier_source'] => $einstellungen['felder']['category_identifier_source_value']); + + $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); } private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false) { @@ -310,7 +252,18 @@ class Shopimporter_Mirakl extends ShopimporterBase { foreach ($field_map_entry as $key => $value) { switch ($key) { case 'feld': - return($article[$value]); + if (isset($article[$value])) { + return($article[$value]); + } else { + throw new Exception("Artikelfeld existiert nicht: \"".$value."\""); + } + break; + case 'freifeld': + if (isset($article['freifelder']['DE'][$value])) { + return($article['freifelder']['DE'][$value]); + } else { + throw new Exception("Freifeld existiert nicht: \"".$value."\""); + } break; case 'eigenschaft': $sql = "SELECT wert FROM artikeleigenschaften ae INNER JOIN artikeleigenschaftenwerte aew ON aew.artikeleigenschaften = ae.id WHERE aew.artikel = '".$article['artikelid']."' AND ae.name = '".$value."' LIMIT 1"; @@ -320,7 +273,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { return($value); break; } - } + } return(null); } @@ -350,23 +303,25 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Export offer */ - $processed = false; + $category_found = false; $additional_fields = array(); $offer_for_mirakl = array( 'state_code' => '11', // ?!?! 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); - - foreach ($this->field_map['angebotskonfiguration'] as $offer_field_entry) { - $kategorie = $this->GetFieldValue($article, $this->field_map['katalogkonfiguration']['kategorie']); + $kategorie = $this->GetFieldValue($article, $this->category_identifier); + + foreach ($this->offer_field_map as $offer_field_entry) { if ($offer_field_entry['kategorien'] != null) { if (!in_array($kategorie,$offer_field_entry['kategorien'])) { continue; } - } - + } + + $category_found = true; + // Check Required attributes $required = [ 'product_id_type', @@ -405,12 +360,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { $offer_for_mirakl[$offer_field] = $offer_field_value; } } - $processed = true; } - if (!$processed) { - return(array('status' => false, 'message' => "Angebotskonfiguration für Kategorie \"".$kategorie."\" nicht gefunden")); - } + if (!$category_found) { + return(array('status' => false, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Kategorie \"".$kategorie."\" nicht gefunden")); + } if (!empty($additional_fields)) { $offer_for_mirakl['offer_additional_fields'] = $additional_fields; diff --git a/www/widgets/widget.shopexport.php b/www/widgets/widget.shopexport.php index 0e6b8ed1..d2ab80d0 100644 --- a/www/widgets/widget.shopexport.php +++ b/www/widgets/widget.shopexport.php @@ -861,7 +861,7 @@ class WidgetShopexport extends WidgetGenShopexport switch($typ) { case 'textarea': - $aktcol .= ''; + $aktcol .= ''; break; case 'checkbox': $aktcol .= ''; @@ -894,6 +894,9 @@ class WidgetShopexport extends WidgetGenShopexport } } break; + case 'info': + $aktcol .= $val['text']; + break; default: switch($typ) { case 'datum': From b06e0aa3e404bf4468550571ed330f020701d414 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Sat, 15 Jun 2024 18:52:46 +0200 Subject: [PATCH 16/52] mirakl create product initial --- www/pages/shopimporter_mirakl.php | 170 +++++++++++++++++++++++++++--- 1 file changed, 157 insertions(+), 13 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 48537af5..2f369bd6 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -29,6 +29,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $category_identifier; private $offer_field_map; + private $product_field_map; public function __construct($app, $intern = false) { $this->app = $app; @@ -81,6 +82,31 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'info' => '', 'default' => 'kategoriename' ], + 'product_field_map' => [ + 'typ' => 'textarea', + 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', + 'cols' => 80, + 'rows' => 20, + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Ist keine Kategorie definiert, gilt der Eintrag für alle Artikel. Jedes Feld kann wie folgt zugeordnet werden:
Artikelfeld: "Mirakel-Feldname": {"feld": "xyz"} oder kurz "Mirakel-Feldname": "xyz",
Freifeld: "Mirakel-Feldname": {"freifeld": "Bezeichnung in Shop"} (Siehe Reiter "Freifelder"),
Eigenschaft: "Mirakel-Feldname": {"eigenschaft": "Eigenschaftenname xyz"},
Fester Wert: "Mirakel-Feldname": {"wert": "xyz"}

Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. "Mirakel-Feldname": {"feld": "name_de", "zusatzfeld": true}', + 'placeholder' => '[ + { + "kategorien": [ + "Schuhe", "Hosen" + ], + "felder": { + "category": {"freifeld": "Kategorie"}, + "Product.SellerProductID": {"feld": "nummer"}, + "SHOP.PRODUCT.TITLE": {"feld": "nummer"}, + "ATT.GLOBAL.Brandname": {"feld": "preis"}, + "Product.BaseUnit": {"freifeld": "Kategorie"}, + "ATT.GLOBAL.NoCUperOU": {"eigenschaft": "Mirakl Steuertext"}, + "ATT.GLOBAL.NoCUperOU__UNIT": {"wert": "false","zusatzfeld": true}, + "Product.TaxIndicator": {"wert": "1","zusatzfeld": true} + } + } +]' + ], + 'offer_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', @@ -145,10 +171,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->category_identifier = array($einstellungen['felder']['category_identifier_source'] => $einstellungen['felder']['category_identifier_source_value']); - $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); + $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); + $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true, flags: JSON_THROW_ON_ERROR); } - private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false) { + private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false, $debug = false, $debugurl = null) { $ch = curl_init(); $url_addition = ""; @@ -171,10 +198,17 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!empty($postdata)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); + $headers[] = 'Content-Type: ' . $content_type; } - curl_setopt($ch, CURLOPT_URL, $this->shopUrl . $endpoint . $url_addition); + if ($debugurl) { + $url = $debugurl; + } else { + $url = $this->shopUrl; + } + + curl_setopt($ch, CURLOPT_URL, $url . $endpoint . $url_addition); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_VERBOSE, true); @@ -187,11 +221,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $information = curl_getinfo($ch); -/* print_r($information); - print_r($postdata); - print_r($response); - exit(); -*/ + if ($debug) { + print_r($information); + print_r($postdata); + print_r($response); + exit(); + } if ($raw) return $response; @@ -287,6 +322,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { public function ImportSendList() { $articleList = $this->CatchRemoteCommand('data'); + + $this->Log('ImportSendList start', print_r($articleList,true)); // First gather all articles as offers and send them // Wait for import to finish @@ -378,12 +415,15 @@ class Shopimporter_Mirakl extends ShopimporterBase { $json_for_mirakl = json_encode($data_for_mirakl); + $this->Log('posting offer data', $json_for_mirakl); + $result = []; $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); $result = json_decode($response); if (!isset($result->import_id)) { + $this->Log('posting offer data error', print_r($response,true)); return(array('status' => false, 'message' => "Angebotsimport in Mirakl abgelehnt: ".print_r($response,true))); } @@ -405,16 +445,120 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { + $this->Log('importing of offer data failed in mirakl', print_r($response,true)); return(array('status' => false, 'message' => "Angebotsimport in Mirakl fehlgeschlagen: ".print_r($response,true))); } - + if ($result->lines_in_error == 0) { + $this->Log('importing of offer data ok', print_r($response,true)); return($result->lines_in_success); } - // Check errors - $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); - return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler: ".print_r($response,true))); + $this->Log('importing of offer returned with '.$result->lines_in_error.' lines', print_r($response,true)); + + $result = array(); + // Check errors with CSV unfucking... + $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); + $response_lines = preg_split('/\R/', $response, flags: PREG_SPLIT_NO_EMPTY); + + $error_message_key = null; + $firstline = true; + + foreach ($response_lines as $response_line) { + + $response_array = str_getcsv($response_line,';','"'); + + if ($firstline) { + $error_message_key = array_search("error-message",$response_array); + $firstline = false; + continue; + } + + switch ($response_array[$error_message_key]) { + case 'The product does not exist': + + // Try to create the product + $product_for_mirakl = array(); + + print_r($this->product_field_map); + + foreach ($this->product_field_map as $product_field_entry) { + foreach ($product_field_entry['felder'] as $product_field => $product_field_source) { + if (!is_array($product_field_source)) { + $product_field_source = array('feld' => $product_field_source); + } + $product_field_value = null; + $product_field_value = $this->GetFieldValue($article, $product_field_source); + $product_for_mirakl[$product_field] = $product_field_value; + } + } + + $this->Log('creating product', print_r($product_for_mirakl,true)); + + // Create CSV from array + $csv1 .= '"'.implode('";"',array_keys($product_for_mirakl)).'"'; + $csv2 .= '"'.implode('";"',$product_for_mirakl).'"'; + $csv = $csv1."\r\n".$csv2; + + $result = []; + + $this->Log('creating product csv', print_r($csv,true)); + + $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); + + $response = $this->miraklRequest('products/imports', postdata: $postdata, content_type: 'multipart/form-data', raw: true); + + $result = json_decode($response); + + $this->Log('posting product data posted', print_r($result,true)); + + if (!isset($result->import_id)) { + $this->Log('posting product data error', print_r($response,true)); + return(array('status' => false, 'message' => "Produktimport in Mirakl abgelehnt: ".print_r($response,true))); + } + + $import_id = $result->import_id; + + // Wait for import to finish + + $status = null; + + /* + WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED + */ + + while ($status != 'COMPLETE' && $status != 'FAILED') { + sleep(5); + $response = $this->miraklRequest('products/imports/'.$import_id, raw: true); + $result = json_decode($response); + $status = $result->import_status; + } + + if ($status == 'FAILED') { + $this->Log('importing of product data failed in mirakl', print_r($response,true)); + return(array('status' => false, 'message' => "Produktimport in Mirakl fehlgeschlagen: ".print_r($response,true))); + } + + if ($result->transform_lines_in_error == 0) { + $this->Log('importing of product data ok', print_r($response,true)); + return($result->lines_in_success); + } + + $this->Log('importing of product returned with '.$result->transform_lines_in_error.' error lines', print_r($response,true)); + + $response = $this->miraklRequest('products/imports/'.$import_id.'/transformation_error_report', raw: true); + + $this->Log('product import error report', print_r($response,true)); + + + break; + default: + $result[] = array('Unhandled error' => $response_array); + break; + } + } + + return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler: ".print_r($result,true))); } @@ -424,7 +568,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private function Log($message, $dump = '') { if ($this->protocol) { - $this->app->erp->Logfile($message, print_r($dump, true)); + $this->app->erp->Logfile('Mirakl (Shop '.$this->shopid.') '.$message, print_r($dump, true)); } } From bb4538498af0fb4c05face8bbb5e8e7ac3b475df Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 17 Jun 2024 13:09:30 +0200 Subject: [PATCH 17/52] mirakl reworked logging and functions --- www/pages/shopimporter_mirakl.php | 657 +++++++++++++++++++----------- 1 file changed, 420 insertions(+), 237 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 2f369bd6..08ecd777 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -28,6 +28,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $category_identifier; + private $create_products; + private $mirakl_error_text_product_missing; + private $offer_field_map; private $product_field_map; @@ -82,6 +85,19 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'info' => '', 'default' => 'kategoriename' ], + 'create_products' => [ + 'typ' => 'checkbox', + 'bezeichnung' => '{|Produkte anlegen|}:', + 'size' => 40, + 'info' => 'Produkte automatisch anlegen wenn sie nicht existieren' + ], + 'mirakl_error_text_product_missing' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Fehlertext Produkt fehlt|}:', + 'size' => 40, + 'info' => 'Der Fehlertext der anzeigt dass das Produkt nicht existiert (Angebotsimport, Fehlerbericht)', + 'default' => 'The product does not exist' + ], 'product_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', @@ -171,8 +187,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->category_identifier = array($einstellungen['felder']['category_identifier_source'] => $einstellungen['felder']['category_identifier_source_value']); - $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); - $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true, flags: JSON_THROW_ON_ERROR); + $this->create_products = $einstellungen['felder']['create_products']; + $this->mirakl_error_text_product_missing = $einstellungen['felder']['mirakl_error_text_product_missing']; + + $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); + $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true, flags: JSON_THROW_ON_ERROR); + } private function miraklRequest(string $endpoint, $postdata = null, array $getdata = null, string $content_type = null, bool $raw = false, $debug = false, $debugurl = null) { @@ -322,243 +342,49 @@ class Shopimporter_Mirakl extends ShopimporterBase { public function ImportSendList() { $articleList = $this->CatchRemoteCommand('data'); - - $this->Log('ImportSendList start', print_r($articleList,true)); - - // First gather all articles as offers and send them - // Wait for import to finish - // Evaluate import - - // Unimplemented (needed?) - // Select offers with no product - // Create products and send - // Wait for import to finish - // Evaluate import - - foreach ($articleList as $article) { - - /* - * Export offer - */ - $category_found = false; - $additional_fields = array(); - - $offer_for_mirakl = array( - 'state_code' => '11', // ?!?! - 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". - ); - - $kategorie = $this->GetFieldValue($article, $this->category_identifier); - - foreach ($this->offer_field_map as $offer_field_entry) { - if ($offer_field_entry['kategorien'] != null) { - if (!in_array($kategorie,$offer_field_entry['kategorien'])) { - continue; - } - } - - $category_found = true; - - // Check Required attributes - $required = [ - 'product_id_type', - 'product_id', - 'shop_sku', - 'price' - ]; - $missing = null; - foreach ($required as $key) { - if (!isset($offer_field_entry['felder'][$key])) { - $missing[] = $key; - } - } - if ($missing) { - return(array('status' => false, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration von Kategorie \"".$offer_field_entry['kategorie']."\": ".implode(', ',$missing))); - } - // Check Required attributes - - foreach ($offer_field_entry['felder'] as $offer_field => $offer_field_source) { - if (!is_array($offer_field_source)) { - $offer_field_source = array('feld' => $offer_field_source); - } - $offer_field_value = null; - $is_additional_field = false; - $offer_field_value = $this->GetFieldValue($article, $offer_field_source); - if (in_array('zusatzfeld', $offer_field_source)) { - $is_additional_field = true; - } - if ($is_additional_field) { - $additional_field = array ( - "code" => $offer_field, - "value" => $offer_field_value - ); - $additional_fields[] = $additional_field; - } else { - $offer_for_mirakl[$offer_field] = $offer_field_value; - } - } - } - - if (!$category_found) { - return(array('status' => false, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Kategorie \"".$kategorie."\" nicht gefunden")); - } - - if (!empty($additional_fields)) { - $offer_for_mirakl['offer_additional_fields'] = $additional_fields; - } - - $offers_for_mirakl[] = $offer_for_mirakl; - } - - $data_for_mirakl = array(); - $data_for_mirakl['offers'] = $offers_for_mirakl; - - $json_for_mirakl = json_encode($data_for_mirakl); - - $this->Log('posting offer data', $json_for_mirakl); - - $result = []; - $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); - - $result = json_decode($response); - - if (!isset($result->import_id)) { - $this->Log('posting offer data error', print_r($response,true)); - return(array('status' => false, 'message' => "Angebotsimport in Mirakl abgelehnt: ".print_r($response,true))); - } - - $import_id = $result->import_id; - - // Wait for import to finish - - $status = null; - - /* - WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED - */ - - while ($status != 'COMPLETE' && $status != 'FAILED') { - sleep(5); - $response = $this->miraklRequest('offers/imports/'.$import_id, raw: true); - $result = json_decode($response); - $status = $result->status; - } - - if ($status == 'FAILED') { - $this->Log('importing of offer data failed in mirakl', print_r($response,true)); - return(array('status' => false, 'message' => "Angebotsimport in Mirakl fehlgeschlagen: ".print_r($response,true))); - } - - if ($result->lines_in_error == 0) { - $this->Log('importing of offer data ok', print_r($response,true)); - return($result->lines_in_success); - } - - $this->Log('importing of offer returned with '.$result->lines_in_error.' lines', print_r($response,true)); - - $result = array(); - // Check errors with CSV unfucking... - $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); - $response_lines = preg_split('/\R/', $response, flags: PREG_SPLIT_NO_EMPTY); - - $error_message_key = null; - $firstline = true; - - foreach ($response_lines as $response_line) { - - $response_array = str_getcsv($response_line,';','"'); - - if ($firstline) { - $error_message_key = array_search("error-message",$response_array); - $firstline = false; - continue; - } - - switch ($response_array[$error_message_key]) { - case 'The product does not exist': - - // Try to create the product - $product_for_mirakl = array(); - - print_r($this->product_field_map); - - foreach ($this->product_field_map as $product_field_entry) { - foreach ($product_field_entry['felder'] as $product_field => $product_field_source) { - if (!is_array($product_field_source)) { - $product_field_source = array('feld' => $product_field_source); - } - $product_field_value = null; - $product_field_value = $this->GetFieldValue($article, $product_field_source); - $product_for_mirakl[$product_field] = $product_field_value; - } - } - - $this->Log('creating product', print_r($product_for_mirakl,true)); - - // Create CSV from array - $csv1 .= '"'.implode('";"',array_keys($product_for_mirakl)).'"'; - $csv2 .= '"'.implode('";"',$product_for_mirakl).'"'; - $csv = $csv1."\r\n".$csv2; - - $result = []; - - $this->Log('creating product csv', print_r($csv,true)); - - $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); - - $response = $this->miraklRequest('products/imports', postdata: $postdata, content_type: 'multipart/form-data', raw: true); - - $result = json_decode($response); - - $this->Log('posting product data posted', print_r($result,true)); - - if (!isset($result->import_id)) { - $this->Log('posting product data error', print_r($response,true)); - return(array('status' => false, 'message' => "Produktimport in Mirakl abgelehnt: ".print_r($response,true))); - } - - $import_id = $result->import_id; - - // Wait for import to finish - - $status = null; - - /* - WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED - */ - - while ($status != 'COMPLETE' && $status != 'FAILED') { - sleep(5); - $response = $this->miraklRequest('products/imports/'.$import_id, raw: true); - $result = json_decode($response); - $status = $result->import_status; - } - - if ($status == 'FAILED') { - $this->Log('importing of product data failed in mirakl', print_r($response,true)); - return(array('status' => false, 'message' => "Produktimport in Mirakl fehlgeschlagen: ".print_r($response,true))); - } - - if ($result->transform_lines_in_error == 0) { - $this->Log('importing of product data ok', print_r($response,true)); - return($result->lines_in_success); - } - - $this->Log('importing of product returned with '.$result->transform_lines_in_error.' error lines', print_r($response,true)); - - $response = $this->miraklRequest('products/imports/'.$import_id.'/transformation_error_report', raw: true); - - $this->Log('product import error report', print_r($response,true)); - - - break; - default: - $result[] = array('Unhandled error' => $response_array); - break; - } + + $offer_export_result = $this->mirakl_export_offers($articleList); + + if ($offer_export_result['returncode'] == 0) { + return(array('status' => true, 'message' => "Angebotsimport in Mirakl ok")); } - return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler: ".print_r($result,true))); + // Check for missing products and try to create + if ($this->create_products) { + + $create_products_list = array(); + + foreach ($offer_export_result['articleList'] as $key => $article) { + if ($article['mirakl_export_offers_result']['returncode'] == 12) { + switch ($article['mirakl_export_offers_result']['message']) { + case $this->mirakl_error_text_product_missing: + $create_products_list[] = $article; + break; + } + } + } + + if (empty($create_products_list)) { + return(array('status' => false, 'message' => "Produktimport nicht möglich")); + } + + $create_products_result = $this->mirakl_create_products($create_products_list); + + if ($create_products_result['returncode'] != 0) { + $this->Log("Produktimport in Mirakl hat Fehler", print_r($create_products_result, true)); + return(array('status' => false, 'message' => "Produktimport in Mirakl hat Fehler")); + } + + // Retry offer import + $offer_export_result = $this->mirakl_export_offers($articleList); + if ($offer_export_result['returncode'] == 0) { + return(array('status' => true, 'message' => "Angebots und Produktimport in Mirakl ok")); + } + } + + $this->Log("Angebotsimport in Mirakl hat Fehler", print_r($offer_export_result, true)); + + return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); } @@ -587,5 +413,362 @@ class Shopimporter_Mirakl extends ShopimporterBase { public function ImportGetAuftrag() { } + + /* + * Send offer data to mirakl + * $articleList = $this->CatchRemoteCommand('data'); + * Return + * array (returncode, message, articleList) articleList with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) + * returncode 0 = ok, 1 = not ok + * returncode articleList 0 = ok, 10 = missing required attributes, 11 category not found, 12 rejected from mirakl + */ + private function mirakl_export_offers(array $articleList) : array { + + $mirakl_export_offers_return_value = array(); + $mirakl_export_offers_return_value['returncode'] = 0; + $mirakl_export_offers_return_value['articleList'] = array(); + + $this->Log('Angebotsexport start', print_r($articleList,true)); + + // First gather all articles as offers and send them + // Wait for import to finish + // Evaluate import + + foreach ($articleList as $key => $article) { + + $skip_article = false; + + /* + * Export offer + */ + $category_found = false; + $additional_fields = array(); + + $offer_for_mirakl = array( + 'state_code' => '11', // ?!?! + 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". + ); + + $kategorie = $this->GetFieldValue($article, $this->category_identifier); + + foreach ($this->offer_field_map as $offer_field_entry) { + if ($offer_field_entry['kategorien'] != null) { + if (!in_array($kategorie,$offer_field_entry['kategorien'])) { + continue; + } + } + + $category_found = true; + + // Check required attributes + $required = [ + 'product_id_type', + 'product_id', + 'shop_sku', + 'price' + ]; + $missing = null; + foreach ($required as $key) { + if (!isset($offer_field_entry['felder'][$key])) { + $missing[] = $key; + } + } + if ($missing) { + $mirakl_export_offers_return_value['returncode'] = 1; + $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration von Kategorie \"".$offer_field_entry['kategorie']."\": ".implode(', ',$missing)); + $mirakl_export_offers_return_value['articleList'][] = $article; + $skip_article = true; + } + // Check Required attributes + + foreach ($offer_field_entry['felder'] as $offer_field => $offer_field_source) { + if (!is_array($offer_field_source)) { + $offer_field_source = array('feld' => $offer_field_source); + } + $offer_field_value = null; + $is_additional_field = false; + $offer_field_value = $this->GetFieldValue($article, $offer_field_source); + if (in_array('zusatzfeld', $offer_field_source)) { + $is_additional_field = true; + } + if ($is_additional_field) { + $additional_field = array ( + "code" => $offer_field, + "value" => $offer_field_value + ); + $additional_fields[] = $additional_field; + } else { + $offer_for_mirakl[$offer_field] = $offer_field_value; + } + } + } + + if ($skip_article) { + continue; + } + + if (!$category_found) { + $mirakl_export_offers_return_value['returncode'] = 1; + $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Kategorie \"".$kategorie."\" nicht gefunden"); + $mirakl_export_offers_return_value['articleList'][] = $article; + continue; + } + + if (!empty($additional_fields)) { + $offer_for_mirakl['offer_additional_fields'] = $additional_fields; + } + + $offers_for_mirakl[] = $offer_for_mirakl; + + $article['mirakl_export_offers_result'] = array('returncode' => 0, 'message' => ""); + $mirakl_export_offers_return_value['articleList'][] = $article; + + } + + if (empty($offers_for_mirakl)) { + $mirakl_export_offers_return_value['returncode'] = 1; + $this->Log('Angebotsexport keine Artikel bereit', $mirakl_export_offers_return_value); + $mirakl_export_offers_return_value['message'] = "Angebotsexport keine Artikel bereit"; + return($mirakl_export_offers_return_value); + } + + $data_for_mirakl = array(); + $data_for_mirakl['offers'] = $offers_for_mirakl; + + $json_for_mirakl = json_encode($data_for_mirakl); + + $this->Log('Angebotsexport Daten', $json_for_mirakl); + + $result = []; + $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); + + $result = json_decode($response); + + if (!isset($result->import_id)) { + $mirakl_export_offers_return_value['returncode'] = 1; + $this->Log('Angebotsimport abgelehnt', print_r($response,true)); + $mirakl_export_offers_return_value['message'] = "Angebotsimport abgelehnt: ".print_r($response,true); + return($mirakl_export_offers_return_value); + } + + $this->Log('Angebotsimport angelegt', print_r($response,true)); + + $import_id = $result->import_id; + + // Wait for import to finish + + $status = null; + + /* + WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED + */ + + while ($status != 'COMPLETE' && $status != 'FAILED') { + sleep(5); + $response = $this->miraklRequest('offers/imports/'.$import_id, raw: true); + $result = json_decode($response); + $status = $result->status; + } + + if ($status == 'FAILED') { + $this->Log('Angebotsimport fehlgeschlagen', print_r($response,true)); + + $mirakl_export_offers_return_value['returncode'] = 2; + $mirakl_export_offers_return_value['message'] = "Angebotsimport fehlgeschlagen: ".print_r($response,true); + return($mirakl_export_offers_return_value); + } + + if ($result->lines_in_error == 0) { + $this->Log('Angebotsimport ok', print_r($response,true)); + return($mirakl_export_offers_return_value); + } + + $this->Log('Angebotsimport meldet Fehler in '.$result->lines_in_error.' Zeilen', print_r($response,true)); + + $result = array(); + // Check errors with CSV unfucking... + $response = $this->miraklRequest('offers/imports/'.$import_id.'/error_report', raw: true); + $response_lines = preg_split('/\R/', $response, flags: PREG_SPLIT_NO_EMPTY); + + $error_message_key = null; + $firstline = true; + + foreach ($response_lines as $key => $response_line) { + $response_array = str_getcsv($response_line,';','"'); + if ($firstline) { + $error_message_key = array_search("error-message",$response_array); + $firstline = false; + continue; + } + + $article_key = array_search( + $response_array['product_id'], + array_column( + $mirakl_export_offers_return_value['articleList'], + 'product_id') + ); + + $mirakl_export_offers_return_value['articleList'][$article_key]['mirakl_export_offers_result'] = array('returncode' => 12, 'message' => $response_array[$error_message_key]); + } + + $this->Log('Angebotsimport Fehlerbericht', print_r($response,true)); + + $mirakl_export_offers_return_value['returncode'] = 1; + + return($mirakl_export_offers_return_value); + } + + /* + * Create products + * Return + * array (returncode, message, articleList) articleList with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) + * returncode 0 = ok, 1 = not ok + * returncode articleList 0 = ok, 20 rejected from mirakl + */ + private function mirakl_create_products(array $articleList) : array { + + $mirakl_create_products_return_value = array(); + $mirakl_create_products_return_value['returncode'] = 0; + $mirakl_create_products_return_value['articleList'] = $articleList; + + // Build CSV + $csv_header = ""; + $newline = ""; + foreach ($articleList as $article) { + + // Try to create the product + $product_for_mirakl = array(); + foreach ($this->product_field_map as $product_field_entry) { + foreach ($product_field_entry['felder'] as $product_field => $product_field_source) { + if (!is_array($product_field_source)) { + $product_field_source = array('feld' => $product_field_source); + } + $product_field_value = null; + $product_field_value = $this->GetFieldValue($article, $product_field_source); + $product_for_mirakl[$product_field] = $product_field_value; + } + } + + // Create CSV from array + if (empty($csv_header)) { + $csv_header .= '"'.implode('";"',array_keys($product_for_mirakl)).'"'; + } + $csv .= $newline.'"'.implode('";"',$product_for_mirakl).'"'; + $newline = "\r\n"; + } + + $csv = $csv_header.$newline.$csv; + + $result = []; + + $this->Log('Produktexport Daten', print_r($csv,true)); + + $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); + + $response = $this->miraklRequest('products/imports', postdata: $postdata, content_type: 'multipart/form-data', raw: true); + + $result = json_decode($response); + + if (!isset($result->import_id)) { + $this->Log('Produktimport abgelehnt', print_r($response,true)); + $mirakl_create_products_return_value['returncode'] = 1; + return($mirakl_create_products_return_value); + } + + $this->Log('Produktimport angelegt', print_r($result,true)); + + $import_id = $result->import_id; + + // Wait for import to finish + + $status = null; + + /* + WAITING_SYNCHRONIZATION_PRODUCT, WAITING, RUNNING, COMPLETE, FAILED + */ + + while ($status != 'COMPLETE' && $status != 'FAILED') { + sleep(5); + $response = $this->miraklRequest('products/imports/'.$import_id, raw: true); + $result = json_decode($response); + $status = $result->import_status; + } + + if ($status == 'FAILED') { + $this->Log('Produktimport fehlgeschlagen', print_r($response,true)); + $mirakl_create_products_return_value['returncode'] = 1; + return($mirakl_create_products_return_value); + } + + if (!$result->has_error_report && !$result->has_transformation_error_report) { + $this->Log('Produktimport ok', print_r($response,true)); + } else { + $this->Log('Produktimport meldet Fehler', print_r($response,true)); + $mirakl_create_products_return_value['returncode'] = 1; + } + + if ($result->has_new_product_report) { + $response = $this->miraklRequest('products/imports/'.$import_id.'/new_product_report', raw: true); + $this->Log('Produktimport "Hinzugefügte Produkte"-Bericht', print_r($response,true)); + } + + if ($result->has_transformed_file) { + $response = $this->miraklRequest('products/imports/'.$import_id.'/transformed_file', raw: true); + $this->Log('Produktimport Datei im Marketplace-Format', print_r($response,true)); + } + + if ($result->has_error_report) { + // Check errors with CSV unfucking... + $response = $this->miraklRequest('products/imports/'.$import_id.'/error_report', raw: true); + $response_lines = preg_split('/\R/', $response, flags: PREG_SPLIT_NO_EMPTY); + $error_message_key = null; + $firstline = true; + foreach ($response_lines as $key => $response_line) { + $response_array = str_getcsv($response_line,';','"'); + if ($firstline) { + $error_message_key = array_search("ERRORS",$response_array); + $firstline = false; + continue; + } + $article_key = array_search( + $response_array['product_id'], + array_column( + $mirakl_create_products_return_value['articleList'], + 'product_id') + ); + + $mirakl_create_products_return_value['articleList'][$article_key]['mirakl_create_products_result'] = array('returncode' => 13, 'message' => $response_array[$error_message_key]); + } + $this->Log('Produktimport Fehlerbericht', print_r($response,true)); + } + + if ($result->has_transformation_error_report) { + // Check errors with CSV unfucking... + $response = $this->miraklRequest('products/imports/'.$import_id.'/transformation_error_report', raw: true); + $response_lines = preg_split('/\R/', $response, flags: PREG_SPLIT_NO_EMPTY); + $error_message_key = null; + $firstline = true; + foreach ($response_lines as $key => $response_line) { + $response_array = str_getcsv($response_line,';','"'); + if ($firstline) { + $error_message_key = array_search("errors",$response_array); + $firstline = false; + continue; + } + $article_key = array_search( + $response_array['product_id'], + array_column( + $mirakl_create_products_return_value['articleList'], + 'product_id') + ); + + $mirakl_create_products_return_value['articleList'][$article_key]['mirakl_create_products_result'] = array('returncode' => 14, 'message' => $response_array[$error_message_key]); + } + $this->Log('Produktimport Transformation-Fehlerbericht', print_r($response,true)); + } + + return($mirakl_create_products_return_value); + } + } From 9b3950e3aa6aa70b4f7ba1e2ec925392fa9b51d0 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 18 Jun 2024 15:18:45 +0200 Subject: [PATCH 18/52] shopimport ajax submit vs. submit --- www/widgets/templates/_gen/shopexport.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/widgets/templates/_gen/shopexport.tpl b/www/widgets/templates/_gen/shopexport.tpl index fab71180..782b78e2 100644 --- a/www/widgets/templates/_gen/shopexport.tpl +++ b/www/widgets/templates/_gen/shopexport.tpl @@ -115,7 +115,7 @@
{|Aktion|} - + [AKTIONBUTTONS]
From 471bceb06010d1d4f74ab1726d53df3eb22319d4 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 18 Jun 2024 15:19:19 +0200 Subject: [PATCH 19/52] mirakl fetch orders --- www/pages/shopimporter_mirakl.php | 156 ++++++++++++++++++++++++++---- 1 file changed, 137 insertions(+), 19 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 08ecd777..07650835 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -16,8 +16,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $apiKey; private $shopUrl; private $mirakl_shopid; - private $createManufacturerAllowed = false; - private $idsabholen; private $idbearbeitung; private $idabgeschlossen; public $data; @@ -31,6 +29,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $create_products; private $mirakl_error_text_product_missing; + private $normalTaxId; + private $reducedTaxId; + private $offer_field_map; private $product_field_map; @@ -98,6 +99,16 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'info' => 'Der Fehlertext der anzeigt dass das Produkt nicht existiert (Angebotsimport, Fehlerbericht)', 'default' => 'The product does not exist' ], + 'normalTaxId' => [ + 'typ' => 'text', + 'bezeichnung' => '{|TaxId für Steuersatz "normal"|}', + 'size' => 40, + ], + 'reducedTaxId' => [ + 'typ' => 'text', + 'bezeichnung' => '{|TaxId für Steuersatz "ermäßigt"|}', + 'size' => 40, + ], 'product_field_map' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', @@ -175,21 +186,15 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->apiKey = $einstellungen['felder']['apikey']; $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; $this->mirakl_shopid = $einstellungen['felder']['mirakl_shopid']; - - if ($einstellungen['felder']['autoerstellehersteller'] === '1') { - $this->createManufacturerAllowed = true; - } - $this->idsabholen = $einstellungen['felder']['abholen']; - $this->idbearbeitung = $einstellungen['felder']['bearbeitung']; - $this->idabgeschlossen = $einstellungen['felder']['abgeschlossen']; - $query = sprintf('SELECT `steuerfreilieferlandexport` FROM `shopexport` WHERE `id` = %d', $this->shopid); - $this->taxationByDestinationCountry = !empty($this->app->DB->Select($query)); - + $this->category_identifier = array($einstellungen['felder']['category_identifier_source'] => $einstellungen['felder']['category_identifier_source_value']); $this->create_products = $einstellungen['felder']['create_products']; $this->mirakl_error_text_product_missing = $einstellungen['felder']['mirakl_error_text_product_missing']; + $this->normalTaxId = $einstellungen['felder']['normalTaxId']; + $this->reducedTaxId = $einstellungen['felder']['reducedTaxId']; + $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true, flags: JSON_THROW_ON_ERROR); @@ -245,7 +250,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { print_r($information); print_r($postdata); print_r($response); - exit(); } if ($raw) @@ -261,7 +265,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($code == 200) { - return 'success ' . print_r($response, true); + return 'success'; } return $response; } @@ -389,7 +393,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { } private function getOrdersToProcess(int $limit) { - + echo("getOrdersToProcess"); + exit(); } private function Log($message, $dump = '') { @@ -399,19 +404,132 @@ class Shopimporter_Mirakl extends ShopimporterBase { } public function ImportDeleteAuftrag() { - + echo("ImportDeleteAuftrag"); + exit(); } public function ImportUpdateAuftrag() { - + echo("ImportUpdateAuftrag"); + exit(); } - public function ImportGetAuftraegeAnzahl() { - + // STAGING, WAITING_ACCEPTANCE, WAITING_DEBIT, WAITING_DEBIT_PAYMENT, SHIPPING, SHIPPED, TO_COLLECT, RECEIVED, CLOSED, REFUSED, CANCELED + public function ImportGetAuftraegeAnzahl() { + $response = $this->miraklRequest('orders', getdata: array('order_state_codes' => 'WAITING_ACCEPTANCE'), raw: true); + $this->Log('ImportGetAuftraegeAnzahl', print_r($response,true)); + $result_array = json_decode($response); + return($result_array->total_count); } public function ImportGetAuftrag() { + + $parameters = array('order_state_codes' => 'WAITING_ACCEPTANCE'); + + if(!empty($this->data['nummer'])) { + $parameters['order_ids'] = $this->data['nummer']; + } + + $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); + $this->Log('ImportGetAuftraegeAnzahl', print_r($response,true)); + $result_array = json_decode($response); + + $fetchedOrders = []; + foreach ($result_array->orders as $order) { + $cart = []; + $cart['zeitstempel'] = strval($order->created_date); + + $cart['auftrag'] = strval($order->order_id); + $cart['onlinebestellnummer'] = strval($order->commercial_id); + $cart['gesamtsumme'] = strval($order->total_price); + + $cart['bestelldatum'] = strval($order->created_date); + + $cart['lieferung'] = strval($order->shipping_type_code); + + $cart['email'] = strval($order->customer_notification_email); + + $cart['kunde_sprache'] = '?'; + $cart['kundennummer'] = $order->customer->customer_id; + + $cart['name'] = ($order->customer->civility?$order->customer->civility." ":"").$order->customer->firstname." ".$order->customer->lastname; + if (!empty(strval($order->customer->company))) { + $cart['ansprechpartner'] = $cart['name']; + $cart['name'] = strval($order->customer->company); + } + $cart['strasse'] = strval($order->customer->billing_address->street_1); + $cart['adresszusatz'] = strval($order->customer->billing_address->street_2); + $cart['telefon'] = strval($order->customer->billing_address->phone); + $cart['plz'] = strval($order->customer->billing_address->zip_code); + $cart['ort'] = strval($order->customer->billing_address->city); + + $cart['ustid'] = '?'; + $cart['land'] = strval($order->customer->billing_address->country_iso_code); + + $cart['abweichendelieferadresse'] = 1; + $cart['lieferadresse_name'] = ($order->customer->shipping_address->civility?$order->customer->shipping_address->civility." ":"").$order->customer->shipping_address->firstname." ".$order->customer->shipping_address->lastname; + if (!empty(strval($order->customer->shipping_address->company))) { + $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; + $cart['lieferadresse_name'] = strval($deliveryAddress->company); + } + $cart['lieferadresse_strasse'] = strval($order->customer->shipping_address->street_1); + $cart['lieferadresse_adresszusatz'] = strval($order->customer->shipping_address->street_2); + $cart['lieferadresse_telefon'] = strval($order->customer->shipping_address->phone); + $cart['lieferadresse_plz'] = strval($order->customer->shipping_address->zip_code); + $cart['lieferadresse_ort'] = strval($order->customer->shipping_address->city); + + $cart['zahlungsweise'] = strval($order->payment_type); + + $cart['ust_befreit'] = '?'; // 1, 2 + + $cart['steuersatz_normal'] = '?';//strval($order->taxes[0]->amount); + $cart['steuersatz_ermaessigt'] = '?'; // strval($order->taxes[0]->amount); + + $cart['articlelist'] = []; + + $shipping_tax_amount = 0; + + foreach ($order->order_lines as $order_row) { + + $steuersatz = '?'; + + switch ($order->row->taxes[0]->code) { + case $this->normalTaxId: + $steuersatz = 'normal'; + break; + case $this->reducedTaxId: + $steuersatz = 'ermaessigt'; + break; + } + + $article = [ + 'articleid' => strval($order_row->offer_sku), + 'name' => strval($order_row->product_title), + 'quantity' => strval($order_row->quantity), + 'price_netto' => strval($order_row->price_unit), + 'steuersatz' => $steuersatz + ]; + + foreach ($order_row->shipping_taxes as $shipment_tax) { + $shipping_tax_amount += $shipment_tax->amount; + } + $cart['articlelist'][] = $article; + } // foreach articles + + $cart['versandkostennetto'] = strval($order->shipping_price); + $cart['versandkostenbrutto'] = $cart['versandkostennetto']+$shipping_tax_amount; + + } // foreach orders + + $fetchedOrders[] = [ + 'id' => $cart['auftrag'], + 'sessionid' => $cart['onlinebestellnummer'], + 'logdatei' => '', + 'warenkorb' => base64_encode(serialize($cart)), + 'warenkorbjson' => base64_encode(json_encode($cart)) + ]; + $this->Log('Auftragsimport', $cart); + return $fetchedOrders; } /* From 15c36925a22b1176cbe9e1258bd6c18c48018d23 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 19 Jun 2024 21:31:40 +0200 Subject: [PATCH 20/52] shopimport preview table --- www/pages/shopimport.php | 19 +++++++++++------- www/themes/new/images/lupe.svg | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 www/themes/new/images/lupe.svg diff --git a/www/pages/shopimport.php b/www/pages/shopimport.php index 0a1112d1..171e0112 100644 --- a/www/pages/shopimport.php +++ b/www/pages/shopimport.php @@ -52,6 +52,7 @@ class Shopimport $this->app->ActionHandler("list","ShopimportList"); $this->app->ActionHandler("alle","ShopimportAlle"); $this->app->ActionHandler("import","ShopimportImport"); + $this->app->ActionHandler("view","ShopimportView"); $this->app->ActionHandler("einzelimport","ShopimportEinzelimport"); $this->app->ActionHandler("navigation","ShopimportNavigation"); $this->app->ActionHandler("logout","ShopimportLogout"); @@ -339,9 +340,9 @@ class Shopimport $this->app->Tpl->Set('TAB1','
Es läuft gerade ein Cronjob der Aufträge abholt. Die manuelle Auftragsabholung ist in dieser Zeit gesperrt. Bitte warten Sie ein paar Minuten und versuchen Sie es erneut.
'); }else{ $table = new EasyTable($this->app); - $table->Query("SELECT ae.bezeichnung,p.abkuerzung, + $table->Query("SELECT ae.bezeichnung,p.abkuerzung as Projekt, ae.id FROM shopexport ae LEFT JOIN projekt p ON p.id=ae.projekt WHERE ae.aktiv='1'"); - $table->DisplayNew('INHALT',"  "); + $table->DisplayNew('INHALT',"   "); $this->app->Tpl->Parse('TAB1','rahmen.tpl'); } $this->app->Tpl->Set('INHALT',''); @@ -949,6 +950,10 @@ class Shopimport $bekanntezahlungsweisen = $this->app->erp->GetZahlungsweise(); $tmpauftragid = $this->app->erp->ImportAuftrag($adresse,$warenkorb,$projekt,$shopid); + if ($tmpauftragid > 0) { + $sucess_import = true; + } + $doctype = 'auftrag'; if($this->app->DB->Select("SELECT angeboteanlegen FROM shopexport WHERE id = '$shopid' LIMIT 1")) { @@ -971,7 +976,7 @@ class Shopimport } } - if($shopimportid) + if($shopimportid && $tmpauftragid) { $this->app->DB->Update("UPDATE shopimport_auftraege SET imported='1' WHERE id='$shopimportid' LIMIT 1"); } @@ -985,10 +990,7 @@ class Shopimport } $this->app->erp->RunHook('Shopimportwarenkorb', 4, $doctype, $tmpauftragid, $shopid, $warenkorb); $this->app->erp->RunHook('Shopimport', 3, $doctype, $tmpauftragid, $shopid); - - $adresse =''; - $sucess_import++; return $sucess_import; } @@ -1112,6 +1114,10 @@ class Shopimport return ['codingerror'=>$umlautefehler, 'success' => $succes]; } + public function ShopimportView() { + $this->ShopimportImport(showonly: true); + } + public function ShopimportImport($id='', $count = 0, $returncount = false, $showonly = false) { $deletedRows = 0; @@ -2002,7 +2008,6 @@ class Shopimport $htmltable->AddCol(''); $htmltable->AddCol($arr[$i]['abkuerzung']); - $htmltable->AddCol(($doppelteonlinebestellnummer?'':'').$warenkorb['onlinebestellnummer'].($doppelteonlinebestellnummer?'':'')); $htmltable->AddCol($warenkorb['name'].$kdr_name.'
'.$warenkorb['email'].$email); $htmltable->AddCol($warenkorb['internebezeichnung']); diff --git a/www/themes/new/images/lupe.svg b/www/themes/new/images/lupe.svg new file mode 100644 index 00000000..ef5adf6b --- /dev/null +++ b/www/themes/new/images/lupe.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 4b7f3e19e7ef804cf719ebb1aaa5bbc00e592753 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 19 Jun 2024 21:33:05 +0200 Subject: [PATCH 21/52] erpapi ImportAuftrag abort with logfile if porto is not defined --- www/lib/class.erpapi.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index b855b0f3..ab84107f 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -18809,16 +18809,23 @@ function CheckShopTabelle($artikel) $artikelporto = $artikelportoermaessigt; } - if(empty($artikelporto) && $this->app->DB->Select("SELECT portoartikelanlegen FROM shopexport WHERE id = '$shop' LIMIT 1")) - { - if($warenkorb['versandkostennetto'] != 0 || $warenkorb['versandkostenbrutto'] != 0 || $portocheck == 1){ - $portoartikelarr = array('projekt'=>$projekt,'porto'=>1, 'lagerartikel'=>0,'name_de'=>'Porto','umsatzsteuer'=>'normal'); - $artikelporto = $this->app->erp->InsertUpdateArtikel($portoartikelarr); - if($artikelporto){ - $this->app->DB->Update("UPDATE shopexport SET artikelporto = '$artikelporto' WHERE id = '$shop' AND artikelporto = 0 LIMIT 1"); - } + if(empty($artikelporto)) { + if ($this->app->DB->Select("SELECT portoartikelanlegen FROM shopexport WHERE id = '$shop' LIMIT 1")) + { + if($warenkorb['versandkostennetto'] != 0 || $warenkorb['versandkostenbrutto'] != 0 || $portocheck == 1) + { + $portoartikelarr = array('projekt'=>$projekt,'porto'=>1, 'lagerartikel'=>0,'name_de'=>'Porto','umsatzsteuer'=>'normal'); + $artikelporto = $this->app->erp->InsertUpdateArtikel($portoartikelarr); + if($artikelporto) + { + $this->app->DB->Update("UPDATE shopexport SET artikelporto = '$artikelporto' WHERE id = '$shop' AND artikelporto = 0 LIMIT 1"); + } + } + } else { + $this->LogFile('Importauftrag Shop '.$shop.' Fehler: Kein Portoartikel vorhanden',['Onlinebestellnummer' => $warenkorb['onlinebestellnummer']]); + return(null); + } } - } $umsatzsteuer_porto = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$artikelporto' LIMIT 1"); $versandname = ''; From 04daacb227e7e98a254c2d796096b10360851c09 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 19 Jun 2024 21:33:49 +0200 Subject: [PATCH 22/52] mirakl importauftrag steuer, iso3 country code --- www/pages/shopimporter_mirakl.php | 56 +++++++++++++++++++------------ 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 07650835..6fbb810e 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -430,7 +430,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); - $this->Log('ImportGetAuftraegeAnzahl', print_r($response,true)); + $this->Log('ImportGetAuftrag', print_r($response,true)); $result_array = json_decode($response); $fetchedOrders = []; @@ -448,7 +448,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['email'] = strval($order->customer_notification_email); - $cart['kunde_sprache'] = '?'; +// $cart['kunde_sprache'] = '?'; $cart['kundennummer'] = $order->customer->customer_id; $cart['name'] = ($order->customer->civility?$order->customer->civility." ":"").$order->customer->firstname." ".$order->customer->lastname; @@ -462,10 +462,15 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['plz'] = strval($order->customer->billing_address->zip_code); $cart['ort'] = strval($order->customer->billing_address->city); - $cart['ustid'] = '?'; - $cart['land'] = strval($order->customer->billing_address->country_iso_code); +// $cart['ustid'] = '?'; + $sql = "SELECT iso FROM laender WHERE iso3 = '".$order->customer->billing_address->country_iso_code."'"; + $cart['land'] = $this->app->DB->Select($sql); $cart['abweichendelieferadresse'] = 1; + + $sql = "SELECT iso FROM laender WHERE iso3 = '".$order->customer->shipping_address->country_iso_code."'"; + $cart['lieferadresse_land'] = $this->app->DB->Select($sql); + $cart['lieferadresse_name'] = ($order->customer->shipping_address->civility?$order->customer->shipping_address->civility." ":"").$order->customer->shipping_address->firstname." ".$order->customer->shipping_address->lastname; if (!empty(strval($order->customer->shipping_address->company))) { $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; @@ -479,34 +484,43 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['zahlungsweise'] = strval($order->payment_type); - $cart['ust_befreit'] = '?'; // 1, 2 + $cart['waehrung'] = strval($order->currency_iso_code); - $cart['steuersatz_normal'] = '?';//strval($order->taxes[0]->amount); - $cart['steuersatz_ermaessigt'] = '?'; // strval($order->taxes[0]->amount); +// $cart['ust_befreit'] = '?'; // 1, 2 - $cart['articlelist'] = []; +// $cart['steuersatz_normal'] = 19;//strval($order->taxes[0]->amount); +// $cart['steuersatz_ermaessigt'] 07; // strval($order->taxes[0]->amount); + + $cart['articlelist'] = []; + $shipping_tax_amount = 0; foreach ($order->order_lines as $order_row) { - $steuersatz = '?'; - - switch ($order->row->taxes[0]->code) { - case $this->normalTaxId: - $steuersatz = 'normal'; - break; - case $this->reducedTaxId: - $steuersatz = 'ermaessigt'; - break; + $steuersatz = 0; + $umsatzsteuer_typ = 'normal'; + foreach($order_row->taxes as $tax) { + if($tax->rate > $steuersatz) { + $steuersatz = $tax->rate; + } + switch ($order->row->taxes[0]->code) { + case $this->reducedTaxId: + $umsatzsteuer_typ = 'ermaessigt'; + break; + default: + case $this->normalTaxId: + $umsatzsteuer_typ = 'normal'; + break; + } } $article = [ 'articleid' => strval($order_row->offer_sku), - 'name' => strval($order_row->product_title), +// 'name' => strval($order_row->product_title), 'quantity' => strval($order_row->quantity), 'price_netto' => strval($order_row->price_unit), - 'steuersatz' => $steuersatz + 'umsatzsteuer' => $steuersatz ]; foreach ($order_row->shipping_taxes as $shipment_tax) { @@ -515,8 +529,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['articlelist'][] = $article; } // foreach articles - $cart['versandkostennetto'] = strval($order->shipping_price); - $cart['versandkostenbrutto'] = $cart['versandkostennetto']+$shipping_tax_amount; + $cart['versandkostennetto'] = round(strval($order->shipping_price),2); + $cart['versandkostenbrutto'] = round($cart['versandkostennetto']+$shipping_tax_amount,2); } // foreach orders From 610ed35218c424e3f56e1f7492354c30c5bee24a Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 20 Jun 2024 14:18:20 +0200 Subject: [PATCH 23/52] shopimport improvements --- www/lib/class.erpapi.php | 9 +- www/pages/shopimport.php | 3623 ++++++++++++++--------------- www/pages/shopimporter_mirakl.php | 9 +- 3 files changed, 1713 insertions(+), 1928 deletions(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index ab84107f..a3a5128c 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -17334,7 +17334,7 @@ function CheckShopTabelle($artikel) return $taxrates; } - function ImportAuftrag($adresse,$warenkorb,$projekt,$shop="",$auftrag=0) + function ImportAuftrag($adresse,$warenkorb,$projekt,$shop="",$auftrag=0) : array { $this->RunHook('ImportAuftragBefore',4, $adresse,$warenkorb,$projekt,$shop); if(!empty($this->app->stringcleaner)){ @@ -18822,8 +18822,9 @@ function CheckShopTabelle($artikel) } } } else { - $this->LogFile('Importauftrag Shop '.$shop.' Fehler: Kein Portoartikel vorhanden',['Onlinebestellnummer' => $warenkorb['onlinebestellnummer']]); - return(null); + $error_msg = 'Importauftrag Shop '.$shop.' Fehler: Kein Portoartikel vorhanden'; + $this->LogFile($error_msg,['Onlinebestellnummer' => $warenkorb['onlinebestellnummer']]); + return(array("status" => false, "message" => $error_msg, "onlinebestellnummer" => $warenkorb['onlinebestellnummer'])); } } $umsatzsteuer_porto = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$artikelporto' LIMIT 1"); @@ -19171,7 +19172,7 @@ function CheckShopTabelle($artikel) } } - return $auftrag; + return array("status" => true, "$auftragid" => $auftrag); } diff --git a/www/pages/shopimport.php b/www/pages/shopimport.php index 171e0112..30b681b1 100644 --- a/www/pages/shopimport.php +++ b/www/pages/shopimport.php @@ -1,4 +1,5 @@ app=$app; - if($intern) { - return; - } - $this->app->ActionHandlerInit($this); + const MODULE_NAME = 'Shopimport'; - $this->app->ActionHandler("login","ShopimportLogin"); - $this->app->ActionHandler("main","ShopimportMain"); - $this->app->ActionHandler("list","ShopimportList"); - $this->app->ActionHandler("alle","ShopimportAlle"); - $this->app->ActionHandler("import","ShopimportImport"); - $this->app->ActionHandler("view","ShopimportView"); - $this->app->ActionHandler("einzelimport","ShopimportEinzelimport"); - $this->app->ActionHandler("navigation","ShopimportNavigation"); - $this->app->ActionHandler("logout","ShopimportLogout"); - $this->app->ActionHandler("archiv","ShopimportArchiv"); + public $javascript = [ + './classes/Modules/Shopimport/www/js/shopimport.js' + ]; - $this->app->DefaultActionHandler("list"); + /** + * Shopimport constructor. + * + * @param Application $app + * @param bool $intern + */ + public function __construct($app, $intern = false) { + $this->app = $app; + if ($intern) { + return; + } + $this->app->ActionHandlerInit($this); + $this->app->ActionHandler("login", "ShopimportLogin"); + $this->app->ActionHandler("main", "ShopimportMain"); + $this->app->ActionHandler("list", "ShopimportList"); + $this->app->ActionHandler("alle", "ShopimportAlle"); + $this->app->ActionHandler("import", "ShopimportImport"); + $this->app->ActionHandler("view", "ShopimportView"); + $this->app->ActionHandler("einzelimport", "ShopimportEinzelimport"); + $this->app->ActionHandler("navigation", "ShopimportNavigation"); + $this->app->ActionHandler("logout", "ShopimportLogout"); + $this->app->ActionHandler("archiv", "ShopimportArchiv"); - $this->app->Tpl->Set('UEBERSCHRIFT','Shop Import'); - $this->app->ActionHandlerListen($app); - } + $this->app->DefaultActionHandler("list"); - /** - * @param int $shopId - * @param array $data - * - * @return int - * - * @throws Exception - */ - public function Refund($shopId, $data) - { - if(empty($shopId)) { - throw new Exception('no Shop given'); - } - if(empty($data)) { - throw new Exception('no Data given'); + $this->app->Tpl->Set('UEBERSCHRIFT', 'Shop Import'); + $this->app->ActionHandlerListen($app); } - $shop = $this->app->DB->SelectRow( - sprintf( - 'SELECT `aktiv`, `id`, `artikelrabatt` FROM `shopexport` WHERE `id` = %d', - $shopId - ) - ); - if(empty($shop)) { - throw new Exception('Shop not found'); - } - if(empty($shop['aktiv'])) { - throw new Exception('Shop is not active'); - } + /** + * @param int $shopId + * @param array $data + * + * @return int + * + * @throws Exception + */ + public function Refund($shopId, $data) { + if (empty($shopId)) { + throw new Exception('no Shop given'); + } + if (empty($data)) { + throw new Exception('no Data given'); + } - if(!empty($data->extid)) { - $order = $this->app->DB->SelectRow( - sprintf( - "SELECT * + $shop = $this->app->DB->SelectRow( + sprintf( + 'SELECT `aktiv`, `id`, `artikelrabatt` FROM `shopexport` WHERE `id` = %d', + $shopId + ) + ); + if (empty($shop)) { + throw new Exception('Shop not found'); + } + if (empty($shop['aktiv'])) { + throw new Exception('Shop is not active'); + } + + if (!empty($data->extid)) { + $order = $this->app->DB->SelectRow( + sprintf( + "SELECT * FROM `auftrag` WHERE `shop` = %d AND `shopextid` = '%s' AND `shopextid` <> '' AND `status` <> 'storniert' LIMIT 1", - $shopId, $this->app->DB->real_escape_string((string)$data->extid) - ) - ); - } - elseif(!empty($data->internet)) { - $order = $this->app->DB->SelectRow( - sprintf( - "SELECT * + $shopId, $this->app->DB->real_escape_string((string) $data->extid) + ) + ); + } elseif (!empty($data->internet)) { + $order = $this->app->DB->SelectRow( + sprintf( + "SELECT * FROM `auftrag` WHERE `shop` = %d AND `internet` = '%s' AND `internet` <> '' AND `status` <> 'storniert' LIMIT 1", - $shopId, $this->app->DB->real_escape_string((string)$data->extid) - ) - ); - } - else { - throw new Exception('No order given'); - } + $shopId, $this->app->DB->real_escape_string((string) $data->extid) + ) + ); + } else { + throw new Exception('No order given'); + } - if(empty($order)) { - throw new Exception('order not found'); - } + if (empty($order)) { + throw new Exception('order not found'); + } - $invoice = $this->app->DB->SelectRow( - sprintf( - "SELECT * FROM `rechnung` WHERE `auftragid` = %d ORDER BY `status` = 'storniert' LIMIT 1", - $order['id'] - ) - ); + $invoice = $this->app->DB->SelectRow( + sprintf( + "SELECT * FROM `rechnung` WHERE `auftragid` = %d ORDER BY `status` = 'storniert' LIMIT 1", + $order['id'] + ) + ); - if(empty($invoice)) { - if(empty($data->createinvoice)){ - throw new Exception('order has no invoice'); - } - $invoiceId = $this->app->erp->WeiterfuehrenAuftragZuRechnung($order['id']); - $this->app->erp->AuftragProtokoll($order['id'], 'Rechnung erstellt durch Shop-Trigger'); - $this->app->erp->RechnungProtokoll($invoiceId, 'Rechnung erstellt durch Shop-Trigger'); - $this->app->erp->BelegFreigabe('rechnung', $invoiceId); - $this->app->erp->RechnungNeuberechnen($invoiceId); - $invoice = $this->app->DB->SelectRow( - sprintf( - "SELECT * FROM `rechnung` WHERE `auftragid` = %d ORDER BY `status` = 'storniert' LIMIT 1", - $order['id'] - ) - ); - } + if (empty($invoice)) { + if (empty($data->createinvoice)) { + throw new Exception('order has no invoice'); + } + $invoiceId = $this->app->erp->WeiterfuehrenAuftragZuRechnung($order['id']); + $this->app->erp->AuftragProtokoll($order['id'], 'Rechnung erstellt durch Shop-Trigger'); + $this->app->erp->RechnungProtokoll($invoiceId, 'Rechnung erstellt durch Shop-Trigger'); + $this->app->erp->BelegFreigabe('rechnung', $invoiceId); + $this->app->erp->RechnungNeuberechnen($invoiceId); + $invoice = $this->app->DB->SelectRow( + sprintf( + "SELECT * FROM `rechnung` WHERE `auftragid` = %d ORDER BY `status` = 'storniert' LIMIT 1", + $order['id'] + ) + ); + } - if($invoice['status'] === 'storniert') { - throw new Exception('order invoice is already cancelled'); - } - if(!empty($data->positions)) { - $positions = $this->app->DB->SelectArr( - sprintf( - "SELECT `op`.webid, ip.artikel, ip.menge,ip.preis, ip.rabatt, ip.auftrag_position_id + if ($invoice['status'] === 'storniert') { + throw new Exception('order invoice is already cancelled'); + } + if (!empty($data->positions)) { + $positions = $this->app->DB->SelectArr( + sprintf( + "SELECT `op`.webid, ip.artikel, ip.menge,ip.preis, ip.rabatt, ip.auftrag_position_id FROM `rechnung_position` AS `ip` INNER JOIN `auftrag_position` AS `op` ON ip.auftrag_position_id = op.id WHERE `ip`.rechnung = %d", - $invoice['id'] - ) - ); - if(empty($positions)) { - throw new Exception('invoice has no positions'); - } - $webIds = []; - $foundWebIds = []; - foreach($positions as $position) { - if(!empty($position['webid'])) { - $webIds[] = $position['webid']; - } - } + $invoice['id'] + ) + ); + if (empty($positions)) { + throw new Exception('invoice has no positions'); + } + $webIds = []; + $foundWebIds = []; + foreach ($positions as $position) { + if (!empty($position['webid'])) { + $webIds[] = $position['webid']; + } + } - $webIdToPosition = []; + $webIdToPosition = []; - foreach($data->positions as $position) { - if(!empty($position->webid)){ - if(!in_array((string)$position->webid, $webIds)){ - throw new Exception(sprintf('position %s not found', (string)$position->webid)); - } - $foundWebIds[] = (string)$position->webid; - $webIdToPosition[$position->webid] = $position; - } - else { - throw new Exception('no webId given'); - } - } + foreach ($data->positions as $position) { + if (!empty($position->webid)) { + if (!in_array((string) $position->webid, $webIds)) { + throw new Exception(sprintf('position %s not found', (string) $position->webid)); + } + $foundWebIds[] = (string) $position->webid; + $webIdToPosition[$position->webid] = $position; + } else { + throw new Exception('no webId given'); + } + } - if(empty($foundWebIds)) { - throw new Exception('positions empty'); - } + if (empty($foundWebIds)) { + throw new Exception('positions empty'); + } - $toDeleteInvoicePositionIds = [0]; - foreach($positions as $position) { - if(empty($position['webid']) || !in_array($position['webid'], $foundWebIds)) { - $toDeleteInvoicePositionIds[] = (int)$position['auftrag_position_id']; - } - } + $toDeleteInvoicePositionIds = [0]; + foreach ($positions as $position) { + if (empty($position['webid']) || !in_array($position['webid'], $foundWebIds)) { + $toDeleteInvoicePositionIds[] = (int) $position['auftrag_position_id']; + } + } - $creditNoteId = $this->app->erp->WeiterfuehrenRechnungZuGutschrift($invoice['id']); - $this->app->erp->RechnungProtokoll($invoice['id'], 'Rechnung durch Shop-Trigger storniert'); - $this->app->erp->GutschriftProtokoll($creditNoteId, 'Gutschrift durch Shop-Trigger angelegt'); - $this->app->erp->BelegFreigabe('gutschrift', $creditNoteId); - $this->app->DB->Delete( - sprintf( - "DELETE FROM `gutschrift_position` WHERE `gutschrift` = %d AND `auftrag_position_id` IN (%s)", - $creditNoteId, implode(',', $toDeleteInvoicePositionIds) - ) - ); - $hasCreditNoteTax = !empty($this->app->erp->GutschriftMitUmsatzeuer($creditNoteId)); - $this->app->erp->GutschriftNeuberechnen($creditNoteId); - $creditNote = $this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM `gutschrift` WHERE `id` = %d', - $creditNoteId - ) - ); - $creditNotePositions = $this->app->DB->SelectArr( - sprintf( - "SELECT op.webid, cnp.id, cnp.menge, cnp.preis, cnp.rabatt, cnp.umsatzsteuer, + $creditNoteId = $this->app->erp->WeiterfuehrenRechnungZuGutschrift($invoice['id']); + $this->app->erp->RechnungProtokoll($invoice['id'], 'Rechnung durch Shop-Trigger storniert'); + $this->app->erp->GutschriftProtokoll($creditNoteId, 'Gutschrift durch Shop-Trigger angelegt'); + $this->app->erp->BelegFreigabe('gutschrift', $creditNoteId); + $this->app->DB->Delete( + sprintf( + "DELETE FROM `gutschrift_position` WHERE `gutschrift` = %d AND `auftrag_position_id` IN (%s)", + $creditNoteId, implode(',', $toDeleteInvoicePositionIds) + ) + ); + $hasCreditNoteTax = !empty($this->app->erp->GutschriftMitUmsatzeuer($creditNoteId)); + $this->app->erp->GutschriftNeuberechnen($creditNoteId); + $creditNote = $this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM `gutschrift` WHERE `id` = %d', + $creditNoteId + ) + ); + $creditNotePositions = $this->app->DB->SelectArr( + sprintf( + "SELECT op.webid, cnp.id, cnp.menge, cnp.preis, cnp.rabatt, cnp.umsatzsteuer, cnp.steuersatz FROM `gutschrift_position` AS `cnp` INNER JOIN `auftrag_position` AS `op` ON cnp.auftrag_position_id = op.id WHERE cnp.gutschrift = %d", - $creditNoteId - ) - ); - foreach($creditNotePositions as $creditNotePosition) { - if(isset($webIdToPosition[$creditNotePosition['webid']])) { - $position = $webIdToPosition[$creditNotePosition['webid']]; - if(!empty($position->quantity)) { - $this->app->DB->Update( - sprintf( - "UPDATE `gutschrift_position` SET `menge` = %f WHERE `id` = %d", - (float)$position->quantity, $creditNotePosition['id'] - ) + $creditNoteId + ) ); - } - elseif(!empty($position->menge)) { - $this->app->DB->Update( - sprintf( - "UPDATE `gutschrift_position` SET `menge` = %f WHERE `id` = %d", - (float)$position->menge, $creditNotePosition['id'] - ) - ); - } - $preis = null; - if(isset($position->price)) { - $preis = (float)$position->price; - } - elseif(isset($position->preis)) { - $preis = (float)$position->preis; - } - elseif(isset($position->amount)) { - $preis = (float)$position->amount; - } - if($preis !== null) { - if($hasCreditNoteTax) { - if($creditNotePosition['steuersatz'] !== null && $creditNotePosition['steuersatz'] >= 0) { - $preis /= 1+ $creditNotePosition['steuersatz'] / 100; - } - elseif($creditNotePosition['umsatzsteuer'] === 'ermaessigt') { - $preis /= 1+ $creditNote['steuersatz_ermaessigt'] / 100; - } - elseif($creditNotePosition['umsatzsteuer'] !== 'befreit') { - $preis /= 1+ $creditNote['steuersatz_normal'] / 100; - } + foreach ($creditNotePositions as $creditNotePosition) { + if (isset($webIdToPosition[$creditNotePosition['webid']])) { + $position = $webIdToPosition[$creditNotePosition['webid']]; + if (!empty($position->quantity)) { + $this->app->DB->Update( + sprintf( + "UPDATE `gutschrift_position` SET `menge` = %f WHERE `id` = %d", + (float) $position->quantity, $creditNotePosition['id'] + ) + ); + } elseif (!empty($position->menge)) { + $this->app->DB->Update( + sprintf( + "UPDATE `gutschrift_position` SET `menge` = %f WHERE `id` = %d", + (float) $position->menge, $creditNotePosition['id'] + ) + ); + } + $preis = null; + if (isset($position->price)) { + $preis = (float) $position->price; + } elseif (isset($position->preis)) { + $preis = (float) $position->preis; + } elseif (isset($position->amount)) { + $preis = (float) $position->amount; + } + if ($preis !== null) { + if ($hasCreditNoteTax) { + if ($creditNotePosition['steuersatz'] !== null && $creditNotePosition['steuersatz'] >= 0) { + $preis /= 1 + $creditNotePosition['steuersatz'] / 100; + } elseif ($creditNotePosition['umsatzsteuer'] === 'ermaessigt') { + $preis /= 1 + $creditNote['steuersatz_ermaessigt'] / 100; + } elseif ($creditNotePosition['umsatzsteuer'] !== 'befreit') { + $preis /= 1 + $creditNote['steuersatz_normal'] / 100; + } + } + $this->app->DB->Update( + sprintf( + 'UPDATE `gutschrift_position` SET `preis` = %f, `rabatt` = 0 WHERE `id` = %d', + $preis, $creditNotePosition['id'] + ) + ); + } + } } - $this->app->DB->Update( - sprintf( - 'UPDATE `gutschrift_position` SET `preis` = %f, `rabatt` = 0 WHERE `id` = %d', - $preis, $creditNotePosition['id'] - ) + + $this->app->erp->GutschriftNeuberechnen($creditNoteId); + + if (!empty($data->amount)) { + $soll = $this->app->DB->Select(sprintf('SELECT `soll` FROM `gutschrift` WHERE `id` = %d', $creditNoteId)); + $diff = round($soll, 2) - round((float) $data->amount, 2); + if ($diff == 0) { + return $creditNoteId; + } + $this->app->erp->AddPositionManuellPreis( + 'gutschrift', $creditNoteId, $shop['artikelrabatt'], 1, 'Differenz', -$diff, 'befreit', $invoice['waehrung'] + ); + } + + return (int) $creditNoteId; + } + $creditNoteId = $this->app->erp->WeiterfuehrenRechnungZuGutschrift($invoice['id']); + $this->app->erp->RechnungProtokoll($invoice['id'], 'Rechnung durch Shop-Trigger storniert'); + $this->app->erp->GutschriftProtokoll($creditNoteId, 'Gutschrift durch Shop-Trigger angelegt'); + $this->app->erp->BelegFreigabe('gutschrift', $creditNoteId); + $this->app->erp->GutschriftNeuberechnen($creditNoteId); + if (!empty($data->amount)) { + $soll = $this->app->DB->Select(sprintf('SELECT `soll` FROM `gutschrift` WHERE `id` = %d', $creditNoteId)); + $diff = round($soll, 2) - round((float) $data->amount, 2); + if ($diff == 0) { + return $creditNoteId; + } + $this->app->erp->AddPositionManuellPreis( + 'gutschrift', $creditNoteId, $shop['artikelrabatt'], 1, 'Differenz', -$diff, 'befreit', $invoice['waehrung'] ); - } } - } - $this->app->erp->GutschriftNeuberechnen($creditNoteId); + return (int) $creditNoteId; + } - if(!empty($data->amount)) { - $soll = $this->app->DB->Select(sprintf('SELECT `soll` FROM `gutschrift` WHERE `id` = %d', $creditNoteId)); - $diff = round($soll,2) - round((float)$data->amount, 2); - if($diff == 0) { - return $creditNoteId; + public function ShopimportList() { + $msg = $this->app->Secure->GetGET('msg'); + if (!empty($msg)) { + $msg = $this->app->erp->base64_url_decode($msg); + $this->app->Tpl->Set('MESSAGE', $msg); } - $this->app->erp->AddPositionManuellPreis( - 'gutschrift', $creditNoteId, $shop['artikelrabatt'], 1, 'Differenz', -$diff,'befreit', $invoice['waehrung'] - ); - } + $this->app->erp->MenuEintrag('index.php?module=importvorlage&action=uebersicht', 'Zurück zur Übersicht'); - return (int)$creditNoteId; - } - $creditNoteId = $this->app->erp->WeiterfuehrenRechnungZuGutschrift($invoice['id']); - $this->app->erp->RechnungProtokoll($invoice['id'], 'Rechnung durch Shop-Trigger storniert'); - $this->app->erp->GutschriftProtokoll($creditNoteId, 'Gutschrift durch Shop-Trigger angelegt'); - $this->app->erp->BelegFreigabe('gutschrift', $creditNoteId); - $this->app->erp->GutschriftNeuberechnen($creditNoteId); - if(!empty($data->amount)) { - $soll = $this->app->DB->Select(sprintf('SELECT `soll` FROM `gutschrift` WHERE `id` = %d', $creditNoteId)); - $diff = round($soll,2) - round((float)$data->amount, 2); - if($diff == 0) { - return $creditNoteId; - } - $this->app->erp->AddPositionManuellPreis( - 'gutschrift', $creditNoteId, $shop['artikelrabatt'], 1, 'Differenz', -$diff,'befreit', $invoice['waehrung'] - ); - } + //$this->app->Tpl->Add(TABS,"
  • Shopimport

  • "); + $this->app->erp->Headlines('Shopimport'); + //$this->app->erp->MenuEintrag("index.php?module=shopimport&action=alle","Alle importieren"); + $this->app->erp->MenuEintrag('index.php?module=shopimport&action=list', 'Übersicht'); - return (int)$creditNoteId; - } - - public function ShopimportList() - { - $msg = $this->app->Secure->GetGET('msg'); - if(!empty($msg)) - { - $msg = $this->app->erp->base64_url_decode($msg); - $this->app->Tpl->Set('MESSAGE',$msg); - } - $this->app->erp->MenuEintrag('index.php?module=importvorlage&action=uebersicht','Zurück zur Übersicht'); - - //$this->app->Tpl->Add(TABS,"
  • Shopimport

  • "); - $this->app->erp->Headlines('Shopimport'); - //$this->app->erp->MenuEintrag("index.php?module=shopimport&action=alle","Alle importieren"); - $this->app->erp->MenuEintrag('index.php?module=shopimport&action=list','Übersicht'); - - if($this->app->erp->RechteVorhanden('shopimport','alle')){ - $this->app->Tpl->Add('INHALT', "


    "); - } - //$this->app->Tpl->Set('SUBHEADING',"Imports"); - //Jeder der in Nachbesserung war egal ob auto oder manuell wandert anschliessend in Manuelle-Freigabe"); - $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); - if($runningcronjob) - { - $this->app->Tpl->Set('TAB1','
    Es läuft gerade ein Cronjob der Aufträge abholt. Die manuelle Auftragsabholung ist in dieser Zeit gesperrt. Bitte warten Sie ein paar Minuten und versuchen Sie es erneut.
    '); - }else{ - $table = new EasyTable($this->app); - $table->Query("SELECT ae.bezeichnung,p.abkuerzung as Projekt, + if ($this->app->erp->RechteVorhanden('shopimport', 'alle')) { + $this->app->Tpl->Add('INHALT', "


    "); + } + //$this->app->Tpl->Set('SUBHEADING',"Imports"); + //Jeder der in Nachbesserung war egal ob auto oder manuell wandert anschliessend in Manuelle-Freigabe"); + $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); + if ($runningcronjob) { + $this->app->Tpl->Set('TAB1', '
    Es läuft gerade ein Cronjob der Aufträge abholt. Die manuelle Auftragsabholung ist in dieser Zeit gesperrt. Bitte warten Sie ein paar Minuten und versuchen Sie es erneut.
    '); + } else { + $table = new EasyTable($this->app); + $table->Query("SELECT ae.bezeichnung,p.abkuerzung as Projekt, ae.id FROM shopexport ae LEFT JOIN projekt p ON p.id=ae.projekt WHERE ae.aktiv='1'"); - $table->DisplayNew('INHALT',"   "); - $this->app->Tpl->Parse('TAB1','rahmen.tpl'); - } - $this->app->Tpl->Set('INHALT',''); + $table->DisplayNew('INHALT', "   "); + $this->app->Tpl->Parse('TAB1', 'rahmen.tpl'); + } + $this->app->Tpl->Set('INHALT', ''); - - // Archiv GESTERN - $table = new EasyTable($this->app); - $table->Query("SELECT a.datum, a.internet, a.transaktionsnummer,a.name, a.land, a.gesamtsumme as betrag, (SELECT SUM(r.soll) FROM rechnung r WHERE r.adresse=a.adresse AND r.status='offen') as mahnwesen, a.zahlungsweise, a.partnerid as Partner, a.id FROM auftrag a WHERE + // Archiv GESTERN + $table = new EasyTable($this->app); + $table->Query("SELECT a.datum, a.internet, a.transaktionsnummer,a.name, a.land, a.gesamtsumme as betrag, (SELECT SUM(r.soll) FROM rechnung r WHERE r.adresse=a.adresse AND r.status='offen') as mahnwesen, a.zahlungsweise, a.partnerid as Partner, a.id FROM auftrag a WHERE (datum=DATE_FORMAT( DATE_SUB( NOW() , INTERVAL 1 DAY ) , '%Y-%m-%d' ) OR (datum=DATE_FORMAT( NOW(), '%Y-%m-%d' ))) AND a.internet>0 ORDER by a.id DESC"); - $table->DisplayNew('INHALT',"app->Conf->WFconf['defaulttheme']."/images/edit.svg\"> - app->Conf->WFconf['defaulttheme']."/images/pdf.svg\">"); + $table->DisplayNew('INHALT', "app->Conf->WFconf['defaulttheme'] . "/images/edit.svg\"> + app->Conf->WFconf['defaulttheme'] . "/images/pdf.svg\">"); - $this->app->Tpl->Parse('TAB2','rahmen.tpl'); - $this->app->Tpl->Set('INHALT',''); + $this->app->Tpl->Parse('TAB2', 'rahmen.tpl'); + $this->app->Tpl->Set('INHALT', ''); - - $summe_heute = $this->app->DB->Select("SELECT SUM(a.gesamtsumme) FROM auftrag a WHERE + $summe_heute = $this->app->DB->Select("SELECT SUM(a.gesamtsumme) FROM auftrag a WHERE a.datum=DATE_FORMAT( NOW(), '%Y-%m-%d' ) AND a.internet>0 "); - $summe_gestern = $this->app->DB->Select("SELECT SUM(a.gesamtsumme) FROM auftrag a WHERE + $summe_gestern = $this->app->DB->Select("SELECT SUM(a.gesamtsumme) FROM auftrag a WHERE a.datum=DATE_FORMAT( DATE_SUB( NOW() , INTERVAL 1 DAY ) , '%Y-%m-%d' ) AND a.internet>0 "); - $this->app->Tpl->Add('TAB2',"
    Heute: $summe_heute EUR (inkl. Steuer und Versand) Umsatz aus den Online-Shop
    "); - $this->app->Tpl->Add('TAB2',"
    Gestern: $summe_gestern EUR (inkl. Steuer und Versand) Umsatz aus den Online-Shop
    "); + $this->app->Tpl->Add('TAB2', "
    Heute: $summe_heute EUR (inkl. Steuer und Versand) Umsatz aus den Online-Shop
    "); + $this->app->Tpl->Add('TAB2', "
    Gestern: $summe_gestern EUR (inkl. Steuer und Versand) Umsatz aus den Online-Shop
    "); - $this->app->Tpl->Set('SUBHEADING',''); - $this->app->Tpl->Parse('PAGE','shopimport_list.tpl'); - } - - - public function ShopimportArchiv() - { - $id = $this->app->Secure->GetGET('id'); - $more = $this->app->Secure->GetGET('more'); - $datum = $this->app->Secure->GetGET('datum'); - - $this->app->Tpl->Set('TABTEXT','Shopimport - Archiv'); - - - //$this->app->YUI->TableSearch('TAB1',"shopimportarchiv"); - - //$this->app->Tpl->Set('TAB1',"Shopimport - Archiv"); - - if($datum=='') - { - $datum = date('Y-m-d'); + $this->app->Tpl->Set('SUBHEADING', ''); + $this->app->Tpl->Parse('PAGE', 'shopimport_list.tpl'); } - $result = $this->app->DB->SelectArr("SELECT * FROM shopimport_auftraege WHERE DATE_FORMAT(logdatei,'%Y-%m-%d') = '$datum'"); + public function ShopimportArchiv() { + $id = $this->app->Secure->GetGET('id'); + $more = $this->app->Secure->GetGET('more'); + $datum = $this->app->Secure->GetGET('datum'); + $this->app->Tpl->Set('TABTEXT', 'Shopimport - Archiv'); - $table = ''; + //$this->app->YUI->TableSearch('TAB1',"shopimportarchiv"); + //$this->app->Tpl->Set('TAB1',"Shopimport - Archiv"); - if(is_array($result)) - { - foreach($result as $key=>$row) - { - //$table = $row['imported']; - if(isset($row['jsonencoded']) && $row['jsonencoded']) - { - $warenkorb = json_decode(base64_decode($row['warenkorb']), true); - }else{ - $warenkorb = unserialize(base64_decode($row['warenkorb'])); - } - $this->app->stringcleaner->XMLArray_clean($warenkorb); - - $table .= ""; - - } - } - - $table .= '
    ".$warenkorb["onlinebestellnummer"]."/".$warenkorb["transaktionsnummer"]."".$warenkorb["name"]."".$warenkorb["email"]."".$warenkorb["gesamtsumme"]." - mehr Informationen
    '; - - if($more > 0) - { - $result = $this->app->DB->Select("SELECT warenkorb FROM shopimport_auftraege WHERE id='$more' LIMIT 1"); - if($this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE id='$more' AND jsonencoded = 1 LIMIT 1")) - { - $warenkorb = json_decode(base64_decode($result), true); - }else{ - $warenkorb = unserialize(base64_decode($result)); - } - - ob_start(); - var_dump($warenkorb); - $var_dump_result = ob_get_clean(); - - $table .='
    '.$var_dump_result.'
    '; - - } - - $this->app->Tpl->Set('TAB1',$table); - $this->app->Tpl->Parse('PAGE','tabview.tpl'); - } - - - public function ShopimportAlle() - { - $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); - if(!empty($runningcronjob)) - { - $this->app->Location->execute('index.php?module=shopimport&action=list'); - } - $lastshop = false; - $shops = $this->app->DB->SelectArr("SELECT ae.id as id FROM shopexport ae LEFT JOIN projekt p ON p.id=ae.projekt WHERE ae.aktiv='1' and ae.demomodus <> '1'"); - if(!empty($shops)) - { - $anz = 0; - $fp = $this->app->erp->ProzessLock('shopimport_alle'); - $cshops = (!empty($shops)?count($shops):0); - for($i=0;$i<$cshops-1;$i++) - { - $anz += $this->ShopimportImport($shops[$i]['id'],$anz,true); - } - $lastshop=$shops[(!empty($shops)?count($shops):0)-1]['id']; - $this->app->erp->ProzessUnlock($fp); - } - if($lastshop && is_numeric($lastshop)){ - $this->app->Location->execute('index.php?module=shopimport&action=import&id='.$lastshop); - } - else{ - $this->app->Location->execute('index.php?module=shopimport&action=list'); - } - } - - /** - * @param int $shopId - * @param string $shopOrderNumber - * @param bool $changeShopOrderStatus - * @param int $projectId - * @param bool $allStati - * - * @return array - */ - public function importSingleOrder($shopId, $shopOrderNumber, $changeShopOrderStatus, $projectId, $allStati = false) - { - $pageContents = $this->app->remote->RemoteConnection($shopId); - if($pageContents==='success') - { - $orderCount = $this->app->remote->RemoteGetAuftraegeAnzahlNummer($shopId, $shopOrderNumber); - - if($orderCount > 0) - { - if($allStati){ - $result = $this->app->remote->RemoteCommand($shopId, 'getauftrag', ['nummer' => $shopOrderNumber]); - } - else { - $result = $this->app->remote->RemoteGetAuftragNummer($shopId, $shopOrderNumber); + if ($datum == '') { + $datum = date('Y-m-d'); } - if(is_array($result)) - { - $result = reset($result); - $shopExtId = $result['id']; - $sessionid = $result['sessionid']; - $jsonEncoded = 0; - if(empty(!$result['warenkorbjson'])) { - $jsonEncoded = 1; - $warenkorb = $result['warenkorbjson']; - } else{ - $warenkorb = $result['warenkorb']; - } - $logdatei = $result['logdatei']; - $username = !empty($this->app->User)?$this->app->User->GetName():'Cronjob'; - $this->app->DB->Insert( - sprintf( - "INSERT INTO shopimport_auftraege (extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei, jsonencoded, shopid) + $result = $this->app->DB->SelectArr("SELECT * FROM shopimport_auftraege WHERE DATE_FORMAT(logdatei,'%Y-%m-%d') = '$datum'"); + + $table = ''; + + if (is_array($result)) { + foreach ($result as $key => $row) { + //$table = $row['imported']; + if (isset($row['jsonencoded']) && $row['jsonencoded']) { + $warenkorb = json_decode(base64_decode($row['warenkorb']), true); + } else { + $warenkorb = unserialize(base64_decode($row['warenkorb'])); + } + $this->app->stringcleaner->XMLArray_clean($warenkorb); + + $table .= ""; + } + } + + $table .= '
    " . $warenkorb["onlinebestellnummer"] . "/" . $warenkorb["transaktionsnummer"] . "" . $warenkorb["name"] . "" . $warenkorb["email"] . "" . $warenkorb["gesamtsumme"] . " + mehr Informationen
    '; + + if ($more > 0) { + $result = $this->app->DB->Select("SELECT warenkorb FROM shopimport_auftraege WHERE id='$more' LIMIT 1"); + if ($this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE id='$more' AND jsonencoded = 1 LIMIT 1")) { + $warenkorb = json_decode(base64_decode($result), true); + } else { + $warenkorb = unserialize(base64_decode($result)); + } + + ob_start(); + var_dump($warenkorb); + $var_dump_result = ob_get_clean(); + + $table .= '
    ' . $var_dump_result . '
    '; + } + + $this->app->Tpl->Set('TAB1', $table); + $this->app->Tpl->Parse('PAGE', 'tabview.tpl'); + } + + public function ShopimportAlle() { + $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); + if (!empty($runningcronjob)) { + $this->app->Location->execute('index.php?module=shopimport&action=list'); + } + $lastshop = false; + $shops = $this->app->DB->SelectArr("SELECT ae.id as id FROM shopexport ae LEFT JOIN projekt p ON p.id=ae.projekt WHERE ae.aktiv='1' and ae.demomodus <> '1'"); + if (!empty($shops)) { + $anz = 0; + $fp = $this->app->erp->ProzessLock('shopimport_alle'); + $cshops = (!empty($shops) ? count($shops) : 0); + for ($i = 0; $i < $cshops - 1; $i++) { + $anz += $this->ShopimportImport($shops[$i]['id'], $anz, true); + } + $lastshop = $shops[(!empty($shops) ? count($shops) : 0) - 1]['id']; + $this->app->erp->ProzessUnlock($fp); + } + if ($lastshop && is_numeric($lastshop)) { + $this->app->Location->execute('index.php?module=shopimport&action=import&id=' . $lastshop); + } else { + $this->app->Location->execute('index.php?module=shopimport&action=list'); + } + } + + /** + * @param int $shopId + * @param string $shopOrderNumber + * @param bool $changeShopOrderStatus + * @param int $projectId + * @param bool $allStati + * + * @return array + */ + public function importSingleOrder($shopId, $shopOrderNumber, $changeShopOrderStatus, $projectId, $allStati = false) { + $pageContents = $this->app->remote->RemoteConnection($shopId); + if ($pageContents === 'success') { + $orderCount = $this->app->remote->RemoteGetAuftraegeAnzahlNummer($shopId, $shopOrderNumber); + + if ($orderCount > 0) { + if ($allStati) { + $result = $this->app->remote->RemoteCommand($shopId, 'getauftrag', ['nummer' => $shopOrderNumber]); + } else { + $result = $this->app->remote->RemoteGetAuftragNummer($shopId, $shopOrderNumber); + } + + if (is_array($result)) { + $result = reset($result); + $shopExtId = $result['id']; + $sessionid = $result['sessionid']; + $jsonEncoded = 0; + if (empty(!$result['warenkorbjson'])) { + $jsonEncoded = 1; + $warenkorb = $result['warenkorbjson']; + } else { + $warenkorb = $result['warenkorb']; + } + $logdatei = $result['logdatei']; + $username = !empty($this->app->User) ? $this->app->User->GetName() : 'Cronjob'; + $this->app->DB->Insert( + sprintf( + "INSERT INTO shopimport_auftraege (extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei, jsonencoded, shopid) VALUES('%s','%s','%s',0,%d, '%s','%s', %d, %d)", - $this->app->DB->real_escape_string($shopExtId), - $this->app->DB->real_escape_string($sessionid), - $this->app->DB->real_escape_string($warenkorb), - (int)$projectId, - $this->app->DB->real_escape_string($username), - $this->app->DB->real_escape_string($logdatei), - $jsonEncoded, - (int)$shopId - ) - ); - $insid = $this->app->DB->GetInsertID(); - if($changeShopOrderStatus && (String)$shopExtId !== '') - { - $this->app->remote->RemoteDeleteAuftrag($shopId, $shopExtId); - } - return ['status'=>1,'id'=>$insid,'info'=>'Auftrag wurde abgeholt.']; + $this->app->DB->real_escape_string($shopExtId), + $this->app->DB->real_escape_string($sessionid), + $this->app->DB->real_escape_string($warenkorb), + (int) $projectId, + $this->app->DB->real_escape_string($username), + $this->app->DB->real_escape_string($logdatei), + $jsonEncoded, + (int) $shopId + ) + ); + $insid = $this->app->DB->GetInsertID(); + if ($changeShopOrderStatus && (String) $shopExtId !== '') { + $this->app->remote->RemoteDeleteAuftrag($shopId, $shopExtId); + } + return ['status' => 1, 'id' => $insid, 'info' => 'Auftrag wurde abgeholt.']; + } + } + return ['status' => 0, 'error' => 'Auftrag wurde nicht gefunden!']; } - } - return ['status'=>0,'error'=>'Auftrag wurde nicht gefunden!']; + return ['status' => 0, 'error' => 'Verbindung fehlgeschlagen!']; } - return ['status'=>0,'error'=>'Verbindung fehlgeschlagen!']; - } - public function ShopimportEinzelimport() - { - $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); - if(!empty($runningcronjob)) - { - $this->app->Location->execute('index.php?module=shopimport&action=list'); - } - $id = (int)$this->app->Secure->GetGET('id'); - $nummer = (String)$this->app->Secure->GetGET('nummer'); - if($nummer === '') - { - $nummer = (String)$this->app->Secure->GetPOST('nummer'); - } - $deleteauftrag = (int)$this->app->Secure->GetPOST('deleteauftrag'); - if(!empty($id) && !empty($nummer)) - { - $shoparr = $this->app->DB->SelectRow("SELECT projekt,holealle FROM shopexport WHERE id = '$id' LIMIT 1"); - $projekt = $shoparr['projekt'];//$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); - $holealle = $shoparr['holealle'];//$this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$id' LIMIT 1"); - if($holealle) - { + public function ShopimportEinzelimport() { + $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); + if (!empty($runningcronjob)) { + $this->app->Location->execute('index.php?module=shopimport&action=list'); + } + $id = (int) $this->app->Secure->GetGET('id'); + $nummer = (String) $this->app->Secure->GetGET('nummer'); + if ($nummer === '') { + $nummer = (String) $this->app->Secure->GetPOST('nummer'); + } + $deleteauftrag = (int) $this->app->Secure->GetPOST('deleteauftrag'); + if (!empty($id) && !empty($nummer)) { + $shoparr = $this->app->DB->SelectRow("SELECT projekt,holealle FROM shopexport WHERE id = '$id' LIMIT 1"); + $projekt = $shoparr['projekt']; //$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); + $holealle = $shoparr['holealle']; //$this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$id' LIMIT 1"); + if ($holealle) { - $res = $this->importSingleOrder($id, $nummer, $deleteauftrag, $projekt); - if($res['status'] == 1){ - $this->app->Tpl->Add('MESSAGE','
    '.$res['info'].'
    '); + $res = $this->importSingleOrder($id, $nummer, $deleteauftrag, $projekt); + if ($res['status'] == 1) { + $this->app->Tpl->Add('MESSAGE', '
    ' . $res['info'] . '
    '); + } else { + $this->app->Tpl->Add('MESSAGE', '
    ' . $res['error'] . '
    '); + } + } else { + $this->app->Tpl->Add('MESSAGE', '
    Shop nicht auf alle Aufträge eingstellt!
    '); + } + } elseif ($id <= 0) { + $msg = $this->app->erp->base64_url_encode('
    Kein Shop gewählt!
    '); + $this->app->Location->execute('index.php?module=shopimport&action=list&msg=' . $msg); } else { - $this->app->Tpl->Add('MESSAGE','
    '.$res['error'].'
    '); + $this->app->Tpl->Add('MESSAGE', '
    Keine Nummer angegeben!
    '); } - }else{ - $this->app->Tpl->Add('MESSAGE','
    Shop nicht auf alle Aufträge eingstellt!
    '); - } - } elseif($id <= 0) { - $msg = $this->app->erp->base64_url_encode('
    Kein Shop gewählt!
    '); - $this->app->Location->execute('index.php?module=shopimport&action=list&msg='.$msg); - } else { - $this->app->Tpl->Add('MESSAGE','
    Keine Nummer angegeben!
    '); - } - $this->app->erp->MenuEintrag('index.php?module=shopimport&action=einzelimport&id='.$id,'Einzelimport'); - $this->app->erp->MenuEintrag('index.php?module=shopimport&action=import','Shopauftrag-Liste'); - $this->app->Tpl->Parse('PAGE','shopimport_einzelimport.tpl'); - } - - public function KundeAnlegenUpdate($shopimportid,$shopextid, $warenkorb, $kundennummer = 0, $import_kundennummer, &$unbekanntezahlungsweisen) - { - if(empty($warenkorb)) { - return 0; - } - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($warenkorb); - } - $i = 0; - $sucess_import = 0; - $shopid = $this->app->DB->Select("SELECT shopid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); - $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id=%d', $shopid)); - $projekt = $shopexportArr['projekt'];//$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$shopid'"); - if(!empty($warenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '".(int)$warenkorb['projekt']."' LIMIT 1")) - { - $projekt = (int)$warenkorb['projekt']; - } - $adresseprojekt = ''; - $kundenurvonprojekt = $shopexportArr['kundenurvonprojekt'];//$this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '".$shopid."' LIMIT 1"); - if($kundenurvonprojekt) - { - $adresseprojekt = $projekt; + $this->app->erp->MenuEintrag('index.php?module=shopimport&action=einzelimport&id=' . $id, 'Einzelimport'); + $this->app->erp->MenuEintrag('index.php?module=shopimport&action=import', 'Shopauftrag-Liste'); + $this->app->Tpl->Parse('PAGE', 'shopimport_einzelimport.tpl'); } - if(isset($warenkorb['subshop']) && $warenkorb['subshop']) - { - $subshopprojekt = $this->app->DB->SelectArr("SELECT * FROM shopexport_subshop WHERE shop = '".$shopid."' AND aktiv = 1 AND subshopkennung = '".$this->app->DB->real_escape_string($warenkorb['subshop'])."' LIMIT 1"); - if($subshopprojekt) - { - if($subshopprojekt[0]['projekt']) - { - $adresseprojekt = $subshopprojekt[0]['projekt']; - $projekt = $subshopprojekt[0]['projekt']; - $arr[$i]['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); + public function KundeAnlegenUpdate($shopimportid, $shopextid, $warenkorb, $kundennummer = 0, $import_kundennummer, &$unbekanntezahlungsweisen) { + if (empty($warenkorb)) { + return 0; } - if($subshopprojekt[0]['sprache']) - { - $defaultsprache = $this->app->DB->Select("SELECT sprache FROM shopexport_sprachen WHERE shop = '$shopid' AND (projekt = '$projekt' OR projekt = 0) AND - land = '' ORDER BY projekt = '$projekt' DESC, land = '".$warenkorb['land']."' DESC LIMIT 1"); - $checksprache = $this->app->DB->Select("SELECT sprache FROM shopexport_sprachen WHERE shop = '$shopid' AND (projekt = '$projekt' OR projekt = 0) AND - land = '".(isset($warenkorb['land'])?$warenkorb['land']:$this->app->erp->Firmendaten('land'))."' ORDER BY projekt = '$projekt' DESC, land = '".$warenkorb['land']."' DESC LIMIT 1"); - if($checksprache != ''){ - if(empty($warenkorb['kunde_sprache'])) - { - $warenkorb['kunde_sprache'] = $checksprache; + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($warenkorb); + } + $i = 0; + $success_import = 0; + $shopid = $this->app->DB->Select("SELECT shopid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); + $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id=%d', $shopid)); + $projekt = $shopexportArr['projekt']; //$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$shopid'"); + if (!empty($warenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '" . (int) $warenkorb['projekt'] . "' LIMIT 1")) { + $projekt = (int) $warenkorb['projekt']; + } + $adresseprojekt = ''; + $kundenurvonprojekt = $shopexportArr['kundenurvonprojekt']; //$this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '".$shopid."' LIMIT 1"); + if ($kundenurvonprojekt) { + $adresseprojekt = $projekt; + } + + if (isset($warenkorb['subshop']) && $warenkorb['subshop']) { + $subshopprojekt = $this->app->DB->SelectArr("SELECT * FROM shopexport_subshop WHERE shop = '" . $shopid . "' AND aktiv = 1 AND subshopkennung = '" . $this->app->DB->real_escape_string($warenkorb['subshop']) . "' LIMIT 1"); + if ($subshopprojekt) { + if ($subshopprojekt[0]['projekt']) { + $adresseprojekt = $subshopprojekt[0]['projekt']; + $projekt = $subshopprojekt[0]['projekt']; + $arr[$i]['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); + } + if ($subshopprojekt[0]['sprache']) { + $defaultsprache = $this->app->DB->Select("SELECT sprache FROM shopexport_sprachen WHERE shop = '$shopid' AND (projekt = '$projekt' OR projekt = 0) AND + land = '' ORDER BY projekt = '$projekt' DESC, land = '" . $warenkorb['land'] . "' DESC LIMIT 1"); + $checksprache = $this->app->DB->Select("SELECT sprache FROM shopexport_sprachen WHERE shop = '$shopid' AND (projekt = '$projekt' OR projekt = 0) AND + land = '" . (isset($warenkorb['land']) ? $warenkorb['land'] : $this->app->erp->Firmendaten('land')) . "' ORDER BY projekt = '$projekt' DESC, land = '" . $warenkorb['land'] . "' DESC LIMIT 1"); + if ($checksprache != '') { + if (empty($warenkorb['kunde_sprache'])) { + $warenkorb['kunde_sprache'] = $checksprache; + } + } else { + if (empty($warenkorb['kunde_sprache'])) { + $warenkorb['kunde_sprache'] = $defaultsprache; + } + } + + if (empty($warenkorb['kunde_sprache'])) { + $warenkorb['kunde_sprache'] = $subshopprojekt[0]['sprache']; + } + } + } else { + if (!$this->app->DB->Select("SELECT id FROM shopexport_subshop WHERE shop = '" . $shopid . "' AND subshopkennung = '" . $this->app->DB->real_escape_string($warenkorb['subshop']) . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO shopexport_subshop (shop, subshopkennung, aktiv, projekt) VALUES ('" . $shopid . "','" . $this->app->DB->real_escape_string($warenkorb['subshop']) . "','0','$projekt')"); + } } - } - else{ - if(empty($warenkorb['kunde_sprache'])) - { - $warenkorb['kunde_sprache'] = $defaultsprache; + } + + $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '$shopid' LIMIT 1"); + if ($kundenurvonprojekt) { + $adresseprojekt = " AND projekt = '" . $adresseprojekt . "' "; + } else { + $adresseprojekt = ''; + } + + if (empty($warenkorb['name'])) { + $warenkorb['name'] = $warenkorb['ansprechpartner']; + $warenkorb['ansprechpartner'] = ''; + } + if (empty($warenkorb['name']) && !empty($warenkorb['lieferadresse_name'])) { + $warenkorb['name'] = $warenkorb['lieferadresse_name']; + } + if (empty($warenkorb['lieferadresse_name'])) { + $warenkorb['lieferadresse_name'] = $warenkorb['lieferadresse_ansprechpartner']; + $warenkorb['lieferadresse_ansprechpartner'] = ''; + } + $warenkorb['email'] = trim($warenkorb['email'], " \t\n\r\0\x0B\xc2\xa0"); + if (empty($warenkorb['name'])) { + return 0; + } + //$projekt = $arr[0][projekt]; + + if ($kundennummer == '1') { + $warenkorb['kundennummer'] = $import_kundennummer; + if (strlen($warenkorb['kundennummer']) != '') { + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='{$warenkorb['kundennummer']}' AND geloescht!=1 $adresseprojekt LIMIT 1"); } - } - - if(empty($warenkorb['kunde_sprache'])) - { - $warenkorb['kunde_sprache'] = $subshopprojekt[0]['sprache']; - } - } - }else{ - if(!$this->app->DB->Select("SELECT id FROM shopexport_subshop WHERE shop = '".$shopid."' AND subshopkennung = '".$this->app->DB->real_escape_string($warenkorb['subshop'])."' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO shopexport_subshop (shop, subshopkennung, aktiv, projekt) VALUES ('".$shopid."','".$this->app->DB->real_escape_string($warenkorb['subshop'])."','0','$projekt')"); - } - } - } + if ($adresse <= 0) { + $adresse = $this->app->erp->KundeAnlegen($warenkorb['anrede'], $warenkorb['name'], $warenkorb['abteilung'], + $warenkorb['unterabteilung'], $warenkorb['ansprechpartner'], $warenkorb['adresszusatz'], $warenkorb['strasse'], $warenkorb['land'], $warenkorb['plz'], $warenkorb['ort'], $warenkorb['email'], + $warenkorb['telefon'], $warenkorb['telefax'], $warenkorb['ustid'], $warenkorb['affiliate_ref'], $projekt); + $warenkorb['customer_created'] = true; + if (isset($warenkorb['kunde_sprache'])) { + if ($warenkorb['kunde_sprache'] == 'englisch' || $warenkorb['kunde_sprache'] == 'english') { + $this->app->DB->Update("UPDATE adresse SET sprache = 'englisch' WHERE id = '$adresse' LIMIT 1"); + } elseif ($warenkorb['kunde_sprache'] == 'deutsch' || $warenkorb['kunde_sprache'] == 'german') { + $this->app->DB->Update("UPDATE adresse SET sprache = 'deutsch' WHERE id = '$adresse' LIMIT 1"); + } elseif (method_exists($this->app->erp, 'GetSprachenSelect')) { + $sprachen = $this->app->erp->GetSprachenSelect; + if (isset($sprachen[strtolower($warenkorb['kunde_sprache'])])) { + $this->app->DB->Update("UPDATE adresse SET sprache = '" . strtolower($warenkorb['kunde_sprache']) . "' WHERE id = '$adresse' LIMIT 1"); + } + } + } + if ($warenkorb['titel'] != '') { + $this->app->DB->Update("UPDATE adresse SET titel = '" . $this->app->DB->real_escape_string($warenkorb['titel']) . "' WHERE id = '$adresse' LIMIT 1"); + } + if (isset($warenkorb['ust_befreit'])) { + $this->app->DB->Update("UPDATE adresse SET ust_befreit = '" . (int) $warenkorb['ust_befreit'] . "' WHERE id = '$adresse' LIMIT 1"); + } - $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '$shopid' LIMIT 1"); - if($kundenurvonprojekt) - { - $adresseprojekt = " AND projekt = '".$adresseprojekt."' "; - }else{ - $adresseprojekt = ''; - } + $kundenGruppen = $this->app->DB->SelectArr("SELECT gruppeid,type FROM shopexport_kundengruppen WHERE shopid=$shopid AND aktiv=1 AND apply_to_new_customers=1 AND type<>'Artikel' AND (projekt=0 OR projekt='$projekt')"); + if (!empty($kundenGruppen)) { + foreach ($kundenGruppen as $gruppe) { + $this->app->erp->AddRolleZuAdresse($adresse, $gruppe['type'], 'von', 'Gruppe', $gruppe['gruppeid']); + } + } - if(empty($warenkorb['name'])){ - $warenkorb['name']=$warenkorb['ansprechpartner']; - $warenkorb['ansprechpartner'] = ''; - } - if(empty($warenkorb['name']) && !empty($warenkorb['lieferadresse_name'])) { - $warenkorb['name'] = $warenkorb['lieferadresse_name']; - } - if(empty($warenkorb['lieferadresse_name'])){ - $warenkorb['lieferadresse_name']=$warenkorb['lieferadresse_ansprechpartner']; - $warenkorb['lieferadresse_ansprechpartner'] = ''; - } - $warenkorb['email'] = trim($warenkorb['email']," \t\n\r\0\x0B\xc2\xa0"); - if(empty($warenkorb['name'])) { - return 0; - } - //$projekt = $arr[0][projekt]; + if (isset($warenkorb['kundengruppe'])) { + $this->shopimportAdresseGruppenMapping($warenkorb['kundengruppe'], $adresse, $shopid, $projekt); + } + if ($shopexportArr['vertrieb']) { + $this->app->DB->Update( + sprintf( + 'UPDATE adresse SET vertrieb = %d WHERE id = %d', + $shopexportArr['vertrieb'], $adresse + ) + ); + } + $this->app->DB->Update( + sprintf( + 'UPDATE adresse SET fromshop = %d WHERE fromshop = 0 AND id = %d', + $shopexportArr['id'], $adresse + ) + ); + } else { + if (!empty($warenkorb['anrede'])) { + $typ = $warenkorb['anrede']; + } else { + $typ = $this->app->DB->Select("SELECT typ FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + $name = $warenkorb['name']; - if($kundennummer=='1') - { - $warenkorb['kundennummer']= $import_kundennummer; - if(strlen($warenkorb['kundennummer'])!=''){ - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='{$warenkorb['kundennummer']}' AND geloescht!=1 $adresseprojekt LIMIT 1"); - } - if($adresse<=0) { - $adresse = $this->app->erp->KundeAnlegen($warenkorb['anrede'],$warenkorb['name'],$warenkorb['abteilung'], - $warenkorb['unterabteilung'],$warenkorb['ansprechpartner'],$warenkorb['adresszusatz'],$warenkorb['strasse'],$warenkorb['land'],$warenkorb['plz'],$warenkorb['ort'],$warenkorb['email'], - $warenkorb['telefon'],$warenkorb['telefax'],$warenkorb['ustid'],$warenkorb['affiliate_ref'],$projekt); - $warenkorb['customer_created'] = true; - if(isset($warenkorb['kunde_sprache'])) - { - if($warenkorb['kunde_sprache'] == 'englisch' || $warenkorb['kunde_sprache'] == 'english') - { - $this->app->DB->Update("UPDATE adresse SET sprache = 'englisch' WHERE id = '$adresse' LIMIT 1"); - }elseif($warenkorb['kunde_sprache'] == 'deutsch' || $warenkorb['kunde_sprache'] == 'german') - { - $this->app->DB->Update("UPDATE adresse SET sprache = 'deutsch' WHERE id = '$adresse' LIMIT 1"); - }elseif(method_exists($this->app->erp, 'GetSprachenSelect')){ - $sprachen = $this->app->erp->GetSprachenSelect; - if(isset($sprachen[strtolower($warenkorb['kunde_sprache'])])) - { - $this->app->DB->Update("UPDATE adresse SET sprache = '".strtolower($warenkorb['kunde_sprache'])."' WHERE id = '$adresse' LIMIT 1"); - } + if (!empty($warenkorb['abteilung'])) { + $abteilung = $warenkorb['abteilung']; + } else { + $abteilung = $this->app->DB->Select("SELECT abteilung FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['unterabteilung'])) { + $unterabteilung = $warenkorb['unterabteilung']; + } else { + $unterabteilung = $this->app->DB->Select("SELECT unterabteilung FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + + $ansprechpartner = $warenkorb['ansprechpartner']; + $adresszusatz = $warenkorb['adresszusatz']; + $strasse = $warenkorb['strasse']; + $land = $warenkorb['land']; + $plz = $warenkorb['plz']; + $ort = $warenkorb['ort']; + if (!empty($warenkorb['email'])) { + $email = $warenkorb['email']; + } else { + $email = $this->app->DB->Select("SELECT email FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['telefon'])) { + $telefon = $warenkorb['telefon']; + } else { + $telefon = $this->app->DB->Select("SELECT telefon FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['telefax'])) { + $telefax = $warenkorb['telefax']; + } else { + $telefax = $this->app->DB->Select("SELECT telefax FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['ustid'])) { + $ustid = $warenkorb['ustid']; + } else { + $ustid = $this->app->DB->Select("SELECT ustid FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['affiliate_ref'])) { + $partner = $warenkorb['affiliate_ref']; + } else { + $partner = $this->app->DB->Select("SELECT partner FROM adresse WHERE id = '$adresse' LIMIT 1"); + } + // Update + protokoll + if (!$this->app->DB->Select("SELECT adressennichtueberschreiben FROM shopexport WHERE id = '$shopid' LIMIT 1")) { + if ($warenkorb['mobil'] != '') { + $this->app->DB->Update("UPDATE adresse SET mobil = '" . $this->app->DB->real_escape_string($warenkorb['mobil']) . "' WHERE id = '$adresse' LIMIT 1"); + } + if ($warenkorb['titel'] != '') { + $this->app->DB->Update("UPDATE adresse SET titel = '" . $this->app->DB->real_escape_string($warenkorb['titel']) . "' WHERE id = '$adresse' LIMIT 1"); + } + if ($warenkorb['geburtstag'] != '') { + $this->app->DB->Update("UPDATE adresse SET geburtstag = '" . $this->app->DB->real_escape_string($warenkorb['geburtstag']) . "' WHERE id = '$adresse' AND ISNULL(geburtstag) LIMIT 1"); + } + if (isset($warenkorb['ust_befreit'])) { + $query = sprintf('UPDATE `adresse` SET `ust_befreit` = %d WHERE `id` = %d LIMIT 1', + $warenkorb['ust_befreit'], $adresse); + $this->app->DB->Update($query); + } + $this->app->erp->KundeUpdate($adresse, $typ, $name, $abteilung, + $unterabteilung, $ansprechpartner, $adresszusatz, $strasse, $land, $plz, $ort, $email, $telefon, $telefax, $ustid, $partner, $projekt); + + if (!empty($warenkorb['bundesland'])) { + $this->app->DB->Update("UPDATE adresse SET bundesland = '" . $this->app->DB->real_escape_string($warenkorb['bundesland']) . "' WHERE id = '$adresse' LIMIT 1"); + } + } } - } - if($warenkorb['titel'] != ''){ - $this->app->DB->Update("UPDATE adresse SET titel = '".$this->app->DB->real_escape_string($warenkorb['titel'])."' WHERE id = '$adresse' LIMIT 1"); - } - if(isset($warenkorb['ust_befreit'])) - { - $this->app->DB->Update("UPDATE adresse SET ust_befreit = '".(int)$warenkorb['ust_befreit']."' WHERE id = '$adresse' LIMIT 1"); - } - - $kundenGruppen = $this->app->DB->SelectArr("SELECT gruppeid,type FROM shopexport_kundengruppen WHERE shopid=$shopid AND aktiv=1 AND apply_to_new_customers=1 AND type<>'Artikel' AND (projekt=0 OR projekt='$projekt')"); - if(!empty($kundenGruppen)){ - foreach ($kundenGruppen as $gruppe){ - $this->app->erp->AddRolleZuAdresse($adresse, $gruppe['type'], 'von', 'Gruppe', $gruppe['gruppeid']); - } - } - - if(isset($warenkorb['kundengruppe'])){ - $this->shopimportAdresseGruppenMapping($warenkorb['kundengruppe'],$adresse,$shopid,$projekt); - } - if($shopexportArr['vertrieb']) { - $this->app->DB->Update( - sprintf( - 'UPDATE adresse SET vertrieb = %d WHERE id = %d', - $shopexportArr['vertrieb'], $adresse - ) - ); - } - $this->app->DB->Update( - sprintf( - 'UPDATE adresse SET fromshop = %d WHERE fromshop = 0 AND id = %d', - $shopexportArr['id'], $adresse - ) - ); - } - else { - if(!empty($warenkorb['anrede'])) - { + } else { + //echo "import als Neu-Kunde $shopimportid
    "; $typ = $warenkorb['anrede']; - }else{ - $typ = $this->app->DB->Select("SELECT typ FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - $name= $warenkorb['name']; - - if(!empty($warenkorb['abteilung'])) - { + $name = $warenkorb['name']; $abteilung = $warenkorb['abteilung']; - }else{ - $abteilung = $this->app->DB->Select("SELECT abteilung FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['unterabteilung'])) - { $unterabteilung = $warenkorb['unterabteilung']; - }else{ - $unterabteilung = $this->app->DB->Select("SELECT unterabteilung FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - - $ansprechpartner = $warenkorb['ansprechpartner']; - $adresszusatz = $warenkorb['adresszusatz']; - $strasse = $warenkorb['strasse']; - $land = $warenkorb['land']; - $plz = $warenkorb['plz']; - $ort = $warenkorb['ort']; - if(!empty($warenkorb['email'])) - { + $ansprechpartner = $warenkorb['ansprechpartner']; + $adresszusatz = $warenkorb['adresszusatz']; + $strasse = $warenkorb['strasse']; + $land = $warenkorb['land']; + $plz = $warenkorb['plz']; + $ort = $warenkorb['ort']; $email = $warenkorb['email']; - }else{ - $email = $this->app->DB->Select("SELECT email FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['telefon'])) - { $telefon = $warenkorb['telefon']; - }else{ - $telefon = $this->app->DB->Select("SELECT telefon FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['telefax'])) - { $telefax = $warenkorb['telefax']; - }else{ - $telefax = $this->app->DB->Select("SELECT telefax FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['ustid'])) - { $ustid = $warenkorb['ustid']; - }else{ - $ustid = $this->app->DB->Select("SELECT ustid FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['affiliate_ref'])) - { $partner = $warenkorb['affiliate_ref']; - }else{ - $partner = $this->app->DB->Select("SELECT partner FROM adresse WHERE id = '$adresse' LIMIT 1"); - } - // Update + protokoll - if(!$this->app->DB->Select("SELECT adressennichtueberschreiben FROM shopexport WHERE id = '$shopid' LIMIT 1")) - { - if($warenkorb['mobil'] != ''){ - $this->app->DB->Update("UPDATE adresse SET mobil = '".$this->app->DB->real_escape_string($warenkorb['mobil'])."' WHERE id = '$adresse' LIMIT 1"); - } - if($warenkorb['titel'] != ''){ - $this->app->DB->Update("UPDATE adresse SET titel = '".$this->app->DB->real_escape_string($warenkorb['titel'])."' WHERE id = '$adresse' LIMIT 1"); - } - if($warenkorb['geburtstag'] != ''){ - $this->app->DB->Update("UPDATE adresse SET geburtstag = '".$this->app->DB->real_escape_string($warenkorb['geburtstag'])."' WHERE id = '$adresse' AND ISNULL(geburtstag) LIMIT 1"); - } - if(isset($warenkorb['ust_befreit'])){ - $query = sprintf('UPDATE `adresse` SET `ust_befreit` = %d WHERE `id` = %d LIMIT 1', - $warenkorb['ust_befreit'], $adresse); - $this->app->DB->Update($query); - } - $this->app->erp->KundeUpdate($adresse,$typ,$name,$abteilung, - $unterabteilung,$ansprechpartner,$adresszusatz,$strasse,$land,$plz,$ort,$email,$telefon,$telefax,$ustid,$partner,$projekt); - - if(!empty($warenkorb['bundesland'])) - { - $this->app->DB->Update("UPDATE adresse SET bundesland = '".$this->app->DB->real_escape_string($warenkorb['bundesland'])."' WHERE id = '$adresse' LIMIT 1"); - } - } - } - } - else { - //echo "import als Neu-Kunde $shopimportid
    "; - $typ = $warenkorb['anrede']; - $name= $warenkorb['name']; - $abteilung = $warenkorb['abteilung']; - $unterabteilung = $warenkorb['unterabteilung']; - $ansprechpartner = $warenkorb['ansprechpartner']; - $adresszusatz = $warenkorb['adresszusatz']; - $strasse = $warenkorb['strasse']; - $land = $warenkorb['land']; - $plz = $warenkorb['plz']; - $ort = $warenkorb['ort']; - $email = $warenkorb['email']; - $telefon = $warenkorb['telefon']; - $telefax = $warenkorb['telefax']; - $ustid = $warenkorb['ustid']; - $partner = $warenkorb['affiliate_ref']; - - // denn fall das es kunde 1:1 schon gibt = alte Kundennummer verwenden kommt vor allem vor, wenn ein Kunde an einem Tag oefters bestellt hat - // $adresse = $this->app->erp->KundeAnlegen($typ,$name,$abteilung, - // $unterabteilung,$ansprechpartner,$adresszusatz,$strasse,$land,$plz,$ort,$email,$telefon,$telefax,$ustid,$partner,$projekt); - if(!empty($warenkorb['kundennummer'])){ - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='{$warenkorb['kundennummer']}' $adresseprojekt AND geloescht!=1 LIMIT 1"); - } - if(empty($adresse)){ - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE email='{$warenkorb['email']}' and email <> '' $adresseprojekt AND geloescht!=1 LIMIT 1"); - } - - if($adresse<=0) { - $adresse = $this->app->erp->KundeAnlegen($typ,$name,$abteilung, - $unterabteilung,$ansprechpartner,$adresszusatz,$strasse,$land,$plz,$ort,$email,$telefon,$telefax,$ustid,$partner,$projekt); - $warenkorb['customer_created'] = true; - if(!empty($warenkorb['bundesland'])) - { - $this->app->DB->Update("UPDATE adresse SET bundesland = '".$this->app->DB->real_escape_string($warenkorb['bundesland'])."' WHERE id = '$adresse' LIMIT 1"); - } - - if(isset($warenkorb['kunde_sprache'])) - { - if($warenkorb['kunde_sprache'] === 'englisch' || $warenkorb['kunde_sprache'] === 'english') - { - $this->app->DB->Update("UPDATE adresse SET sprache = 'englisch' WHERE id = '$adresse' LIMIT 1"); - }elseif($warenkorb['kunde_sprache'] === 'deutsch' || $warenkorb['kunde_sprache'] === 'german') - { - $this->app->DB->Update("UPDATE adresse SET sprache = 'deutsch' WHERE id = '$adresse' LIMIT 1"); - }elseif(method_exists($this->app->erp, 'GetAdressSprachen')){ - $sprachen = $this->app->erp->GetAdressSprachen(); - if(isset($sprachen[strtolower($warenkorb['kunde_sprache'])])) - { - $this->app->DB->Update("UPDATE adresse SET sprache = '".strtolower($warenkorb['kunde_sprache'])."' WHERE id = '$adresse' LIMIT 1"); - } + // denn fall das es kunde 1:1 schon gibt = alte Kundennummer verwenden kommt vor allem vor, wenn ein Kunde an einem Tag oefters bestellt hat + // $adresse = $this->app->erp->KundeAnlegen($typ,$name,$abteilung, + // $unterabteilung,$ansprechpartner,$adresszusatz,$strasse,$land,$plz,$ort,$email,$telefon,$telefax,$ustid,$partner,$projekt); + if (!empty($warenkorb['kundennummer'])) { + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='{$warenkorb['kundennummer']}' $adresseprojekt AND geloescht!=1 LIMIT 1"); } - } - if($warenkorb['titel'] != ''){ - $this->app->DB->Update("UPDATE adresse SET titel = '".$this->app->DB->real_escape_string($warenkorb['titel'])."' WHERE id = '$adresse' LIMIT 1"); - } - if(isset($warenkorb['ust_befreit'])) - { - $this->app->DB->Update("UPDATE adresse SET ust_befreit = '".(int)$warenkorb['ust_befreit']."' WHERE id = '$adresse' LIMIT 1"); - } - if($warenkorb['mobil'] != ''){ - $this->app->DB->Update("UPDATE adresse SET mobil = '".$this->app->DB->real_escape_string($warenkorb['mobil'])."' WHERE id = '$adresse' LIMIT 1"); - } - if(!empty($warenkorb['geburtstag'])){ - $query = sprintf("UPDATE `adresse` SET `geburtstag` = '%s' WHERE `id` = %d", - $this->app->DB->real_escape_string($warenkorb['geburtstag']), - $adresse); - $this->app->DB->Update($query); - } - $kundenGruppen = $this->app->DB->SelectArr("SELECT gruppeid,type FROM shopexport_kundengruppen WHERE shopid=$shopid AND aktiv=1 AND apply_to_new_customers=1 AND (projekt=0 OR projekt='$projekt')"); - if(!empty($kundenGruppen)){ - foreach ($kundenGruppen as $gruppe){ - $this->app->erp->AddRolleZuAdresse($adresse, $gruppe['type'], 'von', 'Gruppe', $gruppe['gruppeid']); - } - } - if(isset($warenkorb['kundengruppe'])){ - $this->shopimportAdresseGruppenMapping($warenkorb['kundengruppe'],$adresse,$shopid,$projekt); - } - if($shopexportArr['vertrieb']) { - $this->app->DB->Update( - sprintf( - 'UPDATE adresse SET vertrieb = %d WHERE id = %d AND geloescht <> 1 AND vertrieb = 0', - $shopexportArr['vertrieb'], $adresse - ) - ); - } - $this->app->DB->Update( - sprintf( - 'UPDATE adresse SET fromshop = %d WHERE fromshop = 0 AND id = %d', - $shopexportArr['id'], $adresse - ) - ); - } else { - // Update + protokoll - if(!$this->app->DB->Select("SELECT adressennichtueberschreiben FROM shopexport WHERE id = '$shopid' LIMIT 1")) - { - $this->app->erp->KundeUpdate($adresse,$typ,$name,$abteilung, - $unterabteilung,$ansprechpartner,$adresszusatz,$strasse,$land,$plz,$ort,$email,$telefon,$telefax,$ustid,$partner,$projekt); - if(!empty($warenkorb['bundesland'])) - { - $this->app->DB->Update("UPDATE adresse SET bundesland = '".$this->app->DB->real_escape_string($warenkorb['bundesland'])."' WHERE id = '$adresse' LIMIT 1"); + if (empty($adresse)) { + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE email='{$warenkorb['email']}' and email <> '' $adresseprojekt AND geloescht!=1 LIMIT 1"); } - } - } - // abweichende lieferadresse gleich angelegen? - if(strlen($warenkorb['lieferadresse_ansprechpartner'])>3) - { - $this->app->DB->Insert("INSERT INTO lieferadressen (typ,name,abteilung,unterabteilung,land,strasse,ort,plz,adresszusatz,adresse) VALUES + + if ($adresse <= 0) { + $adresse = $this->app->erp->KundeAnlegen($typ, $name, $abteilung, + $unterabteilung, $ansprechpartner, $adresszusatz, $strasse, $land, $plz, $ort, $email, $telefon, $telefax, $ustid, $partner, $projekt); + $warenkorb['customer_created'] = true; + if (!empty($warenkorb['bundesland'])) { + $this->app->DB->Update("UPDATE adresse SET bundesland = '" . $this->app->DB->real_escape_string($warenkorb['bundesland']) . "' WHERE id = '$adresse' LIMIT 1"); + } + + if (isset($warenkorb['kunde_sprache'])) { + if ($warenkorb['kunde_sprache'] === 'englisch' || $warenkorb['kunde_sprache'] === 'english') { + $this->app->DB->Update("UPDATE adresse SET sprache = 'englisch' WHERE id = '$adresse' LIMIT 1"); + } elseif ($warenkorb['kunde_sprache'] === 'deutsch' || $warenkorb['kunde_sprache'] === 'german') { + $this->app->DB->Update("UPDATE adresse SET sprache = 'deutsch' WHERE id = '$adresse' LIMIT 1"); + } elseif (method_exists($this->app->erp, 'GetAdressSprachen')) { + $sprachen = $this->app->erp->GetAdressSprachen(); + if (isset($sprachen[strtolower($warenkorb['kunde_sprache'])])) { + $this->app->DB->Update("UPDATE adresse SET sprache = '" . strtolower($warenkorb['kunde_sprache']) . "' WHERE id = '$adresse' LIMIT 1"); + } + } + } + if ($warenkorb['titel'] != '') { + $this->app->DB->Update("UPDATE adresse SET titel = '" . $this->app->DB->real_escape_string($warenkorb['titel']) . "' WHERE id = '$adresse' LIMIT 1"); + } + if (isset($warenkorb['ust_befreit'])) { + $this->app->DB->Update("UPDATE adresse SET ust_befreit = '" . (int) $warenkorb['ust_befreit'] . "' WHERE id = '$adresse' LIMIT 1"); + } + if ($warenkorb['mobil'] != '') { + $this->app->DB->Update("UPDATE adresse SET mobil = '" . $this->app->DB->real_escape_string($warenkorb['mobil']) . "' WHERE id = '$adresse' LIMIT 1"); + } + if (!empty($warenkorb['geburtstag'])) { + $query = sprintf("UPDATE `adresse` SET `geburtstag` = '%s' WHERE `id` = %d", + $this->app->DB->real_escape_string($warenkorb['geburtstag']), + $adresse); + $this->app->DB->Update($query); + } + $kundenGruppen = $this->app->DB->SelectArr("SELECT gruppeid,type FROM shopexport_kundengruppen WHERE shopid=$shopid AND aktiv=1 AND apply_to_new_customers=1 AND (projekt=0 OR projekt='$projekt')"); + if (!empty($kundenGruppen)) { + foreach ($kundenGruppen as $gruppe) { + $this->app->erp->AddRolleZuAdresse($adresse, $gruppe['type'], 'von', 'Gruppe', $gruppe['gruppeid']); + } + } + + if (isset($warenkorb['kundengruppe'])) { + $this->shopimportAdresseGruppenMapping($warenkorb['kundengruppe'], $adresse, $shopid, $projekt); + } + if ($shopexportArr['vertrieb']) { + $this->app->DB->Update( + sprintf( + 'UPDATE adresse SET vertrieb = %d WHERE id = %d AND geloescht <> 1 AND vertrieb = 0', + $shopexportArr['vertrieb'], $adresse + ) + ); + } + $this->app->DB->Update( + sprintf( + 'UPDATE adresse SET fromshop = %d WHERE fromshop = 0 AND id = %d', + $shopexportArr['id'], $adresse + ) + ); + } else { + // Update + protokoll + if (!$this->app->DB->Select("SELECT adressennichtueberschreiben FROM shopexport WHERE id = '$shopid' LIMIT 1")) { + $this->app->erp->KundeUpdate($adresse, $typ, $name, $abteilung, + $unterabteilung, $ansprechpartner, $adresszusatz, $strasse, $land, $plz, $ort, $email, $telefon, $telefax, $ustid, $partner, $projekt); + if (!empty($warenkorb['bundesland'])) { + $this->app->DB->Update("UPDATE adresse SET bundesland = '" . $this->app->DB->real_escape_string($warenkorb['bundesland']) . "' WHERE id = '$adresse' LIMIT 1"); + } + } + } + // abweichende lieferadresse gleich angelegen? + if (strlen($warenkorb['lieferadresse_ansprechpartner']) > 3) { + $this->app->DB->Insert("INSERT INTO lieferadressen (typ,name,abteilung,unterabteilung,land,strasse,ort,plz,adresszusatz,adresse) VALUES ('','{$warenkorb['lieferadresse_ansprechpartner']}', '{$warenkorb['lieferadresse_abteilung']}','{$warenkorb['lieferadresse_unterabteilung']}','{$warenkorb['lieferadresse_land']}', '{$warenkorb['lieferadresse_strasse']}','{$warenkorb['lieferadresse_ort']}','{$warenkorb['lieferadresse_plz']}','{$warenkorb['lieferadresse_adresszusatz']}','$adresse')"); - } + } - if(strlen($warenkorb['lieferadresse_name'])>3 && $warenkorb['lieferadresse_ansprechpartner']=='') - { - $this->app->DB->Insert("INSERT INTO lieferadressen (typ,name,abteilung,unterabteilung,land,strasse,ort,plz,adresszusatz,adresse) VALUES + if (strlen($warenkorb['lieferadresse_name']) > 3 && $warenkorb['lieferadresse_ansprechpartner'] == '') { + $this->app->DB->Insert("INSERT INTO lieferadressen (typ,name,abteilung,unterabteilung,land,strasse,ort,plz,adresszusatz,adresse) VALUES ('','{$warenkorb['lieferadresse_name']}', '{$warenkorb['lieferadresse_abteilung']}','{$warenkorb['lieferadresse_unterabteilung']}','{$warenkorb['lieferadresse_land']}', '{$warenkorb['lieferadresse_strasse']}','{$warenkorb['lieferadresse_ort']}','{$warenkorb['lieferadresse_plz']}','{$warenkorb['lieferadresse_adresszusatz']}','$adresse')"); + } } - } - //print_r($warenkorb); - //echo "

    Ende"; - //exit; - //imort auf kunde - //$bekanntezahlungsweisen = array('rechnung','vorkasse','nachnahme','kreditkarte','einzugsermaechtigung','bar','paypal','amazon','amazon_bestellung','sofortueberweisung','amazoncba','secupay','lastschrift'); + //print_r($warenkorb); + //echo "

    Ende"; + //exit; + //imort auf kunde + //$bekanntezahlungsweisen = array('rechnung','vorkasse','nachnahme','kreditkarte','einzugsermaechtigung','bar','paypal','amazon','amazon_bestellung','sofortueberweisung','amazoncba','secupay','lastschrift'); - $bekanntezahlungsweisen = $this->app->erp->GetZahlungsweise(); + $bekanntezahlungsweisen = $this->app->erp->GetZahlungsweise(); - $tmpauftragid = $this->app->erp->ImportAuftrag($adresse,$warenkorb,$projekt,$shopid); - if ($tmpauftragid > 0) { - $sucess_import = true; - } - - $doctype = 'auftrag'; - if($this->app->DB->Select("SELECT angeboteanlegen FROM shopexport WHERE id = '$shopid' LIMIT 1")) - { - $doctype = 'angebot'; - } + $import_result = $this->app->erp->ImportAuftrag($adresse, $warenkorb, $projekt, $shopid); - if(isset($warenkorb['doctype']) && $warenkorb['doctype']==='angebot'){ - $doctype = 'angebot'; - } + if ($import_result['status']) { + $tmpauftragid = $import_result['auftragid']; + $success_import = true; - $warenkorb['zahlungsweise'] = $this->app->DB->Select("SELECT zahlungsweise FROM $doctype WHERE id = '$tmpauftragid' LIMIT 1"); - if($warenkorb['zahlungsweise'] != ''){ - if(!isset($bekanntezahlungsweisen[$warenkorb['zahlungsweise']])){ - if(!$unbekanntezahlungsweisen || !isset($unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])])){ - $unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])] = false; - } - $tmp = array(); - $tmp['bestellnummer'] = $warenkorb['onlinebestellnummer']; - $unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])][] = $tmp; + $doctype = 'auftrag'; + if ($this->app->DB->Select("SELECT angeboteanlegen FROM shopexport WHERE id = '$shopid' LIMIT 1")) { + $doctype = 'angebot'; + } + + if (isset($warenkorb['doctype']) && $warenkorb['doctype'] === 'angebot') { + $doctype = 'angebot'; + } + + $warenkorb['zahlungsweise'] = $this->app->DB->Select("SELECT zahlungsweise FROM $doctype WHERE id = '$tmpauftragid' LIMIT 1"); + if ($warenkorb['zahlungsweise'] != '') { + if (!isset($bekanntezahlungsweisen[$warenkorb['zahlungsweise']])) { + if (!$unbekanntezahlungsweisen || !isset($unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])])) { + $unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])] = false; + } + $tmp = array(); + $tmp['bestellnummer'] = $warenkorb['onlinebestellnummer']; + $unbekanntezahlungsweisen[strtolower($warenkorb['zahlungsweise'])][] = $tmp; + } + } + + if ($shopimportid && $tmpauftragid) { + $this->app->DB->Update("UPDATE shopimport_auftraege SET imported='1' WHERE id='$shopimportid' LIMIT 1"); + } + if ($shopimportid) { + $shopextid = $this->app->DB->real_escape_string($this->app->DB->Select("SELECT extid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1")); + } + if ($shopextid) { + $this->app->DB->Select("UPDATE $doctype SET shopextid='$shopextid' WHERE id='$tmpauftragid' LIMIT 1"); + } + $this->app->erp->RunHook('Shopimportwarenkorb', 4, $doctype, $tmpauftragid, $shopid, $warenkorb); + $this->app->erp->RunHook('Shopimport', 3, $doctype, $tmpauftragid, $shopid); + $adresse = ''; + } else { + // Error... } - } - - if($shopimportid && $tmpauftragid) - { - $this->app->DB->Update("UPDATE shopimport_auftraege SET imported='1' WHERE id='$shopimportid' LIMIT 1"); - } - if($shopimportid) - { - $shopextid = $this->app->DB->real_escape_string($this->app->DB->Select("SELECT extid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1")); - } - if($shopextid) - { - $this->app->DB->Select("UPDATE $doctype SET shopextid='$shopextid' WHERE id='$tmpauftragid' LIMIT 1"); - } - $this->app->erp->RunHook('Shopimportwarenkorb', 4, $doctype, $tmpauftragid, $shopid, $warenkorb); - $this->app->erp->RunHook('Shopimport', 3, $doctype, $tmpauftragid, $shopid); - $adresse =''; - return $sucess_import; - } - - /** - * @param String $gruppenBezeichnung im Shop - * @param int $adresseId - * @param int $shopId - * @param int $projektId - * - * @return string - */ - private function shopimportAdresseGruppenMapping($gruppenBezeichnung, $adresseId, $shopId, $projektId){ - $kundenGruppen = $this->getShopimportKundenGruppenZuordnungen($gruppenBezeichnung, $shopId, $projektId); - if(empty($kundenGruppen)) { - return ''; - } - foreach ($kundenGruppen as $gruppe => $rolle){ - $this->app->erp->AddRolleZuAdresse($adresseId, $rolle, 'von', 'Gruppe', $gruppe); + return $success_import; } - return ''; - } + /** + * @param String $gruppenBezeichnung im Shop + * @param int $adresseId + * @param int $shopId + * @param int $projektId + * + * @return string + */ + private function shopimportAdresseGruppenMapping($gruppenBezeichnung, $adresseId, $shopId, $projektId) { + $kundenGruppen = $this->getShopimportKundenGruppenZuordnungen($gruppenBezeichnung, $shopId, $projektId); + if (empty($kundenGruppen)) { + return ''; + } + foreach ($kundenGruppen as $gruppe => $rolle) { + $this->app->erp->AddRolleZuAdresse($adresseId, $rolle, 'von', 'Gruppe', $gruppe); + } - /** - * @param String $gruppenBezeichnung im Shop - * @param int $shopId - * @param int $projektId - * - * @return array - */ - private function getShopimportKundenGruppenZuordnungen($gruppenBezeichnung, $shopId, $projektId){ - $gefundeneGruppen = $this->app->DB->SelectArr("SELECT gruppeid, type FROM shopexport_kundengruppen WHERE shopid='$shopId' AND extgruppename='$gruppenBezeichnung' AND projekt='$projektId'"); - - if(empty($gefundeneGruppen)){ - //Fallback, falls kein projektspezifisches Mapping gefunden - $gefundeneGruppen = $this->app->DB->SelectArr("SELECT gruppeid, type FROM shopexport_kundengruppen WHERE shopid='$shopId' AND extgruppename='$gruppenBezeichnung' AND projekt='0'"); + return ''; } - if(empty($gefundeneGruppen)) { - return []; + /** + * @param String $gruppenBezeichnung im Shop + * @param int $shopId + * @param int $projektId + * + * @return array + */ + private function getShopimportKundenGruppenZuordnungen($gruppenBezeichnung, $shopId, $projektId) { + $gefundeneGruppen = $this->app->DB->SelectArr("SELECT gruppeid, type FROM shopexport_kundengruppen WHERE shopid='$shopId' AND extgruppename='$gruppenBezeichnung' AND projekt='$projektId'"); + + if (empty($gefundeneGruppen)) { + //Fallback, falls kein projektspezifisches Mapping gefunden + $gefundeneGruppen = $this->app->DB->SelectArr("SELECT gruppeid, type FROM shopexport_kundengruppen WHERE shopid='$shopId' AND extgruppename='$gruppenBezeichnung' AND projekt='0'"); + } + + if (empty($gefundeneGruppen)) { + return []; + } + + $kundenGruppen = []; + foreach ($gefundeneGruppen as $gruppe) { + $kundenGruppen[$gruppe['gruppeid']] = $gruppe['type']; + } + + return $kundenGruppen; } - $kundenGruppen = []; - foreach ($gefundeneGruppen as $gruppe){ - $kundenGruppen[$gruppe['gruppeid']] = $gruppe['type']; + /** + * @param $shopImportedOrderId + * + * @return bool + */ + public function setShopImportedOrderTrash($shopImportedOrderId) { + $this->app->DB->Update( + sprintf( + 'UPDATE shopimport_auftraege SET trash=1 WHERE id= %d LIMIT 1', + (int) $shopImportedOrderId + ) + ); + return $this->app->DB->affected_rows() > 0; } - return $kundenGruppen; - } + public function importShopOrder($shopImportedOrderId, $utf8coding, $customerNumber, $custumerNumberImported, &$unknownPaymentTypes) { + $shopImportedOrder = $this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM shopimport_auftraege WHERE imported=0 AND trash=0 AND id=%d LIMIT 1', + $shopImportedOrderId + ) + ); + if (empty($shopImportedOrder)) { + return ['success' => 0]; + } - /** - * @param $shopImportedOrderId - * - * @return bool - */ - public function setShopImportedOrderTrash($shopImportedOrderId) { - $this->app->DB->Update( - sprintf( - 'UPDATE shopimport_auftraege SET trash=1 WHERE id= %d LIMIT 1', - (int)$shopImportedOrderId - ) - ); - return $this->app->DB->affected_rows() > 0; - } + if (isset($shopImportedOrder['jsonencoded']) && $shopImportedOrder['jsonencoded']) { + $shopOrder = json_decode(base64_decode($shopImportedOrder['warenkorb']), true); + } else { + $shopOrder = unserialize(base64_decode($shopImportedOrder['warenkorb'])); + } - public function importShopOrder($shopImportedOrderId, $utf8coding, $customerNumber, $custumerNumberImported, &$unknownPaymentTypes) { - $shopImportedOrder = $this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM shopimport_auftraege WHERE imported=0 AND trash=0 AND id=%d LIMIT 1', - $shopImportedOrderId - ) - ); - if(empty($shopImportedOrder)) { - return ['success' => 0]; + //alle leerzeichen am amfang und ende entfernen + umbrueche komplett entfernen + if ($utf8coding == '1') { + $shopOrderCleaned = $this->app->erp->CleanDataBeforImportUTF8($shopOrder, false); + } else { + $shopOrderCleaned = $this->app->erp->CleanDataBeforImport($shopOrder, false); + } + if ($shopOrderCleaned['name'] === '') { + $shopOrderCleaned['name'] = $shopOrderCleaned['ansprechpartner']; + $shopOrderCleaned['ansprechpartner'] = ''; + } + if ($shopOrderCleaned['lieferadresse_name'] === '') { + $shopOrderCleaned['lieferadresse_name'] = $shopOrderCleaned['lieferadresse_ansprechpartner']; + $shopOrderCleaned['lieferadresse_ansprechpartner'] = ''; + } + + if ($shopOrderCleaned['name'] === '' && !empty($shopOrderCleaned['lieferadresse_name'])) { + $shopOrderCleaned['name'] = $shopOrderCleaned['lieferadresse_name']; + } + + foreach ($shopOrderCleaned as $k => $v) { + if (!is_array($v)) { + $shopOrderCleaned[$k] = $this->app->erp->fixeUmlaute($v); + } + } + $umlautefehler = false; + if ((String) $shopOrder['name'] !== '' && (String) $shopOrderCleaned['name'] === '') { + $umlautefehler = true; + $this->app->erp->LogFile('Kodierungsfehler in shopimport_auftraege ' . $shopImportedOrderId); + } + $succes = $this->KundeAnlegenUpdate($shopImportedOrderId, '', $shopOrderCleaned, $customerNumber, $custumerNumberImported, $unknownPaymentTypes); + + return ['codingerror' => $umlautefehler, 'success' => $succes]; } - if(isset($shopImportedOrder['jsonencoded']) && $shopImportedOrder['jsonencoded']) - { - $shopOrder = json_decode(base64_decode($shopImportedOrder['warenkorb']), true); - }else{ - $shopOrder = unserialize(base64_decode($shopImportedOrder['warenkorb'])); + public function ShopimportView() { + $this->ShopimportImport(showonly: true); } - //alle leerzeichen am amfang und ende entfernen + umbrueche komplett entfernen - if($utf8coding=='1') - { - $shopOrderCleaned = $this->app->erp->CleanDataBeforImportUTF8($shopOrder, false); - } else { - $shopOrderCleaned = $this->app->erp->CleanDataBeforImport($shopOrder, false); - } - if($shopOrderCleaned['name']===''){ - $shopOrderCleaned['name']=$shopOrderCleaned['ansprechpartner']; - $shopOrderCleaned['ansprechpartner'] = ''; - } - if($shopOrderCleaned['lieferadresse_name']==='') - { - $shopOrderCleaned['lieferadresse_name']=$shopOrderCleaned['lieferadresse_ansprechpartner']; - $shopOrderCleaned['lieferadresse_ansprechpartner'] = ''; - } - - if($shopOrderCleaned['name']==='' && !empty($shopOrderCleaned['lieferadresse_name'])) - { - $shopOrderCleaned['name'] = $shopOrderCleaned['lieferadresse_name']; - } - - foreach($shopOrderCleaned as $k => $v) - { - if(!is_array($v)){ - $shopOrderCleaned[$k] = $this->app->erp->fixeUmlaute($v); - } - } - $umlautefehler = false; - if((String)$shopOrder['name'] !== '' && (String)$shopOrderCleaned['name'] === '') - { - $umlautefehler = true; - $this->app->erp->LogFile('Kodierungsfehler in shopimport_auftraege '.$shopImportedOrderId); - } - $succes = $this->KundeAnlegenUpdate($shopImportedOrderId,'', $shopOrderCleaned, $customerNumber, $custumerNumberImported,$unknownPaymentTypes); - - return ['codingerror'=>$umlautefehler, 'success' => $succes]; - } - - public function ShopimportView() { - $this->ShopimportImport(showonly: true); - } - - public function ShopimportImport($id='', $count = 0, $returncount = false, $showonly = false) - { - $deletedRows = 0; - if(!is_numeric($id) && $this->app->Secure->GetPOST('deletedouble')) { - $id = (int)$this->app->Secure->GetGET('id'); - $this->app->DB->Update( - sprintf( - 'UPDATE shopimport_auftraege AS sa + public function ShopimportImport($id = '', $count = 0, $returncount = false, $showonly = false) { + $deletedRows = 0; + if (!is_numeric($id) && $this->app->Secure->GetPOST('deletedouble')) { + $showonly = true; + $id = (int) $this->app->Secure->GetGET('id'); + $this->app->DB->Update( + sprintf( + 'UPDATE shopimport_auftraege AS sa INNER JOIN auftrag a ON sa.bestellnummer = a.internet AND sa.shopid = a.shop SET sa.trash = 1 WHERE IFNULL(a.internet,\'\') <> \'\' AND sa.trash = 0 AND sa.imported = 0 AND (sa.shopid = %d OR %d = 0)', - $id, $id - ) - ); - $deletedRows = (int)$this->app->DB->affected_rows(); - $this->app->Tpl->Add('IMPORT','
    Es wurden '.$deletedRows.' bereits importierte Datensätze entfernt.
    '); - } - $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); - if($runningcronjob && !$showonly) - { - $this->app->Location->execute('index.php?module=shopimport&action=list'); - } - if(!is_numeric($id)){ - $id = $this->app->Secure->GetGET('id'); - } - - $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id'"); - $projekt = $shopexportarr['projekt'];//$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id'"); - $demomodus = $shopexportarr['demomodus'];//$this->app->DB->Select("SELECT demomodus FROM shopexport WHERE id='$id'"); - $einzelsync = $shopexportarr['einzelsync'];//$this->app->DB->Select("SELECT einzelsync FROM shopexport WHERE id='$id'"); - $utf8codierung = $shopexportarr['utf8codierung'];//$this->app->DB->Select("SELECT utf8codierung FROM shopexport WHERE id='$id'"); - - if(!$returncount) - { - $this->app->erp->Headlines('Shopimport'); - $this->app->erp->MenuEintrag('index.php?module=shopimport&action=list','Zurück zur Übersicht'); - } - //name, strasse, ort, plz und kundenummer, emailadresse oder bestellung kam von login account ==> Kunde aus DB verwenden - //ACHTUNG Lieferadresse immer aus Auftrag!!! aber Lieferadresse extra bei Kunden anlegen - if($this->app->Secure->GetPOST('submit')!='') - { - $auftraege = $this->app->Secure->GetPOST('auftrag'); - $kundennummer = $this->app->Secure->GetPOST('kundennummer'); - $import= $this->app->Secure->GetPOST('import'); - $import_kundennummer= $this->app->Secure->GetPOST('import_kundennummer'); - - $sucess_import = 0; - $insgs_import = 0; - $unbekanntezahlungsweisen = null; - $cauftraege = $auftraege?count($auftraege):0; - for($i=0;$i<$cauftraege;$i++) - { - $adresse = ''; - $shopimportid = $auftraege[$i]; - $shopid = $this->app->DB->Select("SELECT shopid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); - if($shopid) - { - $demomodus = $this->app->DB->Select("SELECT demomodus FROM shopexport WHERE id='$shopid'"); - $einzelsync = $this->app->DB->Select("SELECT einzelsync FROM shopexport WHERE id='$shopid'"); - $utf8codierung = $this->app->DB->Select("SELECT utf8codierung FROM shopexport WHERE id='$shopid'"); - } - $projekt = $this->app->DB->Select("SELECT projekt FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); - if($import[$shopimportid]==='warten') - { - - } - else if($import[$shopimportid]==='muell') - { - $this->setShopImportedOrderTrash($shopimportid); - } else if($import[$shopimportid]==='import') { - - $res = $this->importShopOrder($shopimportid, $utf8codierung, $kundennummer[$shopimportid], $import_kundennummer[$shopimportid], $unbekanntezahlungsweisen); - if($res['codingerror']) { - $umlautefehler = true; - } - if($res['success']) { - $sucess_import += $res['success']; - } - $insgs_import++; - } - } // ende for - - - if($unbekanntezahlungsweisen) - { - $meldung = ''; - foreach($unbekanntezahlungsweisen as $k => $v) - { - $meldung .= 'Unbekannte Zahlungsart: '.$k.' in Bestellung(en): '; - $first = true; - foreach($v as $k2 => $v2) - { - if(!$first) - { - $meldung .= ', '; - } - $first = false; - $meldung .= $v2['bestellnummer']; - - } - $meldung .= "
    \r\n"; - - } - - if(isset($this->app->User) && method_exists($this->app->User,'GetID') && $this->app->User->GetID()) - { - $this->app->erp->EventMitSystemLog($this->app->User->GetID(), $meldung, -1,'', 'warning', 1); - } - } - if(!empty($umlautefehler)) - { - $msg = $this->app->erp->base64_url_encode("
    $sucess_import".($sucess_import != $insgs_import?" von $insgs_import ":'')." Aufträge importiert. Aufträge mit Kodierungsprobleme. Bitte prüfen Sie sie UTF8-Einstellung in der Shopschnittstelle!
    "); - }else{ - $msg = $this->app->erp->base64_url_encode("
    $sucess_import".($sucess_import != $insgs_import?" von $insgs_import ":'')." Aufträge importiert!
    "); - } - $this->app->Location->execute('index.php?module=shopimport&action=list&msg='.$msg); - } - - - if(!$showonly && $id) - { - try { - $pageContents = $this->app->remote->RemoteConnection($id); - }catch(Exception $e){ - $pageContents = $e->getMessage(); - } - if($pageContents==='success') - { - $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); - $holealle = $shopexportarr['holealle'];//$this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$id' LIMIT 1"); - $statusaendern = $shopexportarr['nummersyncstatusaendern'];//$this->app->DB->Select("SELECT nummersyncstatusaendern FROM shopexport WHERE id = '$id' LIMIT 1"); - $auftragabgleich = $shopexportarr['auftragabgleich'];//$this->app->DB->Select("SELECT auftragabgleich FROM shopexport WHERE id = '$id' LIMIT 1"); - $zeitraum = array('datumvon'=>$shopexportarr['datumvon'], 'datumbis'=>$shopexportarr['datumbis'],'tmpdatumvon'=>$shopexportarr['tmpdatumvon'], 'tmpdatumbis'=>$shopexportarr['tmpdatumbis'], 'anzgleichzeitig'=>$shopexportarr['anzgleichzeitig']); - //$this->app->DB->SelectArr("SELECT datumvon, datumbis,tmpdatumvon, tmpdatumbis, anzgleichzeitig FROM shopexport WHERE id = '$id' LIMIT 1"); - /*if(!empty($zeitraum)) - { - $zeitraum = reset($zeitraum); - }*/ - $anzgleichzeitig = 1; - if(isset($zeitraum['anzgleichzeitig'])){ - $anzgleichzeitig = (int)$zeitraum['anzgleichzeitig']; - } - - if($anzgleichzeitig > 1) - { - $result = $this->app->remote->RemoteGetAuftrag($id); - if(!empty($result) && is_array($result) && isset($result[0])) - { - $maxtime = false; - $mintime = false; - $gesamtanzahl = (!empty($result)?count($result):0); - for($i = 0; $i < $gesamtanzahl; $i++) - { - $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); - $auftrag = $result[$i]['id']; - if(isset($result[$i]['warenkorbjson'])) - { - $isjson = true; - $tmpwarenkorb = json_decode(base64_decode($result[$i]['warenkorbjson']), true); - }else{ - $isjson = false; - $tmpwarenkorb = unserialize(base64_decode($result[$i]['warenkorb'])); - } - if(!empty($tmpwarenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '".(int)$tmpwarenkorb['projekt']."' LIMIT 1")) - { - $projekt = (int)$tmpwarenkorb['projekt']; - } - if(!empty($tmpwarenkorb['zeitstempel'])) - { - $time = strtotime($tmpwarenkorb['zeitstempel']); - if($time < 0) - { - $time = 0; - } - if($maxtime === false) - { - $maxtime = $time; - } - if($mintime === false) - { - $mintime = $time; - } - if($time > $maxtime) - { - $maxtime = $time; - } - if($time < $mintime) - { - $mintime = $time; - } - } - $onlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; - if(!empty($tmpwarenkorb['useorderid']) || - (!is_numeric($onlinebestellnummer) && trim((String)$onlinebestellnummer) !== '')) - { - $onlinebestellnummer = $tmpwarenkorb['auftrag']; - } - - if($holealle && $onlinebestellnummer) - { - $neue_nummer = (int)$onlinebestellnummer+1; - $this->app->DB->Update("UPDATE shopexport SET ab_nummer = '$neue_nummer' WHERE id = '$id'"); - } - $sessionid = isset($result[$i]['sessionid'])?$result[$i]['sessionid']:''; - if($isjson) - { - $warenkorb = $result[$i]['warenkorbjson']; - }else{ - $warenkorb = $result[$i]['warenkorb']; - } - $logdatei = isset($result[$i]['logdatei'])?$result[$i]['logdatei']:null; - if(empty($logdatei)) - { - $logdatei = date('Y-m-d H:i:s'); - } - if(isset($tmpwarenkorb['subshop']) && $tmpwarenkorb['subshop']) - { - $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '$id' AND aktiv = 1 AND subshopkennung = '".$this->app->DB->real_escape_string($tmpwarenkorb['subshop'])."' LIMIT 1"); - if($subshopprojekt) - { - $projekt = $subshopprojekt; - } - } - $letzteonlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; - unset($tmpwarenkorb); - - //globalerauftragsnummernkreis - $standardcheck = true; - $modulename = $this->app->DB->Select( - sprintf( - "SELECT modulename FROM shopexport WHERE id = %d AND modulename <> '' AND (shoptyp = 'intern')", - $id - ) - ); - $shopIds = [$id]; - $otherModules= empty($modulename)?null: - $this->app->DB->SelectFirstCols( - sprintf( - "SELECT id - FROM shopexport - WHERE modulename = '%s' AND id <> %d", - $this->app->DB->real_escape_string($modulename), $id - ) - ); - if(!empty($otherModules) && $this->app->erp->ModulVorhanden($modulename)) { - $obj = $this->app->erp->LoadModul($modulename); - if(!empty($obj) && method_exists($obj, 'EinstellungenStruktur')){ - $konfiguration = $obj->EinstellungenStruktur(); - if($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) { - $shopIds = array_merge([$id], $otherModules); - $standardcheck = false; - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - } - } - } - $checkdoppeltimported = $this->app->DB->Select( - sprintf( - "SELECT id - FROM shopimport_auftraege - WHERE extid = '%s' and shopid IN (%s) AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1", - $this->app->DB->real_escape_string($auftrag), implode(',', $shopIds) - ) - ); - /*if($standardcheck) - {*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and shopid = '$id' and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and shopid = '$id' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1"); - }*/ - $insid = null; - if(empty($checkdoppeltimported)) - { - $this->app->DB->Insert("INSERT INTO shopimport_auftraege (id,extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei) - VALUES('','".$this->app->DB->real_escape_string($auftrag)."','".$this->app->DB->real_escape_string($sessionid)."','".$this->app->DB->real_escape_string($warenkorb)."','0','$projekt','".$this->app->DB->real_escape_string($this->app->User->GetName())."','".$this->app->DB->real_escape_string($logdatei)."')"); - $insid = $this->app->DB->GetInsertID(); - if($insid) - { - if($isjson) - { - $this->app->DB->Update("UPDATE shopimport_auftraege set jsonencoded = 1 where id = '$insid'"); - } - $this->app->DB->Update("UPDATE shopimport_auftraege set shopid = '$id' where id = '$insid'"); - $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '".$this->app->DB->real_escape_string($letzteonlinebestellnummer)."' where id = '$insid'"); - } - } - if($demomodus!='1') - { - $this->app->remote->RemoteDeleteAuftrag($id,$auftrag,$letzteonlinebestellnummer); - } - elseif($demomodus == '1') - { - break; - } - unset($letzteonlinebestellnummer); - - } - if(!$demomodus) - { - if(empty($maxtime)) - { - $maxtime = strtotime(date('Y-m-d H:i:s')); - } - $datumvon = strtotime($zeitraum['datumvon']); - $datumbis = strtotime($zeitraum['datumbis']); - $tmpdatumvon = strtotime($zeitraum['tmpdatumvon']); - $tmpdatumbis = strtotime($zeitraum['tmpdatumbis']); - if($datumvon < 0){ - $datumvon = 0; - } - if($datumbis < 0){ - $datumbis = 0; - } - if($tmpdatumvon < 0){ - $tmpdatumvon = 0; - } - if($tmpdatumbis < 0) - { - $tmpdatumbis = 0; - } - $this->app->DB->Update("UPDATE shopexport SET datumvon = '".date('Y-m-d H:i:s',$maxtime)."', tmpdatumbis = '0000-00-00' WHERE id = '$id' LIMIT 1"); - } - }else{ - if(!$demomodus) - { - if(is_array($result) && !empty($result['zeitstempel'])) - { - $this->app->DB->Update("UPDATE shopexport SET datumvon = '".date('Y-m-d H:i:s',strtotime($result['zeitstempel']))."', tmpdatumbis = '0000-00-00' WHERE id = '$id' AND datumvon < '".date('Y-m-d H:i:s',strtotime($result['zeitstempel']))."' LIMIT 1"); - } - if(empty($maxtime)) - { - $maxtime = strtotime(date('Y-m-d H:i:s')); - } - $datumvon = strtotime($zeitraum['datumvon']); - $datumbis = strtotime($zeitraum['datumbis']); - $tmpdatumvon = strtotime($zeitraum['tmpdatumvon']); - $tmpdatumbis = strtotime($zeitraum['tmpdatumbis']); - if($datumvon < 0){ - $datumvon = 0; - } - if($datumbis < 0){ - $datumbis = 0; - } - if($tmpdatumvon < 0){ - $tmpdatumvon = 0; - } - if($tmpdatumbis < 0){ - $tmpdatumbis = 0; - } - if($tmpdatumbis) - { - $this->app->DB->Update("UPDATE shopexport SET tmpdatumbis = '0000-00-00' WHERE id = '$id' LIMIT 1"); - } - } - } - }else{ - $gesamtanzahl = $this->app->remote->RemoteGetAuftraegeAnzahl($id); - $maxmanuell = (int)$this->app->DB->Select("SELECT maxmanuell FROM shopexport WHERE id = '$id' LIMIT 1"); - if($maxmanuell <= 0){ - $maxmanuell = 100; - } - if($gesamtanzahl > $maxmanuell){ - $gesamtanzahl = $maxmanuell; - } - if($einzelsync=='1' && $gesamtanzahl > 1 && $maxmanuell <= 1){ - $gesamtanzahl = 1; - } - if($gesamtanzahl > 0) - { - for($i=0;$i<$gesamtanzahl;$i++) - { - //import au - $result = $this->app->remote->RemoteGetAuftrag($id); - - if(is_array($result)) - { - $auftrag = $result[0]['id']; - if(isset($result[0]['warenkorbjson'])) - { - $isjson = true; - $tmpwarenkorb = json_decode(base64_decode($result[0]['warenkorbjson']), true); - }else{ - $isjson = false; - $tmpwarenkorb = unserialize(base64_decode($result[0]['warenkorb'])); - } - $onlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; - if(!empty($tmpwarenkorb['useorderid']) || (!is_numeric($onlinebestellnummer) && trim((String)$onlinebestellnummer) !== '')) - { - $onlinebestellnummer = $tmpwarenkorb['auftrag']; - } - if($holealle && $onlinebestellnummer) - { - $neue_nummer = (int)$onlinebestellnummer+1; - $this->app->DB->Update("UPDATE shopexport SET ab_nummer = '$neue_nummer' WHERE id = '$id'"); - } - $sessionid = $result[0]['sessionid']; - if($isjson) - { - $warenkorb = $result[0]['warenkorbjson']; - }else{ - $warenkorb = $result[0]['warenkorb']; - } - $logdatei = $result[0]['logdatei']; - if(empty($logdatei)) - { - $logdatei = date('Y-m-d H:i:s'); - } - $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); - if(!empty($tmpwarenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '".(int)$tmpwarenkorb['projekt']."' LIMIT 1")) - { - $projekt = (int)$tmpwarenkorb['projekt']; - } - if(isset($tmpwarenkorb['subshop']) && $tmpwarenkorb['subshop']) - { - $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '$id' AND aktiv = 1 AND subshopkennung = '".$this->app->DB->real_escape_string($tmpwarenkorb['subshop'])."' LIMIT 1"); - if($subshopprojekt) - { - $projekt = $subshopprojekt; - } - } - unset($tmpwarenkorb); - - $standardcheck = true; - $modulename = $this->app->DB->Select( - sprintf( - "SELECT modulename FROM shopexport WHERE id = %d AND modulename <> '' AND (shoptyp = 'intern')", - $id - ) - ); - $shopIds = [$id]; - $otherModules= empty($modulename)?null: - $this->app->DB->SelectFirstCols( - sprintf( - "SELECT id - FROM shopexport - WHERE modulename = '%s' AND id <> %d", - $this->app->DB->real_escape_string($modulename), $id + $id, $id ) - ); - if(!empty($otherModules) && $this->app->erp->ModulVorhanden($modulename)) { - $obj = $this->app->erp->LoadModul($modulename); - if(!empty($obj) && method_exists($obj, 'EinstellungenStruktur')){ - $konfiguration = $obj->EinstellungenStruktur(); - if($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) { - $shopIds = array_merge([$id], $otherModules); - $standardcheck = false; - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - } - } + ); + $deletedRows = (int) $this->app->DB->affected_rows(); + $this->app->Tpl->Add('IMPORT', '
    Es wurden ' . $deletedRows . ' bereits importierte Datensätze entfernt.
    '); + } + $runningcronjob = $this->app->DB->Select("SELECT id FROM prozessstarter WHERE parameter = 'shopimport' AND aktiv=1 AND mutex = 1 AND UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(letzteausfuerhung) < 300 LIMIT 1"); + if ($runningcronjob && !$showonly) { + $this->app->Location->execute('index.php?module=shopimport&action=list'); + } + if (!is_numeric($id)) { + $id = $this->app->Secure->GetGET('id'); + } + + $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id'"); + $projekt = $shopexportarr['projekt']; //$this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id'"); + $demomodus = $shopexportarr['demomodus']; //$this->app->DB->Select("SELECT demomodus FROM shopexport WHERE id='$id'"); + $einzelsync = $shopexportarr['einzelsync']; //$this->app->DB->Select("SELECT einzelsync FROM shopexport WHERE id='$id'"); + $utf8codierung = $shopexportarr['utf8codierung']; //$this->app->DB->Select("SELECT utf8codierung FROM shopexport WHERE id='$id'"); + + if (!$returncount) { + $this->app->erp->Headlines('Shopimport'); + $this->app->erp->MenuEintrag('index.php?module=shopimport&action=list', 'Zurück zur Übersicht'); + } + //name, strasse, ort, plz und kundenummer, emailadresse oder bestellung kam von login account ==> Kunde aus DB verwenden + //ACHTUNG Lieferadresse immer aus Auftrag!!! aber Lieferadresse extra bei Kunden anlegen + if ($this->app->Secure->GetPOST('submit') != '') { + $auftraege = $this->app->Secure->GetPOST('auftrag'); + $kundennummer = $this->app->Secure->GetPOST('kundennummer'); + $import = $this->app->Secure->GetPOST('import'); + $import_kundennummer = $this->app->Secure->GetPOST('import_kundennummer'); + + $success_import = 0; + $insgs_import = 0; + $unbekanntezahlungsweisen = null; + $cauftraege = $auftraege ? count($auftraege) : 0; + for ($i = 0; $i < $cauftraege; $i++) { + $adresse = ''; + $shopimportid = $auftraege[$i]; + $shopid = $this->app->DB->Select("SELECT shopid FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); + if ($shopid) { + $demomodus = $this->app->DB->Select("SELECT demomodus FROM shopexport WHERE id='$shopid'"); + $einzelsync = $this->app->DB->Select("SELECT einzelsync FROM shopexport WHERE id='$shopid'"); + $utf8codierung = $this->app->DB->Select("SELECT utf8codierung FROM shopexport WHERE id='$shopid'"); } - $checkdoppeltimported = $this->app->DB->Select( - sprintf( - "SELECT id + $projekt = $this->app->DB->Select("SELECT projekt FROM shopimport_auftraege WHERE id='$shopimportid' LIMIT 1"); + if ($import[$shopimportid] === 'warten') { + + } else if ($import[$shopimportid] === 'muell') { + $this->setShopImportedOrderTrash($shopimportid); + } else if ($import[$shopimportid] === 'import') { + + $res = $this->importShopOrder($shopimportid, $utf8codierung, $kundennummer[$shopimportid], $import_kundennummer[$shopimportid], $unbekanntezahlungsweisen); + if ($res['codingerror']) { + $umlautefehler = true; + } + if ($res['success']) { + $success_import += $res['success']; + } + $insgs_import++; + } + } // ende for + + + if ($unbekanntezahlungsweisen) { + $meldung = ''; + foreach ($unbekanntezahlungsweisen as $k => $v) { + $meldung .= 'Unbekannte Zahlungsart: ' . $k . ' in Bestellung(en): '; + $first = true; + foreach ($v as $k2 => $v2) { + if (!$first) { + $meldung .= ', '; + } + $first = false; + $meldung .= $v2['bestellnummer']; + } + $meldung .= "
    \r\n"; + } + + if (isset($this->app->User) && method_exists($this->app->User, 'GetID') && $this->app->User->GetID()) { + $this->app->erp->EventMitSystemLog($this->app->User->GetID(), $meldung, -1, '', 'warning', 1); + } + } + if (!empty($umlautefehler)) { + $msg = $this->app->erp->base64_url_encode("
    $success_import" . ($success_import != $insgs_import ? " von $insgs_import " : '') . " Aufträge importiert. Aufträge mit Kodierungsprobleme. Bitte prüfen Sie sie UTF8-Einstellung in der Shopschnittstelle!
    "); + } else { + $msg = $this->app->erp->base64_url_encode("
    $success_import" . ($success_import != $insgs_import ? " von $insgs_import " : '') . " Aufträge importiert!
    "); + } + $this->app->Location->execute('index.php?module=shopimport&action=list&msg=' . $msg); + } + + + if (!$showonly && $id) { + try { + $pageContents = $this->app->remote->RemoteConnection($id); + } catch (Exception $e) { + $pageContents = $e->getMessage(); + } + if ($pageContents === 'success') { + $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); + $holealle = $shopexportarr['holealle']; //$this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$id' LIMIT 1"); + $statusaendern = $shopexportarr['nummersyncstatusaendern']; //$this->app->DB->Select("SELECT nummersyncstatusaendern FROM shopexport WHERE id = '$id' LIMIT 1"); + $auftragabgleich = $shopexportarr['auftragabgleich']; //$this->app->DB->Select("SELECT auftragabgleich FROM shopexport WHERE id = '$id' LIMIT 1"); + $zeitraum = array('datumvon' => $shopexportarr['datumvon'], 'datumbis' => $shopexportarr['datumbis'], 'tmpdatumvon' => $shopexportarr['tmpdatumvon'], 'tmpdatumbis' => $shopexportarr['tmpdatumbis'], 'anzgleichzeitig' => $shopexportarr['anzgleichzeitig']); + //$this->app->DB->SelectArr("SELECT datumvon, datumbis,tmpdatumvon, tmpdatumbis, anzgleichzeitig FROM shopexport WHERE id = '$id' LIMIT 1"); + /* if(!empty($zeitraum)) + { + $zeitraum = reset($zeitraum); + } */ + $anzgleichzeitig = 1; + if (isset($zeitraum['anzgleichzeitig'])) { + $anzgleichzeitig = (int) $zeitraum['anzgleichzeitig']; + } + + if ($anzgleichzeitig > 1) { + $result = $this->app->remote->RemoteGetAuftrag($id); + if (!empty($result) && is_array($result) && isset($result[0])) { + $maxtime = false; + $mintime = false; + $gesamtanzahl = (!empty($result) ? count($result) : 0); + for ($i = 0; $i < $gesamtanzahl; $i++) { + $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); + $auftrag = $result[$i]['id']; + if (isset($result[$i]['warenkorbjson'])) { + $isjson = true; + $tmpwarenkorb = json_decode(base64_decode($result[$i]['warenkorbjson']), true); + } else { + $isjson = false; + $tmpwarenkorb = unserialize(base64_decode($result[$i]['warenkorb'])); + } + if (!empty($tmpwarenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '" . (int) $tmpwarenkorb['projekt'] . "' LIMIT 1")) { + $projekt = (int) $tmpwarenkorb['projekt']; + } + if (!empty($tmpwarenkorb['zeitstempel'])) { + $time = strtotime($tmpwarenkorb['zeitstempel']); + if ($time < 0) { + $time = 0; + } + if ($maxtime === false) { + $maxtime = $time; + } + if ($mintime === false) { + $mintime = $time; + } + if ($time > $maxtime) { + $maxtime = $time; + } + if ($time < $mintime) { + $mintime = $time; + } + } + $onlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; + if (!empty($tmpwarenkorb['useorderid']) || + (!is_numeric($onlinebestellnummer) && trim((String) $onlinebestellnummer) !== '')) { + $onlinebestellnummer = $tmpwarenkorb['auftrag']; + } + + if ($holealle && $onlinebestellnummer) { + $neue_nummer = (int) $onlinebestellnummer + 1; + $this->app->DB->Update("UPDATE shopexport SET ab_nummer = '$neue_nummer' WHERE id = '$id'"); + } + $sessionid = isset($result[$i]['sessionid']) ? $result[$i]['sessionid'] : ''; + if ($isjson) { + $warenkorb = $result[$i]['warenkorbjson']; + } else { + $warenkorb = $result[$i]['warenkorb']; + } + $logdatei = isset($result[$i]['logdatei']) ? $result[$i]['logdatei'] : null; + if (empty($logdatei)) { + $logdatei = date('Y-m-d H:i:s'); + } + if (isset($tmpwarenkorb['subshop']) && $tmpwarenkorb['subshop']) { + $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '$id' AND aktiv = 1 AND subshopkennung = '" . $this->app->DB->real_escape_string($tmpwarenkorb['subshop']) . "' LIMIT 1"); + if ($subshopprojekt) { + $projekt = $subshopprojekt; + } + } + $letzteonlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; + unset($tmpwarenkorb); + + //globalerauftragsnummernkreis + $standardcheck = true; + $modulename = $this->app->DB->Select( + sprintf( + "SELECT modulename FROM shopexport WHERE id = %d AND modulename <> '' AND (shoptyp = 'intern')", + $id + ) + ); + $shopIds = [$id]; + $otherModules = empty($modulename) ? null : + $this->app->DB->SelectFirstCols( + sprintf( + "SELECT id + FROM shopexport + WHERE modulename = '%s' AND id <> %d", + $this->app->DB->real_escape_string($modulename), $id + ) + ); + if (!empty($otherModules) && $this->app->erp->ModulVorhanden($modulename)) { + $obj = $this->app->erp->LoadModul($modulename); + if (!empty($obj) && method_exists($obj, 'EinstellungenStruktur')) { + $konfiguration = $obj->EinstellungenStruktur(); + if ($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) { + $shopIds = array_merge([$id], $otherModules); + $standardcheck = false; + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + } + } + } + $checkdoppeltimported = $this->app->DB->Select( + sprintf( + "SELECT id FROM shopimport_auftraege WHERE extid = '%s' and shopid IN (%s) AND trash = 0 AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) LIMIT 1", - $this->app->DB->real_escape_string($auftrag), implode(',', $shopIds) - ) - ); - - /*if($standardcheck){*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '" . $this->app->DB->real_escape_string($auftrag) . "' and shopid = '$id' and warenkorb = '" . $this->app->DB->real_escape_string($warenkorb) . "' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1");*/ - /*$checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '" . $this->app->DB->real_escape_string($auftrag) . "' and shopid = '$id' AND trash = 0 - AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) - LIMIT 1"); - }*/ - - $insid = null; - if($demomodus == '1') - { - $checkdoppeltimported = null; - } - if(!$checkdoppeltimported) - { - $this->app->DB->Insert("INSERT INTO shopimport_auftraege (id,extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei) - VALUES('','$auftrag','$sessionid','$warenkorb','0','$projekt','".$this->app->User->GetName()."','$logdatei')"); - $insid = $this->app->DB->GetInsertID(); - if($insid){ - $this->app->DB->Update("UPDATE shopimport_auftraege set shopid = '$id' where id = '$insid'"); - $this->app->DB->Update("UPDATE shopimport_auftraege set logdatei = now() where id = '$insid' AND logdatei = '0000-00-00' OR logdatei > now()"); - if($isjson){ - $this->app->DB->Update("UPDATE shopimport_auftraege set jsonencoded = 1 where id = '$insid'"); + $this->app->DB->real_escape_string($auftrag), implode(',', $shopIds) + ) + ); + /* if($standardcheck) + { */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and shopid = '$id' and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and shopid = '$id' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); + } */ + $insid = null; + if (empty($checkdoppeltimported)) { + $this->app->DB->Insert("INSERT INTO shopimport_auftraege (id,extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei) + VALUES('','" . $this->app->DB->real_escape_string($auftrag) . "','" . $this->app->DB->real_escape_string($sessionid) . "','" . $this->app->DB->real_escape_string($warenkorb) . "','0','$projekt','" . $this->app->DB->real_escape_string($this->app->User->GetName()) . "','" . $this->app->DB->real_escape_string($logdatei) . "')"); + $insid = $this->app->DB->GetInsertID(); + if ($insid) { + if ($isjson) { + $this->app->DB->Update("UPDATE shopimport_auftraege set jsonencoded = 1 where id = '$insid'"); + } + $this->app->DB->Update("UPDATE shopimport_auftraege set shopid = '$id' where id = '$insid'"); + $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '" . $this->app->DB->real_escape_string($letzteonlinebestellnummer) . "' where id = '$insid'"); + } + } + if ($demomodus != '1') { + $this->app->remote->RemoteDeleteAuftrag($id, $auftrag, $letzteonlinebestellnummer); + } elseif ($demomodus == '1') { + break; + } + unset($letzteonlinebestellnummer); + } + if (!$demomodus) { + if (empty($maxtime)) { + $maxtime = strtotime(date('Y-m-d H:i:s')); + } + $datumvon = strtotime($zeitraum['datumvon']); + $datumbis = strtotime($zeitraum['datumbis']); + $tmpdatumvon = strtotime($zeitraum['tmpdatumvon']); + $tmpdatumbis = strtotime($zeitraum['tmpdatumbis']); + if ($datumvon < 0) { + $datumvon = 0; + } + if ($datumbis < 0) { + $datumbis = 0; + } + if ($tmpdatumvon < 0) { + $tmpdatumvon = 0; + } + if ($tmpdatumbis < 0) { + $tmpdatumbis = 0; + } + $this->app->DB->Update("UPDATE shopexport SET datumvon = '" . date('Y-m-d H:i:s', $maxtime) . "', tmpdatumbis = '0000-00-00' WHERE id = '$id' LIMIT 1"); + } + } else { + if (!$demomodus) { + if (is_array($result) && !empty($result['zeitstempel'])) { + $this->app->DB->Update("UPDATE shopexport SET datumvon = '" . date('Y-m-d H:i:s', strtotime($result['zeitstempel'])) . "', tmpdatumbis = '0000-00-00' WHERE id = '$id' AND datumvon < '" . date('Y-m-d H:i:s', strtotime($result['zeitstempel'])) . "' LIMIT 1"); + } + if (empty($maxtime)) { + $maxtime = strtotime(date('Y-m-d H:i:s')); + } + $datumvon = strtotime($zeitraum['datumvon']); + $datumbis = strtotime($zeitraum['datumbis']); + $tmpdatumvon = strtotime($zeitraum['tmpdatumvon']); + $tmpdatumbis = strtotime($zeitraum['tmpdatumbis']); + if ($datumvon < 0) { + $datumvon = 0; + } + if ($datumbis < 0) { + $datumbis = 0; + } + if ($tmpdatumvon < 0) { + $tmpdatumvon = 0; + } + if ($tmpdatumbis < 0) { + $tmpdatumbis = 0; + } + if ($tmpdatumbis) { + $this->app->DB->Update("UPDATE shopexport SET tmpdatumbis = '0000-00-00' WHERE id = '$id' LIMIT 1"); + } + } } - } - } + } else { + $gesamtanzahl = $this->app->remote->RemoteGetAuftraegeAnzahl($id); + $maxmanuell = (int) $this->app->DB->Select("SELECT maxmanuell FROM shopexport WHERE id = '$id' LIMIT 1"); + if ($maxmanuell <= 0) { + $maxmanuell = 100; + } + if ($gesamtanzahl > $maxmanuell) { + $gesamtanzahl = $maxmanuell; + } + if ($einzelsync == '1' && $gesamtanzahl > 1 && $maxmanuell <= 1) { + $gesamtanzahl = 1; + } + if ($gesamtanzahl > 0) { + for ($i = 0; $i < $gesamtanzahl; $i++) { + //import au + $result = $this->app->remote->RemoteGetAuftrag($id); - if($demomodus!='1') - { - $this->app->remote->RemoteDeleteAuftrag($id,$auftrag); + if (is_array($result)) { + $auftrag = $result[0]['id']; + if (isset($result[0]['warenkorbjson'])) { + $isjson = true; + $tmpwarenkorb = json_decode(base64_decode($result[0]['warenkorbjson']), true); + } else { + $isjson = false; + $tmpwarenkorb = unserialize(base64_decode($result[0]['warenkorb'])); + } + $onlinebestellnummer = $tmpwarenkorb['onlinebestellnummer']; + if (!empty($tmpwarenkorb['useorderid']) || (!is_numeric($onlinebestellnummer) && trim((String) $onlinebestellnummer) !== '')) { + $onlinebestellnummer = $tmpwarenkorb['auftrag']; + } + if ($holealle && $onlinebestellnummer) { + $neue_nummer = (int) $onlinebestellnummer + 1; + $this->app->DB->Update("UPDATE shopexport SET ab_nummer = '$neue_nummer' WHERE id = '$id'"); + } + $sessionid = $result[0]['sessionid']; + if ($isjson) { + $warenkorb = $result[0]['warenkorbjson']; + } else { + $warenkorb = $result[0]['warenkorb']; + } + $logdatei = $result[0]['logdatei']; + if (empty($logdatei)) { + $logdatei = date('Y-m-d H:i:s'); + } + $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '$id' LIMIT 1"); + if (!empty($tmpwarenkorb['projekt']) && $this->app->DB->Select("SELECT id FROM projekt WHERE id = '" . (int) $tmpwarenkorb['projekt'] . "' LIMIT 1")) { + $projekt = (int) $tmpwarenkorb['projekt']; + } + if (isset($tmpwarenkorb['subshop']) && $tmpwarenkorb['subshop']) { + $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '$id' AND aktiv = 1 AND subshopkennung = '" . $this->app->DB->real_escape_string($tmpwarenkorb['subshop']) . "' LIMIT 1"); + if ($subshopprojekt) { + $projekt = $subshopprojekt; + } + } + unset($tmpwarenkorb); + + $standardcheck = true; + $modulename = $this->app->DB->Select( + sprintf( + "SELECT modulename FROM shopexport WHERE id = %d AND modulename <> '' AND (shoptyp = 'intern')", + $id + ) + ); + $shopIds = [$id]; + $otherModules = empty($modulename) ? null : + $this->app->DB->SelectFirstCols( + sprintf( + "SELECT id + FROM shopexport + WHERE modulename = '%s' AND id <> %d", + $this->app->DB->real_escape_string($modulename), $id + ) + ); + if (!empty($otherModules) && $this->app->erp->ModulVorhanden($modulename)) { + $obj = $this->app->erp->LoadModul($modulename); + if (!empty($obj) && method_exists($obj, 'EinstellungenStruktur')) { + $konfiguration = $obj->EinstellungenStruktur(); + if ($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) { + $shopIds = array_merge([$id], $otherModules); + $standardcheck = false; + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') and warenkorb = '".$this->app->DB->real_escape_string($warenkorb)."' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '".$this->app->DB->real_escape_string($auftrag)."' and ((modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern') OR shopid = '$id') AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + } + } + } + $checkdoppeltimported = $this->app->DB->Select( + sprintf( + "SELECT id + FROM shopimport_auftraege + WHERE extid = '%s' and shopid IN (%s) AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1", + $this->app->DB->real_escape_string($auftrag), implode(',', $shopIds) + ) + ); + + /* if($standardcheck){ */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '" . $this->app->DB->real_escape_string($auftrag) . "' and shopid = '$id' and warenkorb = '" . $this->app->DB->real_escape_string($warenkorb) . "' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); */ + /* $checkdoppeltimported = $this->app->DB->Select("SELECT id FROM shopimport_auftraege WHERE extid = '" . $this->app->DB->real_escape_string($auftrag) . "' and shopid = '$id' AND trash = 0 + AND (imported = 0 OR (imported = 1 AND DATE_SUB(NOW(),INTERVAL 10 MINUTE)>logdatei )) + LIMIT 1"); + } */ + + $insid = null; + if ($demomodus == '1') { + $checkdoppeltimported = null; + } + if (!$checkdoppeltimported) { + $this->app->DB->Insert("INSERT INTO shopimport_auftraege (id,extid,sessionid,warenkorb,imported,projekt,bearbeiter,logdatei) + VALUES('','$auftrag','$sessionid','$warenkorb','0','$projekt','" . $this->app->User->GetName() . "','$logdatei')"); + $insid = $this->app->DB->GetInsertID(); + if ($insid) { + $this->app->DB->Update("UPDATE shopimport_auftraege set shopid = '$id' where id = '$insid'"); + $this->app->DB->Update("UPDATE shopimport_auftraege set logdatei = now() where id = '$insid' AND logdatei = '0000-00-00' OR logdatei > now()"); + if ($isjson) { + $this->app->DB->Update("UPDATE shopimport_auftraege set jsonencoded = 1 where id = '$insid'"); + } + } + } + + if ($demomodus != '1') { + $this->app->remote->RemoteDeleteAuftrag($id, $auftrag); + } elseif ($demomodus == '1') { + $i = $gesamtanzahl; + } + } + } + } } - elseif($demomodus == '1') - { - $i=$gesamtanzahl; + } else { + if (!$returncount) { + $this->app->Tpl->Set('IMPORT', "
    Verbindungsprobleme! Bitte Administrator kontaktieren! ($pageContents)
    "); + } else { + $this->error = "
    Verbindungsprobleme! Bitte Administrator kontaktieren! ($pageContents)
    "; } - } } - } } - } else { - if(!$returncount) - { - $this->app->Tpl->Set('IMPORT',"
    Verbindungsprobleme! Bitte Administrator kontaktieren! ($pageContents)
    "); - }else { - $this->error = "
    Verbindungsprobleme! Bitte Administrator kontaktieren! ($pageContents)
    "; + + if (!$returncount) { + $this->drawShopOrderTable($deletedRows); + } else { + return $count + (is_numeric($gesamtanzahl) ? $gesamtanzahl : 0); } - } } - if(!$returncount) - { - $this->drawShopOrderTable($deletedRows); - } else - { - return $count+(is_numeric($gesamtanzahl)?$gesamtanzahl:0); - } - } - - /** - * @param array $arr - * - * @return array - */ - public function getCustomerNumberFromShopCart($arr) - { - $validkundennummer = ''; - if(!empty($arr['jsonencoded'])) - { - $warenkorb = json_decode(base64_decode($arr['warenkorb']),true); - }else{ - $warenkorb = unserialize(base64_decode($arr['warenkorb'])); - } - foreach($warenkorb as $key=>$value) { - if(is_string($warenkorb[$key])){ - $warenkorb[$key] = trim($warenkorb[$key]); - } - } - foreach($warenkorb as $k => $v) { - $warenkorb[$k] = $this->app->erp->fixeUmlaute($v); - } - - $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '".$arr['shopid']."' LIMIT 1"); - $adresseprojekt = ''; - if($kundenurvonprojekt) - { - $adresseprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '".$arr['shopid']."' LIMIT 1"); - } - if(!empty($warenkorb['kundennummer'])) { - $validkundennummer = $this->app->DB->Select( - "SELECT kundennummer - FROM adresse - WHERE kundennummer='".$warenkorb['kundennummer']."' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' - LIMIT 1" - ); - } - if(isset($warenkorb['subshop']) && $warenkorb['subshop']) - { - $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '".$arr['shopid']."' AND aktiv = 1 AND subshopkennung = '".$this->app->DB->real_escape_string($warenkorb['subshop'])."' LIMIT 1"); - if($subshopprojekt) - { - if(!$kundenurvonprojekt) - { - $adresseprojekt = $subshopprojekt; + /** + * @param array $arr + * + * @return array + */ + public function getCustomerNumberFromShopCart($arr) { + $validkundennummer = ''; + if (!empty($arr['jsonencoded'])) { + $warenkorb = json_decode(base64_decode($arr['warenkorb']), true); + } else { + $warenkorb = unserialize(base64_decode($arr['warenkorb'])); } - $arr['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); - } - } - if($kundenurvonprojekt) - { - $adresseprojekt = " AND projekt = '".$adresseprojekt."' "; - }else { - $adresseprojekt = ''; - } - - $checkid = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE `name`='".$this->app->DB->real_escape_string($warenkorb['name'])."' AND abteilung='".$this->app->DB->real_escape_string($warenkorb['abteilung'])."' - AND strasse='".$this->app->DB->real_escape_string($warenkorb['strasse'])."' AND plz='".$this->app->DB->real_escape_string($warenkorb['plz'])."' AND ort='".$this->app->DB->real_escape_string($warenkorb['ort'])."' AND kundennummer <> '' AND geloescht!=1 $adresseprojekt - ORDER BY email='".$this->app->DB->real_escape_string($warenkorb['email'])."' DESC - LIMIT 1"); - - - if($warenkorb['email'] != '') - { - if($warenkorb['email']!=='amazon_import_bounce@nfxmedia.de') - { - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE email='".$warenkorb['email']."' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); - } - if((String)$checkidemail === ''){ - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name LIKE '" . $warenkorb['name'] . "' AND ort LIKE '" . $warenkorb['ort'] . "' AND geloescht!=1 $adresseprojekt AND kundennummer <> '' LIMIT 1"); - } - }else{ - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name='".$this->app->DB->real_escape_string($warenkorb['name'])."' AND strasse='".$this->app->DB->real_escape_string($warenkorb['strasse'])."' AND plz='".$this->app->DB->real_escape_string($warenkorb['plz'])."' AND ort='".$this->app->DB->real_escape_string($warenkorb['ort'])."' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); - } - - if($warenkorb['kundennummer']!='' && !empty($validkundennummer) && $validkundennummer==$warenkorb['kundennummer']) - { - $kdrnummer = $warenkorb['kundennummer']; - } - elseif ($checkid!='') - { - $kdrnummer = $checkid; - } - elseif ($checkidemail!='') - { - $kdrnummer = $checkidemail; - } - else { - $kdrnummer=''; - $checkidemail=''; - } - - return [$checkidemail, $kdrnummer]; - } - - public function drawShopOrderTable($deletedRows) { - $checkglobal = null; - $htmltable = new HTMLTable(0,'100%','',3,1,'font-size:85%'); - $htmltable->AddRowAsHeading(array('Import','Müll','Später','Projekt','Internet','Name','Bemerkung','Strasse','PLZ','Ort','Kd.Nr.','vorhanden','Land','Betrag','Offen','Zahlung','Partner')); - $htmltable->ChangingRowColors('#e0e0e0','#fff'); - - $shopid = $this->app->Secure->GetGET('shopid'); - $where = ''; - if(!empty($shopid)){ - $where = 'AND sa.shopid='.(int)$shopid; - } - - $bestellnummer = $this->app->Secure->GetGET('bestellnummer'); - if(!empty($bestellnummer)){ - $bestellnummer = preg_replace('/[^\w-]/', '', $bestellnummer); - $where .= " AND sa.bestellnummer='$bestellnummer'"; - } - - $arr = $this->app->DB->SelectArr("SELECT sa.*, p.abkuerzung FROM shopimport_auftraege sa left join projekt p on sa.projekt = p.id WHERE sa.imported='0' AND sa.trash='0' $where ORDER BY sa.logdatei LIMIT 100"); - if(is_array($arr) && (!empty($arr)?count($arr):0) > 0) - { - - //Alte Auftraege prüfen - $alteauftraegeohnebestellnummer = $this->app->DB->Query("SELECT sa.* FROM shopimport_auftraege sa WHERE isnull(bestellnummer) AND sa.trash='0' LIMIT 100"); - while($row = $this->app->DB->Fetch_Assoc($alteauftraegeohnebestellnummer)) - { - if($row['warenkorb'] != '') - { - if(!empty($row['jsonencoded'])) - { - $warenkorb = json_decode(base64_decode($row['warenkorb']),true); - }else{ - $warenkorb = unserialize(base64_decode($row['warenkorb'])); - } - $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '".(isset($warenkorb['onlinebestellnummer'])?$warenkorb['onlinebestellnummer']:'')."' where id = '".$row['id']."'"); - }else{ - $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '' where id = '".$row['id']."'"); - } - } - $this->app->DB->free($alteauftraegeohnebestellnummer); - - $unbekanntezahlungsweisen = null; - $enthaeltdoppeltenummern = false; - $carr = $arr?count($arr):0; - for($i=0;$i<$carr;$i++) - { - if(empty($checkglobal) || !isset($checkglobal[$arr[$i]['shopid']])) - { - $checkglobal[$arr[$i]['shopid']] = null; - - if(($modulename = $this->app->DB->Select("SELECT modulename FROM shopexport WHERE id = '".$arr[$i]['shopid']."' AND modulename <> '' AND shoptyp = 'intern'")) - && $this->app->DB->Select("SELECT id FROM shopexport WHERE modulename = '".$this->app->DB->real_escape_string($modulename)."' AND id <> '".$arr[$i]['shopid']."' LIMIT 1") - ) - { - $shopsintern = $this->app->DB->SelectArr("SELECT id FROM shopexport WHERE id = '".$arr[$i]['shopid']."' OR (modulename = '".$this->app->DB->real_escape_string($modulename)."' AND shoptyp = 'intern')"); - if($shopsintern) - { - foreach($shopsintern as $vs) - { - $checkglobal[$arr[$i]['shopid']][] = " shopid = '". $vs['id']."' "; - } - if($this->app->erp->ModulVorhanden($modulename)) - { - /** @var ShopimporterBase $obj */ - $obj = $this->app->erp->LoadModul($modulename); - if($obj && method_exists($obj, 'EinstellungenStruktur')){ - $konfiguration = $obj->EinstellungenStruktur(); - if($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) - { - - }else - { - $checkglobal[$arr[$i]['shopid']] = null; - } - }else { - $checkglobal[$arr[$i]['shopid']] = null; - } - }else { - $checkglobal[$arr[$i]['shopid']] = null; - } + foreach ($warenkorb as $key => $value) { + if (is_string($warenkorb[$key])) { + $warenkorb[$key] = trim($warenkorb[$key]); } - } } - } + foreach ($warenkorb as $k => $v) { + $warenkorb[$k] = $this->app->erp->fixeUmlaute($v); + } - $carr = $arr?count($arr):0; - for($i=0;$i<$carr;$i++) - { - $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '".$arr[$i]['shopid']."' LIMIT 1"); - $auftraegeaufspaeter = $this->app->DB->Select("SELECT auftraegeaufspaeter FROM shopexport WHERE id='".$arr[$i]['shopid']."'"); - if(!empty($arr[$i]['jsonencoded'])) - { - $warenkorb = json_decode(base64_decode($arr[$i]['warenkorb']),true); - }else{ - $warenkorb = unserialize(base64_decode($arr[$i]['warenkorb'])); - } - foreach($warenkorb as $key=>$value) { - if(is_string($warenkorb[$key])){ - $warenkorb[$key] = trim($warenkorb[$key]); - } - } - foreach($warenkorb as $k => $v) { - $warenkorb[$k] = $this->app->erp->fixeUmlaute($v); - } - $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '".$arr[$i]['shopid']."' LIMIT 1"); + $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '" . $arr['shopid'] . "' LIMIT 1"); $adresseprojekt = ''; - if($kundenurvonprojekt) - { - $adresseprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '".$arr[$i]['shopid']."' LIMIT 1"); + if ($kundenurvonprojekt) { + $adresseprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '" . $arr['shopid'] . "' LIMIT 1"); } - if(isset($warenkorb['subshop']) && $warenkorb['subshop']) - { - $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '".$arr[$i]['shopid']."' AND aktiv = 1 AND subshopkennung = '".$this->app->DB->real_escape_string($warenkorb['subshop'])."' LIMIT 1"); - if($subshopprojekt) - { - if(!$kundenurvonprojekt) - { - $adresseprojekt = $subshopprojekt; + if (!empty($warenkorb['kundennummer'])) { + $validkundennummer = $this->app->DB->Select( + "SELECT kundennummer + FROM adresse + WHERE kundennummer='" . $warenkorb['kundennummer'] . "' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' + LIMIT 1" + ); + } + if (isset($warenkorb['subshop']) && $warenkorb['subshop']) { + $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '" . $arr['shopid'] . "' AND aktiv = 1 AND subshopkennung = '" . $this->app->DB->real_escape_string($warenkorb['subshop']) . "' LIMIT 1"); + if ($subshopprojekt) { + if (!$kundenurvonprojekt) { + $adresseprojekt = $subshopprojekt; + } + $arr['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); } - $arr[$i]['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); - } } - if($kundenurvonprojekt) - { - $adresseprojekt = " AND projekt = '".$adresseprojekt."' "; - }else { - $adresseprojekt = ''; + if ($kundenurvonprojekt) { + $adresseprojekt = " AND projekt = '" . $adresseprojekt . "' "; + } else { + $adresseprojekt = ''; } - $checkid = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE `name`='".$this->app->DB->real_escape_string($warenkorb['name'])."' AND abteilung='".$this->app->DB->real_escape_string($warenkorb['abteilung'])."' - AND strasse='".$this->app->DB->real_escape_string($warenkorb['strasse'])."' AND plz='".$this->app->DB->real_escape_string($warenkorb['plz'])."' AND ort='".$this->app->DB->real_escape_string($warenkorb['ort'])."' AND kundennummer <> '' AND geloescht!=1 $adresseprojekt - ORDER BY email='".$this->app->DB->real_escape_string($warenkorb['email'])."' DESC + $checkid = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE `name`='" . $this->app->DB->real_escape_string($warenkorb['name']) . "' AND abteilung='" . $this->app->DB->real_escape_string($warenkorb['abteilung']) . "' + AND strasse='" . $this->app->DB->real_escape_string($warenkorb['strasse']) . "' AND plz='" . $this->app->DB->real_escape_string($warenkorb['plz']) . "' AND ort='" . $this->app->DB->real_escape_string($warenkorb['ort']) . "' AND kundennummer <> '' AND geloescht!=1 $adresseprojekt + ORDER BY email='" . $this->app->DB->real_escape_string($warenkorb['email']) . "' DESC LIMIT 1"); - - if($warenkorb['email'] != '') - { - if($warenkorb['email']!=='amazon_import_bounce@nfxmedia.de') - { - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE email='".$warenkorb['email']."' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); - } - if((String)$checkidemail === ''){ - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name LIKE '" . $warenkorb['name'] . "' AND ort LIKE '" . $warenkorb['ort'] . "' AND geloescht!=1 $adresseprojekt AND kundennummer <> '' LIMIT 1"); - } - }else{ - $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name='".$this->app->DB->real_escape_string($warenkorb['name'])."' AND strasse='".$this->app->DB->real_escape_string($warenkorb['strasse'])."' AND plz='".$this->app->DB->real_escape_string($warenkorb['plz'])."' AND ort='".$this->app->DB->real_escape_string($warenkorb['ort'])."' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); + if ($warenkorb['email'] != '') { + if ($warenkorb['email'] !== 'amazon_import_bounce@nfxmedia.de') { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE email='" . $warenkorb['email'] . "' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); + } + if ((String) $checkidemail === '') { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name LIKE '" . $warenkorb['name'] . "' AND ort LIKE '" . $warenkorb['ort'] . "' AND geloescht!=1 $adresseprojekt AND kundennummer <> '' LIMIT 1"); + } + } else { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name='" . $this->app->DB->real_escape_string($warenkorb['name']) . "' AND strasse='" . $this->app->DB->real_escape_string($warenkorb['strasse']) . "' AND plz='" . $this->app->DB->real_escape_string($warenkorb['plz']) . "' AND ort='" . $this->app->DB->real_escape_string($warenkorb['ort']) . "' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); } - if($warenkorb['kundennummer']!='' && !empty($validkundennummer) && $validkundennummer==$warenkorb['kundennummer']) - { - $kdrnummer = $warenkorb['kundennummer']; - $kdr_name = $this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' $adresseprojekt AND geloescht!=1 LIMIT 1"); - $email = $this->app->DB->Select("SELECT email FROM adresse WHERE kundennummer='$kdrnummer' $adresseprojekt AND geloescht!=1 LIMIT 1"); - $parts= explode("\n", wordwrap($kdr_name, 20, "\n")); - $kdr_name = $parts[0]; - $kdr_name = '
    '.$kdr_name.''; - $email = '
    '.$email.''; - - $kdr_strasse = $this->app->DB->Select("SELECT strasse FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); - $parts= explode("\n", wordwrap($kdr_strasse, 20, "\n")); - $kdr_strasse = $parts[0]; - $kdr_strasse = '
    '.$kdr_strasse.''; - - $kdr_plz = '
    '.$this->app->DB->Select("SELECT plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1").''; - $kdr_ort = '
    '.$this->app->DB->Select("SELECT ort FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1").''; - $checked=''; - } - elseif ($checkid!='') - { - $checked='checked'; - $kdrnummer = $checkid; - //$kdr_name = "
    ".$this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' AND firma='".$this->app->User->GetFirma()."' LIMIT 1").""; - $kdrArr = $this->app->DB->SelectRow("SELECT name, email, strasse, ort, plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); - $kdr_name = $kdrArr['name']; - $email = $kdrArr['email']; - $parts= explode("\n", wordwrap($kdr_name, 20, "\n")); - $kdr_name = $parts[0]; - $kdr_name = '
    '.$kdr_name.''; - $email = '
    '.$email.''; - - $kdr_strasse = $kdrArr['strasse']; - $parts= explode("\n", wordwrap($kdr_strasse, 20, "\n")); - $kdr_strasse = $parts[0]; - $kdr_strasse = '
    '.$kdr_strasse.''; - - $kdr_plz = '
    '.$kdrArr['plz'].''; - $kdr_ort = '
    '.$kdrArr['or'].''; - - } - elseif ($checkidemail!='') - { - $checked='checked'; - $kdrnummer = $checkidemail; - $warenkorb['kundennummer'] = $kdrnummer; - //$kdr_name = "
    ".$this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' AND firma='".$this->app->User->GetFirma()."' LIMIT 1").""; - $kdrArr = $this->app->DB->SelectRow("SELECT name, email, strasse, ort, plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); - $kdr_name = $kdrArr['name']; - $email = $kdrArr['email']; - $parts= explode("\n", wordwrap($kdr_name, 20, "\n")); - $kdr_name = $parts[0]; - $kdr_name = '
    '.$kdr_name.''; - $email = '
    '.$email.''; - - $kdr_strasse = $kdrArr['strasse']; - $parts= explode("\n", wordwrap($kdr_strasse, 40, "\n")); - $kdr_strasse = $parts[0]; - $kdr_strasse = '
    '.$kdr_strasse.''; - - $kdr_plz = '
    '.$kdrArr['plz'].''; - $kdr_ort = '
    '.$kdrArr['ort'].''; + if ($warenkorb['kundennummer'] != '' && !empty($validkundennummer) && $validkundennummer == $warenkorb['kundennummer']) { + $kdrnummer = $warenkorb['kundennummer']; + } elseif ($checkid != '') { + $kdrnummer = $checkid; + } elseif ($checkidemail != '') { + $kdrnummer = $checkidemail; + } else { + $kdrnummer = ''; + $checkidemail = ''; } + return [$checkidemail, $kdrnummer]; + } - else { - $checked=''; - $checkid=''; - $kdrnummer=''; - $checkidemail=''; - $kdr_name=''; - $kdr_strasse=''; - $kdr_plz=''; - $kdr_ort=''; - $email=''; - } - if($kdrnummer != ''){ - $kdr_addresse_id = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); - } - else { - $kdr_addresse_id = ''; + public function drawShopOrderTable($deletedRows) { + $checkglobal = null; + $htmltable = new HTMLTable(0, '100%', '', 3, 1, 'font-size:85%'); + $htmltable->AddRowAsHeading(array('Import', 'Müll', 'Später', 'Projekt', 'Internet', 'Name', 'Bemerkung', 'Strasse', 'PLZ', 'Ort', 'Kd.Nr.', 'vorhanden', 'Land', 'Betrag', 'Offen', 'Zahlung', 'Partner')); + $htmltable->ChangingRowColors('#e0e0e0', '#fff'); + + $shopid = $this->app->Secure->GetGET('shopid'); + $where = ''; + if (!empty($shopid)) { + $where = 'AND sa.shopid=' . (int) $shopid; + } + + $bestellnummer = $this->app->Secure->GetGET('bestellnummer'); + if (!empty($bestellnummer)) { + $bestellnummer = preg_replace('/[^\w-]/', '', $bestellnummer); + $where .= " AND sa.bestellnummer='$bestellnummer'"; + } + + $arr = $this->app->DB->SelectArr("SELECT sa.*, p.abkuerzung FROM shopimport_auftraege sa left join projekt p on sa.projekt = p.id WHERE sa.imported='0' AND sa.trash='0' $where ORDER BY sa.logdatei LIMIT 100"); + if (is_array($arr) && (!empty($arr) ? count($arr) : 0) > 0) { + + //Alte Auftraege prüfen + $alteauftraegeohnebestellnummer = $this->app->DB->Query("SELECT sa.* FROM shopimport_auftraege sa WHERE isnull(bestellnummer) AND sa.trash='0' LIMIT 100"); + while ($row = $this->app->DB->Fetch_Assoc($alteauftraegeohnebestellnummer)) { + if ($row['warenkorb'] != '') { + if (!empty($row['jsonencoded'])) { + $warenkorb = json_decode(base64_decode($row['warenkorb']), true); + } else { + $warenkorb = unserialize(base64_decode($row['warenkorb'])); + } + $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '" . (isset($warenkorb['onlinebestellnummer']) ? $warenkorb['onlinebestellnummer'] : '') . "' where id = '" . $row['id'] . "'"); + } else { + $this->app->DB->Update("UPDATE shopimport_auftraege set bestellnummer = '' where id = '" . $row['id'] . "'"); + } + } + $this->app->DB->free($alteauftraegeohnebestellnummer); + + $unbekanntezahlungsweisen = null; + $enthaeltdoppeltenummern = false; + $carr = $arr ? count($arr) : 0; + for ($i = 0; $i < $carr; $i++) { + if (empty($checkglobal) || !isset($checkglobal[$arr[$i]['shopid']])) { + $checkglobal[$arr[$i]['shopid']] = null; + + if (($modulename = $this->app->DB->Select("SELECT modulename FROM shopexport WHERE id = '" . $arr[$i]['shopid'] . "' AND modulename <> '' AND shoptyp = 'intern'")) && $this->app->DB->Select("SELECT id FROM shopexport WHERE modulename = '" . $this->app->DB->real_escape_string($modulename) . "' AND id <> '" . $arr[$i]['shopid'] . "' LIMIT 1") + ) { + $shopsintern = $this->app->DB->SelectArr("SELECT id FROM shopexport WHERE id = '" . $arr[$i]['shopid'] . "' OR (modulename = '" . $this->app->DB->real_escape_string($modulename) . "' AND shoptyp = 'intern')"); + if ($shopsintern) { + foreach ($shopsintern as $vs) { + $checkglobal[$arr[$i]['shopid']][] = " shopid = '" . $vs['id'] . "' "; + } + if ($this->app->erp->ModulVorhanden($modulename)) { + /** @var ShopimporterBase $obj */ + $obj = $this->app->erp->LoadModul($modulename); + if ($obj && method_exists($obj, 'EinstellungenStruktur')) { + $konfiguration = $obj->EinstellungenStruktur(); + if ($konfiguration && isset($konfiguration['globalerauftragsnummernkreis']) && $konfiguration['globalerauftragsnummernkreis']) { + + } else { + $checkglobal[$arr[$i]['shopid']] = null; + } + } else { + $checkglobal[$arr[$i]['shopid']] = null; + } + } else { + $checkglobal[$arr[$i]['shopid']] = null; + } + } + } + } + } + + $carr = $arr ? count($arr) : 0; + for ($i = 0; $i < $carr; $i++) { + $projekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '" . $arr[$i]['shopid'] . "' LIMIT 1"); + $auftraegeaufspaeter = $this->app->DB->Select("SELECT auftraegeaufspaeter FROM shopexport WHERE id='" . $arr[$i]['shopid'] . "'"); + if (!empty($arr[$i]['jsonencoded'])) { + $warenkorb = json_decode(base64_decode($arr[$i]['warenkorb']), true); + } else { + $warenkorb = unserialize(base64_decode($arr[$i]['warenkorb'])); + } + foreach ($warenkorb as $key => $value) { + if (is_string($warenkorb[$key])) { + $warenkorb[$key] = trim($warenkorb[$key]); + } + } + foreach ($warenkorb as $k => $v) { + $warenkorb[$k] = $this->app->erp->fixeUmlaute($v); + } + $kundenurvonprojekt = $this->app->DB->Select("SELECT kundenurvonprojekt FROM shopexport WHERE id = '" . $arr[$i]['shopid'] . "' LIMIT 1"); + $adresseprojekt = ''; + if ($kundenurvonprojekt) { + $adresseprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id = '" . $arr[$i]['shopid'] . "' LIMIT 1"); + } + if (isset($warenkorb['subshop']) && $warenkorb['subshop']) { + $subshopprojekt = $this->app->DB->Select("SELECT projekt FROM shopexport_subshop WHERE shop = '" . $arr[$i]['shopid'] . "' AND aktiv = 1 AND subshopkennung = '" . $this->app->DB->real_escape_string($warenkorb['subshop']) . "' LIMIT 1"); + if ($subshopprojekt) { + if (!$kundenurvonprojekt) { + $adresseprojekt = $subshopprojekt; + } + $arr[$i]['abkuerzung'] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$adresseprojekt' LIMIT 1"); + } + } + if ($kundenurvonprojekt) { + $adresseprojekt = " AND projekt = '" . $adresseprojekt . "' "; + } else { + $adresseprojekt = ''; + } + + $checkid = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE `name`='" . $this->app->DB->real_escape_string($warenkorb['name']) . "' AND abteilung='" . $this->app->DB->real_escape_string($warenkorb['abteilung']) . "' + AND strasse='" . $this->app->DB->real_escape_string($warenkorb['strasse']) . "' AND plz='" . $this->app->DB->real_escape_string($warenkorb['plz']) . "' AND ort='" . $this->app->DB->real_escape_string($warenkorb['ort']) . "' AND kundennummer <> '' AND geloescht!=1 $adresseprojekt + ORDER BY email='" . $this->app->DB->real_escape_string($warenkorb['email']) . "' DESC + LIMIT 1"); + + if ($warenkorb['email'] != '') { + if ($warenkorb['email'] !== 'amazon_import_bounce@nfxmedia.de') { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE email='" . $warenkorb['email'] . "' and email <> '' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); + } + if ((String) $checkidemail === '') { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name LIKE '" . $warenkorb['name'] . "' AND ort LIKE '" . $warenkorb['ort'] . "' AND geloescht!=1 $adresseprojekt AND kundennummer <> '' LIMIT 1"); + } + } else { + $checkidemail = $this->app->DB->Select("SELECT kundennummer FROM adresse WHERE name='" . $this->app->DB->real_escape_string($warenkorb['name']) . "' AND strasse='" . $this->app->DB->real_escape_string($warenkorb['strasse']) . "' AND plz='" . $this->app->DB->real_escape_string($warenkorb['plz']) . "' AND ort='" . $this->app->DB->real_escape_string($warenkorb['ort']) . "' $adresseprojekt AND geloescht!=1 AND kundennummer <> '' LIMIT 1"); + } + + if ($warenkorb['kundennummer'] != '' && !empty($validkundennummer) && $validkundennummer == $warenkorb['kundennummer']) { + $kdrnummer = $warenkorb['kundennummer']; + $kdr_name = $this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' $adresseprojekt AND geloescht!=1 LIMIT 1"); + $email = $this->app->DB->Select("SELECT email FROM adresse WHERE kundennummer='$kdrnummer' $adresseprojekt AND geloescht!=1 LIMIT 1"); + $parts = explode("\n", wordwrap($kdr_name, 20, "\n")); + $kdr_name = $parts[0]; + $kdr_name = '
    ' . $kdr_name . ''; + $email = '
    ' . $email . ''; + + $kdr_strasse = $this->app->DB->Select("SELECT strasse FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); + $parts = explode("\n", wordwrap($kdr_strasse, 20, "\n")); + $kdr_strasse = $parts[0]; + $kdr_strasse = '
    ' . $kdr_strasse . ''; + + $kdr_plz = '
    ' . $this->app->DB->Select("SELECT plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1") . ''; + $kdr_ort = '
    ' . $this->app->DB->Select("SELECT ort FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1") . ''; + $checked = ''; + } elseif ($checkid != '') { + $checked = 'checked'; + $kdrnummer = $checkid; + //$kdr_name = "
    ".$this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' AND firma='".$this->app->User->GetFirma()."' LIMIT 1").""; + $kdrArr = $this->app->DB->SelectRow("SELECT name, email, strasse, ort, plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); + $kdr_name = $kdrArr['name']; + $email = $kdrArr['email']; + $parts = explode("\n", wordwrap($kdr_name, 20, "\n")); + $kdr_name = $parts[0]; + $kdr_name = '
    ' . $kdr_name . ''; + $email = '
    ' . $email . ''; + + $kdr_strasse = $kdrArr['strasse']; + $parts = explode("\n", wordwrap($kdr_strasse, 20, "\n")); + $kdr_strasse = $parts[0]; + $kdr_strasse = '
    ' . $kdr_strasse . ''; + + $kdr_plz = '
    ' . $kdrArr['plz'] . ''; + $kdr_ort = '
    ' . $kdrArr['or'] . ''; + } elseif ($checkidemail != '') { + $checked = 'checked'; + $kdrnummer = $checkidemail; + $warenkorb['kundennummer'] = $kdrnummer; + //$kdr_name = "
    ".$this->app->DB->Select("SELECT name FROM adresse WHERE kundennummer='$kdrnummer' AND firma='".$this->app->User->GetFirma()."' LIMIT 1").""; + $kdrArr = $this->app->DB->SelectRow("SELECT name, email, strasse, ort, plz FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); + $kdr_name = $kdrArr['name']; + $email = $kdrArr['email']; + $parts = explode("\n", wordwrap($kdr_name, 20, "\n")); + $kdr_name = $parts[0]; + $kdr_name = '
    ' . $kdr_name . ''; + $email = '
    ' . $email . ''; + + $kdr_strasse = $kdrArr['strasse']; + $parts = explode("\n", wordwrap($kdr_strasse, 40, "\n")); + $kdr_strasse = $parts[0]; + $kdr_strasse = '
    ' . $kdr_strasse . ''; + + $kdr_plz = '
    ' . $kdrArr['plz'] . ''; + $kdr_ort = '
    ' . $kdrArr['ort'] . ''; + } else { + $checked = ''; + $checkid = ''; + $kdrnummer = ''; + $checkidemail = ''; + $kdr_name = ''; + $kdr_strasse = ''; + $kdr_plz = ''; + $kdr_ort = ''; + $email = ''; + } + if ($kdrnummer != '') { + $kdr_addresse_id = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer='$kdrnummer' AND geloescht!=1 $adresseprojekt LIMIT 1"); + } else { + $kdr_addresse_id = ''; + } + + $warenkorb['name'] = $this->app->erp->LimitWord($warenkorb['name'], 20); + $warenkorb['strasse'] = $this->app->erp->LimitWord($warenkorb['strasse'], 20); + + $htmltable->NewRow(); + + $doppelteonlinebestellnummer = false; + if (!empty($warenkorb['onlinebestellnummer'])) { + $check = $this->app->DB->Select("SELECT id from shopimport_auftraege where id <> '" . $arr[$i]['id'] . "' and shopid = '" . $arr[$i]['shopid'] . "' and bestellnummer = '" . $warenkorb['onlinebestellnummer'] . "' and trash = '0' LIMIT 1"); + if ($check) { + $doppelteonlinebestellnummer = true; + $enthaeltdoppeltenummern = true; + } elseif (!empty($checkglobal) && isset($checkglobal[$arr[$i]['shopid']]) && $checkglobal[$arr[$i]['shopid']]) { + $check = $this->app->DB->Select("SELECT id from shopimport_auftraege where id <> '" . $arr[$i]['id'] . "' and (shopid = '" . $arr[$i]['shopid'] . "' OR " . (implode(" OR ", $checkglobal[$arr[$i]['shopid']])) . ") and bestellnummer = '" . $warenkorb['onlinebestellnummer'] . "' and trash = '0' LIMIT 1"); + if ($check) { + $doppelteonlinebestellnummer = true; + $enthaeltdoppeltenummern = true; + } + } + } + + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol($arr[$i]['abkuerzung']); + + $htmltable->AddCol(($doppelteonlinebestellnummer ? '' : '') . $warenkorb['onlinebestellnummer'] . ($doppelteonlinebestellnummer ? '' : '')); + $htmltable->AddCol($warenkorb['name'] . $kdr_name . '
    ' . $warenkorb['email'] . $email); + $htmltable->AddCol($warenkorb['internebezeichnung']); + + $htmltable->AddCol($warenkorb['strasse'] . $kdr_strasse); + $htmltable->AddCol($warenkorb['plz'] . $kdr_plz); + $htmltable->AddCol($warenkorb['ort'] . $kdr_ort); + if ($checkid != '') { + $htmltable->AddCol(''); + } else { + $htmltable->AddCol(''); + } + + $htmltable->AddCol(''); + //$htmltable->AddCol(' '); + $htmltable->AddCol($warenkorb['land']); + $htmltable->AddCol(number_format($warenkorb['gesamtsumme'], 2, ',', '.')); + $saldo_kunde = round($this->app->erp->SaldoAdresse($kdr_addresse_id), 2); + if ($saldo_kunde > 0) { + $saldo_kunde = '' . number_format($saldo_kunde, 2, ',', '.') . ''; + } else { + $saldo_kunde = '-'; + } + $htmltable->AddCol($saldo_kunde); + $htmltable->AddCol($warenkorb['zahlungsweise']); + + $htmltable->AddCol($warenkorb['affiliate_ref']); + //$htmltable->AddCol('Einzelimport verwerfen'); + //$warenkorb[gesamtsumme] = str_replace(".","",$warenkorb[gesamtsumme]); + $gesamtsumme = (isset($gesamtsumme) ? $gesamtsumme : 0) + $warenkorb['gesamtsumme']; + $checkid = ''; + $checkidemail = ''; + $validkundennummer = ''; + //$this->app->Tpl->Add('INHALT',"{$warenkorb[onlinebestellnummer]}{$warenkorb[name]}{$warenkorb[land]}{$warenkorb[gesamtsumme]}"); + } + } else { + if ($deletedRows > 0) { + $msg = $this->app->erp->base64_url_encode('
    Es wurden ' . $deletedRows . ' bereits importierte Datensätze entfernt.
    '); + } else { + $msg = $this->app->erp->base64_url_encode('
    Aktuell sind keine Aufträge in den Online-Shops vorhanden!
    '); + } + $this->app->Location->execute('Location: index.php?module=shopimport&action=list&msg=' . $msg); } - $warenkorb['name'] = $this->app->erp->LimitWord($warenkorb['name'],20); - $warenkorb['strasse'] = $this->app->erp->LimitWord($warenkorb['strasse'],20); $htmltable->NewRow(); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(''); + $htmltable->AddCol(number_format($gesamtsumme, 2, ',', '.')); + $htmltable->AddCol(''); + $htmltable->AddCol(''); - $doppelteonlinebestellnummer = false; - if(!empty($warenkorb['onlinebestellnummer'])) - { - $check = $this->app->DB->Select("SELECT id from shopimport_auftraege where id <> '".$arr[$i]['id']."' and shopid = '".$arr[$i]['shopid']."' and bestellnummer = '".$warenkorb['onlinebestellnummer']."' and trash = '0' LIMIT 1"); - if($check) - { - $doppelteonlinebestellnummer = true; - $enthaeltdoppeltenummern = true; - }elseif(!empty($checkglobal) && isset($checkglobal[$arr[$i]['shopid']]) && $checkglobal[$arr[$i]['shopid']]) - { - $check = $this->app->DB->Select("SELECT id from shopimport_auftraege where id <> '".$arr[$i]['id']."' and (shopid = '".$arr[$i]['shopid']."' OR ".(implode( " OR ", $checkglobal[$arr[$i]['shopid']])).") and bestellnummer = '".$warenkorb['onlinebestellnummer']."' and trash = '0' LIMIT 1"); - if($check) - { - $doppelteonlinebestellnummer = true; - $enthaeltdoppeltenummern = true; - } - } + if ($enthaeltdoppeltenummern) { + $this->app->Tpl->Add('INHALT', '
    Es wurde ein Auftrag aus einem Shop geholt, der bereits importiert wurde!
    '); } + $this->app->Tpl->Add('INHALT', $htmltable->Get()); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol($arr[$i]['abkuerzung']); - - $htmltable->AddCol(($doppelteonlinebestellnummer?'':'').$warenkorb['onlinebestellnummer'].($doppelteonlinebestellnummer?'':'')); - $htmltable->AddCol($warenkorb['name'].$kdr_name.'
    '.$warenkorb['email'].$email); - $htmltable->AddCol($warenkorb['internebezeichnung']); - - $htmltable->AddCol($warenkorb['strasse'].$kdr_strasse); - $htmltable->AddCol($warenkorb['plz'].$kdr_plz); - $htmltable->AddCol($warenkorb['ort'].$kdr_ort); - if($checkid!=''){ - $htmltable->AddCol(''); - } - else{ - $htmltable->AddCol(''); - } - - $htmltable->AddCol(''); - //$htmltable->AddCol(' '); - $htmltable->AddCol($warenkorb['land']); - $htmltable->AddCol(number_format($warenkorb['gesamtsumme'],2,',','.')); - $saldo_kunde = round($this->app->erp->SaldoAdresse($kdr_addresse_id),2); - if($saldo_kunde > 0){ - $saldo_kunde = '' . number_format($saldo_kunde, 2, ',','.') . ''; - } - else{ - $saldo_kunde = '-'; - } - $htmltable->AddCol($saldo_kunde); - $htmltable->AddCol($warenkorb['zahlungsweise']); - - - $htmltable->AddCol($warenkorb['affiliate_ref']); - //$htmltable->AddCol('Einzelimport verwerfen'); - //$warenkorb[gesamtsumme] = str_replace(".","",$warenkorb[gesamtsumme]); - $gesamtsumme = (isset($gesamtsumme)?$gesamtsumme:0) + $warenkorb['gesamtsumme']; - $checkid = ''; - $checkidemail = ''; - $validkundennummer = ''; - //$this->app->Tpl->Add('INHALT',"{$warenkorb[onlinebestellnummer]}{$warenkorb[name]}{$warenkorb[land]}{$warenkorb[gesamtsumme]}"); - } - - - } else { - if($deletedRows > 0){ - $msg = $this->app->erp->base64_url_encode('
    Es wurden ' . $deletedRows . ' bereits importierte Datensätze entfernt.
    '); - }else{ - $msg = $this->app->erp->base64_url_encode('
    Aktuell sind keine Aufträge in den Online-Shops vorhanden!
    '); - } - $this->app->Location->execute('Location: index.php?module=shopimport&action=list&msg='.$msg); - } - - - $htmltable->NewRow(); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - $htmltable->AddCol(number_format($gesamtsumme,2,',','.')); - $htmltable->AddCol(''); - $htmltable->AddCol(''); - - if($enthaeltdoppeltenummern) - { - $this->app->Tpl->Add('INHALT','
    Es wurde ein Auftrag aus einem Shop geholt, der bereits importiert wurde!
    '); - } - $this->app->Tpl->Add('INHALT',$htmltable->Get()); - - $this->app->Tpl->Add('INHALT',"

    Bedeutung:
      + $this->app->Tpl->Add('INHALT', "

      Bedeutung:
      • Kundennummer von Kunde angegeben, eventuell ist diese falsch!
      • Doppelte Internetbestellnummer!
      • Kundennummer bitte manuell prüfen!
      • Kundennummer aufgrund Felder Ort, Strasse, Name, Abteilung und E-Mail eindeutig gefunden!
      "); - $this->app->Tpl->Set('EXTEND',''); - $this->app->Tpl->Parse('IMPORT','rahmen70.tpl'); + $this->app->Tpl->Set('EXTEND', ''); + $this->app->Tpl->Parse('IMPORT', 'rahmen70.tpl'); + $this->app->Tpl->Parse('PAGE', 'shopimport_import.tpl'); + } - $this->app->Tpl->Parse('PAGE','shopimport_import.tpl'); - } - - public function ShopimportNavigation() - { - $id = $this->app->Secure->GetGET('id'); - $tmp = new Navigation($this->app, $id); - $this->app->Tpl->Set('ID',$id); - $this->app->Tpl->Set('PAGE',$tmp->Get()); - $this->app->BuildNavigation=false; - } - + public function ShopimportNavigation() { + $id = $this->app->Secure->GetGET('id'); + $tmp = new Navigation($this->app, $id); + $this->app->Tpl->Set('ID', $id); + $this->app->Tpl->Set('PAGE', $tmp->Get()); + $this->app->BuildNavigation = false; + } } diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 6fbb810e..608ab1a2 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -452,10 +452,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['kundennummer'] = $order->customer->customer_id; $cart['name'] = ($order->customer->civility?$order->customer->civility." ":"").$order->customer->firstname." ".$order->customer->lastname; - if (!empty(strval($order->customer->company))) { + + if (!empty($order->customer->billing_address->company)) { + $cart['anrede'] = 'firma'; $cart['ansprechpartner'] = $cart['name']; - $cart['name'] = strval($order->customer->company); + $cart['name'] = strval($order->customer->billing_address->company); } + $cart['strasse'] = strval($order->customer->billing_address->street_1); $cart['adresszusatz'] = strval($order->customer->billing_address->street_2); $cart['telefon'] = strval($order->customer->billing_address->phone); @@ -472,10 +475,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['lieferadresse_land'] = $this->app->DB->Select($sql); $cart['lieferadresse_name'] = ($order->customer->shipping_address->civility?$order->customer->shipping_address->civility." ":"").$order->customer->shipping_address->firstname." ".$order->customer->shipping_address->lastname; + if (!empty(strval($order->customer->shipping_address->company))) { $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; $cart['lieferadresse_name'] = strval($deliveryAddress->company); } + $cart['lieferadresse_strasse'] = strval($order->customer->shipping_address->street_1); $cart['lieferadresse_adresszusatz'] = strval($order->customer->shipping_address->street_2); $cart['lieferadresse_telefon'] = strval($order->customer->shipping_address->phone); From f1bd5020448f3bb7eb2aabc1d2eca05f70b35816 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 20 Jun 2024 14:23:51 +0200 Subject: [PATCH 24/52] laender 3-letter codes --- www/pages/content/laender_edit.tpl | 1 + www/pages/laender.php | 428 +++++++++++++++-------------- 2 files changed, 217 insertions(+), 212 deletions(-) diff --git a/www/pages/content/laender_edit.tpl b/www/pages/content/laender_edit.tpl index 802be0f3..978e1eba 100644 --- a/www/pages/content/laender_edit.tpl +++ b/www/pages/content/laender_edit.tpl @@ -22,6 +22,7 @@ {|Land|} + diff --git a/www/pages/laender.php b/www/pages/laender.php index 4870a83f..45550818 100644 --- a/www/pages/laender.php +++ b/www/pages/laender.php @@ -1,215 +1,219 @@ -Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\"> Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">"; - - $where = " l.id > 0 "; - - $sql = "SELECT SQL_CALC_FOUND_ROWS l.id, l.iso, l.bezeichnung_de, l.bezeichnung_en, if(l.eu,'EU',''), l.id FROM laender l"; - - $count = "SELECT count(l.id) FROM laender l WHERE $where"; - break; - - } - - $erg = false; - - foreach($erlaubtevars as $k => $v) - { - if(isset($$v))$erg[$v] = $$v; - } - return $erg; - } - - function __construct($app, $intern = false) { - $this->app=$app; - if($intern)return; - $this->app->ActionHandlerInit($this); - - // ab hier alle Action Handler definieren die das Modul hat - $this->app->ActionHandler("list", "LaenderList"); - $this->app->ActionHandler("create", "LaenderCreate"); - $this->app->ActionHandler("edit", "LaenderEdit"); - $this->app->ActionHandler("delete", "LaenderDelete"); - $this->app->ActionHandler('test', 'LaenderTest'); - - $this->app->ActionHandlerListen($app); - } - - function LaenderTest(){ - $countryModule = $this->app->Container->get('CountryMigrationService'); - if($countryModule->needsMigration()){ - $countryModule->doMigration(); - } - } - - function LaenderMenu() - { - $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); - } - - function LaenderList() - { - $this->app->erp->MenuEintrag("index.php?module=laender&action=create","Neues Land"); - $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Übersicht"); - - $this->app->YUI->TableSearch('TAB1','laender_list', "show","","",basename(__FILE__), __CLASS__); - $this->app->Tpl->Parse("PAGE","laender_list.tpl"); - } - - function LaenderEdit() - { - $id = (int)$this->app->Secure->GetGET('id'); - $submit = $this->app->Secure->GetPOST('submitland'); - - $this->app->Tpl->Add('KURZUEBERSCHRIFT2',$bezeichnung_de); - - - - $input = array(); - - $this->app->erp->MenuEintrag("index.php?module=laender&action=edit&id=$id","Details"); - - $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); - - $input = $this->GetInput(); - - if(is_numeric($id) && $submit!=''){ - - $error = ''; - if($input['iso']=='' || strlen(trim($input['iso'])) > 2) $error .= 'Geben Sie bitte einen zweistelligen ISO-Code ein.
      '; - if($input['bezeichnung_de'] == '') $error .= 'Geben Sie bitte eine deutsche Länderbezeichnung ein.
      '; - if($input['bezeichnung_en'] =='') $error .= 'Geben Sie bitte eine englische Länderbezeichnung ein.
      '; - - if($error!=''){ - $this->app->Tpl->Set('MESSAGE', "
      $error
      "); - }else{ - if($error == ""){ - $this->app->DB->Update("UPDATE laender SET iso='{$input['iso']}', bezeichnung_de='{$input['bezeichnung_de']}', bezeichnung_en='{$input['bezeichnung_en']}', eu='{$input['eu']}' WHERE id = '$id' LIMIT 1"); - if($input['eu']==1){ - $this->app->Tpl->Set('EU', "checked"); - } - $this->app->Tpl->Set('MESSAGE', "
      Die Einstellungen wurden erfolgreich übernommen.
      "); - } - } - } - $iso = $this->app->DB->Select("SELECT iso FROM laender WHERE id = '$id'"); - $bezeichnung_de = $this->app->DB->Select("SELECT bezeichnung_de FROM laender WHERE id = '$id'"); - $bezeichnung_en = $this->app->DB->Select("SELECT bezeichnung_en FROM laender WHERE id = '$id'"); - $eu = $this->app->DB->Select("SELECT eu FROM laender WHERE id = '$id'"); - - - $this->app->Tpl->Set('ISO', $iso); - $this->app->Tpl->Set('BEZEICHNUNG_DE', $bezeichnung_de); - $this->app->Tpl->Set('BEZEICHNUNG_EN', $bezeichnung_en); - if($eu == 1){ - $this->app->Tpl->Set('EU', "checked"); - } - - - //$this->SetInput($input); - - $this->app->Tpl->Parse('PAGE', "laender_edit.tpl"); - } - - function LaenderDelete() - { - $ref = $_SERVER['HTTP_REFERER']; - $id = $this->app->Secure->GetGET("id"); - $this->app->DB->DELETE("DELETE FROM laender WHERE id = '$id' LIMIT 1"); - - //$this->VorlageList(); - header("Location: $ref"); - exit; - } - - function LaenderCreate(){ - // $this->app->Tpl->Add(KURZUEBERSCHRIFT,"Benutzer"); - $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); - - $input = $this->GetInput(); - $submit = $this->app->Secure->GetPOST('submitland'); - - if($submit!='') { - - $error = ''; - - if($input['iso']=='' || strlen(trim($input['iso'])) > 2) $error .= 'Geben Sie bitte einen zweistelligen ISO-Code ein.
      '; - if($input['bezeichnung_de']=='') $error .= 'Geben Sie bitte eine deutsche Länderbezeichnung ein.
      '; - if($input['bezeichnung_en']=='') $error .= 'Geben Sie bitte eine englische Länderbezeichnung ein.
      '; - - if($this->app->DB->Select("SELECT '1' FROM laender WHERE iso='{$input['iso']}' LIMIT 1")=='1') - $error .= "Es existiert bereits ein ISO-Code mit diesem Namen.
      "; - - if($error!=''){ - $this->app->Tpl->Set('MESSAGE', "
      $error
      "); - }else { - $this->app->DB->Insert("INSERT INTO laender (iso, bezeichnung_de, bezeichnung_en, eu) VALUES ('{$input['iso']}', '{$input['bezeichnung_de']}', '{$input['bezeichnung_en']}', '{$input['eu']}')"); - $newid = $this->app->DB->GetInsertID(); - $msg = $this->app->erp->base64_url_encode("
      Der Ländereintrag wurde erfolgreich angelegt.
      "); - header("Location: index.php?module=laender&action=edit&id=$newid&msg=$msg"); - exit; - } - } - - $this->SetInput($input); - - $this->app->Tpl->Parse('PAGE', "laender_edit.tpl"); - } - - - function GetInput(){ - $input = array(); - $input['iso'] = $this->app->Secure->GetPOST('iso'); - $input['bezeichnung_de'] = $this->app->Secure->GetPOST('bezeichnung_de'); - $input['bezeichnung_en'] = $this->app->Secure->GetPOST('bezeichnung_en'); - $input['eu'] = (int)$this->app->Secure->GetPOST('eu'); - return $input; - - } - - function SetInput($input){ - $this->app->Tpl->Set('ISO', $input['iso']); - $this->app->Tpl->Set('BEZEICHNUNG_DE', $input['bezeichnung_de']); - $this->app->Tpl->Set('BEZEICHNUNG_EN', $input['bezeichnung_en']); - if($input['eu']==1){ - $this->app->Tpl->Set('EU', "checked"); - } - - - } - -} +Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\"> Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">"; + + $where = " l.id > 0 "; + + $sql = "SELECT SQL_CALC_FOUND_ROWS l.id, l.iso, l.iso3, l.bezeichnung_de, l.bezeichnung_en, if(l.eu,'EU',''), l.id FROM laender l"; + + $count = "SELECT count(l.id) FROM laender l WHERE $where"; + break; + + } + + $erg = false; + + foreach($erlaubtevars as $k => $v) + { + if(isset($$v))$erg[$v] = $$v; + } + return $erg; + } + + function __construct($app, $intern = false) { + $this->app=$app; + if($intern)return; + $this->app->ActionHandlerInit($this); + + // ab hier alle Action Handler definieren die das Modul hat + $this->app->ActionHandler("list", "LaenderList"); + $this->app->ActionHandler("create", "LaenderCreate"); + $this->app->ActionHandler("edit", "LaenderEdit"); + $this->app->ActionHandler("delete", "LaenderDelete"); + $this->app->ActionHandler('test', 'LaenderTest'); + + $this->app->ActionHandlerListen($app); + } + + function LaenderTest(){ + $countryModule = $this->app->Container->get('CountryMigrationService'); + if($countryModule->needsMigration()){ + $countryModule->doMigration(); + } + } + + function LaenderMenu() + { + $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); + } + + function LaenderList() + { + $this->app->erp->MenuEintrag("index.php?module=laender&action=create","Neues Land"); + $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Übersicht"); + + $this->app->YUI->TableSearch('TAB1','laender_list', "show","","",basename(__FILE__), __CLASS__); + $this->app->Tpl->Parse("PAGE","laender_list.tpl"); + } + + function LaenderEdit() + { + $id = (int)$this->app->Secure->GetGET('id'); + $submit = $this->app->Secure->GetPOST('submitland'); + + $this->app->Tpl->Add('KURZUEBERSCHRIFT2',$bezeichnung_de); + + + + $input = array(); + + $this->app->erp->MenuEintrag("index.php?module=laender&action=edit&id=$id","Details"); + + $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); + + $input = $this->GetInput(); + + if(is_numeric($id) && $submit!=''){ + + $error = ''; + if($input['iso']=='' || strlen(trim($input['iso'])) > 2) $error .= 'Geben Sie bitte einen zweistelligen ISO-Code ein.
      '; + if($input['bezeichnung_de'] == '') $error .= 'Geben Sie bitte eine deutsche Länderbezeichnung ein.
      '; + if($input['bezeichnung_en'] =='') $error .= 'Geben Sie bitte eine englische Länderbezeichnung ein.
      '; + + if($error!=''){ + $this->app->Tpl->Set('MESSAGE', "
      $error
      "); + }else{ + if($error == ""){ + $this->app->DB->Update("UPDATE laender SET iso='{$input['iso']}', iso3='{$input['iso3']}', bezeichnung_de='{$input['bezeichnung_de']}', bezeichnung_en='{$input['bezeichnung_en']}', eu='{$input['eu']}' WHERE id = '$id' LIMIT 1"); + if($input['eu']==1){ + $this->app->Tpl->Set('EU', "checked"); + } + $this->app->Tpl->Set('MESSAGE', "
      Die Einstellungen wurden erfolgreich übernommen.
      "); + } + } + } + $iso = $this->app->DB->Select("SELECT iso FROM laender WHERE id = '$id'"); + $iso3 = $this->app->DB->Select("SELECT iso3 FROM laender WHERE id = '$id'"); + $bezeichnung_de = $this->app->DB->Select("SELECT bezeichnung_de FROM laender WHERE id = '$id'"); + $bezeichnung_en = $this->app->DB->Select("SELECT bezeichnung_en FROM laender WHERE id = '$id'"); + $eu = $this->app->DB->Select("SELECT eu FROM laender WHERE id = '$id'"); + + + $this->app->Tpl->Set('ISO', $iso); + $this->app->Tpl->Set('ISO3', $iso3); + $this->app->Tpl->Set('BEZEICHNUNG_DE', $bezeichnung_de); + $this->app->Tpl->Set('BEZEICHNUNG_EN', $bezeichnung_en); + if($eu == 1){ + $this->app->Tpl->Set('EU', "checked"); + } + + + //$this->SetInput($input); + + $this->app->Tpl->Parse('PAGE', "laender_edit.tpl"); + } + + function LaenderDelete() + { + $ref = $_SERVER['HTTP_REFERER']; + $id = $this->app->Secure->GetGET("id"); + $this->app->DB->DELETE("DELETE FROM laender WHERE id = '$id' LIMIT 1"); + + //$this->VorlageList(); + header("Location: $ref"); + exit; + } + + function LaenderCreate(){ + // $this->app->Tpl->Add(KURZUEBERSCHRIFT,"Benutzer"); + $this->app->erp->MenuEintrag("index.php?module=laender&action=list","Zurück zur Übersicht"); + + $input = $this->GetInput(); + $submit = $this->app->Secure->GetPOST('submitland'); + + if($submit!='') { + + $error = ''; + + if($input['iso']=='' || strlen(trim($input['iso'])) > 2) $error .= 'Geben Sie bitte einen zweistelligen ISO-Code ein.
      '; + if($input['bezeichnung_de']=='') $error .= 'Geben Sie bitte eine deutsche Länderbezeichnung ein.
      '; + if($input['bezeichnung_en']=='') $error .= 'Geben Sie bitte eine englische Länderbezeichnung ein.
      '; + + if($this->app->DB->Select("SELECT '1' FROM laender WHERE iso='{$input['iso']}' LIMIT 1")=='1') + $error .= "Es existiert bereits ein ISO-Code mit diesem Namen.
      "; + + if($error!=''){ + $this->app->Tpl->Set('MESSAGE', "
      $error
      "); + }else { + $this->app->DB->Insert("INSERT INTO laender (iso, iso3, bezeichnung_de, bezeichnung_en, eu) VALUES ('{$input['iso']}', '{$input['iso3']}', '{$input['bezeichnung_de']}', '{$input['bezeichnung_en']}', '{$input['eu']}')"); + $newid = $this->app->DB->GetInsertID(); + $msg = $this->app->erp->base64_url_encode("
      Der Ländereintrag wurde erfolgreich angelegt.
      "); + header("Location: index.php?module=laender&action=edit&id=$newid&msg=$msg"); + exit; + } + } + + $this->SetInput($input); + + $this->app->Tpl->Parse('PAGE', "laender_edit.tpl"); + } + + + function GetInput(){ + $input = array(); + $input['iso'] = $this->app->Secure->GetPOST('iso'); + $input['iso3'] = $this->app->Secure->GetPOST('iso3'); + $input['bezeichnung_de'] = $this->app->Secure->GetPOST('bezeichnung_de'); + $input['bezeichnung_en'] = $this->app->Secure->GetPOST('bezeichnung_en'); + $input['eu'] = (int)$this->app->Secure->GetPOST('eu'); + return $input; + + } + + function SetInput($input){ + $this->app->Tpl->Set('ISO', $input['iso']); + $this->app->Tpl->Set('ISO3', $input['iso3']); + $this->app->Tpl->Set('BEZEICHNUNG_DE', $input['bezeichnung_de']); + $this->app->Tpl->Set('BEZEICHNUNG_EN', $input['bezeichnung_en']); + if($input['eu']==1){ + $this->app->Tpl->Set('EU', "checked"); + } + + + } + +} From 29f76aa9d95c6eabc8cfef1da115dfdc71fbce48 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 21 Jun 2024 18:07:33 +0200 Subject: [PATCH 25/52] mirakle configuration improvements --- www/pages/shopimporter_mirakl.php | 75 +++++++++++++++++++------------ 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 608ab1a2..cd955249 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -24,7 +24,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $taxationByDestinationCountry; private $orderSearchLimit; - private $category_identifier; + private $configuration_identifier; private $create_products; private $mirakl_error_text_product_missing; @@ -71,17 +71,17 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'size' => 40, 'info' => 'optional, int64' ], - 'category_identifier_source' => [ + 'configuration_identifier_source' => [ 'typ' => 'select', - 'bezeichnung' => '{|Katalogkategorie-Typ|}:', + 'bezeichnung' => '{|Konfigurationsidentifizierer-Typ|}:', 'size' => 40, - 'info' => 'Woher soll die Katalogkategorie des jeweiligen Artikels bezogen werden?', + 'info' => 'Woher soll die Konfiguration des jeweiligen Artikels bezogen werden?', 'default' => 'feld', 'optionen' => ['feld' => '{|Feld|}', 'freifeld' => '{|Freifeld|}', 'eigenschaft' => '{|Eigenschaft|}', 'wert' => '{|Fester Wert|}'] ], - 'category_identifier_source_value' => [ + 'configuration_identifier_source_value' => [ 'typ' => 'text', - 'bezeichnung' => '{|Katalogkategorie-Wert|}:', + 'bezeichnung' => '{|Konfigurationsidentifizierer-Wert|}:', 'size' => 40, 'info' => '', 'default' => 'kategoriename' @@ -111,13 +111,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { ], 'product_field_map' => [ 'typ' => 'textarea', - 'bezeichnung' => '{|Zuordnung Produkt-Felder je Kategorie (JSON)|}:', + 'bezeichnung' => '{|Zuordnung Produkt-Felder je Konfiguration (JSON)|}:', 'cols' => 80, 'rows' => 20, - 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Ist keine Kategorie definiert, gilt der Eintrag für alle Artikel. Jedes Feld kann wie folgt zugeordnet werden:
      Artikelfeld: "Mirakel-Feldname": {"feld": "xyz"} oder kurz "Mirakel-Feldname": "xyz",
      Freifeld: "Mirakel-Feldname": {"freifeld": "Bezeichnung in Shop"} (Siehe Reiter "Freifelder"),
      Eigenschaft: "Mirakel-Feldname": {"eigenschaft": "Eigenschaftenname xyz"},
      Fester Wert: "Mirakel-Feldname": {"wert": "xyz"}

      Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. "Mirakel-Feldname": {"feld": "name_de", "zusatzfeld": true}', + 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Ist keine Konfiguration definiert, gilt der Eintrag für alle Artikel. Jedes Feld kann wie folgt zugeordnet werden:
      Artikelfeld: "Mirakel-Feldname": {"feld": "xyz"} oder kurz "Mirakel-Feldname": "xyz",
      Freifeld: "Mirakel-Feldname": {"freifeld": "Bezeichnung in Shop"} (Siehe Reiter "Freifelder"),
      Eigenschaft: "Mirakel-Feldname": {"eigenschaft": "Eigenschaftenname xyz"},
      Fester Wert: "Mirakel-Feldname": {"wert": "xyz"}

      Optionen:
      Text voranstellen: "praefix: "Dieser Text vorne",
      Text hinten anstellen: "postfix: "Dieser Text hinten",
      Standardwert: "standardwert: "Dieser Wert wenn nichts gefunden wurde",
      Als Zusatzfeld senden: "zusatzfeld": true', 'placeholder' => '[ { - "kategorien": [ + "konfigurationen": [ "Schuhe", "Hosen" ], "felder": { @@ -126,7 +126,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { "SHOP.PRODUCT.TITLE": {"feld": "nummer"}, "ATT.GLOBAL.Brandname": {"feld": "preis"}, "Product.BaseUnit": {"freifeld": "Kategorie"}, - "ATT.GLOBAL.NoCUperOU": {"eigenschaft": "Mirakl Steuertext"}, + "ATT.GLOBAL.NoCUperOU": {"eigenschaft": "Mirakl Steuertext", "praefix": "ST-"}, "ATT.GLOBAL.NoCUperOU__UNIT": {"wert": "false","zusatzfeld": true}, "Product.TaxIndicator": {"wert": "1","zusatzfeld": true} } @@ -136,13 +136,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'offer_field_map' => [ 'typ' => 'textarea', - 'bezeichnung' => '{|Zuordnung Angebots-Felder je Kategorie (JSON)|}:', + 'bezeichnung' => '{|Zuordnung Angebots-Felder je Konfiguration (JSON)|}:', 'cols' => 80, 'rows' => 20, - 'info' => 'Die Felder werden vom Mirakl-Betreiber vorgegeben. Ist keine Kategorie definiert, gilt der Eintrag für alle Artikel. Jedes Feld kann wie folgt zugeordnet werden:
      Artikelfeld: "Mirakel-Feldname": {"feld": "xyz"} oder kurz "Mirakel-Feldname": "xyz",
      Freifeld: "Mirakel-Feldname": {"freifeld": "Bezeichnung in Shop"} (Siehe Reiter "Freifelder"),
      Eigenschaft: "Mirakel-Feldname": {"eigenschaft": "Eigenschaftenname xyz"},
      Fester Wert: "Mirakel-Feldname": {"wert": "xyz"}

      Zusatzfelder zusätzlich mit der Eigenschaft "zusatzfeld": true versehen: z.B. "Mirakel-Feldname": {"feld": "name_de", "zusatzfeld": true}', + 'info' => '', 'placeholder' => '[ { - "kategorien": [ + "konfigurationen": [ "Schuhe", "Hosen" ], "felder": { @@ -187,7 +187,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; $this->mirakl_shopid = $einstellungen['felder']['mirakl_shopid']; - $this->category_identifier = array($einstellungen['felder']['category_identifier_source'] => $einstellungen['felder']['category_identifier_source_value']); + $this->configuration_identifier = array($einstellungen['felder']['configuration_identifier_source'] => $einstellungen['felder']['configuration_identifier_source_value']); $this->create_products = $einstellungen['felder']['create_products']; $this->mirakl_error_text_product_missing = $einstellungen['felder']['mirakl_error_text_product_missing']; @@ -308,32 +308,51 @@ class Shopimporter_Mirakl extends ShopimporterBase { * Gets a flexible mapped fieldvalue from feld, wert or eigenschaft */ public function GetFieldValue($article, $field_map_entry) { + + $prefix = null; + $postfix = null; + $returnval = null; + foreach ($field_map_entry as $key => $value) { switch ($key) { case 'feld': if (isset($article[$value])) { - return($article[$value]); + $returnval = $article[$value]; } else { throw new Exception("Artikelfeld existiert nicht: \"".$value."\""); } break; case 'freifeld': if (isset($article['freifelder']['DE'][$value])) { - return($article['freifelder']['DE'][$value]); + $returnval = $article['freifelder']['DE'][$value]; } else { throw new Exception("Freifeld existiert nicht: \"".$value."\""); } break; case 'eigenschaft': $sql = "SELECT wert FROM artikeleigenschaften ae INNER JOIN artikeleigenschaftenwerte aew ON aew.artikeleigenschaften = ae.id WHERE aew.artikel = '".$article['artikelid']."' AND ae.name = '".$value."' LIMIT 1"; - return($this->app->DB->Select($sql)); + $result = $this->app->DB->SelectRow($sql); + if (!empty($result)) { + $returnval = $result['wert']; + } break; case 'wert': - return($value); - break; - } - } - return(null); + return($prefix.$value.$postfix); + break; + case 'praefix': + $prefix = $value; + break; + case 'postfix': + $postfix = $value; + break; + case 'standardwert': + if(empty($returnval)) { + $returnval = $value; + } + break; + } + } + return($prefix.$returnval.$postfix); } public function ImportSendListLager() { @@ -586,11 +605,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); - $kategorie = $this->GetFieldValue($article, $this->category_identifier); + $konfiguration = $this->GetFieldValue($article, $this->configuration_identifier); foreach ($this->offer_field_map as $offer_field_entry) { - if ($offer_field_entry['kategorien'] != null) { - if (!in_array($kategorie,$offer_field_entry['kategorien'])) { + if ($offer_field_entry['konfigurationen'] != null) { + if (!in_array($konfiguration,$offer_field_entry['konfigurationen'])) { continue; } } @@ -612,7 +631,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($missing) { $mirakl_export_offers_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration von Kategorie \"".$offer_field_entry['kategorie']."\": ".implode(', ',$missing)); + $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration \"".$offer_field_entry['konfiguration']."\": ".implode(', ',$missing)); $mirakl_export_offers_return_value['articleList'][] = $article; $skip_article = true; } @@ -636,7 +655,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $additional_fields[] = $additional_field; } else { $offer_for_mirakl[$offer_field] = $offer_field_value; - } + } } } @@ -646,7 +665,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!$category_found) { $mirakl_export_offers_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Kategorie \"".$kategorie."\" nicht gefunden"); + $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); $mirakl_export_offers_return_value['articleList'][] = $article; continue; } From ef8825faa8ac08a9e78eb0d5780ee2ac22c2a7b6 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 21 Jun 2024 22:08:02 +0200 Subject: [PATCH 26/52] importvorlage artikeleigenschaften --- upgrade/data/db_schema.json | 17 +++++++++++++++++ www/pages/importvorlage.php | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/upgrade/data/db_schema.json b/upgrade/data/db_schema.json index 8fc821b2..145517eb 100644 --- a/upgrade/data/db_schema.json +++ b/upgrade/data/db_schema.json @@ -18692,6 +18692,14 @@ "id" ], "Non_unique": "" + }, + { + "Key_name": "eigenschaft_unique", + "Index_type": "BTREE", + "columns": [ + "name" + ], + "Non_unique": "UNIQUE" } ] }, @@ -18802,6 +18810,15 @@ "artikel" ], "Non_unique": "" + }, + { + "Key_name": "eigenschaft_artikel_unique", + "Index_type": "BTREE", + "columns": [ + "artikel", + "artikeleigenschaften" + ], + "Non_unique": "UNIQUE" } ] }, diff --git a/www/pages/importvorlage.php b/www/pages/importvorlage.php index a096fb1d..57ee49b8 100644 --- a/www/pages/importvorlage.php +++ b/www/pages/importvorlage.php @@ -4069,6 +4069,25 @@ class Importvorlage extends GenImportvorlage { } } + // Artikeleigenschaften + // leer = löschen + + $artikeleigenschaften = array(); + foreach ($tmp as $feldname => $feldwerte) { + if (strpos($feldname,'eigenschaftname') !== false) { + $eigenschaftspaltennummer = substr($feldname,strlen('eigenschaftname')); + $artikeleigenschaften[$feldwerte[$i]] = $tmp['eigenschaftwert'.$eigenschaftspaltennummer][$i]; + } + } + foreach ($artikeleigenschaften as $key => $value) { + $sql = "INSERT INTO artikeleigenschaften (name) VALUES ('".$key."') ON DUPLICATE KEY UPDATE name = '".$key."'"; + $this->app->DB->Update($sql); + $sql = "INSERT INTO artikeleigenschaftenwerte (artikel, artikeleigenschaften, wert) VALUES ('".$artikelid."' ,(SELECT id FROM artikeleigenschaften WHERE name = '".$key."'), '".$value."') ON DUPLICATE KEY UPDATE wert = '".$value."'"; + $this->app->DB->Update($sql); + } + $sql = "DELETE FROM artikeleigenschaftenwerte WHERE wert = ''"; + $this->app->DB->Delete($sql); + //freifelduebersetzungen foreach ($tmp as $feldname => $feldwerte) { if(strpos($feldname,'freifeld') !== false && strpos($feldname,'_')>0){ From 8e950b5185fdab4e423a5781c9e0ca01e245490d Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 24 Jun 2024 14:44:34 +0200 Subject: [PATCH 27/52] artikel rework artikelexport returncode messages --- www/pages/artikel.php | 165 +++++++++++++++++++----------------------- 1 file changed, 73 insertions(+), 92 deletions(-) diff --git a/www/pages/artikel.php b/www/pages/artikel.php index 4f583554..089b6197 100644 --- a/www/pages/artikel.php +++ b/www/pages/artikel.php @@ -2831,101 +2831,82 @@ class Artikel extends GenArtikel { return ['status'=>$isOk, 'info'=>$info, 'msg_encoded' => $msg, 'error' => $error]; } - public function ArtikelShopexport() - { - $id = $this->app->Secure->GetGET('id'); - $shop = $this->app->Secure->GetGET('shop'); - $artikel = array($id); - $artikelshopid = (int)$this->app->Secure->GetGET('artikelshopid'); - - if($artikelshopid > 0) - { - $shop = $this->app->DB->Select("SELECT shop FROM artikel_onlineshops WHERE id = '$artikelshopid' AND artikel = '$id' AND aktiv = 1 LIMIT 1"); - $this->app->User->SetParameter('artikel_shopexport_shop', ''); - }else{ - if($shop=='1'){ - $shop = $this->app->DB->Select("SELECT shop FROM artikel WHERE id='$id' LIMIT 1"); - } - elseif($shop=='2'){ - $shop = $this->app->DB->Select("SELECT shop2 FROM artikel WHERE id='$id' LIMIT 1"); - } - elseif($shop=='3'){ - $shop = $this->app->DB->Select("SELECT shop3 FROM artikel WHERE id='$id' LIMIT 1"); - } - } - - $artikelexport = $this->app->DB->Select("SELECT artikelexport FROM shopexport WHERE id='$shop' LIMIT 1"); - $lagerexport = $this->app->DB->Select("SELECT lagerexport FROM shopexport WHERE id='$shop' LIMIT 1"); + public function ArtikelShopexport() { + $id = $this->app->Secure->GetGET('id'); + $shop = $this->app->Secure->GetGET('shop'); + $artikel = array($id); + $artikelshopid = (int) $this->app->Secure->GetGET('artikelshopid'); - $externenummer = $this->app->DB->Select("SELECT nummer FROM artikelnummer_fremdnummern WHERE artikel = '$id' AND aktiv = 1 AND shopid = '$shop' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1"); - - if($externenummer) - { - $extartikelnummer = array($externenummer); - }else{ - $extartikelnummer = ''; - } - - $pageContents = $this->app->remote->RemoteSendArticleList($shop,$artikel,$extartikelnummer); - - $check = strpos((string) $pageContents ,'error:'); - $msg = ''; - if(!empty($pageContents) && is_array($pageContents)) { - if(!empty($pageContents['status']) && !empty($pageContents['message'])) { - $msg = $this->app->erp->base64_url_encode('
      '.$pageContents['message'].'
      '); - } - elseif(isset($pageContents['status']) && !empty($pageContents['message'])) { - $msg = $this->app->erp->base64_url_encode('
      '.$pageContents['message'].'
      '); - } - } - elseif($pageContents=='1') { - $pageContents='success'; - } - - if(empty($msg) && $pageContents!='') { - $pageContents = " ($pageContents)"; - } - - $this->app->erp->LogFile($this->app->DB->real_escape_string('manueller Shopexport Artikel: '.$this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$id' LIMIT 1").' Shop: '.$shop.' Status: '.$pageContents)); - // keine fehlermeldung vom shop - if(empty($msg)) { - $linkToImporterSettings = ''; - if($this->app->erp->RechteVorhanden('onlineshops', 'edit')){ - $url = 'index.php?module=onlineshops&action=edit&id='.$shop; - $linkToImporterSettings = "Zu den Shopeinstellungen"; - } - - if($check === 0){ - $msg = $this->app->erp->base64_url_encode("
      Es gab einen Fehler beim Aktualisieren des Artikels im Shop!$pageContents
      "); - } - else if($pageContents == ''){ - if($artikelexport != 1 && $lagerexport != 1){ - $msg = $this->app->erp->base64_url_encode("
      Der Artikel konnte nicht zum Shop übertragen werden! In den Shopeinstellungen ist festgelegt, dass die Artikelinformation- und Lagerbestandsübertragung nicht erlaubt ist!$pageContents $linkToImporterSettings
      "); + if ($artikelshopid > 0) { + $shop = $this->app->DB->Select("SELECT shop FROM artikel_onlineshops WHERE id = '$artikelshopid' AND artikel = '$id' AND aktiv = 1 LIMIT 1"); + $this->app->User->SetParameter('artikel_shopexport_shop', ''); + } else { + if ($shop == '1') { + $shop = $this->app->DB->Select("SELECT shop FROM artikel WHERE id='$id' LIMIT 1"); + } elseif ($shop == '2') { + $shop = $this->app->DB->Select("SELECT shop2 FROM artikel WHERE id='$id' LIMIT 1"); + } elseif ($shop == '3') { + $shop = $this->app->DB->Select("SELECT shop3 FROM artikel WHERE id='$id' LIMIT 1"); + } } - else{ - if($pageContents === '0' || $pageContents === 0){ - $msg = $this->app->erp->base64_url_encode("
      Es gab einen Fehler beim Aktualisieren des Artikels im Shop! Stellen Sie sicher, dass die Zugangsdaten und URL's korrekt sind! Möglicherweise kein Artikelpreis hinterlegt
      "); - }else{ - $msg = $this->app->erp->base64_url_encode("
      Es gab einen Fehler beim Aktualisieren des Artikels im Shop! Stellen Sie sicher, dass die Zugangsdaten und URL's korrekt sind!$pageContents $linkToImporterSettings
      "); - } - } - } - else{ - if($artikelexport != 1 && $lagerexport == 1){ - $msg = $this->app->erp->base64_url_encode("
      Es wurde nur der Lagerbestand (nicht die Artikelinfos entsprechend der Einstellungen) im Shop aktualisiert!$pageContents $linkToImporterSettings
      "); - } - else if($lagerexport != 1 && $artikelexport == 1){ - $msg = $this->app->erp->base64_url_encode("
      Es wurde nur der Artikel (nicht der Lagerbestand entsprechend der Einstellungen) im Shop aktualisiert!$pageContents $linkToImporterSettings
      "); - } - else{ - $msg = $this->app->erp->base64_url_encode("
      Der Artikel wurde im Shop aktualisiert!$pageContents
      "); - } - } - } - $this->app->erp->LagerSync($artikel); - $this->app->Location->execute("index.php?module=artikel&action=edit&id=$id&msg=$msg#tabs-4"); - } + $artikelexport = $this->app->DB->Select("SELECT artikelexport FROM shopexport WHERE id='$shop' LIMIT 1"); + $lagerexport = $this->app->DB->Select("SELECT lagerexport FROM shopexport WHERE id='$shop' LIMIT 1"); + + $externenummer = $this->app->DB->Select("SELECT nummer FROM artikelnummer_fremdnummern WHERE artikel = '$id' AND aktiv = 1 AND shopid = '$shop' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1"); + + if ($externenummer) { + $extartikelnummer = array($externenummer); + } else { + $extartikelnummer = ''; + } + + $remote_result = $this->app->remote->RemoteSendArticleList($shop, $artikel, $extartikelnummer); + + if (is_array($remote_result)) { + $remote_status = $remote_result['status']; + $remote_message = $remote_result['message']; + } else if (is_numeric($remote_result)) { + if ($remote_result == 1) { + $remote_status = true; + } else { + $remote_status = false; + $remote_message = "Der Artikel konnte nicht zum Shop übertragen werden!"; + } + } else if ($remote_result === null) { + $remote_status = false; + $remote_message = "Keine Aktion durchgeführt"; + } else { + $remote_message = $remote_result; + if (strpos((string) $remote_result, 'error:') === 0) { + $remote_status = false; + } else { + $remote_status = true; + } + } + + if ($remote_status) { + $msg = $this->app->erp->base64_url_encode('
      ' . $remote_message . '
      '); + } else { + $msg = $this->app->erp->base64_url_encode('
      ' . $remote_message . '
      '); + } + + $this->app->erp->LogFile($this->app->DB->real_escape_string('manueller Shopexport Artikel: '.$this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$id' LIMIT 1").' Shop: '.$shop.' Status: '.((int) $remote_status)), $remote_message); + + // keine fehlermeldung vom shop + if ($remote_status) { + $linkToImporterSettings = ''; + if ($this->app->erp->RechteVorhanden('onlineshops', 'edit')) { + $url = 'index.php?module=onlineshops&action=edit&id=' . $shop; + $linkToImporterSettings = "Zu den Shopeinstellungen"; + } + } + + $this->app->erp->LagerSync($artikel); + + $this->app->Location->execute("index.php?module=artikel&action=edit&id=$id&msg=$msg#tabs-4"); + } + public function ArtikelShopexportFiles() { From 35add7d29212c60464744c26b54e94d849600bcb Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 24 Jun 2024 14:45:19 +0200 Subject: [PATCH 28/52] mirakl rework product export configuration --- www/pages/shopimporter_mirakl.php | 156 +++++++++++++++++++----------- 1 file changed, 100 insertions(+), 56 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index cd955249..d4979007 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -26,14 +26,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $configuration_identifier; - private $create_products; private $mirakl_error_text_product_missing; private $normalTaxId; private $reducedTaxId; - private $offer_field_map; - private $product_field_map; + private $offer_configuration; + private $product_configuration; public function __construct($app, $intern = false) { $this->app = $app; @@ -86,12 +85,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'info' => '', 'default' => 'kategoriename' ], - 'create_products' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Produkte anlegen|}:', - 'size' => 40, - 'info' => 'Produkte automatisch anlegen wenn sie nicht existieren' - ], 'mirakl_error_text_product_missing' => [ 'typ' => 'text', 'bezeichnung' => '{|Fehlertext Produkt fehlt|}:', @@ -109,7 +102,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'bezeichnung' => '{|TaxId für Steuersatz "ermäßigt"|}', 'size' => 40, ], - 'product_field_map' => [ + 'product_configuration' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Produkt-Felder je Konfiguration (JSON)|}:', 'cols' => 80, @@ -134,7 +127,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { ]' ], - 'offer_field_map' => [ + 'offer_configuration' => [ 'typ' => 'textarea', 'bezeichnung' => '{|Zuordnung Angebots-Felder je Konfiguration (JSON)|}:', 'cols' => 80, @@ -189,14 +182,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->configuration_identifier = array($einstellungen['felder']['configuration_identifier_source'] => $einstellungen['felder']['configuration_identifier_source_value']); - $this->create_products = $einstellungen['felder']['create_products']; $this->mirakl_error_text_product_missing = $einstellungen['felder']['mirakl_error_text_product_missing']; $this->normalTaxId = $einstellungen['felder']['normalTaxId']; $this->reducedTaxId = $einstellungen['felder']['reducedTaxId']; - $this->offer_field_map = json_decode($einstellungen['felder']['offer_field_map'], true, flags: JSON_THROW_ON_ERROR); - $this->product_field_map = json_decode($einstellungen['felder']['product_field_map'], true, flags: JSON_THROW_ON_ERROR); + $this->offer_configuration = json_decode($einstellungen['felder']['offer_configuration'], true, flags: JSON_THROW_ON_ERROR); + $this->product_configuration = json_decode($einstellungen['felder']['product_configuration'], true, flags: JSON_THROW_ON_ERROR); } @@ -356,24 +348,49 @@ class Shopimporter_Mirakl extends ShopimporterBase { } public function ImportSendListLager() { - return($this->ImportSendList()); + return $this->mirakl_export_offers_and_products(export_products : false); + } + + public function ImportSendList() { + return $this->mirakl_export_offers_and_products(export_products : true); } /* * Send articles to shop */ - public function ImportSendList() { + public function mirakl_export_offers_and_products(bool $export_products) { + + $message = ""; + $komma = ""; + $status = true; $articleList = $this->CatchRemoteCommand('data'); + + if ($export_products) { + $create_products_result = $this->mirakl_create_products($articleList); + if ($create_products_result['returncode'] != 0) { + $this->Log("Produktsync nach Mirakl hat Fehler", print_r($create_products_result, true)); + $message = "Produktsync nach Mirakl hat Fehler"; + $komma = ", "; + } else { + $message = "Produktimport in Mirakl ok"; + $komma = ", "; + } + } $offer_export_result = $this->mirakl_export_offers($articleList); - if ($offer_export_result['returncode'] == 0) { - return(array('status' => true, 'message' => "Angebotsimport in Mirakl ok")); + if ($offer_export_result['returncode'] != 0) { + $this->Log("Angebotsync nach Mirakl hat Fehler", print_r($offer_export_result, true)); + $message .= $komma."Angebotsync in Mirakl hat Fehler"; + } else { + $message .= $komma."Angebotsimport in Mirakl ok"; } + return(array('status' => $status, 'message' => $message)); + // Check for missing products and try to create - if ($this->create_products) { +/* if ($export_products) { $create_products_list = array(); @@ -404,10 +421,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { return(array('status' => true, 'message' => "Angebots und Produktimport in Mirakl ok")); } } + $this->Log("Angebotsimport in Mirakl hat Fehler", print_r($offer_export_result, true)); - return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); + return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); */ } @@ -584,7 +602,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_export_offers_return_value['returncode'] = 0; $mirakl_export_offers_return_value['articleList'] = array(); - $this->Log('Angebotsexport start', print_r($articleList,true)); + $this->Log('Angebotsexport Start', print_r($articleList,true)); // First gather all articles as offers and send them // Wait for import to finish @@ -597,7 +615,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Export offer */ - $category_found = false; + $configuration_found = false; $additional_fields = array(); $offer_for_mirakl = array( @@ -605,17 +623,20 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); - $konfiguration = $this->GetFieldValue($article, $this->configuration_identifier); + $configuration_identifier = $this->GetFieldValue($article, $this->configuration_identifier); - foreach ($this->offer_field_map as $offer_field_entry) { - if ($offer_field_entry['konfigurationen'] != null) { - if (!in_array($konfiguration,$offer_field_entry['konfigurationen'])) { + foreach ($this->offer_configuration as $offer_configuration_entry) { + if ($offer_configuration_entry['konfigurationen'] != null) { + if (!in_array($configuration_identifier,$offer_configuration_entry['konfigurationen'])) { continue; } } + $configuration_found = true; + $offer_configuration = $offer_configuration_entry; + break; + } - $category_found = true; - + if ($configuration_found) { // Check required attributes $required = [ 'product_id_type', @@ -625,19 +646,19 @@ class Shopimporter_Mirakl extends ShopimporterBase { ]; $missing = null; foreach ($required as $key) { - if (!isset($offer_field_entry['felder'][$key])) { + if (!isset($offer_configuration['felder'][$key])) { $missing[] = $key; } } if ($missing) { $mirakl_export_offers_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration \"".$offer_field_entry['konfiguration']."\": ".implode(', ',$missing)); + $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration \"".$configuration['konfiguration']."\": ".implode(', ',$missing)); $mirakl_export_offers_return_value['articleList'][] = $article; $skip_article = true; } // Check Required attributes - foreach ($offer_field_entry['felder'] as $offer_field => $offer_field_source) { + foreach ($offer_configuration['felder'] as $offer_field => $offer_field_source) { if (!is_array($offer_field_source)) { $offer_field_source = array('feld' => $offer_field_source); } @@ -657,28 +678,26 @@ class Shopimporter_Mirakl extends ShopimporterBase { $offer_for_mirakl[$offer_field] = $offer_field_value; } } - } + + if ($skip_article) { + continue; + } + + if (!empty($additional_fields)) { + $offer_for_mirakl['offer_additional_fields'] = $additional_fields; + } + + $offers_for_mirakl[] = $offer_for_mirakl; + + $article['mirakl_export_offers_result'] = array('returncode' => 0, 'message' => ""); + $mirakl_export_offers_return_value['articleList'][] = $article; - if ($skip_article) { - continue; - } - - if (!$category_found) { + } else { // configuration_found $mirakl_export_offers_return_value['returncode'] = 1; $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); $mirakl_export_offers_return_value['articleList'][] = $article; continue; - } - - if (!empty($additional_fields)) { - $offer_for_mirakl['offer_additional_fields'] = $additional_fields; - } - - $offers_for_mirakl[] = $offer_for_mirakl; - - $article['mirakl_export_offers_result'] = array('returncode' => 0, 'message' => ""); - $mirakl_export_offers_return_value['articleList'][] = $article; - + } } if (empty($offers_for_mirakl)) { @@ -693,7 +712,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $json_for_mirakl = json_encode($data_for_mirakl); - $this->Log('Angebotsexport Daten', $json_for_mirakl); + $this->Log('Angebotsexport Daten', $json_for_mirakl); $result = []; $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); @@ -786,15 +805,36 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_create_products_return_value = array(); $mirakl_create_products_return_value['returncode'] = 0; $mirakl_create_products_return_value['articleList'] = $articleList; - + + $number_of_articles = 0; + // Build CSV $csv_header = ""; $newline = ""; foreach ($articleList as $article) { - - // Try to create the product - $product_for_mirakl = array(); - foreach ($this->product_field_map as $product_field_entry) { + $product_for_mirakl = array(); + + // Determine configuration + $configuration_found = false; + $konfiguration = $this->GetFieldValue($article, $this->configuration_identifier); + + foreach ($this->product_configuration as $product_configuration) { + if ($product_configuration['konfigurationen'] != null) { + if (!in_array($konfiguration,$product_configuration['konfigurationen'])) { + continue; + } + } + $configuration_found = true; + } + + if (!$configuration_found) { + $mirakl_create_products_return_value['returncode'] = 1; + $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); + $mirakl_create_products_return_value['articleList'][] = $article; + continue; + } + + foreach ($this->product_configuration as $product_field_entry) { foreach ($product_field_entry['felder'] as $product_field => $product_field_source) { if (!is_array($product_field_source)) { $product_field_source = array('feld' => $product_field_source); @@ -812,7 +852,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { $csv .= $newline.'"'.implode('";"',$product_for_mirakl).'"'; $newline = "\r\n"; } - + + if (!$csv) { // No articles found + return($mirakl_create_products_return_value); + } + $csv = $csv_header.$newline.$csv; $result = []; @@ -844,7 +888,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { */ while ($status != 'COMPLETE' && $status != 'FAILED') { - sleep(5); + sleep(30); $response = $this->miraklRequest('products/imports/'.$import_id, raw: true); $result = json_decode($response); $status = $result->import_status; From 7d182345678e5c0669a86dbefc781188595a2106 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 26 Jun 2024 17:01:40 +0200 Subject: [PATCH 29/52] cronjob artikeluebertragen format --- cronjobs/artikeluebertragen.php | 270 ++++++++++++++---------------- www/pages/shopimporter_mirakl.php | 2 + 2 files changed, 124 insertions(+), 148 deletions(-) diff --git a/cronjobs/artikeluebertragen.php b/cronjobs/artikeluebertragen.php index 88e7391f..36267271 100644 --- a/cronjobs/artikeluebertragen.php +++ b/cronjobs/artikeluebertragen.php @@ -1,198 +1,172 @@ Conf)) { + $conf = new Config(); + $app->Conf = $conf; } -if(empty($app->Conf)) { - $conf = new Config(); - $app->Conf = $conf; +if (empty($app->DB) || empty($app->DB->connection)) { + $app->DB = new DB($app->Conf->WFdbhost, $app->Conf->WFdbname, $app->Conf->WFdbuser, $app->Conf->WFdbpass, null, $app->Conf->WFdbport); } -if(empty($app->DB) || empty($app->DB->connection)) { - $app->DB = new DB($app->Conf->WFdbhost, $app->Conf->WFdbname, $app->Conf->WFdbuser, $app->Conf->WFdbpass, null, $app->Conf->WFdbport); -} -if(!isset($app->erp) || !$app->erp) { - if (class_exists('erpAPICustom')) { - $erp = new erpAPICustom($app); - } else { - $erp = new erpAPI($app); - } -//$remote = new Remote($app); - $app->erp = $erp; -//$app->remote= $remote; -} -if(empty($app->remote)) { - if(is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')) { - if(!class_exists('RemoteCustom')){ - require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; +if (!isset($app->erp) || !$app->erp) { + if (class_exists('erpAPICustom')) { + $erp = new erpAPICustom($app); + } else { + $erp = new erpAPI($app); + } + $app->erp = $erp; +} +if (empty($app->remote)) { + if (is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')) { + if (!class_exists('RemoteCustom')) { + require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; + } + $app->remote = new RemoteCustom($app); + } else { + $app->remote = new Remote($app); } - $app->remote = new RemoteCustom($app); - } - else { - $app->remote = new Remote($app); - } } $app->erp->LogFile('Cronjob Artikeluebertragung Start'); $app->DB->Update( - "UPDATE `prozessstarter` + "UPDATE `prozessstarter` SET `mutexcounter` = `mutexcounter` + 1 WHERE `mutex` = 1 AND (`parameter` = 'artikeluebertragen') AND `aktiv` = 1" ); -if($app->DB->Select("SELECT `mutex` FROM `prozessstarter` WHERE (`parameter` = 'artikeluebertragen') LIMIT 1") == 1){ - return; +if ($app->DB->Select("SELECT `mutex` FROM `prozessstarter` WHERE (`parameter` = 'artikeluebertragen') LIMIT 1") == 1) { + return; } $articles = $app->DB->SelectArr( - 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id` LIMIT 10' + 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id` LIMIT 10' ); -if(!empty($articles)) { - /** @var Shopexport $objShopexport */ - $objShopexport = $app->loadModule('shopexport'); - if($objShopexport !== null && method_exists($objShopexport, 'addChangedArticles')) { - $objShopexport->addChangedArticles(); - } +if (!empty($articles)) { + /** @var Shopexport $objShopexport */ + $objShopexport = $app->loadModule('shopexport'); + if ($objShopexport !== null && method_exists($objShopexport, 'addChangedArticles')) { + $objShopexport->addChangedArticles(); + } } $anzChecked = []; $anzChanged = []; $lastids = []; -while(!empty($articles)) { - foreach($articles as $article) { - if(empty($anzChanged[$article['shop']])) { - $anzChanged[$article['shop']] = 0; +while (!empty($articles)) { + foreach ($articles as $article) { + if (empty($anzChanged[$article['shop']])) { + $anzChanged[$article['shop']] = 0; + } + if (empty($anzChecked[$article['shop']])) { + $anzChecked[$article['shop']] = 0; + } + if (!isset($lastids[$article['shop']])) { + $lastids[$article['shop']] = (int) $app->erp->GetKonfiguration( + 'shopexport_artikeluebertragen_check_lastid_' . $article['shop'] + ); + } + $changed = $objShopexport->hasArticleHashChanged($article['artikel'], $article['shop']); + if ($changed['changed']) { + $app->DB->Insert( + sprintf( + 'INSERT INTO `shopexport_artikeluebertragen` (`artikel`, `shop`, `check_nr`) VALUES (%d, %d, %d)', + $article['artikel'], $article['shop'], $lastids[$article['shop']] + ) + ); + $anzChanged[$article['shop']]++; + } + $anzChecked[$article['shop']]++; + $app->DB->Delete( + sprintf( + 'DELETE FROM `shopexport_artikeluebertragen_check` WHERE `id` = %d', + $article['id'] + ) + ); + $app->DB->Update( + sprintf( + "UPDATE `shopexport` SET `autosendarticle_last` = NOW() WHERE `id` = %d", + $article['shop'] + ) + ); } - if(empty($anzChecked[$article['shop']])) { - $anzChecked[$article['shop']] = 0; + $app->erp->SetKonfigurationValue( + 'shopexport_artikeluebertragen_check_changed_' . $article['shop'], + $anzChanged[$article['shop']] + ); + $app->erp->SetKonfigurationValue( + 'shopexport_artikeluebertragen_check_checked_' . $article['shop'], + $anzChecked[$article['shop']] + ); + if (method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['artikeluebertragen'])) { + return; } - if(!isset($lastids[$article['shop']])) { - $lastids[$article['shop']] = (int)$app->erp->GetKonfiguration( - 'shopexport_artikeluebertragen_check_lastid_' . $article['shop'] - ); - } - $changed = $objShopexport->hasArticleHashChanged($article['artikel'], $article['shop']); - if($changed['changed']) { - $app->DB->Insert( - sprintf( - 'INSERT INTO `shopexport_artikeluebertragen` (`artikel`, `shop`, `check_nr`) VALUES (%d, %d, %d)', - $article['artikel'], $article['shop'], $lastids[$article['shop']] - ) - ); - $anzChanged[$article['shop']]++; - } - $anzChecked[$article['shop']]++; - $app->DB->Delete( - sprintf( - 'DELETE FROM `shopexport_artikeluebertragen_check` WHERE `id` = %d', - $article['id'] - ) + $articles = $app->DB->SelectArr( + 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id` LIMIT 10' ); $app->DB->Update( - sprintf( - "UPDATE `shopexport` SET `autosendarticle_last` = NOW() WHERE `id` = %d", - $article['shop'] - ) - ); - } - $app->erp->SetKonfigurationValue( - 'shopexport_artikeluebertragen_check_changed_'.$article['shop'], - $anzChanged[$article['shop']] - ); - $app->erp->SetKonfigurationValue( - 'shopexport_artikeluebertragen_check_checked_'.$article['shop'], - $anzChecked[$article['shop']] - ); - if(method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['artikeluebertragen'])) { - return; - } - $articles = $app->DB->SelectArr( - 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id` LIMIT 10' - ); - $app->DB->Update( - "UPDATE `prozessstarter` + "UPDATE `prozessstarter` SET `letzteausfuerhung`=NOW(), `mutex` = 1,`mutexcounter`=0 WHERE `parameter` = 'artikeluebertragen'" - ); + ); } $check = $app->DB->Select('SELECT COUNT(`id`) FROM `shopexport_artikeluebertragen`'); $app->DB->Update( - "UPDATE `prozessstarter` + "UPDATE `prozessstarter` SET `letzteausfuerhung`=NOW(), `mutex` = 1,`mutexcounter`=0 WHERE `parameter` = 'artikeluebertragen'" ); -while($check > 0) { - $shopartikel = $app->DB->Query( - "SELECT `id`,`shop`,`artikel`,`check_nr` FROM `shopexport_artikeluebertragen` ORDER BY `id` LIMIT 10" - ); - if(!empty($shopartikel)) { - $anz = 0; - while ($row = $app->DB->Fetch_Assoc($shopartikel)) { - if(!isset($lastids[$row['shop']])) { - $lastids[$row['shop']] = (int)$app->erp->GetKonfiguration('shopexport_artikeluebertragen_check_lastid_' . $row['shop']); - } +while ($check > 0) { + $shopartikel = $app->DB->Query( + "SELECT `id`,`shop`,`artikel`,`check_nr` FROM `shopexport_artikeluebertragen` ORDER BY `id` LIMIT 10" + ); + if (!empty($shopartikel)) { + $anz = 0; + while ($row = $app->DB->Fetch_Assoc($shopartikel)) { + if (!isset($lastids[$row['shop']])) { + $lastids[$row['shop']] = (int) $app->erp->GetKonfiguration('shopexport_artikeluebertragen_check_lastid_' . $row['shop']); + } - $anz++; - try { - $app->remote->RemoteSendArticleList($row['shop'], array($row['artikel'])); - $app->erp->LagerSync($row['artikel'], true); - } - catch (Execption $exception) { - $app->erp->LogFile($app->DB->real_escape_string($exception->getMessage())); - } - $app->DB->Delete( - sprintf( - 'DELETE FROM `shopexport_artikeluebertragen` WHERE `id`= %d LIMIT 1', - $row['id'] - ) - ); + $anz++; + try { + $app->remote->RemoteSendArticleList($row['shop'], array($row['artikel'])); + $app->erp->LagerSync($row['artikel'], true); + } catch (Execption $exception) { + $app->erp->LogFile($app->DB->real_escape_string($exception->getMessage())); + } + $app->DB->Delete( + sprintf( + 'DELETE FROM `shopexport_artikeluebertragen` WHERE `id`= %d LIMIT 1', + $row['id'] + ) + ); - if(!empty($row['check_nr']) && $row['check_nr'] == $lastids[$row['shop']]) { - $transfered = 1+(int)$app->erp->GetKonfiguration('shopexport_artikeluebertragen_check_transfered_'.$row['shop']); - $app->erp->SetKonfigurationValue('shopexport_artikeluebertragen_check_transfered_'.$row['shop'], $transfered); - } + if (!empty($row['check_nr']) && $row['check_nr'] == $lastids[$row['shop']]) { + $transfered = 1 + (int) $app->erp->GetKonfiguration('shopexport_artikeluebertragen_check_transfered_' . $row['shop']); + $app->erp->SetKonfigurationValue('shopexport_artikeluebertragen_check_transfered_' . $row['shop'], $transfered); + } - $app->DB->Update( - "UPDATE `prozessstarter` + $app->DB->Update( + "UPDATE `prozessstarter` SET `letzteausfuerhung`=NOW(), `mutex` = 1,`mutexcounter`=0 WHERE `parameter` = 'artikeluebertragen'" - ); + ); + } + + $app->DB->free($shopartikel); } - $app->DB->free($shopartikel); - } + if (method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['artikeluebertragen'])) { + return; + } - if(method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['artikeluebertragen'])) { - return; - } - - //sleep(20); // das performance nicht total spinnt - $check = $app->DB->Select('SELECT COUNT(`id`) FROM `shopexport_artikeluebertragen`'); + $check = $app->DB->Select('SELECT COUNT(`id`) FROM `shopexport_artikeluebertragen`'); } $app->DB->Update( - "UPDATE `prozessstarter` + "UPDATE `prozessstarter` SET `letzteausfuerhung`= NOW(), `mutex` = 0,`mutexcounter`=0 WHERE `parameter` = 'artikeluebertragen'" ); - - diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index d4979007..f482f221 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -808,6 +808,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { $number_of_articles = 0; + $this->Log('Produktexport Start', print_r($csv,true)); + // Build CSV $csv_header = ""; $newline = ""; From 8ebfc49ad27fb2c9a1bcf84fa5f04ce45b51e011 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 27 Jun 2024 21:38:18 +0200 Subject: [PATCH 30/52] artikeluebertragen WIP bulk transfer, switch to logger --- cronjobs/artikeluebertragen.php | 86 ++++++++++++++++++++++++++++-- www/lib/class.remote.php | 87 +++++++++++++++++++++++-------- www/pages/shopimporter_mirakl.php | 5 +- 3 files changed, 151 insertions(+), 27 deletions(-) diff --git a/cronjobs/artikeluebertragen.php b/cronjobs/artikeluebertragen.php index 36267271..f068e93e 100644 --- a/cronjobs/artikeluebertragen.php +++ b/cronjobs/artikeluebertragen.php @@ -1,5 +1,10 @@ Container->get('Logger'); + if (file_exists(dirname(__DIR__) . '/www/lib/class.erpapi_custom.php') && !class_exists('erpAPICustom')) { include_once dirname(__DIR__) . '/www/lib/class.erpapi_custom.php'; } @@ -29,7 +34,9 @@ if (empty($app->remote)) { } } -$app->erp->LogFile('Cronjob Artikeluebertragung Start'); +$logger->debug( + 'Start' +); $app->DB->Update( "UPDATE `prozessstarter` @@ -38,11 +45,14 @@ $app->DB->Update( ); if ($app->DB->Select("SELECT `mutex` FROM `prozessstarter` WHERE (`parameter` = 'artikeluebertragen') LIMIT 1") == 1) { - return; + $logger->debug( + 'Mutex' + ); +// return; } $articles = $app->DB->SelectArr( - 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id` LIMIT 10' + 'SELECT `id`,`shop`,`artikel` FROM `shopexport_artikeluebertragen_check` ORDER BY `id`' ); if (!empty($articles)) { /** @var Shopexport $objShopexport */ @@ -52,6 +62,13 @@ if (!empty($articles)) { } } +$logger->debug( + 'Prepare', + [ + 'articles' => $articles + ] +); + $anzChecked = []; $anzChanged = []; $lastids = []; @@ -101,6 +118,9 @@ while (!empty($articles)) { $anzChecked[$article['shop']] ); if (method_exists($app->erp, 'canRunCronjob') && !$app->erp->canRunCronjob(['artikeluebertragen'])) { + $logger->debug( + '!canRunCronjob' + ); return; } $articles = $app->DB->SelectArr( @@ -119,6 +139,8 @@ $app->DB->Update( SET `letzteausfuerhung`=NOW(), `mutex` = 1,`mutexcounter`=0 WHERE `parameter` = 'artikeluebertragen'" ); + +/* while ($check > 0) { $shopartikel = $app->DB->Query( "SELECT `id`,`shop`,`artikel`,`check_nr` FROM `shopexport_artikeluebertragen` ORDER BY `id` LIMIT 10" @@ -164,7 +186,65 @@ while ($check > 0) { } $check = $app->DB->Select('SELECT COUNT(`id`) FROM `shopexport_artikeluebertragen`'); +}*/ + + +$sql = "SELECT DISTINCT `shop`, shopexport.`bezeichnung` FROM `shopexport_artikeluebertragen` INNER JOIN shopexport ON shopexport.id = `shop`"; +$shops_to_transmit = $app->DB->SelectArr($sql); + +//$app->erp->LogFile('Cronjob artikeluebertragen '.(!empty($shops_to_transmit)?count($shops_to_transmit):0)." shops", print_r($shops_to_transmit, true)); +$logger->debug( + '{count} Shops', + [ + 'count' => (!empty($shops_to_transmit)?count($shops_to_transmit):0), + 'shops_to_transmit' => $shops_to_transmit + ] +); + +foreach ($shops_to_transmit as $shop_to_transmit) { + $sql = "SELECT `artikel` FROM `shopexport_artikeluebertragen` WHERE `shop` = '".$shop_to_transmit['shop']."'"; + $articles_to_transmit = $app->DB->SelectArr($sql); + + $logger->debug( + '{bezeichnung} (Shop {shop_to_transmit}) {count} Artikel', + [ + 'shop_to_transmit' => $shop_to_transmit['shop'], + 'bezeichnung' => $shop_to_transmit['bezeichnung'], + 'count' => (!empty($articles_to_transmit)?count($articles_to_transmit):0), + 'articles_to_transmit' => $articles_to_transmit + ] + ); + + if (!empty($articles_to_transmit)) { + + $article_ids_to_transmit = array_column($articles_to_transmit, 'artikel'); + + try { + $result = $app->remote->RemoteSendArticleList($shop_to_transmit['shop'], $article_ids_to_transmit); // Expected result is array $articles_to_transmit, field status contains transmission status + } catch (Execption $exception) { + $logger->error( + 'Fehler {bezeichnung} (Shop {shop_to_transmit}) {count} Artikel', + [ + 'shop_to_transmit' => $shop_to_transmit['shop'], + 'bezeichnung' => $shop_to_transmit['bezeichnung'], + 'count' => (!empty($articles_to_transmit)?count($articles_to_transmit):0), + 'exception' => $exception + ] + ); + } + + foreach ($result as $article) { + $app->erp->LagerSync($article['artikel'], true); + } + } else { + + } } + +$logger->debug( + 'Ende' +); + $app->DB->Update( "UPDATE `prozessstarter` SET `letzteausfuerhung`= NOW(), `mutex` = 0,`mutexcounter`=0 diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 0ba1f2a5..943c0893 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1,5 +1,6 @@ app=$app; + $this->logger = $app->Container->get('Logger'); } /** @@ -1171,6 +1176,14 @@ class Remote */ public function RemoteSendArticleList($id,$artikel_arr, $extnummer = '', $nurlager = false) { + + $this->logger->debug( + 'RemoteSendArticleList', + [ + 'artikel_arr' => $artikel_arr + ] + ); + if(!class_exists('ObjGenArtikel') && is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')){ include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; @@ -1217,8 +1230,16 @@ class Remote for($i=0;$i<$cartikel_arr;$i++) { - $artikel = $artikel_arr[$i]; + + $this->logger->debug( + 'RemoteSendArticleList', + [ + 'artikel' => $artikel, + 'i' => $i + ] + ); + $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); $tmp->Select($artikel); $data[$i] = ['artikel' => $artikel,'artikelid' => $artikel]; @@ -1642,17 +1663,19 @@ class Remote AND (v.objekt = 'Standard' OR v.objekt = '') AND (v.adresse = '0' OR v.adresse = '') AND (v.gueltig_bis >= NOW() OR v.gueltig_bis = '0000-00-00') ORDER BY v.preis DESC LIMIT 1"); - $priceInformation = reset($priceInformation); - $defaultPrice = $priceInformation['preis']; - $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; - if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ - $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency - $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); - } - - $data[$i]['waehrung'] = $defaultCurrency; - $data[$i]['preis'] = $defaultPrice; - + + if (!empty($priceInformation)) { + $priceInformation = reset($priceInformation); + $defaultPrice = $priceInformation['preis']; + $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; + if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ + $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency + $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); + } + $data[$i]['waehrung'] = $defaultCurrency; + $data[$i]['preis'] = $defaultPrice; + } + if(!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1){ $data[$i]['steuersatz'] = (float)$tmp->GetSteuersatz(); }elseif($data[$i]['umsatzsteuer'] === 'ermaessigt'){ @@ -1759,8 +1782,6 @@ class Remote * @deprecated Ende */ } - - $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; } $data[$i]['checksum'] = $tmp->GetChecksum(); @@ -2053,11 +2074,11 @@ class Remote $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['values'] = $matrixdaten[$iv]['wert']; } } - + $result = null; if(empty($data)) { continue; - } + } if (!empty($lagerexport)) { $result = $this->sendlistlager($i, $id, $data); } @@ -2182,7 +2203,7 @@ class Remote }else{ $data[$i]['variantevorhanden'] = 0; } - + $result = null; if(empty($data)){ continue; @@ -2445,11 +2466,19 @@ class Remote $this->app->DB->Update($query); $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); - $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ +/* $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ 'orderId' => $orderId, 'shopId' => $shopId, - 'message' => $response->getMessage()],true)); - + 'message' => $response->getMessage()],true));*/ + + $this->logger->error('Versandmeldung an Shop fehlgeschlagen', + [ + 'orderId' => $orderId, + 'shopId' => $shopId, + 'message' => $response->getMessage() + ] + ); + return; } @@ -2857,7 +2886,14 @@ class Remote $post_data['data'] = base64_encode(serialize($data)); $client->timeout = 120; if(!$client->post($geturl,$post_data)) { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); +// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); + + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); + throw new Exception('An error occurred: '.$client->getError()); //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); } @@ -2932,7 +2968,14 @@ class Remote if(!$client->post($geturl,$post_data)) { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); +// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); + + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); + throw new Exception('An error occurred: '.$client->getError()); } return unserialize($aes->decrypt(base64_decode($client->getContent()))); diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index f482f221..a99ad6ea 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -384,6 +384,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->Log("Angebotsync nach Mirakl hat Fehler", print_r($offer_export_result, true)); $message .= $komma."Angebotsync in Mirakl hat Fehler"; } else { + $this->Log("Angebotsync nach Mirakl ok", print_r($offer_export_result, true)); $message .= $komma."Angebotsimport in Mirakl ok"; } @@ -801,11 +802,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { * returncode articleList 0 = ok, 20 rejected from mirakl */ private function mirakl_create_products(array $articleList) : array { - + $mirakl_create_products_return_value = array(); $mirakl_create_products_return_value['returncode'] = 0; $mirakl_create_products_return_value['articleList'] = $articleList; - + $number_of_articles = 0; $this->Log('Produktexport Start', print_r($csv,true)); From 48dbbd1a8b99f29016fbf04c2046850a0588cd5a Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 28 Jun 2024 08:38:26 +0200 Subject: [PATCH 31/52] class.remote.php fixed formatting --- www/lib/class.remote.php | 4995 ++++++++++++++++++-------------------- 1 file changed, 2388 insertions(+), 2607 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 943c0893..7d9f099b 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1,4 +1,5 @@ app=$app; - $this->logger = $app->Container->get('Logger'); - } +class Remote { - /** - * @param int $shopId - * @param null|bool $extra - * - * @return mixed - * @throws Exception - */ - public function RemoteConnection($shopId, $extra = null) - { - $ret = $this->RemoteCommand($shopId,'auth', $extra); - if($ret !== 'success' && empty($extra) && method_exists($this->app->erp, 'setSystemHealth')) { - $this->app->erp->setSystemHealth( - 'shopexport', - 'auth', - 'warning', - 'Verbindung zu '. - $this->app->DB->Select( - sprintf( - 'SELECT bezeichnung FROM shopexport WHERE id = %d', - $shopId - ) - ).' fehlgeschlagen.' - ); - try { - /** @var Systemhealth $systemhealth */ - $systemhealth = $this->app->erp->LoadModul('systemhealth'); - if($systemhealth !== null && method_exists($systemhealth, 'createEvent')){ - $systemhealth->createEvent('shopexport', 'auth', 'warning', 'shopexport', $shopId); + /** @var ApplicationCore $app */ + public $app; + + /** @var Logger $logger */ + public $logger; + + public function __construct($app) { + $this->app = $app; + $this->logger = $app->Container->get('Logger'); + } + + /** + * @param int $shopId + * @param null|bool $extra + * + * @return mixed + * @throws Exception + */ + public function RemoteConnection($shopId, $extra = null) { + $ret = $this->RemoteCommand($shopId, 'auth', $extra); + if ($ret !== 'success' && empty($extra) && method_exists($this->app->erp, 'setSystemHealth')) { + $this->app->erp->setSystemHealth( + 'shopexport', + 'auth', + 'warning', + 'Verbindung zu ' . + $this->app->DB->Select( + sprintf( + 'SELECT bezeichnung FROM shopexport WHERE id = %d', + $shopId + ) + ) . ' fehlgeschlagen.' + ); + try { + /** @var Systemhealth $systemhealth */ + $systemhealth = $this->app->erp->LoadModul('systemhealth'); + if ($systemhealth !== null && method_exists($systemhealth, 'createEvent')) { + $systemhealth->createEvent('shopexport', 'auth', 'warning', 'shopexport', $shopId); + } + } catch (Exception $d) { + + } } - } - catch (Exception $d) { - - } - } - return $ret; - } - - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetUpdateArticleList($shopId) - { - return $this->RemoteCommand($shopId,'getlist'); - } - - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetFileList($shopId) - { - return $this->RemoteCommand($shopId,'getfilelist'); - } - - /** - * @param int $shopId - * @param int|string $articleId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetFileListArticle($shopId, $article) - { - $data['artikel'] = $article; - - return $this->RemoteCommand($shopId,'getfilelistarticle', $data); - } - - /** - * @param int $shopId - * @param array|string $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftraegeAnzahl($shopId,$data = '') - { - if(!empty($data)) - { - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); - } - $data = array(); - $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id = %d LIMIT 1', $shopId)); - $holealle = $shopexportArr['holealle']; - $holeallestati = $shopexportArr['holeallestati']; - $zeitraum = [ - 'datumvon'=>$shopexportArr['datumvon'], - 'datumbis'=>$shopexportArr['datumbis'], - 'tmpdatumvon'=>$shopexportArr['tmpdatumvon'], - 'tmpdatumbis'=>$shopexportArr['tmpdatumbis'], - 'anzgleichzeitig'=>$shopexportArr['anzgleichzeitig'], - ]; - if(!empty($zeitraum)) - { - $data['datumvon'] = $zeitraum['datumvon']; - $data['datumbis'] = $zeitraum['datumbis']; - //if(strtotime($zeitraum[0]['tmpdatumbis']) > 0)$data['datumbis'] = $zeitraum[0]['tmpdatumbis']; - //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; - if($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00'|| strtotime($data['datumvon'])<=0) { - $data['datumvon'] = '2000-01-01 00:00:00'; - } - if($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00'|| strtotime($data['datumbis'])<=0) { - $data['datumbis'] = date('Y-m-d H:i:s'); - $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); - } - $data['anzgleichzeitig'] = $zeitraum[0]['anzgleichzeitig']; - if($holeallestati && $data['anzgleichzeitig'] > 1) - { - $data['holeallestati'] = 1; - } - } - if($holealle) - { - $ab_nummer = $shopexportArr['ab_nummer']; - $data = array('ab_nummer' => $ab_nummer); - if($holeallestati) - { - $data['holeallestati'] = 1; - } - - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); + return $ret; } - return $this->RemoteCommand($shopId,'getauftraegeanzahl'); - } - - /** - * @param int $shopId - * @param string $nummer - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftraegeAnzahlNummer($shopId, $nummer) - { - $data = array('nummer' => $nummer); - - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); - } - - /** - * @param int $shopId - * @param null|array $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftrag($shopId, $data = null) - { - if(!empty($data)) { - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - $data = array(); - - $shopexportArr = $this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM shopexport WHERE id = %d LIMIT 1', - $shopId - ) - ); - $holealle = $shopexportArr['holealle']; - $holeallestati = $shopexportArr['holeallestati']; - $zeitraum = [ - 'datumvon'=>$shopexportArr['datumvon'], - 'datumbis'=>$shopexportArr['datumbis'], - 'tmpdatumvon'=>$shopexportArr['tmpdatumvon'], - 'tmpdatumbis'=>$shopexportArr['tmpdatumbis'], - 'anzgleichzeitig'=>$shopexportArr['anzgleichzeitig'], - ]; - if(!empty($zeitraum)) { - $data['datumvon'] = $zeitraum['datumvon']; - $data['datumbis'] = $zeitraum['datumbis']; - if($zeitraum['tmpdatumbis'] !== null && $zeitraum['tmpdatumbis'] !== '0000-00-00 00:00:00' && - strtotime($zeitraum['tmpdatumbis']) > 0) { - $data['datumbis'] = $zeitraum['tmpdatumbis']; - } - //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; - if($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon'])<=0) { - $data['datumvon'] = '2000-01-01 00:00:00'; - } - if($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis'])<=0) { - $data['datumbis'] = date('Y-m-d H:i:s'); - $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); - } - $data['anzgleichzeitig'] = $zeitraum['anzgleichzeitig']; - if($data['anzgleichzeitig'] > 1 && $shopexportArr['einzelsync']) { - $data['anzgleichzeitig'] = 1; - } - if($holeallestati) { - $data['holeallestati'] = 1; - } - } - if($holealle) { - $ab_nummer = $shopexportArr['ab_nummer']; - $data['ab_nummer'] = $ab_nummer; - if($holeallestati) { - $data['holeallestati'] = 1; - } - - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - if(!empty($zeitraum)) { - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - - return $this->RemoteCommand($shopId,'getauftrag'); - } - - /** - * @param int $shopId - * @param string $nummer - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftragNummer($shopId, $nummer) - { - $holealle = $this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$shopId' LIMIT 1"); - if($holealle) - { - $data = array('nummer' => $nummer); - - return $this->RemoteCommand($shopId,'getauftrag', $data); + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetUpdateArticleList($shopId) { + return $this->RemoteCommand($shopId, 'getlist'); } - return ''; - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetFileList($shopId) { + return $this->RemoteCommand($shopId, 'getfilelist'); + } - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendExportlink($shopId) - { - // passwort erzeugen , daten verschluesseln, wenn passwort neu link an kunden senden - // alternativ artikel umfrage - // $all = $this->app->DB->SelectArr("SELECT * FROM artikelgruppen WHERE shop='$id'"); + /** + * @param int $shopId + * @param int|string $articleId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetFileListArticle($shopId, $article) { + $data['artikel'] = $article; - // alle artikelid = 38 die in einem auftrag sind + return $this->RemoteCommand($shopId, 'getfilelistarticle', $data); + } + /** + * @param int $shopId + * @param array|string $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftraegeAnzahl($shopId, $data = '') { + if (!empty($data)) { + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } + $data = array(); + $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id = %d LIMIT 1', $shopId)); + $holealle = $shopexportArr['holealle']; + $holeallestati = $shopexportArr['holeallestati']; + $zeitraum = [ + 'datumvon' => $shopexportArr['datumvon'], + 'datumbis' => $shopexportArr['datumbis'], + 'tmpdatumvon' => $shopexportArr['tmpdatumvon'], + 'tmpdatumbis' => $shopexportArr['tmpdatumbis'], + 'anzgleichzeitig' => $shopexportArr['anzgleichzeitig'], + ]; + if (!empty($zeitraum)) { + $data['datumvon'] = $zeitraum['datumvon']; + $data['datumbis'] = $zeitraum['datumbis']; + //if(strtotime($zeitraum[0]['tmpdatumbis']) > 0)$data['datumbis'] = $zeitraum[0]['tmpdatumbis']; + //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; + if ($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon']) <= 0) { + $data['datumvon'] = '2000-01-01 00:00:00'; + } + if ($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis']) <= 0) { + $data['datumbis'] = date('Y-m-d H:i:s'); + $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); + } + $data['anzgleichzeitig'] = $zeitraum[0]['anzgleichzeitig']; + if ($holeallestati && $data['anzgleichzeitig'] > 1) { + $data['holeallestati'] = 1; + } + } + if ($holealle) { + $ab_nummer = $shopexportArr['ab_nummer']; + $data = array('ab_nummer' => $ab_nummer); + if ($holeallestati) { + $data['holeallestati'] = 1; + } - // usb90key - $artikelid= 38; + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } - $all = $this->app->DB->SelectArr("SELECT a.id as auftrag, a.adresse as adresse + return $this->RemoteCommand($shopId, 'getauftraegeanzahl'); + } + + /** + * @param int $shopId + * @param string $nummer + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftraegeAnzahlNummer($shopId, $nummer) { + $data = array('nummer' => $nummer); + + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } + + /** + * @param int $shopId + * @param null|array $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftrag($shopId, $data = null) { + if (!empty($data)) { + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + $data = array(); + + $shopexportArr = $this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM shopexport WHERE id = %d LIMIT 1', + $shopId + ) + ); + $holealle = $shopexportArr['holealle']; + $holeallestati = $shopexportArr['holeallestati']; + $zeitraum = [ + 'datumvon' => $shopexportArr['datumvon'], + 'datumbis' => $shopexportArr['datumbis'], + 'tmpdatumvon' => $shopexportArr['tmpdatumvon'], + 'tmpdatumbis' => $shopexportArr['tmpdatumbis'], + 'anzgleichzeitig' => $shopexportArr['anzgleichzeitig'], + ]; + if (!empty($zeitraum)) { + $data['datumvon'] = $zeitraum['datumvon']; + $data['datumbis'] = $zeitraum['datumbis']; + if ($zeitraum['tmpdatumbis'] !== null && $zeitraum['tmpdatumbis'] !== '0000-00-00 00:00:00' && + strtotime($zeitraum['tmpdatumbis']) > 0) { + $data['datumbis'] = $zeitraum['tmpdatumbis']; + } + //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; + if ($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon']) <= 0) { + $data['datumvon'] = '2000-01-01 00:00:00'; + } + if ($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis']) <= 0) { + $data['datumbis'] = date('Y-m-d H:i:s'); + $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); + } + $data['anzgleichzeitig'] = $zeitraum['anzgleichzeitig']; + if ($data['anzgleichzeitig'] > 1 && $shopexportArr['einzelsync']) { + $data['anzgleichzeitig'] = 1; + } + if ($holeallestati) { + $data['holeallestati'] = 1; + } + } + if ($holealle) { + $ab_nummer = $shopexportArr['ab_nummer']; + $data['ab_nummer'] = $ab_nummer; + if ($holeallestati) { + $data['holeallestati'] = 1; + } + + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + if (!empty($zeitraum)) { + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + + return $this->RemoteCommand($shopId, 'getauftrag'); + } + + /** + * @param int $shopId + * @param string $nummer + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftragNummer($shopId, $nummer) { + $holealle = $this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$shopId' LIMIT 1"); + if ($holealle) { + $data = array('nummer' => $nummer); + + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + + return ''; + } + + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendExportlink($shopId) { + // passwort erzeugen , daten verschluesseln, wenn passwort neu link an kunden senden + // alternativ artikel umfrage + // $all = $this->app->DB->SelectArr("SELECT * FROM artikelgruppen WHERE shop='$id'"); + // alle artikelid = 38 die in einem auftrag sind + // usb90key + $artikelid = 38; + + $all = $this->app->DB->SelectArr("SELECT a.id as auftrag, a.adresse as adresse FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag WHERE ap.artikel='$artikelid' AND ap.geliefert_menge < ap.menge AND a.status!='storniert' AND a.status!='abgeschlossen'"); - // mail mit url senden - if(empty($all)) { - return ''; - } - $loop = 0; - $call = (!empty($all)?count($all):0); - for($i=0;$i<$call;$i++) - { - $auftragid = $all[$i]['auftrag']; - $adresse = $all[$i]['adresse']; + // mail mit url senden + if (empty($all)) { + return ''; + } + $loop = 0; + $call = (!empty($all) ? count($all) : 0); + for ($i = 0; $i < $call; $i++) { + $auftragid = $all[$i]['auftrag']; + $adresse = $all[$i]['adresse']; - $grund = 'artikel'; + $grund = 'artikel'; - $check = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE adresse='$adresse' AND objekt='$artikelid' AND ident='$auftragid' LIMIT 1"); + $check = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE adresse='$adresse' AND objekt='$artikelid' AND ident='$auftragid' LIMIT 1"); - if($check=='') - { - $checkreg = 1; - while($checkreg!='') - { - $token1 = md5(uniqid(rand(), true)); - $token2 = md5(uniqid(rand(), true)); + if ($check == '') { + $checkreg = 1; + while ($checkreg != '') { + $token1 = md5(uniqid(rand(), true)); + $token2 = md5(uniqid(rand(), true)); - $token3 = md5(uniqid(rand(), true)); - $token4 = md5(uniqid(rand(), true)); + $token3 = md5(uniqid(rand(), true)); + $token4 = md5(uniqid(rand(), true)); - $zufall = $token1 . '-' . $token2; - $zufall = md5($zufall); + $zufall = $token1 . '-' . $token2; + $zufall = md5($zufall); - $zufall2 = $token3 . '-' . $token4; - $zufall2 = md5($zufall2); + $zufall2 = $token3 . '-' . $token4; + $zufall2 = md5($zufall2); - $reg = md5($zufall2.$zufall); + $reg = md5($zufall2 . $zufall); - $checkreg = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE reg='$reg' LIMIT 1"); + $checkreg = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE reg='$reg' LIMIT 1"); + } + + // pruefen ob es zahl schon gibt sonst nochmal + + $data[$loop]['reg'] = $reg; + $data[$loop]['grund'] = $grund; + $data[$loop]['objekt'] = $artikelid; // artikel id + $data[$loop]['ident'] = $auftragid; // + $loop++; + + $this->app->DB->Insert("INSERT INTO exportlink_sent (reg,grund,objekt,ident,adresse,datum) VALUES ($reg','$grund','$artikelid','$auftragid','$adresse',NOW())"); + } } - // pruefen ob es zahl schon gibt sonst nochmal - - $data[$loop]['reg'] = $reg; - $data[$loop]['grund'] = $grund; - $data[$loop]['objekt'] = $artikelid; // artikel id - $data[$loop]['ident'] = $auftragid;// - $loop++; - - $this->app->DB->Insert("INSERT INTO exportlink_sent (reg,grund,objekt,ident,adresse,datum) VALUES ($reg','$grund','$artikelid','$auftragid','$adresse',NOW())"); - } + return $this->RemoteCommand($shopId, 'exportlink', $data); } - return $this->RemoteCommand($shopId,'exportlink',$data); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendNavigation($shopId) { + //$data[0] = array('aasas','asddd'); - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendNavigation($shopId) - { - //$data[0] = array('aasas','asddd'); + $all = $this->app->DB->SelectArr("SELECT * FROM shopnavigation WHERE shop='$shopId'"); + $call = $all ? count($all) : 0; + $data = $call > 0 ? array() : null; + for ($i = 0; $i < $call; $i++) { + $data[$i]['id'] = $all[$i]['id']; + $data[$i]['bezeichnung'] = $all[$i]['bezeichnung']; + $data[$i]['position'] = $all[$i]['position']; + $data[$i]['parent'] = $all[$i]['parent']; + $data[$i]['bezeichnung_en'] = $all[$i]['bezeichnung_en']; + $data[$i]['plugin'] = $all[$i]['plugin']; + $data[$i]['pluginparameter'] = $all[$i]['pluginparameter']; + $data[$i]['target'] = $all[$i]['target']; + } - $all = $this->app->DB->SelectArr("SELECT * FROM shopnavigation WHERE shop='$shopId'"); - $call = $all?count($all):0; - $data = $call > 0?array():null; - for($i=0;$i<$call;$i++) - { - $data[$i]['id'] = $all[$i]['id']; - $data[$i]['bezeichnung'] = $all[$i]['bezeichnung']; - $data[$i]['position'] = $all[$i]['position']; - $data[$i]['parent'] = $all[$i]['parent']; - $data[$i]['bezeichnung_en'] = $all[$i]['bezeichnung_en']; - $data[$i]['plugin'] = $all[$i]['plugin']; - $data[$i]['pluginparameter'] = $all[$i]['pluginparameter']; - $data[$i]['target'] = $all[$i]['target']; + return $this->RemoteCommand($shopId, 'navigation', $data); } - return $this->RemoteCommand($shopId,'navigation',$data); - } - - /** - * @param int $shopId - * - * @return mixed|string - * @throws Exception - */ - public function RemoteSendArtikelgruppen($shopId) - { - $all = $this->app->DB->SelectArr("SELECT id, bezeichnung,bezeichnung_en,beschreibung_de,beschreibung_en + /** + * @param int $shopId + * + * @return mixed|string + * @throws Exception + */ + public function RemoteSendArtikelgruppen($shopId) { + $all = $this->app->DB->SelectArr("SELECT id, bezeichnung,bezeichnung_en,beschreibung_de,beschreibung_en FROM artikelgruppen WHERE shop='$shopId'"); - if(empty($all)) { - return ''; + if (empty($all)) { + return ''; + } + + return $this->RemoteCommand($shopId, 'artikelgruppen', $all); } - return $this->RemoteCommand($shopId,'artikelgruppen',$all); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendInhalt($shopId) { + $all = $this->app->DB->SelectArr("SELECT * FROM inhalt WHERE shop='$shopId' AND aktiv=1"); + if (empty($all)) { + return ''; + } + $call = (!empty($all) ? count($all) : 0); - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendInhalt($shopId) - { - $all = $this->app->DB->SelectArr("SELECT * FROM inhalt WHERE shop='$shopId' AND aktiv=1"); - if(empty($all)) { - return ''; - } - $call = (!empty($all)?count($all):0); + $data = array(); + for ($i = 0; $i < $call; $i++) { + $data[$i]['sprache'] = $all[$i]['sprache']; + $data[$i]['inhalt'] = $all[$i]['inhalt']; + $data[$i]['kurztext'] = $all[$i]['kurztext']; + $data[$i]['html'] = $all[$i]['html']; + $data[$i]['title'] = $all[$i]['title']; + $data[$i]['description'] = $all[$i]['description']; + $data[$i]['keywords'] = $all[$i]['keywords']; + $data[$i]['inhaltstyp'] = $all[$i]['inhaltstyp']; + $data[$i]['template'] = $all[$i]['template']; + $data[$i]['finalparse'] = $all[$i]['finalparse']; + $data[$i]['navigation'] = $all[$i]['navigation']; + $data[$i]['sichtbarbis'] = $all[$i]['sichtbarbis']; + $data[$i]['datum'] = $all[$i]['datum']; + $data[$i]['aktiv'] = $all[$i]['aktiv']; + } - $data = array(); - for ($i = 0; $i < $call; $i++) { - $data[$i]['sprache'] = $all[$i]['sprache']; - $data[$i]['inhalt'] = $all[$i]['inhalt']; - $data[$i]['kurztext'] = $all[$i]['kurztext']; - $data[$i]['html'] = $all[$i]['html']; - $data[$i]['title'] = $all[$i]['title']; - $data[$i]['description'] = $all[$i]['description']; - $data[$i]['keywords'] = $all[$i]['keywords']; - $data[$i]['inhaltstyp'] = $all[$i]['inhaltstyp']; - $data[$i]['template'] = $all[$i]['template']; - $data[$i]['finalparse'] = $all[$i]['finalparse']; - $data[$i]['navigation'] = $all[$i]['navigation']; - $data[$i]['sichtbarbis'] = $all[$i]['sichtbarbis']; - $data[$i]['datum'] = $all[$i]['datum']; - $data[$i]['aktiv'] = $all[$i]['aktiv']; + return $this->RemoteCommand($shopId, 'inhalt', $data); } - return $this->RemoteCommand($shopId, 'inhalt', $data); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendArtikelArtikelgruppen($shopId) { + $all = $this->app->DB->SelectArr('SELECT * FROM artikel_artikelgruppe'); + $call = $all ? count($all) : 0; + if ($call > 0) { + $data = array(); + for ($i = 0; $i < $call; $i++) { + $data[$i]['id'] = $all[$i]['id']; + $data[$i]['artikel'] = $all[$i]['artikel']; + $data[$i]['artikelgruppe'] = $all[$i]['artikelgruppe']; + $data[$i]['position'] = $all[$i]['position']; + } - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendArtikelArtikelgruppen($shopId) - { - $all = $this->app->DB->SelectArr('SELECT * FROM artikel_artikelgruppe'); - $call = $all?count($all):0; - if($call > 0){ - $data = array(); - for ($i = 0; $i < $call; $i++) { - $data[$i]['id'] = $all[$i]['id']; - $data[$i]['artikel'] = $all[$i]['artikel']; - $data[$i]['artikelgruppe'] = $all[$i]['artikelgruppe']; - $data[$i]['position'] = $all[$i]['position']; - } + return $this->RemoteCommand($shopId, 'artikelartikelgruppen', $data); + } - return $this->RemoteCommand($shopId, 'artikelartikelgruppen', $data); + return ''; } - return ''; - } - - /** - * @param int $shopId - * @param string $tabelle - * @param int $intid - * @param int $intid2 - * - * @return mixed - */ - public function GetShopexportMappingExt($shopId, $tabelle, $intid, $intid2 = 0) - { - return $this->app->DB->Select("SELECT extid + /** + * @param int $shopId + * @param string $tabelle + * @param int $intid + * @param int $intid2 + * + * @return mixed + */ + public function GetShopexportMappingExt($shopId, $tabelle, $intid, $intid2 = 0) { + return $this->app->DB->Select("SELECT extid FROM shopexport_mapping - WHERE shop = '$shopId' AND tabelle = '$tabelle' AND intid = '$intid' ".($intid2?" AND intid2 = '$intid2' ":'')." LIMIT 1"); - } + WHERE shop = '$shopId' AND tabelle = '$tabelle' AND intid = '$intid' " . ($intid2 ? " AND intid2 = '$intid2' " : '') . " LIMIT 1"); + } - /** - * @param int $shopId - * @param string $tabelle - * @param string $extid - * @param int $intid2 - * - * @return mixed - */ - protected function GetShopexportMappingInt($shopId, $tabelle, $extid, $intid2 = 0) - { - return $this->app->DB->Select("SELECT intid + /** + * @param int $shopId + * @param string $tabelle + * @param string $extid + * @param int $intid2 + * + * @return mixed + */ + protected function GetShopexportMappingInt($shopId, $tabelle, $extid, $intid2 = 0) { + return $this->app->DB->Select("SELECT intid FROM shopexport_mapping - WHERE shop = '$shopId' AND tabelle = '$tabelle' AND extid = '$extid' ".($intid2?" AND intid2 = '$intid2' ":'')." + WHERE shop = '$shopId' AND tabelle = '$tabelle' AND extid = '$extid' " . ($intid2 ? " AND intid2 = '$intid2' " : '') . " LIMIT 1"); - } + } - /** - * @param int $shop - * @param string $tabelle - * @param int $intid - * @param string $extid - * @param int $intid2 - * - * @return mixed - */ - public function ShopexportMappingSet($shop, $tabelle, $intid, $extid, $intid2 = 0) - { - $check = $this->app->DB->Select("SELECT id FROM shopexport_mapping + /** + * @param int $shop + * @param string $tabelle + * @param int $intid + * @param string $extid + * @param int $intid2 + * + * @return mixed + */ + public function ShopexportMappingSet($shop, $tabelle, $intid, $extid, $intid2 = 0) { + $check = $this->app->DB->Select("SELECT id FROM shopexport_mapping WHERE shop = '$shop' AND tabelle = '$tabelle' AND intid = '$intid' AND intid2 = '$intid2' LIMIT 1"); - if(!$check) - { - $this->app->DB->Insert("INSERT INTO shopexport_mapping (shop, tabelle, intid, intid2, extid, zeitstempel) + if (!$check) { + $this->app->DB->Insert("INSERT INTO shopexport_mapping (shop, tabelle, intid, intid2, extid, zeitstempel) VALUES ('$shop', '$tabelle', '$intid', '$intid2', '$extid', now())"); - return $this->app->DB->GetInsertID(); - } - $this->app->DB->Update("UPDATE shopexport_mapping SET extid = '$extid' WHERE id = '$check' LIMIT 1"); + return $this->app->DB->GetInsertID(); + } + $this->app->DB->Update("UPDATE shopexport_mapping SET extid = '$extid' WHERE id = '$check' LIMIT 1"); - return $check; - } + return $check; + } - /** - * @param int $id - * @param string $nummer - * @param bool $create - * - * @return mixed - * @throws Exception - */ - public function RemoteGetArticle($id,$nummer, $create = false) - { - if($create) - { - $data['nummerintern'] = $nummer; - }else { - $data['nummer'] = $nummer; - } - $ret = $this->RemoteCommand($id,'getarticle',$data); - $variante_von = null; - //if(!$create)return $ret; - $_nummer = null; - $shopexportArr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); - $projekt = $shopexportArr['projekt']; - $nurneueartikel = $shopexportArr['nurneueartikel']; - $artikelnummerbeimanlegenausshop = $shopexportArr['artikelnummerbeimanlegenausshop']; - if(!$create){ - $nurneueartikel = false; - } - if(!isset($ret['nummer']) && isset($ret[0]) && isset($ret[0]['nummer'])) - { - $reta = $ret; - }elseif(isset($ret['nummer'])) - { - $reta[] = $ret; - }elseif(isset($ret[0]) && isset($ret[0]['name'])){ - $ret[0]['nummer'] = '';//$nummer; - $reta = $ret; - }elseif(isset($ret['name'])){ - $ret['nummer'] = '';//$nummer; - $reta[] = $ret; - }else - { - return $ret; - } - if(!$reta || !is_array($reta)) - { - return $ret; - } - $stuecklistenmechanik = false; - $variantevonorig = null; - $steuersatz_normal = $this->app->erp->Firmendaten('steuersatz_normal'); - $steuersatz_ermaessigt = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); - if(empty($steuersatz_ermaessigt)) - { - $steuersatz_ermaessigt = 7; - } - if(empty($steuersatz_normal)) - { - $steuersatz_normal = 19; - } - $crossellingInstalled = $this->app->erp->ModulVorhanden('crossselling'); - foreach($reta as $k => $ret) - { - if(isset($ret['stueckliste'])){ - $stuecklistenmechanik = $ret['stueckliste']; - } - $ret['nummer'] = $this->app->DB->real_escape_string(trim($ret['nummer'])); - $articleid = null; - if($k == 0) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $nummer,true); - if($articleid) - { - $variantevonorig = $this->app->DB->Select("SELECT variante_von + /** + * @param int $id + * @param string $nummer + * @param bool $create + * + * @return mixed + * @throws Exception + */ + public function RemoteGetArticle($id, $nummer, $create = false) { + if ($create) { + $data['nummerintern'] = $nummer; + } else { + $data['nummer'] = $nummer; + } + $ret = $this->RemoteCommand($id, 'getarticle', $data); + $variante_von = null; + //if(!$create)return $ret; + $_nummer = null; + $shopexportArr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); + $projekt = $shopexportArr['projekt']; + $nurneueartikel = $shopexportArr['nurneueartikel']; + $artikelnummerbeimanlegenausshop = $shopexportArr['artikelnummerbeimanlegenausshop']; + if (!$create) { + $nurneueartikel = false; + } + if (!isset($ret['nummer']) && isset($ret[0]) && isset($ret[0]['nummer'])) { + $reta = $ret; + } elseif (isset($ret['nummer'])) { + $reta[] = $ret; + } elseif (isset($ret[0]) && isset($ret[0]['name'])) { + $ret[0]['nummer'] = ''; //$nummer; + $reta = $ret; + } elseif (isset($ret['name'])) { + $ret['nummer'] = ''; //$nummer; + $reta[] = $ret; + } else { + return $ret; + } + if (!$reta || !is_array($reta)) { + return $ret; + } + $stuecklistenmechanik = false; + $variantevonorig = null; + $steuersatz_normal = $this->app->erp->Firmendaten('steuersatz_normal'); + $steuersatz_ermaessigt = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + if (empty($steuersatz_ermaessigt)) { + $steuersatz_ermaessigt = 7; + } + if (empty($steuersatz_normal)) { + $steuersatz_normal = 19; + } + $crossellingInstalled = $this->app->erp->ModulVorhanden('crossselling'); + foreach ($reta as $k => $ret) { + if (isset($ret['stueckliste'])) { + $stuecklistenmechanik = $ret['stueckliste']; + } + $ret['nummer'] = $this->app->DB->real_escape_string(trim($ret['nummer'])); + $articleid = null; + if ($k == 0) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $nummer, true); + if ($articleid) { + $variantevonorig = $this->app->DB->Select("SELECT variante_von FROM artikel WHERE id = '$articleid' AND variante = 1 LIMIT 1"); - if(!$variantevonorig) - { - $articleid = $this->app->DB->Select("SELECT id + if (!$variantevonorig) { + $articleid = $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(geloescht,0) = 0 AND nummer <> 'DEL' LIMIT 1"); - } - } - } - if((isset($ret['nummerintern']) && $ret['nummerintern'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummerintern']); - } - if(($ret['nummer'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummer']); - } - if(($ret['ean'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['ean']); - } - if($articleid) - { - if(isset($ret['shoparticleid']) && $ret['shoparticleid'] != '' && trim($this->app->DB->real_escape_string($ret['shoparticleid'])) != '') - { - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND artikel = '$articleid' AND nummer = '".trim($this->app->DB->real_escape_string($ret['shoparticleid']))."' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, nummer, bezeichnung) - VALUES ('$articleid','$id','1','".trim($this->app->DB->real_escape_string($ret['shoparticleid']))."','SHOPID')"); - } - } - } - if(!$articleid && !$create) - { - continue; - } - if(!$articleid || !$nurneueartikel) - { - if($articleid) - { - $arr['id'] = $articleid; - $arr['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - }elseif($ret['nummer'] == '') - { - $arr['nummer'] = $this->app->erp->GetNextArtikelnummer('',1,$shopexportArr['projekt']); - } - /*if(isset($ret['nummer']) && $ret['nummer'] == '' && !is_null($variante_von)) - { - $ret['nummer'] = $_nummer.'-'.$ret['nummer']; - $arr['nummer'] = $ret['nummer']; - }*/ - if(isset($ret['stueckliste']) && empty($variante_von)){ - $arr['stueckliste'] = $ret['stueckliste']; - } - $arr['projekt'] = $shopexportArr['projekt']; - $arr['name_de'] = $ret['name']; - $arr['uebersicht_de'] = $ret['uebersicht_de'] ?? ''; - $arr['kurztext_de'] = $ret['kurztext_de'] ?? ''; - $arr['name_en'] = $ret['name_en']; - $arr['uebersicht_en'] = $ret['uebersicht_en'] ?? ''; - $arr['kurztext_en'] = $ret['kurztext_en'] ?? ''; - $arr['metakeywords_de'] = $ret['metakeywords_de'] ?? ''; - $arr['metakeywords_en'] = $ret['metakeywords_en'] ?? ''; - $arr['metatitle_de'] = $ret['metatitle_de'] ?? ''; - $arr['metatitle_en'] = $ret['metatitle_en'] ?? ''; - $arr['metadescription_de'] = $ret['metadescription_de'] ?? ''; - $arr['metadescription_en'] = $ret['metadescription_en'] ?? ''; - //$arr['anabregs_text'] = isset($ret['uebersicht_de'])?$ret['uebersicht_de']:''; - if(isset($ret['ean']) && $ret['ean'] != '') - { - $arr['ean'] = $ret['ean']; - } - if(isset($ret['gewicht']) && $ret['gewicht'] !== '') - { - $arr['gewicht'] = $ret['gewicht']; - } - if(isset($ret['laenge']) && $ret['laenge'] !== '') - { - $arr['laenge'] = $ret['laenge']; - } - if(isset($ret['hoehe']) && $ret['hoehe'] !== '') - { - $arr['hoehe'] = $ret['hoehe']; - } - if(isset($ret['breite']) && $ret['breite'] !== '') - { - $arr['breite'] = $ret['breite']; - } - - if(!$articleid){ - $arr['lagerartikel'] = 1; - } - if(true) - { - if(!empty($ret['umsatzsteuer'])){ - if(is_numeric($ret['umsatzsteuer'])){ - if($ret['umsatzsteuer'] == $steuersatz_normal) - { - $arr['umsatzsteuer'] = 'normal'; - }elseif($ret['umsatzsteuer'] == $steuersatz_ermaessigt) - { - $arr['umsatzsteuer'] = 'ermaessigt'; - } - }elseif(in_array($ret['umsatzsteuer'], array('normal', 'ermaessigt', 'befreit'))){ - $arr['umsatzsteuer'] = $ret['umsatzsteuer']; + } + } } - } - } + if ((isset($ret['nummerintern']) && $ret['nummerintern'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummerintern']); + } + if (($ret['nummer'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummer']); + } + if (($ret['ean'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['ean']); + } + if ($articleid) { + if (isset($ret['shoparticleid']) && $ret['shoparticleid'] != '' && trim($this->app->DB->real_escape_string($ret['shoparticleid'])) != '') { + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND artikel = '$articleid' AND nummer = '" . trim($this->app->DB->real_escape_string($ret['shoparticleid'])) . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, nummer, bezeichnung) + VALUES ('$articleid','$id','1','" . trim($this->app->DB->real_escape_string($ret['shoparticleid'])) . "','SHOPID')"); + } + } + } + if (!$articleid && !$create) { + continue; + } + if (!$articleid || !$nurneueartikel) { + if ($articleid) { + $arr['id'] = $articleid; + $arr['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + } elseif ($ret['nummer'] == '') { + $arr['nummer'] = $this->app->erp->GetNextArtikelnummer('', 1, $shopexportArr['projekt']); + } + /* if(isset($ret['nummer']) && $ret['nummer'] == '' && !is_null($variante_von)) + { + $ret['nummer'] = $_nummer.'-'.$ret['nummer']; + $arr['nummer'] = $ret['nummer']; + } */ + if (isset($ret['stueckliste']) && empty($variante_von)) { + $arr['stueckliste'] = $ret['stueckliste']; + } + $arr['projekt'] = $shopexportArr['projekt']; + $arr['name_de'] = $ret['name']; + $arr['uebersicht_de'] = $ret['uebersicht_de'] ?? ''; + $arr['kurztext_de'] = $ret['kurztext_de'] ?? ''; + $arr['name_en'] = $ret['name_en']; + $arr['uebersicht_en'] = $ret['uebersicht_en'] ?? ''; + $arr['kurztext_en'] = $ret['kurztext_en'] ?? ''; + $arr['metakeywords_de'] = $ret['metakeywords_de'] ?? ''; + $arr['metakeywords_en'] = $ret['metakeywords_en'] ?? ''; + $arr['metatitle_de'] = $ret['metatitle_de'] ?? ''; + $arr['metatitle_en'] = $ret['metatitle_en'] ?? ''; + $arr['metadescription_de'] = $ret['metadescription_de'] ?? ''; + $arr['metadescription_en'] = $ret['metadescription_en'] ?? ''; + //$arr['anabregs_text'] = isset($ret['uebersicht_de'])?$ret['uebersicht_de']:''; + if (isset($ret['ean']) && $ret['ean'] != '') { + $arr['ean'] = $ret['ean']; + } + if (isset($ret['gewicht']) && $ret['gewicht'] !== '') { + $arr['gewicht'] = $ret['gewicht']; + } + if (isset($ret['laenge']) && $ret['laenge'] !== '') { + $arr['laenge'] = $ret['laenge']; + } + if (isset($ret['hoehe']) && $ret['hoehe'] !== '') { + $arr['hoehe'] = $ret['hoehe']; + } + if (isset($ret['breite']) && $ret['breite'] !== '') { + $arr['breite'] = $ret['breite']; + } - $arr['hersteller'] = $ret['hersteller']; - if(!$stuecklistenmechanik && isset($ret['variante_von']) && !$articleid){ - $variantevon = $this->app->DB->Select("SELECT artikel + if (!$articleid) { + $arr['lagerartikel'] = 1; + } + if (true) { + if (!empty($ret['umsatzsteuer'])) { + if (is_numeric($ret['umsatzsteuer'])) { + if ($ret['umsatzsteuer'] == $steuersatz_normal) { + $arr['umsatzsteuer'] = 'normal'; + } elseif ($ret['umsatzsteuer'] == $steuersatz_ermaessigt) { + $arr['umsatzsteuer'] = 'ermaessigt'; + } + } elseif (in_array($ret['umsatzsteuer'], array('normal', 'ermaessigt', 'befreit'))) { + $arr['umsatzsteuer'] = $ret['umsatzsteuer']; + } + } + } + + $arr['hersteller'] = $ret['hersteller']; + if (!$stuecklistenmechanik && isset($ret['variante_von']) && !$articleid) { + $variantevon = $this->app->DB->Select("SELECT artikel FROM `artikelnummer_fremdnummern` - WHERE shopid = '$id' AND aktiv = 1 AND nummer = '".trim($ret['variante_von'])."' AND nummer <> '' + WHERE shopid = '$id' AND aktiv = 1 AND nummer = '" . trim($ret['variante_von']) . "' AND nummer <> '' LIMIT 1"); - if(empty($variantevon)) - { - $variantevon = $this->app->DB->Select("SELECT id + if (empty($variantevon)) { + $variantevon = $this->app->DB->Select("SELECT id FROM artikel - WHERE ifnull(geloescht,0) = 0 AND nummer <> 'DEL' AND nummer <> '' AND nummer = '".trim($ret['variante_von'])."' + WHERE ifnull(geloescht,0) = 0 AND nummer <> 'DEL' AND nummer <> '' AND nummer = '" . trim($ret['variante_von']) . "' ORDER BY projekt = '$projekt' DESC LIMIT 1"); - } - if(empty($variantevon)) - { - $variantevon = $variantevonorig; - } - if(!empty($variantevon)) - { - $arr['variante'] = 1; - $arr['variante_von'] = $variantevon; - } - }elseif($variante_von) - { - if($variante_von) - { - $arr['variante'] = 1; - } - if($variante_von) - { - $arr['variante_von'] = $variante_von; - } - } - $freifeldmapping = $this->app->DB->SelectArr("SELECT * + } + if (empty($variantevon)) { + $variantevon = $variantevonorig; + } + if (!empty($variantevon)) { + $arr['variante'] = 1; + $arr['variante_von'] = $variantevon; + } + } elseif ($variante_von) { + if ($variante_von) { + $arr['variante'] = 1; + } + if ($variante_von) { + $arr['variante_von'] = $variante_von; + } + } + $freifeldmapping = $this->app->DB->SelectArr("SELECT * FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_shop <> '' AND freifeld_wawi <> ''"); - if(!empty($freifeldmapping)) - { - foreach($freifeldmapping as $freifeldval) - { - $freifeldShopKey = 'freifeld_'.$freifeldval['freifeld_shop']; - if(isset($ret[$freifeldShopKey])) - { - $arr[$freifeldval['freifeld_wawi']] = $ret[$freifeldShopKey]; - } - } - } - $articleid = $this->app->erp->InsertUpdateArtikel($arr); - unset($arr); - if($artikelnummerbeimanlegenausshop && !empty($ret['artikelnummerausshop'])) - { - $this->app->DB->Update("UPDATE artikel SET nummer = '".$ret['artikelnummerausshop']."' WHERE id = '$articleid'"); - } - - $ret['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - if(isset($ret['bilder']) && $ret['bilder'] && is_array($ret['bilder'])) - { - $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); - if(empty($dateien)) - { - foreach($ret['bilder'] as $v) - { - if($v['path'] != '' && $v['content'] != '') - { - $path_parts = pathinfo($v['path']); - $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); - file_put_contents($tmpfilename, base64_decode($v['content'])); - $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); - $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); - if (@is_file($tmpfilename)) - unlink($tmpfilename); - } - } - }elseif($dateien[0]['subjekt'] === 'shopbild'){ - $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = 'Shopbild' WHERE id = '".$dateien[0]['id']."' AND subjekt = 'shopbild' LIMIT 1"); - } - } - if($variante_von === null) - { - $variante_von = $articleid; - $_nummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - $nummer = isset($ret['nummerintern'])?$ret['nummerintern']:(isset($ret['nummer'])?$ret['nummer']:''); - } - if(!empty($ret['preis_netto']) && $ret['preis_netto'] > 0) - { - $this->app->erp->AddVerkaufspreis($articleid,1,0,$ret['preis_netto']); - } - - if(!empty($ret['bilder']) && is_array($ret['bilder'])) - { - $dateien = $this->app->DB->SelectArr("SELECT * + if (!empty($freifeldmapping)) { + foreach ($freifeldmapping as $freifeldval) { + $freifeldShopKey = 'freifeld_' . $freifeldval['freifeld_shop']; + if (isset($ret[$freifeldShopKey])) { + $arr[$freifeldval['freifeld_wawi']] = $ret[$freifeldShopKey]; + } + } + } + $articleid = $this->app->erp->InsertUpdateArtikel($arr); + unset($arr); + if ($artikelnummerbeimanlegenausshop && !empty($ret['artikelnummerausshop'])) { + $this->app->DB->Update("UPDATE artikel SET nummer = '" . $ret['artikelnummerausshop'] . "' WHERE id = '$articleid'"); + } + + $ret['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + if (isset($ret['bilder']) && $ret['bilder'] && is_array($ret['bilder'])) { + $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); + if (empty($dateien)) { + foreach ($ret['bilder'] as $v) { + if ($v['path'] != '' && $v['content'] != '') { + $path_parts = pathinfo($v['path']); + $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); + file_put_contents($tmpfilename, base64_decode($v['content'])); + $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); + $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); + if (@is_file($tmpfilename)) + unlink($tmpfilename); + } + } + } elseif ($dateien[0]['subjekt'] === 'shopbild') { + $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = 'Shopbild' WHERE id = '" . $dateien[0]['id'] . "' AND subjekt = 'shopbild' LIMIT 1"); + } + } + if ($variante_von === null) { + $variante_von = $articleid; + $_nummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + $nummer = isset($ret['nummerintern']) ? $ret['nummerintern'] : (isset($ret['nummer']) ? $ret['nummer'] : ''); + } + if (!empty($ret['preis_netto']) && $ret['preis_netto'] > 0) { + $this->app->erp->AddVerkaufspreis($articleid, 1, 0, $ret['preis_netto']); + } + + if (!empty($ret['bilder']) && is_array($ret['bilder'])) { + $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); - if(empty($dateien)) - { - foreach($ret['bilder'] as $v) - { - if($v['path'] != '' && $v['content'] != '') - { - $path_parts = pathinfo($v['path']); - $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); - file_put_contents($tmpfilename, base64_decode($v['content'])); - $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); - if(isset($v['id'])) - { - $this->ShopexportMappingSet($id, 'datei', $fileid, $v['id'], $articleid); + if (empty($dateien)) { + foreach ($ret['bilder'] as $v) { + if ($v['path'] != '' && $v['content'] != '') { + $path_parts = pathinfo($v['path']); + $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); + file_put_contents($tmpfilename, base64_decode($v['content'])); + $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); + if (isset($v['id'])) { + $this->ShopexportMappingSet($id, 'datei', $fileid, $v['id'], $articleid); + } + $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); + if (@is_file($tmpfilename)) + unlink($tmpfilename); + } + } + } } - $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); - if (@is_file($tmpfilename)) - unlink($tmpfilename); - } - } - } - } - if($crossellingInstalled){ - if(!empty($ret['crossselling'])){ - if(!empty($ret['crossselling']['similar'])){ - foreach ($ret['crossselling']['similar'] as $cskey => $csvalue) { - $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '".$csvalue."' and geloescht='0'"); - if($crosssellingartikel){ - if(!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")){ - $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); - $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','1','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); - } + if ($crossellingInstalled) { + if (!empty($ret['crossselling'])) { + if (!empty($ret['crossselling']['similar'])) { + foreach ($ret['crossselling']['similar'] as $cskey => $csvalue) { + $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '" . $csvalue . "' and geloescht='0'"); + if ($crosssellingartikel) { + if (!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")) { + $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); + $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','1','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); + } + } + } + } + if (!empty($ret['crossselling']['related'])) { + foreach ($ret['crossselling']['related'] as $cskey => $csvalue) { + $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '" . $csvalue . "' and geloescht='0'"); + if ($crosssellingartikel) { + if (!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")) { + $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); + $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','2','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); + } + } + } + } + } } - } - } - if(!empty($ret['crossselling']['related'])){ - foreach ($ret['crossselling']['related'] as $cskey => $csvalue) { - $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '".$csvalue."' and geloescht='0'"); - if($crosssellingartikel){ - if(!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")){ - $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); - $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','2','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); - } - } - } - } - } - } - $katext = 0; - if(isset($ret['kategorien_all']) && $ret['kategorien_all']) - { - foreach($ret['kategorien_all'] as $v) - { - if($katext == 0 && $v['parent'] == 0) - { - $katext = $v['id']; - } - if(!$this->app->DB->Select("SELECT id + $katext = 0; + if (isset($ret['kategorien_all']) && $ret['kategorien_all']) { + foreach ($ret['kategorien_all'] as $v) { + if ($katext == 0 && $v['parent'] == 0) { + $katext = $v['id']; + } + if (!$this->app->DB->Select("SELECT id FROM shopexport_kategorien - WHERE shop = '$id' AND extid = '".$this->app->DB->real_escape_string($v['id'])."' LIMIT 1")){ - $this->app->DB->Insert("INSERT INTO shopexport_kategorien (shop, extid, aktiv,extname,extparent,extsort) VALUES - ('$id','" . $this->app->DB->real_escape_string($v['id']) . "','" . (int)$v['aktiv'] . "','" . $this->app->DB->real_escape_string($v['name']) . "','" . $this->app->DB->real_escape_string($v['parent']) . "','" . (int)$v['sort'] . "')"); - } - } - $shopkategorien = $this->getShopKatgeorien($id); - /** @var Onlineshops $onlineShopObj */ - $onlineShopObj = $this->app->loadModule('onlineshops'); - $categoryRootId = 0; - if(!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { - $categoryRootId = (int)$onlineShopObj->getJsonSettings($id, 'category_root_id'); - } - $kategorientoint = [$categoryRootId]; + WHERE shop = '$id' AND extid = '" . $this->app->DB->real_escape_string($v['id']) . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO shopexport_kategorien (shop, extid, aktiv,extname,extparent,extsort) VALUES + ('$id','" . $this->app->DB->real_escape_string($v['id']) . "','" . (int) $v['aktiv'] . "','" . $this->app->DB->real_escape_string($v['name']) . "','" . $this->app->DB->real_escape_string($v['parent']) . "','" . (int) $v['sort'] . "')"); + } + } + $shopkategorien = $this->getShopKatgeorien($id); + /** @var Onlineshops $onlineShopObj */ + $onlineShopObj = $this->app->loadModule('onlineshops'); + $categoryRootId = 0; + if (!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { + $categoryRootId = (int) $onlineShopObj->getJsonSettings($id, 'category_root_id'); + } + $kategorientoint = [$categoryRootId]; - if(!empty($shopkategorien)) - { - foreach($shopkategorien as $v) - { - if(!$v['kategorie']) - { - $parentInXentral = $kategorientoint[$v['extparent']]; - if(empty($parentInXentral)){ - $parentInXentral = $this->app->DB->Select("SELECT kategorie FROM shopexport_kategorien WHERE shop='$id' AND extid='".$v['extparent']."' LIMIT 1"); + if (!empty($shopkategorien)) { + foreach ($shopkategorien as $v) { + if (!$v['kategorie']) { + $parentInXentral = $kategorientoint[$v['extparent']]; + if (empty($parentInXentral)) { + $parentInXentral = $this->app->DB->Select("SELECT kategorie FROM shopexport_kategorien WHERE shop='$id' AND extid='" . $v['extparent'] . "' LIMIT 1"); + } + $this->app->DB->Insert("INSERT INTO `artikelkategorien` (bezeichnung,parent) + VALUES ('" . $this->app->DB->real_escape_string($v['extname']) . "','$parentInXentral')"); + $kategorientoint[$v['extid']] = $this->app->DB->GetInsertID(); + $this->app->DB->Update("UPDATE shopexport_kategorien + SET kategorie = '" . $kategorientoint[$v['extid']] . "' + WHERE id = '" . $v['id'] . "' LIMIT 1"); + $v['kategorie'] = $kategorientoint[$v['extid']]; + } + } + } } - $this->app->DB->Insert("INSERT INTO `artikelkategorien` (bezeichnung,parent) - VALUES ('".$this->app->DB->real_escape_string($v['extname'])."','$parentInXentral')"); - $kategorientoint[$v['extid']] = $this->app->DB->GetInsertID(); - $this->app->DB->Update("UPDATE shopexport_kategorien - SET kategorie = '".$kategorientoint[$v['extid']]."' - WHERE id = '".$v['id']."' LIMIT 1"); - $v['kategorie'] = $kategorientoint[$v['extid']]; - } - } - } - } - if(!empty($ret['kategorien'])) - { - $shopkategorien = $this->app->DB->SelectArr("SELECT * + if (!empty($ret['kategorien'])) { + $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$id' AND kategorie > 0 ORDER BY extparent, extsort"); - if(!empty($shopkategorien)) - { - foreach($shopkategorien as $v) - { - $kategorientoint[$v['extid']] = $v['kategorie']; - } - $kategoriezugewiesen = false; - foreach($ret['kategorien'] as $v) - { - if(!$kategoriezugewiesen){ - $kategorieid = $this->app->DB->Select("SELECT id FROM artikelkategorien WHERE bezeichnung='".$v['name']."' AND parent=0 AND geloescht=0 LIMIT 1"); - if($kategorieid){ - $this->app->DB->Update("UPDATE artikel SET typ = '".$kategorieid."_kat' WHERE id = '$articleid' LIMIT 1"); - $kategoriezugewiesen = true; - } - } + if (!empty($shopkategorien)) { + foreach ($shopkategorien as $v) { + $kategorientoint[$v['extid']] = $v['kategorie']; + } + $kategoriezugewiesen = false; + foreach ($ret['kategorien'] as $v) { + if (!$kategoriezugewiesen) { + $kategorieid = $this->app->DB->Select("SELECT id FROM artikelkategorien WHERE bezeichnung='" . $v['name'] . "' AND parent=0 AND geloescht=0 LIMIT 1"); + if ($kategorieid) { + $this->app->DB->Update("UPDATE artikel SET typ = '" . $kategorieid . "_kat' WHERE id = '$articleid' LIMIT 1"); + $kategoriezugewiesen = true; + } + } - if(isset($kategorientoint[$v['id']]) && $kategorientoint[$v['id']]) - { - if(!$this->app->DB->Select("SELECT id FROM artikelbaum_artikel WHERE artikel = '$articleid' AND kategorie = '".$kategorientoint[$v['id']]."' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO artikelbaum_artikel (artikel, kategorie) - VALUES ('$articleid', '".$kategorientoint[$v['id']]."')"); + if (isset($kategorientoint[$v['id']]) && $kategorientoint[$v['id']]) { + if (!$this->app->DB->Select("SELECT id FROM artikelbaum_artikel WHERE artikel = '$articleid' AND kategorie = '" . $kategorientoint[$v['id']] . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO artikelbaum_artikel (artikel, kategorie) + VALUES ('$articleid', '" . $kategorientoint[$v['id']] . "')"); + } + } + } + } } - } - } - } - } - if(!empty($ret['eigenschaften'])) - { - foreach($ret['eigenschaften'] as $v) - { - if($v['name'] != '') - { - $eigenschaft = $this->app->DB->Select("SELECT id + if (!empty($ret['eigenschaften'])) { + foreach ($ret['eigenschaften'] as $v) { + if ($v['name'] != '') { + $eigenschaft = $this->app->DB->Select("SELECT id FROM `artikeleigenschaften` - WHERE name = '".$this->app->DB->real_escape_string($v['name'])."' AND geloescht = 0 + WHERE name = '" . $this->app->DB->real_escape_string($v['name']) . "' AND geloescht = 0 LIMIT 1"); - if(!$eigenschaft) - { - $this->app->DB->Insert("INSERT INTO `artikeleigenschaften` (name) - VALUES ('".$this->app->DB->real_escape_string($v['name'])."')"); - $eigenschaft = $this->app->DB->GetInsertID(); - } - if($eigenschaft) - { - $wert = $this->app->DB->Select("SELECT id + if (!$eigenschaft) { + $this->app->DB->Insert("INSERT INTO `artikeleigenschaften` (name) + VALUES ('" . $this->app->DB->real_escape_string($v['name']) . "')"); + $eigenschaft = $this->app->DB->GetInsertID(); + } + if ($eigenschaft) { + $wert = $this->app->DB->Select("SELECT id FROM artikeleigenschaftenwerte - WHERE artikel = '$articleid' AND artikeleigenschaften = '$eigenschaft' AND wert = '".$this->app->DB->real_escape_string($v['values'])."' + WHERE artikel = '$articleid' AND artikeleigenschaften = '$eigenschaft' AND wert = '" . $this->app->DB->real_escape_string($v['values']) . "' LIMIT 1"); - if(!$wert) - { - $this->app->DB->Insert("INSERT INTO artikeleigenschaftenwerte (artikel,artikeleigenschaften,wert) - VALUES ('$articleid','$eigenschaft','".$this->app->DB->real_escape_string($v['values'])."')"); + if (!$wert) { + $this->app->DB->Insert("INSERT INTO artikeleigenschaftenwerte (artikel,artikeleigenschaften,wert) + VALUES ('$articleid','$eigenschaft','" . $this->app->DB->real_escape_string($v['values']) . "')"); + } + } + } + } } - } - } - } - } - if(!empty($ret['matrixprodukt_gruppe1'])){ - $query = sprintf("UPDATE artikel SET matrixprodukt=1 WHERE id='%s'",$articleid); - $this->app->DB->Update($query); - for($m=1;$m<=3;$m++){ - if(empty($ret['matrixprodukt_gruppe'.$m])){ - continue; - } + if (!empty($ret['matrixprodukt_gruppe1'])) { + $query = sprintf("UPDATE artikel SET matrixprodukt=1 WHERE id='%s'", $articleid); + $this->app->DB->Update($query); + for ($m = 1; $m <= 3; $m++) { + if (empty($ret['matrixprodukt_gruppe' . $m])) { + continue; + } - $gruppeName = $this->app->DB->real_escape_string($ret['matrixprodukt_gruppe'.$m]); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $gruppeName); - $gruppeId = $this->app->DB->Select($query); - if(empty($gruppeId)){ - $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $gruppeName); - $sort = $this->app->DB->Select($query); - if(empty($sort)){ - $sort = '0'; - } - $query = sprintf("INSERT INTO matrixprodukt_eigenschaftengruppen_artikel + $gruppeName = $this->app->DB->real_escape_string($ret['matrixprodukt_gruppe' . $m]); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $gruppeName); + $gruppeId = $this->app->DB->Select($query); + if (empty($gruppeId)) { + $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $gruppeName); + $sort = $this->app->DB->Select($query); + if (empty($sort)) { + $sort = '0'; + } + $query = sprintf("INSERT INTO matrixprodukt_eigenschaftengruppen_artikel (artikel, aktiv, name, name_ext,projekt,bearbeiter,erstellt,sort, pflicht, oeffentlich,typ) VALUES ('%s','1','%s','','0','','NOW()','%s','1','0','0')", $articleid, $gruppeName, $sort); - $this->app->DB->Insert($query); - $gruppeId = $this->app->DB->GetInsertID(); - } + $this->app->DB->Insert($query); + $gruppeId = $this->app->DB->GetInsertID(); + } - foreach ($ret['matrixprodukt_optionen'.$m] as $optionBezeichnung){ - $optionBezeichnung = $this->app->DB->real_escape_string($optionBezeichnung); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $optionBezeichnung); - $optionId = $this->app->DB->Select($query); - if(empty($optionId)){ - $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $optionBezeichnung); - $sort = $this->app->DB->Select($query); - if(empty($sort)){ - $sort = '1'; - } - $query = sprintf("INSERT INTO matrixprodukt_eigenschaftenoptionen_artikel + foreach ($ret['matrixprodukt_optionen' . $m] as $optionBezeichnung) { + $optionBezeichnung = $this->app->DB->real_escape_string($optionBezeichnung); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $optionBezeichnung); + $optionId = $this->app->DB->Select($query); + if (empty($optionId)) { + $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $optionBezeichnung); + $sort = $this->app->DB->Select($query); + if (empty($sort)) { + $sort = '1'; + } + $query = sprintf("INSERT INTO matrixprodukt_eigenschaftenoptionen_artikel (artikel, matrixprodukt_eigenschaftenoptionen, aktiv,name,name_ext,sort,erstellt,gruppe,bearbeiter,artikelnummer) VALUES ('%s','0','1','%s','','%s','NOW()','%s','','')", - $articleid, $optionBezeichnung, $sort, $gruppeId); - $this->app->DB->Insert($query); - } - } - } - } + $articleid, $optionBezeichnung, $sort, $gruppeId); + $this->app->DB->Insert($query); + } + } + } + } - if(!empty($ret['matrixprodukt_wert1'])){ - for($m=1;$m<=3;$m++){ - if(empty($ret['matrixprodukt_wert'.$m])){ - continue; + if (!empty($ret['matrixprodukt_wert1'])) { + for ($m = 1; $m <= 3; $m++) { + if (empty($ret['matrixprodukt_wert' . $m])) { + continue; + } + + $optionBezeichnung = $this->app->DB->real_escape_string($ret['matrixprodukt_wert' . $m]); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $variante_von, $optionBezeichnung); + $optionId = $this->app->DB->Select($query); + if (!empty($optionId)) { + $query = sprintf("SELECT id FROM matrixprodukt_optionen_zu_artikel WHERE artikel='%s' AND option_id='%s'", + $articleid, $optionId); + $zuordnungId = $this->app->DB->Select($query); + if (empty($zuordnungId)) { + $query = sprintf("INSERT INTO matrixprodukt_optionen_zu_artikel (artikel,option_id) VALUES ('%s','%s')", + $articleid, $optionId); + $this->app->DB->Insert($query); + } + } + } + } + + if (!$this->app->DB->Select("SELECT id FROM `artikel_onlineshops` WHERE artikel = '$articleid' AND shop = '$id' AND aktiv = 1 LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikel_onlineshops` (artikel, shop,aktiv, ausartikel) VALUES ('$articleid', '$id',1 ,1)"); + } + if (isset($ret['nummerintern']) && trim($ret['nummerintern']) != '') { + $data['nummerintern'] = trim($ret['nummerintern']); + } + if (($ret['nummer'] != $data['nummerintern']) && $data['nummerintern'] != '' && trim($data['nummerintern']) != '') { + $data['nummerintern'] = trim($data['nummerintern']); + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$articleid' AND shopid = '$id' AND nummer = '" . $this->app->DB->real_escape_string($data['nummerintern']) . "' AND nummer <> '' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, bearbeiter, zeitstempel,nummer) VALUES ('$articleid','$id','1','Cronjob',now(),'" . $this->app->DB->real_escape_string($data['nummerintern']) . "')"); + } + } + } elseif ($articleid) { + if (isset($ret['ean']) && ($ret['ean'] != '') && $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1")) { + $this->app->DB->Update("UPDATE artikel SET ean = '" . $this->app->DB->real_escape_string($ret['ean']) . "' WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1"); + } } - $optionBezeichnung = $this->app->DB->real_escape_string($ret['matrixprodukt_wert'.$m]); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $variante_von, $optionBezeichnung); - $optionId = $this->app->DB->Select($query); - if(!empty($optionId)){ - $query = sprintf("SELECT id FROM matrixprodukt_optionen_zu_artikel WHERE artikel='%s' AND option_id='%s'", - $articleid, $optionId); - $zuordnungId = $this->app->DB->Select($query); - if(empty($zuordnungId)){ - $query = sprintf("INSERT INTO matrixprodukt_optionen_zu_artikel (artikel,option_id) VALUES ('%s','%s')", - $articleid,$optionId); - $this->app->DB->Insert($query); - } - } - } - } - - if(!$this->app->DB->Select("SELECT id FROM `artikel_onlineshops` WHERE artikel = '$articleid' AND shop = '$id' AND aktiv = 1 LIMIT 1")) { - $this->app->DB->Insert("INSERT INTO `artikel_onlineshops` (artikel, shop,aktiv, ausartikel) VALUES ('$articleid', '$id',1 ,1)"); - } - if(isset($ret['nummerintern']) && trim($ret['nummerintern']) != '') - { - $data['nummerintern'] = trim($ret['nummerintern']); - } - if(($ret['nummer'] != $data['nummerintern']) && $data['nummerintern'] != '' && trim($data['nummerintern']) != '') - { - $data['nummerintern'] = trim($data['nummerintern']); - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$articleid' AND shopid = '$id' AND nummer = '".$this->app->DB->real_escape_string($data['nummerintern'])."' AND nummer <> '' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, bearbeiter, zeitstempel,nummer) VALUES ('$articleid','$id','1','Cronjob',now(),'".$this->app->DB->real_escape_string($data['nummerintern'])."')"); - } - } - }elseif($articleid) - { - if(isset($ret['ean']) && ($ret['ean'] != '') && $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1")) - { - $this->app->DB->Update("UPDATE artikel SET ean = '".$this->app->DB->real_escape_string($ret['ean'])."' WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1"); - } - } - - if($stuecklistenmechanik && !empty($variante_von) && !$this->app->erp->IstStuecklistenZirkel($articleid,$variante_von)){ - $stuecklistenmenge = 1; - if(!empty($ret['stuecklistemenge'])){ - $stuecklistenmenge = $ret['stuecklistemenge']; - } - $query = sprintf('SELECT MAX(sort) FROM stueckliste WHERE stuecklistevonartikel=%d',$variante_von); - $sort = $this->app->DB->Select($query); - if($sort !== NULL){ - $sort++; - }else{ - $sort = 0; - } - $query = sprintf("INSERT INTO stueckliste (sort, artikel, referenz, place, layer, stuecklistevonartikel, + if ($stuecklistenmechanik && !empty($variante_von) && !$this->app->erp->IstStuecklistenZirkel($articleid, $variante_von)) { + $stuecklistenmenge = 1; + if (!empty($ret['stuecklistemenge'])) { + $stuecklistenmenge = $ret['stuecklistemenge']; + } + $query = sprintf('SELECT MAX(sort) FROM stueckliste WHERE stuecklistevonartikel=%d', $variante_von); + $sort = $this->app->DB->Select($query); + if ($sort !== NULL) { + $sort++; + } else { + $sort = 0; + } + $query = sprintf("INSERT INTO stueckliste (sort, artikel, referenz, place, layer, stuecklistevonartikel, menge, firma, wert, bauform, alternative, zachse, xpos, ypos, art) VALUES (%d, %d, '', 'DP', 'Top', %d, %d, 1, '', '', 0, '', '', '', 'et')", - $sort,$articleid,$variante_von,$stuecklistenmenge); - $this->app->DB->Insert($query); - } - - if($variante_von === null) { - if(!empty($articleid) && $stuecklistenmechanik){ - $query = sprintf('DELETE FROM stueckliste WHERE stuecklistevonartikel=%d',$articleid); - $this->app->DB->Delete($query); - } - $variante_von = $articleid; - } - - if(isset($ret['inaktiv'])){ - $ret['aktiv'] = !$ret['inaktiv']; - } - - if(isset($ret['aktiv'])) - { - if($ret['aktiv']){ - $this->app->DB->Update("UPDATE artikel SET inaktiv = '0' WHERE id = '$articleid' LIMIT 1"); - }else{ - $this->app->DB->Update("UPDATE artikel SET inaktiv = '1' WHERE id = '$articleid' LIMIT 1"); - } - } - if(isset($ret['staffelpreise'])){ - $date = new DateTime(); - $date->sub(new DateInterval('P1D')); - $gestern = $date->format('Y-m-d'); - $this->app->DB->Update("UPDATE verkaufspreise SET gueltig_bis='$gestern' WHERE artikel='$articleid' AND adresse='0' AND art='Kunde'"); - - foreach ($ret['staffelpreise'] as $staffelpreis){ - $preis = $staffelpreis['preis']; - if($staffelpreis['brutto']){ - $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$articleid' LIMIT 1"); - $steuersatz = 0; - if($umsatzsteuer === 'ermaessigt') - { - $steuersatz = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + $sort, $articleid, $variante_von, $stuecklistenmenge); + $this->app->DB->Insert($query); } - if($umsatzsteuer === 'normal'){ - $steuersatz = $this->app->erp->Firmendaten('steuersatz_normal'); - } - $preis /= 1+$steuersatz/100; - } - $this->app->erp->AddVerkaufspreis($articleid,$staffelpreis['ab_menge'],0,$preis); - } - } - if(isset($ret['fremdnummern']) && !empty($ret['fremdnummern'])){ - foreach ($ret['fremdnummern'] as $fremdnummer){ - $query = sprintf("SELECT id FROM artikelnummer_fremdnummern WHERE shopid=%d AND nummer='%s' AND bezeichnung='%s' AND aktiv=%d AND artikel=%s", - $id,$this->app->DB->real_escape_string($fremdnummer['nummer']),$this->app->DB->real_escape_string($fremdnummer['bezeichnung']),'1',$articleid); - $fremdnummerfehlt = empty($this->app->DB->Select($query)); - if($fremdnummerfehlt){ - $query = sprintf("INSERT INTO artikelnummer_fremdnummern + if ($variante_von === null) { + if (!empty($articleid) && $stuecklistenmechanik) { + $query = sprintf('DELETE FROM stueckliste WHERE stuecklistevonartikel=%d', $articleid); + $this->app->DB->Delete($query); + } + $variante_von = $articleid; + } + + if (isset($ret['inaktiv'])) { + $ret['aktiv'] = !$ret['inaktiv']; + } + + if (isset($ret['aktiv'])) { + if ($ret['aktiv']) { + $this->app->DB->Update("UPDATE artikel SET inaktiv = '0' WHERE id = '$articleid' LIMIT 1"); + } else { + $this->app->DB->Update("UPDATE artikel SET inaktiv = '1' WHERE id = '$articleid' LIMIT 1"); + } + } + if (isset($ret['staffelpreise'])) { + $date = new DateTime(); + $date->sub(new DateInterval('P1D')); + $gestern = $date->format('Y-m-d'); + $this->app->DB->Update("UPDATE verkaufspreise SET gueltig_bis='$gestern' WHERE artikel='$articleid' AND adresse='0' AND art='Kunde'"); + + foreach ($ret['staffelpreise'] as $staffelpreis) { + $preis = $staffelpreis['preis']; + if ($staffelpreis['brutto']) { + $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$articleid' LIMIT 1"); + $steuersatz = 0; + if ($umsatzsteuer === 'ermaessigt') { + $steuersatz = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + } + if ($umsatzsteuer === 'normal') { + $steuersatz = $this->app->erp->Firmendaten('steuersatz_normal'); + } + $preis /= 1 + $steuersatz / 100; + } + $this->app->erp->AddVerkaufspreis($articleid, $staffelpreis['ab_menge'], 0, $preis); + } + } + if (isset($ret['fremdnummern']) && !empty($ret['fremdnummern'])) { + foreach ($ret['fremdnummern'] as $fremdnummer) { + $query = sprintf("SELECT id FROM artikelnummer_fremdnummern WHERE shopid=%d AND nummer='%s' AND bezeichnung='%s' AND aktiv=%d AND artikel=%s", + $id, $this->app->DB->real_escape_string($fremdnummer['nummer']), $this->app->DB->real_escape_string($fremdnummer['bezeichnung']), '1', $articleid); + $fremdnummerfehlt = empty($this->app->DB->Select($query)); + + if ($fremdnummerfehlt) { + $query = sprintf("INSERT INTO artikelnummer_fremdnummern (artikel, bezeichnung, nummer, shopid, bearbeiter, aktiv) VALUES (%d,'%s','%s',%d,'%s',%d)", - $articleid,$this->app->DB->real_escape_string($fremdnummer['bezeichnung']), - $this->app->DB->real_escape_string($fremdnummer['nummer']),$id,$this->app->User->GetName(),1); - $this->app->DB->Insert($query); - } - } - } + $articleid, $this->app->DB->real_escape_string($fremdnummer['bezeichnung']), + $this->app->DB->real_escape_string($fremdnummer['nummer']), $id, $this->app->User->GetName(), 1); + $this->app->DB->Insert($query); + } + } + } + + if (isset($ret['pseudopreis'])) { + $this->app->DB->Update(sprintf("UPDATE artikel SET pseudopreis='%s' WHERE id=%d", $ret['pseudopreis'], $articleid)); + } + if (!$create) { + return $ret; + } + } - if(isset($ret['pseudopreis'])){ - $this->app->DB->Update(sprintf("UPDATE artikel SET pseudopreis='%s' WHERE id=%d",$ret['pseudopreis'],$articleid)); - } - if(!$create) - { return $ret; - } } - return $ret; - } - - /** - * @param int $shopId - * @param int $parent - * @param int $lvl - * - * @return array - */ - protected function getShopKatgeorien($shopId, $parent = 0, $lvl = 0) - { - if($lvl > 20) - { - return []; - } - $ret = []; - $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$shopId' AND extparent = '$parent' AND extid <> '' ORDER BY extsort"); - if($shopkategorien) - { - foreach($shopkategorien as $v) - { - $ret[] = $v; - $subkategorien = $this->getShopKatgeorien($shopId, $v['extid'], $lvl + 1); - if(!empty($subkategorien)) - { - foreach($subkategorien as $v2) - { - $ret[] = $v2; - } + /** + * @param int $shopId + * @param int $parent + * @param int $lvl + * + * @return array + */ + protected function getShopKatgeorien($shopId, $parent = 0, $lvl = 0) { + if ($lvl > 20) { + return []; } - } - } - - return $ret; - } - - /** - * @param int $id - * @param array $artikel_arr - * @param string|array $extnummer - * @param bool $nurlager - * - * @return mixed|null - * @throws Exception - */ - public function RemoteSendArticleList($id,$artikel_arr, $extnummer = '', $nurlager = false) - { - - $this->logger->debug( - 'RemoteSendArticleList', - [ - 'artikel_arr' => $artikel_arr - ] - ); - - if(!class_exists('ObjGenArtikel') && - is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')){ - include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; - } - $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - $artikelexport = $shopexportarr['artikelexport']; - $translationpossible = false; - if($this->app->erp->ModulVorhanden('artikel_texte')) - { - $translationpossible = true; - } - $loadElements = [ - 'foreign_numbers' => true, - 'article_descriptions' => true, - 'translations' => true, - 'categories' => true, - 'properties' => true, - 'pictures' => true, - 'cross_selling' => true, - 'bulk_prices' => true, - 'standard_price' => true, - 'variants' => true, - 'free_fields' => true, - ]; - - if( - ($nurlager || empty($artikelexport)) - && !empty($shopexportarr['modulename']) - && !is_file(dirname(__DIR__).'/pages/'.$shopexportarr['modulename'].'_custom.php') - ) { - $elementsNotNeededByModule = ShopimporterBase::storageNotNeededElements($shopexportarr['modulename']); - foreach($elementsNotNeededByModule as $element) { - $loadElements[$element] = false; - } - } - - //$lagerexport = $shopexportarr['lagerexport']; - $lagergrundlage = $shopexportarr['lagergrundlage']; - $shopbilderuebertragen = $shopexportarr['shopbilderuebertragen']; - $projekt = (int)$shopexportarr['projekt']; - $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = $projekt AND projektlager = 1 LIMIT 1"); - $tmp = new ObjGenArtikel($this->app); - $cartikel_arr = !empty($artikel_arr)?count($artikel_arr):0; - - for($i=0;$i<$cartikel_arr;$i++) - { - $artikel = $artikel_arr[$i]; - - $this->logger->debug( - 'RemoteSendArticleList', - [ - 'artikel' => $artikel, - 'i' => $i - ] - ); - - $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); - $tmp->Select($artikel); - $data[$i] = ['artikel' => $artikel,'artikelid' => $artikel]; - $data[$i]['nummer'] = $tmp->GetNummer(); - $projekt = $tmp->GetProjekt(); - if(is_array($extnummer) && (!empty($extnummer)?count($extnummer):0) > $i && !empty($extnummer[$i]) && trim($extnummer[$i]) != '') - { - if($data[$i]['nummer'] != trim($extnummer[$i])){ - $data[$i]['fremdnummer'] = trim($extnummer[$i]); - } - } - - $data[$i]['inaktiv'] = $tmp->GetInaktiv(); - - if($tmp->GetIntern_Gesperrt()=='1'){ - $data[$i]['inaktiv'] = 1; - } - - $data[$i]['name_de'] = $tmp->GetName_De(); - $data[$i]['name_en'] = $tmp->GetName_En(); - $data[$i]['einheit'] = $tmp->GetEinheit(); - $data[$i]['hersteller'] = $tmp->GetHersteller(); - $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); - $data[$i]['ean'] = $tmp->GetEan(); - if(!empty($loadElements['foreign_numbers'])) { - $data[$i]['artikelnummer_fremdnummern'] = $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $tmp->GetId() . "' AND shopid = '$id' AND aktiv = '1' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC"); - if(!empty($data[$i]['artikelnummer_fremdnummern'])){ - foreach ($data[$i]['artikelnummer_fremdnummern'] as $fkey => $fval) { - $data[$i]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); - } - } - } - - if(!empty($loadElements['article_descriptions'])) { - $data[$i]['kurztext_de'] = $tmp->GetKurztext_De(); - $data[$i]['kurztext_en'] = $tmp->GetKurztext_En(); - $data[$i]['anabregs_text'] = htmlspecialchars($tmp->GetAnabregs_Text(),ENT_QUOTES); - $data[$i]['anabregs_text_en'] = htmlspecialchars($tmp->GetAnabregs_Text_En(),ENT_QUOTES); - $data[$i]['beschreibung_de'] = $tmp->GetBeschreibung_De(); - $data[$i]['beschreibung_en'] = $tmp->GetBeschreibung_En(); - $data[$i]['uebersicht_de'] = htmlspecialchars($tmp->GetUebersicht_De(),ENT_QUOTES); - $data[$i]['uebersicht_en'] = htmlspecialchars($tmp->GetUebersicht_En(),ENT_QUOTES); - $data[$i]['herkunftsland'] = $tmp->GetHerkunftsland(); - - $data[$i]['texteuebertragen'] = $shopexportarr['texteuebertragen']; - - if(method_exists($tmp,'GetMetadescription_De')) - { - $data[$i]['metadescription_de'] = $tmp->GetMetadescription_De(); - } - if(method_exists($tmp,'GetMetadescription_En')) - { - $data[$i]['metadescription_en'] = $tmp->GetMetadescription_En(); - } - if(method_exists($tmp,'GetMetakeywords_De')) - { - $data[$i]['metakeywords_de'] = $tmp->GetMetakeywords_De(); - } - if(method_exists($tmp,'GetMetakeywords_En')) - { - $data[$i]['metakeywords_en'] = $tmp->GetMetakeywords_En(); - } - if(method_exists($tmp,'GetMetatitle_De')) - { - $data[$i]['metatitle_de'] = $tmp->GetMetatitle_De(); - } - if(method_exists($tmp,'GetMetatitle_En')) - { - $data[$i]['metatitle_en'] = $tmp->GetMetatitle_En(); - } - } - if($tmp->GetVariante()) - { - $variante_von = $tmp->GetVariante_Von(); - if($variante_von) - { - $tmp_2 = new ObjGenArtikel($this->app); - $tmp_2->Select($variante_von); - if($data[$i]['kurztext_de'] == '') - { - $data[$i]['kurztext_de'] = $tmp_2->GetKurztext_De(); - } - if($data[$i]['kurztext_en'] == '') - { - $data[$i]['kurztext_en'] = $tmp_2->GetKurztext_En(); - } - if($data[$i]['beschreibung_de'] == '') - { - $data[$i]['beschreibung_de'] = $tmp_2->GetBeschreibung_De(); - } - if($data[$i]['beschreibung_en'] == '') - { - $data[$i]['beschreibung_en'] = $tmp_2->GetBeschreibung_En(); - } - if($data[$i]['uebersicht_de'] == '') - { - $data[$i]['uebersicht_de'] = htmlspecialchars($tmp_2->GetUebersicht_De(),ENT_QUOTES); - } - if($data[$i]['uebersicht_en'] == '') - { - $data[$i]['uebersicht_en'] = htmlspecialchars($tmp_2->GetUebersicht_En(),ENT_QUOTES); - } - } - } - - if($data[$i]['uebersicht_de'] == '' && $data[$i]['beschreibung_de'] == '' && $data[$i]['kurztext_de'] == '') - { - $data[$i]['uebersicht_de'] = $data[$i]['anabregs_text']; - } - - $data[$i]['links_de'] = $tmp->GetLinks_De(); - $data[$i]['altersfreigabe'] = $tmp->GetAltersfreigabe(); - $data[$i]['links_en'] = $tmp->GetLinks_En(); - $data[$i]['startseite_de'] = $tmp->GetStartseite_De(); - $data[$i]['startseite_en'] = $tmp->GetStartseite_En(); - $data[$i]['restmenge'] = $this->app->erp->GetArtikelShopEinstellung('restmenge', $artikel, $shopexportarr); - $data[$i]['startseite'] = $tmp->GetStartseite(); - $data[$i]['standardbild'] = $tmp->GetStandardbild(); - $data[$i]['herstellerlink'] = $tmp->GetHerstellerlink(); - $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); - $data[$i]['hersteller'] = $tmp->GetHersteller(); - $data[$i]['lieferzeit'] = $tmp->GetLieferzeit(); - $data[$i]['lieferzeitmanuell'] = $this->app->erp->GetArtikelShopEinstellung('lieferzeitmanuell', $artikel, $shopexportarr); - $data[$i]['gewicht'] = $tmp->GetGewicht(); - $data[$i]['laenge'] = $tmp->GetLaenge(); - $data[$i]['breite'] = $tmp->GetBreite(); - $data[$i]['hoehe'] = $tmp->GetHoehe(); - - $data[$i]['wichtig'] = $tmp->GetWichtig(); - $data[$i]['porto'] = $tmp->GetPorto(); - $data[$i]['gesperrt'] = $tmp->GetGesperrt(); - $data[$i]['sperrgrund'] = $tmp->GetSperrgrund(); - $data[$i]['gueltigbis'] = $tmp->GetGueltigbis(); - $data[$i]['umsatzsteuer'] = $tmp->GetUmsatzsteuer(); - if($data[$i]['umsatzsteuer']!=='ermaessigt' && $data[$i]['umsatzsteuer']!=='befreit') { - $data[$i]['umsatzsteuer']="normal"; - } - $data[$i]['ausverkauft'] = $tmp->GetAusverkauft(); - $data[$i]['variante'] = $tmp->GetVariante(); - $data[$i]['variante_von_id'] = $tmp->GetVariante_Von(); - $data[$i]['variantevon'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id='".$tmp->GetVariante_Von()."' LIMIT 1"); - $data[$i]['variantevon_fremdnummer'] = trim($this->app->DB->Select("SELECT nummer FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND aktiv = 1 AND artikel = '".$tmp->GetVariante_Von()."' AND trim(nummer) <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1")); - if($data[$i]['variantevon_fremdnummer'] == '') - { - unset($data[$i]['variantevon_fremdnummer']); - } - //$data[$i]['pseudopreis'] = $tmp->GetPseudopreis(); - $data[$i]['pseudopreis'] = $this->app->erp->GetArtikelShopEinstellung('pseudopreis', $artikel, $shopexportarr); - $data[$i]['keinrabatterlaubt'] = $tmp->GetKeinrabatterlaubt(); - $data[$i]['einkaufspreis'] = $this->app->erp->GetEinkaufspreis($artikel,1); - //$data[$i]['pseudolager'] = $tmp->GetPseudolager(); - $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); - if(is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { - $data[$i]['pseudolager'] = 0; - } - $data[$i]['downloadartikel'] = $tmp->GetDownloadartikel(); - $data[$i]['zolltarifnummer'] = $tmp->GetZolltarifnummer(); - $preisgruppe = $this->app->DB->Select("SELECT s.preisgruppe FROM shopexport s INNER JOIN gruppen g ON s.preisgruppe = g.id AND g.aktiv = 1 WHERE s.id='$id' LIMIT 1"); - - if(empty($loadElements['free_fields'])) { - $freifelder = null; - } - else{ - $freifelder = $this->app->DB->SelectArr("SELECT freifeld_wawi, freifeld_shop FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_wawi <> '' AND freifeld_shop <> ''"); - } - if($freifelder) - { - /** - * @deprecated 20.1 - * AP - * Konstrunktion 'freifeld_Mappingname -> Wert' wird ersetzt durch 'Freifelder-> DE -> Mappingname -> Wert' - */ - foreach($freifelder as $freifeld) - { - if(method_exists($tmp,'Get'.ucfirst($freifeld['freifeld_wawi']))) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - $data[$i]['freifeld_'.$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); - } - } - /** - * @deprecated Ende - */ - - foreach($freifelder as $freifeld) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - if(method_exists($tmp,$_funktionsname)) - { - $data[$i]['freifelder']['DE'][$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); - } - } - - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '$artikel' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if(!empty($freifelduebersetzungen)){ - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } - - $data[$i]['typ'] = $tmp->GetTyp(); - $data[$i]['kategoriename'] = $tmp->GetTyp(); - if(strpos($data[$i]['typ'], '_kat')) - { - $data[$i]['kategoriename'] = $this->app->DB->Select("SELECT bezeichnung FROM artikelkategorien WHERE id = '".(int)str_replace('_kat','',$data[$i]['typ'])."' LIMIT 1"); - } - - $kategorienuebertragen = $shopexportarr['kategorienuebertragen'];//$this->app->DB->Select("SELECT kategorienuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); - if(!empty($kategorienuebertragen) && !empty($loadElements['categories'])) - { - $kategorienbaum = null; - /** @var Onlineshops $onlineShopObj */ - $onlineShopObj = $this->app->loadModule('onlineshops'); - $categoryRootId = 0; - if(!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { - $categoryRootId = (int)$onlineShopObj->getJsonSettings($id, 'category_root_id'); - } - $this->app->erp->GetKategorienbaum($kategorienbaum, $categoryRootId, 0, $id); - if(!empty($kategorienbaum)) - { - $kategorien = $this->app->DB->SelectArr("SELECT ak.id, ak.bezeichnung FROM `artikelbaum_artikel` aa INNER JOIN `artikelkategorien` ak ON aa.kategorie = ak.id AND ak.geloescht <> 1 AND aa.artikel = '$artikel' ORDER by ak.bezeichnung"); - if($kategorien) - { - foreach($kategorien as $v) - { - $katid[$v['id']] = true; + $ret = []; + $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$shopId' AND extparent = '$parent' AND extid <> '' ORDER BY extsort"); + if ($shopkategorien) { + foreach ($shopkategorien as $v) { + $ret[] = $v; + $subkategorien = $this->getShopKatgeorien($shopId, $v['extid'], $lvl + 1); + if (!empty($subkategorien)) { + foreach ($subkategorien as $v2) { + $ret[] = $v2; + } + } } - } - if(!empty($katid)) - { - foreach($kategorienbaum as $v) - { - $data[$i]['kompletter_kategorienbaum'][] = array('name'=>$v['bezeichnung'],'parent'=>$v['parent'],'id'=>$v['id'],'lvl'=>$v['lvl'],'extid'=>$v['extid']); - if(isset($katid[$v['id']])) - { - $data[$i]['kategorien'][] = array('name'=>$v['bezeichnung'],'parent'=>$v['parent'],'id'=>$v['id'],'lvl'=>$v['lvl'],'extid'=>$v['extid']); - } - } - } } - } - $eigenschaftenuebertragen = $shopexportarr['eigenschaftenuebertragen'];//$this->app->DB->Select("SELECT eigenschaftenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); - if(!empty($eigenschaftenuebertragen) && !empty($loadElements['properties'])) { - $eigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften + return $ret; + } + + /** + * @param int $id + * @param array $artikel_arr + * @param string|array $extnummer + * @param bool $nurlager + * + * @return mixed|null + * @throws Exception + */ + public function RemoteSendArticleList($id, $artikel_arr, $extnummer = '', $nurlager = false) { + + $this->logger->debug( + 'RemoteSendArticleList', + [ + 'artikel_arr' => $artikel_arr + ] + ); + + if (!class_exists('ObjGenArtikel') && + is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')) { + include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; + } + $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + $artikelexport = $shopexportarr['artikelexport']; + $translationpossible = false; + if ($this->app->erp->ModulVorhanden('artikel_texte')) { + $translationpossible = true; + } + $loadElements = [ + 'foreign_numbers' => true, + 'article_descriptions' => true, + 'translations' => true, + 'categories' => true, + 'properties' => true, + 'pictures' => true, + 'cross_selling' => true, + 'bulk_prices' => true, + 'standard_price' => true, + 'variants' => true, + 'free_fields' => true, + ]; + + if ( + ($nurlager || empty($artikelexport)) && !empty($shopexportarr['modulename']) && !is_file(dirname(__DIR__) . '/pages/' . $shopexportarr['modulename'] . '_custom.php') + ) { + $elementsNotNeededByModule = ShopimporterBase::storageNotNeededElements($shopexportarr['modulename']); + foreach ($elementsNotNeededByModule as $element) { + $loadElements[$element] = false; + } + } + + //$lagerexport = $shopexportarr['lagerexport']; + $lagergrundlage = $shopexportarr['lagergrundlage']; + $shopbilderuebertragen = $shopexportarr['shopbilderuebertragen']; + $projekt = (int) $shopexportarr['projekt']; + $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = $projekt AND projektlager = 1 LIMIT 1"); + $tmp = new ObjGenArtikel($this->app); + $cartikel_arr = !empty($artikel_arr) ? count($artikel_arr) : 0; + + for ($i = 0; $i < $cartikel_arr; $i++) { + $artikel = $artikel_arr[$i]; + + $this->logger->debug( + 'RemoteSendArticleList', + [ + 'artikel' => $artikel, + 'i' => $i + ] + ); + + $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); + $tmp->Select($artikel); + $data[$i] = ['artikel' => $artikel, 'artikelid' => $artikel]; + $data[$i]['nummer'] = $tmp->GetNummer(); + $projekt = $tmp->GetProjekt(); + if (is_array($extnummer) && (!empty($extnummer) ? count($extnummer) : 0) > $i && !empty($extnummer[$i]) && trim($extnummer[$i]) != '') { + if ($data[$i]['nummer'] != trim($extnummer[$i])) { + $data[$i]['fremdnummer'] = trim($extnummer[$i]); + } + } + + $data[$i]['inaktiv'] = $tmp->GetInaktiv(); + + if ($tmp->GetIntern_Gesperrt() == '1') { + $data[$i]['inaktiv'] = 1; + } + + $data[$i]['name_de'] = $tmp->GetName_De(); + $data[$i]['name_en'] = $tmp->GetName_En(); + $data[$i]['einheit'] = $tmp->GetEinheit(); + $data[$i]['hersteller'] = $tmp->GetHersteller(); + $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); + $data[$i]['ean'] = $tmp->GetEan(); + if (!empty($loadElements['foreign_numbers'])) { + $data[$i]['artikelnummer_fremdnummern'] = $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $tmp->GetId() . "' AND shopid = '$id' AND aktiv = '1' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC"); + if (!empty($data[$i]['artikelnummer_fremdnummern'])) { + foreach ($data[$i]['artikelnummer_fremdnummern'] as $fkey => $fval) { + $data[$i]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); + } + } + } + + if (!empty($loadElements['article_descriptions'])) { + $data[$i]['kurztext_de'] = $tmp->GetKurztext_De(); + $data[$i]['kurztext_en'] = $tmp->GetKurztext_En(); + $data[$i]['anabregs_text'] = htmlspecialchars($tmp->GetAnabregs_Text(), ENT_QUOTES); + $data[$i]['anabregs_text_en'] = htmlspecialchars($tmp->GetAnabregs_Text_En(), ENT_QUOTES); + $data[$i]['beschreibung_de'] = $tmp->GetBeschreibung_De(); + $data[$i]['beschreibung_en'] = $tmp->GetBeschreibung_En(); + $data[$i]['uebersicht_de'] = htmlspecialchars($tmp->GetUebersicht_De(), ENT_QUOTES); + $data[$i]['uebersicht_en'] = htmlspecialchars($tmp->GetUebersicht_En(), ENT_QUOTES); + $data[$i]['herkunftsland'] = $tmp->GetHerkunftsland(); + + $data[$i]['texteuebertragen'] = $shopexportarr['texteuebertragen']; + + if (method_exists($tmp, 'GetMetadescription_De')) { + $data[$i]['metadescription_de'] = $tmp->GetMetadescription_De(); + } + if (method_exists($tmp, 'GetMetadescription_En')) { + $data[$i]['metadescription_en'] = $tmp->GetMetadescription_En(); + } + if (method_exists($tmp, 'GetMetakeywords_De')) { + $data[$i]['metakeywords_de'] = $tmp->GetMetakeywords_De(); + } + if (method_exists($tmp, 'GetMetakeywords_En')) { + $data[$i]['metakeywords_en'] = $tmp->GetMetakeywords_En(); + } + if (method_exists($tmp, 'GetMetatitle_De')) { + $data[$i]['metatitle_de'] = $tmp->GetMetatitle_De(); + } + if (method_exists($tmp, 'GetMetatitle_En')) { + $data[$i]['metatitle_en'] = $tmp->GetMetatitle_En(); + } + } + if ($tmp->GetVariante()) { + $variante_von = $tmp->GetVariante_Von(); + if ($variante_von) { + $tmp_2 = new ObjGenArtikel($this->app); + $tmp_2->Select($variante_von); + if ($data[$i]['kurztext_de'] == '') { + $data[$i]['kurztext_de'] = $tmp_2->GetKurztext_De(); + } + if ($data[$i]['kurztext_en'] == '') { + $data[$i]['kurztext_en'] = $tmp_2->GetKurztext_En(); + } + if ($data[$i]['beschreibung_de'] == '') { + $data[$i]['beschreibung_de'] = $tmp_2->GetBeschreibung_De(); + } + if ($data[$i]['beschreibung_en'] == '') { + $data[$i]['beschreibung_en'] = $tmp_2->GetBeschreibung_En(); + } + if ($data[$i]['uebersicht_de'] == '') { + $data[$i]['uebersicht_de'] = htmlspecialchars($tmp_2->GetUebersicht_De(), ENT_QUOTES); + } + if ($data[$i]['uebersicht_en'] == '') { + $data[$i]['uebersicht_en'] = htmlspecialchars($tmp_2->GetUebersicht_En(), ENT_QUOTES); + } + } + } + + if ($data[$i]['uebersicht_de'] == '' && $data[$i]['beschreibung_de'] == '' && $data[$i]['kurztext_de'] == '') { + $data[$i]['uebersicht_de'] = $data[$i]['anabregs_text']; + } + + $data[$i]['links_de'] = $tmp->GetLinks_De(); + $data[$i]['altersfreigabe'] = $tmp->GetAltersfreigabe(); + $data[$i]['links_en'] = $tmp->GetLinks_En(); + $data[$i]['startseite_de'] = $tmp->GetStartseite_De(); + $data[$i]['startseite_en'] = $tmp->GetStartseite_En(); + $data[$i]['restmenge'] = $this->app->erp->GetArtikelShopEinstellung('restmenge', $artikel, $shopexportarr); + $data[$i]['startseite'] = $tmp->GetStartseite(); + $data[$i]['standardbild'] = $tmp->GetStandardbild(); + $data[$i]['herstellerlink'] = $tmp->GetHerstellerlink(); + $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); + $data[$i]['hersteller'] = $tmp->GetHersteller(); + $data[$i]['lieferzeit'] = $tmp->GetLieferzeit(); + $data[$i]['lieferzeitmanuell'] = $this->app->erp->GetArtikelShopEinstellung('lieferzeitmanuell', $artikel, $shopexportarr); + $data[$i]['gewicht'] = $tmp->GetGewicht(); + $data[$i]['laenge'] = $tmp->GetLaenge(); + $data[$i]['breite'] = $tmp->GetBreite(); + $data[$i]['hoehe'] = $tmp->GetHoehe(); + + $data[$i]['wichtig'] = $tmp->GetWichtig(); + $data[$i]['porto'] = $tmp->GetPorto(); + $data[$i]['gesperrt'] = $tmp->GetGesperrt(); + $data[$i]['sperrgrund'] = $tmp->GetSperrgrund(); + $data[$i]['gueltigbis'] = $tmp->GetGueltigbis(); + $data[$i]['umsatzsteuer'] = $tmp->GetUmsatzsteuer(); + if ($data[$i]['umsatzsteuer'] !== 'ermaessigt' && $data[$i]['umsatzsteuer'] !== 'befreit') { + $data[$i]['umsatzsteuer'] = "normal"; + } + $data[$i]['ausverkauft'] = $tmp->GetAusverkauft(); + $data[$i]['variante'] = $tmp->GetVariante(); + $data[$i]['variante_von_id'] = $tmp->GetVariante_Von(); + $data[$i]['variantevon'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id='" . $tmp->GetVariante_Von() . "' LIMIT 1"); + $data[$i]['variantevon_fremdnummer'] = trim($this->app->DB->Select("SELECT nummer FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND aktiv = 1 AND artikel = '" . $tmp->GetVariante_Von() . "' AND trim(nummer) <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1")); + if ($data[$i]['variantevon_fremdnummer'] == '') { + unset($data[$i]['variantevon_fremdnummer']); + } + //$data[$i]['pseudopreis'] = $tmp->GetPseudopreis(); + $data[$i]['pseudopreis'] = $this->app->erp->GetArtikelShopEinstellung('pseudopreis', $artikel, $shopexportarr); + $data[$i]['keinrabatterlaubt'] = $tmp->GetKeinrabatterlaubt(); + $data[$i]['einkaufspreis'] = $this->app->erp->GetEinkaufspreis($artikel, 1); + //$data[$i]['pseudolager'] = $tmp->GetPseudolager(); + $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); + if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { + $data[$i]['pseudolager'] = 0; + } + $data[$i]['downloadartikel'] = $tmp->GetDownloadartikel(); + $data[$i]['zolltarifnummer'] = $tmp->GetZolltarifnummer(); + $preisgruppe = $this->app->DB->Select("SELECT s.preisgruppe FROM shopexport s INNER JOIN gruppen g ON s.preisgruppe = g.id AND g.aktiv = 1 WHERE s.id='$id' LIMIT 1"); + + if (empty($loadElements['free_fields'])) { + $freifelder = null; + } else { + $freifelder = $this->app->DB->SelectArr("SELECT freifeld_wawi, freifeld_shop FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_wawi <> '' AND freifeld_shop <> ''"); + } + if ($freifelder) { + /** + * @deprecated 20.1 + * AP + * Konstrunktion 'freifeld_Mappingname -> Wert' wird ersetzt durch 'Freifelder-> DE -> Mappingname -> Wert' + */ + foreach ($freifelder as $freifeld) { + if (method_exists($tmp, 'Get' . ucfirst($freifeld['freifeld_wawi']))) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + $data[$i]['freifeld_' . $freifeld['freifeld_shop']] = $tmp->$_funktionsname(); + } + } + /** + * @deprecated Ende + */ + foreach ($freifelder as $freifeld) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + if (method_exists($tmp, $_funktionsname)) { + $data[$i]['freifelder']['DE'][$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); + } + } + + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '$artikel' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } + + $data[$i]['typ'] = $tmp->GetTyp(); + $data[$i]['kategoriename'] = $tmp->GetTyp(); + if (strpos($data[$i]['typ'], '_kat')) { + $data[$i]['kategoriename'] = $this->app->DB->Select("SELECT bezeichnung FROM artikelkategorien WHERE id = '" . (int) str_replace('_kat', '', $data[$i]['typ']) . "' LIMIT 1"); + } + + $kategorienuebertragen = $shopexportarr['kategorienuebertragen']; //$this->app->DB->Select("SELECT kategorienuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); + if (!empty($kategorienuebertragen) && !empty($loadElements['categories'])) { + $kategorienbaum = null; + /** @var Onlineshops $onlineShopObj */ + $onlineShopObj = $this->app->loadModule('onlineshops'); + $categoryRootId = 0; + if (!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { + $categoryRootId = (int) $onlineShopObj->getJsonSettings($id, 'category_root_id'); + } + $this->app->erp->GetKategorienbaum($kategorienbaum, $categoryRootId, 0, $id); + if (!empty($kategorienbaum)) { + $kategorien = $this->app->DB->SelectArr("SELECT ak.id, ak.bezeichnung FROM `artikelbaum_artikel` aa INNER JOIN `artikelkategorien` ak ON aa.kategorie = ak.id AND ak.geloescht <> 1 AND aa.artikel = '$artikel' ORDER by ak.bezeichnung"); + if ($kategorien) { + foreach ($kategorien as $v) { + $katid[$v['id']] = true; + } + } + if (!empty($katid)) { + foreach ($kategorienbaum as $v) { + $data[$i]['kompletter_kategorienbaum'][] = array('name' => $v['bezeichnung'], 'parent' => $v['parent'], 'id' => $v['id'], 'lvl' => $v['lvl'], 'extid' => $v['extid']); + if (isset($katid[$v['id']])) { + $data[$i]['kategorien'][] = array('name' => $v['bezeichnung'], 'parent' => $v['parent'], 'id' => $v['id'], 'lvl' => $v['lvl'], 'extid' => $v['extid']); + } + } + } + } + } + + $eigenschaftenuebertragen = $shopexportarr['eigenschaftenuebertragen']; //$this->app->DB->Select("SELECT eigenschaftenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); + if (!empty($eigenschaftenuebertragen) && !empty($loadElements['properties'])) { + $eigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften WHERE ew.artikel = '$artikel' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1"); - if(!empty($eigenschaften)) - { - $eigenschaftind = 0; - foreach($eigenschaften as $eigenschaft) - { - $eigenschaftind++; - $data[$i]['eigenschaften'][] = array('name'=>$eigenschaft['name'], 'values'=>$eigenschaft['wert']); - } - } + if (!empty($eigenschaften)) { + $eigenschaftind = 0; + foreach ($eigenschaften as $eigenschaft) { + $eigenschaftind++; + $data[$i]['eigenschaften'][] = array('name' => $eigenschaft['name'], 'values' => $eigenschaft['wert']); + } + } - $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '$artikel'"); - $data[$i]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; - } + $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '$artikel'"); + $data[$i]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; + } - //Bilder - $dateien = null; - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($artikel); - if (!empty($dateien)) { - $data[$i]['Dateien'] = []; - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['Dateien'][] = array( - 'datei' => base64_encode($this->app->erp->GetDatei($datei['id'])), - 'filename' => $filename, - 'extension' => $path_info['extension'], - 'titel' => $datei['titel'], - 'beschreibung' => $datei['beschreibung'], - 'id' => $datei['id'], - 'version' => $datei['version'], - 'stichwort' => $datei['subjekt'], - 'extid' => $this->GetShopexportMappingExt($id, 'datei', $datei['id'])); - } - } - $dateiengeloescht = $this->app->DB->SelectArr("SELECT s.extid FROM shopexport_mapping s LEFT JOIN datei d ON s.intid = d.id AND d.geloescht = 0 WHERE s.shop = '$id' AND s.tabelle = 'datei' AND s.intid2 = '$artikel' AND isnull(d.id)"); - if (!empty($dateiengeloescht)) { - if (empty($dateien)) { - $data[$i]['Dateien'] = []; - } - foreach ($dateiengeloescht as $datei) { - $data[$i]['Dateien'][] = array('loeschen' => 1, 'extid' => $datei['extid']); - } - } - } + //Bilder + $dateien = null; + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($artikel); + if (!empty($dateien)) { + $data[$i]['Dateien'] = []; + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['Dateien'][] = array( + 'datei' => base64_encode($this->app->erp->GetDatei($datei['id'])), + 'filename' => $filename, + 'extension' => $path_info['extension'], + 'titel' => $datei['titel'], + 'beschreibung' => $datei['beschreibung'], + 'id' => $datei['id'], + 'version' => $datei['version'], + 'stichwort' => $datei['subjekt'], + 'extid' => $this->GetShopexportMappingExt($id, 'datei', $datei['id'])); + } + } + $dateiengeloescht = $this->app->DB->SelectArr("SELECT s.extid FROM shopexport_mapping s LEFT JOIN datei d ON s.intid = d.id AND d.geloescht = 0 WHERE s.shop = '$id' AND s.tabelle = 'datei' AND s.intid2 = '$artikel' AND isnull(d.id)"); + if (!empty($dateiengeloescht)) { + if (empty($dateien)) { + $data[$i]['Dateien'] = []; + } + foreach ($dateiengeloescht as $datei) { + $data[$i]['Dateien'][] = array('loeschen' => 1, 'extid' => $datei['extid']); + } + } + } - if (method_exists($tmp, 'GetSteuer_Art_Produkt')) { - $data[$i]['steuer_art_produkt'] = $tmp->GetSteuer_Art_Produkt(); - } - if (method_exists($tmp, 'GetSteuer_Art_Produkt_Download')) { - $data[$i]['steuer_art_produkt_download'] = $tmp->GetSteuer_Art_Produkt_Download(); - } + if (method_exists($tmp, 'GetSteuer_Art_Produkt')) { + $data[$i]['steuer_art_produkt'] = $tmp->GetSteuer_Art_Produkt(); + } + if (method_exists($tmp, 'GetSteuer_Art_Produkt_Download')) { + $data[$i]['steuer_art_produkt_download'] = $tmp->GetSteuer_Art_Produkt_Download(); + } - $projekt = $tmp->GetProjekt(); - $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = '$projekt' AND projektlager = 1 LIMIT 1"); - $data[$i]['anzahl_bilder'] = $this->app->DB->Select("SELECT COUNT(datei) FROM datei_stichwoerter WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='$artikel'"); + $projekt = $tmp->GetProjekt(); + $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = '$projekt' AND projektlager = 1 LIMIT 1"); + $data[$i]['anzahl_bilder'] = $this->app->DB->Select("SELECT COUNT(datei) FROM datei_stichwoerter WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='$artikel'"); - $bestandalternativartikel = method_exists($tmp, 'GetBestandalternativartikel') ? $tmp->GetBestandalternativartikel() : 0; + $bestandalternativartikel = method_exists($tmp, 'GetBestandalternativartikel') ? $tmp->GetBestandalternativartikel() : 0; - if ($bestandalternativartikel) { - $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, $id, $lagergrundlage)); - $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); - } else { - $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, $id, $lagergrundlage)); - $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); - } + if ($bestandalternativartikel) { + $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, $id, $lagergrundlage)); + $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); + } else { + $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, $id, $lagergrundlage)); + $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); + } - $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); - if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { - $data[$i]['pseudolager'] = 0; - $data[$i]['anzahl_lager'] = 0; - } elseif ($data[$i]['pseudolager'] > 0) { - $data[$i]['anzahl_lager'] = $data[$i]['pseudolager']; - } - if ($data[$i]['anzahl_lager'] < 0) { - $data[$i]['anzahl_lager'] = 0; - } - $data[$i]['autolagerlampe'] = $tmp->GetAutolagerlampe(); - if (method_exists($this->app->erp, 'GetArtikelShopEinstellung')) { - $data[$i]['autolagerlampe'] = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); - } - if ($data[$i]['autolagerlampe'] != '1') { - $data[$i]['anzahl_lager'] = ''; - $data[$i]['pseudolager'] = ''; - $this->app->DB->Update( - sprintf( - 'UPDATE `artikel_onlineshops` + $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); + if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { + $data[$i]['pseudolager'] = 0; + $data[$i]['anzahl_lager'] = 0; + } elseif ($data[$i]['pseudolager'] > 0) { + $data[$i]['anzahl_lager'] = $data[$i]['pseudolager']; + } + if ($data[$i]['anzahl_lager'] < 0) { + $data[$i]['anzahl_lager'] = 0; + } + $data[$i]['autolagerlampe'] = $tmp->GetAutolagerlampe(); + if (method_exists($this->app->erp, 'GetArtikelShopEinstellung')) { + $data[$i]['autolagerlampe'] = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); + } + if ($data[$i]['autolagerlampe'] != '1') { + $data[$i]['anzahl_lager'] = ''; + $data[$i]['pseudolager'] = ''; + $this->app->DB->Update( + sprintf( + 'UPDATE `artikel_onlineshops` SET `storage_cache` = NULL, `pseudostorage_cache` = NULL WHERE `artikel` = %d AND `shop` = %d', - $artikel, $id - ) - ); - } else { - $this->app->DB->Update( - sprintf( - 'UPDATE `artikel_onlineshops` + $artikel, $id + ) + ); + } else { + $this->app->DB->Update( + sprintf( + 'UPDATE `artikel_onlineshops` SET `storage_cache` = %d, `pseudostorage_cache` = %s WHERE `artikel` = %d AND `shop` = %d', - $data[$i]['anzahl_lager'], - !isset($data[$i]['pseudolager']) || !is_numeric($data[$i]['pseudolager']) ? 'NULL' : $data[$i]['pseudolager'], - $artikel, - $id - ) - ); - } + $data[$i]['anzahl_lager'], + !isset($data[$i]['pseudolager']) || !is_numeric($data[$i]['pseudolager']) ? 'NULL' : $data[$i]['pseudolager'], + $artikel, + $id + ) + ); + } - $projekt = $shopexportarr['projekt'];// $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id' LIMIT 1"); - if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { - //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $data[$i]['crosssellingartikel'] = $this->app->DB->SelectArr("SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer + $projekt = $shopexportarr['projekt']; // $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id' LIMIT 1"); + if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { + //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $data[$i]['crosssellingartikel'] = $this->app->DB->SelectArr("SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer FROM crossselling_artikel ca JOIN artikel a ON ca.crosssellingartikel = a.id LEFT JOIN artikelkategorien ak ON CONCAT(ak.id,'_kat') = a.typ @@ -1608,14 +1458,12 @@ class Remote WHERE ca.artikel='" . $tmp->GetId() . "' AND (ca.shop='$id' OR ca.shop='0') GROUP BY ca.crosssellingartikel, ca.art"); - if (empty($data[$i]['crosssellingartikel'])) { - $data[$i]['crosssellingartikel'] = []; - } + if (empty($data[$i]['crosssellingartikel'])) { + $data[$i]['crosssellingartikel'] = []; + } - - $sql = - - "SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer + + $sql = "SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer FROM crossselling_artikel ca JOIN artikel a ON ca.artikel = a.id LEFT JOIN artikelkategorien ak ON CONCAT(ak.id,'_kat') = a.typ @@ -1624,141 +1472,141 @@ class Remote WHERE ca.crosssellingartikel='" . $tmp->GetId() . "' AND ca.gegenseitigzuweisen=1 AND (ca.shop='$id' OR ca.shop='0') GROUP BY ca.artikel, ca.art"; - $gegenseitigzugewiesen = $this->app->DB->SelectArr($sql); + $gegenseitigzugewiesen = $this->app->DB->SelectArr($sql); - if (!empty($gegenseitigzugewiesen)) { - foreach ($gegenseitigzugewiesen as $gegenseitigzugewiesenercrosssellingartikel) { - $data[$i]['crosssellingartikel'][] = $gegenseitigzugewiesenercrosssellingartikel; - } - } - } - - if (!empty($loadElements['article_descriptions']) && $this->app->erp->ModulVorhanden('artikel_texte')) { - $sprachen = ['de', 'en']; - foreach ($sprachen as $sprache) { - $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", - $id, strtoupper($sprache), $artikel); - $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if (!empty($ersetzeStandardbeschreibung)) { - $data[$i]['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; - $data[$i]['beschreibung_' . $sprache] = $ersetzeStandardbeschreibung['beschreibung_online']; - $data[$i]['kurztext_' . $sprache] = $ersetzeStandardbeschreibung['kurztext']; - $data[$i]['metadescription_' . $sprache] = $ersetzeStandardbeschreibung['meta_description']; - $data[$i]['metakeywords_' . $sprache] = $ersetzeStandardbeschreibung['meta_keywords']; - $data[$i]['metatitle_' . $sprache] = $ersetzeStandardbeschreibung['meta_title']; - if ($sprache === 'de') { - $data[$i]['anabregs_text'] = $ersetzeStandardbeschreibung['beschreibung']; - } else { - $data[$i]['anabregs_text_en'] = $ersetzeStandardbeschreibung['beschreibung']; + if (!empty($gegenseitigzugewiesen)) { + foreach ($gegenseitigzugewiesen as $gegenseitigzugewiesenercrosssellingartikel) { + $data[$i]['crosssellingartikel'][] = $gegenseitigzugewiesenercrosssellingartikel; + } + } } - } - } - } - if(!empty($loadElements['standard_price'])){ + if (!empty($loadElements['article_descriptions']) && $this->app->erp->ModulVorhanden('artikel_texte')) { + $sprachen = ['de', 'en']; + foreach ($sprachen as $sprache) { + $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", + $id, strtoupper($sprache), $artikel); + $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); + if (!empty($ersetzeStandardbeschreibung)) { + $data[$i]['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + $data[$i]['beschreibung_' . $sprache] = $ersetzeStandardbeschreibung['beschreibung_online']; + $data[$i]['kurztext_' . $sprache] = $ersetzeStandardbeschreibung['kurztext']; + $data[$i]['metadescription_' . $sprache] = $ersetzeStandardbeschreibung['meta_description']; + $data[$i]['metakeywords_' . $sprache] = $ersetzeStandardbeschreibung['meta_keywords']; + $data[$i]['metatitle_' . $sprache] = $ersetzeStandardbeschreibung['meta_title']; + if ($sprache === 'de') { + $data[$i]['anabregs_text'] = $ersetzeStandardbeschreibung['beschreibung']; + } else { + $data[$i]['anabregs_text_en'] = $ersetzeStandardbeschreibung['beschreibung']; + } + } + } + } - $priceInformation = $this->app->DB->SelectArr("SELECT v.preis AS preis, v.waehrung + if (!empty($loadElements['standard_price'])) { + + $priceInformation = $this->app->DB->SelectArr("SELECT v.preis AS preis, v.waehrung FROM `verkaufspreise` AS `v` WHERE v.artikel = '{$artikel}' AND v.ab_menge = 1 AND v.geloescht = 0 AND v.art != 'Gruppe' AND (v.objekt = 'Standard' OR v.objekt = '') AND (v.adresse = '0' OR v.adresse = '') AND (v.gueltig_bis >= NOW() OR v.gueltig_bis = '0000-00-00') ORDER BY v.preis DESC LIMIT 1"); - - if (!empty($priceInformation)) { - $priceInformation = reset($priceInformation); - $defaultPrice = $priceInformation['preis']; - $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; - if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ - $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency - $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); - } - $data[$i]['waehrung'] = $defaultCurrency; - $data[$i]['preis'] = $defaultPrice; - } - - if(!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1){ - $data[$i]['steuersatz'] = (float)$tmp->GetSteuersatz(); - }elseif($data[$i]['umsatzsteuer'] === 'ermaessigt'){ - $data[$i]['steuersatz'] = (float)$this->app->erp->GetStandardSteuersatzErmaessigt($projekt); - }elseif($data[$i]['umsatzsteuer'] === 'befreit'){ - $data[$i]['steuersatz'] = 0; - }else{ - $data[$i]['steuersatz'] = (float)$this->app->erp->GetStandardSteuersatzNormal($projekt); - } - $steuer = ($data[$i]['steuersatz'] + 100) / 100.0; + if (!empty($priceInformation)) { + $priceInformation = reset($priceInformation); + $defaultPrice = $priceInformation['preis']; + $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; + if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { + $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency + $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); + } + $data[$i]['waehrung'] = $defaultCurrency; + $data[$i]['preis'] = $defaultPrice; + } - if(!empty($shopexportarr['staffelpreiseuebertragen']) && !empty($loadElements['bulk_prices'])){ - $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; - if(!empty($preisgruppe)){ - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $query = sprintf("SELECT v.adresse, g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung + if (!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1) { + $data[$i]['steuersatz'] = (float) $tmp->GetSteuersatz(); + } elseif ($data[$i]['umsatzsteuer'] === 'ermaessigt') { + $data[$i]['steuersatz'] = (float) $this->app->erp->GetStandardSteuersatzErmaessigt($projekt); + } elseif ($data[$i]['umsatzsteuer'] === 'befreit') { + $data[$i]['steuersatz'] = 0; + } else { + $data[$i]['steuersatz'] = (float) $this->app->erp->GetStandardSteuersatzNormal($projekt); + } + + $steuer = ($data[$i]['steuersatz'] + 100) / 100.0; + + if (!empty($shopexportarr['staffelpreiseuebertragen']) && !empty($loadElements['bulk_prices'])) { + $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $query = sprintf("SELECT v.adresse, g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung FROM `verkaufspreise` AS `v` LEFT JOIN `gruppen` AS `g` on v.gruppe = g.id WHERE v.artikel = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.adresse = 0 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) %s ORDER by g.id, v.ab_menge", $artikel, $preisgruppenzusatz); - $standardstaffelpreise = $this->app->DB->SelectArr($query); - $data[$i]['staffelpreise_standard'] = []; - if(!empty($standardstaffelpreise)){ - foreach ($standardstaffelpreise as $staffelpreis) { - $data[$i]['staffelpreise_standard'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' - ]; - } - } + $standardstaffelpreise = $this->app->DB->SelectArr($query); + $data[$i]['staffelpreise_standard'] = []; + if (!empty($standardstaffelpreise)) { + foreach ($standardstaffelpreise as $staffelpreis) { + $data[$i]['staffelpreise_standard'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' + ]; + } + } - $query = sprintf("SELECT a.name AS `kundenname`, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung + $query = sprintf("SELECT a.name AS `kundenname`, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung FROM `verkaufspreise` AS `v` JOIN `adresse` AS `a` ON v.adresse = a.id AND v.art LIKE 'Kunde' WHERE v.`artikel` = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by v.adresse, v.ab_menge", $artikel); - $staffelpreisekunden = $this->app->DB->SelectArr($query); - if(!empty($staffelpreisekunden)){ - foreach ($staffelpreisekunden as $staffelpreis) { - $data[$i]['staffelpreise_kunden'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'email' => $staffelpreis['email'], - 'kundenname' => $staffelpreis['kundenname'] - ]; - } - } + $staffelpreisekunden = $this->app->DB->SelectArr($query); + if (!empty($staffelpreisekunden)) { + foreach ($staffelpreisekunden as $staffelpreis) { + $data[$i]['staffelpreise_kunden'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'email' => $staffelpreis['email'], + 'kundenname' => $staffelpreis['kundenname'] + ]; + } + } - $query = sprintf("SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, sk.extgruppename + $query = sprintf("SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, sk.extgruppename FROM `verkaufspreise` AS `v` JOIN `gruppen` AS `g` on v.gruppe = g.id JOIN `shopexport_kundengruppen` AS `sk` ON sk.gruppeid = v.gruppe WHERE v.`artikel` = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.art like 'Gruppe' AND v.gruppe <> '%s' AND sk.shopid = %d AND sk.aktiv = 1 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, v.ab_menge", $artikel, $preisgruppe, $id); - $staffelpreisegruppen = $this->app->DB->SelectArr($query); - if(!empty($staffelpreisegruppen)){ - foreach ($staffelpreisegruppen as $staffelpreis) { - $data[$i]['staffelpreise_gruppen'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'kennziffer' => $staffelpreis['kennziffer'], - 'gruppenname' => $staffelpreis['name'], - 'gruppeextern' => $staffelpreis['extgruppename'] - ]; - } - } + $staffelpreisegruppen = $this->app->DB->SelectArr($query); + if (!empty($staffelpreisegruppen)) { + foreach ($staffelpreisegruppen as $staffelpreis) { + $data[$i]['staffelpreise_gruppen'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'kennziffer' => $staffelpreis['kennziffer'], + 'gruppenname' => $staffelpreis['name'], + 'gruppeextern' => $staffelpreis['extgruppename'] + ]; + } + } - /** - * @deprecated 20.3 - * Staffelpreise werden gesondert uebergeben statt in einem sammelarray - */ - $staffelpreise = $this->app->DB->SelectArr(" + /** + * @deprecated 20.3 + * Staffelpreise werden gesondert uebergeben statt in einem sammelarray + */ + $staffelpreise = $this->app->DB->SelectArr(" SELECT a.name AS kundenname, a.email, v.adresse, g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1767,61 +1615,60 @@ class Remote WHERE v.`artikel` = '$artikel' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, ab_menge"); - if(!empty($staffelpreise)){ - foreach ($staffelpreise as $k => $v) { - if(empty($v['adresse'])){ - $data[$i]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); - if($v['id']){ - $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; - $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + if (!empty($staffelpreise)) { + foreach ($staffelpreise as $k => $v) { + if (empty($v['adresse'])) { + $data[$i]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); + if ($v['id']) { + $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; + $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + } + } + } + } + /** + * @deprecated Ende + */ + } + $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; + } + $data[$i]['checksum'] = $tmp->GetChecksum(); + if ($data[$i]['preis'] == '' && !empty($artikelexport) && !$nurlager) { + if ($lagerexport) { + $nurlager = true; + } else { + $this->app->erp->Systemlog( + 'Shopexport bei Artikel ' . $data[$i]['nummer'] . ' ' . $data[$i]['name_de'] . ' fehlgeschlagen, da Verkaufspreis fehlt.' + ); + $data[$i]['artikel'] = 'ignore'; } - } } - } - /** - * @deprecated Ende - */ - } - $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; - } - $data[$i]['checksum'] = $tmp->GetChecksum(); - if ($data[$i]['preis'] == '' && !empty($artikelexport) && !$nurlager) { - if($lagerexport){ - $nurlager = true; - } else { - $this->app->erp->Systemlog( - 'Shopexport bei Artikel ' . $data[$i]['nummer'] . ' ' . $data[$i]['name_de'] . ' fehlgeschlagen, da Verkaufspreis fehlt.' - ); - $data[$i]['artikel'] = 'ignore'; - } - } - $steuerermaessigt = ($this->app->erp->GetStandardSteuersatzErmaessigt($projekt) + 100) / 100.0; - $steuernormal = ($this->app->erp->GetStandardSteuersatzNormal($projekt) + 100) / 100.0; - $steuermapping = [ - 'befreit' => 1, - 'ermaessigt' => $steuerermaessigt, - 'normal' => $steuernormal - ]; + $steuerermaessigt = ($this->app->erp->GetStandardSteuersatzErmaessigt($projekt) + 100) / 100.0; + $steuernormal = ($this->app->erp->GetStandardSteuersatzNormal($projekt) + 100) / 100.0; + $steuermapping = [ + 'befreit' => 1, + 'ermaessigt' => $steuerermaessigt, + 'normal' => $steuernormal + ]; - if (!empty($loadElements['variants']) && !empty($shopexportarr['variantenuebertragen']) - && $this->app->erp->ModulVorhanden('matrixprodukt') && $tmp->GetMatrixprodukt()) { - $artfreifeld = ''; - for ($_i = 1; $_i <= 40; $_i++) { - $artfreifeld .= sprintf(' art.freifeld%d AS `freifeld%d`, ',$_i,$_i); - } - $varianten = null; + if (!empty($loadElements['variants']) && !empty($shopexportarr['variantenuebertragen']) && $this->app->erp->ModulVorhanden('matrixprodukt') && $tmp->GetMatrixprodukt()) { + $artfreifeld = ''; + for ($_i = 1; $_i <= 40; $_i++) { + $artfreifeld .= sprintf(' art.freifeld%d AS `freifeld%d`, ', $_i, $_i); + } + $varianten = null; - $data[$i]['artikel_varianten'] = []; - $db = $this->app->Container->get('Database'); + $data[$i]['artikel_varianten'] = []; + $db = $this->app->Container->get('Database'); - $offset = 0; - $eigenschaftind = 0; + $offset = 0; + $eigenschaftind = 0; - $gruppenuebersetzung = []; - $gruppenwertuebersetzung = []; + $gruppenuebersetzung = []; + $gruppenwertuebersetzung = []; - $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext + $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext FROM matrixprodukt_optionen_zu_artikel AS moza JOIN matrixprodukt_eigenschaftenoptionen_artikel AS meoa ON moza.option_id = meoa.id JOIN matrixprodukt_eigenschaftengruppen_artikel AS mega ON mega.id = meoa.gruppe @@ -1829,42 +1676,42 @@ class Remote WHERE art.variante_von=%d ANd art.geloescht=0 AND art.nummer <> "DEL" AND art.intern_gesperrt=0 GROUP BY mega.id, meoa.id ORDER BY SUM(POW(10,1-mega.sort) * meoa.sort) ASC', $artikel); - foreach ($db->yieldAll($query) as $matrixdaten) { - $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; + foreach ($db->yieldAll($query) as $matrixdaten) { + $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; - if ($translationpossible && !empty($loadElements['translations'])) { - if (empty($gruppenuebersetzung[$matrixdaten['gruppe']])) { - $gruppennamen = $this->app->DB->SelectArr("SELECT + if ($translationpossible && !empty($loadElements['translations'])) { + if (empty($gruppenuebersetzung[$matrixdaten['gruppe']])) { + $gruppennamen = $this->app->DB->SelectArr("SELECT IF(name_external_from<>'',name_external_from,name_from) AS name_from, IF(name_external_to<>'',name_external_to,name_to) AS name_to, language_to FROM `matrix_article_translation` WHERE name_from='" . $matrixdaten['gruppe'] . "' AND (project=0 OR project='$projekt')"); - $gruppenuebersetzung[$matrixdaten['gruppe']] = true; - if (!empty($gruppennamen)) { - foreach ($gruppennamen as $gruppenname) { - $data[$i]['matrix_varianten']['texte']['gruppen'][$gruppenname['language_to']][$gruppenname['name_from']] = $gruppenname['name_to']; - } - } - } - if (empty($gruppenwertuebersetzung[$matrixdaten['wert']])) { - $gruppenwerte = $this->app->DB->SelectArr("SELECT + $gruppenuebersetzung[$matrixdaten['gruppe']] = true; + if (!empty($gruppennamen)) { + foreach ($gruppennamen as $gruppenname) { + $data[$i]['matrix_varianten']['texte']['gruppen'][$gruppenname['language_to']][$gruppenname['name_from']] = $gruppenname['name_to']; + } + } + } + if (empty($gruppenwertuebersetzung[$matrixdaten['wert']])) { + $gruppenwerte = $this->app->DB->SelectArr("SELECT IF(maot.name_external_from<>'',maot.name_external_from,maot.name_from) AS `name_from`, IF(maot.name_external_to<>'',maot.name_external_to,maot.name_to) AS `name_to`, maot.language_to FROM `matrix_article_options_translation` AS `maot` WHERE maot.name_from='" . $this->app->DB->real_escape_string($matrixdaten['wert']) . "'"); - $gruppenwertuebersetzung[$matrixdaten['wert']] = true; - foreach ($gruppenwerte as $gruppenwert) { - $data[$i]['matrix_varianten']['texte']['werte'][$gruppenwert['language_to']][$gruppenwert['name_from']] = $gruppenwert['name_to']; - } - } - } - } + $gruppenwertuebersetzung[$matrixdaten['wert']] = true; + foreach ($gruppenwerte as $gruppenwert) { + $data[$i]['matrix_varianten']['texte']['werte'][$gruppenwert['language_to']][$gruppenwert['name_from']] = $gruppenwert['name_to']; + } + } + } + } - do { - unset($data[$i]['matrix_varianten']['artikel']); - unset($data[$i]['artikel_varianten']); - //if($this->app->DB->Select("SELECT variantenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $varianten = "SELECT art.pseudolager AS `pseudolager`, art.nummer AS `nummer`, art.inaktiv AS `inaktiv`, + do { + unset($data[$i]['matrix_varianten']['artikel']); + unset($data[$i]['artikel_varianten']); + //if($this->app->DB->Select("SELECT variantenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $varianten = "SELECT art.pseudolager AS `pseudolager`, art.nummer AS `nummer`, art.inaktiv AS `inaktiv`, art.id AS `artikel`, art.gewicht AS `gewicht`, art.zolltarifnummer AS `zolltarifnummer`, art.name_en AS `name_en`, $artfreifeld art.pseudopreis AS `pseudopreis`, art.lieferzeitmanuell AS `lieferzeitmanuell`, art.altersfreigabe AS `altersfreigabe`, @@ -1891,78 +1738,76 @@ class Remote GROUP BY art.id ORDER BY SUM(POW(10,1-mega.sort) * meoa.sort) ASC LIMIT 5000 OFFSET $offset"; - $offset += 5000; + $offset += 5000; - foreach ($db->yieldAll($varianten) as $eigenschaft) { - $eigenschaftind++; - $steuer = $steuermapping[$eigenschaft['umsatzsteuer']]; - if(!empty($eigenschaft['steuersatz']) && $eigenschaft['steuersatz'] != -1){ - $steuer = ($eigenschaft['steuersatz'] + 100) / 100; - } - if (empty($steuer)) { - $steuer = $steuernormal; - } - $matrixPseudoStorage = $eigenschaft['pseudolager']; - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $eigenschaft['artikel'], $matrixPseudoStorage); - if(is_numeric($matrixPseudoStorage) && $matrixPseudoStorage < 0) { - $matrixPseudoStorage = 0; - } - $matrixStock = (float)$this->app->erp->ArtikelAnzahlVerkaufbar($eigenschaft['artikel'], 0, $projektlager, $id, $lagergrundlage); - if($matrixStock < 0) { - $matrixStock = 0; - } - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][] = - array('zolltarifnummer' => $eigenschaft['zolltarifnummer'], 'gewicht' => $eigenschaft['gewicht'], - 'artikel' => $eigenschaft['artikel'], 'preis' => $eigenschaft['preis'], 'gesperrt' => $eigenschaft['gesperrt'], - 'nummer' => $eigenschaft['nummer'], 'lieferzeitmanuell' => $eigenschaft['lieferzeitmanuell'], - 'altersfreigabe' => $eigenschaft['altersfreigabe'], 'ean' => $eigenschaft['ean'], - 'lag' => $matrixStock, - 'pseudolager' => $matrixPseudoStorage, 'pseudopreis' => $eigenschaft['pseudopreis'], - 'restmenge' => $eigenschaft['restmenge'], 'steuersatz' => ($steuer - 1) * 100, 'umsatzsteuer' => $eigenschaft['umsatzsteuer'], - 'bruttopreis' => $eigenschaft['preis'] * $steuer, 'inaktiv' => $eigenschaft['inaktiv'], - 'name_de' => $eigenschaft['name_de'], 'name_en' => $eigenschaft['name_en'], - 'uebersicht_de' => $eigenschaft['uebersicht_de'], 'uebersicht_en' => $eigenschaft['uebersicht_en']); - if ($freifelder) { - foreach ($freifelder as $freifeld) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = - $this->app->DB->Select('SELECT ' . $freifeld['freifeld_wawi'] . ' FROM artikel WHERE id=' . $eigenschaft['artikel']); - } + foreach ($db->yieldAll($varianten) as $eigenschaft) { + $eigenschaftind++; + $steuer = $steuermapping[$eigenschaft['umsatzsteuer']]; + if (!empty($eigenschaft['steuersatz']) && $eigenschaft['steuersatz'] != -1) { + $steuer = ($eigenschaft['steuersatz'] + 100) / 100; + } + if (empty($steuer)) { + $steuer = $steuernormal; + } + $matrixPseudoStorage = $eigenschaft['pseudolager']; + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $eigenschaft['artikel'], $matrixPseudoStorage); + if (is_numeric($matrixPseudoStorage) && $matrixPseudoStorage < 0) { + $matrixPseudoStorage = 0; + } + $matrixStock = (float) $this->app->erp->ArtikelAnzahlVerkaufbar($eigenschaft['artikel'], 0, $projektlager, $id, $lagergrundlage); + if ($matrixStock < 0) { + $matrixStock = 0; + } + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][] = array('zolltarifnummer' => $eigenschaft['zolltarifnummer'], 'gewicht' => $eigenschaft['gewicht'], + 'artikel' => $eigenschaft['artikel'], 'preis' => $eigenschaft['preis'], 'gesperrt' => $eigenschaft['gesperrt'], + 'nummer' => $eigenschaft['nummer'], 'lieferzeitmanuell' => $eigenschaft['lieferzeitmanuell'], + 'altersfreigabe' => $eigenschaft['altersfreigabe'], 'ean' => $eigenschaft['ean'], + 'lag' => $matrixStock, + 'pseudolager' => $matrixPseudoStorage, 'pseudopreis' => $eigenschaft['pseudopreis'], + 'restmenge' => $eigenschaft['restmenge'], 'steuersatz' => ($steuer - 1) * 100, 'umsatzsteuer' => $eigenschaft['umsatzsteuer'], + 'bruttopreis' => $eigenschaft['preis'] * $steuer, 'inaktiv' => $eigenschaft['inaktiv'], + 'name_de' => $eigenschaft['name_de'], 'name_en' => $eigenschaft['name_en'], + 'uebersicht_de' => $eigenschaft['uebersicht_de'], 'uebersicht_en' => $eigenschaft['uebersicht_en']); + if ($freifelder) { + foreach ($freifelder as $freifeld) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $this->app->DB->Select('SELECT ' . $freifeld['freifeld_wawi'] . ' FROM artikel WHERE id=' . $eigenschaft['artikel']); + } - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $eigenschaft['artikel'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if (!empty($freifelduebersetzungen)) { - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $eigenschaft['artikel'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($eigenschaft['artikel']); - if (!empty($dateien)) { - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['filename'][] = $filename; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extension'][] = $path_info['extension']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['titel'][] = $datei['titel']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['beschreibung'][] = $datei['beschreibung']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['stichwort'][] = $datei['subjekt']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['id'][] = $datei['id']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['version'][] = $datei['version']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); - } - } - } + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($eigenschaft['artikel']); + if (!empty($dateien)) { + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['filename'][] = $filename; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extension'][] = $path_info['extension']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['titel'][] = $datei['titel']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['beschreibung'][] = $datei['beschreibung']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['stichwort'][] = $datei['subjekt']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['id'][] = $datei['id']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['version'][] = $datei['version']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); + } + } + } - $standardstaffelpreise = null; - if(!empty($loadElements['standard_price'])){ - $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; - if(!empty($preisgruppe)){ - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $standardstaffelpreise = $this->app->DB->SelectArr(" + $standardstaffelpreise = null; + if (!empty($loadElements['standard_price'])) { + $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $standardstaffelpreise = $this->app->DB->SelectArr(" SELECT v.adresse, g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1970,20 +1815,20 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.adresse=0 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) $preisgruppenzusatz ORDER by g.id, ab_menge"); - } - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'] = []; - if (!empty($standardstaffelpreise)) { - foreach ($standardstaffelpreise as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' - ]; - } - } - if(!empty($loadElements['bulk_prices'])){ - $staffelpreisekunden = $this->app->DB->SelectArr(" + } + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'] = []; + if (!empty($standardstaffelpreise)) { + foreach ($standardstaffelpreise as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' + ]; + } + } + if (!empty($loadElements['bulk_prices'])) { + $staffelpreisekunden = $this->app->DB->SelectArr(" SELECT a.name AS kundenname, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1991,20 +1836,20 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by v.adresse, ab_menge"); - if(!empty($staffelpreisekunden)){ - foreach ($staffelpreisekunden as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_kunden'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'email' => $staffelpreis['email'], - 'kundenname' => $staffelpreis['kundenname'] - ]; - } - } + if (!empty($staffelpreisekunden)) { + foreach ($staffelpreisekunden as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_kunden'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'email' => $staffelpreis['email'], + 'kundenname' => $staffelpreis['kundenname'] + ]; + } + } - $staffelpreisegruppen = $this->app->DB->SelectArr(" + $staffelpreisegruppen = $this->app->DB->SelectArr(" SELECT g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer,sk.extgruppename FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -2013,218 +1858,213 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.art like 'Gruppe' AND v.gruppe<>'$preisgruppe' AND sk.shopid='$id' AND sk.aktiv=1 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, ab_menge"); - if(!empty($staffelpreisegruppen)){ - foreach ($staffelpreisegruppen as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_gruppen'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'kennziffer' => $staffelpreis['kennziffer'], - 'gruppenname' => $staffelpreis['name'], - 'gruppeextern' => $staffelpreis['extgruppename'] - ]; - } - } - } - $staffelpreisema = null; - if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { - //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $preisgruppenzusatz = ''; - if (!empty($preisgruppe)) { - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $staffelpreisema = $this->app->DB->SelectArr(" + if (!empty($staffelpreisegruppen)) { + foreach ($staffelpreisegruppen as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_gruppen'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'kennziffer' => $staffelpreis['kennziffer'], + 'gruppenname' => $staffelpreis['name'], + 'gruppeextern' => $staffelpreis['extgruppename'] + ]; + } + } + } + $staffelpreisema = null; + if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { + //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $preisgruppenzusatz = ''; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $staffelpreisema = $this->app->DB->SelectArr(" SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, v.id, v.adresse, v.art, sk.extgruppename FROM `verkaufspreise` AS v LEFT JOIN gruppen g on v.gruppe = g.id AND v.art like 'Gruppe' LEFT JOIN shopexport_kundengruppen sk ON sk.gruppeid=v.gruppe WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (ifnull(v.gueltig_bis,'0000-00-00') = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) $preisgruppenzusatz ORDER by g.id, ab_menge"); - } - if (!empty($staffelpreisema)) { - foreach ($staffelpreisema as $k => $v) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); - if ($v['id']) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenname'] = $v['name']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['adresse'] = $v['adresse']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['art'] = $v['art']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppeextern'] = $v['extgruppename']; - } - } - } + } + if (!empty($staffelpreisema)) { + foreach ($staffelpreisema as $k => $v) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); + if ($v['id']) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['adresse'] = $v['adresse']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['art'] = $v['art']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppeextern'] = $v['extgruppename']; + } + } + } - $articleVariant = $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]; - $articleVariant['artikel'] = $eigenschaft['artikel']; - $data[$i]['artikel_varianten'][] = $articleVariant; - unset($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']); + $articleVariant = $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]; + $articleVariant['artikel'] = $eigenschaft['artikel']; + $data[$i]['artikel_varianten'][] = $articleVariant; + unset($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']); - - $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext + $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext FROM matrixprodukt_optionen_zu_artikel AS moza JOIN matrixprodukt_eigenschaftenoptionen_artikel AS meoa ON moza.option_id = meoa.id JOIN matrixprodukt_eigenschaftengruppen_artikel AS mega ON mega.id = meoa.gruppe WHERE moza.artikel=%d ORDER BY mega.id, moza.id', $eigenschaft['artikel']); - $matrixdaten = $this->app->DB->SelectArr($query); + $matrixdaten = $this->app->DB->SelectArr($query); - for ($iv = 0, $ivMax = (!empty($matrixdaten)?count($matrixdaten):0); $iv < $ivMax; $iv++) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['name'] = $matrixdaten[$iv]['gruppe']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['values'] = $matrixdaten[$iv]['wert']; + for ($iv = 0, $ivMax = (!empty($matrixdaten) ? count($matrixdaten) : 0); $iv < $ivMax; $iv++) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['name'] = $matrixdaten[$iv]['gruppe']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['values'] = $matrixdaten[$iv]['wert']; + } + } + + $result = null; + if (empty($data)) { + continue; + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } + } while (count($data[$i]['matrix_varianten']['artikel']) >= 5000); + + return $result; } - } - - $result = null; - if(empty($data)) { - continue; - } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } - } while (count($data[$i]['matrix_varianten']['artikel'])>=5000); + if (!empty($loadElements['variants']) && $this->app->DB->Select("SELECT id FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { + if ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikel' AND variante = 0 AND matrixprodukt=0 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { + $data[$i]['artikel_varianten'] = []; + $data[$i]['variantevorhanden'] = 1; + $varianten = "SELECT * FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL'"; + $db = $this->app->Container->get('Database'); + foreach ($db->yieldAll($varianten) as $v) { + $steuer = $steuermapping[$v['umsatzsteuer']]; + if ($v['steuersatz'] != -1 && !empty($v['steuersatz'])) { + $steuer = ($v['steuersatz'] + 100) / 100; + } + if (empty($steuer)) { + $steuer = $steuernormal; + } + $variantennettopreis = null; + if (!empty($loadElements['standard_price'])) { + if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { + $variantennettopreis = $this->app->erp->GetVerkaufspreisGruppe($v['id'], 1, $preisgruppe); + } else { + $variantennettopreis = $this->app->erp->GetVerkaufspreis($v['id'], 1, 0); + } + } + if (!empty($loadElements['translations']) && $this->app->erp->ModulVorhanden('artikel_texte')) { + $sprachen = ['de', 'en']; + foreach ($sprachen as $sprache) { + $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", + $id, strtoupper($sprache), $v['id']); + $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); + if (!empty($ersetzeStandardbeschreibung)) { + $v['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + } + } + } + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $v['id'], $v['pseudolager']); + if (is_numeric($v['pseudolager']) && $v['pseudolager'] < 0) { + $v['pseudolager'] = 0; + } + $projectStockId = $this->app->DB->Select("SELECT `id` FROM `projekt` WHERE `id` = '{$projekt}' AND `projektlager` = 1 LIMIT 1"); + $stock = (float) $this->app->erp->ArtikelAnzahlVerkaufbar( + $v['id'], + 0, + $projectStockId, + $id, + $lagergrundlage + ); + if ($stock < 0) { + $stock = 0; + } + $data[$i]['artikel_varianten'][] = array('nummer' => $v['nummer'], 'name_de' => $v['name_de'], 'name_en' => $v['name_en'], 'restmenge' => $v['restmenge'], 'gesperrt' => ($v['gesperrt'] == 1 || $v['intern_gesperrt'] == 1 ? 1 : 0), + 'artikel' => $v['id'], 'zolltarifnummer' => $v['zolltarifnummer'], 'ean' => $v['ean'], 'gewicht' => $v['gewicht'], 'inaktiv' => $v['inaktiv'], 'uebersicht_de' => $v['uebersicht_de'], + 'lag' => $stock, + 'pseudolager' => $v['pseudolager'], 'pseudopreis' => $v['pseudopreis'], 'preis' => $variantennettopreis, 'bruttopreis' => $variantennettopreis * $steuer, + 'artikelnummer_fremdnummern' => $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $v['id'] . "' AND nummer <> '' AND shopid = '$id' AND aktiv = '1'"), + 'steuersatz' => ($steuer - 1) * 100); + if (!empty($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'])) { + foreach ($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'] as $fkey => $fval) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); + } + } + if ($eigenschaftenuebertragen && !empty($loadElements['properties'])) { + $varianteneigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften + WHERE ew.artikel = '" . $v['id'] . "' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1 ORDER BY e.name"); + if (!empty($varianteneigenschaften)) { + foreach ($varianteneigenschaften as $eigenschaft) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaften'][] = array('name' => $eigenschaft['name'], 'values' => $eigenschaft['wert']); + } + } + $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '" . $v['id'] . "'"); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; + } + + if (!empty($freifelder) && !empty($loadElements['free_fields'])) { + foreach ($freifelder as $freifeld) { + if (method_exists($tmp, 'Get' . ucfirst($freifeld['freifeld_wawi']))) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $v[$freifeld['freifeld_wawi']]; + } + } + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $v['id'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($v['id']); + if (!empty($dateien)) { + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['filename'][] = $filename; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extension'][] = $path_info['extension']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['titel'][] = $datei['titel']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['beschreibung'][] = $datei['beschreibung']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['stichwort'][] = $datei['subjekt']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['id'][] = $datei['id']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['version'][] = $datei['version']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); + } + } + } + } + } + } else { + $data[$i]['variantevorhanden'] = 0; + } + + $result = null; + if (empty($data)) { + continue; + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } + } return $result; - } - - if(!empty($loadElements['variants']) && $this->app->DB->Select("SELECT id FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { - if($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikel' AND variante = 0 AND matrixprodukt=0 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")){ - $data[$i]['artikel_varianten'] = []; - $data[$i]['variantevorhanden'] = 1; - $varianten = "SELECT * FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL'"; - $db = $this->app->Container->get('Database'); - foreach ($db->yieldAll($varianten) as $v) { - $steuer = $steuermapping[$v['umsatzsteuer']]; - if($v['steuersatz'] != -1 && !empty($v['steuersatz'])){ - $steuer = ($v['steuersatz'] + 100) / 100; - } - if(empty($steuer)) { - $steuer = $steuernormal; - } - $variantennettopreis = null; - if(!empty($loadElements['standard_price'])){ - if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ - $variantennettopreis = $this->app->erp->GetVerkaufspreisGruppe($v['id'], 1, $preisgruppe); - }else{ - $variantennettopreis = $this->app->erp->GetVerkaufspreis($v['id'], 1, 0); - } - } - if(!empty($loadElements['translations']) && $this->app->erp->ModulVorhanden('artikel_texte')){ - $sprachen = ['de','en']; - foreach ($sprachen as $sprache){ - $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", - $id,strtoupper($sprache),$v['id']); - $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if(!empty($ersetzeStandardbeschreibung)){ - $v['name_'.$sprache] = $ersetzeStandardbeschreibung['name']; - } - } - } - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $v['id'], $v['pseudolager']); - if(is_numeric($v['pseudolager']) && $v['pseudolager'] < 0) { - $v['pseudolager'] = 0; - } - $projectStockId = $this->app->DB->Select("SELECT `id` FROM `projekt` WHERE `id` = '{$projekt}' AND `projektlager` = 1 LIMIT 1"); - $stock = (float)$this->app->erp->ArtikelAnzahlVerkaufbar( - $v['id'], - 0, - $projectStockId, - $id, - $lagergrundlage - ); - if($stock < 0) { - $stock = 0; - } - $data[$i]['artikel_varianten'][] = array('nummer' => $v['nummer'], 'name_de' => $v['name_de'], 'name_en' => $v['name_en'],'restmenge' => $v['restmenge'], 'gesperrt' => ($v['gesperrt']==1||$v['intern_gesperrt']==1?1:0), - 'artikel' => $v['id'],'zolltarifnummer' => $v['zolltarifnummer'],'ean' => $v['ean'],'gewicht' => $v['gewicht'], 'inaktiv' => $v['inaktiv'], 'uebersicht_de' => $v['uebersicht_de'], - 'lag' => $stock, - 'pseudolager' => $v['pseudolager'], 'pseudopreis' => $v['pseudopreis'], 'preis' => $variantennettopreis, 'bruttopreis' => $variantennettopreis * $steuer, - 'artikelnummer_fremdnummern' => $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $v['id'] . "' AND nummer <> '' AND shopid = '$id' AND aktiv = '1'"), - 'steuersatz' => ($steuer - 1) * 100); - if(!empty($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'])) { - foreach($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'] as $fkey => $fval) { - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); - } - } - if($eigenschaftenuebertragen && !empty($loadElements['properties'])){ - $varianteneigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften - WHERE ew.artikel = '".$v['id']."' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1 ORDER BY e.name"); - if(!empty($varianteneigenschaften)){ - foreach($varianteneigenschaften as $eigenschaft){ - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaften'][] = array('name'=>$eigenschaft['name'], 'values'=>$eigenschaft['wert']); - } - } - $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '".$v['id']."'"); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; - } - - if(!empty($freifelder) && !empty($loadElements['free_fields'])) - { - foreach($freifelder as $freifeld) - { - if(method_exists($tmp,'Get'.ucfirst($freifeld['freifeld_wawi']))) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $v[$freifeld['freifeld_wawi']]; - } - } - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '".$v['id']."' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if(!empty($freifelduebersetzungen)){ - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($v['id']); - if (!empty($dateien)) { - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['filename'][] = $filename; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extension'][] = $path_info['extension']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['titel'][] = $datei['titel']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['beschreibung'][] = $datei['beschreibung']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['stichwort'][] = $datei['subjekt']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['id'][] = $datei['id']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['version'][] = $datei['version']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); - } - } - } - } - } - }else{ - $data[$i]['variantevorhanden'] = 0; - } - - $result = null; - if(empty($data)){ - continue; - } - if(!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } } - return $result; - } - /** * @param int $articleId * @return array|null */ - protected function getImagesForArticle($articleId){ - $query = sprintf("SELECT d.id AS `id`, dv.id AS `vid`, d.titel, d.beschreibung, ds.subjekt, ds.sort, dv.version AS `version` + protected function getImagesForArticle($articleId) { + $query = sprintf("SELECT d.id AS `id`, dv.id AS `vid`, d.titel, d.beschreibung, ds.subjekt, ds.sort, dv.version AS `version` FROM `datei_stichwoerter` AS `ds` INNER JOIN `datei` AS `d` ON ds.datei = d.id INNER JOIN `datei_version` AS `dv` ON dv.datei = ds.datei @@ -2232,752 +2072,693 @@ class Remote WHERE ds.parameter = %d AND ds.objekt like 'Artikel' AND ds.subjekt LIKE 'Shopbild' AND d.geloescht = 0 ORDER BY ds.sort", $articleId); - return $this->app->DB->SelectArr($query); - } - - protected function sendlistlager($i,$id,$data){ - $data2 = $data; - foreach ($data2 as $key => $value){ - $data2[$key]['artikel'] = $value['artikelid']; - } - $result = $this->RemoteCommand($id,'sendlistlager',$data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); - return $result; - } - - protected function sendlist($i,$id,$data,$isLagerExported){ - /** @var Shopexport $objShopexport */ - $objShopexport = $this->app->loadModule('shopexport'); - $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); - $hash = $changedHash['hash']; - //$changedHash = $changedHash['changed']; - - $result = $this->RemoteCommand($id,'sendlist',$data); - $checkAo = $this->app->DB->Select( - sprintf( - 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', - $data[0]['artikel'], $id - ) - ); - if(empty($checkAo)) { - $this->app->DB->Insert( - sprintf( - 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) - VALUES (%d, %d, 1, 1) ', - $data[0]['artikel'], $id - ) - ); + return $this->app->DB->SelectArr($query); } - $this->app->DB->Update( - sprintf( - "UPDATE artikel_onlineshops + + protected function sendlistlager($i, $id, $data) { + $data2 = $data; + foreach ($data2 as $key => $value) { + $data2[$key]['artikel'] = $value['artikelid']; + } + $result = $this->RemoteCommand($id, 'sendlistlager', $data2); + $this->app->DB->Update( + sprintf( + 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', + $data2[$i]['artikel'], $id + ) + ); + return $result; + } + + protected function sendlist($i, $id, $data, $isLagerExported) { + /** @var Shopexport $objShopexport */ + $objShopexport = $this->app->loadModule('shopexport'); + $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); + $hash = $changedHash['hash']; + //$changedHash = $changedHash['changed']; + + $result = $this->RemoteCommand($id, 'sendlist', $data); + $checkAo = $this->app->DB->Select( + sprintf( + 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', + $data[0]['artikel'], $id + ) + ); + if (empty($checkAo)) { + $this->app->DB->Insert( + sprintf( + 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) + VALUES (%d, %d, 1, 1) ', + $data[0]['artikel'], $id + ) + ); + } + $this->app->DB->Update( + sprintf( + "UPDATE artikel_onlineshops SET last_article_transfer = NOW(), last_article_hash = '%s' WHERE artikel = %d AND shop = %d", - $this->app->DB->real_escape_string($hash) ,$data[0]['artikel'], $id - ) - ); - if(!empty($result) && is_array($result) && !empty($result['new'])) - { - foreach($result['new'] as $artikelid => $fremdnummer) - { - $artikelid = (int)$artikelid; - $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); - if($artikelid > 0 && $artikelnummer != trim($fremdnummer) && - ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || - $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") - ) && trim($fremdnummer) !== '') - { - //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '".trim($this->app->DB->real_escape_string($fremdnummer))."') LIMIT 1 ")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) - VALUES ('$artikelid','Erstellt durch Artikelexport','".trim($this->app->DB->real_escape_string($fremdnummer))."','$id','".((isset($this->app->User)&& method_exists($this->app->User,'GetName'))?$this->app->DB->real_escape_string($this->app->User->GetName()):'Cronjob') ."',now(),0) + $this->app->DB->real_escape_string($hash), $data[0]['artikel'], $id + ) + ); + if (!empty($result) && is_array($result) && !empty($result['new'])) { + foreach ($result['new'] as $artikelid => $fremdnummer) { + $artikelid = (int) $artikelid; + $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); + if ($artikelid > 0 && $artikelnummer != trim($fremdnummer) && + ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || + $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") + ) && trim($fremdnummer) !== '') { + //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) + VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) "); - } + } + } + } + if (isset($result['anzahl'])) { + $result = $result['anzahl']; + }//Altes Verhalten } - } - if(isset($result['anzahl'])) - { - $result = $result['anzahl']; - }//Altes Verhalten + if (!$isLagerExported) { + $this->sendlistlager($i, $id, $data); + } + return $result; } - if(!$isLagerExported){ - $this->sendlistlager($i,$id,$data); - } - return $result; - } - public function getDataToSendForUpdateOrder(int $shopId, int $orderId): array - { - $orderArr = $this->app->DB->SelectRow("SELECT * FROM `auftrag` WHERE `id` = {$orderId} LIMIT 1"); - $status = $orderArr['status']; - $zahlungsweise = $orderArr['zahlungsweise']; - $shopextid = $orderArr['shopextid']; - $internet = $orderArr['internet']; - $deliveryNoteArr = $this->app->DB->SelectRow( - "SELECT `id`, `versandart` FROM `lieferschein` WHERE `auftragid` = {$orderId} LIMIT 1" - ); - $trackingArr = null; - $versandart = ''; - $tracking = ''; - $shippingProduct = null; - if(!empty($deliveryNoteArr)) { - $deliveryNoteId = $deliveryNoteArr['id']; - $versandart = $deliveryNoteArr['versandart']; - $query = - "SELECT * + public function getDataToSendForUpdateOrder(int $shopId, int $orderId): array { + $orderArr = $this->app->DB->SelectRow("SELECT * FROM `auftrag` WHERE `id` = {$orderId} LIMIT 1"); + $status = $orderArr['status']; + $zahlungsweise = $orderArr['zahlungsweise']; + $shopextid = $orderArr['shopextid']; + $internet = $orderArr['internet']; + $deliveryNoteArr = $this->app->DB->SelectRow( + "SELECT `id`, `versandart` FROM `lieferschein` WHERE `auftragid` = {$orderId} LIMIT 1" + ); + $trackingArr = null; + $versandart = ''; + $tracking = ''; + $shippingProduct = null; + if (!empty($deliveryNoteArr)) { + $deliveryNoteId = $deliveryNoteArr['id']; + $versandart = $deliveryNoteArr['versandart']; + $query = "SELECT * FROM `shopexport_versandarten` WHERE `aktiv`=1 AND `versandart_wawision` = '{$versandart}' AND `shop` = {$shopId} AND `versandart_wawision` <> '' LIMIT 1"; - $shippingMapping = $this->app->DB->SelectRow($query); - $versandartAusgehend = $shippingMapping['versandart_ausgehend'] ?? null; - $shippingProduct = $shippingMapping['produkt_ausgehend'] ?? null; + $shippingMapping = $this->app->DB->SelectRow($query); + $versandartAusgehend = $shippingMapping['versandart_ausgehend'] ?? null; + $shippingProduct = $shippingMapping['produkt_ausgehend'] ?? null; - if(!empty($versandartAusgehend)){ - $versandart = $versandartAusgehend; - } - $trackingArr = $this->app->DB->SelectPairs( - sprintf( - "SELECT `id`, `tracking` + if (!empty($versandartAusgehend)) { + $versandart = $versandartAusgehend; + } + $trackingArr = $this->app->DB->SelectPairs( + sprintf( + "SELECT `id`, `tracking` FROM `versand` WHERE `lieferschein` = {$deliveryNoteId} AND `tracking` <> '' ORDER BY `id` DESC" - ) - ); - $tracking = ''; - if(!empty($trackingArr)) { - $tracking = reset($trackingArr); - } + ) + ); + $tracking = ''; + if (!empty($trackingArr)) { + $tracking = reset($trackingArr); + } - $positionen = $this->app->DB->SelectArr( - "SELECT ap.webid, trim(lp.geliefert)+0 AS `geliefert`, trim(lp.menge)+0 AS `menge`, lp.id + $positionen = $this->app->DB->SelectArr( + "SELECT ap.webid, trim(lp.geliefert)+0 AS `geliefert`, trim(lp.menge)+0 AS `menge`, lp.id FROM `lieferschein_position` AS `lp` INNER JOIN `lieferschein` AS `l` ON l.id = lp.lieferschein INNER JOIN `auftrag` AS `a` ON a.id = l.auftragid INNER JOIN `auftrag_position` AS `ap` ON ap.id = lp.auftrag_position_id WHERE l.id = {$deliveryNoteId} AND ap.webid <> '' " - ); - $allPositions = false; - if(!empty($positionen)) { - $allPositions = true; - foreach($positionen as $position) { - if($position['geliefert'] > 0) { - $itemlist[] = array('webid'=>$position['webid'],'quantity'=>$position['geliefert']); - if($position['geliefert'] < $position['menge']) { - $allPositions = false; - } - } - elseif($this->app->DB->Select("SELECT trim(sum(geliefert))+0 - FROM lieferschein_position - WHERE explodiert_parent = '".$position['id']."' AND lieferschein = '$deliveryNoteId'")) { - $itemlist[] = array('webid'=>$position['webid'],'quantity'=>$position['menge']); - } - else { + ); $allPositions = false; - } - } - if($allPositions && (!empty($itemlist)?count($itemlist):0) < - $this->app->DB->Select( - sprintf('SELECT count(id) FROM auftrag_position WHERE auftrag = %d', $orderId) - ) - ) { - $allPositions = false; - } - } - } - if(!empty($itemlist)) { - $data['itemlist'] = $itemlist; - if($allPositions) { - $data['allpositions'] = 1; - } - } - - $data['orderId'] = $orderId; - $data['auftrag'] = $shopextid; - $data['internet'] = $internet; - $data['zahlungsweise'] = $zahlungsweise; - $data['versandart'] = $versandart; - if(!empty($trackingArr)) { - $data['trackinglist'] = $trackingArr; - } - if($status==='abgeschlossen') { - $data['versand']='1'; - $data['zahlung']='1'; - if($shippingProduct !== null) { - $data['shipping_product'] = $shippingProduct; - } - if($tracking!='') { - $data['tracking']=$tracking; - $lastShippingId = (int)$this->app->DB->Select( - sprintf( - "SELECT `id` FROM `versand` WHERE `lieferschein` = %d AND `lieferschein` > 0 - ORDER BY `id` DESC LIMIT 1", - $deliveryNoteId - ) - ); - $trackinglink = $lastShippingId > 0 && method_exists($this->app->erp,'GetTrackinglink') - ?$this->app->erp->GetTrackinglink($lastShippingId):''; - if($trackinglink) { - $data['trackinglink'] = $trackinglink; - if(!empty($trackingArr)) { - foreach($trackingArr as $versandId => $track) { - $data['trackinglinklist'][$versandId] = $this->app->erp->GetTrackinglink($versandId); + if (!empty($positionen)) { + $allPositions = true; + foreach ($positionen as $position) { + if ($position['geliefert'] > 0) { + $itemlist[] = array('webid' => $position['webid'], 'quantity' => $position['geliefert']); + if ($position['geliefert'] < $position['menge']) { + $allPositions = false; + } + } elseif ($this->app->DB->Select("SELECT trim(sum(geliefert))+0 + FROM lieferschein_position + WHERE explodiert_parent = '" . $position['id'] . "' AND lieferschein = '$deliveryNoteId'")) { + $itemlist[] = array('webid' => $position['webid'], 'quantity' => $position['menge']); + } else { + $allPositions = false; + } + } + if ($allPositions && (!empty($itemlist) ? count($itemlist) : 0) < + $this->app->DB->Select( + sprintf('SELECT count(id) FROM auftrag_position WHERE auftrag = %d', $orderId) + ) + ) { + $allPositions = false; + } } - } } - $trackinglinkRaw = $lastShippingId > 0 && method_exists($this->app->erp,'GetTrackingRawLink') - ?$this->app->erp->GetTrackingRawLink($lastShippingId):''; - if(!empty($trackinglinkRaw)) { - $data['trackinglinkraw'] = $trackinglinkRaw; + if (!empty($itemlist)) { + $data['itemlist'] = $itemlist; + if ($allPositions) { + $data['allpositions'] = 1; + } } - } + + $data['orderId'] = $orderId; + $data['auftrag'] = $shopextid; + $data['internet'] = $internet; + $data['zahlungsweise'] = $zahlungsweise; + $data['versandart'] = $versandart; + if (!empty($trackingArr)) { + $data['trackinglist'] = $trackingArr; + } + if ($status === 'abgeschlossen') { + $data['versand'] = '1'; + $data['zahlung'] = '1'; + if ($shippingProduct !== null) { + $data['shipping_product'] = $shippingProduct; + } + if ($tracking != '') { + $data['tracking'] = $tracking; + $lastShippingId = (int) $this->app->DB->Select( + sprintf( + "SELECT `id` FROM `versand` WHERE `lieferschein` = %d AND `lieferschein` > 0 + ORDER BY `id` DESC LIMIT 1", + $deliveryNoteId + ) + ); + $trackinglink = $lastShippingId > 0 && method_exists($this->app->erp, 'GetTrackinglink') ? $this->app->erp->GetTrackinglink($lastShippingId) : ''; + if ($trackinglink) { + $data['trackinglink'] = $trackinglink; + if (!empty($trackingArr)) { + foreach ($trackingArr as $versandId => $track) { + $data['trackinglinklist'][$versandId] = $this->app->erp->GetTrackinglink($versandId); + } + } + } + $trackinglinkRaw = $lastShippingId > 0 && method_exists($this->app->erp, 'GetTrackingRawLink') ? $this->app->erp->GetTrackingRawLink($lastShippingId) : ''; + if (!empty($trackinglinkRaw)) { + $data['trackinglinkraw'] = $trackinglinkRaw; + } + } + } + + return $data; } - return $data; - } + /** + * @param int $shopId + * @param int $orderId + * + * @throws Exception + */ + public function RemoteUpdateAuftrag($shopId, $orderId) { + $data = $this->getDataToSendForUpdateOrder((int) $shopId, (int) $orderId); + if ($data['versand'] == '1' || $data['zahlung'] == '1') { + $bearbeiter = 'Cronjob'; + if (isset($this->app->User)) { + $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); + } - /** - * @param int $shopId - * @param int $orderId - * - * @throws Exception - */ - public function RemoteUpdateAuftrag($shopId, $orderId) - { - $data = $this->getDataToSendForUpdateOrder((int)$shopId, (int)$orderId); - if($data['versand']=='1' || $data['zahlung']=='1') - { - $bearbeiter = 'Cronjob'; - if(isset($this->app->User)){ - $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); - } - - $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); - if($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()){ - $query = sprintf('UPDATE `auftrag` + $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); + if ($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()) { + $query = sprintf('UPDATE `auftrag` SET `shop_status_update_attempt` = `shop_status_update_attempt` + 1, `shop_status_update_last_attempt_at` = NOW() WHERE `id` = %d', $orderId); - $this->app->DB->Update($query); + $this->app->DB->Update($query); - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); -/* $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ - 'orderId' => $orderId, - 'shopId' => $shopId, - 'message' => $response->getMessage()],true));*/ - - $this->logger->error('Versandmeldung an Shop fehlgeschlagen', - [ - 'orderId' => $orderId, - 'shopId' => $shopId, - 'message' => $response->getMessage() - ] - ); - - return; - } + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); + /* $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ + 'orderId' => $orderId, + 'shopId' => $shopId, + 'message' => $response->getMessage()],true)); */ - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); - $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); + $this->logger->error('Versandmeldung an Shop fehlgeschlagen', + [ + 'orderId' => $orderId, + 'shopId' => $shopId, + 'message' => $response->getMessage() + ] + ); + + return; + } + + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); + $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); + } } - } - /** - * @param int $shopId - * @param string $auftrag - * - * @param string $internet - * - * @throws Exception - */ - public function RemoteDeleteAuftrag($shopId, $auftrag, $internet='') - { - $data['auftrag'] = $auftrag; - $data['internet'] = $internet; - $this->RemoteCommand($shopId,'deleteauftrag',$data); - } - - /** - * @param int $shopId - * @param int $orderId - * - * @throws Exception - */ - public function RemoteStorniereAuftrag($shopId, $orderId) - { - $orderArr = $this->app->DB->SelectRow("SELECT shopextid, internet FROM auftrag WHERE id='$orderId' LIMIT 1"); - if(empty($orderArr)) { - return; + /** + * @param int $shopId + * @param string $auftrag + * + * @param string $internet + * + * @throws Exception + */ + public function RemoteDeleteAuftrag($shopId, $auftrag, $internet = '') { + $data['auftrag'] = $auftrag; + $data['internet'] = $internet; + $this->RemoteCommand($shopId, 'deleteauftrag', $data); } - $shopextid = $orderArr['shopextid']; - $internet = $orderArr['internet']; - $data['auftrag'] = $shopextid; - $data['internet'] = $internet; - - $this->app->DB->Insert(" + + /** + * @param int $shopId + * @param int $orderId + * + * @throws Exception + */ + public function RemoteStorniereAuftrag($shopId, $orderId) { + $orderArr = $this->app->DB->SelectRow("SELECT shopextid, internet FROM auftrag WHERE id='$orderId' LIMIT 1"); + if (empty($orderArr)) { + return; + } + $shopextid = $orderArr['shopextid']; + $internet = $orderArr['internet']; + $data['auftrag'] = $shopextid; + $data['internet'] = $internet; + + $this->app->DB->Insert(" INSERT INTO auftrag_protokoll (auftrag, zeit, bearbeiter, grund) - VALUES ($orderId,now(),'".(isset($this->app->User)?$this->app->DB->real_escape_string($this->app->User->GetName()):'Cronjob')."', + VALUES ($orderId,now(),'" . (isset($this->app->User) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "', 'Stonierung an Shop übertragen')" - ); - $this->RemoteCommand($shopId,'storniereauftrag',$data); - $shopextstatus='storniert'; - $this->app->DB->Update("UPDATE auftrag SET shopextstatus='$shopextstatus' WHERE id='$orderId' LIMIT 1"); - } + ); + $this->RemoteCommand($shopId, 'storniereauftrag', $data); + $shopextstatus = 'storniert'; + $this->app->DB->Update("UPDATE auftrag SET shopextstatus='$shopextstatus' WHERE id='$orderId' LIMIT 1"); + } - /** - * @param int $shopId - * @param int $fileId - * - * @return mixed - * @throws Exception - */ - public function RemoteDeleteFile($shopId, $fileId) - { - $inhalt = $this->app->erp->GetDatei($fileId); - $fileArr = $this->app->DB->SelectRow("SELECT titel,beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); - $titel = $fileArr['titel']; - $beschreibung = $fileArr['beschreibung']; + /** + * @param int $shopId + * @param int $fileId + * + * @return mixed + * @throws Exception + */ + public function RemoteDeleteFile($shopId, $fileId) { + $inhalt = $this->app->erp->GetDatei($fileId); + $fileArr = $this->app->DB->SelectRow("SELECT titel,beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); + $titel = $fileArr['titel']; + $beschreibung = $fileArr['beschreibung']; - $data['datei'] = $fileId; - //$data['checksum'] = md5($inhalt); - $data['checksum'] = md5($inhalt.$titel.$beschreibung); - return $this->RemoteCommand($shopId,'deletefile',$data); - } + $data['datei'] = $fileId; + //$data['checksum'] = md5($inhalt); + $data['checksum'] = md5($inhalt . $titel . $beschreibung); + return $this->RemoteCommand($shopId, 'deletefile', $data); + } - /** - * @param int $articleId - * @param int $shopId - */ - public function RemoteUpdateFilesArtikel($articleId, $shopId) - { - $files = $this->app->DB->SelectArr("SELECT DISTINCT ds.datei + /** + * @param int $articleId + * @param int $shopId + */ + public function RemoteUpdateFilesArtikel($articleId, $shopId) { + $files = $this->app->DB->SelectArr("SELECT DISTINCT ds.datei FROM datei_stichwoerter ds, datei d, artikel a WHERE d.id=ds.datei AND (ds.subjekt='Shopbild' OR ds.subjekt='Gruppenbild') AND ((ds.objekt='Artikel' AND ds.parameter=a.id) OR (ds.objekt='Kampangen' AND ds.parameter='$shopId')) AND - d.firma='".$this->app->User->GetFirma()."' AND a.shop='$shopId' AND a.id='$articleId'" - ); + d.firma='" . $this->app->User->GetFirma() . "' AND a.shop='$shopId' AND a.id='$articleId'" + ); - $tmp = $this->app->remote->RemoteGetFileListArticle($shopId,$articleId); - if(!empty($tmp)){ - foreach ($tmp as $row) { - $checkarray[$row['datei']] = $row['checksum']; - } - } - - if(!empty($files)){ - foreach($files as $file) { - $fid = $file['datei']; - $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fid' LIMIT 1"); - if($geloescht){ - $this->app->remote->RemoteDeleteFile($shopId, $fid); - $checkarray[$fid] = 'delete'; - }else{ - $md5 = !empty($checkarray[$fid]) ? (String)$checkarray[$fid] : ''; - $md5file = md5($this->app->erp->GetDatei($fid)); - if($md5 !== $md5file){ - $this->app->remote->RemoteSendFile($shopId, $fid); - $this->app->remote->RemoteAddFileSubject($shopId, $fid); - $checkarray[$fid] = 'update'; - } + $tmp = $this->app->remote->RemoteGetFileListArticle($shopId, $articleId); + if (!empty($tmp)) { + foreach ($tmp as $row) { + $checkarray[$row['datei']] = $row['checksum']; + } } - $checkarray[$fid] = 'mark'; - } - } - if(!empty($checkarray)) - { - foreach($checkarray as $key=>$value) - { - if($checkarray[$key]!=='mark' && $checkarray[$key]!=='delete' && $checkarray[$key]!=='update') - { - $this->app->remote->RemoteDeleteFile($shopId,$key); + + if (!empty($files)) { + foreach ($files as $file) { + $fid = $file['datei']; + $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fid' LIMIT 1"); + if ($geloescht) { + $this->app->remote->RemoteDeleteFile($shopId, $fid); + $checkarray[$fid] = 'delete'; + } else { + $md5 = !empty($checkarray[$fid]) ? (String) $checkarray[$fid] : ''; + $md5file = md5($this->app->erp->GetDatei($fid)); + if ($md5 !== $md5file) { + $this->app->remote->RemoteSendFile($shopId, $fid); + $this->app->remote->RemoteAddFileSubject($shopId, $fid); + $checkarray[$fid] = 'update'; + } + } + $checkarray[$fid] = 'mark'; + } + } + if (!empty($checkarray)) { + foreach ($checkarray as $key => $value) { + if ($checkarray[$key] !== 'mark' && $checkarray[$key] !== 'delete' && $checkarray[$key] !== 'update') { + $this->app->remote->RemoteDeleteFile($shopId, $key); + } + } } - } } - } + /** + * @param int $shopId + * @param int $fileId + * + * @return mixed|string + * @throws Exception + */ + public function RemoteSendFile($shopId, $fileId) { + // sende stichwoerter + $fileArr = $this->app->DB->SelectRow("SELECT geloescht, titel, beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); + if (empty($fileArr)) { + return ''; + } + $geloescht = $fileArr['geloescht']; + $titel = $fileArr['titel']; + $beschreibung = $fileArr['beschreibung']; - /** - * @param int $shopId - * @param int $fileId - * - * @return mixed|string - * @throws Exception - */ - public function RemoteSendFile($shopId, $fileId) - { - // sende stichwoerter - $fileArr = $this->app->DB->SelectRow("SELECT geloescht, titel, beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); - if(empty($fileArr)) { - return ''; + $inhalt = $this->app->erp->GetDatei($fileId); + $data['datei'] = $fileId; + $data['titel'] = $titel; + $data['beschreibung'] = $beschreibung; + $data['inhalt'] = base64_encode($inhalt); + $data['checksum'] = md5($inhalt . $titel . $beschreibung); + if (!$geloescht) { + return $this->RemoteCommand($shopId, 'sendfile', $data); + } + return ''; } - $geloescht = $fileArr['geloescht']; - $titel = $fileArr['titel']; - $beschreibung = $fileArr['beschreibung']; - $inhalt = $this->app->erp->GetDatei($fileId); - $data['datei'] = $fileId; - $data['titel'] = $titel; - $data['beschreibung'] =$beschreibung; - $data['inhalt'] = base64_encode($inhalt); - $data['checksum'] = md5($inhalt.$titel.$beschreibung); - if(!$geloescht){ - return $this->RemoteCommand($shopId, 'sendfile', $data); - } - return ''; - } - - /** - * @param int $shopId - * @param int $fileId - * - * @throws Exception - */ - public function RemoteAddFileSubject($shopId, $fileId) - { - // sende stichwoerter - $fileList = $this->app->DB->SelectArr("SELECT subjekt, parameter + /** + * @param int $shopId + * @param int $fileId + * + * @throws Exception + */ + public function RemoteAddFileSubject($shopId, $fileId) { + // sende stichwoerter + $fileList = $this->app->DB->SelectArr("SELECT subjekt, parameter FROM datei_stichwoerter WHERE (objekt='Artikel' OR objekt='Kampangen') AND datei='$fileId'" - ); - if(empty($fileList)) { - return; - } - - foreach($fileList as $fileRow) { - $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fileId' LIMIT 1"); - $stichwort['subjekt'] = $fileRow['subjekt']; - $stichwort['artikel'] = $fileRow['parameter']; - $stichwort['datei'] = $fileId; - if(!$geloescht){ - $this->RemoteCommand($shopId, 'addfilesubjekt', $stichwort); - } - } - } - - /** - * @param int $shopId - * @param array $artikel - * - * @return mixed - * @throws Exception - */ - public function RemoteDeleteArticle($shopId,$artikel) - { - return $this->RemoteCommand($shopId,'deletearticle',$artikel); - } - - /** - * @param int $shopId - * @param array $partner - * - * @return mixed - * @throws Exception - */ - public function RemoteSendPartner($shopId, $partner) - { - return $this->RemoteCommand($shopId, 'partnerlist', $partner); - } - - /** - * @param object $obj - * @param string $methodname - * - * @return string - */ - public function getMethod($obj, $methodname) - { - $methodname = trim((String)$methodname); - if($methodname === '') - { - return ''; - } - if(!$obj) - { - return ''; - } - if(method_exists($obj, $methodname)) - { - return $methodname; - } - $methods = get_class_methods($obj); - $classname = get_class($obj); - foreach($methods as $v) - { - if(strtolower($v) === 'import'.strtolower($methodname)) - { - return $v; - } - if(strtolower($v) === strtolower($classname.$methodname)) - { - return $v; - } - } - foreach($methods as $v) - { - if(strtolower($v) === strtolower($methodname)) - { - return $v; - } - } - return ''; - } - - /** - * @param int $id - * @param string $action - * @param string|array $data - * - * @return mixed - * @throws Exception - */ - public function RemoteCommand($id,$action,$data='') - { - $challenge = ''; - $shoptyp = $this->app->DB->Select("SELECT shoptyp FROM shopexport WHERE id='$id' LIMIT 1"); - $modulename = trim($this->app->DB->Select("SELECT modulename FROM shopexport WHERE id='$id' LIMIT 1"),'.'); - $isActionAuth = $action === 'auth'; - if($shoptyp === 'custom') - { - if($modulename != '') - { - - $file = dirname(__DIR__) . '/plugins/external/shopimporter/'.$modulename; - $classa = explode('_',str_replace('_'.$id.'.php','', $modulename)); - foreach($classa as $k => $v) - { - $classa[$k] = ucfirst($v); + ); + if (empty($fileList)) { + return; } - $class = implode('_', $classa); - if($this->app->DB->Select("SELECT aktiv FROM shopexport WHERE id = '$id' LIMIT 1")) - { - if(file_exists($file)) - { - include_once($file); - if(class_exists($class)){ - $obj = new $class($this->app, true); - if($obj){ - if(method_exists($obj,'getKonfig')) - { - $obj->getKonfig($id, $data); - } - $method = $this->getMethod($obj, $action); - if(method_exists($obj,$method)) - { - $ret = $obj->$method(); - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; + + foreach ($fileList as $fileRow) { + $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fileId' LIMIT 1"); + $stichwort['subjekt'] = $fileRow['subjekt']; + $stichwort['artikel'] = $fileRow['parameter']; + $stichwort['datei'] = $fileId; + if (!$geloescht) { + $this->RemoteCommand($shopId, 'addfilesubjekt', $stichwort); } - }elseif($isActionAuth) - { - return 'Fehler: Datei '.$file.' existiert nicht'; - } - }elseif($isActionAuth) { - return 'Fehler: Schnittstelle nicht aktiv'; } - } - return ''; } - if($shoptyp === 'intern') - { - if($modulename != '') - { - if($this->app->erp->ModulVorhanden($modulename)) - { - $obj = $this->app->erp->LoadModul($modulename); - if($obj){ - if(method_exists($obj,'getKonfig')) - { - $obj->getKonfig($id, $data); - } - $method = 'Import'.$action; - - if(method_exists($obj,$method)) { - try { - $ret = $obj->$method(); - } - catch(Exception $e) { - if($isActionAuth) { - return 'Fehler Auth: '.$e->getMessage(); - } - return 'Fehler: '.$e->getMessage(); - } - - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - $this->parseReturn($ret, $id, $action); - return $ret; - } else { - return 'Fehler: Funktion nicht implementiert: '.$method; - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Dieses Modul ist nicht verfügbar'; - } - }elseif($isActionAuth) - { - return 'Fehler: Kein Modul vorhanden'; - } - return ''; + /** + * @param int $shopId + * @param array $artikel + * + * @return mixed + * @throws Exception + */ + public function RemoteDeleteArticle($shopId, $artikel) { + return $this->RemoteCommand($shopId, 'deletearticle', $artikel); } - $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - if($shopexport){ - if($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom'){ + + /** + * @param int $shopId + * @param array $partner + * + * @return mixed + * @throws Exception + */ + public function RemoteSendPartner($shopId, $partner) { + return $this->RemoteCommand($shopId, 'partnerlist', $partner); + } + + /** + * @param object $obj + * @param string $methodname + * + * @return string + */ + public function getMethod($obj, $methodname) { + $methodname = trim((String) $methodname); + if ($methodname === '') { + return ''; + } + if (!$obj) { + return ''; + } + if (method_exists($obj, $methodname)) { + return $methodname; + } + $methods = get_class_methods($obj); + $classname = get_class($obj); + foreach ($methods as $v) { + if (strtolower($v) === 'import' . strtolower($methodname)) { + return $v; + } + if (strtolower($v) === strtolower($classname . $methodname)) { + return $v; + } + } + foreach ($methods as $v) { + if (strtolower($v) === strtolower($methodname)) { + return $v; + } + } return ''; - } - $token = $shopexport['token']; - $url = $shopexport['url']; - $z = $shopexport['passwort']; - $bezeichnung = $shopexport['bezeichnung']; - } - else { - $token = ''; - $z = ''; - $url = ''; - } - if($isActionAuth) { - if($token === '' || strlen($z) < 32 || $url === '') { - return 'Fehler: Bitte Zugangsdaten prüfen'; - } - } - elseif($token === '' || strlen($z) < 32 || $url === '' || !$this->app->DB->Select("SELECT id FROM shopexport WHERE id = '$id' AND aktiv = 1 LIMIT 1")){ - return ''; - } - - $tmp = parse_url($url); - $tmp['host'] = rtrim($tmp['host'],'/'); - $tmp['path'] = rtrim($tmp['path'],'/').'/'; - - $aes = new AES($z); - $token = base64_encode($aes->encrypt(serialize($token))); - $client = new HttpClient($tmp['host'], stripos($url,'https') === 0?443:80); - $geturl = $tmp['path'].'index.php?module=import&action='.$action.'&challenge='.(isset($challenge)?$challenge:''); - //Kein Fragezeichen vor module=import... - if(false !== stripos($bezeichnung, 'woocommerce')) { - $geturl = $tmp['path'].'module=import&action='.$action.'&challenge='.(isset($challenge)?$challenge:''); - } - if(false !== stripos($bezeichnung, 'shopware plugin')) { - $geturl = $tmp['path'].'wawisionimporter/?smodule=import&saction='.$action.'&challenge='.(isset($challenge)?$challenge:''); } - $post_data['token'] = $token; - $post_data['data'] = base64_encode(serialize($data)); - $client->timeout = 120; - if(!$client->post($geturl,$post_data)) { -// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); - - $this->logger->error('An error occurred', - [ - 'error' => $client->getError() - ] - ); - - throw new Exception('An error occurred: '.$client->getError()); - //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); - } - $ret = unserialize(base64_decode($client->getContent())); - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - $this->parseReturn($ret, $id, $action); - return $ret; - } + /** + * @param int $id + * @param string $action + * @param string|array $data + * + * @return mixed + * @throws Exception + */ + public function RemoteCommand($id, $action, $data = '') { + $challenge = ''; + $shoptyp = $this->app->DB->Select("SELECT shoptyp FROM shopexport WHERE id='$id' LIMIT 1"); + $modulename = trim($this->app->DB->Select("SELECT modulename FROM shopexport WHERE id='$id' LIMIT 1"), '.'); + $isActionAuth = $action === 'auth'; + if ($shoptyp === 'custom') { + if ($modulename != '') { - /** - * @param mixed $ret - * @param int $id - * @param string $action - */ - public function parseReturn($ret, $id, $action) - { - if($action === 'getarticlelist') { - if(empty($ret)) { - return; - } - $anz = 0; - if(empty($ret['errors'])) { - foreach($ret as $v) { - $anz++; - $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$id', '".$this->app->DB->real_escape_string($v)."')"); + $file = dirname(__DIR__) . '/plugins/external/shopimporter/' . $modulename; + $classa = explode('_', str_replace('_' . $id . '.php', '', $modulename)); + foreach ($classa as $k => $v) { + $classa[$k] = ucfirst($v); + } + $class = implode('_', $classa); + if ($this->app->DB->Select("SELECT aktiv FROM shopexport WHERE id = '$id' LIMIT 1")) { + if (file_exists($file)) { + include_once($file); + if (class_exists($class)) { + $obj = new $class($this->app, true); + if ($obj) { + if (method_exists($obj, 'getKonfig')) { + $obj->getKonfig($id, $data); + } + $method = $this->getMethod($obj, $action); + if (method_exists($obj, $method)) { + $ret = $obj->$method(); + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Datei ' . $file . ' existiert nicht'; + } + } elseif ($isActionAuth) { + return 'Fehler: Schnittstelle nicht aktiv'; + } + } + return ''; } - if(!$this->app->DB->Select("SELECT id FROM `prozessstarter` WHERE aktiv = 1 AND parameter = 'getarticles' LIMIT 1")) { - $this->app->DB->Update("UPDATE `prozessstarter` SET aktiv = 1 WHERE parameter = 'getarticles' LIMIT 1"); + + if ($shoptyp === 'intern') { + if ($modulename != '') { + if ($this->app->erp->ModulVorhanden($modulename)) { + $obj = $this->app->erp->LoadModul($modulename); + if ($obj) { + if (method_exists($obj, 'getKonfig')) { + $obj->getKonfig($id, $data); + } + $method = 'Import' . $action; + + if (method_exists($obj, $method)) { + try { + $ret = $obj->$method(); + } catch (Exception $e) { + if ($isActionAuth) { + return 'Fehler Auth: ' . $e->getMessage(); + } + return 'Fehler: ' . $e->getMessage(); + } + + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + $this->parseReturn($ret, $id, $action); + return $ret; + } else { + return 'Fehler: Funktion nicht implementiert: ' . $method; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Dieses Modul ist nicht verfügbar'; + } + } elseif ($isActionAuth) { + return 'Fehler: Kein Modul vorhanden'; + } + return ''; + } + $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + if ($shopexport) { + if ($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom') { + return ''; + } + $token = $shopexport['token']; + $url = $shopexport['url']; + $z = $shopexport['passwort']; + $bezeichnung = $shopexport['bezeichnung']; + } else { + $token = ''; + $z = ''; + $url = ''; + } + if ($isActionAuth) { + if ($token === '' || strlen($z) < 32 || $url === '') { + return 'Fehler: Bitte Zugangsdaten prüfen'; + } + } elseif ($token === '' || strlen($z) < 32 || $url === '' || !$this->app->DB->Select("SELECT id FROM shopexport WHERE id = '$id' AND aktiv = 1 LIMIT 1")) { + return ''; } - $this->app->DB->Update("UPDATE `prozessstarter` SET letzteausfuerhung = DATE_SUB(now(), INTERVAL periode MINUTE) WHERE aktiv = 1 AND parameter = 'getarticles' AND mutex = 0 LIMIT 1"); - } - $this->app->erp->SetKonfigurationValue('artikelimportanzahl_'.$id, $anz); - } - } - /** - * @param int $id - * @param string $action - * @param string|array $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteCommandAES($id,$action,$data='') - { - $challenge = ''; - $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - if(!empty($shopexport)){ - if($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom'){ - return ''; - } - $token = $shopexport['token']; - $url = $shopexport['url']; - $z = $shopexport['passwort']; - if($z === '' || $token === '' || $url === '') - { - throw new Exception('Der ImportKey/ImportToken/ImportUrl ist leer'); - } - } - $tmp = parse_url($url); + $tmp = parse_url($url); + $tmp['host'] = rtrim($tmp['host'], '/'); + $tmp['path'] = rtrim($tmp['path'], '/') . '/'; - $aes = new AES($z); - $token = base64_encode($aes->encrypt(serialize($token))); + $aes = new AES($z); + $token = base64_encode($aes->encrypt(serialize($token))); + $client = new HttpClient($tmp['host'], stripos($url, 'https') === 0 ? 443 : 80); + $geturl = $tmp['path'] . 'index.php?module=import&action=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); + //Kein Fragezeichen vor module=import... + if (false !== stripos($bezeichnung, 'woocommerce')) { + $geturl = $tmp['path'] . 'module=import&action=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); + } + if (false !== stripos($bezeichnung, 'shopware plugin')) { + $geturl = $tmp['path'] . 'wawisionimporter/?smodule=import&saction=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); + } - $client = new HttpClient($tmp['host']); - $geturl = $tmp['path'].'index.php?module=import&action='.$action.'&challenge='.$challenge; - - $post_data['token'] = $token; - $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); - - if(!$client->post($geturl,$post_data)) - { + $post_data['token'] = $token; + $post_data['data'] = base64_encode(serialize($data)); + $client->timeout = 120; + if (!$client->post($geturl, $post_data)) { // $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); - $this->logger->error('An error occurred', - [ - 'error' => $client->getError() - ] - ); + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); - throw new Exception('An error occurred: '.$client->getError()); + throw new Exception('An error occurred: ' . $client->getError()); + //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); + } + $ret = unserialize(base64_decode($client->getContent())); + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + $this->parseReturn($ret, $id, $action); + return $ret; + } + + /** + * @param mixed $ret + * @param int $id + * @param string $action + */ + public function parseReturn($ret, $id, $action) { + if ($action === 'getarticlelist') { + if (empty($ret)) { + return; + } + $anz = 0; + if (empty($ret['errors'])) { + foreach ($ret as $v) { + $anz++; + $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$id', '" . $this->app->DB->real_escape_string($v) . "')"); + } + if (!$this->app->DB->Select("SELECT id FROM `prozessstarter` WHERE aktiv = 1 AND parameter = 'getarticles' LIMIT 1")) { + $this->app->DB->Update("UPDATE `prozessstarter` SET aktiv = 1 WHERE parameter = 'getarticles' LIMIT 1"); + } + $this->app->DB->Update("UPDATE `prozessstarter` SET letzteausfuerhung = DATE_SUB(now(), INTERVAL periode MINUTE) WHERE aktiv = 1 AND parameter = 'getarticles' AND mutex = 0 LIMIT 1"); + } + $this->app->erp->SetKonfigurationValue('artikelimportanzahl_' . $id, $anz); + } + } + + /** + * @param int $id + * @param string $action + * @param string|array $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteCommandAES($id, $action, $data = '') { + $challenge = ''; + $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + if (!empty($shopexport)) { + if ($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom') { + return ''; + } + $token = $shopexport['token']; + $url = $shopexport['url']; + $z = $shopexport['passwort']; + if ($z === '' || $token === '' || $url === '') { + throw new Exception('Der ImportKey/ImportToken/ImportUrl ist leer'); + } + } + $tmp = parse_url($url); + + $aes = new AES($z); + $token = base64_encode($aes->encrypt(serialize($token))); + + $client = new HttpClient($tmp['host']); + $geturl = $tmp['path'] . 'index.php?module=import&action=' . $action . '&challenge=' . $challenge; + + $post_data['token'] = $token; + $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); + + if (!$client->post($geturl, $post_data)) { +// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); + + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); + + throw new Exception('An error occurred: ' . $client->getError()); + } + return unserialize($aes->decrypt(base64_decode($client->getContent()))); } - return unserialize($aes->decrypt(base64_decode($client->getContent()))); - } } + From eead99675961ce4d61fbc42e074581d4f98340ee Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 28 Jun 2024 13:14:57 +0200 Subject: [PATCH 32/52] remote changed return values and behaviour WIP --- cronjobs/artikeluebertragen.php | 24 +++++- www/lib/class.remote.php | 67 ++++++++-------- www/pages/shopimporter_mirakl.php | 126 +++++++++++++++--------------- 3 files changed, 121 insertions(+), 96 deletions(-) diff --git a/cronjobs/artikeluebertragen.php b/cronjobs/artikeluebertragen.php index f068e93e..d23f55f5 100644 --- a/cronjobs/artikeluebertragen.php +++ b/cronjobs/artikeluebertragen.php @@ -46,9 +46,9 @@ $app->DB->Update( if ($app->DB->Select("SELECT `mutex` FROM `prozessstarter` WHERE (`parameter` = 'artikeluebertragen') LIMIT 1") == 1) { $logger->debug( - 'Mutex' + 'Läuft bereits' ); -// return; + return; } $articles = $app->DB->SelectArr( @@ -233,7 +233,25 @@ foreach ($shops_to_transmit as $shop_to_transmit) { ); } - foreach ($result as $article) { + $logger->debug( + 'Ende {bezeichnung} (Shop {shop_to_transmit}) {count} Artikel', + [ + 'shop_to_transmit' => $shop_to_transmit['shop'], + 'bezeichnung' => $shop_to_transmit['bezeichnung'], + 'count' => (!empty($articles_to_transmit)?count($articles_to_transmit):0), + 'result' => $result + ] + ); + + // See description of return format in function class.remote.php -> RemoteSendArticleList() + foreach ($result['articlelist'] as $article) { + $app->DB->Delete( + sprintf( + 'DELETE FROM `shopexport_artikeluebertragen` WHERE `artikel`= %d AND `shop` = %d', + $article['artikel'], + $shop_to_transmit['shop'] + ) + ); $app->erp->LagerSync($article['artikel'], true); } } else { diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 7d9f099b..49242cf8 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1062,6 +1062,23 @@ class Remote { * * @return mixed|null * @throws Exception + * + * (NEW 2024-06-28) + * + * return value: (comes from Importsendlist or Importsendlistlager inside shopimporter_...) + * array ( + * 'count' => int, // Number of successfully sent articles + * 'new' => array (artikelid, fremdnummer), // List of new articles with external number + * 'message' => string + * 'status' => bool, // false = failed + * 'articles' => array( + * 'id', + * 'status', + * 'message', + * ... + * ) + * ) + * */ public function RemoteSendArticleList($id, $artikel_arr, $extnummer = '', $nurlager = false) { @@ -1115,15 +1132,6 @@ class Remote { for ($i = 0; $i < $cartikel_arr; $i++) { $artikel = $artikel_arr[$i]; - - $this->logger->debug( - 'RemoteSendArticleList', - [ - 'artikel' => $artikel, - 'i' => $i - ] - ); - $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); $tmp->Select($artikel); $data[$i] = ['artikel' => $artikel, 'artikelid' => $artikel]; @@ -1919,18 +1927,19 @@ class Remote { } } - $result = null; if (empty($data)) { continue; } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } } while (count($data[$i]['matrix_varianten']['artikel']) >= 5000); + // Bulk transfer (new 2024-06-28) + $result = null; + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } return $result; } @@ -2044,18 +2053,19 @@ class Remote { $data[$i]['variantevorhanden'] = 0; } - $result = null; if (empty($data)) { continue; } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } } + // Bulk transfer (new 2024-06-28) + $result = null; + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } return $result; } @@ -2121,6 +2131,8 @@ class Remote { $this->app->DB->real_escape_string($hash), $data[0]['artikel'], $id ) ); + + // See description of return format in function RemoteSendArticleList() if (!empty($result) && is_array($result) && !empty($result['new'])) { foreach ($result['new'] as $artikelid => $fremdnummer) { $artikelid = (int) $artikelid; @@ -2138,7 +2150,7 @@ class Remote { } } if (isset($result['anzahl'])) { - $result = $result['anzahl']; + $result['count'] = $result['anzahl']; }//Altes Verhalten } if (!$isLagerExported) { @@ -2293,10 +2305,6 @@ class Remote { $this->app->DB->Update($query); $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); - /* $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ - 'orderId' => $orderId, - 'shopId' => $shopId, - 'message' => $response->getMessage()],true)); */ $this->logger->error('Versandmeldung an Shop fehlgeschlagen', [ @@ -2670,7 +2678,6 @@ class Remote { $post_data['data'] = base64_encode(serialize($data)); $client->timeout = 120; if (!$client->post($geturl, $post_data)) { -// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); $this->logger->error('An error occurred', [ @@ -2748,8 +2755,6 @@ class Remote { $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); if (!$client->post($geturl, $post_data)) { -// $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); - $this->logger->error('An error occurred', [ 'error' => $client->getError() diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index a99ad6ea..376b30d7 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -1,5 +1,7 @@ app = $app; + $this->logger = $app->Container->get('Logger'); $this->intern = $intern; if ($intern) return; @@ -50,10 +54,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'ausblenden' => ['abholmodus' => ['ab_nummer', 'zeitbereich']], 'functions' => ['getarticlelist'], 'felder' => [ - 'protokoll' => [ - 'typ' => 'checkbox', - 'bezeichnung' => '{|Protokollierung im Logfile|}:' - ], 'apikey' => [ 'typ' => 'text', 'bezeichnung' => '{|API Key|}:', @@ -287,7 +287,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { public function ImportGetArticle() { - $articleList = $this->CatchRemoteCommand('data'); + $articlelist = $this->CatchRemoteCommand('data'); $parameters = array('product_references' => 'productID', 'product_'); @@ -364,38 +364,42 @@ class Shopimporter_Mirakl extends ShopimporterBase { $komma = ""; $status = true; - $articleList = $this->CatchRemoteCommand('data'); + $articlelist = $this->CatchRemoteCommand('data'); if ($export_products) { - $create_products_result = $this->mirakl_create_products($articleList); + $create_products_result = $this->mirakl_create_products($articlelist); if ($create_products_result['returncode'] != 0) { - $this->Log("Produktsync nach Mirakl hat Fehler", print_r($create_products_result, true)); + $this->Log("Produktsync nach Mirakl hat Fehler", $create_products_result); $message = "Produktsync nach Mirakl hat Fehler"; $komma = ", "; + $status = false; } else { + $this->Log("Produktsync nach Mirakl ok", $create_products_result); $message = "Produktimport in Mirakl ok"; $komma = ", "; } } - $offer_export_result = $this->mirakl_export_offers($articleList); + $offer_export_result = $this->mirakl_export_offers($articlelist); if ($offer_export_result['returncode'] != 0) { - $this->Log("Angebotsync nach Mirakl hat Fehler", print_r($offer_export_result, true)); + $this->Log("Angebotsync nach Mirakl hat Fehler", $offer_export_result); $message .= $komma."Angebotsync in Mirakl hat Fehler"; + $status = false; } else { - $this->Log("Angebotsync nach Mirakl ok", print_r($offer_export_result, true)); + $this->Log("Angebotsync nach Mirakl ok", $offer_export_result); $message .= $komma."Angebotsimport in Mirakl ok"; } - return(array('status' => $status, 'message' => $message)); + $articlelist = (array) $create_products_result['articlelist'] + (array) $offer_export_result['articlelist']; // This merges the fields for each article + return(array('status' => $status, 'message' => $message, 'articlelist' => $articlelist)); // Check for missing products and try to create /* if ($export_products) { $create_products_list = array(); - foreach ($offer_export_result['articleList'] as $key => $article) { + foreach ($offer_export_result['articlelist'] as $key => $article) { if ($article['mirakl_export_offers_result']['returncode'] == 12) { switch ($article['mirakl_export_offers_result']['message']) { case $this->mirakl_error_text_product_missing: @@ -412,19 +416,17 @@ class Shopimporter_Mirakl extends ShopimporterBase { $create_products_result = $this->mirakl_create_products($create_products_list); if ($create_products_result['returncode'] != 0) { - $this->Log("Produktimport in Mirakl hat Fehler", print_r($create_products_result, true)); + $this->Log("Produktimport in Mirakl hat Fehler", $create_products_result); return(array('status' => false, 'message' => "Produktimport in Mirakl hat Fehler")); } // Retry offer import - $offer_export_result = $this->mirakl_export_offers($articleList); + $offer_export_result = $this->mirakl_export_offers($articlelist); if ($offer_export_result['returncode'] == 0) { return(array('status' => true, 'message' => "Angebots und Produktimport in Mirakl ok")); } - } - - - $this->Log("Angebotsimport in Mirakl hat Fehler", print_r($offer_export_result, true)); + } + $this->Log("Angebotsimport in Mirakl hat Fehler", $offer_export_result); return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); */ @@ -435,9 +437,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { exit(); } - private function Log($message, $dump = '') { + private function Log($message, $dump = array()) { if ($this->protocol) { - $this->app->erp->Logfile('Mirakl (Shop '.$this->shopid.') '.$message, print_r($dump, true)); + $this->logger->debug('Mirakl (Shop '.$this->shopid.') '.$message, (array) $dump); } } @@ -454,7 +456,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { // STAGING, WAITING_ACCEPTANCE, WAITING_DEBIT, WAITING_DEBIT_PAYMENT, SHIPPING, SHIPPED, TO_COLLECT, RECEIVED, CLOSED, REFUSED, CANCELED public function ImportGetAuftraegeAnzahl() { $response = $this->miraklRequest('orders', getdata: array('order_state_codes' => 'WAITING_ACCEPTANCE'), raw: true); - $this->Log('ImportGetAuftraegeAnzahl', print_r($response,true)); + $this->Log('ImportGetAuftraegeAnzahl', $response); $result_array = json_decode($response); return($result_array->total_count); } @@ -468,7 +470,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); - $this->Log('ImportGetAuftrag', print_r($response,true)); + $this->Log('ImportGetAuftrag', $response); $result_array = json_decode($response); $fetchedOrders = []; @@ -591,25 +593,25 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Send offer data to mirakl - * $articleList = $this->CatchRemoteCommand('data'); + * $articlelist = $this->CatchRemoteCommand('data'); * Return - * array (returncode, message, articleList) articleList with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) + * array (returncode, message, articlelist) articlelist with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) * returncode 0 = ok, 1 = not ok - * returncode articleList 0 = ok, 10 = missing required attributes, 11 category not found, 12 rejected from mirakl + * returncode articlelist 0 = ok, 10 = missing required attributes, 11 category not found, 12 rejected from mirakl */ - private function mirakl_export_offers(array $articleList) : array { + private function mirakl_export_offers(array $articlelist) : array { $mirakl_export_offers_return_value = array(); $mirakl_export_offers_return_value['returncode'] = 0; - $mirakl_export_offers_return_value['articleList'] = array(); + $mirakl_export_offers_return_value['articlelist'] = array(); - $this->Log('Angebotsexport Start', print_r($articleList,true)); + $this->Log('Angebotsexport Start', $articlelist); // First gather all articles as offers and send them // Wait for import to finish // Evaluate import - foreach ($articleList as $key => $article) { + foreach ($articlelist as $key => $article) { $skip_article = false; @@ -654,7 +656,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { if ($missing) { $mirakl_export_offers_return_value['returncode'] = 1; $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration \"".$configuration['konfiguration']."\": ".implode(', ',$missing)); - $mirakl_export_offers_return_value['articleList'][] = $article; + $mirakl_export_offers_return_value['articlelist'][] = $article; $skip_article = true; } // Check Required attributes @@ -691,12 +693,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $offers_for_mirakl[] = $offer_for_mirakl; $article['mirakl_export_offers_result'] = array('returncode' => 0, 'message' => ""); - $mirakl_export_offers_return_value['articleList'][] = $article; + $mirakl_export_offers_return_value['articlelist'][] = $article; } else { // configuration_found $mirakl_export_offers_return_value['returncode'] = 1; $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); - $mirakl_export_offers_return_value['articleList'][] = $article; + $mirakl_export_offers_return_value['articlelist'][] = $article; continue; } } @@ -722,12 +724,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!isset($result->import_id)) { $mirakl_export_offers_return_value['returncode'] = 1; - $this->Log('Angebotsimport abgelehnt', print_r($response,true)); + $this->Log('Angebotsimport abgelehnt', $response); $mirakl_export_offers_return_value['message'] = "Angebotsimport abgelehnt: ".print_r($response,true); return($mirakl_export_offers_return_value); } - $this->Log('Angebotsimport angelegt', print_r($response,true)); + $this->Log('Angebotsimport angelegt', $response); $import_id = $result->import_id; @@ -747,7 +749,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { - $this->Log('Angebotsimport fehlgeschlagen', print_r($response,true)); + $this->Log('Angebotsimport fehlgeschlagen', $response); $mirakl_export_offers_return_value['returncode'] = 2; $mirakl_export_offers_return_value['message'] = "Angebotsimport fehlgeschlagen: ".print_r($response,true); @@ -755,11 +757,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($result->lines_in_error == 0) { - $this->Log('Angebotsimport ok', print_r($response,true)); + $this->Log('Angebotsimport ok', $response); return($mirakl_export_offers_return_value); } - $this->Log('Angebotsimport meldet Fehler in '.$result->lines_in_error.' Zeilen', print_r($response,true)); + $this->Log('Angebotsimport meldet Fehler in '.$result->lines_in_error.' Zeilen', $response); $result = array(); // Check errors with CSV unfucking... @@ -780,14 +782,14 @@ class Shopimporter_Mirakl extends ShopimporterBase { $article_key = array_search( $response_array['product_id'], array_column( - $mirakl_export_offers_return_value['articleList'], + $mirakl_export_offers_return_value['articlelist'], 'product_id') ); - $mirakl_export_offers_return_value['articleList'][$article_key]['mirakl_export_offers_result'] = array('returncode' => 12, 'message' => $response_array[$error_message_key]); + $mirakl_export_offers_return_value['articlelist'][$article_key]['mirakl_export_offers_result'] = array('returncode' => 12, 'message' => $response_array[$error_message_key]); } - $this->Log('Angebotsimport Fehlerbericht', print_r($response,true)); + $this->Log('Angebotsimport Fehlerbericht', $response); $mirakl_export_offers_return_value['returncode'] = 1; @@ -797,24 +799,24 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Create products * Return - * array (returncode, message, articleList) articleList with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) + * array (returncode, message, articlelist) articlelist with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) * returncode 0 = ok, 1 = not ok - * returncode articleList 0 = ok, 20 rejected from mirakl + * returncode articlelist 0 = ok, 20 rejected from mirakl */ - private function mirakl_create_products(array $articleList) : array { + private function mirakl_create_products(array $articlelist) : array { $mirakl_create_products_return_value = array(); $mirakl_create_products_return_value['returncode'] = 0; - $mirakl_create_products_return_value['articleList'] = $articleList; + $mirakl_create_products_return_value['articlelist'] = $articlelist; $number_of_articles = 0; - $this->Log('Produktexport Start', print_r($csv,true)); + $this->Log('Produktexport Start', $articlelist); // Build CSV $csv_header = ""; $newline = ""; - foreach ($articleList as $article) { + foreach ($articlelist as $article) { $product_for_mirakl = array(); // Determine configuration @@ -833,7 +835,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!$configuration_found) { $mirakl_create_products_return_value['returncode'] = 1; $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); - $mirakl_create_products_return_value['articleList'][] = $article; + $mirakl_create_products_return_value['articlelist'][] = $article; continue; } @@ -864,7 +866,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $result = []; - $this->Log('Produktexport Daten', print_r($csv,true)); + $this->Log('Produktexport Daten', array('csv' => $csv)); $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); @@ -873,12 +875,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $result = json_decode($response); if (!isset($result->import_id)) { - $this->Log('Produktimport abgelehnt', print_r($response,true)); + $this->Log('Produktimport abgelehnt', $response); $mirakl_create_products_return_value['returncode'] = 1; return($mirakl_create_products_return_value); } - $this->Log('Produktimport angelegt', print_r($result,true)); + $this->Log('Produktimport angelegt', $result); $import_id = $result->import_id; @@ -898,26 +900,26 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { - $this->Log('Produktimport fehlgeschlagen', print_r($response,true)); + $this->Log('Produktimport fehlgeschlagen', $response); $mirakl_create_products_return_value['returncode'] = 1; return($mirakl_create_products_return_value); } if (!$result->has_error_report && !$result->has_transformation_error_report) { - $this->Log('Produktimport ok', print_r($response,true)); + $this->Log('Produktimport ok', $response); } else { - $this->Log('Produktimport meldet Fehler', print_r($response,true)); + $this->Log('Produktimport meldet Fehler', $response); $mirakl_create_products_return_value['returncode'] = 1; } if ($result->has_new_product_report) { $response = $this->miraklRequest('products/imports/'.$import_id.'/new_product_report', raw: true); - $this->Log('Produktimport "Hinzugefügte Produkte"-Bericht', print_r($response,true)); + $this->Log('Produktimport "Hinzugefügte Produkte"-Bericht', $response); } if ($result->has_transformed_file) { $response = $this->miraklRequest('products/imports/'.$import_id.'/transformed_file', raw: true); - $this->Log('Produktimport Datei im Marketplace-Format', print_r($response,true)); + $this->Log('Produktimport Datei im Marketplace-Format', $response); } if ($result->has_error_report) { @@ -936,13 +938,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { $article_key = array_search( $response_array['product_id'], array_column( - $mirakl_create_products_return_value['articleList'], + $mirakl_create_products_return_value['articlelist'], 'product_id') ); - $mirakl_create_products_return_value['articleList'][$article_key]['mirakl_create_products_result'] = array('returncode' => 13, 'message' => $response_array[$error_message_key]); + $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 13, 'message' => $response_array[$error_message_key]); } - $this->Log('Produktimport Fehlerbericht', print_r($response,true)); + $this->Log('Produktimport Fehlerbericht', $response); } if ($result->has_transformation_error_report) { @@ -961,13 +963,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { $article_key = array_search( $response_array['product_id'], array_column( - $mirakl_create_products_return_value['articleList'], + $mirakl_create_products_return_value['articlelist'], 'product_id') ); - $mirakl_create_products_return_value['articleList'][$article_key]['mirakl_create_products_result'] = array('returncode' => 14, 'message' => $response_array[$error_message_key]); + $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 14, 'message' => $response_array[$error_message_key]); } - $this->Log('Produktimport Transformation-Fehlerbericht', print_r($response,true)); + $this->Log('Produktimport Transformation-Fehlerbericht', $response); } return($mirakl_create_products_return_value); From 448d49ad6d0b16c23a0b0fe3438dbba6ab245d27 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 28 Jun 2024 15:48:39 +0200 Subject: [PATCH 33/52] Logger added log levels public --- classes/Components/Logger/Logger.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/classes/Components/Logger/Logger.php b/classes/Components/Logger/Logger.php index ea3a8b45..6371faba 100644 --- a/classes/Components/Logger/Logger.php +++ b/classes/Components/Logger/Logger.php @@ -10,6 +10,15 @@ use Xentral\Components\Logger\Handler\LogHandlerInterface; final class Logger extends AbstractLogger { + const EMERGENCY = 'emergency'; + const ALERT = 'alert'; + const CRITICAL = 'critical'; + const ERROR = 'error'; + const WARNING = 'warning'; + const NOTICE = 'notice'; + const INFO = 'info'; + const DEBUG = 'debug'; + /** @var LogHandlerInterface[] $levelHandlers */ private $logHandlers; From d0d9c4150bc18138614ca11917c5a177cceaeea2 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 28 Jun 2024 15:49:16 +0200 Subject: [PATCH 34/52] mirakl logging improvements --- www/pages/shopimporter_mirakl.php | 113 ++++++++++++++++-------------- 1 file changed, 62 insertions(+), 51 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 376b30d7..2b95bf0c 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -360,21 +360,28 @@ class Shopimporter_Mirakl extends ShopimporterBase { */ public function mirakl_export_offers_and_products(bool $export_products) { + $this->Log(Logger::DEBUG, "mirakl_export_offers_and_products", array('export products' => $export_products)); + $message = ""; $komma = ""; $status = true; + $level = Logger::NOTICE; + $log_result = null; + $articlelist = $this->CatchRemoteCommand('data'); if ($export_products) { $create_products_result = $this->mirakl_create_products($articlelist); if ($create_products_result['returncode'] != 0) { - $this->Log("Produktsync nach Mirakl hat Fehler", $create_products_result); + $level = Logger::ERROR; + $log_result['create_products_result'] = $create_products_result; $message = "Produktsync nach Mirakl hat Fehler"; $komma = ", "; $status = false; } else { - $this->Log("Produktsync nach Mirakl ok", $create_products_result); + $level = Logger::NOTICE; + $this->Log(Logger::INFO, "Produktsync nach Mirakl ok", $create_products_result); $message = "Produktimport in Mirakl ok"; $komma = ", "; } @@ -383,14 +390,17 @@ class Shopimporter_Mirakl extends ShopimporterBase { $offer_export_result = $this->mirakl_export_offers($articlelist); if ($offer_export_result['returncode'] != 0) { - $this->Log("Angebotsync nach Mirakl hat Fehler", $offer_export_result); + $level = Logger::ERROR; + $log_result['offer_export_result'] = $offer_export_result; $message .= $komma."Angebotsync in Mirakl hat Fehler"; $status = false; } else { - $this->Log("Angebotsync nach Mirakl ok", $offer_export_result); + $this->Log(Logger::INFO, "Angebotsync nach Mirakl ok", $offer_export_result); $message .= $komma."Angebotsimport in Mirakl ok"; } + $this->Log($level, $message, array('create_products_result' => $create_products_result, 'offer_export_result' => $offer_export_result)); + $articlelist = (array) $create_products_result['articlelist'] + (array) $offer_export_result['articlelist']; // This merges the fields for each article return(array('status' => $status, 'message' => $message, 'articlelist' => $articlelist)); @@ -416,7 +426,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $create_products_result = $this->mirakl_create_products($create_products_list); if ($create_products_result['returncode'] != 0) { - $this->Log("Produktimport in Mirakl hat Fehler", $create_products_result); + $this->Log(Logger::DEBUG, "Produktimport in Mirakl hat Fehler", $create_products_result); return(array('status' => false, 'message' => "Produktimport in Mirakl hat Fehler")); } @@ -426,37 +436,16 @@ class Shopimporter_Mirakl extends ShopimporterBase { return(array('status' => true, 'message' => "Angebots und Produktimport in Mirakl ok")); } } - $this->Log("Angebotsimport in Mirakl hat Fehler", $offer_export_result); + $this->Log(Logger::DEBUG, "Angebotsimport in Mirakl hat Fehler", $offer_export_result); return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); */ } - private function getOrdersToProcess(int $limit) { - echo("getOrdersToProcess"); - exit(); - } - - private function Log($message, $dump = array()) { - if ($this->protocol) { - $this->logger->debug('Mirakl (Shop '.$this->shopid.') '.$message, (array) $dump); - } - } - - public function ImportDeleteAuftrag() { - echo("ImportDeleteAuftrag"); - exit(); - } - - public function ImportUpdateAuftrag() { - echo("ImportUpdateAuftrag"); - exit(); - } - // STAGING, WAITING_ACCEPTANCE, WAITING_DEBIT, WAITING_DEBIT_PAYMENT, SHIPPING, SHIPPED, TO_COLLECT, RECEIVED, CLOSED, REFUSED, CANCELED public function ImportGetAuftraegeAnzahl() { $response = $this->miraklRequest('orders', getdata: array('order_state_codes' => 'WAITING_ACCEPTANCE'), raw: true); - $this->Log('ImportGetAuftraegeAnzahl', $response); + $this->Log(Logger::DEBUG, 'ImportGetAuftraegeAnzahl', $response); $result_array = json_decode($response); return($result_array->total_count); } @@ -470,7 +459,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); - $this->Log('ImportGetAuftrag', $response); + $this->Log(Logger::DEBUG, 'ImportGetAuftrag', $response); $result_array = json_decode($response); $fetchedOrders = []; @@ -587,7 +576,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'warenkorbjson' => base64_encode(json_encode($cart)) ]; - $this->Log('Auftragsimport', $cart); + $this->Log(Logger::DEBUG, 'Auftragsimport', $cart); return $fetchedOrders; } @@ -605,7 +594,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_export_offers_return_value['returncode'] = 0; $mirakl_export_offers_return_value['articlelist'] = array(); - $this->Log('Angebotsexport Start', $articlelist); + $this->Log(Logger::DEBUG, 'Angebotsexport Start', $articlelist); // First gather all articles as offers and send them // Wait for import to finish @@ -705,7 +694,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (empty($offers_for_mirakl)) { $mirakl_export_offers_return_value['returncode'] = 1; - $this->Log('Angebotsexport keine Artikel bereit', $mirakl_export_offers_return_value); + $this->Log(Logger::ERROR, 'Angebotsexport keine Artikel bereit', $mirakl_export_offers_return_value); $mirakl_export_offers_return_value['message'] = "Angebotsexport keine Artikel bereit"; return($mirakl_export_offers_return_value); } @@ -715,7 +704,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $json_for_mirakl = json_encode($data_for_mirakl); - $this->Log('Angebotsexport Daten', $json_for_mirakl); + $this->Log(Logger::DEBUG, 'Angebotsexport Daten', $json_for_mirakl); $result = []; $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); @@ -724,12 +713,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!isset($result->import_id)) { $mirakl_export_offers_return_value['returncode'] = 1; - $this->Log('Angebotsimport abgelehnt', $response); + $this->Log(Logger::ERROR, 'Angebotsimport abgelehnt', $response); $mirakl_export_offers_return_value['message'] = "Angebotsimport abgelehnt: ".print_r($response,true); return($mirakl_export_offers_return_value); } - $this->Log('Angebotsimport angelegt', $response); + $this->Log(Logger::INFO, 'Angebotsimport angelegt', $response); $import_id = $result->import_id; @@ -749,7 +738,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { - $this->Log('Angebotsimport fehlgeschlagen', $response); + $this->Log(Logger::ERROR, 'Angebotsimport fehlgeschlagen', $response); $mirakl_export_offers_return_value['returncode'] = 2; $mirakl_export_offers_return_value['message'] = "Angebotsimport fehlgeschlagen: ".print_r($response,true); @@ -757,11 +746,11 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($result->lines_in_error == 0) { - $this->Log('Angebotsimport ok', $response); + $this->Log(Logger::INFO, 'Angebotsimport ok', $response); return($mirakl_export_offers_return_value); } - $this->Log('Angebotsimport meldet Fehler in '.$result->lines_in_error.' Zeilen', $response); + $this->Log(Logger::ERROR, 'Angebotsimport meldet Fehler in '.$result->lines_in_error.' Zeilen', $response); $result = array(); // Check errors with CSV unfucking... @@ -789,7 +778,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_export_offers_return_value['articlelist'][$article_key]['mirakl_export_offers_result'] = array('returncode' => 12, 'message' => $response_array[$error_message_key]); } - $this->Log('Angebotsimport Fehlerbericht', $response); + $this->Log(Logger::ERROR, 'Angebotsimport Fehlerbericht', $response); $mirakl_export_offers_return_value['returncode'] = 1; @@ -811,7 +800,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $number_of_articles = 0; - $this->Log('Produktexport Start', $articlelist); + $this->Log(Logger::DEBUG, 'Produktexport Start', $articlelist); // Build CSV $csv_header = ""; @@ -866,7 +855,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $result = []; - $this->Log('Produktexport Daten', array('csv' => $csv)); + $this->Log(Logger::DEBUG, 'Produktexport Daten', array('csv' => $csv)); $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); @@ -875,12 +864,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $result = json_decode($response); if (!isset($result->import_id)) { - $this->Log('Produktimport abgelehnt', $response); + $this->Log(Logger::ERROR, 'Produktimport abgelehnt', $response); $mirakl_create_products_return_value['returncode'] = 1; return($mirakl_create_products_return_value); } - $this->Log('Produktimport angelegt', $result); + $this->Log(Logger::INFO, 'Produktimport angelegt', $result); $import_id = $result->import_id; @@ -900,26 +889,26 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($status == 'FAILED') { - $this->Log('Produktimport fehlgeschlagen', $response); + $this->Log(Logger::ERROR, 'Produktimport fehlgeschlagen', $response); $mirakl_create_products_return_value['returncode'] = 1; return($mirakl_create_products_return_value); } if (!$result->has_error_report && !$result->has_transformation_error_report) { - $this->Log('Produktimport ok', $response); + $this->Log(Logger::INFO, 'Produktimport ok', $response); } else { - $this->Log('Produktimport meldet Fehler', $response); + $this->Log(Logger::ERROR, 'Produktimport meldet Fehler', $response); $mirakl_create_products_return_value['returncode'] = 1; } if ($result->has_new_product_report) { $response = $this->miraklRequest('products/imports/'.$import_id.'/new_product_report', raw: true); - $this->Log('Produktimport "Hinzugefügte Produkte"-Bericht', $response); + $this->Log(Logger::DEBUG, 'Produktimport "Hinzugefügte Produkte"-Bericht', $response); } if ($result->has_transformed_file) { $response = $this->miraklRequest('products/imports/'.$import_id.'/transformed_file', raw: true); - $this->Log('Produktimport Datei im Marketplace-Format', $response); + $this->Log(Logger::DEBUG, 'Produktimport Datei im Marketplace-Format', $response); } if ($result->has_error_report) { @@ -944,7 +933,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 13, 'message' => $response_array[$error_message_key]); } - $this->Log('Produktimport Fehlerbericht', $response); + $this->Log(Logger::ERROR, 'Produktimport Fehlerbericht', $response); } if ($result->has_transformation_error_report) { @@ -969,11 +958,33 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 14, 'message' => $response_array[$error_message_key]); } - $this->Log('Produktimport Transformation-Fehlerbericht', $response); + $this->Log(Logger::ERROR, 'Produktimport Transformation-Fehlerbericht', $response); } return($mirakl_create_products_return_value); } - + + private function Log($level, $message, $dump = array()) { + if ($this->protocol) { + $this->logger->Log($level, 'Mirakl (Shop '.$this->shopid.') '.$message, (array) $dump); + } + } + + private function getOrdersToProcess(int $limit) { + echo("getOrdersToProcess"); + exit(); + } + + public function ImportDeleteAuftrag() { + echo("ImportDeleteAuftrag"); + exit(); + } + + public function ImportUpdateAuftrag() { + echo("ImportUpdateAuftrag"); + exit(); + } + + } From 01561960ec933498f41eaffd76954323e70c84e5 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Sun, 30 Jun 2024 13:50:59 +0200 Subject: [PATCH 35/52] class.remote.php sendlist changed to work on arrays --- www/lib/class.remote.php | 102 +++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 53 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 49242cf8..1c9c4be1 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1930,15 +1930,15 @@ class Remote { if (empty($data)) { continue; } - } while (count($data[$i]['matrix_varianten']['artikel']) >= 5000); + } while (count($data[$i]['matrix_varianten']['artikel']) >= 5000); // Bulk transfer (new 2024-06-28) $result = null; if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); + $result = $this->sendlistlager($id, $data); } if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); + $result = $this->sendlist($id, $data, true); } return $result; } @@ -2061,10 +2061,10 @@ class Remote { // Bulk transfer (new 2024-06-28) $result = null; if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); + $result = $this->sendlistlager($id, $data); } if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); + $result = $this->sendlist($id, $data, true); } return $result; } @@ -2085,66 +2085,61 @@ class Remote { return $this->app->DB->SelectArr($query); } - protected function sendlistlager($i, $id, $data) { - $data2 = $data; - foreach ($data2 as $key => $value) { - $data2[$key]['artikel'] = $value['artikelid']; - } - $result = $this->RemoteCommand($id, 'sendlistlager', $data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); + protected function sendlistlager(int $shop_id, array $data) { + $result = $this->RemoteCommand($shop_id, 'sendlistlager', $data); return $result; } - protected function sendlist($i, $id, $data, $isLagerExported) { - /** @var Shopexport $objShopexport */ - $objShopexport = $this->app->loadModule('shopexport'); - $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); - $hash = $changedHash['hash']; - //$changedHash = $changedHash['changed']; - - $result = $this->RemoteCommand($id, 'sendlist', $data); - $checkAo = $this->app->DB->Select( - sprintf( - 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', - $data[0]['artikel'], $id - ) - ); - if (empty($checkAo)) { - $this->app->DB->Insert( - sprintf( - 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) - VALUES (%d, %d, 1, 1) ', - $data[0]['artikel'], $id - ) - ); - } - $this->app->DB->Update( - sprintf( - "UPDATE artikel_onlineshops - SET last_article_transfer = NOW(), last_article_hash = '%s' - WHERE artikel = %d AND shop = %d", - $this->app->DB->real_escape_string($hash), $data[0]['artikel'], $id - ) - ); + protected function sendlist(int $shop_id, array $data, $isLagerExported) { // See description of return format in function RemoteSendArticleList() - if (!empty($result) && is_array($result) && !empty($result['new'])) { + $result = $this->RemoteCommand($shop_id, 'sendlist', $data); + + if (!empty($result) && is_array($result)) { + foreach ($result['articles'] as $artikelid) { + /** @var Shopexport $objShopexport */ + $objShopexport = $this->app->loadModule('shopexport'); + $changedHash = $objShopexport->hasArticleHashChanged($artikelid, $shop_id); + $hash = $changedHash['hash']; + + $checkAo = $this->app->DB->Select( + sprintf( + 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', + $artikelid, $shop_id + ) + ); + if (empty($checkAo)) { + $this->app->DB->Insert( + sprintf( + 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) + VALUES (%d, %d, 1, 1) ', + $artikelid, $shop_id + ) + ); + } + $this->app->DB->Update( + sprintf( + "UPDATE artikel_onlineshops + SET last_article_transfer = NOW(), last_article_hash = '%s' + WHERE artikel = %d AND shop = %d", + $this->app->DB->real_escape_string($hash), $artikelid, $shop_id + ) + ); + } + } + + if (!empty($result) && is_array($result)) { foreach ($result['new'] as $artikelid => $fremdnummer) { $artikelid = (int) $artikelid; $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); if ($artikelid > 0 && $artikelnummer != trim($fremdnummer) && - ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || + ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$shop_id' OR shop2 = '$shop_id' OR shop3 = '$shop_id') LIMIT 1") || $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") ) && trim($fremdnummer) !== '') { //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. - if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$shop_id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) - VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) + VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$shop_id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) "); } } @@ -2153,8 +2148,9 @@ class Remote { $result['count'] = $result['anzahl']; }//Altes Verhalten } + if (!$isLagerExported) { - $this->sendlistlager($i, $id, $data); + $this->sendlistlager($shop_id, $data); } return $result; } From 6e834b6df24f7946c8938b46440f9f7c672eaf5e Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 1 Jul 2024 15:25:04 +0200 Subject: [PATCH 36/52] mirakl export products per configuration --- www/pages/shopimporter_mirakl.php | 240 ++++++++++++++++++++---------- 1 file changed, 158 insertions(+), 82 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 2b95bf0c..832c538a 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -360,7 +360,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { */ public function mirakl_export_offers_and_products(bool $export_products) { - $this->Log(Logger::DEBUG, "mirakl_export_offers_and_products", array('export products' => $export_products)); +// $this->Log(Logger::DEBUG, "mirakl_export_offers_and_products", array('export products' => $export_products)); $message = ""; $komma = ""; @@ -372,71 +372,78 @@ class Shopimporter_Mirakl extends ShopimporterBase { $articlelist = $this->CatchRemoteCommand('data'); if ($export_products) { - $create_products_result = $this->mirakl_create_products($articlelist); - if ($create_products_result['returncode'] != 0) { + $export_products_result = $this->mirakl_export_products($articlelist); + if ($export_products_result['export_products_returncode'] != 0) { $level = Logger::ERROR; - $log_result['create_products_result'] = $create_products_result; $message = "Produktsync nach Mirakl hat Fehler"; $komma = ", "; $status = false; } else { $level = Logger::NOTICE; - $this->Log(Logger::INFO, "Produktsync nach Mirakl ok", $create_products_result); + $this->Log(Logger::INFO, "Produktsync nach Mirakl ok", $export_products_result); $message = "Produktimport in Mirakl ok"; $komma = ", "; } } - $offer_export_result = $this->mirakl_export_offers($articlelist); + $export_offers_result = $this->mirakl_export_offers($articlelist); - if ($offer_export_result['returncode'] != 0) { + if ($export_offers_result['returncode'] != 0) { $level = Logger::ERROR; - $log_result['offer_export_result'] = $offer_export_result; $message .= $komma."Angebotsync in Mirakl hat Fehler"; $status = false; } else { - $this->Log(Logger::INFO, "Angebotsync nach Mirakl ok", $offer_export_result); + $this->Log(Logger::INFO, "Angebotsync nach Mirakl ok", $export_offers_result); $message .= $komma."Angebotsimport in Mirakl ok"; } - $this->Log($level, $message, array('create_products_result' => $create_products_result, 'offer_export_result' => $offer_export_result)); + $this->Log($level, $message, array('export_products_result' => $export_products_result, 'export_offers_result' => $export_offers_result)); - $articlelist = (array) $create_products_result['articlelist'] + (array) $offer_export_result['articlelist']; // This merges the fields for each article - return(array('status' => $status, 'message' => $message, 'articlelist' => $articlelist)); + foreach ($articlelist as $key => $article) { + $articlelist[$key] = (array) $export_products_result['articlelist'][$key] + (array) $export_offers_result['articlelist'][$key]; // This merges the fields for each article + } + + return( + array( + 'status' => $status, + 'message' => $message, + 'articlelist' => $articlelist + ) + ); // Check for missing products and try to create /* if ($export_products) { - $create_products_list = array(); + $export_products_list = array(); - foreach ($offer_export_result['articlelist'] as $key => $article) { + foreach ($export_offers_result['articlelist'] as $key => $article) { if ($article['mirakl_export_offers_result']['returncode'] == 12) { switch ($article['mirakl_export_offers_result']['message']) { case $this->mirakl_error_text_product_missing: - $create_products_list[] = $article; + $export_products_list[] = $article; break; } } } - if (empty($create_products_list)) { + if (empty($export_products_list)) { return(array('status' => false, 'message' => "Produktimport nicht möglich")); } - $create_products_result = $this->mirakl_create_products($create_products_list); + $export_products_result = $this->mirakl_export_products($export_products_list); - if ($create_products_result['returncode'] != 0) { - $this->Log(Logger::DEBUG, "Produktimport in Mirakl hat Fehler", $create_products_result); + if ($export_products_result['returncode'] != 0) { + $this->Log(Logger::DEBUG, "Produktimport in Mirakl hat Fehler", $export_products_result); return(array('status' => false, 'message' => "Produktimport in Mirakl hat Fehler")); } // Retry offer import - $offer_export_result = $this->mirakl_export_offers($articlelist); - if ($offer_export_result['returncode'] == 0) { + $export_offers_result = $this->mirakl_export_offers($articlelist); + if ($export_offers_result['returncode'] == 0) { return(array('status' => true, 'message' => "Angebots und Produktimport in Mirakl ok")); } } - $this->Log(Logger::DEBUG, "Angebotsimport in Mirakl hat Fehler", $offer_export_result); + $this->Log(Logger::DEBUG, "Angebotsimport in Mirakl hat Fehler", $export_offers_result); return(array('status' => false, 'message' => "Angebotsimport in Mirakl hat Fehler")); */ @@ -592,8 +599,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $mirakl_export_offers_return_value = array(); $mirakl_export_offers_return_value['returncode'] = 0; - $mirakl_export_offers_return_value['articlelist'] = array(); - + $this->Log(Logger::DEBUG, 'Angebotsexport Start', $articlelist); // First gather all articles as offers and send them @@ -602,6 +608,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { foreach ($articlelist as $key => $article) { + $return_article = + array( + 'artikel' => $article['artikel'], + 'nummer' => $article['nummer'] + ); + $skip_article = false; /* @@ -615,11 +627,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); - $configuration_identifier = $this->GetFieldValue($article, $this->configuration_identifier); + $offer_configuration_name = $this->GetFieldValue($article, $this->configuration_identifier); + $return_article['offer_configuration'] = $offer_configuration_name; foreach ($this->offer_configuration as $offer_configuration_entry) { if ($offer_configuration_entry['konfigurationen'] != null) { - if (!in_array($configuration_identifier,$offer_configuration_entry['konfigurationen'])) { + if (!in_array($offer_configuration_name,$offer_configuration_entry['konfigurationen'])) { continue; } } @@ -644,8 +657,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if ($missing) { $mirakl_export_offers_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 10, 'message' => "Pflichtfelder fehlen in Angebotskonfiguration \"".$configuration['konfiguration']."\": ".implode(', ',$missing)); - $mirakl_export_offers_return_value['articlelist'][] = $article; + $return_article['export_offers_returncode'] = 10; + $return_article['export_offers_message'] = "Pflichtfelder fehlen in Angebotskonfiguration \"".$offer_configuration_name."\": ".implode(', ',$missing); + $mirakl_export_offers_return_value['articlelist'][] = $return_article; $skip_article = true; } // Check Required attributes @@ -681,13 +695,14 @@ class Shopimporter_Mirakl extends ShopimporterBase { $offers_for_mirakl[] = $offer_for_mirakl; - $article['mirakl_export_offers_result'] = array('returncode' => 0, 'message' => ""); - $mirakl_export_offers_return_value['articlelist'][] = $article; + $return_article['export_offers_returncode'] = 0; + $mirakl_export_offers_return_value['articlelist'][] = $return_article; } else { // configuration_found $mirakl_export_offers_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Angebotskonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); - $mirakl_export_offers_return_value['articlelist'][] = $article; + $return_article['export_offers_returncode'] = 11; + $return_article['export_offers_message'] = "Angebotskonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$offer_configuration_name."\" nicht gefunden"; + $mirakl_export_offers_return_value['articlelist'][] = $return_article; continue; } } @@ -788,56 +803,115 @@ class Shopimporter_Mirakl extends ShopimporterBase { /* * Create products * Return - * array (returncode, message, articlelist) articlelist with added mirakl_export_offers_result element (array (returncode, message)) for further processing (e.g. create product) + * array (returncode, message, articlelist) articlelist with added mirakl_export_offers_result element (array (returncode, message)) for further processing * returncode 0 = ok, 1 = not ok - * returncode articlelist 0 = ok, 20 rejected from mirakl + * returncode articlelist 0 = ok */ - private function mirakl_create_products(array $articlelist) : array { + private function mirakl_export_products(array $articlelist) : array { - $mirakl_create_products_return_value = array(); - $mirakl_create_products_return_value['returncode'] = 0; - $mirakl_create_products_return_value['articlelist'] = $articlelist; + $mirakl_export_products_return_value = array(); + $mirakl_export_products_return_value['export_products_returncode'] = 0; - $number_of_articles = 0; - $this->Log(Logger::DEBUG, 'Produktexport Start', $articlelist); + + $articlelist_per_configuration = array(); + + foreach ($articlelist as $key => $article) { - // Build CSV - $csv_header = ""; - $newline = ""; - foreach ($articlelist as $article) { - $product_for_mirakl = array(); - - // Determine configuration + // Determine configuration $configuration_found = false; - $konfiguration = $this->GetFieldValue($article, $this->configuration_identifier); + $product_configuration_name = $this->GetFieldValue($article, $this->configuration_identifier); - foreach ($this->product_configuration as $product_configuration) { + $mirakl_export_products_return_value['articlelist'][] = + array( + 'artikel' => $article['artikel'], + 'nummer' => $article['nummer'], + 'product_configuration' => $product_configuration_name + ); + + foreach ($this->product_configuration as $product_configuration_id => $product_configuration) { if ($product_configuration['konfigurationen'] != null) { - if (!in_array($konfiguration,$product_configuration['konfigurationen'])) { + if (!in_array($product_configuration_name,$product_configuration['konfigurationen'])) { continue; } } $configuration_found = true; + break; } if (!$configuration_found) { - $mirakl_create_products_return_value['returncode'] = 1; - $article['mirakl_export_offers_result'] = array('returncode' => 11, 'message' => "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$konfiguration."\" nicht gefunden"); - $mirakl_create_products_return_value['articlelist'][] = $article; + $mirakl_export_products_return_value['export_products_returncode'] = 1; + $article['product_export_result']['export_products_returncode'] = 11; + $article['product_export_result']['export_products_message'] = "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$product_configuration_name."\" nicht gefunden"; + $mirakl_export_products_return_value['articlelist'][] = $article; continue; } - - foreach ($this->product_configuration as $product_field_entry) { - foreach ($product_field_entry['felder'] as $product_field => $product_field_source) { - if (!is_array($product_field_source)) { - $product_field_source = array('feld' => $product_field_source); - } - $product_field_value = null; - $product_field_value = $this->GetFieldValue($article, $product_field_source); - $product_for_mirakl[$product_field] = $product_field_value; - } - } + + $articlelist_per_configuration[$product_configuration_name]['product_configuration'] = $product_configuration; + $articlelist_per_configuration[$product_configuration_name]['product_configuration_name'] = $product_configuration_name; + $articlelist_per_configuration[$product_configuration_name]['articles'][] = $article; + } + +// $this->Log(Logger::DEBUG, 'Articlelist per config', $articlelist_per_configuration); + + $komma = ''; + + foreach ($articlelist_per_configuration as $articlelist_one_configuration) { + $result = $this->mirakl_export_products_one_configuration($articlelist_one_configuration); + +// $this->Log(Logger::DEBUG, 'Articlelist per config result', $result); + + if ($result['export_products_returncode']) { + $mirakl_export_products_return_value['export_products_returncode'] = 1; + $mirakl_export_products_return_value['message'] .= $komma.$result['message']." (".$articlelist_one_configuration['product_configuration_name'].")"; + $komma = ', '; + } + + foreach ($result['articlelist'] as $article_result) { + $article_key = array_search( + $article_result['artikel'], + array_column( + $mirakl_export_products_return_value['articlelist'], + 'artikel') + ); + + $mirakl_export_products_return_value['articlelist'][$article_key] += $article_result; + } + + // $this->Log(Logger::DEBUG, 'mirakl_export_products_return_value', $mirakl_export_products_return_value); + + } + + return($mirakl_export_products_return_value); + } + + private function mirakl_export_products_one_configuration (array $articlelist_one_configuration) { + + // Build CSV + $csv_header = ""; + $newline = ""; + + $mirakl_export_products_return_value = array(); + + foreach ($articlelist_one_configuration['articles'] as $article) { + $product_for_mirakl = array(); + + $mirakl_export_products_return_value['articlelist'][] = + array( + 'artikel' => $article['artikel'], + 'nummer' => $article['nummer'], + 'product_configuration' => $product_configuration_name, + 'export_products_returncode' => 0 + ); + + foreach ($articlelist_one_configuration['product_configuration']['felder'] as $product_field => $product_field_source) { + if (!is_array($product_field_source)) { + $product_field_source = array('feld' => $product_field_source); + } + $product_field_value = null; + $product_field_value = $this->GetFieldValue($article, $product_field_source); + $product_for_mirakl[$product_field] = $product_field_value; + } // Create CSV from array if (empty($csv_header)) { @@ -848,14 +922,14 @@ class Shopimporter_Mirakl extends ShopimporterBase { } if (!$csv) { // No articles found - return($mirakl_create_products_return_value); + return($mirakl_export_products_return_value); } $csv = $csv_header.$newline.$csv; $result = []; - $this->Log(Logger::DEBUG, 'Produktexport Daten', array('csv' => $csv)); + $this->Log(Logger::DEBUG, 'Produktexport Daten '.$articlelist_one_configuration['product_configuration_name'], array('csv' => $csv)); $postdata = array('file' => new CURLStringFile(postname: 'import.csv', data: $csv)); @@ -865,8 +939,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!isset($result->import_id)) { $this->Log(Logger::ERROR, 'Produktimport abgelehnt', $response); - $mirakl_create_products_return_value['returncode'] = 1; - return($mirakl_create_products_return_value); + $mirakl_export_products_return_value['export_products_returncode'] = 1; + $mirakl_export_products_return_value['export_products_message'] = 'Produktimport abgelehnt'; + return($mirakl_export_products_return_value); } $this->Log(Logger::INFO, 'Produktimport angelegt', $result); @@ -890,15 +965,15 @@ class Shopimporter_Mirakl extends ShopimporterBase { if ($status == 'FAILED') { $this->Log(Logger::ERROR, 'Produktimport fehlgeschlagen', $response); - $mirakl_create_products_return_value['returncode'] = 1; - return($mirakl_create_products_return_value); + $mirakl_export_products_return_value['export_products_returncode'] = 1; + return($mirakl_export_products_return_value); } if (!$result->has_error_report && !$result->has_transformation_error_report) { $this->Log(Logger::INFO, 'Produktimport ok', $response); } else { $this->Log(Logger::ERROR, 'Produktimport meldet Fehler', $response); - $mirakl_create_products_return_value['returncode'] = 1; + $mirakl_export_products_return_value['export_products_returncode'] = 1; } if ($result->has_new_product_report) { @@ -909,8 +984,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { if ($result->has_transformed_file) { $response = $this->miraklRequest('products/imports/'.$import_id.'/transformed_file', raw: true); $this->Log(Logger::DEBUG, 'Produktimport Datei im Marketplace-Format', $response); - } - + } + if ($result->has_error_report) { // Check errors with CSV unfucking... $response = $this->miraklRequest('products/imports/'.$import_id.'/error_report', raw: true); @@ -927,11 +1002,12 @@ class Shopimporter_Mirakl extends ShopimporterBase { $article_key = array_search( $response_array['product_id'], array_column( - $mirakl_create_products_return_value['articlelist'], + $mirakl_export_products_return_value['articlelist'], 'product_id') ); - $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 13, 'message' => $response_array[$error_message_key]); + $mirakl_export_products_return_value['articlelist'][$article_key]['export_products_returncode'] = 13; + $mirakl_export_products_return_value['articlelist'][$article_key]['export_products_message'] = $response_array[$error_message_key]; } $this->Log(Logger::ERROR, 'Produktimport Fehlerbericht', $response); } @@ -952,22 +1028,22 @@ class Shopimporter_Mirakl extends ShopimporterBase { $article_key = array_search( $response_array['product_id'], array_column( - $mirakl_create_products_return_value['articlelist'], + $mirakl_export_products_return_value['articlelist'], 'product_id') ); - - $mirakl_create_products_return_value['articlelist'][$article_key]['mirakl_create_products_result'] = array('returncode' => 14, 'message' => $response_array[$error_message_key]); + + $mirakl_export_products_return_value['articlelist'][$article_key]['export_products_returncode'] = 14; + $mirakl_export_products_return_value['articlelist'][$article_key]['export_products_message'] = $response_array[$error_message_key]; } $this->Log(Logger::ERROR, 'Produktimport Transformation-Fehlerbericht', $response); } - return($mirakl_create_products_return_value); + return($mirakl_export_products_return_value); + } private function Log($level, $message, $dump = array()) { - if ($this->protocol) { - $this->logger->Log($level, 'Mirakl (Shop '.$this->shopid.') '.$message, (array) $dump); - } + $this->logger->Log($level, 'Mirakl (Shop '.$this->shopid.') '.$message, (array) $dump); } private function getOrdersToProcess(int $limit) { From 4337a6503cc3ceb1b2f474a90779c09d0d22717c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 2 Jul 2024 10:33:35 +0200 Subject: [PATCH 37/52] class.remote.php send articles before stock (lagersync) --- www/lib/class.remote.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 1c9c4be1..33278a10 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1934,12 +1934,12 @@ class Remote { // Bulk transfer (new 2024-06-28) $result = null; - if (!empty($lagerexport)) { - $result = $this->sendlistlager($id, $data); - } if (!empty($artikelexport) && !$nurlager) { $result = $this->sendlist($id, $data, true); } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($id, $data); + } return $result; } @@ -2060,12 +2060,12 @@ class Remote { // Bulk transfer (new 2024-06-28) $result = null; - if (!empty($lagerexport)) { - $result = $this->sendlistlager($id, $data); - } if (!empty($artikelexport) && !$nurlager) { $result = $this->sendlist($id, $data, true); } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($id, $data); + } return $result; } From 4ed783a7ca34bc6751fcc8777bfa04e6f9fda37d Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 2 Jul 2024 11:10:49 +0200 Subject: [PATCH 38/52] mirakl logging bugfix --- www/pages/shopimporter_mirakl.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 832c538a..c039e745 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -841,9 +841,8 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!$configuration_found) { $mirakl_export_products_return_value['export_products_returncode'] = 1; - $article['product_export_result']['export_products_returncode'] = 11; - $article['product_export_result']['export_products_message'] = "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$product_configuration_name."\" nicht gefunden"; - $mirakl_export_products_return_value['articlelist'][] = $article; + $mirakl_export_products_return_value['articlelist'][$key]['export_products_returncode'] = 11; + $mirakl_export_products_return_value['articlelist'][$key]['export_products_message'] = "Produktkonfiguration für Artikel ".$article['nummer'].", Konfiguration \"".$product_configuration_name."\" nicht gefunden"; continue; } From ea515b0727ecb5c7f9adc5e458391a59ae459cd0 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 2 Jul 2024 13:54:50 +0200 Subject: [PATCH 39/52] cronjobs/shop_rueckmeldungen.php format --- cronjobs/shop_rueckmeldungen.php | 777 +++++++++++++++---------------- 1 file changed, 387 insertions(+), 390 deletions(-) diff --git a/cronjobs/shop_rueckmeldungen.php b/cronjobs/shop_rueckmeldungen.php index cd69234e..f840102c 100644 --- a/cronjobs/shop_rueckmeldungen.php +++ b/cronjobs/shop_rueckmeldungen.php @@ -1,393 +1,389 @@ 0) { - $aes = '2'; +$phpversion = (String) phpversion(); +if ($phpversion[0] == '7' && (int) $phpversion[2] > 0) { + $aes = '2'; } -if($aes == 2 && is_file(dirname(__DIR__).'/www/lib/class.aes2.php')) { - include_once dirname(__DIR__).'/www/lib/class.aes2.php'; -} -else{ - include_once dirname(__DIR__) . '/www/lib/class.aes.php'; +if ($aes == 2 && is_file(dirname(__DIR__) . '/www/lib/class.aes2.php')) { + include_once dirname(__DIR__) . '/www/lib/class.aes2.php'; +} else { + include_once dirname(__DIR__) . '/www/lib/class.aes.php'; } -$classes = array('briefpapier','lieferschein','auftrag','anfrage','gutschrift','bestellung','rechnung','mahnwesen'); -foreach($classes as $class) -{ - if(file_exists(dirname(__DIR__).'/www/lib/dokumente/class.'.$class.'_custom.php')) - { - include_once dirname(__DIR__).'/www/lib/dokumente/class.'.$class.'_custom.php'; - } - elseif(file_exists(dirname(__DIR__).'/www/lib/dokumente/class.'.$class.'.php')) { - include_once dirname(__DIR__).'/www/lib/dokumente/class.'.$class.'.php'; - } +$classes = array('briefpapier', 'lieferschein', 'auftrag', 'anfrage', 'gutschrift', 'bestellung', 'rechnung', 'mahnwesen'); +foreach ($classes as $class) { + if (file_exists(dirname(__DIR__) . '/www/lib/dokumente/class.' . $class . '_custom.php')) { + include_once dirname(__DIR__) . '/www/lib/dokumente/class.' . $class . '_custom.php'; + } elseif (file_exists(dirname(__DIR__) . '/www/lib/dokumente/class.' . $class . '.php')) { + include_once dirname(__DIR__) . '/www/lib/dokumente/class.' . $class . '.php'; + } } /* -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.briefpapier.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.lieferschein.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.auftrag.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.angebot.php"); -if(file_exists(dirname(__FILE__)."/../www/lib/dokumente/class.anfrage.php"))include_once(dirname(__FILE__)."/../www/lib/dokumente/class.anfrage.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.gutschrift.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.bestellung.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.rechnung.php"); -include_once(dirname(__FILE__)."/../www/lib/dokumente/class.mahnwesen.php");*/ -include_once dirname(__DIR__).'/phpwf/plugins/class.string.php'; -if(!class_exists('app_t2')) -{ - class app_t2 extends ApplicationCore { - var $DB; - var $erp; - var $User; - var $mail; - var $remote; - var $Secure; -function GetLandLang($isocode) -{ - $flipped = array_flip($this->GetLaender()); - if(isset($flipped[$isocode])) - $land = $flipped[$isocode]; - else { - $land = 'unkown'; - } - return $land; -} + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.briefpapier.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.lieferschein.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.auftrag.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.angebot.php"); + if(file_exists(dirname(__FILE__)."/../www/lib/dokumente/class.anfrage.php"))include_once(dirname(__FILE__)."/../www/lib/dokumente/class.anfrage.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.gutschrift.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.bestellung.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.rechnung.php"); + include_once(dirname(__FILE__)."/../www/lib/dokumente/class.mahnwesen.php"); */ +include_once dirname(__DIR__) . '/phpwf/plugins/class.string.php'; +if (!class_exists('app_t2')) { + + class app_t2 extends ApplicationCore { + + var $DB; + var $erp; + var $User; + var $mail; + var $remote; + var $Secure; + + function GetLandLang($isocode) { + $flipped = array_flip($this->GetLaender()); + if (isset($flipped[$isocode])) + $land = $flipped[$isocode]; + else { + $land = 'unkown'; + } + return $land; + } + + function GetLaender() { + $laender = array( + 'Afghanistan' => 'AF', + 'Ägypten' => 'EG', + 'Albanien' => 'AL', + 'Algerien' => 'DZ', + 'Andorra' => 'AD', + 'Angola' => 'AO', + 'Anguilla' => 'AI', + 'Antarktis' => 'AQ', + 'Antigua und Barbuda' => 'AG', + 'Äquatorial Guinea' => 'GQ', + 'Argentinien' => 'AR', + 'Armenien' => 'AM', + 'Aruba' => 'AW', + 'Aserbaidschan' => 'AZ', + 'Äthiopien' => 'ET', + 'Australien' => 'AU', + 'Bahamas' => 'BS', + 'Bahrain' => 'BH', + 'Bangladesh' => 'BD', + 'Barbados' => 'BB', + 'Belgien' => 'BE', + 'Belize' => 'BZ', + 'Benin' => 'BJ', + 'Bermudas' => 'BM', + 'Bhutan' => 'BT', + 'Birma' => 'MM', + 'Bolivien' => 'BO', + 'Bosnien-Herzegowina' => 'BA', + 'Botswana' => 'BW', + 'Bouvet Inseln' => 'BV', + 'Brasilien' => 'BR', + 'Britisch-Indischer Ozean' => 'IO', + 'Brunei' => 'BN', + 'Bulgarien' => 'BG', + 'Burkina Faso' => 'BF', + 'Burundi' => 'BI', + 'Chile' => 'CL', + 'China' => 'CN', + 'Christmas Island' => 'CX', + 'Cook Inseln' => 'CK', + 'Costa Rica' => 'CR', + 'Dänemark' => 'DK', + 'Deutschland' => 'DE', + 'Djibuti' => 'DJ', + 'Dominika' => 'DM', + 'Dominikanische Republik' => 'DO', + 'Ecuador' => 'EC', + 'El Salvador' => 'SV', + 'Elfenbeinküste' => 'CI', + 'Eritrea' => 'ER', + 'Estland' => 'EE', + 'Falkland Inseln' => 'FK', + 'Färöer Inseln' => 'FO', + 'Fidschi' => 'FJ', + 'Finnland' => 'FI', + 'Frankreich' => 'FR', + 'Französisch Guyana' => 'GF', + 'Französisch Polynesien' => 'PF', + 'Französisches Süd-Territorium' => 'TF', + 'Gabun' => 'GA', + 'Gambia' => 'GM', + 'Georgien' => 'GE', + 'Ghana' => 'GH', + 'Gibraltar' => 'GI', + 'Grenada' => 'GD', + 'Griechenland' => 'GR', + 'Grönland' => 'GL', + 'Großbritannien' => 'UK', + 'Großbritannien (UK)' => 'GB', + 'Guadeloupe' => 'GP', + 'Guam' => 'GU', + 'Guatemala' => 'GT', + 'Guinea' => 'GN', + 'Guinea Bissau' => 'GW', + 'Guyana' => 'GY', + 'Haiti' => 'HT', + 'Heard und McDonald Islands' => 'HM', + 'Honduras' => 'HN', + 'Hong Kong' => 'HK', + 'Indien' => 'IN', + 'Indonesien' => 'ID', + 'Irak' => 'IQ', + 'Iran' => 'IR', + 'Irland' => 'IE', + 'Island' => 'IS', + 'Israel' => 'IL', + 'Italien' => 'IT', + 'Jamaika' => 'JM', + 'Japan' => 'JP', + 'Jemen' => 'YE', + 'Jordanien' => 'JO', + 'Jugoslawien' => 'YU', + 'Kaiman Inseln' => 'KY', + 'Kambodscha' => 'KH', + 'Kamerun' => 'CM', + 'Kanada' => 'CA', + 'Kap Verde' => 'CV', + 'Kasachstan' => 'KZ', + 'Kenia' => 'KE', + 'Kirgisistan' => 'KG', + 'Kiribati' => 'KI', + 'Kokosinseln' => 'CC', + 'Kolumbien' => 'CO', + 'Komoren' => 'KM', + 'Kongo' => 'CG', + 'Kongo, Demokratische Republik' => 'CD', + 'Kosovo' => 'KO', + 'Kroatien' => 'HR', + 'Kuba' => 'CU', + 'Kuwait' => 'KW', + 'Laos' => 'LA', + 'Lesotho' => 'LS', + 'Lettland' => 'LV', + 'Libanon' => 'LB', + 'Liberia' => 'LR', + 'Libyen' => 'LY', + 'Liechtenstein' => 'LI', + 'Litauen' => 'LT', + 'Luxemburg' => 'LU', + 'Macao' => 'MO', + 'Madagaskar' => 'MG', + 'Malawi' => 'MW', + 'Malaysia' => 'MY', + 'Malediven' => 'MV', + 'Mali' => 'ML', + 'Malta' => 'MT', + 'Marianen' => 'MP', + 'Marokko' => 'MA', + 'Marshall Inseln' => 'MH', + 'Martinique' => 'MQ', + 'Mauretanien' => 'MR', + 'Mauritius' => 'MU', + 'Mayotte' => 'YT', + 'Mazedonien' => 'MK', + 'Mexiko' => 'MX', + 'Mikronesien' => 'FM', + 'Mocambique' => 'MZ', + 'Moldavien' => 'MD', + 'Monaco' => 'MC', + 'Mongolei' => 'MN', + 'Montenegro' => 'ME', + 'Montserrat' => 'MS', + 'Namibia' => 'NA', + 'Nauru' => 'NR', + 'Nepal' => 'NP', + 'Neukaledonien' => 'NC', + 'Neuseeland' => 'NZ', + 'Nicaragua' => 'NI', + 'Niederlande' => 'NL', + 'Niederländische Antillen' => 'AN', + 'Niger' => 'NE', + 'Nigeria' => 'NG', + 'Niue' => 'NU', + 'Nord Korea' => 'KP', + 'Norfolk Inseln' => 'NF', + 'Norwegen' => 'NO', + 'Oman' => 'OM', + 'Österreich' => 'AT', + 'Pakistan' => 'PK', + 'Palästina' => 'PS', + 'Palau' => 'PW', + 'Panama' => 'PA', + 'Papua Neuguinea' => 'PG', + 'Paraguay' => 'PY', + 'Peru' => 'PE', + 'Philippinen' => 'PH', + 'Pitcairn' => 'PN', + 'Polen' => 'PL', + 'Portugal' => 'PT', + 'Puerto Rico' => 'PR', + 'Qatar' => 'QA', + 'Reunion' => 'RE', + 'Ruanda' => 'RW', + 'Rumänien' => 'RO', + 'Rußland' => 'RU', + 'Saint Lucia' => 'LC', + 'Sambia' => 'ZM', + 'Samoa' => 'AS', + 'Samoa' => 'WS', + 'San Marino' => 'SM', + 'Sao Tome' => 'ST', + 'Saudi Arabien' => 'SA', + 'Schweden' => 'SE', + 'Schweiz' => 'CH', + 'Senegal' => 'SN', + 'Serbien' => 'RS', + 'Seychellen' => 'SC', + 'Sierra Leone' => 'SL', + 'Singapur' => 'SG', + 'Slowakei -slowakische Republik-' => 'SK', + 'Slowenien' => 'SI', + 'Solomon Inseln' => 'SB', + 'Somalia' => 'SO', + 'South Georgia, South Sandwich Isl.' => 'GS', + 'Spanien' => 'ES', + 'Sri Lanka' => 'LK', + 'St. Helena' => 'SH', + 'St. Kitts Nevis Anguilla' => 'KN', + 'St. Pierre und Miquelon' => 'PM', + 'St. Vincent' => 'VC', + 'Süd Korea' => 'KR', + 'Südafrika' => 'ZA', + 'Sudan' => 'SD', + 'Surinam' => 'SR', + 'Svalbard und Jan Mayen Islands' => 'SJ', + 'Swasiland' => 'SZ', + 'Syrien' => 'SY', + 'Tadschikistan' => 'TJ', + 'Taiwan' => 'TW', + 'Tansania' => 'TZ', + 'Thailand' => 'TH', + 'Timor' => 'TP', + 'Togo' => 'TG', + 'Tokelau' => 'TK', + 'Tonga' => 'TO', + 'Trinidad Tobago' => 'TT', + 'Tschad' => 'TD', + 'Tschechische Republik' => 'CZ', + 'Tunesien' => 'TN', + 'Türkei' => 'TR', + 'Turkmenistan' => 'TM', + 'Turks und Kaikos Inseln' => 'TC', + 'Tuvalu' => 'TV', + 'Uganda' => 'UG', + 'Ukraine' => 'UA', + 'Ungarn' => 'HU', + 'Uruguay' => 'UY', + 'Usbekistan' => 'UZ', + 'Vanuatu' => 'VU', + 'Vatikan' => 'VA', + 'Venezuela' => 'VE', + 'Vereinigte Arabische Emirate' => 'AE', + 'Vereinigte Staaten von Amerika' => 'US', + 'Vietnam' => 'VN', + 'Virgin Island (Brit.)' => 'VG', + 'Virgin Island (USA)' => 'VI', + 'Wallis et Futuna' => 'WF', + 'Weißrußland' => 'BY', + 'Westsahara' => 'EH', + 'Zentralafrikanische Republik' => 'CF', + 'Zimbabwe' => 'ZW', + 'Zypern' => 'CY' + ); + return $laender; + } + } -function GetLaender() -{ - $laender = array( - 'Afghanistan' => 'AF', - 'Ägypten' => 'EG', - 'Albanien' => 'AL', - 'Algerien' => 'DZ', - 'Andorra' => 'AD', - 'Angola' => 'AO', - 'Anguilla' => 'AI', - 'Antarktis' => 'AQ', - 'Antigua und Barbuda' => 'AG', - 'Äquatorial Guinea' => 'GQ', - 'Argentinien' => 'AR', - 'Armenien' => 'AM', - 'Aruba' => 'AW', - 'Aserbaidschan' => 'AZ', - 'Äthiopien' => 'ET', - 'Australien' => 'AU', - 'Bahamas' => 'BS', - 'Bahrain' => 'BH', - 'Bangladesh' => 'BD', - 'Barbados' => 'BB', - 'Belgien' => 'BE', - 'Belize' => 'BZ', - 'Benin' => 'BJ', - 'Bermudas' => 'BM', - 'Bhutan' => 'BT', - 'Birma' => 'MM', - 'Bolivien' => 'BO', - 'Bosnien-Herzegowina' => 'BA', - 'Botswana' => 'BW', - 'Bouvet Inseln' => 'BV', - 'Brasilien' => 'BR', - 'Britisch-Indischer Ozean' => 'IO', - 'Brunei' => 'BN', - 'Bulgarien' => 'BG', - 'Burkina Faso' => 'BF', - 'Burundi' => 'BI', - 'Chile' => 'CL', - 'China' => 'CN', - 'Christmas Island' => 'CX', - 'Cook Inseln' => 'CK', - 'Costa Rica' => 'CR', - 'Dänemark' => 'DK', - 'Deutschland' => 'DE', - 'Djibuti' => 'DJ', - 'Dominika' => 'DM', - 'Dominikanische Republik' => 'DO', - 'Ecuador' => 'EC', - 'El Salvador' => 'SV', - 'Elfenbeinküste' => 'CI', - 'Eritrea' => 'ER', - 'Estland' => 'EE', - 'Falkland Inseln' => 'FK', - 'Färöer Inseln' => 'FO', - 'Fidschi' => 'FJ', - 'Finnland' => 'FI', - 'Frankreich' => 'FR', - 'Französisch Guyana' => 'GF', - 'Französisch Polynesien' => 'PF', - 'Französisches Süd-Territorium' => 'TF', - 'Gabun' => 'GA', - 'Gambia' => 'GM', - 'Georgien' => 'GE', - 'Ghana' => 'GH', - 'Gibraltar' => 'GI', - 'Grenada' => 'GD', - 'Griechenland' => 'GR', - 'Grönland' => 'GL', - 'Großbritannien' => 'UK', - 'Großbritannien (UK)' => 'GB', - 'Guadeloupe' => 'GP', - 'Guam' => 'GU', - 'Guatemala' => 'GT', - 'Guinea' => 'GN', - 'Guinea Bissau' => 'GW', - 'Guyana' => 'GY', - 'Haiti' => 'HT', - 'Heard und McDonald Islands' => 'HM', - 'Honduras' => 'HN', - 'Hong Kong' => 'HK', - 'Indien' => 'IN', - 'Indonesien' => 'ID', - 'Irak' => 'IQ', - 'Iran' => 'IR', - 'Irland' => 'IE', - 'Island' => 'IS', - 'Israel' => 'IL', - 'Italien' => 'IT', - 'Jamaika' => 'JM', - 'Japan' => 'JP', - 'Jemen' => 'YE', - 'Jordanien' => 'JO', - 'Jugoslawien' => 'YU', - 'Kaiman Inseln' => 'KY', - 'Kambodscha' => 'KH', - 'Kamerun' => 'CM', - 'Kanada' => 'CA', - 'Kap Verde' => 'CV', - 'Kasachstan' => 'KZ', - 'Kenia' => 'KE', - 'Kirgisistan' => 'KG', - 'Kiribati' => 'KI', - 'Kokosinseln' => 'CC', - 'Kolumbien' => 'CO', - 'Komoren' => 'KM', - 'Kongo' => 'CG', - 'Kongo, Demokratische Republik' => 'CD', - 'Kosovo' => 'KO', - 'Kroatien' => 'HR', - 'Kuba' => 'CU', - 'Kuwait' => 'KW', - 'Laos' => 'LA', - 'Lesotho' => 'LS', - 'Lettland' => 'LV', - 'Libanon' => 'LB', - 'Liberia' => 'LR', - 'Libyen' => 'LY', - 'Liechtenstein' => 'LI', - 'Litauen' => 'LT', - 'Luxemburg' => 'LU', - 'Macao' => 'MO', - 'Madagaskar' => 'MG', - 'Malawi' => 'MW', - 'Malaysia' => 'MY', - 'Malediven' => 'MV', - 'Mali' => 'ML', - 'Malta' => 'MT', - 'Marianen' => 'MP', - 'Marokko' => 'MA', - 'Marshall Inseln' => 'MH', - 'Martinique' => 'MQ', - 'Mauretanien' => 'MR', - 'Mauritius' => 'MU', - 'Mayotte' => 'YT', - 'Mazedonien' => 'MK', - 'Mexiko' => 'MX', - 'Mikronesien' => 'FM', - 'Mocambique' => 'MZ', - 'Moldavien' => 'MD', - 'Monaco' => 'MC', - 'Mongolei' => 'MN', - 'Montenegro' => 'ME', - 'Montserrat' => 'MS', - 'Namibia' => 'NA', - 'Nauru' => 'NR', - 'Nepal' => 'NP', - 'Neukaledonien' => 'NC', - 'Neuseeland' => 'NZ', - 'Nicaragua' => 'NI', - 'Niederlande' => 'NL', - 'Niederländische Antillen' => 'AN', - 'Niger' => 'NE', - 'Nigeria' => 'NG', - 'Niue' => 'NU', - 'Nord Korea' => 'KP', - 'Norfolk Inseln' => 'NF', - 'Norwegen' => 'NO', - 'Oman' => 'OM', - 'Österreich' => 'AT', - 'Pakistan' => 'PK', - 'Palästina' => 'PS', - 'Palau' => 'PW', - 'Panama' => 'PA', - 'Papua Neuguinea' => 'PG', - 'Paraguay' => 'PY', - 'Peru' => 'PE', - 'Philippinen' => 'PH', - 'Pitcairn' => 'PN', - 'Polen' => 'PL', - 'Portugal' => 'PT', - 'Puerto Rico' => 'PR', - 'Qatar' => 'QA', - 'Reunion' => 'RE', - 'Ruanda' => 'RW', - 'Rumänien' => 'RO', - 'Rußland' => 'RU', - 'Saint Lucia' => 'LC', - 'Sambia' => 'ZM', - 'Samoa' => 'AS', - 'Samoa' => 'WS', - 'San Marino' => 'SM', - 'Sao Tome' => 'ST', - 'Saudi Arabien' => 'SA', - 'Schweden' => 'SE', - 'Schweiz' => 'CH', - 'Senegal' => 'SN', - 'Serbien' => 'RS', - 'Seychellen' => 'SC', - 'Sierra Leone' => 'SL', - 'Singapur' => 'SG', - 'Slowakei -slowakische Republik-' => 'SK', - 'Slowenien' => 'SI', - 'Solomon Inseln' => 'SB', - 'Somalia' => 'SO', - 'South Georgia, South Sandwich Isl.' => 'GS', - 'Spanien' => 'ES', - 'Sri Lanka' => 'LK', - 'St. Helena' => 'SH', - 'St. Kitts Nevis Anguilla' => 'KN', - 'St. Pierre und Miquelon' => 'PM', - 'St. Vincent' => 'VC', - 'Süd Korea' => 'KR', - 'Südafrika' => 'ZA', - 'Sudan' => 'SD', - 'Surinam' => 'SR', - 'Svalbard und Jan Mayen Islands' => 'SJ', - 'Swasiland' => 'SZ', - 'Syrien' => 'SY', - 'Tadschikistan' => 'TJ', - 'Taiwan' => 'TW', - 'Tansania' => 'TZ', - 'Thailand' => 'TH', - 'Timor' => 'TP', - 'Togo' => 'TG', - 'Tokelau' => 'TK', - 'Tonga' => 'TO', - 'Trinidad Tobago' => 'TT', - 'Tschad' => 'TD', - 'Tschechische Republik' => 'CZ', - 'Tunesien' => 'TN', - 'Türkei' => 'TR', - 'Turkmenistan' => 'TM', - 'Turks und Kaikos Inseln' => 'TC', - 'Tuvalu' => 'TV', - 'Uganda' => 'UG', - 'Ukraine' => 'UA', - 'Ungarn' => 'HU', - 'Uruguay' => 'UY', - 'Usbekistan' => 'UZ', - 'Vanuatu' => 'VU', - 'Vatikan' => 'VA', - 'Venezuela' => 'VE', - 'Vereinigte Arabische Emirate' => 'AE', - 'Vereinigte Staaten von Amerika' => 'US', - 'Vietnam' => 'VN', - 'Virgin Island (Brit.)' => 'VG', - 'Virgin Island (USA)' => 'VI', - 'Wallis et Futuna' => 'WF', - 'Weißrußland' => 'BY', - 'Westsahara' => 'EH', - 'Zentralafrikanische Republik' => 'CF', - 'Zimbabwe' => 'ZW', - 'Zypern' => 'CY' - ); - return $laender; -} - } } //ENDE - if(empty($app) || !class_exists('ApplicationCore') || !($app instanceof ApplicationCore)) { +if (empty($app) || !class_exists('ApplicationCore') || !($app instanceof ApplicationCore)) { $app = new app_t2(); - } - if(empty($app->Conf)){ +} +if (empty($app->Conf)) { $conf = new Config(); $app->Conf = $conf; - } - if(empty($app->DB)){ +} +if (empty($app->DB)) { $app->DB = new DB($app->Conf->WFdbhost, $app->Conf->WFdbname, $app->Conf->WFdbuser, $app->Conf->WFdbpass, null, $app->Conf->WFdbport); - } - if(empty($app->erp)){ +} +if (empty($app->erp)) { $erp = new erpAPI($app); $app->erp = $erp; - } - $app->String = new WawiString(); - if(empty($app->remote)){ - if(is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')){ - require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; - $app->remote = new RemoteCustom($app); +} +$app->String = new WawiString(); +if (empty($app->remote)) { + if (is_file(dirname(__DIR__) . '/www/lib/class.remote_custom.php')) { + require_once dirname(__DIR__) . '/www/lib/class.remote_custom.php'; + $app->remote = new RemoteCustom($app); + } else { + $app->remote = new Remote($app); } - else{ - $app->remote = new Remote($app); - } - } - //$app->remote = new Remote($app); - $app->Secure = new Secure($app); - $app->User = new User($app); - if(!defined('FPDF_FONTPATH')) { - define('FPDF_FONTPATH',dirname(__DIR__).'/www/lib/pdf/font/'); - } - +} +//$app->remote = new Remote($app); +$app->Secure = new Secure($app); +$app->User = new User($app); +if (!defined('FPDF_FONTPATH')) { + define('FPDF_FONTPATH', dirname(__DIR__) . '/www/lib/pdf/font/'); +} //ENDE - const MAXIMUM_NUMBER_OF_TRIES = 10; +const MAXIMUM_NUMBER_OF_TRIES = 10; - $shops = $app->DB->SelectFirstCols( - 'SELECT id FROM shopexport WHERE auftragabgleich = 1 AND aktiv = 1 AND demomodus <> 1 AND sendonlywithtracking = 0' - ); - if(empty($shops)) { +$shops = $app->DB->SelectFirstCols( + 'SELECT id FROM shopexport WHERE auftragabgleich = 1 AND aktiv = 1 AND demomodus <> 1 AND sendonlywithtracking = 0' +); +if (empty($shops)) { return; - } - $app->DB->Update("UPDATE prozessstarter SET mutexcounter = mutexcounter + 1 WHERE mutex = 1 AND (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); - if(!$app->DB->Select("SELECT id FROM prozessstarter WHERE mutex = 0 AND (parameter = 'shop_rueckmeldungen') AND aktiv = 1")) { +} +$app->DB->Update("UPDATE prozessstarter SET mutexcounter = mutexcounter + 1 WHERE mutex = 1 AND (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); +if (!$app->DB->Select("SELECT id FROM prozessstarter WHERE mutex = 0 AND (parameter = 'shop_rueckmeldungen') AND aktiv = 1")) { return; - } - $app->DB->Update("UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); +} +$app->DB->Update("UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); - $subwhere = sprintf(' a.shop IN (%s) ', implode(',', $shops)); - $join = ''; - $where = ''; - $app->erp->RunHook('shop_rueckmeldung', 2, $join, $where); - $sql = "SELECT a.id,apro.zeit, a.shop, l.id as lieferschein, v.id as versandid, l.projekt +$subwhere = sprintf(' a.shop IN (%s) ', implode(',', $shops)); +$join = ''; +$where = ''; +$app->erp->RunHook('shop_rueckmeldung', 2, $join, $where); +$sql = "SELECT a.id,apro.zeit, a.shop, l.id as lieferschein, v.id as versandid, l.projekt FROM auftrag AS a LEFT JOIN lieferschein AS l on l.auftragid = a.id LEFT JOIN auftrag_protokoll AS apro ON a.id = apro.auftrag AND apro.grund LIKE 'Auftrag importiert vom Shop' @@ -403,41 +399,41 @@ function GetLaender() ((pr.kommissionierverfahren = 'lieferschein' OR pr.kommissionierverfahren = 'rechnungsmail') AND isnull(v.id)) ) AND (ISNULL(a.shop_status_update_last_attempt_at) OR a.shop_status_update_last_attempt_at < DATE_SUB(NOW(), INTERVAL 4 HOUR)) - AND a.shop_status_update_attempt <= ".MAXIMUM_NUMBER_OF_TRIES." + AND a.shop_status_update_attempt <= " . MAXIMUM_NUMBER_OF_TRIES . " $where ORDER BY a.id, l.id DESC, v.id DESC "; - $auftraege = $app->DB->SelectArr($sql); - if(!empty($auftraege)) { +$auftraege = $app->DB->SelectArr($sql); +if (!empty($auftraege)) { $app->DB->Update( - "UPDATE prozessstarter + "UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1" ); $auftragid = null; $countRequests = 0; - foreach($auftraege as $auftrag) { - if($auftrag['id'] != $auftragid) { - $countRequests++; - $auftragid = $auftrag['id']; - $app->remote->RemoteUpdateAuftrag($auftrag['shop'], $auftrag['id']); - if($countRequests % 10 === 0) { - $app->DB->Update( - "UPDATE prozessstarter + foreach ($auftraege as $auftrag) { + if ($auftrag['id'] != $auftragid) { + $countRequests++; + $auftragid = $auftrag['id']; + $app->remote->RemoteUpdateAuftrag($auftrag['shop'], $auftrag['id']); + if ($countRequests % 10 === 0) { + $app->DB->Update( + "UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE parameter = 'shop_rueckmeldungen' AND aktiv = 1" - ); + ); + } } - } } unset($auftraege); - } - $app->DB->Update("UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); +} +$app->DB->Update("UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); - //Zahlungsstatus - $query = $app->DB->Query( - "SELECT a.id +//Zahlungsstatus +$query = $app->DB->Query( + "SELECT a.id FROM `auftrag` AS `a` LEFT JOIN `rechnung` AS `r1` ON r1.id = a.rechnungid LEFT JOIN `rechnung` AS `r2` ON r2.auftragid = a.id @@ -448,21 +444,22 @@ function GetLaender() AND (r1.zahlungsstatus = 'bezahlt' OR r2.zahlungsstatus = 'bezahlt') AND DATEDIFF(NOW(), a.datum) <= 28 GROUP BY a.id LIMIT 1000" - ); - if($query) { +); +if ($query) { $countRequests = 0; - while($row = $app->DB->Fetch_Assoc($query)) { - $app->erp->ImportUpdateZahlungsstatus($row['id']); - $countRequests++; - if($countRequests % 10 === 0) { - $app->DB->Update( - "UPDATE prozessstarter + while ($row = $app->DB->Fetch_Assoc($query)) { + $app->erp->ImportUpdateZahlungsstatus($row['id']); + $countRequests++; + if ($countRequests % 10 === 0) { + $app->DB->Update( + "UPDATE prozessstarter SET mutex = 1 , mutexcounter = 0, letzteausfuerhung = now() WHERE parameter = 'shop_rueckmeldungen' AND aktiv = 1" - ); - } + ); + } } $app->DB->free($query); - } +} + +$app->DB->Update("UPDATE prozessstarter SET mutex = 0, mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); - $app->DB->Update("UPDATE prozessstarter SET mutex = 0, mutexcounter = 0, letzteausfuerhung = now() WHERE (parameter = 'shop_rueckmeldungen' ) AND aktiv = 1"); From f1400c48926887a07156fac9211d19bbaecb6417 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 19 Jul 2024 12:17:24 +0200 Subject: [PATCH 40/52] mirakl bugfix protokoll, taxes --- www/lib/class.remote.php | 1 + www/pages/shopimporter_mirakl.php | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 1c0a2f34..ea75cab4 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -2159,6 +2159,7 @@ class Remote { } public function getDataToSendForUpdateOrder(int $shopId, int $orderId): ?OrderStatusUpdateRequest + { $orderArr = $this->app->DB->SelectRow("SELECT `zahlungsweise`, `shopextid` FROM `auftrag` WHERE `id` = $orderId LIMIT 1"); if (empty($orderArr)) return null; diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index c039e745..3822fb3c 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -175,7 +175,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { if (!empty($importerSettings['einstellungen_json'])) { $einstellungen = json_decode($importerSettings['einstellungen_json'], true); } - $this->protocol = $einstellungen['felder']['protokoll']; $this->apiKey = $einstellungen['felder']['apikey']; $this->shopUrl = rtrim($einstellungen['felder']['shopurl'], '/') . '/'; $this->mirakl_shopid = $einstellungen['felder']['mirakl_shopid']; @@ -545,7 +544,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { if($tax->rate > $steuersatz) { $steuersatz = $tax->rate; } - switch ($order->row->taxes[0]->code) { + switch ($tax->code) { case $this->reducedTaxId: $umsatzsteuer_typ = 'ermaessigt'; break; From 1c8d64f3be5e0c48b3656b469b78f6d78e42ed2b Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 22 Jul 2024 12:29:02 +0200 Subject: [PATCH 41/52] revert faulty commit verbindlichkeit.php --- www/pages/verbindlichkeit.php | 40 ++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/www/pages/verbindlichkeit.php b/www/pages/verbindlichkeit.php index 99a1d0a4..374db9cb 100644 --- a/www/pages/verbindlichkeit.php +++ b/www/pages/verbindlichkeit.php @@ -228,7 +228,11 @@ class Verbindlichkeit { $defaultorder = 1; $defaultorderdesc = 0; - $offen_menge = ""; + $offen_menge = "TRIM(IF( + pd.menge > COALESCE(vp.menge,0), + pd.menge - COALESCE(vp.menge,0), + 0 + ))+0"; $auswahl = array ( '' ); @@ -297,7 +303,7 @@ class Verbindlichkeit { // END Toggle filters $sql = " - SELECT * FROM ( + SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT pa.id pa_id, ".$this->app->erp->ConcatSQL($auswahl)." AS auswahl, @@ -310,7 +316,11 @@ class Verbindlichkeit { art.name_de, pd.bemerkung, pd.menge, - 0 offen_menge, + IF( + pd.menge > COALESCE(vp.menge,0), + pd.menge - COALESCE(vp.menge,0), + 0 + ) offen_menge, ".$this->app->erp->ConcatSQL($werte).", ".$this->app->erp->ConcatSQL($preise)." AS preis, if(art.umsatzsteuer = '',art.steuersatz,art.umsatzsteuer) steuer, @@ -319,28 +329,38 @@ class Verbindlichkeit { CONCAT(skadr.sachkonto,' ',skadr.beschriftung) ) AS sachkonto FROM - paketdistribution pd - LEFT JOIN paketannahme pa ON + paketannahme pa + INNER JOIN paketdistribution pd ON pd.paketannahme = pa.id - LEFT JOIN artikel art ON + INNER JOIN artikel art ON art.id = pd.artikel LEFT JOIN adresse adr ON adr.id = pa.adresse LEFT JOIN bestellung_position bp ON bp.id = pd.bestellung_position LEFT JOIN bestellung b ON - b.id = bp.bestellung + b.id = bp.bestellung + LEFT JOIN( + SELECT + paketdistribution, + SUM(menge) AS menge + FROM + verbindlichkeit_position vp + GROUP BY + paketdistribution + ) vp + ON + vp.paketdistribution = pd.id LEFT JOIN kontorahmen skart ON skart.id = art.kontorahmen LEFT JOIN kontorahmen skadr ON skadr.id = adr.kontorahmen - WHERE pa.adresse = '".$lieferant."' - GROUP BY pd.id + WHERE pa.adresse = ".$lieferant." AND pd.vorlaeufig IS NULL".$innerwhere." ) temp "; $count = ""; - $groupby = ""; +// $groupby = ""; break; case 'verbindlichkeit_positionen': From 58174a8eef14340d38bfb713973e9c20afb957dd Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 23 Jul 2024 13:12:34 +0200 Subject: [PATCH 42/52] mirakl volume pricing --- www/pages/shopimporter_mirakl.php | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 3822fb3c..0d025cc4 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -621,8 +621,27 @@ class Shopimporter_Mirakl extends ShopimporterBase { $configuration_found = false; $additional_fields = array(); + // Prepare volume prices + $volume_prices = array(); + + foreach ($article['staffelpreise_standard'] as $volume_price) { + if ($volume_price['ab_menge'] > 1) { + $volume_prices[] = array ( + 'quantity_threshold' => (int) $volume_price['ab_menge'], + 'unit_discount_price' => $volume_price['preis'], + 'unit_origin_price' => $article['preis'] + ); + } + } + + $all_prices = array ( + 'volume_prices' => $volume_prices + ); + $offer_for_mirakl = array( - 'state_code' => '11', // ?!?! + 'state_code' => '11', // Condition new + 'price' => $article['preis'], + 'all_prices' => array($all_prices), 'update_delete' => null // Update delete flag. Could be empty (means "update"), "update" or "delete". ); @@ -645,8 +664,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $required = [ 'product_id_type', 'product_id', - 'shop_sku', - 'price' + 'shop_sku' ]; $missing = null; foreach ($required as $key) { @@ -718,7 +736,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $json_for_mirakl = json_encode($data_for_mirakl); - $this->Log(Logger::DEBUG, 'Angebotsexport Daten', $json_for_mirakl); + $this->Log(Logger::DEBUG, 'Angebotsexport Daten', ['json' => $json_for_mirakl]); $result = []; $response = $this->miraklRequest('offers', postdata: $json_for_mirakl, content_type: 'application/json', raw: true); From 9a9e34a32ae335d5bf04cbd672849ba655dd34c9 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 24 Jul 2024 16:01:17 +0200 Subject: [PATCH 43/52] erpapi bugfix result of RemoteSendArticleList, new array format --- www/lib/class.erpapi.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index b1ffdedf..72cb4d94 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -21046,7 +21046,7 @@ function ChargenMHDAuslagern($artikel, $menge, $lagerplatztyp, $lpid,$typ,$wert, $anzges = 0; $anzfehler = 0; - $result = null; // 1 on success + $result = null; // $result['status'] == 1 on success if(!empty($extnummer) && is_array($extnummer)) { foreach($extnummer as $nummer) { @@ -21077,9 +21077,9 @@ function ChargenMHDAuslagern($artikel, $menge, $lagerplatztyp, $lpid,$typ,$wert, } - $this->LogFile('*** UPDATE '.$lagerartikel[$ij]['nummer'].' '.$lagerartikel[$ij]['name_de'].' Shop: '.$shop.' Lagernd: '.$verkaufbare_menge.' Korrektur: '.round((float) ($verkaufbare_menge_korrektur - $verkaufbare_menge),7).' Pseudolager: '.round((float) $pseudolager,8).' Result: '.gettype($result).' '.$result); + $this->LogFile('*** UPDATE '.$lagerartikel[$ij]['nummer'].' '.$lagerartikel[$ij]['name_de'].' Shop: '.$shop.' Lagernd: '.$verkaufbare_menge.' Korrektur: '.round((float) ($verkaufbare_menge_korrektur - $verkaufbare_menge),7).' Pseudolager: '.round((float) $pseudolager,8).' Result: '.(is_array($result)?$result['status']:$result), $result); - if ($result == 1) { + if ($result['status'] == 1 || $status === 1) { $cacheQuantity = (int) $verkaufbare_menge_korrektur + (int) $pseudolager; $this->app->DB->Update( "UPDATE `artikel` SET `cache_lagerplatzinhaltmenge` = '{$cacheQuantity}' From fbe266c97c486c841f5c75e3a6bb7c9678a3a561 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 1 Aug 2024 14:04:48 +0200 Subject: [PATCH 44/52] bugfix mirakl auftragsimport country code --- www/pages/shopimporter_mirakl.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 0d025cc4..063a18fc 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -501,7 +501,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['ort'] = strval($order->customer->billing_address->city); // $cart['ustid'] = '?'; - $sql = "SELECT iso FROM laender WHERE iso3 = '".$order->customer->billing_address->country_iso_code."'"; + if ($order->customer->billing_address->country_iso_code) { + $sql = "SELECT iso FROM laender WHERE iso3 = '".$order->customer->billing_address->country_iso_code."' LIMIT 1"; + } $cart['land'] = $this->app->DB->Select($sql); $cart['abweichendelieferadresse'] = 1; From 3eb4d6bc3a736487eb39bcff6d6d731a9bdb7efa Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 22 Aug 2024 12:45:59 +0200 Subject: [PATCH 45/52] lagerzahlen removed 10 sec. wait --- cronjobs/lagerzahlen.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cronjobs/lagerzahlen.php b/cronjobs/lagerzahlen.php index a1ef1e0b..bd50830c 100644 --- a/cronjobs/lagerzahlen.php +++ b/cronjobs/lagerzahlen.php @@ -139,8 +139,8 @@ foreach ($lagerartikel as $articleCounter => $articleId) { $app->erp->LogFile("Lagerzahlen-Synchronisation Ende: lagerzahlen-Job kann nicht geladen werden"); return; } - $app->erp->LogFile("Lagerzahlen-Synchronisation: Warte 10 Sekunden"); - usleep(10000); +// $app->erp->LogFile("Lagerzahlen-Synchronisation: Warte 10 Sekunden"); +// usleep(10000); } $app->DB->Update( "UPDATE `prozessstarter` From 26e6d773a9d047e24351ee3e424e1c76b4278ee1 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 26 Aug 2024 11:03:59 +0200 Subject: [PATCH 46/52] Lagersync bugfix result array --- www/lib/class.erpapi.php | 2 +- www/lib/class.remote.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index 72cb4d94..1e28a58a 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -21079,7 +21079,7 @@ function ChargenMHDAuslagern($artikel, $menge, $lagerplatztyp, $lpid,$typ,$wert, $this->LogFile('*** UPDATE '.$lagerartikel[$ij]['nummer'].' '.$lagerartikel[$ij]['name_de'].' Shop: '.$shop.' Lagernd: '.$verkaufbare_menge.' Korrektur: '.round((float) ($verkaufbare_menge_korrektur - $verkaufbare_menge),7).' Pseudolager: '.round((float) $pseudolager,8).' Result: '.(is_array($result)?$result['status']:$result), $result); - if ($result['status'] == 1 || $status === 1) { + if ((is_array($result)?$result['status'] == 1:false) || $status === 1) { $cacheQuantity = (int) $verkaufbare_menge_korrektur + (int) $pseudolager; $this->app->DB->Update( "UPDATE `artikel` SET `cache_lagerplatzinhaltmenge` = '{$cacheQuantity}' diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index ea75cab4..96f890aa 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1088,6 +1088,7 @@ class Remote { $this->logger->debug( 'RemoteSendArticleList', [ + 'shop' => $id, 'artikel_arr' => $artikel_arr ] ); From 9fbc4e2f6b6845f1234146d4dce9b8e5a434d9e9 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 29 Aug 2024 18:09:04 +0200 Subject: [PATCH 47/52] mirakl configuration_order_fetch_status --- www/pages/shopimporter_mirakl.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index 063a18fc..b3f83aa0 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -30,6 +30,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { private $configuration_identifier; private $mirakl_error_text_product_missing; + private $configuration_order_fetch_status; private $normalTaxId; private $reducedTaxId; @@ -92,6 +93,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { 'info' => 'Der Fehlertext der anzeigt dass das Produkt nicht existiert (Angebotsimport, Fehlerbericht)', 'default' => 'The product does not exist' ], + 'configuration_order_fetch_status' => [ + 'typ' => 'text', + 'bezeichnung' => '{|Status für abzuholende Aufträge|}:', + 'size' => 40, + 'info' => 'STAGING, WAITING_ACCEPTANCE, WAITING_DEBIT, WAITING_DEBIT_PAYMENT, SHIPPING, SHIPPED, TO_COLLECT, RECEIVED, CLOSED, REFUSED, CANCELED', + 'default' => 'WAITING_ACCEPTANCE' + ], 'normalTaxId' => [ 'typ' => 'text', 'bezeichnung' => '{|TaxId für Steuersatz "normal"|}', @@ -182,6 +190,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { $this->configuration_identifier = array($einstellungen['felder']['configuration_identifier_source'] => $einstellungen['felder']['configuration_identifier_source_value']); $this->mirakl_error_text_product_missing = $einstellungen['felder']['mirakl_error_text_product_missing']; + $this->configuration_order_fetch_status = $einstellungen['felder']['configuration_order_fetch_status']; $this->normalTaxId = $einstellungen['felder']['normalTaxId']; $this->reducedTaxId = $einstellungen['felder']['reducedTaxId']; @@ -450,7 +459,7 @@ class Shopimporter_Mirakl extends ShopimporterBase { // STAGING, WAITING_ACCEPTANCE, WAITING_DEBIT, WAITING_DEBIT_PAYMENT, SHIPPING, SHIPPED, TO_COLLECT, RECEIVED, CLOSED, REFUSED, CANCELED public function ImportGetAuftraegeAnzahl() { - $response = $this->miraklRequest('orders', getdata: array('order_state_codes' => 'WAITING_ACCEPTANCE'), raw: true); + $response = $this->miraklRequest('orders', getdata: array('order_state_codes' => $this->configuration_order_fetch_status), raw: true); $this->Log(Logger::DEBUG, 'ImportGetAuftraegeAnzahl', $response); $result_array = json_decode($response); return($result_array->total_count); @@ -458,13 +467,13 @@ class Shopimporter_Mirakl extends ShopimporterBase { public function ImportGetAuftrag() { - $parameters = array('order_state_codes' => 'WAITING_ACCEPTANCE'); + $parameters = array('order_state_codes' => $this->configuration_order_fetch_status); if(!empty($this->data['nummer'])) { $parameters['order_ids'] = $this->data['nummer']; } - $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); + $response = $this->miraklRequest('orders', getdata: $parameters, raw: true); $this->Log(Logger::DEBUG, 'ImportGetAuftrag', $response); $result_array = json_decode($response); From 389a29793ad1397559290ff47fbe4ceb6412cc2c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 29 Aug 2024 18:43:26 +0200 Subject: [PATCH 48/52] mirakl auftrag import additional info --- www/lib/class.erpapi.php | 3 +++ www/pages/shopimporter_mirakl.php | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index 1e28a58a..a436ed3e 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -17727,6 +17727,9 @@ function CheckShopTabelle($artikel) if($doctype === 'angebot'){ $this->app->DB->Update("UPDATE angebot SET anfrage = '".$this->app->DB->real_escape_string($warenkorb['onlinebestellnummer'])."' WHERE id = '$auftrag' LIMIT 1"); } + if($doctype === 'auftrag'){ + $this->app->DB->Update("UPDATE auftrag SET ihrebestellnummer = '".$this->app->DB->real_escape_string($warenkorb['ihrebestellnummer'])."' WHERE id = '$auftrag' LIMIT 1"); + } $this->app->DB->Update("UPDATE $doctype SET belegnr='$belegnr', diff --git a/www/pages/shopimporter_mirakl.php b/www/pages/shopimporter_mirakl.php index b3f83aa0..5f50d34e 100644 --- a/www/pages/shopimporter_mirakl.php +++ b/www/pages/shopimporter_mirakl.php @@ -522,9 +522,9 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['lieferadresse_name'] = ($order->customer->shipping_address->civility?$order->customer->shipping_address->civility." ":"").$order->customer->shipping_address->firstname." ".$order->customer->shipping_address->lastname; - if (!empty(strval($order->customer->shipping_address->company))) { + if (!empty($order->customer->shipping_address->company)) { $cart['lieferadresse_ansprechpartner'] = $cart['lieferadresse_name']; - $cart['lieferadresse_name'] = strval($deliveryAddress->company); + $cart['lieferadresse_name'] = strval($order->customer->shipping_address->company); } $cart['lieferadresse_strasse'] = strval($order->customer->shipping_address->street_1); @@ -532,6 +532,16 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['lieferadresse_telefon'] = strval($order->customer->shipping_address->phone); $cart['lieferadresse_plz'] = strval($order->customer->shipping_address->zip_code); $cart['lieferadresse_ort'] = strval($order->customer->shipping_address->city); + + $cart['internebemerkung'] = strval($order->customer->shipping_address->additional_info); + + if (is_array($order->order_additional_fields)) { + $order_reference = array_search('customer-order-reference',array_column($order->order_additional_fields,'code')); + + if ($order_reference !== false) { + $cart['ihrebestellnummer'] .= $order->order_additional_fields[$order_reference]->value; + } + } $cart['zahlungsweise'] = strval($order->payment_type); @@ -544,7 +554,6 @@ class Shopimporter_Mirakl extends ShopimporterBase { $cart['articlelist'] = []; - $shipping_tax_amount = 0; foreach ($order->order_lines as $order_row) { From 8c3442c73d606bad15408203819f2cfeefea913c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Sat, 31 Aug 2024 13:12:37 +0200 Subject: [PATCH 49/52] class.remote.php formatting --- www/lib/class.remote.php | 4744 ++++++++++++++++++-------------------- 1 file changed, 2265 insertions(+), 2479 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 937ae7a7..e87eb432 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1,4 +1,5 @@ app=$app; - } +class Remote { - /** - * @param int $shopId - * @param null|bool $extra - * - * @return mixed - * @throws Exception - */ - public function RemoteConnection($shopId, $extra = null) - { - $ret = $this->RemoteCommand($shopId,'auth', $extra); - if($ret !== 'success' && empty($extra) && method_exists($this->app->erp, 'setSystemHealth')) { - $this->app->erp->setSystemHealth( - 'shopexport', - 'auth', - 'warning', - 'Verbindung zu '. - $this->app->DB->Select( - sprintf( - 'SELECT bezeichnung FROM shopexport WHERE id = %d', - $shopId - ) - ).' fehlgeschlagen.' - ); - try { - /** @var Systemhealth $systemhealth */ - $systemhealth = $this->app->erp->LoadModul('systemhealth'); - if($systemhealth !== null && method_exists($systemhealth, 'createEvent')){ - $systemhealth->createEvent('shopexport', 'auth', 'warning', 'shopexport', $shopId); + /** @var ApplicationCore $app */ + public $app; + + public function __construct($app) { + $this->app = $app; + } + + /** + * @param int $shopId + * @param null|bool $extra + * + * @return mixed + * @throws Exception + */ + public function RemoteConnection($shopId, $extra = null) { + $ret = $this->RemoteCommand($shopId, 'auth', $extra); + if ($ret !== 'success' && empty($extra) && method_exists($this->app->erp, 'setSystemHealth')) { + $this->app->erp->setSystemHealth( + 'shopexport', + 'auth', + 'warning', + 'Verbindung zu ' . + $this->app->DB->Select( + sprintf( + 'SELECT bezeichnung FROM shopexport WHERE id = %d', + $shopId + ) + ) . ' fehlgeschlagen.' + ); + try { + /** @var Systemhealth $systemhealth */ + $systemhealth = $this->app->erp->LoadModul('systemhealth'); + if ($systemhealth !== null && method_exists($systemhealth, 'createEvent')) { + $systemhealth->createEvent('shopexport', 'auth', 'warning', 'shopexport', $shopId); + } + } catch (Exception $d) { + + } } - } - catch (Exception $d) { - - } - } - return $ret; - } - - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetUpdateArticleList($shopId) - { - return $this->RemoteCommand($shopId,'getlist'); - } - - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetFileList($shopId) - { - return $this->RemoteCommand($shopId,'getfilelist'); - } - - /** - * @param int $shopId - * @param int|string $articleId - * - * @return mixed - * @throws Exception - */ - public function RemoteGetFileListArticle($shopId, $article) - { - $data['artikel'] = $article; - - return $this->RemoteCommand($shopId,'getfilelistarticle', $data); - } - - /** - * @param int $shopId - * @param array|string $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftraegeAnzahl($shopId,$data = '') - { - if(!empty($data)) - { - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); - } - $data = array(); - $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id = %d LIMIT 1', $shopId)); - $holealle = $shopexportArr['holealle']; - $holeallestati = $shopexportArr['holeallestati']; - $zeitraum = [ - 'datumvon'=>$shopexportArr['datumvon'], - 'datumbis'=>$shopexportArr['datumbis'], - 'tmpdatumvon'=>$shopexportArr['tmpdatumvon'], - 'tmpdatumbis'=>$shopexportArr['tmpdatumbis'], - 'anzgleichzeitig'=>$shopexportArr['anzgleichzeitig'], - ]; - if(!empty($zeitraum)) - { - $data['datumvon'] = $zeitraum['datumvon']; - $data['datumbis'] = $zeitraum['datumbis']; - //if(strtotime($zeitraum[0]['tmpdatumbis']) > 0)$data['datumbis'] = $zeitraum[0]['tmpdatumbis']; - //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; - if($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00'|| strtotime($data['datumvon'])<=0) { - $data['datumvon'] = '2000-01-01 00:00:00'; - } - if($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00'|| strtotime($data['datumbis'])<=0) { - $data['datumbis'] = date('Y-m-d H:i:s'); - $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); - } - $data['anzgleichzeitig'] = $zeitraum[0]['anzgleichzeitig']; - if($holeallestati && $data['anzgleichzeitig'] > 1) - { - $data['holeallestati'] = 1; - } - } - if($holealle) - { - $ab_nummer = $shopexportArr['ab_nummer']; - $data = array('ab_nummer' => $ab_nummer); - if($holeallestati) - { - $data['holeallestati'] = 1; - } - - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); + return $ret; } - return $this->RemoteCommand($shopId,'getauftraegeanzahl'); - } - - /** - * @param int $shopId - * @param string $nummer - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftraegeAnzahlNummer($shopId, $nummer) - { - $data = array('nummer' => $nummer); - - return $this->RemoteCommand($shopId,'getauftraegeanzahl', $data); - } - - /** - * @param int $shopId - * @param null|array $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftrag($shopId, $data = null) - { - if(!empty($data)) { - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - $data = array(); - - $shopexportArr = $this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM shopexport WHERE id = %d LIMIT 1', - $shopId - ) - ); - $holealle = $shopexportArr['holealle']; - $holeallestati = $shopexportArr['holeallestati']; - $zeitraum = [ - 'datumvon'=>$shopexportArr['datumvon'], - 'datumbis'=>$shopexportArr['datumbis'], - 'tmpdatumvon'=>$shopexportArr['tmpdatumvon'], - 'tmpdatumbis'=>$shopexportArr['tmpdatumbis'], - 'anzgleichzeitig'=>$shopexportArr['anzgleichzeitig'], - ]; - if(!empty($zeitraum)) { - $data['datumvon'] = $zeitraum['datumvon']; - $data['datumbis'] = $zeitraum['datumbis']; - if($zeitraum['tmpdatumbis'] !== null && $zeitraum['tmpdatumbis'] !== '0000-00-00 00:00:00' && - strtotime($zeitraum['tmpdatumbis']) > 0) { - $data['datumbis'] = $zeitraum['tmpdatumbis']; - } - //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; - if($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon'])<=0) { - $data['datumvon'] = '2000-01-01 00:00:00'; - } - if($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis'])<=0) { - $data['datumbis'] = date('Y-m-d H:i:s'); - $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); - } - $data['anzgleichzeitig'] = $zeitraum['anzgleichzeitig']; - if($data['anzgleichzeitig'] > 1 && $shopexportArr['einzelsync']) { - $data['anzgleichzeitig'] = 1; - } - if($holeallestati) { - $data['holeallestati'] = 1; - } - } - if($holealle) { - $ab_nummer = $shopexportArr['ab_nummer']; - $data['ab_nummer'] = $ab_nummer; - if($holeallestati) { - $data['holeallestati'] = 1; - } - - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - if(!empty($zeitraum)) { - return $this->RemoteCommand($shopId,'getauftrag', $data); - } - - return $this->RemoteCommand($shopId,'getauftrag'); - } - - /** - * @param int $shopId - * @param string $nummer - * - * @return mixed|string - * @throws Exception - */ - public function RemoteGetAuftragNummer($shopId, $nummer) - { - $holealle = $this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$shopId' LIMIT 1"); - if($holealle) - { - $data = array('nummer' => $nummer); - - return $this->RemoteCommand($shopId,'getauftrag', $data); + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetUpdateArticleList($shopId) { + return $this->RemoteCommand($shopId, 'getlist'); } - return ''; - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetFileList($shopId) { + return $this->RemoteCommand($shopId, 'getfilelist'); + } - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendExportlink($shopId) - { - // passwort erzeugen , daten verschluesseln, wenn passwort neu link an kunden senden - // alternativ artikel umfrage - // $all = $this->app->DB->SelectArr("SELECT * FROM artikelgruppen WHERE shop='$id'"); + /** + * @param int $shopId + * @param int|string $articleId + * + * @return mixed + * @throws Exception + */ + public function RemoteGetFileListArticle($shopId, $article) { + $data['artikel'] = $article; - // alle artikelid = 38 die in einem auftrag sind + return $this->RemoteCommand($shopId, 'getfilelistarticle', $data); + } + /** + * @param int $shopId + * @param array|string $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftraegeAnzahl($shopId, $data = '') { + if (!empty($data)) { + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } + $data = array(); + $shopexportArr = $this->app->DB->SelectRow(sprintf('SELECT * FROM shopexport WHERE id = %d LIMIT 1', $shopId)); + $holealle = $shopexportArr['holealle']; + $holeallestati = $shopexportArr['holeallestati']; + $zeitraum = [ + 'datumvon' => $shopexportArr['datumvon'], + 'datumbis' => $shopexportArr['datumbis'], + 'tmpdatumvon' => $shopexportArr['tmpdatumvon'], + 'tmpdatumbis' => $shopexportArr['tmpdatumbis'], + 'anzgleichzeitig' => $shopexportArr['anzgleichzeitig'], + ]; + if (!empty($zeitraum)) { + $data['datumvon'] = $zeitraum['datumvon']; + $data['datumbis'] = $zeitraum['datumbis']; + //if(strtotime($zeitraum[0]['tmpdatumbis']) > 0)$data['datumbis'] = $zeitraum[0]['tmpdatumbis']; + //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; + if ($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon']) <= 0) { + $data['datumvon'] = '2000-01-01 00:00:00'; + } + if ($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis']) <= 0) { + $data['datumbis'] = date('Y-m-d H:i:s'); + $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); + } + $data['anzgleichzeitig'] = $zeitraum[0]['anzgleichzeitig']; + if ($holeallestati && $data['anzgleichzeitig'] > 1) { + $data['holeallestati'] = 1; + } + } + if ($holealle) { + $ab_nummer = $shopexportArr['ab_nummer']; + $data = array('ab_nummer' => $ab_nummer); + if ($holeallestati) { + $data['holeallestati'] = 1; + } - // usb90key - $artikelid= 38; + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } - $all = $this->app->DB->SelectArr("SELECT a.id as auftrag, a.adresse as adresse + return $this->RemoteCommand($shopId, 'getauftraegeanzahl'); + } + + /** + * @param int $shopId + * @param string $nummer + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftraegeAnzahlNummer($shopId, $nummer) { + $data = array('nummer' => $nummer); + + return $this->RemoteCommand($shopId, 'getauftraegeanzahl', $data); + } + + /** + * @param int $shopId + * @param null|array $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftrag($shopId, $data = null) { + if (!empty($data)) { + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + $data = array(); + + $shopexportArr = $this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM shopexport WHERE id = %d LIMIT 1', + $shopId + ) + ); + $holealle = $shopexportArr['holealle']; + $holeallestati = $shopexportArr['holeallestati']; + $zeitraum = [ + 'datumvon' => $shopexportArr['datumvon'], + 'datumbis' => $shopexportArr['datumbis'], + 'tmpdatumvon' => $shopexportArr['tmpdatumvon'], + 'tmpdatumbis' => $shopexportArr['tmpdatumbis'], + 'anzgleichzeitig' => $shopexportArr['anzgleichzeitig'], + ]; + if (!empty($zeitraum)) { + $data['datumvon'] = $zeitraum['datumvon']; + $data['datumbis'] = $zeitraum['datumbis']; + if ($zeitraum['tmpdatumbis'] !== null && $zeitraum['tmpdatumbis'] !== '0000-00-00 00:00:00' && + strtotime($zeitraum['tmpdatumbis']) > 0) { + $data['datumbis'] = $zeitraum['tmpdatumbis']; + } + //if(strtotime($zeitraum[0]['tmpdatumvon']) > 0)$data['datumvon'] = $zeitraum[0]['tmpdatumbis']; + if ($data['datumvon'] === null || $data['datumvon'] === '0000-00-00 00:00:00' || strtotime($data['datumvon']) <= 0) { + $data['datumvon'] = '2000-01-01 00:00:00'; + } + if ($data['datumbis'] === null || $data['datumbis'] === '0000-00-00 00:00:00' || strtotime($data['datumbis']) <= 0) { + $data['datumbis'] = date('Y-m-d H:i:s'); + $data['datumbis_utc'] = $this->app->DB->Select('select date_sub(UTC_TIMESTAMP, INTERVAL 0 MINUTE)'); + } + $data['anzgleichzeitig'] = $zeitraum['anzgleichzeitig']; + if ($data['anzgleichzeitig'] > 1 && $shopexportArr['einzelsync']) { + $data['anzgleichzeitig'] = 1; + } + if ($holeallestati) { + $data['holeallestati'] = 1; + } + } + if ($holealle) { + $ab_nummer = $shopexportArr['ab_nummer']; + $data['ab_nummer'] = $ab_nummer; + if ($holeallestati) { + $data['holeallestati'] = 1; + } + + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + if (!empty($zeitraum)) { + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + + return $this->RemoteCommand($shopId, 'getauftrag'); + } + + /** + * @param int $shopId + * @param string $nummer + * + * @return mixed|string + * @throws Exception + */ + public function RemoteGetAuftragNummer($shopId, $nummer) { + $holealle = $this->app->DB->Select("SELECT holealle FROM shopexport WHERE id = '$shopId' LIMIT 1"); + if ($holealle) { + $data = array('nummer' => $nummer); + + return $this->RemoteCommand($shopId, 'getauftrag', $data); + } + + return ''; + } + + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendExportlink($shopId) { + // passwort erzeugen , daten verschluesseln, wenn passwort neu link an kunden senden + // alternativ artikel umfrage + // $all = $this->app->DB->SelectArr("SELECT * FROM artikelgruppen WHERE shop='$id'"); + // alle artikelid = 38 die in einem auftrag sind + // usb90key + $artikelid = 38; + + $all = $this->app->DB->SelectArr("SELECT a.id as auftrag, a.adresse as adresse FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag WHERE ap.artikel='$artikelid' AND ap.geliefert_menge < ap.menge AND a.status!='storniert' AND a.status!='abgeschlossen'"); - // mail mit url senden - if(empty($all)) { - return ''; - } - $loop = 0; - $call = (!empty($all)?count($all):0); - for($i=0;$i<$call;$i++) - { - $auftragid = $all[$i]['auftrag']; - $adresse = $all[$i]['adresse']; + // mail mit url senden + if (empty($all)) { + return ''; + } + $loop = 0; + $call = (!empty($all) ? count($all) : 0); + for ($i = 0; $i < $call; $i++) { + $auftragid = $all[$i]['auftrag']; + $adresse = $all[$i]['adresse']; - $grund = 'artikel'; + $grund = 'artikel'; - $check = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE adresse='$adresse' AND objekt='$artikelid' AND ident='$auftragid' LIMIT 1"); + $check = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE adresse='$adresse' AND objekt='$artikelid' AND ident='$auftragid' LIMIT 1"); - if($check=='') - { - $checkreg = 1; - while($checkreg!='') - { - $token1 = md5(uniqid(rand(), true)); - $token2 = md5(uniqid(rand(), true)); + if ($check == '') { + $checkreg = 1; + while ($checkreg != '') { + $token1 = md5(uniqid(rand(), true)); + $token2 = md5(uniqid(rand(), true)); - $token3 = md5(uniqid(rand(), true)); - $token4 = md5(uniqid(rand(), true)); + $token3 = md5(uniqid(rand(), true)); + $token4 = md5(uniqid(rand(), true)); - $zufall = $token1 . '-' . $token2; - $zufall = md5($zufall); + $zufall = $token1 . '-' . $token2; + $zufall = md5($zufall); - $zufall2 = $token3 . '-' . $token4; - $zufall2 = md5($zufall2); + $zufall2 = $token3 . '-' . $token4; + $zufall2 = md5($zufall2); - $reg = md5($zufall2.$zufall); + $reg = md5($zufall2 . $zufall); - $checkreg = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE reg='$reg' LIMIT 1"); + $checkreg = $this->app->DB->Select("SELECT reg FROM exportlink_sent WHERE reg='$reg' LIMIT 1"); + } + + // pruefen ob es zahl schon gibt sonst nochmal + + $data[$loop]['reg'] = $reg; + $data[$loop]['grund'] = $grund; + $data[$loop]['objekt'] = $artikelid; // artikel id + $data[$loop]['ident'] = $auftragid; // + $loop++; + + $this->app->DB->Insert("INSERT INTO exportlink_sent (reg,grund,objekt,ident,adresse,datum) VALUES ($reg','$grund','$artikelid','$auftragid','$adresse',NOW())"); + } } - // pruefen ob es zahl schon gibt sonst nochmal - - $data[$loop]['reg'] = $reg; - $data[$loop]['grund'] = $grund; - $data[$loop]['objekt'] = $artikelid; // artikel id - $data[$loop]['ident'] = $auftragid;// - $loop++; - - $this->app->DB->Insert("INSERT INTO exportlink_sent (reg,grund,objekt,ident,adresse,datum) VALUES ($reg','$grund','$artikelid','$auftragid','$adresse',NOW())"); - } + return $this->RemoteCommand($shopId, 'exportlink', $data); } - return $this->RemoteCommand($shopId,'exportlink',$data); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendNavigation($shopId) { + //$data[0] = array('aasas','asddd'); - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendNavigation($shopId) - { - //$data[0] = array('aasas','asddd'); + $all = $this->app->DB->SelectArr("SELECT * FROM shopnavigation WHERE shop='$shopId'"); + $call = $all ? count($all) : 0; + $data = $call > 0 ? array() : null; + for ($i = 0; $i < $call; $i++) { + $data[$i]['id'] = $all[$i]['id']; + $data[$i]['bezeichnung'] = $all[$i]['bezeichnung']; + $data[$i]['position'] = $all[$i]['position']; + $data[$i]['parent'] = $all[$i]['parent']; + $data[$i]['bezeichnung_en'] = $all[$i]['bezeichnung_en']; + $data[$i]['plugin'] = $all[$i]['plugin']; + $data[$i]['pluginparameter'] = $all[$i]['pluginparameter']; + $data[$i]['target'] = $all[$i]['target']; + } - $all = $this->app->DB->SelectArr("SELECT * FROM shopnavigation WHERE shop='$shopId'"); - $call = $all?count($all):0; - $data = $call > 0?array():null; - for($i=0;$i<$call;$i++) - { - $data[$i]['id'] = $all[$i]['id']; - $data[$i]['bezeichnung'] = $all[$i]['bezeichnung']; - $data[$i]['position'] = $all[$i]['position']; - $data[$i]['parent'] = $all[$i]['parent']; - $data[$i]['bezeichnung_en'] = $all[$i]['bezeichnung_en']; - $data[$i]['plugin'] = $all[$i]['plugin']; - $data[$i]['pluginparameter'] = $all[$i]['pluginparameter']; - $data[$i]['target'] = $all[$i]['target']; + return $this->RemoteCommand($shopId, 'navigation', $data); } - return $this->RemoteCommand($shopId,'navigation',$data); - } - - /** - * @param int $shopId - * - * @return mixed|string - * @throws Exception - */ - public function RemoteSendArtikelgruppen($shopId) - { - $all = $this->app->DB->SelectArr("SELECT id, bezeichnung,bezeichnung_en,beschreibung_de,beschreibung_en + /** + * @param int $shopId + * + * @return mixed|string + * @throws Exception + */ + public function RemoteSendArtikelgruppen($shopId) { + $all = $this->app->DB->SelectArr("SELECT id, bezeichnung,bezeichnung_en,beschreibung_de,beschreibung_en FROM artikelgruppen WHERE shop='$shopId'"); - if(empty($all)) { - return ''; + if (empty($all)) { + return ''; + } + + return $this->RemoteCommand($shopId, 'artikelgruppen', $all); } - return $this->RemoteCommand($shopId,'artikelgruppen',$all); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendInhalt($shopId) { + $all = $this->app->DB->SelectArr("SELECT * FROM inhalt WHERE shop='$shopId' AND aktiv=1"); + if (empty($all)) { + return ''; + } + $call = (!empty($all) ? count($all) : 0); - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendInhalt($shopId) - { - $all = $this->app->DB->SelectArr("SELECT * FROM inhalt WHERE shop='$shopId' AND aktiv=1"); - if(empty($all)) { - return ''; - } - $call = (!empty($all)?count($all):0); + $data = array(); + for ($i = 0; $i < $call; $i++) { + $data[$i]['sprache'] = $all[$i]['sprache']; + $data[$i]['inhalt'] = $all[$i]['inhalt']; + $data[$i]['kurztext'] = $all[$i]['kurztext']; + $data[$i]['html'] = $all[$i]['html']; + $data[$i]['title'] = $all[$i]['title']; + $data[$i]['description'] = $all[$i]['description']; + $data[$i]['keywords'] = $all[$i]['keywords']; + $data[$i]['inhaltstyp'] = $all[$i]['inhaltstyp']; + $data[$i]['template'] = $all[$i]['template']; + $data[$i]['finalparse'] = $all[$i]['finalparse']; + $data[$i]['navigation'] = $all[$i]['navigation']; + $data[$i]['sichtbarbis'] = $all[$i]['sichtbarbis']; + $data[$i]['datum'] = $all[$i]['datum']; + $data[$i]['aktiv'] = $all[$i]['aktiv']; + } - $data = array(); - for ($i = 0; $i < $call; $i++) { - $data[$i]['sprache'] = $all[$i]['sprache']; - $data[$i]['inhalt'] = $all[$i]['inhalt']; - $data[$i]['kurztext'] = $all[$i]['kurztext']; - $data[$i]['html'] = $all[$i]['html']; - $data[$i]['title'] = $all[$i]['title']; - $data[$i]['description'] = $all[$i]['description']; - $data[$i]['keywords'] = $all[$i]['keywords']; - $data[$i]['inhaltstyp'] = $all[$i]['inhaltstyp']; - $data[$i]['template'] = $all[$i]['template']; - $data[$i]['finalparse'] = $all[$i]['finalparse']; - $data[$i]['navigation'] = $all[$i]['navigation']; - $data[$i]['sichtbarbis'] = $all[$i]['sichtbarbis']; - $data[$i]['datum'] = $all[$i]['datum']; - $data[$i]['aktiv'] = $all[$i]['aktiv']; + return $this->RemoteCommand($shopId, 'inhalt', $data); } - return $this->RemoteCommand($shopId, 'inhalt', $data); - } + /** + * @param int $shopId + * + * @return mixed + * @throws Exception + */ + public function RemoteSendArtikelArtikelgruppen($shopId) { + $all = $this->app->DB->SelectArr('SELECT * FROM artikel_artikelgruppe'); + $call = $all ? count($all) : 0; + if ($call > 0) { + $data = array(); + for ($i = 0; $i < $call; $i++) { + $data[$i]['id'] = $all[$i]['id']; + $data[$i]['artikel'] = $all[$i]['artikel']; + $data[$i]['artikelgruppe'] = $all[$i]['artikelgruppe']; + $data[$i]['position'] = $all[$i]['position']; + } - /** - * @param int $shopId - * - * @return mixed - * @throws Exception - */ - public function RemoteSendArtikelArtikelgruppen($shopId) - { - $all = $this->app->DB->SelectArr('SELECT * FROM artikel_artikelgruppe'); - $call = $all?count($all):0; - if($call > 0){ - $data = array(); - for ($i = 0; $i < $call; $i++) { - $data[$i]['id'] = $all[$i]['id']; - $data[$i]['artikel'] = $all[$i]['artikel']; - $data[$i]['artikelgruppe'] = $all[$i]['artikelgruppe']; - $data[$i]['position'] = $all[$i]['position']; - } + return $this->RemoteCommand($shopId, 'artikelartikelgruppen', $data); + } - return $this->RemoteCommand($shopId, 'artikelartikelgruppen', $data); + return ''; } - return ''; - } - - /** - * @param int $shopId - * @param string $tabelle - * @param int $intid - * @param int $intid2 - * - * @return mixed - */ - public function GetShopexportMappingExt($shopId, $tabelle, $intid, $intid2 = 0) - { - return $this->app->DB->Select("SELECT extid + /** + * @param int $shopId + * @param string $tabelle + * @param int $intid + * @param int $intid2 + * + * @return mixed + */ + public function GetShopexportMappingExt($shopId, $tabelle, $intid, $intid2 = 0) { + return $this->app->DB->Select("SELECT extid FROM shopexport_mapping - WHERE shop = '$shopId' AND tabelle = '$tabelle' AND intid = '$intid' ".($intid2?" AND intid2 = '$intid2' ":'')." LIMIT 1"); - } + WHERE shop = '$shopId' AND tabelle = '$tabelle' AND intid = '$intid' " . ($intid2 ? " AND intid2 = '$intid2' " : '') . " LIMIT 1"); + } - /** - * @param int $shopId - * @param string $tabelle - * @param string $extid - * @param int $intid2 - * - * @return mixed - */ - protected function GetShopexportMappingInt($shopId, $tabelle, $extid, $intid2 = 0) - { - return $this->app->DB->Select("SELECT intid + /** + * @param int $shopId + * @param string $tabelle + * @param string $extid + * @param int $intid2 + * + * @return mixed + */ + protected function GetShopexportMappingInt($shopId, $tabelle, $extid, $intid2 = 0) { + return $this->app->DB->Select("SELECT intid FROM shopexport_mapping - WHERE shop = '$shopId' AND tabelle = '$tabelle' AND extid = '$extid' ".($intid2?" AND intid2 = '$intid2' ":'')." + WHERE shop = '$shopId' AND tabelle = '$tabelle' AND extid = '$extid' " . ($intid2 ? " AND intid2 = '$intid2' " : '') . " LIMIT 1"); - } + } - /** - * @param int $shop - * @param string $tabelle - * @param int $intid - * @param string $extid - * @param int $intid2 - * - * @return mixed - */ - public function ShopexportMappingSet($shop, $tabelle, $intid, $extid, $intid2 = 0) - { - $check = $this->app->DB->Select("SELECT id FROM shopexport_mapping + /** + * @param int $shop + * @param string $tabelle + * @param int $intid + * @param string $extid + * @param int $intid2 + * + * @return mixed + */ + public function ShopexportMappingSet($shop, $tabelle, $intid, $extid, $intid2 = 0) { + $check = $this->app->DB->Select("SELECT id FROM shopexport_mapping WHERE shop = '$shop' AND tabelle = '$tabelle' AND intid = '$intid' AND intid2 = '$intid2' LIMIT 1"); - if(!$check) - { - $this->app->DB->Insert("INSERT INTO shopexport_mapping (shop, tabelle, intid, intid2, extid, zeitstempel) + if (!$check) { + $this->app->DB->Insert("INSERT INTO shopexport_mapping (shop, tabelle, intid, intid2, extid, zeitstempel) VALUES ('$shop', '$tabelle', '$intid', '$intid2', '$extid', now())"); - return $this->app->DB->GetInsertID(); - } - $this->app->DB->Update("UPDATE shopexport_mapping SET extid = '$extid' WHERE id = '$check' LIMIT 1"); + return $this->app->DB->GetInsertID(); + } + $this->app->DB->Update("UPDATE shopexport_mapping SET extid = '$extid' WHERE id = '$check' LIMIT 1"); - return $check; - } + return $check; + } - /** - * @param int $id - * @param string $nummer - * @param bool $create - * - * @return mixed - * @throws Exception - */ - public function RemoteGetArticle($id,$nummer, $create = false) - { - if($create) - { - $data['nummerintern'] = $nummer; - }else { - $data['nummer'] = $nummer; - } - $ret = $this->RemoteCommand($id,'getarticle',$data); - $variante_von = null; - //if(!$create)return $ret; - $_nummer = null; - $shopexportArr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); - $projekt = $shopexportArr['projekt']; - $nurneueartikel = $shopexportArr['nurneueartikel']; - $artikelnummerbeimanlegenausshop = $shopexportArr['artikelnummerbeimanlegenausshop']; - if(!$create){ - $nurneueartikel = false; - } - if(!isset($ret['nummer']) && isset($ret[0]) && isset($ret[0]['nummer'])) - { - $reta = $ret; - }elseif(isset($ret['nummer'])) - { - $reta[] = $ret; - }elseif(isset($ret[0]) && isset($ret[0]['name'])){ - $ret[0]['nummer'] = '';//$nummer; - $reta = $ret; - }elseif(isset($ret['name'])){ - $ret['nummer'] = '';//$nummer; - $reta[] = $ret; - }else - { - return $ret; - } - if(!$reta || !is_array($reta)) - { - return $ret; - } - $stuecklistenmechanik = false; - $variantevonorig = null; - $steuersatz_normal = $this->app->erp->Firmendaten('steuersatz_normal'); - $steuersatz_ermaessigt = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); - if(empty($steuersatz_ermaessigt)) - { - $steuersatz_ermaessigt = 7; - } - if(empty($steuersatz_normal)) - { - $steuersatz_normal = 19; - } - $crossellingInstalled = $this->app->erp->ModulVorhanden('crossselling'); - foreach($reta as $k => $ret) - { - if(isset($ret['stueckliste'])){ - $stuecklistenmechanik = $ret['stueckliste']; - } - $ret['nummer'] = $this->app->DB->real_escape_string(trim($ret['nummer'])); - $articleid = null; - if($k == 0) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $nummer,true); - if($articleid) - { - $variantevonorig = $this->app->DB->Select("SELECT variante_von + /** + * @param int $id + * @param string $nummer + * @param bool $create + * + * @return mixed + * @throws Exception + */ + public function RemoteGetArticle($id, $nummer, $create = false) { + if ($create) { + $data['nummerintern'] = $nummer; + } else { + $data['nummer'] = $nummer; + } + $ret = $this->RemoteCommand($id, 'getarticle', $data); + $variante_von = null; + //if(!$create)return $ret; + $_nummer = null; + $shopexportArr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id = '$id' LIMIT 1"); + $projekt = $shopexportArr['projekt']; + $nurneueartikel = $shopexportArr['nurneueartikel']; + $artikelnummerbeimanlegenausshop = $shopexportArr['artikelnummerbeimanlegenausshop']; + if (!$create) { + $nurneueartikel = false; + } + if (!isset($ret['nummer']) && isset($ret[0]) && isset($ret[0]['nummer'])) { + $reta = $ret; + } elseif (isset($ret['nummer'])) { + $reta[] = $ret; + } elseif (isset($ret[0]) && isset($ret[0]['name'])) { + $ret[0]['nummer'] = ''; //$nummer; + $reta = $ret; + } elseif (isset($ret['name'])) { + $ret['nummer'] = ''; //$nummer; + $reta[] = $ret; + } else { + return $ret; + } + if (!$reta || !is_array($reta)) { + return $ret; + } + $stuecklistenmechanik = false; + $variantevonorig = null; + $steuersatz_normal = $this->app->erp->Firmendaten('steuersatz_normal'); + $steuersatz_ermaessigt = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + if (empty($steuersatz_ermaessigt)) { + $steuersatz_ermaessigt = 7; + } + if (empty($steuersatz_normal)) { + $steuersatz_normal = 19; + } + $crossellingInstalled = $this->app->erp->ModulVorhanden('crossselling'); + foreach ($reta as $k => $ret) { + if (isset($ret['stueckliste'])) { + $stuecklistenmechanik = $ret['stueckliste']; + } + $ret['nummer'] = $this->app->DB->real_escape_string(trim($ret['nummer'])); + $articleid = null; + if ($k == 0) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $nummer, true); + if ($articleid) { + $variantevonorig = $this->app->DB->Select("SELECT variante_von FROM artikel WHERE id = '$articleid' AND variante = 1 LIMIT 1"); - if(!$variantevonorig) - { - $articleid = $this->app->DB->Select("SELECT id + if (!$variantevonorig) { + $articleid = $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(geloescht,0) = 0 AND nummer <> 'DEL' LIMIT 1"); - } - } - } - if((isset($ret['nummerintern']) && $ret['nummerintern'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummerintern']); - } - if(($ret['nummer'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummer']); - } - if(($ret['ean'] != '') && !$articleid) - { - $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['ean']); - } - if($articleid) - { - if(isset($ret['shoparticleid']) && $ret['shoparticleid'] != '' && trim($this->app->DB->real_escape_string($ret['shoparticleid'])) != '') - { - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND artikel = '$articleid' AND nummer = '".trim($this->app->DB->real_escape_string($ret['shoparticleid']))."' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, nummer, bezeichnung) - VALUES ('$articleid','$id','1','".trim($this->app->DB->real_escape_string($ret['shoparticleid']))."','SHOPID')"); - } - } - } - if(!$articleid && !$create) - { - continue; - } - if(!$articleid || !$nurneueartikel) - { - if($articleid) - { - $arr['id'] = $articleid; - $arr['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - }elseif($ret['nummer'] == '') - { - $arr['nummer'] = $this->app->erp->GetNextArtikelnummer('',1,$shopexportArr['projekt']); - } - /*if(isset($ret['nummer']) && $ret['nummer'] == '' && !is_null($variante_von)) - { - $ret['nummer'] = $_nummer.'-'.$ret['nummer']; - $arr['nummer'] = $ret['nummer']; - }*/ - if(isset($ret['stueckliste']) && empty($variante_von)){ - $arr['stueckliste'] = $ret['stueckliste']; - } - $arr['projekt'] = $shopexportArr['projekt']; - $arr['name_de'] = $ret['name']; - $arr['uebersicht_de'] = $ret['uebersicht_de'] ?? ''; - $arr['kurztext_de'] = $ret['kurztext_de'] ?? ''; - $arr['name_en'] = $ret['name_en']; - $arr['uebersicht_en'] = $ret['uebersicht_en'] ?? ''; - $arr['kurztext_en'] = $ret['kurztext_en'] ?? ''; - $arr['metakeywords_de'] = $ret['metakeywords_de'] ?? ''; - $arr['metakeywords_en'] = $ret['metakeywords_en'] ?? ''; - $arr['metatitle_de'] = $ret['metatitle_de'] ?? ''; - $arr['metatitle_en'] = $ret['metatitle_en'] ?? ''; - $arr['metadescription_de'] = $ret['metadescription_de'] ?? ''; - $arr['metadescription_en'] = $ret['metadescription_en'] ?? ''; - //$arr['anabregs_text'] = isset($ret['uebersicht_de'])?$ret['uebersicht_de']:''; - if(isset($ret['ean']) && $ret['ean'] != '') - { - $arr['ean'] = $ret['ean']; - } - if(isset($ret['gewicht']) && $ret['gewicht'] !== '') - { - $arr['gewicht'] = $ret['gewicht']; - } - if(isset($ret['laenge']) && $ret['laenge'] !== '') - { - $arr['laenge'] = $ret['laenge']; - } - if(isset($ret['hoehe']) && $ret['hoehe'] !== '') - { - $arr['hoehe'] = $ret['hoehe']; - } - if(isset($ret['breite']) && $ret['breite'] !== '') - { - $arr['breite'] = $ret['breite']; - } - - if(!$articleid){ - $arr['lagerartikel'] = 1; - } - if(true) - { - if(!empty($ret['umsatzsteuer'])){ - if(is_numeric($ret['umsatzsteuer'])){ - if($ret['umsatzsteuer'] == $steuersatz_normal) - { - $arr['umsatzsteuer'] = 'normal'; - }elseif($ret['umsatzsteuer'] == $steuersatz_ermaessigt) - { - $arr['umsatzsteuer'] = 'ermaessigt'; - } - }elseif(in_array($ret['umsatzsteuer'], array('normal', 'ermaessigt', 'befreit'))){ - $arr['umsatzsteuer'] = $ret['umsatzsteuer']; + } + } } - } - } + if ((isset($ret['nummerintern']) && $ret['nummerintern'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummerintern']); + } + if (($ret['nummer'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['nummer']); + } + if (($ret['ean'] != '') && !$articleid) { + $articleid = $this->app->erp->GetArticleIDFromShopnumber($id, $ret['ean']); + } + if ($articleid) { + if (isset($ret['shoparticleid']) && $ret['shoparticleid'] != '' && trim($this->app->DB->real_escape_string($ret['shoparticleid'])) != '') { + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND artikel = '$articleid' AND nummer = '" . trim($this->app->DB->real_escape_string($ret['shoparticleid'])) . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, nummer, bezeichnung) + VALUES ('$articleid','$id','1','" . trim($this->app->DB->real_escape_string($ret['shoparticleid'])) . "','SHOPID')"); + } + } + } + if (!$articleid && !$create) { + continue; + } + if (!$articleid || !$nurneueartikel) { + if ($articleid) { + $arr['id'] = $articleid; + $arr['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + } elseif ($ret['nummer'] == '') { + $arr['nummer'] = $this->app->erp->GetNextArtikelnummer('', 1, $shopexportArr['projekt']); + } + /* if(isset($ret['nummer']) && $ret['nummer'] == '' && !is_null($variante_von)) + { + $ret['nummer'] = $_nummer.'-'.$ret['nummer']; + $arr['nummer'] = $ret['nummer']; + } */ + if (isset($ret['stueckliste']) && empty($variante_von)) { + $arr['stueckliste'] = $ret['stueckliste']; + } + $arr['projekt'] = $shopexportArr['projekt']; + $arr['name_de'] = $ret['name']; + $arr['uebersicht_de'] = $ret['uebersicht_de'] ?? ''; + $arr['kurztext_de'] = $ret['kurztext_de'] ?? ''; + $arr['name_en'] = $ret['name_en']; + $arr['uebersicht_en'] = $ret['uebersicht_en'] ?? ''; + $arr['kurztext_en'] = $ret['kurztext_en'] ?? ''; + $arr['metakeywords_de'] = $ret['metakeywords_de'] ?? ''; + $arr['metakeywords_en'] = $ret['metakeywords_en'] ?? ''; + $arr['metatitle_de'] = $ret['metatitle_de'] ?? ''; + $arr['metatitle_en'] = $ret['metatitle_en'] ?? ''; + $arr['metadescription_de'] = $ret['metadescription_de'] ?? ''; + $arr['metadescription_en'] = $ret['metadescription_en'] ?? ''; + //$arr['anabregs_text'] = isset($ret['uebersicht_de'])?$ret['uebersicht_de']:''; + if (isset($ret['ean']) && $ret['ean'] != '') { + $arr['ean'] = $ret['ean']; + } + if (isset($ret['gewicht']) && $ret['gewicht'] !== '') { + $arr['gewicht'] = $ret['gewicht']; + } + if (isset($ret['laenge']) && $ret['laenge'] !== '') { + $arr['laenge'] = $ret['laenge']; + } + if (isset($ret['hoehe']) && $ret['hoehe'] !== '') { + $arr['hoehe'] = $ret['hoehe']; + } + if (isset($ret['breite']) && $ret['breite'] !== '') { + $arr['breite'] = $ret['breite']; + } - $arr['hersteller'] = $ret['hersteller']; - if(!$stuecklistenmechanik && isset($ret['variante_von']) && !$articleid){ - $variantevon = $this->app->DB->Select("SELECT artikel + if (!$articleid) { + $arr['lagerartikel'] = 1; + } + if (true) { + if (!empty($ret['umsatzsteuer'])) { + if (is_numeric($ret['umsatzsteuer'])) { + if ($ret['umsatzsteuer'] == $steuersatz_normal) { + $arr['umsatzsteuer'] = 'normal'; + } elseif ($ret['umsatzsteuer'] == $steuersatz_ermaessigt) { + $arr['umsatzsteuer'] = 'ermaessigt'; + } + } elseif (in_array($ret['umsatzsteuer'], array('normal', 'ermaessigt', 'befreit'))) { + $arr['umsatzsteuer'] = $ret['umsatzsteuer']; + } + } + } + + $arr['hersteller'] = $ret['hersteller']; + if (!$stuecklistenmechanik && isset($ret['variante_von']) && !$articleid) { + $variantevon = $this->app->DB->Select("SELECT artikel FROM `artikelnummer_fremdnummern` - WHERE shopid = '$id' AND aktiv = 1 AND nummer = '".trim($ret['variante_von'])."' AND nummer <> '' + WHERE shopid = '$id' AND aktiv = 1 AND nummer = '" . trim($ret['variante_von']) . "' AND nummer <> '' LIMIT 1"); - if(empty($variantevon)) - { - $variantevon = $this->app->DB->Select("SELECT id + if (empty($variantevon)) { + $variantevon = $this->app->DB->Select("SELECT id FROM artikel - WHERE ifnull(geloescht,0) = 0 AND nummer <> 'DEL' AND nummer <> '' AND nummer = '".trim($ret['variante_von'])."' + WHERE ifnull(geloescht,0) = 0 AND nummer <> 'DEL' AND nummer <> '' AND nummer = '" . trim($ret['variante_von']) . "' ORDER BY projekt = '$projekt' DESC LIMIT 1"); - } - if(empty($variantevon)) - { - $variantevon = $variantevonorig; - } - if(!empty($variantevon)) - { - $arr['variante'] = 1; - $arr['variante_von'] = $variantevon; - } - }elseif($variante_von) - { - if($variante_von) - { - $arr['variante'] = 1; - } - if($variante_von) - { - $arr['variante_von'] = $variante_von; - } - } - $freifeldmapping = $this->app->DB->SelectArr("SELECT * + } + if (empty($variantevon)) { + $variantevon = $variantevonorig; + } + if (!empty($variantevon)) { + $arr['variante'] = 1; + $arr['variante_von'] = $variantevon; + } + } elseif ($variante_von) { + if ($variante_von) { + $arr['variante'] = 1; + } + if ($variante_von) { + $arr['variante_von'] = $variante_von; + } + } + $freifeldmapping = $this->app->DB->SelectArr("SELECT * FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_shop <> '' AND freifeld_wawi <> ''"); - if(!empty($freifeldmapping)) - { - foreach($freifeldmapping as $freifeldval) - { - $freifeldShopKey = 'freifeld_'.$freifeldval['freifeld_shop']; - if(isset($ret[$freifeldShopKey])) - { - $arr[$freifeldval['freifeld_wawi']] = $ret[$freifeldShopKey]; - } - } - } - $articleid = $this->app->erp->InsertUpdateArtikel($arr); - unset($arr); - if($artikelnummerbeimanlegenausshop && !empty($ret['artikelnummerausshop'])) - { - $this->app->DB->Update("UPDATE artikel SET nummer = '".$ret['artikelnummerausshop']."' WHERE id = '$articleid'"); - } - - $ret['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - if(isset($ret['bilder']) && $ret['bilder'] && is_array($ret['bilder'])) - { - $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); - if(empty($dateien)) - { - foreach($ret['bilder'] as $v) - { - if($v['path'] != '' && $v['content'] != '') - { - $path_parts = pathinfo($v['path']); - $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); - file_put_contents($tmpfilename, base64_decode($v['content'])); - $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); - $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); - if (@is_file($tmpfilename)) - unlink($tmpfilename); - } - } - }elseif($dateien[0]['subjekt'] === 'shopbild'){ - $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = 'Shopbild' WHERE id = '".$dateien[0]['id']."' AND subjekt = 'shopbild' LIMIT 1"); - } - } - if($variante_von === null) - { - $variante_von = $articleid; - $_nummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); - $nummer = isset($ret['nummerintern'])?$ret['nummerintern']:(isset($ret['nummer'])?$ret['nummer']:''); - } - if(!empty($ret['preis_netto']) && $ret['preis_netto'] > 0) - { - $this->app->erp->AddVerkaufspreis($articleid,1,0,$ret['preis_netto']); - } - - if(!empty($ret['bilder']) && is_array($ret['bilder'])) - { - $dateien = $this->app->DB->SelectArr("SELECT * + if (!empty($freifeldmapping)) { + foreach ($freifeldmapping as $freifeldval) { + $freifeldShopKey = 'freifeld_' . $freifeldval['freifeld_shop']; + if (isset($ret[$freifeldShopKey])) { + $arr[$freifeldval['freifeld_wawi']] = $ret[$freifeldShopKey]; + } + } + } + $articleid = $this->app->erp->InsertUpdateArtikel($arr); + unset($arr); + if ($artikelnummerbeimanlegenausshop && !empty($ret['artikelnummerausshop'])) { + $this->app->DB->Update("UPDATE artikel SET nummer = '" . $ret['artikelnummerausshop'] . "' WHERE id = '$articleid'"); + } + + $ret['nummer'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + if (isset($ret['bilder']) && $ret['bilder'] && is_array($ret['bilder'])) { + $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); + if (empty($dateien)) { + foreach ($ret['bilder'] as $v) { + if ($v['path'] != '' && $v['content'] != '') { + $path_parts = pathinfo($v['path']); + $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); + file_put_contents($tmpfilename, base64_decode($v['content'])); + $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); + $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); + if (@is_file($tmpfilename)) + unlink($tmpfilename); + } + } + } elseif ($dateien[0]['subjekt'] === 'shopbild') { + $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = 'Shopbild' WHERE id = '" . $dateien[0]['id'] . "' AND subjekt = 'shopbild' LIMIT 1"); + } + } + if ($variante_von === null) { + $variante_von = $articleid; + $_nummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$articleid' LIMIT 1"); + $nummer = isset($ret['nummerintern']) ? $ret['nummerintern'] : (isset($ret['nummer']) ? $ret['nummer'] : ''); + } + if (!empty($ret['preis_netto']) && $ret['preis_netto'] > 0) { + $this->app->erp->AddVerkaufspreis($articleid, 1, 0, $ret['preis_netto']); + } + + if (!empty($ret['bilder']) && is_array($ret['bilder'])) { + $dateien = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter ds INNER JOIN datei_version dv ON ds.datei = dv.datei AND ds.parameter = '$articleid' AND ds.objekt LIKE 'Artikel' ORDER BY ds.sort"); - if(empty($dateien)) - { - foreach($ret['bilder'] as $v) - { - if($v['path'] != '' && $v['content'] != '') - { - $path_parts = pathinfo($v['path']); - $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); - file_put_contents($tmpfilename, base64_decode($v['content'])); - $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); - if(isset($v['id'])) - { - $this->ShopexportMappingSet($id, 'datei', $fileid, $v['id'], $articleid); + if (empty($dateien)) { + foreach ($ret['bilder'] as $v) { + if ($v['path'] != '' && $v['content'] != '') { + $path_parts = pathinfo($v['path']); + $tmpfilename = tempnam($this->app->erp->GetTMP(), 'img'); + file_put_contents($tmpfilename, base64_decode($v['content'])); + $fileid = $this->app->erp->CreateDatei($path_parts['basename'], 'Shopbild', '', '', $tmpfilename, 'Cronjob'); + if (isset($v['id'])) { + $this->ShopexportMappingSet($id, 'datei', $fileid, $v['id'], $articleid); + } + $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); + if (@is_file($tmpfilename)) + unlink($tmpfilename); + } + } + } } - $this->app->erp->AddDateiStichwort($fileid, 'Shopbild', 'artikel', $articleid); - if (@is_file($tmpfilename)) - unlink($tmpfilename); - } - } - } - } - if($crossellingInstalled){ - if(!empty($ret['crossselling'])){ - if(!empty($ret['crossselling']['similar'])){ - foreach ($ret['crossselling']['similar'] as $cskey => $csvalue) { - $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '".$csvalue."' and geloescht='0'"); - if($crosssellingartikel){ - if(!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")){ - $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); - $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','1','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); - } + if ($crossellingInstalled) { + if (!empty($ret['crossselling'])) { + if (!empty($ret['crossselling']['similar'])) { + foreach ($ret['crossselling']['similar'] as $cskey => $csvalue) { + $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '" . $csvalue . "' and geloescht='0'"); + if ($crosssellingartikel) { + if (!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")) { + $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); + $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','1','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); + } + } + } + } + if (!empty($ret['crossselling']['related'])) { + foreach ($ret['crossselling']['related'] as $cskey => $csvalue) { + $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '" . $csvalue . "' and geloescht='0'"); + if ($crosssellingartikel) { + if (!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")) { + $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); + $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','2','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); + } + } + } + } + } } - } - } - if(!empty($ret['crossselling']['related'])){ - foreach ($ret['crossselling']['related'] as $cskey => $csvalue) { - $crosssellingartikel = $this->app->DB->Select("SELECT id from artikel WHERE nummer= '".$csvalue."' and geloescht='0'"); - if($crosssellingartikel){ - if(!$this->app->DB->Select("SELECT id FROM crossselling_artikel WHERE artikel='$articleid' AND crosssellingartikel='$crosssellingartikel' AND shop='$id'")){ - $sort = $this->app->DB->Select("SELECT MAX(sort)+1 from crossselling_artikel WHERE artikel='$articleid' AND shop='$id'"); - $this->app->DB->Insert("INSERT INTO crossselling_artikel (aktiv, art, artikel, crosssellingartikel, shop, sort, bemerkung) VALUES ('1','2','$articleid','$crosssellingartikel','$id','$sort','Über Artikelimport hinzugefügt')"); - } - } - } - } - } - } - $katext = 0; - if(isset($ret['kategorien_all']) && $ret['kategorien_all']) - { - foreach($ret['kategorien_all'] as $v) - { - if($katext == 0 && $v['parent'] == 0) - { - $katext = $v['id']; - } - if(!$this->app->DB->Select("SELECT id + $katext = 0; + if (isset($ret['kategorien_all']) && $ret['kategorien_all']) { + foreach ($ret['kategorien_all'] as $v) { + if ($katext == 0 && $v['parent'] == 0) { + $katext = $v['id']; + } + if (!$this->app->DB->Select("SELECT id FROM shopexport_kategorien - WHERE shop = '$id' AND extid = '".$this->app->DB->real_escape_string($v['id'])."' LIMIT 1")){ - $this->app->DB->Insert("INSERT INTO shopexport_kategorien (shop, extid, aktiv,extname,extparent,extsort) VALUES - ('$id','" . $this->app->DB->real_escape_string($v['id']) . "','" . (int)$v['aktiv'] . "','" . $this->app->DB->real_escape_string($v['name']) . "','" . $this->app->DB->real_escape_string($v['parent']) . "','" . (int)$v['sort'] . "')"); - } - } - $shopkategorien = $this->getShopKatgeorien($id); - /** @var Onlineshops $onlineShopObj */ - $onlineShopObj = $this->app->loadModule('onlineshops'); - $categoryRootId = 0; - if(!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { - $categoryRootId = (int)$onlineShopObj->getJsonSettings($id, 'category_root_id'); - } - $kategorientoint = [$categoryRootId]; + WHERE shop = '$id' AND extid = '" . $this->app->DB->real_escape_string($v['id']) . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO shopexport_kategorien (shop, extid, aktiv,extname,extparent,extsort) VALUES + ('$id','" . $this->app->DB->real_escape_string($v['id']) . "','" . (int) $v['aktiv'] . "','" . $this->app->DB->real_escape_string($v['name']) . "','" . $this->app->DB->real_escape_string($v['parent']) . "','" . (int) $v['sort'] . "')"); + } + } + $shopkategorien = $this->getShopKatgeorien($id); + /** @var Onlineshops $onlineShopObj */ + $onlineShopObj = $this->app->loadModule('onlineshops'); + $categoryRootId = 0; + if (!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { + $categoryRootId = (int) $onlineShopObj->getJsonSettings($id, 'category_root_id'); + } + $kategorientoint = [$categoryRootId]; - if(!empty($shopkategorien)) - { - foreach($shopkategorien as $v) - { - if(!$v['kategorie']) - { - $parentInXentral = $kategorientoint[$v['extparent']]; - if(empty($parentInXentral)){ - $parentInXentral = $this->app->DB->Select("SELECT kategorie FROM shopexport_kategorien WHERE shop='$id' AND extid='".$v['extparent']."' LIMIT 1"); + if (!empty($shopkategorien)) { + foreach ($shopkategorien as $v) { + if (!$v['kategorie']) { + $parentInXentral = $kategorientoint[$v['extparent']]; + if (empty($parentInXentral)) { + $parentInXentral = $this->app->DB->Select("SELECT kategorie FROM shopexport_kategorien WHERE shop='$id' AND extid='" . $v['extparent'] . "' LIMIT 1"); + } + $this->app->DB->Insert("INSERT INTO `artikelkategorien` (bezeichnung,parent) + VALUES ('" . $this->app->DB->real_escape_string($v['extname']) . "','$parentInXentral')"); + $kategorientoint[$v['extid']] = $this->app->DB->GetInsertID(); + $this->app->DB->Update("UPDATE shopexport_kategorien + SET kategorie = '" . $kategorientoint[$v['extid']] . "' + WHERE id = '" . $v['id'] . "' LIMIT 1"); + $v['kategorie'] = $kategorientoint[$v['extid']]; + } + } + } } - $this->app->DB->Insert("INSERT INTO `artikelkategorien` (bezeichnung,parent) - VALUES ('".$this->app->DB->real_escape_string($v['extname'])."','$parentInXentral')"); - $kategorientoint[$v['extid']] = $this->app->DB->GetInsertID(); - $this->app->DB->Update("UPDATE shopexport_kategorien - SET kategorie = '".$kategorientoint[$v['extid']]."' - WHERE id = '".$v['id']."' LIMIT 1"); - $v['kategorie'] = $kategorientoint[$v['extid']]; - } - } - } - } - if(!empty($ret['kategorien'])) - { - $shopkategorien = $this->app->DB->SelectArr("SELECT * + if (!empty($ret['kategorien'])) { + $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$id' AND kategorie > 0 ORDER BY extparent, extsort"); - if(!empty($shopkategorien)) - { - foreach($shopkategorien as $v) - { - $kategorientoint[$v['extid']] = $v['kategorie']; - } - $kategoriezugewiesen = false; - foreach($ret['kategorien'] as $v) - { - if(!$kategoriezugewiesen){ - $kategorieid = $this->app->DB->Select("SELECT id FROM artikelkategorien WHERE bezeichnung='".$v['name']."' AND parent=0 AND geloescht=0 LIMIT 1"); - if($kategorieid){ - $this->app->DB->Update("UPDATE artikel SET typ = '".$kategorieid."_kat' WHERE id = '$articleid' LIMIT 1"); - $kategoriezugewiesen = true; - } - } + if (!empty($shopkategorien)) { + foreach ($shopkategorien as $v) { + $kategorientoint[$v['extid']] = $v['kategorie']; + } + $kategoriezugewiesen = false; + foreach ($ret['kategorien'] as $v) { + if (!$kategoriezugewiesen) { + $kategorieid = $this->app->DB->Select("SELECT id FROM artikelkategorien WHERE bezeichnung='" . $v['name'] . "' AND parent=0 AND geloescht=0 LIMIT 1"); + if ($kategorieid) { + $this->app->DB->Update("UPDATE artikel SET typ = '" . $kategorieid . "_kat' WHERE id = '$articleid' LIMIT 1"); + $kategoriezugewiesen = true; + } + } - if(isset($kategorientoint[$v['id']]) && $kategorientoint[$v['id']]) - { - if(!$this->app->DB->Select("SELECT id FROM artikelbaum_artikel WHERE artikel = '$articleid' AND kategorie = '".$kategorientoint[$v['id']]."' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO artikelbaum_artikel (artikel, kategorie) - VALUES ('$articleid', '".$kategorientoint[$v['id']]."')"); + if (isset($kategorientoint[$v['id']]) && $kategorientoint[$v['id']]) { + if (!$this->app->DB->Select("SELECT id FROM artikelbaum_artikel WHERE artikel = '$articleid' AND kategorie = '" . $kategorientoint[$v['id']] . "' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO artikelbaum_artikel (artikel, kategorie) + VALUES ('$articleid', '" . $kategorientoint[$v['id']] . "')"); + } + } + } + } } - } - } - } - } - if(!empty($ret['eigenschaften'])) - { - foreach($ret['eigenschaften'] as $v) - { - if($v['name'] != '') - { - $eigenschaft = $this->app->DB->Select("SELECT id + if (!empty($ret['eigenschaften'])) { + foreach ($ret['eigenschaften'] as $v) { + if ($v['name'] != '') { + $eigenschaft = $this->app->DB->Select("SELECT id FROM `artikeleigenschaften` - WHERE name = '".$this->app->DB->real_escape_string($v['name'])."' AND geloescht = 0 + WHERE name = '" . $this->app->DB->real_escape_string($v['name']) . "' AND geloescht = 0 LIMIT 1"); - if(!$eigenschaft) - { - $this->app->DB->Insert("INSERT INTO `artikeleigenschaften` (name) - VALUES ('".$this->app->DB->real_escape_string($v['name'])."')"); - $eigenschaft = $this->app->DB->GetInsertID(); - } - if($eigenschaft) - { - $wert = $this->app->DB->Select("SELECT id + if (!$eigenschaft) { + $this->app->DB->Insert("INSERT INTO `artikeleigenschaften` (name) + VALUES ('" . $this->app->DB->real_escape_string($v['name']) . "')"); + $eigenschaft = $this->app->DB->GetInsertID(); + } + if ($eigenschaft) { + $wert = $this->app->DB->Select("SELECT id FROM artikeleigenschaftenwerte - WHERE artikel = '$articleid' AND artikeleigenschaften = '$eigenschaft' AND wert = '".$this->app->DB->real_escape_string($v['values'])."' + WHERE artikel = '$articleid' AND artikeleigenschaften = '$eigenschaft' AND wert = '" . $this->app->DB->real_escape_string($v['values']) . "' LIMIT 1"); - if(!$wert) - { - $this->app->DB->Insert("INSERT INTO artikeleigenschaftenwerte (artikel,artikeleigenschaften,wert) - VALUES ('$articleid','$eigenschaft','".$this->app->DB->real_escape_string($v['values'])."')"); + if (!$wert) { + $this->app->DB->Insert("INSERT INTO artikeleigenschaftenwerte (artikel,artikeleigenschaften,wert) + VALUES ('$articleid','$eigenschaft','" . $this->app->DB->real_escape_string($v['values']) . "')"); + } + } + } + } } - } - } - } - } - if(!empty($ret['matrixprodukt_gruppe1'])){ - $query = sprintf("UPDATE artikel SET matrixprodukt=1 WHERE id='%s'",$articleid); - $this->app->DB->Update($query); - for($m=1;$m<=3;$m++){ - if(empty($ret['matrixprodukt_gruppe'.$m])){ - continue; - } + if (!empty($ret['matrixprodukt_gruppe1'])) { + $query = sprintf("UPDATE artikel SET matrixprodukt=1 WHERE id='%s'", $articleid); + $this->app->DB->Update($query); + for ($m = 1; $m <= 3; $m++) { + if (empty($ret['matrixprodukt_gruppe' . $m])) { + continue; + } - $gruppeName = $this->app->DB->real_escape_string($ret['matrixprodukt_gruppe'.$m]); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $gruppeName); - $gruppeId = $this->app->DB->Select($query); - if(empty($gruppeId)){ - $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $gruppeName); - $sort = $this->app->DB->Select($query); - if(empty($sort)){ - $sort = '0'; - } - $query = sprintf("INSERT INTO matrixprodukt_eigenschaftengruppen_artikel + $gruppeName = $this->app->DB->real_escape_string($ret['matrixprodukt_gruppe' . $m]); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $gruppeName); + $gruppeId = $this->app->DB->Select($query); + if (empty($gruppeId)) { + $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftengruppen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $gruppeName); + $sort = $this->app->DB->Select($query); + if (empty($sort)) { + $sort = '0'; + } + $query = sprintf("INSERT INTO matrixprodukt_eigenschaftengruppen_artikel (artikel, aktiv, name, name_ext,projekt,bearbeiter,erstellt,sort, pflicht, oeffentlich,typ) VALUES ('%s','1','%s','','0','','NOW()','%s','1','0','0')", $articleid, $gruppeName, $sort); - $this->app->DB->Insert($query); - $gruppeId = $this->app->DB->GetInsertID(); - } + $this->app->DB->Insert($query); + $gruppeId = $this->app->DB->GetInsertID(); + } - foreach ($ret['matrixprodukt_optionen'.$m] as $optionBezeichnung){ - $optionBezeichnung = $this->app->DB->real_escape_string($optionBezeichnung); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $optionBezeichnung); - $optionId = $this->app->DB->Select($query); - if(empty($optionId)){ - $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $articleid, $optionBezeichnung); - $sort = $this->app->DB->Select($query); - if(empty($sort)){ - $sort = '1'; - } - $query = sprintf("INSERT INTO matrixprodukt_eigenschaftenoptionen_artikel + foreach ($ret['matrixprodukt_optionen' . $m] as $optionBezeichnung) { + $optionBezeichnung = $this->app->DB->real_escape_string($optionBezeichnung); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $optionBezeichnung); + $optionId = $this->app->DB->Select($query); + if (empty($optionId)) { + $query = sprintf("SELECT MAX(sort) FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $articleid, $optionBezeichnung); + $sort = $this->app->DB->Select($query); + if (empty($sort)) { + $sort = '1'; + } + $query = sprintf("INSERT INTO matrixprodukt_eigenschaftenoptionen_artikel (artikel, matrixprodukt_eigenschaftenoptionen, aktiv,name,name_ext,sort,erstellt,gruppe,bearbeiter,artikelnummer) VALUES ('%s','0','1','%s','','%s','NOW()','%s','','')", - $articleid, $optionBezeichnung, $sort, $gruppeId); - $this->app->DB->Insert($query); - } - } - } - } + $articleid, $optionBezeichnung, $sort, $gruppeId); + $this->app->DB->Insert($query); + } + } + } + } - if(!empty($ret['matrixprodukt_wert1'])){ - for($m=1;$m<=3;$m++){ - if(empty($ret['matrixprodukt_wert'.$m])){ - continue; + if (!empty($ret['matrixprodukt_wert1'])) { + for ($m = 1; $m <= 3; $m++) { + if (empty($ret['matrixprodukt_wert' . $m])) { + continue; + } + + $optionBezeichnung = $this->app->DB->real_escape_string($ret['matrixprodukt_wert' . $m]); + $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", + $variante_von, $optionBezeichnung); + $optionId = $this->app->DB->Select($query); + if (!empty($optionId)) { + $query = sprintf("SELECT id FROM matrixprodukt_optionen_zu_artikel WHERE artikel='%s' AND option_id='%s'", + $articleid, $optionId); + $zuordnungId = $this->app->DB->Select($query); + if (empty($zuordnungId)) { + $query = sprintf("INSERT INTO matrixprodukt_optionen_zu_artikel (artikel,option_id) VALUES ('%s','%s')", + $articleid, $optionId); + $this->app->DB->Insert($query); + } + } + } + } + + if (!$this->app->DB->Select("SELECT id FROM `artikel_onlineshops` WHERE artikel = '$articleid' AND shop = '$id' AND aktiv = 1 LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikel_onlineshops` (artikel, shop,aktiv, ausartikel) VALUES ('$articleid', '$id',1 ,1)"); + } + if (isset($ret['nummerintern']) && trim($ret['nummerintern']) != '') { + $data['nummerintern'] = trim($ret['nummerintern']); + } + if (($ret['nummer'] != $data['nummerintern']) && $data['nummerintern'] != '' && trim($data['nummerintern']) != '') { + $data['nummerintern'] = trim($data['nummerintern']); + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$articleid' AND shopid = '$id' AND nummer = '" . $this->app->DB->real_escape_string($data['nummerintern']) . "' AND nummer <> '' LIMIT 1")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, bearbeiter, zeitstempel,nummer) VALUES ('$articleid','$id','1','Cronjob',now(),'" . $this->app->DB->real_escape_string($data['nummerintern']) . "')"); + } + } + } elseif ($articleid) { + if (isset($ret['ean']) && ($ret['ean'] != '') && $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1")) { + $this->app->DB->Update("UPDATE artikel SET ean = '" . $this->app->DB->real_escape_string($ret['ean']) . "' WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1"); + } } - $optionBezeichnung = $this->app->DB->real_escape_string($ret['matrixprodukt_wert'.$m]); - $query = sprintf("SELECT id FROM matrixprodukt_eigenschaftenoptionen_artikel WHERE artikel='%s' AND name='%s'", - $variante_von, $optionBezeichnung); - $optionId = $this->app->DB->Select($query); - if(!empty($optionId)){ - $query = sprintf("SELECT id FROM matrixprodukt_optionen_zu_artikel WHERE artikel='%s' AND option_id='%s'", - $articleid, $optionId); - $zuordnungId = $this->app->DB->Select($query); - if(empty($zuordnungId)){ - $query = sprintf("INSERT INTO matrixprodukt_optionen_zu_artikel (artikel,option_id) VALUES ('%s','%s')", - $articleid,$optionId); - $this->app->DB->Insert($query); - } - } - } - } - - if(!$this->app->DB->Select("SELECT id FROM `artikel_onlineshops` WHERE artikel = '$articleid' AND shop = '$id' AND aktiv = 1 LIMIT 1")) { - $this->app->DB->Insert("INSERT INTO `artikel_onlineshops` (artikel, shop,aktiv, ausartikel) VALUES ('$articleid', '$id',1 ,1)"); - } - if(isset($ret['nummerintern']) && trim($ret['nummerintern']) != '') - { - $data['nummerintern'] = trim($ret['nummerintern']); - } - if(($ret['nummer'] != $data['nummerintern']) && $data['nummerintern'] != '' && trim($data['nummerintern']) != '') - { - $data['nummerintern'] = trim($data['nummerintern']); - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$articleid' AND shopid = '$id' AND nummer = '".$this->app->DB->real_escape_string($data['nummerintern'])."' AND nummer <> '' LIMIT 1")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, shopid, aktiv, bearbeiter, zeitstempel,nummer) VALUES ('$articleid','$id','1','Cronjob',now(),'".$this->app->DB->real_escape_string($data['nummerintern'])."')"); - } - } - }elseif($articleid) - { - if(isset($ret['ean']) && ($ret['ean'] != '') && $this->app->DB->Select("SELECT id FROM artikel WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1")) - { - $this->app->DB->Update("UPDATE artikel SET ean = '".$this->app->DB->real_escape_string($ret['ean'])."' WHERE id = '$articleid' AND ifnull(ean,'') = '' LIMIT 1"); - } - } - - if($stuecklistenmechanik && !empty($variante_von) && !$this->app->erp->IstStuecklistenZirkel($articleid,$variante_von)){ - $stuecklistenmenge = 1; - if(!empty($ret['stuecklistemenge'])){ - $stuecklistenmenge = $ret['stuecklistemenge']; - } - $query = sprintf('SELECT MAX(sort) FROM stueckliste WHERE stuecklistevonartikel=%d',$variante_von); - $sort = $this->app->DB->Select($query); - if($sort !== NULL){ - $sort++; - }else{ - $sort = 0; - } - $query = sprintf("INSERT INTO stueckliste (sort, artikel, referenz, place, layer, stuecklistevonartikel, + if ($stuecklistenmechanik && !empty($variante_von) && !$this->app->erp->IstStuecklistenZirkel($articleid, $variante_von)) { + $stuecklistenmenge = 1; + if (!empty($ret['stuecklistemenge'])) { + $stuecklistenmenge = $ret['stuecklistemenge']; + } + $query = sprintf('SELECT MAX(sort) FROM stueckliste WHERE stuecklistevonartikel=%d', $variante_von); + $sort = $this->app->DB->Select($query); + if ($sort !== NULL) { + $sort++; + } else { + $sort = 0; + } + $query = sprintf("INSERT INTO stueckliste (sort, artikel, referenz, place, layer, stuecklistevonartikel, menge, firma, wert, bauform, alternative, zachse, xpos, ypos, art) VALUES (%d, %d, '', 'DP', 'Top', %d, %d, 1, '', '', 0, '', '', '', 'et')", - $sort,$articleid,$variante_von,$stuecklistenmenge); - $this->app->DB->Insert($query); - } - - if($variante_von === null) { - if(!empty($articleid) && $stuecklistenmechanik){ - $query = sprintf('DELETE FROM stueckliste WHERE stuecklistevonartikel=%d',$articleid); - $this->app->DB->Delete($query); - } - $variante_von = $articleid; - } - - if(isset($ret['inaktiv'])){ - $ret['aktiv'] = !$ret['inaktiv']; - } - - if(isset($ret['aktiv'])) - { - if($ret['aktiv']){ - $this->app->DB->Update("UPDATE artikel SET inaktiv = '0' WHERE id = '$articleid' LIMIT 1"); - }else{ - $this->app->DB->Update("UPDATE artikel SET inaktiv = '1' WHERE id = '$articleid' LIMIT 1"); - } - } - if(isset($ret['staffelpreise'])){ - $date = new DateTime(); - $date->sub(new DateInterval('P1D')); - $gestern = $date->format('Y-m-d'); - $this->app->DB->Update("UPDATE verkaufspreise SET gueltig_bis='$gestern' WHERE artikel='$articleid' AND adresse='0' AND art='Kunde'"); - - foreach ($ret['staffelpreise'] as $staffelpreis){ - $preis = $staffelpreis['preis']; - if($staffelpreis['brutto']){ - $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$articleid' LIMIT 1"); - $steuersatz = 0; - if($umsatzsteuer === 'ermaessigt') - { - $steuersatz = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + $sort, $articleid, $variante_von, $stuecklistenmenge); + $this->app->DB->Insert($query); } - if($umsatzsteuer === 'normal'){ - $steuersatz = $this->app->erp->Firmendaten('steuersatz_normal'); - } - $preis /= 1+$steuersatz/100; - } - $this->app->erp->AddVerkaufspreis($articleid,$staffelpreis['ab_menge'],0,$preis); - } - } - if(isset($ret['fremdnummern']) && !empty($ret['fremdnummern'])){ - foreach ($ret['fremdnummern'] as $fremdnummer){ - $query = sprintf("SELECT id FROM artikelnummer_fremdnummern WHERE shopid=%d AND nummer='%s' AND bezeichnung='%s' AND aktiv=%d AND artikel=%s", - $id,$this->app->DB->real_escape_string($fremdnummer['nummer']),$this->app->DB->real_escape_string($fremdnummer['bezeichnung']),'1',$articleid); - $fremdnummerfehlt = empty($this->app->DB->Select($query)); - if($fremdnummerfehlt){ - $query = sprintf("INSERT INTO artikelnummer_fremdnummern + if ($variante_von === null) { + if (!empty($articleid) && $stuecklistenmechanik) { + $query = sprintf('DELETE FROM stueckliste WHERE stuecklistevonartikel=%d', $articleid); + $this->app->DB->Delete($query); + } + $variante_von = $articleid; + } + + if (isset($ret['inaktiv'])) { + $ret['aktiv'] = !$ret['inaktiv']; + } + + if (isset($ret['aktiv'])) { + if ($ret['aktiv']) { + $this->app->DB->Update("UPDATE artikel SET inaktiv = '0' WHERE id = '$articleid' LIMIT 1"); + } else { + $this->app->DB->Update("UPDATE artikel SET inaktiv = '1' WHERE id = '$articleid' LIMIT 1"); + } + } + if (isset($ret['staffelpreise'])) { + $date = new DateTime(); + $date->sub(new DateInterval('P1D')); + $gestern = $date->format('Y-m-d'); + $this->app->DB->Update("UPDATE verkaufspreise SET gueltig_bis='$gestern' WHERE artikel='$articleid' AND adresse='0' AND art='Kunde'"); + + foreach ($ret['staffelpreise'] as $staffelpreis) { + $preis = $staffelpreis['preis']; + if ($staffelpreis['brutto']) { + $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$articleid' LIMIT 1"); + $steuersatz = 0; + if ($umsatzsteuer === 'ermaessigt') { + $steuersatz = $this->app->erp->Firmendaten('steuersatz_ermaessigt'); + } + if ($umsatzsteuer === 'normal') { + $steuersatz = $this->app->erp->Firmendaten('steuersatz_normal'); + } + $preis /= 1 + $steuersatz / 100; + } + $this->app->erp->AddVerkaufspreis($articleid, $staffelpreis['ab_menge'], 0, $preis); + } + } + if (isset($ret['fremdnummern']) && !empty($ret['fremdnummern'])) { + foreach ($ret['fremdnummern'] as $fremdnummer) { + $query = sprintf("SELECT id FROM artikelnummer_fremdnummern WHERE shopid=%d AND nummer='%s' AND bezeichnung='%s' AND aktiv=%d AND artikel=%s", + $id, $this->app->DB->real_escape_string($fremdnummer['nummer']), $this->app->DB->real_escape_string($fremdnummer['bezeichnung']), '1', $articleid); + $fremdnummerfehlt = empty($this->app->DB->Select($query)); + + if ($fremdnummerfehlt) { + $query = sprintf("INSERT INTO artikelnummer_fremdnummern (artikel, bezeichnung, nummer, shopid, bearbeiter, aktiv) VALUES (%d,'%s','%s',%d,'%s',%d)", - $articleid,$this->app->DB->real_escape_string($fremdnummer['bezeichnung']), - $this->app->DB->real_escape_string($fremdnummer['nummer']),$id,$this->app->User->GetName(),1); - $this->app->DB->Insert($query); - } - } - } + $articleid, $this->app->DB->real_escape_string($fremdnummer['bezeichnung']), + $this->app->DB->real_escape_string($fremdnummer['nummer']), $id, $this->app->User->GetName(), 1); + $this->app->DB->Insert($query); + } + } + } + + if (isset($ret['pseudopreis'])) { + $this->app->DB->Update(sprintf("UPDATE artikel SET pseudopreis='%s' WHERE id=%d", $ret['pseudopreis'], $articleid)); + } + if (!$create) { + return $ret; + } + } - if(isset($ret['pseudopreis'])){ - $this->app->DB->Update(sprintf("UPDATE artikel SET pseudopreis='%s' WHERE id=%d",$ret['pseudopreis'],$articleid)); - } - if(!$create) - { return $ret; - } } - return $ret; - } - - /** - * @param int $shopId - * @param int $parent - * @param int $lvl - * - * @return array - */ - protected function getShopKatgeorien($shopId, $parent = 0, $lvl = 0) - { - if($lvl > 20) - { - return []; - } - $ret = []; - $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$shopId' AND extparent = '$parent' AND extid <> '' ORDER BY extsort"); - if($shopkategorien) - { - foreach($shopkategorien as $v) - { - $ret[] = $v; - $subkategorien = $this->getShopKatgeorien($shopId, $v['extid'], $lvl + 1); - if(!empty($subkategorien)) - { - foreach($subkategorien as $v2) - { - $ret[] = $v2; - } + /** + * @param int $shopId + * @param int $parent + * @param int $lvl + * + * @return array + */ + protected function getShopKatgeorien($shopId, $parent = 0, $lvl = 0) { + if ($lvl > 20) { + return []; } - } - } - - return $ret; - } - - /** - * @param int $id - * @param array $artikel_arr - * @param string|array $extnummer - * @param bool $nurlager - * - * @return mixed|null - * @throws Exception - */ - public function RemoteSendArticleList($id,$artikel_arr, $extnummer = '', $nurlager = false) - { - if(!class_exists('ObjGenArtikel') && - is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')){ - include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; - } - $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - $artikelexport = $shopexportarr['artikelexport']; - - $loadElements = [ - 'foreign_numbers' => true, - 'article_descriptions' => true, - 'translations' => true, - 'categories' => true, - 'properties' => true, - 'pictures' => true, - 'cross_selling' => true, - 'bulk_prices' => true, - 'standard_price' => true, - 'variants' => true, - 'free_fields' => true, - ]; - - if( - ($nurlager || empty($artikelexport)) - && !empty($shopexportarr['modulename']) - && !is_file(dirname(__DIR__).'/pages/'.$shopexportarr['modulename'].'_custom.php') - ) { - $elementsNotNeededByModule = ShopimporterBase::storageNotNeededElements($shopexportarr['modulename']); - foreach($elementsNotNeededByModule as $element) { - $loadElements[$element] = false; - } - } - - //$lagerexport = $shopexportarr['lagerexport']; - $lagergrundlage = $shopexportarr['lagergrundlage']; - $shopbilderuebertragen = $shopexportarr['shopbilderuebertragen']; - $projekt = (int)$shopexportarr['projekt']; - $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = $projekt AND projektlager = 1 LIMIT 1"); - $tmp = new ObjGenArtikel($this->app); - $cartikel_arr = !empty($artikel_arr)?count($artikel_arr):0; - - for($i=0;$i<$cartikel_arr;$i++) - { - - $artikel = $artikel_arr[$i]; - $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); - $tmp->Select($artikel); - $data[$i] = ['artikel' => $artikel,'artikelid' => $artikel]; - $data[$i]['nummer'] = $tmp->GetNummer(); - $projekt = $tmp->GetProjekt(); - if(is_array($extnummer) && (!empty($extnummer)?count($extnummer):0) > $i && !empty($extnummer[$i]) && trim($extnummer[$i]) != '') - { - if($data[$i]['nummer'] != trim($extnummer[$i])){ - $data[$i]['fremdnummer'] = trim($extnummer[$i]); - } - } - - $data[$i]['inaktiv'] = $tmp->GetInaktiv(); - - if($tmp->GetIntern_Gesperrt()=='1'){ - $data[$i]['inaktiv'] = 1; - } - - $data[$i]['name_de'] = $tmp->GetName_De(); - $data[$i]['name_en'] = $tmp->GetName_En(); - $data[$i]['einheit'] = $tmp->GetEinheit(); - $data[$i]['hersteller'] = $tmp->GetHersteller(); - $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); - $data[$i]['ean'] = $tmp->GetEan(); - if(!empty($loadElements['foreign_numbers'])) { - $data[$i]['artikelnummer_fremdnummern'] = $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $tmp->GetId() . "' AND shopid = '$id' AND aktiv = '1' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC"); - if(!empty($data[$i]['artikelnummer_fremdnummern'])){ - foreach ($data[$i]['artikelnummer_fremdnummern'] as $fkey => $fval) { - $data[$i]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); - } - } - } - - if(!empty($loadElements['article_descriptions'])) { - $data[$i]['kurztext_de'] = $tmp->GetKurztext_De(); - $data[$i]['kurztext_en'] = $tmp->GetKurztext_En(); - $data[$i]['anabregs_text'] = htmlspecialchars($tmp->GetAnabregs_Text(),ENT_QUOTES); - $data[$i]['anabregs_text_en'] = htmlspecialchars($tmp->GetAnabregs_Text_En(),ENT_QUOTES); - $data[$i]['beschreibung_de'] = $tmp->GetBeschreibung_De(); - $data[$i]['beschreibung_en'] = $tmp->GetBeschreibung_En(); - $data[$i]['uebersicht_de'] = htmlspecialchars($tmp->GetUebersicht_De(),ENT_QUOTES); - $data[$i]['uebersicht_en'] = htmlspecialchars($tmp->GetUebersicht_En(),ENT_QUOTES); - $data[$i]['herkunftsland'] = $tmp->GetHerkunftsland(); - - $data[$i]['texteuebertragen'] = $shopexportarr['texteuebertragen']; - - if(method_exists($tmp,'GetMetadescription_De')) - { - $data[$i]['metadescription_de'] = $tmp->GetMetadescription_De(); - } - if(method_exists($tmp,'GetMetadescription_En')) - { - $data[$i]['metadescription_en'] = $tmp->GetMetadescription_En(); - } - if(method_exists($tmp,'GetMetakeywords_De')) - { - $data[$i]['metakeywords_de'] = $tmp->GetMetakeywords_De(); - } - if(method_exists($tmp,'GetMetakeywords_En')) - { - $data[$i]['metakeywords_en'] = $tmp->GetMetakeywords_En(); - } - if(method_exists($tmp,'GetMetatitle_De')) - { - $data[$i]['metatitle_de'] = $tmp->GetMetatitle_De(); - } - if(method_exists($tmp,'GetMetatitle_En')) - { - $data[$i]['metatitle_en'] = $tmp->GetMetatitle_En(); - } - } - if($tmp->GetVariante()) - { - $variante_von = $tmp->GetVariante_Von(); - if($variante_von) - { - $tmp_2 = new ObjGenArtikel($this->app); - $tmp_2->Select($variante_von); - if($data[$i]['kurztext_de'] == '') - { - $data[$i]['kurztext_de'] = $tmp_2->GetKurztext_De(); - } - if($data[$i]['kurztext_en'] == '') - { - $data[$i]['kurztext_en'] = $tmp_2->GetKurztext_En(); - } - if($data[$i]['beschreibung_de'] == '') - { - $data[$i]['beschreibung_de'] = $tmp_2->GetBeschreibung_De(); - } - if($data[$i]['beschreibung_en'] == '') - { - $data[$i]['beschreibung_en'] = $tmp_2->GetBeschreibung_En(); - } - if($data[$i]['uebersicht_de'] == '') - { - $data[$i]['uebersicht_de'] = htmlspecialchars($tmp_2->GetUebersicht_De(),ENT_QUOTES); - } - if($data[$i]['uebersicht_en'] == '') - { - $data[$i]['uebersicht_en'] = htmlspecialchars($tmp_2->GetUebersicht_En(),ENT_QUOTES); - } - } - } - - if($data[$i]['uebersicht_de'] == '' && $data[$i]['beschreibung_de'] == '' && $data[$i]['kurztext_de'] == '') - { - $data[$i]['uebersicht_de'] = $data[$i]['anabregs_text']; - } - - $data[$i]['links_de'] = $tmp->GetLinks_De(); - $data[$i]['altersfreigabe'] = $tmp->GetAltersfreigabe(); - $data[$i]['links_en'] = $tmp->GetLinks_En(); - $data[$i]['startseite_de'] = $tmp->GetStartseite_De(); - $data[$i]['startseite_en'] = $tmp->GetStartseite_En(); - $data[$i]['restmenge'] = $this->app->erp->GetArtikelShopEinstellung('restmenge', $artikel, $shopexportarr); - $data[$i]['startseite'] = $tmp->GetStartseite(); - $data[$i]['standardbild'] = $tmp->GetStandardbild(); - $data[$i]['herstellerlink'] = $tmp->GetHerstellerlink(); - $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); - $data[$i]['hersteller'] = $tmp->GetHersteller(); - $data[$i]['lieferzeit'] = $tmp->GetLieferzeit(); - $data[$i]['lieferzeitmanuell'] = $this->app->erp->GetArtikelShopEinstellung('lieferzeitmanuell', $artikel, $shopexportarr); - $data[$i]['gewicht'] = $tmp->GetGewicht(); - $data[$i]['laenge'] = $tmp->GetLaenge(); - $data[$i]['breite'] = $tmp->GetBreite(); - $data[$i]['hoehe'] = $tmp->GetHoehe(); - - $data[$i]['wichtig'] = $tmp->GetWichtig(); - $data[$i]['porto'] = $tmp->GetPorto(); - $data[$i]['gesperrt'] = $tmp->GetGesperrt(); - $data[$i]['sperrgrund'] = $tmp->GetSperrgrund(); - $data[$i]['gueltigbis'] = $tmp->GetGueltigbis(); - $data[$i]['umsatzsteuer'] = $tmp->GetUmsatzsteuer(); - if($data[$i]['umsatzsteuer']!=='ermaessigt' && $data[$i]['umsatzsteuer']!=='befreit') { - $data[$i]['umsatzsteuer']="normal"; - } - $data[$i]['ausverkauft'] = $tmp->GetAusverkauft(); - $data[$i]['variante'] = $tmp->GetVariante(); - $data[$i]['variante_von_id'] = $tmp->GetVariante_Von(); - $data[$i]['variantevon'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id='".$tmp->GetVariante_Von()."' LIMIT 1"); - $data[$i]['variantevon_fremdnummer'] = trim($this->app->DB->Select("SELECT nummer FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND aktiv = 1 AND artikel = '".$tmp->GetVariante_Von()."' AND trim(nummer) <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1")); - if($data[$i]['variantevon_fremdnummer'] == '') - { - unset($data[$i]['variantevon_fremdnummer']); - } - //$data[$i]['pseudopreis'] = $tmp->GetPseudopreis(); - $data[$i]['pseudopreis'] = $this->app->erp->GetArtikelShopEinstellung('pseudopreis', $artikel, $shopexportarr); - $data[$i]['keinrabatterlaubt'] = $tmp->GetKeinrabatterlaubt(); - $data[$i]['einkaufspreis'] = $this->app->erp->GetEinkaufspreis($artikel,1); - //$data[$i]['pseudolager'] = $tmp->GetPseudolager(); - $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); - if(is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { - $data[$i]['pseudolager'] = 0; - } - $data[$i]['downloadartikel'] = $tmp->GetDownloadartikel(); - $data[$i]['zolltarifnummer'] = $tmp->GetZolltarifnummer(); - $preisgruppe = $this->app->DB->Select("SELECT s.preisgruppe FROM shopexport s INNER JOIN gruppen g ON s.preisgruppe = g.id AND g.aktiv = 1 WHERE s.id='$id' LIMIT 1"); - - if(empty($loadElements['free_fields'])) { - $freifelder = null; - } - else{ - $freifelder = $this->app->DB->SelectArr("SELECT freifeld_wawi, freifeld_shop FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_wawi <> '' AND freifeld_shop <> ''"); - } - if($freifelder) - { - /** - * @deprecated 20.1 - * AP - * Konstrunktion 'freifeld_Mappingname -> Wert' wird ersetzt durch 'Freifelder-> DE -> Mappingname -> Wert' - */ - foreach($freifelder as $freifeld) - { - if(method_exists($tmp,'Get'.ucfirst($freifeld['freifeld_wawi']))) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - $data[$i]['freifeld_'.$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); - } - } - /** - * @deprecated Ende - */ - - foreach($freifelder as $freifeld) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - if(method_exists($tmp,$_funktionsname)) - { - $data[$i]['freifelder']['DE'][$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); - } - } - - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '$artikel' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if(!empty($freifelduebersetzungen)){ - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } - - $data[$i]['typ'] = $tmp->GetTyp(); - $data[$i]['kategoriename'] = $tmp->GetTyp(); - if(strpos($data[$i]['typ'], '_kat')) - { - $data[$i]['kategoriename'] = $this->app->DB->Select("SELECT bezeichnung FROM artikelkategorien WHERE id = '".(int)str_replace('_kat','',$data[$i]['typ'])."' LIMIT 1"); - } - - $kategorienuebertragen = $shopexportarr['kategorienuebertragen'];//$this->app->DB->Select("SELECT kategorienuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); - if(!empty($kategorienuebertragen) && !empty($loadElements['categories'])) - { - $kategorienbaum = null; - /** @var Onlineshops $onlineShopObj */ - $onlineShopObj = $this->app->loadModule('onlineshops'); - $categoryRootId = 0; - if(!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { - $categoryRootId = (int)$onlineShopObj->getJsonSettings($id, 'category_root_id'); - } - $this->app->erp->GetKategorienbaum($kategorienbaum, $categoryRootId, 0, $id); - if(!empty($kategorienbaum)) - { - $kategorien = $this->app->DB->SelectArr("SELECT ak.id, ak.bezeichnung FROM `artikelbaum_artikel` aa INNER JOIN `artikelkategorien` ak ON aa.kategorie = ak.id AND ak.geloescht <> 1 AND aa.artikel = '$artikel' ORDER by ak.bezeichnung"); - if($kategorien) - { - foreach($kategorien as $v) - { - $katid[$v['id']] = true; + $ret = []; + $shopkategorien = $this->app->DB->SelectArr("SELECT * FROM shopexport_kategorien WHERE shop = '$shopId' AND extparent = '$parent' AND extid <> '' ORDER BY extsort"); + if ($shopkategorien) { + foreach ($shopkategorien as $v) { + $ret[] = $v; + $subkategorien = $this->getShopKatgeorien($shopId, $v['extid'], $lvl + 1); + if (!empty($subkategorien)) { + foreach ($subkategorien as $v2) { + $ret[] = $v2; + } + } } - } - if(!empty($katid)) - { - foreach($kategorienbaum as $v) - { - $data[$i]['kompletter_kategorienbaum'][] = array('name'=>$v['bezeichnung'],'parent'=>$v['parent'],'id'=>$v['id'],'lvl'=>$v['lvl'],'extid'=>$v['extid']); - if(isset($katid[$v['id']])) - { - $data[$i]['kategorien'][] = array('name'=>$v['bezeichnung'],'parent'=>$v['parent'],'id'=>$v['id'],'lvl'=>$v['lvl'],'extid'=>$v['extid']); - } - } - } } - } - $eigenschaftenuebertragen = $shopexportarr['eigenschaftenuebertragen'];//$this->app->DB->Select("SELECT eigenschaftenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); - if(!empty($eigenschaftenuebertragen) && !empty($loadElements['properties'])) { - $eigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften + return $ret; + } + + /** + * @param int $id + * @param array $artikel_arr + * @param string|array $extnummer + * @param bool $nurlager + * + * @return mixed|null + * @throws Exception + */ + public function RemoteSendArticleList($id, $artikel_arr, $extnummer = '', $nurlager = false) { + if (!class_exists('ObjGenArtikel') && + is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')) { + include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; + } + $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + $artikelexport = $shopexportarr['artikelexport']; + + $loadElements = [ + 'foreign_numbers' => true, + 'article_descriptions' => true, + 'translations' => true, + 'categories' => true, + 'properties' => true, + 'pictures' => true, + 'cross_selling' => true, + 'bulk_prices' => true, + 'standard_price' => true, + 'variants' => true, + 'free_fields' => true, + ]; + + if ( + ($nurlager || empty($artikelexport)) && !empty($shopexportarr['modulename']) && !is_file(dirname(__DIR__) . '/pages/' . $shopexportarr['modulename'] . '_custom.php') + ) { + $elementsNotNeededByModule = ShopimporterBase::storageNotNeededElements($shopexportarr['modulename']); + foreach ($elementsNotNeededByModule as $element) { + $loadElements[$element] = false; + } + } + + //$lagerexport = $shopexportarr['lagerexport']; + $lagergrundlage = $shopexportarr['lagergrundlage']; + $shopbilderuebertragen = $shopexportarr['shopbilderuebertragen']; + $projekt = (int) $shopexportarr['projekt']; + $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = $projekt AND projektlager = 1 LIMIT 1"); + $tmp = new ObjGenArtikel($this->app); + $cartikel_arr = !empty($artikel_arr) ? count($artikel_arr) : 0; + + for ($i = 0; $i < $cartikel_arr; $i++) { + + $artikel = $artikel_arr[$i]; + $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); + $tmp->Select($artikel); + $data[$i] = ['artikel' => $artikel, 'artikelid' => $artikel]; + $data[$i]['nummer'] = $tmp->GetNummer(); + $projekt = $tmp->GetProjekt(); + if (is_array($extnummer) && (!empty($extnummer) ? count($extnummer) : 0) > $i && !empty($extnummer[$i]) && trim($extnummer[$i]) != '') { + if ($data[$i]['nummer'] != trim($extnummer[$i])) { + $data[$i]['fremdnummer'] = trim($extnummer[$i]); + } + } + + $data[$i]['inaktiv'] = $tmp->GetInaktiv(); + + if ($tmp->GetIntern_Gesperrt() == '1') { + $data[$i]['inaktiv'] = 1; + } + + $data[$i]['name_de'] = $tmp->GetName_De(); + $data[$i]['name_en'] = $tmp->GetName_En(); + $data[$i]['einheit'] = $tmp->GetEinheit(); + $data[$i]['hersteller'] = $tmp->GetHersteller(); + $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); + $data[$i]['ean'] = $tmp->GetEan(); + if (!empty($loadElements['foreign_numbers'])) { + $data[$i]['artikelnummer_fremdnummern'] = $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $tmp->GetId() . "' AND shopid = '$id' AND aktiv = '1' AND nummer <> '' ORDER BY bezeichnung = 'SHOPID' DESC"); + if (!empty($data[$i]['artikelnummer_fremdnummern'])) { + foreach ($data[$i]['artikelnummer_fremdnummern'] as $fkey => $fval) { + $data[$i]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); + } + } + } + + if (!empty($loadElements['article_descriptions'])) { + $data[$i]['kurztext_de'] = $tmp->GetKurztext_De(); + $data[$i]['kurztext_en'] = $tmp->GetKurztext_En(); + $data[$i]['anabregs_text'] = htmlspecialchars($tmp->GetAnabregs_Text(), ENT_QUOTES); + $data[$i]['anabregs_text_en'] = htmlspecialchars($tmp->GetAnabregs_Text_En(), ENT_QUOTES); + $data[$i]['beschreibung_de'] = $tmp->GetBeschreibung_De(); + $data[$i]['beschreibung_en'] = $tmp->GetBeschreibung_En(); + $data[$i]['uebersicht_de'] = htmlspecialchars($tmp->GetUebersicht_De(), ENT_QUOTES); + $data[$i]['uebersicht_en'] = htmlspecialchars($tmp->GetUebersicht_En(), ENT_QUOTES); + $data[$i]['herkunftsland'] = $tmp->GetHerkunftsland(); + + $data[$i]['texteuebertragen'] = $shopexportarr['texteuebertragen']; + + if (method_exists($tmp, 'GetMetadescription_De')) { + $data[$i]['metadescription_de'] = $tmp->GetMetadescription_De(); + } + if (method_exists($tmp, 'GetMetadescription_En')) { + $data[$i]['metadescription_en'] = $tmp->GetMetadescription_En(); + } + if (method_exists($tmp, 'GetMetakeywords_De')) { + $data[$i]['metakeywords_de'] = $tmp->GetMetakeywords_De(); + } + if (method_exists($tmp, 'GetMetakeywords_En')) { + $data[$i]['metakeywords_en'] = $tmp->GetMetakeywords_En(); + } + if (method_exists($tmp, 'GetMetatitle_De')) { + $data[$i]['metatitle_de'] = $tmp->GetMetatitle_De(); + } + if (method_exists($tmp, 'GetMetatitle_En')) { + $data[$i]['metatitle_en'] = $tmp->GetMetatitle_En(); + } + } + if ($tmp->GetVariante()) { + $variante_von = $tmp->GetVariante_Von(); + if ($variante_von) { + $tmp_2 = new ObjGenArtikel($this->app); + $tmp_2->Select($variante_von); + if ($data[$i]['kurztext_de'] == '') { + $data[$i]['kurztext_de'] = $tmp_2->GetKurztext_De(); + } + if ($data[$i]['kurztext_en'] == '') { + $data[$i]['kurztext_en'] = $tmp_2->GetKurztext_En(); + } + if ($data[$i]['beschreibung_de'] == '') { + $data[$i]['beschreibung_de'] = $tmp_2->GetBeschreibung_De(); + } + if ($data[$i]['beschreibung_en'] == '') { + $data[$i]['beschreibung_en'] = $tmp_2->GetBeschreibung_En(); + } + if ($data[$i]['uebersicht_de'] == '') { + $data[$i]['uebersicht_de'] = htmlspecialchars($tmp_2->GetUebersicht_De(), ENT_QUOTES); + } + if ($data[$i]['uebersicht_en'] == '') { + $data[$i]['uebersicht_en'] = htmlspecialchars($tmp_2->GetUebersicht_En(), ENT_QUOTES); + } + } + } + + if ($data[$i]['uebersicht_de'] == '' && $data[$i]['beschreibung_de'] == '' && $data[$i]['kurztext_de'] == '') { + $data[$i]['uebersicht_de'] = $data[$i]['anabregs_text']; + } + + $data[$i]['links_de'] = $tmp->GetLinks_De(); + $data[$i]['altersfreigabe'] = $tmp->GetAltersfreigabe(); + $data[$i]['links_en'] = $tmp->GetLinks_En(); + $data[$i]['startseite_de'] = $tmp->GetStartseite_De(); + $data[$i]['startseite_en'] = $tmp->GetStartseite_En(); + $data[$i]['restmenge'] = $this->app->erp->GetArtikelShopEinstellung('restmenge', $artikel, $shopexportarr); + $data[$i]['startseite'] = $tmp->GetStartseite(); + $data[$i]['standardbild'] = $tmp->GetStandardbild(); + $data[$i]['herstellerlink'] = $tmp->GetHerstellerlink(); + $data[$i]['herstellernummer'] = $tmp->GetHerstellernummer(); + $data[$i]['hersteller'] = $tmp->GetHersteller(); + $data[$i]['lieferzeit'] = $tmp->GetLieferzeit(); + $data[$i]['lieferzeitmanuell'] = $this->app->erp->GetArtikelShopEinstellung('lieferzeitmanuell', $artikel, $shopexportarr); + $data[$i]['gewicht'] = $tmp->GetGewicht(); + $data[$i]['laenge'] = $tmp->GetLaenge(); + $data[$i]['breite'] = $tmp->GetBreite(); + $data[$i]['hoehe'] = $tmp->GetHoehe(); + + $data[$i]['wichtig'] = $tmp->GetWichtig(); + $data[$i]['porto'] = $tmp->GetPorto(); + $data[$i]['gesperrt'] = $tmp->GetGesperrt(); + $data[$i]['sperrgrund'] = $tmp->GetSperrgrund(); + $data[$i]['gueltigbis'] = $tmp->GetGueltigbis(); + $data[$i]['umsatzsteuer'] = $tmp->GetUmsatzsteuer(); + if ($data[$i]['umsatzsteuer'] !== 'ermaessigt' && $data[$i]['umsatzsteuer'] !== 'befreit') { + $data[$i]['umsatzsteuer'] = "normal"; + } + $data[$i]['ausverkauft'] = $tmp->GetAusverkauft(); + $data[$i]['variante'] = $tmp->GetVariante(); + $data[$i]['variante_von_id'] = $tmp->GetVariante_Von(); + $data[$i]['variantevon'] = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id='" . $tmp->GetVariante_Von() . "' LIMIT 1"); + $data[$i]['variantevon_fremdnummer'] = trim($this->app->DB->Select("SELECT nummer FROM `artikelnummer_fremdnummern` WHERE shopid = '$id' AND aktiv = 1 AND artikel = '" . $tmp->GetVariante_Von() . "' AND trim(nummer) <> '' ORDER BY bezeichnung = 'SHOPID' DESC LIMIT 1")); + if ($data[$i]['variantevon_fremdnummer'] == '') { + unset($data[$i]['variantevon_fremdnummer']); + } + //$data[$i]['pseudopreis'] = $tmp->GetPseudopreis(); + $data[$i]['pseudopreis'] = $this->app->erp->GetArtikelShopEinstellung('pseudopreis', $artikel, $shopexportarr); + $data[$i]['keinrabatterlaubt'] = $tmp->GetKeinrabatterlaubt(); + $data[$i]['einkaufspreis'] = $this->app->erp->GetEinkaufspreis($artikel, 1); + //$data[$i]['pseudolager'] = $tmp->GetPseudolager(); + $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); + if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { + $data[$i]['pseudolager'] = 0; + } + $data[$i]['downloadartikel'] = $tmp->GetDownloadartikel(); + $data[$i]['zolltarifnummer'] = $tmp->GetZolltarifnummer(); + $preisgruppe = $this->app->DB->Select("SELECT s.preisgruppe FROM shopexport s INNER JOIN gruppen g ON s.preisgruppe = g.id AND g.aktiv = 1 WHERE s.id='$id' LIMIT 1"); + + if (empty($loadElements['free_fields'])) { + $freifelder = null; + } else { + $freifelder = $this->app->DB->SelectArr("SELECT freifeld_wawi, freifeld_shop FROM shopexport_freifelder WHERE shop = '$id' AND aktiv = 1 AND freifeld_wawi <> '' AND freifeld_shop <> ''"); + } + if ($freifelder) { + /** + * @deprecated 20.1 + * AP + * Konstrunktion 'freifeld_Mappingname -> Wert' wird ersetzt durch 'Freifelder-> DE -> Mappingname -> Wert' + */ + foreach ($freifelder as $freifeld) { + if (method_exists($tmp, 'Get' . ucfirst($freifeld['freifeld_wawi']))) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + $data[$i]['freifeld_' . $freifeld['freifeld_shop']] = $tmp->$_funktionsname(); + } + } + /** + * @deprecated Ende + */ + foreach ($freifelder as $freifeld) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + if (method_exists($tmp, $_funktionsname)) { + $data[$i]['freifelder']['DE'][$freifeld['freifeld_shop']] = $tmp->$_funktionsname(); + } + } + + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '$artikel' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } + + $data[$i]['typ'] = $tmp->GetTyp(); + $data[$i]['kategoriename'] = $tmp->GetTyp(); + if (strpos($data[$i]['typ'], '_kat')) { + $data[$i]['kategoriename'] = $this->app->DB->Select("SELECT bezeichnung FROM artikelkategorien WHERE id = '" . (int) str_replace('_kat', '', $data[$i]['typ']) . "' LIMIT 1"); + } + + $kategorienuebertragen = $shopexportarr['kategorienuebertragen']; //$this->app->DB->Select("SELECT kategorienuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); + if (!empty($kategorienuebertragen) && !empty($loadElements['categories'])) { + $kategorienbaum = null; + /** @var Onlineshops $onlineShopObj */ + $onlineShopObj = $this->app->loadModule('onlineshops'); + $categoryRootId = 0; + if (!empty($onlineShopObj) && method_exists($onlineShopObj, 'getJsonSettings')) { + $categoryRootId = (int) $onlineShopObj->getJsonSettings($id, 'category_root_id'); + } + $this->app->erp->GetKategorienbaum($kategorienbaum, $categoryRootId, 0, $id); + if (!empty($kategorienbaum)) { + $kategorien = $this->app->DB->SelectArr("SELECT ak.id, ak.bezeichnung FROM `artikelbaum_artikel` aa INNER JOIN `artikelkategorien` ak ON aa.kategorie = ak.id AND ak.geloescht <> 1 AND aa.artikel = '$artikel' ORDER by ak.bezeichnung"); + if ($kategorien) { + foreach ($kategorien as $v) { + $katid[$v['id']] = true; + } + } + if (!empty($katid)) { + foreach ($kategorienbaum as $v) { + $data[$i]['kompletter_kategorienbaum'][] = array('name' => $v['bezeichnung'], 'parent' => $v['parent'], 'id' => $v['id'], 'lvl' => $v['lvl'], 'extid' => $v['extid']); + if (isset($katid[$v['id']])) { + $data[$i]['kategorien'][] = array('name' => $v['bezeichnung'], 'parent' => $v['parent'], 'id' => $v['id'], 'lvl' => $v['lvl'], 'extid' => $v['extid']); + } + } + } + } + } + + $eigenschaftenuebertragen = $shopexportarr['eigenschaftenuebertragen']; //$this->app->DB->Select("SELECT eigenschaftenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1"); + if (!empty($eigenschaftenuebertragen) && !empty($loadElements['properties'])) { + $eigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften WHERE ew.artikel = '$artikel' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1"); - if(!empty($eigenschaften)) - { - $eigenschaftind = 0; - foreach($eigenschaften as $eigenschaft) - { - $eigenschaftind++; - $data[$i]['eigenschaften'][] = array('name'=>$eigenschaft['name'], 'values'=>$eigenschaft['wert']); - } - } + if (!empty($eigenschaften)) { + $eigenschaftind = 0; + foreach ($eigenschaften as $eigenschaft) { + $eigenschaftind++; + $data[$i]['eigenschaften'][] = array('name' => $eigenschaft['name'], 'values' => $eigenschaft['wert']); + } + } - $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '$artikel'"); - $data[$i]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; - } + $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '$artikel'"); + $data[$i]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; + } - //Bilder - $dateien = null; - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($artikel); - if (!empty($dateien)) { - $data[$i]['Dateien'] = []; - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['Dateien'][] = array( - 'datei' => base64_encode($this->app->erp->GetDatei($datei['id'])), - 'filename' => $filename, - 'extension' => $path_info['extension'], - 'titel' => $datei['titel'], - 'beschreibung' => $datei['beschreibung'], - 'id' => $datei['id'], - 'version' => $datei['version'], - 'stichwort' => $datei['subjekt'], - 'extid' => $this->GetShopexportMappingExt($id, 'datei', $datei['id'])); - } - } - $dateiengeloescht = $this->app->DB->SelectArr("SELECT s.extid FROM shopexport_mapping s LEFT JOIN datei d ON s.intid = d.id AND d.geloescht = 0 WHERE s.shop = '$id' AND s.tabelle = 'datei' AND s.intid2 = '$artikel' AND isnull(d.id)"); - if (!empty($dateiengeloescht)) { - if (empty($dateien)) { - $data[$i]['Dateien'] = []; - } - foreach ($dateiengeloescht as $datei) { - $data[$i]['Dateien'][] = array('loeschen' => 1, 'extid' => $datei['extid']); - } - } - } + //Bilder + $dateien = null; + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($artikel); + if (!empty($dateien)) { + $data[$i]['Dateien'] = []; + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['Dateien'][] = array( + 'datei' => base64_encode($this->app->erp->GetDatei($datei['id'])), + 'filename' => $filename, + 'extension' => $path_info['extension'], + 'titel' => $datei['titel'], + 'beschreibung' => $datei['beschreibung'], + 'id' => $datei['id'], + 'version' => $datei['version'], + 'stichwort' => $datei['subjekt'], + 'extid' => $this->GetShopexportMappingExt($id, 'datei', $datei['id'])); + } + } + $dateiengeloescht = $this->app->DB->SelectArr("SELECT s.extid FROM shopexport_mapping s LEFT JOIN datei d ON s.intid = d.id AND d.geloescht = 0 WHERE s.shop = '$id' AND s.tabelle = 'datei' AND s.intid2 = '$artikel' AND isnull(d.id)"); + if (!empty($dateiengeloescht)) { + if (empty($dateien)) { + $data[$i]['Dateien'] = []; + } + foreach ($dateiengeloescht as $datei) { + $data[$i]['Dateien'][] = array('loeschen' => 1, 'extid' => $datei['extid']); + } + } + } - if (method_exists($tmp, 'GetSteuer_Art_Produkt')) { - $data[$i]['steuer_art_produkt'] = $tmp->GetSteuer_Art_Produkt(); - } - if (method_exists($tmp, 'GetSteuer_Art_Produkt_Download')) { - $data[$i]['steuer_art_produkt_download'] = $tmp->GetSteuer_Art_Produkt_Download(); - } + if (method_exists($tmp, 'GetSteuer_Art_Produkt')) { + $data[$i]['steuer_art_produkt'] = $tmp->GetSteuer_Art_Produkt(); + } + if (method_exists($tmp, 'GetSteuer_Art_Produkt_Download')) { + $data[$i]['steuer_art_produkt_download'] = $tmp->GetSteuer_Art_Produkt_Download(); + } - $projekt = $tmp->GetProjekt(); - $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = '$projekt' AND projektlager = 1 LIMIT 1"); - $data[$i]['anzahl_bilder'] = $this->app->DB->Select("SELECT COUNT(datei) FROM datei_stichwoerter WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='$artikel'"); + $projekt = $tmp->GetProjekt(); + $projektlager = $this->app->DB->Select("SELECT id FROM projekt WHERE id = '$projekt' AND projektlager = 1 LIMIT 1"); + $data[$i]['anzahl_bilder'] = $this->app->DB->Select("SELECT COUNT(datei) FROM datei_stichwoerter WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='$artikel'"); - $bestandalternativartikel = method_exists($tmp, 'GetBestandalternativartikel') ? $tmp->GetBestandalternativartikel() : 0; + $bestandalternativartikel = method_exists($tmp, 'GetBestandalternativartikel') ? $tmp->GetBestandalternativartikel() : 0; - if ($bestandalternativartikel) { - $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, $id, $lagergrundlage)); - $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); - } else { - $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, $id, $lagergrundlage)); - $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); - } + if ($bestandalternativartikel) { + $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, $id, $lagergrundlage)); + $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($bestandalternativartikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); + } else { + $data[$i]['anzahl_lager'] = floor($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, $id, $lagergrundlage)); + $data[$i]['lagerkorrekturwert'] = floor(-($this->app->erp->ArtikelAnzahlVerkaufbar($artikel, 0, $projektlager, 0, $lagergrundlage) - $data[$i]['anzahl_lager'])); + } - $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); - if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { - $data[$i]['pseudolager'] = 0; - $data[$i]['anzahl_lager'] = 0; - } elseif ($data[$i]['pseudolager'] > 0) { - $data[$i]['anzahl_lager'] = $data[$i]['pseudolager']; - } - if ($data[$i]['anzahl_lager'] < 0) { - $data[$i]['anzahl_lager'] = 0; - } - $data[$i]['autolagerlampe'] = $tmp->GetAutolagerlampe(); - if (method_exists($this->app->erp, 'GetArtikelShopEinstellung')) { - $data[$i]['autolagerlampe'] = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); - } - if ($data[$i]['autolagerlampe'] != '1') { - $data[$i]['anzahl_lager'] = ''; - $data[$i]['pseudolager'] = ''; - $this->app->DB->Update( - sprintf( - 'UPDATE `artikel_onlineshops` + $data[$i]['pseudolager'] = $this->app->erp->GetArtikelShopEinstellung('pseudolager', $artikel, $shopexportarr); + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $artikel, $data[$i]['pseudolager']); + if (is_numeric($data[$i]['pseudolager']) && $data[$i]['pseudolager'] < 0) { + $data[$i]['pseudolager'] = 0; + $data[$i]['anzahl_lager'] = 0; + } elseif ($data[$i]['pseudolager'] > 0) { + $data[$i]['anzahl_lager'] = $data[$i]['pseudolager']; + } + if ($data[$i]['anzahl_lager'] < 0) { + $data[$i]['anzahl_lager'] = 0; + } + $data[$i]['autolagerlampe'] = $tmp->GetAutolagerlampe(); + if (method_exists($this->app->erp, 'GetArtikelShopEinstellung')) { + $data[$i]['autolagerlampe'] = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); + } + if ($data[$i]['autolagerlampe'] != '1') { + $data[$i]['anzahl_lager'] = ''; + $data[$i]['pseudolager'] = ''; + $this->app->DB->Update( + sprintf( + 'UPDATE `artikel_onlineshops` SET `storage_cache` = NULL, `pseudostorage_cache` = NULL WHERE `artikel` = %d AND `shop` = %d', - $artikel, $id - ) - ); - } else { - $this->app->DB->Update( - sprintf( - 'UPDATE `artikel_onlineshops` + $artikel, $id + ) + ); + } else { + $this->app->DB->Update( + sprintf( + 'UPDATE `artikel_onlineshops` SET `storage_cache` = %d, `pseudostorage_cache` = %s WHERE `artikel` = %d AND `shop` = %d', - $data[$i]['anzahl_lager'], - !isset($data[$i]['pseudolager']) || !is_numeric($data[$i]['pseudolager']) ? 'NULL' : $data[$i]['pseudolager'], - $artikel, - $id - ) - ); - } + $data[$i]['anzahl_lager'], + !isset($data[$i]['pseudolager']) || !is_numeric($data[$i]['pseudolager']) ? 'NULL' : $data[$i]['pseudolager'], + $artikel, + $id + ) + ); + } - $projekt = $shopexportarr['projekt'];// $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id' LIMIT 1"); - if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { - //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $data[$i]['crosssellingartikel'] = $this->app->DB->SelectArr("SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer + $projekt = $shopexportarr['projekt']; // $this->app->DB->Select("SELECT projekt FROM shopexport WHERE id='$id' LIMIT 1"); + if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { + //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $data[$i]['crosssellingartikel'] = $this->app->DB->SelectArr("SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer FROM crossselling_artikel ca JOIN artikel a ON ca.crosssellingartikel = a.id LEFT JOIN artikelkategorien ak ON CONCAT(ak.id,'_kat') = a.typ @@ -1587,14 +1436,12 @@ class Remote WHERE ca.artikel='" . $tmp->GetId() . "' AND (ca.shop='$id' OR ca.shop='0') GROUP BY ca.crosssellingartikel, ca.art"); - if (empty($data[$i]['crosssellingartikel'])) { - $data[$i]['crosssellingartikel'] = []; - } + if (empty($data[$i]['crosssellingartikel'])) { + $data[$i]['crosssellingartikel'] = []; + } - - $sql = - - "SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer + + $sql = "SELECT a.id, a.nummer, ak.bezeichnung as kategorie, a.name_de, a.name_en, ca.art, ca.gegenseitigzuweisen, af.nummer AS fremdnummer FROM crossselling_artikel ca JOIN artikel a ON ca.artikel = a.id LEFT JOIN artikelkategorien ak ON CONCAT(ak.id,'_kat') = a.typ @@ -1603,139 +1450,139 @@ class Remote WHERE ca.crosssellingartikel='" . $tmp->GetId() . "' AND ca.gegenseitigzuweisen=1 AND (ca.shop='$id' OR ca.shop='0') GROUP BY ca.artikel, ca.art"; - $gegenseitigzugewiesen = $this->app->DB->SelectArr($sql); + $gegenseitigzugewiesen = $this->app->DB->SelectArr($sql); - if (!empty($gegenseitigzugewiesen)) { - foreach ($gegenseitigzugewiesen as $gegenseitigzugewiesenercrosssellingartikel) { - $data[$i]['crosssellingartikel'][] = $gegenseitigzugewiesenercrosssellingartikel; - } - } - } - - if (!empty($loadElements['article_descriptions']) && $this->app->erp->ModulVorhanden('artikel_texte')) { - $sprachen = ['de', 'en']; - foreach ($sprachen as $sprache) { - $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", - $id, strtoupper($sprache), $artikel); - $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if (!empty($ersetzeStandardbeschreibung)) { - $data[$i]['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; - $data[$i]['beschreibung_' . $sprache] = $ersetzeStandardbeschreibung['beschreibung_online']; - $data[$i]['kurztext_' . $sprache] = $ersetzeStandardbeschreibung['kurztext']; - $data[$i]['metadescription_' . $sprache] = $ersetzeStandardbeschreibung['meta_description']; - $data[$i]['metakeywords_' . $sprache] = $ersetzeStandardbeschreibung['meta_keywords']; - $data[$i]['metatitle_' . $sprache] = $ersetzeStandardbeschreibung['meta_title']; - if ($sprache === 'de') { - $data[$i]['anabregs_text'] = $ersetzeStandardbeschreibung['beschreibung']; - } else { - $data[$i]['anabregs_text_en'] = $ersetzeStandardbeschreibung['beschreibung']; + if (!empty($gegenseitigzugewiesen)) { + foreach ($gegenseitigzugewiesen as $gegenseitigzugewiesenercrosssellingartikel) { + $data[$i]['crosssellingartikel'][] = $gegenseitigzugewiesenercrosssellingartikel; + } + } } - } - } - } - if(!empty($loadElements['standard_price'])){ + if (!empty($loadElements['article_descriptions']) && $this->app->erp->ModulVorhanden('artikel_texte')) { + $sprachen = ['de', 'en']; + foreach ($sprachen as $sprache) { + $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", + $id, strtoupper($sprache), $artikel); + $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); + if (!empty($ersetzeStandardbeschreibung)) { + $data[$i]['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + $data[$i]['beschreibung_' . $sprache] = $ersetzeStandardbeschreibung['beschreibung_online']; + $data[$i]['kurztext_' . $sprache] = $ersetzeStandardbeschreibung['kurztext']; + $data[$i]['metadescription_' . $sprache] = $ersetzeStandardbeschreibung['meta_description']; + $data[$i]['metakeywords_' . $sprache] = $ersetzeStandardbeschreibung['meta_keywords']; + $data[$i]['metatitle_' . $sprache] = $ersetzeStandardbeschreibung['meta_title']; + if ($sprache === 'de') { + $data[$i]['anabregs_text'] = $ersetzeStandardbeschreibung['beschreibung']; + } else { + $data[$i]['anabregs_text_en'] = $ersetzeStandardbeschreibung['beschreibung']; + } + } + } + } - $priceInformation = $this->app->DB->SelectArr("SELECT v.preis AS preis, v.waehrung + if (!empty($loadElements['standard_price'])) { + + $priceInformation = $this->app->DB->SelectArr("SELECT v.preis AS preis, v.waehrung FROM `verkaufspreise` AS `v` WHERE v.artikel = '{$artikel}' AND v.ab_menge = 1 AND v.geloescht = 0 AND v.art != 'Gruppe' AND (v.objekt = 'Standard' OR v.objekt = '') AND (v.adresse = '0' OR v.adresse = '') AND (v.gueltig_bis >= NOW() OR v.gueltig_bis = '0000-00-00') ORDER BY v.preis DESC LIMIT 1"); - $priceInformation = reset($priceInformation); - $defaultPrice = $priceInformation['preis']; - $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; - if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ - $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency - $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); - } + $priceInformation = reset($priceInformation); + $defaultPrice = $priceInformation['preis']; + $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; + if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { + $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency + $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); + } - $data[$i]['waehrung'] = $defaultCurrency; - $data[$i]['preis'] = $defaultPrice; + $data[$i]['waehrung'] = $defaultCurrency; + $data[$i]['preis'] = $defaultPrice; - if(!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1){ - $data[$i]['steuersatz'] = (float)$tmp->GetSteuersatz(); - }elseif($data[$i]['umsatzsteuer'] === 'ermaessigt'){ - $data[$i]['steuersatz'] = (float)$this->app->erp->GetStandardSteuersatzErmaessigt($projekt); - }elseif($data[$i]['umsatzsteuer'] === 'befreit'){ - $data[$i]['steuersatz'] = 0; - }else{ - $data[$i]['steuersatz'] = (float)$this->app->erp->GetStandardSteuersatzNormal($projekt); - } + if (!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1) { + $data[$i]['steuersatz'] = (float) $tmp->GetSteuersatz(); + } elseif ($data[$i]['umsatzsteuer'] === 'ermaessigt') { + $data[$i]['steuersatz'] = (float) $this->app->erp->GetStandardSteuersatzErmaessigt($projekt); + } elseif ($data[$i]['umsatzsteuer'] === 'befreit') { + $data[$i]['steuersatz'] = 0; + } else { + $data[$i]['steuersatz'] = (float) $this->app->erp->GetStandardSteuersatzNormal($projekt); + } - $steuer = ($data[$i]['steuersatz'] + 100) / 100.0; + $steuer = ($data[$i]['steuersatz'] + 100) / 100.0; - if(!empty($shopexportarr['staffelpreiseuebertragen']) && !empty($loadElements['bulk_prices'])){ - $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; - if(!empty($preisgruppe)){ - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $query = sprintf("SELECT v.adresse, g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung + if (!empty($shopexportarr['staffelpreiseuebertragen']) && !empty($loadElements['bulk_prices'])) { + $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $query = sprintf("SELECT v.adresse, g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung FROM `verkaufspreise` AS `v` LEFT JOIN `gruppen` AS `g` on v.gruppe = g.id WHERE v.artikel = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.adresse = 0 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) %s ORDER by g.id, v.ab_menge", $artikel, $preisgruppenzusatz); - $standardstaffelpreise = $this->app->DB->SelectArr($query); - $data[$i]['staffelpreise_standard'] = []; - if(!empty($standardstaffelpreise)){ - foreach ($standardstaffelpreise as $staffelpreis) { - $data[$i]['staffelpreise_standard'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' - ]; - } - } + $standardstaffelpreise = $this->app->DB->SelectArr($query); + $data[$i]['staffelpreise_standard'] = []; + if (!empty($standardstaffelpreise)) { + foreach ($standardstaffelpreise as $staffelpreis) { + $data[$i]['staffelpreise_standard'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' + ]; + } + } - $query = sprintf("SELECT a.name AS `kundenname`, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung + $query = sprintf("SELECT a.name AS `kundenname`, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung FROM `verkaufspreise` AS `v` JOIN `adresse` AS `a` ON v.adresse = a.id AND v.art LIKE 'Kunde' WHERE v.`artikel` = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by v.adresse, v.ab_menge", $artikel); - $staffelpreisekunden = $this->app->DB->SelectArr($query); - if(!empty($staffelpreisekunden)){ - foreach ($staffelpreisekunden as $staffelpreis) { - $data[$i]['staffelpreise_kunden'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'email' => $staffelpreis['email'], - 'kundenname' => $staffelpreis['kundenname'] - ]; - } - } + $staffelpreisekunden = $this->app->DB->SelectArr($query); + if (!empty($staffelpreisekunden)) { + foreach ($staffelpreisekunden as $staffelpreis) { + $data[$i]['staffelpreise_kunden'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'email' => $staffelpreis['email'], + 'kundenname' => $staffelpreis['kundenname'] + ]; + } + } - $query = sprintf("SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, sk.extgruppename + $query = sprintf("SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, sk.extgruppename FROM `verkaufspreise` AS `v` JOIN `gruppen` AS `g` on v.gruppe = g.id JOIN `shopexport_kundengruppen` AS `sk` ON sk.gruppeid = v.gruppe WHERE v.`artikel` = %d AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.art like 'Gruppe' AND v.gruppe <> '%s' AND sk.shopid = %d AND sk.aktiv = 1 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, v.ab_menge", $artikel, $preisgruppe, $id); - $staffelpreisegruppen = $this->app->DB->SelectArr($query); - if(!empty($staffelpreisegruppen)){ - foreach ($staffelpreisegruppen as $staffelpreis) { - $data[$i]['staffelpreise_gruppen'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'kennziffer' => $staffelpreis['kennziffer'], - 'gruppenname' => $staffelpreis['name'], - 'gruppeextern' => $staffelpreis['extgruppename'] - ]; - } - } + $staffelpreisegruppen = $this->app->DB->SelectArr($query); + if (!empty($staffelpreisegruppen)) { + foreach ($staffelpreisegruppen as $staffelpreis) { + $data[$i]['staffelpreise_gruppen'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'kennziffer' => $staffelpreis['kennziffer'], + 'gruppenname' => $staffelpreis['name'], + 'gruppeextern' => $staffelpreis['extgruppename'] + ]; + } + } - /** - * @deprecated 20.3 - * Staffelpreise werden gesondert uebergeben statt in einem sammelarray - */ - $staffelpreise = $this->app->DB->SelectArr(" + /** + * @deprecated 20.3 + * Staffelpreise werden gesondert uebergeben statt in einem sammelarray + */ + $staffelpreise = $this->app->DB->SelectArr(" SELECT a.name AS kundenname, a.email, v.adresse, g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1744,63 +1591,62 @@ class Remote WHERE v.`artikel` = '$artikel' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, ab_menge"); - if(!empty($staffelpreise)){ - foreach ($staffelpreise as $k => $v) { - if(empty($v['adresse'])){ - $data[$i]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); - if($v['id']){ - $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; - $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + if (!empty($staffelpreise)) { + foreach ($staffelpreise as $k => $v) { + if (empty($v['adresse'])) { + $data[$i]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); + if ($v['id']) { + $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; + $data[$i]['staffelpreise'][count($data[$i]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + } + } + } + } + /** + * @deprecated Ende + */ + } + + + $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; + } + $data[$i]['checksum'] = $tmp->GetChecksum(); + if ($data[$i]['preis'] == '' && !empty($artikelexport) && !$nurlager) { + if ($lagerexport) { + $nurlager = true; + } else { + $this->app->erp->Systemlog( + 'Shopexport bei Artikel ' . $data[$i]['nummer'] . ' ' . $data[$i]['name_de'] . ' fehlgeschlagen, da Verkaufspreis fehlt.' + ); + $data[$i]['artikel'] = 'ignore'; } - } } - } - /** - * @deprecated Ende - */ - } + $steuerermaessigt = ($this->app->erp->GetStandardSteuersatzErmaessigt($projekt) + 100) / 100.0; + $steuernormal = ($this->app->erp->GetStandardSteuersatzNormal($projekt) + 100) / 100.0; + $steuermapping = [ + 'befreit' => 1, + 'ermaessigt' => $steuerermaessigt, + 'normal' => $steuernormal + ]; - $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; - } - $data[$i]['checksum'] = $tmp->GetChecksum(); - if ($data[$i]['preis'] == '' && !empty($artikelexport) && !$nurlager) { - if($lagerexport){ - $nurlager = true; - } else { - $this->app->erp->Systemlog( - 'Shopexport bei Artikel ' . $data[$i]['nummer'] . ' ' . $data[$i]['name_de'] . ' fehlgeschlagen, da Verkaufspreis fehlt.' - ); - $data[$i]['artikel'] = 'ignore'; - } - } + if (!empty($loadElements['variants']) && !empty($shopexportarr['variantenuebertragen']) && $this->app->erp->ModulVorhanden('matrixprodukt') && $tmp->GetMatrixprodukt()) { + $artfreifeld = ''; + for ($_i = 1; $_i <= 40; $_i++) { + $artfreifeld .= sprintf(' art.freifeld%d AS `freifeld%d`, ', $_i, $_i); + } + $varianten = null; - $steuerermaessigt = ($this->app->erp->GetStandardSteuersatzErmaessigt($projekt) + 100) / 100.0; - $steuernormal = ($this->app->erp->GetStandardSteuersatzNormal($projekt) + 100) / 100.0; - $steuermapping = [ - 'befreit' => 1, - 'ermaessigt' => $steuerermaessigt, - 'normal' => $steuernormal - ]; + $data[$i]['artikel_varianten'] = []; + $db = $this->app->Container->get('Database'); - if (!empty($loadElements['variants']) && !empty($shopexportarr['variantenuebertragen']) - && $this->app->erp->ModulVorhanden('matrixprodukt') && $tmp->GetMatrixprodukt()) { - $artfreifeld = ''; - for ($_i = 1; $_i <= 40; $_i++) { - $artfreifeld .= sprintf(' art.freifeld%d AS `freifeld%d`, ',$_i,$_i); - } - $varianten = null; + $offset = 0; + $eigenschaftind = 0; - $data[$i]['artikel_varianten'] = []; - $db = $this->app->Container->get('Database'); + $gruppenuebersetzung = []; + $gruppenwertuebersetzung = []; - $offset = 0; - $eigenschaftind = 0; - - $gruppenuebersetzung = []; - $gruppenwertuebersetzung = []; - - $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext + $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext FROM matrixprodukt_optionen_zu_artikel AS moza JOIN matrixprodukt_eigenschaftenoptionen_artikel AS meoa ON moza.option_id = meoa.id JOIN matrixprodukt_eigenschaftengruppen_artikel AS mega ON mega.id = meoa.gruppe @@ -1808,42 +1654,42 @@ class Remote WHERE art.variante_von=%d ANd art.geloescht=0 AND art.nummer <> "DEL" AND art.intern_gesperrt=0 GROUP BY mega.id, meoa.id ORDER BY SUM(POW(10,1-mega.sort) * meoa.sort) ASC', $artikel); - foreach ($db->yieldAll($query) as $matrixdaten) { - $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; + foreach ($db->yieldAll($query) as $matrixdaten) { + $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; - if (!empty($loadElements['translations'])) { - if (empty($gruppenuebersetzung[$matrixdaten['gruppe']])) { - $gruppennamen = $this->app->DB->SelectArr("SELECT + if (!empty($loadElements['translations'])) { + if (empty($gruppenuebersetzung[$matrixdaten['gruppe']])) { + $gruppennamen = $this->app->DB->SelectArr("SELECT IF(name_external_from<>'',name_external_from,name_from) AS name_from, IF(name_external_to<>'',name_external_to,name_to) AS name_to, language_to FROM `matrix_article_translation` WHERE name_from='" . $matrixdaten['gruppe'] . "' AND (project=0 OR project='$projekt')"); - $gruppenuebersetzung[$matrixdaten['gruppe']] = true; - if (!empty($gruppennamen)) { - foreach ($gruppennamen as $gruppenname) { - $data[$i]['matrix_varianten']['texte']['gruppen'][$gruppenname['language_to']][$gruppenname['name_from']] = $gruppenname['name_to']; - } - } - } - if (empty($gruppenwertuebersetzung[$matrixdaten['wert']])) { - $gruppenwerte = $this->app->DB->SelectArr("SELECT + $gruppenuebersetzung[$matrixdaten['gruppe']] = true; + if (!empty($gruppennamen)) { + foreach ($gruppennamen as $gruppenname) { + $data[$i]['matrix_varianten']['texte']['gruppen'][$gruppenname['language_to']][$gruppenname['name_from']] = $gruppenname['name_to']; + } + } + } + if (empty($gruppenwertuebersetzung[$matrixdaten['wert']])) { + $gruppenwerte = $this->app->DB->SelectArr("SELECT IF(maot.name_external_from<>'',maot.name_external_from,maot.name_from) AS `name_from`, IF(maot.name_external_to<>'',maot.name_external_to,maot.name_to) AS `name_to`, maot.language_to FROM `matrix_article_options_translation` AS `maot` WHERE maot.name_from='" . $this->app->DB->real_escape_string($matrixdaten['wert']) . "'"); - $gruppenwertuebersetzung[$matrixdaten['wert']] = true; - foreach ($gruppenwerte as $gruppenwert) { - $data[$i]['matrix_varianten']['texte']['werte'][$gruppenwert['language_to']][$gruppenwert['name_from']] = $gruppenwert['name_to']; - } - } - } - } + $gruppenwertuebersetzung[$matrixdaten['wert']] = true; + foreach ($gruppenwerte as $gruppenwert) { + $data[$i]['matrix_varianten']['texte']['werte'][$gruppenwert['language_to']][$gruppenwert['name_from']] = $gruppenwert['name_to']; + } + } + } + } - do { - unset($data[$i]['matrix_varianten']['artikel']); - unset($data[$i]['artikel_varianten']); - //if($this->app->DB->Select("SELECT variantenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $varianten = "SELECT art.pseudolager AS `pseudolager`, art.nummer AS `nummer`, art.inaktiv AS `inaktiv`, + do { + unset($data[$i]['matrix_varianten']['artikel']); + unset($data[$i]['artikel_varianten']); + //if($this->app->DB->Select("SELECT variantenuebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $varianten = "SELECT art.pseudolager AS `pseudolager`, art.nummer AS `nummer`, art.inaktiv AS `inaktiv`, art.id AS `artikel`, art.gewicht AS `gewicht`, art.zolltarifnummer AS `zolltarifnummer`, art.name_en AS `name_en`, $artfreifeld art.pseudopreis AS `pseudopreis`, art.lieferzeitmanuell AS `lieferzeitmanuell`, art.altersfreigabe AS `altersfreigabe`, @@ -1870,77 +1716,75 @@ class Remote GROUP BY art.id ORDER BY SUM(POW(10,1-mega.sort) * meoa.sort) ASC LIMIT 5000 OFFSET $offset"; - $offset += 5000; + $offset += 5000; - foreach ($db->yieldAll($varianten) as $eigenschaft) { - $eigenschaftind++; - $steuer = $steuermapping[$eigenschaft['umsatzsteuer']]; - if(!empty($eigenschaft['steuersatz']) && $eigenschaft['steuersatz'] != -1){ - $steuer = ($eigenschaft['steuersatz'] + 100) / 100; - } - if (empty($steuer)) { - $steuer = $steuernormal; - } - $matrixPseudoStorage = $eigenschaft['pseudolager']; - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $eigenschaft['artikel'], $matrixPseudoStorage); - if(is_numeric($matrixPseudoStorage) && $matrixPseudoStorage < 0) { - $matrixPseudoStorage = 0; - } - if($matrixStock < 0) { - $matrixStock = 0; - } - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][] = - array('zolltarifnummer' => $eigenschaft['zolltarifnummer'], 'gewicht' => $eigenschaft['gewicht'], - 'artikel' => $eigenschaft['artikel'], 'preis' => $eigenschaft['preis'], 'gesperrt' => $eigenschaft['gesperrt'], - 'nummer' => $eigenschaft['nummer'], 'lieferzeitmanuell' => $eigenschaft['lieferzeitmanuell'], - 'altersfreigabe' => $eigenschaft['altersfreigabe'], 'ean' => $eigenschaft['ean'], - 'lag' => $matrixStock, - 'pseudolager' => $matrixPseudoStorage, 'pseudopreis' => $eigenschaft['pseudopreis'], - 'restmenge' => $eigenschaft['restmenge'], 'steuersatz' => ($steuer - 1) * 100, 'umsatzsteuer' => $eigenschaft['umsatzsteuer'], - 'bruttopreis' => $eigenschaft['preis'] * $steuer, 'inaktiv' => $eigenschaft['inaktiv'], - 'name_de' => $eigenschaft['name_de'], 'name_en' => $eigenschaft['name_en'], - 'uebersicht_de' => $eigenschaft['uebersicht_de'], 'uebersicht_en' => $eigenschaft['uebersicht_en']); - if ($freifelder) { - foreach ($freifelder as $freifeld) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = - $this->app->DB->Select('SELECT ' . $freifeld['freifeld_wawi'] . ' FROM artikel WHERE id=' . $eigenschaft['artikel']); - } + foreach ($db->yieldAll($varianten) as $eigenschaft) { + $eigenschaftind++; + $steuer = $steuermapping[$eigenschaft['umsatzsteuer']]; + if (!empty($eigenschaft['steuersatz']) && $eigenschaft['steuersatz'] != -1) { + $steuer = ($eigenschaft['steuersatz'] + 100) / 100; + } + if (empty($steuer)) { + $steuer = $steuernormal; + } + $matrixPseudoStorage = $eigenschaft['pseudolager']; + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $eigenschaft['artikel'], $matrixPseudoStorage); + if (is_numeric($matrixPseudoStorage) && $matrixPseudoStorage < 0) { + $matrixPseudoStorage = 0; + } + if ($matrixStock < 0) { + $matrixStock = 0; + } + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][] = array('zolltarifnummer' => $eigenschaft['zolltarifnummer'], 'gewicht' => $eigenschaft['gewicht'], + 'artikel' => $eigenschaft['artikel'], 'preis' => $eigenschaft['preis'], 'gesperrt' => $eigenschaft['gesperrt'], + 'nummer' => $eigenschaft['nummer'], 'lieferzeitmanuell' => $eigenschaft['lieferzeitmanuell'], + 'altersfreigabe' => $eigenschaft['altersfreigabe'], 'ean' => $eigenschaft['ean'], + 'lag' => $matrixStock, + 'pseudolager' => $matrixPseudoStorage, 'pseudopreis' => $eigenschaft['pseudopreis'], + 'restmenge' => $eigenschaft['restmenge'], 'steuersatz' => ($steuer - 1) * 100, 'umsatzsteuer' => $eigenschaft['umsatzsteuer'], + 'bruttopreis' => $eigenschaft['preis'] * $steuer, 'inaktiv' => $eigenschaft['inaktiv'], + 'name_de' => $eigenschaft['name_de'], 'name_en' => $eigenschaft['name_en'], + 'uebersicht_de' => $eigenschaft['uebersicht_de'], 'uebersicht_en' => $eigenschaft['uebersicht_en']); + if ($freifelder) { + foreach ($freifelder as $freifeld) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $this->app->DB->Select('SELECT ' . $freifeld['freifeld_wawi'] . ' FROM artikel WHERE id=' . $eigenschaft['artikel']); + } - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $eigenschaft['artikel'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if (!empty($freifelduebersetzungen)) { - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $eigenschaft['artikel'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']]) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($eigenschaft['artikel']); - if (!empty($dateien)) { - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['filename'][] = $filename; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extension'][] = $path_info['extension']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['titel'][] = $datei['titel']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['beschreibung'][] = $datei['beschreibung']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['stichwort'][] = $datei['subjekt']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['id'][] = $datei['id']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['version'][] = $datei['version']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); - } - } - } + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($eigenschaft['artikel']); + if (!empty($dateien)) { + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['filename'][] = $filename; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extension'][] = $path_info['extension']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['titel'][] = $datei['titel']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['beschreibung'][] = $datei['beschreibung']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['stichwort'][] = $datei['subjekt']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['id'][] = $datei['id']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['version'][] = $datei['version']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); + } + } + } - $standardstaffelpreise = null; - if(!empty($loadElements['standard_price'])){ - $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; - if(!empty($preisgruppe)){ - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $standardstaffelpreise = $this->app->DB->SelectArr(" + $standardstaffelpreise = null; + if (!empty($loadElements['standard_price'])) { + $preisgruppenzusatz = " AND v.art = 'Kunde' AND v.adresse = 0"; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $standardstaffelpreise = $this->app->DB->SelectArr(" SELECT v.adresse, g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1948,20 +1792,20 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.adresse=0 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) $preisgruppenzusatz ORDER by g.id, ab_menge"); - } - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'] = []; - if (!empty($standardstaffelpreise)) { - foreach ($standardstaffelpreise as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' - ]; - } - } - if(!empty($loadElements['bulk_prices'])){ - $staffelpreisekunden = $this->app->DB->SelectArr(" + } + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'] = []; + if (!empty($standardstaffelpreise)) { + foreach ($standardstaffelpreise as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_standard'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR' + ]; + } + } + if (!empty($loadElements['bulk_prices'])) { + $staffelpreisekunden = $this->app->DB->SelectArr(" SELECT a.name AS kundenname, a.email, v.adresse, v.ab_menge, v.preis, v.waehrung, art.umsatzsteuer FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1969,20 +1813,20 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by v.adresse, ab_menge"); - if(!empty($staffelpreisekunden)){ - foreach ($staffelpreisekunden as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_kunden'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'email' => $staffelpreis['email'], - 'kundenname' => $staffelpreis['kundenname'] - ]; - } - } + if (!empty($staffelpreisekunden)) { + foreach ($staffelpreisekunden as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_kunden'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'email' => $staffelpreis['email'], + 'kundenname' => $staffelpreis['kundenname'] + ]; + } + } - $staffelpreisegruppen = $this->app->DB->SelectArr(" + $staffelpreisegruppen = $this->app->DB->SelectArr(" SELECT g.name,g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, art.umsatzsteuer,sk.extgruppename FROM `verkaufspreise` AS v INNER JOIN artikel art ON v.artikel = art.id @@ -1991,217 +1835,212 @@ class Remote WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (v.gueltig_bis = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND v.art like 'Gruppe' AND v.gruppe<>'$preisgruppe' AND sk.shopid='$id' AND sk.aktiv=1 AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) ORDER by g.id, ab_menge"); - if(!empty($staffelpreisegruppen)){ - foreach ($staffelpreisegruppen as $staffelpreis) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_gruppen'][] = [ - 'ab_menge' => $staffelpreis['ab_menge'], - 'preis' => $staffelpreis['preis'], - 'bruttopreis' => $staffelpreis['preis'] * $steuer, - 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', - 'kennziffer' => $staffelpreis['kennziffer'], - 'gruppenname' => $staffelpreis['name'], - 'gruppeextern' => $staffelpreis['extgruppename'] - ]; - } - } - } - $staffelpreisema = null; - if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { - //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ - $preisgruppenzusatz = ''; - if (!empty($preisgruppe)) { - $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; - } - $staffelpreisema = $this->app->DB->SelectArr(" + if (!empty($staffelpreisegruppen)) { + foreach ($staffelpreisegruppen as $staffelpreis) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise_gruppen'][] = [ + 'ab_menge' => $staffelpreis['ab_menge'], + 'preis' => $staffelpreis['preis'], + 'bruttopreis' => $staffelpreis['preis'] * $steuer, + 'waehrung' => $staffelpreis['waehrung'] ?: 'EUR', + 'kennziffer' => $staffelpreis['kennziffer'], + 'gruppenname' => $staffelpreis['name'], + 'gruppeextern' => $staffelpreis['extgruppename'] + ]; + } + } + } + $staffelpreisema = null; + if (!empty($shopexportarr['crosssellingartikeluebertragen']) && !empty($loadElements['cross_selling'])) { + //if($this->app->DB->Select("SELECT crosssellingartikeluebertragen FROM shopexport WHERE id = '$id' LIMIT 1")){ + $preisgruppenzusatz = ''; + if (!empty($preisgruppe)) { + $preisgruppenzusatz = " AND v.gruppe = '$preisgruppe'"; + } + $staffelpreisema = $this->app->DB->SelectArr(" SELECT g.name, g.kennziffer, v.ab_menge, v.preis, g.id, v.waehrung, v.id, v.adresse, v.art, sk.extgruppename FROM `verkaufspreise` AS v LEFT JOIN gruppen g on v.gruppe = g.id AND v.art like 'Gruppe' LEFT JOIN shopexport_kundengruppen sk ON sk.gruppeid=v.gruppe WHERE v.`artikel` = '" . $eigenschaft['artikel'] . "' AND v.geloescht = 0 AND (ifnull(v.gueltig_bis,'0000-00-00') = '0000-00-00' OR curdate() <= v.gueltig_bis OR isnull(v.gueltig_bis)) AND (v.gueltig_ab = '0000-00-00' OR curdate() >= v.gueltig_ab OR isnull(v.gueltig_ab)) $preisgruppenzusatz ORDER by g.id, ab_menge"); - } - if (!empty($staffelpreisema)) { - foreach ($staffelpreisema as $k => $v) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); - if ($v['id']) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenname'] = $v['name']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['adresse'] = $v['adresse']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['art'] = $v['art']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppeextern'] = $v['extgruppename']; - } - } - } + } + if (!empty($staffelpreisema)) { + foreach ($staffelpreisema as $k => $v) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][] = array('ab_menge' => $v['ab_menge'], 'preis' => $v['preis'], 'bruttopreis' => $v['preis'] * $steuer, 'waehrung' => ($v['waehrung'] ? $v['waehrung'] : 'EUR')); + if ($v['id']) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenkennziffer'] = $v['kennziffer']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppenname'] = $v['name']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['adresse'] = $v['adresse']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['art'] = $v['art']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise'][count($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['staffelpreise']) - 1]['gruppeextern'] = $v['extgruppename']; + } + } + } - $articleVariant = $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]; - $articleVariant['artikel'] = $eigenschaft['artikel']; - $data[$i]['artikel_varianten'][] = $articleVariant; - unset($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']); + $articleVariant = $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]; + $articleVariant['artikel'] = $eigenschaft['artikel']; + $data[$i]['artikel_varianten'][] = $articleVariant; + unset($data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][0]['Dateien']); - - $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext + $query = sprintf('SELECT meoa.name AS wert,meoa.name_ext AS wert_ext, mega.name AS gruppe, mega.name_ext AS gruppe_ext FROM matrixprodukt_optionen_zu_artikel AS moza JOIN matrixprodukt_eigenschaftenoptionen_artikel AS meoa ON moza.option_id = meoa.id JOIN matrixprodukt_eigenschaftengruppen_artikel AS mega ON mega.id = meoa.gruppe WHERE moza.artikel=%d ORDER BY mega.id, moza.id', $eigenschaft['artikel']); - $matrixdaten = $this->app->DB->SelectArr($query); + $matrixdaten = $this->app->DB->SelectArr($query); - for ($iv = 0, $ivMax = (!empty($matrixdaten)?count($matrixdaten):0); $iv < $ivMax; $iv++) { - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['name'] = $matrixdaten[$iv]['gruppe']; - $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['values'] = $matrixdaten[$iv]['wert']; + for ($iv = 0, $ivMax = (!empty($matrixdaten) ? count($matrixdaten) : 0); $iv < $ivMax; $iv++) { + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['name'] = $matrixdaten[$iv]['gruppe']; + $data[$i]['matrix_varianten']['artikel'][$eigenschaft['artikel']][$iv]['values'] = $matrixdaten[$iv]['wert']; + } + } + + $result = null; + if (empty($data)) { + continue; + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } + } while (count($data[$i]['matrix_varianten']['artikel'] ?? []) >= 5000); + + return $result; } - } - $result = null; - if(empty($data)) { - continue; - } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } + if (!empty($loadElements['variants']) && $this->app->DB->Select("SELECT id FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { + if ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikel' AND variante = 0 AND matrixprodukt=0 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { + $data[$i]['artikel_varianten'] = []; + $data[$i]['variantevorhanden'] = 1; + $varianten = "SELECT * FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL'"; + $db = $this->app->Container->get('Database'); + foreach ($db->yieldAll($varianten) as $v) { + $steuer = $steuermapping[$v['umsatzsteuer']]; + if ($v['steuersatz'] != -1 && !empty($v['steuersatz'])) { + $steuer = ($v['steuersatz'] + 100) / 100; + } + if (empty($steuer)) { + $steuer = $steuernormal; + } + $variantennettopreis = null; + if (!empty($loadElements['standard_price'])) { + if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { + $variantennettopreis = $this->app->erp->GetVerkaufspreisGruppe($v['id'], 1, $preisgruppe); + } else { + $variantennettopreis = $this->app->erp->GetVerkaufspreis($v['id'], 1, 0); + } + } + $sprachen = ['de', 'en']; + foreach ($sprachen as $sprache) { + $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", + $id, strtoupper($sprache), $v['id']); + $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); + if (!empty($ersetzeStandardbeschreibung)) { + $v['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + } + } - } while (count($data[$i]['matrix_varianten']['artikel'] ?? [])>=5000); + $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $v['id'], $v['pseudolager']); + if (is_numeric($v['pseudolager']) && $v['pseudolager'] < 0) { + $v['pseudolager'] = 0; + } + $projectStockId = $this->app->DB->Select("SELECT `id` FROM `projekt` WHERE `id` = '{$projekt}' AND `projektlager` = 1 LIMIT 1"); + $stock = (float) $this->app->erp->ArtikelAnzahlVerkaufbar( + $v['id'], + 0, + $projectStockId, + $id, + $lagergrundlage + ); + if ($stock < 0) { + $stock = 0; + } + $data[$i]['artikel_varianten'][] = array('nummer' => $v['nummer'], 'name_de' => $v['name_de'], 'name_en' => $v['name_en'], 'restmenge' => $v['restmenge'], 'gesperrt' => ($v['gesperrt'] == 1 || $v['intern_gesperrt'] == 1 ? 1 : 0), + 'artikel' => $v['id'], 'zolltarifnummer' => $v['zolltarifnummer'], 'ean' => $v['ean'], 'gewicht' => $v['gewicht'], 'inaktiv' => $v['inaktiv'], 'uebersicht_de' => $v['uebersicht_de'], + 'lag' => $stock, + 'pseudolager' => $v['pseudolager'], 'pseudopreis' => $v['pseudopreis'], 'preis' => $variantennettopreis, 'bruttopreis' => $variantennettopreis * $steuer, + 'artikelnummer_fremdnummern' => $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $v['id'] . "' AND nummer <> '' AND shopid = '$id' AND aktiv = '1'"), + 'steuersatz' => ($steuer - 1) * 100); + if (!empty($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'])) { + foreach ($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'] as $fkey => $fval) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); + } + } + if ($eigenschaftenuebertragen && !empty($loadElements['properties'])) { + $varianteneigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften + WHERE ew.artikel = '" . $v['id'] . "' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1 ORDER BY e.name"); + if (!empty($varianteneigenschaften)) { + foreach ($varianteneigenschaften as $eigenschaft) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaften'][] = array('name' => $eigenschaft['name'], 'values' => $eigenschaft['wert']); + } + } + $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '" . $v['id'] . "'"); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; + } + + if (!empty($freifelder) && !empty($loadElements['free_fields'])) { + foreach ($freifelder as $freifeld) { + if (method_exists($tmp, 'Get' . ucfirst($freifeld['freifeld_wawi']))) { + $_funktionsname = 'Get' . ucfirst($freifeld['freifeld_wawi']); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $v[$freifeld['freifeld_wawi']]; + } + } + //Freifeldübersetzungen + $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '" . $v['id'] . "' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); + if (!empty($freifelduebersetzungen)) { + foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); + } + } + } + if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { + $dateien = $this->getImagesForArticle($v['id']); + if (!empty($dateien)) { + foreach ($dateien as $datei) { + $filename = $this->app->erp->GetDateiName($datei['id']); + $path_info = pathinfo($filename); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['filename'][] = $filename; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extension'][] = $path_info['extension']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['titel'][] = $datei['titel']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['beschreibung'][] = $datei['beschreibung']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['stichwort'][] = $datei['subjekt']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['id'][] = $datei['id']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['version'][] = $datei['version']; + $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); + } + } + } + } + } + } else { + $data[$i]['variantevorhanden'] = 0; + } + + $result = null; + if (empty($data)) { + continue; + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($i, $id, $data); + } + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($i, $id, $data, true); + } + } return $result; - } - - if(!empty($loadElements['variants']) && $this->app->DB->Select("SELECT id FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")) { - if($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikel' AND variante = 0 AND matrixprodukt=0 AND geloescht <> 1 AND nummer != 'DEL' LIMIT 1")){ - $data[$i]['artikel_varianten'] = []; - $data[$i]['variantevorhanden'] = 1; - $varianten = "SELECT * FROM artikel WHERE variante_von = '$artikel' AND variante = 1 AND geloescht <> 1 AND nummer != 'DEL'"; - $db = $this->app->Container->get('Database'); - foreach ($db->yieldAll($varianten) as $v) { - $steuer = $steuermapping[$v['umsatzsteuer']]; - if($v['steuersatz'] != -1 && !empty($v['steuersatz'])){ - $steuer = ($v['steuersatz'] + 100) / 100; - } - if(empty($steuer)) { - $steuer = $steuernormal; - } - $variantennettopreis = null; - if(!empty($loadElements['standard_price'])){ - if($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')){ - $variantennettopreis = $this->app->erp->GetVerkaufspreisGruppe($v['id'], 1, $preisgruppe); - }else{ - $variantennettopreis = $this->app->erp->GetVerkaufspreis($v['id'], 1, 0); - } - } - $sprachen = ['de','en']; - foreach ($sprachen as $sprache){ - $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", - $id,strtoupper($sprache),$v['id']); - $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if(!empty($ersetzeStandardbeschreibung)) { - $v['name_'.$sprache] = $ersetzeStandardbeschreibung['name']; - } - } - - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $v['id'], $v['pseudolager']); - if(is_numeric($v['pseudolager']) && $v['pseudolager'] < 0) { - $v['pseudolager'] = 0; - } - $projectStockId = $this->app->DB->Select("SELECT `id` FROM `projekt` WHERE `id` = '{$projekt}' AND `projektlager` = 1 LIMIT 1"); - $stock = (float)$this->app->erp->ArtikelAnzahlVerkaufbar( - $v['id'], - 0, - $projectStockId, - $id, - $lagergrundlage - ); - if($stock < 0) { - $stock = 0; - } - $data[$i]['artikel_varianten'][] = array('nummer' => $v['nummer'], 'name_de' => $v['name_de'], 'name_en' => $v['name_en'],'restmenge' => $v['restmenge'], 'gesperrt' => ($v['gesperrt']==1||$v['intern_gesperrt']==1?1:0), - 'artikel' => $v['id'],'zolltarifnummer' => $v['zolltarifnummer'],'ean' => $v['ean'],'gewicht' => $v['gewicht'], 'inaktiv' => $v['inaktiv'], 'uebersicht_de' => $v['uebersicht_de'], - 'lag' => $stock, - 'pseudolager' => $v['pseudolager'], 'pseudopreis' => $v['pseudopreis'], 'preis' => $variantennettopreis, 'bruttopreis' => $variantennettopreis * $steuer, - 'artikelnummer_fremdnummern' => $this->app->DB->SelectArr("SELECT * FROM artikelnummer_fremdnummern WHERE artikel = '" . $v['id'] . "' AND nummer <> '' AND shopid = '$id' AND aktiv = '1'"), - 'steuersatz' => ($steuer - 1) * 100); - if(!empty($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'])) { - foreach($data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'] as $fkey => $fval) { - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten'])-1]['artikelnummer_fremdnummern'][$fkey]['nummer'] = trim($fval['nummer']); - } - } - if($eigenschaftenuebertragen && !empty($loadElements['properties'])){ - $varianteneigenschaften = $this->app->DB->SelectArr("SELECT e.name, ew.wert FROM artikeleigenschaften e INNER JOIN artikeleigenschaftenwerte ew ON e.id = ew.artikeleigenschaften - WHERE ew.artikel = '".$v['id']."' AND e.name <> '' AND ew.wert <> '' AND e.geloescht <> 1 ORDER BY e.name"); - if(!empty($varianteneigenschaften)){ - foreach($varianteneigenschaften as $eigenschaft){ - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaften'][] = array('name'=>$eigenschaft['name'], 'values'=>$eigenschaft['wert']); - } - } - $eigenschaftenuebersetzungen = $this->app->DB->SelectArr("SELECT language_from, language_to, property_from, property_to,property_value_from,property_value_to FROM article_property_translation WHERE article_id = '".$v['id']."'"); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['eigenschaftenuebersetzungen'] = $eigenschaftenuebersetzungen; - } - - if(!empty($freifelder) && !empty($loadElements['free_fields'])) - { - foreach($freifelder as $freifeld) - { - if(method_exists($tmp,'Get'.ucfirst($freifeld['freifeld_wawi']))) - { - $_funktionsname = 'Get'.ucfirst($freifeld['freifeld_wawi']); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder']['DE'][$freifeld['freifeld_shop']] = $v[$freifeld['freifeld_wawi']]; - } - } - //Freifeldübersetzungen - $freifelduebersetzungen = $this->app->DB->SelectArr("SELECT sf.freifeld_shop, af.sprache, af.nummer, af.wert FROM shopexport_freifelder sf JOIN artikel_freifelder af ON sf.freifeld_wawi = CONCAT('freifeld',af.nummer) WHERE sf.shop = '$id' AND af.artikel = '".$v['id']."' AND sf.aktiv = 1 AND sf.freifeld_wawi <> '' AND sf.freifeld_shop <> '' AND af.wert <> ''"); - if(!empty($freifelduebersetzungen)){ - foreach ($freifelduebersetzungen as $ffukey => $ffuvalue) { - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['freifelder'][$ffuvalue['sprache']][] = array('mapping' => $ffuvalue['freifeld_shop'], 'freifeldnummer' => $ffuvalue['nummer'], 'wert' => $ffuvalue['wert']); - } - } - } - if ($shopbilderuebertragen && !empty($loadElements['pictures'])) { - $dateien = $this->getImagesForArticle($v['id']); - if (!empty($dateien)) { - foreach ($dateien as $datei) { - $filename = $this->app->erp->GetDateiName($datei['id']); - $path_info = pathinfo($filename); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['datei'][] = base64_encode($this->app->erp->GetDatei($datei['id'])); - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['filename'][] = $filename; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extension'][] = $path_info['extension']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['titel'][] = $datei['titel']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['beschreibung'][] = $datei['beschreibung']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['stichwort'][] = $datei['subjekt']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['id'][] = $datei['id']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['version'][] = $datei['version']; - $data[$i]['artikel_varianten'][count($data[$i]['artikel_varianten']) - 1]['Dateien']['extid'][] = $this->GetShopexportMappingExt($id, 'datei', $datei['id']); - } - } - } - } - } - }else{ - $data[$i]['variantevorhanden'] = 0; - } - - $result = null; - if(empty($data)){ - continue; - } - if(!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } } - return $result; - } - /** * @param int $articleId * @return array|null */ - protected function getImagesForArticle($articleId){ - $query = sprintf("SELECT d.id AS `id`, dv.id AS `vid`, d.titel, d.beschreibung, ds.subjekt, ds.sort, dv.version AS `version` + protected function getImagesForArticle($articleId) { + $query = sprintf("SELECT d.id AS `id`, dv.id AS `vid`, d.titel, d.beschreibung, ds.subjekt, ds.sort, dv.version AS `version` FROM `datei_stichwoerter` AS `ds` INNER JOIN `datei` AS `d` ON ds.datei = d.id INNER JOIN `datei_version` AS `dv` ON dv.datei = ds.datei @@ -2209,117 +2048,111 @@ class Remote WHERE ds.parameter = %d AND ds.objekt like 'Artikel' AND ds.subjekt LIKE 'Shopbild' AND d.geloescht = 0 ORDER BY ds.sort", $articleId); - return $this->app->DB->SelectArr($query); - } - - protected function sendlistlager($i,$id,$data){ - $data2 = $data; - foreach ($data2 as $key => $value){ - $data2[$key]['artikel'] = $value['artikelid']; + return $this->app->DB->SelectArr($query); } - $result = $this->RemoteCommand($id,'sendlistlager',$data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); - return $result; - } - protected function sendlist($i,$id,$data,$isLagerExported){ - /** @var Shopexport $objShopexport */ - $objShopexport = $this->app->loadModule('shopexport'); - $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); - $hash = $changedHash['hash']; - //$changedHash = $changedHash['changed']; + protected function sendlistlager($i, $id, $data) { + $data2 = $data; + foreach ($data2 as $key => $value) { + $data2[$key]['artikel'] = $value['artikelid']; + } + $result = $this->RemoteCommand($id, 'sendlistlager', $data2); + $this->app->DB->Update( + sprintf( + 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', + $data2[$i]['artikel'], $id + ) + ); + return $result; + } - $result = $this->RemoteCommand($id,'sendlist',$data); - $checkAo = $this->app->DB->Select( - sprintf( - 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', - $data[0]['artikel'], $id - ) - ); - if(empty($checkAo)) { - $this->app->DB->Insert( - sprintf( - 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) + protected function sendlist($i, $id, $data, $isLagerExported) { + /** @var Shopexport $objShopexport */ + $objShopexport = $this->app->loadModule('shopexport'); + $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); + $hash = $changedHash['hash']; + //$changedHash = $changedHash['changed']; + + $result = $this->RemoteCommand($id, 'sendlist', $data); + $checkAo = $this->app->DB->Select( + sprintf( + 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', + $data[0]['artikel'], $id + ) + ); + if (empty($checkAo)) { + $this->app->DB->Insert( + sprintf( + 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) VALUES (%d, %d, 1, 1) ', - $data[0]['artikel'], $id - ) - ); - } - $this->app->DB->Update( - sprintf( - "UPDATE artikel_onlineshops + $data[0]['artikel'], $id + ) + ); + } + $this->app->DB->Update( + sprintf( + "UPDATE artikel_onlineshops SET last_article_transfer = NOW(), last_article_hash = '%s' WHERE artikel = %d AND shop = %d", - $this->app->DB->real_escape_string($hash) ,$data[0]['artikel'], $id - ) - ); - if(!empty($result) && is_array($result) && !empty($result['new'])) - { - foreach($result['new'] as $artikelid => $fremdnummer) - { - $artikelid = (int)$artikelid; - $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); - if($artikelid > 0 && $artikelnummer != trim($fremdnummer) && - ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || - $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") - ) && trim($fremdnummer) !== '') - { - //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. - if(!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '".trim($this->app->DB->real_escape_string($fremdnummer))."') LIMIT 1 ")) - { - $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) - VALUES ('$artikelid','Erstellt durch Artikelexport','".trim($this->app->DB->real_escape_string($fremdnummer))."','$id','".((isset($this->app->User)&& method_exists($this->app->User,'GetName'))?$this->app->DB->real_escape_string($this->app->User->GetName()):'Cronjob') ."',now(),0) + $this->app->DB->real_escape_string($hash), $data[0]['artikel'], $id + ) + ); + if (!empty($result) && is_array($result) && !empty($result['new'])) { + foreach ($result['new'] as $artikelid => $fremdnummer) { + $artikelid = (int) $artikelid; + $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); + if ($artikelid > 0 && $artikelnummer != trim($fremdnummer) && + ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || + $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") + ) && trim($fremdnummer) !== '') { + //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { + $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) + VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) "); - } + } + } + } + if (isset($result['anzahl'])) { + $result = $result['anzahl']; + }//Altes Verhalten } - } - if(isset($result['anzahl'])) - { - $result = $result['anzahl']; - }//Altes Verhalten + if (!$isLagerExported) { + $data2 = $data; + foreach ($data2 as $key => $value) { + $data2[$key]['artikel'] = $value['artikelid']; + } + $this->RemoteCommand($id, 'sendlistlager', $data2); + $this->app->DB->Update( + sprintf( + 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', + $data2[$i]['artikel'], $id + ) + ); + } + return $result; } - if(!$isLagerExported){ - $data2 = $data; - foreach ($data2 as $key => $value){ - $data2[$key]['artikel'] = $value['artikelid']; - } - $this->RemoteCommand($id,'sendlistlager',$data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); - } - return $result; - } - public function getDataToSendForUpdateOrder(int $shopId, int $orderId): ?OrderStatusUpdateRequest - { - $orderArr = $this->app->DB->SelectRow("SELECT `zahlungsweise`, `shopextid` FROM `auftrag` WHERE `id` = $orderId LIMIT 1"); - if (empty($orderArr)) - return null; + public function getDataToSendForUpdateOrder(int $shopId, int $orderId): ?OrderStatusUpdateRequest { + $orderArr = $this->app->DB->SelectRow("SELECT `zahlungsweise`, `shopextid` FROM `auftrag` WHERE `id` = $orderId LIMIT 1"); + if (empty($orderArr)) + return null; - $data = new OrderStatusUpdateRequest(); - $data->orderId = $orderId; - $data->shopOrderId = $orderArr['shopextid']; + $data = new OrderStatusUpdateRequest(); + $data->orderId = $orderId; + $data->shopOrderId = $orderArr['shopextid']; - $statusArr = $this->app->DB->SelectFirstCols("SELECT DISTINCT status FROM auftrag WHERE id = $orderId OR teillieferungvon = $orderId"); - if (in_array('storniert', $statusArr)) - $data->orderStatus = OrderStatus::Cancelled; - if (in_array('abgeschlossen', $statusArr)) - $data->orderStatus = OrderStatus::Completed; - if (in_array('freigegeben', $statusArr)) - $data->orderStatus = OrderStatus::InProgress; - if (in_array('angelegt', $statusArr)) - $data->orderStatus = OrderStatus::Imported; + $statusArr = $this->app->DB->SelectFirstCols("SELECT DISTINCT status FROM auftrag WHERE id = $orderId OR teillieferungvon = $orderId"); + if (in_array('storniert', $statusArr)) + $data->orderStatus = OrderStatus::Cancelled; + if (in_array('abgeschlossen', $statusArr)) + $data->orderStatus = OrderStatus::Completed; + if (in_array('freigegeben', $statusArr)) + $data->orderStatus = OrderStatus::InProgress; + if (in_array('angelegt', $statusArr)) + $data->orderStatus = OrderStatus::Imported; - $sql = " + $sql = " SELECT DISTINCT v.id, v.tracking, @@ -2340,530 +2173,483 @@ class Remote WHERE (a.id = $orderId OR a.teillieferungvon = $orderId) AND v.id IS NOT NULL ORDER BY v.id"; - $shipments = $this->app->DB->SelectArr($sql); - foreach ($shipments as $shipment) { - $item = new Shipment(); - $item->id = $shipment['id']; - $item->trackingNumber = $shipment['tracking']; - $item->trackingUrl = $shipment['tracking_link']; - $item->shippingMethod = $shipment['versandart']; - $data->shipments[] = $item; - } + $shipments = $this->app->DB->SelectArr($sql); + foreach ($shipments as $shipment) { + $item = new Shipment(); + $item->id = $shipment['id']; + $item->trackingNumber = $shipment['tracking']; + $item->trackingUrl = $shipment['tracking_link']; + $item->shippingMethod = $shipment['versandart']; + $data->shipments[] = $item; + } - return $data; - } + return $data; + } - /** - * @param int $shopId - * @param int $orderId - * - * @throws Exception - */ - public function RemoteUpdateAuftrag($shopId, $orderId) - { - $data = $this->getDataToSendForUpdateOrder((int)$shopId, (int)$orderId); - if($data?->orderStatus !== OrderStatus::Completed) - return; + /** + * @param int $shopId + * @param int $orderId + * + * @throws Exception + */ + public function RemoteUpdateAuftrag($shopId, $orderId) { + $data = $this->getDataToSendForUpdateOrder((int) $shopId, (int) $orderId); + if ($data?->orderStatus !== OrderStatus::Completed) + return; - $bearbeiter = 'Cronjob'; - if(isset($this->app->User)){ - $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); - } + $bearbeiter = 'Cronjob'; + if (isset($this->app->User)) { + $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); + } - $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); - if($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()){ - $query = sprintf('UPDATE `auftrag` + $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); + if ($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()) { + $query = sprintf('UPDATE `auftrag` SET `shop_status_update_attempt` = `shop_status_update_attempt` + 1, `shop_status_update_last_attempt_at` = NOW() WHERE `id` = %d', $orderId); - $this->app->DB->Update($query); + $this->app->DB->Update($query); - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); - $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ - 'orderId' => $orderId, - 'shopId' => $shopId, - 'message' => $response->getMessage()],true)); + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); + $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ + 'orderId' => $orderId, + 'shopId' => $shopId, + 'message' => $response->getMessage()], true)); - return; - } + return; + } - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); - $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); - } - - /** - * @param int $shopId - * @param string $auftrag - * - * @param string $internet - * - * @throws Exception - */ - public function RemoteDeleteAuftrag($shopId, $auftrag, $internet='') - { - $data['auftrag'] = $auftrag; - $data['internet'] = $internet; - $this->RemoteCommand($shopId,'deleteauftrag',$data); - } - - /** - * @param int $shopId - * @param int $orderId - * - * @throws Exception - */ - public function RemoteStorniereAuftrag($shopId, $orderId) - { - $orderArr = $this->app->DB->SelectRow("SELECT shopextid, internet FROM auftrag WHERE id='$orderId' LIMIT 1"); - if(empty($orderArr)) { - return; + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); + $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); } - $shopextid = $orderArr['shopextid']; - $internet = $orderArr['internet']; - $data['auftrag'] = $shopextid; - $data['internet'] = $internet; - - $this->app->DB->Insert(" + + /** + * @param int $shopId + * @param string $auftrag + * + * @param string $internet + * + * @throws Exception + */ + public function RemoteDeleteAuftrag($shopId, $auftrag, $internet = '') { + $data['auftrag'] = $auftrag; + $data['internet'] = $internet; + $this->RemoteCommand($shopId, 'deleteauftrag', $data); + } + + /** + * @param int $shopId + * @param int $orderId + * + * @throws Exception + */ + public function RemoteStorniereAuftrag($shopId, $orderId) { + $orderArr = $this->app->DB->SelectRow("SELECT shopextid, internet FROM auftrag WHERE id='$orderId' LIMIT 1"); + if (empty($orderArr)) { + return; + } + $shopextid = $orderArr['shopextid']; + $internet = $orderArr['internet']; + $data['auftrag'] = $shopextid; + $data['internet'] = $internet; + + $this->app->DB->Insert(" INSERT INTO auftrag_protokoll (auftrag, zeit, bearbeiter, grund) - VALUES ($orderId,now(),'".(isset($this->app->User)?$this->app->DB->real_escape_string($this->app->User->GetName()):'Cronjob')."', + VALUES ($orderId,now(),'" . (isset($this->app->User) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "', 'Stonierung an Shop übertragen')" - ); - $this->RemoteCommand($shopId,'storniereauftrag',$data); - $shopextstatus='storniert'; - $this->app->DB->Update("UPDATE auftrag SET shopextstatus='$shopextstatus' WHERE id='$orderId' LIMIT 1"); - } + ); + $this->RemoteCommand($shopId, 'storniereauftrag', $data); + $shopextstatus = 'storniert'; + $this->app->DB->Update("UPDATE auftrag SET shopextstatus='$shopextstatus' WHERE id='$orderId' LIMIT 1"); + } - /** - * @param int $shopId - * @param int $fileId - * - * @return mixed - * @throws Exception - */ - public function RemoteDeleteFile($shopId, $fileId) - { - $inhalt = $this->app->erp->GetDatei($fileId); - $fileArr = $this->app->DB->SelectRow("SELECT titel,beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); - $titel = $fileArr['titel']; - $beschreibung = $fileArr['beschreibung']; + /** + * @param int $shopId + * @param int $fileId + * + * @return mixed + * @throws Exception + */ + public function RemoteDeleteFile($shopId, $fileId) { + $inhalt = $this->app->erp->GetDatei($fileId); + $fileArr = $this->app->DB->SelectRow("SELECT titel,beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); + $titel = $fileArr['titel']; + $beschreibung = $fileArr['beschreibung']; - $data['datei'] = $fileId; - //$data['checksum'] = md5($inhalt); - $data['checksum'] = md5($inhalt.$titel.$beschreibung); - return $this->RemoteCommand($shopId,'deletefile',$data); - } + $data['datei'] = $fileId; + //$data['checksum'] = md5($inhalt); + $data['checksum'] = md5($inhalt . $titel . $beschreibung); + return $this->RemoteCommand($shopId, 'deletefile', $data); + } - /** - * @param int $articleId - * @param int $shopId - */ - public function RemoteUpdateFilesArtikel($articleId, $shopId) - { - $files = $this->app->DB->SelectArr("SELECT DISTINCT ds.datei + /** + * @param int $articleId + * @param int $shopId + */ + public function RemoteUpdateFilesArtikel($articleId, $shopId) { + $files = $this->app->DB->SelectArr("SELECT DISTINCT ds.datei FROM datei_stichwoerter ds, datei d, artikel a WHERE d.id=ds.datei AND (ds.subjekt='Shopbild' OR ds.subjekt='Gruppenbild') AND ((ds.objekt='Artikel' AND ds.parameter=a.id) OR (ds.objekt='Kampangen' AND ds.parameter='$shopId')) AND - d.firma='".$this->app->User->GetFirma()."' AND a.shop='$shopId' AND a.id='$articleId'" - ); + d.firma='" . $this->app->User->GetFirma() . "' AND a.shop='$shopId' AND a.id='$articleId'" + ); - $tmp = $this->app->remote->RemoteGetFileListArticle($shopId,$articleId); - if(!empty($tmp)){ - foreach ($tmp as $row) { - $checkarray[$row['datei']] = $row['checksum']; - } - } - - if(!empty($files)){ - foreach($files as $file) { - $fid = $file['datei']; - $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fid' LIMIT 1"); - if($geloescht){ - $this->app->remote->RemoteDeleteFile($shopId, $fid); - $checkarray[$fid] = 'delete'; - }else{ - $md5 = !empty($checkarray[$fid]) ? (String)$checkarray[$fid] : ''; - $md5file = md5($this->app->erp->GetDatei($fid)); - if($md5 !== $md5file){ - $this->app->remote->RemoteSendFile($shopId, $fid); - $this->app->remote->RemoteAddFileSubject($shopId, $fid); - $checkarray[$fid] = 'update'; - } + $tmp = $this->app->remote->RemoteGetFileListArticle($shopId, $articleId); + if (!empty($tmp)) { + foreach ($tmp as $row) { + $checkarray[$row['datei']] = $row['checksum']; + } } - $checkarray[$fid] = 'mark'; - } - } - if(!empty($checkarray)) - { - foreach($checkarray as $key=>$value) - { - if($checkarray[$key]!=='mark' && $checkarray[$key]!=='delete' && $checkarray[$key]!=='update') - { - $this->app->remote->RemoteDeleteFile($shopId,$key); + + if (!empty($files)) { + foreach ($files as $file) { + $fid = $file['datei']; + $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fid' LIMIT 1"); + if ($geloescht) { + $this->app->remote->RemoteDeleteFile($shopId, $fid); + $checkarray[$fid] = 'delete'; + } else { + $md5 = !empty($checkarray[$fid]) ? (String) $checkarray[$fid] : ''; + $md5file = md5($this->app->erp->GetDatei($fid)); + if ($md5 !== $md5file) { + $this->app->remote->RemoteSendFile($shopId, $fid); + $this->app->remote->RemoteAddFileSubject($shopId, $fid); + $checkarray[$fid] = 'update'; + } + } + $checkarray[$fid] = 'mark'; + } + } + if (!empty($checkarray)) { + foreach ($checkarray as $key => $value) { + if ($checkarray[$key] !== 'mark' && $checkarray[$key] !== 'delete' && $checkarray[$key] !== 'update') { + $this->app->remote->RemoteDeleteFile($shopId, $key); + } + } } - } } - } + /** + * @param int $shopId + * @param int $fileId + * + * @return mixed|string + * @throws Exception + */ + public function RemoteSendFile($shopId, $fileId) { + // sende stichwoerter + $fileArr = $this->app->DB->SelectRow("SELECT geloescht, titel, beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); + if (empty($fileArr)) { + return ''; + } + $geloescht = $fileArr['geloescht']; + $titel = $fileArr['titel']; + $beschreibung = $fileArr['beschreibung']; - /** - * @param int $shopId - * @param int $fileId - * - * @return mixed|string - * @throws Exception - */ - public function RemoteSendFile($shopId, $fileId) - { - // sende stichwoerter - $fileArr = $this->app->DB->SelectRow("SELECT geloescht, titel, beschreibung FROM datei WHERE id='$fileId' LIMIT 1"); - if(empty($fileArr)) { - return ''; + $inhalt = $this->app->erp->GetDatei($fileId); + $data['datei'] = $fileId; + $data['titel'] = $titel; + $data['beschreibung'] = $beschreibung; + $data['inhalt'] = base64_encode($inhalt); + $data['checksum'] = md5($inhalt . $titel . $beschreibung); + if (!$geloescht) { + return $this->RemoteCommand($shopId, 'sendfile', $data); + } + return ''; } - $geloescht = $fileArr['geloescht']; - $titel = $fileArr['titel']; - $beschreibung = $fileArr['beschreibung']; - $inhalt = $this->app->erp->GetDatei($fileId); - $data['datei'] = $fileId; - $data['titel'] = $titel; - $data['beschreibung'] =$beschreibung; - $data['inhalt'] = base64_encode($inhalt); - $data['checksum'] = md5($inhalt.$titel.$beschreibung); - if(!$geloescht){ - return $this->RemoteCommand($shopId, 'sendfile', $data); - } - return ''; - } - - /** - * @param int $shopId - * @param int $fileId - * - * @throws Exception - */ - public function RemoteAddFileSubject($shopId, $fileId) - { - // sende stichwoerter - $fileList = $this->app->DB->SelectArr("SELECT subjekt, parameter + /** + * @param int $shopId + * @param int $fileId + * + * @throws Exception + */ + public function RemoteAddFileSubject($shopId, $fileId) { + // sende stichwoerter + $fileList = $this->app->DB->SelectArr("SELECT subjekt, parameter FROM datei_stichwoerter WHERE (objekt='Artikel' OR objekt='Kampangen') AND datei='$fileId'" - ); - if(empty($fileList)) { - return; - } - - foreach($fileList as $fileRow) { - $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fileId' LIMIT 1"); - $stichwort['subjekt'] = $fileRow['subjekt']; - $stichwort['artikel'] = $fileRow['parameter']; - $stichwort['datei'] = $fileId; - if(!$geloescht){ - $this->RemoteCommand($shopId, 'addfilesubjekt', $stichwort); - } - } - } - - /** - * @param int $shopId - * @param array $artikel - * - * @return mixed - * @throws Exception - */ - public function RemoteDeleteArticle($shopId,$artikel) - { - return $this->RemoteCommand($shopId,'deletearticle',$artikel); - } - - /** - * @param int $shopId - * @param array $partner - * - * @return mixed - * @throws Exception - */ - public function RemoteSendPartner($shopId, $partner) - { - return $this->RemoteCommand($shopId, 'partnerlist', $partner); - } - - /** - * @param object $obj - * @param string $methodname - * - * @return string - */ - public function getMethod($obj, $methodname) - { - $methodname = trim((String)$methodname); - if($methodname === '') - { - return ''; - } - if(!$obj) - { - return ''; - } - if(method_exists($obj, $methodname)) - { - return $methodname; - } - $methods = get_class_methods($obj); - $classname = get_class($obj); - foreach($methods as $v) - { - if(strtolower($v) === 'import'.strtolower($methodname)) - { - return $v; - } - if(strtolower($v) === strtolower($classname.$methodname)) - { - return $v; - } - } - foreach($methods as $v) - { - if(strtolower($v) === strtolower($methodname)) - { - return $v; - } - } - return ''; - } - - /** - * @param int $id - * @param string $action - * @param string|array $data - * - * @return mixed - * @throws Exception - */ - public function RemoteCommand($id,$action,$data='') - { - $challenge = ''; - $shoptyp = $this->app->DB->Select("SELECT shoptyp FROM shopexport WHERE id='$id' LIMIT 1"); - $modulename = trim($this->app->DB->Select("SELECT modulename FROM shopexport WHERE id='$id' LIMIT 1"),'.'); - $isActionAuth = $action === 'auth'; - if($shoptyp === 'custom') - { - if($modulename != '') - { - - $file = dirname(__DIR__) . '/plugins/external/shopimporter/'.$modulename; - $classa = explode('_',str_replace('_'.$id.'.php','', $modulename)); - foreach($classa as $k => $v) - { - $classa[$k] = ucfirst($v); + ); + if (empty($fileList)) { + return; } - $class = implode('_', $classa); - if($this->app->DB->Select("SELECT aktiv FROM shopexport WHERE id = '$id' LIMIT 1")) - { - if(file_exists($file)) - { - include_once($file); - if(class_exists($class)){ - $obj = new $class($this->app, true); - if($obj){ - if(method_exists($obj,'getKonfig')) - { - $obj->getKonfig($id, $data); - } - $method = $this->getMethod($obj, $action); - if(method_exists($obj,$method)) - { - $ret = $obj->$method(); - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; + + foreach ($fileList as $fileRow) { + $geloescht = $this->app->DB->Select("SELECT geloescht FROM datei WHERE id='$fileId' LIMIT 1"); + $stichwort['subjekt'] = $fileRow['subjekt']; + $stichwort['artikel'] = $fileRow['parameter']; + $stichwort['datei'] = $fileId; + if (!$geloescht) { + $this->RemoteCommand($shopId, 'addfilesubjekt', $stichwort); } - }elseif($isActionAuth) - { - return 'Fehler: Datei '.$file.' existiert nicht'; - } - }elseif($isActionAuth) { - return 'Fehler: Schnittstelle nicht aktiv'; } - } - return ''; } - if($shoptyp === 'intern') - { - if($modulename != '') - { - if($this->app->erp->ModulVorhanden($modulename)) - { - $obj = $this->app->erp->LoadModul($modulename); - if($obj){ - if(method_exists($obj,'getKonfig')) - { - $obj->getKonfig($id, $data); + + /** + * @param int $shopId + * @param array $artikel + * + * @return mixed + * @throws Exception + */ + public function RemoteDeleteArticle($shopId, $artikel) { + return $this->RemoteCommand($shopId, 'deletearticle', $artikel); + } + + /** + * @param int $shopId + * @param array $partner + * + * @return mixed + * @throws Exception + */ + public function RemoteSendPartner($shopId, $partner) { + return $this->RemoteCommand($shopId, 'partnerlist', $partner); + } + + /** + * @param object $obj + * @param string $methodname + * + * @return string + */ + public function getMethod($obj, $methodname) { + $methodname = trim((String) $methodname); + if ($methodname === '') { + return ''; + } + if (!$obj) { + return ''; + } + if (method_exists($obj, $methodname)) { + return $methodname; + } + $methods = get_class_methods($obj); + $classname = get_class($obj); + foreach ($methods as $v) { + if (strtolower($v) === 'import' . strtolower($methodname)) { + return $v; } - $method = 'Import'.$action; - if(method_exists($obj,$method)) { - try { - $ret = $obj->$method(); - } - catch(Exception $e) { - if($isActionAuth) { - return 'Fehler: '.$e->getMessage(); + if (strtolower($v) === strtolower($classname . $methodname)) { + return $v; + } + } + foreach ($methods as $v) { + if (strtolower($v) === strtolower($methodname)) { + return $v; + } + } + return ''; + } + + /** + * @param int $id + * @param string $action + * @param string|array $data + * + * @return mixed + * @throws Exception + */ + public function RemoteCommand($id, $action, $data = '') { + $challenge = ''; + $shoptyp = $this->app->DB->Select("SELECT shoptyp FROM shopexport WHERE id='$id' LIMIT 1"); + $modulename = trim($this->app->DB->Select("SELECT modulename FROM shopexport WHERE id='$id' LIMIT 1"), '.'); + $isActionAuth = $action === 'auth'; + if ($shoptyp === 'custom') { + if ($modulename != '') { + + $file = dirname(__DIR__) . '/plugins/external/shopimporter/' . $modulename; + $classa = explode('_', str_replace('_' . $id . '.php', '', $modulename)); + foreach ($classa as $k => $v) { + $classa[$k] = ucfirst($v); } + $class = implode('_', $classa); + if ($this->app->DB->Select("SELECT aktiv FROM shopexport WHERE id = '$id' LIMIT 1")) { + if (file_exists($file)) { + include_once($file); + if (class_exists($class)) { + $obj = new $class($this->app, true); + if ($obj) { + if (method_exists($obj, 'getKonfig')) { + $obj->getKonfig($id, $data); + } + $method = $this->getMethod($obj, $action); + if (method_exists($obj, $method)) { + $ret = $obj->$method(); + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Datei ' . $file . ' existiert nicht'; + } + } elseif ($isActionAuth) { + return 'Fehler: Schnittstelle nicht aktiv'; + } + } + return ''; + } + if ($shoptyp === 'intern') { + if ($modulename != '') { + if ($this->app->erp->ModulVorhanden($modulename)) { + $obj = $this->app->erp->LoadModul($modulename); + if ($obj) { + if (method_exists($obj, 'getKonfig')) { + $obj->getKonfig($id, $data); + } + $method = 'Import' . $action; + if (method_exists($obj, $method)) { + try { + $ret = $obj->$method(); + } catch (Exception $e) { + if ($isActionAuth) { + return 'Fehler: ' . $e->getMessage(); + } + return ''; + } + + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + $this->parseReturn($ret, $id, $action); + return $ret; + } + } elseif ($isActionAuth) { + return 'Fehler: Importer konnte nicht initialisiert werden'; + } + } elseif ($isActionAuth) { + return 'Fehler: Dieses Modul ist nicht verfügbar'; + } + } elseif ($isActionAuth) { + return 'Fehler: Kein Modul vorhanden'; + } + return ''; + } + $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + if ($shopexport) { + if ($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom') { return ''; - } - - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - $this->parseReturn($ret, $id, $action); - return $ret; } - }elseif($isActionAuth) - { - return 'Fehler: Importer konnte nicht initialisiert werden'; - } - }elseif($isActionAuth) - { - return 'Fehler: Dieses Modul ist nicht verfügbar'; + $token = $shopexport['token']; + $url = $shopexport['url']; + $z = $shopexport['passwort']; + $bezeichnung = $shopexport['bezeichnung']; + } else { + $token = ''; + $z = ''; + $url = ''; } - }elseif($isActionAuth) - { - return 'Fehler: Kein Modul vorhanden'; - } - return ''; - } - $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - if($shopexport){ - if($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom'){ - return ''; - } - $token = $shopexport['token']; - $url = $shopexport['url']; - $z = $shopexport['passwort']; - $bezeichnung = $shopexport['bezeichnung']; - } - else { - $token = ''; - $z = ''; - $url = ''; - } - if($isActionAuth) { - if($token === '' || strlen($z) < 32 || $url === '') { - return 'Fehler: Bitte Zugangsdaten prüfen'; - } - } - elseif($token === '' || strlen($z) < 32 || $url === '' || !$this->app->DB->Select("SELECT id FROM shopexport WHERE id = '$id' AND aktiv = 1 LIMIT 1")){ - return ''; - } - - $tmp = parse_url($url); - $tmp['host'] = rtrim($tmp['host'],'/'); - $tmp['path'] = rtrim($tmp['path'],'/').'/'; - - $aes = new AES($z); - $token = base64_encode($aes->encrypt(serialize($token))); - $client = new HttpClient($tmp['host'], stripos($url,'https') === 0?443:80); - $geturl = $tmp['path'].'index.php?module=import&action='.$action.'&challenge='.(isset($challenge)?$challenge:''); - //Kein Fragezeichen vor module=import... - if(false !== stripos($bezeichnung, 'woocommerce')) { - $geturl = $tmp['path'].'module=import&action='.$action.'&challenge='.(isset($challenge)?$challenge:''); - } - if(false !== stripos($bezeichnung, 'shopware plugin')) { - $geturl = $tmp['path'].'wawisionimporter/?smodule=import&saction='.$action.'&challenge='.(isset($challenge)?$challenge:''); - } - - $post_data['token'] = $token; - $post_data['data'] = base64_encode(serialize($data)); - $client->timeout = 120; - if(!$client->post($geturl,$post_data)) { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); - throw new Exception('An error occurred: '.$client->getError()); - //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); - } - $ret = unserialize(base64_decode($client->getContent())); - if(!empty($this->app->stringcleaner)){ - $this->app->stringcleaner->XMLArray_clean($ret); - } - $this->parseReturn($ret, $id, $action); - return $ret; - } - - /** - * @param mixed $ret - * @param int $id - * @param string $action - */ - public function parseReturn($ret, $id, $action) - { - if($action === 'getarticlelist') { - if(empty($ret)) { - return; - } - $anz = 0; - if(empty($ret['errors'])) { - foreach($ret as $v) { - $anz++; - $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$id', '".$this->app->DB->real_escape_string($v)."')"); + if ($isActionAuth) { + if ($token === '' || strlen($z) < 32 || $url === '') { + return 'Fehler: Bitte Zugangsdaten prüfen'; + } + } elseif ($token === '' || strlen($z) < 32 || $url === '' || !$this->app->DB->Select("SELECT id FROM shopexport WHERE id = '$id' AND aktiv = 1 LIMIT 1")) { + return ''; } - if(!$this->app->DB->Select("SELECT id FROM `prozessstarter` WHERE aktiv = 1 AND parameter = 'getarticles' LIMIT 1")) { - $this->app->DB->Update("UPDATE `prozessstarter` SET aktiv = 1 WHERE parameter = 'getarticles' LIMIT 1"); + + $tmp = parse_url($url); + $tmp['host'] = rtrim($tmp['host'], '/'); + $tmp['path'] = rtrim($tmp['path'], '/') . '/'; + + $aes = new AES($z); + $token = base64_encode($aes->encrypt(serialize($token))); + $client = new HttpClient($tmp['host'], stripos($url, 'https') === 0 ? 443 : 80); + $geturl = $tmp['path'] . 'index.php?module=import&action=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); + //Kein Fragezeichen vor module=import... + if (false !== stripos($bezeichnung, 'woocommerce')) { + $geturl = $tmp['path'] . 'module=import&action=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); } - $this->app->DB->Update("UPDATE `prozessstarter` SET letzteausfuerhung = DATE_SUB(now(), INTERVAL periode MINUTE) WHERE aktiv = 1 AND parameter = 'getarticles' AND mutex = 0 LIMIT 1"); - } - $this->app->erp->SetKonfigurationValue('artikelimportanzahl_'.$id, $anz); + if (false !== stripos($bezeichnung, 'shopware plugin')) { + $geturl = $tmp['path'] . 'wawisionimporter/?smodule=import&saction=' . $action . '&challenge=' . (isset($challenge) ? $challenge : ''); + } + + $post_data['token'] = $token; + $post_data['data'] = base64_encode(serialize($data)); + $client->timeout = 120; + if (!$client->post($geturl, $post_data)) { + $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection, 'An error occurred: ' . $client->getError())); + throw new Exception('An error occurred: ' . $client->getError()); + //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); + } + $ret = unserialize(base64_decode($client->getContent())); + if (!empty($this->app->stringcleaner)) { + $this->app->stringcleaner->XMLArray_clean($ret); + } + $this->parseReturn($ret, $id, $action); + return $ret; } - } - /** - * @param int $id - * @param string $action - * @param string|array $data - * - * @return mixed|string - * @throws Exception - */ - public function RemoteCommandAES($id,$action,$data='') - { - $challenge = ''; - $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); - if(!empty($shopexport)){ - if($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom'){ - return ''; - } - $token = $shopexport['token']; - $url = $shopexport['url']; - $z = $shopexport['passwort']; - if($z === '' || $token === '' || $url === '') - { - throw new Exception('Der ImportKey/ImportToken/ImportUrl ist leer'); - } + /** + * @param mixed $ret + * @param int $id + * @param string $action + */ + public function parseReturn($ret, $id, $action) { + if ($action === 'getarticlelist') { + if (empty($ret)) { + return; + } + $anz = 0; + if (empty($ret['errors'])) { + foreach ($ret as $v) { + $anz++; + $this->app->DB->Insert("INSERT INTO shopexport_getarticles (shop, nummer) VALUES ('$id', '" . $this->app->DB->real_escape_string($v) . "')"); + } + if (!$this->app->DB->Select("SELECT id FROM `prozessstarter` WHERE aktiv = 1 AND parameter = 'getarticles' LIMIT 1")) { + $this->app->DB->Update("UPDATE `prozessstarter` SET aktiv = 1 WHERE parameter = 'getarticles' LIMIT 1"); + } + $this->app->DB->Update("UPDATE `prozessstarter` SET letzteausfuerhung = DATE_SUB(now(), INTERVAL periode MINUTE) WHERE aktiv = 1 AND parameter = 'getarticles' AND mutex = 0 LIMIT 1"); + } + $this->app->erp->SetKonfigurationValue('artikelimportanzahl_' . $id, $anz); + } } - $tmp = parse_url($url); - $aes = new AES($z); - $token = base64_encode($aes->encrypt(serialize($token))); + /** + * @param int $id + * @param string $action + * @param string|array $data + * + * @return mixed|string + * @throws Exception + */ + public function RemoteCommandAES($id, $action, $data = '') { + $challenge = ''; + $shopexport = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); + if (!empty($shopexport)) { + if ($shopexport['shoptyp'] === 'intern' || $shopexport['shoptyp'] === 'custom') { + return ''; + } + $token = $shopexport['token']; + $url = $shopexport['url']; + $z = $shopexport['passwort']; + if ($z === '' || $token === '' || $url === '') { + throw new Exception('Der ImportKey/ImportToken/ImportUrl ist leer'); + } + } + $tmp = parse_url($url); - $client = new HttpClient($tmp['host']); - $geturl = $tmp['path'].'index.php?module=import&action='.$action.'&challenge='.$challenge; + $aes = new AES($z); + $token = base64_encode($aes->encrypt(serialize($token))); - $post_data['token'] = $token; - $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); + $client = new HttpClient($tmp['host']); + $geturl = $tmp['path'] . 'index.php?module=import&action=' . $action . '&challenge=' . $challenge; - if(!$client->post($geturl,$post_data)) - { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection,'An error occurred: '.$client->getError())); - throw new Exception('An error occurred: '.$client->getError()); + $post_data['token'] = $token; + $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); + + if (!$client->post($geturl, $post_data)) { + $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection, 'An error occurred: ' . $client->getError())); + throw new Exception('An error occurred: ' . $client->getError()); + } + return unserialize($aes->decrypt(base64_decode($client->getContent()))); } - return unserialize($aes->decrypt(base64_decode($client->getContent()))); - } } + From 1cc50d5cd7846f145f105dc49596c4c9e03451f0 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Sat, 31 Aug 2024 13:13:08 +0200 Subject: [PATCH 50/52] class.remote.php improvements --- www/lib/class.remote.php | 340 ++++++++++++++++++++++----------------- 1 file changed, 193 insertions(+), 147 deletions(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index e87eb432..96f890aa 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -2,6 +2,7 @@ /* * SPDX-FileCopyrightText: 2022-2024 Andreas Palm + * SPDX-FileCopyrightText: 2024 OpenXE project * SPDX-FileCopyrightText: 2019 Xentral (c) Xentral ERP Software GmbH, Fuggerstrasse 11, D-86150 Augsburg, Germany * * SPDX-License-Identifier: LicenseRef-EGPL-3.1 @@ -26,14 +27,19 @@ use Xentral\Modules\Onlineshop\Data\OrderStatus; use Xentral\Modules\Onlineshop\Data\OrderStatusUpdateRequest; use Xentral\Modules\Onlineshop\Data\Shipment; use Xentral\Modules\Onlineshop\Data\ShopConnectorResponseInterface; +use Xentral\Components\Logger\Logger; class Remote { /** @var ApplicationCore $app */ public $app; + /** @var Logger $logger */ + public $logger; + public function __construct($app) { $this->app = $app; + $this->logger = $app->Container->get('Logger'); } /** @@ -1059,15 +1065,44 @@ class Remote { * * @return mixed|null * @throws Exception + * + * (NEW 2024-06-28) + * + * return value: (comes from Importsendlist or Importsendlistlager inside shopimporter_...) + * array ( + * 'count' => int, // Number of successfully sent articles + * 'new' => array (artikelid, fremdnummer), // List of new articles with external number + * 'message' => string + * 'status' => bool, // false = failed + * 'articles' => array( + * 'id', + * 'status', + * 'message', + * ... + * ) + * ) + * */ public function RemoteSendArticleList($id, $artikel_arr, $extnummer = '', $nurlager = false) { + + $this->logger->debug( + 'RemoteSendArticleList', + [ + 'shop' => $id, + 'artikel_arr' => $artikel_arr + ] + ); + if (!class_exists('ObjGenArtikel') && is_file(dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php')) { include_once dirname(__DIR__) . '/objectapi/mysql/_gen/object.gen.artikel.php'; } $shopexportarr = $this->app->DB->SelectRow("SELECT * FROM shopexport WHERE id='$id' LIMIT 1"); $artikelexport = $shopexportarr['artikelexport']; - + $translationpossible = false; + if ($this->app->erp->ModulVorhanden('artikel_texte')) { + $translationpossible = true; + } $loadElements = [ 'foreign_numbers' => true, 'article_descriptions' => true, @@ -1100,7 +1135,6 @@ class Remote { $cartikel_arr = !empty($artikel_arr) ? count($artikel_arr) : 0; for ($i = 0; $i < $cartikel_arr; $i++) { - $artikel = $artikel_arr[$i]; $lagerexport = $this->app->erp->GetArtikelShopEinstellung('autolagerlampe', $artikel, $shopexportarr); $tmp->Select($artikel); @@ -1489,16 +1523,18 @@ class Remote { AND (v.objekt = 'Standard' OR v.objekt = '') AND (v.adresse = '0' OR v.adresse = '') AND (v.gueltig_bis >= NOW() OR v.gueltig_bis = '0000-00-00') ORDER BY v.preis DESC LIMIT 1"); - $priceInformation = reset($priceInformation); - $defaultPrice = $priceInformation['preis']; - $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; - if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { - $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency - $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); - } - $data[$i]['waehrung'] = $defaultCurrency; - $data[$i]['preis'] = $defaultPrice; + if (!empty($priceInformation)) { + $priceInformation = reset($priceInformation); + $defaultPrice = $priceInformation['preis']; + $defaultCurrency = $priceInformation['waehrung'] ?: 'EUR'; + if ($preisgruppe && method_exists($this->app->erp, 'GetVerkaufspreisGruppe')) { + $defaultCurrency = 'EUR'; //the follow up function imply EUR as the default currency + $defaultPrice = $this->app->erp->GetVerkaufspreisGruppe($artikel, 1, $preisgruppe); + } + $data[$i]['waehrung'] = $defaultCurrency; + $data[$i]['preis'] = $defaultPrice; + } if (!empty($tmp->GetSteuersatz()) && $tmp->GetSteuersatz() != -1) { $data[$i]['steuersatz'] = (float) $tmp->GetSteuersatz(); @@ -1606,8 +1642,6 @@ class Remote { * @deprecated Ende */ } - - $data[$i]['bruttopreis'] = $data[$i]['preis'] * $steuer; } $data[$i]['checksum'] = $tmp->GetChecksum(); @@ -1657,7 +1691,7 @@ class Remote { foreach ($db->yieldAll($query) as $matrixdaten) { $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; - if (!empty($loadElements['translations'])) { + if ($translationpossible && !empty($loadElements['translations'])) { if (empty($gruppenuebersetzung[$matrixdaten['gruppe']])) { $gruppennamen = $this->app->DB->SelectArr("SELECT IF(name_external_from<>'',name_external_from,name_from) AS name_from, @@ -1732,6 +1766,7 @@ class Remote { if (is_numeric($matrixPseudoStorage) && $matrixPseudoStorage < 0) { $matrixPseudoStorage = 0; } + $matrixStock = (float) $this->app->erp->ArtikelAnzahlVerkaufbar($eigenschaft['artikel'], 0, $projektlager, $id, $lagergrundlage); if ($matrixStock < 0) { $matrixStock = 0; } @@ -1896,18 +1931,19 @@ class Remote { } } - $result = null; if (empty($data)) { continue; } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } - } while (count($data[$i]['matrix_varianten']['artikel'] ?? []) >= 5000); + } while (count($data[$i]['matrix_varianten']['artikel'] ?? [])>=5000); + // Bulk transfer (new 2024-06-28) + $result = null; + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($id, $data, true); + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($id, $data); + } return $result; } @@ -1933,16 +1969,17 @@ class Remote { $variantennettopreis = $this->app->erp->GetVerkaufspreis($v['id'], 1, 0); } } - $sprachen = ['de', 'en']; - foreach ($sprachen as $sprache) { - $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", - $id, strtoupper($sprache), $v['id']); - $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if (!empty($ersetzeStandardbeschreibung)) { - $v['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + if (!empty($loadElements['translations']) && $this->app->erp->ModulVorhanden('artikel_texte')) { + $sprachen = ['de', 'en']; + foreach ($sprachen as $sprache) { + $query = sprintf("SELECT * FROM artikel_texte WHERE shop=%d AND sprache='%s' AND artikel=%d AND aktiv=1 LIMIT 1", + $id, strtoupper($sprache), $v['id']); + $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); + if (!empty($ersetzeStandardbeschreibung)) { + $v['name_' . $sprache] = $ersetzeStandardbeschreibung['name']; + } } } - $this->app->erp->RunHook('remote_send_article_list_pseudostorage', 3, $id, $v['id'], $v['pseudolager']); if (is_numeric($v['pseudolager']) && $v['pseudolager'] < 0) { $v['pseudolager'] = 0; @@ -2020,18 +2057,19 @@ class Remote { $data[$i]['variantevorhanden'] = 0; } - $result = null; if (empty($data)) { continue; } - if (!empty($lagerexport)) { - $result = $this->sendlistlager($i, $id, $data); - } - if (!empty($artikelexport) && !$nurlager) { - $result = $this->sendlist($i, $id, $data, true); - } } + // Bulk transfer (new 2024-06-28) + $result = null; + if (!empty($artikelexport) && !$nurlager) { + $result = $this->sendlist($id, $data, true); + } + if (!empty($lagerexport)) { + $result = $this->sendlistlager($id, $data); + } return $result; } @@ -2051,108 +2089,97 @@ class Remote { return $this->app->DB->SelectArr($query); } - protected function sendlistlager($i, $id, $data) { - $data2 = $data; - foreach ($data2 as $key => $value) { - $data2[$key]['artikel'] = $value['artikelid']; - } - $result = $this->RemoteCommand($id, 'sendlistlager', $data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); + protected function sendlistlager(int $shop_id, array $data) { + $result = $this->RemoteCommand($shop_id, 'sendlistlager', $data); return $result; } - protected function sendlist($i, $id, $data, $isLagerExported) { - /** @var Shopexport $objShopexport */ - $objShopexport = $this->app->loadModule('shopexport'); - $changedHash = $objShopexport->hasArticleHashChanged($data[0]['artikel'], $id); - $hash = $changedHash['hash']; - //$changedHash = $changedHash['changed']; + protected function sendlist(int $shop_id, array $data, $isLagerExported) { - $result = $this->RemoteCommand($id, 'sendlist', $data); - $checkAo = $this->app->DB->Select( - sprintf( - 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', - $data[0]['artikel'], $id - ) - ); - if (empty($checkAo)) { - $this->app->DB->Insert( - sprintf( - 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) - VALUES (%d, %d, 1, 1) ', - $data[0]['artikel'], $id - ) - ); + // See description of return format in function RemoteSendArticleList() + $result = $this->RemoteCommand($shop_id, 'sendlist', $data); + + if (!empty($result) && is_array($result)) { + foreach ($result['articles'] as $artikelid) { + /** @var Shopexport $objShopexport */ + $objShopexport = $this->app->loadModule('shopexport'); + $changedHash = $objShopexport->hasArticleHashChanged($artikelid, $shop_id); + $hash = $changedHash['hash']; + + $checkAo = $this->app->DB->Select( + sprintf( + 'SELECT id FROM artikel_onlineshops WHERE artikel = %d AND shop=%d LIMIT 1', + $artikelid, $shop_id + ) + ); + if (empty($checkAo)) { + $this->app->DB->Insert( + sprintf( + 'INSERT INTO artikel_onlineshops (artikel, shop, aktiv, ausartikel) + VALUES (%d, %d, 1, 1) ', + $artikelid, $shop_id + ) + ); + } + $this->app->DB->Update( + sprintf( + "UPDATE artikel_onlineshops + SET last_article_transfer = NOW(), last_article_hash = '%s' + WHERE artikel = %d AND shop = %d", + $this->app->DB->real_escape_string($hash), $artikelid, $shop_id + ) + ); + } } - $this->app->DB->Update( - sprintf( - "UPDATE artikel_onlineshops - SET last_article_transfer = NOW(), last_article_hash = '%s' - WHERE artikel = %d AND shop = %d", - $this->app->DB->real_escape_string($hash), $data[0]['artikel'], $id - ) - ); - if (!empty($result) && is_array($result) && !empty($result['new'])) { + + if (!empty($result) && is_array($result)) { foreach ($result['new'] as $artikelid => $fremdnummer) { $artikelid = (int) $artikelid; $artikelnummer = $this->app->DB->Select("SELECT nummer FROM artikel WHERE id = '$artikelid' LIMIT 1"); if ($artikelid > 0 && $artikelnummer != trim($fremdnummer) && - ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$id' OR shop2 = '$id' OR shop3 = '$id') LIMIT 1") || + ($this->app->DB->Select("SELECT id FROM artikel WHERE id = '$artikelid' AND (shop = '$shop_id' OR shop2 = '$shop_id' OR shop3 = '$shop_id') LIMIT 1") || $this->app->DB->Select("SELECT id FROM artikel_onlineshops WHERE artikel = '$artikelid' AND aktiv = 1") ) && trim($fremdnummer) !== '') { //Nur falls Artikel zum Shop passt und keine aktive Fremdnummer exisitert. - if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { + if (!$this->app->DB->Select("SELECT id FROM `artikelnummer_fremdnummern` WHERE artikel = '$artikelid' AND shopid = '$shop_id' AND nummer <> '' AND (aktiv = 1 OR nummer = '" . trim($this->app->DB->real_escape_string($fremdnummer)) . "') LIMIT 1 ")) { $this->app->DB->Insert("INSERT INTO `artikelnummer_fremdnummern` (artikel, bezeichnung, nummer, shopid, bearbeiter, zeitstempel, aktiv) - VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) + VALUES ('$artikelid','Erstellt durch Artikelexport','" . trim($this->app->DB->real_escape_string($fremdnummer)) . "','$shop_id','" . ((isset($this->app->User) && method_exists($this->app->User, 'GetName')) ? $this->app->DB->real_escape_string($this->app->User->GetName()) : 'Cronjob') . "',now(),0) "); } } } if (isset($result['anzahl'])) { - $result = $result['anzahl']; + $result['count'] = $result['anzahl']; }//Altes Verhalten } + if (!$isLagerExported) { - $data2 = $data; - foreach ($data2 as $key => $value) { - $data2[$key]['artikel'] = $value['artikelid']; - } - $this->RemoteCommand($id, 'sendlistlager', $data2); - $this->app->DB->Update( - sprintf( - 'UPDATE artikel_onlineshops SET last_storage_transfer = NOW() WHERE artikel = %d AND shop = %d', - $data2[$i]['artikel'], $id - ) - ); + $this->sendlistlager($shop_id, $data); } return $result; } - public function getDataToSendForUpdateOrder(int $shopId, int $orderId): ?OrderStatusUpdateRequest { - $orderArr = $this->app->DB->SelectRow("SELECT `zahlungsweise`, `shopextid` FROM `auftrag` WHERE `id` = $orderId LIMIT 1"); - if (empty($orderArr)) - return null; + public function getDataToSendForUpdateOrder(int $shopId, int $orderId): ?OrderStatusUpdateRequest + { + $orderArr = $this->app->DB->SelectRow("SELECT `zahlungsweise`, `shopextid` FROM `auftrag` WHERE `id` = $orderId LIMIT 1"); + if (empty($orderArr)) + return null; - $data = new OrderStatusUpdateRequest(); - $data->orderId = $orderId; - $data->shopOrderId = $orderArr['shopextid']; + $data = new OrderStatusUpdateRequest(); + $data->orderId = $orderId; + $data->shopOrderId = $orderArr['shopextid']; - $statusArr = $this->app->DB->SelectFirstCols("SELECT DISTINCT status FROM auftrag WHERE id = $orderId OR teillieferungvon = $orderId"); - if (in_array('storniert', $statusArr)) - $data->orderStatus = OrderStatus::Cancelled; - if (in_array('abgeschlossen', $statusArr)) - $data->orderStatus = OrderStatus::Completed; - if (in_array('freigegeben', $statusArr)) - $data->orderStatus = OrderStatus::InProgress; - if (in_array('angelegt', $statusArr)) - $data->orderStatus = OrderStatus::Imported; + $statusArr = $this->app->DB->SelectFirstCols("SELECT DISTINCT status FROM auftrag WHERE id = $orderId OR teillieferungvon = $orderId"); + if (in_array('storniert', $statusArr)) + $data->orderStatus = OrderStatus::Cancelled; + if (in_array('abgeschlossen', $statusArr)) + $data->orderStatus = OrderStatus::Completed; + if (in_array('freigegeben', $statusArr)) + $data->orderStatus = OrderStatus::InProgress; + if (in_array('angelegt', $statusArr)) + $data->orderStatus = OrderStatus::Imported; - $sql = " + $sql = " SELECT DISTINCT v.id, v.tracking, @@ -2170,20 +2197,20 @@ class Remote { vlp.versandpaket = v.id OR v.lieferschein_ohne_pos = l.id LEFT JOIN shopexport_versandarten sv ON sv.versandart_wawision = v.versandart AND sv.shop = $shopId - WHERE (a.id = $orderId OR a.teillieferungvon = $orderId) AND v.id IS NOT NULL + WHERE a.id = $orderId OR a.teillieferungvon = $orderId ORDER BY v.id"; - $shipments = $this->app->DB->SelectArr($sql); - foreach ($shipments as $shipment) { - $item = new Shipment(); - $item->id = $shipment['id']; - $item->trackingNumber = $shipment['tracking']; - $item->trackingUrl = $shipment['tracking_link']; - $item->shippingMethod = $shipment['versandart']; - $data->shipments[] = $item; - } + $shipments = $this->app->DB->SelectArr($sql); + foreach ($shipments as $shipment) { + $item = new Shipment(); + $item->id = $shipment['id']; + $item->trackingNumber = $shipment['tracking']; + $item->trackingUrl = $shipment['tracking_link']; + $item->shippingMethod = $shipment['versandart']; + $data->shipments[] = $item; + } - return $data; + return $data; } /** @@ -2193,36 +2220,40 @@ class Remote { * @throws Exception */ public function RemoteUpdateAuftrag($shopId, $orderId) { - $data = $this->getDataToSendForUpdateOrder((int) $shopId, (int) $orderId); - if ($data?->orderStatus !== OrderStatus::Completed) - return; + $data = $this->getDataToSendForUpdateOrder((int)$shopId, (int)$orderId); + if($data?->orderStatus !== OrderStatus::Completed) + return; - $bearbeiter = 'Cronjob'; - if (isset($this->app->User)) { - $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); - } + $bearbeiter = 'Cronjob'; + if (isset($this->app->User)) { + $bearbeiter = $this->app->DB->real_escape_string($this->app->User->GetName()); + } - $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); - if ($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()) { - $query = sprintf('UPDATE `auftrag` + $response = $this->RemoteCommand($shopId, 'updateauftrag', $data); + if ($response instanceOf ShopConnectorResponseInterface && !$response->isSuccessful()) { + $query = sprintf('UPDATE `auftrag` SET `shop_status_update_attempt` = `shop_status_update_attempt` + 1, `shop_status_update_last_attempt_at` = NOW() WHERE `id` = %d', $orderId); - $this->app->DB->Update($query); + $this->app->DB->Update($query); - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); - $this->app->erp->Logfile('Versandmeldung an Shop fehlgeschlagen', print_r([ - 'orderId' => $orderId, - 'shopId' => $shopId, - 'message' => $response->getMessage()], true)); + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop fehlgeschlagen', $bearbeiter); - return; + $this->logger->error('Versandmeldung an Shop fehlgeschlagen', + [ + 'orderId' => $orderId, + 'shopId' => $shopId, + 'message' => $response->getMessage() + ] + ); + + return; + } + + $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); + $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); } - $this->app->erp->AuftragProtokoll($orderId, 'Versandmeldung an Shop übertragen', $bearbeiter); - $this->app->DB->Update("UPDATE `auftrag` SET `shopextstatus` = 'abgeschlossen' WHERE `id` = $orderId LIMIT 1"); - } - /** * @param int $shopId * @param string $auftrag @@ -2497,6 +2528,7 @@ class Remote { } return ''; } + if ($shoptyp === 'intern') { if ($modulename != '') { if ($this->app->erp->ModulVorhanden($modulename)) { @@ -2506,14 +2538,15 @@ class Remote { $obj->getKonfig($id, $data); } $method = 'Import' . $action; + if (method_exists($obj, $method)) { try { $ret = $obj->$method(); } catch (Exception $e) { if ($isActionAuth) { - return 'Fehler: ' . $e->getMessage(); + return 'Fehler Auth: ' . $e->getMessage(); } - return ''; + return 'Fehler: ' . $e->getMessage(); } if (!empty($this->app->stringcleaner)) { @@ -2521,6 +2554,8 @@ class Remote { } $this->parseReturn($ret, $id, $action); return $ret; + } else { + return 'Fehler: Funktion nicht implementiert: ' . $method; } } elseif ($isActionAuth) { return 'Fehler: Importer konnte nicht initialisiert werden'; @@ -2575,7 +2610,13 @@ class Remote { $post_data['data'] = base64_encode(serialize($data)); $client->timeout = 120; if (!$client->post($geturl, $post_data)) { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection, 'An error occurred: ' . $client->getError())); + + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); + throw new Exception('An error occurred: ' . $client->getError()); //return 'Netzwerkverbindung von WaWison zu Shopimporter fehlgeschlagen: '.$client->getError(); } @@ -2646,7 +2687,12 @@ class Remote { $post_data['data'] = base64_encode($aes->encrypt(serialize($data))); if (!$client->post($geturl, $post_data)) { - $this->app->erp->LogFile(mysqli_real_escape_string($this->app->DB->connection, 'An error occurred: ' . $client->getError())); + $this->logger->error('An error occurred', + [ + 'error' => $client->getError() + ] + ); + throw new Exception('An error occurred: ' . $client->getError()); } return unserialize($aes->decrypt(base64_decode($client->getContent()))); From e40e543a7d01f66b9d42535300da08734e51eb84 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Fri, 6 Sep 2024 20:12:37 +0200 Subject: [PATCH 51/52] bugfix remotesendlistlager result --- www/lib/class.erpapi.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index fc1d4c21..ade72442 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -21064,9 +21064,9 @@ function ChargenMHDAuslagern($artikel, $menge, $lagerplatztyp, $lpid,$typ,$wert, } - $this->LogFile('*** UPDATE '.$lagerartikel[$ij]['nummer'].' '.$lagerartikel[$ij]['name_de'].' Shop: '.$shop.' Lagernd: '.$verkaufbare_menge.' Korrektur: '.round((float) ($verkaufbare_menge_korrektur - $verkaufbare_menge),7).' Pseudolager: '.round((float) $pseudolager,8).' Result: '.(is_array($result)?$result['status']:$result), $result); + $this->LogFile('*** UPDATE '.$lagerartikel[$ij]['nummer'].' '.$lagerartikel[$ij]['name_de'].' Shop: '.$shop.' Lagernd: '.$verkaufbare_menge.' Korrektur: '.round((float) ($verkaufbare_menge_korrektur - $verkaufbare_menge),7).' Pseudolager: '.round((float) $pseudolager,8).' Result: '.(is_array($result)?$result['status']:$result), $result); - if ((is_array($result)?$result['status'] == 1:false) || $status === 1) { + if ((is_array($result)?$result['status'] == 1:false) || $result === 1) { $cacheQuantity = (int) $verkaufbare_menge_korrektur + (int) $pseudolager; $this->app->DB->Update( "UPDATE `artikel` SET `cache_lagerplatzinhaltmenge` = '{$cacheQuantity}' From f725281d7e90ef666f0609d4103739b7357df3a8 Mon Sep 17 00:00:00 2001 From: Andreas Palm Date: Tue, 10 Sep 2024 23:09:39 +0200 Subject: [PATCH 52/52] Re-add previous fix --- www/lib/class.remote.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 96f890aa..d1883f32 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -2197,7 +2197,7 @@ class Remote { vlp.versandpaket = v.id OR v.lieferschein_ohne_pos = l.id LEFT JOIN shopexport_versandarten sv ON sv.versandart_wawision = v.versandart AND sv.shop = $shopId - WHERE a.id = $orderId OR a.teillieferungvon = $orderId + WHERE (a.id = $orderId OR a.teillieferungvon = $orderId) AND v.id IS NOT NULL ORDER BY v.id"; $shipments = $this->app->DB->SelectArr($sql);
      Zweistelliger ISO Code:
      Dreistelliger ISO Code:
      Bezeichnung Deutsch:
      Bezeichnung Englisch:
      EU: