Recipes

Four integrations people ask for, step by step: what key to create, which calls to make, and what to watch for.

1. Export invoices to accounting software every night

Every night, send the invoices issued or changed during the day to your accounting tool, with their PDF.

The key

An organization key named after the job (“Export comptable Sage”), with INVOICES_LIST and COMPANIES_LIST, and nothing else: it only reads.

The run

  1. List what changed since the last run, a few minutes of overlap included, leaving drafts out:

    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}");
    }
    Follow nextCursor to the end. Drafts (DRAFT) have no legal number yet (number is null); statuses grow, so decide which ones you export and tolerate the others.
  2. For each invoice, upsert it in the accounting tool by its id; updatedAt tells you whether your copy is older. Credit notes are invoices too, linked through creditNoteIds and correctsInvoiceId.
  3. Fetch the PDF of the new ones: the same address, another 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
    PDFs count in the export policy (20 a minute): pace them, and wait Retry-After on a 429.
  4. The customer, when the accounting tool needs its account number: GET /organizations/{id}/companies/{companyId} (accountingNumber). The invoice also carries a frozen snapshot of the customer as it was invoiced, in company.
  5. Store the instant the run started for the next updatedAfter, only once everything was written.

Amounts are decimal strings ({"amount": "1250.00", "currency": "EUR"}): never go through a float on the way to your ledger.

2. Push e-shop orders as invoices

When an order is paid on your e-shop, create the invoice in Myle, give it its legal number, say the customer has it, and record the payment.

The key

An organization key named after the shop, with ARTICLES_LIST, COMPANIES_LIST, COMPANIES_CREATE, INVOICES_CREATE, INVOICES_PATCH (validate, share, pay) and, to have Myle send the invoice, INVOICES_SEND_EMAIL.

Products: available today

Map the shop's catalog to Myle's products once, then keep the map up to date with a delta sync:

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));

Match on number (the product reference) or on a barcode (?barcode=3760…), and keep the product's id.

For each paid order

  1. Find the customer, or create it. Use an idempotency key derived from the shop's customer id, so a retry never creates two:

    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. Create the invoice, with a key derived from the order:

    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
    It is born a draft (DRAFT), without a number.
  3. Validate it, which gives it its legal number, then sends it the way the customer's settings say (an e-invoice through the network, or the PDF to its addresses marked for invoices):

    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. A customer created by the shop has no address marked for invoices unless you gave one: send it to the buyer's address (in emailAddresses when the customer was created) by the ids of the customer's e-mail addresses (emailAddresses[].id). The answer is one result per recipient:

    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. Say the customer has it: POST …/share moves it to SHARED, the first status that takes a payment, whether your shop sent it (its own receipt, your own e-mail) or Myle did (its delivered e-mail would do the same a little later; asking again changes nothing):

    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
    A customer that receives e-invoices gets this one through the e-invoicing network, which the validation used: POST …/share then answers 409 billing.invoice.einvoice-required, and the invoice takes payments once the network has it (a status EINVOICE_…); a customer of an e-shop, a consumer, is never reached that way.
  6. Record the payment, with a key derived from the order too (without one, a retry records a second payment):

    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}");
    The invoice moves to PAID once nothing remains due (amountDue), and the payment is booked in the ledger and lettered. An invoice not shared yet answers 409 billing.invoice.not-payable (context.status: VALIDATED): share it first.
  7. Store the invoice id next to the order. An idempotency key is kept 24 hours; past that, your own map is what prevents a second invoice.

A draft is fixed with POST …/invoices/{invoiceId}/edit (its lines, customer and description) until it leaves the organization; a validated invoice cannot be changed nor deleted. Once an order is cancelled, write its invoice off (POST …/mark-lost), cancel it whole with a credit note (POST …/credit-notes), and re-bill the sale if needed (POST …/reinvoice on the validated credit note). For a partial return, create a draft credit note with negative lines, name the invoice it corrects (POST …/set-corrected-invoice) and validate it. A payment keyed in by mistake goes with DELETE …/payments/{paymentId}, all of them with POST …/unpay.

3. Keep a CRM's customers in sync

Keep the customers of Myle and of your CRM the same, in both directions.

The key

An organization key with COMPANIES_LIST, COMPANIES_CREATE and COMPANIES_PATCH; add a tag scope if the CRM should only see some customers.

From Myle to the CRM

  1. Pull the changes: GET /organizations/{id}/companies?updatedAfter=…&limit=200, following the cursors.
  2. Upsert each one in the CRM by its Myle id.
  3. Deletions do not appear in a delta: once a week, list every id and remove from the CRM those Myle no longer returns.

From the CRM to Myle

  1. A new customer: POST /organizations/{id}/companies with an Idempotency-Key derived from the CRM's id, then store the Myle id in the CRM.
  2. A change: read the customer to get its ETag, then PATCH only what changed, with If-Match.
  3. On 412 core.precondition-failed, someone changed it in Myle meanwhile: read it again, decide which side wins field by field, and retry with the new ETag. Never retry blindly without If-Match: you would erase their change.

To avoid echoes, skip the changes you made yourself: compare the updatedAt Myle answered to your write with the one the next delta brings.

4. Turn a won deal into a quotation, then an invoice

When a deal is drawn up in your CRM or your shop, send the customer a Myle quotation; when they accept it, bill it.

The key

An organization key with QUOTATION_CREATE, QUOTATION_PATCH and QUOTATION_TRANSFORM_TO_INVOICE (and QUOTATION_LIST to read them back). The customer and the products are Myle's: their ids come from the CRM recipe above.

The calls

  1. POST /organizations/{id}/quotations creates the quotation, VALIDATED at once with its number (a quotation has no draft) and valid 30 days unless you send expiryDate. Myle mails it to the customer's addresses marked « Devis », as the web app does; POST …/send mails it to others. Then POST …/share once the customer has it, POST …/approve when they say yes, and POST …/invoice: a VALIDATED invoice, numbered, sent the way the customer's settings say, its id in the quotation's invoiceIds. Derive every Idempotency-Key from the deal:

    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. The customer declined: POST …/cancel. Still thinking past its date: POST …/extend gives it a new one (an EXPIRED quotation gets back its status).
  3. Billed by someone else meanwhile (the web app, another key): 409 quotations.quotation.already-invoiced names the invoice; billed by you already, the same invoice is answered again (the same 409 if that invoice was deleted since). A quotation with deposit invoices is settled by its final invoice, in the web app (409 quotations.quotation.has-deposits).

5. Take an order, deliver it from its stock lots, bill it

When your shop, your EDI or a sales rep's app takes an order, put it in Myle; when it leaves, say which stock lots the goods came from: the delivery note carries them, and the stock moves.

The key

An organization key with ORDER_CREATE, ORDER_PATCH, ORDER_TRANSFORM_TO_DELIVERYFORM and DELIVERYFORMS_CREATE (for the stocks a delivery can take), and DELIVERYFORMS_LIST and INVOICES_LIST to read the delivery note and its invoice back. Without ORDER_LIST_ALL, a key's robot reads the orders it created, prepares or delivers.

The calls

  1. POST /organizations/{id}/orders takes the order, VALIDATED at once with its number; Myle mails it to the customer's addresses marked « Commande ». POST …/approve when the customer confirms it, POST …/mark-waiting-for-delivery once it is prepared. GET …/stock-availability gives, per line, the stocks and the lots that can still give goods; POST …/deliver with the lots makes the delivery note — one line per lot, several lots per order line — and moves the stock. Derive every Idempotency-Key from your order:

    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. The invoice: Myle bills the delivery note with the customer's invoicing period (each one, weekly, monthly), and the note lists it in invoiceIds. To bill at once without a delivery note, POST …/orders/{orderId}/invoice with the same lots: a VALIDATED invoice, numbered (on an invoice, the lots of a line add up to exactly what it ordered).
  3. The lots do not fit the line (zero, more than ordered): 422 core.validation-failed, pointing at /lots/{i}/quantity, nothing written. Billed by someone else meanwhile: 409 orders.order.already-invoiced; an order with deposit invoices is settled by its final invoice, in the web app (409 orders.order.has-deposits).