Files
Khaemhat/docs/API.md
T
Alby96andClaude Opus 5.5 e746d99dab docs: add specification, design docs, mockups, wiki and deploy files
Prepare everything needed before development starts on Khaemhat, the
ERP + CRM for Italian SMEs:

- docs/SPEC.md: the original project specification, unchanged, plus
  CLAUDE.md with operational rules and amendments (Gitea instead of
  GitHub/GHCR, Docker image as the only deliverable).
- ADR 0001-0011 for the baseline decisions.
- Mockups: 22 high-resolution screens, the full gallery, 88 thumbnails
  cropped from it, mockup.css and an index.
- Technical docs (architecture, data model, modules, API, MCP, deploy,
  security, development process, status with open spec questions).
- Full draft wiki in docs/wiki (already published to the Gitea wiki).
- Icons in assets/ and deploy files for Docker Compose and Unraid,
  pointing to the Gitea package registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 22:26:58 +01:00

309 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# REST API `/api/v1`
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §7.3, §8.1, §9.5, §11.11, §12.1, §15; mockup 088
Questo documento è il contratto previsto dell'API REST di Khaemhat, realizzata in **M12** (`v0.12.0`) con Minimal
API di ASP.NET Core, senza librerie esterne. Ogni modifica a endpoint, parametri o formati aggiorna questo file,
la wiki ([API](wiki/API.md)) e `CHANGELOG.md` nello stesso commit (SPEC §17).
Le parti marcate **(proposta)** non sono fissate da SPEC: sono la soluzione suggerita per chi sviluppa e vanno
confermate (o cambiate con un ADR) in M12.
Documenti collegati: [MCP.md](MCP.md) · [MODULES.md](MODULES.md) · [ARCHITECTURE.md](ARCHITECTURE.md) §6.2.
---
## 1. Principi
| Aspetto | Regola | Fonte |
|---|---|---|
| Base | `/api/v1/{modulo}/{risorsa}` | SPEC §15 |
| Formato | JSON `camelCase` (`System.Text.Json`), UTF-8; date `yyyy-MM-dd`, istanti ISO 8601 UTC, importi come numero decimale | SPEC §15, §19 |
| Licenza | richiede il modulo `API`; gli endpoint di un modulo non licenziato **non sono registrati** | SPEC §8.1 |
| Permessi | ogni endpoint dichiara `[RequireModule]` e `[RequirePermission]`; il server verifica sempre | SPEC §7.2 |
| Errori | RFC 9457 (`application/problem+json`) con trace id | SPEC §15 |
| Concorrenza | ETag / `If-Match` su `row_version` | SPEC §5.2, §15 |
| Idempotenza | header `Idempotency-Key` sulle creazioni | SPEC §15 |
| Limiti | rate limiting per chiave | SPEC §15 |
| Documentazione | OpenAPI 3.1 generato in casa su `/api/v1/openapi.json` + pagina `/api/docs` | SPEC §15 |
## 2. Autenticazione
### 2.1 Chiave API (consigliata per le integrazioni)
```
Authorization: Bearer kh_<chiave>
```
- Le chiavi hanno prefisso `kh_`; nel database si conserva solo l'**hash SHA-256** e il **prefisso visibile** (per
riconoscerle nell'elenco del mockup 088). La chiave completa è mostrata **una sola volta** alla creazione.
- Ogni chiave è legata a un **utente tecnico** (`users.kind = Technical`), ha **permessi propri**, un'**azienda**,
una **scadenza** e un elenco di **IP consentiti** (SPEC §7.3).
- Chiavi aziendali in `api_keys` (database dell'azienda); chiavi di istanza in `sys_api_keys` (database di sistema).
- Gestione: *Amministrazione › Chiavi API, MCP e webhook* (mockup 088), servizio `ApiKeyService`.
- L'utente collegato deve avere il flag "può usare le API" (SPEC §7.2).
### 2.2 Cookie di sessione
Le chiamate dal browser già autenticato (stessa origine) possono usare il cookie di sessione di Khaemhat
(`HttpOnly; Secure; SameSite=Lax`). Le richieste che modificano dati con autenticazione a cookie richiedono il
token antiforgery **(proposta)**, per evitare CSRF.
### 2.3 Azienda: header `X-Company`
```
X-Company: DEMO
```
- Indica il codice dell'azienda (quello di `sys_companies.code`) su cui opera la richiesta; popola
`ICompanyContext`.
- Con una **chiave aziendale** l'header è facoltativo; se presente deve coincidere con l'azienda della chiave,
altrimenti `403` **(proposta)**.
- Con una **chiave di istanza** o con il cookie di un account di istanza è **obbligatorio** per le risorse
aziendali; manca → `400` con `code: company_required` **(proposta)**.
- Azienda in **manutenzione** → `503 Service Unavailable` con `Retry-After` (SPEC §12.1); azienda in **sola
lettura** → le scritture rispondono `409` con `code: company_read_only` **(proposta)**.
## 3. Elenchi: paginazione, ordinamento, filtri
```
GET /api/v1/parties?page=2&pageSize=50&sort=-updatedAt,name&filter=kind eq 'Customer' and disabled eq false
```
| Parametro | Significato | Default / limiti |
|---|---|---|
| `page` | pagina, da 1 | 1 |
| `pageSize` | righe per pagina | 50; massimo 500 **(proposta)** |
| `sort` | campi separati da virgola; `-` davanti = decrescente | ordinamento naturale della risorsa |
| `filter` | espressione di filtro | nessuno |
**Sintassi del filtro (proposta).** SPEC non la definisce. Si propone un sottoinsieme che si traduce direttamente
nelle espressioni sicure di `QueryBuilder<T>` (SPEC §5.2): operatori `eq`, `ne`, `gt`, `ge`, `lt`, `le`,
`contains`, `startswith`, `in`, `isnull`; connettivi `and`, `or`, `not`, parentesi; stringhe tra apici singoli,
date `yyyy-MM-dd`. Esempi: `date ge 2026-01-01 and status in ('Issued','SdiDelivered')`,
`contains(name,'demo')`. I campi filtrabili e ordinabili sono dichiarati per risorsa nell'OpenAPI; un campo non
ammesso dà `400`.
Risposta di un elenco (forma di `PagedResult<T>`):
```json
{
"items": [ { "id": 1042, "code": "C000042", "name": "Alfa Beta S.r.l.", "kind": "Customer" } ],
"page": 2,
"pageSize": 50,
"totalCount": 213
}
```
## 4. Errori (RFC 9457)
Tutti gli errori hanno `Content-Type: application/problem+json` e sono prodotti da `ProblemDetailsMiddleware`:
```json
{
"type": "https://gestionale.example.com/api/problems/validation",
"title": "Dati non validi",
"status": 400,
"detail": "La partita IVA non è valida.",
"instance": "/api/v1/parties",
"code": "validation_failed",
"traceId": "4f1c2a9e7b3d4c10",
"errors": { "vatNumber": [ "Il carattere di controllo non è corretto." ] }
}
```
- **`traceId`**: è il `trace_id` del log (SPEC §9.5), lo stesso mostrato all'utente come "Codice errore"; con esso
un amministratore trova l'evento in *Amministrazione › Log*. Il nome del membro JSON segue la convenzione
`camelCase` dell'API **(proposta)**.
- **`code`**: codice stabile leggibile da programma (estensione RFC 9457). Codici già definiti in SPEC:
`module_not_licensed`, `license_test_only`. Gli altri sotto sono **proposte**.
- I testi di `title` e `detail` sono localizzati in italiano tramite `ITexts`.
| Stato | Quando | `code` |
|---|---|---|
| `400` | parametri o corpo non validi, filtro non ammesso | `validation_failed`, `invalid_filter`, `company_required` |
| `401` | chiave assente, errata, scaduta o IP non consentito | `unauthenticated` |
| `403` | permesso mancante, modulo non licenziato | `permission_denied`, `module_not_licensed` |
| `404` | risorsa inesistente nell'azienda | `not_found` |
| `409` | conflitto di stato (fattura già emessa, periodo bloccato, azienda in sola lettura), concorrenza senza `If-Match` | `conflict`, `period_locked`, `company_read_only` |
| `412` | `If-Match` non corrisponde all'ETag corrente | `precondition_failed` |
| `422` | regola di dominio violata (es. registrazione non quadrata da rendere definitiva) | `domain_rule` |
| `428` | `If-Match` mancante su `PUT`/`PATCH`/`DELETE` **(proposta)** | `precondition_required` |
| `429` | limite di richieste superato; header `Retry-After` | `rate_limited` |
| `503` | azienda o istanza in manutenzione; header `Retry-After` | `maintenance` |
## 5. Concorrenza: ETag e `If-Match`
- Ogni risorsa singola restituisce `ETag` calcolato da `row_version` (es. `ETag: "17"`).
- `PUT`, `PATCH` e `DELETE` richiedono `If-Match: "<etag>"`; il repository esegue
`UPDATE … WHERE id = @id AND row_version = @v`. Se nel frattempo un altro utente ha salvato →
`412 Precondition Failed` (nessuna modifica applicata).
- `GET` con `If-None-Match` può rispondere `304 Not Modified` **(proposta)**.
## 6. Idempotenza: `Idempotency-Key`
```
POST /api/v1/sale-orders
Idempotency-Key: 6c0e2b9a-3f7d-4d1e-9a51-2a8f1c0d7e44
```
- Consigliato su tutte le `POST` che creano risorse (ordini, anagrafiche, pagamenti, upload).
- Il server registra chiave + hash del corpo + risposta: una seconda richiesta con la stessa chiave e lo stesso corpo
restituisce la **stessa risposta** senza creare duplicati; stessa chiave con corpo diverso → `422`
`code: idempotency_mismatch`.
- Conservazione delle chiavi: 24 ore **(proposta)**; serve una tabella aziendale dedicata, non ancora presente in
[DATA-MODEL.md](DATA-MODEL.md) (da aggiungere in M12).
## 7. Rate limiting
- Limiti **per chiave API** (e per IP su `/login` e `/api` senza autenticazione valida), con il rate limiter di
piattaforma ASP.NET Core.
- Soglie configurabili da *Amministrazione › Impostazioni › Sicurezza* (SPEC §12.9); valori predefiniti da definire
in sviluppo.
- Superamento → `429` con `Retry-After`. Header informativi `RateLimit-Limit`, `RateLimit-Remaining` **(proposta)**.
## 8. Risorse previste
Elenco delle risorse di SPEC §15 con i metodi **previsti** (da confermare in M12). Percorsi relativi a
`/api/v1`. "Licenza" indica il modulo necessario oltre a `API`.
| Risorsa | Metodi | Licenza | Permesso indicativo | Note |
|---|---|---|---|---|
| `parties` | `GET` (elenco), `POST` | CORE | `parties.party.read` / `write` | clienti, fornitori, prospect (`kind`) |
| `parties/{id}` | `GET`, `PUT`, `DELETE` | CORE | `parties.party.write` / `delete` | `DELETE` disabilita se esistono documenti |
| `items`, `items/{id}` | `GET`, `POST`, `PUT`, `DELETE` | CORE | `items.item.*` | costi visibili solo con `items.cost.read` |
| `price-lists`, `price-lists/{id}` | `GET`, `POST`, `PUT` | CORE | `items.price_list.*` | righe listino × articolo |
| `sale-orders`, `sale-orders/{id}` | `GET`, `POST`, `PUT`, `DELETE` (solo bozza) | CORE | `sales.order.*` | |
| `sale-orders/{id}/confirm` | `POST` | CORE | `sales.order.write` | azione di stato **(proposta)** |
| `delivery-notes`, `delivery-notes/{id}` | `GET`, `POST` | CORE | `sales.delivery_note.*` | |
| `invoices`, `invoices/{id}` | `GET`, `POST` (bozza), `PUT` (bozza) | CORE | `sales.invoice.*` | fattura emessa immutabile |
| `invoices/{id}/issue` | `POST` | CORE | **`sales.invoice.issue`** | numerazione e contabilizzazione **(proposta)** |
| `purchase-orders`, `purchase-orders/{id}` | `GET`, `POST`, `PUT` | CORE | `purchases.order.*` | |
| `purchase-invoices`, `purchase-invoices/{id}` | `GET`, `POST` | CORE | `purchases.invoice.*` | anche da XML importato |
| `inventory/balances` | `GET` | CORE | `inventory.balance.read` | giacenza, impegnato, ordinato, disponibile per articolo × deposito |
| `inventory/entries`, `inventory/entries/{id}` | `GET`, `POST` | CORE | **`inventory.entry.post`** | movimenti manuali |
| `ledger/accounts`, `ledger/accounts/{id}` | `GET` | ACCT | `ledger.account.read` | piano dei conti e saldi |
| `ledger/entries`, `ledger/entries/{id}` | `GET`, `POST` (provvisoria) | ACCT | `ledger.entry.*` | definitiva con **`ledger.entry.finalize`** |
| `open-items` | `GET` | FIN | `finance.open_item.read` | partite aperte, aging |
| `payments`, `payments/{id}` | `GET`, `POST` | FIN | `finance.payment.write` | incassi/pagamenti con righe su partite |
| `e-invoices`, `e-invoices/{id}` | `GET` | EINV | `einvoicing.invoice.read` | stato SDI, notifiche, canale |
| `attachments/{id}` | `GET` (download) | CORE | permesso di lettura del documento | `Content-Disposition: attachment` |
| `{risorsa}/{id}/attachments` | `GET`, `POST` (upload) | CORE | permesso di scrittura del documento | upload su **un** documento (SPEC §9.4); `multipart/form-data` |
| `crm/leads`, `crm/leads/{id}` | `GET`, `POST`, `PUT` | CRM | `crm.lead.*` | anche dal form del sito web |
| `crm/opportunities`, `crm/opportunities/{id}` | `GET`, `POST`, `PUT` | CRM | **`crm.opportunity.write`** | |
| `crm/activities`, `crm/activities/{id}` | `GET`, `POST`, `PUT` | CRM | `crm.activity.*` | |
| `channels/{code}/orders` | `POST`, `GET` | CHAN | `channels.order.import` | connettore generico (SPEC §11.11) |
| `reports/{code}` | `GET` | CORE / REPORT | `reports.report.read` | parametri in query; `Accept` JSON, CSV, XLSX o PDF **(proposta)** |
| `admin/status` | `GET` | — | account di istanza | **sola lettura**: stato, versione, controlli |
Il percorso SPEC `/api/v1/{modulo}/{risorsa}` è applicato letteralmente all'elenco di SPEC §15: alcune risorse hanno
il prefisso di modulo (`inventory/…`, `ledger/…`, `crm/…`, `channels/…`, `reports/…`, `admin/…`), altre no
(`parties`, `invoices`, …). Uniformare (per esempio `sales/invoices`) è una decisione da prendere con ADR prima di
pubblicare `v1`.
Endpoint non versionati dell'host (non fanno parte di `/api/v1`): `/health/live` (healthcheck del container),
`/health` e la metrica `MetricsEndpoint` (SPEC §21).
## 9. OpenAPI e documentazione
- `GET /api/v1/openapi.json`: documento **OpenAPI 3.1** generato in casa da `OpenApiWriter` a partire dagli endpoint
registrati; contiene solo i moduli licenziati e gli schemi dei DTO.
- `GET /api/docs`: pagina di documentazione navigabile (`ApiDocsPage`) servita dall'app, senza librerie esterne
né CDN.
- Il documento dichiara lo schema di sicurezza `bearerAuth` (HTTP bearer) e il parametro di header `X-Company`.
## 10. Webhook in uscita
Configurati in *Amministrazione › Chiavi API, MCP e webhook* (mockup 088, entità `Webhook`); inviati da
`OutboundWebhookClient` quando una **regola di automazione** ha l'azione *webhook* (SPEC §11.12, §15).
Richiesta inviata (formato **proposta**):
```
POST https://sito.example.com/hooks/khaemhat
Content-Type: application/json
X-Khaemhat-Event: DocumentIssued
X-Khaemhat-Delivery: 0b7f5e0e-2c43-4c7e-8d1a-5f3b2e9a1c77
X-Khaemhat-Timestamp: 1794303000
X-Khaemhat-Signature: sha256=3d2c…e91a
{ "event": "DocumentIssued", "company": "DEMO", "occurredAt": "2026-11-10T09:30:00Z",
"data": { "entity": "SaleDocument", "id": 5120, "number": "FT/2026/000412" } }
```
- **Firma HMAC**: `HMAC-SHA256(segreto_del_webhook, "<timestamp>.<corpo>")` in esadecimale. Il destinatario
ricalcola la firma, la confronta in tempo costante e rifiuta timestamp più vecchi di 5 minuti **(proposta)**.
- **Retry**: risposta non `2xx` o timeout → nuovi tentativi con attesa crescente (proposta: 1 min, 5 min, 30 min,
2 h, 12 h), poi disattivazione dopo N errori come per le regole (SPEC §11.12) e notifica agli amministratori.
- Il segreto del webhook è cifrato nel database (`SecretProtector`); ogni consegna è registrata nel log, sezione
*API/MCP*.
## 11. Esempi `curl`
Valori fittizi: host `gestionale.example.com`, azienda `DEMO`, chiave `kh_test_…`.
Elenco clienti, seconda pagina:
```bash
curl -s "https://gestionale.example.com/api/v1/parties?page=2&pageSize=20&sort=name" \
-H "Authorization: Bearer kh_test_0000000000000000000000" \
-H "X-Company: DEMO"
```
Creazione di un ordine cliente con idempotenza:
```bash
curl -s -X POST "https://gestionale.example.com/api/v1/sale-orders" \
-H "Authorization: Bearer kh_test_0000000000000000000000" \
-H "X-Company: DEMO" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 6c0e2b9a-3f7d-4d1e-9a51-2a8f1c0d7e44" \
-d '{ "partyCode": "C000042", "date": "2026-11-10",
"lines": [ { "itemCode": "ART-0001", "quantity": 3, "price": 12.50 } ] }'
```
Aggiornamento con controllo di concorrenza:
```bash
curl -s -i "https://gestionale.example.com/api/v1/parties/1042" \
-H "Authorization: Bearer kh_test_0000000000000000000000" -H "X-Company: DEMO"
# … ETag: "17"
curl -s -X PUT "https://gestionale.example.com/api/v1/parties/1042" \
-H "Authorization: Bearer kh_test_0000000000000000000000" -H "X-Company: DEMO" \
-H "If-Match: \"17\"" -H "Content-Type: application/json" \
-d '{ "name": "Alfa Beta S.r.l.", "email": "amministrazione@alfabeta.example" }'
```
Upload di un allegato su una fattura e download:
```bash
curl -s -X POST "https://gestionale.example.com/api/v1/invoices/5120/attachments" \
-H "Authorization: Bearer kh_test_0000000000000000000000" -H "X-Company: DEMO" \
-F "file=@ordine-firmato.pdf"
curl -s -o copia.pdf "https://gestionale.example.com/api/v1/attachments/880" \
-H "Authorization: Bearer kh_test_0000000000000000000000" -H "X-Company: DEMO"
```
Ordine dal connettore generico di un canale e-commerce:
```bash
curl -s -X POST "https://gestionale.example.com/api/v1/channels/WEB/orders" \
-H "Authorization: Bearer kh_test_0000000000000000000000" -H "X-Company: DEMO" \
-H "Content-Type: application/json" -H "Idempotency-Key: web-ordine-100231" \
-d @ordine-web.json
```
Stato dell'istanza (chiave di istanza):
```bash
curl -s "https://gestionale.example.com/api/v1/admin/status" \
-H "Authorization: Bearer kh_test_1111111111111111111111"
```
## 12. Test previsti (SPEC §18)
- `Khaemhat.Web.Tests`: autenticazione con API key (valida, scaduta, IP non consentito), cookie, `X-Company`,
permessi e licenze (`module_not_licensed`), `412` su `If-Match` obsoleto, idempotenza, `429`, `503` in
manutenzione, forma RFC 9457 con `traceId`, validità del documento OpenAPI.
- Tutti i test girano con `KHAEMHAT_LICENSE_MODE=test` e la licenza `KH-TEST-ALL-0000-9999`.