Zum Inhalt springen

Benutzung und Konfiguration (Codebasis: wunschtorte.ch): Unterschied zwischen den Versionen

Aus Computech CMS Wiki
Stefan.thalmann (Diskussion | Beiträge)
Stefan.thalmann (Diskussion | Beiträge)
Keine Bearbeitungszusammenfassung
 
(150 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt)
Zeile 1: Zeile 1:
== Zusätzliche Module, die benötigt werden ==
* zeberliedvcommercecart - Steuert die Darstellung des Commerce Carts
* commerce_cart_expiration - Löscht Warenkörbe, die älter sind als angegeben, wenn der Cronjob gestartet wird
== Grundsätzlicher Ablauf beim Erstellen neuer Produkte ==
== Grundsätzlicher Ablauf beim Erstellen neuer Produkte ==
# Produktarten erfassen
# Produktarten erfassen
# Produkte erfassen
# Produkte erfassen
# Produktedarstellung (Node) mit Referenz auf das Produkt erstellen
# Produktedarstellung (Node) mit Referenz auf das Produkt erstellen
  Hinweis zu Schritt 3: Die dafür nötigen manuellen Arbeitschritte können mit Hilfe des Moduls "Auto Product Display" (commerce_apd) automatisiert werden (so umgesetzt bei wunschtorte.ch)


== Produktarten erfassen (mit Workflow) ==
== Produktearten erfassen (mit Unterstützung des Workflows) ==
: [[Datei:04_Warenkorb.jpg|mini|100px|Nach Nummerierung sortierter Warenkorb]]
Sämtliche Produktarten enthalten folgende Felder:
* Produkt-Artikelnummer (Systemvorgabe)
* Titel (Systemvorgabe)
* Produktabbildung (Typ: Bild)
* Produktbeschreibung (Typ: Langer Text)
* Preis (Typ: Preis)
* Status (Systemvorgabe)
* Nummerierung der Tortenschit für Sortierung im Warenkorb (Typ: Ganzzahl)
 
Das Feld "Nummerierung der Tortenschicht" ist notwendig, um die Darstellung (Sortierung) der einzelnen Tortenelemente im Warenkorb und beim Checkout zu kontrollieren. Bei der Erfassung von Produktarten ist bei diesem Feld ein Vorgabewert empfehlenswert. Pro Tortenschicht wurde im Fall wunschtorte.ch in 10er-Schritten nummeriert (Tortenform = 10, Tortenboden = 20, Bisquitboden = 30 usw.). Somit werden im Warenkorb die einzelnen Tortenschickten korrekt sortiert dargestellt (Tortenform als unterstes Element, gefolgt vom Tortenbode, Bisquitboden usw. bis hin zur Dekoration).
 
== Produkte erfassen (mit Unterstützung des Workflows) ==
* Der Systemname eines Produkts im Shop muss zwingend mit dem Linkname für die entsprechnede Produkteübersicht übereinstimmen.
* Der Systemname eines Produkts im Shop muss zwingend mit dem Linkname für die entsprechnede Produkteübersicht übereinstimmen.
: Grund: Für die Darstellung von einzelnen Produktgruppen wird jeweils eine separate View erfasst, auf die im Workflow anhand des Systemnamen des Produkts verwiesen wird.
: '''Grund''': Für die Darstellung von einzelnen Produktgruppen wird jeweils eine separate View erfasst, auf die im Workflow anhand des Systemnamen des Produkts verwiesen wird.
: <div class="tright" style="clear:none">[[Datei:02_views_uebersicht_bisquitboden.jpg|frame|left|Übersicht der Views(/admin/structure/views) mit der entsprechenden Ansicht zur Darstellung von verschiedenen "Bisquitboden" (Link: <span style="background:yellow">bisquitboden)</span>]]</div>
 
: <div class="tright" style="clear:none">[[Datei:01_produkteliste_korrekte_systemnamen.jpg|frame|left|Produktliste(admin/commerce/products/types) mit dem Produkt "Bisquitboden" (Systemname: <span style="background:yellow">bisquitboden</span>)]]</div>
* Der SKU (Artikelnummer) eines Produkt muss ein eineindeutiges Präfix für die Produktelinie zugewisen sein. In unserem Beispiel beginnen die SKUs aller Bisquitboden mit "bisq", jene der Tortenboden mit "bode" und jene für Dekorationen mit "deko" usw.
* Der SKU (Artikelnummer) eines Produkt muss ein eineindeutiges Präfix für die Produktelinie zugewisen sein.
: '''Gründe''': In den Produktübersichten (Views) werden die Produkte nach dem Präfix in der SKU gefiltert. Zudem wird der Präfix gebraucht, um im Workflow beim Hinzufügen von Produkten aus Produktdetailansichten heraus zum nächsten Menüpunkt zu springen.
: Grund: In den Produktübersichten (Views) werden die Produkte nach dem Präfix in der SKU gefiltert.
 
: [[Datei:03_eineindeutiges_präfix_sku.jpg|frame|left|Produkteübersicht mit SKU-Präfix <span style="background:yellow">bisq</span> für "Bisquitboden"]]
<div>
<ul style="clear:none;float:none;>
<li style="display: inline-block;">[[File:01_produkteliste_korrekte_systemnamen.jpg|thumb|400px|Produktliste(admin/commerce/products/types) mit dem Produkt "Bisquitboden" (Systemname: <span style="background:yellow">bisquitboden</span>]]</li>
<li style="display: inline-block;">[[File:02_views_uebersicht_bisquitboden.jpg|thumb|400px|Übersicht ViewsÜbersicht der Views(/admin/structure/views) mit der entsprechenden Ansicht zur Darstellung von verschiedenen "Bisquitboden" (Link: <span style="background:yellow">bisquitboden)</span>]]</li>
<li style="display: inline-block;">[[File:03_eineindeutiges_präfix_sku.jpg|thumb|400px|Produkteübersicht mit SKU-Präfix <span style="background:yellow">bisq</span> für unterschiedliche "Bisquitboden"]]</li>
</ul>
</div>
 
== Fixe Nodes (zur Unterstützung des Workflows) ==
Folgende beiden Nodenummern sind fix vergeben (als Teil des Workflows):
  node/15: "Teil der Torte bereits festgelegt"
  node/19: "Ihre Torte ist noch nicht fertig"
 
'''Grund''': Der Workflow unterstützt die Anzeige von Meldungen, die Teil des Bestellprozesses sind. Dazu gehört die Meldung, dass die Torte noch nicht fertiggestellt ist, wenn noch nicht alle notwendigen Tortenelemente dem Warenkorb zugefügt wurden. Andererseits muss beim Klicken auf ein bereits bestelltes Tortenelement die Meldung erscheinen, dass dieser Teil der Torte bereits hinzugefügt wurde und nicht nochmals bestellt werden kann. Die Angaben zu diesen beiden Nodes sind zur Zeit des Abfassung dieses Textes innerhalb des template.php fix implementiert. Ändern sich die Node-Nummern, müssen diese Änderungen also auch im template.php vorgenommen werden.
 
== Produktedarstellung (Node) mit Referenz auf das Produkt erstellen ==
Wie bereits oben erwähnt, können diese Schritte automatisiert werden.
Wenn Produkteansichten manuell erstellt werden, dann muss wie folgt vorgegangen werden:
:* Ein Inhaltstyp muss erstellt werden, der die Produktdarstellung übernehmen kann (in unserem Fall lautet der Name des Inhaltstyps "Tortenelement").
:* Dieser Inhaltsyp enthält neben den Standardfeldern ein zusätzliches Feld vom Typ "Produktreferenz".
::ACHTUNG: Bei der Felddefinition müssen die verfügbaren Produktegruppen, welche zur Verfügung stehen sollen, angewählt werden (in unserem Fall sind das alle Warengruppen).
 
<div>
<ul style="clear:none;float:none;>
<li style="display: inline-block;">[[File:08_content-type_felder.jpg|thumb|400px|Liste der Felder des Inhalttyps Tortenelemente(admin/structure/types/manage/tortenelemente/fields)]]</li>
<li style="display: inline-block;">[[File:09_warengruppen.jpg|thumb|400px|Verfügbare Warengruppen innerhalb der Einstellungen für die Produktreferenz]]</li>
</ul>
</div>
 
== Programmcode Workflow (in template.php) ==
 
Dieser Abschnitt enthält den Code, welcher innerhalb der Datei /sites/all/themes/template.php enthalten sein muss.
 
<div class="toccolours mw-collapsible mw-collapsed" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
Programm-Code "template.php", Stand: 02.05.2017
<div class="mw-collapsible-content">
<syntaxhighlight lang="php">
<?php
/**
* @file
* Integrates a Menu-Workflow with drupal commerce
*
* @see template_preprocess_page()
*
* @ingroup themeable
*/
 
/**
* Sets the Session-Menu to a superfish-slot
*/
function wunschtorte_preprocess_page(&$vars) {
    $menu_name=initMenu();
    menu_load($menu_name);
    $session_menu = menu_tree_output(menu_tree_all_data($menu_name));
    $block = block_load('superfish', 2);
    variable_set('superfish_menu_2', $menu_name);   
    $vars['page']['navigation']['superfish_2']['#contextual_links']['superfish'][1][0]=$menu_name;
    $vars['page']['navigation']['superfish_2']['#markup']=render(_block_get_renderable_array(_block_render_blocks(array($block))));
}
 
/**
* One-time Initialization to populate menu-items
* to the session menu.
*
* @param array $links
*  the array holding all links
* @param string $menu_name
*  the name of the menu to populate
* @param int $plid=0
*  the parent link id (mlid - menu link id - of the parent)
*/
 
//Global functions
if (!function_exists('populate_menu')) {
    function populate_menu($links, $menu_name, $plid = 0) {
      foreach ($links as $link) {
         
        $ls = array();
         
        $arr_menulinks=menu_load_links($menu_name);
        foreach ($arr_menulinks as $menu_link) {
            if ($link['link_title']===$menu_link['link_title'])  {
                menu_link_delete($menu_link['mlid']);
            }
            if ($menu_link['weight']>0) {
                $ls['weight'] = $link['weight'];
            }
        }
        $ls['menu_name'] = $menu_name;
        $ls['link_title'] = $link['link_title'];
        $ls['link_path'] = $link['link_path'];
        $ls['weight'] = $link['weight'];
        $ls['plid'] = $plid;
       
        //$ls['weight'] = $link['weight'];
        $ls['options']['attributes']['class'] = $link['class'];
 
        $newpid = menu_link_save($ls);
        if (!empty($link['childs'])) {
          populate_menu($link['childs'], $menu_name, $newpid);
        }
      }
    }
}
 
/**
* Returns an array containing the next step and
* the minimum quantity of Elements needed
* defined in the workflow.
*
* One-time Initialization of the function
*
* @param string $nextStep
*  the string holding the next step
* @param string $element
*  the name of the current element
* @param int $must_have_quantity=1
*  the minimum quantity for this element
*/
if (!function_exists('must_have_line_items')) {
    function must_have_line_items($nextStep, $element, $must_have_quantity=1) {
        $itemsInCart=evalItemsInCart();
     
        if ($itemsInCart[$element]) {
           
            $quantity=$itemsInCart[$element][0];
           
            if (intval($quantity) >= $must_have_quantity) {
                $result=getNextMenuLink($element,$nextStep);
            }
            elseif (intval($quantity)===0) {
                $result=$nextStep;
            } else {
                $result=$element;
            }
        }
        return array('nextLink'=>$result,'mustHave'=>$must_have_quantity);
    }
}
 
/**
* Returns the next step (to create the correct url)
*
* @param string $currentStep
*  the string holding the current step
* @param string $nextStep
*  the name of the next step
*/
function getNextMenuLink($currentStep, $nextStep) {
    $menu_name=$_SESSION['menu_name'];
    $arr_menulinks=menu_load_links($menu_name);
    $saved_currentStep=$currentStep; 
    foreach ($arr_menulinks as $menu_link) {
        $currentStep=$saved_currentStep;
       
        if ($menu_link['link_path']=='node/15') {
            $currentStep='';
        }
 
        if (($menu_link['link_path']=='node/19') && ($currentStep)) {
            enableCheckout();
            global $user;
            $userid='/'.commerce_cart_order_id();
            return 'checkout'.$userid;
        } elseif (($menu_link['link_path']!=$nextStep) && (!$currentStep) && ($menu_link['link_path']!='node/15'))  {
            return $nextStep;
        } elseif ((!$currentStep) && ($menu_link['link_path']!='node/15')) {
            return $menu_link['link_path'];
        } elseif (($menu_link['link_path']!=$currentStep) && ($menu_link['link_path']!=$nextStep) && ($currentStep) && ($menu_link['link_path']!='node/15'))  {
           
            return $menu_link['link_path'];
        } elseif (($menu_link['link_path']!=$currentStep) && ($menu_link['link_path']==$nextStep) && ($currentStep) && ($menu_link['link_path']!='node/15'))  {
            return $nextStep;
        }
    }
}
 
/**
* Enables the Checkout-Menubutton
*/
function enableCheckout() {
    $menu_name=$_SESSION['menu_name'];
    $arr_menu_items=menu_load_links($menu_name);
    foreach ($arr_menu_items as $menu_item) {
        if ($menu_item['link_path']=='node/19') {
            $menu_item['options']['attributes']['class']='incart';
            $menu_item['link_path']='checkout';
            menu_link_save($menu_item);
        }
    }
}
 
/**
* Disables the Checkout-Menubutton
*/
function disableCheckout() {
    $items = array(
        array(
            'link_title' => 'Kasse',
            'link_path' => 'node/19',
            'childs' => '',
            'weight' => 0,
        ),
    );
 
    $menu_name = $_SESSION['menu_name'];
    if (menu_load($menu_name)) {
      populate_menu($items, $menu_name);
    }
}
 
/**
* Returns the current commerce cart
*/
function getCurrentCart() {
    global $user;
    return commerce_cart_order_load($user->uid);
}
 
/**
* Initializes the Session Menu (LIVE)
* by creating a copy of the Session Menu (Template)
*/
function initMenu() {
    // Create menu if it doesn't exist.
    // Copy Session Menu from Menu-Template "menu-session-menu-template"
    global $user;
    $menu_name = $_SESSION['menu_name'];
    if (!$menu_name) {
        drupal_session_start();
        //$client_session=md5($_SERVER['REMOTE_ADDR']);
        //$menu_name=substr($client_session,0,26);
        $menu_name='session-menu-live';
        $_SESSION['menu_name']=$menu_name;
    }
   
    if (!menu_load($menu_name)) {
        $items=menu_load_links('menu-session-menu-template');
        $menu = array(
            'menu_name' => $menu_name,
            'title' => 'Session Menü (LIVE)',
            'description' => 'Session Menu',
        );
        menu_save($menu);
        populate_menu($items, $menu_name);
    }
   
   
    $itemsInCart=evalItemsInCart();
   
   
    if ($itemsInCart) {
        repaintMenu();
    } else {
        resetMenu();
    }
    return $menu_name;
}
 
/**
* Resets the Session Menu
*/
function resetMenu() {
    $menu_name=$_SESSION['menu_name']; 
    $items=menu_load_links('menu-session-menu-template');
    populate_menu($items, $menu_name);
}
 
/**
* Repaints the Session Menu
*/
function repaintMenu() {
    resetMenu();
    $menu_name=$_SESSION['menu_name']; 
    $arr_mustHaveResult=array();
    $cart=getCurrentCart();
    $arr_menu_items=menu_load_links($menu_name);
    $itemsInCart=evalItemsInCart();
   
   
    foreach ($arr_menu_items as $menu_item) {
        $arr_mustHaveResult=checkCartMustHaves($menu_item['link_path']);
       
        if ($menu_item['link_path']!='node/19') {
            if ($menu_item['link_path']!='node/15') {
               
                if ($itemsInCart[$menu_item['link_path']][0]) {
                    if ($arr_mustHaveResult['mustHave']) {
                        if(
                            ($itemsInCart[$menu_item['link_path']][0]>=$arr_mustHaveResult['mustHave']) &&
                            ($itemsInCart[$menu_item['link_path']][0])
                            ) {
                            $menu_item['options']['attributes']['class']='incart';
                            $menu_item['link_path']='node/15';
                            menu_link_save($menu_item);
                        } elseif (
                            ($itemsInCart[$menu_item['link_path']][0]<$arr_mustHaveResult['mustHave'])&&
                            ($itemsInCart[$menu_item['link_path']][0])
                            ) {
                            $menu_item['options']['attributes']['class']='incart-more';
                            menu_link_save($menu_item);
                        } else {
                            $menu_item['options']['attributes']['class']='';
                            menu_link_save($menu_item);
                        }
 
                    }
                } else {
                    $menu_item['options']['attributes']['class']='';
                    menu_link_save($menu_item);
                }
            } else {
                $menu_item['options']['attributes']['class']='incart';
                menu_link_save($menu_item);
            }
        }
    }
}
 
/**
* Jumps to the next step in the workflow
*
* @param string $element
*  the current element
*/
function checkCartMustHaves($element='') {
    if ($element=='') {
        $element=arg(0);
    }
    if ($element=='node') {
        $nid=arg(1);
        $element=node_load($nid);
        $element=$element->field_tortenelement['und'][0]['product_id'];
        $element=commerce_product_load($element);
        $element=$element->type;
    }
 
    $cart=getCurrentCart();
    $rules_switchcase=loadWorkflow();
   
    foreach($rules_switchcase as $rule) {
       
        if ($rule[0]==$element) {
            //echo('<pre>');var_dump($rule[0].'=='.$element.' then '.$rule[2]);echo('</pre>');
            $result=must_have_line_items($rule[2],$element,$rule[3]);
        }
    }
    return $result;
}
 
/**
* Loads and returns the workflow rules defined
* in the description part of the Sessio Menu (Template)
*/
function loadWorkflow() {
    $menu=menu_load('menu-session-menu-template');
    $arr_switchcase=explode(chr(10),$menu['description']);
    $rules_switchcase=array();
    foreach ($arr_switchcase as $switchcase) {
        $switchcase=trim($switchcase);
        array_push($rules_switchcase,explode(',',$switchcase));
    }
    return $rules_switchcase;
}
 
/**
* Returns the number of commerce line items
* in the cart
*/
function evalItemsInCart() {
    $count_line_item = array();
    $cart=getCurrentCart();
    $line_items=$cart->commerce_line_items['und'];
   
    if ($line_items) {
        $li = array();
        foreach ($line_items as $item) {
            array_push($li,$item['line_item_id']);
        }
        $line_items=commerce_line_item_load_multiple($li);
 
        foreach ($line_items as $item) {
            $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $item);
            $order_wrapper = entity_metadata_wrapper('commerce_order', $cart); //$order
            $line_item_quantity = (float)$line_item_wrapper->quantity->value();
            //for views
            $key=$item->data['context']['view']['view_name'];
            if (!$key) { //if it is a node, not a view
                $key = $item->line_item_label;
                $rules_switchcase=loadWorkflow();
                foreach($rules_switchcase as $rule) {
                    if (strpos($key,$rule[1])===0) { 
                        //die(var_dump('$key='.$key.' / $rule[1]='.$rule[1]));
                        $key=$rule[0];
                    }
                }
            }
            $curr_count=$count_line_item[$key][0];
            $curr_count+=$line_item_quantity;
            $count_line_item[$key]=[$curr_count];
        }
    }
    return $count_line_item;
}
 
/**
* Calculates and returns the prices for an items in the
* cart by multiply it with the value of $price_factor
* defined in "tortenformen" (expect of "tortenformen"
* itself).
*
* @param array $row
*  the current row in the cart
*/
function calcViewPrice($row) {
    $product=commerce_product_load($row->commerce_price);
    if (isset($_SESSION['price_factor']['value'])) {
        $price_factor=$_SESSION['price_factor']['value'];
    }
    $itemsInCart=evalItemsInCart();
    if (!$itemsInCart['tortenformen']) {
        $price_factor=1;
    }
    return $product->commerce_price['und'][0]['amount']*doubleval($price_factor);
}
 
/**
* Returns the display for an items in the
* cart by formatting it as currency (CHF).
*
* @param array $row
*  the current row in the cart
*/
function showViewPrice($row) {
    return money_format('%i CHF',calcViewPrice($row)/100);
}
</syntaxhighlight>
</div>
</div>
 
== Rules ==
Dieser Abschnitt enthält die Exports der beiden Rules, welche für ein korrektes Funktioneren des Workflows nötig sind.
 
<div class="toccolours mw-collapsible mw-collapsed" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
Rule-Export für Preisberechnung, Stand: 02.05.2017
<div class="mw-collapsible-content">
<syntaxhighlight>
{ "rules_darstellung_berechneter_wert" : {
    "LABEL" : "wunschtorte.ch - Preis anhand Preisfaktor berechnen f\u00fcr Darstellung in Cart",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "9",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "menu_rules",
      "php",
      "rules",
      "commerce_product_reference",
      "commerce_cart"
    ],
    "ON" : {
      "commerce_product_calculate_sell_price" : [],
      "commerce_cart_product_add" : []
    },
    "IF" : [
      { "commerce_order_contains_product_type" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "product_type" : { "value" : { "tortenformen" : "tortenformen" } },
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "NOT menu_rules_node_has_menu_entry" : { "nid" : "tortenformen" } }
    ],
    "DO" : [
      { "php_eval" : { "code" : "$str_label=$commerce_line_item-\u003Eline_item_label;\r\n$product = commerce_product_load($commerce_line_item-\u003Ecommerce_product[\u0022und\u0022][0][\u0022product_id\u0022]);\r\n\r\nif (isset($_SESSION[\u0027price_factor\u0027][\u0027value\u0027])) {\r\n    $price_factor=$_SESSION[\u0027price_factor\u0027][\u0027value\u0027];\r\n}\r\n\r\nif ((strpos($str_label, \u0027form\u0027) !== false) )\r\n{\r\n    $price_factor=$product-\u003Efield_preis_faktor[\u0022und\u0022][0][\u0022value\u0022];\r\n    $_SESSION[\u0027price_factor\u0027][\u0027value\u0027]=$price_factor;\r\n\/\/echo(\u0027\u003Cpre\u003E\u0027);var_dump( $product);die(\u0027\u003C\/pre\u003E\u0027);\r\n    \/\/$product-\u003Ecommerce_price[\u0022und\u0022][0][\u0022amount\u0022]=$product-\u003Ecommerce_price[\u0022und\u0022][0][\u0022amount\u0022]*doubleval($price_factor);\r\n\r\n}\r\n\r\nif (strpos($str_label, \u0027form\u0027) === false)\r\n{\r\n  $commerce_line_item-\u003Ecommerce_unit_price[\u0022und\u0022][0][\u0022amount\u0022]=$commerce_line_item-\u003Ecommerce_unit_price[\u0022und\u0022][0][\u0022amount\u0022]*doubleval($price_factor);\r\n  $commerce_line_item-\u003Ecommerce_unit_price[\u0027und\u0027][0][\u0027data\u0027][\u0027components\u0027][0][\u0027price\u0027][\u0027amount\u0027]=$commerce_line_item-\u003Ecommerce_unit_price[\u0027und\u0027][0][\u0027data\u0027][\u0027components\u0027][0][\u0027price\u0027][\u0027amount\u0027]*doubleval($price_factor);\r\n}" } }
    ]
  }
}
</syntaxhighlight>
</div>
</div>
 
<div class="toccolours mw-collapsible mw-collapsed" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
Rule-Export für Workflow-Weiterleitungen, Stand: 02.05.2017
<div class="mw-collapsible-content">
<syntaxhighlight>
{ "rules_weiterleitung_in_cart" : {
    "LABEL" : "wunschtorte.ch - Weiterleitungen Workflow",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [
      { "redirect" : { "url" : "\u003C?php\r\n$result=checkCartMustHaves();\r\necho $result[\u0027nextLink\u0027];\r\n?\u003E" } }
    ]
  }
}
</syntaxhighlight>
</div>
</div>
 
<div class="toccolours mw-collapsible mw-collapsed" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
Rule-Export für Cart Expiration, Stand: 04.05.2017
<div class="mw-collapsible-content">
<syntaxhighlight>
{ "commerce_cart_expiration_delete_expired_carts" : {
    "LABEL" : "Delete expired carts",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart_expiration" ],
    "ON" : { "commerce_cart_expiration_cron" : [] },
    "DO" : [
      { "commerce_cart_expiration_delete_orders" : { "interval" : 172800, "limit" : "0" } }
    ]
  }
}
</syntaxhighlight>
</div>
</div>

Aktuelle Version vom 4. Mai 2017, 08:57 Uhr

Zusätzliche Module, die benötigt werden

  • zeberliedvcommercecart - Steuert die Darstellung des Commerce Carts
  • commerce_cart_expiration - Löscht Warenkörbe, die älter sind als angegeben, wenn der Cronjob gestartet wird

Grundsätzlicher Ablauf beim Erstellen neuer Produkte

  1. Produktarten erfassen
  2. Produkte erfassen
  3. Produktedarstellung (Node) mit Referenz auf das Produkt erstellen
 Hinweis zu Schritt 3: Die dafür nötigen manuellen Arbeitschritte können mit Hilfe des Moduls "Auto Product Display" (commerce_apd) automatisiert werden (so umgesetzt bei wunschtorte.ch)

Produktearten erfassen (mit Unterstützung des Workflows)

Fehler beim Erstellen des Vorschaubildes: Datei fehlt
Nach Nummerierung sortierter Warenkorb

Sämtliche Produktarten enthalten folgende Felder:

  • Produkt-Artikelnummer (Systemvorgabe)
  • Titel (Systemvorgabe)
  • Produktabbildung (Typ: Bild)
  • Produktbeschreibung (Typ: Langer Text)
  • Preis (Typ: Preis)
  • Status (Systemvorgabe)
  • Nummerierung der Tortenschit für Sortierung im Warenkorb (Typ: Ganzzahl)

Das Feld "Nummerierung der Tortenschicht" ist notwendig, um die Darstellung (Sortierung) der einzelnen Tortenelemente im Warenkorb und beim Checkout zu kontrollieren. Bei der Erfassung von Produktarten ist bei diesem Feld ein Vorgabewert empfehlenswert. Pro Tortenschicht wurde im Fall wunschtorte.ch in 10er-Schritten nummeriert (Tortenform = 10, Tortenboden = 20, Bisquitboden = 30 usw.). Somit werden im Warenkorb die einzelnen Tortenschickten korrekt sortiert dargestellt (Tortenform als unterstes Element, gefolgt vom Tortenbode, Bisquitboden usw. bis hin zur Dekoration).

Produkte erfassen (mit Unterstützung des Workflows)

  • Der Systemname eines Produkts im Shop muss zwingend mit dem Linkname für die entsprechnede Produkteübersicht übereinstimmen.
Grund: Für die Darstellung von einzelnen Produktgruppen wird jeweils eine separate View erfasst, auf die im Workflow anhand des Systemnamen des Produkts verwiesen wird.
  • Der SKU (Artikelnummer) eines Produkt muss ein eineindeutiges Präfix für die Produktelinie zugewisen sein. In unserem Beispiel beginnen die SKUs aller Bisquitboden mit "bisq", jene der Tortenboden mit "bode" und jene für Dekorationen mit "deko" usw.
Gründe: In den Produktübersichten (Views) werden die Produkte nach dem Präfix in der SKU gefiltert. Zudem wird der Präfix gebraucht, um im Workflow beim Hinzufügen von Produkten aus Produktdetailansichten heraus zum nächsten Menüpunkt zu springen.

Fixe Nodes (zur Unterstützung des Workflows)

Folgende beiden Nodenummern sind fix vergeben (als Teil des Workflows):

 node/15: "Teil der Torte bereits festgelegt"
 node/19: "Ihre Torte ist noch nicht fertig"

Grund: Der Workflow unterstützt die Anzeige von Meldungen, die Teil des Bestellprozesses sind. Dazu gehört die Meldung, dass die Torte noch nicht fertiggestellt ist, wenn noch nicht alle notwendigen Tortenelemente dem Warenkorb zugefügt wurden. Andererseits muss beim Klicken auf ein bereits bestelltes Tortenelement die Meldung erscheinen, dass dieser Teil der Torte bereits hinzugefügt wurde und nicht nochmals bestellt werden kann. Die Angaben zu diesen beiden Nodes sind zur Zeit des Abfassung dieses Textes innerhalb des template.php fix implementiert. Ändern sich die Node-Nummern, müssen diese Änderungen also auch im template.php vorgenommen werden.

Produktedarstellung (Node) mit Referenz auf das Produkt erstellen

Wie bereits oben erwähnt, können diese Schritte automatisiert werden. Wenn Produkteansichten manuell erstellt werden, dann muss wie folgt vorgegangen werden:

  • Ein Inhaltstyp muss erstellt werden, der die Produktdarstellung übernehmen kann (in unserem Fall lautet der Name des Inhaltstyps "Tortenelement").
  • Dieser Inhaltsyp enthält neben den Standardfeldern ein zusätzliches Feld vom Typ "Produktreferenz".
ACHTUNG: Bei der Felddefinition müssen die verfügbaren Produktegruppen, welche zur Verfügung stehen sollen, angewählt werden (in unserem Fall sind das alle Warengruppen).

Programmcode Workflow (in template.php)

Dieser Abschnitt enthält den Code, welcher innerhalb der Datei /sites/all/themes/template.php enthalten sein muss.

Programm-Code "template.php", Stand: 02.05.2017

<?php
/**
 * @file
 * Integrates a Menu-Workflow with drupal commerce
 *
 * @see template_preprocess_page()
 *
 * @ingroup themeable
 */

/**
 * Sets the Session-Menu to a superfish-slot
 */
function wunschtorte_preprocess_page(&$vars) { 
    $menu_name=initMenu();
    menu_load($menu_name);
    $session_menu = menu_tree_output(menu_tree_all_data($menu_name));
    $block = block_load('superfish', 2);
    variable_set('superfish_menu_2', $menu_name);    
    $vars['page']['navigation']['superfish_2']['#contextual_links']['superfish'][1][0]=$menu_name;
    $vars['page']['navigation']['superfish_2']['#markup']=render(_block_get_renderable_array(_block_render_blocks(array($block))));
}

/**
 * One-time Initialization to populate menu-items
 * to the session menu.
 *
 * @param array $links
 *   the array holding all links
 * @param string $menu_name
 *   the name of the menu to populate
 * @param int $plid=0
 *   the parent link id (mlid - menu link id - of the parent)
 */

//Global functions
if (!function_exists('populate_menu')) {
    function populate_menu($links, $menu_name, $plid = 0) {
      foreach ($links as $link) {
          
        $ls = array();
          
        $arr_menulinks=menu_load_links($menu_name);
        foreach ($arr_menulinks as $menu_link) {
            if ($link['link_title']===$menu_link['link_title'])  {
                menu_link_delete($menu_link['mlid']);
            }
            if ($menu_link['weight']>0) {
                $ls['weight'] = $link['weight'];
            }
        }
        $ls['menu_name'] = $menu_name;
        $ls['link_title'] = $link['link_title'];
        $ls['link_path'] = $link['link_path'];
        $ls['weight'] = $link['weight'];
        $ls['plid'] = $plid;
        
        //$ls['weight'] = $link['weight'];
        $ls['options']['attributes']['class'] = $link['class'];

        $newpid = menu_link_save($ls);
        if (!empty($link['childs'])) {
          populate_menu($link['childs'], $menu_name, $newpid);
        }
      }
    }
}

/**
 * Returns an array containing the next step and
 * the minimum quantity of Elements needed
 * defined in the workflow.
 *
 * One-time Initialization of the function
 *
 * @param string $nextStep
 *   the string holding the next step
 * @param string $element
 *   the name of the current element
 * @param int $must_have_quantity=1
 *   the minimum quantity for this element
 */
if (!function_exists('must_have_line_items')) {
    function must_have_line_items($nextStep, $element, $must_have_quantity=1) {
        $itemsInCart=evalItemsInCart();
       
        if ($itemsInCart[$element]) {
             
            $quantity=$itemsInCart[$element][0];
            
            if (intval($quantity) >= $must_have_quantity) {
                $result=getNextMenuLink($element,$nextStep);
            } 
            elseif (intval($quantity)===0) {
                $result=$nextStep;
            } else {
                $result=$element;
            }
        }
        return array('nextLink'=>$result,'mustHave'=>$must_have_quantity);
    }
}

/**
 * Returns the next step (to create the correct url)
 *
 * @param string $currentStep
 *   the string holding the current step
 * @param string $nextStep
 *   the name of the next step
 */
function getNextMenuLink($currentStep, $nextStep) {
    $menu_name=$_SESSION['menu_name'];
    $arr_menulinks=menu_load_links($menu_name);
    $saved_currentStep=$currentStep;  
    foreach ($arr_menulinks as $menu_link) {
        $currentStep=$saved_currentStep;
        
        if ($menu_link['link_path']=='node/15') {
            $currentStep='';
        }

        if (($menu_link['link_path']=='node/19') && ($currentStep)) {
            enableCheckout();
            global $user;
            $userid='/'.commerce_cart_order_id();
            return 'checkout'.$userid;
        } elseif (($menu_link['link_path']!=$nextStep) && (!$currentStep) && ($menu_link['link_path']!='node/15'))  {
            return $nextStep;
        } elseif ((!$currentStep) && ($menu_link['link_path']!='node/15')) {
            return $menu_link['link_path']; 
        } elseif (($menu_link['link_path']!=$currentStep) && ($menu_link['link_path']!=$nextStep) && ($currentStep) && ($menu_link['link_path']!='node/15'))  {
            
            return $menu_link['link_path'];
        } elseif (($menu_link['link_path']!=$currentStep) && ($menu_link['link_path']==$nextStep) && ($currentStep) && ($menu_link['link_path']!='node/15'))  {
            return $nextStep;
        }
    }
}

/**
 * Enables the Checkout-Menubutton
 */
function enableCheckout() {
    $menu_name=$_SESSION['menu_name'];
    $arr_menu_items=menu_load_links($menu_name);
    foreach ($arr_menu_items as $menu_item) {
        if ($menu_item['link_path']=='node/19') {
            $menu_item['options']['attributes']['class']='incart';
            $menu_item['link_path']='checkout';
            menu_link_save($menu_item);
        }
    } 
}

/**
 * Disables the Checkout-Menubutton
 */
function disableCheckout() {
    $items = array(
        array(
            'link_title' => 'Kasse',
            'link_path' => 'node/19',
            'childs' => '',
            'weight' => 0,
        ),
    );

    $menu_name = $_SESSION['menu_name'];
    if (menu_load($menu_name)) {
      populate_menu($items, $menu_name);
    }
}

/**
 * Returns the current commerce cart
 */
function getCurrentCart() {
    global $user;
    return commerce_cart_order_load($user->uid);
}

/**
 * Initializes the Session Menu (LIVE)
 * by creating a copy of the Session Menu (Template)
 */
function initMenu() {
    // Create menu if it doesn't exist.
    // Copy Session Menu from Menu-Template "menu-session-menu-template"
    global $user;
    $menu_name = $_SESSION['menu_name'];
    if (!$menu_name) {
        drupal_session_start();
        //$client_session=md5($_SERVER['REMOTE_ADDR']);
        //$menu_name=substr($client_session,0,26);
        $menu_name='session-menu-live';
        $_SESSION['menu_name']=$menu_name;
    }
    
    if (!menu_load($menu_name)) {
        $items=menu_load_links('menu-session-menu-template');
        $menu = array(
            'menu_name' => $menu_name,
            'title' => 'Session Menü (LIVE)',
            'description' => 'Session Menu',
        );
        menu_save($menu);
        populate_menu($items, $menu_name);
    } 
    
    
    $itemsInCart=evalItemsInCart();
    
    
    if ($itemsInCart) {
        repaintMenu();
    } else {
        resetMenu();
    }
    return $menu_name;
}

/**
 * Resets the Session Menu
 */
function resetMenu() {
    $menu_name=$_SESSION['menu_name'];   
    $items=menu_load_links('menu-session-menu-template');
    populate_menu($items, $menu_name);
}

/**
 * Repaints the Session Menu
 */
function repaintMenu() {
    resetMenu();
    $menu_name=$_SESSION['menu_name'];   
    $arr_mustHaveResult=array();
    $cart=getCurrentCart();
    $arr_menu_items=menu_load_links($menu_name);
    $itemsInCart=evalItemsInCart();
    
    
    foreach ($arr_menu_items as $menu_item) {
        $arr_mustHaveResult=checkCartMustHaves($menu_item['link_path']);
        
        if ($menu_item['link_path']!='node/19') {
            if ($menu_item['link_path']!='node/15') {
                
                if ($itemsInCart[$menu_item['link_path']][0]) {
                    if ($arr_mustHaveResult['mustHave']) {
                        if(
                            ($itemsInCart[$menu_item['link_path']][0]>=$arr_mustHaveResult['mustHave']) &&
                            ($itemsInCart[$menu_item['link_path']][0])
                            ) {
                            $menu_item['options']['attributes']['class']='incart';
                            $menu_item['link_path']='node/15';
                            menu_link_save($menu_item);
                        } elseif (
                            ($itemsInCart[$menu_item['link_path']][0]<$arr_mustHaveResult['mustHave'])&&
                            ($itemsInCart[$menu_item['link_path']][0])
                            ) {
                            $menu_item['options']['attributes']['class']='incart-more';
                            menu_link_save($menu_item);
                        } else {
                            $menu_item['options']['attributes']['class']='';
                            menu_link_save($menu_item);
                        }

                    }
                } else {
                    $menu_item['options']['attributes']['class']='';
                    menu_link_save($menu_item);
                }
            } else {
                $menu_item['options']['attributes']['class']='incart';
                menu_link_save($menu_item);
            }
        }
    }
}

/**
 * Jumps to the next step in the workflow
 *
 * @param string $element
 *   the current element
 */
function checkCartMustHaves($element='') {
    if ($element=='') {
        $element=arg(0);
    }
    if ($element=='node') {
        $nid=arg(1);
        $element=node_load($nid);
        $element=$element->field_tortenelement['und'][0]['product_id'];
        $element=commerce_product_load($element);
        $element=$element->type;
    }

    $cart=getCurrentCart();
    $rules_switchcase=loadWorkflow();
    
    foreach($rules_switchcase as $rule) {
        
        if ($rule[0]==$element) {
            //echo('<pre>');var_dump($rule[0].'=='.$element.' then '.$rule[2]);echo('</pre>');
            $result=must_have_line_items($rule[2],$element,$rule[3]);
        } 
    }
    return $result;
} 

/**
 * Loads and returns the workflow rules defined
 * in the description part of the Sessio Menu (Template)
 */
function loadWorkflow() {
    $menu=menu_load('menu-session-menu-template');
    $arr_switchcase=explode(chr(10),$menu['description']);
    $rules_switchcase=array();
    foreach ($arr_switchcase as $switchcase) {
        $switchcase=trim($switchcase);
        array_push($rules_switchcase,explode(',',$switchcase));
    }
    return $rules_switchcase;
}

/**
 * Returns the number of commerce line items
 * in the cart
 */
function evalItemsInCart() {
    $count_line_item = array();
    $cart=getCurrentCart();
    $line_items=$cart->commerce_line_items['und'];
    
    if ($line_items) {
        $li = array();
        foreach ($line_items as $item) {
            array_push($li,$item['line_item_id']);
        }
        $line_items=commerce_line_item_load_multiple($li);

        foreach ($line_items as $item) {
            $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $item);
            $order_wrapper = entity_metadata_wrapper('commerce_order', $cart); //$order
            $line_item_quantity = (float)$line_item_wrapper->quantity->value();
            //for views
            $key=$item->data['context']['view']['view_name'];
            if (!$key) { //if it is a node, not a view
                $key = $item->line_item_label;
                $rules_switchcase=loadWorkflow();
                foreach($rules_switchcase as $rule) {
                    if (strpos($key,$rule[1])===0) {  
                        //die(var_dump('$key='.$key.' / $rule[1]='.$rule[1]));
                        $key=$rule[0];
                    } 
                }
            }
            $curr_count=$count_line_item[$key][0];
            $curr_count+=$line_item_quantity;
            $count_line_item[$key]=[$curr_count];
        }
    }
    return $count_line_item;
}

/**
 * Calculates and returns the prices for an items in the
 * cart by multiply it with the value of $price_factor
 * defined in "tortenformen" (expect of "tortenformen"
 * itself).
 *
 * @param array $row
 *   the current row in the cart
 */
function calcViewPrice($row) {
    $product=commerce_product_load($row->commerce_price);
    if (isset($_SESSION['price_factor']['value'])) {
        $price_factor=$_SESSION['price_factor']['value'];
    }
    $itemsInCart=evalItemsInCart();
    if (!$itemsInCart['tortenformen']) {
        $price_factor=1;
    }
    return $product->commerce_price['und'][0]['amount']*doubleval($price_factor);
}

/**
 * Returns the display for an items in the
 * cart by formatting it as currency (CHF).
 *
 * @param array $row
 *   the current row in the cart
 */
function showViewPrice($row) {
    return money_format('%i CHF',calcViewPrice($row)/100);
}

Rules

Dieser Abschnitt enthält die Exports der beiden Rules, welche für ein korrektes Funktioneren des Workflows nötig sind.

Rule-Export für Preisberechnung, Stand: 02.05.2017

{ "rules_darstellung_berechneter_wert" : {
    "LABEL" : "wunschtorte.ch - Preis anhand Preisfaktor berechnen f\u00fcr Darstellung in Cart",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "9",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "menu_rules",
      "php",
      "rules",
      "commerce_product_reference",
      "commerce_cart"
    ],
    "ON" : {
      "commerce_product_calculate_sell_price" : [],
      "commerce_cart_product_add" : []
    },
    "IF" : [
      { "commerce_order_contains_product_type" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "product_type" : { "value" : { "tortenformen" : "tortenformen" } },
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "NOT menu_rules_node_has_menu_entry" : { "nid" : "tortenformen" } }
    ],
    "DO" : [
      { "php_eval" : { "code" : "$str_label=$commerce_line_item-\u003Eline_item_label;\r\n$product = commerce_product_load($commerce_line_item-\u003Ecommerce_product[\u0022und\u0022][0][\u0022product_id\u0022]);\r\n\r\nif (isset($_SESSION[\u0027price_factor\u0027][\u0027value\u0027])) {\r\n    $price_factor=$_SESSION[\u0027price_factor\u0027][\u0027value\u0027];\r\n}\r\n\r\nif ((strpos($str_label, \u0027form\u0027) !== false) )\r\n{\r\n    $price_factor=$product-\u003Efield_preis_faktor[\u0022und\u0022][0][\u0022value\u0022];\r\n    $_SESSION[\u0027price_factor\u0027][\u0027value\u0027]=$price_factor;\r\n\/\/echo(\u0027\u003Cpre\u003E\u0027);var_dump( $product);die(\u0027\u003C\/pre\u003E\u0027);\r\n    \/\/$product-\u003Ecommerce_price[\u0022und\u0022][0][\u0022amount\u0022]=$product-\u003Ecommerce_price[\u0022und\u0022][0][\u0022amount\u0022]*doubleval($price_factor);\r\n\r\n}\r\n\r\nif (strpos($str_label, \u0027form\u0027) === false)\r\n{\r\n   $commerce_line_item-\u003Ecommerce_unit_price[\u0022und\u0022][0][\u0022amount\u0022]=$commerce_line_item-\u003Ecommerce_unit_price[\u0022und\u0022][0][\u0022amount\u0022]*doubleval($price_factor);\r\n   $commerce_line_item-\u003Ecommerce_unit_price[\u0027und\u0027][0][\u0027data\u0027][\u0027components\u0027][0][\u0027price\u0027][\u0027amount\u0027]=$commerce_line_item-\u003Ecommerce_unit_price[\u0027und\u0027][0][\u0027data\u0027][\u0027components\u0027][0][\u0027price\u0027][\u0027amount\u0027]*doubleval($price_factor);\r\n}" } }
    ]
  }
}

Rule-Export für Workflow-Weiterleitungen, Stand: 02.05.2017

{ "rules_weiterleitung_in_cart" : {
    "LABEL" : "wunschtorte.ch - Weiterleitungen Workflow",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [
      { "redirect" : { "url" : "\u003C?php\r\n$result=checkCartMustHaves();\r\necho $result[\u0027nextLink\u0027];\r\n?\u003E" } }
    ]
  }
}

Rule-Export für Cart Expiration, Stand: 04.05.2017

{ "commerce_cart_expiration_delete_expired_carts" : {
    "LABEL" : "Delete expired carts",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart_expiration" ],
    "ON" : { "commerce_cart_expiration_cron" : [] },
    "DO" : [
      { "commerce_cart_expiration_delete_orders" : { "interval" : 172800, "limit" : "0" } }
    ]
  }
}