Difference between revisions of "Interfaces Dolibarr toward foreign systems"

From Dolibarr ERP CRM Wiki
Jump to navigation Jump to search
Line 5: Line 5:
 
{{ToTranslate}}
 
{{ToTranslate}}
  
Pour permettre de déclencher du code personnalisé en réaction à un évènement Dolibarr (création/modification/suppression d'une société/facture/produit/utilisateur ou autre), Dolibarr propose un mécanisme de triggers métiers. Ce mécanisme vous permet de personnaliser un workflow afin que les évènements de gestion Dolibarr soient répercutés dans une autre application par exemple.
+
To execute personalized code after a Dolibarr event (create/modify/remove a third party/invoice/product or other), Dolibarr offers a mecanism of business triggers. This mecanism allows you to personalize a workflow to have Dolibarr business events being synchronized into another application for example.
Rien n'empêche également de l'utiliser pour modifier le comportement de Dolibarr même: par exemple, pour que la validation d'une facture provoque la création d'un contrat automatiquement.
+
You can also use triggers to modify the behaviour of Dolibarr itself: for example, to create automatically a contract when an invoice is validated.
  
Donc, pour ajouter son propre code qui sera déclenché par trigger, la procédure est la suivante:
+
So, to add your own code that will be triggered by a Dolibarr trigger, this is the way to process:
  
  
1) Copier le fichier '''htdocs/includes/triggers/interface_all_Demo.class.php''' sous le nom:
+
1) Copy file '''htdocs/includes/triggers/interface_all_Demo.class.php''' under the new name:
 
* '''interface_all_''Xxx''.class.php'''
 
* '''interface_all_''Xxx''.class.php'''
ou bien
+
or
* '''interface_mod''MonModule_Xxx''.class.php'''
+
* '''interface_mod''MyModule_Xxx''.class.php'''
''Xxx'' est une chaine de votre choix commençant par une majuscule et ''MonModule'' est le nom du module si votre trigger ne doit être activé que si le module MonModule est actif. Si on désire que le trigger soit toujours actif, on mettra ''all'' à la place de modMonModule.
+
where ''Xxx'' is a string of your choice startint with uppercase character and ''MyModule'' is the name of a module if you want that trigger is activated only if module MyModyle is activated. If you want the trigger to be always active, use ''all'' instead of  modMyModule.
Il faut laisser ce nouveau fichier dans le même répertoire.
+
This new file must be saved inside same directory.
Rem: Les valeurs à utiliser pour modMonModule sont visibles dans le répertoire
+
Note: Value you can use for modMyModule are values found in directory
 
''htdocs/includes/modules''.
 
''htdocs/includes/modules''.
  
Par exemple, on pourra nommer notre nouveau trigger:  
+
For example, you can name your new trigger file:  
''htdocs/includes/triggers/interface_modFacture_Monworkflow.class.php''
+
''htdocs/includes/triggers/interface_modFacture_Myworkflow.class.php''
  
En créant un fichier nommé comme dans cet exemple, notre nouveau trigger sera déclenché à chaque évènement métier Dolibarr et à condition que le module Facture soit actif.
+
By creating such a file with name as in the example, your new trigger file will be executed each time a Dolibarr business event occurs but only if the module Facture is enabled.
  
  
2) Editer ce fichier ''interface_modMonModule_Monworkflow.class.php'' afin de renommer la classe ''InterfaceDemo'' par ''InterfaceMonworkflow''
+
2) Edit the file ''interface_modMyModule_Myworkflow.class.php'' to rename class ''InterfaceDemo'' by ''InterfaceMyworkflow''
  
  
Ensuite, accéder à la page Accueil-> Infos Systèmes -> Dolibarr -> Triggers.
+
Then go on page Home-> System Infos -> Dolibarr -> Triggers.
Votre fichier trigger doit apparaitre dans la liste sans erreur indiquant que les opérations précédentes ont été réalisées avec succès.
+
Your new trigger file must appears in the list without any error message. This means preceding actions have been done successfully.
  
  
3) Revenez maintenant à l'édition du fichier trigger afin d'ajouter votre code dans la fonction ''run_trigger''.
+
3) Return now to edition of file to add your own code inside function  ''run_trigger''.
Cette fonction est appelée à chaque évènement Dolibarr. Placer votre code en fonction du ou des évènements sur lesquels vous voulez réagir, chaque évènement étant identifié par un code (voir chapitres suivant pour la liste des codes), on peut réagir ou non à un évènement donnée par un test sur la variable '''$action''':
+
This function is called at each Dolibarr business event. Put your code according to events on which you want to run. Each event is identified by a code (see following chapter to get full list of codes). So you can react or no after an event by doing just a test on variable '''$action''':
  
 
<source lang="php">
 
<source lang="php">
 
   function run_trigger($action,$object,$user,$lang,$conf)
 
   function run_trigger($action,$object,$user,$lang,$conf)
 
   {
 
   {
         // Mettre ici le code à exécuter en réaction de l'action
+
         // Put here code to execute after an action
         // Le type de l'évènement Dolibarr est stocké dans $action
+
         // The type of Dolibarr business event is stored into $action
         // Les données de l'action sont stockées dans $object
+
         // Data of action are stored into object $object
         // La configuration, utilisateur et langage sont dans $conf,$user et $lang
+
         // Setup, user and language are saved into $conf, $user and $lang
 
         if ($action == 'COMPANY_CREATE')
 
         if ($action == 'COMPANY_CREATE')
 
         {
 
         {
Line 56: Line 56:
 
</source>
 
</source>
  
Vous pouvez faire ce que vous voulez dans cette portion de code du moment que la fonction run_trigger renvoi un code retour sur le principe suivant:
+
You can do what you want into this coding part, if you check that function run_trigger returns a return code according to following rule:
  
<0 si ko, 0 si aucune action faite, >0 si ok
+
<0 if KO, 0 if nothing is done, >0 if OK
  
Vous pouvez de plus dans cette fonction utiliser les objets suivant:
+
You can also use in this function the preinitialized following variables:
* '''$object''' est l'objet sur lequel porte l'action (voir chapitre suivant)
+
* '''$object''' is the object on which action is done (see next chapter)
* '''$user''' est l'objet de l'utilisateur Dolibarr qui réalise l'action
+
* '''$user''' is the object containg all information of Dolibarr user that realizes the business event.
* '''$langs''' est l'objet qui contient la langue de l'utilisateur Dolibarr
+
* '''$langs''' is the object that contains the user language and translations strings
* '''$conf''' est l'objet qui contient toute la configuration de Dolibarr.
+
* '''$conf''' is the object that contains all the Dolibarr configuration.
  
 
4) Une fois le code réalisé, il n'y a plus qu'à tester, en provoquant l'évènement déclencheur dans Dolibarr. Attention, l'appel au '''run_trigger''' et encapsuler dans un transaction. Si votre trigger renvoie un code ko, la fonction appelante peut annuler la transaction (ceci dépend de la fonction appelante).
 
4) Une fois le code réalisé, il n'y a plus qu'à tester, en provoquant l'évènement déclencheur dans Dolibarr. Attention, l'appel au '''run_trigger''' et encapsuler dans un transaction. Si votre trigger renvoie un code ko, la fonction appelante peut annuler la transaction (ceci dépend de la fonction appelante).

Revision as of 18:52, 31 March 2010

Dolibarr provides a simple mecanism to make Dolibarr act into an external system on a Dolibarr event (For more inforation on the other direction and allow an external system to act into Dolibarr system, see page Interfaces from foreign systems toward Dolibarr).

Execute your own code on a Dolibarr event

En verysmall.png Page waiting for translation. To translate, create an account, go back and clic on "Modify".
Fr verysmall.png Page en attente de traduction. Pour traduire, créez un compte, revenez et cliquez sur "Modifier".
Es verysmall.png Página a traducir. Para traducirla, cree una cuenta, vuelva a la página y haga clic en "editar".
It verysmall.png Pagina da tradurre. Per tradurla, crea un utente, torna indietro e clicca su "modifica".
Pt verysmall.png Página a aguardar por tradução. Para traduzir, crie uma conta, volte atrás e clique em "Modificar".
De verysmall.png Seite wartet auf Übersetzung. Um Übersetzung zu erstellen, richte einen Account ein, geh zurück und klicke auf "bearbeiten".
Zh verysmall.png 页面等待翻译。若要翻译本页,先创建一个帐户、登录并返回本页后单击“编辑”。

To execute personalized code after a Dolibarr event (create/modify/remove a third party/invoice/product or other), Dolibarr offers a mecanism of business triggers. This mecanism allows you to personalize a workflow to have Dolibarr business events being synchronized into another application for example. You can also use triggers to modify the behaviour of Dolibarr itself: for example, to create automatically a contract when an invoice is validated.

So, to add your own code that will be triggered by a Dolibarr trigger, this is the way to process:


1) Copy file htdocs/includes/triggers/interface_all_Demo.class.php under the new name:

  • interface_all_Xxx.class.php

or

  • interface_modMyModule_Xxx.class.php

where Xxx is a string of your choice startint with uppercase character and MyModule is the name of a module if you want that trigger is activated only if module MyModyle is activated. If you want the trigger to be always active, use all instead of modMyModule. This new file must be saved inside same directory. Note: Value you can use for modMyModule are values found in directory htdocs/includes/modules.

For example, you can name your new trigger file: htdocs/includes/triggers/interface_modFacture_Myworkflow.class.php

By creating such a file with name as in the example, your new trigger file will be executed each time a Dolibarr business event occurs but only if the module Facture is enabled.


2) Edit the file interface_modMyModule_Myworkflow.class.php to rename class InterfaceDemo by InterfaceMyworkflow


Then go on page Home-> System Infos -> Dolibarr -> Triggers. Your new trigger file must appears in the list without any error message. This means preceding actions have been done successfully.


3) Return now to edition of file to add your own code inside function run_trigger. This function is called at each Dolibarr business event. Put your code according to events on which you want to run. Each event is identified by a code (see following chapter to get full list of codes). So you can react or no after an event by doing just a test on variable $action:

  function run_trigger($action,$object,$user,$lang,$conf)
  {
        // Put here code to execute after an action
        // The type of Dolibarr business event is stored into $action
        // Data of action are stored into object $object
        // Setup, user and language are saved into $conf, $user and $lang
        if ($action == 'COMPANY_CREATE')
        {
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);
        }
        elseif ($action == 'COMPANY_MODIFY')
        {        
            dol_syslog("Trigger for action '$action' launched. id=".$object->id);
        }
        elseif ($action == 'COMPANY_DELETE')
        ...
  }

You can do what you want into this coding part, if you check that function run_trigger returns a return code according to following rule:

<0 if KO, 0 if nothing is done, >0 if OK

You can also use in this function the preinitialized following variables:

  • $object is the object on which action is done (see next chapter)
  • $user is the object containg all information of Dolibarr user that realizes the business event.
  • $langs is the object that contains the user language and translations strings
  • $conf is the object that contains all the Dolibarr configuration.

4) Une fois le code réalisé, il n'y a plus qu'à tester, en provoquant l'évènement déclencheur dans Dolibarr. Attention, l'appel au run_trigger et encapsuler dans un transaction. Si votre trigger renvoie un code ko, la fonction appelante peut annuler la transaction (ceci dépend de la fonction appelante). Ajouter des traces dans un fichier dans la fonction run_trigger afin de vous assurer que le code s'exécute bien. Vous pouvez pour cela si vous le désirer, utiliser la fonction dol_syslog("mon texte de trace", LOG_DEBUG);

List of known events

Dolibarr events that launch triggers are identified by an event code $action. Existing codes are:

  • USER_CREATE
  • USER_MODIFY
  • USER_DISABLE

In such cases, the variable $object contains an object of type user.class.php

  • COMPANY_CREATE
  • COMPANY_MODIFY
  • COMPANY_DELETE

In such cases, the variable $object contains an object of type societe.class.php

  • PRODUCT_CREATE
  • PRODUCT_MODIFY
  • PRODUCT_DELETE

In such cases, the variable $object contains an object of type product.class.php

  • ORDER_CREATE
  • ORDER_VALIDATE
  • ORDER_DELETE

In such cases, the variable $object contains an object of type commande.class.php

  • ORDER_SUPPLIER_CREATE
  • ORDER_SUPPLIER_VALIDATE

In such cases, the variable $object contains an object of type fournisseur.commande.class.php

  • PROPAL_CREATE
  • PROPAL_MODIFY
  • PROPAL_VALIDATE
  • PROPAL_CLOSE_SIGNED
  • PROPAL_CLOSE_REFUSED

In such cases, the variable $object contains an object of type societe.class.php

  • CONTRACT_CREATE
  • CONTRACT_MODIFY
  • CONTRACT_ACTIVATE
  • CONTRACT_CANCEL
  • CONTRACT_CLOSE
  • CONTRACT_DELETE

In such cases, the variable $object contains an object of type contract.class.php

  • BILL_CREATE
  • BILL_MODIFY
  • BILL_VALIDATE
  • BILL_CANCEL
  • BILL_DELETE

In such cases, the variable $object contains an object of type facture.class.php

  • PAYMENT_CUSTOMER_CREATE

In such cases, the variable $object contains an object of type paiement.class.php

  • PAYMENT_SUPPLIER_CREATE

In such cases, the variable $object contains an object of type paiementfourn.class.php

  • FICHEINTER_VALIDATE

In such cases, the variable $object contains an object of type ficheinter.class.php

  • MEMBER_CREATE
  • MEMBER_VALIDATE
  • MEMBER_SUBSCRIPTION
  • MEMBER_MODIFY
  • MEMBER_RESILIATE
  • MEMBER_DELETE

In such cases, the variable $object contains an object of type adherent.class.php

  • CATEGORY_CREATE
  • CATEGORY_MODIFY
  • CATEGORY_DELETE

In such cases, the variable $object contains an object of type category.class.php

Manage new events

Pour gérer d'autre évènements que ceux ci-dessus, il faut modifier le code Dolibarr pour y ajouter la séquence suivante dans les méthodes métiers des classes utilisées pour gérer les évenements:

// Appel des triggers
include_once(DOL_DOCUMENT_ROOT . "/interfaces.class.php");
$interface=new Interfaces($this->db);
$interface->run_triggers('XXXXX_YYYYYY',$this,$user,$lang,$conf);
// Fin appel triggers

Ici, $this doit être l'objet de la classe métier qui contient toutes les informations à passer au trigger. Remplacer, de plus, le 'XXXXX_YYYYYY' par un code évènement non déjà utilisé. Il sera alors possible d'ajouter dans la méthode run_trigger, un if qui permet de gérer ce code. La méthode run_trigger serait alors de la forme :

function run_trigger($action,$object,$user,$lang,$conf)
{
      // Mettre ici le code à exécuter en réaction de l'action
      // Le type de l'évènement Dolibarr est stocké dans $action
      // Les données de l'action sont stockées dans $object
      // La configuration, utilisateur et langage sont dans $conf,$user et $lang
      <b>
      if ($action == 'XXXXX_YYYYY')
      {
          dol_syslog("Trigger for action '$action' launched. id=".$object->id);
      }
      </b>
      elseif ($action == 'COMPANY_CREATE')
      {
          dol_syslog("Trigger for action '$action' launched. id=".$object->id);
      }
      elseif ($action == 'COMPANY_MODIFY')
      {        
          dol_syslog("Trigger for action '$action' launched. id=".$object->id);
      }
      elseif ($action == 'COMPANY_DELETE')
      ...
}

Conclusion

Vous pouvez donc en quelques minutes, ajouter une interface Dolibarr vers exterieur sans risque puisqu'on ne touche pas au code Dolibarr, on s'est contenté de placer un nouveau fichier trigger dans le répertoire des triggers. Si cette interface peut être utile à d'autre, n'hésitez pas à la packager en tgz (voir les wiki sur la diffusion de modules) et de la soumettre dans l'espace des téléchargement-contributions sur le site de Dolibarr.