# Milestone 2 build plan — real ΚΕΔ flow (fake-first) + dev BFF bridge + React demo

> **Status: DELIVERED 2026-08-06.** All phases done; 102 tests passing. The plan below is kept
> as the record of what was decided and why — for what actually exists read
> `../architecture.md`, `../data-model.md` and `../message-contract.md`.
>
> **Scope grew during execution, by owner decision:** this service is the system of record, so
> it also owns drafts, the UI-only fields ΚΕΔ never sees, the lookup values and a **scheduled
> reconciler** (a fourth compose service). The BFF stores nothing.
>
> **What differs from the plan as written:**
> - Lookups are **one `get_lookups` command**, not one per set — cached against a content hash.
> - The **Ταυτότητα Οφειλής is per ΑΦΜ**, so it lives on `beveosi_debtors`, not on the
>   certification. A βεβαίωση with two συνυπόχρεοι has three of them.
> - The duplicate guard is a plain column + unique index maintained in application code:
>   MariaDB 10.6 rejects the stored generated column that was the first choice (error 1901).
> - Παράρτημα Ζ's unlock rule is conjunctive, so reconciliation **never auto-unlocks** — an
>   empty `retrieveVerificationProgress` is not proof of absence.
> - All six audit fields are mandatory for this service; `CLAUDE.md` was corrected.
> - The M1 `SubmitBeveosiCommandTest` was deleted: every assertion was about the stub it
>   replaced. `KedeCommandsTest` covers the same ground against real behaviour.
>
> **Still open, none blocking:** the ΚΕΔ daily call quota (unknown — the sweep interval is a
> guess), pilot credentials, and the deferred PDF attachment.

## Context

The wire format is no longer an unknown: `egov/rabbitmq-classes` v1.1.27 is installed and
verified end-to-end, so there is no codec abstraction to hide behind and nothing to guess.
Goal: build Milestone 2 plus a sample React frontend (in `frontend/` in this repo) to
exercise the whole flow end-to-end: forms → HTTP → RabbitMQ → worker → ΚΕΔ client → reply → UI.

Decisions taken with the owner (2026-08-06):

- **Full M2 command surface**: `submit_beveosi` (extended fields), `declare_signers`,
  `get_beveosi_status`, `list_beveoseis`.
- React app **inside the repo** (`frontend/`, Vite; port 5173 already published in compose).
- ΚΕΔ via a **fake driver first**, real pilot as a gated smoke test.

What exists already (M1, ported into this repo): working `WsseSoapClient` (SOAP 1.1, TLS 1.2,
WSSE injection, unit-tested), stub `KedeProgressClient` (all 4 methods throw),
`AuditRecordFactory`, migrations for `beveosi_certifications` (locking table) and
`ked_call_log` (no models yet), `submit_beveosi` (stub, inline validation) registered under
`commands` in `config/rabbit_commands.php`, `BffPublishCommand` (publishes in the real wire
format, waits on an exclusive reply queue), sanitized Postman collection with known-good
request/response XML for all 4 progress operations.

What comes from **their** package, and is therefore not ours to design: the consumer
(`artisan rabbitmq:read`), message parsing, command dispatch, and `RabbitMQResponse`. New
commands are plain classes implementing `App\Commands\ICommand` that `return json_encode($response)`
— see `docs/architecture.md`. The M1-era `App\Messaging\*`, `CommandDispatcher` and
`RabbitConsumeCommand` from `ms.beveosiofeilon` do not exist here; ignore references to them
in the historical plans.

Hard constraints (CLAUDE.md): all php/composer via Sail; `compose.yaml` only; Laravel 10 /
PHP 8.1 pinned; credential values never leave `.env` and `docs/source_docs/credentials/`
(developer hand-fills `.env`); money/ΑΦΜ/ΚΑΕ/atbNo as strings, `atbNo` DECIMAL(20,0);
Claude never commits; never push to the `demokritos` remote.

## Key design choices

- **Fake = transport-level**: `FakeKedeProgressClient extends KedeProgressClient`
  overriding `__doRequest()` with canned response envelopes (fixtures from the sanitized
  Postman responses — credential-free). Real XML building, WSSE injection and parsing run
  in dev/tests; only the network hop is skipped. Scenario selection via magic input values
  (invalid-data error, SoapFault → ambiguous path, closeDay empty). Switch:
  `config('ked.driver')` = `KED_DRIVER` env, `fake|soap`, default `fake`; container binds
  `KedeProgressClient::class` accordingly.
- **Non-WSDL SoapClient**: construct with `null` + `location` (plain endpoint, no `?wsdl`)
  + `uri` (body namespace); send literal XML via `SoapVar(XSD_ANYXML)`; parse
  `__getLastResponse()` raw XML. Avoids construct-time WSDL fetch. Fallback if pilot
  rejects the envelope: vendored WSDL or direct `__doRequest`.
- **State machine** (`CertificationStatus` enum on `beveosi_certifications.status`):
  `pending` → `sent` (locked) → `certified_pending_closeday` → `certified`;
  business error → `failed` (unlocked, resendable, **same audit_protocol reused** — that id
  is what lets ΚΕΔ detect duplicates); ambiguous outcome → `needs_reconciliation` (stays
  locked; only proof-of-absence via retrieveVerificationProgress + retrieveCloseDay
  unlocks — Παράρτημα Ζ).
- **Concurrency**: natural key unique index (afm, kae, fiscal_year, apof_no_etos);
  `DB::transaction` + `lockForUpdate()` on submit; SOAP call after commit.
- **HTTP bridge**: one generic `POST /api/dev-bff/commands` `{command, params}`;
  publish/wait logic extracted from `BffPublishCommand` into `App\Bff\RpcPublisher`
  (shared by artisan + controller; the old `App\Messaging` namespace is gone). It must keep
  encoding bodies as `command|http_build_query(...)` and declaring the queue non-durable.
  Route registered only when `DEV_BFF_ENABLED` and
  `app()->environment('local')`. CORS already `*` on `api/*`.
- **Frontend**: `frontend/` Vite + React + TS, plain fetch, no router/state lib. One
  `src/api.ts` (`callCommand`), one `src/fields.ts` with typed per-command field
  definitions (incl. repeatable rows for δόσεις/ΚΑΕ/συνυπόχρεοι) — doubles as the fields
  spec deliverable promised to the BFF team on 2026-08-05, liftable into the owner's own
  React app. Text inputs (never `type=number`), validated with the same regexes.

## Steps

### Phase 0 — Groundwork
1. **Transcribe Παράρτημα Ζ**: Read tool on `docs/source_docs/specs/ked-progress-api_101.pdf`
   pages (Greek text not machine-extractable otherwise) → `docs/internal/parartima-z-notes.md`.
   Validate/adjust the state machine BEFORE writing CertificationService. **Still to do.**
2. ~~**MariaDB 10.6** in `compose.yaml`~~ — **done 2026-08-06**: this repo's `compose.yaml`
   already runs `mariadb:10.6` on volume `sail-mariadb`, with the MariaDB init script and
   healthcheck. `soap` and `sockets` verified present in the 8.1 runtime.

### Phase 1 — ΚΕΔ client
3. **Config**: `config/ked.php` add `driver`, `progress.endpoint`, `progress.namespace`;
   `.env.example` adds `KED_DRIVER=fake`, `KED_PROGRESS_ENDPOINT=…` (creds stay empty).
4. **XML layer** `app/Ked/Progress/Xml/`: request builders (element names exactly per
   Postman; strings throughout; source of truth = Postman collection +
   `KEDE_Progress_Service_v1.03_MySQL.xlsx` — read, don't guess) and `KedeResponseParser`
   → `KedeResult` DTO (outputRecord, callSequenceId/Date, errorCode/Descr, `isSuccess()`
   treating empty errorRecord and `errorCode==='0'` as success; handles errorMsg inside
   OutputRecord, list unwrapping, **trims space-padded afm** in tofeilisRecord).
5. **Implement `KedeProgressClient`** (4 methods): build → `__soapCall` → parse; new
   `KedCallRecorder` persists every call to `ked_call_log` in `finally`, **WSSE password
   masked** in the stored request XML.
6. **`FakeKedeProgressClient`** + fixtures in `resources/ked/fake/*.xml` (from Postman
   responses; dynamic mcNo/atbNo/payId/callSequenceId templated so the demo flow is
   coherent) + container binding by driver.

### Phase 2 — Persistence + services
7. **Migrations**: alter `beveosi_certifications` (rename `xk_no`→`mc_no`; add `mc_date`,
   `atb_date`, `txt_code`, `ypiresia_descr`, `ins_frequency`, `last_day_rule`, discount
   cols, `sunolo` decimal(17,2), `comments`, `apof_no_etos`, `afm_ypogr`, `name_ypogr`,
   unique(afm,kae,fiscal_year,apof_no_etos)); new child tables `beveosi_installments`
   (aa, due_date, amount), `beveosi_kae_lines`, `beveosi_synypochreoi`; new
   `declared_signers`; nullable FK on `ked_call_log`. Types per the xlsx.
8. **Models**: `BeveosiCertification` (enum cast, decimal:2 casts, `atb_no` string,
   hasMany children), `KedCallLog`, `DeclaredSigner`, child models.
9. **Services** `app/Ked/Progress/`: `CertificationService::submit()` (lock txn → call →
   outcome mapping) and `ReconciliationService::reconcile()` (verificationProgress match by
   doy+mcNo, closeDay match by lineNo+trimmed afm → atb_no/taftotita_ofeilis; proven-absent
   → failed+unlock; else stay locked).

### Phase 3 — Commands
10. **Extract validation** to `app/Commands/Kede/SubmitBeveosiRules.php`; extend to full
    field set (installments as `{aa, dueDate, amount}` rows, kaeLines, txtCode,
    ypiresiaDescr, insFrequency, lastDayRule, optional doy/discounts, sunolo cross-check).
11. **Rewrite `SubmitBeveosiCommand`**: rules → `CertificationService` → response (status,
    mcNo/lineNo, auditProtocol, «ΑΤΒ arrives async — poll get_beveosi_status»); duplicate
    while locked → clear ERROR. Update `tests/fixtures/beveosi.json`.
12. **New commands** + registry (`config/rabbit_commands.php`): `declare_signers`
    (retrieveNames, ≤10, replace `declared_signers` in txn; new `KED_FOREAS_AFM` config),
    `get_beveosi_status` (inline reconcile when pending/ambiguous), `list_beveoseis`
    (paginate + pagination block).
13. **`artisan ked:reconcile`** for stuck rows (scheduler deliberately not enabled yet).

### Phase 4 — Bridge
14. **`App\Bff\RpcPublisher`** extracted from `BffPublishCommand` (command becomes a
    thin wrapper; behaviour unchanged).
15. **`POST /api/dev-bff/commands`**: controller + env-gated route in `routes/api.php`;
    `.env.example` gets `DEV_BFF_ENABLED=false`.

### Phase 5 — Frontend
16. **`frontend/`**: Vite React TS scaffold (npm inside the sail container); `src/api.ts`,
    `src/fields.ts`, pages Signers / SubmitBeveosi (dynamic rows) / Status (poll) / List
    (pagination); `frontend/README.md` run instructions; gitignore node_modules.

### Phase 6 — Tests, docs
17. **Tests**: unit (builders/parser vs Postman-shaped fixtures), feature with fake driver +
    `RefreshDatabase` (CertificationService, Reconciliation, all commands, double-submit,
    resend-reuses-audit_protocol), bridge test with fake `RpcPublisher` + 404-when-disabled.
    The existing 3 test files stay green (`SubmitBeveosiCommandTest` updated, and
    `InterpreterIntegrationTest` extended with the new commands — it is the cheapest guard
    that a new command is wired into their dispatcher correctly).
18. **Docs**: `docs/message-contract.md` + `docs/architecture.md` — new commands, revised
    submit payload, state machine, polling narrative, `KED_DRIVER`, dev bridge. Keep the
    response-shape facts as corrected on 2026-08-06 (int `status`, lowercase `type`); the
    `commands` vs `api_commands` question is settled — ours are plain `commands`.

## Verification
1. `sail down -v && sail up -d && sail artisan migrate` — MariaDB healthy, soap ext present.
2. `sail test` green.
3. Worker + `bff:publish` smoke: declare_signers → submit (expect
   `certified_pending_closeday`) → get_beveosi_status (flips to `certified` via fake
   closeDay) → list_beveoseis; check `ked_call_log` rows, password masked.
4. Ambiguous fixture → row locked `needs_reconciliation` → `ked:reconcile` resolves.
5. Browser E2E: `DEV_BFF_ENABLED=true`, worker running, `npm run dev` in frontend → full
   flow: signers → submit with δόσεις + συνυπόχρεος → status poll → paginated list.
6. Pilot smoke (only when the developer fills creds + `KED_EXT_ORG` in `.env`,
   `KED_DRIVER=soap`): `declare_signers`/retrieveNames first (cheapest op), compare the
   logged envelope vs Postman before ever calling retrieveKedeAmount live.

## Risks / open
- SoapClient-emitted envelope vs pilot tolerance — gated by pilot smoke; fallbacks noted.
- Παράρτημα Ζ exact wording may refine unlock rules — that is why transcription is step 1.
- `extOrg` (production value) + pilot access still pending from Demokritos; the fake driver
  keeps everything demoable meanwhile.
- One-ΧΚ-batching semantics unknown (mc_no + line_no schema accommodates both).
- Payments (M3) and delete service (M4) deliberately untouched; `KedeDeleteClient` stays a
  seam. Written scope confirmation still required before M3 (see internal notes).
