diff --git a/app/code/community/PedroTeixeira/Correios/Model/Cache.php b/app/code/community/PedroTeixeira/Correios/Model/Cache.php
new file mode 100644
index 0000000..8d4cb95
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/Model/Cache.php
@@ -0,0 +1,266 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
+class PedroTeixeira_Correios_Model_Cache
+ extends Varien_Object
+{
+ /**
+ * Code property
+ *
+ * @var string
+ */
+ protected $_code = 'pedroteixeira_correios';
+
+ /**
+ * Core cache instance
+ *
+ * @var Zend_Cache_Core
+ */
+ private $_cache = null;
+
+ /**
+ * Retrieve cache instance.
+ *
+ * @return Zend_Cache_Core
+ */
+ private function getCache()
+ {
+ if ($this->_cache == null) {
+ $this->_cache = Mage::app()->getCache();
+ }
+ return $this->_cache;
+ }
+
+ /**
+ * Retrieve Zip Tags
+ *
+ * @return array
+ */
+ protected function getZipTags()
+ {
+ $padLength = $this->getConfigData('cache_accuracy/zip');
+ $zipLength = $padLength - 1;
+ $tags = array();
+ $tags[] = "ZIP_".str_pad(substr($this->getData('sCepDestino'), 0, $zipLength--), $padLength, '0');
+ $tags[] = "ZIP_".str_pad(substr($this->getData('sCepDestino'), 0, $zipLength--), $padLength, '0');
+ $tags[] = "ZIP_".str_pad(substr($this->getData('sCepDestino'), 0, $zipLength--), $padLength, '0');
+ $tags[] = "ZIP_".str_pad(substr($this->getData('sCepDestino'), 0, $zipLength--), $padLength, '0');
+ return $tags;
+ }
+
+ /**
+ * Retrieve Weight Tags
+ *
+ * @return array
+ */
+ protected function getWeightTags()
+ {
+ $tags = array();
+ $tags[] = "WEIGHT_".floor($this->getData('nVlPeso'));
+ $tags[] = "WEIGHT_".ceil($this->getData('nVlPeso'));
+ return $tags;
+ }
+
+ /**
+ * Retrieve Size Tags
+ *
+ * @return array
+ */
+ protected function getSizeTags()
+ {
+ $tags = array();
+ $type = ($this->getData('nVlAltura') < 40) ? 'REAL' : 'UNDEFINED';
+ $tags[] = "SIZE_{$type}";
+ return $tags;
+ }
+
+ /**
+ * Retrieve Post Methods Tags
+ *
+ * @return array
+ */
+ protected function getPostMethodsTags()
+ {
+ $tags = explode(',', $this->getData('nCdServico'));
+ return $tags;
+ }
+
+ /**
+ * When
+ * ZIP: 51038245
+ * WEIGHT: 1.3kg
+ * SIZE: 22cm
+ *
+ * Return example:
+ * array(
+ * 41068,
+ * 81019,
+ * ZIP_51038240,
+ * ZIP_51038200,
+ * ZIP_51038000,
+ * WEIGHT_1,
+ * WEIGHT_2,
+ * SIZE_REAL,
+ * PEDROTEIXEIRA_CORREIOS
+ * )
+ *
+ * @return array
+ */
+ protected function getCacheTags()
+ {
+ $tags = array();
+ $tags = array_merge($tags, $this->getPostMethodsTags());
+ $tags = array_merge($tags, $this->getZipTags());
+ $tags = array_merge($tags, $this->getWeightTags());
+ $tags = array_merge($tags, $this->getSizeTags());
+ $tags[] = 'PEDROTEIXEIRA_CORREIOS';
+ return $tags;
+ }
+
+ /**
+ * Return example:
+ * 41068x40096x81019_10_16_51030240
+ *
+ * @return string
+ */
+ protected function _getId()
+ {
+ $weight = round($this->getData('nVlPeso'), $this->getConfigData('cache_accuracy/weight'));
+ $zip = substr($this->getData('sCepDestino'), 0, $this->getConfigData('cache_accuracy/zip'));
+ $size = round($this->getData('nVlAltura'), $this->getConfigData('cache_accuracy/size'));
+ $methods = str_replace(',', 'x', $this->getData('nCdServico'));
+ $cacheId = "{$methods}_{$weight}_{$size}_{$zip}";
+ $cacheId = preg_replace("/[^[:alnum:]^_]/", "", $cacheId);
+ return $cacheId;
+ }
+
+ /**
+ * Retrieve the cache content.
+ *
+ * @return string
+ */
+ public function load()
+ {
+ $data = $this->loadById();
+ if ( !$data ) {
+ $data = $this->loadByTags();
+ }
+ return $data;
+ }
+
+ /**
+ * Retrieve the cache content by key.
+ *
+ * @return string
+ */
+ public function loadById()
+ {
+ $id = $this->_getId();
+ $data = $this->getCache()->load($id);
+ if ( $data ) {
+ Mage::log("{$this->_code} [cache]: mode={$this->getConfigData('cache_mode')} status=hit");
+ }
+ return $data;
+ }
+
+ /**
+ * Iterates over the ZIP codes, and returns the closest match.
+ *
+ * @return string
+ */
+ public function loadByTags()
+ {
+ $data = false;
+ $padLength = $this->getConfigData('cache_accuracy/zip');
+ for ($i=1; $i<5; $i++) {
+ $zipTag = str_pad(substr($this->getData('sCepDestino'), 0, $padLength-$i), $padLength, '0');
+ $tags = array();
+ $tags = array_merge($tags, $this->getPostMethodsTags());
+ $tags = array_merge($tags, $this->getWeightTags());
+ $tags = array_merge($tags, $this->getSizeTags());
+ $tags[] = 'PEDROTEIXEIRA_CORREIOS';
+ $tags[] = "ZIP_{$zipTag}";
+ $keys = $this->getCache()->getIdsMatchingTags($tags);
+ if (count($keys)) {
+ Mage::log("{$this->_code} [cache]: mode={$this->getConfigData('cache_mode')} status=hit tag=zip");
+ $data = $this->getCache()->load($keys[0]);
+ break;
+ }
+ }
+ return $data;
+ }
+
+ /**
+ * Validate the response data from Correios.
+ *
+ * @param string $data XML Content
+ *
+ * @return boolean
+ */
+ protected function _isValidCache($data)
+ {
+ $response = Zend_Http_Response::fromString($data);
+ $content = $response->getBody();
+ $pattern = $this->getConfigData('pattern_nocache');
+ if ($pattern != '' && preg_match($pattern, $content, $matches)) {
+ return false;
+ }
+ if (empty($content)) {
+ return false;
+ }
+ libxml_use_internal_errors(true);
+ $xml = simplexml_load_string($content);
+ if (!$xml || !isset($xml->cServico)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Save Correios content, tags and expiration period.
+ *
+ * @param string $data XML Content
+ *
+ * @throws Exception
+ *
+ * @return PedroTeixeira_Correios_Model_Cache
+ */
+ public function save($data)
+ {
+ if (!$this->_isValidCache($data)) {
+ return false; // Invalid for the Cache only
+ }
+ $id = $this->_getId();
+ $tags = $this->getCacheTags();
+ if ($this->getCache()->save($data, $id, $tags)) {
+ Mage::log("{$this->_code} [cache]: mode={$this->getConfigData('cache_mode')} status=write key={$id}");
+ }
+ return $this;
+ }
+
+ /**
+ * Retrieve information from carrier configuration
+ *
+ * @param string $field Field
+ *
+ * @return mixed
+ */
+ public function getConfigData($field)
+ {
+ if (empty($this->_code)) {
+ return false;
+ }
+ $path = 'carriers/'.$this->_code.'/'.$field;
+ return Mage::getStoreConfig($path);
+ }
+}
\ 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
index 9d4b634..d7aadc4 100644
--- a/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php
+++ b/app/code/community/PedroTeixeira/Correios/Model/Carrier/CorreiosMethod.php
@@ -42,6 +42,8 @@ class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
protected $_packageWeight = null;
protected $_volumeWeight = null;
protected $_freeMethodWeight = null;
+ protected $_midSize = null;
+ protected $_splitUp = 0;
/**
* Post methods
@@ -85,16 +87,8 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
}
// Fix weight
- $weightCompare = $this->getConfigData('maxweight');
if ($this->getConfigData('weight_type') == PedroTeixeira_Correios_Model_Source_WeightType::WEIGHT_GR) {
$this->_packageWeight = number_format($this->_packageWeight / 1000, 2, '.', '');
- $weightCompare = number_format($weightCompare / 1000, 2, '.', '');
- }
-
- // Check weght
- if ($this->_packageWeight > $weightCompare) {
- $this->_throwError('maxweighterror', 'Weight exceeded limit', __LINE__);
- return $this->_result;
}
// Check weight zero
@@ -103,16 +97,17 @@ public function collectRates(Mage_Shipping_Model_Rate_Request $request)
return $this->_result;
}
+ $this->_postMethods = $this->getConfigData('postmethods');
+ $this->_postMethodsFixed = $this->_postMethods;
+ $this->_postMethodsExplode = explode(',', $this->getConfigData('postmethods'));
+
// Generate Volume Weight
- if ($this->_generateVolumeWeight() === false) {
+ if ($this->_generateVolumeWeight() === false || $this->_removeInvalidServices() === false) {
$this->_throwError('dimensionerror', 'Dimension error', __LINE__);
return $this->_result;
}
- $this->_postMethods = $this->getConfigData('postmethods');
- $this->_postMethodsFixed = $this->_postMethods;
- $this->_postMethodsExplode = explode(',', $this->getConfigData('postmethods'));
-
+ $this->_filterMethodByItemRestriction();
if ($this->_getQuotes()->getError()) {
return $this->_result;
}
@@ -135,6 +130,7 @@ protected function _getQuotes()
if ($correiosReturn !== false) {
+ $correiosReturn = $this->_addPostMethods($correiosReturn);
$existReturn = false;
foreach ($correiosReturn as $servicos) {
@@ -149,6 +145,7 @@ protected function _getQuotes()
$stringPrice = str_replace('.', '', $stringPrice);
$stringPrice = str_replace(',', '.', $stringPrice);
$shippingPrice = floatval($stringPrice);
+ $shippingPrice *= pow(2, $this->_splitUp);
$shippingDelivery = (int) $servicos->PrazoEntrega;
if ($shippingPrice <= 0) {
@@ -236,27 +233,20 @@ protected function _getCorreiosReturn()
$client = new Zend_Http_Client($filename);
$client->setConfig(
array(
- 'timeout' => $this->getConfigData('ws_timeout')
+ 'timeout' => $this->getConfigData('ws_timeout'),
+ 'adapter' => Mage::getModel('pedroteixeira_correios/http_client_adapter_socket')
)
);
$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('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'));
+ $client->setParameterGet('nVlComprimento', $this->_midSize);
+ $client->setParameterGet('nVlAltura', $this->_midSize);
+ $client->setParameterGet('nVlLargura', $this->_midSize);
if ($this->getConfigData('mao_propria')) {
$client->setParameterGet('sCdMaoPropria', 'S');
@@ -273,7 +263,7 @@ protected function _getCorreiosReturn()
if ($this->getConfigData('valor_declarado')
|| in_array($this->getConfigData('acobrar_code'), $this->_postMethodsExplode)
) {
- $client->setParameterGet('nVlValorDeclarado', number_format($this->_packageValue, 2, ',', '.'));
+ $client->setParameterGet('nVlValorDeclarado', number_format($this->_packageValue, 2, ',', ''));
} else {
$client->setParameterGet('nVlValorDeclarado', 0);
}
@@ -420,6 +410,10 @@ protected function _generateVolumeWeight()
$items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems();
+ if (count($items) == 0) {
+ $items = Mage::getSingleton('adminhtml/session_quote')->getQuote()->getAllVisibleItems();
+ }
+
foreach ($items as $item) {
$_product = $item->getProduct();
@@ -442,23 +436,26 @@ protected function _generateVolumeWeight()
}
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'
- )
- || ($itemAltura + $itemLargura + $itemComprimento) < $this->getConfigData(
- 'volume_validation/sum_min'
- )
- ) {
+ foreach ($this->_postMethodsExplode as $key => $method) {
+ $sizeMax = max($itemAltura, $itemLargura, $itemComprimento);
+ $sumMax = ($itemAltura + $itemLargura + $itemComprimento);
+ $isValid = ($sizeMax <= $this->getConfigData("validate/serv_{$method}/max/size"));
+ $isValid &= ($sumMax <= $this->getConfigData("validate/serv_{$method}/max/sum"));
+
+ if (!$isValid) {
+ unset($this->_postMethodsExplode[$key]);
+ }
+ }
+
+ if (count($this->_postMethodsExplode) == 0) {
return false;
}
+
+ $this->_postMethods = implode(',', $this->_postMethodsExplode);
+ $this->_postMethodsFixed = $this->_postMethods;
}
+ $itemAltura = $this->_getFitHeight($item);
$pesoCubicoTotal += (($itemAltura * $itemLargura * $itemComprimento) *
$item->getQty()) / $this->getConfigData('coeficiente_volume');
}
@@ -665,4 +662,200 @@ public function isZipCodeRequired($countryId = null)
{
return true;
}
+
+ /**
+ * Retrieve an average size.
+ * For optimization purposes all tree box sizes are converted in one medium dimension.
+ * Result cant exceed the minimum transportation limits.
+ *
+ * @return PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
+ */
+ protected function _loadMidSize()
+ {
+ $volumeFactor = $this->getConfigData('coeficiente_volume');
+ $volumeTotal = $this->_volumeWeight * $volumeFactor;
+ $pow = round(pow((int) $volumeTotal, (1/3)));
+ $min = $this->getConfigData('midsize_min');
+ $this->_midSize = max($pow, $min);
+ return $this;
+ }
+
+ /**
+ * Validate post methods removing invalid services from quotation.
+ *
+ * @return boolean|PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
+ */
+ protected function _removeInvalidServices()
+ {
+ $this->_loadMidSize();
+ $tmpMethods = $this->_postMethodsExplode;
+ foreach ($tmpMethods as $key => $method) {
+ $isOverSize = ($this->_midSize > $this->getConfigData("validate/serv_{$method}/max/size"));
+ $isOverSize |= ($this->_midSize * 3 > $this->getConfigData("validate/serv_{$method}/max/sum"));
+ $isOverWeight = ($this->_packageWeight > $this->getConfigData("validate/serv_{$method}/max/weight"));
+
+ if ($isOverSize || $isOverWeight) {
+ unset($tmpMethods[$key]);
+ }
+ }
+
+ $isDivisible = (count($tmpMethods) == 0);
+ $isLoopBreakable = (count($this->_postMethodsExplode) > 0);
+ if ($isDivisible && $isLoopBreakable) {
+ return $this->_splitPack();
+ }
+
+ $this->_postMethodsExplode = $tmpMethods;
+ $this->_postMethods = implode(',', $this->_postMethodsExplode);
+ $this->_postMethodsFixed = $this->_postMethods;
+ return $this;
+ }
+
+ /**
+ * Include an additional method to quote content before showing.
+ * When requested the new method is added in xml content as specified in config.xml like below:
+ *
+ *
+ * 10065
+ * 2.45
+ * 5
+ *
+ * 00000000
+ * 0.0
+ * 0
+ *
+ *
+ * 99999999
+ * 0.1
+ * 150
+ *
+ *
+ *
+ * @param SimpleXMLElement $cServico XML Node
+ *
+ * @see http://www.correios.com.br/para-voce/consultas-e-solicitacoes/precos-e-prazos/servicos-nacionais_pasta/carta
+ *
+ * @return SimpleXMLElement
+ */
+ protected function _addPostMethods($cServico)
+ {
+ $i = 0;
+ while ( !is_null($this->getConfigData("add_method_{$i}")) ) {
+ $isValid = true;
+ $isValid &= $this->_packageWeight >= $this->getConfigData("add_method_{$i}/from/weight");
+ $isValid &= $this->_packageWeight <= $this->getConfigData("add_method_{$i}/to/weight");
+ $isValid &= $this->_midSize >= $this->getConfigData("add_method_{$i}/from/size");
+ $isValid &= $this->_midSize <= $this->getConfigData("add_method_{$i}/to/size");
+ $isValid &= $this->_toZip >= $this->getConfigData("add_method_{$i}/from/zip");
+ $isValid &= $this->_toZip <= $this->getConfigData("add_method_{$i}/to/zip");
+
+ if ( $isValid ) {
+ $price = $this->getConfigData("add_method_{$i}/price");
+ $days = $this->getConfigData("add_method_{$i}/days");
+ $method = $this->getConfigData("add_method_{$i}/code");
+ foreach ($cServico as $servico) {
+ if ($servico->Codigo == $method) {
+ $servico->Valor = number_format($price, 2, ',', '');
+ $servico->PrazoEntrega = $days;
+ $servico->EntregaDomiciliar = 'S';
+ $servico->EntregaSabado = 'S';
+ $servico->Erro = '0';
+ $servico->MsgErro = '';
+ }
+ }
+ }
+
+ $i++;
+ }
+
+ return $cServico;
+ }
+
+ /**
+ * This keeps only postmethods available for all items in cart.
+ * In other words you can set post methods by products.
+ * Methods not available for all items in cart are removed.
+ * Require attribute creation called postmethods.
+ * Example:
+ * code: postmethods
+ * type: multiselect
+ * label: [free]
+ * value 1: 41068
+ * value 2: 40096
+ * ...
+ * value 99: 81019
+ *
+ * @return PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
+ */
+ protected function _filterMethodByItemRestriction()
+ {
+ if ( $this->getConfigFlag('filter_by_item') ) {
+ $items = Mage::getSingleton('checkout/cart')->getQuote()->getAllVisibleItems();
+
+ if (count($items) == 0) {
+ $items = Mage::getSingleton('adminhtml/session_quote')->getQuote()->getAllVisibleItems();
+ }
+
+ $intersection = $this->_postMethodsExplode;
+ foreach ($items as $item) {
+ $product = Mage::getModel('catalog/product')->load($item->getProductId());
+ $prodPostMethods = explode(',', $product->getData('postmethods'));
+ $intersection = array_intersect($prodPostMethods, $intersection);
+ }
+
+ $this->_postMethodsExplode = $intersection;
+ $this->_postMethods = implode(',', $intersection);
+ $this->_postMethodsFixed = $this->_postMethods;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Added a fit size for items in large quantities.
+ * Means you can join items like two or more glasses, pots and vases.
+ * The calc is applied only for height side.
+ * Required attribute fit_size. Example:
+ *
+ * code: fit_size
+ * type: varchar
+ *
+ * After you can set a fit size for all products and improve your sells
+ *
+ * @param Mage_Eav_Model_Entity_Abstract $item Order Item
+ *
+ * @return number
+ */
+ protected function _getFitHeight($item)
+ {
+ $product = $item->getProduct();
+ $height = $product->getData('volume_altura');
+ $height = ($height > 0) ? $height : (int) $this->getConfigData('altura_padrao');
+ $fitSize = (float) $product->getData('fit_size');
+
+ if ($item->getQty() > 1 && is_numeric($fitSize) && $fitSize > 0) {
+ $totalSize = $height + ($fitSize * ($item->getQty() - 1));
+ $height = $totalSize/$item->getQty();
+ }
+
+ return $height;
+ }
+
+ /**
+ * Splits the package in two parts.
+ * If the package is already splited, each piece will be splited in two equal parts.
+ *
+ * @return boolean|PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
+ */
+ protected function _splitPack()
+ {
+ if ($this->getConfigFlag('split_pack')) {
+ $this->_splitUp++;
+ $this->_volumeWeight /= 2;
+ $this->_packageWeight /= 2;
+ $this->_packageValue /= 2;
+ return $this->_removeInvalidServices();
+ }
+ return false;
+ }
}
diff --git a/app/code/community/PedroTeixeira/Correios/Model/Http/Client/Adapter/Socket.php b/app/code/community/PedroTeixeira/Correios/Model/Http/Client/Adapter/Socket.php
new file mode 100644
index 0000000..5af4048
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/Model/Http/Client/Adapter/Socket.php
@@ -0,0 +1,142 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
+class PedroTeixeira_Correios_Model_Http_Client_Adapter_Socket
+ extends Zend_Http_Client_Adapter_Socket
+{
+ protected $_cache = null;
+ protected $_params = null;
+ protected $_code = 'pedroteixeira_correios';
+ const CACHE_TYPE = 'pedroteixeira_correios';
+
+ /**
+ * Connect to the remote server
+ *
+ * @param string $host Host name
+ * @param int $port Port number
+ * @param bool $secure Secure flag
+ *
+ * @return void
+ */
+ public function connect($host, $port=80, $secure=false)
+ {
+ if (Mage::app()->useCache(self::CACHE_TYPE)) {
+ $mode = $this->getConfigData('cache_mode');
+ if (!($mode == PedroTeixeira_Correios_Model_Source_CacheMode::MODE_CACHE_ONLY)) {
+ try {
+ parent::connect($host, $port, $secure);
+ } catch (Zend_Http_Client_Adapter_Exception $e) {
+ Mage::log("{$this->_code} [socket]: {$e->getMessage()}");
+ }
+ }
+ } else {
+ parent::connect($host, $port, $secure);
+ }
+ }
+
+ /**
+ * Send request to the remote server
+ *
+ * @param string $method Method
+ * @param Zend_Uri_Http $uri Uri
+ * @param string $http_ver HTTP version
+ * @param array $headers Headers
+ * @param string $body Body
+ *
+ * @return string Request as string
+ */
+ public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
+ {
+ $request = false;
+ if (Mage::app()->useCache(self::CACHE_TYPE)) {
+ $this->_params = $uri->getQueryAsArray();
+ try {
+ $request = parent::write($method, $uri, $http_ver, $headers, $body);
+ } catch (Zend_Http_Client_Adapter_Exception $e) {
+ Mage::log("{$this->_code} [socket]: {$e->getMessage()}");
+ }
+ } else {
+ $request = parent::write($method, $uri, $http_ver, $headers, $body);
+ }
+ return $request;
+ }
+
+ /**
+ * Read response from server
+ *
+ * @see Zend_Http_Client_Adapter_Socket::read()
+ *
+ * @return string
+ */
+ public function read()
+ {
+ $response = false;
+ if (Mage::app()->useCache(self::CACHE_TYPE)) {
+ $cache = $this->getCache();
+ $cache->addData($this->_params);
+ $cacheMode = $this->getConfigData('cache_mode');
+ if ($cacheMode == PedroTeixeira_Correios_Model_Source_CacheMode::MODE_HTTP_PRIOR) {
+ try {
+ $response = parent::read();
+ $cache->save($response);
+ } catch (Zend_Http_Client_Adapter_Exception $e) {
+ $response = $cache->load();
+ }
+ } elseif ($cacheMode == PedroTeixeira_Correios_Model_Source_CacheMode::MODE_CACHE_PRIOR) {
+ $response = $cache->loadById();
+ if (!$response) {
+ try {
+ $response = parent::read();
+ $cache->save($response);
+ } catch (Zend_Http_Client_Adapter_Exception $e) {
+ $response = $cache->loadByTags();
+ }
+ }
+ } elseif ($cacheMode == PedroTeixeira_Correios_Model_Source_CacheMode::MODE_CACHE_ONLY) {
+ $response = $cache->load();
+ }
+ } else {
+ $response = parent::read();
+ }
+ return $response;
+ }
+
+ /**
+ * Retrieves the cache instance
+ *
+ * @return PedroTeixeira_Correios_Model_Cache
+ */
+ public function getCache()
+ {
+ if ($this->_cache == null) {
+ $this->_cache = Mage::getModel('pedroteixeira_correios/cache');
+ }
+ return $this->_cache;
+ }
+
+ /**
+ * Retrieve information from carrier configuration
+ *
+ * @param string $field Field
+ *
+ * @return mixed
+ */
+ public function getConfigData($field)
+ {
+ if (empty($this->_code)) {
+ return false;
+ }
+ $path = 'carriers/'.$this->_code.'/'.$field;
+ return Mage::getStoreConfig($path);
+ }
+}
\ No newline at end of file
diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/CacheMode.php b/app/code/community/PedroTeixeira/Correios/Model/Source/CacheMode.php
new file mode 100644
index 0000000..d7d6552
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/Model/Source/CacheMode.php
@@ -0,0 +1,45 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
+class PedroTeixeira_Correios_Model_Source_CacheMode extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
+{
+ const MODE_HTTP_PRIOR = 0;
+ const MODE_CACHE_PRIOR = 1;
+ const MODE_CACHE_ONLY = 2;
+
+ /**
+ * Get options for methods
+ *
+ * @return array
+ */
+ public function toOptionArray()
+ {
+ return array(
+ array('value' => self::MODE_HTTP_PRIOR, 'label' => 'Consultar os Correios; e, se falhar, o Cache'),
+ array('value' => self::MODE_CACHE_PRIOR, 'label' => 'Consultar o Cache; e, se falhar, os Correios'),
+ array('value' => self::MODE_CACHE_ONLY, 'label' => 'Consultar somente o Cache'),
+ );
+ }
+
+ /**
+ * Get options for input fields
+ *
+ * @see Mage_Eav_Model_Entity_Attribute_Source_Interface::getAllOptions()
+ *
+ * @return array
+ */
+ public function getAllOptions()
+ {
+ return self::toOptionArray();
+ }
+}
diff --git a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php
index d7bc0d8..18110f5 100644
--- a/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php
+++ b/app/code/community/PedroTeixeira/Correios/Model/Source/PostMethods.php
@@ -11,7 +11,7 @@
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/pedro-teixeira/correios
*/
-class PedroTeixeira_Correios_Model_Source_PostMethods
+class PedroTeixeira_Correios_Model_Source_PostMethods extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
/**
* Get options for methods
@@ -29,6 +29,21 @@ public function toOptionArray()
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)')),
+ array('value' => 41300, 'label' => Mage::helper('adminhtml')->__('PAC GF (41300)')),
+ array('value' => 10065, 'label' => Mage::helper('adminhtml')->__('Carta Comercial (10065)')),
+ array('value' => 10138, 'label' => Mage::helper('adminhtml')->__('Carta Comercial Registrada (10138)')),
);
}
+
+ /**
+ * Get options for input fields
+ *
+ * @see Mage_Eav_Model_Entity_Attribute_Source_Interface::getAllOptions()
+ *
+ * @return array
+ */
+ public function getAllOptions()
+ {
+ return self::toOptionArray();
+ }
}
diff --git a/app/code/community/PedroTeixeira/Correios/etc/config.xml b/app/code/community/PedroTeixeira/Correios/etc/config.xml
index b82eeff..f3e2c60 100644
--- a/app/code/community/PedroTeixeira/Correios/etc/config.xml
+++ b/app/code/community/PedroTeixeira/Correios/etc/config.xml
@@ -15,7 +15,7 @@
- 4.2.0
+ 4.4.0
@@ -29,6 +29,8 @@
+
+
@@ -62,6 +64,15 @@
+
+
+
+
+ Banco de Cotações dos Correios.
+ PEDROTEIXEIRA_CORREIOS
+
+
+
@@ -77,7 +88,6 @@
1
0
10000
- 30
0
20
@@ -90,27 +100,95 @@
2
16
11
- 2
- 16
- 11
+ 16
-
-
- 105
- 2
- 105
- 16
- 105
- 11
- 200
- 29
-
+
+
+
+ 105
+ 200
+ 30
+
+
+
+
+ 105
+ 200
+ 30
+
+
+
+
+ 105
+ 200
+ 15
+
+
+
+
+ 105
+ 200
+ 30
+
+
+
+
+ 105
+ 200
+ 30
+
+
+
+
+ 105
+ 200
+ 10
+
+
+
+
+ 105
+ 200
+ 10
+
+
+
+
+ 105
+ 200
+ 30
+
+
+
+
+ 150
+ 300
+ 30
+
+
+
+
+ 30
+ 50
+ 0.5
+
+
+
+
+ 30
+ 50
+ 0.5
+
+
+
40010
kg
0
1
+ 0
+ 1
%s - Em média %d dia(s)
@@ -132,11 +210,355 @@
Sedex 10,1
Sedex HOJE,1
Sedex a Cobrar,5
- 5
+ PAC GF,4
+ Carta Comercial,3
+ Carta Comercial Registrada,3
6000
40045
- 40096,81019,41068
+ 40096,81019,41068,41300
http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx
+
+
+ (-2|-3|-5|-6|-7|-8|-9|-10|-11|-12|-13|-14|-15|-16|-17|-18|-20|-22|-23|-24|-25|-26|-27|-28|-29|-30|-31|-32|-33|-34|-35|-36|-37|-38|-39|-40|-41|-42|-43|-44|-45|-888|006|007|009|010|011|7|99)<\/Erro>/]]>
+ 31536000
+
+ 1
+ 8
+ 0
+
+ 0
+
+
+
+ 10065
+ 1.30
+ 5
+
+ 00000000
+ 0
+ 0
+
+
+ 99999999
+ 0.020
+ 30
+
+
+
+ 10065
+ 1.80
+ 5
+
+ 00000000
+ 0.020
+ 0
+
+
+ 99999999
+ 0.050
+ 30
+
+
+
+ 10065
+ 2.45
+ 5
+
+ 00000000
+ 0.050
+ 0
+
+
+ 99999999
+ 0.100
+ 30
+
+
+
+ 10065
+ 3.00
+ 5
+
+ 00000000
+ 0.100
+ 0
+
+
+ 99999999
+ 0.150
+ 30
+
+
+
+ 10065
+ 3.60
+ 5
+
+ 00000000
+ 0.150
+ 0
+
+
+ 99999999
+ 0.200
+ 30
+
+
+
+ 10065
+ 4.15
+ 5
+
+ 00000000
+ 0.200
+ 0
+
+
+ 99999999
+ 0.250
+ 30
+
+
+
+ 10065
+ 4.70
+ 5
+
+ 00000000
+ 0.250
+ 0
+
+
+ 99999999
+ 0.300
+ 30
+
+
+
+ 10065
+ 5.25
+ 5
+
+ 00000000
+ 0.300
+ 0
+
+
+ 99999999
+ 0.350
+ 30
+
+
+
+ 10065
+ 5.80
+ 5
+
+ 00000000
+ 0.350
+ 0
+
+
+ 99999999
+ 0.400
+ 30
+
+
+
+ 10065
+ 6.35
+ 5
+
+ 00000000
+ 0.400
+ 0
+
+
+ 99999999
+ 0.450
+ 30
+
+
+
+ 10065
+ 6.90
+ 5
+
+ 00000000
+ 0.450
+ 0
+
+
+ 99999999
+ 0.500
+ 30
+
+
+
+ 10138
+ 4.50
+ 5
+
+ 00000000
+ 0
+ 0
+
+
+ 99999999
+ 0.020
+ 30
+
+
+
+ 10138
+ 5.00
+ 5
+
+ 00000000
+ 0.020
+ 0
+
+
+ 99999999
+ 0.050
+ 30
+
+
+
+ 10138
+ 5.65
+ 5
+
+ 00000000
+ 0.050
+ 0
+
+
+ 99999999
+ 0.100
+ 30
+
+
+
+ 10138
+ 6.20
+ 5
+
+ 00000000
+ 0.100
+ 0
+
+
+ 99999999
+ 0.150
+ 30
+
+
+
+ 10138
+ 6.80
+ 5
+
+ 00000000
+ 0.150
+ 0
+
+
+ 99999999
+ 0.200
+ 30
+
+
+
+ 10138
+ 7.35
+ 5
+
+ 00000000
+ 0.200
+ 0
+
+
+ 99999999
+ 0.250
+ 30
+
+
+
+ 10138
+ 7.90
+ 5
+
+ 00000000
+ 0.250
+ 0
+
+
+ 99999999
+ 0.300
+ 30
+
+
+
+ 10138
+ 8.45
+ 5
+
+ 00000000
+ 0.300
+ 0
+
+
+ 99999999
+ 0.350
+ 30
+
+
+
+ 10138
+ 9.00
+ 5
+
+ 00000000
+ 0.350
+ 0
+
+
+ 99999999
+ 0.400
+ 30
+
+
+
+ 10138
+ 9.55
+ 5
+
+ 00000000
+ 0.400
+ 0
+
+
+ 99999999
+ 0.450
+ 30
+
+
+
+ 10138
+ 10.10
+ 5
+
+ 00000000
+ 0.450
+ 0
+
+
+ 99999999
+ 0.500
+ 30
+
+
diff --git a/app/code/community/PedroTeixeira/Correios/etc/system.xml b/app/code/community/PedroTeixeira/Correios/etc/system.xml
index 7e4bff8..b6fbc31 100644
--- a/app/code/community/PedroTeixeira/Correios/etc/system.xml
+++ b/app/code/community/PedroTeixeira/Correios/etc/system.xml
@@ -320,6 +320,36 @@
mostrar as mensagens de erro?
+
+
+ select
+ adminhtml/system_config_source_yesno
+ 265
+ 1
+ 1
+ 1
+ A cotação irá exibir somente os serviços de postagem comuns a todos os produtos do carrinho de compras.
+
+
+
+ select
+ PedroTeixeira_Correios_Model_Source_CacheMode
+ 267
+ 1
+ 1
+ 1
+ Esta configuração se aplica somente quando Correios Cache estiver ativo, em Sistema > Gerenciar Cache.
+
+
+
+ select
+ adminhtml/system_config_source_yesno
+ 268
+ 1
+ 1
+ 1
+ O pacote é dividido, caso o carrinho exceda os limites de peso e tamanho, para todos os serviços. A divisão se repete até que os limites sejam válidos, para um ou mais serviços.
+
text
diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/install-4.4.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/install-4.4.0.php
new file mode 100644
index 0000000..3edb7ed
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/install-4.4.0.php
@@ -0,0 +1,92 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
+
+/** @var $installer Mage_Core_Model_Resource_Setup */
+$installer = $this;
+$installer->startSetup();
+
+/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */
+$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
+
+// Add volume to prduct attribute set
+$codigo = 'volume_comprimento';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Comprimento (cm)',
+ 'type' => 'int',
+ 'input' => 'text',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Comprimento da embalagem do produto (Para cálculo de PAC, mínimo de 16)'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+// Add volume to prduct attribute set
+$codigo = 'volume_altura';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Altura (cm)',
+ 'type' => 'int',
+ 'input' => 'text',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Altura da embalagem do produto (Para cálculo de PAC, mínimo de 2)'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+// Add volume to prduct attribute set
+$codigo = 'volume_largura';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Largura (cm)',
+ 'type' => 'int',
+ 'input' => 'text',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Largura da embalagem do produto (Para cálculo de PAC, mínimo de 11)'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+$codigo = 'postmethods';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Serviços de Entrega',
+ 'type' => 'text',
+ 'input' => 'multiselect',
+ 'source' => 'pedroteixeira_correios/source_postMethods',
+ 'backend' => 'eav/entity_attribute_backend_array',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Selecione os serviços apropriados para o produto.'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+$codigo = 'fit_size';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Diferença do Encaixe (cm)',
+ 'type' => 'varchar',
+ 'input' => 'text',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Exemplo: Se 1 item mede 10cm de altura, e 2 itens encaixados medem 11cm. A diferença é de 1cm.'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+$installer->endSetup();
diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.2.0-4.3.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.2.0-4.3.0.php
new file mode 100644
index 0000000..5024f71
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.2.0-4.3.0.php
@@ -0,0 +1,13 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
diff --git a/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.3.0-4.4.0.php b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.3.0-4.4.0.php
new file mode 100644
index 0000000..24b4103
--- /dev/null
+++ b/app/code/community/PedroTeixeira/Correios/sql/pedroteixeira_correios_setup/upgrade-4.3.0-4.4.0.php
@@ -0,0 +1,50 @@
+
+ * @copyright 2014 Pedro Teixeira (http://pedroteixeira.io)
+ * @license http://opensource.org/licenses/MIT MIT
+ * @link https://github.com/pedro-teixeira/correios
+ */
+
+/** @var $installer Mage_Core_Model_Resource_Setup */
+$installer = $this;
+$installer->startSetup();
+
+/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */
+$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
+
+$codigo = 'postmethods';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Serviços de Entrega',
+ 'type' => 'text',
+ 'input' => 'multiselect',
+ 'source' => 'pedroteixeira_correios/source_postMethods',
+ 'backend' => 'eav/entity_attribute_backend_array',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Selecione os serviços apropriados para o produto.'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+$codigo = 'fit_size';
+$config = array(
+ 'position' => 1,
+ 'required' => 0,
+ 'label' => 'Diferença do Encaixe (cm)',
+ 'type' => 'varchar',
+ 'input' => 'text',
+ 'apply_to' => 'simple,bundle,grouped,configurable',
+ 'note' => 'Exemplo: Se 1 item mede 10cm de altura, e 2 itens encaixados medem 11cm. A diferença é de 1cm.'
+);
+
+$setup->addAttribute('catalog_product', $codigo, $config);
+
+$installer->endSetup();