Skip to content

Instantly share code, notes, and snippets.

@voku

voku/Blf_Pim.php Secret

Created Aug 27, 2021
Embed
What would you like to do?
<?php
// dummy variables
$catalogArticles = [];
$lieferant = null;
$access_token = null;
$catalogConverter = null;
$logger = null;
foreach ($catalogArticles as $catalogArticle) {
if ($catalogConverter instanceof BlfCsvCatalogConverter) {
$logger->log('-------');
if (!$access_token && !$token_created) {
$logger->log("Fetching first Token!");
$access_token = Blf_Pim_Importer::getWebserviceToken();
$token_created = strtotime(date('Y-m-d H:i:s', time()));
$article_data = Blf_Pim_Importer::getWebserviceResponseBySupplierArticlenumber($logger, $catalogArticle->lieferant_artikelnummer, $access_token);
} else {
$article_data = Blf_Pim_Importer::getWebserviceResponseBySupplierArticlenumber($logger, $catalogArticle->lieferant_artikelnummer, $access_token);
}
$dateTimeNow = strtotime(date('Y-m-d H:i:s', time()));
$diff = $dateTimeNow - $token_created;
if ($diff >= 1800) { // 30 Minutes => Token is valid for 60 Minutes
$logger->log("Fetching new Token!");
$logger->log('Token Before: ' . $access_token);
$access_token = Blf_Pim_Importer::getWebserviceToken();
$token_created = strtotime(date('Y-m-d H:i:s', time()));
$logger->log('New Token: ' . $access_token);
} else {
$logger->log('Token Diff = ' . $diff . " von 1800 Sekunden");
}
if (!$article_data || !$article_data['values']) {
$logger->log('Could not Fetch PIM Data for Article: ' . $catalogArticle->lieferant_artikelnummer);
$logger->log(print_r($article_data, true));
continue;
}
$logger->log('Could Fetch PIM Data for Article: ' . $catalogArticle->lieferant_artikelnummer);
if (isset($article_data['values']['productimage_1_mam']['0']['data'])) {
$article_image = $article_data['values']['productimage_1_mam']['0']['data'];
} elseif (isset($article_data['values']['productimage_3_mam']['0']['data'])) {
$article_image = $article_data['values']['productimage_3_mam']['0']['data'];
} else {
$article_image = '';
}
$catalogArticle->catalog_bild_url = $article_image;
$logger->log('Set: ' . $article_image . ' as Article Image');
$article_specification = $article_data['values']['productpdf_1_mam']['0']['data'] ?? '';
$catalogArticle->catalog_document_url1 = $article_specification;
$logger->log('Set: ' . $article_specification . ' as Article Specification');
$catalogArticle->update();
foreach ($article_data['values'] as $identifier => $data) {
$unit = '';
if (is_array($data[0]['data'])) {
$value = array_first($data[0]['data']);
if (isset($data[0]['data']['unit'])) {
$unit = $data[0]['data']['unit'];
}
} elseif ($data[0]['data'] != '' && $data[0]['data'] != ' ') {
$value = $data[0]['data'];
} else {
continue;
}
// allergens
if ($value == 'Y') {
$value = 'x';
} elseif ($value == 'T') {
$value = 'spuren';
} elseif ($value == 'N') {
continue;
}
if (
$identifier == 'pim_allergens_gluten_type'
||
$identifier == 'pim_allergens_milk_type'
||
$identifier == 'pim_allergens_nuts_type'
) {
foreach ($data[0]['data'] as $extra_allergen) {
$identifier = $extra_allergen;
$value = 'x';
}
}
if ($value != '' || (float)$value != 0) {
$labelname = trim(Blf_Pim_Importer::getShowName($identifier));
$labelname = trim(substr($labelname, 0, 50));
if (!$labelname) {
// we cannot process label without a name
continue;
}
$valuetype = ArticleLabelSupplierValueTypeFactory::singleton()->fetchOneByLabelAndSupplierId(
$labelname,
$lieferant->lieferant_id
);
// the valuetype is missing for this supplier / label combination
//
// we cannot import label - backoffice should set labeltype (e.g. allergen, additive, etc.)
if (!$valuetype) {
$type = ArticleLabelSupplierValueTypeFactory::singleton()->fetchEmpty();
$type->lieferant_id = $lieferant->lieferant_id;
$type->label = $labelname;
$type->original_valuetype = 'text';
$type->status = 1;
$found = null;
if (
$unit != ''
&&
!is_numeric($unit)
) {
$einheitArray = LieferantEinheitFactory::singleton()->fetchByLieferantId($lieferant->lieferant_id);
$found = 0;
foreach ($einheitArray as $einheit) {
$einh = EinheitFactory::singleton()->fetchByIdIfExists($einheit->einheit_id);
if (
strtoupper($unit) == strtoupper($einheit->lieferant_einheit_name)
||
strtoupper($unit) == strtoupper($einh->name)
) {
$found = $einheit->einheit_id;
break;
}
}
}
$type->unit = $unit;
$type->einheit_id = $found;
$type->systemname = '';
$type->insert();
$logger->log(sprintf("Inserted new valuetype for label %s supplier %s", $labelname, $lieferant->lieferant_id));
}
$label = CatalogArticleLabelFactory::singleton()->fetchEmpty();
$label->catalogarticle_id = $catalogArticle->getId();
$label->systemname = '';
$label->idref = null;
$label->name = trim($labelname);
$label->description = '';
$label->unit = $unit;
$label->datatype = '';
$label->value = $value;
$label->status = (string)CatalogArticleConst::CATALOGARTICLE_LABEL_TYPE_OPEN;
$label->insert();
$logger->log('Created CatalogArticleLabel ID:' . $label->catalogarticlelabel_id);
}
}
}
}
// -----------------------
class Blf_Pim_Importer {
/**
* @param SystemLogger $logger
* @param string $lief_id
* @param string $access_token
*
* @return null|array
*/
public static function getWebserviceResponseBySupplierArticlenumber($logger, $lief_id, $access_token) {
$get_data_cmd = 'curl -s -X GET \
https://pim.blf-gruppe.de/api/rest/v1/products/' . $lief_id . ' \
-H \'Authorization: Bearer ' . $access_token . '\' \
-H \'Cache-Control: no-cache\' \
-d \'{
"code": "master",
"parent": null,
"labels": {
"en_US": "Master catalog modified",
"de_DE": "Hauptkatalog",
"fr_FR": "Catalogue principal"
}
}\'';
exec($get_data_cmd, $data_return);
$json_lmiv = json_decode($data_return[0], true);
// check "not found" Response
if (isset($json_lmiv['code']) && $json_lmiv['code'] == '404') {
$logger->log('Error:');
$logger->log(print_r($json_lmiv, true));
return null;
}
return $json_lmiv;
}
/**
* @return null|string
*/
public static function getWebserviceToken() {
$get_token_cmd = 'curl -s -X POST \
https://pim.blf-gruppe.de/api/oauth/v1/token \
-u \'dummy:dummy\' \
-H \'content-type: application/json\' \
-d \'{
"username" : "dummy",
"password" : "dummy",
"client_id" : "dummy",
"grant_type": "password"
}\'';
exec($get_token_cmd, $token_return);
$json_token = json_decode($token_return[0], true);
$access_token = $json_token['access_token'];
return $access_token;
}
/**
* @param string $property_name
*
* @return string
*/
public static function getShowName($property_name) {
$mapping_array = [
"pim_add_info_fish_breading" => "Angabe zur Panade",
"pim_add_info_fish_fishbones" => "Angabe zu Gräten",
"pim_add_info_fish_fishing_area" => "Fanggebiet(e)",
"pim_add_info_fish_fishing_type" => "Wildfang/ Aquakultur",
"pim_add_info_fish_glaze" => "Glasuranteil vorhanden",
"pim_add_info_fish_processing" => "Verarbeitung",
"pim_add_info_fish_seal" => "Qualitäts Siegel",
"pim_add_info_fish_skin" => "Angabe zur Haut",
"pim_add_info_fish_weight_fish_per_piece" => "Fischanteil pro Stück",
"pim_add_info_fish_weight_per_piece" => "Gewicht pro Stück",
"pim_add_info_meat_composed_pieces" => "aus Fleischstücken zusammengefügt",
"pim_add_info_meat_concern_gelatin" => "enthält Gelatine",
"pim_add_info_meat_concern_pieces" => "enthält z.T zerkleinertes Fleisch",
"pim_add_info_meat_place_birth" => "Geburtsort",
"pim_add_info_meat_place_rearing" => "Aufzuchtsort",
"pim_add_info_meat_place_segmentation" => "Zerlegungsort",
"pim_add_info_meat_place_slaughter" => "Schlachtort",
"pim_add_info_meat_weight_meat_per_piece" => "Fleischanteil in g",
"pim_additives_antioxidants" => "beinhaltet Antioxidationsmittel",
"pim_additives_antioxidants_type" => "Antioxidationsmittel Art(en)",
"pim_additives_carrageenan" => "Carrageen",
"pim_additives_declarable" => "beinhaltet deklarationspflichtige Zutaten/Zusatzstoffe",
"pim_additives_dye" => "beinhaltet Farbstoffe",
"pim_additives_dye_type" => "Farbstoff Art(en)",
"pim_additives_emulsifiers" => "Emulgatoren",
"pim_additives_flavor_enhancers" => "beinhaltet Geschmacksverstärker",
"pim_additives_flavor_enhancers_type" => "Geschmacksverstärker",
"pim_additives_flavorings" => "Aromastoffe",
"pim_additives_licorice_extract" => "enthält Süßholzextrakt (Glyzyrrhizinsäure oder deren Ammoniumsalz)",
"pim_additives_nitrates" => "beinhaltet Nitrite/ Nitrate",
"pim_additives_nitrates_type" => "Nitrit/ Nitrat Art(en)",
"pim_additives_preservatives" => "beinhaltet Konservierungsstoffe",
"pim_additives_preservatives_type" => "Konservierungsstoff Art(en)",
"pim_additives_stabilizer" => "Verdickungsmittel/ Stabilisatoren",
"pim_additives_reaction_alcohol" => "enthält Alkohol",
"pim_additives_reaction_alcohol_similar" => "enthält alkoholähnliche Stoffe",
"pim_additives_reaction_caffeine" => "koffeinhaltig",
"pim_additives_reaction_effects_on_children" => "kann bei Kindern Aufmersamkeit beeinträchtigen",
"pim_additives_reaction_laxatives_type" => "abführende Wirkung Art(en)",
"pim_additives_reaction_quinine" => "chininhaltig",
"pim_additives_reaction_taurine" => "taurinhaltig",
"pim_additives_sweeteners" => "beinhaltet Süßungsmittel",
"pim_additives_sweeteners_laxatives" => "Produkt kann bei übermäßigem Verzehr abführend wirken",
"pim_additives_sweeteners_phenylalanines" => "Produkt enthält eine Phenylalaninquelle",
"pim_additives_sweeteners_phenylalanines_type" => "Phenylalaninquelle Art(en)",
"pim_additives_sweeteners_type" => "Süßungsmittel Art(en)",
"pim_additives_treatment_barks" => "Rinde (Überzug zum Verzehr geeignet)",
"pim_additives_treatment_blackened" => "Produkt wird geschwärzt",
"pim_additives_treatment_blackened_type" => "Geschwärzt Art(en)",
"pim_additives_treatment_iodized_salt" => "Jodsalz",
"pim_additives_treatment_phosphates" => "beinhaltet Phosphate",
"pim_additives_treatment_phosphates_type" => "Phosphat Art(en)",
"pim_additives_treatment_salt_nitrate" => "Pökelsalz mit Nitrat",
"pim_additives_treatment_salt_nitrite" => "Pökelsalz mit Nitrit",
"pim_additives_treatment_sulphuretted" => "Produkt wird geschwefelt",
"pim_additives_treatment_sulphuretted_type" => "Geschwefelt Art(en)",
"pim_additives_treatment_waxed" => "Produkt wird gewachst",
"pim_additives_treatment_waxed_type" => "Gewachst Art(en)",
"pim_allergens" => "Allergene",
"pim_allergens_celery" => "Sellerie",
"pim_allergens_crustaceans" => "Krusten-/ Schalentiere",
"pim_allergens_eggs" => "Eier",
"pim_allergens_fish" => "Fisch",
"pim_allergens_gluten" => "Getreide/ Gluten",
"pim_allergens_lupines" => "Lupinen",
"pim_allergens_milk" => "Milch",
"pim_allergens_molluscs" => "Weichtiere",
"pim_allergens_mustard" => "Senf",
"pim_allergens_nuts" => "Nüsse/ Schalenfrüchte",
"pim_allergens_peanuts" => "Erdnüsse",
"pim_allergens_sesame" => "Sesam",
"pim_allergens_soy" => "Soja",
"pim_allergens_sulphites" => "Sulfite/ Sulfate",
"pim_allergens_type" => "Allergene Kennungen",
"pim_nutrients_common_salt" => "Kochsalz auf 100 g / 100 ml",
"pim_nutrients_fat_composition_acids_linoleic" => "davon Linolsäure (Omega-6-Fettsäure) mg",
"pim_nutrients_fat_composition_acids_linolenic" => "davon Linolensäure (Omega-3-Fettsäure) mg",
"pim_nutrients_fat_composition_acids_monounsaturated" => "einfach ungesättigte Fettsäuren g",
"pim_nutrients_fat_composition_acids_polyunsaturated" => "mehrfach ungesättigte Fettsäure g",
"pim_nutrients_fat_composition_cholesterol" => "Cholesterin mg",
"pim_nutrients_fat_composition_hydrogenated_fats" => "gehärtete Fette",
"pim_nutrients_trace_elements_calcium" => "Calcium mg",
"pim_nutrients_trace_elements_chloride" => "Chlorid mg",
"pim_nutrients_trace_elements_copper" => "Kupfer µg",
"pim_nutrients_trace_elements_fluoride" => "Fluorid µg",
"pim_nutrients_trace_elements_iodide" => "Jodid µg",
"pim_nutrients_trace_elements_iron" => "Eisen µg",
"pim_nutrients_trace_elements_magnesium" => "Magnesium mg",
"pim_nutrients_trace_elements_manganese" => "Mangan µg",
"pim_nutrients_trace_elements_phosphorus" => "Phosphor mg",
"pim_nutrients_trace_elements_potassium" => "Kalium mg",
"pim_nutrients_trace_elements_purines" => "Purine mg",
"pim_nutrients_trace_elements_roughage" => "Ballaststoffe g",
"pim_nutrients_trace_elements_sodium" => "Natrium mg",
"pim_nutrients_trace_elements_sulfur" => "Schwefel mg",
"pim_nutrients_trace_elements_uric_acid" => "Harnsäure mg",
"pim_nutrients_trace_elements_zinc" => "Zink µg",
"pim_nutrients_trace_vitamins_a" => "Vitamin A µg",
"pim_nutrients_trace_vitamins_b1" => "Vitamin B1 Thiamin µg",
"pim_nutrients_trace_vitamins_b12" => "Vitamin B12 µg",
"pim_nutrients_trace_vitamins_b2" => "Vitamin B2 Riboflavin µg",
"pim_nutrients_trace_vitamins_b3" => "Vitamin B3 Niacin µg",
"pim_nutrients_trace_vitamins_b5" => "Vitamin B5 Pantothensäure µg",
"pim_nutrients_trace_vitamins_b6" => "Vitamin B6 µg",
"pim_nutrients_trace_vitamins_biotin" => "Biotin µg",
"pim_nutrients_trace_vitamins_c" => "Vitamin C Ascorbinsäure µg",
"pim_nutrients_trace_vitamins_d" => "Vitamin D µg",
"pim_nutrients_trace_vitamins_e" => "Vitamin E µg",
"pim_nutrients_trace_vitamins_folate" => "Folsäure µg",
"pim_nutrients_trace_vitamins_k" => "Vitamin K µg",
"pim_name_alpha_register" => "Artikel-Bezeichnung im Alpharegister",
"pim_source_data" => "Quelle der Daten",
"reg_brand" => "Marke",
"reg_duration_consumption" => "Mindest Verbrauchszeit",
"reg_duration_min_shelf_life" => "MHD",
"reg_duration_preorder" => "Vorbestellung",
"reg_manufacturer" => "Hersteller",
"reg_name_01" => "Produkt Bezeichnung 01",
"reg_name_02" => "Produkt Bezeichnung 02",
"reg_name_03" => "Produkt Bezeichnung 03",
"reg_package_divide_allowed" => "Anbruch erlaubt",
"reg_product_blocked" => "Artikel gesperrt",
"reg_unit_sale" => "Handelseinheit",
"sku" => "Artikel Nr.",
"reg_product_prices_validity" => "Artikel vom Preistyp",
"reg_product_prices_vat_rate" => "Mehrwertsteuer",
"pim_suitable_for_preparation" => "Produkt eignet sich zur Zubereitung mit/ im",
"pim_allergens_eggs_type" => "Eier Haltungsform",
"pim_allergens_gluten_type" => "Getreide/ Gluten Art(en)",
"pim_allergens_milk_type" => "Milch Art(en)",
"pim_allergens_nuts_type" => "Nüsse/ Schalenfrüchte Art(en)",
"pim_country_origin" => "Ursprungsland",
"pim_country_manufacture" => "Herstellungsland",
"reg_sku_como" => "Como Nr.",
"pim_additives_reaction_dye_azo" => "AZO Farbstoff",
"pim_additives_treatment_protective_atmosphere" => "Schutzatmosphäre",
"pim_editing_remark_date_specification" => "Datum Spezifikation laut Hersteller",
"pim_editing_remark_date_audit" => "Datum Spezifikation eingepflegt am",
"pim_editing_remark_date_audit_next" => "Datum nächste Spezifikationsprüfung am",
"pim_additives_glutamate_yeast" => "Ersatzstoffe (?)",
"reg_unit_price" => "Preiseinheit",
"pim_nutrients_protein" => "Eiweiß auf 100 g / 100 ml",
"pim_nutrients_fat" => "Fett auf 100 g / 100 ml",
"pim_nutrients_carb" => "Kohlenhydrate auf 100 g / 100 ml",
"pim_nutrients_carb_sugar" => "Kohlehydrate, davon gesamt Zucker auf 100 g / 100 ml",
"pim_nutrients_fatty_acid_saturated" => "gesättigte Fettsäure auf 100 g / 100 ml",
"reg_unit_basic" => "Basiseinheit",
"pim_editing_remark_specification_editor" => "Herausgeber der Spezifikation",
"pim_additives_sweeteners_sugar" => "beinhaltet Zuckerart(en) und Süßungsmittel",
"pim_additives_sweeteners_sugar_type" => "Zucker & Süßungsmittel Art(en)",
"pim_product_ingredients_list_description" => "Zutaten",
"pim_name_trade_official" => "Verkehrsbezeichnung",
"pim_suitable_for_preparation_cook_chill" => "Cook-Chill geeignet",
"pim_nutritional_aspects_certificate_gmo_free" => "GVO-frei",
"pim_nutritional_aspects_certificate" => "nach Zertifikaten",
"pim_nutritional_aspects_rel" => "nach religiösen Aspekten",
"pim_nutritional_aspects_suitable" => "geeignet für spezielle Kostform",
"pim_nutritional_aspects_reduced" => "reduziert an",
"pim_nutritional_aspects_nutrition" => "nach Ernährungs Aspekten",
"pim_suitable_for_preparation_convenience_level" => "Convenience Grad",
"pim_nutritional_aspects_free" => "frei von",
"reg_product_packaging_contents_text" => "Inhalt",
"pim_product_is_regional" => "regionaler Artikel",
"reg_name_short" => "regulus Kurzbezeichnung",
"pim_add_info_fish_exact_description" => "Genaue Bezeichnung",
"pim_add_info_meat_concern" => "Produkt enthält",
"pim_nutrients_kcal" => "kcal auf 100 g / 100 ml",
"pim_nutrients_kj" => "kj auf 100 g / 100 ml",
"reg_product_prices_rail_01" => "Preisschiene 1",
"reg_product_prices_rail_02" => "Preisschiene 2",
"reg_product_prices_rail_03" => "Preisschiene 3",
"reg_product_prices_rail_04" => "Preisschiene 4",
"reg_product_prices_rail_05" => "Preisschiene 5",
"reg_product_prices_rail_06" => "Preisschiene 6",
"reg_product_prices_rail_07" => "Preisschiene 7 (KD 110093, Aktion)",
"reg_product_prices_rail_08" => "Preisschiene 8 (GHL)",
"reg_product_prices_price" => "Preis",
"reg_product_prices_rail_promotion" => "Werbepreisschiene",
"reg_supplier" => "Lieferant",
"reg_supplier_product_id" => "Lieferanten Artikel Nr.",
"productimage_1" => "Einzelbild",
"productimage_2" => "Displaykarton",
"productimage_3" => "Foodmotiv",
"productimage_4" => "Serviervorschlag",
"reg_identifier_ean" => "GTIN",
"sku_range" => "Artikelnummer Sortiment",
"pim_weight_g_ml" => "Gewicht in g/ml",
"pim_number_portions" => "Anzahl Portionen",
"pim_portion_weight_g_ml" => "Portionsgewicht g/ml",
"pim_additives_declarable_yn" => "Deklarationspflichtige Zutaten/Zusatzstoffe",
"pim_bls_key" => "BLS Schlüssel",
"pim_marketing_article_name_01" => "Marketing-Artikelbezeichnung 1",
"pim_marketing_article_name_02" => "Marketing-Artikelbezeichnung 2",
"pim_marketing_article_description" => "Marketing-Artikelbeschreibung",
"spezificationimages_1" => "Artikelspezifikation",
"productimages_status" => "vorhandene Produktbilder",
"pim_product_packaging_contents_text2" => "Inhalt 2",
"pim_special_product_characteristics" => "Besondere Produkteigenschaften",
"regulus_angelegt" => "Angelegt am",
"regulus_geaendert" => "Geändert am",
"pim_product_prices_piece_07" => "Preisschiene 7 (Stückpreis)",
"pim_product_prices_top_07" => "Preisschiene 7 (Top-Preis)",
"pim_product_is_msc" => "MSC Artikel",
"reg_category_products_1" => "Hauptwarengruppe (1. Ebene)",
"reg_category_products_2" => "Unterwarengruppe (2. Ebene)",
"reg_category_products_3" => "Unterwarengruppe (3. Ebene)",
"symcode_test_attribute" => "null",
"pagenumber" => "Seitenzahl im Katalog (nummerisch)",
"sequence" => "Reihenfolge in Preisliste",
"pagenumber_str" => "Seitenzahl im Katalog",
"pim_marketing_article_description_long" => "Marketing-Artikelbeschreibung-Langtext",
"Wz" => "Weizen",
"Ro" => "Roggen",
"Ge" => "Gerste",
"Hf" => "Hafer",
"Di" => "Dinkel",
"Gk" => "Grünkern",
"Ek" => "Einkorn",
"Em" => "Emmer",
"Kt" => "Kamut",
"Tr" => "Triticale",
"1" => "Kuhmilch",
"2" => "Ziegenmilch",
"3" => "Schafsmilch",
"custom_1" => "Laktose",
"custom_2" => "Milcheiweiß",
"Hs" => "Haselnuss",
"Man" => "Mandeln",
"Wa" => "Walnüsse",
"Pa" => "Paranüsse",
"Pe" => "Pekannüsse",
"Pi" => "Pistazien",
"Ka" => "Kaschunüsse",
"Mak" => "Makadamianüsse",
];
if (isset($mapping_array[$property_name])) {
return $mapping_array[$property_name];
}
return $property_name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment