diff --git a/CHANGELOG.md b/CHANGELOG.md index af063e3..27c8b7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,25 @@ +# 4.1.0 +--- + +### Bugfix + +- Desconsiderando duplicidade de produtos configuráveis no cálculo do volume do PAC +- Corrigido problema com a função depreciada slipt() +- Corrigido mensagem de erro de peso e valor de "a cima" para "acima" + +### Feature + +- Nova estrutura do Model, facilitando o entendimento e manutenção +- Nova forma de passar o volume do PAC para os Correios +- Novos filtros para evitar erros na interface +- Nomes dos métodos, URL dos Correios, prazo de entrega e outros + parâmetros configurados no xml +- Integração total com as regras de frete grátis utilizando a função _setFreeMethodRequest() +- Logs mais completos para identificação de possíveis problemas +- Realiza apenas uma consulta ao webservice para todos os serviços +- Sedex a cobrar mostra o valor do frete na mensagem e deixa como gratuito + + # 4.0.0 --- diff --git a/app/code/community/PedroTeixeira/Correios/Helper/Data.php b/app/code/community/PedroTeixeira/Correios/Helper/Data.php old mode 100755 new mode 100644 index 43ffde5..e763ffe --- a/app/code/community/PedroTeixeira/Correios/Helper/Data.php +++ b/app/code/community/PedroTeixeira/Correios/Helper/Data.php @@ -13,5 +13,4 @@ class PedroTeixeira_Correios_Helper_Data extends Mage_Core_Helper_Abstract { - } \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php b/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php old mode 100755 new mode 100644 index ccd5480..dfb795f --- a/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php +++ b/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php @@ -12,17 +12,13 @@ */ /** - * PedroTeixeira_Correios_Model_Carrier_CorreioMethod + * PedroTeixeira_Correios_Model_Carrier_CorreiosMethod * * @category PedroTeixeira * @package PedroTeixeira_Correios * @author Pedro Teixeira */ -class ParametersLocaweb -{ -} - class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface @@ -43,14 +39,31 @@ class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod protected $_result = null; /** - * Check if current carrier offer support to tracking - * - * @return boolean true + * ZIP code vars */ - public function isTrackingAvailable() - { - return true; - } + protected $_fromZip = null; + protected $_toZip = null; + + /** + * Value and Weight + */ + protected $_packageValue = null; + protected $_packageWeight = null; + protected $_pacWeight = null; + protected $_freeMethodWeight = null; + + /** + * Post methods + */ + protected $_postMethods = null; + protected $_postMethodsFixed = null; + protected $_postMethodsExplode = null; + + /** + * Free method request + */ + protected $_freeMethodRequest = false; + protected $_freeMethodRequestResult = null; /** * Collect Rates @@ -61,387 +74,591 @@ public function isTrackingAvailable() */ public function collectRates(Mage_Shipping_Model_Rate_Request $request) { - if (!$this->getConfigFlag('active')) { - //Disabled - Mage::log('PedroTeixeira_Correios: Disabled'); + // Do initial check + if ($this->_inicialCheck($request) === false) { return false; } + // Check package value + if ($this->_packageValue < $this->getConfigData( + 'min_order_value' + ) || $this->_packageValue > $this->getConfigData('max_order_value') + ) { + //Value limits + $this->_throwError('valueerror', 'Value limits', __LINE__); + return $this->_result; + } - $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; + // Check ZIP Code + if (!preg_match("/^([0-9]{8})$/", $this->_toZip)) { + //Invalid Zip Code + $this->_throwError('zipcodeerror', 'Invalid Zip Code', __LINE__); + return $this->_result; } + // Fix weight + $weightCompare = $this->getConfigData('maxweight'); + if ($this->getConfigData('weight_type') == 'gr') { + $this->_packageWeight = number_format($this->_packageWeight / 1000, 2, '.', ''); + $weightCompare = number_format($weightCompare / 1000, 2, '.', ''); + } + // Check weght + if ($this->_packageWeight > $weightCompare) { + //Weight exceeded limit + $this->_throwError('maxweighterror', 'Weight exceeded limit', __LINE__); + return $this->_result; + } - $result = Mage::getModel('shipping/rate_result'); - $error = Mage::getModel('shipping/rate_result_error'); + // Check weight zero + if ($this->_packageWeight <= 0) { + //Weight zero + $this->_throwError('weightzeroerror', 'Weight zero', __LINE__); + return $this->_result; + } - $error->setCarrier($this->_code); - $error->setCarrierTitle($this->getConfigData('title')); + // Generate PAC Weight + $this->_generatePacWeight(); + // Get post methods + $this->_postMethods = $this->getConfigData('postmethods'); + $this->_postMethodsFixed = $this->_postMethods; + $this->_postMethodsExplode = explode(",", $this->getConfigData('postmethods')); - $packagevalue = $request->getBaseCurrency()->convert( - $request->getPackageValue(), - $request->getPackageCurrency() - ); - $minorderval = $this->getConfigData('min_order_value'); - $maxorderval = $this->getConfigData('max_order_value'); - if ($packagevalue <= $minorderval || $packagevalue >= $maxorderval) { - //Value limits - Mage::log('PedroTeixeira_Correios: Value limits'); - $error->setErrorMessage($this->getConfigData('valueerror')); - $result->append($error); - return $result; + // Get quotes + if ($this->_getQuotes()->getError()) { + return $this->_result; } - $frompcode = Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()); - $topcode = $request->getDestPostcode(); + // Use descont codes + $this->_updateFreeMethodQuote($request); - //Fix Zip Code - $frompcode = str_replace('-', '', trim($frompcode)); - $topcode = str_replace('-', '', trim($topcode)); + // Return rates / errors + return $this->_result; + } - if (!preg_match("/^([0-9]{8})$/", $topcode)) { - //Invalid Zip Code - Mage::log('PedroTeixeira_Correios: Invalid Zip Code'); - $error->setErrorMessage($this->getConfigData('zipcodeerror')); - $result->append($error); - Mage::helper('customer')->__('Invalid ZIP CODE'); - return $result; + /** + * Get shipping quote + * + * @return bool + */ + protected function _getQuotes() + { + + $pacCodes = explode(",", $this->getConfigData('pac_codes')); + $contratoCodes = explode(",", $this->getConfigData('contrato_codes')); + $dieErrors = explode(",", $this->getConfigData('die_errors')); + + + //Define URL method + switch ($this->getConfigData('urlmethod')) { + + //Locaweb + case 1: + + foreach ($this->_postMethodsExplode as $postmethod) { + + try { + $soap = new SoapClient($this->getConfigData('url_ws_locaweb'), array( + 'trace' => true, + 'exceptions' => true, + 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, + 'connection_timeout' => $this->getConfigData('ws_timeout') + )); + + // Postagem dos parâmetros + $parms = new Varien_Object(); + $parms->cepOrigem = utf8_encode($this->_fromZip); + $parms->cepDestino = utf8_encode($this->_toZip); + + // If PAC use PAC weight + if (in_array($postmethod, $pacCodes) && $this->_pacWeight > $this->_packageWeight) { + $parms->peso = utf8_encode(str_replace(".", ",", $this->_pacWeight)); + } else { + $parms->peso = utf8_encode(str_replace(".", ",", $this->_packageWeight)); + } + + $parms->volume = utf8_encode(1); + $parms->codigo = utf8_encode($postmethod); + + // Resgata o valor calculado + $resposta = $soap->Correios($parms); + + $shippingPrice = floatval(str_replace(",", ".", $resposta->CorreiosResult)); + } catch (Exception $e) { + //URL Error + $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__); + return $this->_result; + } + + //URL Error + if ($shippingPrice == 0) { + //URL Error + $this->_throwError('urlerror', 'URL Error', __LINE__); + return $this->_result; + } + + $this->_apendShippingReturn($postmethod, $shippingPrice); + } + break; + + //Correios + case 0: + + $correiosReturn = $this->_getCorreiosReturn(); + if ($correiosReturn !== false) { + + // Check if exist return from Correios + $existReturn = false; + + foreach ($correiosReturn as $servicos) { + + // Get Correios error + $errorId = $this->_cleanCorreiosError((string) $servicos->Erro); + + if ($errorId != 0) { + // Error, throw error message + if (in_array($errorId, $dieErrors)) { + $this->_throwError( + 'correioserror', + 'Correios Error: ' . (string) $servicos->MsgErro . ' [Cod. ' . $errorId . '] [Serv. ' . (string) $servicos->Codigo . ']', + __LINE__, + (string) $servicos->MsgErro . ' (Cod. ' . $errorId . ')' + ); + return $this->_result; + } else { + continue; + } + } + + // If PAC, make a new call to WS + if (in_array( + (string) $servicos->Codigo, + $pacCodes + ) && $this->_pacWeight > $this->_packageWeight && !in_array( + $this->_postMethodsFixed, + $pacCodes + ) + ) { + + $this->_postMethods = (string) $servicos->Codigo; + $this->_postMethodsExplode = array((string) $servicos->Codigo); + + $correiosReturnPac = $this->_getCorreiosReturn(); + if ($correiosReturnPac !== false) { + + foreach ($correiosReturnPac as $servicosPac) { + + // Get Correios error + $errorId = $this->_cleanCorreiosError((string) $servicosPac->Erro); + + if ($errorId != 0) { + // Error, throw error message + if (in_array($errorId, $dieErrors)) { + $this->_throwError( + 'correioserror', + 'Correios Error: ' . (string) $servicosPac->MsgErro . ' (Cod. ' . $errorId . ')', + __LINE__, + (string) $servicosPac->MsgErro . ' (Cod. ' . $errorId . ')' + ); + return $this->_result; + } else { + continue; + } + } + + $shippingPrice = floatval(str_replace(",", ".", (string) $servicosPac->Valor)); + $shippingDelivery = (int) $servicosPac->PrazoEntrega; + } + } else { + return $this->_result; + } + } else { + + $shippingPrice = floatval(str_replace(",", ".", (string) $servicos->Valor)); + $shippingDelivery = (int) $servicos->PrazoEntrega; + } + + if ($shippingPrice <= 0) { + continue; + } + + // Apend shipping + $this->_apendShippingReturn((string) $servicos->Codigo, $shippingPrice, $shippingDelivery); + $existReturn = true; + } + + // All services are ignored + if ($existReturn === false) { + $this->_throwError('urlerror', 'URL Error, all services return with error', __LINE__); + return $this->_result; + } + } else { + // Error on HTTP Correios + return $this->_result; + } + + break; } + // Success + if ($this->_freeMethodRequest === true) { + return $this->_freeMethodRequestResult; + } else { + return $this->_result; + } + } - $sweight = $request->getPackageWeight(); - $weightCompare = $this->getConfigData('maxweight'); - if ($this->getConfigData('weight_type') == 'gr') { - $sweight = number_format($sweight / 1000, 2, '.', ''); - $weightCompare = number_format($weightCompare / 1000, 2, '.', ''); + /** + * Make initial checks and iniciate module variables + * + * @param Mage_Shipping_Model_Rate_Request $request + * + * @return boolean + */ + protected function _inicialCheck(Mage_Shipping_Model_Rate_Request $request) + { + + if (!$this->getConfigFlag('active')) { + //Disabled + Mage::log('PedroTeixeira_Correios: Disabled'); + return false; } - if ($sweight > $weightCompare) { - //Weight exceeded limit - Mage::log('PedroTeixeira_Correios: Weight exceeded limit'); - $error->setErrorMessage($this->getConfigData('maxweighterror')); - $result->append($error); - return $result; + $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; } + // ZIP Code + $this->_fromZip = Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()); + $this->_toZip = $request->getDestPostcode(); - if ($sweight == 0) { - //Weight zero - Mage::log('PedroTeixeira_Correios: Weight zero'); - $error->setErrorMessage($this->getConfigData('weightzeroerror')); - $result->append($error); - return $result; + //Fix Zip Code + $this->_fromZip = str_replace('-', '', trim($this->_fromZip)); + $this->_toZip = str_replace('-', '', trim($this->_toZip)); + + if (!preg_match("/^([0-9]{8})$/", $this->_fromZip)) { + //From zip code error + Mage::log('PedroTeixeira_Correios: From ZIP Code Error'); + return false; } + // Result model + $this->_result = Mage::getModel('shipping/rate_result'); - //Create the volume of the cart + // Value + $this->_packageValue = $request->getBaseCurrency()->convert( + $request->getPackageValue(), + $request->getPackageCurrency() + ); - $pesoCubicoTotal = 0; - $volumeTotal = 0; + // Weight + $this->_packageWeight = number_format($request->getPackageWeight(), 2, '.', ''); - $items = Mage::getModel('checkout/cart')->getQuote()->getAllItems(); + // Free method weight + $this->_freeMethodWeight = number_format($request->getFreeMethodWeight(), 2, '.', ''); + } - foreach ($items as $item) { + /** + * Get Correios return + * + * @return bool + */ + protected function _getCorreiosReturn() + { - $while = 0; - $_product = $item->getProduct(); + $filename = $this->getConfigData('url_ws_correios'); - if ($_product->getData('volume_altura') == '' || (int) $_product->getData('volume_altura') == 0) { - $itemAltura = $this->getConfigData('altura_padrao'); + $pacCodes = explode(",", $this->getConfigData('pac_codes')); + $contratoCodes = explode(",", $this->getConfigData('contrato_codes')); + + try { + $client = new Zend_Http_Client($filename); + $client->setConfig( + array( + 'timeout' => $this->getConfigData('ws_timeout') + ) + ); + + $client->setParameterGet('StrRetorno', 'xml'); + $client->setParameterGet('nCdServico', $this->_postMethods); + + if (in_array($this->_postMethods, $pacCodes) && $this->_pacWeight > $this->_packageWeight) { + $client->setParameterGet('nVlPeso', $this->_pacWeight); } else { - $itemAltura = $_product->getData('volume_altura'); + $client->setParameterGet('nVlPeso', $this->_packageWeight); } - if ($_product->getData('volume_largura') == '' || (int) $_product->getData('volume_largura') == 0) { - $itemLargura = $this->getConfigData('largura_padrao'); + $client->setParameterGet('sCepOrigem', $this->_fromZip); + $client->setParameterGet('sCepDestino', $this->_toZip); + $client->setParameterGet('nCdFormato', 1); + $client->setParameterGet('nVlComprimento', $this->getConfigData('comprimento_sent')); + $client->setParameterGet('nVlAltura', $this->getConfigData('altura_sent')); + $client->setParameterGet('nVlLargura', $this->getConfigData('largura_sent')); + + if ($this->getConfigData('mao_propria')) { + $client->setParameterGet('sCdMaoPropria', 'S'); } else { - $itemLargura = $_product->getData('volume_largura'); + $client->setParameterGet('sCdMaoPropria', 'N'); } - if ($_product->getData('volume_comprimento') == '' || (int) $_product->getData('volume_comprimento') == 0) { - $itemComprimento = $this->getConfigData('comprimento_padrao'); + if ($this->getConfigData('aviso_recebimento')) { + $client->setParameterGet('sCdAvisoRecebimento', 'S'); } else { - $itemComprimento = $_product->getData('volume_comprimento'); + $client->setParameterGet('sCdAvisoRecebimento', 'N'); } - while ($while < $item->getQty()) { - $itemPesoCubico = ($itemAltura * $itemLargura * $itemComprimento) / 4800; - $pesoCubicoTotal = $pesoCubicoTotal + $itemPesoCubico; - $volumeTotal = $volumeTotal + ($itemPesoCubico * 4800); + if ($this->getConfigData('valor_declarado') || in_array( + $this->getConfigData('acobrar_code'), + $this->_postMethodsExplode + ) + ) { + $client->setParameterGet('nVlValorDeclarado', number_format($this->_packageValue, 2, ',', '.')); + } else { + $client->setParameterGet('nVlValorDeclarado', 0); + } - $while++; + $contrato = false; + foreach ($contratoCodes as $contratoEach) { + if (in_array($contratoEach, $this->_postMethodsExplode)) { + $contrato = true; + } } - } - if ($pesoCubicoTotal > $sweight) { - $mediaMedidas = round(pow((int) $volumeTotal, (1 / 3))); - $volumeComprimento = (($mediaMedidas < 16) ? 16 : $mediaMedidas); - $volumeAltura = (($mediaMedidas < 2) ? 2 : $mediaMedidas); - $volumeLargura = (($mediaMedidas < 11) ? 11 : $mediaMedidas); - } else { - $volumeComprimento = 16; - $volumeAltura = 2; - $volumeLargura = 11; - } + if ($contrato) { + if ($this->getConfigData('cod_admin') == '' || $this->getConfigData('senha_admin') == '') { + // Need correios admin data + $this->_throwError('coderror', 'Need correios admin data', __LINE__); + return false; + } else { + $client->setParameterGet('nCdEmpresa', $this->getConfigData('cod_admin')); + $client->setParameterGet('sDsSenha', $this->getConfigData('senha_admin')); + } + } + + $content = $client->request(); + $conteudo = $content->getBody(); - //Define post method - $shipping_methods = array(); - - $postmethods = explode(",", $this->getConfigData('postmethods')); - - foreach ($postmethods as $methods) { - - switch ($methods) { - case 0: - $shipping_methods["40010"] = array("Sedex", "3"); - break; - case 1: - $shipping_methods["40096"] = array("Sedex", "3"); - break; - case 2: - $shipping_methods["81019"] = array("E-Sedex", "3"); - break; - case 3: - $shipping_methods["41025"] = array("PAC", "3"); - break; - case 4: - $shipping_methods["41106"] = array("PAC", "3"); - break; - case 5: - $shipping_methods["41068"] = array("PAC", "3"); - break; - case 6: - $shipping_methods["40215"] = array("Sedex 10", "1"); - break; - case 7: - $shipping_methods["40290"] = array("Sedex HOJE", "1"); - break; - case 8: - $shipping_methods["40045"] = array("Sedex a Cobrar", "5"); - break; + if ($conteudo == "") { + throw new Exception("No XML returned [" . __LINE__ . "]"); } - } - foreach ($shipping_methods as $shipping_method => $shipping_values) { + libxml_use_internal_errors(true); + $sxe = simplexml_load_string($conteudo); + if (!$sxe) { + throw new Exception("Bad XML [" . __LINE__ . "]"); + } - //Define URL method - switch ($this->getConfigData('urlmethod')) { + // Load XML + $xml = new SimpleXMLElement($conteudo); - case 1: + if (count($xml->cServico) <= 0) { + throw new Exception("No tag cServico in Correios XML [" . __LINE__ . "]"); + } - $correiosWSLocaWeb = "http://comercio.locaweb.com.br/correios/frete.asmx?WSDL"; + return $xml->cServico; + } catch (Exception $e) { + //URL Error + $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__); + return false; + }; + } - $soap = @new SoapClient($correiosWSLocaWeb, array( - 'trace' => true, - 'exceptions' => true, - 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, - 'connection_timeout' => 1000 - )); + /** + * Apend shipping value to return + * + * @param $shipping_method string + * @param $shippingPrice float + * @param $correiosReturn array + */ + protected function _apendShippingReturn($shipping_method, $shippingPrice = 0, $correiosDelivery = 0) + { - // Postagem dos parâmetros - $parms = new ParametersLocaweb(); - $parms->cepOrigem = utf8_encode($frompcode); - $parms->cepDestino = utf8_encode($topcode); - $parms->peso = utf8_encode(str_replace(".", ",", $sweight)); - $parms->volume = utf8_encode($volumeTotal); - $parms->codigo = utf8_encode($shipping_method); + $method = Mage::getModel('shipping/rate_result_method'); + $method->setCarrier($this->_code); + $method->setCarrierTitle($this->getConfigData('title')); + $method->setMethod($shipping_method); - // Resgata o valor calculado - $resposta = $soap->Correios($parms); + $shippingCost = $shippingPrice; + $shippingPrice = $shippingPrice + $this->getConfigData('handling_fee'); - $shippingPrice = floatval(str_replace(",", ".", $resposta->CorreiosResult)); + $shipping_data = explode(',', $this->getConfigData('serv_' . $shipping_method)); - break; + if ($shipping_method == $this->getConfigData('acobrar_code')) { + $shipping_data[0] = $shipping_data[0] . ' ( R$' . number_format($shippingPrice, 2, ',', '.') . ' )'; + $shippingPrice = 0; + } - case 0: - $filename = "http://shopping.correios.com.br/wbm/shopping/script/CalcPrecoPrazo.aspx"; + // Show delivery days + if ($this->getConfigFlag('prazo_entrega')) { - try { - $client = new Zend_Http_Client($filename); - - $client->setParameterGet('StrRetorno', 'xml'); - $client->setParameterGet('nCdServico', $shipping_method); - $client->setParameterGet('nVlPeso', $sweight); - $client->setParameterGet('sCepOrigem', $frompcode); - $client->setParameterGet('sCepDestino', $topcode); - $client->setParameterGet('nCdFormato', 1); - $client->setParameterGet('nVlComprimento', $volumeComprimento); - $client->setParameterGet('nVlAltura', $volumeAltura); - $client->setParameterGet('nVlLargura', $volumeLargura); - if ($this->getConfigData('mao_propria')) { - $client->setParameterGet('sCdMaoPropria', 'S'); - } else { - $client->setParameterGet('sCdMaoPropria', 'N'); - } + // Delivery days from WS + if ($correiosDelivery > 0) { + $method->setMethodTitle( + sprintf( + $this->getConfigData('msgprazo'), + $shipping_data[0], + (int) ($correiosDelivery + $this->getConfigData('add_prazo')) + ) + ); + } else { + $method->setMethodTitle( + sprintf( + $this->getConfigData('msgprazo'), + $shipping_data[0], + (int) ($shipping_data[1] + $this->getConfigData('add_prazo')) + ) + ); + } + } else { + $method->setMethodTitle($shipping_data[0]); + } - if ($this->getConfigData('aviso_recebimento')) { - $client->setParameterGet('sCdAvisoRecebimento', 'S'); - } else { - $client->setParameterGet('sCdAvisoRecebimento', 'N'); - } + $method->setPrice($shippingPrice); + $method->setCost($shippingCost); - if ($this->getConfigData('valor_declarado') || $shipping_method == 40045) { - $client->setParameterGet('nVlValorDeclarado', number_format($packagevalue, 2, ',', '.')); - } else { - $client->setParameterGet('nVlValorDeclarado', 0); - } + if ($this->_freeMethodRequest === true) { + $this->_freeMethodRequestResult->append($method); + } else { + $this->_result->append($method); + } + } + /** + * Throw error + * + * @param $message string + * @param $log string + * @param $line int + * @param $custom string + */ + protected function _throwError($message, $log = null, $line = 'NO LINE', $custom = null) + { + $this->_result = null; + $this->_result = Mage::getModel('shipping/rate_result'); - if ($shipping_method == 40096 || $shipping_method == 81019 || $shipping_method == 41068) { - if ($this->getConfigData('cod_admin') == '' || $this->getConfigData('senha_admin') == '') { - // Need correios admin data - Mage::log('PedroTeixeira_Correios: Need correios admin data'); - $error->setErrorMessage($this->getConfigData('coderror')); - $result->append($error); - return $result; - } else { - $client->setParameterGet('nCdEmpresa', $this->getConfigData('cod_admin')); - $client->setParameterGet('sDsSenha', $this->getConfigData('senha_admin')); - } - } + // Get error model + $error = Mage::getModel('shipping/rate_result_error'); + $error->setCarrier($this->_code); + $error->setCarrierTitle($this->getConfigData('title')); - $content = $client->request(); - $conteudo = $content->getBody(); + if (is_null($custom)) { + //Log error + Mage::log($this->_code . ' [' . $line . ']: ' . $log); + $error->setErrorMessage($this->getConfigData($message)); + } else { + //Log error + Mage::log($this->_code . ' [' . $line . ']: ' . $log); + $error->setErrorMessage(sprintf($this->getConfigData($message), $custom)); + } - if (!stristr($conteudo, "setCarrier($this->_code); - $error->setCarrierTitle($this->getConfigData('title')); - $error->setMethod($shipping_method); - $error->setErrorMessage($this->getConfigData('urlerror')); - $result->append($error); - $shippingPrice = 0; - - continue; - }; - - preg_match_all("/(.+)<\/Codigo>/", $conteudo, $xml_servico); - preg_match_all("/(.+)<\/Valor>/", $conteudo, $preco_postal); - preg_match_all("/(.+)<\/PrazoEntrega>/", $conteudo, $prazo_postal); - preg_match_all("/(.+)<\/Erro>/", $conteudo, $err_id); - $err_id = str_replace('-', '', $err_id[1][0]); - $err_id = (int) $err_id; - preg_match_all("/(.+)<\/MsgErro>/", $conteudo, $err_msg); - - - $correiosReturn = array( - "prazo" => $prazo_postal[1][0] - ); - - if (trim($err_id) == "0") { - $shippingPrice = floatval(str_replace(",", ".", $preco_postal[1][0])); - } else { - - $ignorar = explode(',', $this->getConfigData('ignorar_erro')); - $ignorar = array_flip($ignorar); - if (!array_key_exists($err_id, $ignorar)) { - //Error - $error = Mage::getModel('shipping/rate_result_error'); - $error->setCarrier($this->_code); - $error->setCarrierTitle($this->getConfigData('title')); - $error->setMethod($shipping_method); - - // Correios Error - Mage::log('PedroTeixeira_Correios: Correios Error'); - $error->setErrorMessage( - sprintf( - $this->getConfigData('correioserror'), - $shipping_values[0], - $err_msg[1][0], - $err_id - ) - ); - $result->append($error); - $shippingPrice = 0; - } else { - $shippingPrice = 0; - } - } + // Apend error + $this->_result->append($error); + } + /** + * Generate PAC weight + */ + protected function _generatePacWeight() + { + //Create PAC weight + $pesoCubicoTotal = 0; - break; - default: - //URL method undefined - Mage::log('PedroTeixeira_Correios: URL method undefined'); - $error->setErrorMessage($this->getConfigData('urlerror')); - $result->append($error); - return $result; - } + // Get all visible itens from quote + $items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems(); - if ($shippingPrice <= 0) { - continue; - } + foreach ($items as $item) { - $method = Mage::getModel('shipping/rate_result_method'); + $while = 0; + $itemAltura = 0; + $itemLargura = 0; + $itemComprimento = 0; - $method->setCarrier($this->_code); - $method->setCarrierTitle($this->getConfigData('title')); + $_product = $item->getProduct(); - $method->setMethod($shipping_method); + if ($_product->getData('volume_altura') == '' || (int) $_product->getData('volume_altura') == 0) { + $itemAltura = $this->getConfigData('altura_padrao'); + } else { + $itemAltura = $_product->getData('volume_altura'); + } - if ($this->getConfigFlag('prazo_entrega')) { + if ($_product->getData('volume_largura') == '' || (int) $_product->getData('volume_largura') == 0) { + $itemLargura = $this->getConfigData('largura_padrao'); + } else { + $itemLargura = $_product->getData('volume_largura'); + } - if (isset($correiosReturn)) { - if ($correiosReturn['prazo'] > 0) { - $method->setMethodTitle( - sprintf( - $this->getConfigData('msgprazo'), - $shipping_values[0], - (int) $correiosReturn['prazo'] + $this->getConfigData('add_prazo') - ) - ); - } else { - $method->setMethodTitle( - sprintf( - $this->getConfigData('msgprazo'), - $shipping_values[0], - $shipping_values[1] + $this->getConfigData('add_prazo') - ) - ); - } - } else { - $method->setMethodTitle( - sprintf( - $this->getConfigData('msgprazo'), - $shipping_values[0], - $shipping_values[1] + $this->getConfigData('add_prazo') - ) - ); - } + if ($_product->getData('volume_comprimento') == '' || (int) $_product->getData('volume_comprimento') == 0) { + $itemComprimento = $this->getConfigData('comprimento_padrao'); } else { - $method->setMethodTitle($shipping_values[0]); + $itemComprimento = $_product->getData('volume_comprimento'); } - $method->setPrice($shippingPrice + $this->getConfigData('handling_fee')); + while ($while < $item->getQty()) { + $itemPesoCubico = 0; + $itemPesoCubico = ($itemAltura * $itemLargura * $itemComprimento) / 4800; + $pesoCubicoTotal = $pesoCubicoTotal + $itemPesoCubico; + $while++; + } + } - $method->setCost($shippingPrice); + $this->_pacWeight = number_format($pesoCubicoTotal, 2, '.', ''); + } - $result->append($method); + /** + * Generate free shipping for a product + * + * @param string $freeMethod + */ + protected function _setFreeMethodRequest($freeMethod) + { + // Set request as free method request + $this->_freeMethodRequest = true; + $this->_freeMethodRequestResult = Mage::getModel('shipping/rate_result'); + + $this->_postMethods = $freeMethod; + $this->_postMethodsExplode = array($freeMethod); - $shippingPrice = null; + // Tranform free shipping weight + if ($this->getConfigData('weight_type') == 'gr') { + $this->_freeMethodWeight = number_format($this->_freeMethodWeight / 1000, 2, '.', ''); } - $this->_result = $result; + $this->_packageWeight = $this->_freeMethodWeight; + $this->_pacWeight = $this->_freeMethodWeight; + } - $this->_updateFreeMethodQuote($request); + /** + * Clean correios error code, usualy with "-" before the code + * + * @param string $error + * + * @return int + */ + protected function _cleanCorreiosError($error) + { + $error = str_replace('-', '', $error); + $error = (int) $error; + return $error; + } - return $this->_result; + + /** + * Check if current carrier offer support to tracking + * + * @return boolean true + */ + public function isTrackingAvailable() + { + return true; } /** @@ -461,7 +678,6 @@ public function getTrackingInfo($tracking) } elseif (is_string($result) && !empty($result)) { return $result; } - return false; } @@ -546,11 +762,10 @@ protected function _getTracking($code) } if ($found) { - $datetime = split(' ', $matches[1]); - - $locale = new Zend_Locale('pt_BR'); - $date = ''; - $date = new Zend_Date($datetime[0], 'dd/MM/YYYY', $locale); + $datetime = explode(' ', $matches[1]); + $locale = new Zend_Locale('pt_BR'); + $date = ''; + $date = new Zend_Date($datetime[0], 'dd/MM/YYYY', $locale); $track = array( 'deliverydate' => $date->toString('YYYY-MM-dd'), @@ -605,4 +820,4 @@ public function isZipCodeRequired() { return true; } -} +} \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/FreeMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/FreeMethods.php deleted file mode 100755 index 0bfac51..0000000 --- a/app/code/community/PedroTeixeira/Correios/Model/Source/FreeMethods.php +++ /dev/null @@ -1,34 +0,0 @@ - - * @license http://opensource.org/licenses/MIT - */ - -class PedroTeixeira_Correios_Model_Source_FreeMethods -{ - - public function toOptionArray() - { - return array( - array('value' => 40010, 'label' => Mage::helper('adminhtml')->__('Sedex Sem Contrato (Correios)')), - array('value' => 40096, 'label' => Mage::helper('adminhtml')->__('Sedex Com Contrato (Correios/Locaweb)')), - array( - 'value' => 81019, - 'label' => Mage::helper('adminhtml')->__('E-Sedex Com Contrato (Correios/Locaweb)') - ), - array('value' => 41025, 'label' => Mage::helper('adminhtml')->__('PAC Normal (Locaweb)')), - array('value' => 41106, 'label' => Mage::helper('adminhtml')->__('PAC Sem Contrato (Correios)')), - array('value' => 41068, 'label' => Mage::helper('adminhtml')->__('PAC Com Contrato (Correios/Locaweb)')), - array('value' => 40215, 'label' => Mage::helper('adminhtml')->__('Sedex 10 (Correios)')), - array('value' => 40290, 'label' => Mage::helper('adminhtml')->__('Sedex HOJE (Correios)')), - array('value' => 40045, 'label' => Mage::helper('adminhtml')->__('Sedex a Cobrar (Correios)')), - ); - } -} \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php old mode 100755 new mode 100644 index 93eb247..bf052f3 --- a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php +++ b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php @@ -17,15 +17,15 @@ class PedroTeixeira_Correios_Model_Source_PostMethods public function toOptionArray() { return array( - array('value' => 0, 'label' => Mage::helper('adminhtml')->__('Sedex Sem Contrato (Correios)')), - array('value' => 1, 'label' => Mage::helper('adminhtml')->__('Sedex Com Contrato (Correios/Locaweb)')), - array('value' => 2, 'label' => Mage::helper('adminhtml')->__('E-Sedex Com Contrato (Correios/Locaweb)')), - array('value' => 3, 'label' => Mage::helper('adminhtml')->__('PAC Normal (Locaweb)')), - array('value' => 4, 'label' => Mage::helper('adminhtml')->__('PAC Sem Contrato (Correios)')), - array('value' => 5, 'label' => Mage::helper('adminhtml')->__('PAC Com Contrato (Correios/Locaweb)')), - array('value' => 6, 'label' => Mage::helper('adminhtml')->__('Sedex 10 (Correios)')), - array('value' => 7, 'label' => Mage::helper('adminhtml')->__('Sedex HOJE (Correios)')), - array('value' => 8, 'label' => Mage::helper('adminhtml')->__('Sedex a Cobrar (Correios)')), + array('value' => 40010, 'label' => Mage::helper('adminhtml')->__('Sedex Sem Contrato (Correios)')), + array('value' => 40096, 'label' => Mage::helper('adminhtml')->__('Sedex Com Contrato (Correios/Locaweb)')), + array('value' => 81019, 'label' => Mage::helper('adminhtml')->__('E-Sedex Com Contrato (Correios/Locaweb)')), + array('value' => 41025, 'label' => Mage::helper('adminhtml')->__('PAC Normal (Locaweb)')), + array('value' => 41106, 'label' => Mage::helper('adminhtml')->__('PAC Sem Contrato (Correios)')), + array('value' => 41068, 'label' => Mage::helper('adminhtml')->__('PAC Com Contrato (Correios/Locaweb)')), + array('value' => 40215, 'label' => Mage::helper('adminhtml')->__('Sedex 10 (Correios)')), + array('value' => 40290, 'label' => Mage::helper('adminhtml')->__('Sedex HOJE (Correios)')), + array('value' => 40045, 'label' => Mage::helper('adminhtml')->__('Sedex a Cobrar (Correios)')), ); } } \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/UrlMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/UrlMethods.php old mode 100755 new mode 100644 diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php b/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php old mode 100755 new mode 100644 diff --git a/app/code/community/PedroTeixeira/Correios/etc/config.xml b/app/code/community/PedroTeixeira/Correios/etc/config.xml old mode 100755 new mode 100644 index b86cbeb..045ad8d --- a/app/code/community/PedroTeixeira/Correios/etc/config.xml +++ b/app/code/community/PedroTeixeira/Correios/etc/config.xml @@ -15,7 +15,7 @@ - 4.0.0 + 4.1.0 @@ -67,40 +67,72 @@ + 1 PedroTeixeira_Correios_Model_Carrier_CorreiosMethod Correios + 40010 + 1,2,3,4,5,33,34,35,36,37,38,888,7,99 + 0 + 0 + 10000 + 30 + 0 + 30 + + 0 0 0 - 1,2,5,6,7,10,36,37,38,99 + + 2 16 11 - 0 - 0 - 0 - 500 + 2 + 16 + 11 + + 0 + 40010 kg - 30 - 0 0 + 1 + + %s - Em média %d dia(s) - 40010 - %s - Houve um erro inesperado, por favor entre em contato. %s (Cod. %d) - Valor de compra a cima do permitido pelos Correios. Por favor entre em contato conosco. + Houve um erro inesperado, por favor entre em contato. %s + Valor de compra fora do permitido pelos Correios. Por favor entre em contato conosco. Por favor, corrija o CEP digitado, ele não está correto. - Peso dos produtos a cima do permitido pelos Correios. Por favor entre em contato + Peso dos produtos acima do permitido pelos Correios. Por favor entre em contato conosco. Lojista: O peso do produto deverá ser maior que zero. Se você está usando a media de peso como gramas, o peso mínimo é de 10 gramas. - Esse método de envio está fora do ar. Por favor entre em contato conosco. Lojista: Para calcular esse serviço você precisa ter contrato com os Correios. - 0 + Esse método de envio está fora do ar. Por favor entre em contato conosco. + + + Sedex,3 + Sedex,3 + E-Sedex,3 + PAC,3 + PAC,3 + PAC,3 + Sedex 10,1 + Sedex HOJE,1 + Sedex a Cobrar,5 + + 41025,41106,41068 + 40045 + 40096,81019,41068 + + http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx + http://comercio.locaweb.com.br/correios/frete.asmx?WSDL + diff --git a/app/code/community/PedroTeixeira/Correios/etc/system.xml b/app/code/community/PedroTeixeira/Correios/etc/system.xml old mode 100755 new mode 100644 index e30a4d2..e6479f6 --- a/app/code/community/PedroTeixeira/Correios/etc/system.xml +++ b/app/code/community/PedroTeixeira/Correios/etc/system.xml @@ -29,13 +29,14 @@
Informações Importantes

Você pode tirar dúvidas ou sugerir melhorias do módulo através do site www.pteixeira.com.br.

- Na versão 4.0.0 o módulo de cálculo de frete conta com instalação automática dos atributos de volume, SEDEX a Cobrar, opção de configurar o formato do peso de seus produtos, - correção do problema de getBody(), correção do problema de ereg(), nova forma de passar o volume para cálculo do PAC, log de erros e outras funcionalidades.

+ Na versão 4.1.0 o módulo de cálculo de frete conta com chamada única ao WebService dos Correios para cálculo de todos os serviços, novos filtros para evitar erros no frontend, nomes dos serviços e prazos de entrega configuráveis por xml, integração total com as regras de desconto, novos logs de erros mais completos, desconsiderando duplicidade de produtos configuráveis dentre várias outras modificações.

Para um bom funcionamento do módulo, é necessário que você configure os serviços que deseja disponibilizar em sua loja e escolher a fonte de cálculo de acordo com os serviços habilitados. - Por exemplo, se você habilitar "Sedex Com Contrato (Correios)" lembre-se de configurar a fonte de cálculo como Correios, já se habilitar "PAC Normal (Locaweb)" lembre-se de configurar a fonte como "Locaweb".

+ Por exemplo, se você habilitar "Sedex Com Contrato (Correios)" lembre-se de configurar a fonte de cálculo como Correios, já se habilitar "PAC Normal (Locaweb)" + lembre-se de configurar a fonte como "Locaweb".

Lembre-se de configurar as "Definições de Envio" no menu ao lado esquerdo.

Para serviços que tenham em seu nome "Com Contrato", é necessário configurar o "Código Administrativo dos Correios" e "Senha Administrativa dos Correios".

A lista completa de códigos de erros está disponibilizada no site do desenvolvedor.

+ Para utilizar as regras de desconto de frete, você deve configurar o "Serviço para entrega gratuita", lembre-se de habilitar o serviço.

Importante: Para utilização da função de tracking é necessário corrigir alguns erros do próprio Magento, veja mais informações no site do desenvolvedor.




@@ -71,6 +72,19 @@ fonte configurada. + + + select + free-method + PedroTeixeira_Correios_Model_Source_PostMethods + 21 + 1 + 1 + 1 + Quando usar um cupom oferecendo frete gratuito, qual serviço será gratuito. + Lembre-se de habilitar o serviço. + + select @@ -144,15 +158,6 @@ 1 1 - - - text - 66 - 1 - 1 - 1 - Códigos separados por vírgula. - text @@ -303,6 +308,18 @@ 1 1 + + + select + 200 + adminhtml/system_config_source_yesno + 1 + 1 + 1 + Se houver um erro ou o método não for aplicável naquela situação, mesmo assim + mostrar as mensagens de erro? + + text diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-install-4.0.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-install-4.0.0.php old mode 100755 new mode 100644 index 016c16f..278aa80 --- a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-install-4.0.0.php +++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-install-4.0.0.php @@ -18,7 +18,7 @@ $installer->startSetup(); -// Adiciona o volume como atributo do produto +// Add volume to prduct attribute set $codigo = 'volume_comprimento'; $config = array( 'position' => 1, @@ -32,7 +32,7 @@ $setup->addAttribute('catalog_product', $codigo, $config); -// Adiciona o volume como atributo do produto +// Add volume to prduct attribute set $codigo = 'volume_altura'; $config = array( 'position' => 1, @@ -46,7 +46,7 @@ $setup->addAttribute('catalog_product', $codigo, $config); -// Adiciona o volume como atributo do produto +// Add volume to prduct attribute set $codigo = 'volume_largura'; $config = array( 'position' => 1, diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.0.0-4.1.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.0.0-4.1.0.php new file mode 100644 index 0000000..d2823b2 --- /dev/null +++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.0.0-4.1.0.php @@ -0,0 +1,25 @@ + + * @license http://opensource.org/licenses/MIT + */ + +$installer = $this; +$installer->startSetup(); + +// Delete unused or edited config data +$installer->deleteConfigData('carriers/pedroteixeira_correios/ignorar_erro'); +$installer->deleteConfigData('carriers/pedroteixeira_correios/correioserror'); +$installer->deleteConfigData('carriers/pedroteixeira_correios/maxweighterror'); +$installer->deleteConfigData('carriers/pedroteixeira_correios/valueerror'); +$installer->deleteConfigData('carriers/pedroteixeira_correios/showmethod'); + +$installer->endSetup(); +?> \ No newline at end of file diff --git a/app/etc/modules/PedroTeixeira_Correios.xml b/app/etc/modules/PedroTeixeira_Correios.xml old mode 100755 new mode 100644