public function checkAvailableShipCountries(Mage_Shipping_Model_Rate_Request $request)
 {
     $speCountriesAllow = $this->getConfigData('sallowspecific');
     /*
      * for specific countries, the flag will be 1
      */
     if ($speCountriesAllow && $speCountriesAllow == 1) {
         $showMethod = $this->getConfigData('showmethod');
         $availableCountries = array();
         if ($this->getConfigData('specificcountry')) {
             $availableCountries = explode(',', $this->getConfigData('specificcountry'));
         }
         if ($availableCountries && in_array($request->getDestCountryId(), $availableCountries)) {
             return $this;
         } elseif ($showMethod && (!$availableCountries || $availableCountries && !in_array($request->getDestCountryId(), $availableCountries))) {
             $error = Mage::getModel('shipping/rate_result_error');
             $error->setCarrier($this->_code);
             $error->setCarrierTitle($this->getConfigData('title'));
             $errorMsg = $this->getConfigData('specificerrmsg');
             $error->setErrorMessage($errorMsg ? $errorMsg : Mage::helper('shipping')->__('The shipping module is not available for selected delivery country'));
             return $error;
         } else {
             /*
              * The admin set not to show the shipping module if the devliery country is not within specific countries
              */
             return false;
         }
     }
     return $this;
 }
Exemple #2
0
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     }
     if ($request->getFedexAccount()) {
         $account = $request->getFedexAccount();
     } else {
         $account = $this->getConfigData('account');
     }
     $r->setAccount($account);
     if ($request->getFedexDropoff()) {
         $dropoff = $request->getFedexDropoff();
     } else {
         $dropoff = $this->getConfigData('dropoff');
     }
     $r->setDropoffType($dropoff);
     if ($request->getFedexPackaging()) {
         $packaging = $request->getFedexPackaging();
     } else {
         $packaging = $this->getConfigData('packaging');
     }
     $r->setPackaging($packaging);
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     }
     $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     } else {
     }
     $r->setWeight($request->getPackageWeight());
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $this->_rawRequest = $r;
     return $this;
 }
 /**
  * Collects the shipping rates for Australia Post from the REST API.
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return Mage_Shipping_Model_Rate_Result|bool
  */
 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
 {
     // Check if this method is active
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     // Check if this method is even applicable (shipping from Australia)
     $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $request->getStore());
     if ($origCountry != Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE) {
         return false;
     }
     if ($this->_client == null) {
         return false;
     }
     $fromPostcode = (int) Mage::getStoreConfig('shipping/origin/postcode', $this->getStore());
     $toPostcode = (int) $request->getDestPostcode();
     $destCountry = $request->getDestCountryId();
     if (!$destCountry) {
         $destCountry = Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE;
     }
     /** @var Fontis_Australia_Helper_Australiapost $helper */
     $helper = Mage::helper('australia/australiapost');
     $weight = (int) $request->getPackageWeight();
     $length = (int) $helper->getAttribute($request, 'length');
     $width = (int) $helper->getAttribute($request, 'width');
     $height = (int) $helper->getAttribute($request, 'height');
     $extraCover = max((int) $request->getPackageValue(), self::EXTRA_COVER_LIMIT);
     $config = array('from_postcode' => $fromPostcode, 'to_postcode' => $toPostcode, 'length' => $length, 'width' => $width, 'height' => $height, 'weight' => $weight, 'country_code' => $destCountry);
     $this->_getQuotes($extraCover, $config);
     $_result = $this->_result->asArray();
     if (empty($_result)) {
         return false;
     }
     return $this->_result;
 }
 protected function _getCourierRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $package_cost = $request->getPackageValueWithDiscount();
     $shipping_settings = Mage::helper('altteam_qwintry')->getShippingSettings();
     $pounds = $request->getPackageWeight();
     $currencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();
     $currency = $request->getPackageCurrency();
     if (in_array('USD', $currencies)) {
         Mage::helper('directory')->currencyConvert($package_cost, $currency->getCurrencyCode(), 'USD');
     } elseif ($currency->getCurrencyCode() == 'EUR') {
         $package_cost = $package_cost * 1.097;
     } elseif ($currency->getCurrencyCode() == 'RMB') {
         $package_cost = $package_cost * 1.157;
     }
     $data = array('params' => array('method' => 'qwair', 'hub_code' => empty($shipping_settings['hub']) ? 'DE1' : $shipping_settings['hub'], 'insurance' => false, 'retail_pricing' => false, 'weight' => $pounds > 0.1 ? $pounds : (empty($shipping_settings['default_weight']) ? 4 : $shipping_settings['default_weight']), 'items_value' => $package_cost, 'addr_country' => $request->getDestCountryId(), 'addr_zip' => $request->getDestPostcode(), 'addr_line1' => $request->getDestStreet(), 'addr_line2' => '', 'addr_city' => $request->getDestCity(), 'addr_state' => $request->getDestRegionCode()));
     $response = Mage::helper('altteam_qwintry')->sendApiRequest('cost', $data);
     if (!$response || empty($response->success) || !$response->success) {
         return false;
     }
     $rate = Mage::getModel('shipping/rate_result_method');
     $rate->setCarrier($this->_code);
     $rate->setCarrierTitle($this->getConfigData('title'));
     $rate->setMethod('courier');
     $rate->setMethodTitle('Courier');
     $rate->setPrice($response->result->total);
     $rate->setCost(0);
     return $rate;
 }
Exemple #5
0
 public function getRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $read = $this->_getReadAdapter();
     $write = $this->_getWriteAdapter();
     $select = $read->select()->from($this->getMainTable());
     /*
     //commented out code since we don't want to get state by using zip code
     if (!$request->getDestCountryId() && !$request->getDestRegionId()) {
     
         // assuming that request is coming from shopping cart
         // for shipping prices pre-estimation...
     
         // also probably it will be required to move this part to
         // Sales/Model/Quote/Address.php !
     
         $selectCountry = $read->select()->from(Mage::getSingleton('core/resource')->getTableName('usa/postcode'), array('country_id', 'region_id'));
         $selectCountry->where('postcode=?', $request->getDestPostcode());
         $selectCountry->limit(1);
         $countryRegion = $read->fetchRow($selectCountry);
         $region = $read->quote($countryRegion['region_id']);
         $country = $read->quote($countryRegion['country_id']);
     } else {
         $region = $read->quote($request->getDestRegionId());
         $country = $read->quote($request->getDestCountryId());
     }
     */
     $region = $read->quote($request->getDestRegionId());
     $country = $read->quote($request->getDestCountryId());
     $zip = $read->quote($request->getDestPostcode());
     $select->where("(dest_zip={$zip})\n                     OR (dest_region_id={$region} AND dest_zip='')\n                     OR (dest_country_id={$country} AND dest_region_id='0' AND dest_zip='')\n                     OR (dest_country_id='0' AND dest_region_id='0' AND dest_zip='')");
     if (is_array($request->getConditionName())) {
         $i = 0;
         foreach ($request->getConditionName() as $conditionName) {
             if ($i == 0) {
                 $select->where('condition_name=?', $conditionName);
             } else {
                 $select->orWhere('condition_name=?', $conditionName);
             }
             $select->where('condition_value<=?', $request->getData($conditionName));
             $i++;
         }
     } else {
         $select->where('condition_name=?', $request->getConditionName());
         $select->where('condition_value<=?', $request->getData($request->getConditionName()));
     }
     $select->where('website_id=?', $request->getWebsiteId());
     $select->order('condition_value DESC')->limit(1);
     $row = $read->fetchRow($select);
     return $row;
 }
Exemple #6
0
 public function setBaseRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $r = new Varien_Object();
     $r->setAllowedMethods($this->getConfigData('allowed_methods'));
     $r->setWeight(ceil($request->getPackageWeight() * (double) $this->getConfigData('wt_units')));
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     $r->setDestCountryIso3(Mage::getModel('directory/country')->load($destCountry)->getIso3Code());
     $r->setDestCountryName(Mage::getModel('directory/country')->load($destCountry)->getName());
     $r->setMailClass($this->getDeliveryServiceLevel($destCountry));
     if ($request->getDestPostcode()) {
         $r->setDestPostal('US' == $r->getDestCountry() ? substr($request->getDestPostcode(), 0, 5) : $request->getDestPostcode());
     }
     return $r;
 }
 public function getNewRate(Mage_Shipping_Model_Rate_Request $request, $zipRangeSet = 0)
 {
     $newdata = array();
     $collection = Mage::getResourceModel('matrixrate_shipping/carrier_matrixrate_collection');
     $collection->setConditionFilter($request->getConditionName())->setWebsiteFilter($request->getWebsiteId());
     $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns(array('website_id', 'zone', 'condition_name', 'condition_from_value', 'condition_to_value', 'shipping_charge'));
     $collection->getSelect()->join(array('zones' => 'shipping_zones'), "zones.zone=s.zone and zones.delivery_type='standard' and zones.country_code='" . $request->getDestCountryId() . "' AND (condition_from_value<='" . $request->getData($request->getConditionName()) . "') AND (condition_to_value>='" . $request->getData($request->getConditionName()) . "')", array('delivery_type', 'shipping_provider'));
     //print $collection->getSelect();die;
     if ($collection->count()) {
         foreach ($collection->getData() as $data) {
             $newdata[] = $data;
         }
     }
     return $newdata;
 }
Exemple #8
0
 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
 {
     if (!Mage::getStoreConfig('carriers/' . $this->_code . '/active')) {
         return false;
     }
     $destinationData = array('city' => ucwords(strtolower($request->getDestCity())), 'country_id' => $request->getDestCountryId(), 'postcode' => $request->getDestPostcode());
     $quoteId = Mage::getSingleton('checkout/session')->getQuoteId();
     $quote = Mage::getModel("sales/quote")->load($quoteId);
     $result = Mage::getModel('aramexshipping/shipping')->getRatesAndPackages($quote, true, $destinationData);
     $error = $result['error'];
     $error_msg = isset($result['error_msg']) ? 'Aramex Error: ' . $result['error_msg'] : '';
     $price = $result['price'];
     $methodTitle = $request->getFreeShipping() ? Mage::helper('aramexshipping')->__('Free shipping applied') : '';
     $handling = Mage::getStoreConfig('carriers/' . $this->_code . '/handling');
     $result = Mage::getModel('shipping/rate_result');
     if (!$error && $price > 0 || !$error && $request->getFreeShipping()) {
         $method = Mage::getModel('shipping/rate_result_method');
         $method->setCarrier($this->_code);
         $method->setMethod($this->_code);
         $method->setCarrierTitle($this->getConfigData('title'));
         $method->setMethodTitle($methodTitle);
         $method->setPrice($price);
         $method->setCost($price);
         $result->append($method);
     } else {
         $error = Mage::getModel('shipping/rate_result_error');
         $error->setCarrier($this->_code);
         $error->setCarrierTitle($this->getConfigData('title'));
         $error->setErrorMessage($error_msg ? $error_msg : $this->getConfigData('specificerrmsg'));
         $result->append($error);
         if ($error_msg) {
             Mage::helper('aramexshipping')->log($error_msg, '', 'aramex_collect_rates');
             Mage::helper('aramexshipping')->sendLogEmail(array('subject' => 'Collect Rates Error Log', 'content' => $error_msg));
         }
     }
     return $result;
 }
 /**
  * Fetch rate from the table for selected shipping address.
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return array
  */
 public function getRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $adapter = $this->_getReadAdapter();
     $bind = array(':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':postcode' => $request->getDestPostcode());
     $select = $adapter->select()->from($this->getMainTable())->where('website_id = :website_id')->order(array('dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC', 'condition_value DESC'))->limit(1);
     // Render destination condition
     $orWhere = '(' . implode(') OR (', array("dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = '*'", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'", "dest_country_id = '0' AND dest_region_id = :region_id AND dest_zip = '*'", "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = '*'", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'")) . ')';
     $select->where($orWhere);
     // Render condition by condition name
     if (is_array($request->getConditionName())) {
         $orWhere = array();
         $i = 0;
         foreach ($request->getConditionName() as $conditionName) {
             $bindNameKey = sprintf(':condition_name_%d', $i);
             $bindValueKey = sprintf(':condition_value_%d', $i);
             $orWhere[] = "(condition_name = {$bindNameKey} AND condition_value <= {$bindValueKey})";
             $bind[$bindNameKey] = $conditionName;
             $bind[$bindValueKey] = $request->getData($conditionName);
             $i++;
         }
         if ($orWhere) {
             $select->where(implode(' OR ', $orWhere));
         }
     } else {
         $bind[':condition_name'] = $request->getConditionName();
         $bind[':condition_value'] = $request->getData($request->getConditionName());
         $select->where('condition_name = :condition_name');
         $select->where('condition_value <= :condition_value');
     }
     $result = $adapter->fetchRow($select, $bind);
     // Normalize destination zip code
     if ($result && $result['dest_zip'] == '*') {
         $result['dest_zip'] = '';
     }
     return $result;
 }
Exemple #10
0
 public function getRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $read = $this->_getReadAdapter();
     $postcode = $request->getDestPostcode();
     $table = $this->getMainTable();
     $storeId = $request->getStoreId();
     $insuranceStep = (double) Mage::getStoreConfig('carriers/eparcel/insurance_step', $storeId);
     $insuranceCostPerStep = (double) Mage::getStoreConfig('carriers/eparcel/insurance_cost_per_step', $storeId);
     $signatureRequired = Mage::getStoreConfigFlag('carriers/eparcel/signature_required', $storeId);
     if ($signatureRequired) {
         $signatureCost = (double) Mage::getStoreConfig('carriers/eparcel/signature_cost', $storeId);
     } else {
         $signatureCost = 0;
     }
     for ($j = 0; $j < 5; $j++) {
         $select = $read->select()->from($table);
         // Support for Multi Warehouse Extension.
         if ($request->getWarehouseId() > 0) {
             $select->where('stock_id = ?', $request->getWarehouseId());
         }
         switch ($j) {
             case 0:
                 $select->where($read->quoteInto(" (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=? ", $request->getDestRegionId()) . $read->quoteInto(" AND dest_zip=?) ", $postcode));
                 break;
             case 1:
                 $select->where($read->quoteInto("  (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=? AND dest_zip='0000') ", $request->getDestRegionId()));
                 break;
             case 2:
                 $select->where($read->quoteInto("  (dest_country_id=? AND dest_region_id='0' AND dest_zip='0000') ", $request->getDestCountryId()));
                 break;
             case 3:
                 $select->where($read->quoteInto("  (dest_country_id=? AND dest_region_id='0' ", $request->getDestCountryId()) . $read->quoteInto("  AND dest_zip=?) ", $postcode));
                 break;
             case 4:
                 $select->where("  (dest_country_id='0' AND dest_region_id='0' AND dest_zip='0000')");
                 break;
         }
         if (is_array($request->getConditionName())) {
             $i = 0;
             foreach ($request->getConditionName() as $conditionName) {
                 if ($i == 0) {
                     $select->where('condition_name=?', $conditionName);
                 } else {
                     $select->orWhere('condition_name=?', $conditionName);
                 }
                 $select->where('condition_from_value<=?', $request->getData($conditionName));
                 $select->where('condition_to_value>=?', $request->getData($conditionName));
                 $i++;
             }
         } else {
             $select->where('condition_name=?', $request->getConditionName());
             $select->where('condition_from_value<=?', $request->getData($request->getConditionName()));
             $select->where('condition_to_value>=?', $request->getData($request->getConditionName()));
         }
         $select->where('website_id=?', $request->getWebsiteId());
         $select->order('dest_country_id DESC');
         $select->order('dest_region_id DESC');
         $select->order('dest_zip DESC');
         $select->order('condition_from_value DESC');
         // pdo has an issue. we cannot use bind
         $newdata = array();
         $row = $read->fetchAll($select);
         if (!empty($row) && $j < 5) {
             // have found a result or found nothing and at end of list!
             foreach ($row as $data) {
                 try {
                     $price = (double) $data['price'];
                     // add per-Kg cost
                     $conditionValue = (double) $request->getData($request->getConditionName());
                     $price += (double) $data['price_per_kg'] * $conditionValue;
                     // add signature cost
                     $price += $signatureCost;
                     // add version without insurance
                     $data['price'] = (string) $price;
                     $newdata[] = $data;
                     if (Mage::getStoreConfig('carriers/eparcel/insurance_enable', $storeId)) {
                         // add version with insurance
                         // work out how many insurance 'steps' we have
                         $steps = ceil($request->getPackageValue() / $insuranceStep);
                         // add on number of 'steps' multiplied by the
                         // insurance cost per step
                         $insuranceCost = $insuranceCostPerStep * $steps;
                         $price += $insuranceCost;
                         $data['price'] = (string) $price;
                         $data['delivery_type'] .= " with TransitCover";
                         $newdata[] = $data;
                     }
                 } catch (Exception $e) {
                     Mage::log($e->getMessage());
                 }
             }
             break;
         }
     }
     return $newdata;
 }
Exemple #11
0
 /**
  * Return table rate array or false by rate request
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return array|false
  */
 public function getRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $adapter = $this->_getReadAdapter();
     $bind = array(':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => $request->getDestRegionId());
     $select = $adapter->select()->from($this->getMainTable())->where('website_id=:website_id')->order(array('dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC'))->limit(1);
     // render destination condition
     $orWhere = '(' . implode(') OR (', array("dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip like '{$request->getDestPostcode()}%'", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip like '{$request->getDestPostcode()}%'", "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = ''")) . ')';
     $select->where($orWhere);
     // render condition by condition name
     if (is_array($request->getConditionName())) {
         $orWhere = array();
         $i = 0;
         foreach ($request->getConditionName() as $conditionName) {
             $bindNameKey = sprintf(':condition_name_%d', $i);
             $bindValueKey = sprintf(':condition_value_%d', $i);
             $orWhere[] = "(condition_name = {$bindNameKey} AND condition_value <= {$bindValueKey})";
             $bind[$bindNameKey] = $conditionName;
             $bind[$bindValueKey] = $request->getData($conditionName);
             $i++;
         }
         if ($orWhere) {
             $select->where(implode(' OR ', $orWhere));
         }
     } else {
         $bind[':condition_name'] = $request->getConditionName();
         $bind[':condition_value'] = $request->getData($request->getConditionName());
         $select->where('condition_name = :condition_name');
         $select->where('condition_value <= :condition_value');
     }
     //if( $_SERVER['REMOTE_ADDR'] == '193.108.122.187') { mage::D($bind ); mage::d($select->__toString()); }
     return $adapter->fetchRow($select, $bind);
 }
 private function _getProductionShipmentFields(Mage_Shipping_Model_Rate_Request $mgrequest)
 {
     $regionId = $mgrequest->getRegionId();
     $region = Mage::getModel('directory/region')->load($regionId);
     $request->Shipment->SenderInformation->Address->Name = "Aaron Summer";
     //$request->Shipment->SenderInformation->Address->StreetNumber = "1234";
     $request->Shipment->SenderInformation->Address->StreetName = $mgrequest->getStreet();
     $request->Shipment->SenderInformation->Address->City = $mgrequest->getCity();
     $request->Shipment->SenderInformation->Address->Province = $region->getCode();
     $request->Shipment->SenderInformation->Address->Country = $mgrequest->getCountryId();
     $request->Shipment->SenderInformation->Address->PostalCode = $mgrequest->getPostcode();
     $request->Shipment->SenderInformation->Address->PhoneNumber->CountryCode = "1";
     $request->Shipment->SenderInformation->Address->PhoneNumber->AreaCode = "905";
     $request->Shipment->SenderInformation->Address->PhoneNumber->Phone = substr("123456789", -7);
     //Populate the Desination Information
     $request->Shipment->ReceiverInformation->Address->Name = "Aaron Summer";
     $request->Shipment->ReceiverInformation->Address->StreetName = $mgrequest->getDestStreet();
     $request->Shipment->ReceiverInformation->Address->City = $mgrequest->getDestCity();
     $regionId = $mgrequest->getDestRegionId();
     $region = Mage::getModel('directory/region')->load($regionId);
     $request->Shipment->ReceiverInformation->Address->Province = $region->getCode();
     $request->Shipment->ReceiverInformation->Address->Country = $mgrequest->getDestCountryId();
     $request->Shipment->ReceiverInformation->Address->PostalCode = $mgrequest->getDestPostcode();
     $request->Shipment->ReceiverInformation->Address->PhoneNumber->CountryCode = "1";
     $request->Shipment->ReceiverInformation->Address->PhoneNumber->AreaCode = "604";
     $request->Shipment->ReceiverInformation->Address->PhoneNumber->Phone = substr("123456789", -7);
     //Future Dated Shipments - YYYY-MM-DD format
     $request->Shipment->ShipmentDate = Mage::getModel('core/date')->date('Y-m-d');
     //Populate the Package Information
     $request->Shipment->PackageInformation->TotalWeight->Value = $mgrequest->getPackageWeight();
     $request->Shipment->PackageInformation->TotalWeight->WeightUnit = "lb";
     $request->Shipment->PackageInformation->TotalPieces = $mgrequest->getPackageQty();
     $request->Shipment->PackageInformation->ServiceID = "PurolatorExpress";
     //Populate the Payment Information
     $request->Shipment->PaymentInformation->PaymentType = "Sender";
     $request->Shipment->PaymentInformation->BillingAccountNumber = $this->BILLING_ACCOUNT;
     $request->Shipment->PaymentInformation->RegisteredAccountNumber = $this->REGISTERED_ACCOUNT;
     //Populate the Pickup Information
     $request->Shipment->PickupInformation->PickupType = "DropOff";
     $request->ShowAlternativeServicesIndicator = "true";
     //OriginSignatureNotRequired
     $request->Shipment->PackageInformation->OptionsInformation->Options->OptionIDValuePair->ID = "OriginSignatureNotRequired";
     $request->Shipment->PackageInformation->OptionsInformation->Options->OptionIDValuePair->Value = "true";
     return $request;
 }
Exemple #13
0
 public function getNewRate(Mage_Shipping_Model_Rate_Request $request, $zipRangeSet = 0)
 {
     $read = $this->_getReadAdapter();
     $write = $this->_getWriteAdapter();
     $postcode = $request->getDestPostcode();
     $table = Mage::getSingleton('core/resource')->getTableName('matrixrate_shipping/matrixrate');
     if ($zipRangeSet && is_numeric($postcode)) {
         #  Want to search for postcodes within a range
         $zipSearchString = ' AND ' . $postcode . ' BETWEEN dest_zip AND dest_zip_to )';
     } else {
         $zipSearchString = $read->quoteInto(" AND ? LIKE dest_zip )", $postcode);
     }
     for ($j = 0; $j < 10; $j++) {
         $select = $read->select()->from($table);
         switch ($j) {
             case 0:
                 $select->where($read->quoteInto(" (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=? ", $request->getDestRegionId()) . $read->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  ", $request->getDestCity()) . $zipSearchString);
                 break;
             case 1:
                 $select->where($read->quoteInto(" (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=?  AND dest_city=''", $request->getDestRegionId()) . $zipSearchString);
                 break;
             case 2:
                 $select->where($read->quoteInto(" (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=? ", $request->getDestRegionId()) . $read->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_zip='')", $request->getDestCity()));
                 break;
             case 3:
                 $select->where($read->quoteInto("  (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_region_id='0'", $request->getDestCity()) . $zipSearchString);
                 break;
             case 4:
                 $select->where($read->quoteInto("  (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_region_id='0' AND dest_zip='') ", $request->getDestCity()));
                 break;
             case 5:
                 $select->where($read->quoteInto("  (dest_country_id=? AND dest_region_id='0' AND dest_city='' ", $request->getDestCountryId()) . $zipSearchString);
                 break;
             case 6:
                 $select->where($read->quoteInto("  (dest_country_id=? ", $request->getDestCountryId()) . $read->quoteInto(" AND dest_region_id=? AND dest_city='' AND dest_zip='') ", $request->getDestRegionId()));
                 break;
             case 7:
                 $select->where($read->quoteInto("  (dest_country_id=? AND dest_region_id='0' AND dest_city='' AND dest_zip='') ", $request->getDestCountryId()));
                 break;
             case 8:
                 $select->where("  (dest_country_id='0' AND dest_region_id='0'" . $zipSearchString);
                 break;
             case 9:
                 $select->where("  (dest_country_id='0' AND dest_region_id='0' AND dest_zip='')");
                 break;
         }
         if (is_array($request->getMRConditionName())) {
             $i = 0;
             foreach ($request->getMRConditionName() as $conditionName) {
                 if ($i == 0) {
                     $select->where('condition_name=?', $conditionName);
                 } else {
                     $select->orWhere('condition_name=?', $conditionName);
                 }
                 $select->where('condition_from_value<=?', $request->getData($conditionName));
                 $i++;
             }
         } else {
             $select->where('condition_name=?', $request->getMRConditionName());
             $select->where('condition_from_value<=?', $request->getData($request->getMRConditionName()));
             $select->where('condition_to_value>=?', $request->getData($request->getMRConditionName()));
         }
         $select->where('website_id=?', $request->getWebsiteId());
         if ($filter = $request->getData('filter')) {
             $select->where('filter IN (?)', $filter);
         }
         $select->order('dest_country_id DESC');
         $select->order('dest_region_id DESC');
         $select->order('dest_zip DESC');
         $select->order('condition_from_value DESC');
         /*
         pdo has an issue. we cannot use bind
         */
         $newdata = array();
         $row = $read->fetchAll($select);
         if (!empty($row)) {
             // have found a result or found nothing and at end of list!
             foreach ($row as $data) {
                 $newdata[] = $data;
             }
             break;
         }
     }
     return $newdata;
 }
 /**
  * Collect rates for this shipping method based on information in $request
  *
  * @param Mage_Shipping_Model_Rate_Request $data
  * @return Mage_Shipping_Model_Rate_Result
  */
 public function getMethods(Mage_Shipping_Model_Rate_Request $request, $my_code = false)
 {
     $dest_country = $request->getDestCountryId();
     $dest_region = $request->getDestRegionId();
     $package_value = $request->getPackageValue();
     $shipping_price = 0;
     // 			Mage::log($request->debug(), null, 'test.log');
     // 			Mage::log($exception_regions, null, 'test.log');
     // 			Mage::log($dest_country, null, 'test.log');
     // 			Mage::log($dest_region, null, 'test.log');
     $i = 1;
     $max_price = 0;
     $items = array();
     $cart_products_price_reduction = 0;
     if ($_items = $request->getAllItems()) {
         foreach ($_items as $item) {
             // 					if($item->getProductType() != 'simple') continue;
             // 					Mage::log($i++, null, 'test.log');
             // 					Mage::log($item->debug(), null, 'test.log');
             if ($parent_item_id = $item->getParentItemId()) {
                 continue;
                 // 							$items[$item_id]['free_shipping'] = $item->getMaxFreeShipping();
                 // 							$items[$item_id]['primary_shipping'] = $item->getMaxPrimaryShip();
                 // 							$items[$item_id]['secondary_shipping'] = $item->getMaxSecondaryShip();
             } elseif ($item->getProductType() == 'cartproduct') {
                 continue;
             }
             $p = Mage::getModel('catalog/product')->load($item->getProductId());
             $item_id = $item->getItemId();
             $items[$item_id]['price'] = $item->getPrice();
             $items[$item_id]['sku'] = $item->getSku();
             $items[$item_id]['qty'] = $item->getQty();
             $items[$item_id]['free_shipping'] = $p->getMaxFreeShipping();
             $items[$item_id]['primary_shipping'] = $p->getMaxPrimaryShip();
             $items[$item_id]['secondary_shipping'] = $p->getMaxSecondaryShip();
             if ($item->getPrice() >= $max_price) {
                 $max_price = $item->getPrice();
                 $max_id = $item_id;
             }
             // 					$p = Mage::getModel('catalog/product')->load($item->getProductId());
             // 					$tmp_price = (float) $p->getFreightShipTotal();
             // 					Mage::log($p->getData(), null, 'test.log');
             //          Mage::log($item->debug(), null, 'test.log');
         }
     }
     foreach ($items as $item_id => $item) {
         $qty = (int) $item['qty'];
         $max_done = false;
         for ($i = 1; $i <= $qty; $i++) {
             if (!$max_done && $item_id == $max_id) {
                 $shipping_price += $item['free_shipping'] ? 0 : (double) $item['primary_shipping'];
                 $max_done = true;
                 continue;
             }
             $shipping_price += $item['free_shipping'] ? 0 : (double) $item['secondary_shipping'];
         }
     }
     // 199.5 + 105 + 210
     if ($dest_country == 'CA') {
         $item_percent = (double) Mage::getStoreConfig('carriers/maxshipping/canadian_percent') / 100;
         $duty = (double) Mage::getStoreConfig('carriers/maxshipping/canadian_duty') / 100;
         $tax = (double) Mage::getStoreConfig('carriers/maxshipping/canadian_tax') / 100;
         $shipping_price += $request->getPackagePhysicalValue() * $item_percent;
         $shipping_price += $request->getPackagePhysicalValue() * $duty;
         $shipping_price += $request->getPackagePhysicalValue() * $tax;
         $shipping_price += (double) Mage::getStoreConfig('carriers/maxshipping/canadian_border_fee');
     }
     $methods = array();
     // 			$label = Mage::getStoreConfig('carriers/maxshipping/title');
     $method = Mage::getModel('shipping/rate_result_method');
     $method->setMethodTitle('');
     $method->setCarrier($this->_code);
     $method->setMethod('standard');
     $method->setPrice($shipping_price);
     $methods[] = $method;
     // 			Mage::log($methods, null, 'methods.log');
     return $methods;
 }
    /**
     * @param Mage_Shipping_Model_Rate_Request $requestVar
     * @return array
     */
    private function _submitRequest(Mage_Shipping_Model_Rate_Request $requestVar)
    {
        $shipwireAvailableServices = $this->getConfigData('availableservices');
        $shipwireUsername = $this->getConfigData('shipwire_email');
        $shipwirePassword = $this->getConfigData('shipwire_password');
        $orderCurrencyCode = 'USD';
        /**
         * @var $orderCurrency Mage_Directory_Model_Currency
         */
        $orderCurrency = $requestVar->getBaseCurrency();
        if (!empty($orderCurrency)) {
            $orderCurrencyCode = $orderCurrency->getCode();
        }
        $orderNumber = uniqid('magento', TRUE);
        $shipToAddress1 = $requestVar->getDestStreet();
        $shipToCity = $requestVar->getDestCity();
        $shipToRegion = $requestVar->getDestRegionCode();
        $shipToCountry = $requestVar->getDestCountryId();
        $shiptoPostalCode = $requestVar->getDestPostcode();
        $requestItems = $requestVar->getAllItems();
        $itemXml = $this->_buildRequestItemXml($requestItems);
        $rateRequestXml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE RateRequest SYSTEM "http://www.shipwire.com/exec/download/RateRequest.dtd">
<RateRequest currency="{$orderCurrencyCode}">
  <Username><![CDATA[{$shipwireUsername}]]></Username>
  <Password><![CDATA[{$shipwirePassword}]]></Password>
  <Source>{$this->_version}</Source>
  <Order id="{$orderNumber}">
    <AddressInfo type="ship">
      <Address1><![CDATA[{$shipToAddress1}]]></Address1>
      <City><![CDATA[{$shipToCity}]]></City>
      <State><![CDATA[{$shipToRegion}]]></State>
      <Country><![CDATA[{$shipToCountry}]]></Country>
      <Zip><![CDATA[{$shiptoPostalCode}]]></Zip>
    </AddressInfo>
    {$itemXml}
  </Order>
</RateRequest>
XML;
        $curlSession = curl_init();
        curl_setopt($curlSession, CURLOPT_URL, $this->_apiEndpoint);
        curl_setopt($curlSession, CURLOPT_POST, true);
        curl_setopt($curlSession, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
        curl_setopt($curlSession, CURLOPT_POSTFIELDS, $rateRequestXml);
        curl_setopt($curlSession, CURLOPT_HEADER, false);
        curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlSession, CURLOPT_TIMEOUT, 60);
        $response = curl_exec($curlSession);
        $emptyRateResult = array();
        if (FALSE === $response) {
            return $emptyRateResult;
        }
        $parser = xml_parser_create();
        xml_parse_into_struct($parser, $response, $xmlVals, $xmlIndex);
        xml_parser_free($parser);
        foreach ($xmlVals as $key) {
            if ($key['tag'] == 'STATUS') {
                if ($key['value'] != 'OK') {
                    return $emptyRateResult;
                }
            }
        }
        $code = array();
        $method = array();
        $cost = array();
        $supportedServices = explode(',', $shipwireAvailableServices);
        foreach ($xmlVals as $key) {
            if ($key['tag'] == 'QUOTE' && $key['type'] == 'open' && $key['level'] == 4) {
                $code[] = $key['attributes']['METHOD'];
            }
            if ($key['tag'] == 'SERVICE' && $key['type'] == 'complete' && $key['level'] == 5) {
                $method[] = $key['value'];
            }
            if ($key['tag'] == 'COST' && $key['type'] == 'complete' && $key['level'] == 5) {
                $cost[] = $key['value'];
            }
        }
        $la = count($code);
        $lb = count($method);
        $lc = count($cost);
        $rateResult = array();
        if ($la == $lb && $lb == $lc) {
            foreach ($code as $index => $value) {
                if (in_array($value, $supportedServices)) {
                    $rateResult[] = array('code' => $code[$index], 'title' => $method[$index], 'amount' => $cost[$index]);
                }
            }
        }
        return $rateResult;
    }
Exemple #16
0
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     $r->setStoreId($request->getStoreId());
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     }
     if ($request->getDhlId()) {
         $id = $request->getDhlId();
     } else {
         $id = $this->getConfigData('id');
     }
     $r->setId($id);
     if ($request->getDhlPassword()) {
         $password = $request->getDhlPassword();
     } else {
         $password = $this->getConfigData('password');
     }
     $r->setPassword($password);
     if ($request->getDhlAccount()) {
         $accountNbr = $request->getDhlAccount();
     } else {
         $accountNbr = $this->getConfigData('account');
     }
     $r->setAccountNbr($accountNbr);
     if ($request->getDhlShippingKey()) {
         $shippingKey = $request->getDhlShippingKey();
     } else {
         $shippingKey = $this->getConfigData('shipping_key');
     }
     $r->setShippingKey($shippingKey);
     if ($request->getDhlShippingIntlKey()) {
         $shippingKey = $request->getDhlShippingIntlKey();
     } else {
         $shippingKey = $this->getConfigData('shipping_intlkey');
     }
     $r->setShippingIntlKey($shippingKey);
     if ($request->getDhlShipmentType()) {
         $shipmentType = $request->getDhlShipmentType();
     } else {
         $shipmentType = $this->getConfigData('shipment_type');
     }
     $r->setShipmentType($shipmentType);
     if ($request->getDhlDutiable()) {
         $shipmentDutible = $request->getDhlDutiable();
     } else {
         $shipmentDutible = $this->getConfigData('dutiable');
     }
     $r->setDutiable($shipmentDutible);
     if ($request->getDhlDutyPaymentType()) {
         $dutypaytype = $request->getDhlDutyPaymentType();
     } else {
         $dutypaytype = $this->getConfigData('dutypaymenttype');
     }
     $r->setDutyPaymentType($dutypaytype);
     if ($request->getDhlContentDesc()) {
         $contentdesc = $request->getDhlContentDesc();
     } else {
         $contentdesc = $this->getConfigData('contentdesc');
     }
     $r->setContentDesc($contentdesc);
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     }
     $r->setOrigCountry($origCountry);
     /*
      * DHL only accepts weight as a whole number. Maximum length is 3 digits.
      */
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $shippingWeight = round(max(1, $weight), 0);
     $r->setValue(round($request->getPackageValue(), 2));
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setDestStreet(Mage::helper('core/string')->substr($request->getDestStreet(), 0, 35));
     $r->setDestCity($request->getDestCity());
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     //for DHL, puero rico state for US will assume as puerto rico country
     //for puerto rico, dhl will ship as international
     if ($destCountry == self::USA_COUNTRY_ID && ($request->getDestPostcode() == '00912' || $request->getDestRegionCode() == self::PUERTORICO_COUNTRY_ID)) {
         $destCountry = self::PUERTORICO_COUNTRY_ID;
     }
     $r->setDestCountryId($destCountry);
     $r->setDestState($request->getDestRegionCode());
     $r->setWeight($shippingWeight);
     $r->setFreeMethodWeight($request->getFreeMethodWeight());
     $this->_rawRequest = $r;
     //        $methods = explode(',', $this->getConfigData('allowed_methods'));
     //
     //        $freeMethod = $this->getConfigData('free_method');
     //
     //        $internationcode = $this->getCode('international_searvice');
     //        $minOrderAmount = $this->getConfigData('cutoff_cost') ? $this->getConfigData('cutoff_cost') : 0;
     //        if ($shippingWeight>0) {
     //             $this->_rawRequest->setWeight($shippingWeight);
     //             $this->_getQuotes();
     //            foreach ($methods as $method) {
     //                if(($method==$internationcode && ($r->getDestCountryId() != self::USA_COUNTRY_ID)) ||
     //                ($method!=$internationcode && ($r->getDestCountryId() == self::USA_COUNTRY_ID)))
     //                {
     //                    $weight = $freeMethod==$method && $this->getConfigData('cutoff_cost') <= $r->getValue() ? 0 : $shippingWeight;
     //                    if ($weight>0) {
     //                        $this->_rawRequest->setWeight($weight);
     //                	    $this->_rawRequest->setService($method);
     //                        $this->_getQuotes();
     //                    } else {
     //                        $this->_dhlRates[$method] = array(
     //                            'term' => $this->getCode('service', $method),
     //                            'price_total' => 0,
     //                        );
     //                    }
     //                }
     //            }
     //        } else {
     //           $this->_errors[] = Mage::helper('usa')->__('Please enter the package weight');
     //        }
     return $this;
 }
Exemple #17
0
 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     if ($request->getDestCountry()) {
         $destCountry = $request->getDestCountry();
     }
     $zip = substr($request->getDestPostcode(), 0, 8);
     //echo "zip=(".$zip.")";
     //$request->getDestCity() - ???????? ?????: "???????????"
     //$request->getDestCountryId(); //RU
     //echo '<br>****destCountry='.$destCountry,'<br>****getDestCity='.$request->getDestCity().' getDestRegionId='.$request->getDestRegionId();
     //return $this->PrintDebug( '<br>****destCountry='.$request->getDestCountryId() ); //????? ?????????? ??????????
     $county_edost = array(1960 => 'AU', 1961 => 'AT', 1962 => 'AZ', 1963 => 'AL', 1964 => 'DZ', 1965 => 'AS', 1966 => 'AI', 1968 => 'AO', 1969 => 'AD', 1970 => 'AG', 1971 => 'AN', 1972 => 'AR', 1973 => 'AM', 1974 => 'AW', 1975 => 'AF', 1976 => 'BS', 1977 => 'BD', 1978 => 'BB', 1979 => 'BH', 1980 => 'BY', 1981 => 'BZ', 1982 => 'BE', 1983 => 'BJ', 1984 => 'BM', 1985 => 'BG', 1986 => 'BO', 1988 => 'BA', 1989 => 'BW', 1990 => 'BR', 1991 => 'BN', 1992 => 'BF', 1993 => 'BI', 1994 => 'BT', 1995 => 'WF', 1996 => 'VU', 1997 => 'GB', 1998 => 'HU', 1999 => 'VE', 2000 => 'VG', 2001 => 'VI', 2002 => 'TL', 2003 => 'VN', 2004 => 'GA', 2005 => 'HT', 2006 => 'GY', 2007 => 'GM', 2008 => 'GH', 2009 => 'GP', 2010 => 'GT', 2011 => 'GN', 2012 => 'GQ', 2013 => 'GW', 2014 => 'DE', 2016 => 'GI', 2017 => 'HN', 2018 => 'HK', 2019 => 'GD', 2020 => 'GL', 2021 => 'GR', 2022 => 'GE', 2023 => 'GU', 2024 => 'DK', 2026 => 'DJ', 2027 => 'DM', 2028 => 'DO', 2029 => 'EG', 2030 => 'ZM', 2031 => 'CV', 2032 => 'ZW', 2033 => 'IL', 2034 => 'IN', 2035 => 'ID', 2036 => 'JO', 2037 => 'IQ', 2038 => 'IR', 2039 => 'IE', 2040 => 'IS', 2041 => 'ES', 2042 => 'IT', 2043 => 'YE', 2044 => 'KZ', 2045 => 'KY', 2046 => 'KH', 2047 => 'CM', 2048 => 'CA', 2049 => 'EQ', 2050 => 'QA', 2051 => 'KE', 2052 => 'CY', 2053 => 'KI', 2054 => 'CN', 2055 => 'CO', 2056 => 'KM', 2057 => 'CG', 2058 => 'CD', 2059 => 'KP', 2060 => 'KR', 2062 => 'CR', 2063 => 'CI', 2064 => 'CU', 2065 => 'KW', 2066 => 'CK', 2067 => 'KG', 2069 => 'LA', 2070 => 'LV', 2071 => 'LS', 2072 => 'LR', 2073 => 'LB', 2074 => 'LY', 2075 => 'LT', 2076 => 'LI', 2077 => 'LU', 2078 => 'MU', 2079 => 'MR', 2080 => 'MG', 2081 => 'YT', 2082 => 'MO', 2083 => 'MK', 2084 => 'MW', 2085 => 'MY', 2086 => 'ML', 2087 => 'MV', 2088 => 'MT', 2089 => 'MA', 2090 => 'MQ', 2091 => 'MH', 2092 => 'MX', 2093 => 'FM', 2094 => 'MZ', 2095 => 'MD', 2096 => 'MC', 2097 => 'MN', 2098 => 'MS', 2099 => 'MM', 2100 => 'NA', 2101 => 'NR', 2102 => 'KN', 2103 => 'NP', 2104 => 'NE', 2105 => 'NG', 2106 => 'NL', 2107 => 'NI', 2108 => 'NU', 2109 => 'NZ', 2110 => 'NC', 2111 => 'NO', 2112 => 'AE', 2113 => 'OM', 2114 => 'PK', 2115 => 'PW', 2116 => 'PA', 2117 => 'PG', 2118 => 'PY', 2119 => 'PE', 2120 => 'PL', 2121 => 'PT', 2122 => 'PR', 2123 => 'RE', 2124 => 'RW', 2125 => 'RO', 2126 => 'MP', 2127 => 'SV', 2128 => 'WS', 2129 => 'SM', 2130 => 'ST', 2131 => 'SA', 2132 => 'SZ', 2134 => 'SC', 2136 => 'SN', 2137 => 'VC', 2138 => 'KN', 2139 => 'KN', 2140 => 'LC', 2145 => 'SG', 2146 => 'SY', 2147 => 'SK', 2148 => 'SI', 2149 => 'SB', 2150 => 'SO', 2152 => 'SD', 2153 => 'SR', 2154 => 'US', 2155 => 'SL', 2156 => 'TJ', 2157 => 'TH', 2158 => 'PF', 2159 => 'TW', 2160 => 'TZ', 2161 => 'TG', 2162 => 'TO', 2163 => 'TT', 2164 => 'TV', 2165 => 'TN', 2166 => 'TM', 2167 => 'TC', 2168 => 'TR', 2169 => 'UG', 2170 => 'UZ', 2171 => 'UA', 2172 => 'UY', 2174 => 'FO', 2175 => 'FJ', 2176 => 'PH', 2177 => 'FI', 2178 => 'FK', 2179 => 'FR', 2180 => 'GF', 2181 => 'PF', 2182 => 'HR', 2183 => 'CF', 2184 => 'TD', 2186 => 'CZ', 2187 => 'CL', 2188 => 'CH', 2189 => 'SE', 2191 => 'LK', 2192 => 'EC', 2193 => 'ER', 2194 => 'EE', 2195 => 'ET', 2196 => 'ZA', 2197 => 'JM', 2198 => 'JP', 0 => 'RU');
     $country = array_search($request->getDestCountryId(), $county_edost);
     //echo '<br>****getDestCountryId='.$request->getDestCountryId().' - edost_id='.$country; //RU
     //echo '<br>****getDestRegionId='.$request->getDestRegionId(); //??? ?????? ??? ??????? edost
     $edost_calc = new edost_class();
     //?????? ? id ????????
     $edost_calc->edost_id = $this->getConfigData('id');
     $edost_calc->edost_pswd = $this->getConfigData('password');
     $edost_calc->SetSiteUTF();
     $strah = $request->getPackageValue();
     //??????
     $host = trim(strtolower($this->getConfigData('gateway_url')));
     if (substr($host, 0, 7) == "http://") {
         $host = substr($host, 7, 100);
     }
     //if (substr($host,0,4) == "www.") $host = substr($host,4,100);
     if ($host == '') {
         $edost_calc->adr = EDOST_ADDR;
     } else {
         $edost_calc->adr = "http://" . $host . "/" . EDOST_PAGE;
     }
     //?????????? ?????? ? ????? ???????
     $country_hide = false;
     if ($country_hide) {
         $country = 0;
     }
     //?.?. ?? ????????? ??????????? US, ???? ?? ??????? ??????
     if (!$country) {
         $country = 0;
     }
     //RU
     if (isset($_SESSION['city_for_cart'])) {
         $to_city = Mage::getModel('directory/region')->load($_SESSION['city_for_cart'])->getCode();
         //????? ??? ??????
         $city_code = Mage::getModel('directory/region')->load($_SESSION['city_for_cart'])->getCdekCode();
     } else {
         if ($country == 0) {
             $to_city = Mage::getModel('directory/region')->load($request->getDestRegionId())->getCode();
             //????? ??? ??????
             $city_code = Mage::getModel('directory/region')->load($request->getDestRegionId())->getCdekCode();
         } else {
             $to_city = $country;
             $city_code = '0';
         }
     }
     /* 		if($country==0)
           $to_city = Mage::getModel('directory/region')->load( $request->getDestRegionId() )->getCode(); //????? ??? ??????
           else
           $to_city = $country;
          */
     //$weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     /*        $packageParams = $request->getPackageParams();
               $height = $packageParams->getHeight();
               $width = $packageParams->getWidth();
               $length = $packageParams->getLength();
               echo "<br>*** height=$height,  width=$width,  length=$length";
              */
     //echo $cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
     /* 		Mage::getSingleton('core/session', array('name'=>'frontend'));
               $cart = Mage::getModel('checkout/cart');
               $ids = $cart->getProductIds();
               print_r($ids);
               foreach ($ids as $i=>$productId) {
               echo "<br>id=$id ($i)";
               $product = Mage::getModel('catalog/product')->load($productId);
               $attributes = $product->getAttributes();
     
               foreach ($attributes as $attribute) {
               $attributeCode = $attribute->getAttributeCode();
               if ($attributeCode == 'length') {
               $value = $attribute->getFrontend()->getValue($product);
               echo $attributeCode . '-' . '-' . $value;
               }
               }
     
               }
              */
     $session = Mage::getSingleton('checkout/session');
     $output = "<br>";
     $weight = 0;
     $size_in = null;
     $weight_zero = false;
     $k = 0;
     if (isset($_SESSION['product_for_cart'])) {
         $products_in_session[0] = $_SESSION['product_for_cart'];
     } else {
         $products_in_session = $session->getQuote()->getAllVisibleItems();
     }
     $sdbg = '';
     //getAllItems() - ??????, ?.?. ?????????? ????? ??????? ? ???????!
     foreach ($products_in_session as $item) {
         if (isset($_SESSION['productid'])) {
             $productId = $_SESSION['productid'];
             $item = Mage::getModel('catalog/product')->load($productId);
             $price_final = $item->getFinalPrice();
             $qty = '1';
         } else {
             $productId = $item->getProductId();
             $price_final = $item->getBaseCalculationPrice();
             $qty = $item->getQty();
         }
         $sdbg .= '<br>************* Sku=' . $item->getSku() . "<br>Name=" . $item->getName() . "<br>" . $item->getDescription() . "<br>BaseCalculationPrice=" . $price_final . "<br>ProductId=" . $productId . "<br>Weight=" . $item->getWeight() . "<br>Qty=" . $qty;
         //."<br><pre>".print_r($item, true)."</pre>"
         //echo "<br>************************ <pre>".print_r($item, true)."</pre>";
         $weight += $item->getWeight() * $qty;
         if (!($item->getWeight() > 0)) {
             $weight_zero = true;
         }
         //            $product = Mage::getModel('catalog/product')->loadBySku($item->getSku());
         $product = Mage::getModel('catalog/product');
         $productId = $product->getIdBySku($item->getSku());
         if ($productId) {
             $product->load($productId);
         }
         $attributes = $product->getAttributes();
         $x = 0;
         $y = 0;
         $z = 0;
         foreach ($attributes as $attribute) {
             $attributeCode = $attribute->getAttributeCode();
             if ($attributeCode == 'length') {
                 $x = $attribute->getFrontend()->getValue($product);
             }
             if ($attributeCode == 'width') {
                 $y = $attribute->getFrontend()->getValue($product);
             }
             if ($attributeCode == 'height') {
                 $z = $attribute->getFrontend()->getValue($product);
             }
         }
         $sdbg .= '<br>******' . "<br>productId = {$productId} , length={$x} , width={$y} , height={$z}";
         //echo "<br>length=$x , width=$y , height=$z";
         if ($x > 0 && $y > 0 && $z > 0) {
             // ?????? ????????? ?????? (???? ??????? ?????? ????????? ??????, ????? ??? ??? ???????????? ? ???? ????)
             $size_one = $edost_calc->SumSizeOneGoods($x, $y, $z, $item->getQty());
             $size_in[] = array('X' => $size_one['X'], 'Y' => $size_one['Y'], 'Z' => $size_one['Z']);
             //$sdbg .= '<br>******'."<br>length=".$size_in[$k]['X']." , width=".$size_in[$k]['Y']." , height=".$size_in[$k]['Z'];
             $k++;
         } else {
             $weight_zero = true;
         }
     }
     if ($weight_zero) {
         $weight = 0;
     }
     //return $this->PrintDebug( '<br>****='.$sdbg.' = '.'<br>' ); //????? ?????????? ??????????
     //return $this->PrintDebug( '<br>****to_city='.$to_city.' = '.$weight ); //????? ?????????? ??????????
     //echo '<br>*** to_city='.$to_city.' , WEIGHT='.$weight.' , strah='.$strah;
     //echo '<br>*** to_city='.$to_city.' , WEIGHT='.$weight.' , strah='.$strah.' , id='.$this->getConfigData('id').' , ps='.$this->getConfigData('password');
     //????????? ??????? ?????
     $size = $edost_calc->SumSize($size_in);
     $length = $size['length'];
     $width = $size['width'];
     $height = $size['height'];
     $length = 20;
     $width = 20;
     $height = 15;
     $weight = 20;
     //echo "<br>length=$length , width=$width , height=$height";
     //return $this->PrintDebug( '<br>****='."<br>length=$length , width=$width , height=$height".' = '.'<br>'."<br><pre>".print_r($size_in, true)."</pre>" ); //????? ?????????? ??????????
     $result = Mage::getModel('shipping/rate_result');
     $r = $edost_calc->edost_calc($to_city, $weight, $strah, $length, $width, $height, $zip);
     if (isset($city_code)) {
         if ($city_code != '0') {
             $av_cities = array(1068, 1070, 14454, 2893, 1072, 1543, 2894, 15161, 13161, 2895, 2896, 15162, 14751, 1075, 2897, 2898, 15163, 14449, 1316, 1540, 2899, 15164, 15165, 14966, 2900, 2901, 15166, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 14448, 15167, 15168, 953, 1245, 14750, 15169, 2909, 2910, 15170, 14447, 15199, 1539, 14450, 14452, 2911, 15171, 14749, 2912, 2913, 14453, 2914, 14660, 1060, 2915, 15200, 14451, 15201, 15202, 2916, 1748, 1071, 206, 2917, 2918, 1738, 15203, 2919, 14456, 2920, 15204, 15205, 15206, 2921, 15207, 15208, 2922, 2923, 2924, 2925, 438, 15209, 15210, 15211, 2926, 2927, 15212, 15213, 2928, 15214, 14527, 13154, 15215, 2929, 15216, 15217, 1069, 2930, 2931, 2932, 15218, 15219, 14264, 14292, 14324, 2933, 2934, 2935, 2936, 2349, 14659, 14455, 14752, 15220);
             $dop_tarif_mag = $edost_calc->calculateCC($city_code, $weight, $length, $width, $height);
             $dop_tarif_ekonom = $edost_calc->calculateCD($city_code, $weight, $length, $width, $height);
             if (in_array((int) $city_code, $av_cities)) {
                 if ($dop_tarif_ekonom['result']) {
                     $method = Mage::getModel('shipping/rate_result_method');
                     $method->setCarrier('edost');
                     //$method->setCarrierTitle('???????????? ???????? ???? ('.$dop_tarif_ekonom['result']['deliveryPeriodMin'].'-'.$dop_tarif_ekonom['result']['deliveryPeriodMax'].' ????)');
                     $method->setMethod('dop2');
                     $method->setMethodTitle('Транспортная компания СДЭК (' . $dop_tarif_ekonom['result']['deliveryPeriodMin'] . '-' . $dop_tarif_ekonom['result']['deliveryPeriodMax'] . ' дней)');
                     $method->setCost($dop_tarif_ekonom['result']['price']);
                     $method->setPrice($dop_tarif_ekonom['result']['price']);
                     $result->append($method);
                 }
             } else {
                 if ($dop_tarif_mag['result']) {
                     $method = Mage::getModel('shipping/rate_result_method');
                     $method->setCarrier('edost');
                     //$method->setCarrierTitle('???????????? ???????? ???? ('.$dop_tarif_mag['result']['deliveryPeriodMin'].'-'.$dop_tarif_mag['result']['deliveryPeriodMax'].' ????)');
                     $method->setMethod('dop1');
                     $method->setMethodTitle('Транспортная компания СДЭК (' . $dop_tarif_mag['result']['deliveryPeriodMin'] . '-' . $dop_tarif_mag['result']['deliveryPeriodMax'] . ' дней');
                     $method->setCost($dop_tarif_mag['result']['price']);
                     $method->setPrice($dop_tarif_mag['result']['price']);
                     $result->append($method);
                 }
             }
         }
     }
     //
     //
     //        //== ????? ??????????? ============================================
     //        $st = '';
     //        if ($r['qty_company'] == 0) {
     //            switch ($r['stat']) {
     //                // ???? ?????? ?? ???????? ??????? ?? ?????? edost
     //                case 0: $st = '';
     //                    break;
     //                case 1: $st = '';
     //                    break; //????? ???????, ?? ?????????? ??????? ?? ???????
     //                case 2: $st = Mage::helper('rus')->__("edost_err2");
     //                    break; //"?????? ? ??????? ????????????"
     //                case 3: $st = Mage::helper('rus')->__("edost_err3");
     //                    break; //"?? ?????? ?????? ???????? (?????? ??? ?????????????)"
     //                case 4: $st = Mage::helper('rus')->__("edost_err4");
     //                    break; //"?? ?????? ??????? ?????????"
     //                case 5: $st = Mage::helper('rus')->__("edost_err5");
     //                    break; //"?? ?????? ????? ??? ??????"
     //                case 6: $st = Mage::helper('rus')->__("edost_err6");
     //                    break; //"?????????? ?????? ??????? ????????"
     //                case 7: $st = Mage::helper('rus')->__("edost_err7");
     //                    break; //"?? ?????? ???????? ???????? ? ?????????? ????????"
     //                case 8: $st = Mage::helper('rus')->__("edost_err8");
     //                    break; //"?????? ??????? ?? ????????"
     //                case 9: $st = Mage::helper('rus')->__("edost_err9");
     //                    break; //"???????? ????? ???????? ?? ????"
     //                case 10:$st = Mage::helper('rus')->__("edost_err10");
     //                    break; //"?? ?????? ?????? XML"
     //                case 11:$st = Mage::helper('rus')->__("edost_err11");
     //                    break; //"?? ?????? ???"
     //                case 12:$st = Mage::helper('rus')->__("edost_err12");
     //                    break; //"?? ?????? ?????? ???????? (?????? ??? ?????????????)"
     //                case 14:$st = Mage::helper('rus')->__("edost_err14");
     //                    break; //"????????? ??????? ?? ????????? ????????? ?????? ?? ??????"
     //                default:$st = Mage::helper('rus')->__("edost_err0"); //"?????? ???????."
     //            };
     //            if ($city_code != 0) {
     //                $st = 15;
     //            }
     //            //if ( ($r['stat']>=2) and ($r['stat']<=12) ) {
     //            if ($this->getConfigData('hide_err'))
     //                $st = '';
     //            //}
     //
     //            if (($st <> '') && ($st != '15')) {
     //                //????? ?????? - ??? ????????? ????????!!!
     //                $result = Mage::getModel('shipping/rate_result_error');
     //                $result->setCarrier('edost');
     //                $result->setCarrierTitle($this->getConfigData('title'));
     //                $result->setErrorMessage($st);
     //                return $result;
     //            }
     //
     //            //<br>? ?????? ????? ?????????????? ?????? ???????? ?? ??????????????. ? ??????????? ? ????????? ????????, ??????????, ???????? ? ?????????.
     //            if ($this->getConfigData('show_msg')) {
     ////				$st = '';
     //                //??????
     //                $mba = 'blankshippingmodule';
     //                if (Mage::getStoreConfig('carriers/' . $mba . '/active')) {
     //                    $config = Mage::getStoreConfig('carriers/' . $mba);
     //                    $session = Mage::getSingleton('checkout/session');
     //                    $sum = 0;
     //                    foreach ($products_in_session as $item) {
     //                        if (isset($_SESSION['productid'])) {
     //                            $productId = $_SESSION['productid'];
     //                            $item = Mage::getModel('catalog/product')->load($productId);
     //                            $price_final = $item->getFinalPrice();
     //                            $qty = '1';
     //                        } else {
     //                            $productId = $item->getProductId();
     //                            $price_final = $item->getBaseCalculationPrice();
     //                            $qty = $item->getQty();
     //                        }
     //                        $sum += $qty * $item->getWeight();
     //                    }
     //                    $session = Mage::getSingleton('core/session');
     //                    $session_geo_ip = $session->getGeoIp();
     //
     //                    if (isset($session_geo_ip['code'])) {
     //                        $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
     //
     //                        if (!isset($ship_data['name']) || ($ship_data['dscr'] == '')) {
     //                            return false;
     //                        } else {
     //                            if ($ship_data['name'] == '2137') {
     //                                $cost = $config['moscow_ship'];
     //                            } else {
     //                                if ($ship_data['name'] == '2344') {
     //                                    $cost = $config['piter_ship'];
     //                                } else {
     //                                    $km = $ship_data['dscr'];
     //                                    if ($km < 5) {
     //                                        $cost = $config['mkad_shipdo5'] + $config['piter_ship'];
     //                                    } else {
     //                                        if (($km >= 5) && ($km < 10)) {
     //                                            $cost = $config['mkad_shipdo10'] + $config['piter_ship'];
     //                                        } else {
     //                                            $cost = $ship_data['dscr'] * $config['mkad_shipb10'] + $config['piter_ship'];
     //                                        }
     //                                    }
     //                                }
     //                            }
     //
     //                            $result = Mage::getModel('shipping/rate_result');
     //                            $method = Mage::getModel('shipping/rate_result_method');
     //                            //????????? ???????
     //                            $method->setCarrier('edost');
     //                            $method->setCarrierTitle('');
     //                            $method->setMethod('pickup1');
     //                            $method->setMethodTitle('Курьерская доставка');
     //                            $method->setCost($cost);
     //                            $method->setPrice($cost);
     //                            $result->append($method);
     ////?????????
     //                            if ($sum < 25) {
     //                                $method = Mage::getModel('shipping/rate_result_method');
     //                                $method->setCarrier('freeshipping');
     //                                $method->setCarrierTitle('Самовывоз в пункте Курьер.ру г.Москва');
     //                                $method->setMethod('pickup2');
     //                                $method->setMethodTitle('Самовывоз в пункте Курьер.ру г.Москва');
     //                                $method->setCost($config['ship_sam']);
     //                                $method->setPrice($config['ship_sam']);
     //                                $result->append($method);
     //                            }
     //                        }
     //                    }
     //                }
     //
     //                $cour = 'morphescourier';
     //                if (Mage::getStoreConfig('carriers/' . $cour . '/active')) {
     //                    $session = Mage::getSingleton('checkout/session');
     //                    $sum = 0;
     //                    foreach ($session->getQuote()->getAllVisibleItems() as $item) {
     //                        if (isset($_SESSION['productid'])) {
     //                            $productId = $_SESSION['productid'];
     //                            $item = Mage::getModel('catalog/product')->load($productId);
     //                            $price_final = $item->getFinalPrice();
     //                            $qty = '1';
     //                        } else {
     //                            $productId = $item->getProductId();
     //                            $price_final = $item->getBaseCalculationPrice();
     //                            $qty = $item->getQty();
     //                        }
     //                        $sum += $qty * $item->getWeight();
     //                    }
     //                    $session = Mage::getSingleton('core/session');
     //                    $session_geo_ip = $session->getGeoIp();
     //                    if (isset($session_geo_ip['code'])) {
     //                        $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
     //                        if (!isset($ship_data['name'])) {
     //                            return false;
     //                        } else {
     //                            $diap = array('20', '15', '10', '5', '3', '1');
     //                            $costs = explode(';', $ship_data['costs']);
     //                            $costs = array_reverse($costs);
     //                            $count = 0;
     //                            foreach ($diap as $value) {
     //                                if ($sum < (int) $value) {
     //                                    $cost_cour = $ship_data['km' . $value];  //?????????? ?????????
     //                                    $cost_sam = $costs[$count];            //????????? ??????????
     //                                }
     //                                $count++;
     //                            }
     //                            $diap_km = array('50' => '500', '45' => '450', '40' => '400', '35' => '350', '30' => '300', '25' => '250', '20' => '200', '15' => '150', '10' => '100', '5' => '50');
     //                            if ($ship_data['dscr'] != '') {
     //                                foreach ($diap_km as $km => $cost) {
     //                                    if ($ship_data['dscr'] <= $km)
     //                                        $cost_dop_km = $cost;
     //                                }
     //                            } else {
     //                                $cost_dop_km = 0;
     //                            }
     //                            if ($ship_data['dscr'] == '0')
     //                                $cost_dop_km = 500;
     //                            /* $result = Mage::getModel('shipping/rate_result');
     //                              $method = Mage::getModel('shipping/rate_result_method');
     //                              $method->setCarrier('edost');
     //                              $method->setCarrierTitle('???????? ????????');
     //                              $method->setMethod('pickup0');
     //                              $method->setMethodTitle('???????? ????????');
     //                              $method->setCost($cost_cour);
     //                              $method->setPrice($cost_cour+$cost_dop_km);
     //                              $result->append($method); */
     //                            $addresses = explode(';', $ship_data['addressess']);
     //                            $count = 1;
     //                            if ($sum < 25) {
     //
     //                                foreach ($addresses as $address) {
     //                                    $method = Mage::getModel('shipping/rate_result_method');
     //                                    $method->setCarrier('freeshipping');
     //                                    $method->setCarrierTitle('Im-Logistics Пункт Самовывоза');
     //                                    $method->setMethod('pickup' . $count);
     //                                    $method->setMethodTitle($address . ' Logistic');
     //                                    $method->setCost($cost_sam);
     //                                    $method->setPrice($cost_sam);
     //                                    $result->append($method);
     //                                    $count++;
     //                                }
     //                            }
     //                        }
     //                    }
     //                }
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //
     //                $rate = Mage::getModel('shipping/rate_result_method');
     //                $rate->setCarrier('edost');
     //                $rate->setCarrierTitle($this->getConfigData('title'));
     //                $rate->setMethod('error');
     //                $rate->setMethodTitle($this->getConfigData('specificerrmsg'));
     //                $rate->setCost(0); //
     //                $rate->setPrice(0); //???? ????????? (cost+handling)
     //                //  $result->append($rate);
     //            }
     //        } else {
     //
     //
     //            //????????? ?? ?????? ? ?????? ????????
     //            $baseCurr = Mage::app()->getStore()->getBaseCurrency();
     //            //echo "<br><pre>",print_r($baseCurr),"</pre>";
     //
     //            $allCurr = Mage::app()->getStore()->getAvailableCurrencyCodes();
     //            //echo "<br><pre>",print_r($allCurr),"</pre>";
     //            if (!in_array('RUB', $allCurr) or ($baseCurr->getRate('RUB') == 0)) {
     //                //????? ?????? - ??? ????????? ????????!!!
     //                $result = Mage::getModel('shipping/rate_result_error');
     //                $result->setCarrier('edost');
     //                $result->setCarrierTitle($this->getConfigData('title'));
     //                $result->setErrorMessage('eDost: Not Available Currency RUB!');
     //                return $result;
     //            }
     //
     //            if ($baseCurr->getCode() != 'RUB') {
     //                $rateToBase = $baseCurr->getRate('RUB');
     //            }
     //
     //            for ($i = 1; $i <= $r['qty_company']; $i++) {
     //
     //                if ($r['name' . $i] == '')
     //                    $q = '';
     //                else
     //                    $q = $r['name' . $i];
     //                if ($r['day' . $i] == '&nbsp;')
     //                    $q.='';
     //                else
     //                    $q.= ($q == '') ? $r['day' . $i] : (', ' . $r['day' . $i]);
     //
     //                $priceCurrency = $r['price' . $i];
     //
     //                if ($baseCurr->getCode() != 'RUB') {
     //                    $priceCurrency = round($priceCurrency / $rateToBase, 2);
     //                }
     //
     //                $strDelivery = $r["company" . $i];
     //                if ($q <> '')
     //                    $strDelivery .= ' (' . $q . ')';
     //
     //
     //
     //
     //
     //
     //
     //                $session = Mage::getSingleton('core/session');
     //                $session_geo_ip = $session->getGeoIp();
     //                if (isset($session_geo_ip['code'])) {
     //
     //                    if ($session_geo_ip['code'] == '2137') {
     //                        if (strpos($strDelivery, '????') === false) {
     //                            $rate = Mage::getModel('shipping/rate_result_method');
     //                            $rate->setCarrier('edost');
     //                            //$rate->setCarrierTitle($this->getConfigData('title').'asdf');
     //                            $rate->setMethod($r['id' . $i] . '-' . $r['strah' . $i]);
     //                            $rate->setMethodTitle('Транспортная компания ' . $strDelivery);
     //                            $rate->setCost($priceCurrency); //
     //                            $rate->setPrice($priceCurrency); //???? ????????? (cost+handling)
     //                            $result->append($rate);
     //                        }
     //                    } else {
     //
     //                        $rate = Mage::getModel('shipping/rate_result_method');
     //                        $rate->setCarrier('edost');
     //                        //$rate->setCarrierTitle($this->getConfigData('title'));
     //                        $rate->setCarrierTitle('');
     //                        $rate->setMethod($r['id' . $i] . '-' . $r['strah' . $i]);
     //                        $rate->setMethodTitle('Транспортная компания ' . $strDelivery);
     //                        $rate->setCost($priceCurrency); //
     //                        $rate->setPrice($priceCurrency); //???? ????????? (cost+handling)
     //                        $result->append($rate);
     //                    }
     //                }
     //            }
     //
     //
     //
     //            //??????
     //            $mba = 'blankshippingmodule';
     //            if (Mage::getStoreConfig('carriers/' . $mba . '/active')) {
     //                $config = Mage::getStoreConfig('carriers/' . $mba);
     //                $session = Mage::getSingleton('checkout/session');
     //                $sum = 0;
     //                foreach ($session->getQuote()->getAllVisibleItems() as $item) {
     //                    $sum += $item->getQty() * $item->getWeight();
     //                }
     //                $session = Mage::getSingleton('core/session');
     //                $session_geo_ip = $session->getGeoIp();
     //
     //                if (isset($session_geo_ip['code'])) {
     //                    $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
     //
     //                    if (!isset($ship_data['name']) || ($ship_data['dscr'] == '')) {
     //                        //return false;
     //                    } else {
     //                        if ($ship_data['name'] == '2137') {
     //                            $cost = $config['moscow_ship'];
     //                        } else {
     //                            if ($ship_data['name'] == '2344') {
     //                                $cost = $config['piter_ship'];
     //                            } else {
     //                                $km = $ship_data['dscr'];
     //                                if ($km < 5) {
     //                                    $cost = $config['mkad_shipdo5'] + $config['piter_ship'];
     //                                } else {
     //                                    if (($km >= 5) && ($km < 10)) {
     //                                        $cost = $config['mkad_shipdo10'] + $config['piter_ship'];
     //                                    } else {
     //                                        $cost = $ship_data['dscr'] * $config['mkad_shipb10'] + $config['piter_ship'];
     //                                    }
     //                                }
     //                            }
     //                        }
     //
     //                        //$result = Mage::getModel('shipping/rate_result');
     //                        $method = Mage::getModel('shipping/rate_result_method');
     //                        //????????? ???????
     //                        $method->setCarrier('edost');
     //                        $method->setCarrierTitle('?????????? ????????');
     //                        $method->setMethod('pickup1');
     //                        $method->setMethodTitle('');
     //                        $method->setCost($cost);
     //                        $method->setPrice($cost);
     //                        $result->append($method);
     ////????????? ??????????
     //                        if ($sum < 25) {
     //                            $method = Mage::getModel('shipping/rate_result_method');
     //                            $method->setCarrier('freeshipping');
     //                            $method->setCarrierTitle('Самовывоз в пункте Курьер.ру г.Москва');
     //                            $method->setMethod('pickup2');
     //                            $method->setMethodTitle('Самовывоз в пункте Курьер.ру г.Москва');
     //                            $method->setCost($config['ship_sam']);
     //                            $method->setPrice($config['ship_sam']);
     //                            $result->append($method);
     //                        }
     //                    }
     //                }
     //            }
     //
     //            $cour = 'morphescourier';
     //            if (Mage::getStoreConfig('carriers/' . $cour . '/active')) {
     //                $session = Mage::getSingleton('checkout/session');
     //                $sum = 0;
     //                foreach ($session->getQuote()->getAllVisibleItems() as $item) {
     //                    $sum += $item->getQty() * $item->getWeight();
     //                }
     //                $session = Mage::getSingleton('core/session');
     //                $session_geo_ip = $session->getGeoIp();
     //                if (isset($session_geo_ip['code'])) {
     //                    $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
     //                    if (!isset($ship_data['name'])) { //return false;
     //                    } else {
     //                        $diap = array('20', '15', '10', '5', '3', '1');
     //                        $costs = explode(';', $ship_data['costs']);
     //                        $costs = array_reverse($costs);
     //                        $count = 0;
     //                        foreach ($diap as $value) {
     //                            if ($sum < (int) $value) {
     //                                $cost_cour = $ship_data['km' . $value];  //?????????? ?????????
     //                                $cost_sam = $costs[$count];            //????????? ??????????
     //                            }
     //                            $count++;
     //                        }
     //                        $diap_km = array('50' => '500', '45' => '450', '40' => '400', '35' => '350', '30' => '300', '25' => '250', '20' => '200', '15' => '150', '10' => '100', '5' => '50');
     //                        if ($ship_data['dscr'] != '') {
     //                            foreach ($diap_km as $km => $cost) {
     //                                if ($ship_data['dscr'] <= $km)
     //                                    $cost_dop_km = $cost;
     //                            }
     //                        } else {
     //                            $cost_dop_km = 0;
     //                        }
     //
     //                        if ($ship_data['dscr'] == '') {
     //                            $cost_dop_km = 500;
     //
     //                            $method = Mage::getModel('shipping/rate_result_method');
     //                            $method->setCarrier('edost');
     //                            $method->setCarrierTitle('Курьерская доставка');
     //                            $method->setMethod('pickup1');
     //                            $method->setMethodTitle('Курьерская доставка');
     //                            $method->setCost($cost_dop_km);
     //                            $method->setPrice($cost_dop_km);
     //                            if ($sum < 25) {
     //                                $result->append($method);
     //                            }
     //                        }
     //
     //                        $addresses = explode(';', $ship_data['addressess']);
     //                        $count = 1;
     //                        if ($sum < 25) {
     //                            foreach ($addresses as $address) {
     //                                $method = Mage::getModel('shipping/rate_result_method');
     //                                $method->setCarrier('freeshipping');
     //                                $method->setCarrierTitle('Im-Logistics Пункт Самовывоза');
     //                                $method->setMethod('pickup' . $count);
     //                                $method->setMethodTitle($address . ' Logistic');
     //                                $method->setCost($cost_sam);
     //                                $method->setPrice($cost_sam);
     //                                $result->append($method);
     //                                $count++;
     //                            }
     //                        }
     //                    }
     //                }
     //            }
     //        }
     //        $_SESSION['result'] = $result;
     //
     //
     //        Mage::log($result, true, 'edostlog11.log');
     //        $_SESSION['shipping_inf_edost'] = $result->getRatesByCarrier('edost');
     //        $_SESSION['shipping_inf_free'] = $result->getRatesByCarrier('freeshipping');
     return $result;
 }
 /**
  * Verifica se o país está dentro da área atendida 
  * 
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return boolean
  */
 protected function _checkCountry(Mage_Shipping_Model_Rate_Request $request)
 {
     $from = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     $to = $request->getDestCountryId();
     if ($from != "BR" || $to != "BR") {
         $this->_log('Fora da área de atendimento');
         return false;
     }
     return true;
 }
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $accArray = array();
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         //TODO is this reqd?
         $r->setService($request->getLimitMethod());
     } else {
         $r->setService('ALL');
     }
     $r->setUserId($this->getConfigData('userid'));
     $r->setPassword($this->getConfigData('password'));
     $r->setBusRole('Shipper');
     $r->setPaymentTerms($this->getConfigData('payment_terms'));
     $r->setContainer($this->getConfigData('container'));
     $r->setAllowedMethods($this->getConfigData('allowed_methods'));
     $r->setOriginLiftgateReqd($this->getConfigData('liftgate_origin'));
     $r->setOriginResidential($this->getConfigData('residential_origin'));
     /* if ($this->getConfigData('hazardous')) {
          	
         		$r->setHazmatInd('Y'); 
       	$accArray[]="ZHM";
          } else {
         		$r->setHazmatInd('N'); 
          }*/
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     }
     $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
     if ($request->getOrigRegionCode()) {
         $origRegionCode = $request->getOrigRegionCode();
     } else {
         $origRegionCode = Mage::getStoreConfig('shipping/origin/region_id', $this->getStore());
         if (is_numeric($origRegionCode)) {
             $origRegionCode = Mage::getModel('directory/region')->load($origRegionCode)->getCode();
         }
     }
     $r->setOrigRegionCode($origRegionCode);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()));
     }
     if ($request->getOrigCity()) {
         $r->setOrigCity($request->getOrigCity());
     } else {
         $r->setOrigCity(Mage::getStoreConfig('shipping/origin/city', $this->getStore()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     //for UPS, puero rico state for US will assume as puerto rico country
     if ($destCountry == self::USA_COUNTRY_ID && ($request->getDestPostcode() == '00912' || $request->getDestRegionCode() == self::PUERTORICO_COUNTRY_ID)) {
         $destCountry = self::PUERTORICO_COUNTRY_ID;
     }
     // For UPS, Guam state of the USA will be represented by Guam country
     if ($destCountry == self::USA_COUNTRY_ID && $request->getDestRegionCode() == self::GUAM_REGION_CODE) {
         $destCountry = self::GUAM_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     $r->setDestRegionCode($request->getDestRegionCode());
     if ($request->getDestPostcode()) {
         $r->setDestPostal('US' == $r->getDestCountry() ? substr($request->getDestPostcode(), 0, 5) : $request->getDestPostcode());
     } else {
     }
     $r->setPayorName($this->getConfigData('payor_name'));
     if ($request->getPayorCountry()) {
         $payorCountry = $request->getPayorCountry();
     } else {
         $payorCountry = $this->getConfigData('payor_country_id');
     }
     $r->setPayorCountry(Mage::getModel('directory/country')->load($payorCountry)->getIso2Code());
     if ($request->getPayorRegionCode()) {
         $payorRegionCode = $request->getPayorRegionCode();
     } else {
         $payorRegionCode = $this->getConfigData('payor_region_id');
         if (is_numeric($payorRegionCode)) {
             $payorRegionCode = Mage::getModel('directory/region')->load($payorRegionCode)->getCode();
         }
     }
     $r->setPayorRegionCode($payorRegionCode);
     if ($request->getPayorPostcode()) {
         $r->setPayorPostal($request->getPayorPostcode());
     } else {
         $r->setPayorPostal($this->getConfigData('payor_postcode'));
     }
     if ($request->getPayorCity()) {
         $r->setPayorCity($request->getPayorCity());
     } else {
         $r->setPayorCity($this->getConfigData('payor_city'));
     }
     if ($request->getPayorStreetAddress()) {
         $r->setPayorStreetAddress($request->getPayorStreetAddress());
     } else {
         $r->setPayorStreetAddress($this->getConfigData('payor_street_address'));
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setLiftgateRequired($request->getLiftgateRequired());
     $r->setShiptoType($request->getShiptoType());
     $this->_topUpPrice = 0;
     if ($request->getLiftgateRequired() || Mage::helper('wsaupsfreight')->isFixedLiftgateFee()) {
         $fee = $this->getConfigData('liftgate_fee');
         if (is_numeric($fee) && $fee > 0) {
             $this->_topUpPrice = $fee;
         }
         $accArray[] = "LIFT";
     }
     if (!is_null($request->getShiptoType() && !Mage::helper('wsaupsfreight')->isFixedDeliveryType())) {
         $shipToType = $request->getShiptoType();
         if ($shipToType == '0' || $shipToType == 'Residential') {
             $fee = $this->getConfigData('residential_fee');
             if (is_numeric($fee) && $fee > 0) {
                 $this->_topUpPrice += $fee;
             }
             $accArray[] = "RES";
         }
     }
     if ($request->getUpsUnitMeasure()) {
         $unit = $request->getUpsUnitMeasure();
     } else {
         $unit = $this->getConfigData('unit_of_measure');
     }
     $r->setUnitMeasure($unit);
     $r->setAccessories($accArray);
     $r->setIgnoreFreeItems(false);
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #20
0
 public function process(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     }
     if ($request->getDhlId()) {
         $id = $request->getDhlId();
     } else {
         $id = $this->getConfigData('id');
     }
     $r->setId($id);
     if ($request->getDhlPassword()) {
         $password = $request->getDhlPassword();
     } else {
         $password = $this->getConfigData('password');
     }
     $r->setPassword($password);
     if ($request->getDhlAccount()) {
         $accountNbr = $request->getDhlAccount();
     } else {
         $accountNbr = $this->getConfigData('account');
     }
     $r->setAccountNbr($accountNbr);
     if ($request->getDhlShippingKey()) {
         $shippingKey = $request->getDhlShippingKey();
     } else {
         $shippingKey = $this->getConfigData('shipping_key');
     }
     $r->setShippingKey($shippingKey);
     if ($request->getDhlShippingIntlKey()) {
         $shippingKey = $request->getDhlShippingIntlKey();
     } else {
         $shippingKey = $this->getConfigData('shipping_intlkey');
     }
     $r->setShippingIntlKey($shippingKey);
     if ($request->getDhlShipmentType()) {
         $shipmentType = $request->getDhlShipmentType();
     } else {
         $shipmentType = $this->getConfigData('shipment_type');
     }
     $r->setShipmentType($shipmentType);
     if ($request->getDhlDutiable()) {
         $shipmentDutible = $request->getDhlDutiable();
     } else {
         $shipmentDutible = $this->getConfigData('dutiable');
     }
     $r->setDutiable($shipmentDutible);
     if ($request->getDhlDutyPaymentType()) {
         $dutypaytype = $request->getDhlDutyPaymentType();
     } else {
         $dutypaytype = $this->getConfigData('dutypaymenttype');
     }
     $r->setDutyPaymentType($dutypaytype);
     if ($request->getDhlContentDesc()) {
         $contentdesc = $request->getDhlContentDesc();
     } else {
         $contentdesc = $this->getConfigData('contentdesc');
     }
     $r->setContentDesc($contentdesc);
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     }
     $r->setOrigCountry($origCountry);
     /*
      * DHL only accepts weight as a whole number. Maximum length is 3 digits.
      */
     $shippingWeight = round(min(1, $request->getPackageWeight()), 0);
     $freeMethodWeight = round(min(1, $request->getFreeMethodWeight()), 0);
     $r->setValue(round($request->getPackageValue(), 2));
     $r->setDestStreet(substr($request->getDestStreet(), 0, 35));
     $r->setDestCity($request->getDestCity());
     $r->setDestCountryId($request->getDestCountryId());
     $r->setDestState($request->getDestRegionCode());
     $this->_rawRequest = $r;
     $methods = explode(',', $this->getConfigData('allowed_methods'));
     $freeMethod = $this->getConfigData('free_method');
     $internationcode = $this->getCode('international_searvice');
     foreach ($methods as $method) {
         if ($method == $internationcode && $r->getDestCountryId() != self::USA_COUNTRY_ID || $method != $internationcode && $r->getDestCountryId() == self::USA_COUNTRY_ID) {
             $weight = $freeMethod == $method ? $freeMethodWeight : $shippingWeight;
             if ($weight > 0) {
                 $this->_rawRequest->setWeight($weight);
                 $this->_rawRequest->setService($method);
                 $this->_getQuotes();
             } else {
                 $this->_dhlRates[$method] = array('term' => $this->getCode('service', $method), 'price_total' => 0);
             }
         }
     }
     return $this;
 }
 /**
  * Return table rate array or false by rate request
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  *
  * @return array|false
  */
 public function getRate(Mage_Shipping_Model_Rate_Request $request)
 {
     $adapter = $this->_getReadAdapter();
     $bind = array(':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => $request->getDestRegionId(), ':postcode' => $request->getDestPostcode(), ':weight' => (double) $request->getPackageWeight(), ':price' => (double) $request->getData('zitec_table_price'));
     $select = $adapter->select()->from($this->getMainTable())->where('website_id=:website_id')->order(array('dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC', 'method DESC', 'price_vs_dest DESC', 'weight DESC'));
     // render destination condition
     $orWhere = '(' . implode(') OR (', array("dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = :postcode", "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = ''")) . ')';
     $select->where($orWhere);
     $select->where('((weight <= :weight and price_vs_dest = 0) or (weight <= :price and price_vs_dest = 1))');
     $rates = $adapter->fetchAll($select, $bind);
     if (empty($rates)) {
         $rates = Mage::getModel('zitec_dpd/config_source_service')->getDefaultShipingRates();
     }
     return $rates;
 }
Exemple #22
0
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setAction($this->getCode('action', 'single'));
         $r->setProduct($request->getLimitMethod());
     } else {
         $r->setAction($this->getCode('action', 'all'));
         $r->setProduct('GNDRES');
     }
     if ($request->getUpsPickup()) {
         $pickup = $request->getUpsPickup();
     } else {
         $pickup = $this->getConfigData('pickup');
     }
     $r->setPickup($this->getCode('pickup', $pickup));
     if ($request->getUpsContainer()) {
         $container = $request->getUpsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($this->getCode('container', $container));
     if ($request->getUpsDestType()) {
         $destType = $request->getUpsDestType();
     } else {
         $destType = $this->getConfigData('dest_type');
     }
     $r->setDestType($this->getCode('dest_type', $destType));
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     }
     $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     } else {
     }
     $r->setWeight($request->getPackageWeight());
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     if ($request->getUpsUnitMeasure()) {
         $unit = $request->getUpsUnitMeasure();
     } else {
         $unit = $this->getConfigData('unit_of_measure');
     }
     $r->setUnitMeasure($unit);
     $this->_rawRequest = $r;
     return $this;
 }
 /**
  * Make initial checks and iniciate module variables
  *
  * @param Mage_Shipping_Model_Rate_Request $request Mage request
  *
  * @return bool
  */
 protected function _inicialCheck(Mage_Shipping_Model_Rate_Request $request)
 {
     if (!$this->getConfigFlag('active')) {
         // Disabled
         Mage::log('pedroteixeira_correios: Disabled');
         return false;
     }
     $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     $destCountry = $request->getDestCountryId();
     if ($origCountry != 'BR' || $destCountry != 'BR') {
         // Out of delivery area
         Mage::log('pedroteixeira_correios: Out of delivery area');
         return false;
     }
     $this->_fromZip = Mage::getStoreConfig('shipping/origin/postcode', $this->getStore());
     $this->_toZip = $request->getDestPostcode();
     // Fix ZIP code
     $this->_fromZip = str_replace(array('-', '.'), '', trim($this->_fromZip));
     $this->_toZip = str_replace(array('-', '.'), '', trim($this->_toZip));
     if (!preg_match('/^([0-9]{8})$/', $this->_fromZip)) {
         Mage::log('pedroteixeira_correios: From ZIP Code Error');
         return false;
     }
     $this->_result = Mage::getModel('shipping/rate_result');
     $this->_packageValue = $request->getBaseCurrency()->convert($request->getPackageValue(), $request->getPackageCurrency());
     $this->_packageWeight = number_format($request->getPackageWeight(), 2, '.', '');
     $this->_freeMethodWeight = number_format($request->getFreeMethodWeight(), 2, '.', '');
 }
 /**
  * Prepare and set request to this instance
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return Mage_Usa_Model_Shipping_Carrier_Usps
  */
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     } else {
         $r->setService('ALL');
     }
     if ($request->getUspsUserid()) {
         $userId = $request->getUspsUserid();
     } else {
         $userId = $this->getConfigData('userid');
     }
     $r->setUserId($userId);
     if ($request->getUspsContainer()) {
         $container = $request->getUspsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($container);
     if ($request->getUspsSize()) {
         $size = $request->getUspsSize();
     } else {
         $size = $this->getConfigData('size');
     }
     $r->setSize($size);
     if ($request->getGirth()) {
         $girth = $request->getGirth();
     } else {
         $girth = $this->getConfigData('girth');
     }
     $r->setGirth($girth);
     if ($request->getHeight()) {
         $height = $request->getHeight();
     } else {
         $height = $this->getConfigData('height');
     }
     $r->setHeight($height);
     if ($request->getLength()) {
         $length = $request->getLength();
     } else {
         $length = $this->getConfigData('length');
     }
     $r->setLength($length);
     if ($request->getWidth()) {
         $width = $request->getWidth();
     } else {
         $width = $this->getConfigData('width');
     }
     $r->setWidth($width);
     if ($request->getUspsMachinable()) {
         $machinable = $request->getUspsMachinable();
     } else {
         $machinable = $this->getConfigData('machinable');
     }
     $r->setMachinable($machinable);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_ZIP, $request->getStoreId()));
     }
     if ($request->getOrigCountryId()) {
         $r->setOrigCountryId($request->getOrigCountryId());
     } else {
         $r->setOrigCountryId(Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_COUNTRY_ID, $request->getStoreId()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountryId($destCountry);
     if (!$this->_isUSCountry($destCountry)) {
         $r->setDestCountryName($this->_getCountryName($destCountry));
     }
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeightPounds(floor($weight));
     $r->setWeightOunces(round(($weight - floor($weight)) * self::OUNCES_POUND, 1));
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #25
0
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     } else {
         $r->setService('ALL');
     }
     if ($request->getUspsUserid()) {
         $userId = $request->getUspsUserid();
     } else {
         $userId = $this->getConfigData('userid');
     }
     $r->setUserId($userId);
     if ($request->getUspsContainer()) {
         $container = $request->getUspsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($container);
     if ($request->getUspsSize()) {
         $size = $request->getUspsSize();
     } else {
         $size = $this->getConfigData('size');
     }
     $r->setSize($size);
     if ($request->getUspsMachinable()) {
         $machinable = $request->getUspsMachinable();
     } else {
         $machinable = $this->getConfigData('machinable');
     }
     $r->setMachinable($machinable);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode'));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountryId($destCountry);
     /*
     for GB, we cannot use United Kingdom
     */
     if ($destCountry == 'GB') {
         $countryName = 'Great Britain and Northern Ireland';
     } else {
         $countries = Mage::getResourceModel('directory/country_collection')->addCountryIdFilter($destCountry)->load()->getItems();
         $country = array_shift($countries);
         $countryName = $country->getName();
     }
     $r->setDestCountryName($countryName);
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeightPounds(floor($weight));
     $r->setWeightOunces(round(($weight - floor($weight)) * 16, 1));
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #26
0
 /**
  * Collects the shipping rates for Australia Post from the DRC API.
  *
  * @param Mage_Shipping_Model_Rate_Request $data
  * @return Mage_Shipping_Model_Rate_Result
  */
 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
 {
     // Check if this method is active
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     // Check if this method is even applicable (shipping from Australia)
     $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
     if ($origCountry != "AU") {
         return false;
     }
     $result = Mage::getModel('shipping/rate_result');
     // TODO: Add some more validations
     $frompcode = Mage::getStoreConfig('shipping/origin/postcode', $this->getStore());
     $topcode = $request->getDestPostcode();
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = "AU";
     }
     // Here we get the weight (and convert it to grams) and set some
     // sensible defaults for other shipping parameters.
     $sweight = (int) ((double) $request->getPackageWeight() * (double) $this->getConfigData('weight_units'));
     $sheight = $swidth = $slength = 100;
     $shipping_num_boxes = 1;
     // Switch between domestic and international shipping methods based
     // on destination country.
     if ($destCountry == "AU") {
         //============= Domestic Shipping ==================
         $shipping_methods = array('STANDARD', 'EXPRESS');
         foreach ($shipping_methods as $shipping_method) {
             $drc = $this->_drcRequest($shipping_method, $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
             if ($drc['err_msg'] == 'OK') {
                 // Check for registered post activation. If so, add extra options
                 if ($this->getConfigData('registered_post')) {
                     $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                     $title = $this->getConfigData('name') . " " . ucfirst(strtolower($shipping_method)) . $title_days;
                     $charge = $drc['charge'];
                     $charge += $this->getConfigData('registered_post_charge');
                     if ($this->getConfigData('person_to_person')) {
                         $charge += 5.5;
                     } elseif ($this->getConfigData('delivery_confirmation')) {
                         $charge += 1.85;
                     }
                     $method = $this->_createMethod($request, $shipping_method, $title, $charge, $charge);
                     $result->append($method);
                     // Insurance only covers up to $5000 worth of goods.
                     $packageValue = $request->getPackageValue() > 5000 ? 5000 : $request->getPackageValue();
                     // Insurance cost is $1.25 per $100 or part thereof. First $100 is
                     // included in normal registered post costs.
                     $insurance = (ceil($packageValue / 100) - 1) * 1.25;
                     // Only add a new method if the insurance is different
                     if ($insurance > 0) {
                         $charge += $insurance;
                         $title = $this->getConfigData('name') . " " . ucfirst(strtolower($shipping_method)) . ' with Extra Cover';
                         $method = $this->_createMethod($request, $shipping_method . '_EC', $title, $charge, $charge);
                         $result->append($method);
                     }
                 } else {
                     $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                     $title = $this->getConfigData('name') . " " . ucfirst(strtolower($shipping_method)) . $title_days;
                     $method = $this->_createMethod($request, $shipping_method, $title, $drc['charge'], $drc['charge']);
                     $result->append($method);
                 }
             }
         }
     } else {
         //============= International Shipping ==================
         // International shipping options are highly dependent upon whether
         // or not you are using registered post.
         if ($this->getConfigData('registered_post')) {
             //============= Registered Post ================
             // Registered Post International
             // Same price as Air Mail, plus $5. Extra cover is not available.
             // A weight limit of 2kg applies.
             if ($sweight <= 2000) {
                 $drc = $this->_drcRequest('AIR', $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
                 if ($drc['err_msg'] == 'OK') {
                     $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                     $title = $this->getConfigData('name') . ' Registered Post International' . $title_days;
                     // RPI is another 5 dollars.
                     $charge = $drc['charge'] + 5;
                     if ($this->getConfigData('delivery_confirmation')) {
                         $charge += 3.3;
                     }
                     $charge += $this->getConfigData('registered_post_charge');
                     $method = $this->_createMethod($request, 'AIR', $title, $charge, $charge);
                     $result->append($method);
                 }
             }
             // Express Post International
             $drc = $this->_drcRequest('EPI', $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
             if ($drc['err_msg'] == 'OK') {
                 $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                 $title = $this->getConfigData('name') . ' Express Post International' . $title_days;
                 $charge = $drc['charge'];
                 if ($this->getConfigData('delivery_confirmation')) {
                     $charge += 3.3;
                 }
                 $charge += $this->getConfigData('registered_post_charge');
                 $method = $this->_createMethod($request, 'EPI', $title, $charge, $charge);
                 $result->append($method);
                 // Insurance only covers up to $5000 worth of goods.
                 $packageValue = $request->getPackageValue() > 5000 ? 5000 : $request->getPackageValue();
                 // Insurance cost is $2.25 per $100 or part thereof. First $100 is $8.45.
                 $insurance = 8.449999999999999 + (ceil($packageValue / 100) - 1) * 1.25;
                 $charge += $insurance;
                 $title = $this->getConfigData('name') . ' Express Post International with Extra Cover';
                 $method = $this->_createMethod($request, 'EPI-EC', $title, $charge, $charge);
                 $result->append($method);
             }
             // Express Courier International
             // TODO: Create a table for this method.
         } else {
             //============= Standard Post ================
             // Sea Shipping
             $drc = $this->_drcRequest('SEA', $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
             if ($drc['err_msg'] == 'OK') {
                 $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                 $title = $this->getConfigData('name') . ' Sea Mail' . $title_days;
                 $method = $this->_createMethod($request, 'SEA', $title, $drc['charge'], $drc['charge']);
                 $result->append($method);
             }
             // Air Mail
             $drc = $this->_drcRequest('AIR', $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
             if ($drc['err_msg'] == 'OK') {
                 $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                 $title = $this->getConfigData('name') . ' Air Mail' . $title_days;
                 $method = $this->_createMethod($request, 'AIR', $title, $drc['charge'], $drc['charge']);
                 $result->append($method);
             }
             // Express Post International
             $drc = $this->_drcRequest('EPI', $frompcode, $topcode, $destCountry, $sweight, $slength, $swidth, $sheight, $shipping_num_boxes);
             if ($drc['err_msg'] == 'OK') {
                 $title_days = $drc['days'] == 1 ? ' (1 day)' : ' (' . $drc['days'] . ' days)';
                 $title = $this->getConfigData('name') . ' Express Post International' . $title_days;
                 $method = $this->_createMethod($request, 'EPI', $title, $drc['charge'], $drc['charge']);
                 $result->append($method);
             }
             // Express Courier International
             // TODO: Create a table for this method.
         }
     }
     Mage::log(print_r($result->asArray(), true), null, 'rates.log');
     return $result;
 }
Exemple #27
0
 /**
  * Prepare and set request to this instance
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return Mage_Usa_Model_Shipping_Carrier_Ups
  */
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setAction($this->getCode('action', 'single'));
         $r->setProduct($request->getLimitMethod());
     } else {
         $r->setAction($this->getCode('action', 'all'));
         $r->setProduct('GND' . $this->getConfigData('dest_type'));
     }
     if ($request->getUpsPickup()) {
         $pickup = $request->getUpsPickup();
     } else {
         $pickup = $this->getConfigData('pickup');
     }
     $r->setPickup($this->getCode('pickup', $pickup));
     if ($request->getUpsContainer()) {
         $container = $request->getUpsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($this->getCode('container', $container));
     if ($request->getUpsDestType()) {
         $destType = $request->getUpsDestType();
     } else {
         $destType = $this->getConfigData('dest_type');
     }
     $r->setDestType($this->getCode('dest_type', $destType));
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_COUNTRY_ID, $request->getStoreId());
     }
     $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
     if ($request->getOrigRegionCode()) {
         $origRegionCode = $request->getOrigRegionCode();
     } else {
         $origRegionCode = Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_REGION_ID, $request->getStoreId());
     }
     if (is_numeric($origRegionCode)) {
         $origRegionCode = Mage::getModel('directory/region')->load($origRegionCode)->getCode();
     }
     $r->setOrigRegionCode($origRegionCode);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_ZIP, $request->getStoreId()));
     }
     if ($request->getOrigCity()) {
         $r->setOrigCity($request->getOrigCity());
     } else {
         $r->setOrigCity(Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_CITY, $request->getStoreId()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     //for UPS, puero rico state for US will assume as puerto rico country
     if ($destCountry == self::USA_COUNTRY_ID && ($request->getDestPostcode() == '00912' || $request->getDestRegionCode() == self::PUERTORICO_COUNTRY_ID)) {
         $destCountry = self::PUERTORICO_COUNTRY_ID;
     }
     // For UPS, Guam state of the USA will be represented by Guam country
     if ($destCountry == self::USA_COUNTRY_ID && $request->getDestRegionCode() == self::GUAM_REGION_CODE) {
         $destCountry = self::GUAM_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     $r->setDestRegionCode($request->getDestRegionCode());
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     } else {
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $weight = $this->_getCorrectWeight($weight);
     $r->setWeight($weight);
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     if ($request->getUpsUnitMeasure()) {
         $unit = $request->getUpsUnitMeasure();
     } else {
         $unit = $this->getConfigData('unit_of_measure');
     }
     $r->setUnitMeasure($unit);
     $r->setIsReturn($request->getIsReturn());
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #28
0
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     } else {
         $r->setService('ALL');
     }
     if ($request->getUspsUserid()) {
         $userId = $request->getUspsUserid();
     } else {
         $userId = $this->getConfigData('userid');
     }
     $r->setUserId($userId);
     if ($request->getUspsContainer()) {
         $container = $request->getUspsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($container);
     if ($request->getUspsSize()) {
         $size = $request->getUspsSize();
     } else {
         $size = $this->getConfigData('size');
     }
     $r->setSize($size);
     if ($request->getUspsMachinable()) {
         $machinable = $request->getUspsMachinable();
     } else {
         $machinable = $this->getConfigData('machinable');
     }
     $r->setMachinable($machinable);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig(Mage_Shipping_Model_Config::XML_PATH_ORIGIN_POSTCODE, $this->getStore()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountryId($destCountry);
     if (!$this->_isUSCountry($destCountry)) {
         $r->setDestCountryName($this->_getCountryName($destCountry));
     }
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeightPounds(floor($weight));
     $r->setWeightOunces(round(($weight - floor($weight)) * 16, 1));
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #29
0
 /**
  * Prepare and set request to this instance
  *
  * @param Mage_Shipping_Model_Rate_Request $request
  * @return Mage_Usa_Model_Shipping_Carrier_Fedex
  */
 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
 {
     $this->_request = $request;
     $r = new Varien_Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     }
     if ($request->getFedexAccount()) {
         $account = $request->getFedexAccount();
     } else {
         $account = $this->getConfigData('account');
     }
     $r->setAccount($account);
     if ($request->getFedexDropoff()) {
         $dropoff = $request->getFedexDropoff();
     } else {
         $dropoff = $this->getConfigData('dropoff');
     }
     $r->setDropoffType($dropoff);
     if ($request->getFedexPackaging()) {
         $packaging = $request->getFedexPackaging();
     } else {
         $packaging = $this->getConfigData('packaging');
     }
     $r->setPackaging($packaging);
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_COUNTRY_ID, $request->getStoreId());
     }
     $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal(Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_ZIP, $request->getStoreId()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     } else {
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeight($weight);
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackagePhysicalValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setMeterNumber($this->getConfigData('meter_number'));
     $r->setKey($this->getConfigData('key'));
     $r->setPassword($this->getConfigData('password'));
     $r->setIsReturn($request->getIsReturn());
     $r->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
     $this->_rawRequest = $r;
     return $this;
 }
Exemple #30
0
 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     if ($request->getDestCountry()) {
         $destCountry = $request->getDestCountry();
     }
     $zip = substr($request->getDestPostcode(), 0, 8);
     //echo "zip=(".$zip.")";
     //$request->getDestCity() - Ââåäåíûé Ãîðîä: "Âëàäèâîñòîê"
     //$request->getDestCountryId(); //RU
     //echo '<br>****destCountry='.$destCountry,'<br>****getDestCity='.$request->getDestCity().' getDestRegionId='.$request->getDestRegionId();
     //return $this->PrintDebug( '<br>****destCountry='.$request->getDestCountryId() ); //Âûâîä îòëàäî÷íîé èíôîðìàöèè
     $county_edost = array(1960 => 'AU', 1961 => 'AT', 1962 => 'AZ', 1963 => 'AL', 1964 => 'DZ', 1965 => 'AS', 1966 => 'AI', 1968 => 'AO', 1969 => 'AD', 1970 => 'AG', 1971 => 'AN', 1972 => 'AR', 1973 => 'AM', 1974 => 'AW', 1975 => 'AF', 1976 => 'BS', 1977 => 'BD', 1978 => 'BB', 1979 => 'BH', 1980 => 'BY', 1981 => 'BZ', 1982 => 'BE', 1983 => 'BJ', 1984 => 'BM', 1985 => 'BG', 1986 => 'BO', 1988 => 'BA', 1989 => 'BW', 1990 => 'BR', 1991 => 'BN', 1992 => 'BF', 1993 => 'BI', 1994 => 'BT', 1995 => 'WF', 1996 => 'VU', 1997 => 'GB', 1998 => 'HU', 1999 => 'VE', 2000 => 'VG', 2001 => 'VI', 2002 => 'TL', 2003 => 'VN', 2004 => 'GA', 2005 => 'HT', 2006 => 'GY', 2007 => 'GM', 2008 => 'GH', 2009 => 'GP', 2010 => 'GT', 2011 => 'GN', 2012 => 'GQ', 2013 => 'GW', 2014 => 'DE', 2016 => 'GI', 2017 => 'HN', 2018 => 'HK', 2019 => 'GD', 2020 => 'GL', 2021 => 'GR', 2022 => 'GE', 2023 => 'GU', 2024 => 'DK', 2026 => 'DJ', 2027 => 'DM', 2028 => 'DO', 2029 => 'EG', 2030 => 'ZM', 2031 => 'CV', 2032 => 'ZW', 2033 => 'IL', 2034 => 'IN', 2035 => 'ID', 2036 => 'JO', 2037 => 'IQ', 2038 => 'IR', 2039 => 'IE', 2040 => 'IS', 2041 => 'ES', 2042 => 'IT', 2043 => 'YE', 2044 => 'KZ', 2045 => 'KY', 2046 => 'KH', 2047 => 'CM', 2048 => 'CA', 2049 => 'EQ', 2050 => 'QA', 2051 => 'KE', 2052 => 'CY', 2053 => 'KI', 2054 => 'CN', 2055 => 'CO', 2056 => 'KM', 2057 => 'CG', 2058 => 'CD', 2059 => 'KP', 2060 => 'KR', 2062 => 'CR', 2063 => 'CI', 2064 => 'CU', 2065 => 'KW', 2066 => 'CK', 2067 => 'KG', 2069 => 'LA', 2070 => 'LV', 2071 => 'LS', 2072 => 'LR', 2073 => 'LB', 2074 => 'LY', 2075 => 'LT', 2076 => 'LI', 2077 => 'LU', 2078 => 'MU', 2079 => 'MR', 2080 => 'MG', 2081 => 'YT', 2082 => 'MO', 2083 => 'MK', 2084 => 'MW', 2085 => 'MY', 2086 => 'ML', 2087 => 'MV', 2088 => 'MT', 2089 => 'MA', 2090 => 'MQ', 2091 => 'MH', 2092 => 'MX', 2093 => 'FM', 2094 => 'MZ', 2095 => 'MD', 2096 => 'MC', 2097 => 'MN', 2098 => 'MS', 2099 => 'MM', 2100 => 'NA', 2101 => 'NR', 2102 => 'KN', 2103 => 'NP', 2104 => 'NE', 2105 => 'NG', 2106 => 'NL', 2107 => 'NI', 2108 => 'NU', 2109 => 'NZ', 2110 => 'NC', 2111 => 'NO', 2112 => 'AE', 2113 => 'OM', 2114 => 'PK', 2115 => 'PW', 2116 => 'PA', 2117 => 'PG', 2118 => 'PY', 2119 => 'PE', 2120 => 'PL', 2121 => 'PT', 2122 => 'PR', 2123 => 'RE', 2124 => 'RW', 2125 => 'RO', 2126 => 'MP', 2127 => 'SV', 2128 => 'WS', 2129 => 'SM', 2130 => 'ST', 2131 => 'SA', 2132 => 'SZ', 2134 => 'SC', 2136 => 'SN', 2137 => 'VC', 2138 => 'KN', 2139 => 'KN', 2140 => 'LC', 2145 => 'SG', 2146 => 'SY', 2147 => 'SK', 2148 => 'SI', 2149 => 'SB', 2150 => 'SO', 2152 => 'SD', 2153 => 'SR', 2154 => 'US', 2155 => 'SL', 2156 => 'TJ', 2157 => 'TH', 2158 => 'PF', 2159 => 'TW', 2160 => 'TZ', 2161 => 'TG', 2162 => 'TO', 2163 => 'TT', 2164 => 'TV', 2165 => 'TN', 2166 => 'TM', 2167 => 'TC', 2168 => 'TR', 2169 => 'UG', 2170 => 'UZ', 2171 => 'UA', 2172 => 'UY', 2174 => 'FO', 2175 => 'FJ', 2176 => 'PH', 2177 => 'FI', 2178 => 'FK', 2179 => 'FR', 2180 => 'GF', 2181 => 'PF', 2182 => 'HR', 2183 => 'CF', 2184 => 'TD', 2186 => 'CZ', 2187 => 'CL', 2188 => 'CH', 2189 => 'SE', 2191 => 'LK', 2192 => 'EC', 2193 => 'ER', 2194 => 'EE', 2195 => 'ET', 2196 => 'ZA', 2197 => 'JM', 2198 => 'JP', 0 => 'RU');
     $country = array_search($request->getDestCountryId(), $county_edost);
     //echo '<br>****getDestCountryId='.$request->getDestCountryId().' - edost_id='.$country; //RU
     //echo '<br>****getDestRegionId='.$request->getDestRegionId(); //êîä ãîðîäà èëè ðåãèîíà edost
     $edost_calc = new edost_class();
     //ïàðîëü è id ìàãàçèíà
     $edost_calc->edost_id = $this->getConfigData('id');
     $edost_calc->edost_pswd = $this->getConfigData('password');
     $edost_calc->SetSiteUTF();
     $strah = $request->getPackageValue();
     //îöåíêà
     $host = trim(strtolower($this->getConfigData('gateway_url')));
     if (substr($host, 0, 7) == "http://") {
         $host = substr($host, 7, 100);
     }
     //if (substr($host,0,4) == "www.") $host = substr($host,4,100);
     if ($host == '') {
         $edost_calc->adr = EDOST_ADDR;
     } else {
         $edost_calc->adr = "http://" . $host . "/" . EDOST_PAGE;
     }
     //îïðåäåëÿåì ñòðàíó è ãîðîä êëèåíòà
     $country_hide = false;
     if ($country_hide) {
         $country = 0;
     }
     //ò.ê. ïî óìîë÷àíèþ ïðèñâàèâàåò US, åñëè íå âûáðàíà ñòðàíà
     if (!$country) {
         $country = 0;
     }
     //RU
     if (isset($_SESSION['city_for_cart'])) {
         $to_city = Mage::getModel('directory/region')->load($_SESSION['city_for_cart'])->getCode();
         //ãîðîä èëè ðåãèîí
         $city_code = Mage::getModel('directory/region')->load($_SESSION['city_for_cart'])->getCdekCode();
     } else {
         if ($country == 0) {
             $to_city = Mage::getModel('directory/region')->load($request->getDestRegionId())->getCode();
             //ãîðîä èëè ðåãèîí
             $city_code = Mage::getModel('directory/region')->load($request->getDestRegionId())->getCdekCode();
         } else {
             $to_city = $country;
             $city_code = '0';
         }
     }
     /*		if($country==0)
     			$to_city = Mage::getModel('directory/region')->load( $request->getDestRegionId() )->getCode(); //ãîðîä èëè ðåãèîí
     		else
     			$to_city = $country;
     */
     //$weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     /*        $packageParams = $request->getPackageParams();
             $height = $packageParams->getHeight();
             $width = $packageParams->getWidth();
             $length = $packageParams->getLength();
     		echo "<br>*** height=$height,  width=$width,  length=$length";
     */
     //echo $cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
     /*		Mage::getSingleton('core/session', array('name'=>'frontend'));
     		$cart = Mage::getModel('checkout/cart');
     		$ids = $cart->getProductIds();
     		print_r($ids);
     		foreach ($ids as $i=>$productId) {
     			echo "<br>id=$id ($i)";
     			$product = Mage::getModel('catalog/product')->load($productId);
     			$attributes = $product->getAttributes();
     
     			foreach ($attributes as $attribute) {
     				$attributeCode = $attribute->getAttributeCode();
     				if ($attributeCode == 'length') {
     					$value = $attribute->getFrontend()->getValue($product);
     					echo $attributeCode . '-' . '-' . $value;
     				}
     			}
     
     		}
     */
     $session = Mage::getSingleton('checkout/session');
     $output = "<br>";
     $weight = 0;
     $size_in = null;
     $weight_zero = false;
     $k = 0;
     if (isset($_SESSION['product_for_cart'])) {
         $products_in_session[0] = $_SESSION['product_for_cart'];
     } else {
         $products_in_session = $session->getQuote()->getAllVisibleItems();
     }
     $sdbg = '';
     //getAllItems() - íåëüçÿ, ò.ê. ïîÿâëÿþòñÿ äóáëè òîâàðîâ â êîðçèíå!
     foreach ($products_in_session as $item) {
         if (isset($_SESSION['productid'])) {
             $productId = $_SESSION['productid'];
             $item = Mage::getModel('catalog/product')->load($productId);
             $price_final = $item->getFinalPrice();
             $qty = '1';
         } else {
             $productId = $item->getProductId();
             $price_final = $item->getBaseCalculationPrice();
             $qty = $item->getQty();
         }
         $sdbg .= '<br>************* Sku=' . $item->getSku() . "<br>Name=" . $item->getName() . "<br>" . $item->getDescription() . "<br>BaseCalculationPrice=" . $price_final . "<br>ProductId=" . $productId . "<br>Weight=" . $item->getWeight() . "<br>Qty=" . $qty;
         //."<br><pre>".print_r($item, true)."</pre>"
         //echo "<br>************************ <pre>".print_r($item, true)."</pre>";
         $weight += $item->getWeight() * $qty;
         if (!($item->getWeight() > 0)) {
             $weight_zero = true;
         }
         $product = Mage::getModel('catalog/product')->load($productId);
         $attributes = $product->getAttributes();
         $x = 0;
         $y = 0;
         $z = 0;
         foreach ($attributes as $attribute) {
             $attributeCode = $attribute->getAttributeCode();
             if ($attributeCode == 'length') {
                 $x = $attribute->getFrontend()->getValue($product);
             }
             if ($attributeCode == 'width') {
                 $y = $attribute->getFrontend()->getValue($product);
             }
             if ($attributeCode == 'height') {
                 $z = $attribute->getFrontend()->getValue($product);
             }
         }
         $sdbg .= '<br>******' . "<br>productId = {$productId} , length={$x} , width={$y} , height={$z}";
         //echo "<br>length=$x , width=$y , height=$z";
         if ($x > 0 && $y > 0 && $z > 0) {
             // ðàñ÷åò ãàáàðèòîâ òîâàðà (åñëè äàííîãî òîâàðà íåñêîëüêî åäèíèö, òîãäà îíè âñå ñêëàäûâàþòñÿ â îäèí ÿùèê)
             $size_one = $edost_calc->SumSizeOneGoods($x, $y, $z, $item->getQty());
             $size_in[] = array('X' => $size_one['X'], 'Y' => $size_one['Y'], 'Z' => $size_one['Z']);
             //$sdbg .= '<br>******'."<br>length=".$size_in[$k]['X']." , width=".$size_in[$k]['Y']." , height=".$size_in[$k]['Z'];
             $k++;
         } else {
             $weight_zero = true;
         }
     }
     if ($weight_zero) {
         $weight = 0;
     }
     //return $this->PrintDebug( '<br>****='.$sdbg.' = '.'<br>' ); //Âûâîä îòëàäî÷íîé èíôîðìàöèè
     //return $this->PrintDebug( '<br>****to_city='.$to_city.' = '.$weight ); //Âûâîä îòëàäî÷íîé èíôîðìàöèè
     //echo '<br>*** to_city='.$to_city.' , WEIGHT='.$weight.' , strah='.$strah;
     //echo '<br>*** to_city='.$to_city.' , WEIGHT='.$weight.' , strah='.$strah.' , id='.$this->getConfigData('id').' , ps='.$this->getConfigData('password');
     //Ñóììèðóåì ðàçìåðû ãðóçà
     $size = $edost_calc->SumSize($size_in);
     $length = $size['length'];
     $width = $size['width'];
     $height = $size['height'];
     //echo "<br>length=$length , width=$width , height=$height";
     //return $this->PrintDebug( '<br>****='."<br>length=$length , width=$width , height=$height".' = '.'<br>'."<br><pre>".print_r($size_in, true)."</pre>" ); //Âûâîä îòëàäî÷íîé èíôîðìàöèè
     $result = Mage::getModel('shipping/rate_result');
     $r = $edost_calc->edost_calc($to_city, $weight, $strah, $length, $width, $height, $zip);
     if ($city_code != '0') {
         $dop_tarif_mag = $edost_calc->calculateMag($city_code, $weight, $length, $width, $height);
         $dop_tarif_ekonom = $edost_calc->calculateEkonom($city_code, $weight, $length, $width, $height);
         if ($dop_tarif_mag['result']) {
             $method = Mage::getModel('shipping/rate_result_method');
             $method->setCarrier('edost');
             $method->setCarrierTitle('Магистральный экспресс склад-склад');
             $method->setMethod('dop1');
             $method->setMethodTitle('Магистральный экспресс склад-склад');
             $method->setCost($dop_tarif_mag['result']['price']);
             $method->setPrice($dop_tarif_mag['result']['price']);
             $result->append($method);
         }
         if ($dop_tarif_ekonom['result']) {
             $method = Mage::getModel('shipping/rate_result_method');
             $method->setCarrier('edost');
             $method->setCarrierTitle('Экономичный экспресс   склад-склад');
             $method->setMethod('dop2');
             $method->setMethodTitle('Экономичный экспресс   склад-склад');
             $method->setCost($dop_tarif_ekonom['result']['price']);
             $method->setPrice($dop_tarif_ekonom['result']['price']);
             $result->append($method);
         }
     }
     //== Âûâîä ðåçóëüòàòîâ ============================================
     $st = '';
     if ($r['qty_company'] == 0) {
         switch ($r['stat']) {
             // êîäû îøèáîê èç ãëàâíîãî çàïðîñà íà ñåðâåð edost
             case 0:
                 $st = '';
                 break;
             case 1:
                 $st = '';
                 break;
                 //ÓÑÏÅÕ ðàñ÷åòà, íî ïîäõîäÿùèõ òàðèôîâ íå íàøëîñü
             //ÓÑÏÅÕ ðàñ÷åòà, íî ïîäõîäÿùèõ òàðèôîâ íå íàøëîñü
             case 2:
                 $st = Mage::helper('rus')->__("edost_err2");
                 break;
                 //"Äîñòóï ê ðàñ÷åòó çàáëîêèðîâàí"
             //"Äîñòóï ê ðàñ÷åòó çàáëîêèðîâàí"
             case 3:
                 $st = Mage::helper('rus')->__("edost_err3");
                 break;
                 //"Íå âåðíûå äàííûå ìàãàçèíà (ïàðîëü èëè èäåíòèôèêàòîð)"
             //"Íå âåðíûå äàííûå ìàãàçèíà (ïàðîëü èëè èäåíòèôèêàòîð)"
             case 4:
                 $st = Mage::helper('rus')->__("edost_err4");
                 break;
                 //"Íå âåðíûå âõîäíûå ïàðàìåòðû"
             //"Íå âåðíûå âõîäíûå ïàðàìåòðû"
             case 5:
                 $st = Mage::helper('rus')->__("edost_err5");
                 break;
                 //"Íå âåðíûé ãîðîä èëè ñòðàíà"
             //"Íå âåðíûé ãîðîä èëè ñòðàíà"
             case 6:
                 $st = Mage::helper('rus')->__("edost_err6");
                 break;
                 //"Âíóòðåííÿÿ îøèáêà ñåðâåðà ðàñ÷åòîâ"
             //"Âíóòðåííÿÿ îøèáêà ñåðâåðà ðàñ÷åòîâ"
             case 7:
                 $st = Mage::helper('rus')->__("edost_err7");
                 break;
                 //"Íå çàäàíû êîìïàíèè äîñòàâêè â íàñòðîéêàõ ìàãàçèíà"
             //"Íå çàäàíû êîìïàíèè äîñòàâêè â íàñòðîéêàõ ìàãàçèíà"
             case 8:
                 $st = Mage::helper('rus')->__("edost_err8");
                 break;
                 //"Ñåðâåð ðàñ÷åòà íå îòâå÷àåò"
             //"Ñåðâåð ðàñ÷åòà íå îòâå÷àåò"
             case 9:
                 $st = Mage::helper('rus')->__("edost_err9");
                 break;
                 //"Ïðåâûøåí ëèìèò ðàñ÷åòîâ çà äåíü"
             //"Ïðåâûøåí ëèìèò ðàñ÷åòîâ çà äåíü"
             case 10:
                 $st = Mage::helper('rus')->__("edost_err10");
                 break;
                 //"Íå âåðíûé ôîðìàò XML"
             //"Íå âåðíûé ôîðìàò XML"
             case 11:
                 $st = Mage::helper('rus')->__("edost_err11");
                 break;
                 //"Íå óêàçàí âåñ"
             //"Íå óêàçàí âåñ"
             case 12:
                 $st = Mage::helper('rus')->__("edost_err12");
                 break;
                 //"Íå çàäàíû äàííûå ìàãàçèíà (ïàðîëü èëè èäåíòèôèêàòîð)"
             //"Íå çàäàíû äàííûå ìàãàçèíà (ïàðîëü èëè èäåíòèôèêàòîð)"
             case 14:
                 $st = Mage::helper('rus')->__("edost_err14");
                 break;
                 //"Íàñòðîéêè ñåðâåðà íå ïîçâîëÿþò îòïðàâèòü çàïðîñ íà ðàñ÷åò"
             //"Íàñòðîéêè ñåðâåðà íå ïîçâîëÿþò îòïðàâèòü çàïðîñ íà ðàñ÷åò"
             default:
                 $st = Mage::helper('rus')->__("edost_err0");
                 //"Îøèáêà ðàñ÷åòà."
         }
         if ($city_code != 0) {
             $st = 15;
         }
         //if ( ($r['stat']>=2) and ($r['stat']<=12) ) {
         if ($this->getConfigData('hide_err')) {
             $st = '';
         }
         //}
         if ($st != '' && $st != '15') {
             //Âûâîä îøèáêè - òàê ïðàâèëüíî ðàáîòàåò!!!
             $result = Mage::getModel('shipping/rate_result_error');
             $result->setCarrier('edost');
             $result->setCarrierTitle($this->getConfigData('title'));
             $result->setErrorMessage($st);
             return $result;
         }
         //<br> äàííûé ãîðîä àâòîìàòè÷åñêèé ðàñ÷åò äîñòàâêè íå îñóùåñòâëÿåòñÿ. Î âîçìîæíîñòè è ñòîèìîñòè äîñòàâêè, ïîæàëóéñòà, óòî÷íèòå ó ìåíåäæåðà.
         if ($this->getConfigData('show_msg')) {
             //				$st = '';
             //курьер
             $mba = 'blankshippingmodule';
             if (Mage::getStoreConfig('carriers/' . $mba . '/active')) {
                 $config = Mage::getStoreConfig('carriers/' . $mba);
                 $session = Mage::getSingleton('checkout/session');
                 $sum = 0;
                 foreach ($products_in_session as $item) {
                     if (isset($_SESSION['productid'])) {
                         $productId = $_SESSION['productid'];
                         $item = Mage::getModel('catalog/product')->load($productId);
                         $price_final = $item->getFinalPrice();
                         $qty = '1';
                     } else {
                         $productId = $item->getProductId();
                         $price_final = $item->getBaseCalculationPrice();
                         $qty = $item->getQty();
                     }
                     $sum += $qty * $item->getWeight();
                 }
                 $session = Mage::getSingleton('core/session');
                 $session_geo_ip = $session->getGeoIp();
                 if (isset($session_geo_ip['code'])) {
                     $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
                     if (!isset($ship_data['name']) || $ship_data['dscr'] == '') {
                         return false;
                     } else {
                         if ($ship_data['name'] == '2137') {
                             $cost = $config['moscow_ship'];
                         } else {
                             if ($ship_data['name'] == '2344') {
                                 $cost = $config['piter_ship'];
                             } else {
                                 $km = $ship_data['dscr'];
                                 if ($km < 5) {
                                     $cost = $config['mkad_shipdo5'] + $config['piter_ship'];
                                 } else {
                                     if ($km >= 5 && $km < 10) {
                                         $cost = $config['mkad_shipdo10'] + $config['piter_ship'];
                                     } else {
                                         $cost = $ship_data['dscr'] * $config['mkad_shipb10'] + $config['piter_ship'];
                                     }
                                 }
                             }
                         }
                         $result = Mage::getModel('shipping/rate_result');
                         $method = Mage::getModel('shipping/rate_result_method');
                         //Стоимость курьера
                         $method->setCarrier('edost');
                         $method->setCarrierTitle('Курьерская доставка');
                         $method->setMethod('pickup1');
                         $method->setMethodTitle('');
                         $method->setCost($cost);
                         $method->setPrice($cost);
                         $result->append($method);
                         //Стоимость
                         if ($sum < 25) {
                             $method = Mage::getModel('shipping/rate_result_method');
                             $method->setCarrier('freeshipping');
                             $method->setCarrierTitle('Самовывоз в пункте Курьер.ру г.Москва');
                             $method->setMethod('pickup2');
                             $method->setMethodTitle('Самовывоз в пункте Курьер.ру г.Москва');
                             $method->setCost($config['ship_sam']);
                             $method->setPrice($config['ship_sam']);
                             $result->append($method);
                         }
                     }
                 }
             }
             $cour = 'morphescourier';
             if (Mage::getStoreConfig('carriers/' . $cour . '/active')) {
                 $session = Mage::getSingleton('checkout/session');
                 $sum = 0;
                 foreach ($session->getQuote()->getAllVisibleItems() as $item) {
                     if (isset($_SESSION['productid'])) {
                         $productId = $_SESSION['productid'];
                         $item = Mage::getModel('catalog/product')->load($productId);
                         $price_final = $item->getFinalPrice();
                         $qty = '1';
                     } else {
                         $productId = $item->getProductId();
                         $price_final = $item->getBaseCalculationPrice();
                         $qty = $item->getQty();
                     }
                     $sum += $qty * $item->getWeight();
                 }
                 $session = Mage::getSingleton('core/session');
                 $session_geo_ip = $session->getGeoIp();
                 if (isset($session_geo_ip['code'])) {
                     $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
                     if (!isset($ship_data['name'])) {
                         return false;
                     } else {
                         $diap = array('20', '15', '10', '5', '3', '1');
                         $costs = explode(';', $ship_data['costs']);
                         $costs = array_reverse($costs);
                         $count = 0;
                         foreach ($diap as $value) {
                             if ($sum < (int) $value) {
                                 $cost_cour = $ship_data['km' . $value];
                                 //Курьерская стоимость
                                 $cost_sam = $costs[$count];
                                 //Стоимость самовывоза
                             }
                             $count++;
                         }
                         $diap_km = array('50' => '500', '45' => '450', '40' => '400', '35' => '350', '30' => '300', '25' => '250', '20' => '200', '15' => '150', '10' => '100', '5' => '50');
                         if ($ship_data['dscr'] != '') {
                             foreach ($diap_km as $km => $cost) {
                                 if ($ship_data['dscr'] <= $km) {
                                     $cost_dop_km = $cost;
                                 }
                             }
                         } else {
                             $cost_dop_km = 0;
                         }
                         if ($ship_data['dscr'] == '0') {
                             $cost_dop_km = 500;
                         }
                         /*$result = Mage::getModel('shipping/rate_result');
                           $method = Mage::getModel('shipping/rate_result_method');
                           $method->setCarrier('edost');
                           $method->setCarrierTitle('Доставка курьером');
                           $method->setMethod('pickup0');
                           $method->setMethodTitle('Доставка курьером');
                           $method->setCost($cost_cour);
                           $method->setPrice($cost_cour+$cost_dop_km);
                           $result->append($method);*/
                         $addresses = explode(';', $ship_data['addressess']);
                         $count = 1;
                         if ($sum < 25) {
                             foreach ($addresses as $address) {
                                 $method = Mage::getModel('shipping/rate_result_method');
                                 $method->setCarrier('freeshipping');
                                 $method->setCarrierTitle('Im-Logistics Пункт Самовывоза');
                                 $method->setMethod('pickup' . $count);
                                 $method->setMethodTitle($address . ' Logistic');
                                 $method->setCost($cost_sam);
                                 $method->setPrice($cost_sam);
                                 $result->append($method);
                                 $count++;
                             }
                         }
                     }
                 }
             }
             $rate = Mage::getModel('shipping/rate_result_method');
             $rate->setCarrier('edost');
             $rate->setCarrierTitle($this->getConfigData('title'));
             $rate->setMethod('error');
             $rate->setMethodTitle($this->getConfigData('specificerrmsg'));
             $rate->setCost(0);
             //
             $rate->setPrice(0);
             //öåíà âûâîäèìàÿ (cost+handling)
             //  $result->append($rate);
         }
     } else {
         //ïåðåâîäèì èç ðóáëåé â âàëþòó ìàãàçèíà
         $baseCurr = Mage::app()->getStore()->getBaseCurrency();
         //echo "<br><pre>",print_r($baseCurr),"</pre>";
         $allCurr = Mage::app()->getStore()->getAvailableCurrencyCodes();
         //echo "<br><pre>",print_r($allCurr),"</pre>";
         if (!in_array('RUB', $allCurr) or $baseCurr->getRate('RUB') == 0) {
             //Âûâîä îøèáêè - òàê ïðàâèëüíî ðàáîòàåò!!!
             $result = Mage::getModel('shipping/rate_result_error');
             $result->setCarrier('edost');
             $result->setCarrierTitle($this->getConfigData('title'));
             $result->setErrorMessage('eDost: Not Available Currency RUB!');
             return $result;
         }
         if ($baseCurr->getCode() != 'RUB') {
             $rateToBase = $baseCurr->getRate('RUB');
         }
         for ($i = 1; $i <= $r['qty_company']; $i++) {
             if ($r['name' . $i] == '') {
                 $q = '';
             } else {
                 $q = $r['name' . $i];
             }
             if ($r['day' . $i] == '&nbsp;') {
                 $q .= '';
             } else {
                 $q .= $q == '' ? $r['day' . $i] : ', ' . $r['day' . $i];
             }
             $priceCurrency = $r['price' . $i];
             if ($baseCurr->getCode() != 'RUB') {
                 $priceCurrency = round($priceCurrency / $rateToBase, 2);
             }
             $strDelivery = $r["company" . $i];
             if ($q != '') {
                 $strDelivery .= ' (' . $q . ')';
             }
             $session = Mage::getSingleton('core/session');
             $session_geo_ip = $session->getGeoIp();
             if (isset($session_geo_ip['code'])) {
                 if ($session_geo_ip['code'] == '2137') {
                     if (strpos($strDelivery, 'СДЭК') === false) {
                         $rate = Mage::getModel('shipping/rate_result_method');
                         $rate->setCarrier('edost');
                         $rate->setCarrierTitle($this->getConfigData('title'));
                         $rate->setMethod($r['id' . $i] . '-' . $r['strah' . $i]);
                         $rate->setMethodTitle($strDelivery);
                         $rate->setCost($priceCurrency);
                         //
                         $rate->setPrice($priceCurrency);
                         //öåíà âûâîäèìàÿ (cost+handling)
                         $result->append($rate);
                     }
                 } else {
                     $rate = Mage::getModel('shipping/rate_result_method');
                     $rate->setCarrier('edost');
                     $rate->setCarrierTitle($this->getConfigData('title'));
                     $rate->setMethod($r['id' . $i] . '-' . $r['strah' . $i]);
                     $rate->setMethodTitle($strDelivery);
                     $rate->setCost($priceCurrency);
                     //
                     $rate->setPrice($priceCurrency);
                     //öåíà âûâîäèìàÿ (cost+handling)
                     $result->append($rate);
                 }
             }
         }
         //курьер
         $mba = 'blankshippingmodule';
         if (Mage::getStoreConfig('carriers/' . $mba . '/active')) {
             $config = Mage::getStoreConfig('carriers/' . $mba);
             $session = Mage::getSingleton('checkout/session');
             $sum = 0;
             foreach ($session->getQuote()->getAllVisibleItems() as $item) {
                 $sum += $item->getQty() * $item->getWeight();
             }
             $session = Mage::getSingleton('core/session');
             $session_geo_ip = $session->getGeoIp();
             if (isset($session_geo_ip['code'])) {
                 $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
                 if (!isset($ship_data['name']) || $ship_data['dscr'] == '') {
                     //return false;
                 } else {
                     if ($ship_data['name'] == '2137') {
                         $cost = $config['moscow_ship'];
                     } else {
                         if ($ship_data['name'] == '2344') {
                             $cost = $config['piter_ship'];
                         } else {
                             $km = $ship_data['dscr'];
                             if ($km < 5) {
                                 $cost = $config['mkad_shipdo5'] + $config['piter_ship'];
                             } else {
                                 if ($km >= 5 && $km < 10) {
                                     $cost = $config['mkad_shipdo10'] + $config['piter_ship'];
                                 } else {
                                     $cost = $ship_data['dscr'] * $config['mkad_shipb10'] + $config['piter_ship'];
                                 }
                             }
                         }
                     }
                     //$result = Mage::getModel('shipping/rate_result');
                     $method = Mage::getModel('shipping/rate_result_method');
                     //Стоимость курьера
                     $method->setCarrier('edost');
                     $method->setCarrierTitle('Курьерская доставка');
                     $method->setMethod('pickup1');
                     $method->setMethodTitle('');
                     $method->setCost($cost);
                     $method->setPrice($cost);
                     $result->append($method);
                     //Стоимость самовывоза
                     if ($sum < 25) {
                         $method = Mage::getModel('shipping/rate_result_method');
                         $method->setCarrier('freeshipping');
                         $method->setCarrierTitle('Самовывоз в пункте Курьер.ру г.Москва');
                         $method->setMethod('pickup2');
                         $method->setMethodTitle('Самовывоз в пункте Курьер.ру г.Москва');
                         $method->setCost($config['ship_sam']);
                         $method->setPrice($config['ship_sam']);
                         $result->append($method);
                     }
                 }
             }
         }
         $cour = 'morphescourier';
         if (Mage::getStoreConfig('carriers/' . $cour . '/active')) {
             $session = Mage::getSingleton('checkout/session');
             $sum = 0;
             foreach ($session->getQuote()->getAllVisibleItems() as $item) {
                 $sum += $item->getQty() * $item->getWeight();
             }
             $session = Mage::getSingleton('core/session');
             $session_geo_ip = $session->getGeoIp();
             if (isset($session_geo_ip['code'])) {
                 $ship_data = Mage::getModel('freaks_quotes/quote')->loadByName($session_geo_ip['code']);
                 if (!isset($ship_data['name'])) {
                     //return false;
                 } else {
                     $diap = array('20', '15', '10', '5', '3', '1');
                     $costs = explode(';', $ship_data['costs']);
                     $costs = array_reverse($costs);
                     $count = 0;
                     foreach ($diap as $value) {
                         if ($sum < (int) $value) {
                             $cost_cour = $ship_data['km' . $value];
                             //Курьерская стоимость
                             $cost_sam = $costs[$count];
                             //Стоимость самовывоза
                         }
                         $count++;
                     }
                     $diap_km = array('50' => '500', '45' => '450', '40' => '400', '35' => '350', '30' => '300', '25' => '250', '20' => '200', '15' => '150', '10' => '100', '5' => '50');
                     if ($ship_data['dscr'] != '') {
                         foreach ($diap_km as $km => $cost) {
                             if ($ship_data['dscr'] <= $km) {
                                 $cost_dop_km = $cost;
                             }
                         }
                     } else {
                         $cost_dop_km = 0;
                     }
                     if ($ship_data['dscr'] == '') {
                         $cost_dop_km = 500;
                         $method = Mage::getModel('shipping/rate_result_method');
                         $method->setCarrier('edost');
                         $method->setCarrierTitle('Курьерская доставка');
                         $method->setMethod('pickup1');
                         $method->setMethodTitle('');
                         $method->setCost($cost_dop_km);
                         $method->setPrice($cost_dop_km);
                         $result->append($method);
                     }
                     $addresses = explode(';', $ship_data['addressess']);
                     $count = 1;
                     if ($sum < 25) {
                         foreach ($addresses as $address) {
                             $method = Mage::getModel('shipping/rate_result_method');
                             $method->setCarrier('freeshipping');
                             $method->setCarrierTitle('Im-Logistics Пункт Самовывоза');
                             $method->setMethod('pickup' . $count);
                             $method->setMethodTitle($address . ' Logistic');
                             $method->setCost($cost_sam);
                             $method->setPrice($cost_sam);
                             $result->append($method);
                             $count++;
                         }
                     }
                 }
             }
         }
     }
     $_SESSION['result'] = $result;
     //Mage::log($result, true, 'edost.log');
     $_SESSION['shipping_inf_edost'] = $result->getRatesByCarrier('edost');
     $_SESSION['shipping_inf_free'] = $result->getRatesByCarrier('freeshipping');
     return $result;
 }