# Architecture — ms.gov_ked, module `beveosi_ofeilwn`

Headless Laravel 10 / PHP 8.1 microservice for ΕΚΕΦΕ Δημόκριτος: certifies third-party
debts (Βεβαίωση Οφειλών) at the ΔΟΥ via the ΑΑΔΕ ΚΕΔ web services. The React/BFF layer
communicates with it exclusively over RabbitMQ; there is no frontend and no authentication
in this service — identity is handled upstream.

```
React UI ──▶ BFF ──▶ [RabbitMQ] ──▶ ms.gov_ked ──SOAP/WS-Security──▶ ΚΕΔ (ΑΑΔΕ)
                         ▲               │  ▲
                         └─── response ──┘  └── scheduler: ked:reconcile every 15'
```

Milestone 2 implements the whole chain: real ΚΕΔ calls, the certification state machine, the
full command surface and a scheduled reconciler. The bytes on the queue are in
[`message-contract.md`](message-contract.md), the schema in [`data-model.md`](data-model.md),
the two-terminal demo in [`rabbitmq-flow.md`](rabbitmq-flow.md).

**This service is the system of record.** The BFF stores nothing: it asks us for βεβαιώσεις,
for drafts, for lookup values, and it polls us for outcomes. That decision shapes everything
below — we hold drafts, we hold fields ΚΕΔ never sees, and we chase ΚΕΔ on a timer so that a
βεβαίωση nobody is watching still completes.

## The one thing to understand first

**The ΑΤΒ does not come back in the response.** `retrieveKedeAmount` returns ΔΟΥ, ΧΚ and
γραμμή; the Αριθμός Τριπλότυπου Βεβαίωσης and the Ταυτότητες Οφειλής exist only once the ΔΟΥ
closes the day, which can be hours later:

```
submit_beveosi ──▶ certified_pending_closeday ──(scheduled sweep)──▶ certified
                        no ΑΤΒ yet                       ΑΤΒ + one ΤΟ per ΑΦΜ
```

The polling command, the scheduler container and half the schema follow from that one fact.

## Ours and theirs

The transport is **not ours**. Consumer, message parsing, command dispatch and the response
class all come from Demokritos' `egov/rabbitmq-classes` (v1.1.27), auto-discovered from
`vendor/egov/`. We supply the domain and the command implementations, and nothing else.
That boundary is deliberate: their infrastructure changes on their schedule, not ours.

## The path of a message

| Step | Component | Behaviour |
|---|---|---|
| Consume | **theirs**: `artisan rabbitmq:read` → `Egov\…\Jobs\RabbitMQJob` | Queue declared **non-durable**, prefetch 1. Every message is acked in a `finally`, success or failure — a poison message is consumed after one attempt rather than redelivered, and nothing survives a broker restart. Runs inline because `QUEUE_CONNECTION=sync`. |
| Parse | **theirs**: `RabbitMQMessageInterpreter::loadMessageInfo()` | The body is `command|http_build_query(params)`, split on `|` then run through `parse_url` + `parse_str`. Nested arrays survive; every value arrives as a **string**. Params prefixed `_` are held separately as internal params. There is no `token` field. |
| Dispatch | **theirs**: `RabbitMQMessageInterpreter::process()` + `config/rabbit_commands.php` | Looks the command up under `commands`, instantiates the class and calls `execute($params)`. (`api_commands` is for REST proxying and does not apply here.) An unknown command returns a bare `{"error": …}`, not a `RabbitMQResponse`. |
| Execute | **ours**: `app/Commands/…` implementing their `App\Commands\ICommand` | Nine commands (see below), all extending `Kede\KedeCommand`, which catches everything and returns a **JSON string**. Note their interpreter does `new $class` — **no container injection**, so commands resolve services with `app(...)` inside `execute()`. |
| Respond | **theirs**: `Egov\…\RabbitMQ\RabbitMQResponse` | Keys in declaration order: `data, pagination, extraData, errors, warnings, messages, status, type`. `status` is an int enum (1 OK, 2 WARNING, 3 ERROR, 4 BUSINESS_ERROR); `type` is lowercase `single`/`list`/`lookup`. Whatever `execute()` returns is published verbatim to the request's `reply_to` with its `correlation_id`. |

Because their `deserialize()` on the BFF side silently degrades anything that is not a
`RabbitMQResponse` into a default OK response, **our commands must catch their own errors**
and always return a complete response object. Never let an exception escape as a string.

### The command surface

Registered in `config/rabbit_commands.php` under `commands` — never `api_commands`, which
assumes an HTTP client hitting a REST endpoint, and ΚΕΔ is SOAP.

| Command | Does |
|---|---|
| `get_lookups` | **Every** lookup set in one cacheable payload, with a content hash as `version`. Deliberately not one command per list. |
| `declare_signers` | `retrieveNames`. The whole list, ≤ 10. Writes locally only after ΚΕΔ accepts. |
| `save_beveosi_draft` / `delete_beveosi_draft` | We own drafts. Delete refuses anything but a draft. |
| `submit_beveosi` | `retrieveKedeAmount` via `CertificationService`. |
| `get_beveosi_status` | Polling, with an inline reconcile throttled by `KED_STATUS_POLL_THROTTLE`. |
| `list_beveoseis` | Filters + `pagination`. Each row carries `taftotites` — the Τ.Ο. per ΑΦΜ, empty before close-day. |
| `get_payment_progress` | `retrievePayProgress` via `PaymentProgressService`. Read-only, fetch-on-demand. |
| `get_payment_data` | `retrievePaymentData`; the movements of one Τ.Ο. in a range, with server-side totals in `extraData`. |
| `set_beveosi_attachments` | Purely local: replaces the `{title, filepath}` list of one βεβαίωση, at **any** status — never sent to ΚΕΔ, so the Παράρτημα Ζ lock does not apply. |

### Dev-only publishing

Two ways in, sharing `App\Bff\RpcPublisher` so they cannot drift apart:

- `artisan bff:publish` — encodes exactly as their `RpcClient` does, waits on an exclusive
  reply queue, prints the reply.
- `POST /api/dev-bff/commands` — the same thing for a browser, since `frontend/` cannot speak
  AMQP. Registered **only** when `DEV_BFF_ENABLED` and the app is not in production; it has no
  authentication, so the route simply does not exist elsewhere. It casts every scalar to a
  string, because `parse_str` means commands only ever see strings on the real path — without
  that the browser would be exercising a contract that does not exist.

## Certification, and why it is stateful

`app/Ked/Progress/CertificationService` sends a βεβαίωση and maps the outcome onto the state
machine in [`data-model.md`](data-model.md). Three rules from Παράρτημα Ζ drive it:

1. **Lock at the moment of sending**, and commit that lock *before* the SOAP call — a crash
   mid-call must still leave a durable locked row.
2. **A rejection is proof the debt was not registered.** Unlock, keep the `audit_protocol`, let
   them fix and resend. Reusing that id is how ΚΕΔ recognises the resend as the same βεβαίωση.
3. **No answer is proof of nothing.** The row stays locked in `needs_reconciliation`. An empty
   `retrieveVerificationProgress` does not settle it either — the ΧΚ may open on a later date —
   so `ReconciliationService` only ever *promotes* rows it can positively match on ΔΟΥ + ΧΚ, and
   never unlocks anything. Stuck rows are escalated to a human by `artisan ked:reconcile`.

Two refinements (Φάση 4, 2026-11-04) around rule 3's edge:

- **Provably never-sent is not ambiguous.** The transport layer classifies the failure:
  connect/TLS/DNS failures (`KedeNeverConnectedException`) mean no byte reached ΚΕΔ, so the
  ambiguity the lock exists for never arose — the row goes back to the state it came from and
  the reply carries `retryable: true` (spec §4's retryable case). Read timeouts and anything
  unrecognised stay ambiguous — fail-safe, because ext-soap's strings are not a contract.
- **The human exit is a command, not a DB edit.** `artisan ked:settle` settles a stuck row two
  ways, always with a named decider (`--by`) and a written justification: `--absent` unlocks it
  as `failed` (resendable, same `audit_protocol`), `--found --mc-no=… --doy=…` records the ΧΚ
  it was found in and leaves completion to the sweep. Stuck rows past
  `KED_STUCK_ALERT_ATTEMPTS` are logged on every sweep and emailed to `KED_ALERT_EMAIL` at
  most once a day. The proof-of-absence WINDOW rule (auto-release after N silent days) is a
  pending Δημόκριτος decision — until they set the number, nothing auto-unlocks.

Getting rule 3 wrong raises duplicate debts against real people at the ΔΟΥ. That is the whole
reason this service carries a database.

The duplicate guard is the backstop: a unique index over «one live βεβαίωση per
(ΑΦΜ, ΚΑΕ, έτος, αρ. απόφασης)», which catches the case where the BFF times out, the user
assumes failure and submits again while the first call is still with ΚΕΔ.

## Talking to ΚΕΔ

`app/Ked/Progress/KedeProgressClient` is built in **non-WSDL mode** (`location` + `uri`, no
`?wsdl` fetch at construction) and hands a self-built envelope straight to `__doRequest`, so
what goes on the wire is byte-comparable with the known-good Postman requests rather than
whatever PHP's SOAP encoder decides to emit.

`KED_DRIVER` picks the transport. `fake` (the default) replaces **only the network hop** —
`FakeKedeProgressClient` overrides a `transport()` seam on `WsseSoapClient`, so envelope
building, WSSE injection, parsing and logging all still run against canned responses taken
from the pilot. A fresh checkout is therefore demoable with no ΑΑΔΕ credentials, and switching
to `soap` changes one line of behaviour. `artisan ked:smoke` drives all six operations by
hand, and refuses the certifying call on the live service without `--write` — the two payment
reads are the exception: read-only, so `ked:smoke --payId=…` interrogates a Τ.Ο. from an
earlier certified run against the live pilot without any gate. That is deliberately the
calibration tool for those two calls, which have no wire sample anywhere.

### Payments are fetch-on-demand, on purpose

The two payment commands store **nothing**. Every view of «Πορεία Είσπραξης» is one live ΚΕΔ
call — exactly what a cache miss would cost — and `get_beveosi_status` does not refresh
payments, because every poll would spend quota on a resource nobody asked to see. The audit
obligation is already covered (`ked_call_log` + `ked_audit_records`), the state machine has no
reader for payment data, and a payments table would need an invented unique key before a
single live response has been seen. The deferred design lives in `data-model.md` as an open
question.

Every call is written to `ked_call_log` in a `finally`, with the WSSE password masked. That
journal is an obligation on the Φορέας (Παράρτημα Γ), and it is the only evidence available
when a call goes ambiguous.

## Type discipline

From the ΚΕΔ interface spec, enforced in validation, stubs and schema:

- Money is `DECIMAL(17,2)` and travels as a **string with two decimals** — never a float.
- ΑΦΜ, ΚΑΕ, ΔΟΥ, `extOrg` and Ταυτότητα Οφειλής are **strings**; leading zeros are significant.
- `atbNo` reaches 20 digits: `DECIMAL(20,0)` in the schema, a string in PHP/JSON — it must
  not be parsed into a 64-bit integer.

The transport reinforces this: `parse_str` hands us strings for everything, so a rule that
accepts a number would be accepting something the BFF can no longer send anyway.

## Layout

```
app/
├── Bff/                    RpcPublisher — dev-only, shared by bff:publish and the HTTP bridge
├── Commands/Kede/          the thirteen commands, KedeCommand base, SubmitBeveosiRules,
│                           DeleteKedeAmountRules, AttachmentRules, BeveosiPayload
│                           (params → service), CertificationPresenter / ReductionPresenter (→ JSON)
├── Console/Commands/       bff:publish, ked:smoke, ked:smoke-delete, ked:reconcile,
│                           ked:reduction-reconcile
├── Ked/
│   ├── WsseSoapClient      SOAP 1.1 + WS-Security UsernameToken, TLS 1.2, transport() seam
│   ├── AuditRecordFactory  the auditRecord block; auditProtocol is our per-βεβαίωση/ΑΦΕΚ id
│   ├── Progress/           KedeProgressClient, Fake…, CertificationService,
│   │                       ReconciliationService, KedCallRecorder, enums, Xml/
│   └── Delete/             KedeDeleteClient, Fake…, ReductionService,
│                           ReductionReconciliationService, AfekStatus, Xml/ — M4, done
├── Models/                 BeveosiCertification + children, AfekRecord + AfekKaeLine,
│                           DeclaredSigner, lookups
└── Http/Controllers/       DevBffController (local only)

frontend/                   sample React app; src/lib/fields.ts is the BFF fields spec
```

The two ΚΕΔ services use **separate credential pairs** and are never mixed.

## Type discipline

From the ΚΕΔ interface spec, enforced in validation, schema and presenters:

- Money is `DECIMAL(17,2)` and travels as a **string with two decimals** — never a float.
- ΑΦΜ, ΚΑΕ, ΔΟΥ, `extOrg` and Ταυτότητα Οφειλής are **strings**; leading zeros are significant.
- `atbNo` reaches 20 digits: `DECIMAL(20,0)` in the schema, a string in PHP/JSON — it must
  not be parsed into a 64-bit integer.

The transport reinforces this: `parse_str` hands us strings for everything, so a rule that
accepts a number would be accepting something the BFF can no longer send anyway.

## Environments

- **Development:** Laravel Sail (`compose.yaml`) — app container pinned to PHP 8.1,
  `mariadb:10.6` behind a service still named `mysql`, `rabbitmq:3-management`, and a
  `scheduler` service running `artisan schedule:work`. See `README.local.md`.
- **Production (on-prem):** php-fpm, MariaDB 10.6; the consumer runs under supervisor
  (`artisan rabbitmq:read`). Nothing in the worker or config assumes Sail.
  **The scheduler must run there too** — without it the ΑΤΒ never arrives. Either
  `schedule:work` under supervisor or a single cron entry calling `schedule:run` each minute.

### Operational notes

- `KED_DRIVER` must be `soap` in production, and the ΚΕΔ credentials filled in. It defaults to
  `fake`, which is the safe default but silently certifies nothing.
- The ΚΕΔ **daily call quota** (`GET_AUTHORIZATION_MAX_OPEN_CALLS_EXCEEDED`) is a real budget
  and ΑΑΔΕ has not told us the limit. Three things spend it: submissions, the sweep
  (`KED_RECONCILE_INTERVAL`, one call per open date plus one per open ΧΚ) and status polling
  (`KED_STATUS_POLL_THROTTLE`). Validation deliberately rejects locally whatever ΚΕΔ would
  reject anyway, because a rejected send still costs a call.
- `DEV_BFF_ENABLED` must stay `false` outside a developer's machine. The route is not
  registered in production regardless, but the flag should not be lying either.
- Watch for rows stuck in `needs_reconciliation`: `artisan ked:reconcile` reports them. They
  mean nobody knows whether a real debt exists, and only a person can find out.
