# Facturation

Les outils de facturation permettent de gérer l'ensemble du cycle de vie des documents : factures, devis, bons de commande, acomptes et avoirs.

{% hint style="warning" %}
Tous les montants sont exprimés en **centimes** (100€ = 10000). Consultez les [conventions](/mcp/conventions.md) pour plus de détails.
{% endhint %}

## Consultation

### `get-billings`

Récupère les documents de facturation avec pagination et filtres avancés.

**Paramètres**

| Paramètre    | Type      | Requis | Description                                                                          |
| ------------ | --------- | ------ | ------------------------------------------------------------------------------------ |
| `page`       | number    | Non    | Numéro de page (défaut : 1)                                                          |
| `limit`      | number    | Non    | Résultats par page, max 100 (défaut : 10)                                            |
| `type`       | string\[] | Non    | Types : `invoice`, `estimate`, `advance`, `asset`, `purchase_order`                  |
| `state`      | string\[] | Non    | États : `draft`, `finalized`, `signed`, `refused`, `paid`                            |
| `search`     | string    | Non    | Recherche par numéro, titre ou nom client                                            |
| `customerId` | string    | Non    | Filtrer par identifiant client                                                       |
| `archived`   | boolean   | Non    | Filtrer par statut d'archivage                                                       |
| `late`       | boolean   | Non    | Uniquement les documents en retard                                                   |
| `rangeFrom`  | string    | Non    | Début de la plage de dates (ISO 8601)                                                |
| `rangeTo`    | string    | Non    | Fin de la plage de dates (ISO 8601)                                                  |
| `rangeType`  | string    | Non    | Champ de date : `emittedAt`, `dueAt`, `paidAt`, `signedAt`, `expiredAt`, `refusedAt` |

**Réponse**

```json
{
  "success": true,
  "total": 42,
  "page": 1,
  "limit": 10,
  "totalPages": 5,
  "hasNextPage": true,
  "hasPrevPage": false,
  "billings": [
    {
      "id": "string",
      "type": "invoice",
      "number": "FA-2025-001",
      "title": "string",
      "state": "finalized",
      "emittedAt": "2025-01-15T00:00:00.000Z",
      "customer": {
        "id": "string",
        "name": "Dupont SARL",
        "email": "contact@dupont.fr"
      },
      "totalAmountWithTax": 12000,
      "totalAmountWithoutTax": 10000,
      "currencyCode": "EUR",
      "archived": false,
      "dueAt": "2025-02-15T00:00:00.000Z",
      "paidAt": null,
      "remainingAmountWithTax": 12000,
      "remainingAmountWithoutTax": 10000
    }
  ]
}
```

***

### `get-billing-by-id`

Récupère le détail complet d'un document par son identifiant. Inclut les lignes, totaux, informations client, mentions légales, ventilation TVA, informations de paiement et pièces jointes.

**Paramètres**

| Paramètre   | Type   | Requis | Description             |
| ----------- | ------ | ------ | ----------------------- |
| `billingId` | string | Oui    | Identifiant du document |

***

### `get-billing-statistics`

Récupère les statistiques de facturation : compteurs et montants par état (brouillon, en retard, en attente, payé, finalisé, signé, refusé).

**Paramètres**

| Paramètre | Type      | Requis | Description                                                                       |
| --------- | --------- | ------ | --------------------------------------------------------------------------------- |
| `type`    | string\[] | Non    | Filtrer par type(s) : `invoice`, `estimate`, `advance`, `asset`, `purchase_order` |

***

### `get-customers`

Récupère les clients facturables (contacts et organisations) avec pagination et recherche. Retourne l'identifiant client nécessaire pour `create-invoice`.

**Paramètres**

| Paramètre | Type   | Requis | Description                               |
| --------- | ------ | ------ | ----------------------------------------- |
| `page`    | number | Non    | Numéro de page (défaut : 1)               |
| `limit`   | number | Non    | Résultats par page, max 100 (défaut : 50) |
| `search`  | string | Non    | Recherche par nom ou email                |

**Réponse**

```json
{
  "success": true,
  "total": 15,
  "customers": [
    {
      "id": "string",
      "displayName": "Dupont SARL",
      "firstname": null,
      "lastname": null,
      "name": "Dupont SARL",
      "commercialName": "Dupont & Fils",
      "emails": ["contact@dupont.fr"],
      "siret": "12345678901234",
      "vatNumber": "FR12345678901",
      "billingAddress": { ... },
      "isContact": false,
      "isOrganization": true,
      "contactId": null,
      "organizationId": "string"
    }
  ]
}
```

***

### `download-billing-document`

Télécharge un document au format PDF. Retourne une URL de téléchargement temporaire valide 7 jours.

**Paramètres**

| Paramètre         | Type    | Requis | Description                                              |
| ----------------- | ------- | ------ | -------------------------------------------------------- |
| `billingId`       | string  | Oui    | Identifiant du document                                  |
| `withAttachments` | boolean | Non    | Inclure les pièces jointes dans le PDF (défaut : `true`) |

**Réponse**

```json
{
  "success": true,
  "downloadUrl": "https://...",
  "filename": "FA-2025-042.pdf",
  "expiresIn": "7 days",
  "billingId": "string"
}
```

***

## Création

### `create-invoice`

Crée une facture en brouillon avec des lignes de facturation.

**Paramètres**

| Paramètre    | Type   | Requis | Description                                                          |
| ------------ | ------ | ------ | -------------------------------------------------------------------- |
| `customerId` | string | Oui    | Identifiant client (depuis `get-customers`)                          |
| `lines`      | array  | Oui    | Lignes de facturation (voir [schéma des lignes](#schema-des-lignes)) |
| `discount`   | object | Non    | Remise globale (`mode`: `PERCENTAGE` ou `AMOUNT`, `amount`: valeur)  |

***

### `create-estimate`

Crée un devis ou bon de commande en brouillon.

**Paramètres**

| Paramètre      | Type   | Requis | Description                                                                   |
| -------------- | ------ | ------ | ----------------------------------------------------------------------------- |
| `customerId`   | string | Oui    | Identifiant client                                                            |
| `lines`        | array  | Oui    | Lignes du devis (voir [schéma des lignes](#schema-des-lignes))                |
| `estimateType` | string | Non    | `estimate` (devis) ou `purchase_order` (bon de commande). Défaut : `estimate` |
| `discount`     | object | Non    | Remise globale                                                                |

***

### `create-advance`

Crée un acompte à partir d'un devis finalisé ou signé.

**Paramètres**

| Paramètre    | Type   | Requis | Description                                                     |
| ------------ | ------ | ------ | --------------------------------------------------------------- |
| `estimateId` | string | Oui    | Identifiant du devis finalisé                                   |
| `mode`       | string | Non    | `percentage` ou `amount` (défaut : `percentage`)                |
| `value`      | number | Non    | Pourcentage (30 = 30%) ou montant en **centimes** selon le mode |

{% hint style="info" %}
L'acompte hérite automatiquement du client et des informations du devis parent. Le devis doit être dans l'état `finalized` ou `signed`.
{% endhint %}

***

### `create-asset`

Crée un avoir (note de crédit) en brouillon.

**Paramètres**

| Paramètre           | Type   | Requis | Description                                 |
| ------------------- | ------ | ------ | ------------------------------------------- |
| `billingCustomerId` | string | Non    | Identifiant client (depuis `get-customers`) |
| `opportunityId`     | string | Non    | Identifiant de l'opportunité                |

{% hint style="info" %}
Au moins un des deux paramètres (`billingCustomerId` ou `opportunityId`) doit être fourni.
{% endhint %}

***

## Actions

### `finalize-billing`

Finalise un document en brouillon (facture, devis, acompte, bon de commande). Attribue un numéro définitif. **Le document ne peut plus être modifié après finalisation.**

Fonctionne en deux étapes :

1. **Aperçu** (`confirm` absent ou `false`) — retourne un résumé du document avant finalisation
2. **Confirmation** (`confirm: true`) — finalise définitivement le document

**Paramètres**

| Paramètre   | Type    | Requis | Description                                                  |
| ----------- | ------- | ------ | ------------------------------------------------------------ |
| `billingId` | string  | Oui    | Identifiant du document brouillon                            |
| `confirm`   | boolean | Non    | `true` pour finaliser. Sans confirmation, retourne un aperçu |

***

### `update-billing-lines`

Met à jour les lignes d'un document en brouillon. **Remplace toutes les lignes existantes.**

**Paramètres**

| Paramètre   | Type   | Requis | Description                                                     |
| ----------- | ------ | ------ | --------------------------------------------------------------- |
| `billingId` | string | Oui    | Identifiant du document brouillon                               |
| `lines`     | array  | Oui    | Nouvelles lignes (voir [schéma des lignes](#schema-des-lignes)) |
| `discount`  | object | Non    | Remise globale                                                  |

***

### `send-invoice-by-email`

Envoie un document par email avec le PDF en pièce jointe.

**Paramètres**

| Paramètre   | Type      | Requis | Description                                         |
| ----------- | --------- | ------ | --------------------------------------------------- |
| `billingId` | string    | Oui    | Identifiant du document                             |
| `emails`    | string\[] | Oui    | Adresses email (1 à 10 destinataires)               |
| `subject`   | string    | Oui    | Objet de l'email                                    |
| `content`   | string    | Oui    | Corps de l'email (HTML supporté)                    |
| `inCopy`    | boolean   | Non    | Envoyer une copie à l'expéditeur (défaut : `false`) |

***

### `duplicate-billing`

Duplique un document existant en nouveau brouillon. Peut optionnellement convertir vers un autre type.

**Paramètres**

| Paramètre    | Type   | Requis | Description                                                                                 |
| ------------ | ------ | ------ | ------------------------------------------------------------------------------------------- |
| `documentId` | string | Oui    | Identifiant du document à dupliquer                                                         |
| `targetType` | string | Non    | Type cible : `invoice`, `estimate`, `purchase_order`. Si absent, duplique dans le même type |

***

### `cancel-invoice`

Annule une facture finalisée et **crée automatiquement un avoir**. Action irréversible.

**Paramètres**

| Paramètre   | Type   | Requis | Description                         |
| ----------- | ------ | ------ | ----------------------------------- |
| `invoiceId` | string | Oui    | Identifiant de la facture finalisée |

**Réponse**

```json
{
  "success": true,
  "message": "Invoice cancelled successfully. A credit note (avoir) has been created.",
  "cancelledInvoice": {
    "id": "string",
    "number": "FA-2025-042",
    "state": "cancelled",
    "canceledAt": "2025-03-15T00:00:00.000Z"
  },
  "asset": {
    "id": "string",
    "number": "AV-2025-003",
    "state": "finalized",
    "total": { ... }
  }
}
```

***

### `sign-estimate`

Marque un devis finalisé comme signé/accepté par le client.

**Paramètres**

| Paramètre    | Type   | Requis | Description                   |
| ------------ | ------ | ------ | ----------------------------- |
| `estimateId` | string | Oui    | Identifiant du devis finalisé |

***

### `refuse-estimate`

Marque un devis finalisé comme refusé par le client.

**Paramètres**

| Paramètre    | Type   | Requis | Description                   |
| ------------ | ------ | ------ | ----------------------------- |
| `estimateId` | string | Oui    | Identifiant du devis finalisé |

***

### `archive-billing`

Archive un document. Les documents archivés sont masqués des listes actives mais conservés.

**Paramètres**

| Paramètre    | Type   | Requis | Description             |
| ------------ | ------ | ------ | ----------------------- |
| `documentId` | string | Oui    | Identifiant du document |

***

### `unarchive-billing`

Restaure un document archivé dans les listes actives.

**Paramètres**

| Paramètre    | Type   | Requis | Description                     |
| ------------ | ------ | ------ | ------------------------------- |
| `documentId` | string | Oui    | Identifiant du document archivé |

***

## Schéma des lignes <a href="#schema-des-lignes" id="schema-des-lignes"></a>

Les outils `create-invoice`, `create-estimate` et `update-billing-lines` partagent le même schéma de lignes :

| Paramètre      | Type   | Requis | Description                                                                                               |
| -------------- | ------ | ------ | --------------------------------------------------------------------------------------------------------- |
| `designation`  | string | Oui    | Nom du produit ou service                                                                                 |
| `unitPrice`    | number | Oui    | Prix unitaire en **centimes**                                                                             |
| `quantity`     | number | Non    | Quantité (défaut : 1)                                                                                     |
| `quantityUnit` | string | Non    | Unité : `UNIT`, `HOUR`, `DAY`, `MONTH`, etc. (défaut : `UNIT`)                                            |
| `type`         | string | Non    | Type : `SERVICE_DELIVERY`, `GOODS_SALE`, etc. (défaut : `SERVICE_DELIVERY`)                               |
| `vatCode`      | string | Non    | Code TVA : `fr_20`, `fr_10`, `fr_5_5`, `fr_2_1`, `fr_0`, `fr_8_5`, `fr_not_applicable` (défaut : `fr_20`) |
| `description`  | string | Non    | Description détaillée                                                                                     |
| `reference`    | string | Non    | Référence produit                                                                                         |
| `productId`    | string | Non    | Identifiant produit du catalogue                                                                          |

***

## Scopes requis

| Outil                                                                                                                                                                                                                                                         | Scope           |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
| `get-billings`, `get-billing-by-id`, `get-billing-statistics`, `get-customers`, `download-billing-document`                                                                                                                                                   | `billing:read`  |
| `create-invoice`, `create-estimate`, `create-advance`, `create-asset`, `finalize-billing`, `update-billing-lines`, `send-invoice-by-email`, `duplicate-billing`, `cancel-invoice`, `sign-estimate`, `refuse-estimate`, `archive-billing`, `unarchive-billing` | `billing:write` |


---

# Agent Instructions: 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:

```
GET https://docs.abby.fr/mcp/facturation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
