Skip to content

Commit

Permalink
Merge pull request #266 from rafaelpatro/tracking_improvement
Browse files Browse the repository at this point in the history
Melhoria no Monitoramento Automático
  • Loading branch information
pedro-teixeira committed May 29, 2017
2 parents f13c92d + 26257f0 commit 4baccbe
Show file tree
Hide file tree
Showing 12 changed files with 972 additions and 72 deletions.
79 changes: 57 additions & 22 deletions app/code/community/PedroTeixeira/Correios/Model/Observer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,67 @@ class PedroTeixeira_Correios_Model_Observer
*/
public function sroTrackingJob()
{
$count = 0;
/* @var $sro PedroTeixeira_Correios_Model_Sro */
$sro = Mage::getModel('pedroteixeira_correios/sro');
if ($sro->getConfigData('sro_tracking_job') == 0) {
return "SRO Tracking Job disabled.";
$message = "SRO Tracking Job disabled.";
if (Mage::helper('pedroteixeira_correios')->getConfigData('sro_tracking_job') == 0) {
return $message;
}

$collection = $sro->getShippedTracks();
foreach ($collection as $track) {
/* @var $track Mage_Sales_Model_Order_Shipment_Track */
if ($sro->request($track->getNumber())) {
$savedId = $track->getDescription();
$eventId = $sro->getEventId();
if ($eventId != $savedId) {
$track->setDescription($eventId)->save();
$track->getShipment()->getOrder()
->setStatus($sro->getStatus())
->save();
$track->getShipment()
->addComment($sro->getComment(), $sro->isNotify(), true)
->sendUpdateEmail($sro->isNotify(), $sro->getEmailComment())
->save();
$count++;
$message = "No tracking updates";
$count = 0;
$countTrack = 0;
$trackList = array();
$sro = Mage::getModel('pedroteixeira_correios/sro')->init();
$response = $sro->request();

if ($response && $response->return->qtd > 0) {
$tracksTxn = Mage::getModel('core/resource_transaction');
$ordersTxn = Mage::getModel('core/resource_transaction');
$shipmentsTxn = Mage::getModel('core/resource_transaction');
foreach ($response->return->objeto as $obj) {
if (isset($obj->erro)) {
Mage::log("{$obj->numero}: {$obj->erro}");
continue;
}

if ($track = $sro->getTrack($obj)) {
$savedId = $track->getDescription();
$eventId = $sro->getEventId($obj);
if ($eventId != $savedId) {
$status = $sro->getStatus($obj);
$notify = $sro->isNotify($obj);
$comment = $sro->getComment($obj);
$mailComment = $sro->getEmailComment($obj, $track);
$tracksTxn->addObject(
$track->setDescription($eventId)
);
$ordersTxn->addObject(
$track->getShipment()->getOrder()->setStatus($status)
);
$shipmentsTxn->addObject(
$track->getShipment()
->addComment($comment, $notify, true)
->sendUpdateEmail($notify, $mailComment)
);
Mage::log("{$obj->numero}: saving scheduled");
$count++;
}
}
$countTrack++;
}

if ($count) {
try {
$tracksTxn->save();
$ordersTxn->save();
$shipmentsTxn->save();
$message = "Updated {$count} objects of {$countTrack} tracked.";
} catch (Exception $e) {
$message = $e->getMessage();
}
}
}
return "Tracked {$count} objects of {$collection->getSize()}.";

Mage::log($message);
return $message;
}
}
167 changes: 117 additions & 50 deletions app/code/community/PedroTeixeira/Correios/Model/Sro.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,27 @@ class PedroTeixeira_Correios_Model_Sro extends Varien_Object
const CARRIER_CODE = 'pedroteixeira_correios';
const ORDER_SHIPPED_STATUS = 'complete_shipped';
const ORDER_WARNED_STATUS = 'complete_warned';


protected $_trackList = array();

/**
* Request response
* Retrieves all valid tracking codes
*
* @var SimpleXMLElement
* @return PedroTeixeira_Correios_Model_Sro
*/
protected $_xml = null;

public function init()
{
$collection = $this->getShippedTracks();
foreach ($collection as $track) {
if ($this->validateTrackNumber($track->getNumber())) {
$this->_trackList[$track->getNumber()] = $track;
continue;
}
Mage::log("{$track->getNumber()}: invalid tracking code");
}
return $this;
}

/**
* Load all opened tracks from database.
* Filter tracks only with complete order state, and shipped status.
Expand All @@ -48,40 +61,44 @@ public function getShippedTracks()
/**
* Load XML response from Correios
*
* @param string $trackingCode Tracking Code
*
* @throws Exception
*
* @link http://www.correios.com.br/para-voce/correios-de-a-a-z/pdf/rastreamento-de-objetos/
* Manual_SROXML_28fev14.pdf
* @link http://www.corporativo.correios.com.br/encomendas/sigepweb/doc/
* Manual_de_Implementacao_do_Web_Service_SIGEPWEB_Logistica_Reversa.pdf
*
* @return boolean|PedroTeixeira_Correios_Model_Sro
* @return boolean|Correios_Rastro_BuscaEventosResponse
*/
public function request($trackingCode)
public function request()
{
$params = array(
'usuario' => $this->getConfigData('sro_username'),
'senha' => $this->getConfigData('sro_password'),
'tipo' => $this->getConfigData('sro_type'),
'resultado' => $this->getConfigData('sro_result'),
'lingua' => $this->getConfigData('sro_language'),
'objetos' => $trackingCode,
);

try {
$client = new SoapClient($this->getConfigData('url_sro_correios'));
$response = $client->buscaEventos($params);
if (empty($response)) {
throw new Exception("Empty response");
$response = false;
if (count($this->_trackList)) {
$trackingCodes = implode('', array_keys($this->_trackList));
$params = new Correios_Rastro_BuscaEventos(
$this->getConfigData('sro_username'),
$this->getConfigData('sro_password'),
$this->getConfigData('sro_type'),
$this->getConfigData('sro_result'),
$this->getConfigData('sro_language'),
$trackingCodes
);
Mage::log(print_r($params, true));

try {
$client = new Correios_Rastro(
Mage::helper('pedroteixeira_correios')->getStreamContext(),
$this->getConfigData('url_sro_correios')
);
$response = $client->buscaEventos($params);
if (empty($response)) {
throw new Exception("Empty response");
}
} catch (Exception $e) {
Mage::log("Soap Error: {$e->getMessage()}");
}
$this->_xml = $response->return;
} catch (Exception $e) {
Mage::log("Soap Error: {$e->getMessage()}");
return false;
}
return $this;
return $response;
}

/**
Expand All @@ -99,12 +116,14 @@ public function getConfigData($path)
/**
* Returns a Shipping comment message
*
* @param Correios_Rastro_Objeto $obj Response Object
*
* @return string
*/
public function getComment()
public function getComment($obj)
{
$code = $this->_xml->objeto->numero;
$evento = $this->_xml->objeto->evento;
$code = $obj->numero;
$evento = $obj->evento;
$msg = array();
$msg[] = $code;
$msg[] = "{$evento->cidade}/{$evento->uf}";
Expand All @@ -126,14 +145,17 @@ public function getComment()
/**
* Returns an Update Shipping e-mail comment
*
* @param Correios_Rastro_Objeto $obj Response Object
* @param Mage_Sales_Model_Order_Shipment_Track $track Tracking instance
*
* @return string
*/
public function getEmailComment()
public function getEmailComment($obj, $track)
{
$trackUrl = $this->getConfigData('url_tracking');
$code = $this->_xml->objeto->numero;
$evento = $this->_xml->objeto->evento;
$htmlAnchor = "<a href=\"{$trackUrl}?P_LINGUA=001&P_TIPO=001&P_COD_UNI={$code}\">{$code}</a>";
$trackUrl = Mage::helper('shipping')->getTrackingPopupUrlBySalesModel($track);
$code = $obj->numero;
$evento = $obj->evento;
$htmlAnchor = "<a href=\"{$trackUrl}\">{$code}</a>";
$msg = array();
$msg[] = Mage::helper('pedroteixeira_correios')->__('Rastreador: %s', $htmlAnchor);
$msg[] = Mage::helper('pedroteixeira_correios')->__('Local: %s', "{$evento->cidade}/{$evento->uf}");
Expand All @@ -154,14 +176,15 @@ public function getEmailComment()
/**
* Check the event type
*
* @param string $mode Event Type Mode
* @param Correios_Rastro_Objeto $obj Response Object
* @param string $mode Event Type Mode
*
* @return boolean
*/
public function validate($mode)
public function validate($obj, $mode)
{
$isValid = false;
$evento = $this->_xml->objeto->evento;
$evento = $obj->evento;
$hashTypes = explode(',', $this->getConfigData("sro_event_type_{$mode}"));
if (in_array($evento->tipo, $hashTypes)) {
$type = strtolower($evento->tipo);
Expand All @@ -175,41 +198,85 @@ public function validate($mode)
* Track Description field are now being used to save the event id.
* Event Id is a simple key to identify the last carrier event.
*
* @param Correios_Rastro_Objeto $obj Response Object
*
* @return string
*/
public function getEventId()
public function getEventId($obj)
{
$code = $this->_xml->objeto->numero;
$date = $this->_xml->objeto->evento->data;
$hour = $this->_xml->objeto->evento->hora;
$type = $this->_xml->objeto->evento->tipo;
return "{$code}::{$date}{$hour}::{$type}";
if ($obj->numero && $obj->evento) {
$code = $obj->numero;
$date = $obj->evento->data;
$hour = $obj->evento->hora;
$type = $obj->evento->tipo;
return "{$code}::{$date}{$hour}::{$type}";
}
return false;
}

/**
* Check whether event notify is enabled or not
*
* @param Correios_Rastro_Objeto $obj Response Object
*
* @return boolean
*/
public function isNotify()
public function isNotify($obj)
{
return $this->validate('notify');
return $this->validate($obj, 'notify');
}

/**
* Load order status based on event checking
*
* @param Correios_Rastro_Objeto $obj Response Object
*
* @return string
*/
public function getStatus()
public function getStatus($obj)
{
$status = self::ORDER_SHIPPED_STATUS;
if ($this->validate('warn')) {
if ($this->validate($obj, 'warn')) {
$status = self::ORDER_WARNED_STATUS;
}
if ($this->validate('last')) {
if ($this->validate($obj, 'last')) {
$status = Mage_Sales_Model_Order::STATE_COMPLETE;
}
return $status;
}

/**
* Validates the tracking code
*
* @param string $trackNumber Tracking Code
*
* @return boolean
*/
public function validateTrackNumber($trackNumber)
{
return preg_match('/^[a-zA-Z]{2}[0-9]{9}[a-zA-Z]{2}$/', $trackNumber);
}

/**
* Retrieves the tracking instance
*
* @param Correios_Rastro_Objeto $obj Return Object
*
* @throws Exception
*
* @return Mage_Sales_Model_Order_Shipment_Track
*/
public function getTrack($obj)
{
$track = $this->_trackList[$obj->numero];
if (!($desc = $track->getDescription())) {
Mage::log("{$obj->numero}: tracking instance missed. Trying to reload");
try {
$track = Mage::getModel('sales/order_shipment_track')->load($obj->numero, 'track_number');
} catch (Exception $e) {
Mage::log("{$obj->numero}: {$e->getMessage()}");
}
}
return $track;
}
}
Loading

0 comments on commit 4baccbe

Please sign in to comment.