# Βεβαίωση Οφειλών Microservice — Build Plan (Milestone 1)

> **HISTORICAL (2026-08-06).** Delivered, then ported into this repo. It describes the
> standalone `ms.beveosiofeilon` service, including a messaging layer (`App\Messaging\*`,
> `CommandDispatcher`, `rabbit:consume`) that does not exist here — `egov/rabbitmq-classes`
> replaced it. Kept as a record of what was built and why.

> **Note (2026-08-06):** this plan was written when the repo lived inside a parent working
> directory. Paths of the form `source_docs/...` now live at `docs/source_docs/...`, and the
> "never commit source_docs / credentials" instruction below was superseded by an explicit
> owner decision to commit them. The body is kept as a historical record.

---

## ▶ START HERE — instructions for the implementing agent

You have been pointed at this file to build Milestone 1. Read this whole document,
then implement the section titled **"The Fable prompt"** near the end — that fenced block
is the complete, authoritative specification. Everything above it is context that explains
*why*; the fenced block tells you *what*.

**State of play — the scaffold already exists, do not recreate it:**

- Working directory: `~/projects/dimikritos-ked/ms.beveosiofeilon`
- Laravel **10.50.2** + Sail are installed, with a clean initial commit
  (`Initial Laravel 10 + Sail scaffold`). Build on top of it.
- **Do not change the Laravel version.** Laravel 10 is a deliberate decision to match
  Demokritos' guide, made with the security trade-off understood and accepted.
  `composer.json` carries `policy.advisories.block=false` for this reason — leave it.
- Sail generated **`compose.yaml`** (not `docker-compose.yml`) with a MySQL service.
  Extend that file; do not create a second one. Its PHP runtime defaults to **8.5**, which
  is outside Laravel 10's supported range and **must** be pinned to 8.1.
- **There is no local PHP or Composer.** Every `php` / `composer` / `artisan` invocation must
  run through Sail or a throwaway `composer:2` container.
- Specs, the ΚΕΔ SOAP documentation and a working Postman collection are in
  `~/projects/dimikritos-ked/source_docs/`. **That folder contains live ΑΑΔΕ pilot
  credentials in plaintext.** Read them if you must, but never copy them into code, tests,
  fixtures, docs or git.

**Before reporting done:** run the verification steps in the "Verification" section yourself.

**When finished:** list every point where you had to guess because Demokritos' guide was
silent — especially the inbound message envelope and the queue / exchange / routing-key
topology. That list becomes the follow-up questions we send them.

---

## Context

ΕΚΕΦΕ Δημόκριτος currently certifies third-party debts to the ΔΟΥ by filling in an Excel
sheet and sending it physically. ΦΕΚ 1911/Β΄/2019 obliges them to do this electronically via
the ΑΑΔΕ Κέντρο Διαλειτουργικότητας (ΚΕΔ) web services. Logicea is building the microservice
that performs that certification.

The May 2026 offer (`101-052726dem_ked.docx`) proposed a standalone Java Quarkus + React +
AWS system. **That is superseded** by the 08 June and 15 July 2026 technical integration
meetings and `Beveosi_Ofeilon_PHP_Confirmation.docx`. The agreed shape is now:

- **PHP / Laravel** standalone microservice (explicitly requested by Demokritos).
- **No frontend from us.** Demokritos builds the forms in their React / BFF layer. We deliver
  input-field specs and data lists.
- **No auth from us.** D.U.A. handles identity; the BFF propagates the token to us.
- **RabbitMQ is the only transport.** BFF → RabbitMQ → our MS → ΚΕΔ → back over RabbitMQ.
- **On-premises** production hosting at Demokritos; development on Logicea premises.

`Creating+a+New+Microservice+(External)+…doc` is Demokritos' own guide for building an
external MS against their `egovPackage`. We follow it.

**Intended outcome of Milestone 1:** a running Laravel MS that consumes a message off a local
RabbitMQ, dispatches it through the command pattern, and publishes back a correctly shaped
`RabbitMQResponse` JSON — so Demokritos can confirm the message contract before we invest in
the ΚΕΔ business logic.

---

## Findings that change the work

These came out of reading the source docs and are worth stating explicitly, because several
contradict what is written down elsewhere in the project.

1. **ΚΕΔ is SOAP, not REST.** `Beveosi_Ofeilon_PHP_Confirmation.docx` §2 says "calls the KED
   API over HTTPS / REST". It does not. Per `ked-progress-api_101.pdf`, it is SOAP 1.1 with
   **WS-Security UsernameToken (PasswordText)** over **TLS 1.2**:
   - Pilot WSDL: `https://test.gsis.gr/esbpilot/kedeProgressService?wsdl`
   - Prod WSDL: `https://ked.gsis.gr/esb/kedeProgressService?wsdl`
   - Body namespace: `http://gsis.ggps.interoperability/KedeProgressInterface`
   This correction should be pushed back to Demokritos in writing.

2. **There are two separate ΚΕΔ services, with two separate credential pairs.** `KED Dev
   Creds.docx` holds pilot credentials for both:
   - `kedeProgressService` — certification (this build)
   - `kedeDeleteService` — Μείωση/Διαγραφή Βεβαίωσης, spec `Kede_Delete_Amount_Service_K___v_0.99.pdf`
     (`deleteKedeAmount`, `deleteKedeHub`, `deleteKedeProgress`, `deleteKedeComplete`)
   The internal estimate says the Delete spec is missing — **we now have it.** Cancel is
   therefore buildable, but per decision it is scoped as *structure only* for now.

3. **`egov/rabbitmq-classes` is a blocker and is not yet available to us.** The guide requires
   `composer require egov/rabbitmq-classes:1.1.x` from `gitlab.skel.iit.demokritos.gr`, and
   messages travel as a *single proprietary hash string*, not raw JSON. We do not have the
   package or the format spec. **We must not guess the wire format.** Everything that touches
   it goes behind our own interface (below).

4. **The guide has real defects to work around.** Its `.env` defines `INVOICES_*` keys but
   `config/microservices.php` reads `MYSERVICE_*` — they do not match, so a literal copy
   yields null config. It also never documents the artisan command that starts the consumer
   worker, nor the inbound message envelope. Both must be asked for.

5. **Anti-duplicate locking is a hard ΚΕΔ rule** (Παράρτημα Ζ): lock every βεβαίωση the moment
   it is sent; unlock only after `retrieveVerificationProgress` + `retrieveCloseDay` prove it
   was not certified. Each βεβαίωση must carry a unique local id in `auditRecord/auditProtocol`
   so ΚΕΔ can detect duplicates. This makes the MS **stateful** — it needs a database. The
   "stateless vs db" open question in `Simeioseis_Meeting_KED.docx` is effectively answered: DB.

---

## Environment prerequisites (WSL2 Ubuntu + Rancher Desktop)

Verified working: `git 2.43`, `docker 29.5.3-rd` (daemon reachable, 16 GB), `docker compose
v5.1.4`, `node v24.14`. PHP and Composer are **not** installed locally — and with Laravel Sail
they don't need to be.

**Use Laravel Sail.** Everything runs in containers, so there is no PHP install in WSL, and the
`sail-8.1` runtime gives us the PHP 8.1 that Demokritos' guide specifies without the
`ondrej/php` PPA. Two limits to work around: Sail has **no RabbitMQ preset**, so that service is
added to the generated compose file by hand; and **Sail is a development tool only** — on-prem
production at Demokritos will be php-fpm with supervisor keeping the consumer alive, so no
Sail-specific assumption may leak into the worker or the deploy docs.

**Repo layout.** Create the Laravel project as its own repo in a **subdirectory**, leaving
`source_docs/` outside it. This matches Demokritos' `ms.` naming convention and — more
importantly — puts the plaintext ΑΑΔΕ pilot credentials physically outside the deliverable repo
rather than relying on a `.gitignore` entry someone later edits.

```
dimikritos-ked/
├── source_docs/          ← reference + credentials, NOT in the MS repo
└── ms.beveosiofeilon/    ← git init here; this is what ships to Demokritos
```

**Bootstrap sequence** (no local PHP; each step runs in a throwaway container):

```bash
cd ~/projects/dimikritos-ked
docker run --rm -v "$PWD":/app -w /app composer:2 \
  create-project laravel/laravel:^10.0 ms.beveosiofeilon
cd ms.beveosiofeilon && git init
docker run --rm -v "$PWD":/app -w /app composer:2 require laravel/sail --dev
docker run --rm -v "$PWD":/app -w /app composer:2 php artisan sail:install --with=mysql
```

Then, before the first `sail up`:
- **Pin PHP 8.1 in `compose.yaml`** (note: modern Sail generates `compose.yaml`, not
  `docker-compose.yml`). Sail defaults the runtime to **8.5**, which is outside Laravel 10's
  supported range of 8.1–8.3 and will break. Change build context to
  `./vendor/laravel/sail/runtimes/8.1` and image to `sail-8.1/app`. The 8.1 runtime is present.
- Add the `rabbitmq:3-management` service (5672 + 15672, guest/guest) on the `sail` network.
- `./vendor/bin/sail up -d`, then work through `sail artisan …`, `sail composer …`, `sail test`.

Keep the project on the WSL filesystem (`/home/…`), never `/mnt/c`, or file I/O will crawl.

## Architecture

```
React UI ──▶ BFF ──▶ [RabbitMQ] ──▶ ms.beveosiofeilon ──SOAP/WS-Security──▶ ΚΕΔ (ΑΑΔΕ)
                          ▲                  │
                          └──── response ────┘
```

Inside the MS, per the guide: DDD + Service-Repository, Command Pattern, Template Method.

**The one abstraction we add beyond the guide** — because item 3 above forces it:

```
App\Messaging\MessageCodec              (interface: decode(string): Envelope, encode(Response): string)
  ├── JsonMessageCodec                  default for local dev — payload is plain JSON
  └── EgovHashMessageCodec              adapter over egov/rabbitmq-classes; throws until available
```

Selected by `MS_CODEC=json|egov` in `.env`. Nothing else in the codebase references the egov
namespace directly, so swapping in their library later is a one-class change, not a rewrite.

Mirror their response contract in our own `App\Messaging\RabbitMQResponse` so the emitted JSON
keys match the guide exactly: `data`, `type`, `status`, `messages`, `warnings`, `errors`,
`extraData`, `pagination` (`page`, `page_size`, `total_count`, `page_count`). Enums:
`RabbitMQResultType` (`SINGLE_ITEM`, `LIST`), `RabbitMQResponseStatus` (`OK`, `ERROR`).

---

## Scope ladder

A call has since added `retrievePayProgress` / `retrievePaymentData` and the `kedeDeleteService`
methods to scope. **This is not captured in any document we hold** — every written source
(`Beveosi_Ofeilon_PHP_Confirmation.docx` §6, `dimokritos_kede_estimate_internal.md` §5) puts
payment tracking in Phase 2 and deletions in Phase 3, against a €5,000 net Phase A. Get the
revised scope in writing before building M3.

Build order, because each rung reuses the rung below:

| | Scope | Why here |
|---|---|---|
| **M1** | RabbitMQ handshake: `ping` + one stubbed ΚΕΔ command | Nothing else can be verified until the message contract is agreed |
| **M2** | `retrieveNames`, `retrieveKedeAmount`, `retrieveCloseDay`, `retrieveVerificationProgress` live against `test.gsis.gr/esbpilot` + locking | The core certification flow — this is what replaces the Excel |
| **M3** | `retrievePayProgress`, `retrievePaymentData` | Same client, same rails: one command class + one response mapper each. Cheap once M2 lands |
| **M4** | `kedeDeleteService` — `deleteKedeAmount`, `deleteKedeProgress`, `deleteKedeComplete` | Genuinely separate: second WSDL, second credential pair, own audit/locking rules. Spec `Kede_Delete_Amount_Service_K___v_0.99.pdf` and pilot creds are in hand, so it is unblocked — just not small |

M1 leaves seams for all of these (see §5 below); it does not implement them.

## Milestone 1 — scope

Prove the RabbitMQ handshake. Implement `ping` plus **one stubbed ΚΕΔ command** returning a
well-formed response. Real ΚΕΔ calls come in Milestone 2.

### 1. Scaffold
- Laravel 10 / PHP 8.1, repo named `ms.beveosiofeilon` (confirm name with Demokritos — their
  convention is the `ms.` prefix).
- `.env` per the guide, but with a **consistent** prefix — use `BEVEOSI_*` in both `.env` and
  `config/microservices.php`. Keep `QUEUE_CONNECTION=sync` (the guide is explicit).
- `config/app.php` gains `'ms_name' => env('MS_NAME', 'beveosiofeilon')`.
- `config/microservices.php` and `config/rabbit_commands.php` per the guide.
- **Do not** commit `.env`, and **do not** commit the ΚΕΔ pilot credentials from
  `KED Dev Creds.docx` — those go in `.env` locally and in their secret store on-prem.

### 2. Local RabbitMQ
- `docker-compose.yml` with `rabbitmq:3-management` (5672 + 15672, guest/guest), and a MySQL 8
  service for the locking/audit tables.
- `Makefile` / `composer` scripts: `up`, `down`, `worker`, `publish`.

### 3. Consumer worker
- `php artisan rabbit:consume` — connects via `php-amqplib`, consumes the configured queue,
  hands the raw payload to `MessageCodec::decode()`, resolves `command` against
  `config/rabbit_commands.php`, executes, publishes the encoded response to the `reply_to` /
  routing key. Manual ack; nack-with-requeue=false on unhandled failure so we never hot-loop.
- **Flag:** their `RabbitMQMessageInterpreter` presumably ships its own worker command. Ours is
  a stand-in for local dev and must be replaced/reconciled once we have the package.

### 4. Commands
- `App\Commands\ICommand` — `execute(array $params)`.
- `App\Commands\General\PingCommand` — returns `SINGLE_ITEM` / `OK`.
- `App\Commands\Kede\SubmitBeveosiCommand` — validates the full input field set and returns a
  **stubbed** ΑΤΒ / Ταυτότητα Οφειλής. This is the command whose JSON contract Demokritos
  needs to see.

### 5. ΚΕΔ client seams (structure, not implementation)
- `App\Ked\Progress\KedeProgressClient` — `\SoapClient` subclass, WSSE UsernameToken header
  injected via `__doRequest`, `stream_context` pinned to TLS 1.2.
- `App\Ked\Delete\KedeDeleteClient` — empty seam for the Μείωση service.
- `App\Ked\AuditRecordFactory` — builds `auditTransactionId`, `auditTransactionDate`
  (`Y-m-d\TH:i:s\Z`), `auditUnit`, `auditProtocol` (**our unique βεβαίωση id**), `auditUserId`,
  `auditUserIp` from the BFF-propagated token. First four are mandatory on every call.
- Type discipline from `KEDE_Progress_Service_v1.03_MySQL.xlsx`: money is always
  `DECIMAL(17,2)` and never float; ΑΦΜ / ΚΑΕ / ΔΟΥ / extOrg / Ταυτότητα Οφειλής are **strings**
  (leading zeros are significant); `atbNo` is up to 20 digits so `DECIMAL(20,0)`, not `BIGINT`.

### 6. Test harness — this is what Demokritos signs off on
- `php artisan bff:publish {command} {--params=}` — a fake-BFF publisher that puts a message on
  the queue exactly as the BFF would and prints the response it gets back.
- A committed `docs/message-contract.md` with **request and response JSON samples per command**
  — this is the artifact to send them.
- Import their Postman collection into `docs/postman/` as the reference for ΚΕΔ payloads.
- Feature tests: codec round-trip, command dispatch, response shape, unknown-command error path.

---

## Critical files

| Path | Purpose |
|---|---|
| `config/microservices.php`, `config/rabbit_commands.php`, `config/app.php` | Guide-mandated config |
| `app/Messaging/MessageCodec.php` + `JsonMessageCodec` / `EgovHashMessageCodec` | The swappable wire format |
| `app/Messaging/RabbitMQResponse.php` | Response contract mirror |
| `app/Console/Commands/RabbitConsumeCommand.php` | Worker |
| `app/Console/Commands/BffPublishCommand.php` | Fake-BFF test publisher |
| `app/Commands/General/PingCommand.php`, `app/Commands/Kede/SubmitBeveosiCommand.php` | Commands |
| `app/Ked/Progress/KedeProgressClient.php`, `app/Ked/AuditRecordFactory.php` | ΚΕΔ SOAP seams |
| `docker-compose.yml`, `docs/message-contract.md` | Local env + the deliverable |

---

## Verification

1. `docker compose up -d` → RabbitMQ management UI reachable at `localhost:15672`.
2. `php artisan rabbit:consume` in one shell; queue appears in the management UI with one consumer.
3. `php artisan bff:publish ping` in another → response JSON printed, `status: OK`,
   `type: SINGLE_ITEM`.
4. `php artisan bff:publish submit_beveosi --params=@tests/fixtures/beveosi.json` → stubbed ΑΤΒ
   returned in a well-formed envelope.
5. `php artisan test` green.
6. Kill the worker mid-message → message is redelivered, not lost.
7. Send an unknown command → `status: ERROR` with a populated `errors` array, worker stays up.

Milestone 2 gate (not this build): replay the Postman ΚΕΔ calls through
`KedeProgressClient` against `test.gsis.gr/esbpilot` and match the responses byte-for-byte
against what Postman returned.

---

## Send to Demokritos alongside Milestone 1

1. `docs/message-contract.md` — the request/response JSON per command, for their BFF team.
2. The written correction that ΚΕΔ is SOAP + WS-Security, not REST.
3. Blocking asks:
   - Access to `gitlab.skel.iit.demokritos.gr` for `egov/rabbitmq-classes`, **or** the
     hash-string (de)serialization spec.
   - The artisan command / class that starts their consumer worker, and a **real sample inbound
     message** off a live queue.
   - Confirmation of the `MYSERVICE_*` vs `INVOICES_*` env-key mismatch in their guide.
   - Queue / exchange / routing-key naming and the reply mechanism (`reply_to` vs fixed queue).
   - Which MySQL/MariaDB version is available on-prem for our locking + audit tables.
4. Non-blocking asks carried over from `Simeioseis_Meeting_KED.docx`: `extOrg` code from the
   ΑΑΔΕ certification, permitted ΚΑΕ list, `txtCode` (είδος φόρου) values, whether they work in
   batches (one ΧΚ = many debtors = one ΑΤΒ) or one debt at a time, and the exact semantics of
   "cancel".

---

## On using Fable

Yes for this milestone. It is scaffold- and boilerplate-heavy against a spec that is now fully
pinned down, which is where Fable is strongest. Keep two things under closer review rather than
delegating them: the ΚΕΔ SOAP payload mapping (Milestone 2) and the anti-duplicate locking
semantics — both have real financial consequences if wrong (duplicate debt raised at the ΔΟΥ).

### Are Demokritos' instructions clear enough to build from?

Enough to scaffold, not enough to integrate. `Creating+a+New+Microservice+(External)+…doc`
is clear on project layout, the three config files, the Command/Template-Method patterns and
the shape of `RabbitMQResponse`. It is silent or self-contradictory on:

1. **No worker command.** It never says how the consumer is started — it only says
   `RabbitMQMessageInterpreter` "will match the command name". No artisan command, no class.
2. **No inbound message schema.** Not one sample of a real message off their queue.
3. **No serialization spec.** The hash-string format is proprietary and the package is
   inaccessible to us. Unguessable.
4. **Env key mismatch.** `.env` defines `INVOICES_*`; `config/microservices.php` reads
   `MYSERVICE_*`. A literal copy produces null config.
5. **Class name mismatch.** `rabbit_commands.php` references `GetSingleInvoiceHttpClient`; the
   code sample defines `GetSingleInvoiceClient`.
6. **No topology.** Nothing on exchange, routing keys, reply mechanism (`reply_to` vs fixed
   queue), token propagation, or what is inside the auth token.

M1 is scoped precisely to make these answerable: we build our best-guess contract, publish
`docs/message-contract.md`, and let them correct it — far cheaper than guessing wrong deep
inside the ΚΕΔ logic.

---

## The Fable prompt

Switch model, then paste everything between the fences. It is written to be self-contained.

````text
Build Milestone 1 of a PHP/Laravel microservice for ΕΚΕΦΕ Δημόκριτος, in the current empty
repo. Source specs are in ./source_docs/ — read them if you need detail, but everything you
need to build M1 is below.

# What this service is
"Βεβαίωση Οφειλών" — it certifies third-party debts to the Greek tax office via the ΑΑΔΕ
ΚΕΔ SOAP web services. It is a headless microservice: no frontend, no auth. Demokritos'
React/BFF layer sends it requests over RabbitMQ and reads responses back over RabbitMQ.

# Milestone 1 goal
Prove the RabbitMQ handshake end to end on a local RabbitMQ, and emit a documented JSON
message contract that Demokritos' BFF team can review. ΚΕΔ calls are STUBBED in M1 — build
the seams, not the SOAP payloads.

# Hard constraints — do not deviate
- Laravel 10, PHP 8.1. Follow Demokritos' guide layout exactly (source_docs/Creating+a+New+
  Microservice+(External)+-+using+egovPackage+for+RabbitMQ+Communication.doc).
- QUEUE_CONNECTION=sync in .env. Their guide is explicit that RabbitMQ requires it.
- Do NOT composer require egov/rabbitmq-classes. It lives on Demokritos' internal GitLab and
  we have no access. Do NOT reference the Egov\ namespace anywhere outside the one adapter
  class named below.
- Do NOT invent or guess the proprietary hash-string wire format. Unknown = behind an
  interface.
- Do NOT commit any credentials. source_docs/"KED Dev Creds.docx" AND
  source_docs/Dimokritos-KED.postman_collection.json both contain live ΑΑΔΕ pilot credentials
  in plaintext. They go in .env (gitignored) and in .env.example as empty placeholders only.
  Add source_docs/ to .gitignore. Never echo those values into code, tests, docs or fixtures.

# Known-good ΚΕΔ values (from the Postman collection — requests already verified working)
Use these as .env defaults / test fixtures. They are real pilot values, not placeholders:
  foreasAfm 090085651, extOrg 82838, kae 82838, txtCode 4102, doy 9776,
  inMctCod 1, inSctCod 98, doyFlag 0, insFrequency 1, lastDayRule 1,
  signer afmYpogr 003067224 "ΧΡΙΣΤΟΠΟΥΛΟΥ ΕΥΓΕΝ", test debtor afm 137569280.

The SOAP envelope shape is fixed and confirmed working. Content-Type: text/xml.
Body namespace ked = http://gsis.ggps.interoperability/KedeProgressInterface. Structure:
  <ked:{method}Request>
    <auditRecord>auditTransactionId, auditTransactionDate, auditUnit, auditProtocol,
                 auditUserId, auditUserIp</auditRecord>
    <{method}InputRecord>...business fields...</{method}InputRecord>
  </ked:{method}Request>
Confirmed input records:
  retrieveNames: foreasAfm, extOrg, ypiresiaDescr, plithosYpogr, inputDate,
    then 1..10 repeated <YPOGR>{afmYpogr, onomaYpogr, eponymoYpogr}</YPOGR>
  retrieveKedeAmount: repeated <AFM>{afm[, code, category]}</AFM>, repeated
    <TABLE>{aa, dueDate, amount}</TABLE>, repeated <KAE>{kae, amount}</KAE>, inMctCod,
    inSctCod, extOrg, txtCode, insFrequency, lastDayRule, fiscalYear, sunolo, comments,
    ypiresiaDescr, apofNoEtos, doyFlag, afmYpogr, nameYpogr [, doy, attachedFile,
    attFileName, attExtension]
  retrieveVerificationProgress: dateFrom, extOrg
  retrieveCloseDay: doy, extOrg, mcNo, mcDate
  deleteKedeAmount (kedeDeleteService, separate WSDL + separate credential pair): afm, extOrg,
    afekType, comments, deptId, approvalDate, fiscalYear, atbNo, mcNo, lineNo, adtCode,
    decYear, decisionNum, afkDoy, repeated <KAE>{kae, amount}</KAE>, afmYpogr, nameYpogr
M1 does not build these payloads — but shape KedeProgressClient and the DTOs so M2 is a fill-in.
- Money is always DECIMAL(17,2) / string in PHP, never float. ΑΦΜ, ΚΑΕ, ΔΟΥ, extOrg and
  Ταυτότητα Οφειλής are STRINGS — leading zeros are significant. atbNo is up to 20 digits, so
  DECIMAL(20,0), never BIGINT.

# Config (fix their guide's bugs)
Their .env uses INVOICES_* but their config/microservices.php reads MYSERVICE_*. They don't
match. Use a consistent BEVEOSI_* prefix in both.

- .env / .env.example: APP_NAME="Beveosi Ofeilon", MS_NAME=beveosiofeilon, MS_CODEC=json,
  QUEUE_CONNECTION=sync, DB_* (mysql, db name egov_ms.beveosiofeilon), RABBITMQ_HOST/PORT/
  USER/PASSWORD (localhost/5672/guest/guest), BEVEOSI_RABBITMQ_QUEUE_NAME=beveosiofeilon,
  BEVEOSI_RABBITMQ_ROUTING_KEY=beveosiofeilon, BEVEOSI_RABBITMQ_BASH_LOG=FULL,
  KED_PROGRESS_WSDL=https://test.gsis.gr/esbpilot/kedeProgressService?wsdl,
  KED_PROGRESS_USER=, KED_PROGRESS_PASS=, KED_EXT_ORG=, KED_AUDIT_UNIT="EKEFE DEMOKRITOS"
- config/app.php: add 'ms_name' => env('MS_NAME', 'beveosiofeilon')
- config/microservices.php: 'beveosiofeilon' => [baseURL, queue, routing_key, host, port,
  user, password] + 'settings' => ['bash_log' => env('BEVEOSI_RABBITMQ_BASH_LOG','FULL')]
- config/rabbit_commands.php: 'commands' => ['ping' => ['commandClass' => PingCommand::class],
  'submit_beveosi' => ['commandClass' => SubmitBeveosiCommand::class]], plus an empty
  'api_commands' => [].

# Build these

1. app/Messaging/MessageCodec.php — interface: decode(string $raw): Envelope,
   encode(RabbitMQResponse $r): string.
   app/Messaging/Envelope.php — value object: command (string), params (array),
   token (?string), correlationId (?string), replyTo (?string).
   app/Messaging/JsonMessageCodec.php — payload is plain JSON. Default.
   app/Messaging/EgovHashMessageCodec.php — adapter placeholder. Constructor or methods throw
   a clear \RuntimeException naming the missing egov/rabbitmq-classes dependency. This is the
   ONLY file allowed to mention Egov\.
   Bind by MS_CODEC in a service provider.

2. app/Messaging/RabbitMQResponse.php — mirror their contract exactly. Fluent setters
   setData/setType/setStatus/addError/addMessage/setMessages/setWarnings/setExtraData/
   setPagination, and hasMessages/hasWarnings/getMessages/getWarnings. JsonSerializable,
   emitting keys: data, type, status, messages, warnings, errors, extraData, pagination.
   Pagination keys are exactly: page, page_size, total_count, page_count.
   Enums RabbitMQResultType (SINGLE_ITEM, LIST) and RabbitMQResponseStatus (OK, ERROR).

3. app/Commands/ICommand.php — execute(array $params).
   app/Commands/General/PingCommand.php — SINGLE_ITEM / OK, echoes back a pong payload.
   app/Commands/Kede/SubmitBeveosiCommand.php — validates the full βεβαίωση input set
   (afm, optional synypochreoi list with code+category, kae, amount, installments, fiscalYear,
   comments, apofNoEtos, afmYpogr, nameYpogr, doyFlag) and returns a STUBBED response
   containing doy, xkNo, lineNo, atbNo and a Ταυτότητα Οφειλής. Validation failures →
   status ERROR with populated errors[], never an exception escaping to the worker.

4. app/Console/Commands/RabbitConsumeCommand.php — signature rabbit:consume. php-amqplib.
   Consumes the configured queue, decodes via MessageCodec, resolves command against
   config/rabbit_commands.php, executes, publishes the encoded response to the message's
   reply_to (falling back to the configured routing key), preserving correlation_id.
   Manual ack. On unhandled throwable: log, publish an ERROR response, nack WITHOUT requeue —
   the worker must never hot-loop. Unknown command → ERROR response, worker stays up.

5. app/Console/Commands/BffPublishCommand.php — signature
   bff:publish {command} {--params=} {--timeout=10}. Fake BFF: publishes a message shaped
   exactly as the BFF would onto the queue, waits on a temporary reply queue, pretty-prints
   the response JSON. --params accepts inline JSON or @path/to/file.json.

6. ΚΕΔ seams — structure only, no SOAP payload building in M1:
   app/Ked/AuditRecordFactory.php — builds auditTransactionId, auditTransactionDate
   (format Y-m-d\TH:i:s\Z), auditUnit, auditProtocol, auditUserId, auditUserIp. The first four
   are mandatory on every ΚΕΔ call. auditProtocol MUST carry our unique local βεβαίωση id —
   ΚΕΔ uses it to detect duplicate submissions.
   app/Ked/Progress/KedeProgressClient.php — extends \SoapClient, overrides __doRequest to
   inject a WS-Security UsernameToken header (PasswordText, oasis-200401-wss-wssecurity-secext-1.0
   namespace), stream_context pinned to TLS 1.2. Body namespace is
   http://gsis.ggps.interoperability/KedeProgressInterface. Methods may throw
   \LogicException('not implemented in M1').
   app/Ked/Delete/KedeDeleteClient.php — same shape, empty. Separate WSDL
   (https://test.gsis.gr/esbpilot/kedeDeleteService?wsdl) and separate credential pair.

7. Migrations: beveosi_certifications (local unique id used as auditProtocol, status, lock
   columns locked_at/locked_by, afm CHAR(12), amounts DECIMAL(17,2), doy CHAR(4),
   xk_no/line_no INT UNSIGNED, atb_no DECIMAL(20,0) nullable, taftotita_ofeilis CHAR(30)
   nullable) and ked_call_log (method, auditProtocol, request/response payloads,
   callSequenceId BIGINT UNSIGNED, callSequenceDate DATETIME(6), error code/description).
   No locking logic in M1 — just the schema.

8. Local environment — Laravel Sail. There is NO local PHP or Composer; every php/composer/
   artisan invocation must go through a container. The project is scaffolded with Sail already
   installed (mysql preset). Sail generated **compose.yaml** — that is the real filename.
   EXTEND that file. Do NOT create a docker-compose.yml; two compose files in one project is
   a mess. Required changes:
   - pin PHP 8.1: build context ./vendor/laravel/sail/runtimes/8.1, image sail-8.1/app.
     Sail defaulted this to 8.5, which is outside Laravel 10's supported range (8.1-8.3)
     and will break. The 8.1 runtime directory already exists.
   - add a rabbitmq:3-management service on the sail network, ports 5672 and 15672,
     guest/guest, with a healthcheck and a named volume
   - make the laravel.test service depend_on rabbitmq
   - RABBITMQ_HOST=rabbitmq (the service name), NOT localhost, from inside the containers
   Add a Makefile wrapping Sail: up, down, worker, publish, test, shell.
   Sail is DEV ONLY. Production at Demokritos is on-prem php-fpm with supervisor keeping
   `rabbit:consume` alive — do not let any Sail assumption leak into the worker, the config,
   or the deployment notes. Document the supervisor program stanza in README.md.

9. docs/message-contract.md — request and response JSON samples for ping and submit_beveosi,
   including the error shape. This is the deliverable Demokritos reviews. Write it for a
   reader who has never seen this codebase.
   docs/postman/ — copy source_docs/Dimokritos-KED.postman_collection.json here WITH THE
   CREDENTIALS STRIPED and replaced by {{ked_user}} / {{ked_pass}} collection variables.

10. Tests (php artisan test, all green): JsonMessageCodec round-trip; RabbitMQResponse
    serializes to exactly the documented keys; command dispatch resolves via config; unknown
    command yields ERROR without throwing; SubmitBeveosiCommand validation rejects a bad ΑΦΜ
    and preserves leading zeros on a good one.

# Definition of done
`sail up -d`, then `sail artisan rabbit:consume` in one shell and `sail artisan bff:publish ping`
in another returns a well-formed OK response. `sail test` is green. RabbitMQ management UI at
localhost:15672 shows the queue with one consumer attached. README.md documents the local loop
in under a page, including the supervisor stanza for on-prem production.

# Report back
List every place you had to guess because Demokritos' guide was silent — especially the
inbound envelope shape and the queue/exchange/routing-key topology. Those become questions
we send them.
````

---

## Post-build review notes (Fable, 2026-08-04)

Corrections found while cross-checking this plan against the Postman collection and the
delivered M1 code. The M1 build itself is committed and verified; these matter for M2–M4.

1. **`deleteKedeAmount` field list above is incomplete**: the working Postman request also
   carries a **`decFile`** element (alongside the `KAE` group, before `afmYpogr`). Include it
   when building M4. The four progress-service field lists match the collection exactly.
2. **The reply fallback rule ("falling back to the configured routing key") is unsafe as
   written**: with the single-queue topology, the configured routing key IS the consume
   queue, so the worker consumes its own replies in an infinite loop (observed live). The
   delivered worker refuses to reply onto its own queue; messages without `reply_to` get no
   reply. Revisit once Demokritos answers the topology question.
3. **`bff:publish {command}` cannot be implemented literally** — artisan reserves the
   argument name `command`; the delivered signature uses `{cmd}` (usage unchanged).
4. **`egov_ms.beveosiofeilon` is not a legal MySQL schema name** (no dots allowed); the
   delivered database is `egov_ms_beveosiofeilon`. Ask Demokritos how their convention maps
   to real schema names.
5. **PHP's SoapClient emits the envelope prefix `SOAP-ENV`** (with a hyphen) — any prefix
   matching in WSSE header injection must allow `-`. The delivered `WsseSoapClient` handles
   this and is unit-tested against that exact shape.
