Skip to content

Commit

Permalink
Merge pull request #73 from jarjar123/master
Browse files Browse the repository at this point in the history
Correções Cache, Melhorias PAC GF, Área de Risco
  • Loading branch information
pedro-teixeira committed Jul 13, 2015
2 parents c38f378 + c971ed3 commit 383897f
Show file tree
Hide file tree
Showing 6 changed files with 471 additions and 50 deletions.
50 changes: 33 additions & 17 deletions app/code/community/PedroTeixeira/Correios/Model/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,25 +202,44 @@ public function loadByTags()

/**
* Validate the response data from Correios.
* This method will choose between Request Cache or Save in Cache
*
* Step 1:
* Invalid responses must call the Cache load.
* Cache loading is requested by throwing adapter exception.
*
* Step 2:
* To save valid responses, it must contain no errors.
* Errors are detected by pattern_nocache and returns false.
*
* @param string $data XML Content
*
* @throws Zend_Http_Client_Adapter_Exception
*
* @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;
// Step 1
try {
$response = Zend_Http_Response::fromString($data);
$content = $response->getBody();
} catch (Zend_Http_Exception $e) {
throw new Zend_Http_Client_Adapter_Exception($e->getMessage());
}

if (empty($content)) {
return false;
throw new Zend_Http_Client_Adapter_Exception();
}
libxml_use_internal_errors(true);
$xml = simplexml_load_string($content);
if (!$xml || !isset($xml->cServico)) {
throw new Zend_Http_Client_Adapter_Exception();
}

// Step 2
$pattern = $this->getConfigData('pattern_nocache');
if ($pattern != '' && preg_match($pattern, $content, $matches)) {
return false;
}
return true;
Expand All @@ -231,19 +250,16 @@ protected function _isValidCache($data)
*
* @param string $data XML Content
*
* @throws Exception
*
* @return PedroTeixeira_Correios_Model_Cache
* @return boolean|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}");
if ($this->_isValidCache($data)) {
$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;
}
Expand All @@ -263,4 +279,4 @@ public function getConfigData($field)
$path = 'carriers/' . $this->_code . '/' . $field;
return Mage::getStoreConfig($path);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class PedroTeixeira_Correios_Model_Carrier_CorreiosMethod
protected $_freeMethodWeight = null;
protected $_midSize = null;
protected $_splitUp = 0;
protected $_postingDays = 0;

/**
* Post methods
Expand Down Expand Up @@ -178,6 +179,9 @@ protected function _getQuotes()
}

$this->_appendShippingReturn((string) $servicos->Codigo, $shippingPrice, $shippingDelivery);
if ($this->getConfigFlag('show_soft_errors') && !isset($isWarnAppended)) {
$isWarnAppended = $this->_appendShippingWarning($servicos);
}
$existReturn = true;
}

Expand Down Expand Up @@ -368,15 +372,15 @@ protected function _appendShippingReturn($shippingMethod, $shippingPrice = 0, $c
sprintf(
$this->getConfigData('msgprazo'),
$shippingData[0],
(int) ($correiosDelivery + $this->getConfigData('add_prazo'))
(int) ($correiosDelivery + $this->getConfigData('add_prazo') + $this->_postingDays)
)
);
} else {
$method->setMethodTitle(
sprintf(
$this->getConfigData('msgprazo'),
$shippingData[0],
(int) ($shippingData[1] + $this->getConfigData('add_prazo'))
(int) ($shippingData[1] + $this->getConfigData('add_prazo') + $this->_postingDays)
)
);
}
Expand Down Expand Up @@ -483,6 +487,8 @@ protected function _generateVolumeWeight()
$itemAltura = $this->_getFitHeight($item);
$pesoCubicoTotal += (($itemAltura * $itemLargura * $itemComprimento) *
$item->getQty()) / $this->getConfigData('coeficiente_volume');

$this->_postingDays = max($this->_postingDays, (int) $_product->getData('posting_days'));
}

$this->_volumeWeight = number_format($pesoCubicoTotal, 2, '.', '');
Expand Down Expand Up @@ -712,21 +718,11 @@ protected function _loadMidSize()
*/
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) {
$tmpMethods = $this->_filterMethodByConfigRestriction($tmpMethods);
$isDivisible = (count($tmpMethods) == 0);

if ($isDivisible) {
return $this->_splitPack();
}

Expand Down Expand Up @@ -764,33 +760,35 @@ protected function _removeInvalidServices()
*/
protected function _addPostMethods($cServico)
{
$i = 0;
while (!is_null($this->getConfigData("add_method_{$i}"))) {
$addMethods = $this->getConfigData("add_postmethods");
foreach ($addMethods as $configData) {
$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");
$isValid &= $this->_packageWeight >= $configData['from']['weight'];
$isValid &= $this->_packageWeight <= $configData['to']['weight'];
$isValid &= $this->_midSize >= $configData['from']['size'];
$isValid &= $this->_midSize <= $configData['to']['size'];
$isValid &= $this->_toZip >= $configData['from']['zip'];
$isValid &= $this->_toZip <= $configData['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");
$price = $configData['price'];
$days = $configData['days'];
$method = $configData['code'];
foreach ($cServico as $servico) {
if ($servico->Codigo == $method) {
$servico->Valor = number_format($price, 2, ',', '');
$servico->PrazoEntrega = $days;
if (!empty($price)) {
$servico->Valor = number_format($price, 2, ',', '');
}
if (!empty($days)) {
$servico->PrazoEntrega = $days;
}
$servico->EntregaDomiciliar = 'S';
$servico->EntregaSabado = 'S';
$servico->Erro = '0';
$servico->MsgErro = '<![CDATA[]]>';
}
}
}

$i++;
}

return $cServico;
Expand Down Expand Up @@ -874,7 +872,9 @@ protected function _getFitHeight($item)
*/
protected function _splitPack()
{
if ($this->getConfigFlag('split_pack')) {
$isSplitEnabled = $this->getConfigFlag('split_pack');
$isMethodAvailable = (count($this->_postMethodsExplode) > 0);
if ($isSplitEnabled && $isMethodAvailable) {
$this->_splitUp++;
$this->_volumeWeight /= 2;
$this->_packageWeight /= 2;
Expand All @@ -883,4 +883,74 @@ protected function _splitPack()
}
return false;
}

/**
* Receive a list of methods, and validate one-by-one using the config settings.
* Returns a list of valid methods or empty.
*
* @param array $postmethods Services List
*
* @return array
*/
protected function _filterMethodByConfigRestriction($postmethods)
{
$validMethods = array();
$this->_loadMidSize();
foreach ($postmethods 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"));
$isOverCubic = ($this->_volumeWeight > $this->getConfigData("validate/serv_{$method}/max/volume_weight"));
$isZipAllowed = $this->_validateZipRestriction($method);

if (!$isOverSize && !$isOverWeight && !$isOverCubic && $isZipAllowed) {
$validMethods[] = $method;
}
}
return $validMethods;
}

/**
* Loads the zip range list.
* Returns TRUE only if zip target is included in the range.
*
* @param array $method Current Post Method
*
* @return boolean
*/
protected function _validateZipRestriction($method)
{
$zipConfig = $this->getConfigData("validate/serv_{$method}/zips");
foreach ($zipConfig as $data) {
$zipRange = explode(',', $data);
$isBetweenRange = true;
$isBetweenRange &= ($this->_toZip >= $zipRange[0]);
$isBetweenRange &= ($this->_toZip <= $zipRange[1]);
if ($isBetweenRange) {
return true;
}
}
return false;
}

/**
* Add a warning message at the top of the shipping method list.
*
* @param SimpleXMLElement $servico Post Method
*
* @return boolean
*/
protected function _appendShippingWarning(SimpleXMLElement $servico)
{
$id = (string) $servico->Erro;
$ids = explode(',', $this->getConfigData('soft_errors'));
if (in_array($id, $ids)) {
$error = Mage::getModel('shipping/rate_result_error');
$error->setCarrier($this->_code);
$error->setErrorMessage($servico->MsgErro);
$this->_result->append($error);
return true;
}
return false;
}
}
Loading

0 comments on commit 383897f

Please sign in to comment.