/** * "pc_shop/cart/calculate_prices" event handler. * * Validates delivery specific form information and calculates delivery price. * * @param array $params An associative array containing cart and order information that should be used for calculation. * - 'data' array: A reference to an associative array representing current cart state that should be filled with calculated data. * - 'order_data' array: An associative array containing information on current order. * - 'coupon_data' array: An associative array containing information on applied discount coupon. * - 'delivery_option_data' array: An associative array containing information on the currently selected delivery method. * - 'delivery_form_data' array: An associative array containing values of fields filled in the form specific to currently selected delivery method. */ function calculateCartPrice($params) { global $cfg, $core, $cache; $data =& $params['data']; if (isset($params['delivery_form_data']['city']) && $params['delivery_form_data']['city']) { /** @var PC_shop_site $shop */ $shop = $core->Get_object('PC_shop_site'); $limit = $this->getCityCODLimit($params['delivery_form_data']['city']); $data['delivery_info']['cod_limit'] = $limit; // print_pre($params['data']['items']); // print_pre($params['data']['products']); $maxX = 0; // package width $maxY = 0; // package length $totalZ = 0; // package height $totalSizeWeight = 0; $totalVolume = 0; $totalVolumeWeight = 0; foreach ($params['data']['items'] as $cartItem) { $product = $shop->products->applyAttributes($params['data']['products'][$cartItem['product_id']], $cartItem['attributes']); unset($product['attributes'], $product['attribute_index'], $product['combinations'], $product['price_combinations'], $product['resources'], $product['text'], $product['description']); if (!$product['weight']) { continue; } /* $measurements = array( 'weight' => $product['weight'], 'width' => $product['width'], 'height' => $product['height'], 'length' => $product['length'], 'volume' => $product['volume'], ); print_pre($measurements); */ if ($product['width'] > 0 && $product['height'] > 0 && $product['length'] > 0) { if ($product['width'] <= $product['height'] && $product['width'] <= $product['length']) { $x = $product['height']; $y = $product['length']; $z = $product['width']; } else { if ($product['height'] <= $product['width'] && $product['height'] <= $product['length']) { $x = $product['width']; $y = $product['length']; $z = $product['height']; } else { $x = $product['width']; $y = $product['height']; $z = $product['length']; } } $maxX = max($maxX, min($x, $y)); $maxY = max($maxY, max($x, $y)); $totalZ += $z * $cartItem['basket_quantity']; $totalSizeWeight += $product['weight'] * $cartItem['basket_quantity']; } else { if ($product['volume']) { $totalVolume += $product['volume'] * $cartItem['basket_quantity']; $totalVolumeWeight += $product['weight'] * $cartItem['basket_quantity']; } } } $senderCity = v($cfg['pc_shop_delivery_sdek']['sdek_sender_city'], 44); $destinationCity = $params['delivery_form_data']['city']; $date = date('Y-m-d'); $tariffId = v($cfg['pc_shop_delivery_sdek']['sdek_tariff_id'], null); $deliveryMode = v($cfg['pc_shop_delivery_sdek']['sdek_delivery_mode'], null); if (!$tariffId && !$deliveryMode) { $deliveryMode = 3; } // by default use warehouse-house $key = md5("{$senderCity}.{$destinationCity}.{$date}.{$tariffId}.{$deliveryMode}.{$totalSizeWeight}.{$maxX}.{$maxY}.{$totalZ}.{$totalVolumeWeight}.{$totalVolume}"); if (($calcData = $cache->get($key)) === null) { try { $calc = new CalculatePriceDeliveryCdek(); if ($cfg['pc_shop_delivery_sdek']['sdek_login']) { $calc->setAuth($cfg['pc_shop_delivery_sdek']['sdek_login'], $cfg['pc_shop_delivery_sdek']['sdek_password']); } $calc->setSenderCityId($senderCity); $calc->setReceiverCityId($destinationCity); $calc->setDateExecute($date); if ($tariffId) { $calc->setTariffId($tariffId); } if ($deliveryMode) { $calc->setModeDeliveryId($deliveryMode); } if ($totalSizeWeight > 0) { $calc->addGoodsItemBySize($totalSizeWeight, $maxY / 10, $maxX / 10, $totalZ / 10); } // divided by 10 because it must be in cm. if ($totalVolumeWeight > 0) { $calc->addGoodsItemByVolume($totalVolumeWeight, $totalVolume); } if ($calc->calculate()) { $calcData = $calc->getResult(); } else { $calcData = $calc->getError(); } $cacheDuration = 3600; } catch (\Exception $ex) { $calcData = array('error' => array(array('text' => strtr($core->Get_plugin_variable('error_internal', 'pc_shop_delivery_sdek'), array('{error}' => $ex->getMessage()))))); $cacheDuration = 600; } $cache->set($key, $calcData, $cacheDuration); } $data['delivery_info']['package'] = array('totalSizeWeight' => $totalSizeWeight, 'dimensions' => array($maxX, $maxY, $totalZ), 'totalVolumeWeight' => $totalVolumeWeight, 'volume' => $totalVolume); if (isset($calcData['result'])) { $result = $calcData['result']; $price = $result['price']; $cod = array_key_exists('cashOnDelivery', $result) ? $result['cashOnDelivery'] : null; $baseCur = $shop->price->get_base_currency(); if ($baseCur != $result['currency']) { $price = $shop->price->get_converted_price_in_base_currency($price, $result['currency'], true); if ($cod !== null) { $cod = $shop->price->get_converted_price_in_base_currency($cod, $result['currency'], true); } } $data['order_delivery_price'] = $shop->price->get_price_in_user_currency($price); if ($cod !== null) { $data['order_cod_price'] = $shop->price->get_price_in_user_currency($cod); } $data['delivery_info']['period_min'] = $result['deliveryPeriodMin']; $data['delivery_info']['period_max'] = $result['deliveryPeriodMax']; $data['delivery_info']['date_min'] = $result['deliveryDateMin']; $data['delivery_info']['date_max'] = $result['deliveryDateMax']; if (!$price && $result['price'] || !$cod && array_key_exists('cashOnDelivery', $result) && $result['cashOnDelivery']) { $data['errors'][] = $core->Get_variable('error_impossible_to_calculate', null, 'pc_shop_delivery_sdek'); } } else { if (isset($calcData['error']) && is_array($calcData['error'])) { foreach ($calcData['error'] as $error) { $data['errors'][] = $error['text']; } } } } else { $data['errors'][] = $core->Get_variable('error_city_required', null, 'pc_shop_delivery_sdek'); } }
function quote($method = '') { global $order, $cart, $shipping_weight, $own_city_id; $calc = new CalculatePriceDeliveryCdek(); try { if ($this->tax_class > 0) { $this->quotes['tax'] = vam_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']); } //устанавливаем город-отправитель $check_query = vam_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key='MODULE_SHIPPING_SDEK_FROM_CITY'"); $check = vam_db_fetch_array($check_query); $own_city_name = $check['configuration_value']; //echo 'Grad:'.$own_city_name.'<br>'; $city_check_query = vam_db_query("select city_id from city where city_name='" . $own_city_name . "'"); $city_check = vam_db_fetch_array($city_check_query); $own_city_id = $city_check['city_id']; $calc->setSenderCityId($own_city_id); //echo 'Grad:'.$own_city_id.'<br>'; //устанавливаем город-получатель $city_shipping_to_name = $order->delivery['city']; $city_check_query = vam_db_query("select city_id from city where city_name='" . $city_shipping_to_name . "'"); $city_check = vam_db_fetch_array($city_check_query); $city_shipping_id = $city_check['city_id']; $calc->setReceiverCityId($city_shipping_id); //echo 'Grad primaoca:'.$city_shipping_id.'<br>'; //устанавливаем дату планируемой отправки $shipping_date = date("Y-m-d"); $calc->setDateExecute($shipping_date); //echo 'Datum:'.$shipping_date.'<br>'; //устанавливаем тариф по-умолчанию $calc->setTariffId('1'); //устанавливаем режим доставки $calc->setModeDeliveryId('1'); //добавляем места в отправление if ($shipping_weight == 0) { $shipping_weight = MODULE_SHIPPING_SDEK_DEFAULT_SHIPPING_WEIGHT; //echo 'Tezina:'.$shipping_weight.'<br>'; } $calc->addGoodsItemBySize($shipping_weight, '40', '50', '60'); //$calc->addGoodsItemByVolume('0.1', '0.1'); if ($calc->calculate() === true) { $res = $calc->getResult(); } /* echo 'Цена доставки: ' . $res['result']['price'] . 'руб.<br />'; echo 'Срок доставки: ' . $res['result']['deliveryPeriodMin'] . '-' . $res['result']['deliveryPeriodMax'] . ' дн.<br />'; echo 'Планируемая дата доставки: c ' . $res['result']['deliveryDateMin'] . ' по ' . $res['result']['deliveryDateMax'] . '.<br />'; echo 'id тарифа, по которому произведён расчёт: ' . $res['result']['tariffId'] . '.<br />'; if(array_key_exists('cashOnDelivery', $res['result'])) { echo 'Ограничение оплаты наличными, от (руб): ' . $res['result']['cashOnDelivery'] . '.<br />'; } } else { $err = $calc->getError(); if( isset($err['error']) && !empty($err) ) { var_dump($err); foreach($err['error'] as $e) { echo 'Код ошибки: ' . $e['code'] . '.<br />'; echo 'Текст ошибки: ' . $e['text'] . '.<br />'; } } } */ } catch (Exception $e) { echo 'Ошибка: ' . $e->getMessage() . "<br />"; } if ($method != '') { $title = strip_tags($title); } $this->quotes = array('id' => $this->code, 'module' => MODULE_SHIPPING_SDEK_TEXT_TITLE); $this->quotes['methods'] = array(array('id' => $this->code, 'title' => MODULE_SHIPPING_SDEK_TEXT_NOTE, 'cost' => $res['result']['price'])); if (vam_not_null($this->icon)) { $this->quotes['icon'] = vam_image($this->icon, $this->title); } return $this->quotes; }
$this->init_settings(); // This is part of the settings API. Loads settings you previously init. // Save settings in admin if you have any defined add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options')); } /** * calculate_shipping function. * * @access public * @param mixed $package * @return void */ public function calculate_shipping($package = array()) { //подключаем файл с классом CalculatePriceDeliveryCdek include_once TEMPLATEPATH . "/calc_deliv_cdek_js/CalculatePriceDeliveryCdek.php"; try { //создаём экземпляр объекта CalculatePriceDeliveryCdek $calc = new CalculatePriceDeliveryCdek(); //Авторизация. Для получения логина/пароля (в т.ч. тестового) обратитесь к разработчикам СДЭК --> //$calc->setAuth('authLoginString', 'passwordString'); if (isset($_REQUEST['calc_shipping'])) { foreach ($_REQUEST as $k => $v) { $_SESSION[$k] = $_REQUEST[$k]; } } $labb = 'Доставка'; $res['result'] = 0; //устанавливаем город-отправитель $calc->setSenderCityId("152"); //устанавливаем город-получатель $calc->setReceiverCityId($_SESSION['receiverCityId']); //устанавливаем дату планируемой отправки $calc->setDateExecute($_SESSION['dateExecute']); //устанавливаем тариф по-умолчанию $calc->setTariffId('11'); //задаём список тарифов с приоритетами // $calc->addTariffPriority($_REQUEST['tariffList1']); // $calc->addTariffPriority($_REQUEST['tariffList2']); //устанавливаем режим доставки $calc->setModeDeliveryId($_SESSION['modeId']); //добавляем места в отправление $total_items = isset($_SESSION['total_items']) ? $_SESSION['total_items'] : 0; global $woocommerce; $total_weight = (int) $total_items * (double) $_SESSION['weight1']; $calc->addGoodsItemBySize($total_weight, $_SESSION['length1'], $_SESSION['width1'], $_SESSION['height1']); //$calc->addGoodsItemByVolume($_REQUEST['weight2'], $_REQUEST['volume2']); if ($calc->calculate() === true) { $res = $calc->getResult(); //$res['result']['price'] = round( $res['result']['price'] + $res['result']['price'], -1 ); $pr = 5; // Проценты $labb = 'EMS'; $code = getCityCode(trim(mb_strtolower($_SESSION['country']))); $total_items = isset($_SESSION['total_items']) ? $_SESSION['total_items'] : 0; if (sizeof($woocommerce->cart->get_cart()) > 0) { foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) { $total_items = (int) $values['quantity']; } } $total_weight = (int) $total_items * (double) $_SESSION['total_items']; $total_weight = $_SESSION['total_items'] * 0.025; $json = file_get_contents("http://emspost.ru/api/rest?method=ems.calculate&from=city--kaliningrad&to={$code}&weight={$total_weight}"); $rh = fopen('log.txt', 'a+'); fputs($rh, $json . "\t" . $_SESSION['country'] . "\n"); fputs($rh, $total_weight . " " . $code . "\n"); $json = json_decode($json); $json = $json->rsp; $aa = $json->price; $aa = round($aa); $aa = max($aa * 1.05, 790); $bbb = ceil($aa / 10) * 10; fclose($rh); if ($_SESSION['calc_tip'] == '2') { $labb = 'Почта'; $res['result']['price'] = $woocommerce->cart->cart_contents_total * ($pr / 100); $res['result']['price'] = max(min(1700, $res['result']['price']), 350); $res['result']['price'] = round($res['result']['price'], -1); $bbb = ceil($res['result']['price'] / 10) * 10; } //$bbb=$_SESSION['calc_tip']; if ($_SESSION['country'] == '444') { $t = $total_weight; switch (true) { case $t > 0 and $t <= 1.5: // дапазон чисел $bbb = 1755; break; case $t > 1.5 and $t <= 3: // дапазон чисел $bbb = 2145; break; case $t > 3 and $t <= 6: // дапазон чисел $bbb = 2715; break; case $t > 6 and $t <= 11: // дапазон чисел $bbb = 3655; break; case $t > 11 and $t <= 16: // дапазон чисел $bbb = 4615; break; case $t > 16 and $t <= 20: // дапазон чисел $bbb = 5565; break; } } $html = array("Цена доставки: {$res['result']['price']}"); if (array_key_exists('cashOnDelivery', $res['result'])) { $html[] = "Ограничение оплаты наличными, от (руб): " . $res['result']['cashOnDelivery']; } //printf("<div class='woocommerce-message'>%s</div>", implode("<br/>", $html) ); } else { $err = $calc->getError(); if (isset($err['error']) && !empty($err)) { print "<div class = 'woocommerce-error'>"; //var_dump($err); foreach ($err['error'] as $e) { echo 'Код ошибки: ' . $e['code'] . '.<br />'; echo 'Текст ошибки: ' . $e['text'] . '.<br />'; } print "</div>"; } } //раскомментируйте, чтобы просмотреть исходный ответ сервера // var_dump($calc->getResult()); // var_dump($calc->getError()); global $delta; $rate = array('id' => $this->id, 'label' => $labb, 'cost' => $bbb, 'calc_tax' => 'per_item'); // Register the rate
/** * calculate_shipping function. * * @access public * @param mixed $package * @return void */ public function calculate_shipping($package = array()) { //подключаем файл с классом CalculatePriceDeliveryCdek include_once TEMPLATEPATH . "/calc_deliv_cdek_js/CalculatePriceDeliveryCdek.php"; try { //создаём экземпляр объекта CalculatePriceDeliveryCdek $calc = new CalculatePriceDeliveryCdek(); //Авторизация. Для получения логина/пароля (в т.ч. тестового) обратитесь к разработчикам СДЭК --> //$calc->setAuth('authLoginString', 'passwordString'); if (isset($_REQUEST['calc_shipping'])) { foreach ($_REQUEST as $k => $v) { $_SESSION[$k] = $_REQUEST[$k]; } } //устанавливаем город-отправитель $calc->setSenderCityId("152"); //устанавливаем город-получатель $calc->setReceiverCityId($_SESSION['receiverCityId']); //устанавливаем дату планируемой отправки $calc->setDateExecute($_SESSION['dateExecute']); //устанавливаем тариф по-умолчанию $calc->setTariffId('11'); //задаём список тарифов с приоритетами // $calc->addTariffPriority($_REQUEST['tariffList1']); // $calc->addTariffPriority($_REQUEST['tariffList2']); //устанавливаем режим доставки $calc->setModeDeliveryId($_SESSION['modeId']); //добавляем места в отправление $total_items = isset($_SESSION['total_items']) ? $_SESSION['total_items'] : 0; $total_weight = (int) $total_items * (double) $_SESSION['weight1']; $calc->addGoodsItemBySize($total_weight, $_SESSION['length1'], $_SESSION['width1'], $_SESSION['height1']); //$calc->addGoodsItemByVolume($_REQUEST['weight2'], $_REQUEST['volume2']); if ($calc->calculate() === true) { $res = $calc->getResult(); //$res['result']['price'] = round( $res['result']['price'] + 0.00 * $res['result']['price'], -1 ); global $woocommerce; $res['result']['price'] = $woocommerce->cart->cart_contents_total * 0.08; $res['result']['price'] = max(min(1950, $res['result']['price']), 350); $res['result']['price'] = round($res['result']['price'], -1); file_put_contents(dirname(__FILE__) . "/log.txt", json_encode($woocommerce->cart)); $html = array("Цена доставки: {$res['result']['price']}"); if (array_key_exists('cashOnDelivery', $res['result'])) { $html[] = "Ограничение оплаты наличными, от (руб): " . $res['result']['cashOnDelivery']; } //printf("<div class='woocommerce-message'>%s</div>", implode("<br/>", $html) ); } else { $err = $calc->getError(); if (isset($err['error']) && !empty($err)) { print "<div class = 'woocommerce-error'>"; //var_dump($err); foreach ($err['error'] as $e) { echo 'Код ошибки: ' . $e['code'] . '.<br />'; echo 'Текст ошибки: ' . $e['text'] . '.<br />'; } print "</div>"; } } //раскомментируйте, чтобы просмотреть исходный ответ сервера // var_dump($calc->getResult()); // var_dump($calc->getError()); global $delta; $rate = array('id' => $this->id, 'label' => $this->title, 'cost' => $res['result']['price'] + $delta, 'calc_tax' => 'per_order'); // Register the rate $this->add_rate($rate); } catch (Exception $e) { echo 'Ошибка: ' . $e->getMessage() . "<br />"; } }
echo "<br />Данные из формы: <br /><pre>"; var_dump($_REQUEST); echo "</pre>"; //подключаем файл с классом CalculatePriceDeliveryCdek include_once "CalculatePriceDeliveryCdek.php"; try { //создаём экземпляр объекта CalculatePriceDeliveryCdek $calc = new CalculatePriceDeliveryCdek(); //Авторизация. Для получения логина/пароля (в т.ч. тестового) обратитесь к разработчикам СДЭК --> //$calc->setAuth('authLoginString', 'passwordString'); //устанавливаем город-отправитель $calc->setSenderCityId($_REQUEST['senderCityId']); //устанавливаем город-получатель $calc->setReceiverCityId($_REQUEST['receiverCityId']); //устанавливаем дату планируемой отправки $calc->setDateExecute($_REQUEST['dateExecute']); //устанавливаем тариф по-умолчанию $calc->setTariffId('137'); //задаём список тарифов с приоритетами // $calc->addTariffPriority($_REQUEST['tariffList1']); // $calc->addTariffPriority($_REQUEST['tariffList2']); //устанавливаем режим доставки $calc->setModeDeliveryId($_REQUEST['modeId']); //добавляем места в отправление $calc->addGoodsItemBySize($_REQUEST['weight1'], $_REQUEST['length1'], $_REQUEST['width1'], $_REQUEST['height1']); $calc->addGoodsItemByVolume($_REQUEST['weight2'], $_REQUEST['volume2']); if ($calc->calculate() === true) { $res = $calc->getResult(); echo 'Цена доставки: ' . $res['result']['price'] . 'руб.<br />'; echo 'Срок доставки: ' . $res['result']['deliveryPeriodMin'] . '-' . $res['result']['deliveryPeriodMax'] . ' дн.<br />'; echo 'Планируемая дата доставки: c ' . $res['result']['deliveryDateMin'] . ' по ' . $res['result']['deliveryDateMax'] . '.<br />';