WebsiteBaker Community Forum

WebsiteBaker Support (2.8.x) => Bakery Shop => Topic started by: gearup on September 19, 2012, 11:25:57 AM

Title: Include a product by default with each order[solved]
Post by: gearup on September 19, 2012, 11:25:57 AM
Hi,

Right now there is a need to add an "Order Processing Fee" as a flat charge to each order.

My idea is to add a product with this title and mark it inactive so it is not displayed to the customer.

Alternatively it could be Active but not displayed perhaps by controlling it by its ID in Page Settings, Product Loop.

Then with the "Add to Cart" action on any other product it is added by default (if not already added) and this would be hard coded maybe in add_item.php but I am not sure how to do this.

Also it would need controlling in the Cart so the quantity could not be modified.

Bakery version in use is 1.60 with WB 2.8.3 SP1.

Anyone any ideas?

Regards,

Title: Re: Include a product by default with each order
Post by: hillschmidt on September 20, 2012, 09:52:29 AM
There is this option under "Shipping": "a flat Amount" - see here a screenshot from my German bakery:

Isn't this the option you'll need?
Title: Re: Include a product by default with each order
Post by: gearup on September 20, 2012, 06:54:28 PM
hi Hillschmidt,

thanks for your input. I was aware of this option and know how it works but unfortunately it is not what I have been asked to do.

For marketing reasons shipping needs to be shown as Free (0.00).

The charge that is wanted to be added is for services provided by a 3rd party.

The bean counter guy has said he wants this to be separate from shipping.

As I was not sure what to do I moved this down (off) my list :|

Now they want the website to go live next week and I am a bit stuck :(

It was suggested that later they may give free items with each order so I thought to add this "Order processing fee" as a product would allow me to sort of kill two birds with one stone and gain the experience for the change they would later need.


What I think I need is to find what to add to the php when someone presses "add to cart" so that the product I have already added and know the ID for is included in the Add method.

Of course it needs only adding once but that can be a secondary task.

Regards,
Title: Re: Include a product by default with each order
Post by: hillschmidt on September 21, 2012, 08:34:15 AM
If Shipping is ALWAYS free, you could consider to do the following:
- insert in the templates for order card, invoice, etc. a static text: Shipping cost 0 US$ in the same format as the rest,
- change the language file(s) of the original Shipping field from "Shipping" to "Order processing fee"
and you're close to I suggest.
This way should easily be implemented, and the processing of this fee will automatically work in the whole bakery processing like a shipping fee.

This will not solve your problem on how to include one (or more) items AUTOMATICALLY to each order ... here I suggest that the developer should consider this as an future enhancement 'cause it seems a very good feature ...
The article options could be expanded by additional fields "include in each order", "quantity", "order limit for processing/including" - but of course this will require a lot of changes in all scripts needed during the processing.
Title: Re: Include a product by default with each order
Post by: gearup on September 22, 2012, 08:57:56 PM
Hi hillschmidt,

thanks for your input.

I had considered modifying the shipping text as you suggested but decided against it. Yes shipping will always be free except when my boss decides it is no longer free. So for me I will leave shipping untouched.

However, I have had some success and have a better idea what area needs changing but I don't have it working properly yet.

I made some changes to Bakery files;

view.php (line 230 - $item_id = 39;)
I hard coded the id for the fixed charge item and it gets added to the cart OK
Code: [Select]
if (substr($field,0,4) == "item" && $value > 0) {
// Get item_id
//$item_id = substr($field,4,strlen($field)-4);
$item_id = 39;
// Get item attributes and make comma separated string
if (isset($_POST['attribute'][0])) {
$attributes = implode(",", $_POST['attribute']);
} else {
                              ....

Now I can see this will work I will need to undo this and add code to an earlier place in view.php where the order_id is created so that I can do a run once operation to add my fixed charge product item.

I have had a couple of goes at this but so far been unable to get it to work.

The other change I wanted to make was to make the field for quantity displayed in the Cart be read only for this item.

so in \templates\cart\table_body.htm
I modified the code as shown below (my changes are the added php).
It did not quite work but at least I did get a second read only column for quantity (cart image is attached)

maybe someone can suggest why my 'if' clause is not working

Code: [Select]
<tr>
<td class="mod_bakery_cart_td_thumb_f"><a href="{LINK}"><img src="{THUMB_URL}" alt="{NAME}" width="{THUMB_WIDTH}" height="{THUMB_HEIGHT}" border="0" /></a></td>
<td class="mod_bakery_cart_td_sku_f">{SKU}</td>
<td class="mod_bakery_cart_td_name_f"><span class="mod_bakery_cart_item_f">{NAME}</span><br />{ATTRIBUTE}</td>
<td class="mod_bakery_cart_td_quantity_f">
<?php $id "{ITEM_ID}";
if $id != "39"): ?>

<input type="text" name="quantity[{ITEM_ID}][{ATTRIBUTES}]" value="{QUANTITY}" id="id_{ITEM_ID}_{ATTRIBUTES}" style="text-align: right" size="4" />
<?php else: ?>
<input type="text" name="quantity[{ITEM_ID}][{ATTRIBUTES}]" readonly="readonly" value="{QUANTITY}" id="id_{ITEM_ID}_{ATTRIBUTES}" style="text-align: right" size="4" />
<?php endif; ?>
<a href="#" onclick="javascript: mod_bakery_delete_item_f('{ITEM_ID}_{ATTRIBUTES}');"> <img src="{WB_URL}/modules/bakery/images/delete.gif" alt="{TEXT_DELETE}" title="{TEXT_DELETE}" /></a></td>
<td class="mod_bakery_cart_td_price_f">{PRICE}</td>
    ....

Here is the current Cart display,


Title: Re: Include a product by default with each order
Post by: jacobi22 on September 23, 2012, 02:23:57 AM
Quote
maybe someone can suggest why my 'if' clause is not working

its a htm-file (not PHP)   :wink:

set your 'if' clause in view_cart.php. build a new variable (line 247ff)

like this

Orignal Code view_cart / line 246
Code: [Select]
// Show cart table body using template file
        $tpl->set_file('cart_table_body', 'table_body.htm');
        $tpl->set_var(array(
                'THUMB_URL'                        =>        $items[$i]['thumb_url'],
                'THUMB_WIDTH'                =>        $items[$i]['thumb_width'],
                'THUMB_HEIGHT'                =>        $items[$i]['thumb_height'],
                'LINK'                                =>        $items[$i]['link'],
                'FIELD_1'                        =>        $items[$i]['definable_field_0'],
                'FIELD_2'                        =>        $items[$i]['definable_field_1'],
                'FIELD_3'                        =>        $items[$i]['definable_field_2'],
                'SKU'                                =>        $items[$i]['sku'],
                'NAME'                                =>        $items[$i]['name'],
                'ATTRIBUTE'                        =>        $items[$i]['show_attribute'],
                'ITEM_ID'                        =>        $items[$i]['item_id'],
                'ATTRIBUTES'                =>        $items[$i]['attributes'],
                'QUANTITY'                        =>        $items[$i]['quantity'],
                'WB_URL'                        =>        WB_URL,
                'TEXT_DELETE'                =>        $TEXT['DELETE'],
                'PRICE'                                =>        $f_price,
                'DISPLAY_SHIPPING'        =>        $display_shipping,
                'SHIPPING'                        =>        $f_shipping,
                'TOTAL'                                =>        $f_total
        ));

new Code at the same place

Code: [Select]
$read_txt = ($items[$i]['item_id'] == "39") ? 'readonly="readonly"' : '';
        // Show cart table body using template file
        $tpl->set_file('cart_table_body', 'table_body.htm');
        $tpl->set_var(array(
                'THUMB_URL'                        =>        $items[$i]['thumb_url'],
                'THUMB_WIDTH'                =>        $items[$i]['thumb_width'],
                'THUMB_HEIGHT'                =>        $items[$i]['thumb_height'],
                'LINK'                                =>        $items[$i]['link'],
                'FIELD_1'                        =>        $items[$i]['definable_field_0'],
                'FIELD_2'                        =>        $items[$i]['definable_field_1'],
                'FIELD_3'                        =>        $items[$i]['definable_field_2'],
                'SKU'                                =>        $items[$i]['sku'],
                'NAME'                                =>        $items[$i]['name'],
                'ATTRIBUTE'                        =>        $items[$i]['show_attribute'],
                'ITEM_ID'                        =>        $items[$i]['item_id'],
                'ATTRIBUTES'                =>        $items[$i]['attributes'],
                'QUANTITY'                        =>        $items[$i]['quantity'],
                'WB_URL'                        =>        WB_URL,
                'TEXT_DELETE'                =>        $TEXT['DELETE'],
                'PRICE'                                =>        $f_price,
                'DISPLAY_SHIPPING'        =>        $display_shipping,
                'SHIPPING'                        =>        $f_shipping,
                'TOTAL'                                =>        $f_total,
                'READONLY'                 =>   $read_txt
        ));

and in the template   \templates\cart\table_body.htm

Code: [Select]
<tr>
        <td class="mod_bakery_cart_td_thumb_f"><a href="{LINK}"><img src="{THUMB_URL}" alt="{NAME}" width="{THUMB_WIDTH}" height="{THUMB_HEIGHT}" border="0" /></a></td>
        <td class="mod_bakery_cart_td_sku_f">{SKU}</td>
        <td class="mod_bakery_cart_td_name_f"><span class="mod_bakery_cart_item_f">{NAME}</span><br />{ATTRIBUTE}</td>
        <td class="mod_bakery_cart_td_quantity_f"><input type="text" name="quantity[{ITEM_ID}][{ATTRIBUTES}]" {READONLY} value="{QUANTITY}" id="id_{ITEM_ID}_{ATTRIBUTES}" style="text-align: right" size="4" />
                <a href="#" onclick="javascript: mod_bakery_delete_item_f('{ITEM_ID}_{ATTRIBUTES}');"> <img src="{WB_URL}/modules/bakery/images/delete.gif" alt="{TEXT_DELETE}" title="{TEXT_DELETE}" /></a></td>
        <td class="mod_bakery_cart_td_price_f">{PRICE}</td>
        <td class="mod_bakery_cart_td_shipping_f" style="display: {DISPLAY_SHIPPING}">{SHIPPING}</td>
        <td class="mod_bakery_cart_td_sum_f">{TOTAL}</td>
</tr>

Title: Re: Include a product by default with each order
Post by: gearup on September 23, 2012, 05:36:57 AM
Thanks jacobi22,

I made the changes you showed and it works now.

Next I will try to add this product item to the cart correctly.

My idea is to add a control flag in view.php and so it is set when a new order number is generated.

This control flag would be then used to run a cut down copy of view.php (I named it view2.php)

This is still work in progress but here is what I have done so far,

view.php

Code: [Select]
//added at the beginning (line 137)
// control flag to run view2.php
$run_once = 0;

// if a new order_id is needed (line 171)
// Check order id
if (!isset($_SESSION['bakery']['order_id']) || ($_SESSION['bakery']['order_id'] == '')) {
$run_once = 1;

// just before the end of this section (line 218 / 308)
// PUT ITEM INTO THE CART
if (isset($_POST['add_to_cart']) && ($_POST['add_to_cart'] != '')) {
...
...
// Add default product to cart
// ***************************
if ($run_once == 1) {
include('view2.php');
}
}

I am working on view2.php but add below what it looks like at the moment.

Still trying to carefully decide what should be removed from view2.php.

regards,

Code: [Select]
<?php

/*
  Module developed for the Open Source Content Management System WebsiteBaker (http://WebsiteBaker.org)
  Copyright (C) 2012, Christoph Marti

  LICENCE TERMS:
  This module is free software. You can redistribute it and/or modify it 
  under the terms of the GNU General Public License - version 2 or later, 
  as published by the Free Software Foundation: http://www.gnu.org/licenses/gpl.html.

  DISCLAIMER:
  This module is distributed in the hope that it will be useful, 
  but WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
  GNU General Public License for more details.
*/


// Prevent this file from being accessed directly
if (defined('WB_PATH') == false) {
exit("Cannot access this file directly"); 
}

// Look for language file
if (LANGUAGE_LOADED) {
    include(
WB_PATH.'/modules/bakery/languages/EN.php');
    if (
file_exists(WB_PATH.'/modules/bakery/languages/'.LANGUAGE.'.php')) {
        include(
WB_PATH.'/modules/bakery/languages/'.LANGUAGE.'.php');
    }
}

// Check if there is a start point defined
if (isset($_GET['p']) AND is_numeric($_GET['p']) AND $_GET['p'] >= 0) {
$position $_GET['p'];
} else {
$position 0;
}

// Get user's username, display name, email, and id - needed for insertion into item info
$users = array();
$query_users $database->query("SELECT user_id,username,display_name,email FROM ".TABLE_PREFIX."users");
if (
$query_users->numRows() > 0) {
while ($user $query_users->fetchRow()) {
// Insert user info into users array
$user_id $user['user_id'];
$users[$user_id]['username'] = $user['username'];
$users[$user_id]['display_name'] = $user['display_name'];
$users[$user_id]['email'] = $user['email'];
}
}

// Update the section id of the last visited Bakery section for use with MiniCart
$_SESSION['bakery']['last_section_id'] = $section_id;

// Get general settings
$query_general_settings $database->query("SELECT * FROM ".TABLE_PREFIX."mod_bakery_general_settings");
if (
$query_general_settings->numRows() > 0) {
$fetch_general_settings $query_general_settings->fetchRow();

$setting_shop_name stripslashes($fetch_general_settings['shop_name']);
$setting_shop_email stripslashes($fetch_general_settings['shop_email']);
$setting_tac_url stripslashes($fetch_general_settings['tac_url']);
$setting_shop_country stripslashes($fetch_general_settings['shop_country']);
$setting_shop_state stripslashes($fetch_general_settings['shop_state']);
$setting_shipping_form stripslashes($fetch_general_settings['shipping_form']);
$setting_state_field stripslashes($fetch_general_settings['state_field']);
$setting_tax_no_field stripslashes($fetch_general_settings['tax_no_field']);
$setting_tax_group stripslashes($fetch_general_settings['tax_group']);
$setting_zip_location stripslashes($fetch_general_settings['zip_location']);
$setting_skip_cart stripslashes($fetch_general_settings['skip_cart']);
$setting_use_captcha stripslashes($fetch_general_settings['use_captcha']);

$setting_definable_field_0 stripslashes($fetch_general_settings['definable_field_0']);
$setting_definable_field_1 stripslashes($fetch_general_settings['definable_field_1']);
$setting_definable_field_2 stripslashes($fetch_general_settings['definable_field_2']);
$setting_stock_mode stripslashes($fetch_general_settings['stock_mode']);
$setting_stock_limit stripslashes($fetch_general_settings['stock_limit']);
$setting_out_of_stock_orders stripslashes($fetch_general_settings['out_of_stock_orders']);

$setting_shop_currency stripslashes($fetch_general_settings['shop_currency']);
$setting_dec_point stripslashes($fetch_general_settings['dec_point']);
$setting_thousands_sep stripslashes($fetch_general_settings['thousands_sep']);
$setting_tax_by stripslashes($fetch_general_settings['tax_by']);
$setting_tax_rate stripslashes($fetch_general_settings['tax_rate']);
$setting_tax_rate1 stripslashes($fetch_general_settings['tax_rate1']);
$setting_tax_rate2 stripslashes($fetch_general_settings['tax_rate2']);
$setting_tax_included stripslashes($fetch_general_settings['tax_included']);
$setting_skip_checkout stripslashes($fetch_general_settings['skip_checkout']);

$setting_tax_rate_shipping stripslashes($fetch_general_settings['tax_rate_shipping']);
$setting_free_shipping stripslashes($fetch_general_settings['free_shipping']);
$setting_free_shipping_msg stripslashes($fetch_general_settings['free_shipping_msg']);
$setting_shipping_method stripslashes($fetch_general_settings['shipping_method']);
$setting_shipping_domestic stripslashes($fetch_general_settings['shipping_domestic']);
$setting_shipping_abroad stripslashes($fetch_general_settings['shipping_abroad']);
$setting_shipping_zone stripslashes($fetch_general_settings['shipping_zone']);
$setting_zone_countries explode(","stripslashes($fetch_general_settings['zone_countries']));  // make array
$setting_shipping_d_a $setting_shipping_domestic."/".$setting_shipping_abroad;
}

// Get payment method settings
$query_payment_methods $database->query("SELECT directory FROM ".TABLE_PREFIX."mod_bakery_payment_methods WHERE active = '1'");
if (
$query_payment_methods->numRows() > 0) {
while ($fetch_payment_methods $query_payment_methods->fetchRow()) {
$setting_payment_methods[] = stripslashes($fetch_payment_methods['directory']);
}
} else {
$setting_payment_methods = array();
}
$num_payment_methods count($setting_payment_methods);
$skip_checkout = ($setting_skip_checkout == && $num_payment_methods == 1) ? true false;
// If checkout is omitted (1 step less) switch the directory for the step 1-2-3 images to step 1-2 images
$step_img_dir $skip_checkout "2_steps" "3_steps";

// Get page settings
$query_page_settings $database->query("SELECT page_offline, offline_text FROM ".TABLE_PREFIX."mod_bakery_page_settings WHERE section_id = '$section_id'");
if (
$query_page_settings->numRows() > 0) {
$fetch_page_settings $query_page_settings->fetchRow();

$setting_page_offline stripslashes($fetch_page_settings['page_offline']);
$setting_offline_text stripslashes($fetch_page_settings['offline_text']);
}

// Get continue url
$query_continue_url $database->query("SELECT p.link FROM ".TABLE_PREFIX."pages p INNER JOIN ".TABLE_PREFIX."mod_bakery_page_settings ps ON p.page_id = ps.page_id WHERE p.page_id = ps.continue_url AND ps.section_id = '$section_id'");
if (
$query_continue_url->numRows() > 0) {
$fetch_continue_url $query_continue_url->fetchRow();
$setting_continue_url WB_URL.PAGES_DIRECTORY.stripslashes($fetch_continue_url['link']).PAGE_EXTENSION;
}

// Add a wrapper for Bakery to help with layout
echo "\n<div id='mod_bakery_wrapper_f'>\n";
$end_of_wrapper "\n</div> <!-- End of bakery wrapper -->\n";



// ***************************************************************************************** //
// Check if we should show the SHOPPING CART, PROCESS ORDER, the MAIN PAGE or an ITEM itself //
// ***************************************************************************************** //


// GENERATE ORDER ID FOR NEW ORDERS
// ********************************

// MSIE image buttons only submit the click coordinates like 'anything_x' and 'anything_y'
// Convert POST name 'anything_x' to 'anything'
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
foreach ($_POST as $key => $value) {
$count 0;
$ie_post_key str_replace('_x'''$key$count);
if ($count 0) {
$_POST[$ie_post_key] = 1;
}
}
}

// Check submitted POST/GET vars
// if (isset($_REQUEST['view_cart'])  && ($_REQUEST['view_cart'] != '') || // normally POST, GET for MiniCart
//    isset($_POST['add_to_cart'])    && ($_POST['add_to_cart'] != '') ||
//    isset($_POST['update_cart'])    && ($_POST['update_cart'] != '') ||
//    isset($_POST['submit_order'])   && ($_POST['submit_order'] != '') ||
//    isset($_POST['hide_ship_form']) && ($_POST['hide_ship_form'] != '') ||
//    isset($_POST['add_ship_form'])  && ($_POST['add_ship_form'] != '')) {

// Check order id
if (!isset($_SESSION['bakery']['order_id']) || ($_SESSION['bakery']['order_id'] == '')) {
$mktime = @mktime();
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_customer (order_date) VALUES ('$mktime')");
$order_id mysql_insert_id(); 
$_SESSION['bakery']['order_id'] = $order_id;

}
$order_id $_SESSION['bakery']['order_id'];



//  SHOPPING CART FUNCTIONS
//  ***********************


// PUT ITEM INTO THE CART
//if (isset($_POST['add_to_cart']) && ($_POST['add_to_cart'] != '')) {

// Get item ID and quantity ( -> $value)
$sql_result1 $database->query("SELECT * FROM " .TABLE_PREFIX."mod_bakery_order WHERE order_id = '$order_id'");

foreach ($_POST as $field => $value) {
// Error message if quantity < 1
if (substr($field,0,4) == "item" && $value 1) {
$cart_error[] = $MOD_BAKERY['ERR_QUANTITY_ZERO'];
}
if (substr($field,0,4) == "item" && $value 0) {
// Get item_id
//$item_id = substr($field,4,strlen($field)-4);
$item_id 39;
// Get item attributes and make comma separated string
if (isset($_POST['attribute'][0])) {
$attributes implode(","$_POST['attribute']);
} else {
// If no attribute is given set it to "none"
$attributes "none";
}

//  Error message if item is in cart already
while ($row1 $sql_result1->fetchRow()) {
if ($row1['item_id'] == $item_id && $row1['attributes'] == $attributes) {
$cart_error[] = $MOD_BAKERY['ERR_ITEM_EXISTS'];
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
}

// Get item price, sku, stock and tax_rate
$sql_result2 $database->query("SELECT title, price, sku, stock, tax_rate FROM " .TABLE_PREFIX."mod_bakery_items WHERE item_id = '$item_id'");
$row2 $sql_result2->fetchRow();
$row2 array_map('stripslashes'$row2);
$title $row2['title'];
$sku $row2['sku'];
$price $row2['price'];
$tax_rate $row2['tax_rate'];
$stock $row2['stock'];
$quantity $value;

// Only use stock admin if stock is not blank
if (is_numeric($stock) && $stock != '') {
// If item is short of stock show error message
if ($setting_out_of_stock_orders) {

// Case: Allow out of stock orders
if ($stock $value) {
$cart_error[] = "{$MOD_BAKERY['TXT_SHORT_OF_STOCK_SUBSEQUENT_DELIVERY']}!<br /><b>$stock</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.";
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$value' WHERE item_id = '$item_id'");

} else {
// Case: No out of stock orders
// If item is short of stock...
if ($stock <= $value) {
// ...set quantity to remaining stock
$quantity $stock;
// Show error message
if ($stock $value) {
$cart_error[] = "<b>$quantity</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.<br />{$MOD_BAKERY['TXT_SHORT_OF_STOCK_QUANTITY_CAPPED']}!";
}
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$quantity' WHERE item_id = '$item_id'");
}
}
// Insert ordered item data into db
if ($quantity 0) {
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_order (order_id, item_id, attributes, sku, quantity, price, tax_rate) VALUES ('$order_id', '$item_id', '$attributes', '$sku', '$quantity', '$price', '$tax_rate')");
}
}
}

// If required skip cart
if ($setting_skip_cart == "yes") {
include('view_overview.php');
echo $end_of_wrapper;  // End of bakery wrapper
unset($_SESSION['bakery']['minicart']);
return;
} else {
// Show cart
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
//}


//}

?>

Title: Re: Include a product by default with each order
Post by: gearup on September 23, 2012, 10:12:11 AM
Hi,

so now I am about 90% done. It works ok under normal conditions and there very little left to fix.

If I choose "add to cart" on a product to create a new order then my default product is correctly added at the same time as this other product with quantity value as read only.

All controls in the cart work as they should.

There are 2 points still to do.

1. In the cart this default product can still be removed by clicking on the "X".
<update>
Now resolved, changed the javascript line in table body.htm file to add a conditional test,
Code: [Select]
<a href="#" onclick="javascript: if ({ITEM_ID} != 39) {mod_bakery_delete_item_f('{ITEM_ID}_{ATTRIBUTES}');}">
<img src="{WB_URL}/modules/bakery/images/delete.gif" alt="{TEXT_DELETE}" title="{TEXT_DELETE}" /></a></td>

Maybe i should surround {ITEM_ID} by "{ITEM_ID}" or '{ITEM_ID}' - I am still not sure of the correct syntax.


2. If before I add a product to the cart to create a new order I instead select "view cart" it correctly states the cart is empty but then when I add the first product my default product does not get added along with it.

I decided not to use the "view2.php" file mentioned in my previous post but instead modified the view .php file.

Modified code can be found below, I will post the changed files when it is finally all working.

regards,

Code: [Select]
added at line 137
// control flag to run view2.php
$run_once = 0;
// variable to preserve $item_id
$item_id_saved = '';

inserted my control flag (line 173)
// Check order id
if (!isset($_SESSION['bakery']['order_id']) || ($_SESSION['bakery']['order_id'] == '')) {
$run_once = 1;
$mktime = @mktime();

inserted repeated code at line 295
// Add default product to cart
if ($run_once == 1) {
$item_id_saved = $item_id;


// Error message if quantity < 1
if (substr($field,0,4) == "item" && $value < 1) {
$cart_error[] = $MOD_BAKERY['ERR_QUANTITY_ZERO'];
}
if (substr($field,0,4) == "item" && $value > 0) {
// Get item_id
//$item_id = substr($field,4,strlen($field)-4);
$item_id = 39;
// Get item attributes and make comma separated string
if (isset($_POST['attribute'][0])) {
$attributes = implode(",", $_POST['attribute']);
} else {
// If no attribute is given set it to "none"
$attributes = "none";
}

//  Error message if item is in cart already
while ($row1 = $sql_result1->fetchRow()) {
if ($row1['item_id'] == $item_id && $row1['attributes'] == $attributes) {
$cart_error[] = $MOD_BAKERY['ERR_ITEM_EXISTS'];
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
}

// Get item price, sku, stock and tax_rate
$sql_result2 = $database->query("SELECT title, price, sku, stock, tax_rate FROM " .TABLE_PREFIX."mod_bakery_items WHERE item_id = '$item_id'");
$row2 = $sql_result2->fetchRow();
$row2 = array_map('stripslashes', $row2);
$title = $row2['title'];
$sku = $row2['sku'];
$price = $row2['price'];
$tax_rate = $row2['tax_rate'];
$stock = $row2['stock'];
$quantity = $value;

// Only use stock admin if stock is not blank
if (is_numeric($stock) && $stock != '') {
// If item is short of stock show error message
if ($setting_out_of_stock_orders) {

// Case: Allow out of stock orders
if ($stock < $value) {
$cart_error[] = "{$MOD_BAKERY['TXT_SHORT_OF_STOCK_SUBSEQUENT_DELIVERY']}!<br /><b>$stock</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.";
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$value' WHERE item_id = '$item_id'");

} else {
// Case: No out of stock orders
// If item is short of stock...
if ($stock <= $value) {
// ...set quantity to remaining stock
$quantity = $stock;
// Show error message
if ($stock < $value) {
$cart_error[] = "<b>$quantity</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.<br />{$MOD_BAKERY['TXT_SHORT_OF_STOCK_QUANTITY_CAPPED']}!";
}
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$quantity' WHERE item_id = '$item_id'");
}
}
// Insert ordered item data into db
if ($quantity > 0) {
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_order (order_id, item_id, attributes, sku, quantity, price, tax_rate) VALUES ('$order_id', '$item_id', '$attributes', '$sku', '$quantity', '$price', '$tax_rate')");
}
}
// tidy up and restore $item_id
$run_once == 0;
$item_id = $item_id_saved;
}
Title: Re: Include a product by default with each order[solved]
Post by: gearup on September 23, 2012, 12:18:08 PM
Hi,

So now it all works, I include the 3 changed files in this post should anyone else have a similar need.

I have hard coded the ID for my default product, while not ideal it achieves the aim.

For someone else to use this you need to replace the '39' ID with the one for your default product.

and here are the changed files,

view.php
Code: [Select]

Note: no changes above this point, reduced code in post to stop overflowing the post character limit

// Add a wrapper for Bakery to help with layout
echo "\n<div id='mod_bakery_wrapper_f'>\n";
$end_of_wrapper = "\n</div> <!-- End of bakery wrapper -->\n";


// control flag to run view2.php
$run_once = 0;
// variable to preserve $item_id
$item_id_saved = '';



// ***************************************************************************************** //
// Check if we should show the SHOPPING CART, PROCESS ORDER, the MAIN PAGE or an ITEM itself //
// ***************************************************************************************** //


// GENERATE ORDER ID FOR NEW ORDERS
// ********************************

// MSIE image buttons only submit the click coordinates like 'anything_x' and 'anything_y'
// Convert POST name 'anything_x' to 'anything'
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
foreach ($_POST as $key => $value) {
$count = 0;
$ie_post_key = str_replace('_x', '', $key, $count);
if ($count > 0) {
$_POST[$ie_post_key] = 1;
}
}
}

// Check submitted POST/GET vars
if (isset($_REQUEST['view_cart'])  && ($_REQUEST['view_cart'] != '') || // normally POST, GET for MiniCart
   isset($_POST['add_to_cart'])    && ($_POST['add_to_cart'] != '') ||
   isset($_POST['update_cart'])    && ($_POST['update_cart'] != '') ||
   isset($_POST['submit_order'])   && ($_POST['submit_order'] != '') ||
   isset($_POST['hide_ship_form']) && ($_POST['hide_ship_form'] != '') ||
   isset($_POST['add_ship_form'])  && ($_POST['add_ship_form'] != '')) {

// Check order id
if (!isset($_SESSION['bakery']['order_id']) || ($_SESSION['bakery']['order_id'] == '')) {
$mktime = @mktime();
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_customer (order_date) VALUES ('$mktime')");
$order_id = mysql_insert_id();
$_SESSION['bakery']['order_id'] = $order_id;

// Delete db records of not submitted orders older than 1 hour
$outdate = $mktime - (60 * 60 * 1);
$query_outdated_orders = $database->query("SELECT order_id FROM " .TABLE_PREFIX."mod_bakery_customer WHERE order_date < $outdate AND submitted = 'no'");
if ($query_outdated_orders->numRows() > 0) {
while ($outdated_orders = $query_outdated_orders->fetchRow()) {
$outdated_order_id = stripslashes($outdated_orders['order_id']);

// First put not sold items back to stock...
$query_order = $database->query("SELECT item_id, quantity FROM " .TABLE_PREFIX."mod_bakery_order WHERE order_id = '$outdated_order_id'");
if ($query_order->numRows() > 0) {
while ($order = $query_order->fetchRow()) {
$item_id = stripslashes($order['item_id']);
$quantity = stripslashes($order['quantity']);
// Query item stock
$query_items = $database->query("SELECT stock FROM " .TABLE_PREFIX."mod_bakery_items WHERE item_id = '$item_id'");
$item = $query_items->fetchRow();
$stock = stripslashes($item['stock']);
// Only use stock admin if stock is not blank
if (is_numeric($stock) && $stock != '') {
// Update stock to required quantity
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock + '$quantity' WHERE item_id = '$item_id'");
}
}
}

// ...then delete not submitted orders
$database->query("DELETE FROM " .TABLE_PREFIX."mod_bakery_customer WHERE order_id = '$outdated_order_id' AND submitted = 'no'");
$database->query("DELETE FROM " .TABLE_PREFIX."mod_bakery_order WHERE order_id = '$outdated_order_id'");
}
}
}
$order_id = $_SESSION['bakery']['order_id'];



//  SHOPPING CART FUNCTIONS
//  ***********************


// PUT ITEM INTO THE CART
if (isset($_POST['add_to_cart']) && ($_POST['add_to_cart'] != '')) {

// Get item ID and quantity ( -> $value)
$sql_result1 = $database->query("SELECT * FROM " .TABLE_PREFIX."mod_bakery_order WHERE order_id = '$order_id'");

foreach ($_POST as $field => $value) {
// Error message if quantity < 1
if (substr($field,0,4) == "item" && $value < 1) {
$cart_error[] = $MOD_BAKERY['ERR_QUANTITY_ZERO'];
}
if (substr($field,0,4) == "item" && $value > 0) {
// Get item_id
$item_id = substr($field,4,strlen($field)-4);
// Get item attributes and make comma separated string
if (isset($_POST['attribute'][0])) {
$attributes = implode(",", $_POST['attribute']);
} else {
// If no attribute is given set it to "none"
$attributes = "none";
}

// If cart is empty, set flag to add Default Product
$n_row = $sql_result1->numRows();
if ($n_row < 1) {
$run_once = 1;
}

//  Error message if item is in cart already
while ($row1 = $sql_result1->fetchRow()) {
if ($row1['item_id'] == $item_id && $row1['attributes'] == $attributes) {
$cart_error[] = $MOD_BAKERY['ERR_ITEM_EXISTS'];
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
}

// Get item price, sku, stock and tax_rate
$sql_result2 = $database->query("SELECT title, price, sku, stock, tax_rate FROM " .TABLE_PREFIX."mod_bakery_items WHERE item_id = '$item_id'");
$row2 = $sql_result2->fetchRow();
$row2 = array_map('stripslashes', $row2);
$title = $row2['title'];
$sku = $row2['sku'];
$price = $row2['price'];
$tax_rate = $row2['tax_rate'];
$stock = $row2['stock'];
$quantity = $value;

// Only use stock admin if stock is not blank
if (is_numeric($stock) && $stock != '') {
// If item is short of stock show error message
if ($setting_out_of_stock_orders) {

// Case: Allow out of stock orders
if ($stock < $value) {
$cart_error[] = "{$MOD_BAKERY['TXT_SHORT_OF_STOCK_SUBSEQUENT_DELIVERY']}!<br /><b>$stock</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.";
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$value' WHERE item_id = '$item_id'");

} else {
// Case: No out of stock orders
// If item is short of stock...
if ($stock <= $value) {
// ...set quantity to remaining stock
$quantity = $stock;
// Show error message
if ($stock < $value) {
$cart_error[] = "<b>$quantity</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.<br />{$MOD_BAKERY['TXT_SHORT_OF_STOCK_QUANTITY_CAPPED']}!";
}
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$quantity' WHERE item_id = '$item_id'");
}
}
// Insert ordered item data into db
if ($quantity > 0) {
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_order (order_id, item_id, attributes, sku, quantity, price, tax_rate) VALUES ('$order_id', '$item_id', '$attributes', '$sku', '$quantity', '$price', '$tax_rate')");
}
}

// Add default product to cart
if ($run_once == 1) {
$item_id_saved = $item_id;


// Error message if quantity < 1
if (substr($field,0,4) == "item" && $value < 1) {
$cart_error[] = $MOD_BAKERY['ERR_QUANTITY_ZERO'];
}
if (substr($field,0,4) == "item" && $value > 0) {
// Get item_id
//$item_id = substr($field,4,strlen($field)-4);
$item_id = 39;
// Get item attributes and make comma separated string
if (isset($_POST['attribute'][0])) {
$attributes = implode(",", $_POST['attribute']);
} else {
// If no attribute is given set it to "none"
$attributes = "none";
}

//  Error message if item is in cart already
while ($row1 = $sql_result1->fetchRow()) {
if ($row1['item_id'] == $item_id && $row1['attributes'] == $attributes) {
$cart_error[] = $MOD_BAKERY['ERR_ITEM_EXISTS'];
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
}

// Get item price, sku, stock and tax_rate
$sql_result2 = $database->query("SELECT title, price, sku, stock, tax_rate FROM " .TABLE_PREFIX."mod_bakery_items WHERE item_id = '$item_id'");
$row2 = $sql_result2->fetchRow();
$row2 = array_map('stripslashes', $row2);
$title = $row2['title'];
$sku = $row2['sku'];
$price = $row2['price'];
$tax_rate = $row2['tax_rate'];
$stock = $row2['stock'];
$quantity = $value;

// Only use stock admin if stock is not blank
if (is_numeric($stock) && $stock != '') {
// If item is short of stock show error message
if ($setting_out_of_stock_orders) {

// Case: Allow out of stock orders
if ($stock < $value) {
$cart_error[] = "{$MOD_BAKERY['TXT_SHORT_OF_STOCK_SUBSEQUENT_DELIVERY']}!<br /><b>$stock</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.";
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$value' WHERE item_id = '$item_id'");

} else {
// Case: No out of stock orders
// If item is short of stock...
if ($stock <= $value) {
// ...set quantity to remaining stock
$quantity = $stock;
// Show error message
if ($stock < $value) {
$cart_error[] = "<b>$quantity</b> {$MOD_BAKERY['TXT_ITEMS']} <b>$title</b> {$MOD_BAKERY['TXT_AVAILABLE_QUANTITY']}.<br />{$MOD_BAKERY['TXT_SHORT_OF_STOCK_QUANTITY_CAPPED']}!";
}
}
// Update stock
$database->query("UPDATE ".TABLE_PREFIX."mod_bakery_items SET stock = stock - '$quantity' WHERE item_id = '$item_id'");
}
}
// Insert ordered item data into db
if ($quantity > 0) {
$database->query("INSERT INTO " .TABLE_PREFIX."mod_bakery_order (order_id, item_id, attributes, sku, quantity, price, tax_rate) VALUES ('$order_id', '$item_id', '$attributes', '$sku', '$quantity', '$price', '$tax_rate')");
}
}
// tidy up and restore $item_id
$run_once == 0;
$item_id = $item_id_saved;
}
}

// If required skip cart
if ($setting_skip_cart == "yes") {
include('view_overview.php');
echo $end_of_wrapper;  // End of bakery wrapper
unset($_SESSION['bakery']['minicart']);
return;
} else {
// Show cart
include('view_cart.php');
echo $end_of_wrapper;  // End of bakery wrapper
return;
}
}


// UPDATE CART
elseif (isset($_POST['update_cart']) && ($_POST['update_cart'] != '')) {


Note: no changes below this point, reduced code in post to stop overflowing the post character limit



view_cart.php
Code: [Select]

Note: if I include the full code I go over the post character limit so here is the changed section only.

// Show cart table body using template file
$read_txt = ($items[$i]['item_id'] == "39") ? 'readonly="readonly"' : '';
$tpl->set_file('cart_table_body', 'table_body.htm');
$tpl->set_var(array(
'THUMB_URL' => $items[$i]['thumb_url'],
'THUMB_WIDTH' => $items[$i]['thumb_width'],
'THUMB_HEIGHT' => $items[$i]['thumb_height'],
'LINK' => $items[$i]['link'],
'SKU' => $items[$i]['sku'],
'NAME' => $items[$i]['name'],
'ATTRIBUTE' => $items[$i]['show_attribute'],
'ITEM_ID' => $items[$i]['item_id'],
'ATTRIBUTES' => $items[$i]['attributes'],
'QUANTITY' => $items[$i]['quantity'],
'WB_URL' => WB_URL,
'TEXT_DELETE' => $TEXT['DELETE'],
'PRICE' => $f_price,
'DISPLAY_SHIPPING' => $display_shipping,
'SHIPPING' => $f_shipping,
'TOTAL' => $f_total,
'READONLY'          =>  $read_txt
));
$tpl->pparse('output', 'cart_table_body');
}


\templates\cart\table_body.htm
Code: [Select]
<tr>
<td class="mod_bakery_cart_td_thumb_f"><a href="{LINK}"><img src="{THUMB_URL}" alt="{NAME}" width="{THUMB_WIDTH}" height="{THUMB_HEIGHT}" border="0" /></a></td>
<td class="mod_bakery_cart_td_sku_f">{SKU}</td>
<td class="mod_bakery_cart_td_name_f"><span class="mod_bakery_cart_item_f">{NAME}</span><br />{ATTRIBUTE}</td>
<td class="mod_bakery_cart_td_quantity_f"><input type="text" name="quantity[{ITEM_ID}][{ATTRIBUTES}]" {READONLY} value="{QUANTITY}" id="id_{ITEM_ID}_{ATTRIBUTES}" style="text-align: right" size="4" />
<a href="#" onclick="javascript: if ({ITEM_ID} != 39) {mod_bakery_delete_item_f('{ITEM_ID}_{ATTRIBUTES}');}"> <img src="{WB_URL}/modules/bakery/images/delete.gif" alt="{TEXT_DELETE}" title="{TEXT_DELETE}" /></a></td>
<td class="mod_bakery_cart_td_price_f">{PRICE}</td>
<td class="mod_bakery_cart_td_shipping_f" style="display: {DISPLAY_SHIPPING}">{SHIPPING}</td>
<td class="mod_bakery_cart_td_sum_f">{TOTAL}</td>
</tr>

<update>
Now I see others add the changed files in zip form I will do the same.

regards,