diff --git a/CHANGELOG.md b/CHANGELOG.md index 27c8b7e..b2edee1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +# 4.2.0 +--- + +### Bugfix + +- Timeout dos Correios reduzido para ficar compatível com o timeout do banco +- Modificada a quebra de linha para formato Linux + +### Feature + +- Utilizando peso volumétrico para todos os serviços +- Retirada a URL de cálculo da Locaweb +- Possibilidade de limitar as dimensões dos produtos +- Retirando "ponto" do CEP + + # 4.1.0 --- diff --git a/LICENSE b/LICENSE index 42259f4..4fc4660 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2010 Pedro Teixeira +Copyright (c) 2010-2011 Pedro Teixeira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/app/code/community/PedroTeixeira/Correios/Helper/Data.php b/app/code/community/PedroTeixeira/Correios/Helper/Data.php index e763ffe..3c569a6 100644 --- a/app/code/community/PedroTeixeira/Correios/Helper/Data.php +++ b/app/code/community/PedroTeixeira/Correios/Helper/Data.php @@ -1,16 +1,16 @@ - - * @license http://opensource.org/licenses/MIT - */ - -class PedroTeixeira_Correios_Helper_Data extends Mage_Core_Helper_Abstract -{ -} \ No newline at end of file + + * @license http://opensource.org/licenses/MIT + */ + +class PedroTeixeira_Correios_Helper_Data extends Mage_Core_Helper_Abstract +{ +} diff --git a/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php b/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php index dfb795f..8fd5c7b 100644 --- a/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php +++ b/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php @@ -1,823 +1,742 @@ - - * @license http://opensource.org/licenses/MIT - */ - -/** - * PedroTeixeira_Correios_Model_Carrier_CorreiosMethod - * - * @category PedroTeixeira - * @package PedroTeixeira_Correios - * @author Pedro Teixeira - */ - -class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod - extends Mage_Shipping_Model_Carrier_Abstract - implements Mage_Shipping_Model_Carrier_Interface -{ - - /** - * _code property - * - * @var string - */ - protected $_code = 'pedroteixeira_correios'; - - /** - * _result property - * - * @var Mage_Shipping_Model_Rate_Result / Mage_Shipping_Model_Tracking_Result - */ - protected $_result = null; - - /** - * ZIP code vars - */ - 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 - * - * @param Mage_Shipping_Model_Rate_Request $request - * - * @return Mage_Shipping_Model_Rate_Result - */ - public function collectRates(Mage_Shipping_Model_Rate_Request $request) - { - // 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; - } - - // 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; - } - - // Check weight zero - if ($this->_packageWeight <= 0) { - //Weight zero - $this->_throwError('weightzeroerror', 'Weight zero', __LINE__); - return $this->_result; - } - - // Generate PAC Weight - $this->_generatePacWeight(); - - // Get post methods - $this->_postMethods = $this->getConfigData('postmethods'); - $this->_postMethodsFixed = $this->_postMethods; - $this->_postMethodsExplode = explode(",", $this->getConfigData('postmethods')); - - // Get quotes - if ($this->_getQuotes()->getError()) { - return $this->_result; - } - - // Use descont codes - $this->_updateFreeMethodQuote($request); - - // Return rates / errors - return $this->_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; - } - } - - - /** - * 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; - } - - - $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(); - - //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'); - - // Value - $this->_packageValue = $request->getBaseCurrency()->convert( - $request->getPackageValue(), - $request->getPackageCurrency() - ); - - // Weight - $this->_packageWeight = number_format($request->getPackageWeight(), 2, '.', ''); - - // Free method weight - $this->_freeMethodWeight = number_format($request->getFreeMethodWeight(), 2, '.', ''); - } - - /** - * Get Correios return - * - * @return bool - */ - protected function _getCorreiosReturn() - { - - $filename = $this->getConfigData('url_ws_correios'); - - $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 { - $client->setParameterGet('nVlPeso', $this->_packageWeight); - } - - $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 { - $client->setParameterGet('sCdMaoPropria', 'N'); - } - - if ($this->getConfigData('aviso_recebimento')) { - $client->setParameterGet('sCdAvisoRecebimento', 'S'); - } else { - $client->setParameterGet('sCdAvisoRecebimento', 'N'); - } - - 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); - } - - $contrato = false; - foreach ($contratoCodes as $contratoEach) { - if (in_array($contratoEach, $this->_postMethodsExplode)) { - $contrato = true; - } - } - - 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(); - - if ($conteudo == "") { - throw new Exception("No XML returned [" . __LINE__ . "]"); - } - - libxml_use_internal_errors(true); - $sxe = simplexml_load_string($conteudo); - if (!$sxe) { - throw new Exception("Bad XML [" . __LINE__ . "]"); - } - - // Load XML - $xml = new SimpleXMLElement($conteudo); - - if (count($xml->cServico) <= 0) { - throw new Exception("No tag cServico in Correios XML [" . __LINE__ . "]"); - } - - return $xml->cServico; - } catch (Exception $e) { - //URL Error - $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__); - return false; - }; - } - - /** - * Apend shipping value to return - * - * @param $shipping_method string - * @param $shippingPrice float - * @param $correiosReturn array - */ - protected function _apendShippingReturn($shipping_method, $shippingPrice = 0, $correiosDelivery = 0) - { - - $method = Mage::getModel('shipping/rate_result_method'); - $method->setCarrier($this->_code); - $method->setCarrierTitle($this->getConfigData('title')); - $method->setMethod($shipping_method); - - $shippingCost = $shippingPrice; - $shippingPrice = $shippingPrice + $this->getConfigData('handling_fee'); - - $shipping_data = explode(',', $this->getConfigData('serv_' . $shipping_method)); - - if ($shipping_method == $this->getConfigData('acobrar_code')) { - $shipping_data[0] = $shipping_data[0] . ' ( R$' . number_format($shippingPrice, 2, ',', '.') . ' )'; - $shippingPrice = 0; - } - - - // Show delivery days - if ($this->getConfigFlag('prazo_entrega')) { - - // 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]); - } - - $method->setPrice($shippingPrice); - $method->setCost($shippingCost); - - 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'); - - // Get error model - $error = Mage::getModel('shipping/rate_result_error'); - $error->setCarrier($this->_code); - $error->setCarrierTitle($this->getConfigData('title')); - - 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)); - } - - // Apend error - $this->_result->append($error); - } - - /** - * Generate PAC weight - */ - protected function _generatePacWeight() - { - //Create PAC weight - $pesoCubicoTotal = 0; - - // Get all visible itens from quote - $items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems(); - - foreach ($items as $item) { - - $while = 0; - $itemAltura = 0; - $itemLargura = 0; - $itemComprimento = 0; - - $_product = $item->getProduct(); - - if ($_product->getData('volume_altura') == '' || (int) $_product->getData('volume_altura') == 0) { - $itemAltura = $this->getConfigData('altura_padrao'); - } else { - $itemAltura = $_product->getData('volume_altura'); - } - - if ($_product->getData('volume_largura') == '' || (int) $_product->getData('volume_largura') == 0) { - $itemLargura = $this->getConfigData('largura_padrao'); - } else { - $itemLargura = $_product->getData('volume_largura'); - } - - if ($_product->getData('volume_comprimento') == '' || (int) $_product->getData('volume_comprimento') == 0) { - $itemComprimento = $this->getConfigData('comprimento_padrao'); - } else { - $itemComprimento = $_product->getData('volume_comprimento'); - } - - while ($while < $item->getQty()) { - $itemPesoCubico = 0; - $itemPesoCubico = ($itemAltura * $itemLargura * $itemComprimento) / 4800; - $pesoCubicoTotal = $pesoCubicoTotal + $itemPesoCubico; - $while++; - } - } - - $this->_pacWeight = number_format($pesoCubicoTotal, 2, '.', ''); - } - - /** - * 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); - - // Tranform free shipping weight - if ($this->getConfigData('weight_type') == 'gr') { - $this->_freeMethodWeight = number_format($this->_freeMethodWeight / 1000, 2, '.', ''); - } - - $this->_packageWeight = $this->_freeMethodWeight; - $this->_pacWeight = $this->_freeMethodWeight; - } - - /** - * 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; - } - - - /** - * Check if current carrier offer support to tracking - * - * @return boolean true - */ - public function isTrackingAvailable() - { - return true; - } - - /** - * Get Tracking Info - * - * @param mixed $tracking - * - * @return mixed - */ - public function getTrackingInfo($tracking) - { - $result = $this->getTracking($tracking); - if ($result instanceof Mage_Shipping_Model_Tracking_Result) { - if ($trackings = $result->getAllTrackings()) { - return $trackings[0]; - } - } elseif (is_string($result) && !empty($result)) { - return $result; - } - return false; - } - - /** - * Get Tracking - * - * @param array $trackings - * - * @return Mage_Shipping_Model_Tracking_Result - */ - public function getTracking($trackings) - { - $this->_result = Mage::getModel('shipping/tracking_result'); - foreach ((array) $trackings as $code) { - $this->_getTracking($code); - } - return $this->_result; - } - - /** - * Protected Get Tracking, opens the request to Correios - * - * @param string $code - * - * @return boolean - */ - protected function _getTracking($code) - { - $error = Mage::getModel('shipping/tracking_result_error'); - $error->setTracking($code); - $error->setCarrier($this->_code); - $error->setCarrierTitle($this->getConfigData('title')); - $error->setErrorMessage($this->getConfigData('urlerror')); - - $url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList'; - $url .= '?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $code; - try { - $client = new Zend_Http_Client(); - $client->setUri($url); - $content = $client->request(); - $body = $content->getBody(); - } catch (Exception $e) { - $this->_result->append($error); - return false; - } - - if (!preg_match('#]+)>(.*?)
#is', $body, $matches)) { - $this->_result->append($error); - return false; - } - $table = $matches[2]; - - if (!preg_match_all('/(.*)<\/tr>/i', $table, $columns, PREG_SET_ORDER)) { - $this->_result->append($error); - return false; - } - - $progress = array(); - for ($i = 0; $i < count($columns); $i++) { - $column = $columns[$i][1]; - - $description = ''; - $found = false; - if (preg_match('/(.*)<\/td>(.*)<\/td>(.*)<\/font><\/td>/i', - $column, - $matches - ) - ) { - if (preg_match('/(.*)<\/td>/i', $columns[$i + 1][1], $matchesDescription)) { - $description = str_replace(' ', '', $matchesDescription[1]); - } - - $found = true; - } elseif (preg_match( - '/(.*)<\/td>(.*)<\/td>(.*)<\/font><\/td>/i', - $column, - $matches - ) - ) { - $found = true; - } - - if ($found) { - $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'), - 'deliverytime' => $datetime[1] . ':00', - 'deliverylocation' => htmlentities($matches[2]), - 'status' => htmlentities($matches[3]), - 'activity' => htmlentities($matches[3]) - ); - - if ($description !== '') { - $track['activity'] = $matches[3] . ' - ' . htmlentities($description); - } - - $progress[] = $track; - } - } - - if (!empty($progress)) { - $track = $progress[0]; - $track['progressdetail'] = $progress; - - $tracking = Mage::getModel('shipping/tracking_result_status'); - $tracking->setTracking($code); - $tracking->setCarrier('correios'); - $tracking->setCarrierTitle($this->getConfigData('title')); - $tracking->addData($track); - - $this->_result->append($tracking); - return true; - } else { - $this->_result->append($error); - return false; - } - } - - /** - * Returns the allowed carrier methods - * - * @return array - */ - public function getAllowedMethods() - { - return array($this->_code => $this->getConfigData('title')); - } - - /** - * Define ZIP Code as required - * - * @return boolean - */ - public function isZipCodeRequired() - { - return true; - } -} \ No newline at end of file + + * @license http://opensource.org/licenses/MIT + */ + +/** + * PedroTeixeira_Correios_Model_Carrier_CorreiosMethod + * + * @category PedroTeixeira + * @package PedroTeixeira_Correios + * @author Pedro Teixeira + */ + +class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod + extends Mage_Shipping_Model_Carrier_Abstract + implements Mage_Shipping_Model_Carrier_Interface +{ + + /** + * _code property + * + * @var string + */ + protected $_code = 'pedroteixeira_correios'; + + /** + * _result property + * + * @var Mage_Shipping_Model_Rate_Result / Mage_Shipping_Model_Tracking_Result + */ + protected $_result = null; + + /** + * ZIP code vars + */ + protected $_fromZip = null; + protected $_toZip = null; + + /** + * Value and Weight + */ + protected $_packageValue = null; + protected $_packageWeight = null; + protected $_volumeWeight = 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 + * + * @param Mage_Shipping_Model_Rate_Request $request + * + * @return Mage_Shipping_Model_Rate_Result + */ + public function collectRates(Mage_Shipping_Model_Rate_Request $request) + { + // 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; + } + + // 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; + } + + // Check weight zero + if ($this->_packageWeight <= 0) { + // Weight zero + $this->_throwError('weightzeroerror', 'Weight zero', __LINE__); + return $this->_result; + } + + // Generate Volume Weight + if ($this->_generateVolumeWeight() === false) { + // Dimension error + $this->_throwError('dimensionerror', 'Dimension error', __LINE__); + return $this->_result; + } + + // Get post methods + $this->_postMethods = $this->getConfigData('postmethods'); + $this->_postMethodsFixed = $this->_postMethods; + $this->_postMethodsExplode = explode(",", $this->getConfigData('postmethods')); + + // Get quotes + if ($this->_getQuotes()->getError()) { + return $this->_result; + } + + // Use descont codes + $this->_updateFreeMethodQuote($request); + + // Return rates / errors + return $this->_result; + } + + /** + * Get shipping quote + * + * @return object + */ + protected function _getQuotes() + { + + $dieErrors = explode(",", $this->getConfigData('die_errors')); + + // Call Correios + $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; + } + } + + $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; + } + + // Success + if ($this->_freeMethodRequest === true) { + return $this->_freeMethodRequestResult; + } else { + return $this->_result; + } + } + + + /** + * 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; + } + + + $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(); + + //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)) { + //From zip code error + Mage::log('PedroTeixeira_Correios: From ZIP Code Error'); + return false; + } + + // Result model + $this->_result = Mage::getModel('shipping/rate_result'); + + // Value + $this->_packageValue = $request->getBaseCurrency()->convert( + $request->getPackageValue(), + $request->getPackageCurrency() + ); + + // Weight + $this->_packageWeight = number_format($request->getPackageWeight(), 2, '.', ''); + + // Free method weight + $this->_freeMethodWeight = number_format($request->getFreeMethodWeight(), 2, '.', ''); + } + + /** + * Get Correios return + * + * @return bool + */ + protected function _getCorreiosReturn() + { + + $filename = $this->getConfigData('url_ws_correios'); + $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 ($this->_volumeWeight > $this->getConfigData( + 'volume_weight_min' + ) && $this->_volumeWeight > $this->_packageWeight + ) { + $client->setParameterGet('nVlPeso', $this->_volumeWeight); + } else { + $client->setParameterGet('nVlPeso', $this->_packageWeight); + } + + $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 { + $client->setParameterGet('sCdMaoPropria', 'N'); + } + + if ($this->getConfigData('aviso_recebimento')) { + $client->setParameterGet('sCdAvisoRecebimento', 'S'); + } else { + $client->setParameterGet('sCdAvisoRecebimento', 'N'); + } + + 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); + } + + $contrato = false; + foreach ($contratoCodes as $contratoEach) { + if (in_array($contratoEach, $this->_postMethodsExplode)) { + $contrato = true; + } + } + + 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()->getBody(); + + if ($content == "") { + throw new Exception("No XML returned [" . __LINE__ . "]"); + } + + libxml_use_internal_errors(true); + $sxe = simplexml_load_string($content); + if (!$sxe) { + throw new Exception("Bad XML [" . __LINE__ . "]"); + } + + // Load XML + $xml = new SimpleXMLElement($content); + + if (count($xml->cServico) <= 0) { + throw new Exception("No tag cServico in Correios XML [" . __LINE__ . "]"); + } + + return $xml->cServico; + } catch (Exception $e) { + //URL Error + $this->_throwError('urlerror', 'URL Error - ' . $e->getMessage(), __LINE__); + return false; + }; + } + + /** + * Apend shipping value to return + * + * @param $shipping_method string + * @param $shippingPrice float + * @param $correiosReturn array + * + * @return void + */ + protected function _apendShippingReturn($shipping_method, $shippingPrice = 0, $correiosDelivery = 0) + { + + $method = Mage::getModel('shipping/rate_result_method'); + $method->setCarrier($this->_code); + $method->setCarrierTitle($this->getConfigData('title')); + $method->setMethod($shipping_method); + + $shippingCost = $shippingPrice; + $shippingPrice = $shippingPrice + $this->getConfigData('handling_fee'); + + $shipping_data = explode(',', $this->getConfigData('serv_' . $shipping_method)); + + if ($shipping_method == $this->getConfigData('acobrar_code')) { + $shipping_data[0] = $shipping_data[0] . ' ( R$' . number_format($shippingPrice, 2, ',', '.') . ' )'; + $shippingPrice = 0; + } + + // Show delivery days + if ($this->getConfigFlag('prazo_entrega')) { + // 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]); + } + + $method->setPrice($shippingPrice); + $method->setCost($shippingCost); + + 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 + * + * @return void + */ + protected function _throwError($message, $log = null, $line = 'NO LINE', $custom = null) + { + + $this->_result = null; + $this->_result = Mage::getModel('shipping/rate_result'); + + // Get error model + $error = Mage::getModel('shipping/rate_result_error'); + $error->setCarrier($this->_code); + $error->setCarrierTitle($this->getConfigData('title')); + + if (is_null($custom) || $this->getConfigData($message) == '') { + //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)); + } + + // Apend error + $this->_result->append($error); + } + + /** + * Generate Volume weight + * + * @return bool + */ + protected function _generateVolumeWeight() + { + //Create volume weight + $pesoCubicoTotal = 0; + + // Get all visible itens from quote + $items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems(); + + foreach ($items as $item) { + + $itemAltura = 0; + $itemLargura = 0; + $itemComprimento = 0; + + $_product = $item->getProduct(); + + if ($_product->getData('volume_altura') == '' || (int) $_product->getData('volume_altura') == 0) { + $itemAltura = $this->getConfigData('altura_padrao'); + } else { + $itemAltura = $_product->getData('volume_altura'); + } + + if ($_product->getData('volume_largura') == '' || (int) $_product->getData('volume_largura') == 0) { + $itemLargura = $this->getConfigData('largura_padrao'); + } else { + $itemLargura = $_product->getData('volume_largura'); + } + + if ($_product->getData('volume_comprimento') == '' || (int) $_product->getData('volume_comprimento') == 0) { + $itemComprimento = $this->getConfigData('comprimento_padrao'); + } else { + $itemComprimento = $_product->getData('volume_comprimento'); + } + + if ($this->getConfigFlag('check_dimensions')) { + if ( + $itemAltura > $this->getConfigData('volume_validation/altura_max') + || $itemAltura < $this->getConfigData('volume_validation/altura_min') + || $itemLargura > $this->getConfigData('volume_validation/largura_max') + || $itemLargura < $this->getConfigData('volume_validation/largura_min') + || $itemComprimento > $this->getConfigData('volume_validation/comprimento_max') + || $itemComprimento < $this->getConfigData('volume_validation/comprimento_min') + || ($itemAltura + $itemLargura + $itemComprimento) > $this->getConfigData( + 'volume_validation/sum_max' + ) + ) { + return false; + } + } + + $pesoCubicoTotal += (($itemAltura * $itemLargura * $itemComprimento) * $item->getQty( + )) / $this->getConfigData('coeficiente_volume'); + } + + $this->_volumeWeight = number_format($pesoCubicoTotal, 2, '.', ''); + + return true; + } + + /** + * Generate free shipping for a product + * + * @param string $freeMethod + * + * @return void + */ + 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); + + // Tranform free shipping weight + if ($this->getConfigData('weight_type') == 'gr') { + $this->_freeMethodWeight = number_format($this->_freeMethodWeight / 1000, 2, '.', ''); + } + + $this->_packageWeight = $this->_freeMethodWeight; + $this->_pacWeight = $this->_freeMethodWeight; + } + + /** + * 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; + } + + + /** + * Check if current carrier offer support to tracking + * + * @return boolean true + */ + public function isTrackingAvailable() + { + return true; + } + + /** + * Get Tracking Info + * + * @param mixed $tracking + * + * @return mixed + */ + public function getTrackingInfo($tracking) + { + $result = $this->getTracking($tracking); + if ($result instanceof Mage_Shipping_Model_Tracking_Result) { + if ($trackings = $result->getAllTrackings()) { + return $trackings[0]; + } + } elseif (is_string($result) && !empty($result)) { + return $result; + } + return false; + } + + /** + * Get Tracking + * + * @param array $trackings + * + * @return Mage_Shipping_Model_Tracking_Result + */ + public function getTracking($trackings) + { + $this->_result = Mage::getModel('shipping/tracking_result'); + foreach ((array) $trackings as $code) { + $this->_getTracking($code); + } + return $this->_result; + } + + /** + * Protected Get Tracking, opens the request to Correios + * + * @param string $code + * + * @return boolean + */ + protected function _getTracking($code) + { + $error = Mage::getModel('shipping/tracking_result_error'); + $error->setTracking($code); + $error->setCarrier($this->_code); + $error->setCarrierTitle($this->getConfigData('title')); + $error->setErrorMessage($this->getConfigData('urlerror')); + + $url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList'; + $url .= '?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $code; + try { + $client = new Zend_Http_Client(); + $client->setUri($url); + $content = $client->request(); + $body = $content->getBody(); + } catch (Exception $e) { + $this->_result->append($error); + return false; + } + + if (!preg_match('#]+)>(.*?)
#is', $body, $matches)) { + $this->_result->append($error); + return false; + } + $table = $matches[2]; + + if (!preg_match_all('/(.*)<\/tr>/i', $table, $columns, PREG_SET_ORDER)) { + $this->_result->append($error); + return false; + } + + $progress = array(); + for ($i = 0; $i < count($columns); $i++) { + $column = $columns[$i][1]; + + $description = ''; + $found = false; + if (preg_match('/(.*)<\/td>(.*)<\/td>(.*)<\/font><\/td>/i', + $column, + $matches + ) + ) { + if (preg_match('/(.*)<\/td>/i', $columns[$i + 1][1], $matchesDescription)) { + $description = str_replace(' ', '', $matchesDescription[1]); + } + + $found = true; + } elseif (preg_match( + '/(.*)<\/td>(.*)<\/td>(.*)<\/font><\/td>/i', + $column, + $matches + ) + ) { + $found = true; + } + + if ($found) { + $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'), + 'deliverytime' => $datetime[1] . ':00', + 'deliverylocation' => htmlentities($matches[2]), + 'status' => htmlentities($matches[3]), + 'activity' => htmlentities($matches[3]) + ); + + if ($description !== '') { + $track['activity'] = $matches[3] . ' - ' . htmlentities($description); + } + + $progress[] = $track; + } + } + + if (!empty($progress)) { + $track = $progress[0]; + $track['progressdetail'] = $progress; + + $tracking = Mage::getModel('shipping/tracking_result_status'); + $tracking->setTracking($code); + $tracking->setCarrier('correios'); + $tracking->setCarrierTitle($this->getConfigData('title')); + $tracking->addData($track); + + $this->_result->append($tracking); + return true; + } else { + $this->_result->append($error); + return false; + } + } + + /** + * Returns the allowed carrier methods + * + * @return array + */ + public function getAllowedMethods() + { + return array($this->_code => $this->getConfigData('title')); + } + + /** + * Define ZIP Code as required + * + * @return boolean + */ + public function isZipCodeRequired() + { + return true; + } +} diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php index bf052f3..9ea4879 100644 --- a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php +++ b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php @@ -1,31 +1,30 @@ - - * @license http://opensource.org/licenses/MIT - */ - -class PedroTeixeira_Correios_Model_Source_PostMethods -{ - - 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 + + * @license http://opensource.org/licenses/MIT + */ + +class PedroTeixeira_Correios_Model_Source_PostMethods +{ + + public function toOptionArray() + { + return array( + array('value' => 40010, 'label' => Mage::helper('adminhtml')->__('Sedex Sem Contrato (40010)')), + array('value' => 40096, 'label' => Mage::helper('adminhtml')->__('Sedex Com Contrato (40096)')), + array('value' => 81019, 'label' => Mage::helper('adminhtml')->__('E-Sedex Com Contrato (81019)')), + array('value' => 41106, 'label' => Mage::helper('adminhtml')->__('PAC Sem Contrato (41106)')), + array('value' => 41068, 'label' => Mage::helper('adminhtml')->__('PAC Com Contrato (41068)')), + array('value' => 40215, 'label' => Mage::helper('adminhtml')->__('Sedex 10 (40215)')), + array('value' => 40290, 'label' => Mage::helper('adminhtml')->__('Sedex HOJE (40290)')), + array('value' => 40045, 'label' => Mage::helper('adminhtml')->__('Sedex a Cobrar (40045)')), + ); + } +} diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/UrlMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/UrlMethods.php deleted file mode 100644 index 3acbe98..0000000 --- a/app/code/community/PedroTeixeira/Correios/Model/Source/UrlMethods.php +++ /dev/null @@ -1,24 +0,0 @@ - - * @license http://opensource.org/licenses/MIT - */ - -class PedroTeixeira_Correios_Model_Source_UrlMethods -{ - - public function toOptionArray() - { - return array( - array('value' => 1, 'label' => Mage::helper('adminhtml')->__('Locaweb')), - array('value' => 0, 'label' => Mage::helper('adminhtml')->__('Correios')), - ); - } -} \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php b/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php index 4e8e751..ccba448 100644 --- a/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php +++ b/app/code/community/PedroTeixeira/Correios/Model/Source/WeightType.php @@ -1,24 +1,24 @@ - - * @license http://opensource.org/licenses/MIT - */ - -class PedroTeixeira_Correios_Model_Source_WeightType -{ - - public function toOptionArray() - { - return array( - array('value' => 'gr', 'label' => Mage::helper('adminhtml')->__('Gramas')), - array('value' => 'kg', 'label' => Mage::helper('adminhtml')->__('Kilos')), - ); - } -} \ No newline at end of file + + * @license http://opensource.org/licenses/MIT + */ + +class PedroTeixeira_Correios_Model_Source_WeightType +{ + + public function toOptionArray() + { + return array( + array('value' => 'gr', 'label' => Mage::helper('adminhtml')->__('Gramas')), + array('value' => 'kg', 'label' => Mage::helper('adminhtml')->__('Kilos')), + ); + } +} diff --git a/app/code/community/PedroTeixeira/Correios/etc/config.xml b/app/code/community/PedroTeixeira/Correios/etc/config.xml index 045ad8d..99db631 100644 --- a/app/code/community/PedroTeixeira/Correios/etc/config.xml +++ b/app/code/community/PedroTeixeira/Correios/etc/config.xml @@ -1,139 +1,147 @@ - - - - - - 4.1.0 - - - - - - - - - - - - - - - - - - - - PedroTeixeira_Correios_Model - - - - - - PedroTeixeira_Correios - - - directory_setup - - - - - - PedroTeixeira_Correios_Helper - - - - - - - PedroTeixeira_Correios_Model_Carrier_CorreiosMethod - - - - - - - - - - - 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 - - - 2 - 16 - 11 - 2 - 16 - 11 - - - 0 - 40010 - kg - 0 - 1 - - - %s - Em média %d dia(s) - 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 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. - - Lojista: Para calcular esse serviço você precisa ter contrato com os Correios. - 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 - - - - - \ No newline at end of file + + + + + + 4.2.0 + + + + + + + + + + + + + + + + + + + + PedroTeixeira_Correios_Model + + + + + + PedroTeixeira_Correios + + + directory_setup + + + + + + PedroTeixeira_Correios_Helper + + + + + + + PedroTeixeira_Correios_Model_Carrier_CorreiosMethod + + + + + + + + + + + 1 + PedroTeixeira_Correios_Model_Carrier_CorreiosMethod + Correios + 40010 + 1,2,3,4,5,33,34,35,36,37,38,888,7,99 + 0 + 1 + 0 + 10000 + 30 + 0 + 20 + + + 0 + 0 + 0 + + + 2 + 16 + 11 + 2 + 16 + 11 + + + + 90 + 2 + 90 + 16 + 90 + 11 + 160 + + + + 40010 + kg + 0 + 1 + + + %s - Em média %d dia(s) + 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 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. + + Lojista: Para calcular esse serviço você precisa ter contrato com os Correios. + Esse método de envio está fora do ar. Por favor entre em contato conosco. + Dimensões dos produtos fora do permitido pelos Correios. + + + Sedex,3 + Sedex,3 + E-Sedex,3 + PAC,3 + PAC,3 + Sedex 10,1 + Sedex HOJE,1 + Sedex a Cobrar,5 + 5 + 6000 + 40045 + 40096,81019,41068 + http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx + + + + diff --git a/app/code/community/PedroTeixeira/Correios/etc/system.xml b/app/code/community/PedroTeixeira/Correios/etc/system.xml index e6479f6..fa03f0d 100644 --- a/app/code/community/PedroTeixeira/Correios/etc/system.xml +++ b/app/code/community/PedroTeixeira/Correios/etc/system.xml @@ -1,336 +1,342 @@ - - - - - - - - - text - 1 - 1 - 1 - 1 - - -
- 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.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".

- 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. -




- - ]]> -
- - - - select - adminhtml/system_config_source_yesno - 10 - 1 - 1 - 1 - - - <label>Nome do Meio de Entrega</label> - <frontend_type>text</frontend_type> - <sort_order>15</sort_order> - <show_in_default>1</show_in_default> - <show_in_website>1</show_in_website> - <show_in_store>1</show_in_store> - - - - multiselect - PedroTeixeira_Correios_Model_Source_PostMethods - 20 - 1 - 1 - 1 - Serviços que estarão disponíveis, lembre-se de usar os serviços correspondentes a - 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 - PedroTeixeira_Correios_Model_Source_UrlMethods - 30 - 1 - 1 - 1 - Ative apenas os serviços relativos a fonte. - - - - select - PedroTeixeira_Correios_Model_Source_WeightType - 30 - 1 - 1 - 1 - Formato do peso dos produtos. - - - - select - adminhtml/system_config_source_yesno - 40 - 1 - 1 - 1 - - - - text - 61 - 1 - 1 - 1 - - - - text - 62 - 1 - 1 - 1 - O padrão de senha são os 8 primeiros dígitos do CNPJ - - - - select - adminhtml/system_config_source_yesno - 63 - 1 - 1 - 1 - - - - select - adminhtml/system_config_source_yesno - 64 - 1 - 1 - 1 - - - - select - adminhtml/system_config_source_yesno - 65 - 1 - 1 - 1 - - - - text - 70 - 1 - 1 - 1 - - Mínimo de 2 cm.]]> - - - - text - 80 - 1 - 1 - 1 - - Mínimo de 16 cm.]]> - - - - text - 90 - 1 - 1 - 1 - - Mínimo de 11 cm.]]> - - - - text - 100 - 1 - 1 - 1 - - - - text - 110 - 1 - 1 - 1 - - - - text - 120 - 1 - 1 - 1 - Utilize o mesmo formato de peso configurado no módulo, kilos ou gramas. - - - - text - 130 - 1 - 1 - 1 - Essa taxa será adicionada ao valor do frete. - - - - text - 131 - 1 - 1 - 1 - Adicionará mais dias aos prazos fornecidos pelos Correios. - - - - text - 135 - 1 - 1 - 1 - - - - text - 140 - 1 - 1 - 1 - - - - select - free-method - PedroTeixeira_Correios_Model_Source_FreeMethods - 150 - 1 - 1 - 1 - Quando usar um cupom oferecendo frete gratuito, qual serviço será gratuito. - Lembre-se de habilitar o serviço. - - - - - textarea - 160 - 1 - 1 - 1 - - - - textarea - 170 - 1 - 1 - 1 - - - - textarea - 180 - 1 - 1 - 1 - - - - textarea - 185 - 1 - 1 - 1 - - - - textarea - 190 - 1 - 1 - 1 - - - - textarea - 191 - 1 - 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 - 230 - 1 - 1 - 1 - - -
-
-
-
-
+ + + + + + + + + text + 1 + 1 + 1 + 1 + + +
+ 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.2.0 o módulo de cálculo de frete foi atualizado para utilizar a nova + lógica de cálculo de peso volumétrico para todos os serviços, teve sua licença + alterada para New BSD, + possibilidade de utilizar limites de dimensões dos Correios, retirada da URL de cálculo da + Locaweb além de outras correções e melhorias.

+ 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".

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

+


+ + ]]> +
+ + + + select + adminhtml/system_config_source_yesno + 10 + 1 + 1 + 1 + + + <label>Nome do Meio de Entrega</label> + <frontend_type>text</frontend_type> + <sort_order>15</sort_order> + <show_in_default>1</show_in_default> + <show_in_website>1</show_in_website> + <show_in_store>1</show_in_store> + + + + select + PedroTeixeira_Correios_Model_Source_WeightType + 20 + 1 + 1 + 1 + Formato do peso dos produtos. + O formato do peso irá implicar na maneira como o mesmo é cadastrado no produto, por + exemplo, 1 Kg no formato "Kilo" será "1.000", já em "Gramas" será "1000.000". + + + + + multiselect + PedroTeixeira_Correios_Model_Source_PostMethods + 25 + 1 + 1 + 1 + Serviços que estarão disponíveis, lembre-se de usar os serviços correspondentes a + fonte configurada. + + + + + select + free-method + PedroTeixeira_Correios_Model_Source_PostMethods + 30 + 1 + 1 + 1 + Quando usar um cupom oferecendo frete gratuito, qual serviço será gratuito. + Lembre-se de habilitar o serviço. + + + + + text + 35 + 1 + 1 + 1 + + + + text + 40 + 1 + 1 + 1 + O padrão de senha são os 8 primeiros dígitos do CNPJ + + + + select + adminhtml/system_config_source_yesno + 45 + 1 + 1 + 1 + + + + text + 50 + 1 + 1 + 1 + "%s" para o nome do serviço, por exemplo "Sedex", "%d" para o número de dias. + + + 1 + + + + + select + adminhtml/system_config_source_yesno + 60 + 1 + 1 + 1 + + + + select + adminhtml/system_config_source_yesno + 70 + 1 + 1 + 1 + + + + select + adminhtml/system_config_source_yesno + 80 + 1 + 1 + 1 + + + + select + adminhtml/system_config_source_yesno + 90 + 1 + 1 + 1 + + A regra pode ser encontrada nesse link.]]> + + + + text + 100 + 1 + 1 + 1 + + Mínimo de 2 cm.]]> + + + + text + 110 + 1 + 1 + 1 + + Mínimo de 16 cm.]]> + + + + text + 120 + 1 + 1 + 1 + + Mínimo de 11 cm.]]> + + + + text + 130 + 1 + 1 + 1 + + + + text + 140 + 1 + 1 + 1 + + + + text + 150 + 1 + 1 + 1 + Utilize o mesmo formato de peso configurado no módulo, kilos ou gramas. + + + + text + 160 + 1 + 1 + 1 + Essa taxa será adicionada ao valor do frete. + + + + text + 170 + 1 + 1 + 1 + Adicionará mais dias aos prazos fornecidos pelos Correios. + + + + text + 180 + 1 + 1 + 1 + + + + textarea + 190 + 1 + 1 + 1 + + + + textarea + 200 + 1 + 1 + 1 + + + + textarea + 210 + 1 + 1 + 1 + + + + textarea + 220 + 1 + 1 + 1 + + + + textarea + 230 + 1 + 1 + 1 + + + + textarea + 240 + 1 + 1 + 1 + + + + textarea + 250 + 1 + 1 + 1 + + + + select + 260 + 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 + 270 + 1 + 1 + 1 + + +
+
+
+
+
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 index 278aa80..0a056bd 100644 --- 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 @@ -6,7 +6,7 @@ * * @category PedroTeixeira * @package PedroTeixeira_Correios - * @copyright Copyright (c) 2010 Pedro Teixeira (http://www.pteixeira.com.br) + * @copyright Copyright (c) 2011 Pedro Teixeira (http://www.pteixeira.com.br) * @author Pedro Teixeira * @license http://opensource.org/licenses/MIT */ @@ -61,4 +61,3 @@ $setup->addAttribute('catalog_product', $codigo, $config); $installer->endSetup(); -?> \ No newline at end of file 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 index d2823b2..8eefa2c 100644 --- 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 @@ -6,7 +6,7 @@ * * @category PedroTeixeira * @package PedroTeixeira_Correios - * @copyright Copyright (c) 2010 Pedro Teixeira (http://www.pteixeira.com.br) + * @copyright Copyright (c) 2011 Pedro Teixeira (http://www.pteixeira.com.br) * @author Pedro Teixeira * @license http://opensource.org/licenses/MIT */ @@ -22,4 +22,3 @@ $installer->deleteConfigData('carriers/pedroteixeira_correios/showmethod'); $installer->endSetup(); -?> \ No newline at end of file diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.1.0-4.2.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.1.0-4.2.0.php new file mode 100644 index 0000000..23a9f5e --- /dev/null +++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/mysql4-upgrade-4.1.0-4.2.0.php @@ -0,0 +1,61 @@ + + * @license http://opensource.org/licenses/MIT + */ + +$installer = $this; +$installer->startSetup(); +$connection = $installer->getConnection(); + +$installer->deleteConfigData('carriers/pedroteixeira_correios/urlmethod'); + +$sql = "select value from " . $installer->getTable( + 'core/config_data' + ) . " where path='carriers/pedroteixeira_correios/postmethods'"; +$methods = explode(',', $connection->fetchOne($sql)); +foreach ($methods as $key => $method) { + if ($method == '41025') { + unset($methods[$key]); + } +} +if (count($methods) <= 0) { + $methods[] = '41106'; +} +$installer->setConfigData('carriers/pedroteixeira_correios/postmethods', implode(',', $methods)); + +$sql = "select value from " . $installer->getTable( + 'core/config_data' + ) . " where path='carriers/pedroteixeira_correios/free_method'"; +if ($connection->fetchOne($sql) == '41025') { + $installer->setConfigData('carriers/pedroteixeira_correios/free_method', '41106'); +} + +$setup = new Mage_Eav_Model_Entity_Setup('core_setup'); +$setup->updateAttribute( + 'catalog_product', + 'volume_comprimento', + 'note', + 'Comprimento da embalagem do produto (Para cálculo dos Correios)' +); +$setup->updateAttribute( + 'catalog_product', + 'volume_altura', + 'note', + 'Altura da embalagem do produto (Para cálculo dos Correios)' +); +$setup->updateAttribute( + 'catalog_product', + 'volume_largura', + 'note', + 'Largura da embalagem do produto (Para cálculo dos Correios)' +); + +$installer->endSetup(); diff --git a/app/etc/modules/PedroTeixeira_Correios.xml b/app/etc/modules/PedroTeixeira_Correios.xml index 76cb436..3a75158 100644 --- a/app/etc/modules/PedroTeixeira_Correios.xml +++ b/app/etc/modules/PedroTeixeira_Correios.xml @@ -1,22 +1,22 @@ - - - - - - true - community - - - + + + + + + true + community + + +