Перейти к содержимому


Juggler

Регистрация: 14 Aug 2012
Offline Активность: Oct 14 2012 09:03 PM
-----

Мои темы

Простая накопительная скидка

05 October 2012 - 01:07 PM

По аналогии с существующим модулем "Накопительная скидка", только проще. Добавляем новые типы скидок к существующим, в которых используется еще один параметр - общая сумма заказов покупателя.

Вносим изменения в файлы (пути даю по версии ShopCMS 3.0.1 и 3.1.2 VIP):

Добавляем в languages/russian.php (3.0.1) или core/languages/russian.php (3.1.2)

define('ADMIN_DISCOUNT_GENERAL_ORDER_PRICE_TOTAL_ORDERS', 'Скидка вычисляется исходя из общей стоимости всех заказов пользователя');
define('ADMIN_DISCOUNT_CUSTOMER_GROUP_PLUS_GENERAL_ORDER_PRICE_TOTAL_ORDERS', 'Скидка вычисляется как сумма скидки группы пользователя и скидки от суммы всех его заказов');
define('ADMIN_DISCOUNT_MAX_CUSTOMER_GROUP_TOTAL_ORDERS', 'Скидка вычисляется как максимальная из скидки группы пользователя и скидки от суммы всех его заказов');
define('ADMIN_DISCOUNT_MAX_CUSTOMER_GROUP_GENERAL_ORDER_PRICE_TOTAL_ORDERS', 'Скидка вычисляется как максимальная из скидки группы пользователя, скидки от суммы заказа и общей суммы всех заказов пользователя');


Заменяем существующую функцию в functions/setting_functions.php (3.0.1) или core/functions/setting_functions.php (3.1.2)

function settingCONF_DISCOUNT_TYPE()
{
if ( isset($_POST["save"]) )
_setSettingOptionValue( "CONF_DISCOUNT_TYPE", $_POST["settingCONF_DISCOUNT_TYPE"] );
$value = _getSettingOptionValue("CONF_DISCOUNT_TYPE");
$value_go = _getSettingOptionValue("CONF_USER_SYSTEM");
if ($value_go == 1){
$res = "";
$res .= "<table class=and>";
$res .= _CONF_DISCOUNT_TYPE_radio_button( "1", ADMIN_DISCOUNT_IS_SWITCHED_OFF, $value=="1"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "2", ADMIN_DISCOUNT_CUSTOMER_GROUP, $value=="2"?1:0, 1 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "3", ADMIN_DISCOUNT_GENERAL_ORDER_PRICE, $value=="3"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "7", ADMIN_DISCOUNT_GENERAL_ORDER_PRICE_TOTAL_ORDERS, $value=="7"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "4", ADMIN_DISCOUNT_CUSTOMER_GROUP_PLUS_GENERAL_ORDER_PRICE,$value=="4"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "8", ADMIN_DISCOUNT_CUSTOMER_GROUP_PLUS_GENERAL_ORDER_PRICE_TOTAL_ORDERS, $value=="8"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "5", ADMIN_DISCOUNT_MAX_CUSTOMER_GROUP_GENERAL_ORDER_PRICE, $value=="5"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "9", ADMIN_DISCOUNT_MAX_CUSTOMER_GROUP_TOTAL_ORDERS, $value=="9"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "6", ADMIN_DISCOUNT_MAX_CUSTOMER_GROUP_GENERAL_ORDER_PRICE_TOTAL_ORDERS, $value=="6"?1:0, 0 );
$res .= "</table>";
}else{
$res = "";
$res .= "<table class=and>";
$res .= _CONF_DISCOUNT_TYPE_radio_button( "1", ADMIN_DISCOUNT_IS_SWITCHED_OFF, $value=="1"?1:0, 0 );
$res .= _CONF_DISCOUNT_TYPE_radio_button( "3", ADMIN_DISCOUNT_GENERAL_ORDER_PRICE, $value=="3"?1:0, 0 );
$res .= "</table>";
}
return $res;
}


Добавляем в functions/order_amount_functions.php (3.0.1) или core/functions/order_amount_functions.php (3.1.2)

function oaGetTotalPrice( $log )
{
$q = db_query("select sum(ot.order_amount-ot.shipping_cost) from ".ORDERS_TABLE." ot, ".ORDER_STATUES_TABLE.
" st where ot.statusID=st.statusID and st.statusID=".CONF_COMPLETED_ORDER_STATUS." and ot.customerID=".(int)regGetIdByLogin($log));
$row=db_fetch_row($q);
return $row[0];
}


Заменяем в functions/discount_functions.php (3.0.1) или core/functions/discount_functions.php (3.1.2)

function dscCalculateDiscount( $orderPrice, $log )
{
$discount = array(
"discount_percent" => 0,
"discount_standart_unit" => 0,
"discount_current_unit" => 0,
"rest_standart_unit" => 0,
"rest_current_unit" => 0,
"priceUnit" => getPriceUnit() );
$totalPrice = oaGetTotalPrice( $log );
switch( CONF_DISCOUNT_TYPE )
{
// discount is switched off
case 1:
return $discount;
break;

// discount is based on customer group
case 2:
$discount["discount_percent"] = _calculateCustomerGroupDiscount($log);
return $discount;
break;

// discount is calculated with help general order price
case 3:
$discount["discount_percent"] = _calculateGeneralPriceDiscount( $orderPrice, $log );
break;

// discount equals to discount is based on customer group plus
// discount calculated with help general order price
case 4:
$discount["discount_percent"] = _calculateCustomerGroupDiscount($log) + _calculateGeneralPriceDiscount($orderPrice, $log );
break;

// discount is calculated as MAX( discount is based on customer group,
// discount calculated with help general order price )
case 5:
$discount["discount_percent"] = max(_calculateCustomerGroupDiscount($log), _calculateGeneralPriceDiscount($orderPrice, $log ));
break;
// discount is calculated as MAX( discount is based on customer group,
// discount calculated with help general order price and discount calculated on base of all customer orders )
case 6:
$discount["discount_percent"] = max(
max(_calculateCustomerGroupDiscount($log), _calculateGeneralPriceDiscount($orderPrice, $log )),
_calculateGeneralPriceDiscount($totalPrice, $log )
);
break;
// discount is calculated with help of total customer order prices
case 7:
$discount["discount_percent"] = _calculateGeneralPriceDiscount( $totalPrice, $log );
break;

// discount equals to discount is based on customer group plus
// discount calculated with help of total customer order prices
case 8:
$discount["discount_percent"] = _calculateCustomerGroupDiscount($log) + _calculateGeneralPriceDiscount($totalPrice, $log );
break;

// discount is calculated as MAX( discount is based on customer group,
// discount calculated with help of total customer order prices )
case 9:
$discount["discount_percent"] = max(_calculateCustomerGroupDiscount($log), _calculateGeneralPriceDiscount($totalPrice, $log ));
break;
}

if(CONF_DISCOUNT_TYPE == 7 || CONF_DISCOUNT_TYPE == 8 || CONF_DISCOUNT_TYPE == 9) $orderPrice = $totalPrice;
elseif (CONF_DISCOUNT_TYPE == 6) $orderPrice = max($orderPrice, $totalPrice);

$discount["discount_standart_unit"] = ((float)$orderPrice/100)*(float)$discount["discount_percent"];
$discount["discount_current_unit"] = show_priceWithOutUnit( $discount["discount_standart_unit"] );
$discount["rest_standart_unit"] = $orderPrice - $discount["discount_standart_unit"];
$discount["rest_current_unit"] = show_priceWithOutUnit( $discount["rest_standart_unit"] );
return $discount;
}


Добавляем в functions/discount_functions.php (3.0.1) или core/functions/discount_functions.php (3.1.2)

function _calculateCustomerGroupDiscount($log)
{
$customerID = (int)regGetIdByLogin($log);
if ( !is_bool($customerID) ){
$customer_group = GetCustomerGroupByCustomerId( $customerID );
if ( !$customer_group) return 0;
else return $customer_group["custgroup_discount"];
}
else return 0;
}

Передача заказа другому покупателю

01 October 2012 - 01:37 PM

Перемещение заказа от одного покупателя к другому. Полезно, когда в магазине один и тот же покупатель регистрируется несколько раз. Можно собрать все его заказы вместе, а лишние учетные записи удалить.


function ordMoveOrder($orderID, $toCustomerID){
$q = db_query("select customerID from ".ORDERS_TABLE." where orderID=".(int)$orderID);
if($row = db_fetch_row($q) && ($row[0] <> (int)$toCustomerID)){ // if exists order with this ID and it's not the same as dest customerID
$q1 = db_query("select c.first_name, c.last_name, c.email, ca.city, ca.address, cn.country_name, zn.zone_name from ".CUSTOMERS_TABLE." c ".
"join ".CUSTOMER_ADDRESSES_TABLE." ca on ca.customerID=c.customerID and ca.addressID=c.addressID ".
"join ".COUNTRIES_TABLE." cn on cn.countryID=ca.countryID ".
"join ".ZONES_TABLE." zn on zn.zoneID=ca.zoneID ".
"where c.customerID=".(int)$toCustomerID
);
// get data about current customer
if($row1 = db_fetch_row($q1)){
db_query("update ".ORDERS_TABLE." set ".
"customerID=".(int)$toCustomerID.", ".
"customer_firstname='".$row1[0]."', ".
"customer_lastname='".$row1[1]."', ".
"customer_email='".$row1[2]."', ".
"shipping_firstname='".$row1[0]."', ".
"shipping_lastname='".$row1[1]."', ".
"shipping_country='".$row1[5]."', ".
"shipping_state='".$row1[6]."', ".
"shipping_city='".$row1[3]."', ".
"shipping_address='".$row1[4]."', ".
"billing_firstname='".$row1[0]."', ".
"billing_lastname='".$row1[1]."', ".
"billing_country='".$row1[5]."', ".
"billing_state='".$row1[6]."', ".
"billing_city='".$row1[3]."', ".
"billing_address='".$row1[4]."' ".
"where orderID=".(int)$orderID
);
}
}
}

Перерасчет суммы заказа

01 October 2012 - 01:33 PM

При изменении любых параметров заказа, которые влияют на его сумму, её требуется перерасчитать и обновить. Это нужно, к примеру, при изменении
  • количества товара, добавлении или удалении позиций
  • размера скидки
  • способа доставки
Для удобства, операция оформлена в виде единственной функции, которую нужно вызывать после реализации нужных изменений в заказе.


function ordUpdateTotal($orderID){
// set temp order amount with discount and without shipping
$subq = "select SUM(Price*Quantity) from ".ORDERED_CARTS_TABLE." WHERE orderID=".(int)$orderID;
db_query("update ".ORDERS_TABLE." SET order_amount=(".$subq.")*(100-order_discount)/100 WHERE orderID=".(int)$orderID);

// update shipping cost
db_query("update ".ORDERS_TABLE." set shipping_cost=".(float)ordShippingRate($orderID)." where orderID=".(int)$orderID);

// update total amount
$subq = "select SUM(Price*Quantity) from ".ORDERED_CARTS_TABLE." WHERE orderID=".(int)$orderID;
db_query("update ".ORDERS_TABLE." SET order_amount=(".$subq.")*(100-order_discount)/100+shipping_cost WHERE orderID=".(int)$orderID);
}

function ordShippingRate($orderID)
{
$q = db_query("select shipping_type, customerID from ".ORDERS_TABLE." where orderID=".(int)$orderID);
if($row = db_fetch_row($q)){
$shipping=GetShippingIdbyName($row["shipping_type"]);
if(($shippingModule = modGetModuleObj($shipping["module_id"], SHIPPING_RATE_MODULE )) != null){
// Fill in address
$sq = "select c.customerID, c.first_name, c.last_name, ca.countryID, ca.zoneID, ca.state, ca.city, ca.address from ".CUSTOMERS_TABLE." c ".
"join ".CUSTOMER_ADDRESSES_TABLE." ca on ca.addressID=c.addressID and ca.customerID=c.customerID ".
"where c.customerID=".(int)$row["customerID"];
$q = db_query($sq);
if($row = db_fetch_row($q)) $address = $row;
else $address=array();
// Fill in order
$order = ordGetOrder((int)$orderID);
$order["orderContent"]["cart_content"] = ordGetOrderContent( $orderID );
for($i=0; $i<count($order["orderContent"]["cart_content"]); ++$i){
$order["orderContent"]["cart_content"][$i]["id"] = $order["orderContent"]["cart_content"][$i]["itemID"];
$order["orderContent"]["cart_content"][$i]["quantity"] = $order["orderContent"]["cart_content"][$i]["Quantity"];
$order["orderContent"]["cart_content"][$i]["product_img"] = $order["orderContent"]["cart_content"][$i]["product_picture"];

$variants=GetConfigurationByItemId( $order["orderContent"]["cart_content"][$i]["itemID"] );
$order["orderContent"]["cart_content"][$i]["costUC"] = GetPriceProductWithOption( $variants, $order["orderContent"]["cart_content"][$i]["productID"]);
$order["orderContent"]["cart_content"][$i]["cost"] = show_price($order["orderContent"]["cart_content"][$i]["Quantity"]*$order["orderContent"]["cart_content"][$i]["costUC"]);

$strOptions=GetStrOptions($variants);
if ( trim($strOptions) != "" ) $order["orderContent"]["cart_content"][$i]["name"].=" (".$strOptions.")";
}

// calculate rate
$newRate = (float)$shippingModule->calculate_shipping_rate($order, $address) ;
}
else $newRate = 0.0;
}
else $newRate = 0.0;

return $newRate;
}

База городов России (MySQL)

06 September 2012 - 10:33 AM

Надеюсь, будет для кого-то полезно

База городов России в формате MySQL с привязкой к ZoneID и countryID существующих регионов и стран в ShopCMS.