#!/usr/bin/env bash # Record a payment (règlement) on a validated invoice in the SANDBOX. # # Input: a JSON object on stdin (or a file path in $1): # invoice_id (required) the invoice to pay # kind "customer" | "supplier" (default "customer") # mode "VIR" | "CB" | "CHQ" | "LIQ" (default "VIR") # account_id (required) the bank account id receiving/paying # date "YYYY-MM-DD" (default today) # amount (REQUIRED for supplier; customer pays the full remaining) # transaction_id (recommended) the originating bank transaction id (the Qonto/Wise # 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. # NORMALIZED before POST: Dolibarr stores num_payment in varchar(50) # (llx_paiement.num_paiement / llx_paiementfourn.num_paiement) while # Qonto ids run ~67 chars (---transaction-), so # everything through "transaction-" is stripped and the UUID suffix # (globally unique, ~37 chars) is the canonical stored form. Wise ids # (short numerics) pass through unchanged. An id still >50 chars after # normalization is REFUSED with an error — never truncated silently. # comment (optional) # # The invoice must be VALIDATED first (invoice-create.sh ... "validate":true). # Emits {id, bank_transaction_id, transaction_id} on stdout — `transaction_id` is # the NORMALIZED num actually stored (what bank-match keys on). `bank_transaction_id` # is the Dolibarr bank line (llx_bank.fk_bank_line) the payment created — the id # 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 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" W="${DOL_WRITE:-${SCRIPT_DIR}/dol-write.sh}" SRC="${1:-}" if [[ -n "${SRC}" && "${SRC}" != "-" ]]; then INPUT="$(cat "${SRC}")"; else INPUT="$(cat)"; fi PYF="$(mktemp -t dolpy.XXXXXX)"; PYF2="$(mktemp -t dolpy2.XXXXXX)" trap 'rm -f "${PYF}" "${PYF2}"' EXIT cat > "${PYF}" <<'PY' import json, sys, datetime, re d = json.loads(sys.stdin.read()) if not d.get("invoice_id"): sys.exit("payment-record.sh: 'invoice_id' is required") if not d.get("account_id"): sys.exit("payment-record.sh: 'account_id' is required") # Stable Dolibarr c_paiement ids (sandbox seeded from prod / standard defaults). MODE = {"VIR": 2, "CB": 6, "CHQ": 7, "LIQ": 4} mode = MODE.get(str(d.get("mode", "VIR")).upper()) if mode is None: sys.exit("payment-record.sh: unknown mode (use VIR|CB|CHQ|LIQ)") supplier = d.get("kind", "customer").lower() in ("supplier", "fournisseur") ds = d.get("date") epoch = int((datetime.datetime.strptime(ds, "%Y-%m-%d") if ds else datetime.datetime.now()).timestamp()) inv = d["invoice_id"] # transaction_id is the first-class bank-feed tx id; num is the back-compat alias. raw_tx = str(d.get("transaction_id") or d.get("num") or "") # Normalize to the canonical short form. Dolibarr stores num_payment in # varchar(50) (llx_paiement.num_paiement / llx_paiementfourn.num_paiement) and # a Qonto id (~67 chars, ---transaction-) blows past it — # HTTP 400 "value too long for type character varying(50)". Strip everything # through "transaction-" and store the UUID suffix (globally unique). Wise ids # (short numerics, no "transaction-") pass through unchanged. bank-match.sh # normalizes feed ids the same way, so the short form still reconciles by id. tx = re.sub(r'^.*transaction-', '', raw_tx) if tx != raw_tx: sys.stderr.write("payment-record.sh: transaction_id normalized to %r " "(Qonto prefix stripped — num_payment is varchar(50))\n" % tx) if len(tx) > 50: sys.exit("payment-record.sh: transaction_id %r is %d chars even after " "normalization — Dolibarr's num_payment is varchar(50) and silent " "truncation would break bank reconciliation; pass a shorter id" % (tx, len(tx))) 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 d.get("amount") is None: sys.exit("payment-record.sh: supplier payments require an 'amount'") endpoint = "/supplierinvoices/%s/payments" % inv body = {"datepaye": epoch, "payment_mode_id": mode, "closepaidinvoices": "yes", "accountid": d["account_id"], "amount": str(d["amount"]), "num_payment": tx, "comment": d.get("comment", "")} else: endpoint = "/invoices/%s/payments" % inv body = {"datepaye": epoch, "paymentid": mode, "closepaidinvoices": "yes", "accountid": d["account_id"], "num_payment": tx, "comment": d.get("comment", "")} print(endpoint) print(json.dumps(body)) print(tx) PY # 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 # transaction_id (the external bank ref), else fall back to the most recent line. cat > "${PYF2}" <<'PY' import json, sys, os rows = json.load(sys.stdin); rows = rows if isinstance(rows, list) else [] tx = os.environ.get("TX", ""); pid = int(os.environ["PAYID"]) pick = None if tx: cand = [r for r in rows if str(r.get("num", "")) == tx] if cand: pick = cand[-1] if pick is None and rows: pick = max(rows, key=lambda r: r.get("date", "")) btx = (pick or {}).get("fk_bank_line") # transaction_id: the num as stored (normalized) — fall back to the sent TX so # the JSON always reports the canonical short form even on the recency fallback. print(json.dumps({"id": pid, "bank_transaction_id": int(btx) if btx and str(btx).isdigit() else btx, "transaction_id": (pick or {}).get("num", "") or tx})) PY MAPPED="$(printf '%s' "${INPUT}" | python3 "${PYF}")" ENDPOINT="$(sed -n 1p <<<"${MAPPED}")" BODY="$(sed -n 2p <<<"${MAPPED}")" TX="$(sed -n 3p <<<"${MAPPED}")" PAYID="$("${W}" POST "${ENDPOINT}" "${BODY}")" if [[ ! "${PAYID}" =~ ^[0-9]+$ ]]; then echo "payment-record.sh: payment POST did not return an id: ${PAYID}" >&2 exit 1 fi # Same path serves the GET list; resolve fk_bank_line and emit the enriched record. "${W}" GET "${ENDPOINT}" | PAYID="${PAYID}" TX="${TX}" python3 "${PYF2}"