Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correções Cache, Melhorias PAC GF, Área de Risco #73

Merged
merged 24 commits into from
Jul 13, 2015
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
f771220
Merge pull request #9 from pedro-teixeira/master
rafaelpatro Mar 31, 2015
dfcd820
#72 Corrige exceção no caso de falha na comunicação com os Correios
rafaelpatro Mar 31, 2015
5286945
#72 Correção do build
rafaelpatro Mar 31, 2015
161e7a8
Merge remote-tracking branch 'origin/cache_fix' into cache_fix
rafaelpatro Mar 31, 2015
86616ab
Merge pull request #10 from jarjar123/cache_fix
rafaelpatro Mar 31, 2015
3ce0664
#73 Corrigidos e refatorados os métodos de Validação e Escrita em cache
rafaelpatro Apr 1, 2015
fdd09ac
Merge pull request #11 from jarjar123/cache_fix_2
rafaelpatro Apr 1, 2015
63b0644
#74 Correção de Prazo para Mapeamentos Recentes dos Correios
rafaelpatro Apr 1, 2015
e953e7b
Merge pull request #12 from jarjar123/replace_service_feature
rafaelpatro Apr 6, 2015
867dff4
#74 Melhoria na configuração de novos serviços de postagem.
rafaelpatro Apr 6, 2015
635d211
#74 Alteração cosmética
rafaelpatro Apr 6, 2015
91313fe
Merge pull request #13 from jarjar123/improve_add_post_methods
rafaelpatro Apr 6, 2015
e070489
#75 Adicionada opção de exibir aviso de área de risco.
rafaelpatro Apr 9, 2015
3b0e3ad
#75 Correção do build
rafaelpatro Apr 9, 2015
940409b
Merge pull request #14 from jarjar123/warn_soft_errors
rafaelpatro Apr 9, 2015
2c40794
#73 Adicionada validação por faixa de CEP.
rafaelpatro Apr 9, 2015
f4ed1d6
Merge branch 'master' of https://github.com/jarjar123/correios.git in…
rafaelpatro Apr 9, 2015
c43a128
#73 Correção do build
rafaelpatro Apr 9, 2015
aefd898
Merge branch 'improved_pacgf' of https://github.com/jarjar123/correio…
rafaelpatro Apr 9, 2015
bc24265
Merge pull request #15 from jarjar123/improved_pacgf
rafaelpatro Apr 9, 2015
af679d5
#62 Correção do build
rafaelpatro Apr 24, 2015
1445926
Merge pull request #16 from jarjar123/prazo_por_produto
rafaelpatro Apr 24, 2015
60d607d
#73 Atualizado o fork, e alterada a versão para 4.5.0
rafaelpatro Jul 12, 2015
c971ed3
Merge pull request #17 from pedro-teixeira/master
rafaelpatro Jul 12, 2015
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -44,6 +44,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 @@ -153,6 +154,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 @@ -343,15 +347,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 @@ -458,6 +462,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 @@ -687,21 +693,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 @@ -739,33 +735,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 @@ -849,7 +847,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 @@ -858,4 +858,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