# gov_ked / module beveosi_ofeilwn — RabbitMQ message contract

Per command: the exact bytes the microservice expects on its queue and the exact JSON it
publishes back.

**Read this first if you are building the BFF:** the microservice is the **system of record**.
It holds drafts, the lookup values, and everything about a βεβαίωση including the fields ΚΕΔ
never sees. The BFF stores nothing; it asks and it polls.

## The commands

| Command | What it does | Calls ΚΕΔ | Reply `type` |
|---|---|---|---|
| `ping` | Handshake check. | — | `single` |
| `get_lookups` | Every dropdown in one cacheable payload (relations, ΚΑΕ, tax types, signers, statuses, frequencies, lastDayRules) + `driver`/`environment`. Conditional fetch via `knownVersion`. | — | `lookup` |
| `declare_signers` | Declares the **whole** signer list to ΚΕΔ (`retrieveNames`). Prerequisite for every βεβαίωση; invalidates the lookups cache when it succeeds. | ✓ | `single` |
| `save_beveosi_draft` | Stores or updates a local draft; contacts nobody. | — | `single` |
| `delete_beveosi_draft` | Deletes a `draft` or a `failed` row — never anything locked. | — | `single` |
| `submit_beveosi` | Certifies one βεβαίωση at the ΔΟΥ (`retrieveKedeAmount`). The response **never** contains the ΑΤΒ. | ✓ | `single` |
| `get_beveosi_status` | The polling endpoint: full record plus `pending`. | throttled | `single` |
| `list_beveoseis` | Paginated list of βεβαιώσεις for the BFF table. | — | `list` |
| `get_payment_progress` | The balances of one Ταυτότητα Οφειλής (`retrievePayProgress`). Read-only, fetch-on-demand. | ✓ | `single` |
| `get_payment_data` | The payment movements of one Τ.Ο. in a date range (`retrievePaymentData`), totals in `extraData`. | ✓ | `list` |
| `set_beveosi_attachments` | Replaces the local attachment list (`{title, filepath}`) of one βεβαίωση. Works at **any** status. | — | `single` |
| `submit_reduction` | Μείωση/Διαγραφή of an already-certified debt (`deleteKedeAmount`). **Not yet verified against a successful real pilot call** — see the M4 section below. | ✓ | `single` |
| `get_reduction_status` | The polling endpoint for one ΑΦΕΚ, mirrors `get_beveosi_status`. | throttled | `single` |
| `list_reductions` | Paginated list of ΑΦΕΚ. | — | `list` |
| `get_reduction_progress` | On-demand cross-check by date range (`deleteKedeProgress`) — not a gate on `get_reduction_status`. | ✓ | `list` |

— = purely local (DB only). *throttled* = only if the row has not been checked within
`KED_STATUS_POLL_THROTTLE` seconds; the scheduled sweep settles rows anyway. Sections below
cover each command in full.

## Transport

| | Value |
|---|---|
| Queue consumed | `gov_ked`, declared **non-durable** (`queue_declare(queue, false, false, false, false)` in their `RabbitMQJob`) |
| Exchange | default, direct-to-queue on the routing key `config('microservices.gov_ked.routing_key')` |
| Reply mechanism | AMQP `reply_to` property; `correlation_id` echoed back |
| Payload format | plain string, **not JSON** — see below |
| Content-Type | not inspected by the consumer |

## Inbound message

The body is a single string:

```
<command>|<http_build_query($params, '', null, PHP_QUERY_RFC3986)>
```

For example:

```
submit_beveosi|afm=137569280&sunolo=600.00&installments%5B0%5D%5Baa%5D=1
```

- **The `|` is always present**, even with no params (`ping|`). Without it,
  `RabbitMQMessageInterpreter` never initialises its params array and dies with a TypeError.
- Nested structures use `http_build_query` bracket notation and are rebuilt by `parse_str`, so
  `installments[0][amount]` arrives as a nested array. Verified end to end.
- **Every value arrives as a string** — `parse_str` does no type inference. So send `"1"`, not
  `1`, and `"600.00"`, not `600.0`. This is not pedantry: a float amount becomes a wrong debt
  against a real person, and `parse_str` would hand us a string anyway.
- Params whose name starts with `_` are treated as *internal* by the library and kept in a
  separate array (they matter only for `api_commands`, i.e. REST proxying, which this module
  does not use).
- **There is no `token` field.** The envelope has no room for one, so the ΚΕΔ audit identity
  travels as ordinary params — see below.

### Two naming traps

**1. `auditUserId` and `auditUserIp` are mandatory, and must be spelled exactly that way.**
Παράρτημα Γ of the ΚΕΔ spec makes all six audit fields mandatory *for this service*
(`auditTransactionId`, `auditTransactionDate`, `auditUnit`, `auditProtocol`, `auditUserId`,
`auditUserIp`). The first four we generate; the last two only the BFF knows. A command that
reaches ΚΕΔ without them is a validation error, not a silent omission.

**2. Avoid `date`, `date_from`, `date_to`, `created_at`, `updated_at`.** The library pushes any
param with one of those names (plus `contract_start_date`, `contract_end_date`,
`extend_until_date`, `card_delivered_date`, `card_returned_date`) through
`Carbon::parse()->toDateString()` before we see it. A real date survives unchanged — but
**`Carbon::parse('')` returns today**, so an empty filter silently becomes "only today". Use
`dateFrom` / `dateTo`. Both spellings are accepted by `list_beveoseis`; only the camelCase ones
are safe.

## Outbound response (all commands)

`json_encode` of their `RabbitMQResponse`, published verbatim to `reply_to`. Property order is
fixed by the class:

```json
{
    "data": null,
    "pagination": [],
    "extraData": [],
    "errors": [],
    "warnings": [],
    "messages": [],
    "status": 1,
    "type": "single"
}
```

- `status` is an **integer**: `1` OK, `2` WARNING, `3` ERROR, `4` BUSINESS_ERROR.
- `type` is **lowercase**: `single`, `list`, `lookup`.
- Empty defaults are `[]`, not `null`. Note that `pagination` and `extraData` are `[]` when
  empty and objects when populated — a JSON-typed client needs to allow both.
- `pagination`, when populated, is **snake_case**:
  `{"page": 1, "page_size": 20, "total_count": 0, "page_count": 0}`.
- Their `addError()` sets `status` to ERROR as a side effect; we call `setStatus()` afterwards,
  which is why a rejection arrives as `4` rather than `3`.

### How to read the status

| status | Meaning | What the BFF should do |
|---|---|---|
| `1` OK | It worked. | Use `data`. |
| `4` BUSINESS_ERROR | Rejected for a reason the user can act on: bad input, a ΚΕΔ refusal, a duplicate. `errors[0]` is a Greek sentence fit to display; `extraData.fields` maps param paths to messages. | Show it. **Check `extraData.resendable` before offering a retry.** |
| `3` ERROR | Something unexpected broke. | Log it; do not invite a retry. |

## The type system, in one place

**Everything you send is a string.** Their interpreter `parse_str`s the query string and does
no type inference: numbers, money, flags — all strings or arrays of strings. So `"1"`, never
`1`; `"600.00"`, never `600.0`. This is not pedantry: a float amount becomes a wrong debt
against a real person.

**What you get back has real JSON types, chosen by rule:**

| JSON type | Appears where | Why |
|---|---|---|
| `string` | money (`sunolo`, `amount`, `origAmount`); identifiers (ΑΦΜ, ΚΑΕ, ΔΟΥ, `atbNo`, `mcNo`, `lineNo`, `taftotitaOfeilis`, `auditProtocol`, `hashId`, `unitId`, `unitAcronym`); enums; dates; timestamps | leading zeros are significant; `atbNo` reaches 20 digits — beyond a JSON-safe integer; money must never round |
| `number` | `id`, `position`, pagination numbers, `frequencies.value`, `lastDayRules.value` | no leading zeros, no decimals — safe |
| `boolean` | `locked`, `isPrimary`, `unchanged`, `deleted`, `requiresActivation`, `pending` | |
| `null` | anything «not yet»: `atbNo` before the close-day, `certifiedAt` before certification, `relationCode` for the primary debtor, the whole value block of a bare draft | check `null` before parsing, not after |

Dates are `YYYY-MM-DD`; timestamps are ISO-8601 with offset (`2026-09-03T17:31:48+03:00`).

Request tables use: **Req** ✓ = must be present — **omit** the field when unused, never send
`""`; `string ≤N` = max length; regexes are the literal validation we run; enum rows list every
accepted value.

## Shared response objects

The `data` payloads are built from a small set of objects that repeat across commands. They
are defined here once — as TypeScript, the language the BFF is written in — and each command
below references them.

```ts
type RabbitMQStatus = 1 | 2 | 3 | 4;   // 1 OK, 2 WARNING, 3 ERROR, 4 BUSINESS_ERROR
type ResultType = 'single' | 'list' | 'lookup';

interface RabbitMQEnvelope<T> {
  data: T | null;                          // null on every error response
  pagination: [] | Pagination;             // [] when empty — a typed parser must allow both
  extraData: [] | Record<string, unknown>; // ditto
  errors: string[];                        // Greek sentences, fit to display
  warnings: string[];
  messages: string[];
  status: RabbitMQStatus;
  type: ResultType;
}

interface Pagination {                     // snake_case — their convention
  page: number;
  page_size: number;
  total_count: number;
  page_count: number;
}

type BeveosiStatus =
  | 'draft' | 'sent' | 'certified_pending_closeday'
  | 'certified' | 'failed' | 'needs_reconciliation';

interface BeveosiSummary {   // every list_beveoseis row; the first block of every BeveosiDetail
  id: number;
  auditProtocol: string;     // «{n}/DD-MM-YYYY» (Παράρτημα Γ's own format), minted once per
                             // βεβαίωση and reused on resends (Παράρτημα Ζ) — opaque to the BFF
  hashId: string;            // SHA-256 hex (64 chars) of the auditProtocol — computed by us at
                             // draft creation, never a request field, stable across resends.
                             // Use it as the base key for your MinIO object names, and as a
                             // lookup selector wherever id/auditProtocol work
  status: BeveosiStatus;
  statusLabel: string;
  locked: boolean;
  afm: string;                  // 9 digits, leading zeros significant
  debtorName: string | null;    // the οφειλέτης display name, ours only — never sent to ΚΕΔ;
                                //   null on a bare draft. Lets the list table render the name
                                //   without a detail round-trip
  unitId: string | null;        // η μονάδα που υπέβαλλε τη βεβαίωση, as you sent it — ours only,
  unitAcronym: string | null;   //   never sent to ΚΕΔ. unitId is a list_beveoseis filter
  kae: string | null;           // the value block from here down is null on a bare draft
  fiscalYear: string | null;    // NOT number — the wire is all strings
  apofNoEtos: string | null;
  sunolo: string;               // money: string with exactly two decimals
  doy: string | null;           // the ΔΟΥ ΚΕΔ assigned (result_doy), not your request field
  mcNo: string | null;
  mcDate: string | null;        // YYYY-MM-DD
  atbNo: string | null;         // up to 20 digits — never a JSON number
  atbDate: string | null;
  errorCode: string | null;     // ΚΕΔ's code on a rejection (e.g. GEN_INVALID_DATA), or
                                //   TRANSPORT_ERROR when ΚΕΔ never answered — never decide a
                                //   retry from it: use status / resendable
  errorDescr: string | null;
  submittedAt: string | null;   // ISO-8601 with offset
  certifiedAt: string | null;
  createdAt: string;
  taftotites: Taftotita[];      // [] until close-day hands them out — «not yet» vs «nothing to ask»
}

interface Debtor {             // one per ΑΦΜ — one Ταυτότητα Οφειλής each, filled at close-day
  afm: string;
  position: number;            // 0 = ο οφειλέτης, 1.. = συνυπόχρεοι
  isPrimary: boolean;
  fullName: string | null;
  phone: string | null;            // ours only — no phone field exists anywhere in the ΚΕΔ interface
  relationCode: string | null;     // null for the primary, a get_lookups pair for the rest
  relationCategory: string | null;
  amount: string;
  lineNo: string | null;
  taftotitaOfeilis: string | null;
  origAmount: string | null;       // equals amount at issuance — the pre-Μείωση reference;
}                                   // see PaymentProgress.reducedAmount/deletedAmount below

interface Installment { aa: string; dueDate: string; amount: string; }
interface KaeLine { kae: string; amount: string; }

interface Attachment {          // ours only — never sent to ΚΕΔ, editable at any status
  title: string;
  filepath: string;                // the Φορέας' object storage (MinIO) — opaque to the microservice
}

interface Taftotita {            // one row of BeveosiSummary.taftotites — the «Πορεία» action and the
  afm: string;                   // detail page's per-debtor links key on it
  fullName: string | null;
  payId: string;                 // 30 digits — never a JSON number
}

interface PaymentProgress {      // get_payment_progress — the seven balances, all verbatim
  payId: string;
  afm: string | null;            // null when no local row carries the Τ.Ο. (raw payId of an old run)
  fullName: string | null;
  auditProtocol: string | null;
  apofNoEtos: string | null;
  sunolo: string | null;
  firstEstablishedAmount: string | null;   // money: strings, two decimals — and NEVER derived from
  paidAmount: string | null;               // one another: the spec's own sample has totalAmount <
  deletedAmount: string | null;            // restAmount (απαιτητό includes συνεισπραττόμενα).
  reducedAmount: string | null;            // Computed by ΚΕΔ itself from ITS OWN record of any
                                            // deleteKedeAmount call against this debt — nothing in
                                            // the delete-service spec says we feed anything back
                                            // into the progress service. Our local afek_records
                                            // (M4) is an independent ledger of what WE submitted
                                            // and its finalization state; it does not write these
                                            // two fields, and the two can legitimately disagree
                                            // while an ΑΦΕΚ is still awaiting_finalization.
  restAmount: string | null;
  overdueAmount: string | null;
  totalAmount: string | null;              // το απαιτητό, NOT το υπόλοιπο
  callSequenceId: string | null;           // ΚΕΔ provenance, per answer
  callSequenceDate: string | null;
}

interface PaymentRow {           // get_payment_data — one row of retrievePaymentData's Payment List
  dbtDoy: string | null;
  dbtDept: string | null;
  dbtMctCode: string | null;     // 1 — this service
  dbtSctCode: string | null;     // 98 — third-party debts
  dbtYear: string | null;
  dbtSrcCode: string | null;
  dbtMcNo: string | null;        // the ΧΚ — with dbtMcLine it disambiguates one ΧΚ, many βεβαιώσεις
  dbtMcLine: string | null;
  dbtAtbNo: string | null;       // up to 20 digits — never a JSON number
  dbtAtbYear: string | null;
  dbtAtbDate: string | null;     // YYYY-MM-DD (normalised from the ISO wire form)
  dbtAfmDebtor: string | null;   // CHAR(12) on the wire, trimmed; leading zeros significant
  outTo: string | null;          // the Τ.Ο. the payment belongs to
  paymentDate: string | null;
  posoPlirwmhs: string | null;   // money, strings, two decimals
  kefPlirwmhs: string | null;
  tokoiPlirwmhs: string | null;
}

interface BeveosiDetail extends BeveosiSummary {
  comments: string | null;       // the whole value block is null on a bare draft
  insFrequency: '1' | '2' | '3' | null;
  lastDayRule: '1' | '2' | null;
  afmYpogr: string | null;
  nameYpogr: string | null;
  discountPcg: string | null;
  discountDate: string | null;
  debtors: Debtor[];
  installments: Installment[];
  kaeLines: KaeLine[];
  attachments: Attachment[];     // detail only — never in the list summary, never sent to ΚΕΔ
}

interface Relation { code: string; category: string; label: string; categoryLabel: string; }
interface KaeOption { kae: string; description: string; }
interface TaxTypeOption { txtCode: string; description: string; }
interface SignerOption { afm: string; firstName: string; lastName: string; fullName: string; }

interface Lookups {
  version: string;              // content hash — cache against it, indefinitely
  unchanged: false;
  generatedAt: string;
  driver: 'fake' | 'soap';
  environment: 'fake' | 'pilot' | 'production';
  relations: Relation[];        // the seven permitted pairs
  kae: KaeOption[];
  taxTypes: TaxTypeOption[];    // informational — NOT a dropdown; txtCode is ours to send
  signers: SignerOption[];      // only what ΚΕΔ has accepted — key on afm
  statuses: { value: BeveosiStatus; label: string }[];    // value is a STRING here…
  frequencies: { value: number; label: string }[];        // …and a NUMBER for these two —
  lastDayRules: { value: number; label: string; requiresActivation: boolean }[];  // mind the mix
}

interface LookupsUnchanged { version: string; unchanged: true; }  // the knownVersion hit
```

---

## Command: `ping`

Handshake check, supplied by the skeleton.

```
ping|
```

`data: string`.

```json
{ "data": "pinged successfully", "status": 1, "type": "single" }
```

---

## Command: `get_lookups`

**Every lookup in one payload.** Deliberately not one command per list: call this once, cache
it, reuse it everywhere.

`version` is a hash of the content, so it changes only when the content does — cache against
it indefinitely and refetch when it moves. It *will* move: `signers` is live data that
`declare_signers` mutates.

**Request:**

| Field | Req | Type | Rules |
|---|---|---|---|
| `knownVersion` | — | string | the `version` you already hold; on a hit you get `LookupsUnchanged` |

This is a conditional fetch: if nothing changed you get a few dozen bytes back instead of
the whole payload.

```json
{ "data": { "version": "sha256:54eb05763e4341a6", "unchanged": true }, "status": 1, "type": "lookup" }
```

Send `knownVersion` on every revalidation — the only way to learn that `signers` changed is to
ask, so the ask itself has to be cheap. On a miss (or with no `knownVersion`) you get the full
payload, `unchanged: false`.

**Response:** `data: Lookups` (`type: "lookup"`, abridged):

```json
{
    "data": {
        "version": "sha256:54eb05763e4341a6",
        "unchanged": false,
        "generatedAt": "2026-09-03T12:00:00+03:00",
        "driver": "soap",
        "environment": "pilot",
        "relations": [
            { "code": "1", "category": "2", "label": "ΔΙΑΧΕΙΡΙΣΤΗΣ", "categoryLabel": "ΕΠΙΧΕΙΡΗΜΑΤΙΚΗ" }
        ],
        "kae": [{ "kae": "82838", "description": "Αχρεωστήτως καταβληθέντα" }],
        "taxTypes": [{ "txtCode": "4102", "description": "Έσοδα υπέρ τρίτων" }],
        "signers": [
            { "afm": "003067224", "firstName": "ΕΥΓΕΝ", "lastName": "ΧΡΙΣΤΟΠΟΥΛΟΥ", "fullName": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ" }
        ],
        "statuses": [{ "value": "draft", "label": "Πρόχειρο" }],
        "frequencies": [{ "value": 1, "label": "Μηνιαία" }],
        "lastDayRules": [{ "value": 1, "label": "Τελευταία εργάσιμη", "requiresActivation": false }]
    },
    "status": 1,
    "type": "lookup"
}
```

| Set | Contents |
|---|---|
| `driver`, `environment` | Which transport is wired and **which ΑΑΔΕ system it reaches** — they are independent. `driver`: `fake` (canned XML, no network) or `soap` (a real call). `environment`: `pilot` = debts land in ΑΑΔΕ's test TAXIS, `production` = a real debt against a real person, undoable only through kedeDeleteService; the `fake` driver always reports `fake`. Worth showing in the UI: a screen that shouts «πραγματικό χρέος!» while on the pilot trains people to dismiss the warning that will matter. |
| `relations` | The **seven** permitted σχέσεις συνυποχρέωσης. Sent to ΚΕΔ as a `code` + `category` **pair**; any other combination is «Μη αποδεκτή σχέση». |
| `kae` | The ΚΑΕ ΑΑΔΕ granted the Φορέας. |
| `taxTypes` | Informational. `txtCode` is **not** a user choice — ΑΑΔΕ assigns it and the microservice sends it from config. Do not build a dropdown from this. |
| `signers` | Only υπογράφοντες ΚΕΔ has actually accepted. Key your dropdown on `afm`, never on the name. |
| `statuses`, `frequencies`, `lastDayRules` | Labels for the enums. `requiresActivation` on a rule means ΑΑΔΕ must enable it for the Φορέας first. |

A reference implementation of the caching is in `frontend/src/lib/lookups.ts`.

---

## Command: `declare_signers`

Δηλώνει τους υπογράφοντες στο ΚΕΔ (`retrieveNames`). **Prerequisite for every βεβαίωση.**

**Send the whole valid list every time, never just the changes** — ΚΕΔ replaces the declared
list with whatever arrives. Anyone missing is deactivated on our side too. Maximum 10.

**Request:**

| Field | Req | Type | Rules |
|---|---|---|---|
| `signers` | ✓ | array | 1..10 — the **whole** list every time |
| `signers[].afm` | ✓ | string | `^\d{9}$`, leading zeros significant |
| `signers[].firstName` | ✓ | string ≤50 | |
| `signers[].lastName` | ✓ | string ≤50 | |
| `auditUserId` | ✓ | string ≤100 | Παράρτημα Γ |
| `auditUserIp` | ✓ | string ≤45 | Παράρτημα Γ |

```json
{
    "signers": [
        { "afm": "003067224", "firstName": "ΕΥΓΕΝ", "lastName": "ΧΡΙΣΤΟΠΟΥΛΟΥ" }
    ],
    "auditUserId": "user1",
    "auditUserIp": "10.6.32.28"
}
```

**Response (OK)** — `data: { declared: string; plithosYpogr: string; signers: SignerOption[]; message: string }`
(counts are strings — the wire is all strings):

```json
{
    "data": {
        "declared": "1",
        "plithosYpogr": "1",
        "signers": [{ "afm": "003067224", "firstName": "ΕΥΓΕΝ", "lastName": "ΧΡΙΣΤΟΠΟΥΛΟΥ", "fullName": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ" }],
        "message": "Η λίστα υπογραφόντων ενημερώθηκε. Ανανεώστε την cache του get_lookups."
    },
    "status": 1,
    "type": "single"
}
```

The local list is written **only after ΚΕΔ accepts it**, so a rejected signer never becomes
selectable. `inputDate` is set to today by the microservice (ΚΕΔ answers
`WS_PROCEDURE_ERROR_DATE` otherwise), and `plithosYpogr` is derived from the row count — the
caller does not supply either.

Rejections carry `extraData.retryable: true`: unlike a certification, this operation creates
nothing, so retrying is safe. A ΚΕΔ refusal additionally carries `extraData.errorCode` next to
the Greek sentence in `errors[0]` (e.g. `WS_PROCEDURE_ERROR_PLITHOS` for more than 10,
`WS_PROCEDURE_ERROR_DATE` — the latter cannot happen from the BFF, since we stamp today's
`inputDate` ourselves).

---

## Command: `submit_beveosi`

Certifies one βεβαίωση at the ΔΟΥ (`retrieveKedeAmount`).

Either send the full payload, or pass `id` / `auditProtocol` to certify a stored draft.

**The response never contains the ΑΤΒ.** `retrieveKedeAmount` returns ΔΟΥ, ΧΚ and γραμμή only;
the Αριθμός Τριπλότυπου Βεβαίωσης and the Ταυτότητες Οφειλής exist only once the ΔΟΥ closes
the day. This is the single most important thing to design the UI around.

**Request**

```json
{
    "afm": "137569280",
    "debtorName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
    "debtorPhone": "6971234567",
    "synypochreoi": [
        { "afm": "063745180", "code": "20", "category": "3", "amount": "600.00", "fullName": "ΓΕΩΡΓΙΟΥ ΜΑΡΙΑ" }
    ],
    "installments": [
        { "aa": "1", "dueDate": "2026-08-31", "amount": "300.00" },
        { "aa": "2", "dueDate": "2026-09-30", "amount": "300.00" }
    ],
    "kaeLines": [{ "kae": "82838", "amount": "600.00" }],
    "sunolo": "600.00",
    "fiscalYear": "2026",
    "apofNoEtos": "10/2026",
    "comments": "Απόφαση 10/2026",
    "insFrequency": "1",
    "lastDayRule": "1",
    "doyFlag": "0",
    "afmYpogr": "003067224",
    "nameYpogr": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ",
    "auditUserId": "user1",
    "auditUserIp": "10.6.32.28"
}
```

**Omit unused optional fields — never send `""`.** Our `nullable` skips `null`, not the empty
string, so `"doy": ""`, `"discountPcg": ""` or `"discountDate": ""` is a **validation error**,
not a blank. A form builder that serialises every input must strip the empties before
publishing. (`doyFlag` is the one that tolerates `""`; `doy` and the discount pair must simply
be absent when unused. `tests/fixtures/beveosi.json` is the exact shape we test against.)

| Field | Req | Type | Rules |
|---|---|---|---|
| `id` / `auditProtocol` / `hashId` | — | string | any ONE of them names the stored draft/rejected row to certify; any other fields you also send override the stored ones. `hashId` is read-only — it selects, it is never stored from a request |
| `unitId` | ✓ | string ≤120 | η μονάδα που υπέβαλλε τη βεβαίωση — **stored by us, never sent to ΚΕΔ**. Required on submission, optional on a draft. Echoed as `unitId` in every summary, and accepted as a prefix-match `list_beveoseis` filter (on the id or the acronym) |
| `unitAcronym` | — | string ≤120 | το ακρωνύμιο της μονάδας, display-only — stored and echoed like `unitId`, never required |
| `afm` | ✓ | string | `^\d{9}$` — ο οφειλέτης, leading zeros significant |
| `debtorName` | — | string ≤120 | **stored by us, never sent to ΚΕΔ** — the ΚΕΔ contract has no name field for a debtor. Comes back as `debtorName` in every `BeveosiSummary`, list rows included |
| `debtorPhone` | — | string | free-form contact info — a phone number, an email, whatever reaches the debtor; no format or length is enforced (the column is `TEXT`). **Stored by us, never sent to ΚΕΔ** — no such field exists anywhere in the ΚΕΔ interface. Ο οφειλέτης only |
| `attachments` | — | array ≤10 | local attachments, `{title ≤255, filepath ≤500}` — **full replace when present, kept when absent; never sent to ΚΕΔ**. See `set_beveosi_attachments` for the semantics and the empty-list wire trap |
| `synypochreoi` | — | array ≤9 | omit entirely when there are none |
| `synypochreoi[].afm` | ✓ | string | `^\d{9}$` |
| `synypochreoi[].code` + `.category` | ✓ | string | **must be a pair from `get_lookups.relations`** |
| `synypochreoi[].amount` | — | string | money; defaults to `sunolo` (joint liability is for the whole debt) |
| `synypochreoi[].fullName` | — | string ≤120 | ours only |
| `installments` | ✓ | array ≥1 | |
| `installments[].aa` | ✓ | string | `^\d{1,4}$` |
| `installments[].dueDate` | ✓ | string | `YYYY-MM-DD`; ΚΕΔ's schedule rules — **first δόση in the month after submission**, δόσεις exactly `insFrequency` months apart, and with `lastDayRule=1` every date on the **last working day** of its month (31/10/2026 is a Saturday → rejected) — all checked locally before we spend a ΚΕΔ call |
| `installments[].amount` | ✓ | string | money, **non-zero** |
| `kaeLines` | ✓ | array ≥1 | |
| `kaeLines[].kae` | ✓ | string | `^\d{1,5}$`, must be one from `get_lookups.kae` |
| `kaeLines[].amount` | ✓ | string | money, **non-zero** |
| `sunolo` | ✓ | string | `^\d{1,15}\.\d{2}$`; **must equal Σ(installments) AND Σ(kaeLines)** — checked locally before we spend a ΚΕΔ call |
| `fiscalYear` | ✓ | string | `^\d{4}$`, 2010…current year — enforced locally (DB spec input table: «Οικονομικό έτος (>=2010, <= τρέχον)») |
| `apofNoEtos` | ✓ | string ≤40 | Αριθμός απόφασης – έτος |
| `comments` | ✓ | string ≤4000 | Σχόλια — spec §2.1 (σελ. 6) demands the έτος and αριθμός of the απόφασης **also inside the comments text, in addition to `apofNoEtos`**; ≤4000 per Παράρτημα Δ (σελ. 35, VARCHAR2(4000)) |
| `insFrequency` | ✓ | enum | `"1"` (μηνιαία) \| `"2"` \| `"3"` |
| `lastDayRule` | ✓ | enum | `"1"` (τελ. **εργάσιμη** — ΑΑΔΕ xlsx: «1=τελ. εργάσιμη») \| `"2"` (τακτή ημερομηνία) — `"2"` needs prior ΑΑΔΕ activation |
| `doy` | — | string | **exactly** `^\d{4}$` (DB spec: CHAR(4)); ΔΟΥ καθ' υπέρβαση αρμοδιότητας; omit entirely when unused |
| `doyFlag` | — | enum | `"0"` only; `"1"` (ΔΟΥ ακινήτου) is out of scope and refused |
| `discountPcg` | — | string | `^\d{1,2}\.\d{2}$` |
| `discountDate` | —¹ | string | `YYYY-MM-DD`; required whenever `discountPcg` is present |
| `afmYpogr` | ✓ | string | `^\d{9}$`; **must already be declared** via `declare_signers` |
| `nameYpogr` | ✓ | string ≤120 | |
| `auditUserId` | ✓ | string ≤100 | Παράρτημα Γ — mandatory |
| `auditUserIp` | ✓ | string ≤45 | Παράρτημα Γ — mandatory |

✓ inside an array row means: required in every element, once the array itself is present.
¹ conditionally required (see Rules).

Not accepted: `txtCode` (config, assigned by ΑΑΔΕ) and `attachedFile` / `attFileName` /
`attExtension` (the PDF απόφασης — deferred, see `data-model.md`). Note that our own
`attachments` param is **unrelated** to those ΚΕΔ elements: it is local metadata that never
leaves the microservice. Also not accepted: `hashId` — it is computed by us from the minted
`auditProtocol` and only ever comes back in replies.

**Response (OK)** — `data: BeveosiDetail & { message: string }`: the **full record**, the same
object `get_beveosi_status` returns, so everything you just sent (debtors, installments, ΚΑΕ
lines, comments, `attachments`) comes back in the reply. `list_beveoseis` rows are the shorter
`BeveosiSummary`, i.e. the first block below without the detail fields.

```json
{
    "data": {
        "id": 1,
        "auditProtocol": "1/06-08-2026",
        "hashId": "88468689707b4599be6efd959c4f241ed94449725881d8b0db35a55c140cd8ac",
        "status": "certified_pending_closeday",
        "statusLabel": "Βεβαιώθηκε — αναμονή ΑΤΒ",
        "locked": true,
        "afm": "137569280",
        "debtorName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
        "unitId": "1204",
        "unitAcronym": "ΙΝΡΑ",
        "kae": "82838",
        "fiscalYear": "2026",
        "apofNoEtos": "10/2026",
        "sunolo": "600.00",
        "doy": "9776",
        "mcNo": "2",
        "mcDate": "2026-08-06",
        "atbNo": null,
        "atbDate": null,
        "errorCode": null,
        "errorDescr": null,
        "submittedAt": "2026-08-06T22:57:19+03:00",
        "certifiedAt": null,
        "createdAt": "2026-08-06T22:57:18+03:00",
        "taftotites": [],
        "comments": "Απόφαση 10/2026",
        "insFrequency": "1",
        "lastDayRule": "1",
        "afmYpogr": "003067224",
        "nameYpogr": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ",
        "discountPcg": null,
        "discountDate": null,
        "debtors": [
            {
                "afm": "137569280",
                "position": 0,
                "isPrimary": true,
                "fullName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
                "phone": "6971234567",
                "relationCode": null,
                "relationCategory": null,
                "amount": "600.00",
                "lineNo": "1",
                "taftotitaOfeilis": null,
                "origAmount": null
            }
        ],
        "installments": [{ "aa": "1", "dueDate": "2026-09-30", "amount": "600.00" }],
        "kaeLines": [{ "kae": "82838", "amount": "600.00" }],
        "attachments": [{ "title": "Απόφαση 10/2026", "filepath": "minio://beveoseis/10-2026.pdf" }],
        "message": "Η βεβαίωση καταχωρήθηκε. Ο ΑΤΒ και οι Ταυτότητες Οφειλής αποδίδονται με το κλείσιμο της ημέρας στη ΔΟΥ — δείτε get_beveosi_status."
    },
    "status": 1,
    "type": "single"
}
```

`taftotites` and each debtor's `taftotitaOfeilis` stay empty until the ΔΟΥ closes the day;
`get_beveosi_status` fills them in. Field-by-field notes on the detail block: see
`get_beveosi_status` below.

Notes on the summary fields: `doy` here is the ΔΟΥ **ΚΕΔ assigned** (`result_doy`), not your request
field. `submittedAt` / `certifiedAt` / `createdAt` are ISO-8601 with offset; the `At` pair are
`null` until they happen. `atbNo` is a **string** — 20 digits does not fit a 64-bit integer.
`mcNo` and `lineNo` are strings for the same reason ΑΦΜ is.

### The three failure modes, and why they are different

In modes (a) and (b), `extraData` is the **full record above (`BeveosiDetail`) plus one extra
key**, `resendable`. Build against the whole object, not a subset.

```ts
extraData:
  | (BeveosiDetail & { resendable: true })     // a: ΚΕΔ rejected it
  | (BeveosiDetail & { resendable: false })    // b: no answer (status needs_reconciliation)
  | (BeveosiDetail & { retryable: true })      // a2: ΚΕΔ unreachable — connection never opened
  | { existing: { id: number; auditProtocol: string;    // c: duplicate already in flight
                  hashId: string;                        // key your MinIO objects on it
                  status: BeveosiStatus; statusLabel: string } }
  | { fields: Record<string, string[]> };      // validation errors, keyed by dotted path
```

**a. ΚΕΔ rejected it** — `status: 4`, `resendable: true`, and the record shows
`status: "failed"` with `errorCode` / `errorDescr` filled in. The debt was **not** registered.
Let the user fix the input and submit again; the βεβαίωση keeps its `auditProtocol`, which is
how ΚΕΔ recognises the resend as the same one.

**a2. ΚΕΔ unreachable — the connection never opened** (Φάση 4, 2026-11-04) — `status: 4`,
`retryable: true`, record back at `status: "draft"` (or `"failed"` for a resubmission) with
`errorCode: "KED_UNREACHABLE"`. This is the transport failure that happens **before any byte
was sent** (ΚΕΔ down / DNS / TLS handshake): provably nothing exists at ΚΕΔ, so — unlike mode b
below — the βεβαίωση was NOT locked and submitting again is safe and expected. Offer the
retry button; treat any other transport wording as mode b.

**b. No answer from ΚΕΔ** — `status: 4`, `resendable: **false**`, record `status:
"needs_reconciliation"` (detail fields shortened here — they are the same as in the OK reply):

```json
{
    "data": null,
    "extraData": {
        "id": 3,
        "auditProtocol": "3/06-08-2026",
        "status": "needs_reconciliation",
        "statusLabel": "Εκκρεμεί έλεγχος",
        "locked": true,
        "afm": "137569280",
        "debtorName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
        "kae": "82838",
        "fiscalYear": "2026",
        "apofNoEtos": "10/2026",
        "sunolo": "600.00",
        "doy": null,
        "mcNo": null,
        "mcDate": "2026-08-06",
        "atbNo": null,
        "atbDate": null,
        "errorCode": "TRANSPORT_ERROR",
        "errorDescr": "No response from ΚΕΔ for retrieveKedeAmount.",
        "submittedAt": "2026-08-06T22:57:19+03:00",
        "certifiedAt": null,
        "createdAt": "2026-08-06T22:57:18+03:00",
        "taftotites": [],
        "comments": "Απόφαση 10/2026",
        "debtors": ["…"],
        "installments": ["…"],
        "kaeLines": ["…"],
        "attachments": [{ "title": "Απόφαση 10/2026", "filepath": "minio://beveoseis/10-2026.pdf" }],
        "resendable": false
    },
    "errors": ["Δεν ελήφθη απάντηση από το ΚΕΔ. Η βεβαίωση παραμένει κλειδωμένη μέχρι να επιβεβαιωθεί αν καταχωρήθηκε — ΜΗΝ την υποβάλετε ξανά."],
    "status": 4
}
```

Note that `errorCode` is **not** null here: it is `TRANSPORT_ERROR`, and `errorDescr` says no
answer came back. A non-null `errorCode` therefore does **not** mean «ΚΕΔ rejected it». Decide
whether to offer a retry **only** from `resendable` (or `status`: `failed` is resendable,
`needs_reconciliation` is not). `mcDate` is the submission date, which reconciliation searches.

The debt **may exist at the ΔΟΥ**. The row stays locked until reconciliation or a human
settles it. A UI that offers "try again" here will eventually raise a duplicate debt against a
real person. Do not.

**c. A duplicate is already in flight** — `status: 4`, naming the existing βεβαίωση:

```json
{
    "extraData": {
        "existing": {
            "id": 1,
            "auditProtocol": "1/06-08-2026",
            "hashId": "88468689707b4599be6efd959c4f241ed94449725881d8b0db35a55c140cd8ac",
            "status": "certified",
            "statusLabel": "Βεβαιωμένη"
        }
    },
    "errors": ["Υπάρχει ήδη ενεργή βεβαίωση για το ίδιο χρέος (ΑΦΜ, ΚΑΕ, έτος, αριθμός απόφασης)."],
    "status": 4
}
```

This is the path a user takes when the BFF times out waiting and they assume failure. Link them
to the existing βεβαίωση rather than letting them try again.

**Validation errors** put per-field messages in `extraData.fields`, keyed by dotted path
(`synypochreoi.0.code`, `installments.1.amount`, `sunolo`, `fiscalYear`), with the same Greek
sentences in `errors[]`.

### Resending a rejected βεβαίωση

Three equivalent doors — pick whichever fits the UI:

1. `id`, `auditProtocol` or `hashId` of the `failed` row, **plus only the corrected fields**.
   The stored payload is reused and your fields override it, so the form does not need to resend
   everything. That includes our local-only fields (`debtorName`, `debtorPhone`, `unitId`,
   `unitAcronym`, `synypochreoi[].fullName`, `attachments`): they survive the resend unless you
   send them.
2. The full corrected payload with **no** selector. If a `failed` row matches the natural key
   (ΑΦΜ, ΚΑΕ, έτος, αριθμός απόφασης), the oldest match is adopted — same row, same
   `auditProtocol`. Five attempts will not mean five rows.
3. `save_beveosi_draft` with the `id`, then `submit_beveosi` with the `id`.

Only `failed` rows are ever adopted. Anything that already reached ΚΕΔ goes through the
duplicate guard (mode c) instead — that is the Παράρτημα Ζ anti-duplicate defence, and no
payload can bypass it.

---

## Command: `save_beveosi_draft` / `delete_beveosi_draft`

We hold the drafts. `save_beveosi_draft` takes the same payload as `submit_beveosi` and
contacts nobody; validation is looser, because a half-finished form legitimately references a
signer or ΚΑΕ that is not declared yet.

> **An update is a full save, not a patch.** With `id`/`auditProtocol`, the debtors,
> installments and ΚΑΕ lines are **rewritten** from the request: send the whole form, or what
> you omit is removed. Only `attachments` is kept when absent. This is the opposite of
> `submit_beveosi` by `id`, which reuses the stored payload and lets your fields override it.

**Request:**

| Field | Req | Type | Rules |
|---|---|---|---|
| `id` / `auditProtocol` / `hashId` | — | string | which stored row to update — any one of the three |
| `afm` | ✓ | string | `^\d{9}$` |
| `sunolo` | ✓ | string | money — **required in practice even for a draft**: the debtor row stores it as its amount, and a draft without it is an error, not a blank |
| `attachments` | — | array ≤10 | same semantics as on `submit_beveosi`: present replaces the whole list, absent keeps it |
| everything else | — | | same fields, same formats as `submit_beveosi`; `installments` / `kaeLines` may be absent entirely (a bare draft is `afm` + `sunolo` + the audit pair) |

What is relaxed on a draft: `afmYpogr` need not be a declared signer, `kae` need not be in the
lookups. What is **still** enforced: every value constraint — money/ΑΦΜ/ημερομηνία formats, the
totals check, the relation pairs, the `fiscalYear` range — and the **omit-don't-empty** rule
(`"doy": ""` fails a draft too).

**Response (OK):** `data: BeveosiDetail` — the full record; the value block is `null` on
a bare draft.

`delete_beveosi_draft` takes `id` or `auditProtocol`:

| Field | Req | Type | Rules |
|---|---|---|---|
| `id` / `auditProtocol` | ✓ | string | at least one of the two must be present |

and deletes a `draft` **or a `failed`** row — the two statuses where nothing outside this
database knows the debt exists. On success — `data: { id: number; deleted: boolean }`:

```json
{ "data": { "id": 7, "deleted": true }, "status": 1, "type": "single" }
```

Deleting a `failed` row forfeits its `audit_protocol` — the one a correct-and-resend
(`submit_beveosi` reusing the row, see above) would otherwise carry forward to ΚΕΔ unchanged.
That stays the recommended path when the intent is to fix and retry; `delete_beveosi_draft` on a
`failed` row is for abandoning the attempt instead — a later resubmission for the same debt then
mints a fresh `audit_protocol`, not the old one.

Anything locked is refused:

```json
{
    "errors": ["Δεν επιτρέπεται η διαγραφή βεβαίωσης σε κατάσταση «Βεβαιωμένη». Η διαγραφή/μείωση πραγματικής οφειλής γίνεται μόνο μέσω της υπηρεσίας kedeDeleteService (submit_reduction)."],
    "status": 4
}
```

Once sent, a debt exists (or may exist) at the ΔΟΥ. Deleting our row would not remove it — it
would only destroy the record of it. Μείωση/Διαγραφή is `kedeDeleteService`, a separate service —
see `submit_reduction` below (M4).

---

## Command: `set_beveosi_attachments`

Replaces the attachment list of one βεβαίωση — **at any status**, including `certified` and
`needs_reconciliation`.

**You do not need this command to attach files when creating a βεβαίωση.** Send `attachments`
with the first `save_beveosi_draft` or `submit_beveosi`: no prior save, no `auditProtocol`
needed. This command is for changing the list afterwards, typically once the row is locked and
save/submit no longer accept edits.

Attachments are purely local metadata (`{title, filepath}` where `filepath` points at the
Φορέας' own object storage — MinIO): nothing here ever enters a ΚΕΔ envelope, which is why the
Παράρτημα Ζ lock does not apply to them (that lock guards what ΚΕΔ has seen) and why there is
**no `auditUserId`/`auditUserIp` here** — those exist for the ΚΕΔ audit record, and this command
makes no ΚΕΔ call and writes no ledger entry.

**Full-replace semantics:** the list sent is the list stored — send the complete list every
time, never a diff. An empty list clears. The same param on `save_beveosi_draft` /
`submit_beveosi` is optional: present replaces, absent keeps.

> **Wire trap:** `http_build_query` **drops an empty array**, so `attachments=[]` emits nothing.
> The only «empty list» that can travel is `attachments=` — which arrives as the empty *string*.
> We resolve `''` to `[]`, so both spellings clear; just never send `null`.

**Request:**

| Field | Req | Type | Rules |
|---|---|---|---|
| `id` / `auditProtocol` / `hashId` | ✓ | string | any ONE of the three must be present |
| `attachments` | ✓ | array ≤10 | the **whole** list; `[]` (or `attachments=`) clears |
| `attachments[].title` | ✓ | string ≤255 | |
| `attachments[].filepath` | ✓ | string ≤500 | opaque to us — we never fetch or validate the object |

```json
{
    "auditProtocol": "43/25-09-2026",
    "attachments": [
        { "title": "Απόφαση 10/2026", "filepath": "minio://beveoseis/10-2026.pdf" }
    ]
}
```

**Response (OK):** `data: BeveosiDetail` — the full record, `attachments` included. Statuses
never move: a locked row answers with the same status it had.

Failures: `4` with `extraData.fields` for a missing selector/list or a bad row (`4` also when
the βεβαίωση does not exist — `errors[0]` says so in Greek).

---

## Command: `get_beveosi_status`

The polling endpoint.

| Field | Req | Type | Rules |
|---|---|---|---|
| `id` / `auditProtocol` / `hashId` | ✓ | string | any ONE of the three must be present |

**Response:** `data: BeveosiDetail & { pending: boolean }` — the full record plus `pending`,
the only field the poller needs to read: it is `true` while the status is one of `sent`,
`certified_pending_closeday`, `needs_reconciliation`; when it is `false` there is nothing more
to wait for.

```json
{
    "data": {
        "id": 1,
        "auditProtocol": "1/06-08-2026",
        "hashId": "88468689707b4599be6efd959c4f241ed94449725881d8b0db35a55c140cd8ac",
        "status": "certified",
        "statusLabel": "Βεβαιωμένη",
        "locked": true,
        "afm": "137569280",
        "unitId": "1204",
        "unitAcronym": "ΙΝΡΑ",
        "debtorName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
        "kae": "82838",
        "fiscalYear": "2026",
        "apofNoEtos": "10/2026",
        "sunolo": "900.00",
        "doy": "9776",
        "mcNo": "2",
        "mcDate": "2026-08-06",
        "atbNo": "861679",
        "atbDate": "2026-08-06",
        "errorCode": null,
        "errorDescr": null,
        "submittedAt": "2026-08-06T22:57:19+03:00",
        "certifiedAt": "2026-08-07T06:12:40+03:00",
        "createdAt": "2026-08-06T22:57:18+03:00",
        "taftotites": [
            { "afm": "137569280", "fullName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ", "payId": "137569280910100000004000000001" },
            { "afm": "063745180", "fullName": "ΓΕΩΡΓΙΟΥ ΜΑΡΙΑ", "payId": "063745180910100000004000000002" }
        ],
        "comments": "Απόφαση 10/2026",
        "insFrequency": "1",
        "lastDayRule": "1",
        "afmYpogr": "003067224",
        "nameYpogr": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ",
        "discountPcg": null,
        "discountDate": null,
        "debtors": [
            {
                "afm": "137569280",
                "position": 0,
                "isPrimary": true,
                "fullName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
                "phone": "6971234567",
                "relationCode": null,
                "relationCategory": null,
                "amount": "900.00",
                "lineNo": "1",
                "taftotitaOfeilis": "137569280910100000004000000001",
                "origAmount": null
            },
            {
                "afm": "063745180",
                "position": 1,
                "isPrimary": false,
                "fullName": "ΓΕΩΡΓΙΟΥ ΜΑΡΙΑ",
                "phone": null,
                "relationCode": "20",
                "relationCategory": "3",
                "amount": "900.00",
                "lineNo": "2",
                "taftotitaOfeilis": "063745180910100000004000000002",
                "origAmount": null
            }
        ],
        "installments": [{ "aa": "1", "dueDate": "2026-09-30", "amount": "450.00" }],
        "kaeLines": [{ "kae": "82838", "amount": "900.00" }],
        "attachments": [{ "title": "Απόφαση 10/2026", "filepath": "minio://beveoseis/10-2026.pdf" }],
        "pending": false
    },
    "status": 1,
    "type": "single"
}
```

`amount` and `origAmount` are strings (money); `position` is an int, `0` = ο οφειλέτης;
`relationCode` / `relationCategory` are `null` for the primary debtor and the `get_lookups`
pair for each συνυπόχρεος. `origAmount` equals `amount` at issuance and stays the
pre-Μείωση reference even after a `submit_reduction` runs against this Ταυτότητα Οφειλής — a
Μείωση never rewrites it, it only shows up as a new `afek_records` row (`list_reductions`) and,
server-side at ΚΕΔ, as `reducedAmount`/`deletedAmount` on `get_payment_progress`. `attachments` is
detail-only (`[]` when none) — the list rows deliberately carry no attachments, and the
«Πορεία» action on the βεβαιώσεις table keys on `taftotites` instead.

**One Ταυτότητα Οφειλής per ΑΦΜ.** A βεβαίωση with two συνυπόχρεοι has three: ο οφειλέτης and
each συνυπόχρεος gets their own γραμμή and their own ΤΟ. This is the shape people get wrong.

Polling is cheap: the microservice only re-asks ΚΕΔ if the row has not been checked within
`KED_STATUS_POLL_THROTTLE` seconds (default 60), and a scheduled sweep settles rows anyway with
nobody watching. Poll every 10–30s; do not poll a row whose `pending` is `false`.

---

## Command: `list_beveoseis`

**Request** — all filters optional:

```json
{
    "status": "certified",
    "afm": "137",
    "unitId": "1204",
    "dateFrom": "2026-01-01",
    "dateTo": "2026-12-31",
    "page": "1",
    "page_size": "10"
}
```

| Field | Req | Type | Rules |
|---|---|---|---|
| `status` | — | enum string | one of the six `BeveosiStatus` values; `""` means no filter, not «no results» |
| `afm` | — | string | `^\d{1,9}$` — digits only; prefix match (`"137"`, not `"137-"`) |
| `unitId` | — | string ≤120 | **prefix match on either identifier** — the `unitId` you sent with the βεβαίωση **or** its `unitAcronym`, same style as `afm`; `""` means no filter |
| `dateFrom` / `dateTo` | — | string | `YYYY-MM-DD`; **camelCase** — see the naming traps |
| `page` | — | string | `^\d{1,6}$`, default `"1"` |
| `pageSize` / `page_size` | — | string | default 25, cap 200 |

**Response:** `type: "list"`; `data: BeveosiSummary[]` — the summary block only
(no debtors, installments, ΚΑΕ lines, comments or attachments; fetch those per row with
`get_beveosi_status`) — and `pagination: Pagination` is populated:

```json
{ "page": 1, "page_size": 5, "total_count": 4, "page_count": 1 }
```

---

## Command: `get_payment_progress`

**Πορεία είσπραξης μίας Ταυτότητας Οφειλής** (`retrievePayProgress`, spec §2.5 / Πίνακας 7): the
seven balances of one already-sent debt, as ΚΕΔ sees them right now.

Fetch-on-demand by design: nothing is stored locally, every call is a real ΚΕΔ call against the
daily quota, so the BFF refreshes when the user asks — never on a timer, never per keystroke.
`get_beveosi_status` deliberately does **not** refresh payments: every poll would spend quota on
a different ΚΕΔ resource for data nobody asked to see.

**Request** — two ways to name the debt:

```json
{
    "payId": "137569280910100000002000000001",
    "auditUserId": "u",
    "auditUserIp": "127.0.0.1"
}
```

| Field | Req | Type | Rules |
|---|---|---|---|
| `payId` | ✓* | string | `^\d{30}$` — the Τ.Ο. itself. *Required unless `id`/`auditProtocol` + `afm` is sent instead |
| `id` / `auditProtocol` | ✓* | string | the selector alternative — resolved through our own rows |
| `afm` | ✓** | string | `^\d{9}$`; **required with the selector**: one Τ.Ο. per ΑΦΜ, so with συνυπόχρεοι the ΑΦΜ says whose |
| `auditUserId` | ✓ | string ≤100 | Παράρτημα Γ — see the naming traps |
| `auditUserIp` | ✓ | string ≤45 | |

We are the system of record — the BFF should never have to remember a Τ.Ο. itself; the selector
resolves through `beveosi_debtors.pay_id`. A **raw `payId` answers even when no local row carries
it** (a Τ.Ο. from an earlier run); the reply then simply has no local context. `extOrg` is our
configuration, never a request field.

**Response:** `data: PaymentProgress` (`type: "single"`):

```json
{
    "data": {
        "payId": "137569280910100000002000000001",
        "afm": "137569280",
        "fullName": "ΠΑΠΑΔΟΠΟΥΛΟΣ ΙΩΑΝΝΗΣ",
        "auditProtocol": "43/25-09-2026",
        "apofNoEtos": "123/2026",
        "sunolo": "150.00",
        "firstEstablishedAmount": "150.00",
        "paidAmount": "75.00",
        "deletedAmount": "0.00",
        "reducedAmount": "0.00",
        "restAmount": "75.00",
        "overdueAmount": "75.00",
        "totalAmount": "75.00",
        "callSequenceId": "10070000011",
        "callSequenceDate": "2026-09-25T14:40:08.513+03:00"
    },
    "status": 1,
    "type": "single"
}
```

The seven amounts pass through verbatim (normalised to two decimals, bcmath, never derived).
**`totalAmount` is το απαιτητό, not το υπόλοιπο** — do not render it as «what remains».

**Failures:** a ΚΕΔ refusal (unknown Τ.Ο., unknown εξ. Οργανισμός) arrives as `4` with
`extraData: {errorCode, retryable: true}` — the call is read-only, so retrying is always safe. A
selector for a row close-day has not reached yet is refused with a message naming
`get_beveosi_status`, because the Τ.Ο. genuinely does not exist yet.

---

## Command: `get_payment_data`

**Οι κινήσεις πληρωμής μίας Τ.Ο. σε διάστημα** (`retrievePaymentData`, spec §2.7 / Πίνακας 9):
one row per payment collected on the debt inside the range.

Same selector rules as `get_payment_progress`; the range is **required** on both ends — a missing
bound would silently mean «ever».

**Request:**

```json
{
    "payId": "137569280910100000002000000001",
    "dateFrom": "2026-01-01",
    "dateTo": "2026-12-31",
    "auditUserId": "u",
    "auditUserIp": "127.0.0.1"
}
```

| Field | Req | Type | Rules |
|---|---|---|---|
| `payId` / selector | ✓ | — | exactly as `get_payment_progress` |
| `dateFrom` | ✓ | string | `YYYY-MM-DD`; **camelCase** — see the naming traps (`date_from` survives only by luck of `Carbon::parse`) |
| `dateTo` | ✓ | string | `YYYY-MM-DD`, `≥ dateFrom` |
| `auditUserId` / `auditUserIp` | ✓ | — | Παράρτημα Γ |

**Response:** `type: "list"`; `data: PaymentRow[]`, and `extraData` carries what the movements
table needs around it — the Σύνολο summed **server-side with bcmath**, so the money never becomes
a JavaScript float:

```json
{
    "data": [ { "paymentDate": "2026-09-25", "posoPlirwmhs": "75.00", "...": "..." } ],
    "extraData": {
        "payId": "137569280910100000002000000001",
        "afm": "137569280",
        "callSequenceId": "10070000012",
        "callSequenceDate": "2026-09-25T14:40:18.608+03:00",
        "totals": { "posoPlirwmhs": "75.00", "kefPlirwmhs": "75.00", "tokoiPlirwmhs": "0.00" }
    },
    "status": 1,
    "type": "list"
}
```

A range that covers no movements is **success with an empty `data: []`** (assumed behaviour — the
first live pilot answer decides; no wire sample exists for this operation). `pagination` stays
`[]`: ΚΕΔ returns the whole range. `dbtMcNo` + `dbtMcLine` in each row let the BFF tell payments
of one ΧΚ apart when several βεβαιώσεις share it.

---

## Command: `submit_reduction` (M4)

> **Status: pilot-proven end to end (2026-11-04).** A fresh βεβαίωση was certified live, then
> reduced and finalized with `deleteKedeAmount` → `deleteKedeComplete` in under six minutes
> (ΑΦΕΚ no. 1, οριστικό ΑΒΚΤ 404946, `callSequenceId` 10091590754 / 10091590768). The one rule
> that matters: **certifications with only 5-digit ΚΑΕ (no ΑΛΕ) must send `afekType: "2"`** —
> ΚΕΔ guidance of 2026-11-03; every earlier rejection was an `afekType: "1"` submission.
> `get_reduction_progress` was also proven live (2026-11-03, empty-window answer per its
> Πίνακας 4).

**Μείωση/Διαγραφή** (`deleteKedeAmount`, Kede_Delete_Amount_Service spec §2.1). Single-shot:
creates and sends an ΑΦΕΚ in one call — there is no save-draft equivalent for a Μείωση. The
target debt must already be `certified` (have an ΑΤΒ); name it either with `debtorId` directly,
or with `id`/`auditProtocol` (the certification) **plus** `afm` — a certification with
συνυπόχρεοι has several independently-reducible Ταυτότητες Οφειλής, so the ΑΦΜ disambiguates
exactly as it does for `get_payment_progress`.

**Request:**

```json
{
    "debtorId": 5,
    "afekType": "2",
    "comments": "Απόφαση 10/2026",
    "deptId": "137569280910104293686167500001",
    "approvalDate": "2026-10-01",
    "fiscalYear": "2026",
    "atbNo": "861675",
    "mcNo": "1",
    "lineNo": "1",
    "adtCode": "4",
    "decYear": "2026",
    "decisionNum": "10",
    "afkDoy": "9776",
    "kaeLines": [{ "kae": "82838", "amount": "100.00" }],
    "afmYpogr": "003067224",
    "nameYpogr": "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ",
    "auditUserId": "u",
    "auditUserIp": "127.0.0.1"
}
```

| Field | Req | Rules |
|---|---|---|
| `debtorId` / (`id`\|`auditProtocol` + `afm`) | ✓ | selector for the target `beveosi_debtors` row |
| `afekType` | ✓ | `1` reversible, `2` irreversible. **Use `2` for certifications with only 5-digit ΚΑΕ (no ΑΛΕ): ΚΕΔ confirmed on 2026-11-03 that `1` on such debts is rejected with `WS_PROCEDURE_ERROR` — «Δεν συμπεριλαμβάνεται ΚΑΕ Εντός Προϋπολ/μού και ο Τύπος Εκκαθάρισης θα πρέπει να είναι Διαγραφής Υπολοίπου». Our UI defaults to `2`. |
| `comments` | ✓ | VARCHAR2(**70**) — narrower than `submit_beveosi`'s 4000; must include Έτος + Αριθμός απόφασης |
| `deptId`, `fiscalYear`, `atbNo`, `mcNo`, `lineNo` | ✓ | must exactly match the target debt (`lineNo` = the ΧΚ line, i.e. the debtor's own `lineNo`) |
| `approvalDate` | ✓ | `YYYY-MM-DD` — the spec's sample marks it optional, but a real pilot call (2026-10-08) confirmed ΚΕΔ answers GEN_INVALID_DATA without it |
| `adtCode` | ✓ | `1` Απόφαση Δικαστηρίου, `4` Λοιπά |
| `decYear`, `decisionNum`, `afkDoy` | ✓ | decision year/number, ΔΟΥ code |
| `kaeLines` | ✓ | each `kae` must exist on the original debt; `amount` must not exceed its **remaining** deletable balance (checked locally, conservatively — every non-`failed` ΑΦΕΚ already submitted counts against it) |
| `decFile` / `attFileName` / `attExtension` | optional | base64 decision file — **pass-through only**, never stored locally |
| `afmYpogr`, `nameYpogr` | ✓ | must already be `declare_signers`-declared |
| `auditUserId` / `auditUserIp` | ✓ | Παράρτημα Γ |

**Response**, `type: "single"`, same shape as `submit_beveosi`'s three outcomes:

```json
{ "data": { "id": 1, "auditProtocol": "...", "status": "awaiting_finalization", "afekNo": "1", "message": "..." }, "status": 1, "type": "single" }
```

`failed` and `needs_reconciliation` come back the same way `submit_beveosi` reports them —
`status: 4` (BUSINESS_ERROR), the ΑΦΕΚ summary plus `resendable`. Unlike a βεβαίωση, a resend
after `failed` is **always a new row with a new `auditProtocol`**: there is no durable unsent
row here to resubmit through, a direct consequence of the single-shot design.

---

## Command: `get_reduction_status`

Polls one ΑΦΕΚ by `id` or `auditProtocol` — mirrors `get_beveosi_status`, including the inline
reconciliation throttle (`ked.status_poll_throttle`) that calls `deleteKedeComplete` when the
row is stale, so a poller cannot burn the daily quota. `data` is the full `ReductionPresenter`
detail shape (`kaeLines`, `comments`, `afmYpogr`, …) plus `pending: boolean`.

---

## Command: `list_reductions`

Paginated list of ΑΦΕΚ — mirrors `list_beveoseis` (same `page`/`page_size` snake_case pagination
block, same `dateFrom`/`dateTo` camelCase preference). Filters: `status`, `certificationId`,
`debtorId`, `afm`, `dateFrom`/`dateTo`.

---

## Command: `get_reduction_progress`

**Πρόοδος ΑΦΕΚ σε χρονικό διάστημα** (`deleteKedeProgress`, spec §2.3). On-demand, read-only
cross-check — **not** a prerequisite for `get_reduction_status`: `deleteKedeComplete`'s inputs
(`doy`, `year`, `afekNo`, `lineNo`) are already fully known the moment `deleteKedeAmount`
succeeds, so there is no date-discovery gate the way `retrieveVerificationProgress` is for the
progress service. Nothing is stored; every call costs ΚΕΔ quota.

**Request:** `{ "dateFrom": "2026-10-01", "dateTo": "2026-10-31", "auditUserId": "u", "auditUserIp": "127.0.0.1" }`

**Response:** `type: "list"`, one row per ΑΦΕΚ issued in the range: `{ doy, afekNo, issueDate, abktDoy, abktDate, abktNo, totalAmount, totalLines }`.

---

## Lifecycle, end to end

The operations behind each step — what `retrieveVerificationProgress` asks versus
`retrieveCloseDay`, and the payments pair — are mapped in
[`ked-operations.md`](ked-operations.md).

```
declare_signers            once, and again whenever the list changes
      │
save_beveosi_draft ◀──┐    optional, any number of times
      │               │
submit_beveosi ───────┘    → certified_pending_closeday   (NO ΑΤΒ yet)
      │                    → failed              (rejected; fix and resend)
      │                    → needs_reconciliation (unknown; DO NOT resend)
      ▼
get_beveosi_status         poll while pending → certified, with ΑΤΒ + one ΤΟ per ΑΦΜ
      │
      ▼
get_payment_progress       from `certified` on, when the user asks — never a timer
get_payment_data           each call is real ΚΕΔ quota; payments have no async
                           lifecycle, so there is nothing to poll

set_beveosi_attachments   off the lifecycle: local metadata, any status, no ΚΕΔ call

                          ── once `certified`, zero or more times, each independent (M4) ──
submit_reduction          creates + sends an ΑΦΕΚ in one call → awaiting_finalization
      │                                                       → failed (resendable, new row)
      │                                                       → needs_reconciliation (DO NOT resend)
      ▼
get_reduction_status      poll while pending → finalized, with abktNo
get_reduction_progress    on-demand cross-check only — not a gate, see its own section above
```

| status | Greek | Locked? | Meaning |
|---|---|---|---|
| `draft` | Πρόχειρο | no | Ours alone; deletable. |
| `sent` | Απεστάλη | yes | In flight. |
| `certified_pending_closeday` | Βεβαιώθηκε — αναμονή ΑΤΒ | yes | ΚΕΔ accepted it; the ΔΟΥ has not closed the day. |
| `certified` | Βεβαιωμένη | yes | ΑΤΒ and ΤΟ received. Terminal. |
| `failed` | Απορρίφθηκε | no | ΚΕΔ said no. Nothing exists at the ΔΟΥ. |
| `needs_reconciliation` | Εκκρεμεί έλεγχος | yes | Outcome unknown. Needs a human. |

**ΑΦΕΚ status (M4, `afek_records.status`)**

| status | Greek | Locked? | Meaning |
|---|---|---|---|
| `sent` | Απεστάλη | yes | In flight. |
| `awaiting_finalization` | Εκκρεμεί εκκαθάριση | yes | `deleteKedeAmount` accepted it; `afekNo` known, not yet finalized. |
| `finalized` | Οριστικοποιήθηκε | yes | `deleteKedeComplete` confirmed it. Terminal. |
| `failed` | Απορρίφθηκε | no | ΚΕΔ said no. |
| `needs_reconciliation` | Εκκρεμεί έλεγχος | yes | Outcome unknown. Needs a human. |

---

## Error handling (all commands)

Behaviour below the command layer belongs to `egov/rabbitmq-classes`, not to us:

- **Unknown command** → the interpreter replies `{"error": "command: ..., has not been
  recognised…"}` — a bare object, *not* a `RabbitMQResponse`. The BFF's `deserialize()` finds no
  matching properties and hands back a default **status-OK** response. A typo'd command name
  therefore looks like success; the dev bridge rejects unknown commands with a 404 for exactly
  this reason.
- **Exception inside a command** → the interpreter returns a JSON *string*. Same caveat, which
  is why every command here catches its own errors and always returns a full response.
- **Every message is acked in a `finally`**, success or failure. A poison message is consumed
  after one attempt rather than redelivered, and the queue is non-durable, so nothing survives a
  broker restart.

## Trying it locally

```bash
sail up -d && sail artisan migrate --seed
sail artisan rabbitmq:read                                          # shell 1

sail artisan bff:publish get_lookups                                # shell 2
sail artisan bff:publish get_lookups --params='{"knownVersion":"sha256:54eb05763e4341a6"}'
sail artisan bff:publish declare_signers --params='{"signers":[{"afm":"003067224","firstName":"ΕΥΓΕΝ","lastName":"ΧΡΙΣΤΟΠΟΥΛΟΥ"}],"auditUserId":"u","auditUserIp":"127.0.0.1"}'
sail artisan bff:publish submit_beveosi --params=@tests/fixtures/beveosi.json
sail artisan bff:publish list_beveoseis --params='{"page":"1","page_size":"10"}'
```

And once a row reaches `certified` (poll `get_beveosi_status` until the ΑΤΒ appears), the
payments door opens — both take the Τ.Ο. straight from the status reply:

```bash
sail artisan bff:publish get_payment_progress --params='{"payId":"137569280910100000002000000001","auditUserId":"u","auditUserIp":"127.0.0.1"}'
sail artisan bff:publish get_payment_data --params='{"payId":"137569280910100000002000000001","dateFrom":"2026-01-01","dateTo":"2026-12-31","auditUserId":"u","auditUserIp":"127.0.0.1"}'
```

Attachments are local and status-agnostic — try them on the certified row you just polled,
including the clear form (the empty string is the only «empty list» the wire can carry):

```bash
sail artisan bff:publish set_beveosi_attachments --params='{"auditProtocol":"1/06-08-2026","attachments":[{"title":"Απόφαση 10/2026","filepath":"minio://beveoseis/10-2026.pdf"}]}'
sail artisan bff:publish set_beveosi_attachments --params='{"auditProtocol":"1/06-08-2026","attachments":""}'
```

`bff:publish` encodes the body exactly as their `RpcClient` does. There is also a browser-shaped
door, `POST /api/dev-bff/commands` with `{command, params}`, enabled by `DEV_BFF_ENABLED=true` in
local development only — that is what `frontend/` uses.

To exercise the failure paths **on `KED_DRIVER=fake`** (the default locally — these two ΑΦΜ are
sentinel values our own fake driver recognises, not real pilot data, and do nothing special
against `KED_DRIVER=soap`), submit with ΑΦΜ `000000000` (ΚΕΔ rejects) or `999999999` (no
answer at all). For real-pilot error paths, see `docs/test-data.md`.
