> For the complete documentation index, see [llms.txt](https://edissyum.gitbook.io/open-capture/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://edissyum.gitbook.io/open-capture/parametrages/reglages-verifier/workflows/exemples-de-scriptings.md).

# Exemples de scriptings

## Détection FacturX

Vérification si le document est de type FacturX, afin de l'envoyer vers le workflow spécifique à FacturX.

```python
# La fonction `main` sera appelé avant le traitement d'un document, ne changez pas le nom de cette fonction
# Ce script sera effectué avant la partie `traitement`, si cette dernière est activée

# Depuis l'étape `entrée` vous avez accès aux variables suivantes :
#   - ip --> (string) Adresse IP de l'utilisateur
#   - user_info --> (string) Informations sur l'utilisateur courant
#   - custom_id --> (string) Identifiant du custom
#   - file --> (string) Chemin complet du fichier à traiter
#   - opencapture_path --> (string) Racine du dossier d'installation Open-Capture
#   - log --> (classe Log) Instance de la classe Log permettant de logger (info ou error) différentes données
#   - input_path --> (string) Chemin de capture des documents
#   - customer_id --> (integer) Identifiant du compte client
#   - ia_model_id --> (integer) Identifiant du modèle d'intelligence artificielle

# Depuis l'étape `entrée` vous avez accès aux fonctions suivantes :
#   - send_to_workflow() --> Envoi du document vers un autre workflow
#		- arguments : ip, log, file, user_info, workflow_id, custom_id

# La liste des librairies Python disponible sont visibles ici :
# https://github.com/edissyum/opencapture/blob/master/bin/install/pip-requirements.txt

# Ce script est un exemple permettant de lire les code QR dans le document en cours de traitement
# Si le contenu du QR Code dispose du mot clé facture, le workflow continue
# Sinon, le workflow s'arrête et un autre est automatiquement lancé

import os
import facturx
from src.backend.scripting_functions import send_to_workflow

def main(args):
    args['log'].info(f"[INPUT_SCRIPT] Vérification si le document {os.path.basename(args['file'])} est de type FacturX")
    with open(args['file'], 'rb') as pdf_file:
        _, xml_content = facturx.get_facturx_xml_from_pdf(pdf_file.read())
        if _ is not None:
            args['log'].info(f"[INPUT_SCRIPT] Le document est detecté comme FacturX, changement de workflow...")
            res = send_to_workflow({
                'ip': args['ip'],
                'log': args['log'],
                'file': args['file'],
                'user_info': args['user_info'],
                'workflow_id': 'facturx',
                'custom_id': args['custom_id'],
            })
            return res
        else:
            args['log'].info(f"[INPUT_SCRIPT] Le document n'est pas detecté comme FacturX, poursuite du workflow classique...")
    return 'continue_workflow'
```

## Détection de QR Code

Vérification de la présence d'un QR code contenant le mot clé facture. S'il n'est pas présent, renvoi du document vers le workflow d'océrisation uniquement.

```python
# La fonction `main` sera appelé avant le traitement d'un document, ne changez pas le nom de cette fonction
# Ce script sera effectué avant la partie `traitement`, si cette dernière est activée

# Depuis l'étape `entrée` vous avez accès aux variables suivantes :
#   - ip --> (string) Adresse IP de l'utilisateur
#   - user_info --> (string) Informations sur l'utilisateur courant
#   - custom_id --> (string) Identifiant du custom
#   - file --> (string) Chemin complet du fichier à traiter
#   - opencapture_path --> (string) Racine du dossier d'installation Open-Capture
#   - log --> (classe Log) Instance de la classe Log permettant de logger (info ou error) différentes données
#   - input_path --> (string) Chemin de capture des documents
#   - customer_id --> (integer) Identifiant du compte client
#   - ia_model_id --> (integer) Identifiant du modèle d'intelligence artificielle

# Depuis l'étape `entrée` vous avez accès aux fonctions suivantes :
#   - send_to_workflow() --> Envoi du document vers un autre workflow
#		- arguments : ip, log, file, user_info, workflow_id, custom_id
# Si vous utilisez la fonction send_to_workflow(), il faut la combiner avec un return
# Si la fonction send_to_workflow() est utilisée uniquement dans un cas, et pas dans un autre, finir la fonction par "return 'continue_workflow'"

# La liste des librairies Python disponible sont visibles ici :
# https://github.com/edissyum/opencapture/blob/master/install/pip-requirements.txt

# Ce script est un exemple permettant de lire les code QR dans le document en cours de traitement
# Si le contenu du QR Code dispose du mot clé facture, le workflow continue
# Sinon, le workflow s'arrête et un autre est automatiquement lancé

import pdf2image
from pyzbar.pyzbar import decode
from src.backend.scripting_functions import send_to_workflow

def read_qrcode(args):
    args['log'].info('[INPUT_SCRIPT] Recherche de code QR dans le document')
    pages = pdf2image.convert_from_path(args['file'])
    barcodes = []
    cpt = 0
    for page in pages:
        detected_barcode = decode(page)
        if detected_barcode:
            for barcode in detected_barcode:
                if barcode.type == 'QRCODE':
                    barcodes.append({'text': barcode.data.decode('utf-8')})
        cpt += 1
    return barcodes


def main(args):
    args['log'].info(f"[INPUT_SCRIPT] Traitement du fichier {args['file']}")
    barcodes = read_qrcode(args)
    is_invoice = False

    for barcode in barcodes:
        if 'facture' in barcode['text'].lower():
            is_invoice = True

    if is_invoice:
        args['log'].info('[INPUT_SCRIPT] Le document est bien une facture, le traitement continue...')
        return 'continue_workflow'
    else:
        args['log'].info('[INPUT_SCRIPT] Le document n\'est pas une facture, lancement du workflow&nbsp;ocr_only')
        return send_to_workflow({
            'ip': args['ip'],
            'log': args['log'],
            'file': args['file'],
            'user_info': args['user_info'],
            'workflow_id': 'ocr_only',
            'custom_id': args['custom_id'],
        })
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://edissyum.gitbook.io/open-capture/parametrages/reglages-verifier/workflows/exemples-de-scriptings.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
