我为事件“sales_order_invoice_save_after”做了一个观察员,每次管理员为SQL Server上的数据库创建发票时,都会导出发票和订单数据。连接成功。但是我尝试的事情并不重要,总是被解雇两次。我在DB上保存了两次数据。我尝试了一切:
1.-我使用注册表在观察者中创建了一个标志,但它不起作用。
public function exportInvoice(Varien_Event_Observer $observer){
try{
if(Mage::registry('sql_salvado')){
return $this;
}
//My code
Mage::register('sql_salvado',true,true);
}catch(Mage_Core_Exception $e){
Mage::log("No fue posible exportar pedidos a SQL Server " . $e->getMessage());
}
return $this;
2.-我还在类中创建了一个方法,用于验证SQL Server数据库以检查Invoice是否已经注册,如果没有继续注册或停止注册,但它不起作用。 Magento只是两次发射事件。
if($this->_verifyInsertion($order['invoice']) == true){
Mage::log('Invoice ya existe no se va a repetir', null, 'escritura_sql.log');
return $this;
}else{
这是该方法的示例:
protected function _verifyInsertion($invoice){
$_servidor = $this->_mssqlhost.':'.$this->_mssqlpuerto.$this->_mssqlinstancia;
$link = mssql_connect( $_servidor,$this->_mssqlusr,$this->_mssqlpsswd );
if (!$link || !mssql_select_db($this->_mssqlbd, $link)) {
die('No me pude conectar o seleccionar la BD!');
}
$query = mssql_query("SELECT id_order, invoice FROM [order] WHERE invoice LIKE '$invoice'");
$fila = mssql_fetch_object($query);
if($fila->invoice == $invoice){
Mage::log("$invoice ya existe no debes repetirte", null, 'escritura_sql.log');
return true;
}else{
Mage::log("$invoice no existe, escribelo...", null, 'escritura_sql.log');
return false;
}
3.-我也尝试使用“sales_order_invoice_save_before”和“sales_order_invoice_register”但没有成功。没有什么工作,Magento仍然两次开火。
我想知道是否有办法知道事件是否已被触发,然后第二次停止。有人能指出我正确的方向吗?。
克里斯托弗,首先感谢你的帮助。
这是config.xml
<?xml version="1.0"?>
<config>
<modules>
<Cmm_Qad>
<version>0.1.0</version>
</Cmm_Qad>
</modules>
<global>
<models>
<qad>
<class>Cmm_Qad_Model</class>
<resourceModel>qad_mysql4</resourceModel>
</qad>
<qad_mysql4>
<class>Cmm_Qad_Model_Mysql4</class>
</qad_mysql4>
</models>
<events>
<sales_order_invoice_save_after>
<observers>
<cmm_qad_pedidos_exporta>
<type>singleton</type>
<class>Cmm_Qad_Model_Pedidos_Exporta</class>
<method>exportInvoice</method>
</cmm_qad_pedidos_exporta>
</observers>
</sales_order_invoice_save_after>
</events>
<blocks>
<qad>
<class>Cmm_Qad_Block</class>
</qad>
</blocks>
<helpers>
<qad>
<class>Cmm_Qad_Helper</class>
</qad>
</helpers>
</global>
<crontab>
<jobs>
<cmm_qad_stock>
<run>
<schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
<model>cmm/qad::sincronizaInventario</model>
</run>
</cmm_qad_stock>
<cmm_qad_precios>
<run>
<schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
<model>cmm/qad::sincronizaPrecios</model>
</run>
</cmm_qad_precios>
</jobs>
</crontab>
<admin>
<routers>
<qad>
<use>admin</use>
<args>
<module>Cmm_Qad</module>
<frontName>qad</frontName>
</args>
</qad>
</routers>
</admin>
<adminhtml>
<translate>
<modules>
<mage_adminhtml>
<files>
<qad>Cmm_Qad.csv</qad>
</files>
</mage_adminhtml>
</modules>
</translate>
<menu>
<catalog>
<children>
<qad_adminform translate="title" module="qad">
<title>Sincronizar con QAD</title>
<action>qad/adminhtml_qad</action>
</qad_adminform>
</children>
</catalog>
</menu>
<acl>
<resources>
<admin>
<children>
<catalog>
<children>
<qad_adminform>
<title>QAD ERP</title>
</qad_adminform>
</children>
</catalog>
</children>
</admin>
</resources>
</acl>
<!-- Segunda inserción por configuracion-->
<acl>
<resources>
<all>
<title>Allow Everything</title>
</all>
<admin>
<children>
<system>
<children>
<config>
<children>
<qad>
<title>QAD - All</title>
</qad>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
<!-- /Segunda inserción por configuración -->
<layout>
<updates>
<qad>
<file>qad.xml</file>
</qad>
</updates>
</layout>
</adminhtml>
以下是插入上方的代码:
require_once(Mage::getBaseDir('lib'). '/cmm/mssql.php');
/**
* Clase de escritura de Datos a SQL Server para CMM
*/
class Cmm_Qad_Model_Pedidos_Exporta{
private static $_conexion;
private static $_dateCreated;
private static $_dateUpdated;
private static $_mssqlhost;
private static $_mssqlpuerto;
private static $_mssqlinstancia;
private static $_mssqlusr;
private static $_mssqlpsswd;
private static $_mssqlbd;
//Variables para valores identitys
private static $_id_client;
private static $_id_address;
private static $_id_order;
private static $_id_detail;
/*
* We open the connection to SQL Server in the constructor
*
*/
public function __construct(){
ini_set("display_errors",1);
$this->_mssqlhost = Mage::getStoreConfig('qad/qad_group/mssql_host', Mage::app()->getStore());
$this->_mssqlpuerto = Mage::getStoreConfig('qad/qad_group/mssql_puerto', Mage::app()->getStore());
$this->_mssqlinstancia = Mage::getStoreConfig('qad/qad_group/mssql_instancia', Mage::app()->getStore());
$this->_mssqlusr = Mage::getStoreConfig('qad/qad_group/mssql_usr', Mage::app()->getStore());
$this->_mssqlpsswd = Mage::getStoreConfig('qad/qad_group/mssql_pass', Mage::app()->getStore());
$this->_mssqlbd = Mage::getStoreConfig('qad/qad_group/mssql_bd', Mage::app()->getStore());
$this->_dateCreated = Varien_Date::now();
$this->_dateUpdated = Varien_Date::now();
/*
* Open the connection with SQL Server
* */
$_servidor = $this->_mssqlhost.':'.$this->_mssqlpuerto.$this->_mssqlinstancia;
$this->_conexion = new mssqlClass();
$this->_conexion->connect($_servidor,$this->_mssqlusr,$this->_mssqlpsswd);
$this->_conexion->select($this->_mssqlbd);
}
/**
* Mage::dispatchEvent($this->_eventPrefix.'_save_after', $this->_getEventData());
* protected $_eventPrefix = 'sales_order';
* protected $_eventObject = 'order';
* event: sales_order_save_after
*/
public function exportInvoice(Varien_Event_Observer $observer){
if(Mage::registry('sql_salvado') == 1){
Mage::unregister('sql_salvado');
return NULL;
}
$invoice = $observer->getInvoice();
$pedido = $invoice->getOrder();
$client = array();
$client_del_address = array();
$order = array();
$order_detail = array();
/*
* Recopilamos los datos
*/
//Client
$client['name'] = $pedido->getCustomerFirstname()." ".$pedido->getCustomerLastname();
$client['type'] = 1;
$client['rfc'] = "UWXU8609121O6";
$client['curp'] = "CMM";
$client['email'] = $pedido->getCustomerEmail();
$client['phone'] = $pedido->getCustomerTelephone();
$client['phone2'] = $pedido->getCustomerTelephone();
$client['clave_qad'] = "CLAVEQ";
$client['address'] = $pedido->getBillingAddress()->getStreet(); //Es otro array
$client['zipcode'] = $pedido->getBillingAddress()->getPostcode();
$client['colony'] = "Colonia";
$client['country'] = $pedido->getBillingAddress()->getCountry();
$client['id_state'] = 1;
$client['id_country'] = 2;
//Client_del_address
$client_del_address['address'] = $pedido->getShippingAddress()->getStreet(); //Es un array()
$client_del_address['zipcode'] = $pedido->getShippingAddress()->getPostcode();
$client_del_address['colony'] = "Colonia";
$client_del_address['country'] = $pedido->getShippingAddress()->getCountry();
$client_del_address['is_state'] = 1;
$client_del_address['id_country'] = 2;
//Order
$order['invoice'] = (int) $invoice->getIncrementId();
$order['status'] = 1;
$order['subtotal_notax'] = $invoice->getSubtotal();
$order['subtotal_tax'] = $invoice->getSubtotal() + $invoice->getTaxAmount();
$order['total_tax'] = $invoice->getTaxAmount();
$order['total'] = $invoice->getGrandTotal();
//Se abre la validación del semáforo
if($this->_verifyInsertion($order['invoice']) == true){
Mage::log('Invoice ya existe no se va a repetir', null, 'escritura_sql.log');
return NULL;
}else{
Mage::log('Invoice es nuevo', null, 'escritura_sql.log');
//Validamos que el cliente exista o no exista.
if($this->_existeCliente($client['email']) == true){
Mage::log('El cliente existe', null, 'escritura_sql.log');
if($this->_insertaDirEnvio($client_del_address, $client) == true){
//The rest of the code...
我在日志中看到的是该进程只运行一次,实际上我的验证工作但注册表总是写两次。以下是在DB上插入的方法之一的示例
/*
* Inserta clientes
*/
protected function _insertaCliente(array $client){
$sql_client="INSERT INTO [client] (name, type, rfc, curp, email, phone1, phone2, clave_qad, address, zipcode, colony, county, id_state, id_country, date_created, date_updated) VALUES ('".$client['name']."', '".$client['type']."', '".$client['rfc']."', '".$client['curp']."', '".$client['email']."', '".$client['phone1']."', '".$client['phone2']."', '".$client['clave_qad']."', '".$client['address'][0]."', '".$client['zipcode']."', '".$client['colony']."', '".$client['country']."', '".$client['id_state']."', '".$client['id_country']."', '".$this->_dateCreated."', '".$this->_dateUpdated."') SELECT LAST_INSERT_ID=@@IDENTITY";
if($this->_conexion->query($sql_client)){
$_identity = mssql_fetch_assoc($this->_conexion->query($sql_client));
$this->_id_client = $_identity['LAST_INSERT_ID'];
return true;
}else{
echo $this->_conexion->getLastErrorMessage()." Inserta Cliente";
return false;
}
}
在我的所有插入中,我正在进行另一个选择“SELECT LAST_INSERT_ID = @@ IDENTITY”,因为SQL服务器具有自动增加其id的标识字段。然后我将这些身份保存在其他变量中(我在构造函数中创建)并将其重用于以后的插入,例如发票或order_details等。
感谢提前获得任何帮助!!
答案 0 :(得分:0)
我检查了Mage :: register的签名(因为我不知道第三个参数):
public static function register($key, $value, $graceful = false)
当$ graceful设置为true时,该方法根本不会抛出任何异常。
所以试试这个(未经测试):
public function exportInvoice(Varien_Event_Observer $observer){
if(Mage::registry('sql_salvado')){
return $this;
}
// your code here
try{
Mage::register('sql_salvado',true);
} catch(Mage_Core_Exception $e){
Mage::log("No fue posible exportar pedidos a SQL Server " . $e->getMessage());
}
return $this;
}
然后验证这段代码是否被执行,即模块的config.xml是否正确。