Logic hook on Emails module

Hi everyone,

I'm developing a logic hook on Emails module to create a new Account with the info that I receive in this email and relate this account with the email, my issue is when I install the logic hook the functionality to create a new Case for the email doesn't work and my logic hook either, so I want to know, how can I deploy my logic hook working at the same time with the sugar process to create cases to the email?

Best Regards

  • Can you share the logic hook? It is hard to know why this is happening otherwise.

  • Yes, sure, this is my last version, I tried to put it on the Cases' module with an after relationship add, to find the relationship with the Emails' module.

    class catch_email_class
        {

            public function catch_email_method($bean, $event, $arguments)
            {
                if ($arguments['related_module'] != 'Emails') {
                    return;
                }

                // Capturo el correo electronico
                $beanEmails = BeanFactory::retrieveBean('Emails'$arguments['related_id']);
                $from = $beanEmails->from_addr;
                $to = $beanEmails->to_addrs;
                $subject = $beanEmails->name;
                $body = $bean->description;

                $value = '] PETICIONES, QUEJAS Y RECLAMOS';
                $reclamo = stripos($subject$value);
                if ($reclamo === false) {
                    return;
                }

                //Capturar datos del cuerpo del correo
                $email = catch_email_class::getEmail($body);
                $GLOBALS['log']->fatal('email: ' . $email);

                $tlf = catch_email_class::getDatos($body'Telefono:');
                $identificacion = catch_email_class::getDatos($body'identidad:');
                $solicitud = catch_email_class::getDatos($body'Solicitud:');
                $tienda = catch_email_class::getDatos($body'Center:');
                $cliente = catch_email_class::getDatos($body'Cliente,');
                $factura = catch_email_class::getDatos($body'factura:');

                // Verificar si existe un cliente un email al extraido del cuerpo del correo
                $beanCE0 = BeanFactory::newBean('Accounts');

                require_once 'include/SugarQuery/SugarQuery.php';
                $sugarQuery0 = new SugarQuery();
                $sugarQuery0->select(['id']);
                $sugarQuery0->from($beanCE0);
                $sugarQuery0->where()
                ->equals('email1'$email);
                $result0 = $sugarQuery0->getOne();

                if ($result0) {
                    //Vincular el correo  al cliente
                    //Crea una relación entre cliente y correo
                    $beanAccount = BeanFactory::retrieveBean('Accounts'$result0);
                    $beanAccount->load_relationship('archived_emails');
                    $beanAccount->archived_emails->add($beanEmails->id);
                    $beanAccount->save();
                    $GLOBALS['log']->fatal(print_r($result0true));
                    $GLOBALS['log']->fatal('Cuenta');
                    $GLOBALS['log']->fatal(print_r($beanAccounttrue));
                } else {
                    $newAccountID = catch_email_class::create_account($email$tlf$identificacion$subject);
                    $beanAccount = BeanFactory::retrieveBean('Accounts'$newAccountID);
                    $beanAccount->load_relationship('archived_emails');
                    $beanAccount->archived_emails->add($beanEmails->id);
                    $beanAccount->save();
                    $GLOBALS['log']->fatal('create_account');
                }

                $bean->tienda_c = $tienda;
                $bean->documentoidentidad_c = $identificacion;
                $bean->nombrecompleto_c = $cliente;
                $bean->telefonomovil_c = $tlf;
                $bean->account_id = $beanAccount->id;
                $bean->email_c = $email;
                $bean->numerofactura_c = $factura;

                if ($solicitud == 'Peticiones') {
                    $bean->type = 'Peticiones';
                } elseif ($solicitud == 'Quejas') {
                    $bean->type = 'Quejas';
                } elseif ($solicitud == 'Reclamo') {
                    $bean->type = 'Reclamo';
                } elseif ($solicitud == 'Sugerencia') {
                    $bean->type = 'Sugerencia';
                } elseif ($solicitud == 'Felicitaciones') {
                    $bean->type = 'Felicitaciones';
                }
            }
            
            public function getEmail($excerpt)
            {
                preg_match('/[A-Za-z0-9._%+-]+@[a-z0-9._%+-]+\.[a-z]+/'$excerpt$m);
                return $m[0];
            }

            public function getDatos($desciption_html, $texto)
            {
                $patron = "/[\n\s,]+/";
                $array = preg_split($patron$desciption);
                for ($i = 0;$i < sizeof($array);$i++) {
                    if ($array[$i] == $texto && $texto == 'Center:') {
                        $dato = trim($array[$i + 1. ' - ' . $array[$i + 3]);
                    } elseif ($array[$i] == $texto) {
                        $dato = trim($array[$i + 1]);
                    }
                }
                return $dato;
            }

            public function create_account($email, $tlf, $identificacion, $subject)
            {
                //Agrega un nuevo account con los datos del correo recibido y el name
                $beanAccountNew = BeanFactory::newBean('Accounts');
                $name = explode(':'$subject);
                $nameN = count($name) - 1;
                $beanAccountNew->name = $name[$nameN];
                $beanAccountNew->numerodeidentificacion_c = $identificacion;
                $beanAccountNew->movil_c = $tlf;
                $beanAccountNew->email1 = $email;
                $beanAccountNew->save();

                //Recupera el id insertado
                $accountID = $beanAccountNew->id;
                return $accountID;
            }
        }
  • If I am reading your code correctly, you have a form that generates an email which you then parse to figure out the parameters and create an Account if needed.

    Why not use an API instead? It will keep you from having to parse the email to get the values you need.

    You can create a custom API that would create the Account, if needed, and then the Case and relate the Account to the Case. Doing it that way would keep all your form fields neatly separated and you would not have to parse the body of the email for your data.

    As for your logic hook: 

    When an email comes in, the Email record is created (the email bean is saved populating the emails, emails_text, email_addresses if needed, and emails_email_addr_rel tables), then the Case record is created (the case bean is saved in the cases, cases_cstm if applicable, tables), then the Email is related to the Case and thus the Email bean is saved again (populating the emails_beans table).

    As you can see, the Case and the Email records should both be created before the email is related to the Case (Of course this is assuming the email address that the email goes to is an Inbound Email that has the "Create Case From Email" checked.) So if you are not even getting a Case I would take a step back and see if your Inbound Email is set up properly. Check your PHP log and your Sugar log to see if there are any clues as to why it's not creating the Case.

    Once you are sure that a Case and an Email are created and the logic hook fires check a few things:

    Note that you are parsing all incoming and outgoing emails related to Cases. That's a lot of processing

    I would add a check to see if the email is inbound, else skip the hook.

    email1 is a deprecated field, so try not to use it, see:

    Using e-mail fields correctly in Sugar 

    When searching for the Account, you can use the built in functionality instead of querying for email1.

    email1 is not a database field, it is a construct on the bean for the primary address, so I think your sugarQuery would fail because it would use a non-existant field. Also if you are looking at email1 only you will miss out on any addresses that might be on the Account that are not marked as primary.

    $sea = new SugarEmailAddress();
    $results = $sea->getBeansByEmailAddress($email_address );
    foreach ($results as $aBean) {
       <...check if $aBean is an Account and do what you need to do...>
    }

    (see: https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.0/Architecture/Email_Addresses/#Fetch… ) 

    I don't think you need to explicitly relate the email to the Account. 

    When an inbound email is received the InboundEmail.php creates entries in the 

    emails, emails_text, email_addresses (if the address doesn't already exist), and emails_email_addr_rel tables

    When you create the Account and relate it to an existing email address you create entries in the email_addr_bean_rel which relates the email address bean to the account bean. The email address was already in the email_addresses table because the case put it there. The system now sees the email related to the emails_email_addr_rel related to the email_address which is now related to the Account via the email_addr_bean_rel table and therefore the email should show in the Emails subpanel on the Account.

    Hope this helps you get a bit further with your hook.

    Best of luck,

    FrancescaS