feat(payment): first-class transaction_id when recording a règlement

Make the originating bank transaction id a first-class input on payment-record.sh
so every règlement is tied to the real bank movement at write time.

- `transaction_id` is the canonical field (the Qonto/Wise feed tx id); `num` stays
  as a back-compat alias. It's stored on the payment's bank line (llx_bank.num_chq),
  the reconciliation key.
- Recording WITHOUT a transaction_id prints a stderr warning (still posts, but won't
  auto-reconcile) — nudges the agent to always carry it.
- Output normalises to {id, bank_transaction_id, transaction_id}.
- Promote: manifests' payment ops carry transaction_id; promote-plan shows it
  (tx=… or tx=MISSING).

Proven live: customer + supplier record with transaction_id; the `num` alias maps
to the same field; the no-tx warning fires; promote plan/apply carry it through.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-30 00:34:10 +02:00
parent d81bff0ed3
commit b945c8de47
5 changed files with 42 additions and 28 deletions

View File

@@ -96,8 +96,8 @@ to leave a draft. Emits `{id, ref, ref_supplier, total_ht, total_ttc, statut}`.
### 3 · Payment (règlement) — `scripts/payment-record.sh` ### 3 · Payment (règlement) — `scripts/payment-record.sh`
```sh ```sh
echo '{"invoice_id":19,"mode":"VIR","account_id":1,"num":"QONTO-TX-1234"}' | scripts/payment-record.sh echo '{"invoice_id":19,"mode":"VIR","account_id":1,"transaction_id":"QONTO-TX-1234"}' | scripts/payment-record.sh
echo '{"invoice_id":13,"kind":"supplier","mode":"VIR","account_id":1,"amount":96,"num":"WISE-TX-5678"}' \ echo '{"invoice_id":13,"kind":"supplier","mode":"VIR","account_id":1,"amount":96,"transaction_id":"WISE-TX-5678"}' \
| scripts/payment-record.sh | scripts/payment-record.sh
``` ```
The invoice must be **validated** first. `mode`: `VIR|CB|CHQ|LIQ`. Customer The invoice must be **validated** first. `mode`: `VIR|CB|CHQ|LIQ`. Customer
@@ -105,12 +105,16 @@ payments settle the full remaining amount and mark the invoice paid; **supplier*
payments require an explicit `amount`. `account_id` is the bank account id — list payments require an explicit `amount`. `account_id` is the bank account id — list
them with `scripts/bank-accounts.sh` (`ai_agent_sandbox` now holds `banque lire`). them with `scripts/bank-accounts.sh` (`ai_agent_sandbox` now holds `banque lire`).
Emits **`{id, bank_transaction_id, num}`**. `bank_transaction_id` is the Dolibarr **Always pass `transaction_id`** — the originating bank transaction id (the
bank line (`llx_bank`) the payment created — the id bank reconciliation Qonto/Wise tx id from the feed). It is the first-class way to tie a règlement to
(`arcodange-bank-reco`) keys on to link a règlement to a statement line. Put the the real bank movement: stored on the payment's bank line (`llx_bank.num_chq`), so
**originating bank transaction id** (the Qonto/Wise tx id) in `num`: it is stored reconciliation matches **by id** rather than by fuzzy amount/date. (`num` is a
on that bank line (`num_chq`), so the feed reconciles by id rather than by fuzzy back-compat alias for the same field.) Recording without it prints a warning — the
amount/date. Both ends of the reconciliation are therefore captured at write time. payment still posts, but it won't auto-reconcile.
Emits **`{id, bank_transaction_id, transaction_id}`**. `bank_transaction_id` is the
Dolibarr bank line (`llx_bank.fk_bank_line`) the payment created — the id the
reconciliation (`arcodange-bank-reco`) keys on. Both ends are captured at write time.
### 4 · Credit note (avoir) — `scripts/creditnote-create.sh` ### 4 · Credit note (avoir) — `scripts/creditnote-create.sh`

View File

@@ -8,5 +8,6 @@
{ "desc": "Licence annuelle", "qty": 1, "price_ht": 100, "tva": 20, "type": "product" } ] } }, { "desc": "Licence annuelle", "qty": 1, "price_ht": 100, "tva": 20, "type": "product" } ] } },
{ "op": "payment", { "op": "payment",
"input": { "invoice_id": "@inv1", "mode": "VIR", "account_id": 1, "comment": "Acompte" } } "input": { "invoice_id": "@inv1", "mode": "VIR", "account_id": 1,
"transaction_id": "WISE-TX-2026-042", "comment": "Acompte" } }
] ]

View File

@@ -8,14 +8,17 @@
# account_id (required) the bank account id receiving/paying # account_id (required) the bank account id receiving/paying
# date "YYYY-MM-DD" (default today) # date "YYYY-MM-DD" (default today)
# amount (REQUIRED for supplier; customer pays the full remaining) # amount (REQUIRED for supplier; customer pays the full remaining)
# num (optional) the bank reference stored on the payment — put the # transaction_id (recommended) the originating bank transaction id (the Qonto/Wise
# Qonto/Wise transaction id here so the règlement reconciles to the feed # tx id from the feed). Stored on the payment's bank line
# (llx_bank.num_chq) so the règlement reconciles to the feed by id.
# `num` is a back-compat alias for the same field.
# comment (optional) # comment (optional)
# #
# The invoice must be VALIDATED first (invoice-create.sh ... "validate":true). # The invoice must be VALIDATED first (invoice-create.sh ... "validate":true).
# Emits {id, bank_transaction_id, num} on stdout. `bank_transaction_id` is the # Emits {id, bank_transaction_id, transaction_id} on stdout. `bank_transaction_id`
# Dolibarr bank line (llx_bank.fk_bank_line) the payment created — the id that bank # is the Dolibarr bank line (llx_bank.fk_bank_line) the payment created — the id
# reconciliation (bank-match) keys on to link this payment to a statement line. # bank reconciliation (arcodange-bank-reco) keys on to link this règlement to a
# statement line. Recording without a transaction_id warns (it won't auto-reconcile).
set -euo pipefail set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
W="${DOL_WRITE:-${SCRIPT_DIR}/dol-write.sh}" W="${DOL_WRITE:-${SCRIPT_DIR}/dol-write.sh}"
@@ -42,35 +45,39 @@ ds = d.get("date")
epoch = int((datetime.datetime.strptime(ds, "%Y-%m-%d") if ds epoch = int((datetime.datetime.strptime(ds, "%Y-%m-%d") if ds
else datetime.datetime.now()).timestamp()) else datetime.datetime.now()).timestamp())
inv = d["invoice_id"] inv = d["invoice_id"]
num = d.get("num", "") # transaction_id is the first-class bank-feed tx id; num is the back-compat alias.
tx = str(d.get("transaction_id") or d.get("num") or "")
if not tx:
sys.stderr.write("payment-record.sh: WARNING — no transaction_id given; this "
"règlement won't auto-reconcile to the bank feed\n")
if supplier: if supplier:
if d.get("amount") is None: if d.get("amount") is None:
sys.exit("payment-record.sh: supplier payments require an 'amount'") sys.exit("payment-record.sh: supplier payments require an 'amount'")
endpoint = "/supplierinvoices/%s/payments" % inv endpoint = "/supplierinvoices/%s/payments" % inv
body = {"datepaye": epoch, "payment_mode_id": mode, "closepaidinvoices": "yes", body = {"datepaye": epoch, "payment_mode_id": mode, "closepaidinvoices": "yes",
"accountid": d["account_id"], "accountid": d["account_id"],
"amount": str(d["amount"]), "num_payment": num, "amount": str(d["amount"]), "num_payment": tx,
"comment": d.get("comment", "")} "comment": d.get("comment", "")}
else: else:
endpoint = "/invoices/%s/payments" % inv endpoint = "/invoices/%s/payments" % inv
body = {"datepaye": epoch, "paymentid": mode, "closepaidinvoices": "yes", body = {"datepaye": epoch, "paymentid": mode, "closepaidinvoices": "yes",
"accountid": d["account_id"], "num_payment": num, "accountid": d["account_id"], "num_payment": tx,
"comment": d.get("comment", "")} "comment": d.get("comment", "")}
print(endpoint) print(endpoint)
print(json.dumps(body)) print(json.dumps(body))
print(num) print(tx)
PY PY
# Correlate the created payment back to its bank transaction line. The payments # Correlate the created payment back to its bank transaction line. The payments
# list carries fk_bank_line but not the paiement rowid, so match on the provided # list carries fk_bank_line but not the paiement rowid, so match on the provided
# num (the external bank ref), else fall back to the most recent line. # transaction_id (the external bank ref), else fall back to the most recent line.
cat > "${PYF2}" <<'PY' cat > "${PYF2}" <<'PY'
import json, sys, os import json, sys, os
rows = json.load(sys.stdin); rows = rows if isinstance(rows, list) else [] rows = json.load(sys.stdin); rows = rows if isinstance(rows, list) else []
num = os.environ.get("NUM", ""); pid = int(os.environ["PAYID"]) tx = os.environ.get("TX", ""); pid = int(os.environ["PAYID"])
pick = None pick = None
if num: if tx:
cand = [r for r in rows if str(r.get("num", "")) == num] cand = [r for r in rows if str(r.get("num", "")) == tx]
if cand: if cand:
pick = cand[-1] pick = cand[-1]
if pick is None and rows: if pick is None and rows:
@@ -78,13 +85,13 @@ if pick is None and rows:
btx = (pick or {}).get("fk_bank_line") btx = (pick or {}).get("fk_bank_line")
print(json.dumps({"id": pid, print(json.dumps({"id": pid,
"bank_transaction_id": int(btx) if btx and str(btx).isdigit() else btx, "bank_transaction_id": int(btx) if btx and str(btx).isdigit() else btx,
"num": (pick or {}).get("num", "")})) "transaction_id": (pick or {}).get("num", "")}))
PY PY
MAPPED="$(printf '%s' "${INPUT}" | python3 "${PYF}")" MAPPED="$(printf '%s' "${INPUT}" | python3 "${PYF}")"
ENDPOINT="$(sed -n 1p <<<"${MAPPED}")" ENDPOINT="$(sed -n 1p <<<"${MAPPED}")"
BODY="$(sed -n 2p <<<"${MAPPED}")" BODY="$(sed -n 2p <<<"${MAPPED}")"
NUM="$(sed -n 3p <<<"${MAPPED}")" TX="$(sed -n 3p <<<"${MAPPED}")"
PAYID="$("${W}" POST "${ENDPOINT}" "${BODY}")" PAYID="$("${W}" POST "${ENDPOINT}" "${BODY}")"
if [[ ! "${PAYID}" =~ ^[0-9]+$ ]]; then if [[ ! "${PAYID}" =~ ^[0-9]+$ ]]; then
@@ -93,4 +100,4 @@ if [[ ! "${PAYID}" =~ ^[0-9]+$ ]]; then
fi fi
# Same path serves the GET list; resolve fk_bank_line and emit the enriched record. # Same path serves the GET list; resolve fk_bank_line and emit the enriched record.
"${W}" GET "${ENDPOINT}" | PAYID="${PAYID}" NUM="${NUM}" python3 "${PYF2}" "${W}" GET "${ENDPOINT}" | PAYID="${PAYID}" TX="${TX}" python3 "${PYF2}"

View File

@@ -31,8 +31,10 @@ for i, op in enumerate(ops, 1):
print(" - %r qty=%s pu_ht=%s tva=%s%%" % (ln.get("desc", ""), ln.get("qty", 1), print(" - %r qty=%s pu_ht=%s tva=%s%%" % (ln.get("desc", ""), ln.get("qty", 1),
ln.get("price_ht", ln.get("subprice")), ln.get("tva", ln.get("tva_tx", 20)))) ln.get("price_ht", ln.get("subprice")), ln.get("tva", ln.get("tva_tx", 20))))
elif t == "payment": elif t == "payment":
print(" invoice=%s mode=%s account=%s %s" % (inp.get("invoice_id"), inp.get("mode", "VIR"), txid = inp.get("transaction_id") or inp.get("num")
inp.get("account_id"), ("amount=%s" % inp["amount"]) if inp.get("amount") else "(full)")) print(" invoice=%s mode=%s account=%s %s%s" % (inp.get("invoice_id"), inp.get("mode", "VIR"),
inp.get("account_id"), ("amount=%s" % inp["amount"]) if inp.get("amount") else "(full)",
(" tx=%s" % txid) if txid else " tx=MISSING"))
print("\nNext:") print("\nNext:")
print(" promote-apply.sh <manifest> --target sandbox # rehearse the replay (safe)") print(" promote-apply.sh <manifest> --target sandbox # rehearse the replay (safe)")
print(" promote-apply.sh <manifest> --target prod # WRITES PROD — needs DOLIBARR_PROD_WRITE_KEY") print(" promote-apply.sh <manifest> --target prod # WRITES PROD — needs DOLIBARR_PROD_WRITE_KEY")

View File

@@ -85,7 +85,7 @@ COMMANDS
sandbox WRITE ops on erp-sandbox ONLY (host-guarded; JSON on stdin) sandbox WRITE ops on erp-sandbox ONLY (host-guarded; JSON on stdin)
thirdparty Create a client/supplier fiche thirdparty Create a client/supplier fiche
invoice Customer/supplier invoice + product/service lines invoice Customer/supplier invoice + product/service lines
payment Record a règlement (num=bank tx id) → bank_transaction_id payment Record a règlement (transaction_id=bank tx) → bank_transaction_id
creditnote Create an avoir — customer or supplier (kind) creditnote Create an avoir — customer or supplier (kind)
accounts List bank accounts (id/label) to pick account_id accounts List bank accounts (id/label) to pick account_id
write <METHOD> <path> [body] Raw host-guarded write write <METHOD> <path> [body] Raw host-guarded write