2

我为事件“sales_order_invoice_save_after”做了一个观察者,以在管理员每次向 SQL Server 上的数据库创建发票时导出发票和订单数据。连接成功。但是我尝试什么并不重要,事件总是被触发两次。我在数据库上保存了两次数据。我尝试了一切:

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 DB 以检查发票是否已经注册,如果没有,则继续注册或停止注册,但它不起作用。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...

我在日志中看到的是该过程只运行了一次,实际上我的验证工作但注册表总是被写入两次。这是在数据库上进行插入的方法之一的示例

/*
 * 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 等。

提前感谢您的任何帮助!

4

1 回答 1

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 是否正确。

于 2013-09-18T01:04:17.677 回答