Recettes

Quatre intégrations souvent demandées, pas à pas : quelle clé créer, quels appels faire, et à quoi faire attention.

1. Exporter les factures vers un logiciel comptable chaque nuit

Chaque nuit, envoyer à votre outil comptable les factures émises ou modifiées dans la journée, avec leur PDF.

La clé

Une clé d'organisation au nom de la tâche (« Export comptable Sage »), avec INVOICES_LIST et COMPANIES_LIST, et rien d'autre : elle ne fait que lire.

Le passage

  1. Lister ce qui a changé depuis le dernier passage, quelques minutes de chevauchement comprises, sans les brouillons :

    CLI

    #!/usr/bin/env bash
    # recipes-invoices-delta: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # --status again for each status (no drafts); --all follows every page.
    myle invoices list --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --updated-after 2026-11-20T23:55:00Z \
      --status VALIDATED --status UNPAID --status PARTIALLY_PAID --status PAID \
      --limit 200 --all --format jsonl \
      | jq -r '[.id, .number, .status, .total.amount, .updatedAt] | @tsv'
    # Upsert by id; statuses grow, so tolerate one you do not know.

    HTTP (curl)

    curl -G "https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices" \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -d updatedAfter=2026-11-20T23:55:00Z \
      -d status=VALIDATED -d status=UNPAID -d status=PARTIALLY_PAID -d status=PAID \
      -d limit=200

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    const changed = invoices.list({
      updatedAfter: '2026-11-20T23:55:00Z', // the last run's start, a few minutes earlier
      status: ['VALIDATED', 'UNPAID', 'PARTIALLY_PAID', 'PAID'], // no drafts
      limit: 200,
    });
    for await (const invoice of changed) {
      // Upsert by id; statuses grow, so tolerate one you do not know.
      console.log(invoice.id, invoice.number, invoice.status, invoice.total.amount, invoice.updatedAt);
    }

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    changed = invoices.list(
        updated_after="2026-11-20T23:55:00Z",  # the last run's start, a few minutes earlier
        status=["VALIDATED", "UNPAID", "PARTIALLY_PAID", "PAID"],  # no drafts
        limit=200,
    )
    for invoice in changed:
        # Upsert by id; statuses grow, so tolerate one you do not know.
        print(invoice.id, invoice.number, invoice.status, invoice.total.amount, invoice.updated_at)

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        changed := invoices.List(context.Background(), &myle.InvoiceListParams{
            UpdatedAfter: myle.String("2026-11-20T23:55:00Z"), // the last run's start, a few minutes earlier
            Status: []myle.InvoiceStatus{ // no drafts
                myle.InvoiceStatusValidated, myle.InvoiceStatusUnpaid, myle.InvoiceStatusPartiallyPaid, myle.InvoiceStatusPaid,
            },
            Limit: myle.Int(200),
        })
        for invoice, err := range changed.All() {
            if err != nil {
                log.Fatal(err)
            }
            // Upsert by id; statuses grow, so tolerate one you do not know.
            fmt.Println(invoice.ID, text(invoice.Number), invoice.Status, invoice.Total.Amount, invoice.UpdatedAt)
        }
    }
    
    // text is a member that may be null (a pointer) as text: "" for null.
    func text(s *string) string {
        if s == nil {
            return ""
        }
        return *s
    }

    Java

    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.InvoiceListParams;
    import fr.myleapp.myle.InvoiceStatus;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.Paginator;
    import java.time.OffsetDateTime;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            Paginator<Invoice> changed = invoices.list(InvoiceListParams.builder()
                    .updatedAfter(OffsetDateTime.parse("2026-11-20T23:55:00Z")) // the last run's start, a few minutes earlier
                    .status(InvoiceStatus.VALIDATED, InvoiceStatus.UNPAID, InvoiceStatus.PARTIALLY_PAID, InvoiceStatus.PAID) // no drafts
                    .limit(200)
                    .build());
            for (Invoice invoice : changed) {
                // Upsert by id; statuses grow, so tolerate one you do not know.
                System.out.println(invoice.id() + " " + invoice.number() + " " + invoice.status() + " "
                        + invoice.total().amount() + " " + invoice.updatedAt());
            }
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.{InvoiceStatus, ListInvoicesParams}
    
    object RecipesInvoicesDelta {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        val changed = invoices.list(
          ListInvoicesParams(
            updatedAfter = Some("2026-11-20T23:55:00Z"), // the last run's start, a few minutes earlier
            status = List(InvoiceStatus.Validated, InvoiceStatus.Unpaid, InvoiceStatus.PartiallyPaid, InvoiceStatus.Paid), // no drafts
            limit = Some(200)
          )
        )
        for (invoice <- changed) {
          // Upsert by id; statuses grow, so tolerate one you do not know.
          println(s"${invoice.id} ${invoice.number.getOrElse("")} ${invoice.status} ${invoice.total.amount} ${invoice.updatedAt}")
        }
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    $changed = $invoices->list(
        updatedAfter: '2026-11-20T23:55:00Z', // the last run's start, a few minutes earlier
        status: ['VALIDATED', 'UNPAID', 'PARTIALLY_PAID', 'PAID'], // no drafts
        limit: 200,
    );
    foreach ($changed as $invoice) {
        // Upsert by id; statuses grow, so tolerate one you do not know (it stays a string).
        $status = is_string($invoice->status) ? $invoice->status : $invoice->status->value;
        echo $invoice->id, ' ', $invoice->number, ' ', $status, ' ', $invoice->total->amount, ' ', $invoice->updatedAt, "\n";
    }

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    var changed = invoices.ListAsync(new InvoiceListParams
    {
        UpdatedAfter = new DateTimeOffset(2026, 11, 20, 23, 55, 0, TimeSpan.Zero), // the last run's start, a few minutes earlier
        Status = [InvoiceStatus.Validated, InvoiceStatus.Unpaid, InvoiceStatus.PartiallyPaid, InvoiceStatus.Paid], // no drafts
        Limit = 200,
    });
    await foreach (var invoice in changed)
    {
        // Upsert by id; statuses grow, so tolerate one you do not know.
        Console.WriteLine($"{invoice.Id} {invoice.Number} {invoice.Status} {invoice.Total.Amount} {invoice.UpdatedAt:O}");
    }
    Suivez nextCursor jusqu'au bout. Les brouillons (DRAFT) n'ont pas encore de numéro légal (number vaut null) ; la liste des statuts s'enrichit, décidez donc lesquels vous exportez et acceptez les autres.
  2. Pour chaque facture, l'écrire dans l'outil comptable d'après son id ; updatedAt dit si votre copie est plus ancienne. Les avoirs sont aussi des factures, liées par creditNoteIds et correctsInvoiceId.
  3. Récupérer le PDF des nouvelles : la même adresse, un autre format.

    CLI

    #!/usr/bin/env bash
    # recipes-invoice-pdf: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # -o writes the file as received; --format facturx for the Factur-X of a validated invoice.
    myle invoices retrieve invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1 \
      --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --format pdf -o invoice.pdf

    HTTP (curl)

    curl "https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices/invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1" \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Accept: application/pdf" \
      -o invoice.pdf

    TypeScript

    import { writeFile } from 'node:fs/promises';
    
    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    // The bytes as received, never parsed; { format: 'facturx' } for the Factur-X of a validated invoice.
    const pdf = await invoices.downloadPdf('invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1');
    await writeFile('invoice.pdf', pdf.data);
    console.log(pdf.filename, pdf.contentType); // its name from Content-Disposition, application/pdf

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    # The bytes as received, never parsed; format="facturx" for the Factur-X of a validated invoice.
    pdf = invoices.download_pdf("invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1")
    pdf.save("invoice.pdf")
    print(pdf.filename, pdf.content_type)  # its name from Content-Disposition, application/pdf

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        // The bytes as received, never parsed; &myle.GetInvoicePDFParams{Format: myle.Value(myle.GetInvoicePDFFormatFacturx)}
        // for the Factur-X of a validated invoice.
        pdf, err := invoices.DownloadPDF(context.Background(), "invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1", nil)
        if err != nil {
            log.Fatal(err)
        }
        if err := pdf.Save("invoice.pdf"); err != nil {
            log.Fatal(err)
        }
        fmt.Println(pdf.Filename, pdf.ContentType) // its name from Content-Disposition, application/pdf
    }

    Java

    import fr.myleapp.myle.FileDownload;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.MyleClient;
    import java.nio.file.Path;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            // The bytes as received, never parsed; GetInvoicePdfParams with InvoiceFormat.FACTURX
            // for the Factur-X of a validated invoice.
            FileDownload pdf = invoices.downloadPdf("invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1");
            pdf.save(Path.of("invoice.pdf"));
            System.out.println(pdf.filename() + " " + pdf.contentType()); // its name from Content-Disposition, application/pdf
        }
    }

    Scala

    import java.nio.file.Paths
    
    import fr.myleapp.myle.MyleClient
    
    object RecipesInvoicePdf {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        // The bytes as received, never parsed; GetInvoicePdfParams(format = Some(InvoiceFormat.Facturx))
        // for the Factur-X of a validated invoice.
        val pdf = invoices.downloadPdf("invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1")
        pdf.save(Paths.get("invoice.pdf"))
        println(s"${pdf.filename.getOrElse("")} ${pdf.contentType}") // its name from Content-Disposition, application/pdf
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    // The bytes as received, never parsed; format: 'facturx' for the Factur-X of a validated invoice.
    $pdf = $invoices->downloadPdf('invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1');
    $pdf->save('invoice.pdf');
    echo $pdf->filename, ' ', $pdf->contentType, "\n"; // its name from Content-Disposition, application/pdf

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    // The bytes as received, never decoded; new GetInvoicePdfParams { Format = InvoiceFormat.Facturx }
    // for the Factur-X of a validated invoice.
    var pdf = await invoices.DownloadPdfAsync("invoice_3c5e7a9b-1d2f-4a6b-8c0d-e2f4a6b8c0d1");
    await pdf.SaveAsync("invoice.pdf");
    Console.WriteLine($"{pdf.FileName} {pdf.ContentType}"); // its name from Content-Disposition, application/pdf
    Les PDF comptent dans la politique export (20 par minute) : espacez-les, et attendez Retry-After sur un 429.
  4. Le client, quand l'outil comptable a besoin de son numéro de compte : GET /organizations/{id}/companies/{companyId} (accountingNumber). La facture porte aussi, dans company, une copie figée du client tel qu'il a été facturé.
  5. Retenir l'instant de début du passage pour le prochain updatedAfter, seulement une fois tout écrit.

Les montants sont des chaînes décimales ({"amount": "1250.00", "currency": "EUR"}) : ne passez jamais par un flottant sur le chemin de votre comptabilité.

2. Transformer les commandes d'une boutique en ligne en factures

Quand une commande est payée sur votre boutique, créer la facture dans Myle, lui donner son numéro légal, dire que le client l'a et enregistrer le paiement.

La clé

Une clé d'organisation au nom de la boutique, avec ARTICLES_LIST, COMPANIES_LIST, COMPANIES_CREATE, INVOICES_CREATE, INVOICES_PATCH (valider, partager, payer) et, pour que Myle envoie la facture, INVOICES_SEND_EMAIL.

Les articles : disponibles aujourd'hui

Faites correspondre une fois le catalogue de la boutique et les articles de Myle, puis tenez la correspondance à jour avec une synchronisation :

CLI

#!/usr/bin/env bash
# recipes-products-delta: the myle CLI (key from `myle login` or MYLE_API_KEY).
# The shop's map, product reference -> Myle id, kept up to date run after run.
myle products list --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
  --updated-after 2026-11-20T23:55:00Z --sort updatedAt --limit 200 --all --format jsonl \
  | jq -s 'map({(.number): .id}) | add // {}'

HTTP (curl)

curl "https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/products?updatedAfter=2026-11-20T23:55:00Z&sort=updatedAt&limit=200" \
  -H "Authorization: Bearer $MYLE_API_KEY"

TypeScript

import { Myle } from '@myleapp/myle';

const myle = new Myle();
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;

// The shop's map, product reference -> Myle id, kept up to date run after run.
const idByNumber = new Map<string, string>();
for await (const product of products.list({ updatedAfter: '2026-11-20T23:55:00Z', sort: 'updatedAt', limit: 200 })) {
  idByNumber.set(product.number, product.id);
}
console.log(idByNumber);

Python

from myle import Myle

myle = Myle()
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

# The shop's map, product reference -> Myle id, kept up to date run after run.
id_by_number: dict[str, str] = {}
for product in products.list(updated_after="2026-11-20T23:55:00Z", sort="updatedAt", limit=200):
    id_by_number[product.number] = product.id
print(id_by_number)

Go

package main

import (
    "context"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    client := myle.NewClient()
    products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products

    // The shop's map, product reference -> Myle id, kept up to date run after run.
    idByNumber := map[string]string{}
    params := &myle.ProductListParams{UpdatedAfter: myle.String("2026-11-20T23:55:00Z"), Sort: myle.Value(myle.ProductListSortUpdatedAt), Limit: myle.Int(200)}
    for product, err := range products.List(context.Background(), params).All() {
        if err != nil {
            log.Fatal(err)
        }
        idByNumber[product.Number] = product.ID
    }
    fmt.Println(idByNumber)
}

Java

import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Product;
import fr.myleapp.myle.ProductListParams;
import fr.myleapp.myle.ProductSort;
import fr.myleapp.myle.Products;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        MyleClient client = MyleClient.builder().build();
        Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();

        // The shop's map, product reference -> Myle id, kept up to date run after run.
        Map<String, String> idByNumber = new HashMap<>();
        ProductListParams params = ProductListParams.builder()
                .updatedAfter(OffsetDateTime.parse("2026-11-20T23:55:00Z")).sort(ProductSort.UPDATED_AT).limit(200).build();
        for (Product product : products.list(params)) {
            idByNumber.put(product.number(), product.id());
        }
        System.out.println(idByNumber);
    }
}

Scala

import scala.collection.mutable

import fr.myleapp.myle.MyleClient
import fr.myleapp.myle.models.{ListProductsParams, ProductSort}

object RecipesProductsDelta {
  def main(args: Array[String]): Unit = {
    val myle = MyleClient()
    val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products

    // The shop's map, product reference -> Myle id, kept up to date run after run.
    val idByNumber = mutable.Map.empty[String, String]
    val changed = ListProductsParams(updatedAfter = Some("2026-11-20T23:55:00Z"), sort = Some(ProductSort.UpdatedAt), limit = Some(200))
    for (product <- products.list(changed)) {
      idByNumber(product.number) = product.id
    }
    println(idByNumber)
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;

$myle = new Client();
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;

// The shop's map, product reference -> Myle id, kept up to date run after run.
$idByNumber = [];
foreach ($products->list(updatedAfter: '2026-11-20T23:55:00Z', sort: 'updatedAt', limit: 200) as $product) {
    $idByNumber[$product->number] = $product->id;
}
print_r($idByNumber);

C#

using Myle;

using var client = new MyleClient();
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;

// The shop's map, product reference -> Myle id, kept up to date run after run.
var idByNumber = new Dictionary<string, string>();
var changed = products.ListAsync(new ProductListParams
{
    UpdatedAfter = new DateTimeOffset(2026, 11, 20, 23, 55, 0, TimeSpan.Zero),
    Sort = ProductSort.UpdatedAt,
    Limit = 200,
});
await foreach (var product in changed)
{
    idByNumber[product.Number] = product.Id;
}
Console.WriteLine(string.Join(", ", idByNumber));

Faites correspondre sur number (la référence de l'article) ou sur un code-barres (?barcode=3760…), et gardez l'id de l'article.

Pour chaque commande payée

  1. Trouver le client, ou le créer. Prenez une clé d'idempotence tirée de l'identifiant du client dans la boutique, pour qu'un nouvel essai n'en crée jamais deux :

    CLI

    #!/usr/bin/env bash
    # recipes-create-customer: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # A key derived from the shop's customer id: a retry, even days later, never creates two.
    answer=$(myle companies create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --number WEB-8812 --name 'Marie Dupont' --idempotency-key shop-customer-8812 -i --format json)
    # -i --format json prints one object: {status, headers, body}.
    jq -r .body.id <<<"$answer"
    jq -e '.headers["myle-idempotent-replayed"] == "true"' <<<"$answer" >/dev/null && echo '(already created)'

    HTTP (curl)

    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/companies \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-customer-8812" \
      -d '{ "number": "WEB-8812", "name": "Marie Dupont" }'

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const companies = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').companies;
    
    // A key derived from the shop's customer id: a retry, even days later, never creates two.
    const customer = await companies.create(
      { number: 'WEB-8812', name: 'Marie Dupont' },
      { idempotencyKey: 'shop-customer-8812' },
    );
    console.log(customer.id, customer.lastResponse.idempotentReplayed ? '(already created)' : '');

    Python

    from myle import Myle
    
    myle = Myle()
    companies = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").companies
    
    # A key derived from the shop's customer id: a retry, even days later, never creates two.
    customer = companies.create(number="WEB-8812", name="Marie Dupont", idempotency_key="shop-customer-8812")
    replayed = customer.last_response is not None and customer.last_response.idempotent_replayed
    print(customer.id, "(already created)" if replayed else "")

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        companies := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Companies
    
        // A key derived from the shop's customer id: a retry, even days later, never creates two.
        customer, err := companies.Create(context.Background(),
            &myle.CompanyCreateParams{Number: "WEB-8812", Name: "Marie Dupont"},
            myle.IdempotencyKey("shop-customer-8812"),
        )
        if err != nil {
            log.Fatal(err)
        }
        replayed := ""
        if customer.LastResponse().IdempotentReplayed {
            replayed = "(already created)"
        }
        fmt.Println(customer.ID, replayed)
    }

    Java

    import fr.myleapp.myle.Companies;
    import fr.myleapp.myle.Company;
    import fr.myleapp.myle.CompanyCreateParams;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.RequestOptions;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Companies companies = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").companies();
    
            // A key derived from the shop's customer id: a retry, even days later, never creates two.
            Company customer = companies.create(
                    CompanyCreateParams.builder().number("WEB-8812").name("Marie Dupont").build(),
                    RequestOptions.builder().idempotencyKey("shop-customer-8812").build());
            System.out.println(customer.id() + " " + (customer.lastResponse().idempotentReplayed() ? "(already created)" : ""));
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.CreateCompany
    
    object RecipesCreateCustomer {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val companies = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").companies
    
        // A key derived from the shop's customer id: a retry, even days later, never creates two.
        val customer = companies.create(
          CreateCompany(number = "WEB-8812", name = "Marie Dupont"),
          idempotencyKey = Some("shop-customer-8812")
        )
        val replayed = customer.lastResponse.exists(_.idempotentReplayed)
        println(s"${customer.id} ${if (replayed) "(already created)" else ""}")
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $companies = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->companies;
    
    // A key derived from the shop's customer id: a retry, even days later, never creates two.
    $customer = $companies->create(number: 'WEB-8812', name: 'Marie Dupont', idempotencyKey: 'shop-customer-8812');
    echo $customer->id, ' ', $customer->lastResponse()?->idempotentReplayed ? '(already created)' : '', "\n";

    C#

    using Myle;
    
    using var client = new MyleClient();
    var companies = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Companies;
    
    // A key derived from the shop's customer id: a retry, even days later, never creates two.
    var customer = await companies.CreateAsync(
        new CompanyCreateParams { Number = "WEB-8812", Name = "Marie Dupont" },
        new RequestOptions { IdempotencyKey = "shop-customer-8812" });
    Console.WriteLine($"{customer.Id} {(customer.LastResponse?.IdempotentReplayed == true ? "(already created)" : "")}");
  2. Créer la facture, avec une clé tirée de la commande :

    CLI

    #!/usr/bin/env bash
    # recipes-create-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # Nested members go through -d, wire names, quoted (zsh treats [...] as a glob).
    myle invoices create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --company-id company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3 \
      -d 'lines[0][productId]=product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d' \
      -d 'lines[0][name]=Ensilage maïs' \
      -d 'lines[0][quantity]=2' \
      -d 'lines[0][unitPrice][amount]=45.00' \
      -d 'lines[0][unitPrice][currency]=EUR' \
      -d 'lines[0][vatRate]=20' \
      --idempotency-key shop-order-1234 \
      | jq -r '[.id, .status] | @tsv'   # a DRAFT, no number yet

    HTTP (curl)

    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-order-1234" \
      -d '{
            "companyId": "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            "lines": [
              { "productId": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d", "name": "Ensilage maïs",
                "quantity": "2", "unitPrice": { "amount": "45.00", "currency": "EUR" }, "vatRate": "20" }
            ]
          }'

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    const invoice = await invoices.create(
      {
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
          {
            productId: 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
            name: 'Ensilage maïs',
            quantity: '2',
            unitPrice: { amount: '45.00', currency: 'EUR' },
            vatRate: '20',
          },
        ],
      },
      { idempotencyKey: 'shop-order-1234' }, // derived from the order
    );
    console.log(invoice.id, invoice.status); // a DRAFT, no number yet

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    invoice = invoices.create(
        company_id="company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
        lines=[
            {
                "product_id": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                "name": "Ensilage maïs",
                "quantity": "2",
                "unit_price": {"amount": "45.00", "currency": "EUR"},
                "vat_rate": "20",
            }
        ],
        idempotency_key="shop-order-1234",  # derived from the order
    )
    print(invoice.id, invoice.status)  # a DRAFT, no number yet

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        invoice, err := invoices.Create(context.Background(), &myle.InvoiceCreateParams{
            CompanyID: "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines: []myle.InvoiceLineInput{{
                ProductID: myle.String("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d"),
                Name:      "Ensilage maïs",
                Quantity:  "2",
                UnitPrice: myle.Money{Amount: "45.00", Currency: "EUR"},
                VatRate:   "20",
            }},
        }, myle.IdempotencyKey("shop-order-1234")) // derived from the order
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(invoice.ID, invoice.Status) // a DRAFT, no number yet
    }

    Java

    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.InvoiceCreateParams;
    import fr.myleapp.myle.InvoiceLineInput;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.Money;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.RequestOptions;
    import java.util.List;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            Invoice invoice = invoices.create(
                    InvoiceCreateParams.builder()
                            .companyId("company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3")
                            .lines(List.of(InvoiceLineInput.builder()
                                    .productId("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
                                    .name("Ensilage maïs")
                                    .quantity("2")
                                    .unitPrice(new Money("45.00", "EUR"))
                                    .vatRate("20")
                                    .build()))
                            .build(),
                    RequestOptions.builder().idempotencyKey("shop-order-1234").build()); // derived from the order
            System.out.println(invoice.id() + " " + invoice.status()); // a DRAFT, no number yet
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.{CreateInvoice, InvoiceLineInput, Money}
    
    object RecipesCreateInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        val invoice = invoices.create(
          CreateInvoice(
            companyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            lines = List(
              InvoiceLineInput(
                productId = Some("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d"),
                name = "Ensilage maïs",
                quantity = "2",
                unitPrice = Money(amount = "45.00", currency = "EUR"),
                vatRate = "20"
              )
            )
          ),
          idempotencyKey = Some("shop-order-1234") // derived from the order
        )
        println(s"${invoice.id} ${invoice.status}") // a DRAFT, no number yet
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    $invoice = $invoices->create(
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
            [
                'productId' => 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
                'name' => 'Ensilage maïs',
                'quantity' => '2',
                'unitPrice' => ['amount' => '45.00', 'currency' => 'EUR'],
                'vatRate' => '20',
            ],
        ],
        idempotencyKey: 'shop-order-1234', // derived from the order
    );
    $status = is_string($invoice->status) ? $invoice->status : $invoice->status->value;
    echo $invoice->id, ' ', $status, "\n"; // a DRAFT, no number yet

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    var invoice = await invoices.CreateAsync(
        new InvoiceCreateParams
        {
            CompanyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines =
            [
                new InvoiceLineInput
                {
                    ProductId = "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                    Name = "Ensilage maïs",
                    Quantity = "2",
                    UnitPrice = new Money { Amount = "45.00", Currency = "EUR" },
                    VatRate = "20",
                },
            ],
        },
        new RequestOptions { IdempotencyKey = "shop-order-1234" }); // derived from the order
    Console.WriteLine($"{invoice.Id} {invoice.Status}"); // a DRAFT, no number yet
    Elle naît brouillon (DRAFT), sans numéro.
  3. La valider, ce qui lui donne son numéro légal, puis l'envoie comme le disent les réglages du client (une facture électronique par le réseau, ou le PDF à ses adresses marquées pour les factures) :

    CLI

    #!/usr/bin/env bash
    # recipes-validate-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    myle invoices validate invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --idempotency-key shop-order-1234-validate \
      | jq -r '[.number, .status] | @tsv'   # its legal number, VALIDATED

    HTTP (curl)

    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices/invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c/validate \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: shop-order-1234-validate"

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    const invoice = await invoices.validate('invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c', {
      idempotencyKey: 'shop-order-1234-validate', // derived from the order
    });
    console.log(invoice.number, invoice.status); // its legal number, VALIDATED

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    invoice = invoices.validate(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        idempotency_key="shop-order-1234-validate",  # derived from the order
    )
    print(invoice.number, invoice.status)  # its legal number, VALIDATED

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        invoice, err := invoices.Validate(context.Background(), "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
            myle.IdempotencyKey("shop-order-1234-validate")) // derived from the order
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(*invoice.Number, invoice.Status) // its legal number, VALIDATED
    }

    Java

    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.RequestOptions;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            Invoice invoice = invoices.validate(
                    "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
                    RequestOptions.builder().idempotencyKey("shop-order-1234-validate").build()); // derived from the order
            System.out.println(invoice.number() + " " + invoice.status()); // its legal number, VALIDATED
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    
    object RecipesValidateInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        val invoice = invoices.validate(
          "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
          idempotencyKey = Some("shop-order-1234-validate") // derived from the order
        )
        println(s"${invoice.number.getOrElse("")} ${invoice.status}") // its legal number, VALIDATED
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    $invoice = $invoices->validate(
        'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
        idempotencyKey: 'shop-order-1234-validate', // derived from the order
    );
    $status = is_string($invoice->status) ? $invoice->status : $invoice->status->value;
    echo $invoice->number ?? '', ' ', $status, "\n"; // its legal number, VALIDATED

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    var invoice = await invoices.ValidateAsync(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        new RequestOptions { IdempotencyKey = "shop-order-1234-validate" }); // derived from the order
    Console.WriteLine($"{invoice.Number} {invoice.Status}"); // its legal number, VALIDATED
  4. Un client créé par la boutique n'a pas encore d'adresse marquée pour les factures, sauf si vous lui en avez donné une : envoyez-la à l'adresse de l'acheteur (dans emailAddresses à la création du client) par les ids des adresses e-mail du client (emailAddresses[].id). La réponse donne un résultat par destinataire :

    CLI

    #!/usr/bin/env bash
    # recipes-send-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # One result per recipient: SUCCEEDED, or FAILED with its error.
    myle invoices send invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --to companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f \
      --idempotency-key shop-order-1234-send \
      | jq -r '[.id, .status] | @tsv'

    HTTP (curl)

    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices/invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c/send \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-order-1234-send" \
      -d '{ "to": ["companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f"] }'

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    // One result per recipient: SUCCEEDED, or FAILED with its error.
    const results = invoices.send(
      'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
      { to: ['companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f'] },
      { idempotencyKey: 'shop-order-1234-send' }, // without a key, a retry sends again
    );
    for await (const result of results) {
      console.log(result.id, result.status, result.error?.code ?? '');
    }

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    # One result per recipient: SUCCEEDED, or FAILED with its error.
    results = invoices.send(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        to=["companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f"],
        idempotency_key="shop-order-1234-send",  # without a key, a retry sends again
    )
    for result in results:
        print(result.id, result.status, result.error.code if result.error else "")

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        // One result per recipient: SUCCEEDED, or FAILED with its error.
        results := invoices.Send(context.Background(), "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c", &myle.InvoiceSendParams{
            To: []string{"companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f"},
        }, myle.IdempotencyKey("shop-order-1234-send")) // without a key, a retry sends again
        for result, err := range results.All() {
            if err != nil {
                log.Fatal(err)
            }
            if result.Error != nil {
                fmt.Println(result.ID, result.Status, result.Error.Code)
                continue
            }
            fmt.Println(result.ID, result.Status)
        }
    }

    Java

    import fr.myleapp.myle.InvoiceSendParams;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.ItemResult;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.RequestOptions;
    import java.util.List;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            // One result per recipient: SUCCEEDED, or FAILED with its error.
            InvoiceSendParams params = InvoiceSendParams.builder()
                    .to(List.of("companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f"))
                    .build();
            RequestOptions options = RequestOptions.builder().idempotencyKey("shop-order-1234-send").build();
            for (ItemResult result : invoices.send("invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c", params, options)) {
                String code = result.error() == null ? "" : result.error().code();
                System.out.println(result.id() + " " + result.status() + " " + code);
            }
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.SendInvoice
    
    object RecipesSendInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        // One result per recipient: SUCCEEDED, or FAILED with its error.
        val results = invoices.send(
          "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
          SendInvoice(to = List("companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f")),
          idempotencyKey = Some("shop-order-1234-send") // without a key, a retry sends again
        )
        for (result <- results) println(s"${result.id} ${result.status} ${result.error.map(_.code).getOrElse("")}")
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    // One result per recipient: SUCCEEDED, or FAILED with its error.
    $results = $invoices->send(
        'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
        to: ['companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f'],
        idempotencyKey: 'shop-order-1234-send', // without a key, a retry sends again
    );
    foreach ($results as $result) {
        $status = is_string($result->status) ? $result->status : $result->status->value;
        echo $result->id, ' ', $status, ' ', $result->error->code ?? '', "\n";
    }

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    // One result per recipient: SUCCEEDED, or FAILED with its error.
    var results = invoices.SendAsync(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        new InvoiceSendParams { To = ["companyEmailAddress_e4d3c2b1-a0f9-4e8d-b7c6-5a4b3c2d1e0f"] },
        new RequestOptions { IdempotencyKey = "shop-order-1234-send" }); // without a key, a retry sends again
    await foreach (var result in results)
        Console.WriteLine($"{result.Id} {result.Status} {result.Error?.Code}");
  5. Dire que le client l'a : POST …/share la passe SHARED, le premier statut qui accepte un paiement, que la boutique l'ait envoyée (son propre reçu, votre propre e-mail) ou Myle (son e-mail délivré ferait de même un peu plus tard ; le redemander ne change rien) :

    CLI

    #!/usr/bin/env bash
    # recipes-share-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    myle invoices share invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      --idempotency-key shop-order-1234-share \
      | jq -r '.status'   # SHARED: it takes payments now

    HTTP (curl)

    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices/invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c/share \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: shop-order-1234-share"

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const invoices = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices;
    
    // The customer has it (your shop sent it): it takes payments from now on.
    const invoice = await invoices.share('invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c', {}, {
      idempotencyKey: 'shop-order-1234-share', // derived from the order
    });
    console.log(invoice.status); // SHARED

    Python

    from myle import Myle
    
    myle = Myle()
    invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
    # The customer has it (your shop sent it): it takes payments from now on.
    invoice = invoices.share(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        idempotency_key="shop-order-1234-share",  # derived from the order
    )
    print(invoice.status)  # SHARED

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        invoices := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices
    
        // The customer has it (your shop sent it): it takes payments from now on.
        invoice, err := invoices.Share(context.Background(), "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c", nil,
            myle.IdempotencyKey("shop-order-1234-share")) // derived from the order
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(invoice.Status) // SHARED
    }

    Java

    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.Invoices;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.RequestOptions;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Invoices invoices = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices();
    
            // The customer has it (your shop sent it): it takes payments from now on.
            Invoice invoice = invoices.share(
                    "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
                    RequestOptions.builder().idempotencyKey("shop-order-1234-share").build()); // derived from the order
            System.out.println(invoice.status()); // SHARED
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    
    object RecipesShareInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val invoices = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices
    
        // The customer has it (your shop sent it): it takes payments from now on.
        val invoice = invoices.share(
          "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
          idempotencyKey = Some("shop-order-1234-share") // derived from the order
        )
        println(invoice.status) // SHARED
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $invoices = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices;
    
    // The customer has it (your shop sent it): it takes payments from now on.
    $invoice = $invoices->share(
        'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
        idempotencyKey: 'shop-order-1234-share', // derived from the order
    );
    echo is_string($invoice->status) ? $invoice->status : $invoice->status->value, "\n"; // SHARED

    C#

    using Myle;
    
    using var client = new MyleClient();
    var invoices = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices;
    
    // The customer has it (your shop sent it): it takes payments from now on.
    var invoice = await invoices.ShareAsync(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        null,
        new RequestOptions { IdempotencyKey = "shop-order-1234-share" }); // derived from the order
    Console.WriteLine(invoice.Status); // SHARED
    Un client qui reçoit des factures électroniques reçoit celle-ci par le réseau de facturation électronique, que la validation a emprunté : POST …/share répond alors 409 billing.invoice.einvoice-required, et la facture accepte les paiements une fois que le réseau l'a (un statut EINVOICE_…) ; le client d'une boutique, un particulier, n'est jamais joint ainsi.
  6. Enregistrer le paiement, avec une clé tirée de la commande elle aussi (sans clé, un nouvel essai enregistre un second paiement) :

    CLI

    #!/usr/bin/env bash
    # recipes-record-payment: the myle CLI (key from `myle login` or MYLE_API_KEY).
    myle invoice-payments create invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
      -d 'amount[amount]=108.00' -d 'amount[currency]=EUR' \
      --method CARD --reference 'Commande 1234' \
      --idempotency-key shop-order-1234-payment \
      | jq -r '[.id, .amount.amount] | @tsv'

    HTTP (curl)

    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/invoices/invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c/payments \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-order-1234-payment" \
      -d '{
            "amount": { "amount": "108.00", "currency": "EUR" },
            "method": "CARD",
            "reference": "Commande 1234"
          }'

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const payments = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').invoices.payments;
    
    const payment = await payments.create(
      'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
      { amount: { amount: '108.00', currency: 'EUR' }, method: 'CARD', reference: 'Commande 1234' },
      { idempotencyKey: 'shop-order-1234-payment' }, // derived from the order
    );
    console.log(payment.id, payment.amount.amount);

    Python

    from myle import Myle
    
    myle = Myle()
    payments = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices.payments
    
    payment = payments.create(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        amount={"amount": "108.00", "currency": "EUR"},
        method="CARD",
        reference="Commande 1234",
        idempotency_key="shop-order-1234-payment",  # derived from the order
    )
    print(payment.id, payment.amount.amount)

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        client := myle.NewClient()
        payments := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices.Payments
    
        payment, err := payments.Create(context.Background(), "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c", &myle.InvoicePaymentCreateParams{
            Amount:    myle.Money{Amount: "108.00", Currency: "EUR"},
            Method:    myle.String("CARD"),
            Reference: myle.String("Commande 1234"),
        }, myle.IdempotencyKey("shop-order-1234-payment")) // derived from the order
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(payment.ID, payment.Amount.Amount)
    }

    Java

    import fr.myleapp.myle.InvoicePaymentCreateParams;
    import fr.myleapp.myle.InvoicePayments;
    import fr.myleapp.myle.Money;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.Payment;
    import fr.myleapp.myle.RequestOptions;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            InvoicePayments payments = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices().payments();
    
            Payment payment = payments.create(
                    "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
                    InvoicePaymentCreateParams.builder()
                            .amount(new Money("108.00", "EUR"))
                            .method("CARD")
                            .reference("Commande 1234")
                            .build(),
                    RequestOptions.builder().idempotencyKey("shop-order-1234-payment").build()); // derived from the order
            System.out.println(payment.id() + " " + payment.amount().amount());
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.{CreatePayment, Money}
    
    object RecipesRecordPayment {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val payments = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").invoices.payments
    
        val payment = payments.create(
          "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
          CreatePayment(
            amount = Money(amount = "108.00", currency = "EUR"),
            method = Some("CARD"),
            reference = Some("Commande 1234")
          ),
          idempotencyKey = Some("shop-order-1234-payment") // derived from the order
        )
        println(s"${payment.id} ${payment.amount.amount}")
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $payments = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->invoices->payments;
    
    $payment = $payments->create(
        'invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c',
        amount: ['amount' => '108.00', 'currency' => 'EUR'],
        method: 'CARD',
        reference: 'Commande 1234',
        idempotencyKey: 'shop-order-1234-payment', // derived from the order
    );
    echo $payment->id, ' ', $payment->amount->amount, "\n";

    C#

    using Myle;
    
    using var client = new MyleClient();
    var payments = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Invoices.Payments;
    
    var payment = await payments.CreateAsync(
        "invoice_5c8e2f1a-3b7d-4e9c-8a6f-0d1e2f3a4b5c",
        new InvoicePaymentCreateParams
        {
            Amount = new Money { Amount = "108.00", Currency = "EUR" },
            Method = "CARD",
            Reference = "Commande 1234",
        },
        new RequestOptions { IdempotencyKey = "shop-order-1234-payment" }); // derived from the order
    Console.WriteLine($"{payment.Id} {payment.Amount.Amount}");
    La facture passe PAID quand il ne reste rien à payer (amountDue), et le paiement est passé en comptabilité et lettré. Une facture pas encore partagée répond 409 billing.invoice.not-payable (context.status : VALIDATED) : partagez-la d'abord.
  7. Garder l'identifiant de la facture à côté de la commande. Une clé d'idempotence est gardée 24 heures ; au-delà, c'est votre propre correspondance qui évite une seconde facture.

Un brouillon se corrige avec POST …/invoices/{invoiceId}/edit (ses lignes, son client et sa description) tant qu'il n'est pas sorti de l'organisation ; une facture validée ne se modifie ni ne se supprime. Une commande annulée : déclarez sa facture perdue (POST …/mark-lost), annulez-la en entier par un avoir (POST …/credit-notes), et refacturez la vente s'il le faut (POST …/reinvoice sur l'avoir validé). Pour un retour partiel, créez un avoir brouillon aux lignes négatives, nommez la facture qu'il rectifie (POST …/set-corrected-invoice) et validez-le. Un paiement saisi par erreur s'enlève avec DELETE …/payments/{paymentId}, tous avec POST …/unpay.

3. Tenir à jour les clients d'un CRM

Garder les mêmes clients dans Myle et dans votre CRM, dans les deux sens.

La clé

Une clé d'organisation avec COMPANIES_LIST, COMPANIES_CREATE et COMPANIES_PATCH ; ajoutez une restriction par étiquettes si le CRM ne doit voir que certains clients.

De Myle vers le CRM

  1. Lire les changements : GET /organizations/{id}/companies?updatedAfter=…&limit=200, en suivant les curseurs.
  2. Écrire chacun dans le CRM d'après son id Myle.
  3. Les suppressions n'apparaissent pas dans une synchronisation : une fois par semaine, listez tous les identifiants et retirez du CRM ceux que Myle ne renvoie plus.

Du CRM vers Myle

  1. Un nouveau client : POST /organizations/{id}/companies avec une Idempotency-Key tirée de l'identifiant du CRM, puis gardez l'id Myle dans le CRM.
  2. Une modification : lisez le client pour obtenir son ETag, puis envoyez un PATCH de ce qui a changé seulement, avec If-Match.
  3. Sur 412 core.precondition-failed, quelqu'un l'a modifié dans Myle entre-temps : relisez-le, décidez champ par champ quel côté l'emporte, et réessayez avec le nouvel ETag. Ne réessayez jamais à l'aveugle sans If-Match : vous effaceriez son changement.

Pour éviter les échos, sautez vos propres changements : comparez l'updatedAt que Myle a répondu à votre écriture avec celui qu'apporte la synchronisation suivante.

4. D'une affaire gagnée à un devis, puis à une facture

Quand une affaire se conclut dans votre CRM ou votre boutique, envoyez au client un devis Myle ; quand il l'accepte, facturez-le.

La clé

Une clé d'organisation avec QUOTATION_CREATE, QUOTATION_PATCH et QUOTATION_TRANSFORM_TO_INVOICE (et QUOTATION_LIST pour les relire). Le client et les articles sont ceux de Myle : leurs identifiants viennent de la recette CRM ci-dessus.

Les appels

  1. POST /organizations/{id}/quotations crée le devis, VALIDATED tout de suite avec son numéro (un devis n'a pas de brouillon) et valable 30 jours sauf expiryDate. Myle l'envoie aux adresses du client marquées « Devis », comme l'application web ; POST …/send l'envoie à d'autres. Puis POST …/share quand le client l'a, POST …/approve quand il dit oui, et POST …/invoice : une facture VALIDATED, numérotée, envoyée comme le veulent les réglages du client, son identifiant dans les invoiceIds du devis. Tirez chaque Idempotency-Key de l'affaire :

    CLI

    #!/usr/bin/env bash
    # recipes-quotation-to-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # Nested members go through -d, wire names, quoted (zsh treats [...] as a glob).
    org=organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d
    quotation=$(myle quotations create --organization "$org" \
      --company-id company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3 \
      -d 'lines[0][productId]=product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d' \
      -d 'lines[0][name]=Ensilage maïs' \
      -d 'lines[0][quantity]=2' \
      -d 'lines[0][unitPrice][amount]=45.00' \
      -d 'lines[0][unitPrice][currency]=EUR' \
      -d 'lines[0][vatRate]=20' \
      --idempotency-key crm-deal-5678 \
      | jq -r '.id')   # VALIDATED at once, with its number
    # The customer has it, then said yes.
    myle quotations share "$quotation" --organization "$org" --idempotency-key crm-deal-5678-share > /dev/null
    myle quotations approve "$quotation" --organization "$org" --idempotency-key crm-deal-5678-approve > /dev/null
    # Billed: a VALIDATED invoice, numbered, linked to the quotation.
    myle quotations invoice "$quotation" --organization "$org" --idempotency-key crm-deal-5678-invoice \
      | jq -r '[.id, .number, .total.amount] | @tsv'

    HTTP (curl)

    # Create the quotation: VALIDATED at once, with its number.
    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/quotations \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: crm-deal-5678" \
      -d '{
            "companyId": "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            "lines": [
              { "productId": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d", "name": "Ensilage maïs",
                "quantity": "2", "unitPrice": { "amount": "45.00", "currency": "EUR" }, "vatRate": "20" }
            ]
          }'
    
    # The customer has it, then said yes (its id from the answer above).
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/quotations/quotation_3e1f7a2c-9b4d-4c8e-a6f0-1d2b3c4e5f6a/share \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: crm-deal-5678-share"
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/quotations/quotation_3e1f7a2c-9b4d-4c8e-a6f0-1d2b3c4e5f6a/approve \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: crm-deal-5678-approve"
    
    # Billed: 201, the invoice (VALIDATED, numbered), its path in Location.
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/quotations/quotation_3e1f7a2c-9b4d-4c8e-a6f0-1d2b3c4e5f6a/invoice \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: crm-deal-5678-invoice"

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const quotations = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').quotations;
    
    // VALIDATED at once, with its number.
    const quotation = await quotations.create(
      {
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
          {
            productId: 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
            name: 'Ensilage maïs',
            quantity: '2',
            unitPrice: { amount: '45.00', currency: 'EUR' },
            vatRate: '20',
          },
        ],
      },
      { idempotencyKey: 'crm-deal-5678' }, // derived from the deal
    );
    // The customer has it, then said yes.
    await quotations.share(quotation.id, { idempotencyKey: 'crm-deal-5678-share' });
    await quotations.approve(quotation.id, { idempotencyKey: 'crm-deal-5678-approve' });
    // Billed: a VALIDATED invoice, numbered, linked to the quotation.
    const invoice = await quotations.invoice(quotation.id, { idempotencyKey: 'crm-deal-5678-invoice' });
    console.log(invoice.id, invoice.number, invoice.total.amount);

    Python

    from myle import Myle
    
    myle = Myle()
    quotations = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").quotations
    
    # VALIDATED at once, with its number.
    quotation = quotations.create(
        company_id="company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
        lines=[
            {
                "product_id": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                "name": "Ensilage maïs",
                "quantity": "2",
                "unit_price": {"amount": "45.00", "currency": "EUR"},
                "vat_rate": "20",
            }
        ],
        idempotency_key="crm-deal-5678",  # derived from the deal
    )
    # The customer has it, then said yes.
    quotations.share(quotation.id, idempotency_key="crm-deal-5678-share")
    quotations.approve(quotation.id, idempotency_key="crm-deal-5678-approve")
    # Billed: a VALIDATED invoice, numbered, linked to the quotation.
    invoice = quotations.invoice(quotation.id, idempotency_key="crm-deal-5678-invoice")
    print(invoice.id, invoice.number, invoice.total.amount)

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        ctx := context.Background()
        client := myle.NewClient()
        quotations := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Quotations
    
        // VALIDATED at once, with its number.
        quotation, err := quotations.Create(ctx, &myle.QuotationCreateParams{
            CompanyID: "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines: []myle.QuotationLineInput{{
                ProductID: "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                Name:      "Ensilage maïs",
                Quantity:  "2",
                UnitPrice: myle.Money{Amount: "45.00", Currency: "EUR"},
                VatRate:   "20",
            }},
        }, myle.IdempotencyKey("crm-deal-5678")) // derived from the deal
        if err != nil {
            log.Fatal(err)
        }
        // The customer has it, then said yes.
        if _, err := quotations.Share(ctx, quotation.ID, myle.IdempotencyKey("crm-deal-5678-share")); err != nil {
            log.Fatal(err)
        }
        if _, err := quotations.Approve(ctx, quotation.ID, myle.IdempotencyKey("crm-deal-5678-approve")); err != nil {
            log.Fatal(err)
        }
        // Billed: a VALIDATED invoice, numbered, linked to the quotation.
        invoice, err := quotations.Invoice(ctx, quotation.ID, myle.IdempotencyKey("crm-deal-5678-invoice"))
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(invoice.ID, invoice.Status, invoice.Total.Amount)
    }

    Java

    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.Money;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.Quotation;
    import fr.myleapp.myle.QuotationCreateParams;
    import fr.myleapp.myle.QuotationLineInput;
    import fr.myleapp.myle.Quotations;
    import fr.myleapp.myle.RequestOptions;
    import java.util.List;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            Quotations quotations = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").quotations();
    
            // VALIDATED at once, with its number.
            Quotation quotation = quotations.create(
                    QuotationCreateParams.builder()
                            .companyId("company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3")
                            .lines(List.of(QuotationLineInput.builder()
                                    .productId("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
                                    .name("Ensilage maïs")
                                    .quantity("2")
                                    .unitPrice(new Money("45.00", "EUR"))
                                    .vatRate("20")
                                    .build()))
                            .build(),
                    RequestOptions.builder().idempotencyKey("crm-deal-5678").build()); // derived from the deal
            // The customer has it, then said yes.
            quotations.share(quotation.id(), RequestOptions.builder().idempotencyKey("crm-deal-5678-share").build());
            quotations.approve(quotation.id(), RequestOptions.builder().idempotencyKey("crm-deal-5678-approve").build());
            // Billed: a VALIDATED invoice, numbered, linked to the quotation.
            Invoice invoice = quotations.invoice(
                    quotation.id(), RequestOptions.builder().idempotencyKey("crm-deal-5678-invoice").build());
            System.out.println(invoice.id() + " " + invoice.status() + " " + invoice.total().amount());
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.{CreateQuotation, Money, QuotationLineInput}
    
    object RecipesQuotationToInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val quotations = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").quotations
    
        // VALIDATED at once, with its number.
        val quotation = quotations.create(
          CreateQuotation(
            companyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            lines = List(
              QuotationLineInput(
                productId = "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                name = "Ensilage maïs",
                quantity = "2",
                unitPrice = Money(amount = "45.00", currency = "EUR"),
                vatRate = "20"
              )
            )
          ),
          idempotencyKey = Some("crm-deal-5678") // derived from the deal
        )
        // The customer has it, then said yes.
        quotations.share(quotation.id, idempotencyKey = Some("crm-deal-5678-share"))
        quotations.approve(quotation.id, idempotencyKey = Some("crm-deal-5678-approve"))
        // Billed: a VALIDATED invoice, numbered, linked to the quotation.
        val invoice = quotations.invoice(quotation.id, idempotencyKey = Some("crm-deal-5678-invoice"))
        println(s"${invoice.id} ${invoice.number.getOrElse("")} ${invoice.total.amount}")
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $quotations = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->quotations;
    
    // VALIDATED at once, with its number.
    $quotation = $quotations->create(
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
            [
                'productId' => 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
                'name' => 'Ensilage maïs',
                'quantity' => '2',
                'unitPrice' => ['amount' => '45.00', 'currency' => 'EUR'],
                'vatRate' => '20',
            ],
        ],
        idempotencyKey: 'crm-deal-5678', // derived from the deal
    );
    // The customer has it, then said yes.
    $quotations->share($quotation->id, idempotencyKey: 'crm-deal-5678-share');
    $quotations->approve($quotation->id, idempotencyKey: 'crm-deal-5678-approve');
    // Billed: a VALIDATED invoice, numbered, linked to the quotation.
    $invoice = $quotations->invoice($quotation->id, idempotencyKey: 'crm-deal-5678-invoice');
    echo $invoice->id, ' ', $invoice->number ?? '', ' ', $invoice->total->amount, "\n";

    C#

    using Myle;
    
    using var client = new MyleClient();
    var quotations = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Quotations;
    
    // VALIDATED at once, with its number.
    var quotation = await quotations.CreateAsync(
        new QuotationCreateParams
        {
            CompanyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines =
            [
                new QuotationLineInput
                {
                    ProductId = "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                    Name = "Ensilage maïs",
                    Quantity = "2",
                    UnitPrice = new Money { Amount = "45.00", Currency = "EUR" },
                    VatRate = "20",
                },
            ],
        },
        new RequestOptions { IdempotencyKey = "crm-deal-5678" }); // derived from the deal
    // The customer has it, then said yes.
    await quotations.ShareAsync(quotation.Id, new RequestOptions { IdempotencyKey = "crm-deal-5678-share" });
    await quotations.ApproveAsync(quotation.Id, new RequestOptions { IdempotencyKey = "crm-deal-5678-approve" });
    // Billed: a VALIDATED invoice, numbered, linked to the quotation.
    var invoice = await quotations.InvoiceAsync(quotation.Id, new RequestOptions { IdempotencyKey = "crm-deal-5678-invoice" });
    Console.WriteLine($"{invoice.Id} {invoice.Number} {invoice.Total.Amount}");
  2. Le client refuse : POST …/cancel. Il hésite encore après la date : POST …/extend lui en donne une nouvelle (un devis EXPIRED retrouve son statut).
  3. Facturé par quelqu'un d'autre entre-temps (l'application web, une autre clé) : 409 quotations.quotation.already-invoiced nomme la facture ; déjà facturé par vous, la même facture est répondue (le même 409 si cette facture a été supprimée depuis). Un devis avec des factures d'acompte se solde par sa facture de solde, dans l'application web (409 quotations.quotation.has-deposits).

5. Prendre une commande, la livrer depuis ses lots, la facturer

Quand votre boutique, votre EDI ou l'application d'un commercial prend une commande, mettez-la dans Myle ; quand elle part, dites de quels lots viennent les marchandises : le bon de livraison les porte, et le stock bouge.

La clé

Une clé d'organisation avec ORDER_CREATE, ORDER_PATCH, ORDER_TRANSFORM_TO_DELIVERYFORM et DELIVERYFORMS_CREATE (pour les stocks qu'une livraison peut prendre), et DELIVERYFORMS_LIST et INVOICES_LIST pour relire le bon de livraison et sa facture. Sans ORDER_LIST_ALL, le robot d'une clé lit les commandes qu'il a créées, prépare ou livre.

Les appels

  1. POST /organizations/{id}/orders prend la commande, VALIDATED aussitôt avec son numéro ; Myle l'envoie aux adresses du client marquées « Commande ». POST …/approve quand le client la confirme, POST …/mark-waiting-for-delivery une fois préparée. GET …/stock-availability donne, par ligne, les stocks et les lots qui peuvent encore donner ; POST …/deliver avec les lots fait le bon de livraison — une ligne par lot, plusieurs lots par ligne de commande — et fait sortir le stock. Tirez chaque Idempotency-Key de votre commande :

    CLI

    #!/usr/bin/env bash
    # recipes-order-to-invoice: the myle CLI (key from `myle login` or MYLE_API_KEY).
    # Nested members go through -d, wire names, quoted (zsh treats [...] as a glob).
    org=organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d
    stock=stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c
    order=$(myle orders create --organization "$org" \
      --company-id company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3 \
      -d 'lines[0][productId]=product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d' \
      -d 'lines[0][name]=Pommes de terre Charlotte (carton 10 kg)' \
      -d 'lines[0][quantity]=9' \
      -d 'lines[0][unitPrice][amount]=14.50' \
      -d 'lines[0][unitPrice][currency]=EUR' \
      -d 'lines[0][vatRate]=5.5' \
      --idempotency-key shop-order-1042 \
      | jq -r '.id')   # VALIDATED at once, with its number
    # The customer confirmed it; it is prepared.
    myle orders approve "$order" --organization "$org" --idempotency-key shop-order-1042-approve > /dev/null
    myle orders mark-waiting-for-delivery "$order" --organization "$org" --idempotency-key shop-order-1042-prepared > /dev/null
    # Delivered: one delivery note line per lot, 7 cartons from lot 8326, 2 from lot 8327.
    note=$(myle orders deliver "$order" --organization "$org" \
      -d 'lots[0][lineIndex]=0' -d "lots[0][stockId]=$stock" -d 'lots[0][lotNumber]=8326' -d 'lots[0][quantity]=7' \
      -d 'lots[1][lineIndex]=0' -d "lots[1][stockId]=$stock" -d 'lots[1][lotNumber]=8327' -d 'lots[1][quantity]=2' \
      --idempotency-key shop-order-1042-deliver \
      | jq -r '.id')
    # Billed with the customer's invoicing period: the invoice is in the note's invoiceIds once it exists.
    myle delivery-notes retrieve "$note" --organization "$org" | jq -r '.invoiceIds[]'

    HTTP (curl)

    # Take the order: VALIDATED at once, with its number.
    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/orders \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-order-1042" \
      -d '{
            "companyId": "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            "lines": [
              { "productId": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d", "name": "Pommes de terre Charlotte (carton 10 kg)",
                "quantity": "9", "unitPrice": { "amount": "14.50", "currency": "EUR" }, "vatRate": "5.5" }
            ]
          }'
    
    # The customer confirmed it; it is prepared (its id from the answer above).
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/orders/order_4b6d8f0a-2c4e-4a6b-8d0f-1a3c5e7b9d2f/approve \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: shop-order-1042-approve"
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/orders/order_4b6d8f0a-2c4e-4a6b-8d0f-1a3c5e7b9d2f/mark-waiting-for-delivery \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Idempotency-Key: shop-order-1042-prepared"
    
    # Delivered: 201, the delivery note, one line per lot (7 cartons from lot 8326, 2 from 8327), its path in Location.
    curl -X POST https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/orders/order_4b6d8f0a-2c4e-4a6b-8d0f-1a3c5e7b9d2f/deliver \
      -H "Authorization: Bearer $MYLE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: shop-order-1042-deliver" \
      -d '{
            "lots": [
              { "lineIndex": 0, "stockId": "stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c", "lotNumber": "8326", "quantity": "7" },
              { "lineIndex": 0, "stockId": "stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c", "lotNumber": "8327", "quantity": "2" }
            ]
          }'
    
    # Billed with the customer's invoicing period: its invoiceIds, then GET …/invoices/{invoiceId}.
    curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/delivery-notes/deliveryNote_8e0a2c4d-6f8b-4d0e-9a2c-3e5f7a9b1c4d \
      -H "Authorization: Bearer $MYLE_API_KEY"

    TypeScript

    import { Myle } from '@myleapp/myle';
    
    const myle = new Myle();
    const organization = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d');
    const orders = organization.orders;
    
    // VALIDATED at once, with its number.
    const order = await orders.create(
      {
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
          {
            productId: 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
            name: 'Pommes de terre Charlotte (carton 10 kg)',
            quantity: '9',
            unitPrice: { amount: '14.50', currency: 'EUR' },
            vatRate: '5.5',
          },
        ],
      },
      { idempotencyKey: 'shop-order-1042' }, // derived from the shop's order
    );
    // The customer confirmed it; it is prepared.
    await orders.approve(order.id, { idempotencyKey: 'shop-order-1042-approve' });
    await orders.markWaitingForDelivery(order.id, { idempotencyKey: 'shop-order-1042-prepared' });
    // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
    const stock = 'stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c';
    const note = await orders.deliver(
      order.id,
      {
        lots: [
          { lineIndex: 0, stockId: stock, lotNumber: '8326', quantity: '7' },
          { lineIndex: 0, stockId: stock, lotNumber: '8327', quantity: '2' },
        ],
      },
      { idempotencyKey: 'shop-order-1042-deliver' },
    );
    console.log(note.id, note.status, note.lines.length); // two lines, one per lot
    // Billed with the customer's invoicing period: the invoice is in the note's invoiceIds once it exists.
    const billed = await organization.deliveryNotes.get(note.id);
    for (const invoiceId of billed.invoiceIds) {
      const invoice = await organization.invoices.get(invoiceId);
      console.log(invoice.id, invoice.number, invoice.total.amount);
    }

    Python

    from myle import Myle
    
    myle = Myle()
    organization = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d")
    orders = organization.orders
    
    # VALIDATED at once, with its number.
    order = orders.create(
        company_id="company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
        lines=[
            {
                "product_id": "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                "name": "Pommes de terre Charlotte (carton 10 kg)",
                "quantity": "9",
                "unit_price": {"amount": "14.50", "currency": "EUR"},
                "vat_rate": "5.5",
            }
        ],
        idempotency_key="shop-order-1042",  # derived from the shop's order
    )
    # The customer confirmed it; it is prepared.
    orders.approve(order.id, idempotency_key="shop-order-1042-approve")
    orders.mark_waiting_for_delivery(order.id, idempotency_key="shop-order-1042-prepared")
    # Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
    stock = "stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c"
    note = orders.deliver(
        order.id,
        lots=[
            {"line_index": 0, "stock_id": stock, "lot_number": "8326", "quantity": "7"},
            {"line_index": 0, "stock_id": stock, "lot_number": "8327", "quantity": "2"},
        ],
        idempotency_key="shop-order-1042-deliver",
    )
    print(note.id, note.status, len(note.lines))  # two lines, one per lot
    # Billed with the customer's invoicing period: the invoice is in the note's invoice_ids once it exists.
    billed = organization.delivery_notes.get(note.id)
    for invoice_id in billed.invoice_ids:
        invoice = organization.invoices.get(invoice_id)
        print(invoice.id, invoice.number, invoice.total.amount)

    Go

    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        myle "github.com/myleapp/myle-go"
    )
    
    func main() {
        ctx := context.Background()
        client := myle.NewClient()
        organization := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d")
        orders := organization.Orders
    
        // VALIDATED at once, with its number.
        order, err := orders.Create(ctx, &myle.OrderCreateParams{
            CompanyID: "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines: []myle.OrderLineInput{{
                ProductID: "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                Name:      "Pommes de terre Charlotte (carton 10 kg)",
                Quantity:  "9",
                UnitPrice: myle.Money{Amount: "14.50", Currency: "EUR"},
                VatRate:   "5.5",
            }},
        }, myle.IdempotencyKey("shop-order-1042")) // derived from the shop's order
        if err != nil {
            log.Fatal(err)
        }
        // The customer confirmed it; it is prepared.
        if _, err := orders.Approve(ctx, order.ID, myle.IdempotencyKey("shop-order-1042-approve")); err != nil {
            log.Fatal(err)
        }
        if _, err := orders.MarkWaitingForDelivery(ctx, order.ID, myle.IdempotencyKey("shop-order-1042-prepared")); err != nil {
            log.Fatal(err)
        }
        // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
        stock := myle.Value("stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c")
        note, err := orders.Deliver(ctx, order.ID, &myle.OrderDeliverParams{
            Lots: myle.Value([]myle.OrderLotInput{
                {LineIndex: 0, StockID: stock, LotNumber: myle.Value("8326"), Quantity: "7"},
                {LineIndex: 0, StockID: stock, LotNumber: myle.Value("8327"), Quantity: "2"},
            }),
        }, myle.IdempotencyKey("shop-order-1042-deliver"))
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(note.ID, note.Status, len(note.Lines)) // two lines, one per lot
        // Billed with the customer's invoicing period: the invoice is in the note's InvoiceIDs once it exists.
        billed, err := organization.DeliveryNotes.Get(ctx, note.ID)
        if err != nil {
            log.Fatal(err)
        }
        for _, invoiceID := range billed.InvoiceIDs {
            invoice, err := organization.Invoices.Get(ctx, invoiceID)
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(invoice.ID, invoice.Status, invoice.Total.Amount)
        }
    }

    Java

    import fr.myleapp.myle.DeliveryNote;
    import fr.myleapp.myle.Invoice;
    import fr.myleapp.myle.Money;
    import fr.myleapp.myle.MyleClient;
    import fr.myleapp.myle.Order;
    import fr.myleapp.myle.OrderCreateParams;
    import fr.myleapp.myle.OrderDeliverParams;
    import fr.myleapp.myle.OrderLineInput;
    import fr.myleapp.myle.OrderLotInput;
    import fr.myleapp.myle.Orders;
    import fr.myleapp.myle.OrganizationScope;
    import fr.myleapp.myle.RequestOptions;
    import java.util.List;
    
    public class Example {
        public static void main(String[] args) {
            MyleClient client = MyleClient.builder().build();
            OrganizationScope organization = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d");
            Orders orders = organization.orders();
    
            // VALIDATED at once, with its number.
            Order order = orders.create(
                    OrderCreateParams.builder()
                            .companyId("company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3")
                            .lines(List.of(OrderLineInput.builder()
                                    .productId("product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d")
                                    .name("Pommes de terre Charlotte (carton 10 kg)")
                                    .quantity("9")
                                    .unitPrice(new Money("14.50", "EUR"))
                                    .vatRate("5.5")
                                    .build()))
                            .build(),
                    RequestOptions.builder().idempotencyKey("shop-order-1042").build()); // derived from the shop's order
            // The customer confirmed it; it is prepared.
            orders.approve(order.id(), RequestOptions.builder().idempotencyKey("shop-order-1042-approve").build());
            orders.markWaitingForDelivery(
                    order.id(), RequestOptions.builder().idempotencyKey("shop-order-1042-prepared").build());
            // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
            String stock = "stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c";
            DeliveryNote note = orders.deliver(
                    order.id(),
                    OrderDeliverParams.builder()
                            .lots(List.of(
                                    OrderLotInput.builder().lineIndex(0).stockId(stock).lotNumber("8326").quantity("7").build(),
                                    OrderLotInput.builder().lineIndex(0).stockId(stock).lotNumber("8327").quantity("2").build()))
                            .build(),
                    RequestOptions.builder().idempotencyKey("shop-order-1042-deliver").build());
            System.out.println(note.id() + " " + note.status() + " " + note.lines().size()); // two lines, one per lot
            // Billed with the customer's invoicing period: the invoice is in the note's invoiceIds once it exists.
            DeliveryNote billed = organization.deliveryNotes().get(note.id());
            for (String invoiceId : billed.invoiceIds()) {
                Invoice invoice = organization.invoices().get(invoiceId);
                System.out.println(invoice.id() + " " + invoice.status() + " " + invoice.total().amount());
            }
        }
    }

    Scala

    import fr.myleapp.myle.MyleClient
    import fr.myleapp.myle.models.{ConvertOrder, CreateOrder, Money, OrderLineInput, OrderLotInput}
    
    object RecipesOrderToInvoice {
      def main(args: Array[String]): Unit = {
        val myle = MyleClient()
        val organization = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d")
        val orders = organization.orders
    
        // VALIDATED at once, with its number.
        val order = orders.create(
          CreateOrder(
            companyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            lines = List(
              OrderLineInput(
                productId = "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                name = "Pommes de terre Charlotte (carton 10 kg)",
                quantity = "9",
                unitPrice = Money(amount = "14.50", currency = "EUR"),
                vatRate = "5.5"
              )
            )
          ),
          idempotencyKey = Some("shop-order-1042") // derived from the shop's order
        )
        // The customer confirmed it; it is prepared.
        orders.approve(order.id, idempotencyKey = Some("shop-order-1042-approve"))
        orders.markWaitingForDelivery(order.id, idempotencyKey = Some("shop-order-1042-prepared"))
        // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
        val stock = Some("stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c")
        val note = orders.deliver(
          order.id,
          ConvertOrder(lots =
            Some(
              List(
                OrderLotInput(lineIndex = 0, quantity = "7", stockId = stock, lotNumber = Some("8326")),
                OrderLotInput(lineIndex = 0, quantity = "2", stockId = stock, lotNumber = Some("8327"))
              )
            )
          ),
          idempotencyKey = Some("shop-order-1042-deliver")
        )
        println(s"${note.id} ${note.status} ${note.lines.size}") // two lines, one per lot
        // Billed with the customer's invoicing period: the invoice is in the note's invoiceIds once it exists.
        val billed = organization.deliveryNotes.get(note.id)
        billed.invoiceIds.foreach { invoiceId =>
          val invoice = organization.invoices.get(invoiceId)
          println(s"${invoice.id} ${invoice.number.getOrElse("")} ${invoice.total.amount}")
        }
      }
    }

    PHP

    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Myle\Client;
    
    $myle = new Client();
    $organization = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d');
    $orders = $organization->orders;
    
    // VALIDATED at once, with its number.
    $order = $orders->create(
        companyId: 'company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3',
        lines: [
            [
                'productId' => 'product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d',
                'name' => 'Pommes de terre Charlotte (carton 10 kg)',
                'quantity' => '9',
                'unitPrice' => ['amount' => '14.50', 'currency' => 'EUR'],
                'vatRate' => '5.5',
            ],
        ],
        idempotencyKey: 'shop-order-1042', // derived from the shop's order
    );
    // The customer confirmed it; it is prepared.
    $orders->approve($order->id, idempotencyKey: 'shop-order-1042-approve');
    $orders->markWaitingForDelivery($order->id, idempotencyKey: 'shop-order-1042-prepared');
    // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
    $stock = 'stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c';
    $note = $orders->deliver(
        $order->id,
        lots: [
            ['lineIndex' => 0, 'stockId' => $stock, 'lotNumber' => '8326', 'quantity' => '7'],
            ['lineIndex' => 0, 'stockId' => $stock, 'lotNumber' => '8327', 'quantity' => '2'],
        ],
        idempotencyKey: 'shop-order-1042-deliver',
    );
    echo $note->id, ' ', $note->status, ' ', count($note->lines), "\n"; // two lines, one per lot
    // Billed with the customer's invoicing period: the invoice is in the note's invoiceIds once it exists.
    $billed = $organization->deliveryNotes->get($note->id);
    foreach ($billed->invoiceIds as $invoiceId) {
        $invoice = $organization->invoices->get($invoiceId);
        echo $invoice->id, ' ', $invoice->number ?? '', ' ', $invoice->total->amount, "\n";
    }

    C#

    using Myle;
    
    using var client = new MyleClient();
    var organization = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d");
    var orders = organization.Orders;
    
    // VALIDATED at once, with its number.
    var order = await orders.CreateAsync(
        new OrderCreateParams
        {
            CompanyId = "company_9d1e4b7a-2c3f-4e5d-a6b7-c8d9e0f1a2b3",
            Lines =
            [
                new OrderLineInput
                {
                    ProductId = "product_2ab4c6e8-1f3d-4a5b-8c7d-9e0f1a2b3c4d",
                    Name = "Pommes de terre Charlotte (carton 10 kg)",
                    Quantity = "9",
                    UnitPrice = new Money { Amount = "14.50", Currency = "EUR" },
                    VatRate = "5.5",
                },
            ],
        },
        new RequestOptions { IdempotencyKey = "shop-order-1042" }); // derived from the shop's order
    // The customer confirmed it; it is prepared.
    await orders.ApproveAsync(order.Id, new RequestOptions { IdempotencyKey = "shop-order-1042-approve" });
    await orders.MarkWaitingForDeliveryAsync(order.Id, new RequestOptions { IdempotencyKey = "shop-order-1042-prepared" });
    // Delivered: 7 cartons from lot 8326, 2 from lot 8327 (GET …/stock-availability lists them).
    const string stock = "stock_5c7e9a1b-3d2f-4e6a-8b9c-0d1e2f3a4b5c";
    var note = await orders.DeliverAsync(
        order.Id,
        new OrderDeliverParams
        {
            Lots =
            [
                new OrderLotInput { LineIndex = 0, StockId = stock, LotNumber = "8326", Quantity = "7" },
                new OrderLotInput { LineIndex = 0, StockId = stock, LotNumber = "8327", Quantity = "2" },
            ],
        },
        new RequestOptions { IdempotencyKey = "shop-order-1042-deliver" });
    Console.WriteLine($"{note.Id} {note.Status} {note.Lines.Count}"); // two lines, one per lot
    // Billed with the customer's invoicing period: the invoice is in the note's InvoiceIds once it exists.
    var billed = await organization.DeliveryNotes.GetAsync(note.Id);
    foreach (var invoiceId in billed.InvoiceIds)
    {
        var invoice = await organization.Invoices.GetAsync(invoiceId);
        Console.WriteLine($"{invoice.Id} {invoice.Number} {invoice.Total.Amount}");
    }
  2. La facture : Myle facture le bon de livraison selon la périodicité de facturation du client (à chaque bon, à la semaine, au mois), et le bon la cite dans invoiceIds. Pour facturer tout de suite sans bon de livraison, POST …/orders/{orderId}/invoice avec les mêmes lots : une facture VALIDATED, numérotée (sur une facture, les lots d'une ligne font exactement la quantité commandée).
  3. Les lots ne vont pas à la ligne (zéro, plus que commandé) : 422 core.validation-failed, qui désigne /lots/{i}/quantity, rien n'est écrit. Facturée entre temps par quelqu'un d'autre : 409 orders.order.already-invoiced ; une commande avec des factures d'acompte se solde par sa facture de solde, dans l'application (409 orders.order.has-deposits).