feat(skills): dolibarr-sandbox-write — host-guarded write skill (V9)

The write-capable companion to the read-only dolibarr* skills, scoped to the
erp-sandbox. Lets an AI agent rehearse bookkeeping writes against a copy of prod
(ADR-0003) before a human promotes the reviewed change to prod.

- scripts/dol-write.sh: write wrapper that REFUSES any host that is not
  erp-sandbox.arcodange.lab (the structural prod-safety guarantee) using the
  ai_agent_sandbox key from a gitignored .env.
- scripts/thirdparty-create.sh: create client/supplier fiches; codes auto-assign
  via the elephant mask (code="-1").
- scripts/invoice-create.sh: customer (/invoices) or supplier (/supplierinvoices)
  invoices with product/service lines + ref_supplier, optional validate.
- scripts/payment-record.sh: record a règlement (VIR/CB/CHQ/LIQ); customer pays
  full + marks paid, supplier needs an amount.
- SKILL.md (safety model + workflows + the human-gated promote flow), .env.example,
  example input.

Proven end-to-end live against the sandbox: client -> invoice (service+product
lines, HT 1100 / TTC 1320) -> validate -> payment (paid); supplier -> supplier
invoice (ref_supplier carried) -> validate. Host guard verified to refuse a prod
URL before sending.

Avoirs (credit notes) and bin/arcodange CLI wiring are planned follow-ups.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-29 20:49:31 +02:00
parent 2154bf319e
commit d2e8b3a3a4
7 changed files with 395 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Host-guarded WRITE wrapper for the Arcodange Dolibarr SANDBOX API.
#
# THE GUARANTEE (ADR-0003): this wrapper REFUSES to run against anything that is
# not the erp-sandbox host. It is the structural reason an AI agent driving this
# skill can never mutate production — prod is a different host, and the guard
# below rejects it before any request is sent.
#
# Usage:
# dol-write.sh <METHOD> <path> [json-body|@file]
# dol-write.sh POST /thirdparties '{"name":"Acme","client":"1"}'
# dol-write.sh POST /invoices @invoice.json
# dol-write.sh PUT /thirdparties/42 '{"phone":"+33..."}'
# dol-write.sh GET /thirdparties?limit=5 # reads are allowed too
#
# Reads DOLIBARR_SANDBOX_URL + DOLIBARR_SANDBOX_API_KEY from the sibling .env
# (.claude/skills/dolibarr-sandbox-write/.env), mode 600, gitignored.
# Prints the response body to stdout; exits non-zero on HTTP >= 400.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${SCRIPT_DIR}/../.env"
if [[ ! -f "${ENV_FILE}" ]]; then
echo "dol-write.sh: missing ${ENV_FILE}" >&2
echo " Create it with DOLIBARR_SANDBOX_URL + DOLIBARR_SANDBOX_API_KEY. See README.md." >&2
exit 2
fi
# shellcheck disable=SC1090
set -a; source "${ENV_FILE}"; set +a
: "${DOLIBARR_SANDBOX_URL:?dol-write.sh: DOLIBARR_SANDBOX_URL not set in .env}"
: "${DOLIBARR_SANDBOX_API_KEY:?dol-write.sh: DOLIBARR_SANDBOX_API_KEY not set in .env}"
# ---------------------------------------------------------------------------
# HOST GUARD — the structural safety invariant. Only the sandbox host passes.
# Override the allowed pattern only via DOLIBARR_SANDBOX_HOST_RE in .env if the
# sandbox FQDN ever changes; never widen it to include a prod host.
# ---------------------------------------------------------------------------
ALLOWED_RE="${DOLIBARR_SANDBOX_HOST_RE:-^https://erp-sandbox\.arcodange\.lab(/|$)}"
if [[ ! "${DOLIBARR_SANDBOX_URL}" =~ ${ALLOWED_RE} ]]; then
echo "dol-write.sh: REFUSING to write — DOLIBARR_SANDBOX_URL='${DOLIBARR_SANDBOX_URL}'" >&2
echo " is not the erp-sandbox host (allowed: ${ALLOWED_RE})." >&2
echo " This skill only writes the sandbox. Promotion to prod is a separate, human-gated step." >&2
exit 3
fi
if [[ $# -lt 2 ]]; then
echo "dol-write.sh: usage: dol-write.sh <METHOD> <path> [json-body|@file]" >&2
exit 2
fi
METHOD="$1"; API_PATH="$2"; BODY="${3-}"
case "${METHOD}" in
GET|POST|PUT|DELETE|PATCH) ;;
*) echo "dol-write.sh: unsupported method '${METHOD}'" >&2; exit 2 ;;
esac
CURL_ARGS=(
-sS -X "${METHOD}"
-H "DOLAPIKEY: ${DOLIBARR_SANDBOX_API_KEY}"
-H "Accept: application/json"
--max-time 30
)
if [[ -n "${BODY}" ]]; then
# curl --data supports '@file' to read a JSON body from a file.
CURL_ARGS+=( -H "Content-Type: application/json" --data "${BODY}" )
fi
BODY_FILE="$(mktemp -t dolwrite.XXXXXX)"
trap 'rm -f "${BODY_FILE}"' EXIT
HTTP_CODE=$(curl "${CURL_ARGS[@]}" \
-o "${BODY_FILE}" -w "%{http_code}" \
"${DOLIBARR_SANDBOX_URL}/api/index.php${API_PATH}")
cat "${BODY_FILE}"
if [[ "${HTTP_CODE}" -ge 400 ]]; then
echo "" >&2
echo "dol-write.sh: HTTP ${HTTP_CODE} on ${METHOD} ${API_PATH}" >&2
exit 1
fi

View File

@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Create a customer or supplier invoice (facture) with product/service lines in
# the SANDBOX, optionally validating it.
#
# Input: a JSON object on stdin (or a file path in $1):
# socid (required) thirdparty id
# kind "customer" | "supplier" (default "customer")
# date "YYYY-MM-DD" (default today)
# ref_supplier supplier's own invoice ref (supplier invoices)
# validate true|false (default false = leave draft)
# lines: [ { desc, qty, price_ht, tva, type: "product"|"service", product_id? } ]
#
# Emits {id, ref, ref_supplier, total_ht, total_ttc, statut} on stdout.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
W="${SCRIPT_DIR}/dol-write.sh"
SRC="${1:-}"
if [[ -n "${SRC}" && "${SRC}" != "-" ]]; then INPUT="$(cat "${SRC}")"; else INPUT="$(cat)"; fi
PYF="$(mktemp -t dolpy.XXXXXX)"; trap 'rm -f "${PYF}"' EXIT
cat > "${PYF}" <<'PY'
import json, sys, datetime
d = json.loads(sys.stdin.read())
if not d.get("socid"):
sys.exit("invoice-create.sh: 'socid' is required")
supplier = d.get("kind", "customer").lower() in ("supplier", "fournisseur")
endpoint = "/supplierinvoices" if supplier else "/invoices"
ds = d.get("date")
epoch = int((datetime.datetime.strptime(ds, "%Y-%m-%d") if ds
else datetime.datetime.now()).timestamp())
lines = []
for ln in d.get("lines", []):
is_product = ln.get("type", "service").lower() in ("product", "produit")
L = {
"desc": ln.get("desc", ""),
"subprice": str(ln.get("price_ht", ln.get("subprice", 0))),
"qty": str(ln.get("qty", 1)),
"tva_tx": str(ln.get("tva", ln.get("tva_tx", 20))),
"product_type": "0" if is_product else "1",
}
if ln.get("product_id"):
L["fk_product"] = str(ln["product_id"])
lines.append(L)
body = {"socid": d["socid"], "date": epoch, "type": 0, "lines": lines}
if supplier and d.get("ref_supplier"):
body["ref_supplier"] = d["ref_supplier"]
print(endpoint)
print(json.dumps(body))
print("1" if d.get("validate") else "0")
PY
MAPPED="$(printf '%s' "${INPUT}" | python3 "${PYF}")"
ENDPOINT="$(sed -n 1p <<<"${MAPPED}")"
BODY="$(sed -n 2p <<<"${MAPPED}")"
VALIDATE="$(sed -n 3p <<<"${MAPPED}")"
ID="$("${W}" POST "${ENDPOINT}" "${BODY}")"
if [[ ! "${ID}" =~ ^[0-9]+$ ]]; then
echo "invoice-create.sh: create did not return an id: ${ID}" >&2
exit 1
fi
if [[ "${VALIDATE}" == "1" ]]; then
"${W}" POST "${ENDPOINT}/${ID}/validate" '{}' >/dev/null
fi
"${W}" GET "${ENDPOINT}/${ID}" | python3 -c "import json,sys
d=json.load(sys.stdin)
print(json.dumps({k:d.get(k) for k in ('id','ref','ref_supplier','total_ht','total_ttc','statut')}))"

View File

@@ -0,0 +1,59 @@
#!/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)
# num, comment (optional)
#
# The invoice must be VALIDATED first (invoice-create.sh ... "validate":true).
# Emits the new payment id on stdout.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
W="${SCRIPT_DIR}/dol-write.sh"
SRC="${1:-}"
if [[ -n "${SRC}" && "${SRC}" != "-" ]]; then INPUT="$(cat "${SRC}")"; else INPUT="$(cat)"; fi
PYF="$(mktemp -t dolpy.XXXXXX)"; trap 'rm -f "${PYF}"' EXIT
cat > "${PYF}" <<'PY'
import json, sys, datetime
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"]
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, "paymentid": mode, "accountid": d["account_id"],
"amount": str(d["amount"]), "num_payment": d.get("num", ""),
"comment": d.get("comment", "")}
else:
endpoint = "/invoices/%s/payments" % inv
body = {"datepaye": epoch, "paymentid": mode, "closepaidinvoices": "yes",
"accountid": d["account_id"], "num_payment": d.get("num", ""),
"comment": d.get("comment", "")}
print(endpoint)
print(json.dumps(body))
PY
MAPPED="$(printf '%s' "${INPUT}" | python3 "${PYF}")"
ENDPOINT="$(sed -n 1p <<<"${MAPPED}")"
BODY="$(sed -n 2p <<<"${MAPPED}")"
"${W}" POST "${ENDPOINT}" "${BODY}"

View File

@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# Create a client and/or supplier thirdparty (fiche tiers) in the SANDBOX.
#
# Input: a JSON object on stdin (or a file path in $1). Fields:
# name (required)
# role "client" | "supplier" | "both" (default "client")
# country_id numeric, default 1 (France)
# client_code / supplier_code default "-1" = auto-generate via the code mask
# siret, tva_intra, address, zip, town, email, phone, idprof1 (optional)
#
# Emits the new thirdparty id on stdout. All writes go through dol-write.sh,
# which refuses any host that is not the sandbox.
#
# Examples:
# echo '{"name":"KissMetrics","role":"client","tva_intra":"US.."}' | thirdparty-create.sh
# thirdparty-create.sh fournisseur.json
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
W="${SCRIPT_DIR}/dol-write.sh"
SRC="${1:-}"
if [[ -n "${SRC}" && "${SRC}" != "-" ]]; then INPUT="$(cat "${SRC}")"; else INPUT="$(cat)"; fi
PYF="$(mktemp -t dolpy.XXXXXX)"; trap 'rm -f "${PYF}"' EXIT
cat > "${PYF}" <<'PY'
import json, sys
d = json.loads(sys.stdin.read())
if not d.get("name"):
sys.exit("thirdparty-create.sh: 'name' is required")
role = d.get("role", "client").lower()
is_client = role in ("client", "both")
is_supp = role in ("supplier", "fournisseur", "both")
body = {
"name": d["name"],
"client": "1" if is_client else "0",
"fournisseur": "1" if is_supp else "0",
"country_id": str(d.get("country_id", 1)),
# "-1" => Dolibarr auto-assigns the next code from the mask
# (COMPANY_ELEPHANT_MASK_CUSTOMER / _SUPPLIER); "0" when that role is off.
"code_client": (d.get("client_code", "-1") if is_client else "0"),
"code_fournisseur": (d.get("supplier_code", "-1") if is_supp else "0"),
}
for k in ("siret", "tva_intra", "address", "zip", "town", "email", "phone", "idprof1"):
if d.get(k):
body[k] = d[k]
print(json.dumps(body))
PY
BODY="$(printf '%s' "${INPUT}" | python3 "${PYF}")"
"${W}" POST /thirdparties "${BODY}"