Advertisement
Guest User

Untitled

a guest
Jul 15th, 2011
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 33.68 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Pedro Teixeira
  4.  *
  5.  * NOTICE OF LICENSE
  6.  *
  7.  * This source file is subject to the Open Software License (OSL).
  8.  * It is also available through the world-wide-web at this URL:
  9.  * http://opensource.org/licenses/osl-3.0.php
  10.  *
  11.  * @category   PedroTeixeira
  12.  * @package    PedroTeixeira_Correios
  13.  * @copyright  Copyright (c) 2010 Pedro Teixeira (http://www.pteixeira.com.br)
  14.  * @author     Pedro Teixeira <pedro@pteixeira.com.br>
  15.  * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  16.  */
  17.  
  18. /**
  19.  * PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
  20.  *
  21.  * @category   PedroTeixeira
  22.  * @package    PedroTeixeira_Correios
  23.  * @author     Pedro Teixeira <pedro@pteixeira.com.br>
  24.  */
  25.  
  26. class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
  27.     extends Mage_Shipping_Model_Carrier_Abstract
  28.     implements Mage_Shipping_Model_Carrier_Interface
  29. {
  30.  
  31.     /**
  32.      * _code property
  33.      *
  34.      * @var string
  35.      */
  36.     protected $_code                    = 'pedroteixeira_correios';
  37.  
  38.     /**
  39.      * _result property
  40.      *
  41.      * @var Mage_Shipping_Model_Rate_Result / Mage_Shipping_Model_Tracking_Result
  42.      */
  43.     protected $_result                  = null;
  44.  
  45.     /**
  46.      * ZIP code vars
  47.      */
  48.     protected $_fromZip                 = null;
  49.     protected $_toZip                   = null;
  50.  
  51.     /**
  52.      * Value and Weight
  53.      */
  54.     protected $_packageValue            = null;
  55.     protected $_packageWeight           = null;
  56.     protected $_pacWeight               = null;
  57.     protected $_freeMethodWeight        = null;
  58.  
  59.     /**
  60.      * Post methods
  61.      */
  62.     protected $_postMethods             = null;
  63.     protected $_postMethodsFixed        = null;
  64.     protected $_postMethodsExplode      = null;
  65.  
  66.     /**
  67.      * Free method request
  68.      */
  69.     protected $_freeMethodRequest       = false;
  70.     protected $_freeMethodRequestResult = null;
  71.  
  72.  
  73.     /**
  74.      * Values when multiple shipping
  75.      */
  76.  
  77.     protected $_shippingMethodCost = array();
  78.     protected $_shippingMethodPrice = array();
  79.  
  80.     protected $_shippingReturnToAppend = array();
  81.  
  82.     /**
  83.      * Collect Rates
  84.      *
  85.      * @param Mage_Shipping_Model_Rate_Request $request
  86.      * @return Mage_Shipping_Model_Rate_Result
  87.      */
  88.     public function collectRates(Mage_Shipping_Model_Rate_Request $request)
  89.     {      
  90.         // Do initial check
  91.         if($this->_inicialCheck($request) === false)
  92.         {
  93.             return false;
  94.         }      
  95.  
  96.         // Check package value
  97.         if($this->_packageValue < $this->getConfigData('min_order_value') || $this->_packageValue > $this->getConfigData('max_order_value'))
  98.         {
  99.             //Value limits
  100.             $this->_throwError('valueerror', 'Value limits', __LINE__);
  101.             return $this->_result;
  102.         }
  103.  
  104.         // Check ZIP Code
  105.         if(!preg_match("/^([0-9]{8})$/", $this->_toZip))
  106.     {
  107.             //Invalid Zip Code
  108.             $this->_throwError('zipcodeerror', 'Invalid Zip Code', __LINE__);
  109.             return $this->_result;
  110.         }
  111.        
  112.         // Fix weight
  113.         $weightCompare = $this->getConfigData('maxweight');
  114.         if($this->getConfigData('weight_type') == 'gr')
  115.         {
  116.             $this->_packageWeight = number_format($this->_packageWeight/1000, 2, '.', '');
  117.             $weightCompare = number_format($weightCompare/1000, 2, '.', '');
  118.         }
  119.  
  120.         // Check weight zero
  121.         if ($this->_packageWeight <= 0)
  122.         {
  123.             //Weight zero
  124.             $this->_throwError('weightzeroerror', 'Weight zero', __LINE__);
  125.             return $this->_result;
  126.         }
  127.  
  128.         // Check weght
  129.         if ($this->_packageWeight > $weightCompare)
  130.         {
  131. //            Weight exceeded limit
  132. //            $this->_throwError('maxweighterror', 'Weight exceeded limit', __LINE__);
  133. //            return $this->_result;
  134.  
  135.             $arrWeights = array();
  136.             foreach($request->getAllItems() as $item) {
  137.                 $i = 0;
  138.                 while ( $i < $item->getQty() ) {
  139.                     $i++;
  140.                     $arrWeights[] = (float) $item->getWeight();
  141.                 }
  142.             }
  143.  
  144.             $arrPackages = $this->_decidePackages($arrWeights, $weightCompare);
  145.  
  146.             // Get post methods
  147.             $this->_postMethods = $this->getConfigData('postmethods');
  148.             $this->_postMethodsFixed = $this->_postMethods;
  149.             $this->_postMethodsExplode = explode(",", $this->getConfigData('postmethods'));
  150.            
  151.             $results = array();
  152.             foreach($arrPackages as $package) {
  153.  
  154.                 //$this->_generatePacWeight($package);
  155.  
  156.                 // Get quotes
  157.                 if($this->_getQuotes($package)->getError()) {
  158.                     $results[] =  $this->_result;
  159.                 }
  160.             }
  161.  
  162.  
  163.             foreach($this->_shippingReturnToAppend as $shippingMethod => $shippingReturns) {
  164.                 $deliveryDays = 0;
  165.                 $shippingPrice = 0;
  166.  
  167.                 foreach($shippingReturns as $shippingReturn) {
  168.                     if ($shippingReturn['delivery'] > $deliveryDays)
  169.                         $deliveryDays = $shippingReturn['delivery'];
  170.  
  171.                     $shippingPrice += $shippingReturn['price'];
  172.                 }
  173.  
  174.                 $this->_apendShippingReturn($shippingMethod, $shippingPrice, $deliveryDays);
  175.             }
  176.  
  177.         } else {
  178.  
  179.             // Generate PAC Weight
  180.             $this->_generatePacWeight();
  181.  
  182.             // Get post methods
  183.             $this->_postMethods = $this->getConfigData('postmethods');
  184.             $this->_postMethodsFixed = $this->_postMethods;
  185.             $this->_postMethodsExplode = explode(",", $this->getConfigData('postmethods'));
  186.  
  187.             // Get quotes
  188.             if($this->_getQuotes()->getError()) {
  189.                 return $this->_result;
  190.             }
  191.         }
  192.  
  193.         // Use descont codes
  194.         $this->_updateFreeMethodQuote($request);
  195.  
  196.         // Return rates / errors
  197.         return $this->_result;
  198.        
  199.     }
  200.  
  201.     protected function _decidePackages($arrWeights, $maximumPackageWeight) {
  202. //        var_dump($maximumPackageWeight);
  203. //        var_dump($arrWeights);
  204.  
  205.         $arrPackages = array();
  206.  
  207.         # Order weights DESC
  208.        rsort($arrWeights);
  209.  
  210.         $packedWeights = array();
  211.         foreach($arrWeights as $key => $weight) {
  212.  
  213.             if (!count($arrPackages)) {
  214.                 # First run, there are no packages yet
  215.                # Creating empty package with heaviest item
  216.                $arrPackages[] = array($key => $weight);
  217.                 $packedWeights[$key] = $weight;
  218.  
  219. //                print "Empacotando primeiro item: $key -> $weight\n";
  220. //                continue;
  221.             }
  222.  
  223.             # If weight has already been packed, move on to next one
  224.            if (array_key_exists($key, $packedWeights)) {
  225. //                print $key . " já empacotado, continuando...\n";
  226.                 continue;
  227.             }
  228.  
  229.             # Create an array with the weights that haven't been packed and that are not the weight
  230.            # being packed right now. This array are the
  231.            $remainingWeights = array_diff_assoc($arrWeights, $packedWeights);
  232. //            print "Ainda não empacotados: \n";
  233. //            var_dump($remainingWeights);
  234.  
  235.             foreach($remainingWeights as $key => $weight) {
  236.                 $i = 0;
  237.  
  238.                 foreach( $arrPackages as $packageKey => $package ) {
  239.                     $i++;
  240.                    
  241.                     # Calculate package weight
  242.                    $packageWeight = 0;
  243.                     foreach( $package as $packageItemWeight ) {
  244.                         $packageWeight += $packageItemWeight;
  245.                     }
  246. //                    print "Peso do pacote $packageKey => $packageWeight. \$i => $i. Numero de pacotes: " . count($arrPackages) . "\n";
  247.                     if ( ($packageWeight + $weight) <= $maximumPackageWeight) {
  248.                         # This weight fits this package. Add it up
  249. //                        print "Adicionando peso $key => $weight ao pacote $packageKey\n";
  250.                         $arrPackages[$packageKey][$key] = $weight;
  251.                         $packedWeights[$key] = $weight;
  252.                         break 2;
  253.                     } else {
  254.                         if ( $i == count($arrPackages) ) {
  255. //                            print "Criando novo pacote para o produto $key => $weight\n";
  256.                             # It doesn't fit. Create a new package
  257.                            $arrPackages[] = array($key => $weight);
  258.                             $packedWeights[$key] = $weight;
  259.                             break 2;
  260.                         }
  261.                     }
  262.                 }
  263.             }
  264.  
  265. //            print "Pacotes até agora: \n";
  266. //            var_dump($arrPackages);
  267.  
  268. //            print "\n\n";
  269.         }
  270.  
  271. //        var_dump($arrPackages);
  272.  
  273.         //var_dump($arrWeights);
  274.         return $arrPackages;
  275.     }
  276.  
  277.     /**
  278.      * Get shipping quote
  279.      *
  280.      * @return bool
  281.      */
  282.     protected function _getQuotes($package = null){
  283.  
  284.         $pacCodes = explode(",", $this->getConfigData('pac_codes'));
  285.         $contratoCodes = explode(",", $this->getConfigData('contrato_codes'));        
  286.         $dieErrors = explode(",", $this->getConfigData('die_errors'));
  287.  
  288.  
  289.         //Define URL method
  290.         switch ($this->getConfigData('urlmethod')){
  291.  
  292.             //Locaweb
  293.             case 1:
  294.  
  295.                 foreach ($this->_postMethodsExplode as $postmethod){
  296.  
  297.                     try{
  298.                         $soap = new SoapClient($this->getConfigData('url_ws_locaweb'), array(
  299.                                 'trace' => true,
  300.                                 'exceptions' => true,
  301.                                 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
  302.                                 'connection_timeout' => $this->getConfigData('ws_timeout')
  303.                         ));
  304.  
  305.                         // Postagem dos parâmetros
  306.                         $parms = new Varien_Object();
  307.                         $parms->cepOrigem = utf8_encode($this->_fromZip);
  308.                         $parms->cepDestino = utf8_encode($this->_toZip);
  309.  
  310.                         // If PAC use PAC weight
  311.                         if(in_array($postmethod, $pacCodes) && $this->_pacWeight > $this->_packageWeight){
  312.                             $parms->peso = utf8_encode(str_replace(".",",",$this->_pacWeight));
  313.                         }else{
  314.                             if ($package) {
  315.                                 $pesoPacote = 0;
  316.                                 foreach($package as $packageItem)
  317.                                     $pesoPacote += $packageItem;
  318.                                 $parms->peso = utf8_encode(str_replace(".",",",$pesoPacote));
  319.                             } else {
  320.                                 $parms->peso = utf8_encode(str_replace(".",",",$this->_packageWeight));
  321.                             }
  322.                         }
  323.  
  324.                         $parms->volume = utf8_encode(1);
  325.                         $parms->codigo = utf8_encode($postmethod);
  326.  
  327.                         // Resgata o valor calculado
  328.                         $resposta = $soap->Correios($parms);
  329.  
  330.                         $shippingPrice = floatval(str_replace(",",".",$resposta->CorreiosResult));
  331.                        
  332.                     }catch(Exception $e){
  333.                         //URL Error
  334.                         $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__);
  335.                         return $this->_result;
  336.                     }
  337.  
  338.                     //URL Error
  339.                     if($shippingPrice == 0){
  340.                         //URL Error
  341.                         $this->_throwError('urlerror', 'URL Error', __LINE__);
  342.                         return $this->_result;
  343.                     }
  344.  
  345.                     $this->_apendShippingReturn($postmethod, $shippingPrice);
  346.  
  347.                 }
  348.             break;
  349.  
  350.             //Correios
  351.             case 0:
  352.  
  353.                 $correiosReturn = $this->_getCorreiosReturn($package);
  354.                 if($correiosReturn !== false){
  355.  
  356.                     // Check if exist return from Correios
  357.                     $existReturn = false;
  358.  
  359.                     foreach($correiosReturn as $servicos){
  360.  
  361.                         // Get Correios error
  362.                         $errorId = $this->_cleanCorreiosError((string)$servicos->Erro);
  363.  
  364.                         if($errorId != 0){
  365.                             // Error, throw error message
  366.                             if(in_array($errorId, $dieErrors)){
  367.                                 $this->_throwError('correioserror', 'Correios Error: ' . (string)$servicos->MsgErro . ' [Cod. ' . $errorId . '] [Serv. ' . (string)$servicos->Codigo . ']' , __LINE__, (string)$servicos->MsgErro . ' (Cod. ' . $errorId . ')');
  368.                                 return $this->_result;
  369.                             }else{
  370.                                 continue;
  371.                             }
  372.                         }
  373.  
  374.                         // If PAC, make a new call to WS
  375.                         if(in_array((string)$servicos->Codigo, $pacCodes) && $this->_pacWeight > $this->_packageWeight && !in_array($this->_postMethodsFixed, $pacCodes)){
  376.  
  377.                             $this->_postMethods = (string)$servicos->Codigo;
  378.                             $this->_postMethodsExplode = array((string)$servicos->Codigo);
  379.  
  380.                             $correiosReturnPac = $this->_getCorreiosReturn();
  381.                             if($correiosReturnPac !== false){
  382.  
  383.                                 foreach($correiosReturnPac as $servicosPac){
  384.  
  385.                                     // Get Correios error
  386.                                     $errorId = $this->_cleanCorreiosError((string)$servicosPac->Erro);
  387.  
  388.                                     if($errorId != 0){
  389.                                         // Error, throw error message
  390.                                         if(in_array($errorId, $dieErrors)){
  391.                                             $this->_throwError('correioserror', 'Correios Error: ' . (string)$servicosPac->MsgErro . ' (Cod. ' . $errorId . ')', __LINE__, (string)$servicosPac->MsgErro . ' (Cod. ' . $errorId . ')');
  392.                                             return $this->_result;
  393.                                         }else{
  394.                                             continue;
  395.                                         }
  396.                                     }
  397.  
  398.                                     $shippingPrice = floatval(str_replace(",",".",(string)$servicosPac->Valor));
  399.                                     $shippingDelivery = (int)$servicosPac->PrazoEntrega;
  400.  
  401.                                 }
  402.  
  403.                             }else{
  404.                                 return $this->_result;
  405.                             }
  406.                         }else{
  407.  
  408.                             $shippingPrice = floatval(str_replace(",",".",(string)$servicos->Valor));
  409.                             $shippingDelivery = (int)$servicos->PrazoEntrega;
  410.  
  411.                         }
  412.  
  413.                         if($shippingPrice <= 0){
  414.                             continue;
  415.                         }
  416.  
  417.                         // Apend shipping
  418.                         if ($package) {
  419.                             $this->_delayedAppendShippingReturn((string)$servicos->Codigo, $shippingPrice, $shippingDelivery);
  420.                         } else {
  421.                             $this->_apendShippingReturn((string)$servicos->Codigo, $shippingPrice, $shippingDelivery);
  422.                         }
  423.                        
  424.                         $existReturn = true;
  425.  
  426.                     }
  427.  
  428.                     // All services are ignored
  429.                     if($existReturn === false){
  430.                         $this->_throwError('urlerror', 'URL Error, all services return with error', __LINE__);
  431.                         return $this->_result;
  432.                     }
  433.  
  434.                 }else{
  435.                     // Error on HTTP Correios
  436.                     $this->_apendShippingReturn('40010', 34, '2 dias');
  437.                     $this->_apendShippingReturn('41106', 14, '6 dias');
  438.                     return $this->_result;
  439.  
  440.                 }
  441.  
  442.             break;
  443.  
  444.         }
  445.  
  446.         // Successg
  447.         if($this->_freeMethodRequest === true){
  448.             return $this->_freeMethodRequestResult;
  449.         }else{
  450.             return $this->_result;
  451.         }
  452.     }
  453.  
  454.  
  455.     protected function _delayedAppendShippingReturn($shipping_method, $shippingPrice = 0, $correiosDelivery = 0) {
  456.  
  457.         $this->_shippingReturnToAppend[$shipping_method][] = array('price' => $shippingPrice, 'delivery' => $correiosDelivery);
  458.  
  459.     }
  460.  
  461.     /**
  462.      * Make initial checks and iniciate module variables
  463.      *
  464.      * @param Mage_Shipping_Model_Rate_Request $request
  465.      * @return boolean
  466.      */
  467.     protected function _inicialCheck(Mage_Shipping_Model_Rate_Request $request){
  468.  
  469.         if (!$this->getConfigFlag('active'))
  470.         {
  471.             //Disabled
  472.             Mage::log('PedroTeixeira_Correios: Disabled');
  473.             return false;
  474.         }
  475.  
  476.  
  477.         $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
  478.         $destCountry = $request->getDestCountryId();
  479.         if ($origCountry != "BR" || $destCountry != "BR"){
  480.             //Out of delivery area
  481.             Mage::log('PedroTeixeira_Correios: Out of delivery area');
  482.             return false;
  483.         }
  484.  
  485.         // ZIP Code
  486.         $this->_fromZip = Mage::getStoreConfig('shipping/origin/postcode', $this->getStore());
  487.         $this->_toZip = $request->getDestPostcode();
  488.  
  489.         //Fix Zip Code
  490.         $this->_fromZip = str_replace('-', '', trim($this->_fromZip));
  491.         $this->_toZip = str_replace('-', '', trim($this->_toZip));
  492.  
  493.         if(!preg_match("/^([0-9]{8})$/", $this->_fromZip)){
  494.             //From zip code error
  495.             Mage::log('PedroTeixeira_Correios: From ZIP Code Error');
  496.             return false;
  497.         }
  498.  
  499.         // Result model
  500.         $this->_result = Mage::getModel('shipping/rate_result');
  501.  
  502.         // Value
  503.         $this->_packageValue = $request->getBaseCurrency()->convert($request->getPackageValue(), $request->getPackageCurrency());
  504.  
  505.         // Weight
  506.         $this->_packageWeight = number_format($request->getPackageWeight(), 2, '.', '');
  507.  
  508.         // Free method weight
  509.         $this->_freeMethodWeight = number_format($request->getFreeMethodWeight(), 2, '.', '');
  510.  
  511.     }
  512.  
  513.     /**
  514.      * Get Correios return
  515.      *
  516.      * @return bool
  517.      */
  518.     protected function _getCorreiosReturn($package = null){
  519.  
  520.         $filename = $this->getConfigData('url_ws_correios');
  521.  
  522.         $pacCodes = explode(",", $this->getConfigData('pac_codes'));
  523.         $contratoCodes = explode(",", $this->getConfigData('contrato_codes'));
  524.        
  525.         try {
  526.             $client = new Zend_Http_Client($filename);
  527.             $client->setConfig(array(
  528.                         'timeout' => $this->getConfigData('ws_timeout')
  529.                     ));
  530.  
  531.             $client->setParameterGet('StrRetorno', 'xml');
  532.             $client->setParameterGet('nCdServico', $this->_postMethods);
  533.  
  534.             if(in_array($this->_postMethods, $pacCodes) && $this->_pacWeight > $this->_packageWeight){
  535.                 $client->setParameterGet('nVlPeso', $this->_pacWeight);
  536.             }else{
  537.                 if ($package) {
  538.                     $pesoPacote = 0;
  539.                     foreach($package as $packageItem)
  540.                         $pesoPacote += $packageItem;
  541.                     $this->_packageWeight = utf8_encode(str_replace(".",",",$pesoPacote));
  542.                 } else {
  543.                     $this->_packageWeight = utf8_encode(str_replace(".",",",$this->_packageWeight));
  544.                 }
  545.                 $client->setParameterGet('nVlPeso', $this->_packageWeight);
  546.             }
  547.  
  548.  
  549.             $client->setParameterGet('sCepOrigem', $this->_fromZip);
  550.             $client->setParameterGet('sCepDestino', $this->_toZip);
  551.             $client->setParameterGet('nCdFormato',1);
  552.             $client->setParameterGet('nVlComprimento',$this->getConfigData('comprimento_sent'));
  553.             $client->setParameterGet('nVlAltura',$this->getConfigData('altura_sent'));
  554.             $client->setParameterGet('nVlLargura',$this->getConfigData('largura_sent'));
  555.  
  556.             if($this->getConfigData('mao_propria')){
  557.                 $client->setParameterGet('sCdMaoPropria','S');
  558.             }else{
  559.                 $client->setParameterGet('sCdMaoPropria','N');
  560.             }
  561.  
  562.             if($this->getConfigData('aviso_recebimento')){
  563.                 $client->setParameterGet('sCdAvisoRecebimento','S');
  564.             }else{
  565.                 $client->setParameterGet('sCdAvisoRecebimento','N');
  566.             }
  567.  
  568.             if($this->getConfigData('valor_declarado') || in_array($this->getConfigData('acobrar_code'), $this->_postMethodsExplode)){
  569.                 $client->setParameterGet('nVlValorDeclarado',number_format($this->_packageValue, 2, ',', '.'));
  570.             }else{
  571.                 $client->setParameterGet('nVlValorDeclarado',0);
  572.             }
  573.  
  574.             $contrato = false;
  575.             foreach($contratoCodes as $contratoEach){
  576.                 if(in_array($contratoEach, $this->_postMethodsExplode)){
  577.                     $contrato = true;
  578.                 }
  579.             }
  580.  
  581.             if($contrato){
  582.                 if($this->getConfigData('cod_admin') == '' || $this->getConfigData('senha_admin') == ''){
  583.                     // Need correios admin data
  584.                     $this->_throwError('coderror', 'Need correios admin data', __LINE__);
  585.                     return false;
  586.                 }else{
  587.                     $client->setParameterGet('nCdEmpresa',$this->getConfigData('cod_admin'));
  588.                     $client->setParameterGet('sDsSenha',$this->getConfigData('senha_admin'));
  589.                 }
  590.             }            
  591.  
  592.             $content = $client->request();
  593.             $conteudo = $content->getBody();
  594.  
  595.  
  596.  
  597.             if ($conteudo == ""){
  598.                 throw new Exception("No XML returned [" . __LINE__ . "]");
  599.             }
  600.  
  601.             libxml_use_internal_errors(true);
  602.             $sxe = simplexml_load_string($conteudo);
  603.             if (!$sxe) {
  604.                 throw new Exception("Bad XML [" . __LINE__ . "]");
  605.             }
  606.  
  607.             // Load XML
  608.             $xml = new SimpleXMLElement($conteudo);
  609.  
  610.             if(count($xml->cServico) <= 0){
  611.                 throw new Exception("No tag cServico in Correios XML [" . __LINE__ . "]");
  612.             }
  613.  
  614.             return $xml->cServico;
  615.  
  616.  
  617.         } catch (Exception $e) {
  618.             //URL Error
  619.             $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__);
  620.             return false;
  621.         };
  622.  
  623.  
  624.     }
  625.  
  626.     /**
  627.      * Apend shipping value to return
  628.      *
  629.      * @param $shipping_method string
  630.      * @param $shippingPrice float
  631.      * @param $correiosReturn array
  632.      */
  633.     protected function _apendShippingReturn($shipping_method, $shippingPrice = 0, $correiosDelivery = 0){
  634.  
  635.         $method = Mage::getModel('shipping/rate_result_method');
  636.         $method->setCarrier($this->_code);
  637.         $method->setCarrierTitle($this->getConfigData('title'));
  638.         $method->setMethod($shipping_method);
  639.  
  640. //        print $shipping_method . " => " . $shippingPrice . "\n";
  641.  
  642.         $shippingCost = $shippingPrice;
  643.         $shippingPrice = $shippingPrice + $this->getConfigData('handling_fee');
  644.  
  645.         $shipping_data = explode(',', $this->getConfigData('serv_' . $shipping_method));
  646.  
  647.         if($shipping_method == $this->getConfigData('acobrar_code')){
  648.             $shipping_data[0] = $shipping_data[0] . ' ( R$' . number_format($shippingPrice, 2, ',', '.') . ' )';
  649.             $shippingPrice = 0;
  650.         }
  651.  
  652.  
  653.         // Show delivery days
  654.         if ($this->getConfigFlag('prazo_entrega')){
  655.  
  656.             // Delivery days from WS
  657.             if($correiosDelivery  > 0){
  658.                 $method->setMethodTitle(sprintf($this->getConfigData('msgprazo'), $shipping_data[0], (int)($correiosDelivery + $this->getConfigData('add_prazo'))));
  659.             }else{
  660.                 $method->setMethodTitle(sprintf($this->getConfigData('msgprazo'), $shipping_data[0], (int)($shipping_data[1] + $this->getConfigData('add_prazo'))));
  661.             }
  662.  
  663.  
  664.         }else{
  665.                 $method->setMethodTitle($shipping_data[0]);
  666.         }
  667.        
  668. //        print $this->_shippingMethodCost[$shipping_method] . " " . $this->_shippingMethodPrice[$shipping_method] . "\n";
  669.  
  670.  
  671.         $method->setPrice($shippingPrice);
  672.         $method->setCost($shippingPrice);
  673.  
  674.  
  675.         if($this->_freeMethodRequest === true){
  676.             $this->_freeMethodRequestResult->append($method);
  677.         }else{
  678.             $this->_result->append($method);
  679.         }
  680.     }
  681.  
  682.     /**
  683.      * Throw error
  684.      *
  685.      * @param $message string
  686.      * @param $log     string
  687.      * @param $line    int
  688.      * @param $custom  string
  689.      */
  690.     protected function _throwError($message, $log = null, $line = 'NO LINE', $custom = null){
  691.  
  692.         $this->_result = null;
  693.         $this->_result = Mage::getModel('shipping/rate_result');
  694.  
  695.         // Get error model
  696.         $error = Mage::getModel('shipping/rate_result_error');
  697.         $error->setCarrier($this->_code);
  698.         $error->setCarrierTitle($this->getConfigData('title'));
  699.  
  700.         if(is_null($custom)){
  701.             //Log error
  702.             Mage::log($this->_code . ' [' . $line . ']: ' . $log);
  703.             $error->setErrorMessage($this->getConfigData($message));
  704.         }else{
  705.             //Log error
  706.             Mage::log($this->_code . ' [' . $line . ']: ' . $log);
  707.             $error->setErrorMessage(sprintf($this->getConfigData($message), $custom));
  708.         }        
  709.  
  710.         // Apend error
  711.         $this->_result->append($error);
  712.     }
  713.  
  714.     /**
  715.      * Generate PAC weight
  716.      */
  717.     protected function _generatePacWeight($packages = null){
  718.         //Create PAC weight
  719.         $pesoCubicoTotal = 0;
  720.  
  721.         // Get all visible itens from quote
  722.         $items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems();
  723.  
  724.         foreach($items as $item){
  725.  
  726.             $while = 0;
  727.             $itemAltura= 0;
  728.             $itemLargura = 0;
  729.             $itemComprimento = 0;
  730.  
  731.             $_product = $item->getProduct();
  732.  
  733.             if($_product->getData('volume_altura') == '' || (int)$_product->getData('volume_altura') == 0)
  734.                 $itemAltura = $this->getConfigData('altura_padrao');
  735.             else
  736.                 $itemAltura = $_product->getData('volume_altura');
  737.  
  738.             if($_product->getData('volume_largura') == '' || (int)$_product->getData('volume_largura') == 0)
  739.                 $itemLargura = $this->getConfigData('largura_padrao');
  740.             else
  741.                 $itemLargura = $_product->getData('volume_largura');
  742.  
  743.             if($_product->getData('volume_comprimento') == '' || (int)$_product->getData('volume_comprimento') == 0)
  744.                 $itemComprimento = $this->getConfigData('comprimento_padrao');
  745.             else
  746.                 $itemComprimento = $_product->getData('volume_comprimento');
  747.  
  748.             while($while < $item->getQty()){
  749.                 $itemPesoCubico = 0;
  750.                 $itemPesoCubico = ($itemAltura * $itemLargura * $itemComprimento)/4800;
  751.                 $pesoCubicoTotal = $pesoCubicoTotal + $itemPesoCubico;
  752.                 $while ++;
  753.             }
  754.         }
  755.  
  756.         $this->_pacWeight = number_format($pesoCubicoTotal, 2, '.', '');
  757.     }
  758.  
  759.     /**
  760.      * Generate free shipping for a product
  761.      *
  762.      * @param string $freeMethod
  763.      */
  764.     protected function _setFreeMethodRequest($freeMethod)
  765.     {
  766.         // Set request as free method request
  767.         $this->_freeMethodRequest = true;
  768.         $this->_freeMethodRequestResult = Mage::getModel('shipping/rate_result');
  769.  
  770.         $this->_postMethods = $freeMethod;
  771.         $this->_postMethodsExplode = array($freeMethod);      
  772.  
  773.         // Tranform free shipping weight
  774.         if($this->getConfigData('weight_type') == 'gr')
  775.         {
  776.             $this->_freeMethodWeight = number_format($this->_freeMethodWeight/1000, 2, '.', '');
  777.         }
  778.        
  779.         $this->_packageWeight = $this->_freeMethodWeight;
  780.         $this->_pacWeight = $this->_freeMethodWeight;
  781.     }
  782.  
  783.     /**
  784.      * Clean correios error code, usualy with "-" before the code
  785.      *
  786.      * @param string $error
  787.      * @return int
  788.      */
  789.     protected function _cleanCorreiosError($error){
  790.         $error = str_replace('-', '', $error);
  791.         $error = (int)$error;
  792.         return $error;
  793.     }
  794.  
  795.  
  796.     /**
  797.      * Check if current carrier offer support to tracking
  798.      *
  799.      * @return boolean true
  800.      */
  801.     public function isTrackingAvailable() {
  802.         return true;
  803.     }
  804.  
  805.     /**
  806.      * Get Tracking Info
  807.      *
  808.      * @param mixed $tracking
  809.      * @return mixed
  810.      */
  811.     public function getTrackingInfo($tracking) {
  812.         $result = $this->getTracking($tracking);
  813.         if ($result instanceof Mage_Shipping_Model_Tracking_Result){
  814.             if ($trackings = $result->getAllTrackings()) {
  815.                     return $trackings[0];
  816.             }
  817.         } elseif (is_string($result) && !empty($result)) {
  818.             return $result;
  819.         }
  820.         return false;
  821.     }
  822.  
  823.     /**
  824.      * Get Tracking
  825.      *
  826.      * @param array $trackings
  827.      * @return Mage_Shipping_Model_Tracking_Result
  828.      */
  829.     public function getTracking($trackings) {
  830.         $this->_result = Mage::getModel('shipping/tracking_result');
  831.         foreach ((array) $trackings as $code) {
  832.             $this->_getTracking($code);
  833.         }
  834.         return $this->_result;
  835.     }
  836.  
  837.     /**
  838.      * Protected Get Tracking, opens the request to Correios
  839.      *
  840.      * @param string $code
  841.      * @return boolean
  842.      */
  843.     protected function _getTracking($code) {
  844.         $error = Mage::getModel('shipping/tracking_result_error');
  845.         $error->setTracking($code);
  846.         $error->setCarrier($this->_code);
  847.         $error->setCarrierTitle($this->getConfigData('title'));
  848.         $error->setErrorMessage($this->getConfigData('urlerror'));
  849.  
  850.         $url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList';
  851.         $url .= '?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $code;
  852.         try {
  853.             $client = new Zend_Http_Client();
  854.             $client->setUri($url);
  855.             $content = $client->request();
  856.             $body = $content->getBody();
  857.         } catch (Exception $e) {
  858.             $this->_result->append($error);
  859.             return false;
  860.         }
  861.  
  862.         if (!preg_match('#<table ([^>]+)>(.*?)</table>#is', $body, $matches)) {
  863.             $this->_result->append($error);
  864.             return false;
  865.         }
  866.         $table = $matches[2];
  867.  
  868.         if (!preg_match_all('/<tr>(.*)<\/tr>/i', $table, $columns, PREG_SET_ORDER)) {
  869.             $this->_result->append($error);
  870.             return false;
  871.         }
  872.  
  873.         $progress = array();
  874.         for ($i = 0; $i < count($columns); $i++) {
  875.             $column = $columns[$i][1];
  876.  
  877.             $description = '';
  878.             $found = false;
  879.             if (preg_match('/<td rowspan="?2"?/i', $column) && preg_match('/<td rowspan="?2"?>(.*)<\/td><td>(.*)<\/td><td><font color="[A-Z0-9]{6}">(.*)<\/font><\/td>/i', $column, $matches)) {
  880.                 if (preg_match('/<td colspan="?2"?>(.*)<\/td>/i', $columns[$i+1][1], $matchesDescription)) {
  881.                     $description = str_replace('  ', '', $matchesDescription[1]);
  882.                 }
  883.  
  884.                 $found = true;
  885.             } elseif (preg_match('/<td rowspan="?1"?>(.*)<\/td><td>(.*)<\/td><td><font color="[A-Z0-9]{6}">(.*)<\/font><\/td>/i', $column, $matches)) {
  886.                 $found = true;
  887.             }
  888.  
  889.             if ($found) {
  890.                 $datetime = explode(' ', $matches[1]);
  891.                 $locale = new Zend_Locale('pt_BR');
  892.                 $date='';
  893.                 $date = new Zend_Date($datetime[0], 'dd/MM/YYYY', $locale);
  894.  
  895.                 $track = array(
  896.                             'deliverydate' => $date->toString('YYYY-MM-dd'),
  897.                             'deliverytime' => $datetime[1] . ':00',
  898.                             'deliverylocation' => htmlentities($matches[2]),
  899.                             'status' => htmlentities($matches[3]),
  900.                             'activity' => htmlentities($matches[3])
  901.                             );
  902.  
  903.                 if ($description !== '') {
  904.                     $track['activity'] = $matches[3] . ' - ' . htmlentities($description);
  905.                 }
  906.  
  907.                 $progress[] = $track;
  908.             }
  909.         }
  910.  
  911.         if (!empty($progress)) {
  912.             $track = $progress[0];
  913.             $track['progressdetail'] = $progress;
  914.  
  915.             $tracking = Mage::getModel('shipping/tracking_result_status');
  916.             $tracking->setTracking($code);
  917.             $tracking->setCarrier('correios');
  918.             $tracking->setCarrierTitle($this->getConfigData('title'));
  919.             $tracking->addData($track);
  920.  
  921.             $this->_result->append($tracking);
  922.             return true;
  923.         } else {
  924.             $this->_result->append($error);
  925.             return false;
  926.         }
  927.     }
  928.  
  929.     /**
  930.      * Returns the allowed carrier methods
  931.      *
  932.      * @return array
  933.      */
  934.     public function getAllowedMethods()
  935.     {
  936.         return array($this->_code => $this->getConfigData('title'));
  937.     }
  938.  
  939.     /**
  940.      * Define ZIP Code as required
  941.      *
  942.      * @return boolean
  943.      */
  944.     public function isZipCodeRequired()
  945.     {
  946.         return true;
  947.     }
  948.  
  949. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement