From 9d547c6e5227d2c2ec52a12cabd4e0c4462ab0c8 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 13 May 2024 14:43:33 +0200 Subject: [PATCH 01/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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/87] 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 a5f5f4aede130e73b9654cd05937182cf60737fb Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 5 Jun 2024 09:48:56 +0200 Subject: [PATCH 15/87] reimplemented module artikeltexte --- phpwf/plugins/class.yui.php | 11 +- www/lib/class.erpapi.php | 27 ++- www/lib/class.remote.php | 21 +- www/pages/artikel.php | 6 +- www/pages/artikeltexte.php | 270 ++++++++++++++++++++++++ www/pages/content/artikeltexte_edit.tpl | 144 +++++++++++++ www/pages/content/artikeltexte_list.tpl | 10 + www/pages/importvorlage.php | 4 +- www/widgets/templates/_gen/artikel.tpl | 6 +- 9 files changed, 465 insertions(+), 34 deletions(-) create mode 100644 www/pages/artikeltexte.php create mode 100644 www/pages/content/artikeltexte_edit.tpl create mode 100644 www/pages/content/artikeltexte_list.tpl diff --git a/phpwf/plugins/class.yui.php b/phpwf/plugins/class.yui.php index d78eb336..c2d2398e 100644 --- a/phpwf/plugins/class.yui.php +++ b/phpwf/plugins/class.yui.php @@ -1921,8 +1921,17 @@ class YUI { } } - $this->app->erp->RunHook('AARLGPositionenSprache', 6, $module, $id, $artikel_id, $sprache, $bezeichnung, $beschreibung); + + // OpenXE artikel_texte + $language = $this->app->erp->GetSpracheBeleg($module,$id); + $sql = "SELECT * FROM artikel_texte WHERE artikel = '".$artikel_id."' AND sprache = '".$language."'"; + $uebersetzung = $this->app->DB->SelectRow($sql); + if ($uebersetzung) { + $bezeichnung = $uebersetzung['name']; + $beschreibung = $uebersetzung['beschreibung']; + } + $bezeichnung = $this->app->DB->real_escape_string($bezeichnung); $beschreibung = $this->app->DB->real_escape_string($beschreibung); diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index b855b0f3..9ec83a60 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -31396,15 +31396,15 @@ function Firmendaten($field,$projekt="") $variante_von = $this->app->DB->Select("SELECT variante_von FROM artikel WHERE id = '$artikel' LIMIT 1"); if($variante_von)$beschreibung = $this->app->DB->real_escape_string($this->app->DB->Select("SELECT anabregs_text FROM artikel WHERE id='$variante_von' LIMIT 1")); } - if($this->ModulVorhanden('artikel_texte')){ - if(array_key_exists($belegsprache,$adresssprachen)){ + + if(array_key_exists($belegsprache,$adresssprachen)){ $belegsprache = $adresssprachen[$belegsprache]; - } - $artikelbeschreibung = $this->app->DB->Select("SELECT beschreibung FROM artikel_texte WHERE artikel=$artikel AND sprache='$belegsprache'"); - if($artikelbeschreibung){ - $beschreibung = $artikelbeschreibung; - } } + $artikelbeschreibung = $this->app->DB->Select("SELECT beschreibung FROM artikel_texte WHERE artikel=$artikel AND sprache='$belegsprache'"); + if($artikelbeschreibung){ + $beschreibung = $artikelbeschreibung; + } + } //$vpe = $this->app->DB->Select("SELECT vpe FROM verkaufspreise WHERE id='$verkauf' LIMIT 1"); $sort = $this->app->DB->Select("SELECT MAX(sort) FROM ".$typ."_position WHERE $typ='$id' LIMIT 1"); @@ -31419,20 +31419,19 @@ function Firmendaten($field,$projekt="") if($this->app->DB->Select("SELECT adr.id FROM auftrag auf INNER JOIN adresse adr ON auf.adresse = adr.id AND adr.sprache = 'englisch' WHERE auf.id = '$id' LIMIT 1")) $name = $this->app->DB->Select("SELECT name_en FROM artikel WHERE id = '$artikel'"); if($name === '')$name = $this->app->DB->Select("SELECT name_de FROM artikel WHERE id = '$artikel'"); - if($this->ModulVorhanden('artikel_texte')){ - if(array_key_exists($belegsprache,$adresssprachen)){ + + if(array_key_exists($belegsprache,$adresssprachen)){ $belegsprache = $adresssprachen[$belegsprache]; - } - $artikelbezeichnung = $this->app->DB->Select( + } + $artikelbezeichnung = $this->app->DB->Select( "SELECT name FROM artikel_texte WHERE artikel=$artikel AND sprache='$belegsprache' ORDER BY name <> '' DESC LIMIT 1" - ); - if($artikelbezeichnung){ + ); + if($artikelbezeichnung){ $name = $artikelbezeichnung; - } } } diff --git a/www/lib/class.remote.php b/www/lib/class.remote.php index 0eb67ede..3880b024 100644 --- a/www/lib/class.remote.php +++ b/www/lib/class.remote.php @@ -1177,11 +1177,7 @@ class Remote } $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, @@ -1811,7 +1807,7 @@ class Remote foreach ($db->yieldAll($query) as $matrixdaten) { $data[$i]['matrix_varianten']['gruppen'][$matrixdaten['gruppe']][$matrixdaten['wert']] = true; - if ($translationpossible && !empty($loadElements['translations'])) { + 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, @@ -2092,17 +2088,16 @@ class Remote $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){ + $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']); + $id,strtoupper($sprache),$v['id']); $ersetzeStandardbeschreibung = $this->app->DB->SelectRow($query); - if(!empty($ersetzeStandardbeschreibung)){ - $v['name_'.$sprache] = $ersetzeStandardbeschreibung['name']; + 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; diff --git a/www/pages/artikel.php b/www/pages/artikel.php index 34af81c7..4412e536 100644 --- a/www/pages/artikel.php +++ b/www/pages/artikel.php @@ -7333,6 +7333,10 @@ class Artikel extends GenArtikel { $this->app->erp->MenuEintrag('index.php?module=artikel&action=eigenschaften&id='.$id, 'Eigenschaften'); } + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list&artikel=$id",'Übersetzung'); + + $this->app->erp->MenuEintrag("index.php?module=artikel&action=baum&id=$id",'Artikelbaum'); + if($rabatt!='1'){ $this->app->erp->MenuEintrag("index.php?module=artikel&action=einkauf&id=$id",'Einkauf'); if($this->app->erp->RechteVorhanden('einkaufabgleich','einkaufapi')) @@ -7393,7 +7397,7 @@ class Artikel extends GenArtikel { } $this->app->erp->MenuEintrag('index.php?module=artikel&action=list','Zurück zur Übersicht'); - $this->app->erp->InsertMenuAfter("index.php?module=artikel&action=baum&id=$id",'Artikelbaum','artikel','eigenschaften'); + } } $this->app->erp->MenuEintrag('index.php?module=artikel&action=create','Neuen Artikel anlegen'); diff --git a/www/pages/artikeltexte.php b/www/pages/artikeltexte.php new file mode 100644 index 00000000..adc4f311 --- /dev/null +++ b/www/pages/artikeltexte.php @@ -0,0 +1,270 @@ +app = $app; + if ($intern) + return; + + $this->app->ActionHandlerInit($this); + $this->app->ActionHandler("list", "artikel_texte_list"); + $this->app->ActionHandler("create", "artikel_texte_edit"); // This automatically adds a "New" button + $this->app->ActionHandler("edit", "artikel_texte_edit"); + $this->app->ActionHandler("delete", "artikel_texte_delete"); + $this->app->DefaultActionHandler("list"); + $this->app->ActionHandlerListen($app); + } + + public function Install() { + /* Fill out manually later */ + } + + static function TableSearch(&$app, $name, $erlaubtevars) { + switch ($name) { + case "artikel_texte_list": + $allowed['artikel_texte_list'] = array('list'); + $heading = array('','','Nummer','Artikel','Sprache', 'Name', 'Kurztext', 'Beschreibung', 'Beschreibung_online', 'Meta title', 'Meta description', 'Meta keywords', 'Katalogartikel', 'Katalogbezeichnung', 'Katalogtext', 'Shop', 'Aktiv', 'Menü'); + $width = array('1%','1%','1%'); // Fill out manually later + + $artikel = $app->User->GetParameter('artikeltexte_artikel'); + + // columns that are aligned right (numbers etc) + // $alignright = array(4,5,6,7,8); + + $findcols = array('a.id','a.id','art.nummer', 'art.name_de', 'a.sprache', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalogartikel', 'a.katalog_bezeichnung', 'a.katalog_text', 'a.shop', 'a.aktiv'); + $searchsql = array('a.artikel', 'a.sprache', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalogartikel', 'a.katalog_bezeichnung', 'a.katalog_text', 'a.shop', 'a.aktiv'); + + $defaultorder = 1; + $defaultorderdesc = 0; + $aligncenter = array(); + $alignright = array(); + $numbercols = array(); + $sumcol = array(); + + $dropnbox = "'' AS `open`, CONCAT('') AS `auswahl`"; + +// $moreinfo = true; // Allow drop down details +// $moreinfoaction = "lieferschein"; // specify suffix for minidetail-URL to allow different minidetails +// $mencol = 11; // Set id col for moredata/menu + + $menu = "
" . "Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\"> " . "Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">" . "
"; + + $sql = " + SELECT SQL_CALC_FOUND_ROWS a.id, $dropnbox, + art.nummer, + art.name_de, + a.sprache, + a.name, + a.kurztext, + a.beschreibung, + a.beschreibung_online, + a.meta_title, + a.meta_description, + a.meta_keywords, + a.katalogartikel, + a.katalog_bezeichnung, + a.katalog_text, + a.shop, + a.aktiv, + a.id FROM artikel_texte a + INNER JOIN artikel art ON art.id = a.artikel + "; + + $where = "1"; + + if ($artikel) { + // $where .= " AND a.artikel = '".$artikel."'"; + } + + $count = "SELECT count(DISTINCT id) FROM artikel_texte a WHERE $where"; +// $groupby = ""; + + break; + } + + $erg = false; + + foreach ($erlaubtevars as $k => $v) { + if (isset($$v)) { + $erg[$v] = $$v; + } + } + return $erg; + } + + function artikel_texte_list() { + + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list", "Übersicht"); + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=create", "Neu anlegen"); + + $this->app->erp->MenuEintrag("index.php", "Zurück"); + + $artikel = $this->app->Secure->GetGET('artikel'); + $this->app->User->SetParameter('artikeltexte_artikel', $artikel); + + $this->app->YUI->TableSearch('TAB1', 'artikel_texte_list', "show", "", "", basename(__FILE__), __CLASS__); + $this->app->Tpl->Parse('PAGE', "artikeltexte_list.tpl"); + } + + public function artikel_texte_delete() { + $id = (int) $this->app->Secure->GetGET('id'); + $this->app->DB->Delete("DELETE FROM `artikel_texte` WHERE `id` = '{$id}'"); + $this->app->Tpl->addMessage('error', 'Der Eintrag wurde gelöscht'); + $this->artikel_texte_list(); + } + + /* + * Edit artikel_texte item + * If id is empty, create a new one + */ + + function artikel_texte_edit() { + $id = $this->app->Secure->GetGET('id'); + // Check if other users are editing this id +/* if($this->app->erp->DisableModul('artikel_texte',$id)) + { + return; + } */ + + $this->app->Tpl->Set('ID', $id); + + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=edit&id=$id", "Details"); + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list", "Zurück zur Übersicht"); + $id = $this->app->Secure->GetGET('id'); + $input = $this->GetInput(); + $submit = $this->app->Secure->GetPOST('submit'); + + if (empty($id)) { + // New item + $id = 'NULL'; + } + + if ($submit != '') + { + + // Write to database + + // Add checks here + + // $input['projekt'] = $this->app->erp->ReplaceProjekt(true,$input['projekt'],true); // Parameters: Target db?, value, from form? + + $columns = "id, "; + $values = "$id, "; + $update = ""; + + $fix = ""; + + foreach ($input as $key => $value) { + $columns = $columns.$fix.$key; + $values = $values.$fix."'".$value."'"; + $update = $update.$fix.$key." = '$value'"; + + $fix = ", "; + } + +// echo($columns."
"); +// echo($values."
"); +// echo($update."
"); + + $sql = "INSERT INTO artikel_texte (".$columns.") VALUES (".$values.") ON DUPLICATE KEY UPDATE ".$update; + +// echo($sql); + + $this->app->DB->Update($sql); + + if ($id == 'NULL') { + $msg = $this->app->erp->base64_url_encode("
Das Element wurde erfolgreich angelegt.
"); + header("Location: index.php?module=artikeltexte&action=list&msg=$msg"); + } else { + $this->app->Tpl->addMessage('success', 'Die Einstellungen wurden erfolgreich übernommen.'); + } + } + + + // Load values again from database + if ($id != 'NULL') { + + $dropnbox = "'' AS `open`, CONCAT('') AS `auswahl`"; + $result = $this->app->DB->SelectArr(" + SELECT SQL_CALC_FOUND_ROWS + a.id, + $dropnbox, + art.name_de, + a.sprache, + a.name, + a.kurztext, + a.beschreibung, + a.beschreibung_online, + a.meta_title, + a.meta_description, + a.meta_keywords, + a.katalogartikel, + a.katalog_bezeichnung, + a.katalog_text, + a.shop, + a.aktiv, + a.id + FROM + artikel_texte a + INNER JOIN artikel art ON a.artikel = art.id + WHERE a.id=$id + "); + + + foreach ($result[0] as $key => $value) { + $this->app->Tpl->Set(strtoupper($key), $value); + } + + if (!empty($result)) { + $artikel_texte_from_db = $result[0]; + } else { + return; + } + } + + /* + * Add displayed items later + * + $this->app->Tpl->Add('EMAIL', $email); + $this->app->Tpl->Add('ANGEZEIGTERNAME', $angezeigtername); + + $this->app->YUI->AutoComplete("artikel", "artikelnummer"); + + */ + + $sprachenOptions = $this->app->erp->GetSprachenSelect(); + $this->app->Tpl->Set('SPRACHE', $this->app->erp->GetSelectAsso($sprachenOptions, $artikel_texte_from_db['sprache'])); + $this->app->Tpl->Parse('PAGE', "artikeltexte_edit.tpl"); + } + + /** + * Get all paramters from html form and save into $input + */ + public function GetInput(): array { + $input = array(); + //$input['EMAIL'] = $this->app->Secure->GetPOST('email'); + + $input['sprache'] = $this->app->Secure->GetPOST('sprache'); + $input['name'] = $this->app->Secure->GetPOST('name'); + $input['kurztext'] = $this->app->Secure->GetPOST('kurztext'); + $input['beschreibung'] = $this->app->Secure->GetPOST('beschreibung'); + $input['beschreibung_online'] = $this->app->Secure->GetPOST('beschreibung_online'); + $input['meta_title'] = $this->app->Secure->GetPOST('meta_title'); + $input['meta_description'] = $this->app->Secure->GetPOST('meta_description'); + $input['meta_keywords'] = $this->app->Secure->GetPOST('meta_keywords'); + $input['katalogartikel'] = $this->app->Secure->GetPOST('katalogartikel'); + $input['katalog_bezeichnung'] = $this->app->Secure->GetPOST('katalog_bezeichnung'); + $input['katalog_text'] = $this->app->Secure->GetPOST('katalog_text'); + $input['shop'] = $this->app->Secure->GetPOST('shop'); + $input['aktiv'] = $this->app->Secure->GetPOST('aktiv')?'1':'0'; + + return $input; + } + } diff --git a/www/pages/content/artikeltexte_edit.tpl b/www/pages/content/artikeltexte_edit.tpl new file mode 100644 index 00000000..9e784335 --- /dev/null +++ b/www/pages/content/artikeltexte_edit.tpl @@ -0,0 +1,144 @@ +
+
    +
  • +
+ +
+ [MESSAGE] +
+ [FORMHANDLEREVENT] +
+
+
+
+
+ {|Artikeltexte (Übersetzung)|} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ {|Artikel|}: + + +
+ {|Sprache|}: + + +
+ {|Name|}: + + +
+ {|Kurztext|}: + + +
+ {|Beschreibung|}: + + +
+ {|Beschreibung online|}: + + +
+ {|Meta title|}: + + +
+ {|Meta description|}: + + +
+ {|Meta keywords|}: + + +
+ {|Katalogartikel|}: + + +
+ {|Katalogbezeichnung|}: + + +
+ {|Katalogtext|}: + + +
+ {|Shop|}: + + +
+ {|Aktiv|}: + + +
+
+
+
+
+
+ +
+
+
+ diff --git a/www/pages/content/artikeltexte_list.tpl b/www/pages/content/artikeltexte_list.tpl new file mode 100644 index 00000000..394c103a --- /dev/null +++ b/www/pages/content/artikeltexte_list.tpl @@ -0,0 +1,10 @@ +
+ +
+ [MESSAGE] + [TAB1] + [TAB1NEXT] +
+
diff --git a/www/pages/importvorlage.php b/www/pages/importvorlage.php index a096fb1d..ea9be2ee 100644 --- a/www/pages/importvorlage.php +++ b/www/pages/importvorlage.php @@ -3990,7 +3990,6 @@ class Importvorlage extends GenImportvorlage { if($this->app->DB->Select("SELECT id FROM artikel WHERE id ='$artikelid' LIMIT 1")){ //Sprachen - if($this->app->erp->ModulVorhanden('artikel_texte')){ $erlaubtefelder= array('name','kurztext','beschreibung','beschreibung_online','meta_title', 'meta_description','meta_keywords','katalog_bezeichnung','katalog_text','katalogartikel','shop','aktiv'); $zuImportierendeSprachen = []; @@ -4066,8 +4065,7 @@ class Importvorlage extends GenImportvorlage { } } } - } - } + } // Sprachen //freifelduebersetzungen foreach ($tmp as $feldname => $feldwerte) { diff --git a/www/widgets/templates/_gen/artikel.tpl b/www/widgets/templates/_gen/artikel.tpl index a7cc327e..3230ce71 100644 --- a/www/widgets/templates/_gen/artikel.tpl +++ b/www/widgets/templates/_gen/artikel.tpl @@ -566,11 +566,13 @@
-
 {|Beschreibung|}  +
+  {|Beschreibung|}  - + + From 1321cb9ece0c365bfec45a2f5c42322a41d5c54e Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 5 Jun 2024 18:44:24 +0200 Subject: [PATCH 16/87] artikeltexte improvements and navigation --- upgrade/data/db_schema.json | 2 +- www/pages/artikeltexte.php | 57 ++++++++++++++++--------- www/pages/content/artikeltexte_edit.tpl | 19 +++++---- 3 files changed, 49 insertions(+), 29 deletions(-) diff --git a/upgrade/data/db_schema.json b/upgrade/data/db_schema.json index ba830e9c..7360bbc7 100644 --- a/upgrade/data/db_schema.json +++ b/upgrade/data/db_schema.json @@ -18174,7 +18174,7 @@ }, { "Field": "sprache", - "Type": "varchar(11)", + "Type": "varchar(30)", "Collation": "utf8mb3_general_ci", "Null": "NO", "Key": "", diff --git a/www/pages/artikeltexte.php b/www/pages/artikeltexte.php index adc4f311..dea987a6 100644 --- a/www/pages/artikeltexte.php +++ b/www/pages/artikeltexte.php @@ -30,7 +30,7 @@ class Artikeltexte { switch ($name) { case "artikel_texte_list": $allowed['artikel_texte_list'] = array('list'); - $heading = array('','','Nummer','Artikel','Sprache', 'Name', 'Kurztext', 'Beschreibung', 'Beschreibung_online', 'Meta title', 'Meta description', 'Meta keywords', 'Katalogartikel', 'Katalogbezeichnung', 'Katalogtext', 'Shop', 'Aktiv', 'Menü'); + $heading = array('','','Nummer','Artikel','Sprache', 'Aktiv', 'Name', 'Kurztext', 'Beschreibung', 'Beschreibung online', 'Meta title', 'Meta description', 'Meta keywords', 'Katalogartikel', 'Katalogbezeichnung', 'Katalogtext', 'Shop', 'Menü'); $width = array('1%','1%','1%'); // Fill out manually later $artikel = $app->User->GetParameter('artikeltexte_artikel'); @@ -38,8 +38,8 @@ class Artikeltexte { // columns that are aligned right (numbers etc) // $alignright = array(4,5,6,7,8); - $findcols = array('a.id','a.id','art.nummer', 'art.name_de', 'a.sprache', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalogartikel', 'a.katalog_bezeichnung', 'a.katalog_text', 'a.shop', 'a.aktiv'); - $searchsql = array('a.artikel', 'a.sprache', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalogartikel', 'a.katalog_bezeichnung', 'a.katalog_text', 'a.shop', 'a.aktiv'); + $findcols = array('a.id','a.id','art.nummer', 'art.name_de', 'a.sprache', 'a.aktiv', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalogartikel', 'a.katalog_bezeichnung', 'a.katalog_text', 'a.shop' ); + $searchsql = array('a.artikel', 'a.sprache', 'a.name', 'a.kurztext', 'a.beschreibung', 'a.beschreibung_online', 'a.meta_title', 'a.meta_description', 'a.meta_keywords', 'a.katalog_bezeichnung', 'a.katalog_text'); $defaultorder = 1; $defaultorderdesc = 0; @@ -61,6 +61,7 @@ class Artikeltexte { art.nummer, art.name_de, a.sprache, + a.aktiv, a.name, a.kurztext, a.beschreibung, @@ -71,10 +72,10 @@ class Artikeltexte { a.katalogartikel, a.katalog_bezeichnung, a.katalog_text, - a.shop, - a.aktiv, + shopexport.bezeichnung as shop, a.id FROM artikel_texte a INNER JOIN artikel art ON art.id = a.artikel + LEFT JOIN shopexport ON shopexport.id = a.shop "; $where = "1"; @@ -100,13 +101,15 @@ class Artikeltexte { } function artikel_texte_list() { + + $artikel = $this->app->Secure->GetGET('artikel'); + if ($artikel) { + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=create&artikel=".$artikel, "Neu anlegen"); + $this->app->erp->MenuEintrag("index.php?module=artikel&action=edit&id=".$artikel."#tabs-2", "Zurück"); + } + + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list&artikel=".$artikel, "Übersicht"); - $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list", "Übersicht"); - $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=create", "Neu anlegen"); - - $this->app->erp->MenuEintrag("index.php", "Zurück"); - - $artikel = $this->app->Secure->GetGET('artikel'); $this->app->User->SetParameter('artikeltexte_artikel', $artikel); $this->app->YUI->TableSearch('TAB1', 'artikel_texte_list', "show", "", "", basename(__FILE__), __CLASS__); @@ -115,9 +118,10 @@ class Artikeltexte { public function artikel_texte_delete() { $id = (int) $this->app->Secure->GetGET('id'); + $artikel = $this->app->DB->Select("SELECT artikel FROM `artikel_texte` WHERE `id` = '{$id}'"); $this->app->DB->Delete("DELETE FROM `artikel_texte` WHERE `id` = '{$id}'"); - $this->app->Tpl->addMessage('error', 'Der Eintrag wurde gelöscht'); - $this->artikel_texte_list(); + $msg = $this->app->erp->base64_url_encode("
Der Eintrag wurde gelöscht.
"); + header("Location: index.php?module=artikeltexte&action=list&artikel=".$artikel."&msg=".$msg); } /* @@ -127,6 +131,7 @@ class Artikeltexte { function artikel_texte_edit() { $id = $this->app->Secure->GetGET('id'); + $artikel = $this->app->Secure->GetGET('artikel'); // Check if other users are editing this id /* if($this->app->erp->DisableModul('artikel_texte',$id)) { @@ -136,7 +141,7 @@ class Artikeltexte { $this->app->Tpl->Set('ID', $id); $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=edit&id=$id", "Details"); - $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list", "Zurück zur Übersicht"); + $id = $this->app->Secure->GetGET('id'); $input = $this->GetInput(); $submit = $this->app->Secure->GetPOST('submit'); @@ -144,9 +149,11 @@ class Artikeltexte { if (empty($id)) { // New item $id = 'NULL'; + $input['artikel'] = $artikel; + $input['aktiv'] = 1; } - if ($submit != '') + if ($submit != '' || $id == 'NULL') { // Write to database @@ -181,7 +188,7 @@ class Artikeltexte { if ($id == 'NULL') { $msg = $this->app->erp->base64_url_encode("
Das Element wurde erfolgreich angelegt.
"); - header("Location: index.php?module=artikeltexte&action=list&msg=$msg"); + header("Location: index.php?module=artikeltexte&action=list&artikel=".$artikel."&msg=".$msg); } else { $this->app->Tpl->addMessage('success', 'Die Einstellungen wurden erfolgreich übernommen.'); } @@ -198,6 +205,7 @@ class Artikeltexte { $dropnbox, art.name_de, a.sprache, + a.aktiv, a.name, a.kurztext, a.beschreibung, @@ -209,8 +217,8 @@ class Artikeltexte { a.katalog_bezeichnung, a.katalog_text, a.shop, - a.aktiv, - a.id + a.id, + a.artikel FROM artikel_texte a INNER JOIN artikel art ON a.artikel = art.id @@ -228,6 +236,12 @@ class Artikeltexte { return; } } + + if ($artikel_texte_from_db['artikel']) { + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=create&artikel=".$artikel_texte_from_db['artikel'], "Neu anlegen"); + $this->app->erp->MenuEintrag("index.php?module=artikeltexte&action=list&artikel=".$artikel_texte_from_db['artikel'], "Zurück"); + } + /* * Add displayed items later @@ -239,6 +253,11 @@ class Artikeltexte { */ + $this->app->Tpl->Set('AKTIV', $artikel_texte_from_db['aktiv']?'checked':''); + $this->app->Tpl->Set('KATALOGARTIKEL', $artikel_texte_from_db['katalogartikel']?'checked':''); + + $this->app->YUI->AutoComplete('shop','shopnameid'); + $sprachenOptions = $this->app->erp->GetSprachenSelect(); $this->app->Tpl->Set('SPRACHE', $this->app->erp->GetSelectAsso($sprachenOptions, $artikel_texte_from_db['sprache'])); $this->app->Tpl->Parse('PAGE', "artikeltexte_edit.tpl"); @@ -259,7 +278,7 @@ class Artikeltexte { $input['meta_title'] = $this->app->Secure->GetPOST('meta_title'); $input['meta_description'] = $this->app->Secure->GetPOST('meta_description'); $input['meta_keywords'] = $this->app->Secure->GetPOST('meta_keywords'); - $input['katalogartikel'] = $this->app->Secure->GetPOST('katalogartikel'); + $input['katalogartikel'] = $this->app->Secure->GetPOST('katalogartikel')?'1':'0'; $input['katalog_bezeichnung'] = $this->app->Secure->GetPOST('katalog_bezeichnung'); $input['katalog_text'] = $this->app->Secure->GetPOST('katalog_text'); $input['shop'] = $this->app->Secure->GetPOST('shop'); diff --git a/www/pages/content/artikeltexte_edit.tpl b/www/pages/content/artikeltexte_edit.tpl index 9e784335..bb5a967c 100644 --- a/www/pages/content/artikeltexte_edit.tpl +++ b/www/pages/content/artikeltexte_edit.tpl @@ -25,6 +25,7 @@ @@ -35,6 +36,14 @@ + + + + @@ -123,14 +132,6 @@ - - - -
{|Artikel (DE) (Bitte im ersten Tab bearbeiten)|}:
[ARTIKEL_DE_ANZEIGE]
{|Artikel (EN)|}:
[NAME_EN][MSGNAME_EN]
{|Artikel (EN)|}:
[NAME_EN][MSGNAME_EN]
{|Kurztext (DE) (Bitte im ersten Tab bearbeiten)|}:
[KURZTEXT_DE_ANZEIGE]
+
+ {|Aktiv|}: + + +
{|Name|}: @@ -96,7 +105,7 @@ {|Katalogartikel|}: - +
- {|Aktiv|}: - - -
From 575c15c3338d0b60a163e6fb662d3fbf3d0ef561 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Sat, 8 Jun 2024 10:03:14 +0200 Subject: [PATCH 17/87] adress search filter search in delivery adress --- phpwf/plugins/class.yui.php | 19 +++++++++++++++++++ www/pages/content/adresse_table_filter.tpl | 20 +++++++++++++------- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/phpwf/plugins/class.yui.php b/phpwf/plugins/class.yui.php index c2d2398e..a276877c 100644 --- a/phpwf/plugins/class.yui.php +++ b/phpwf/plugins/class.yui.php @@ -5275,6 +5275,25 @@ url:strUrl, success:function(html){strReturn = html;}, async:false ) "; } + + if(isset($parameter['lieferadresse']) && !empty($parameter['lieferadresse'])) { + $paramsArray[] = " + ( + a.id IN + ( + SELECT + adresse + FROM + lieferadressen lfadr + WHERE + lfadr.name LIKE '%" . $parameter['lieferadresse'] . "%' OR + lfadr.strasse LIKE '%" . $parameter['lieferadresse'] . "%' OR + lfadr.plz LIKE '%" . $parameter['lieferadresse'] . "%' OR + lfadr.ort LIKE '%" . $parameter['lieferadresse'] . "%' + ) + ) + "; + } if(isset($parameter['abteilung']) && !empty($parameter['abteilung'])) { $paramsArray[] = "a.abteilung LIKE '%".$parameter['abteilung']."%' "; diff --git a/www/pages/content/adresse_table_filter.tpl b/www/pages/content/adresse_table_filter.tpl index 28437af7..551aaecb 100644 --- a/www/pages/content/adresse_table_filter.tpl +++ b/www/pages/content/adresse_table_filter.tpl @@ -62,10 +62,14 @@ {|E-Mail|}: - - {|Kunde hat Abo|} {|Marketingsperre|}: {|Lead|}: - - + + {|Lieferadresse|}: + + + + {|Kunde hat Abo|} {|Marketingsperre|}: {|Lead|}: + +
@@ -150,13 +154,15 @@ [ROLLEN] - Gruppen: - + + + Gruppen: + - +
From 3c170318dfe27aabba76623f1aef7970d8df782b Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Mon, 10 Jun 2024 17:43:16 +0200 Subject: [PATCH 18/87] gruppen module reimplemented --- www/pages/content/gruppen_edit.tpl | 784 +++++++++++++++++++++++++++++ www/pages/content/gruppen_list.tpl | 667 +----------------------- www/pages/gruppen.php | 351 +++++++++++-- 3 files changed, 1107 insertions(+), 695 deletions(-) create mode 100644 www/pages/content/gruppen_edit.tpl diff --git a/www/pages/content/gruppen_edit.tpl b/www/pages/content/gruppen_edit.tpl new file mode 100644 index 00000000..33b41335 --- /dev/null +++ b/www/pages/content/gruppen_edit.tpl @@ -0,0 +1,784 @@ +
+ + +
+ [MESSAGE] +
+ [FORMHANDLEREVENT] +
+
+
+
+
+ {|Gruppe|}Gruppe für die Zuordnung zu Preislisten, Onlineshop-Preislisten oder Adressgruppen + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ {|Aktiv|}: + + +
+ {|Name|}: + + +
+ {|Kennziffer|}: + + +
+ {|Internebemerkung|}: + + +
+ {|Art|}: + + +
+ {|Projekt|}: + + +
+ {|Grundrabatt|}: + + +
+ {|Zahlungszieltage|}: + + +
+ {|Zahlungszielskonto|}: + + +
+ {|Zahlungszieltageskonto|}: + + +
+ {|Portofrei_aktiv|}: + + +
+ {|Portofreiab|}: + + +
+
+
+
+
+
+ + +
+
+ +
+ diff --git a/www/pages/content/gruppen_list.tpl b/www/pages/content/gruppen_list.tpl index 860568d6..394c103a 100644 --- a/www/pages/content/gruppen_list.tpl +++ b/www/pages/content/gruppen_list.tpl @@ -1,661 +1,10 @@
- -
- - [MESSAGE] - -
-
-
{|Filter|}
-
    -
  • - - -
  • -
-
-
- -[TAB1] + +
+ [MESSAGE] + [TAB1] + [TAB1NEXT] +
- -
-[TAB3] -
- -
- -[EXTRA] - - - - - - - - - diff --git a/www/pages/gruppen.php b/www/pages/gruppen.php index 6fd22eab..41b52b5c 100644 --- a/www/pages/gruppen.php +++ b/www/pages/gruppen.php @@ -1,43 +1,322 @@ - app=$app; - if($intern) { - return; - } - $this->app->ActionHandlerInit($this); +/* + * Copyright (c) 2022 OpenXE project + */ - $this->app->ActionHandler("list","GruppenList"); - $this->app->DefaultActionHandler("list"); +use Xentral\Components\Database\Exception\QueryFailureException; +class Gruppen { - $this->app->ActionHandlerListen($app); - } - function GruppenList() - { - $this->app->Tpl->Set('VERS','Professional'); - $this->app->Tpl->Set('MODUL','Professional'); - $this->app->Tpl->Parse('PAGE', "only_version.tpl"); + function __construct($app, $intern = false) { + $this->app = $app; + if ($intern) + return; + + $this->app->ActionHandlerInit($this); + $this->app->ActionHandler("list", "gruppen_list"); + $this->app->ActionHandler("create", "gruppen_edit"); // This automatically adds a "New" button + $this->app->ActionHandler("edit", "gruppen_edit"); + $this->app->ActionHandler("delete", "gruppen_delete"); + $this->app->DefaultActionHandler("list"); + $this->app->ActionHandlerListen($app); } - } -} + public function Install() { + /* Fill out manually later */ + } + + static function TableSearch(&$app, $name, $erlaubtevars) { + switch ($name) { + case "gruppen_list": + $allowed['gruppen_list'] = array('list'); + $heading = array( + '', + '', + 'Kennziffer', + 'Name', + 'Art', + 'Internebemerkung', + 'Projekt', + 'Aktiv', + 'Menü'); + $width = array('1%','1%','10%'); // Fill out manually later + + // columns that are aligned right (numbers etc) + // $alignright = array(4,5,6,7,8); + + $findcols = array( + 'g.id', + 'g.id', + 'g.kennziffer', + 'g.name', + 'g.art', + 'g.internebemerkung', + 'p.abkuerzung', + 'g.aktiv', + 'g.id' + ); + $searchsql = array('g.name', 'g.art', 'g.kennziffer', 'g.internebemerkung'); + + $defaultorder = 1; + $defaultorderdesc = 0; + $aligncenter = array(); + $alignright = array(); + $numbercols = array(); + $sumcol = array(); + + $dropnbox = "'' AS `open`, CONCAT('') AS `auswahl`"; + +// $moreinfo = true; // Allow drop down details +// $moreinfoaction = "lieferschein"; // specify suffix for minidetail-URL to allow different minidetails +// $menucol = 11; // Set id col for moredata/menu + + $menu = "
" . "Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\"> " . "Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">" . "
"; + + $sql = "SELECT SQL_CALC_FOUND_ROWS g.id, $dropnbox, g.kennziffer, g.name, g.art, g.internebemerkung, p.abkuerzung, g.aktiv, g.id FROM gruppen g LEFT JOIN projekt p ON g.projekt = p.id"; + + $where = "1"; + $count = "SELECT count(DISTINCT id) FROM gruppen WHERE $where"; +// $groupby = ""; + + break; + } + + $erg = false; + + foreach ($erlaubtevars as $k => $v) { + if (isset($$v)) { + $erg[$v] = $$v; + } + } + return $erg; + } + + function gruppen_list() { + $this->app->erp->MenuEintrag("index.php?module=gruppen&action=list", "Übersicht"); + $this->app->erp->MenuEintrag("index.php?module=gruppen&action=create", "Neu anlegen"); + + $this->app->erp->MenuEintrag("index.php", "Zurück"); + + $this->app->YUI->TableSearch('TAB1', 'gruppen_list', "show", "", "", basename(__FILE__), __CLASS__); + $this->app->Tpl->Parse('PAGE', "gruppen_list.tpl"); + } + + public function gruppen_delete() { + $id = (int) $this->app->Secure->GetGET('id'); + + $this->app->DB->Delete("DELETE FROM `gruppen` WHERE `id` = '{$id}'"); + $this->app->Tpl->Set('MESSAGE', "
Der Eintrag wurde gelöscht.
"); + + $this->gruppen_list(); + } + + /* + * Edit gruppen item + * If id is empty, create a new one + */ + + function gruppen_edit() { + $id = $this->app->Secure->GetGET('id'); + + // Check if other users are editing this id +/* if($this->app->erp->DisableModul('gruppen',$id)) + { + return; + } */ + + $this->app->Tpl->Set('ID', $id); + + $this->app->erp->MenuEintrag("index.php?module=gruppen&action=edit&id=$id", "Details"); + $this->app->erp->MenuEintrag("index.php?module=gruppen&action=list", "Zurück zur Übersicht"); + $id = $this->app->Secure->GetGET('id'); + $input = $this->GetInput(); + + // Convert here + $input['aktiv'] = !empty($this->app->Secure->GetPOST('aktiv'))?"1":"0"; + + $submit = $this->app->Secure->GetPOST('submit'); + + if (empty($id)) { + // New item + $id = 'NULL'; + } + + if ($submit != '') + { + + // Write to database + + // Add checks here + + $input['projekt'] = $this->app->erp->ReplaceProjekt(true,$input['projekt'],true); // Parameters: Target db?, value, from form? + + $columns = "id, "; + $values = "$id, "; + $update = ""; + + $fix = ""; + + foreach ($input as $key => $value) { + $columns = $columns.$fix.$key; + $values = $values.$fix."'".$value."'"; + $update = $update.$fix.$key." = '$value'"; + + $fix = ", "; + } + +// echo($columns."
"); +// echo($values."
"); +// echo($update."
"); + + $sql = "INSERT INTO gruppen (".$columns.") VALUES (".$values.") ON DUPLICATE KEY UPDATE ".$update; + +// echo($sql); + + $this->app->DB->Update($sql); + + if ($id == 'NULL') { + $msg = $this->app->erp->base64_url_encode("
Das Element wurde erfolgreich angelegt.
"); + header("Location: index.php?module=gruppen&action=list&msg=$msg"); + } else { + $this->app->Tpl->Set('MESSAGE', "
Die Einstellungen wurden erfolgreich übernommen.
"); + } + } + + + // Load values again from database + $dropnbox = "'' AS `open`, CONCAT('') AS `auswahl`"; + $result = $this->app->DB->SelectArr("SELECT SQL_CALC_FOUND_ROWS g.id, $dropnbox, g.name, g.art, g.kennziffer, g.internebemerkung, g.grundrabatt, g.rabatt1, g.rabatt2, g.rabatt3, g.rabatt4, g.rabatt5, g.sonderrabatt_skonto, g.provision, g.kundennummer, g.partnerid, g.dta_aktiv, g.dta_periode, g.dta_dateiname, g.dta_mail, g.dta_mail_betreff, g.dta_mail_text, g.dtavariablen, g.dta_variante, g.bonus1, g.bonus1_ab, g.bonus2, g.bonus2_ab, g.bonus3, g.bonus3_ab, g.bonus4, g.bonus4_ab, g.bonus5, g.bonus5_ab, g.bonus6, g.bonus6_ab, g.bonus7, g.bonus7_ab, g.bonus8, g.bonus8_ab, g.bonus9, g.bonus9_ab, g.bonus10, g.bonus10_ab, g.zahlungszieltage, g.zahlungszielskonto, g.zahlungszieltageskonto, g.portoartikel, g.portofreiab, g.erweiterteoptionen, g.zentralerechnung, g.zentralregulierung, g.gruppe, g.preisgruppe, g.verbandsgruppe, g.rechnung_name, g.rechnung_strasse, g.rechnung_ort, g.rechnung_plz, g.rechnung_abteilung, g.rechnung_land, g.rechnung_email, g.rechnung_periode, g.rechnung_anzahlpapier, g.rechnung_permail, g.webid, g.portofrei_aktiv, g.projekt, g.objektname, g.objekttyp, g.parameter, g.objektname2, g.objekttyp2, g.parameter2, g.objektname3, g.objekttyp3, g.parameter3, g.kategorie, g.aktiv, g.id FROM gruppen g"." WHERE id=$id"); + + foreach ($result[0] as $key => $value) { + $this->app->Tpl->Set(strtoupper($key), $value); + } + + if (!empty($result)) { + $gruppen_from_db = $result[0]; + } else { + + } + + /* + * Add displayed items later + * + + $this->app->Tpl->Add('KURZUEBERSCHRIFT2', $email); + $this->app->Tpl->Add('EMAIL', $email); + $this->app->Tpl->Add('ANGEZEIGTERNAME', $angezeigtername); + + $this->app->YUI->AutoComplete("artikel", "artikelnummer"); + + */ + + $this->app->YUI->AutoComplete("kennziffer", "gruppekennziffer"); + + if ($gruppen_from_db['art'] != 'preisgruppe') { + $this->app->Tpl->Set('PREISGRUPPEHIDDEN','hidden'); + } + + $art_select = Array( + 'gruppe' => 'Gruppe', + 'preisgruppe' => 'Preisgruppe' + ); + $art_select = $this->app->erp->GetSelectAsso($art_select,$gruppen_from_db['art']); + $this->app->Tpl->Set('ARTSELECT',$art_select); + + $this->app->YUI->AutoComplete("projekt","projektname",1); + $this->app->Tpl->Set('PROJEKT',$this->app->erp->ReplaceProjekt(false,$gruppen_from_db['projekt'],false)); + + $this->app->Tpl->Set('AKTIV', $gruppen_from_db['aktiv']==1?"checked":""); + + $this->app->Tpl->Parse('PAGE', "gruppen_edit.tpl"); + } + + /** + * Get all paramters from html form and save into $input + */ + public function GetInput(): array { + $input = array(); + //$input['EMAIL'] = $this->app->Secure->GetPOST('email'); + + $input['name'] = $this->app->Secure->GetPOST('name'); + $input['art'] = $this->app->Secure->GetPOST('art'); + $input['kennziffer'] = $this->app->Secure->GetPOST('kennziffer'); + $input['internebemerkung'] = $this->app->Secure->GetPOST('internebemerkung'); + $input['grundrabatt'] = $this->app->Secure->GetPOST('grundrabatt'); + $input['rabatt1'] = $this->app->Secure->GetPOST('rabatt1'); + $input['rabatt2'] = $this->app->Secure->GetPOST('rabatt2'); + $input['rabatt3'] = $this->app->Secure->GetPOST('rabatt3'); + $input['rabatt4'] = $this->app->Secure->GetPOST('rabatt4'); + $input['rabatt5'] = $this->app->Secure->GetPOST('rabatt5'); + $input['sonderrabatt_skonto'] = $this->app->Secure->GetPOST('sonderrabatt_skonto'); + $input['provision'] = $this->app->Secure->GetPOST('provision'); + $input['kundennummer'] = $this->app->Secure->GetPOST('kundennummer'); + $input['partnerid'] = $this->app->Secure->GetPOST('partnerid'); + $input['dta_aktiv'] = $this->app->Secure->GetPOST('dta_aktiv'); + $input['dta_periode'] = $this->app->Secure->GetPOST('dta_periode'); + $input['dta_dateiname'] = $this->app->Secure->GetPOST('dta_dateiname'); + $input['dta_mail'] = $this->app->Secure->GetPOST('dta_mail'); + $input['dta_mail_betreff'] = $this->app->Secure->GetPOST('dta_mail_betreff'); + $input['dta_mail_text'] = $this->app->Secure->GetPOST('dta_mail_text'); + $input['dtavariablen'] = $this->app->Secure->GetPOST('dtavariablen'); + $input['dta_variante'] = $this->app->Secure->GetPOST('dta_variante'); + $input['bonus1'] = $this->app->Secure->GetPOST('bonus1'); + $input['bonus1_ab'] = $this->app->Secure->GetPOST('bonus1_ab'); + $input['bonus2'] = $this->app->Secure->GetPOST('bonus2'); + $input['bonus2_ab'] = $this->app->Secure->GetPOST('bonus2_ab'); + $input['bonus3'] = $this->app->Secure->GetPOST('bonus3'); + $input['bonus3_ab'] = $this->app->Secure->GetPOST('bonus3_ab'); + $input['bonus4'] = $this->app->Secure->GetPOST('bonus4'); + $input['bonus4_ab'] = $this->app->Secure->GetPOST('bonus4_ab'); + $input['bonus5'] = $this->app->Secure->GetPOST('bonus5'); + $input['bonus5_ab'] = $this->app->Secure->GetPOST('bonus5_ab'); + $input['bonus6'] = $this->app->Secure->GetPOST('bonus6'); + $input['bonus6_ab'] = $this->app->Secure->GetPOST('bonus6_ab'); + $input['bonus7'] = $this->app->Secure->GetPOST('bonus7'); + $input['bonus7_ab'] = $this->app->Secure->GetPOST('bonus7_ab'); + $input['bonus8'] = $this->app->Secure->GetPOST('bonus8'); + $input['bonus8_ab'] = $this->app->Secure->GetPOST('bonus8_ab'); + $input['bonus9'] = $this->app->Secure->GetPOST('bonus9'); + $input['bonus9_ab'] = $this->app->Secure->GetPOST('bonus9_ab'); + $input['bonus10'] = $this->app->Secure->GetPOST('bonus10'); + $input['bonus10_ab'] = $this->app->Secure->GetPOST('bonus10_ab'); + $input['zahlungszieltage'] = $this->app->Secure->GetPOST('zahlungszieltage'); + $input['zahlungszielskonto'] = $this->app->Secure->GetPOST('zahlungszielskonto'); + $input['zahlungszieltageskonto'] = $this->app->Secure->GetPOST('zahlungszieltageskonto'); + $input['portoartikel'] = $this->app->Secure->GetPOST('portoartikel'); + $input['portofreiab'] = $this->app->Secure->GetPOST('portofreiab'); + $input['erweiterteoptionen'] = $this->app->Secure->GetPOST('erweiterteoptionen'); + $input['zentralerechnung'] = $this->app->Secure->GetPOST('zentralerechnung'); + $input['zentralregulierung'] = $this->app->Secure->GetPOST('zentralregulierung'); + $input['gruppe'] = $this->app->Secure->GetPOST('gruppe'); + $input['preisgruppe'] = $this->app->Secure->GetPOST('preisgruppe'); + $input['verbandsgruppe'] = $this->app->Secure->GetPOST('verbandsgruppe'); + $input['rechnung_name'] = $this->app->Secure->GetPOST('rechnung_name'); + $input['rechnung_strasse'] = $this->app->Secure->GetPOST('rechnung_strasse'); + $input['rechnung_ort'] = $this->app->Secure->GetPOST('rechnung_ort'); + $input['rechnung_plz'] = $this->app->Secure->GetPOST('rechnung_plz'); + $input['rechnung_abteilung'] = $this->app->Secure->GetPOST('rechnung_abteilung'); + $input['rechnung_land'] = $this->app->Secure->GetPOST('rechnung_land'); + $input['rechnung_email'] = $this->app->Secure->GetPOST('rechnung_email'); + $input['rechnung_periode'] = $this->app->Secure->GetPOST('rechnung_periode'); + $input['rechnung_anzahlpapier'] = $this->app->Secure->GetPOST('rechnung_anzahlpapier'); + $input['rechnung_permail'] = $this->app->Secure->GetPOST('rechnung_permail'); + $input['webid'] = $this->app->Secure->GetPOST('webid'); + $input['portofrei_aktiv'] = $this->app->Secure->GetPOST('portofrei_aktiv'); + $input['projekt'] = $this->app->Secure->GetPOST('projekt'); + $input['objektname'] = $this->app->Secure->GetPOST('objektname'); + $input['objekttyp'] = $this->app->Secure->GetPOST('objekttyp'); + $input['parameter'] = $this->app->Secure->GetPOST('parameter'); + $input['objektname2'] = $this->app->Secure->GetPOST('objektname2'); + $input['objekttyp2'] = $this->app->Secure->GetPOST('objekttyp2'); + $input['parameter2'] = $this->app->Secure->GetPOST('parameter2'); + $input['objektname3'] = $this->app->Secure->GetPOST('objektname3'); + $input['objekttyp3'] = $this->app->Secure->GetPOST('objekttyp3'); + $input['parameter3'] = $this->app->Secure->GetPOST('parameter3'); + $input['kategorie'] = $this->app->Secure->GetPOST('kategorie'); + $input['aktiv'] = $this->app->Secure->GetPOST('aktiv'); + + + return $input; + } + } From 0b5b7cbed19ca2d075b0779100980c538949da5c Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 11 Jun 2024 19:45:39 +0200 Subject: [PATCH 19/87] Bugfixes adressstammdatenblatt --- www/lib/dokumente/class.adressstammblatt.php | 465 +++++++++--------- www/lib/dokumente/class.dokumentenvorlage.php | 6 +- www/pages/adresse.php | 2 +- 3 files changed, 238 insertions(+), 235 deletions(-) diff --git a/www/lib/dokumente/class.adressstammblatt.php b/www/lib/dokumente/class.adressstammblatt.php index 93904637..2a7c8507 100644 --- a/www/lib/dokumente/class.adressstammblatt.php +++ b/www/lib/dokumente/class.adressstammblatt.php @@ -1,235 +1,236 @@ -app=$app; - //parent::Dokumentenvorlage(); - $this->doctype="adresse"; - $this->doctypeOrig="Adressstammblatt"; - parent::__construct($this->app,$projekt); - } - - public function renderDocument() { - // prepare page details - SuperFPDF::__construct('P','mm','A4'); - - - $this->AddPage(); - $this->SetDisplayMode("real","single"); - - $this->SetMargins(15,50); - $this->SetAutoPageBreak(true,40); - $this->AliasNbPages('{nb}'); - - - // Bei Adressstammblatt immer oben beginnen - $this->abstand_betreffzeileoben=0; - $this->logofile = "";//$this->app->erp->GetTMP()."/".$this->app->Conf->WFdbname."_logo.jpg"; - $this->briefpapier=""; - - - $schrift = $this->app->erp->Firmendaten('schriftgroesse'); - - $this->SetFontSize($schrift); - $this->SetFont($this->GetFont(),'','10'); - $this->SetX($this->GetX()+160); - $this->Cell(10,0,date("d.m.Y"),"","","L"); - - $this->renderDoctype(); - - $adresse = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='".$this->id."'"); - $adresse = reset($adresse); - - if($adresse['typ']=="firma") - { - $infofields[]=array("Firma",$adresse['name']); - if($adresse['ansprechpartner']!="") - $infofields[]=array("Ansprechpartner",$adresse['ansprechpartner']); - } else { - $infofields[]=array("Name",$adresse['name']); - } - - $infofields[]=array("Anschrift",$adresse['land']."-".$adresse['plz']." ".$adresse['ort'].", ".$adresse['strasse']); - - $felder = array('telefon','telefax','mobil','email','web'); - foreach($felder as $feldname) - { - $infofields[]=array(ucfirst($feldname),$adresse[$feldname=='web'?'internetseite':$feldname]); - } - - - if($this->app->erp->Firmendaten("modul_mlm")==1) - { - $mlmvertragsbeginn = $this->app->DB->Select("SELECT DATE_FORMAT(mlmvertragsbeginn,'%d.%m.%Y') FROM adresse WHERE id='".$adresse['id']."' LIMIT 1"); - if($mlmvertragsbeginn=="00.00.0000") $mlmvertragsbeginn = "kein Vertragsbeginn eingestellt"; - $sponsorid = $this->app->DB->Select("SELECT sponsor FROM adresse WHERE id='".$adresse['id']."' LIMIT 1"); - if($sponsorid> 0) - $sponsor = $this->app->DB->Select("SELECT CONCAT(kundennummer,' ',name) FROM adresse WHERE id='$sponsorid' LIMIT 1"); - else - $sponsor = "Kein Sponsor vorhanden"; - - $erfasstam = $this->app->DB->Select("SELECT DATE_FORMAT(zeitstempel,'%d.%m.%Y') FROM objekt_protokoll WHERE objekt='adresse' AND objektid='".$adresse['id']."' AND action_long='adresse_create' LIMIT 1"); - - $infofields[]=array("Sponsor",$sponsor); - $infofields[]=array("Erfasst am",$erfasstam); - $infofields[]=array("Vertragsbeginn am",$mlmvertragsbeginn); - } - - - - $infofields[]=array("UST-ID",$adresse['ustid']); - - - if($adresse['kundennummer']!="") - $numbers[] = array("Kunden Nr.",$adresse['kundennummer']); - - if($adresse['lieferantennummer']!="") - $numbers[] = array("Lieferanten Nr.",$adresse['lieferantennummer']); - - if($adresse['mitarbeiternummer']!="") - $numbers[] = array("Mitarbeiter Nr.",$adresse['mitarbeiternummer']); - - if(count($numbers)>0) - $this->renderInfoBox($numbers); - - $this->Ln(5); - $this->renderHeading("Adressstammblatt",8); - $this->renderInfoBox($infofields); - - - - $ansprechpartner_tmp = $this->app->DB->SelectArr("SELECT CONCAT(name,', ',if(bereich='','-',bereich), - ', Telefon: ',telefon, - ', Mobil: ',mobil, - ', E-Mail: ',email - ) as 'value' FROM ansprechpartner WHERE adresse='".$adresse['id']."'"); - - for($i=0;$i 0) - { - $this->Ln(5); - $this->renderHeading("Ansprechpartner",8); - $this->renderInfoBoxSingle($ansprechpartner); - } - - $lieferadressen_tmp = $this->app->DB->SelectArr("SELECT name,abteilung,unterabteilung,adresszusatz,strasse,plz,ort,land, - telefon,email - FROM lieferadressen WHERE adresse='".$adresse['id']."' ORDER by standardlieferadresse DESC"); - - for($i=0;$i$value) - { - switch($key) - { - case "email": - $lieferadressen_tmp[$i]['value'] .= "E-Mail: $value, "; - break; - - case "telefon": - $lieferadressen_tmp[$i]['value'] .= "Telefon: $value, "; - break; - case "telefax": - $lieferadressen_tmp[$i]['value'] .= "Telefax: $value, "; - break; - - default: - if($value!="") - $lieferadressen_tmp[$i]['value'] .= "$value, "; - } - } - - $lieferadressen_tmp[$i]['value'] = trim($lieferadressen_tmp[$i]['value'],', '); - if($i==0) $standard = " (Standard)"; else $standard=""; - - $lieferadressen[] = $lieferadressen_tmp[$i]['value'].$standard; - } - - if(count($lieferadressen) > 0) - { - $this->Ln(5); - $this->renderHeading("Lieferadressen",8); - $this->renderInfoBoxSingle($lieferadressen); - } - - - $this->Ln(5); - - if($adresse['sonstiges']!="") - { - $this->renderHeading("Sonstiges",8); - $this->SetFont($this->GetFont(),'',7); - $this->MultiCell(180,4,$this->WriteHTML($adresse['sonstiges'])); - } - - $this->renderFooter(); - } - - - function GetAdressstammblatt($id,$info="",$extrafreitext="") - { - $this->id = $id; - // das muss vom reisekosten sein!!!! - //$this->setRecipientLieferadresse($id,"reisekosten"); - - // OfferNo, customerId, OfferDate - /*$auftrag = $this->app->DB->Select("SELECT auftragid FROM reisekosten WHERE id='$id' LIMIT 1"); - $auftrag = $this->app->DB->Select("SELECT belegnr FROM auftrag WHERE id='$auftrag' LIMIT 1"); - $bearbeiter = $this->app->DB->Select("SELECT bearbeiter FROM reisekosten WHERE id='$id' LIMIT 1"); - $prefix = $this->app->DB->Select("SELECT prefix FROM reisekosten WHERE id='$id' LIMIT 1"); - $bestellbestaetigung = $this->app->DB->Select("SELECT bestellbestaetigung FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->datum = $this->app->DB->Select("SELECT DATE_FORMAT(datum,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); - - $this->von = $this->app->DB->Select("SELECT DATE_FORMAT(von,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->bis = $this->app->DB->Select("SELECT DATE_FORMAT(bis,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->von_zeit = $this->app->DB->Select("SELECT von_zeit FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->bis_zeit = $this->app->DB->Select("SELECT bis_zeit FROM reisekosten WHERE id='$id' LIMIT 1"); - $belegnr = $this->app->DB->Select("SELECT belegnr FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->anlass = $this->app->DB->Select("SELECT anlass FROM reisekosten WHERE id='$id' LIMIT 1"); - $this->freitext = $this->app->DB->Select("SELECT freitext FROM reisekosten WHERE id='$id' LIMIT 1"); - $projekt = $this->app->DB->Select("SELECT projekt FROM reisekosten WHERE id='$id' LIMIT 1"); - $mitarbeiter = $this->app->DB->Select("SELECT mitarbeiter FROM reisekosten WHERE id='$id' LIMIT 1");*/ - $kunde= $this->app->DB->SelectArr("SELECT name,kundennummer,lieferantennummer FROM adresse WHERE id='$id' LIMIT 1"); - $kunde = reset($kunde); - - $kundennummer = $kunde['kundennummer']; - $this->name = $kunde['name']; - - $this->projektabkuerzung = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='$projekt'"); - $this->firmenname = $this->app->erp->Firmendaten('name'); - $this->doctypeOrig="Adresse: ".$kunde['name']; - $this->barcode=$belegnr; - - //$ohne_briefpapier = $this->app->DB->Select("SELECT ohne_briefpapier FROM reisekosten WHERE id='$id' LIMIT 1"); - - - - - //$artikel = $this->app->DB->SelectArr("SELECT *,DATE_FORMAT(datum,'%d.%m.%Y') as datum, CONCAT(rk.nummer,'- ',rk.beschreibung) as reisekostenart FROM reisekosten_position rp LEFT JOIN reisekostenart rk ON rk.id=rp.reisekostenart WHERE rp.reisekosten='$id' ORDER By rp.sort"); - - //$waehrung = $this->app->DB->Select("SELECT waehrung FROM reisekosten_position WHERE reisekosten='$id' LIMIT 1"); - - /* Dateiname */ - $this->filename = date('Ymd')."_STAMMDATEN_ADRESSE_".$this->app->erp->Dateinamen($kunde['name']).".pdf"; - - $this->setBarcode($id); - } - - -} +app=$app; + //parent::Dokumentenvorlage(); + $this->doctype="adresse"; + $this->table="adresse"; + $this->doctypeOrig="Adressstammblatt"; + parent::__construct($this->app,$projekt); + } + + public function renderDocument() { + // prepare page details + SuperFPDF::__construct('P','mm','A4'); + + + $this->AddPage(); + $this->SetDisplayMode("real","single"); + + $this->SetMargins(15,50); + $this->SetAutoPageBreak(true,40); + $this->AliasNbPages('{nb}'); + + + // Bei Adressstammblatt immer oben beginnen + $this->abstand_betreffzeileoben=0; + $this->logofile = "";//$this->app->erp->GetTMP()."/".$this->app->Conf->WFdbname."_logo.jpg"; + $this->briefpapier=""; + + + $schrift = $this->app->erp->Firmendaten('schriftgroesse'); + + $this->SetFontSize($schrift); + $this->SetFont($this->GetFont(),'','10'); + $this->SetX($this->GetX()+160); + $this->Cell(10,0,date("d.m.Y"),"","","L"); + + $this->renderDoctype(); + + $adresse = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='".$this->id."'"); + $adresse = reset($adresse); + + if($adresse['typ']=="firma") + { + $infofields[]=array("Firma",$adresse['name']); + if($adresse['ansprechpartner']!="") + $infofields[]=array("Ansprechpartner",$adresse['ansprechpartner']); + } else { + $infofields[]=array("Name",$adresse['name']); + } + + $infofields[]=array("Anschrift",$adresse['land']."-".$adresse['plz']." ".$adresse['ort'].", ".$adresse['strasse']); + + $felder = array('telefon','telefax','mobil','email','web'); + foreach($felder as $feldname) + { + $infofields[]=array(ucfirst($feldname),$adresse[$feldname=='web'?'internetseite':$feldname]); + } + + + if($this->app->erp->Firmendaten("modul_mlm")==1) + { + $mlmvertragsbeginn = $this->app->DB->Select("SELECT DATE_FORMAT(mlmvertragsbeginn,'%d.%m.%Y') FROM adresse WHERE id='".$adresse['id']."' LIMIT 1"); + if($mlmvertragsbeginn=="00.00.0000") $mlmvertragsbeginn = "kein Vertragsbeginn eingestellt"; + $sponsorid = $this->app->DB->Select("SELECT sponsor FROM adresse WHERE id='".$adresse['id']."' LIMIT 1"); + if($sponsorid> 0) + $sponsor = $this->app->DB->Select("SELECT CONCAT(kundennummer,' ',name) FROM adresse WHERE id='$sponsorid' LIMIT 1"); + else + $sponsor = "Kein Sponsor vorhanden"; + + $erfasstam = $this->app->DB->Select("SELECT DATE_FORMAT(zeitstempel,'%d.%m.%Y') FROM objekt_protokoll WHERE objekt='adresse' AND objektid='".$adresse['id']."' AND action_long='adresse_create' LIMIT 1"); + + $infofields[]=array("Sponsor",$sponsor); + $infofields[]=array("Erfasst am",$erfasstam); + $infofields[]=array("Vertragsbeginn am",$mlmvertragsbeginn); + } + + + + $infofields[]=array("UST-ID",$adresse['ustid']); + + + if($adresse['kundennummer']!="") + $numbers[] = array("Kunden Nr.",$adresse['kundennummer']); + + if($adresse['lieferantennummer']!="") + $numbers[] = array("Lieferanten Nr.",$adresse['lieferantennummer']); + + if($adresse['mitarbeiternummer']!="") + $numbers[] = array("Mitarbeiter Nr.",$adresse['mitarbeiternummer']); + + if($numbers?count($numbers):0>0) + $this->renderInfoBox($numbers); + + $this->Ln(5); + $this->renderHeading("Adressstammblatt",8); + $this->renderInfoBox($infofields); + + + + $ansprechpartner_tmp = $this->app->DB->SelectArr("SELECT CONCAT(name,', ',if(bereich='','-',bereich), + ', Telefon: ',telefon, + ', Mobil: ',mobil, + ', E-Mail: ',email + ) as 'value' FROM ansprechpartner WHERE adresse='".$adresse['id']."'"); + + for($i=0;$i<($ansprechpartner_tmp?count($ansprechpartner_tmp):0);$i++) $ansprechpartner[] = $ansprechpartner_tmp[$i]['value']; + if($ansprechpartner_tmp?count($ansprechpartner):0 > 0) + { + $this->Ln(5); + $this->renderHeading("Ansprechpartner",8); + $this->renderInfoBoxSingle($ansprechpartner); + } + + $lieferadressen_tmp = $this->app->DB->SelectArr("SELECT name,abteilung,unterabteilung,adresszusatz,strasse,plz,ort,land, + telefon,email + FROM lieferadressen WHERE adresse='".$adresse['id']."' ORDER by standardlieferadresse DESC"); + + for($i=0;$i<($lieferadressen_tmp?count($lieferadressen_tmp):0);$i++) { + $lieferadressen_tmp[$i]['value']=""; + foreach($lieferadressen_tmp[$i] as $key=>$value) + { + switch($key) + { + case "email": + $lieferadressen_tmp[$i]['value'] .= "E-Mail: $value, "; + break; + + case "telefon": + $lieferadressen_tmp[$i]['value'] .= "Telefon: $value, "; + break; + case "telefax": + $lieferadressen_tmp[$i]['value'] .= "Telefax: $value, "; + break; + + default: + if($value!="") + $lieferadressen_tmp[$i]['value'] .= "$value, "; + } + } + + $lieferadressen_tmp[$i]['value'] = trim($lieferadressen_tmp[$i]['value'],', '); + if($i==0) $standard = " (Standard)"; else $standard=""; + + $lieferadressen[] = $lieferadressen_tmp[$i]['value'].$standard; + } + + if($lieferadressen?count($lieferadressen):0 > 0) + { + $this->Ln(5); + $this->renderHeading("Lieferadressen",8); + $this->renderInfoBoxSingle($lieferadressen); + } + + + $this->Ln(5); + + if($adresse['sonstiges']!="") + { + $this->renderHeading("Sonstiges",8); + $this->SetFont($this->GetFont(),'',7); + $this->MultiCell(180,4,$this->WriteHTML($adresse['sonstiges'])); + } + + $this->renderFooter(); + } + + + function GetAdressstammblatt($id,$info="",$extrafreitext="") + { + $this->id = $id; + // das muss vom reisekosten sein!!!! + //$this->setRecipientLieferadresse($id,"reisekosten"); + + // OfferNo, customerId, OfferDate + /*$auftrag = $this->app->DB->Select("SELECT auftragid FROM reisekosten WHERE id='$id' LIMIT 1"); + $auftrag = $this->app->DB->Select("SELECT belegnr FROM auftrag WHERE id='$auftrag' LIMIT 1"); + $bearbeiter = $this->app->DB->Select("SELECT bearbeiter FROM reisekosten WHERE id='$id' LIMIT 1"); + $prefix = $this->app->DB->Select("SELECT prefix FROM reisekosten WHERE id='$id' LIMIT 1"); + $bestellbestaetigung = $this->app->DB->Select("SELECT bestellbestaetigung FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->datum = $this->app->DB->Select("SELECT DATE_FORMAT(datum,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); + + $this->von = $this->app->DB->Select("SELECT DATE_FORMAT(von,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->bis = $this->app->DB->Select("SELECT DATE_FORMAT(bis,'%d.%m.%Y') FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->von_zeit = $this->app->DB->Select("SELECT von_zeit FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->bis_zeit = $this->app->DB->Select("SELECT bis_zeit FROM reisekosten WHERE id='$id' LIMIT 1"); + $belegnr = $this->app->DB->Select("SELECT belegnr FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->anlass = $this->app->DB->Select("SELECT anlass FROM reisekosten WHERE id='$id' LIMIT 1"); + $this->freitext = $this->app->DB->Select("SELECT freitext FROM reisekosten WHERE id='$id' LIMIT 1"); + $projekt = $this->app->DB->Select("SELECT projekt FROM reisekosten WHERE id='$id' LIMIT 1"); + $mitarbeiter = $this->app->DB->Select("SELECT mitarbeiter FROM reisekosten WHERE id='$id' LIMIT 1");*/ + $kunde= $this->app->DB->SelectArr("SELECT name,kundennummer,lieferantennummer FROM adresse WHERE id='$id' LIMIT 1"); + $kunde = reset($kunde); + + $kundennummer = $kunde['kundennummer']; + $this->name = $kunde['name']; + + $this->projektabkuerzung = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='$projekt'"); + $this->firmenname = $this->app->erp->Firmendaten('name'); + $this->doctypeOrig="Adresse: ".$kunde['name']; + $this->barcode=$belegnr; + + //$ohne_briefpapier = $this->app->DB->Select("SELECT ohne_briefpapier FROM reisekosten WHERE id='$id' LIMIT 1"); + + + + + //$artikel = $this->app->DB->SelectArr("SELECT *,DATE_FORMAT(datum,'%d.%m.%Y') as datum, CONCAT(rk.nummer,'- ',rk.beschreibung) as reisekostenart FROM reisekosten_position rp LEFT JOIN reisekostenart rk ON rk.id=rp.reisekostenart WHERE rp.reisekosten='$id' ORDER By rp.sort"); + + //$waehrung = $this->app->DB->Select("SELECT waehrung FROM reisekosten_position WHERE reisekosten='$id' LIMIT 1"); + + /* Dateiname */ + $this->filename = date('Ymd')."_STAMMDATEN_ADRESSE_".$this->app->erp->Dateinamen($kunde['name']).".pdf"; + + $this->setBarcode($id); + } + + +} diff --git a/www/lib/dokumente/class.dokumentenvorlage.php b/www/lib/dokumente/class.dokumentenvorlage.php index 1c14dcd3..f2a024f9 100644 --- a/www/lib/dokumente/class.dokumentenvorlage.php +++ b/www/lib/dokumente/class.dokumentenvorlage.php @@ -474,9 +474,11 @@ class Dokumentenvorlage extends SuperFPDF { $this->Output($dir."/".$this->table."/".$this->id."_".$this->filename,'F'); } - public function displayDocument() { + public function displayDocument($archive = true) { $this->renderDocument(); - $this->archiveDocument(); + if ($archive) { + $this->archiveDocument(); + } $this->Output($this->filename,'D'); exit; } diff --git a/www/pages/adresse.php b/www/pages/adresse.php index ca86ff8d..82c3a957 100644 --- a/www/pages/adresse.php +++ b/www/pages/adresse.php @@ -780,7 +780,7 @@ class Adresse extends GenAdresse { } $Brief->GetAdressstammblatt($id); - $Brief->displayDocument(); + $Brief->displayDocument(archive: false); $this->app->ExitXentral(); } From 2b43efca70d3e8f6224116b47b4f528e6b110a02 Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Tue, 11 Jun 2024 20:00:16 +0200 Subject: [PATCH 20/87] Bugfix add price when address is in several groups --- www/lib/class.erpapi.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index 9ec83a60..27679ee4 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -38222,7 +38222,7 @@ function Firmendaten($field,$projekt="") $sql_erweiterung = ''; if(!empty($gruppenarr)) { - $sql_erweiterung .= ' OR v.gruppe IN ('.implode(' ', $gruppenarr).') '; + $sql_erweiterung .= ' OR v.gruppe IN ('.implode(', ', $gruppenarr).') '; } if(!$guenstigste_vk) { $vkarr = $this->app->DB->SelectArr("SELECT * FROM verkaufspreise v WHERE v.ab_menge <= '$menge' AND From 09aacfbb7bb6bedc52eb115913d906a5547a278d Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Wed, 12 Jun 2024 11:24:10 +0200 Subject: [PATCH 21/87] Bugfix file upload dragndrop --- phpwf/plugins/class.yui.php | 168 +++++++++++++++----------- www/pages/content/datei_neudirekt.tpl | 6 +- 2 files changed, 103 insertions(+), 71 deletions(-) diff --git a/phpwf/plugins/class.yui.php b/phpwf/plugins/class.yui.php index a276877c..bfe50fbd 100644 --- a/phpwf/plugins/class.yui.php +++ b/phpwf/plugins/class.yui.php @@ -14135,24 +14135,18 @@ source: "index.php?module=ajax&action=filter&filtername=' . $filter . $extendurl $action = $this->app->Secure->GetGET("action"); $id = $this->app->Secure->GetGET("id"); if($id)$this->app->Tpl->Set('ID',$id); - if ($speichern != "") { - $titel = $this->app->Secure->GetPOST("titel"); - $beschreibung = $this->app->Secure->GetPOST("beschreibung"); - $stichwort = $this->app->Secure->GetPOST("stichwort"); - $this->app->Tpl->Set('TITLE', $titel); - $this->app->Tpl->Set('BESCHREIBUNG', $beschreibung); - - if ($_FILES['upload']['tmp_name'] == "") { - $this->app->Tpl->Set('ERROR', "
Bitte wählen Sie eine Datei aus und laden Sie diese herauf!
"); - $this->app->erp->EnableTab("tabs-2"); - } else { - //$fileid = $this->app->erp->CreateDatei($_FILES['upload']['name'],$titel,$beschreibung,"",$_FILES['upload']['tmp_name'],$this->app->User->GetName()); - $this->app->erp->AddDateiVersion($datei, $this->app->User->GetName(), $_FILES['upload']['name'], "Neue Version", $_FILES['upload']['tmp_name']); - header("Location: index.php?module=$module&action=$action&id=$id"); - exit; + // Get files here + if ($speichern != "") { + $retval = $this->FilesFromUploadtoDMS(null, null, $datei); + if ($retval !== true) { + $this->app->Tpl->Set('ERROR', implode(', ',$retval)); + $this->app->erp->EnableTab("tabs-2"); + } else { + header("Location: index.php?module=$module&action=$action&id=$id"); } } + $this->app->Tpl->Set('STARTDISABLE', ""); $this->app->Tpl->Parse($parsetarget, "datei_neudirekt.tpl"); @@ -14229,61 +14223,18 @@ source: "index.php?module=ajax&action=filter&filtername=' . $filter . $extendurl $id = $this->app->Secure->GetGET("id"); $sid = $this->app->Secure->GetGET("sid"); if($id)$this->app->Tpl->Set('ID', $id); + + // Get files here if ($speichern != "") { - if($parameter == '')$parameter = $id; - if(isset($_POST['dateiv'])) - { - foreach($_POST['dateiv'] as $k => $v) - { - $name = $this->app->DB->real_escape_string($_POST['dateiname'][$k]); - $titel = $this->app->DB->real_escape_string($_POST['dateititel'][$k]); - $beschreibung = $this->app->DB->real_escape_string($_POST['beschreibung'][$k]); - $stichwort = $this->app->DB->real_escape_string($_POST['dateistichwort'][$k]); - - //$getMime = explode('.', $name); - //$mime = end($getMime); - - $data = explode(',', $v); - - $encodedData = str_replace(' ','+',$data[1]); - $decodedData = base64_decode($encodedData); - - $this->app->Tpl->Set('TITLE', $titel); - $this->app->Tpl->Set('BESCHREIBUNG', $beschreibung); - - if ($v == "" ) { - $this->app->Tpl->Set('ERROR', "
Keine Datei ausgewählt!
"); - $this->app->erp->EnableTab("tabs-2"); - } else { - $fileid = $this->app->erp->CreateDatei($name, $titel, $beschreibung, "", $decodedData, $this->app->User->GetName()); - - // stichwoerter hinzufuegen - $this->app->erp->AddDateiStichwort($fileid, $stichwort, $objekt, $parameter); - } - } - if($_FILES['upload']['tmp_name'] == "") - { - header("Location: index.php?module=$_module&action=$_action&id=$id&sid=$sid".($typ!=''?"&typ=".$typ:'')); - } + if($parameter == '') { + $parameter = $id; } - - - - $titel = $this->app->Secure->GetPOST("titel"); - $beschreibung = $this->app->Secure->GetPOST("beschreibung"); - $stichwort = $this->app->Secure->GetPOST("stichwort"); - $this->app->Tpl->Set('TITLE', $titel); - $this->app->Tpl->Set('BESCHREIBUNG', $beschreibung); - - if ($_FILES['upload']['tmp_name'] == "" && empty($_POST['dateiv'])) { - $this->app->Tpl->Set('ERROR', "
Keine Datei ausgewählt!
"); - $this->app->erp->EnableTab("tabs-2"); - } elseif($_FILES['upload']['tmp_name'] != '') { - $fileid = $this->app->erp->CreateDatei($_FILES['upload']['name'], $titel, $beschreibung, "", $_FILES['upload']['tmp_name'], $this->app->User->GetName()); - - // stichwoerter hinzufuegen - $this->app->erp->AddDateiStichwort($fileid, $stichwort, $objekt, $parameter); - header("Location: index.php?module=$_module&action=$_action&id=$id&sid=$sid".($typ!=''?"&typ=".$typ:'')); + $retval = $this->FilesFromUploadtoDMS($objekt, $parameter); + if ($retval !== true) { + $this->app->Tpl->Set('ERROR', implode(', ',$retval)); + $this->app->erp->EnableTab("tabs-2"); + } else { + header("Location: index.php?module=$_module&action=$_action&id=$id&sid=$sid".($typ!=''?"&typ=".$typ:'')); } } @@ -14551,6 +14502,87 @@ source: "index.php?module=ajax&action=filter&filtername=' . $filter . $extendurl } } + /* + * Retrieve uploaded files and put them into DMS + * $datei: given file, just add a new version + * Return array of errors or true + */ + function FilesFromUploadtoDMS($objekt, $parameter, $datei = false) { + + $retval = true; + // Files come from drag'n'drop + if(isset($_POST['dateiv'])) + { + foreach($_POST['dateiv'] as $k => $v) + { + $name = $this->app->DB->real_escape_string($_POST['dateiname'][$k]); + $titel = $this->app->DB->real_escape_string($_POST['dateititel'][$k]); + $beschreibung = $this->app->DB->real_escape_string($_POST['dateibeschreibung'][$k]); + $stichwort = $this->app->DB->real_escape_string($_POST['dateistichwort'][$k]); + + $data = explode(',', $v); + + $encodedData = str_replace(' ','+',$data[1]); + $decodedData = base64_decode($encodedData); + + $this->app->Tpl->Set('TITLE', $titel); + $this->app->Tpl->Set('BESCHREIBUNG', $beschreibung); + + if ($v == "" ) { + $this->app->Tpl->Set('ERROR', "
Keine Datei ausgewählt!
"); + $this->app->erp->EnableTab("tabs-2"); + } else { + // Save file to disk first + $tempfilename = rtrim($this->app->erp->GetTMP(), '/') . "/" . $name; + if($handle = fopen($tempfilename, "wb")){ + fwrite($handle, $decodedData); + fclose($handle); + // Add file to DMS + if ($datei) { + $this->app->erp->AddDateiVersion($datei, $this->app->User->GetName(), $name, "Neue Version", $tempfilename); + } else { + $fileid = $this->app->erp->CreateDatei($name, $titel, $beschreibung, "", $tempfilename, $this->app->User->GetName()); + // stichwoerter hinzufuegen + $this->app->erp->AddDateiStichwort($fileid, $stichwort, $objekt, $parameter); + } + } else { + if ($retval === true) { + $retval = array(); + } + $retval[] = "
Datei konnte nicht gespeichert werden: ".$name."
"; + } + } + } + } // drag'n'drop + // Single file comes from browse button + else { + $titel = $this->app->Secure->GetPOST("titel"); + $beschreibung = $this->app->Secure->GetPOST("beschreibung"); + $stichwort = $this->app->Secure->GetPOST("stichwort"); + $this->app->Tpl->Set('TITLE', $titel); + $this->app->Tpl->Set('BESCHREIBUNG', $beschreibung); + + if ($_FILES['upload']['tmp_name'] == "" && empty($_POST['dateiv'])) { + $this->app->erp->EnableTab("tabs-2"); + if ($retval === true) { + $retval = array(); + } + $retval[] = "
Keine Datei ausgewählt!
"; + + } elseif ($_FILES['upload']['tmp_name'] != '') { + if ($datei) { + $this->app->erp->AddDateiVersion($datei, $this->app->User->GetName(), $_FILES['upload']['name'], "Neue Version", $_FILES['upload']['tmp_name']); + } + else { + $fileid = $this->app->erp->CreateDatei($_FILES['upload']['name'], $titel, $beschreibung, "", $_FILES['upload']['tmp_name'], $this->app->User->GetName()); + // stichwoerter hinzufuegen + $this->app->erp->AddDateiStichwort($fileid, $stichwort, $objekt, $parameter); + } + } + } + return($retval); + } + function SortListAdd($parsetarget, &$ref, $menu, $sql, $sort = true) { $module = $this->app->Secure->GetGET("module"); diff --git a/www/pages/content/datei_neudirekt.tpl b/www/pages/content/datei_neudirekt.tpl index f7200905..3321a05d 100644 --- a/www/pages/content/datei_neudirekt.tpl +++ b/www/pages/content/datei_neudirekt.tpl @@ -11,7 +11,7 @@ [ERROR] - +
{|Dateien hier einfügen|}
@@ -333,8 +333,8 @@ $(document).ready(function() { } } - $('#trdatei').before('Datei '+vorschau+''+filenameEncoded+'Titel: '); - }; + $('#trdatei').before(' Datei '+vorschau+' '+filenameEncoded+' Titel: {|Beschreibung|}: '); + }; })(files[index]); fileReader.readAsDataURL(file); From f95918647a37595203d7ed3fc78119f28003a7bf Mon Sep 17 00:00:00 2001 From: OpenXE <> Date: Thu, 13 Jun 2024 15:51:30 +0200 Subject: [PATCH 22/87] 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 23/87] 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 24/87] 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 25/87] 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 26/87] 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 27/87] 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 28/87] 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 29/87] 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 30/87] 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: