Saltar a contenido

CONVENTIONS — GatewayPrismaQR

Decisions of the slices that are not ADRs but that the code depends on. Each one names the test that keeps it true.

1. Time

  • One java.time.Clock bean (config/ApplicationConfiguration): UTC, truncated to the millisecond, so the instants the domain holds are exactly what a DATETIME2(3) column stores.
  • domain and application never read the wall clock: no Instant.now(), LocalDateTime.now(), new Date(), System.currentTimeMillis(). They receive the instant (Payment.moveTo(state, now)) or the Clock. ArchUnit enforces it (ArchitectureGateTest.d05_*, proven on fixtures).
  • Leases computed with database time arrive with S4 (D-05); -Duser.timezone=UTC stays in the NSSM parameters.
  • The one write that does not go through Hibernate, the compensation task insert (JdbcCompensationTasks), leaves its timestamps to the column defaults (SYSUTCDATETIME(), database time): plain JDBC would shift an Instant by the JVM zone, which only the JPA mappings pin (PersistenceAdaptersIT.scheduledCompensation...).

2. Hibernate on SQL Server

spring.jpa.hibernate.ddl-auto is validate: the entities must agree with V1. What that took:

Column Mapping Why
DATETIME2(3) instants Instant, with hibernate.type.preferred_instant_jdbc_type=TIMESTAMP and hibernate.jdbc.time_zone=UTC Hibernate 7 maps Instant to datetimeoffset otherwise (schema validation fails), and without the UTC zone every value is shifted by the JVM offset. PersistenceAdaptersIT fails on either omission (the second one proven by running the test with another zone).
NVARCHAR(79) (denial_reason) @Nationalized, length = 79 the text the POS reads in mensajevarios, cut to 79 UTF-8 bytes (PosMessage), so never more than 79 characters
CHAR(3) (currency) @JdbcTypeCode(SqlTypes.CHAR), length = 3 VARCHAR would be a validation error
DECIMAL(13,2) money BigDecimal, precision = 13, scale = 2 never double (INV-04). Nothing above 99,999,999,999.99 is accepted anywhere (Money.cents, also at the POS boundary), so no write can overflow the column.
BIGINT version @Version long and a version check in save @Version alone only guards one persistence context, where the row is read again just before the write. Both repositories therefore compare the version of the aggregate (read in an earlier transaction) with the stored one before writing, so a stale write is refused: PaymentChangedConcurrentlyException, IntentionChangedConcurrentlyException (PersistenceAdaptersIT.aStaleWriteLosesToTheOptimisticLock, aStaleIntentionWriteLosesToTheOptimisticLockAcrossTransactions).
states stored by name() in VARCHAR, converted in the entity the domain enum is the vocabulary, the entity only a column
plan_code, tid, wallet_code plain columns of PaymentEntity, in the snapshot WalletFacts carries them (PersistenceAdaptersIT.s4_*), a reversal (S4) may need the tid

JPA entities never leave adapter.out.persistence (INV-09); the domain objects are Payment / Intention rebuilt from PaymentSnapshot / IntentionSnapshot. Reads that are not an aggregate (CheckoutDirectory) are plain JDBC.

3. Transactions, the wait policy and what the POS is told (D-20)

  • No transaction and no database connection is held across a call to Prisma or across a wait for the POS. The application talks to storage through UnitOfWork.execute(...): one short transaction per call. StartPaymentService shows the shape: (1) one transaction records the command and opens the intention, (2) the authorizer is called with nothing open, (3) the outcome is recorded in short transactions of its own. StartPaymentServiceTest.theAuthorizerIsNeverCalledInsideATransaction asserts it.
  • The three outcomes of the create call (IntentionOutcome, the contract of AuthorizerPort, pinned by IntentionOutcomeTest; the Prisma adapter of S2a applies it, CreateIntentionOutcomesTest):
  • Created: Prisma answered 201 with the intention id. The id is stored on the intention in a transaction of its own, first, whatever happened to the payment meanwhile (a cashier cancel or a supersede during the call moves the payment and takes the intention out of the live set; the id is attached anyway), and only then the payment follows if both it and the intention are still where the create call left them. A lost race on either write is retried (3 attempts) by reading again, never by overwriting. The compensation task needs the id for DELETE /intentions/{id}, so losing it is not an option (StartPaymentServiceTest.thePrismaIdIsStoredEven...). The step addresses its own intention by its id, never "the latest" of the payment (D-48). An id that arrives after the hand-over means Prisma created an intention the compensation did not know: the task is scheduled again if it has none, and a compensation that already finished is reopened (Payment.reopenCompensation, StartPaymentServiceTest.d48_...). An id outside twelve digits, or one that another intention already holds (ux_intention_prisma_id, IntentionPrismaIdInUseException), is never stored: the call counts as Unknown (D-43).
  • Failed: only a definite refusal (D-46): 400, 401, 403, 404 and a 422 that is not a duplicate. Prisma understood the request and refused it, so nothing was created and no compensation is owed; intention and payment fail together and the reason is stored. The reason is what the cashier may read: short, plain ASCII, at most 79 characters, and never Prisma's own words (the adapter says only Prisma refused the intention (HTTP 403)).
  • Unknown: a 5xx, a timeout, an IO error, an untrusted certificate, a 2xx without a usable id (or any 2xx but 201), an unreadable answer, 408, 409, 429 and every other 4xx Prisma has not said means "refused" (question 14), a 422 that may be a duplicate integrator id and any exception thrown by the port. The intention may exist and the wallet may charge the customer, so INV-01 and INV-02 apply (ADR-002): CompensationHandOff writes, in one transaction, the payment -> COMPENSATION_PENDING, its intention -> CANCELLED (out of the live set, D-34) and the compensation_task row, with the cause in compensation_task.last_error (HTTP 503, SocketTimeoutException, ... never a body, a URL or a secret; D-53); only after the commit does the POS hear "denied". TransactionsIT proves the atomicity on the real transaction manager: a failure after the task was inserted rolls back the payment and the intention too. If any of the three writes fails nothing was promised (StartPaymentServiceTest.inv02_theHandOverIsOneTransaction...). The POS never gets a 500 for an unknown outcome, and a retry returns the stored denial without sending a second intention.
  • Recording the outcome never leaves a live intention behind. Any failure of the record steps that is not a lost race on the payment (an id that cannot be stored, an unexpected exception) hands the payment over like an unknown outcome (D-43). A lost race on the payment is retried and, after the third loss, answered 409.
  • The Prisma id is never lost once Prisma named it (D-48, INV-01). A 2xx that is not the documented 201 is Unknown but carries the usable id it named (IntentionOutcome.Unknown.prismaIntentionId, read from the body of any 2xx and never from an error), and a failure while storing the id of a 201 (a transient exception, or the optimistic lock lost three times) hands over WITH the id attached: CompensationHandOff.handOver(..., prismaIntentionId, ...) cancels the intention and attaches the id in the same write of the same transaction, and reopens a compensation that already finished when the intention still lacks it. Only an id that another intention holds (IntentionPrismaIdInUseException, the unique index rolls the whole hand-over back) or that cannot be stored falls back to the plain hand-over, which runs in a second transaction (StartPaymentServiceTest.d48_*, CompensationHandOffTest.d48_*).
  • An interrupted create call still hands over. The authorizer restores the interrupt flag, and the connection pool refuses a connection to an interrupted thread, so recording or handing over on that thread would fail and the POS would get a 500. StartPaymentService.start clears the flag while it records the outcome and sets it again afterwards (StartPaymentServiceTest.inv02_anInterrupted...). If the database itself is down even the hand-over fails and the POS gets a 500: nothing was promised to it, the payment stays INTENT_SENDING and the orphan-wait reaper (section 11) hands it over once the database is back (the failure that started it travels with the exception as a suppressed one).
  • One lock order everywhere: payment, then intention, then charge, reversal and task (D-49; S4 adds the charge and the reversal between the intention and the task, and CompensationQueue.lockPayment takes the payment row with UPDLOCK first in every settling transaction). CompensationHandOff writes in that order (CompensationHandOffTest.d49_...), so does every recording step (StartPaymentServiceTest.d49_...). A transaction chosen as a deadlock victim (SQL Server 1205) is run again, at most three times, by TransactionalUnitOfWork (DeadlockRetry): the application stays Spring-free and its units of work must be safe to repeat. TransactionsIT provokes a real deadlock with two latched transactions and shows both finish. A read that only correlates must not sit in the same statement as a write that waits for a row the writers hold: JdbcWireLog finds the payment of a callback in a statement of its own, before the insert, because inside one statement the read of the intention was still held while the foreign key waited for the payment, a cycle SQL Server broke only after up to five seconds, with the callback answered that late (D-86, WireLogLockOrderIT).
  • Polls are read-only. UnitOfWork.read opens a read-only transaction (the status query and every poll of the wait use it), execute a read-write one.
  • A crash in the middle still leaves INTENT_SENDING. A node that dies during the authorizer call, or between the two transactions of the Created outcome (the id is stored, the payment has not followed yet), leaves the payment INTENT_SENDING with nothing scheduled: only an exception is handed to compensation at once, a dead process cannot do it. The reaper (S4, OrphanWaitReaper, section 11) finds payments whose wait deadline passed with nobody holding the wait (INTENT_SENDING included) and hands them to compensation (AC-25); CompensationHandOff finds the Prisma id on the intention when there is one.
  • A compensation without a Prisma id. In the Unknown case Prisma never told us an intention id, so the task has nothing to DELETE. It relies on two things, neither confirmed by Prisma yet: (a) a new intention on the same checkout invalidates the previous one (the QR of a checkout is fixed, so the next payment creates one anyway), and (b) the open question 4b of docs/PRISMA-PREGUNTAS.md: whether an intention can be queried or cancelled by our integrator_intention_id (<prefix>-<paymentId>-<attempt>, unique per attempt). If the customer does pay, the late notification (INV-03) carries the wallet payment id and the charge gets a forced annulment of its own. The compensation job (section 11, RUNBOOK section 9) works the tasks off; a cancel task without an id logs COMPENSATION_NO_PRISMA_ID and closes.
  • The wait for the wallet is section 9, rule 14: it reads the payment row at a short interval (250 ms by default) on the request's virtual thread, until the state is final or the persisted deadline passes; every poll is its own read-only transaction, so the wait costs no connection while it sleeps and every node sees what another node applied. The deadline ends before the caller's read timeout (R-13), and when it expires the payment goes through the same CompensationHandOff as an unknown outcome: the POS hears "denied", never SINRESPUESTA. The load-shaped IT (many simultaneous waits, a small pool) is still to come (D-82).
  • Pool: Hikari is explicit in application.yml: maximum-pool-size: 20, minimum-idle: 5, connection-timeout: 5000. Transactions last milliseconds, so 20 connections serve the 5 payments/s design target with large headroom; a request that cannot get a connection within 5 s fails instead of queueing behind the 30 s default.
  • Retries of trxpago (AC-04): the same id with exactly what is stored (amount, cashback, base amount and promotions, compared by value, so 4739 equals 4739.00) returns the stored status; a payment that never had an amount (CANCELLED, EXPIRED: it never reached Prisma) answers its stored denial whatever the retry asks (D-53); anything else is a 409 {status, message}. When two requests race, the loser re-reads once: if the winner committed it resumes the winner's payment, if the winner rolled back (the payment is ID_ISSUED again) it begins the authorization itself, once. A second lost race is a 409 as well and the POS retries. A retry of a payment that is still waiting for the wallet (the first request is still open, or its node died) waits for the same persisted wait_deadline_at, never a fresh one, on whichever node it lands (AuthorizePaymentService, section 9, rule 14); one that finds the result returns it at once.
  • Enabled checks: a merchant, branch or checkout disabled after trxid refuses trxpago with a 404 (the check is made when the payment begins, CheckoutDirectory.findEnabledById); a retry of a payment that already started does not need the checkout to still be enabled.
  • integrator_intention_id is <prefix>-<paymentId>-<attempt> (IntegratorIntentionIds), at most 40 characters (the column): the prefix (gateway.intentions.id-prefix, default GPQR, 1 to 16 letters, digits or underscores) names the deployment and must differ between two gateways that share a Prisma environment. One intention per attempt: a new attempt of the same payment gets the next number.

4. The POS wire (verified against pos_ctoq.cpp, the real E2E log and RouterQR)

SPEC 3.0 and ADR-004 describe the DOS POS as speaking "raw TCP HTTP/1.0". The source and the log say otherwise:

  • PAGOQR::TxRx (pos_ctoq.cpp:3312-3325) writes POST /api/trxid HTTP/1.1 (two spaces after the method), then Host, User-Agent, accept, content-type, Cache-Control, Content-Length, with a bare LF at the end of every line and a blank line before the body. E2E_V1_log.txt shows exactly that. Tomcat accepts it (PosApiIT sends those bytes). HTTP/1.0 without Host is still tested (RawHttp.post10), as the worst case of that client family.
  • The POS reads until Content-Length or the close, then waits for more. It polls the socket every 250 ms, takes the first bytes that arrive, waits 500 ms and reads once more "in case more arrives" with a 1.5 s timeout (pos_ctoq.cpp:3373-3388) before it looks for the JSON in what it got; it cannot parse a chunked body. Two consequences, both enforced by PosContentLengthFilter for every answer of /api/* and of the error page:
  • Content-Length, never chunked. Spring MVC streams JSON and Tomcat then sends it chunked, so the (small) body is buffered and sent with its length. RawHttp refuses a chunked response, which is how the problem was found (and how the 404 and 405 pages were found chunked: PosWireIT).
  • Connection: close. On a kept-alive connection that second read lasts its whole timeout: E2E_V1_log.txt shows TCPRx: OK [Tout:1] followed by TCPRx: ERROR [Tout:2] 2 to 3 seconds later after every trxid and trxpago (the trxid sent at 08:33:39 ends at 08:33:44, the trxpago sent at 08:33:47 at 08:33:51, with RouterQR in front answering Connection: keep-alive). The server closes right after the answer so that read ends at once; the POS opens a new connection for every call anyway (pos_ctoq.cpp:3466, SafeCloseTCP; PosWireIT.theServerClosesTheConnectionRightAfterAnAnswer..., with RawHttp.exchangeAndWaitForClose).
  • Success is HTTP 200 or 201 (pos_ctoq.cpp:3472); anything else is an error and the POS copies message of the JSON body (at most 99 characters) into the text it shows. Every error under /api is {"status": <int>, "message": "..."}, messages short and without internals, always as JSON whatever the Accept header says, with a Content-Length: the ones a handler raises (PosApiExceptionHandler) and the ones that never reach a handler, an unknown path (404) or a wrong method (405), which the container sends to its error page (ErrorPageController asks PosErrorShape, PosErrors). A request for a path outside /api/ on the POS port is refused by ListenerSeparationFilter with an empty 404, not part of the POS contract. The /error page is global but not the POS's: it words each error in the shape of the listener whose path failed (ErrorShape), and the Connection: close of PosContentLengthFilter applies only to /api (D-52, section 8 for the callbacks).
  • trxid answers 201 with {id, pos, sucursal, comercio, mediodepago}. RouterQR parses the answer with org.json: it needs id (a number) and reads mpposid only when present, so mpposid and qrData (MercadoPago leftovers) are not sent.
  • trxpago bodies: POS-native {id, totalitem, totalcashback, nropv, nroticketfiscal} (a POS may still send base_amount and promos: both are ignored, section 9b); RouterQR's AutorizadorService.replaceJsonRequestFieldIdAutTrxId rewrites it (the gateway trx id in id, tipoautorizador: "TECSO", importe = totalitem, totalitem stays). Numbers arrive as JSON numbers or as text (nropv is 1 from the POS and "12346" in the RouterQR/GatewayQR examples); amounts have at most two decimals (finer is refused, never rounded) and at most 99,999,999,999.99, checked from the precision and scale before anything is rescaled (a 1e999999999 is a 400, not an allocation); totalitem and importe must agree. promos and base_amount are not read: the plans are the gateway's, so what a POS sends about them can neither refuse a sale nor be stored (section 9b).
  • Responses use the types of the real traffic: autorizadortrxid and autorizadorintencionid are strings of digits, everything numeric is a number, importe_recdesc is signed, mediodepago is gateway.pos.medio-de-pago (default PRISMA). The POS decodes the installments from paymentinstallments (pos_ctoq.cpp:3485), never from cuotas, so both are sent with the same value. Only a payment the wallet paid (APPROVED, ANNULLED, REFUNDED) carries the wallet's result (importe_final, importe_recdesc, the installments, the method, the wallet payment id, the authorization code as mensajevarios); a payment handed to compensation, even after a late wallet result stored those facts, answers the denial only. pos-golden/real-rx/*.json is the reference (PosResponsesTest).
  • mensajevarios is at most 79 BYTES of UTF-8 (the POS keeps it in a char[80]), cut at a code point, never in the middle of one (PosMessage). The reason a payment was denied is stored (payment.denial_reason), so trxpago, its retries and GET /api/trxes/{id} say exactly the same (AC-05). The DOS POS is an OEM-codepage client, so non-ASCII reasons may display badly (D-42); the gateway's own messages are ASCII.
  • What the POS does after trxpago fails (the consulta loop, pos_ctoq.cpp 3681-3733; real E2E 2026-10-04). The first trxpago is read for max(profile 496 TIMEOUT_RX / 3, 30) s (50 s with 150: RUNBOOK section 3 has the profile of the gateway for that caller). If its answer is not an approval the POS does not take the denial as final: it sleeps 10 s (ten 1 s idles, the cashier may cancel in between when profile CancelEnabled is on), then asks GET /api/trxes/{id} (read for 5 s, profile 497) and repeats until (496 / 3) * 2 s (100 s) after the first answer. Only three estados end the loop: REFUND_DENEGADO (the POS shows "Denegado" and drops the sale), AUTORIZACION_DE_PAGO_APROBADA and AUTORIZACION_DE_ANULACION_APROBADA (pos_ctoq.cpp 3520-3555). AUTORIZACION_DE_PAGO_DENEGADA, INTENCION_DE_PAGO_RECIBIDA_DENEGADA and every waiting estado are read as "ask again". That is why the consulta of a payment the gateway decided as no sale answers REFUND_DENEGADO (AC-05, ADR-004, amended 2026-10-04: PosEstadoMapper.ofConsulta, while trxpago keeps AUTORIZACION_DE_PAGO_DENEGADA). After the 100 s the POS prompts the cashier "Reintenta via Consulta del PAGO?" (OK asks again, with no 10 s sleep) and, on cancel, "Confirma Cancelacion de Consulta PAGOQR?" (OK drops the sale as denied). A cashier who confirms that cancel while the gateway still has the payment waiting leaves a payment the wallet may still charge: compensation (trxanulacion, S4) is what covers it. The denial's mensajevarios is not shown by the Almacor DLL (D-117).
  • The marker of "the POS was told approved" (INV-01, D-105). A POS can hear "denied" on trxpago and then "approved" on the consulta, and what counts for a sale is the last answer it heard. So every AUTORIZACION_DE_PAGO_APROBADA answer, on trxpago or on GET /api/trxes/{id} (native and RouterQR-shaped requests alike: one controller), is recorded durably in payment.pos_told_approved_at after it has been written out completely. PosApiController only tags the request with the approved answer it built (PosApprovedAnswer: a request attribute, nothing is parsed from the body); PosApprovalMarkerFilter, registered outside PosContentLengthFilter, records the marker when the chain returned a 200, the content-length filter copied the buffered body to the real response, and flushBuffer() of that response returned without an IOException. The order of the two filters is the point: ContentCachingResponseWrapper.flushBuffer() does not flush, so only outside the wrapper does a flush mean that the bytes left. An answer that was only built, only buffered, or whose flush failed leaves no marker; a denial, a REFUND_DENEGADO and an annulment's estado never tag. The record is a small update of its own (PosApprovals, WHERE pos_told_approved_at IS NULL, database time, no version or updated_at bump), never inside a money transaction. If it fails the answer already sent is untouched and one ERROR line starting with POS_APPROVAL_UNRECORDED payment=<id> path=<trxpago|consulta> is logged (RUNBOOK section 3). The flush proves the bytes were handed to the connection, not that the POS read them; the record runs on the request thread before the connection closes, which the POS tolerates (it bounds its extra read by 1.5 s).
  • The intent comes first: no durable intent, no approved answer (INV-01, D-105). One database brownout could otherwise cause both an INV02_UNPERSISTED_DENIAL and a failed told-marker write on the later consulta that told the POS "approved", leaving the marker NULL for a sale the POS printed (and the S4 reconciliation would annul it). So, before PosApiController returns an AUTORIZACION_DE_PAGO_APROBADA (on trxpago, on the consulta, native or RouterQR-shaped), PosApprovalGuard durably writes payment.pos_approval_intent_at (PosApprovals.recordApprovalIntent: a small update of its own, database time, first instant kept, never inside a money transaction), and only then tags the answer for the filter. If the write fails the gateway does not say approved: it answers INTENCION_DE_PAGO_RECIBIDA_APROBADA, statuscode 0, with none of the approval's fields (PosResponses.deferredApproval), on trxpago and on the consulta alike, and logs one ERROR line POS_APPROVAL_DEFERRED payment=<id> path=<trxpago|consulta> failure=<class> (RUNBOOK section 3); the answer is not tagged, so no told marker is asked for. Why that estado is safe: it is the estado the gateway already returns for a payment that is not settled (INTENT_CREATED, BINS_RECEIVED, COMPLETE_SENT), the Almacor POS reads it as "ask again" on trxpago and on the consulta (only REFUND_DENEGADO, an approval and an annulment end its loop), so it keeps polling every 10 s and the next consulta retries the intent and answers approved once it is stored; a RouterQR approves only on AUTORIZACION_DE_PAGO_APROBADA, so it sees no approval and its sweeper annuls through trxanulacion, the safe direction. Either marker set means "the POS may have heard approved"; both NULL means it never did (PosApprovalGuardTest, PosApiControllerTest.inv01_*, PosWaitIT.inv01_*). The intent is also refused while the sale is being annulled (section 11, rule 8, D-S4-10): the POS then hears the annulment view of the consulta, never approved.
  • trxanulacion (D-19): the DOS POS sends id = the payment id and trxidoriginal = 0, because PAGOQR_MenuAnulacion sets lIdTrx = labs(lIdTrxPagoQR) and never sets lIdTrxOri (pos_ctoq.cpp:4028, the struct is memset to 0, pos_defi.h:1347); RouterQR sends the payment id in both. The rule is: payment to annul = trxidoriginal if it is greater than 0, otherwise id (PosRequestNormalizer.annulment). A request with a fresh id next to a positive trxidoriginal (the GatewayQR documented form) is accepted and keeps the requestId, which S4 stores nowhere (the annulment is idempotent per payment, D-S4-6). The behavior is section 11, rules 10 to 12.
  • No authentication on the POS port (the POS sends no auth header, D-16): checkout.pos_api_key_hash is gone. The source-IP allowlist of ADR-004 stays an option for later, inside the VPN.

5. State machines

  • Payment: one table (PaymentStateMachine); an undeclared transition is an error (IllegalPaymentTransitionException), tested for every pair of states. moveTo is the generic step and refuses the seven states that carry an invariant or a duty, even where the table declares the edge: INTENT_SENDING (beginAuthorization: the amount), APPROVED (approve: INV-04 and INV-06), ANNULLED (annul), REFUNDED (refund), INTENT_FAILED (intentFailed: the reason the POS reads), COMPENSATION_PENDING (handOverToCompensation, recordWalletResult, reopenCompensation: the compensation is owed and its intent must be persisted, INV-02) and SUPERSEDED (supersede) (D-47). The database says the same: ck_payment_settled_needs_result refuses an approved, annulled or refunded payment without its final amount, method and installments, and PosResponses refuses to answer one.
  • No UNKNOWN. SPEC 3.1 and ADR-002 replace the state machine of the original discovery proposal (retired; see docs/SISTEMA.md, section 8): a wait that expires, a cashier cancel, an unknown create outcome and a supersede hand the payment to COMPENSATION_PENDING (the compensation intent is persisted first, INV-02) and the POS sees a denial. CANCELLED and EXPIRED remain for an id that never reached Prisma (D-28). Edges added in the S1 fix pass: INTENT_SENDING -> SUPERSEDED (a newer payment starts while the create call is in flight) and REJECTED -> COMPENSATION_PENDING (a wallet that refused and then approved).
  • Late and out-of-order wallet results (INV-03, ADR-002, AC-20, AC-21, D-44, D-45). Every wallet result goes through Payment.recordWalletResult(WalletFacts, PaymentAmounts, now), which never refuses and never throws for what a result says: it answers a WalletResultEffect and the caller does what it says. WalletFacts (wallet payment id, installments, method id and type, authorization code) carries no amounts: the amounts travel apart because they may break INV-04 (PaymentAmounts.tryOf gives none then) or not match the payment; whatever cannot be stored is dropped or cut to its column (30 characters for the type and the code).
  • the same wallet payment id as the stored one is DUPLICATE in every state, nothing changes and a finished compensation (COMPENSATED, COMPENSATION_FAILED) is not reopened (AC-10);
  • a different wallet payment id never overwrites the first: SECOND_WALLET_PAYMENT, the caller records the anomaly in the inbox row (outcome) and records the second charge for annulment (S4: ChargeLedger.recordForReversal, the per-charge model of section 11);
  • the expected result of a payment in COMPLETE_SENT (the amount the POS asked for, facts that can settle it: installments, method and type) is APPROVED;
  • everything else stores the facts and goes to COMPENSATION_PENDING (or stays): COMPENSATE, the caller makes sure the task exists. That includes a different amount in COMPLETE_SENT (no throw, the facts are stored and the payment is compensated: INV-01) and a matching amount with facts that cannot settle the payment. The amounts are stored only when they match the amount the POS asked for (ck_payment_amounts); otherwise they stay in the raw notification kept by the inbox;
  • a payment that never reached the wallet (ID_ISSUED, CANCELLED, EXPIRED) takes no result: WRONG_STATE.
  • WalletFacts carries what S4 reversals need, all optional: tid, walletCode, planCode (stored on the payment, columns tid 40, wallet_code 30, plan_code 10) and the terminal data of the payment (traceNumber, ticketNumber, terminalNumber, establishmentId), carried but not stored on the payment because the complete snapshot holds what was offered. What the facts leave out never erases what the payment already knows.
  • A wallet REFUSAL is its own command (Payment.recordWalletRejection, not a flag on the facts): no money was taken, so it never approves, schedules no forced annulment, claims no prismaPaymentId (a rejected id must not count as the "first" wallet payment, or the real approval that follows would read as a second charge) and sets the denialReason (Payment.WALLET_REJECTED_MESSAGE, ours, never the wallet's words). Effects by state: COMPLETE_SENT -> REJECTED (effect REJECTED, the intention follows to REJECTED); every other state that reached the wallet (waiting for BINs or plan, already rejected, failed, superseded, settled, in or after compensation) is recorded only, REJECTION_RECORDED, nothing changes and a finished compensation is never reopened; a payment that never reached the wallet is WRONG_STATE. A later approval with a new wallet payment id after REJECTED is compensated (REJECTED -> COMPENSATION_PENDING, INV-01; PaymentWalletRejectionTest.inv01_*).
  • One application API applies a result: WalletResults.apply(paymentId, WalletReport) (WalletReport.Paid(facts, amounts) or Rejected). It is the only caller of recordWalletResult and recordWalletRejection (ArchUnit, ArchitectureGateTest.inv01_*, proven on fixtures) and it carries the effect out in one transaction, payment then intention then task: APPROVED and REJECTED store the payment and move the intention out of COMPLETE_SENT; COMPENSATE goes through CompensationHandOff (the intention leaves the live set and the task is persisted), so the follow-up cannot be forgotten by a caller; the other effects write nothing and are the inbox row's outcome. Finding the payment of a notification is PaymentNotificationWorker (section 9, rule 12).
  • A result names its intention (D-61, D-48). Every WalletReport carries our intention id (the worker resolves Prisma's intention_id of the notification to our row when it finds the payment) and that intention, by id, is the one that follows the payment, never the payment's latest. One that does not exist or belongs to another payment makes the result FOREIGN_INTENTION: nothing is written, on the payment or on any of its intentions, and a warning is logged (WalletResultsTest.d61_*). Batch a had recorded such a Paid result on the payment and compensated it "through the payment's latest intention"; the review of batch c found that this let a result about somebody else's money cancel the live intention of a payment that was waiting for its own result, hand it to compensation and store the foreign wallet payment id in it (where a later real approval would read as a second charge). The money of a foreign result is not this payment's to compensate: it is for a person, and for the S4 reconciliation of the uncorrelated (D-79). The worker of S2b never produces one, it takes the payment from the intention it resolved; this is the defence in depth. A lost optimistic race on the payment or the intention re-runs the whole transaction, three attempts, then the exception reaches the caller. Payment.handOverToCompensation on a finished compensation is a no-op, and so is CompensationHandOff (it writes and schedules nothing, D-45). COMPENSATED -> COMPENSATION_PENDING stays declared in the table: recordWalletResult (a new wallet payment after the cancel) and reopenCompensation (a Prisma id that arrived after the compensation finished, D-48) use it. A supersede is Payment.supersede followed by CompensationHandOff.handOverSuperseded (the intention becomes SUPERSEDED, AC-32).
  • Intention: its own table (IntentionStateMachine), declared and tested the same way. The live states are INTENT_SENDING, INTENT_CREATED, BINS_RECEIVED, COMPLETE_SENT (the literals of ux_intention_one_live_per_checkout; FlywayBaselineMigrationIT cross-checks them against the domain). D-34, decided: a payment that goes to compensation (an unknown create outcome, a timeout, a cashier cancel) moves its intention, in the same transaction, to CANCELLED (SUPERSEDED for a supersede), so the checkout is free for the next payment at once and no 409 follows; the intention keeps its prisma_intention_id because the task still owes Prisma the DELETE. UNKNOWN and CLOSED stay in the schema list but nothing writes them. CompensationHandOff is the one place that does it (CompensationHandOffTest, StartPaymentServiceTest.d34_..., PosApiIT.d34_...). If Prisma's answer to the create call arrives after the intention left INTENT_SENDING, Intention.attachPrismaIntentionId stores the id and leaves the state alone.
  • The legacy estado strings are produced by PosEstadoMapper (a switch without default: a new state does not compile until its POS translation is decided). The POS never receives AUTORIZACION_DE_PAGO_SINRESPUESTA.
  • Money: PaymentAmounts enforces INV-04 (amount + adjustment == finalAmount to the cent) and Payment.approve refuses an amount different from the one the POS asked for (INV-06); PosResponses refuses to answer a total that does not add up.

6. Tests

  • Names carry the acceptance criterion (ac01_...) or the invariant (inv04_..., inv09_..., d34_...) they cover. AC-04 is proven end to end by PosWaitIT and PosWaitMultiNodeIT (a retry while waiting, after the result, after the expiry, concurrent duplicates, on another node, after a node died) over the groundwork of S1 (ac04_* tests of StartPaymentServiceTest and PosApiIT: a retry never sends a second intention).
  • HTTP tests of the full application run with RANDOM_PORT and talk to PosListener.port() through raw sockets (RawHttp); MockMvc against the full context would bypass the listener routing (D-31). Controller-only checks use @WebMvcTest (PosApiControllerTest). What the POS lives through on the wire (close, Content-Length, error shape) is PosWireIT.
  • End to end, one test per flow (SPEC 3.2): e2e/PosFlowsE2EIT drives the real POS wire (e2e/PosTerminal, the dialect of section 4) from trxid through trxpago to the answer and GET /api/trxes/{id}, with the workers and the emulated wallet, and asserts the answer, the final rows (payment, intention, compensation task) and the wire log. It does not repeat the finer cases of PosWaitIT and the others; what happens at the emulator after the POS answered is awaited by a condition, never by time (RUNBOOK section 7, "E2E suite"). AC-21 is proven by flows 7 and 8 (ac21_flow07_*, ac21_flow08_*) over PosWaitIT.ac21_*.
  • The application layer is tested with in-memory fakes (Fakes) whose transactions can roll back (RollingBackUnitOfWork), so a test can prove that a failure leaves nothing half written.
  • Test-only endpoints are @TestComponents imported by a @TestConfiguration (ListenerProbeConfiguration): a plain nested @RestController of a test class is component-scanned into every test context.
  • The authorizer of most POS tests is a scripted stub (StubAuthorizerConfiguration, @Primary): it can answer any IntentionOutcome or throw. The real adapter (PrismaAuthorizer) is tested against the in-process emulator (PrismaAuthorizerEmulatorTest, PrismaWireIT, PrismaCallbacksIT, section 10); with no gateway.prisma.* on a developer machine it answers Failed("Prisma is not configured"): nothing is sent, nothing is owed.
  • Golden fixtures live in src/test/resources/pos-golden (its README says which files are captured and which derived).
  • The ITs share one database and run one class after the other. InboxClaimIT and BinsWorkerDatabaseIT begin by finishing every unprocessed inbox row with the outcome TEST_CLEANUP, so the rows another class left cannot be claimed; that is only correct while IT classes never run in parallel (failsafe is sequential here, D-97). A new IT that leaves rows behind must not assume more, and none may assume that the database holds only its own rows.

7. Liveness

The two ping stubs (/api/ping, /prisma/v1/ping) stay as the production liveness probes of RUNBOOK section 4; the listener tests use @TestComponent probes instead of them (behind the callbacks apikey like every other callback path). The callbacks ping is the only path under the prefix that needs no apikey (section 8). Readiness (database reachable) is a hardening item.

The POS has a liveness of its own that the gateway must feed: after a trxpago that did not approve it polls the consulta every 10 s for 100 s and stops only on REFUND_DENEGADO or an approved or annulled estado (section 4, pos_ctoq.cpp 3681-3733). A payment that stays in a waiting state, or that answers an ordinary denial, keeps the cashier in front of "Verificando(n)" until the cashier cancels.

8. The Prisma adapter and the callbacks (S2a)

Where Prisma v27 is silent the choice is the safest behavior, written here, and a setting where it could reasonably differ. Open questions are in docs/PRISMA-PREGUNTAS.md; none of the choices below is a substitute for an answer.

Calls (adapter.out.prisma).

  • POST /largeaccounts/intentions carries integrator_intention_id, cuit, branch, checkout, cbu (only when the merchant operates Transferencias 3.0), mcc, intention_type = payment, currency = ARS, original_amount (a JSON number with its cents) and bins_max_quantity = 99 (AC-06, CreateIntentionBodyTest, checked against the v27 example in src/test/resources/prisma-v27/ and by an emulator that applies the v27 rules).
  • Cashback (D-40). original_amount is the sale amount exactly as the POS asked (totalitem); the cashback is neither added nor subtracted (whether totalitem includes it is Prisma question 21). A cashback above zero is sent as cashback_max_amount with absolute_cashback = true: the customer withdraws exactly what the POS already printed or nothing, a smaller withdrawal would leave ticket and money apart (gateway.prisma.absolute-cashback=false relaxes it, on the wire and in what the gateway honors, section 9c). Cashback only with Visa Debito in one payment is checked on the notification (section 9c, AC-17).
  • payment_methods_data is never sent (optional in v27, effect unknown: question 1); the plans come from the complete intention after the BINs.
  • The CUIT goes as the merchant record stores it (eleven digits); gateway.prisma.cuit-format=DASHED writes 20-31455999-9 like the v27 example. It must match the QR registration, which v27 does not describe.
  • The whole exchange is bounded (INV-01, INV-02). connect-timeout is 3 s and read-timeout (10 s) is the deadline of the whole exchange, from sending the request to the last byte of the answer. HttpRequest.timeout alone is not enough: the JDK client cancels that timer once the headers arrive, so an answer that sends its headers and then stalls would hold the payment for as long as the server likes. PrismaHttp therefore runs sendAsync(...).get(read-timeout) and cancels the exchange (which closes the connection) on expiry: an HttpTimeoutException, an unknown outcome. The body is read through BoundedBody, never beyond max-response-bytes (1 MiB, 1 KiB to 16 MiB): a longer answer, or a Content-Length above it, is a ResponseTooLargeException, also an unknown outcome and never buffered whole (PrismaAuthorizerEmulatorTest.inv01_*; PrismaDeadlineIT proves on the real application that the payment is handed over, and the POS answered, within the deadline for a stalled, a cut and an oversized answer). No redirect is ever followed (the apikey header must not leave for another host); the HTTP client is the JDK's, no new dependency.
  • TLS is always validated (INV-10). The JVM trust store applies, or the trust material of the Spring SSL bundle named by gateway.prisma.ssl-bundle (a private CA, a test certificate). No trust manager or host name verifier of ours exists and ArchitectureGateTest.inv10_* fails if one appears. The gate also closes its blind spots (each proven on a fixture): a verifier or a socket factory set on one connection (HttpsURLConnection.setHostnameVerifier, setSSLSocketFactory), SSLParameters.setEndpointIdentificationAlgorithm (banned outright: ArchUnit cannot see a null argument), any class named *InsecureTrustManagerFactory (Netty's trust-all), and System.setProperty, System.getProperties() and System.setProperties in production code, because jdk.internal.httpclient.disableHostnameVerification switches the host name check off for the whole JVM with none of the above. A JVM that is started with that property is refused by PrismaConfigurationGuard in every profile, and the RUNBOOK checks the service parameters. An untrusted certificate is an IOException: an unknown outcome, and nothing (no apikey) reached the server (PrismaAuthorizerEmulatorTest.inv10_*).
  • Outcome rule (D-46) applied to the answer: 201 with a number or a text of digits in intention_id is Created (1 to 12 digits, else Unknown); 400, 401, 403, 404 are Failed; a 422 is a Failed only when the body is the v27 validation error (error_type = invalid_request_error, a non-empty validation_errors, none about the integrator id or saying duplicate, already or exists), every other 422 is treated as a possible duplicate integrator id (question 14) and is Unknown; 408, 409, 429, other 4xx, 5xx, 3xx and every transport failure are Unknown.
  • The complete intention (S2b, D-56). PUT /largeaccounts/intentions/complete?cuit=&branch=&checkout= (the CUIT in the cuit-format, every value URL-encoded: the intention is addressed by checkout, never by id; the values are the CUIT and codes the intention was created with, kept on the intention row, never the current configuration, D-130) with one entry per payment method and BIN: bin (a number), payment_method_id, bank_id, establishment_id, terminal_number, trace_number, ticket_number and installments[] (quantity, total_amount, amount_per_installment, cft, tna); method 112 has no bin and no bank_id. Through the same bounded PrismaHttp as the create call, recorded in the wire log as COMPLETE_INTENTION after the call. Its outcome rule: 204 is Accepted; 400, 401, 403, 404 and 422 are Refused; every other answer (a 2xx that is not the 204, 3xx, 408, 409, 429, other 4xx, 5xx) and every transport failure is Unknown. Both of the last two hand the payment over (section 9, rule 11); the difference is in the cause kept with the task (CompleteOutcomeTest, PrismaCompleteIntentionEmulatorTest).
  • The status query (S2b, D-56). GET /payments/qr?intention_id= (v27 3.5: the body of the purchase notification without its transaction_type; the emulator answers exactly that, PrismaPurchaseQueryEmulatorTest), asked by the wait of the POS when no notification came (section 9, rule 15), through the same bounded PrismaHttp and never longer than what is left of the wait, recorded in the wire log as QUERY_PAYMENT after the call, outside any transaction. Its outcome rule (PurchaseQueryOutcome, PurchaseQueryOutcomeTest): 200 with a body is Answered, 404 is NotFound (v27: the operation does not exist, which for a purchase means nobody paid yet; never a rejection) and every other answer (400, 401, 403, 408, 409, 429, 5xx, a 2xx that is not 200, an empty body) and every transport failure (timeout, reset, a body beyond max-response-bytes, an untrusted certificate) is Unavailable: nothing is known, the wait keeps waiting.

Callbacks (adapter.in.prisma).

  • Paths under gateway.listeners.callbacks.path-prefix (default /prisma/v1, D-38): PUT /intentions/{intention_id} answers 204, POST /annulment and POST /refund 202, the purchase notification the configured 2xx. The purchase notification has no path and no answer in v27: it is POST /payment and 200 by default, and gateway.listeners.callbacks.payment-path and payment-ack-status change them (question 5). The path is validated at startup (plain segments, never /ping, /annulment, /refund or /intentions) and dispatched from the bound ListenerProperties value, not from a second reading of the property (D-63, PrismaCallbacksBoundPathTest).
  • Whatever else Prisma sends under the prefix is stored too (INV-03). A catch-all (PrismaCallbacksController.unrouted) takes any method on any path that no callback above takes (a notification that arrives where no callback lives, a GET on /payment): the call is authenticated, so it is Prisma's, and it is stored as UNKNOWN with "<METHOD> <path>" as its raw type (masked like every text we store; never the query string, which can carry a secret), written to the wire log as CALLBACK_UNKNOWN and answered with the purchase notification's 2xx. A person reads it; nothing is refused or lost. This replaces the Prisma-shaped 404/405 under the prefix (D-52): what remains of that shape is the api_error of a failure of ours. Unauthenticated calls are still refused first (403, nothing stored).
  • No content type ever hides a body. Spring's FormContentFilter reads the body of a PUT (the BINs callback) with a form content type as parameters and the dispatcher parses a multipart body away, either leaving the inbox an empty body and the hash of nothing. spring.mvc.formcontent.filter.enabled=false and spring.servlet.multipart.enabled=false (the gateway has no upload endpoint) make every body reach the inbox byte for byte (PrismaCallbacksIT.inv03_a...Form..., ...Multipart...).
  • The apikey gate (AC-09, INV-08). CallbackApiKeyFilter covers everything under the prefix, so a new callback is secured by default. A list of keys is accepted (gateway.listeners.callbacks.api-keys: the current one and, during a rotation, the next one; deploy the pair, give Prisma the new key, then drop the old one). The received key and every configured one are hashed with SHA-256 and compared with MessageDigest.isEqual (constant time, no length leak), all of them, without stopping at the first match; a blank entry is not a key. A missing, empty or wrong key, a key in the query string or the body, and no configured key at all (fail-closed; production does not even start) are answered 403 {"message":"Invalid authentication credentials"}, Prisma's own shape. GET <prefix>/ping, the liveness probe, is the only exception. A refused callback is not stored: an unauthenticated body is not Prisma's, and storing it would let anyone fill the database. Startup refuses a weak key (PrismaConfigurationGuard, KeyRules): the Prisma apikey, every callback key and the body hash secret must be at least 32 characters, with no leading or trailing blank and no control character; the refusal names the property (and the position in the list) and what is wrong, never the value. The rule lives in the guard, not in the property records, so the local and test profiles keep their short test keys.
  • The inbox (INV-03). The body is read once as raw bytes (at most max-body-bytes, a longer one is stored cut and a warning says so), whatever its content type or content: JSON or not, any ids or none. ReceiveNotificationService hashes the exact bytes and JdbcInboundNotifications stores the masked text in inbound_notification before the answer. body_hash is an HMAC-SHA256 (hex) under a server-side secret (gateway.listeners.callbacks.body-hash-key, required outside local/test, never logged): the stored body is masked, and a bare SHA-256 would let anyone holding the table confirm a guess of the original (a card number, an amount). Duplicates stay exact-bytes. Where the key is not set (a developer machine) a random per-process key is used and a warning says duplicates are not recognized across a restart. Correlation columns come from the body as far as they can be read (intention_id, id, transaction_type; the BINs callback takes the intention from the path). A failure of the store is the only error (500, so Prisma can retry). The records that hold a raw body (WireEntry, NewInboundNotification) print their size, never the body. One clock (D-56): received_at, processed_at and the window of the BINs duplicates are written from the gateway Clock, not from the column default, so the 27 seconds of the BINs are counted from the instant the callback arrived with the clock that decides whether they passed (InboxClaimIT.d56_aRowIsReceivedAtTheInstant...); only the leases of the claim use database time.
  • Duplicates (AC-10). Every delivery has a row (audit); the same callback again (same type, same body hash, same intention and payment ids, NULL equal to NULL) is stored already finished with outcome = 'DUPLICATE', so exactly one row per distinct callback is left with processed_at and outcome empty: that is the one processing effect S2b will work off. The decision and the insert are one transaction under UPDLOCK, HOLDLOCK on the body_hash index, so ten simultaneous deliveries leave one original (InboundNotificationsIT). The same BINs body for another intention, or a notification that differs only in its status, is another callback. The BINs trade-off (section 9): Prisma may send the same BINs again after our complete intention (question 2), which is a second round, not a duplicate. So for BINS an identical body is a duplicate only while the earlier identical row is unprocessed, or within bins-duplicate-window (default none) after it arrived; every other type stays a duplicate forever.
  • Error shape (D-52). Errors that never reach a handler under the prefix (what the catch-all above does not take: a failure of ours) are Prisma-style JSON (api_error) with no Connection: close; the POS port keeps {status, message} and its close.

The wire log and the masking contract (AC-27, INV-07, D-08). Every call to Prisma (OUT, CREATE_INTENTION, COMPLETE_INTENTION and QUERY_PAYMENT, written after the call, whatever its outcome, with the HTTP status or no answer: <exception class> and the duration) and every callback (IN, CALLBACK_<type>, with the status the gateway answered) is a wire_log row with the payment id; a callback that names only a Prisma intention id gets its payment through intention.prisma_intention_id. Rows are written in a transaction of their own and a failure to write is logged (class only) and never fails the payment. The wire log is never written inside a transaction: its own transaction (REQUIRES_NEW) would hold a second connection and could wait on a row lock the caller holds (the payment row its foreign key points at), a deadlock the database does not see. JdbcWireLog.record therefore refuses a call made while a transaction is active (checked before the try, so the swallowing of write failures cannot hide it; PrismaWireIT.ac27_theWireLogRefuses...) and the port says so. The store masks before the insert (PayloadMasker, applied inside JdbcWireLog, JdbcInboundNotifications for the body AND the raw type, and, from S2b, bins_snapshot): a card_number or pan keeps its last four characters whatever it is made of, an apikey, authorization, password, secret or token (any case, _ and - ignored, any depth) becomes ***, numbers keep their exact text. A body that is not valid JSON is masked as text: the same quoted keys ("apikey":"x", "card_number":"AB12 3456 ...", also in a truncated JSON), apikey: value pairs, Authorization: Bearer|Basic <token> (the scheme and the token) and a bare Bearer|Basic <token>, and any run of 13 or more digits, also in groups separated by single spaces or dashes (4000 1234 1234 1234 becomes **** **** **** 1234). The raw_type is masked as plain text, never re-serialized as JSON. The limit is 16 MiB characters (ListenerProperties.Callbacks.MAX_BODY_BYTES_LIMIT, the greatest max-body-bytes): a body counts bytes and the masker counts characters, never more than the bytes, so the masker never cuts what the callbacks kept whole; the cut, with its marker, happens after masking. PayloadMasker.maskAsJson is the JSON-valid mode for bins_snapshot (ck_bins_snapshot_bins is ISJSON): its result is always an object or an array, anything else (a scalar, text, nothing, a body that would have to be cut) is wrapped as {"raw": "<masked text>"} with the cut inside the text, proven by real inserts (PayloadMaskerBinsSnapshotIT). Headers are never part of a record, so the apikey cannot be stored; PrismaWireIT, PrismaCallbacksIT grep the rows and the log output for the keys and for a full benefit card number.

9. The S2 flow contract (D-50)

The slices S2a (this one: create call, callbacks, inbox, wire log) and S2b (BINs to complete intention, notification to POS answer) build one flow. These rules bind both:

  1. Every exit of the POS trxpago waits to a final state or hands off. After the create call (start(), which only starts the payment) the request waits (database poll, rule 14) until the payment is APPROVED, REJECTED or in compensation; when the wait expires it hands the payment over (CompensationHandOff) and the POS hears "denied". There is no exit that leaves the payment waiting: AuthorizePaymentService is the one place that runs both steps. The one exception is the one of INV-02 (CONSTITUTION, ADR-002): when the storage cannot be reached for the whole hand-over budget the POS is still answered "denied", with no compensation intent persisted, and an alert names the payment (rule 14, item 7); the domain then never approves that payment (Payment.recordWalletResult, at or after its wait deadline).
  2. An expiry that races a late approval answers the final state. The expiry re-reads the payment inside the very transaction that would hand it over: if the notification was applied in the meantime the payment is APPROVED and that is the answer, not a denial of a charged customer (PaymentWaitTest.d56_anExpiryThatRacesALateApproval...).
  3. COMPLETE_SENT is persisted before the complete call. The state and the complete_snapshot rows (establishment, terminal, trace and ticket numbers per entry) are committed first, then PUT /largeaccounts/intentions/complete is sent, so a crash after the call leaves the numbers a forced annulment needs (BinsWorkerTest.d56_theStateAndTheSnapshotArePersistedBeforeTheCall: the worker sees both, with no transaction open, when it calls Prisma; rule 11). The snapshot is per payment method AND BIN. The wallet offers one card entry per BIN and the complete intention of v27 carries bin and bank_id on each, so complete_snapshot_method has bin (digits, 6 or 8) and bank_id, both NULL for method 112 (no card), and is unique on (complete_snapshot_id, payment_method_id, bin): the same method for two BINs is two entries, and method 112 appears once because SQL Server's UNIQUE treats NULL as one value (FlywayBaselineMigrationIT, the theSnapshot... tests). Trace and ticket numbers are per ENTRY (D-25 is still open with Prisma, question 6, and this is the safe choice until it is answered): every entry takes the next numbers of the terminal, capped at 10 and 6 digits by the checks, so a forced annulment repeats exactly the numbers of the entry the customer paid. A complete intention with many BINs therefore burns many numbers per payment; the wrap policy (D-09) and a smaller offer (one entry per method for the BINs the wallet listed) are open until Prisma answers.
  4. A callback that cannot be correlated yet is retried from the inbox. The BINs callback can arrive before the gateway stored the Prisma id (the create call is still in flight): it is stored (S2a does this) and left unprocessed; the worker (BinsWorker, rule 11) claims unprocessed rows (claimed_by, claimed_until) and retries the correlation every gateway.inbox.retry-delay (1 s) until the intention exists or gateway.inbox.correlation-timeout (60 s from the arrival) passes, then marks the row UNCORRELATED for manual handling. A callback whose path names no usable intention id is UNCORRELATED at once. A callback is never answered with an error because of it (BinsWorkerTest.d56_binsThatArriveBeforeThePrismaIdIsStored...).
  5. Question 1 of docs/PRISMA-PREGUNTAS.md is a dependency. The flow assumes the plans are offered after the BINs, within 27 seconds (AC-07); if Prisma lets the integrator preload them at creation the BINs step may disappear.
  6. A wallet result is applied through WalletResults.apply (section 5: the only caller of recordWalletResult and recordWalletRejection) by the inbox worker of the purchase notification (rule 12), and the worker sets the row's outcome from the effect: APPROVED, REJECTED, COMPENSATE, DUPLICATE, REJECTION_RECORDED, SECOND_WALLET_PAYMENT (the anomaly of D-45, for S4), WRONG_STATE and FOREIGN_INTENTION (section 5), plus its own: UNCORRELATED, CHECKOUT_MISMATCH, UNUSABLE_NOTIFICATION, UNUSABLE_RESULT, STATUS_NOT_FINAL, REVERSAL_RESULT, AMOUNT_MISMATCH, UNOFFERED_PLAN, CASHBACK_NOT_OFFERED (section 9c) and ABANDONED (all at most 30 characters, the column). A result without a usable wallet payment id cannot be a WalletFacts: the worker hands a payment that waits for the wallet over and records UNUSABLE_RESULT; nothing is dropped. The outcomes of a BINs row (BinsWorker, VARCHAR(30)): COMPLETE_SENT (Prisma answered 204), COMPLETE_REFUSED (a definite refusal: 400, 401, 403, 404, 422) and COMPLETE_UNKNOWN (anything else: 5xx, timeout, IO error, a 2xx that is not the 204, 408, 409, 429...), both of which hand the payment over; PAST_DEADLINE (the 27 s ran out, or less than gateway.inbox.complete-minimum-budget was left of them: nothing was sent); WAIT_EXPIRED (the wait deadline of the payment had passed, the POS was or is being told "no sale": nothing was sent and the payment is handed over in the same transaction, BinsWorkerTest.s2b_c3_*, BinsWorkerDatabaseIT.s2b_c3_*); NO_OFFER (the offer cannot be built: no establishment for an accepted method or for 112, no terminal, a checkout disabled meanwhile), UNUSABLE_BINS (the body is not the BINs of a wallet) and NUMBERS_EXHAUSTED (rule 10), all handing the payment over, fail closed; ALREADY_PROCESSED (the intention is past INTENT_CREATED, rule 8) and NOT_LIVE (superseded, cancelled, failed or paid: it gets no complete, rule 11), which change nothing; UNCORRELATED (rule 4) and ABANDONED (an unexpected failure kept the row from being processed for ten minutes; its error is in the log, class only).
  7. The complete intention that did not make it. Two different things, two different states. A complete intention that was never sent because the 27 seconds ran out is COMPLETE_FAILED (BINS_RECEIVED -> COMPLETE_FAILED, the edge the transition tables already declare) and is entered together with the hand-over to compensation, in the same transaction (CompensationHandOff.handOverCompleteFailed: payment, intention, task). A complete intention that was sent (COMPLETE_SENT is persisted first, rule 3) and that Prisma refused, for instance with the 404 of a late or superseded one, or answered with an unknown outcome, hands the payment over from COMPLETE_SENT (the intention becomes CANCELLED): no new edge, and the stored state says that the plans were offered (BinsWorkerDatabaseIT.d56_*).
  8. AC-10 versus a second BINs round (the trade-off). The inbox cannot tell a delivery that Prisma retries from a second round that carries the same body. The rule of section 8 favors never swallowing a second round (the money path needs it processed): an identical BINs body is a duplicate only while the earlier one is unprocessed, or within bins-duplicate-window. The cost is that a retried delivery that arrives after the first was processed (outside the window) is processed again, so the BINs step is idempotent by the state of the intention, not by the dedupe (D-60): an intention already past INTENT_CREATED (BINS_RECEIVED, COMPLETE_SENT) ends the row as ALREADY_PROCESSED, sends no second complete intention and takes no number, and an intention that is not live ends it as NOT_LIVE (BinsWorkerTest.d60_*, BinsWorkerDatabaseIT.d60_*). v27 accepts the complete intention only for an intention in state created, so a second round after a complete would be a 404 anyway: a genuine second BINs round (COMPLETE_SENT -> BINS_RECEIVED, declared in the tables) is not wired, and the window is the knob if Prisma turns out to retry slowly (InboundNotificationsIT.ac10_...Bins..., InboundNotificationsWindowIT).
  9. The plans come through a seam (PlanSource, ADR-003). domain.PlanSource answers the plans of one card entry and domain.CompleteOffer builds the whole offer: one entry per accepted payment method AND BIN the wallet listed (the same method for two BINs is two entries, the same BIN twice is one, a method the merchant does not accept is not offered), method 112 once at the end with neither BIN nor bank, and in every entry the 1-installment plan of the whole amount, added by the builder when a source leaves it out, so no source can break AC-08 (CompleteOfferTest.ac08_*). The plan a source gives for 1 installment may only replace the plain one by a discount; a 1-installment plan that charges more than the amount is OfferNotPossibleException (PLANES-CUOTAS D3, CompleteOfferTest.d3_*). An accepted method, or 112, without an establishment is OfferNotPossibleException: the offer would be invalid, so there is none and the payment is handed over (fail closed). S3 replaced the seam of the build order: the PlanSource bean is now MerchantPlanSource, which looks up the checkout in the catalog and answers through PlanSource.forPayment(PlanContext) (the checkout and the instant: the one call BinsWorker changed) with a GatewayConfiguredPlanSource over the plans of installment_plan of the merchant and the branch. There is one source and no per-merchant setting (ADR-003, Mode A removed 2026-10-28). The rules of the plans are section 9a; what a POS sends about plans is ignored (section 9b).
  10. The numbers of a complete intention are one block (CompleteSnapshots.allocateNumbers, INV-05). The whole offer (method + BIN entries, method 112 included) takes its trace and ticket numbers from the terminal with ONE UPDATE terminal SET trace_seq = trace_seq + N, ticket_seq = ticket_seq + N OUTPUT INSERTED.*, in the same transaction as the snapshot rows, never a read followed by a write: the row lock lasts to the end of that transaction, so blocks taken at the same moment, also on two nodes, are disjoint, and a rollback gives the numbers back (TerminalNumbersIT.ac26_*). The same statement returns the terminal number the row has at that moment (NumberBlock.terminalNumber), and that number, not the one terminalOf read earlier without a lock, goes in the complete intention and in the snapshot: an ADMIN who renames a never-numbered terminal between the read and the allocation cannot make the sale send (oldNumber, 1, 1) while the terminal continues as the new number, so no two terminals ever send the same (terminalNumber, trace, ticket) (D-125, BinsWorkerTerminalRenameIT). Entry i gets first + i of both. At the Prisma limit (ticket 999,999; trace 9,999,999,999) the CHECK of V1 refuses the block, the sequence is untouched and the adapter reports NumberRangeExhaustedException: the numbers never wrap (a repeated number would address another operation in a forced annulment, and uq_complete_snapshot_method_ticket would refuse it anyway), the complete intention is not sent and the payment is handed over (NUMBERS_EXHAUSTED). The wrap policy is Prisma question 6 (D-09, D-75, still open).
  11. The BINs worker (D-56). The callback only stores its row and wakes the worker (InboxWake); BinsWorker takes the row off the inbox on a virtual thread of InboxWorkerRunner (up to gateway.inbox.max-concurrent, 16, rows at the same time for each kind of work, a sweep every gateway.inbox.poll-interval, 500 ms, for rows nobody woke it for), so the callback answers 204 whatever the processing costs (CompleteIntentionIT.ac07_*). The BINs and the purchase notifications have permits of their own: a backlog of BINs on a slow Prisma holds the BINs permits, never those of the notifications that end a waiting payment (InboxWorkerRunnerTest.s2b_*, InboxLanesIT); the runner also stops after the web server has drained (getPhase()), so the rows that are already stored when a restart begins are still worked while the in-flight POS requests finish (InboxShutdownOrderIT). A notification that arrives during the drain is not served by this node: graceful shutdown refuses new connections on it, so Prisma's callback goes to another node (or, with one node, waits for Prisma's retry after the restart); only rows stored before the drain, or stored by another node, are applied. Rows are leased with UPDATE ... OUTPUT ... WITH (READPAST) in database time (gateway.inbox.lease, 30 s), so several nodes never process the same row (InboxClaimIT); every claim is held under an owner of its own (the node name and a number, ClaimOwners), so a drainer whose lease ran out can never finish or defer a row that another drainer claimed again. The lease must outlast the call to Prisma, which the startup refuses otherwise (TimingGuard: lease at least gateway.prisma.read-timeout plus 5 s). For one row, with no transaction open across the call to Prisma and the wire log written after it, outside any transaction:
    1. Prepare, one transaction repeated on a lost race or a deadlock victim (UnitOfWork.execute, three attempts): find the intention by Prisma's id; finish the follow step of the create call (the payment INTENT_SENDING -> INTENT_CREATED); an intention past INTENT_CREATED is ALREADY_PROCESSED (rule 8), one that is not live is NOT_LIVE. v27 addresses the complete intention by CUIT, branch and checkout, never by intention id, so a complete sent for a superseded intention would land on the newer one: it is made only while this intention is still the checkout's live one. ux_intention_one_live_per_checkout makes "live" mean "the live one of its checkout" and the optimistic lock closes the race with a supersede that commits before the prepare does (BinsWorkerTest.d56_anIntentionThatWasSupersededWhileTheWorkerPrepared...). Past the deadline, no complete: rule 7.
    2. The 27 seconds are counted from received_at, the moment the BINs arrived, with one clock: the gateway Clock writes received_at (and processed_at, and the window of the BINs duplicates) and the same Clock decides whether the 27 seconds passed. A worker that takes the row late finds the deadline already behind it (BinsWorkerDatabaseIT.d56_theDeadlineIsCountedFromTheArrivalOfTheBins..., driven by a movable clock, no sleeps). Only leases use database time (D-05). The call is bounded by what is left: CompleteIntentionRequest.budget is the time between now and the 27th second, measured again just before the call, and the adapter gives the exchange that limit (never more than gateway.prisma.read-timeout). With less than gateway.inbox.complete-minimum-budget (1 s) left the complete is not sent at all (PAST_DEADLINE, fail closed): decided at the prepare, before any number is taken, or, when the prepare transaction itself used the time up, at the call, handing the payment over from COMPLETE_SENT (BinsWorkerTest.s2b_m3_*, PrismaCompleteIntentionEmulatorTest.s2b_m3_*). With the minimum at zero a complete at exactly 27.000 s is still handed to the adapter, which sends nothing when no time is left.
    3. In the same transaction as the decision: payment and intention to COMPLETE_SENT, the BINs snapshot (bins_snapshot, masked), the numbers of the whole offer (rule 10) and the complete snapshot (rule 3). The writes go payment, intention, then the rest (D-49): lock order payment, intention, task everywhere (BinsWorkerTest.d56_theLockOrder...).
    4. The call goes through AuthorizerPort.completeIntention and the bounded PrismaHttp (the same whole-exchange deadline as the create call, never longer than gateway.prisma.read-timeout). An answer that is not the 204 (a refusal, a timeout, a 5xx, an IO error, an exception from the port) hands the payment over from COMPLETE_SENT and finishes the row in the same transaction; the cause (complete intention refused: HTTP 404, complete intention outcome unknown: HttpTimeoutException: never a body, a URL or a secret) is kept in compensation_task.last_error, and the POS hears "denied" later, from the wait (rule 14). If the payment already left COMPLETE_SENT meanwhile (the wallet got its plans, paid and its result was applied), nothing is handed over. A claim lost by then does not undo the hand-over: the call was made and what it answered is what the payment lives with, so the hand-over stays and the lost claim is an INFO line (the new holder of the row finds the intention out of INTENT_CREATED and finishes it as NOT_LIVE). Before the call, where nothing was sent, a lost claim does undo the decision, because whoever holds the row decides it again.
    5. Fail closed. The offer is never smaller than v27 requires: a body that is not the BINs of a wallet, no terminal, no establishment for an accepted method or for 112, a checkout disabled meanwhile or a terminal without numbers hands the payment over instead of sending a partial complete intention. Known windows (D-76): a node that dies between the commit of the prepare and the call, or whose record transaction fails, leaves COMPLETE_SENT with nothing sent or recorded. The redelivery or the next lease finds the intention past INTENT_CREATED and ignores it; the payment is handed over when the wait of the POS expires (rule 14) or by the reaper of S4, and INV-01 holds because a wallet without plans cannot pay. A supersede that commits after the prepare and before Prisma reads the call can still make the call land on the newer intention (v27 question 24): the residual window of D-56. v27 does not say where the terminal number goes (per entry in the example, at the top in the table, question 10): the body keeps it per entry; a BIN is a number, as v27 says, except one with a leading zero (text).
  12. The purchase notification worker (D-56, D-57, AC-10). PaymentNotificationWorker takes the PAYMENT rows off the same inbox, claims and runner as the BINs worker (InboxWork beans, InboxRetries for the retry and the abandon), with a claim name of its own. It claims only PAYMENT: ANNULMENT, REFUND and UNKNOWN rows stay unprocessed (rule 13). For one row, with nothing slow inside a transaction:

    1. Decode and classify (PaymentNotificationDecoder, NotificationStatus.of(status, transaction_type)). The status table (text compared trimmed and ignoring case, only the exact word counts, NotificationStatusTest):
    transaction_type / status of the notification Meaning What the worker does Row outcome
    payment (or absent) / approved a definite approval WalletReport.Paid through WalletResults.apply (after the offer check below) the effect: APPROVED, COMPENSATE, DUPLICATE, SECOND_WALLET_PAYMENT, WRONG_STATE, FOREIGN_INTENTION; or AMOUNT_MISMATCH / UNOFFERED_PLAN / CASHBACK_NOT_OFFERED (a COMPENSATE caused by the offer or cashback check)
    payment (or absent) / rejected a definite refusal WalletReport.Rejected through WalletResults.apply: never approves, claims no wallet payment id, schedules nothing REJECTED, REJECTION_RECORDED, WRONG_STATE, FOREIGN_INTENTION
    any / annulled, refunded; or a transaction type that contains annul or refund (whatever the status says: an approved annulment is not a payment) money going back nothing about the payment changes; recorded for the reversal flow of S4 (D-78) REVERSAL_RESULT
    anything else: pending, in_process, a word nobody described, a status that is not text, none; a transaction type other than payment that is not a reversal not final nothing about the payment changes, nothing is scheduled (never an annulment) STATUS_NOT_FINAL

    The body is not JSON, or not an object: UNUSABLE_NOTIFICATION. v27 names no status other than these four and no intermediate one: whether pending or in_process exist, and whether annulled and refunded really arrive on this channel, is question 5b of docs/PRISMA-PREGUNTAS.md. 2. Correlate through the intention, by the Prisma intention_id the row names, never through the wallet payment id (Prisma's payment id has 7 digits and repeats, D-56): the payment of the intention is the one the notification is about (PaymentNotificationWorkerTest.d56_theWalletPaymentIdNeverCorrelates...). An intention the create call has not stored yet is deferred and retried like the BINs (rule 4) and marked UNCORRELATED after gateway.inbox.correlation-timeout; a notification that names none is UNCORRELATED at once. The cuit, branch and checkout it states (when it states them) must be those the intention was created with (intention.merchant_cuit, branch_code, checkout_code: Prisma echoes what the create call sent, and the console may have renamed the checkout since, D-130), found whether or not the checkout is still enabled: the CUIT by its digits, the codes ignoring case and blanks. Another checkout's is CHECKOUT_MISMATCH: logged as an error, never applied to a payment, kept for a person (D-79). 3. Check the charge against the offer (D-57, INV-06, OfferCheck over CompleteSnapshots.offeredMethods, the read model of the latest complete intention that was sent): the notified method, BIN (the same, or the 6 or 8 digits of the other length; absent: any entry of the method; method 112 has none), installments and total must be an entry and a plan of the offer, and the total that plan's total_amount to the cent (Money.sameCents). It carries its amounts (PaymentAmounts: the adjustment is Money.difference(total, amount asked), so INV-04 holds by construction) and the plan code of the offered plan. Anything else (a total one cent away, a plan or a method or a BIN never offered, no amount, no installments) is applied without amounts, which can never approve (Payment.recordWalletResult): the wallet facts are kept (they are the compensation's key) and the payment goes to compensation (ADR-002, D-44), with the cause kept with the task for the operator (notified charge is not the total of the offered plan, notified charge is not an offered plan). A payment that never got a complete intention (cancelled before the wallet got its plans, the late payment after cancel) has no offer to compare with: its late approval is simply COMPENSATE. Assumptions that Prisma has not confirmed and that fail closed: the notified amount is the plan's total_amount (question 12), and it excludes the cashback (question 21, section 9c); a notification of method 112 (a transfer) carries installments, and every notification carries payment_method_type (questions 5c and 5d of docs/PRISMA-PREGUNTAS.md; 5e asks whether a rejected is final for the intention): without the first no plan of the offer can be matched, without the second the facts cannot settle the payment (section 5), and either way the payment goes to compensation with its facts instead of approving. A wallet that says otherwise makes every such payment a compensated one until it is answered. 4. Apply through WalletResults.apply (its own transaction, payment then intention then task, the retry of a lost race and DeadlockRetry) and finish the row with the effect as the outcome, in a second step: apply and finish are two transactions (the lease covers both). A node that dies between them leaves the row to the next lease, whose worker applies the same result again: by wallet payment id that is a DUPLICATE, so the effect on the payment is once and only the audit row says DUPLICATE instead of what the first node did (D-80). A lost lease at the finish is a warning, never an undo. 5. Idempotency, AC-10. The same notification twice: the inbox stores the second already finished as DUPLICATE (rule 8); the same wallet payment id in a row with other bytes is DUPLICATE by the effect, and nothing is written (PaymentNotificationIT.ac10_aDuplicateNotification...). A second, different approved wallet payment for the same payment is never approved twice and is not applied to it: the first wallet payment id is kept, the row is SECOND_WALLET_PAYMENT with the payment id resolved, and an error is logged. ADR-002 (amended in S4, D-79) says a second charge is annulled and only the second: the charge is recorded in wallet_charge (sale = 0) and gets a reversal and a REVERSE_CHARGE task of its own, so the sale is never annulled (CompensationFlowIT, WalletResultsTest.d79_*, section 11). A late approval after a rejection is a different case and is compensated (REJECTED -> COMPENSATION_PENDING). 6. Anything unexpected (a failure of the store, of the decoder) defers the row and abandons it after ten minutes (ABANDONED), exactly like the BINs; a failure inside the apply rolls the whole effect back and the row is tried again (PaymentNotificationWorkerTest.inv02_*). 13. Reversal notifications are stored by the callback and applied by the reversal worker (D-78, S4). The ANNULMENT and REFUND callbacks are stored by the callbacks like every other (INV-03, CALLBACK_ANNULMENT and CALLBACK_REFUND in the wire log). ReversalNotificationWorker (an InboxWork of the same queue, InboxQueue.claimNext with its types) correlates them by intention id and type, never through prisma_payment_id, and settles the reversal exactly as the job does when it polls (ReversalSettlement): section 11. A PAYMENT row whose status or transaction type is a reversal is still finished as REVERSAL_RESULT with its payment resolved and nothing applied. An operator sees both in the queries of RUNBOOK section 11 (PaymentNotificationIT.d56_aReversalNotificationNobodyAskedFor..., ReversalNotificationWorkerTest).

  13. The wait of the POS trxpago (D-56, R-13, ADR-002). AuthorizePaymentService is what the POS request runs: StartPaymentService.start (record the command, send the intention once, record the answer) and then PaymentWait until the payment can be answered. This is rule 1 made real: no request leaves a payment that is still waiting.

    1. The database is the source of truth. The BINs callback and the notification can land on another node than the one holding the request (several nodes are active at once), so the wait reads the payment row every gateway.pos.wait.poll-interval (250 ms), each poll a read-only transaction, until the state is not one of the four that wait for the wallet (PaymentState.isWaitingForTheWallet: INTENT_SENDING, INTENT_CREATED, BINS_RECEIVED, COMPLETE_SENT). It sleeps with Thread.sleep on the request's virtual thread (no thread pinning on JDBC: Java 25), and holds no connection while it sleeps. There is no in-process latch; one could only shorten the sleep, never replace the read, and the cost of not having it is at most one poll interval of latency (D-85). PosWaitMultiNodeIT.d56_theOutcomeDeliveredToAnotherNodeEndsTheWaitOfThisOne proves it with two Spring contexts on one database: the wallet talks only to node B, node A has no inbox worker at all and still answers.
    2. The deadline is payment.wait_deadline_at, written in the transaction that starts the authorization (before the call to Prisma, so a node that dies during it still leaves it), counted from the instant the POS request arrived (StartPaymentService, WaitPolicy.deadlineFor): the create call is part of it, a slow one shortens the wait and never stretches the answer (AuthorizePaymentServiceTest.r13_theDeadlineCounts...). The arrival is taken once, at the entry of AuthorizePaymentService, before the begin transaction waits for its connection (Hikari: up to 5 s), reads and is rerun after a lost race, and is carried to StartPaymentService.start(command, arrivedAt) and PaymentWait.await(status, arrivedAt); stamping the deadline inside the begin transaction would have let the denial leave after the caller's read timeout (StartPaymentServiceTest.s2b_c3_*, AuthorizePaymentServiceTest.s2b_c3_*). The first deadline is the only one (Payment.waitUntil): a retry, another node and a restart wait for that same instant, and a persisted deadline later than this request's own arrival + deadline is not obeyed (PaymentWaitTest.s2b_c3_*). A payment that waits with none (a row from before) gets one from the arrival of the request, once; if that cannot be stored, an approval is never applied to it (Payment.recordWalletResult fails closed with no persisted deadline).
    3. It must fit before the caller gives up (R-13). The caller's read timeout, gateway.pos.wait.caller-read-timeout (59 s: RouterQR's dev timeout-pago is 60 s, its read 59 s), is spent from the arrival of the request in three parts: the gateway.pos.wait.deadline (45 s), then the hand-over budget (12 s), then gateway.pos.wait.safety-margin (2 s) for the answer and the network. The budget is what is left between the other two, so every give-up (an expiry and an interrupt alike) is capped at arrival + caller-read-timeout - safety-margin (57 s from the arrival, WaitPolicy.giveUpAt) and the denial never leaves later. The safety margin is at least 1 s (PosWaitPropertiesTest.s2b_c3_*), and a key under gateway.pos.wait that does not exist (a leftover answer-margin) fails the start. The deadline plus the safety margin plus one poll interval must fit in the read timeout, otherwise the gateway refuses to start and says which of the three to change (PosWaitPropertiesTest.r13_*). That same maximum, caller-read-timeout - safety-margin counted from the arrival (57 s), must also fit in spring.lifecycle.timeout-per-shutdown-phase (60 s), or a restart would cut the waits it promised to let finish (TimingGuardTest.inv02_*, TimingGuardTest.s2b_c3_*, StartupRefusalIT). The create call counts inside the deadline, so gateway.prisma.read-timeout must also be shorter than the deadline (TimingGuard, outside the local and test profiles, S2b M2). The caller's real value is not known in production, nor is the read timeout of the DOS POS on the direct VPN: both are to be verified and the settings are the place to put them (RUNBOOK section 3, D-83). The status query cannot push the answer past the deadline either: it runs on a thread of its own and is called off when the wait ends.
    4. Expiry is cancellation with automatic annulment (ADR-002). At the deadline PaymentWait re-reads the payment in the transaction that hands it over: if the wallet's result was applied meanwhile, that final state is the answer, not a denial of a customer who was charged (rule 2, PaymentWaitTest.d56_anExpiryThatRacesALateApproval...); otherwise CompensationHandOff.handOver writes, in one transaction and in the lock order payment, intention, task, the payment -> COMPENSATION_PENDING, its intention -> CANCELLED (the one that is live for the payment: a retry holds none of its own) and the compensation task PENDING, with the cause wait for the wallet's result expired in compensation_task.last_error; a lost optimistic race is run again. Only then is the POS answered: AUTORIZACION_DE_PAGO_DENEGADA, statuscode 1, mensajevarios = Payment.UNCONFIRMED_MESSAGE (53 bytes, never empty, at most 79), never SINRESPUESTA and never a 500 (PosWaitIT.r13_*). A wait that is interrupted (the server is stopping) gives up the same way, with the cause wait for the wallet's result was interrupted: the interrupt flag is cleared while the hand-over is written, because the pool refuses a connection to an interrupted thread, and restored afterwards. An interrupt shortens nothing: it tries to persist for as long as an expiry does, until the cap of item 3 (a second interrupt in the middle of the retries does not stop them either), and denies with the alert of item 7 only when that instant is reached (PaymentWaitTest.s2b_c3_*). If the process is killed first no answer is sent, which is not a breach of INV-02.
    5. The boundary with S4: the wait only persists the intent. The wait never calls Prisma to cancel: the DELETE /intentions/{id} that cancels the intention at Prisma, the forced annulment of a payment that was paid, the retries with backoff and COMPENSATION_FAILED are the compensation job (section 11, ADR-002, D-05), which works the task the hand-over wrote (RUNBOOK section 9). A notification that arrives after the hand-over is the late result of section 5 (PosWaitIT.ac21_*: stored, outcome COMPENSATE, the facts kept for the annulment, the cancel task plus the annulment task of the late charge, and the POS keeps hearing the denial it was given).
    6. Retries (AC-04). start never sends a second intention for a payment that already began: it returns the stored status, and when that status is still waiting the retry resumes the wait against the same persisted deadline; when it is final it returns the stored result at once; after the expiry it returns the stored denial. Concurrent duplicates for one id send exactly one create call, also across two nodes (PosWaitIT.ac04_*, PosWaitMultiNodeIT.ac04_*), and a retry that arrives after the node that started the payment died works from the database alone.
    7. The storage may fail and the wait never does (S2b H1). Every storage call of the wait (a poll, the read of the Prisma id, the expiry) runs on a virtual thread of its own under a time limit, because a pool that gives no connection holds the request for as long as Hikari's connection-timeout (5 s): a poll may take at most what is left before the deadline and the expiry at most until WaitPolicy.giveUpAt(arrival) (item 3: the arrival plus the caller's read timeout less the safety margin, 57 s with the defaults, so 12 s after the deadline), so the denial still reaches the caller. A closed executor does not lift that limit: the call then runs on a virtual thread of its own under the same limit. Every attempt is cut at the time that is left by the wait itself (PaymentWait.bounded), not by the pool: a pool slower than the budget, or a connection that is granted and then hangs, cannot hold the answer, which is why Hikari's connection-timeout (5 s) is left as it is (two whole pool timeouts fit in the budget). A poll that fails (any failure but a payment that does not exist) is logged, class only and not every 250 ms, and the wait goes on to the next one. At the deadline the hand-over is attempted until the budget is spent: a lost race reads again and decides again (never a 409 with the payment still waiting, and what another node made durable, an approval above all, is the answer), a failed attempt is tried again after a poll interval. If nothing can be persisted the POS is denied all the same (never a 500, never SINRESPUESTA) with no compensation intent stored: this is the exception to INV-02 (CONSTITUTION, ADR-002), and what replaces the persisted intent is, first, an alert: one ERROR line that starts with the stable marker INV02_UNPERSISTED_DENIAL payment=<id> (then the state, the reason expired or interrupted and the class of the failure: never a message, a body or a secret), to be wired to an alert by the operator (RUNBOOK section 3); and second, the domain: a wallet approval applied at or after the payment's wait deadline never approves it (Payment.recordWalletResult, whoever applies it, the notification worker or the status query through WalletResults), it is recorded and handed over to compensation (PaymentLateResultTest.inv02_*, PosWaitStorageFailureIT.inv02_*). The payment stays as it was, and a retry of trxpago hands it over at once. An approval that another node committed before the deadline while this node could not read it is for the reconciliation (D-105, S4: the node leaves a durable marker, UnpersistedDenials, before it answers, and UnpersistedDenialReconciler settles it, section 11), which annuls only a payment whose pos_told_approved_at and pos_approval_intent_at are both absent (rule 16); the complete intention of a BINs row that is drained after the deadline is never sent (BinsWorker.prepare, outcome WAIT_EXPIRED, rule 6) (PaymentWaitTest.s2b_h1_* and inv02_*, PosWaitStorageFailureIT: a database that fails and a pool with no connection left, both answered 200 AUTORIZACION_DE_PAGO_DENEGADA inside the budget).
  14. The status query of the wait (D-56). From gateway.pos.wait.status-query-lead (15 s) before the deadline, and again every gateway.pos.wait.status-query-interval (5 s) while it settles nothing, the wait asks Prisma what happened to the payment of its intention (StatusQuery, PurchaseStatusFallback, section 8), on a virtual thread of its own with the time that is left as its budget. A definite answer is applied only through PurchaseResults, the code the notification worker uses (rule 12): the same decoder, the same status table (approved, rejected; pending, annulled, refunded and every word nobody described change nothing), the same check of the charge against the offered plan (an amount a cent away, a plan never offered: compensated, never approved) and WalletResults.apply, the one applier. An answer that names another intention than the one asked, or another checkout, is never applied. Applying the same result twice (by the query and by a notification) is a DUPLICATE by the wallet payment id. A 404, a status that is not final, a 5xx, a stall, a reset, a body beyond the cap, an unreadable answer, an exception: nothing changes and the wait goes on to the deadline (PurchaseStatusFallbackTest, PosWaitIT.r13_aFaultOfTheStatusQuery...: 500, 503, stall, reset and huge body all end in a 200 denial at the deadline). The result is applied with no inbox row: the audit of the query is its wire log row (QUERY_PAYMENT, PosWaitIT.ac27_*).
  15. The record that the POS was told "approved" (INV-01, D-105). The one fact the money transactions do not hold is what left the gateway: payment.pos_told_approved_at is written by PosApprovalMarkerFilter through PosApprovals, after the approved answer was written out completely (section 4), in a small update of its own and never inside a unit of work (the JDBC adapter refuses a call made inside a transaction, like the wire log, and it does not map the column in PaymentEntity, so a save of the payment cannot overwrite it). It keeps the first instant, so a retry, a consulta or another node asking again changes nothing, and it does not touch version or updated_at: a money write never loses its optimistic lock to it, and the sanity query of RUNBOOK section 3 (updated_at >= wait_deadline_at) does not mistake a consulta answered after the deadline for a late approval. A payment whose marker is set is a sale and is never compensated as a no-sale (the S4 reconciliation and the compensation job read it, D-105); one whose record failed raised POS_APPROVAL_UNRECORDED (PosApprovalMarkerFilterTest, PersistenceAdaptersIT.inv01_*, PosWaitIT.inv01_*, PosFlowsE2EIT flows 1, 2 and 12). Its twin, written first: payment.pos_approval_intent_at (PosApprovals.recordApprovalIntent, same adapter, same rules, same unmapped column). PosApprovalGuard writes it before the controller returns an approved answer; if it cannot be stored the answer is INTENCION_DE_PAGO_RECIBIDA_APROBADA (nothing of the approval in it) and POS_APPROVAL_DEFERRED is logged, so the gateway never tells the POS approved without a durable record that it may have heard it. A payment with either marker set is "the POS may have heard approved" (never compensated as a no-sale, never auto-annulled); with both NULL the POS never heard approved (PosApprovalGuardTest, PersistenceAdaptersIT.inv01_*Intent*, PosWaitIT.inv01_*Intent*, PosFlowsE2EIT).

9a. Plans, surcharges and discounts (S3, ADR-003)

What the complete intention offers per card (ADR-003: the plans are the gateway's). Pure code in domain (GatewayConfiguredPlanSource, InstallmentPlan, BinMatcher, PlanFigures, PosRounding, MipymePlans); the only reads are in JdbcPlanCatalog behind the port PlanCatalog, and the plan CRUD is S5.

  1. Rounding is the POS's, in its arithmetic (AC-14 open, D-S3-9). The source is the Almacor POS: ROUND_DOUBLE (pos_misc.cpp; the active build calls ROUND_DOUBLE3) rounds a double to two decimals away from zero, floor(abs(x) * 100 + 0.5 + 1e-10) / 100 with the sign put back (the 0.50000001 of the older, commented version is not what runs). The POS has three ways to turn "an amount and a percentage" into an amount and only one is the plan of an installment payment (S3 QA fix pass; read-only on C:\Work\AI\pcpos\20261003\src\ALMACOR): (i) the payment-method promotion engine (TICKET::PromocionesMdeP_Consultar, pos_prom.cpp, called by pos_mppo.cpp:4193 with the installments the cashier picked; its sibling PromocionesMdeP finishes the sale, pos_prom.cpp:2343-2365 and 2492): ROUND_DOUBLE((ROUND_DOUBLE(base) * ROUND_DOUBLE(pct)) / 100), one rounding of the quotient, whose result is RES_ID_RECDESC and the recargo or descuento that is printed; (ii) RoundExp100 (pos_mis2.cpp:1287), round2(round2(x) / 100), two roundings, used for taxes, the change limits and the fixed surcharge of a payment method when promotions by method are off (CalculateRecDescMdeP, pos_mppo.cpp:264-299), not for a card plan; (iii) dM_TarPl.fRecDescMPP taken as an amount in pesos (pos_mis2.cpp:3857-3858), only for a pre-scanned card that the engine did not price (BASES.TXT documents the column as a percentage: D-S3-9 asks which one the real tables hold). The plans use (i): a plan of the gateway replaces the one the POS would have printed for the same card. adjustment = ROUND_DOUBLE((ROUND_DOUBLE(base) x ROUND_DOUBLE(pct)) / 100), with the percentage as it is written (12 for 12 %, -10 for a 10 % discount) and rounded to two decimals first (pos_prom.cpp:4417: 12.345 % is applied as 12.35 %, so 1000.00 gives 123.50 and not 123.45; PosRoundingTest.ac14_thePercentageIsRounded...), and with the final rounding skipped when the result is at most 0.0099999 (pos_prom.cpp:4683; what stays under a cent belongs to a total the sale rounds to cents, so half a cent or more still makes the cent here), computed in double with those same operations (PosRounding.adjustmentOf; a value enters as the nearest double to its decimal text, like the atof of the POS, and leaves at two decimals). Two cases tell the formulas apart and are pinned: 1000.11 at 4.5 % is 45.00 (45.00495 rounded once; the two-step RoundExp100 gives 45.01, which is what this section said before the fix pass), and an exact tie that the double lands just under, 173244.75 at 10 % (17324.475) and 71504.90 at 55 %, is 17324.47 and 39327.69 where exact half-up gives 17324.48 and 39327.70 (the 1e-10 of the guard is smaller than the spacing of the doubles at that size); PosRoundingTest.ac14_* and PlanFiguresTest.ac14_* pin them, GatewayConfiguredPlanSourceTest.ac14_modeB... pins the source, and PlanFiguresTest compares the whole DECIMAL(13,2) x DECIMAL(7,4) range with the POS formula. total = amount + adjustment, so importe + importe_recdesc == importe_final holds by construction (INV-04; the column check ck_payment_amounts repeats it). amount_per_installment = round2(total / quantity), exact quotient, half away from zero (not a POS function). The doubt: the POS is Borland C++ 3.1 on x87, whose intermediates may be wider than a double, so Java can still differ from the pinpad on some inputs; AC-14 stays unticked until the pinpad's cents are measured (D-S3-9). The remainder is not reconciled: 112000.00 in 6 installments is 6 x 18666.67 = 112000.02, the offer says total_amount 112000.00 and amount_per_installment 18666.67 and the notified amount is checked against the total (Prisma question 11 asks which of the two Prisma charges). The adjustment is always on the whole amount; a plan that leaves nothing to pay or whose installment rounds to zero is a configuration error.
  2. Which plans (AC-13). A plan applies to a card entry on a day when it is enabled, has the entry's payment method, and every condition it fixes holds: the bank, the BIN range (digit prefixes compared like the POS strncmp, BinMatcher: a bound longer than the BIN never matches, R-08), valid_from <= day <= valid_to (inclusive), a weekday of the mask (Monday 1 ... Sunday 64, empty means every day) and min_amount <= amount (inclusive). Plans of another branch are never used. For each number of installments the most specific wins, compared in this order: a plan of the branch before a plan of the merchant (a branch that has its own plan replaces what the merchant set for it, "reemplaza", docs/PLANES-CUOTAS.md section 2), and then BIN range (2) before bank (1) before payment method alone (0). The order of the two axes, branch first and card second, is a human decision (2026-10-04, D-S3-1 closed): the documents list them without saying which dominates, and the human confirmed that a branch plan beats a merchant plan before card specificity is compared. It is one Comparator in GatewayConfiguredPlanSource. A 1-installment plan that is a discount replaces the implicit one; one with a surcharge is refused, when the plan is read (InstallmentPlan) and again by CompleteOffer for any source (PLANES-CUOTAS D3: one payment without adjustment is always offered); without any, CompleteOffer adds the plan of the whole amount. Method 112 takes only plans of 1 installment with no bank and no BIN. The plans are offered in ascending installments.
  3. Ties and bad rows fail closed (AC-13). Two plans that tie for the same card, day and installments (same branch scope, same card specificity) are a configuration error: PlanConfigurationException, an OfferNotPossibleException, so the existing catch of BinsWorker ends the BINs row as NO_OFFER, nothing is sent to Prisma and the payment is handed over (the operator finds plans 41, 42 tie for 6 installments ... in compensation_task.last_error). The gateway never guesses which plan the merchant meant, and offering the other installments instead would hide the error. A tie under a more specific plan is shadowed and harmless. The console (S5) must refuse to save such plans; what it needs (the comparison) is InstallmentPlan.ofABranch()/cardSpecificity(). The same exception covers every row that cannot be offered as it is: a quantity above 99, bounds that are not 1 to 8 digits, a percentage of -100 or less, a surcharge without rates, rates on a plan without surcharge, a surcharge of 1 installment, a MiPyME code with the wrong installments: every check that needs one row only is made when the row is read, so a broken plan is caught even when a more specific one wins the selection. One bad row does not deny the merchant's sales (S3 final fix pass, D-S3-19): a row is skipped only when its card scope or its installment count cannot be read: a payment method, a bank, BIN bounds (a missing bound, more than 8 digits, out of order) or a quantity that is not 1 to 99; it cannot even say which cards it is for, so it cannot claim anything (WARN; PlanCatalogIT.ac13_aRowTheSchemaAccepts...). Any other fault keeps the row as not offerable (InstallmentPlan.offerable, WARN in JdbcPlanCatalog, once per row per five minutes so the log is not flooded): wrong rates (a surcharge without valid rates, rates on a plan without surcharge), a plan code that is blank or not for its installments, a negative minimum, a surcharge of 1 installment, a percentage that the POS rounding takes to -100 (PosRounding.roundedPercentage: -99.995 is applied as -100.00, so it is validated rounded), a window that ends before it starts or a weekday mask outside 1 to 127. The row still wins its installments for the cards it applies to and is simply not offered, so a more general plan cannot price a count the merchant priced otherwise (GatewayConfiguredPlanSourceTest.ac15_aPlanThatIsNotOffered..., PlanCatalogIT.ac15_aSurchargeWhoseRatesAreWrong..., PlanCatalogIT.ac13_aRowWithAReadableCard..., PlansE2EIT.ac13_aModeBRowWithAWrongPlanCode...). No surcharge is ever offered without valid rates.
  4. TNA and CFT (AC-15). The gateway does not compute them (PLANES-CUOTAS D7: they are the acquirer's or the bank's figures, a regulatory responsibility); it sends the plan's own and checks only their structure, when the plan is read: a plan with a surcharge (percentage above zero) needs both at least 0.01 as they are sent (two decimals, half up: a rate of 0.004 would reach Prisma as 0.00) and the total cost not below the nominal rate, compared as sent; any other plan (no interest, discount) has both at zero. That the rates are consistent with the adjustment and the installments is not checked, and AC-15 is open (D-S3-10): PLANES-CUOTAS section 8 shows the French system with 21 % VAT only as an illustration and gives no tolerance. They go as percentages with two decimals (40.05, half up from the four of the column): provisional, until Prisma answers question 8 (40.05 or 0.4005); the emulator and the snapshot keep the same numbers.
  5. Cuotas MiPyME (AC-16). plan_code 13 is 3 installments and 16 is 6 (MipymePlans, the seam for Prisma question 9: v27's installments[] has no field for the code). The code lives on the offered plan, in the complete snapshot (plan_code) and, on approval, on the payment (OfferCheck hands it over); nothing about it is sent to Prisma (an unknown field could make Prisma refuse the whole offer). A code with other installments, or another code, is refused. A regular plan and a MiPyME plan of the same installments tie unless one of them is more specific. AC-16 is open: the code never reaches the wire, so "offered with its plan code" is not proven until Prisma question 9 is answered (D-S3-11).
  6. The day is the shops' (AC-13). The server runs in UTC, where Tuesday 22:30 in Argentina is already Wednesday: the day a plan is valid on, and its weekday, are read in gateway.plans.zone (default America/Argentina/Buenos_Aires, MerchantPlanSourceTest.ac13_theDayOfAPlan...) at the instant the offer is built, the clock of the worker. The domain only gets the day, and the catalog reads only the plans that are valid that day (PlanCatalog.of(checkout, day)), so an expired row that is malformed cannot fail every offer (PlanCatalogIT.ac13_aPlanThatIsNotValidThatDay...). The zone is gateway.plans.zone (application.yml, RUNBOOK section 3).
  7. What is checked later. The complete snapshot stores the plans with their totals; OfferCheck (rule 12) validates the notified method, BIN, installments and total to the cent against them, so a surcharge or a discount that was offered is accepted and anything else is compensated (PlansE2EIT.ac03_aChargeOneCentAway...). The POS answer carries importe_recdesc signed (PosResponsesTest.ac03_*, PlansE2EIT.ac03_*).
  8. Not here. What a POS sends as promotions is section 9b and cashback section 9c; the console that refuses ties (AC-13, last clause) and the simulator are in section 12 (S5 batch 3); that Prisma accepts a total_amount different from original_amount is question 10, and until it answers surcharges and discounts must not be enabled in production (ADR-003).

9b. What a POS sends about plans is ignored (ADR-003, AC-18)

Mode A, in which the POS sent its promotions (promos, base_amount) in each trxpago, was removed by human decision on 2026-10-28: less attack surface (no untrusted promotion input), one plan path to maintain and test, and no dependency on a POS release for promotions. The code is recoverable from the tag mode-a-reference. These are the rules that remain.

  1. The plans are the gateway's. They come only from installment_plan, per merchant and branch, through MerchantPlanSource.forPayment (section 9a). merchant has no plan-source column and the console has no such setting.
  2. promos and base_amount are not read. PosRequestNormalizer does not look at them, in the POS-native shape or in the RouterQR shape, so whatever they hold (an array of garbage, a negative or hostile base_amount, a text where a number was expected) cannot refuse the sale with a 400 and costs nothing. They are not stored (payment has no such columns), so a retry of trxpago with other promotions is not a conflict (AC-04 compares the amount and the cashback only). No log line is needed; DEBUG at most (PosRequestNormalizerTest.ac18_*, PosApiIT.ac18_*, PlansE2EIT.ac18_*).
  3. A merchant with no plans offers the single payment. CompleteOffer always adds the 1-installment plan of the whole amount and method 112 (rule 9 of section 9, AC-08).
  4. Rates stay with the plan. A surcharge plan carries its own TNA and CFT (section 9a, rule 4); the gateway never computes them.

9c. Cashback (S3 batch 2, AC-17, v27 pp. 8 and 97)

Cashback is the cash a customer withdraws at the checkout together with the payment. v27 says very little (CONVENTIONS section 8 has the create call, cashback_max_amount and absolute_cashback), so everything below is the safe reading, behind domain.Cashback, with the open points in docs/PRISMA-PREGUNTAS.md 21 and 22 and in D-S3-15.

  1. What v27 gives. Cashback exists only with Visa Debito (method 31). The intention carries a maximum and absolute_cashback; the wallet user chooses "1- no retirar" or "2- retirar un monto menor o igual a este", and with absolute_cashback = true a user who withdraws must withdraw exactly the maximum. The notification carries cashback_amount (the actual withdrawal). A forced annulment returns the cashback too (v0.14), a forced refund does not (R-10). The complete intention (v3.4) has no cashback field: nothing about it can be sent per method, so "offering cashback only with Visa Debito in 1 payment" is enforced on what comes back, not on what is sent.
  2. What is sent. original_amount is the sale (totalitem), never plus or minus the cashback; a cashback above zero goes as cashback_max_amount with absolute_cashback = true (gateway.prisma.absolute-cashback, default true), so the customer takes the exact cash the POS has printed or none. The setting is honored on both sides (decision of the S3 QA fix pass, D-S3-15 (e)): with false it is sent as false and Cashback.check accepts any withdrawal above zero up to what was asked for, kept and answered as what was withdrawn (totalcashback, which the POS reads from the answer and hands out), never above the maximum (CashbackRelaxedE2EIT); the alternative, removing the setting, would have left a setting that only changes what Prisma allows while the gateway still compensated every partial withdrawal. The plans of the complete intention are computed on the sale only: the adjustment never applies to the cashback (a surcharge of 12 % is 12 % of the sale, PlansE2EIT.ac17_theAdjustmentNeverApplies...; the cash is in its own field, never in importe, importe_recdesc or importe_final).
  3. What is checked (AC-17, Cashback.check, in PurchaseResults, the one place the notification and the status query share). With requested = the totalcashback of the POS and notified = the cashback_amount of the wallet: | notified | method and installments | requested | result | |---|---|---|---| | absent, JSON null or 0 | any | any | honored, nothing withdrawn: the sale stands, the POS is told zero cash | | equal to requested, to the cent | Visa Debito (31), 1 payment | above 0 | honored, kept as cashback_paid | | up to requested and above 0, only with gateway.prisma.absolute-cashback=false | Visa Debito (31), 1 payment | above 0 | honored, cashback_paid is what was withdrawn | | present but not a number (text such as "5000,00", a boolean, an object, an empty text) | any | any | not honored: it is a withdrawal the gateway cannot read, never "nothing" | | a number that cannot be held (finer than a cent, above 99,999,999,999.99), negative | any | any | not honored | | anything else (another method, installments, a smaller (with true) or larger amount, an amount never asked for) | | | not honored | A result that is not honored is applied without amounts, so it can never approve, and the payment goes to compensation with its facts (the wallet's cashback_amount is kept in cashback_paid for the annulment, which returns it when it can be held as an amount; a value that is not a number or cannot be held is recorded as no amount, so the annulment is the forced one and the cause says why): the customer is never left with cash taken out that no sale accounts for. The three states are carried, not collapsed (Cashback.Reported: absent, stated as written, unreadable; the decoder tells "no cashback_amount" from "a cashback_amount that is not a number"), so a malformed field can never fail open as "nothing withdrawn" (JacksonPaymentNotificationDecoderTest.ac17_*, CashbackTest.ac17_*, PaymentNotificationWorkerTest.ac17_aCashbackThatCannotBeHeld..., PlansE2EIT.ac17_aCashbackFinerThanACent..., ...AboveTheMaximum..., ...IsNotANumber..., ...OfTheWrongType...). The inbox row says CASHBACK_NOT_OFFERED and compensation_task.last_error says why (no amount in it). A total that is not the offered one, or a plan never offered, is reported as such first (AMOUNT_MISMATCH, UNOFFERED_PLAN): the cashback is judged only for a charge that matched the offer.
  4. What the POS is told. The POS reads totalcashback from the answer (pos_ctoq.cpp, GetValue("totalcashback"), and pos_mppo.cpp hands out that cash and adds it to its total), so the answer of a paid sale that asked for cashback carries totalcashback: what the customer withdrew, which is zero when the customer declined it (the cashier hands out none, whatever the ticket printed). A sale that asked for none answers exactly as before, without the field, and a denied or compensated payment never carries it. importe_final never includes it. GET /api/trxes/{id} says the same (PosResponses.payment, one builder).
  5. Assumptions that fail closed (Prisma questions 21 and 22). The notified amount is the total of the plan without the cashback: if Prisma adds the cash to it every payment with cashback is a mismatch and is compensated, never approved at a wrong amount (D-S3-15 names the one place to change, PurchaseResults.approved). A wallet that reports cashback_amount without payment_method_type, or on a method that is not 31, is compensated.
  6. Not built. A per-merchant switch for cashback (a POS that sends totalcashback above zero gets it asked of Prisma whatever the merchant accepts, and a merchant that does not accept Visa Debito simply never sees it honored); a restriction of the offer to Visa Debito when cash is asked (v27 gives no way to say so and omitting cards is Prisma question 13).

10. The emulator

prisma-emulator is a Spring Boot application that plays Prisma's Gateway QR v27 and its wallet (D-02, AC-30).

  • Prisma side: POST /largeaccounts/intentions (every v27 rule: mandatory fields, bins_max_quantity = 99, 201 with intention_id and qr_raw, the 400 invalid_request_error / 403 shapes), PUT /largeaccounts/intentions/complete (204; 404 unless the intention is created, the wallet sent its BINs and the 27 s have not passed; method 112 and the 1-installment plan are required), DELETE /intentions/{id}, GET /payments/qr, /annulments, /refunds, POST /forcedannulments, /forcedrefunds. The apikey header is checked with a 403. Where v27 is silent (emulator.*): a complete intention before the BINs or after the deadline is a 404 (require-bins, complete-deadline), a second complete intention is a 404 (allow-second-complete), a cancel after the payment is a 404, a second forced operation for the same payment is a 400 invalid_param on intention_id.
  • Wallet side: POST /emulator/scenarios scans the latest intention of a checkout, calls the gateway's BINs callback, waits for the complete intention and chooses a plan (waitForComplete, on by default since the gateway sends the complete intention from S2b on; false pays at once), pays and sends the notification to the gateway callbacks with the apikey the gateway issued (PUT /emulator/gateway or emulator.*). Outcomes: APPROVED, REJECTED, MISSING_BINS, MISSING_NOTIFICATION (the gateway must ask GET /payments/qr), DUPLICATE_NOTIFICATION, LATE_NOTIFICATION, LATE_PAYMENT_AFTER_CANCEL, and the two wallets that do not charge what was offered (D-57): APPROVED_AMOUNT_MISMATCH (the plan it chose, one cent above that plan's total) and APPROVED_UNOFFERED_PLAN (the total of the 1-installment plan, in one installment more than the largest plan offered); a forced annulment or refund is finished by the emulator after emulator.reversal-delay and notified (POST /emulator/reversals/{intention}/{kind} finishes it by hand, also rejected). Fidelity rules (EmulatorFidelityTest):
  • the BINs are marked as forwarded before the gateway is called (a gateway that answers the BINs with the complete intention at once must find the intention ready), and the mark is rolled back when the callback fails or is refused;
  • a wallet does not pay a cancelled or superseded intention (nor one that was paid): the scenario fails with "the intention is CANCELLED: the wallet cannot pay it" and EmulatorState.pay refuses too. The one way to get that payment is the explicit LATE_PAYMENT_AFTER_CANCEL scenario, the late charge that INV-01 compensates (the intention then ends APPROVED, so a forced annulment works);
  • GET /payments/qr reports annulled or refunded once a reversal finished (and still approved while it is in progress or after it was rejected); a notification always says how the payment itself ended.
  • IntentionRecord.completeReceivedAt() is the moment the complete intention arrived (and binsForwardedAt() the one the wallet forwarded its BINs): a test measures the delay without sleeping (CompleteIntentionIT.ac07_*).
  • Failure injection: POST /emulator/faults (per operation, a count): STATUS (5xx, with executeAnyway the intention is created and only the answer is lost: the unknown outcome of ADR-002), CONFLICT (409), DELAY, TIMEOUT, GARBAGE_ID, and three transport faults that run the operation first: STALL_AFTER_HEADERS (status and headers at once, the body after delayMillis: what a header-only timeout never notices), RESET_AFTER_REQUEST (a body announced and cut after a few bytes with Connection: close: a servlet cannot send a TCP reset, this is the closest thing) and HUGE_BODY (a valid 2 MiB JSON answer).
  • Strict modes (off by default, emulator.*, each a test switch because v27 is silent): reject-duplicate-integrator-id (a repeated integrator_intention_id is a 422 duplicate on that field, which the gateway must read as a possible duplicate, Unknown), alphanumeric-codes-only (branch and checkout may hold only letters and digits; the integration data of the gateway tests has hyphens, so it stays off there) and dashed-cuit-only (the CUIT must be XX-XXXXXXXX-X). EmulatorStrictModesTest.
  • Packaging. The plain jar is a library; -exec is the runnable fat jar. A standalone emulator listens on the loopback (server.address=127.0.0.1, applied by startStandalone, which main uses; an explicit --server.address wins): its control API has no apikey, so it must not be offered on every interface of a shared machine. In-process it keeps its own binding rules (start). The emulator has no application.yml (every default is in EmulatorProperties), so started inside another application it never reads that application's configuration; PrismaEmulatorApplication.start(...) excludes the persistence auto-configurations by name for the same reason. The gateway tests depend on the plain jar (test scope) and start it in the same JVM on a random port (InProcessEmulator.plain(), and .tls() with a certificate generated for the run by SelfSignedKeystore: keytool, in a temporary directory, never committed); no second process, no fixed port. The end-to-end tests of S2b use the same handles (state(), faults(), wallet()).
  • HTTPS. --server.ssl.* serves HTTPS; a client that does not trust the certificate is refused. The emulated wallet reaches the gateway callbacks over plain HTTP in tests (the TLS of the callbacks listener is proven by CallbacksTlsIT).

11. The compensation job, the per-charge reversal and the reconciliations (S4)

  1. A reversal belongs to a charge, not to a payment (ADR-002 amended, D-79). wallet_charge has one row per wallet charge of an intention (uq_wallet_charge (intention_id, prisma_payment_id); the Prisma payment id repeats between intentions, D-56). The charge that moved the payment to APPROVED is the sale (sale = 1, one per payment); every other charge is annulled. reversal has one row per attempt to give money back for a charge: at most one active (REQUESTED, IN_PROGRESS) and at most one that returns money (ANNULMENT or REFUND not failed) per charge, both by filtered unique indexes, so the money of a charge goes back at most once (CompensationPersistenceIT). WalletResults is the only writer of charges (ArchUnit): an approval records the sale (ChargeLedger.recordSale), a late or unoffered charge is handed over and recorded for reversal, a second charge only recorded for reversal. A no-sale payment annuls every charge, a sale annuls only the others.
  2. v27 addresses a forced annulment or refund by the charge, not by Prisma's payment id (intention_id, payment_method_id, establishment_id, trace_number, ticket_number, plus cuit and terminal_number): that is why the numbers of the complete intention are stored in wallet_charge; the cuit is the one the intention was created with (intention.merchant_cuit, written when the intention is opened), never the merchant's current one, so a rename in the console after the sale (D-126, D-130) does not change how its reversal is addressed; a charge whose numbers are unknown cannot be named (ForcedReversalBody, PrismaCompensationEmulatorTest, docs/PRISMA-PREGUNTAS.md section D). GET /annulments|/refunds ?intention_id= take no payment id either: with several charges the answer is ambiguous, so the job asks once per reversal and trusts the notification (per intention and type) for the result. No idempotency is documented for the forced requests: the job never sends one again once it may have reached Prisma without asking first (ac22_beforeSendingAForcedOperationAgainItsStatusIsQueriedFirst).
  3. The leased queue (D-05). CompensationQueue.claimNext is one statement, UPDATE ... OUTPUT with UPDLOCK, READPAST, in database time (SYSUTCDATETIME): a task is due when PENDING with next_attempt_at <= now, or IN_PROGRESS with lease_until < now (a dead worker). A claim counts one attempt and sets lease_owner (a name per claim, ClaimOwners) and lease_until. Every settlement is guarded by the owner: a worker whose lease ran out and was taken over gets LeaseLostException, which rolls the whole settlement back (ac19_aLeaseLostAtTheEndUndoesTheSettlementOfThePayment). The lease must cover two bounded calls plus a margin (TimingGuard, RUNBOOK section 3).
  4. The job (CompensationJob.processNext). No transaction is open across a call to Prisma and every call goes through the bounded PrismaHttp and is wire-logged outside any transaction (ac22_everyCallOfAReversalIsMadeOutsideATransaction, ac19_inv02_theCancelIsNeverMadeInsideATransaction). Cancel task: DELETE /intentions/{id}; 204 and "not found" end it, but a 404 on an intention that may have been paid is not a conclusion: the job re-reads the purchase (PurchaseCheck, GET /payments/qr) and, if it was paid, hands the charge over to a reversal. Before closing a task the job re-reads the intention's Prisma id (D-56): an id that arrived after the hand-over is cancelled too, never lost. Reverse task: ask Prisma first, send the forced annulment only if it knows none, then poll its result every poll-delay (the notification is the faster way). A real refusal of the annulment schedules a forced refund as its own reversal and task; a refused refund or an exhausted retry ends in COMPENSATION_FAILED with the alert. A payment is COMPENSATED when its last task is done, COMPENSATION_FAILED if any gave up, and stays COMPENSATION_PENDING while another task of it works (ReversalSettlement).
  5. Late results (D-29). A result for a reversal the gateway had given up on is applied as COMPLETED_LATE, or LATE_AFTER_REFUND when another reversal already returned that charge's money (alert REVERSAL_LATE_AFTER_REFUND). A notification that matches no reversal of the intention is REVERSAL_UNKNOWN (alert). ReversalNotificationWorker and the job share ReversalSettlement, so the effect is the same whoever sees the result first.
  6. Retries. CompensationPolicy (domain, no clock): max-attempts, exponential backoff from initial-backoff to max-backoff, and a fixed poll-delay for a request Prisma accepted. A failed try keeps only the class of the failure, cut to the column (INV-07).
  7. The orphan-wait reaper (D-81). OrphanWaitReaper.sweep takes payments waiting for the wallet whose wait_deadline_at is older than reaper-grace (ix_payment_waiting_deadline) and hands each over through the same CompensationHandOff. The grace is at least the hand-over budget plus the safety margin, so it never races the node that holds the wait (TimingGuard). Idempotent across sweeps and nodes (OrphanWaitReaperTest, CompensationFlowIT.d81_*).
  8. The reconciliation of the unpersisted denial (INV-02, D-105) and the last answer the POS heard (INV-01). When the wait answers the POS "no sale" without having persisted the hand-over, PaymentWait first notes the payment id in a local durable file (UnpersistedDenials, FileUnpersistedDenials: SYNC append, only the id and the moment): the database is what is down, so the marker cannot live in it; one file per node. UnpersistedDenialReconciler runs in the sweep: a payment that waits is handed over; a final or already compensating one is only settled; an APPROVED one is handled by the next rule; a marker that cannot be decided stays for the next sweep. "No sale" means the last answer the POS heard. A payment the POS heard as approved (trxpago or consulta; a direct-VPN POS keeps polling the consulta after a trxpago denial and closes "APROBADA via CONSULTA") is a sale and is never compensated as a no-sale. Two records say it: payment.pos_approval_intent_at (written by PosApprovalGuard before an approved answer leaves) and payment.pos_told_approved_at (written by PosApprovalMarkerFilter after it left). They are written by the POS answer path, never by the compensation, which only reads them through the same port that writes them (PosApprovals.wasToldApproved, PosApprovals.approvalWasIntended; one port, D-S4-12; V1 declares the columns once, an unmapped plain column). The reconciliation skips a payment whose told marker is set, never annuls one whose intent is set without the told marker (the answer may have left: INV02_RECONCILIATION asks a person to check the POS journal), and annuls an alerted APPROVED payment with BOTH empty only after wait_deadline_at + pos-polling-window (d105_* and qa5_* tests, CompensationFlowIT). The other direction (D-S4-10): the reconciliation or the cashier may schedule the annulment of the sale between the moment the consulta read the payment and the moment its approved answer is built, so PosApprovals.recordApprovalIntent takes the lock of the payment row (the first lock of the order payment, reversal, task), reads the reversal of the sale's charge and refuses (false, nothing written) while it is in flight or done, or while the job gave up on it (D-134: Prisma may still complete it and a late result annuls the payment) and no intent is recorded yet (an intent already recorded stands: that reversal can only be the cashier's): PosApprovalGuard then answers the annulment view of the consulta (D-118), untagged, with one WARN line POS_APPROVAL_WITHHELD payment=<id> path=<trxpago|consulta>, and a view that is approved again (the annulment failed meanwhile) is deferred like an approval that cannot be recorded (ApprovalVersusReconciliationRaceIT, PosApprovalGuardTest.dS410_*, CompensationPersistenceIT.dS410_*). A payment named in a POS_APPROVAL_UNRECORDED payment=<id> log line (the answer path could not record the told marker) has its intent set, so it is not annulled by code either; the operator may fill the marker by hand (RUNBOOK section 3).
  9. Emulator (v27, test-first). prisma-emulator plays DELETE /intentions/{id}, POST /forcedannulments|/forcedrefunds (addressed by the charge's numbers), GET /annulments|/refunds, per-charge reversals in EmulatorState, a second charge of an intention (Outcome.DOUBLE_CHARGE) and fault injection per operation. CompensationFlowIT runs the job, a second GatewayNode, the reaper and the reconciliation against it end to end.
  10. trxanulacion (AC-23, AC-24, AC-31; D-19, D-118). AnnulPaymentService, one transaction per call, idempotent per payment: the POS, RouterQR's sweeper (every 5 s until a 2xx) and the job converge on one reversal per charge (the service decides by ChargeLedger.saleReversal, and the filtered unique indexes of reversal refuse a second active or money-returning one whatever races). The payment row is locked first (CompensationQueue.lockPayment, the order of the reconciler, the job and the notification worker: payment, then reversal, then task), so callers that overlap take turns and the later ones read the reversal the first committed; if reverseSale is refused anyway (a writer outside the lock), the service reads the reversal once more and answers from it, never with a refusal for an annulment that is owed. Without that, the loser of a POS + sweeper (or POS + reconciliation) race got a 409 and a false ANNULMENT_NOT_POSSIBLE while the winner's reversal refunded the customer, and the DOS POS keeps the sale on a non-2xx (D-S4-10, AnnulmentRaceIT). The payment to annul is trxidoriginal if positive, otherwise id (PosRequestNormalizer.annulment); the label of who asked is ReversalTrigger.ROUTER for a positive trxidoriginal and POS for 0, and only labels the reversal (the first caller's label stays). The answer is AUTORIZACION_DE_ANULACION_APROBADA only when the annulment is durably owed, written in the same transaction that decides it (INV-02), and it is the only estado of the endpoint (the Almacor POS takes REFUND_APROBADO and this one; a statuscode 0, mensajevarios says which case, at most 79 bytes). By state: APPROVED schedules the annulment of the sale's charge once (ChargeLedger.reverseSale: reversal REQUESTED and its REVERSE_CHARGE task) and a repeat finds it in flight; a waiting payment (INTENT_SENDING .. COMPLETE_SENT) takes the compensation path through CompensationHandOff.handOver (AC-31: payment COMPENSATION_PENDING "Cancelled by the cashier", intention CANCELLED, CANCEL_INTENTION task; the open trxpago ends as that denial; an approval that arrives afterwards is COMPENSATEd); ID_ISSUED becomes CANCELLED (Payment.cancelUnstarted; a later trxpago is denied); ANNULLED/REFUNDED and every state that was never a sale are answered "annulled" / "no sale to annul" and write nothing (the sweeper sends it for those too). What is never answered with the estado is an annulment the gateway cannot stand behind: a sale with no recorded charge, or whose annulment failed for good, or whose reversal the job gave up on without learning what Prisma did (the first may still be at Prisma, so no second is scheduled), is a 409 (AnnulmentNotPossibleException) and an ANNULMENT_NOT_POSSIBLE line (RUNBOOK section 9); an id the gateway never issued is a 404. Every answer, errors included, has a Content-Length and Connection: close; the only 500 is the unexpected-exception catch-all of S1, which is not an acceptance either.
  11. The consulta never calls an annulment owed an approval (D-118). PaymentStatusService.statusOf shows an APPROVED payment whose sale reversal is in flight or done as ANNULLED (Payment.restore(...).annul(...): the same payment through its own transition, so the result of the sale stays intact), read in the consulta's read-only transaction. Why: the DOS POS reads AUTORIZACION_DE_PAGO_APROBADA on the consulta as a sale, and after a trxanulacion that timed out it reads an approved estado as "annulled by consulta"; a payment we are annulling must therefore never answer it. The stored payment stays APPROVED until Prisma completes the annulment (ReversalNotificationWorker, the job), and a failed annulment is still shown APPROVED because the money is still charged. A retry of trxpago for the same payment gets the same view (PaymentStatusService.asThePosMustSeeIt, shared by the consulta and StartPaymentService.resumedStatus, D-S4-7). A reversal the job gave up on reads as FAILED. After the poll deadline the job fails the task (COMPENSATION_FAILED, alert) but leaves a sent reversal IN_PROGRESS on purpose (Prisma may still hold the request and a late result completes it; nothing is ever sent again), so saleReversal treats an active reversal whose tasks are all over with one COMPENSATION_FAILED as FAILED: trxanulacion is a 409, the consulta shows the sale, and a person finishes it at Prisma (RUNBOOK section 9, D-S4-8). No new ReversalState was added: the derived read changes no stored fact.
  12. Supersede (AC-32, INV-01). StartPaymentService.supersedeThePendingPaymentOfTheCheckout, in the transaction that opens the new payment (beginAuthorization): the checkout's one live intention (findLiveByCheckoutId, ux_intention_one_live_per_checkout) belongs to a payment that still waits for the wallet, and that payment is superseded and handed over (handOverSuperseded: COMPENSATION_PENDING "Superseded by a newer payment", intention SUPERSEDED, CANCEL_INTENTION task) before the new intention is stored. A payment the POS was told approved is never superseded: its intention left the live set when the approval was applied, so it has no live intention to find, and the new payment starts beside the sale. A wallet that pays the superseded QR afterwards is a late result: recorded, compensated (REVERSE_CHARGE) and never approved. Two payments that start together on one checkout meet in the optimistic lock or the unique index and one is retried. A payment whose trxpago never came (ID_ISSUED) has no intention and is not touched.
  13. Production settings (RUNBOOK section 3). TimingGuard refuses a start outside local/test unless gateway.compensation.denial-marker-file is an absolute path, gateway.compensation.pos-polling-window is at least twice gateway.pos.wait.caller-read-timeout (the consulta loop of the POS) and gateway.compensation.lease outlasts two calls to Prisma; every problem is reported at once.
  14. What the gateway cannot fix for a POS that goes direct (D-S4-11, needs human acceptance). A trxanulacion that never committed (the node crashed, or the connection dropped before the commit, so no reversal exists) leaves the payment APPROVED with nothing owed. RouterQR's sweeper repeats the request until a 2xx and heals it. The DOS POS without RouterQR does not: after a trxanulacion that timed out it asks the consulta, which answers the approved estado (nothing is owed, so item 11 does not apply), and the POS reads it as 'annulled by consulta' (pos_ctoq.cpp 3820-3846) while the customer stays charged. The gateway cannot tell it from a sale nobody annulled; the supported topology has RouterQR in front of every POS (RUNBOOK section 9 says how an operator finds the case).
  15. Not here yet: see ISSUES-DEFERRED (D-S4-n rows) for what batch 2 left open, including what the merge with main must do about the approval marker (D-S4-10 and D-S4-12).

12. The admin console (S5)

The console is a React single-page app (console/) plus the admin API (/admin/api/v1), both served by a third connector of the gateway. Decisions below are the agent's unless a line says the human confirmed them.

Listeners and where each thing lives

Listener Serves only Bound to Configured by
POS /api/** the VPN-side IP (gateway.listeners.pos.*) ADR-004
Prisma callbacks (primary) <callbacks path-prefix>/** server.address / server.port, HTTPS ADR-004
Admin /admin/**: the console's files and /admin/api/v1/** loopback by default (gateway.admin.address, an IP literal), gateway.admin.port (8091) config/AdminProperties, config/AdminListener
  • config/ListenerSeparationFilter routes by the local port: the admin port serves only /admin/, the POS port only /api/, the callbacks port only its prefix; everything else is a 404 before any handler. Both the raw and the container-normalized path are checked, so no .., %2e, ; or // trick crosses over (AdminListenerSeparationIT, ListenerSeparationFilterTest). The callbacks prefix may not be /admin (PosListener, PosListenerTest).
  • Fail closed at startup (AdminListener, AdminListenerTest, StartupRefusalIT.s5_*): the address must be an IP literal and not a wildcard; a non-loopback address is refused unless gateway.admin.allow-remote=true AND gateway.admin.ssl-bundle names a Spring SSL bundle (HTTPS on the admin connector; plain HTTP is never offered off loopback, AdminTlsIT). Whoever may reach the connector still has to log in. AdminRemoteAddressFilter is a second lock: while allow-remote is off, a request whose TCP source is not loopback is a 403. It checks the TCP source only: a reverse proxy on the same host connects from loopback and passes it, so do not front the admin connector with one unless allow-remote and ssl-bundle are set and the login is what protects it (D-S5-8).
  • Spring Security protects /admin/** only. Its servlet filter is registered for /admin/* (AdminSecurityConfiguration; Boot's own registration for every path is excluded in application.yml), so the POS API and the callbacks never pass through its firewall, which refuses paths a callback must always be accepted on (INV-03). The default "generated user" is excluded too, and so is Spring Security in the in-process Prisma emulator (PrismaEmulatorApplication), which shares the test classpath. Boot ignores an exclusion by a name that does not exist, so AutoConfigurationExcludesTest loads every excluded name (the gateway's and the emulator's) and requires an @AutoConfiguration class; it caught JpaRepositoriesAutoConfiguration, which is DataJpaRepositoriesAutoConfiguration in Boot 4. SecurityScopeIT proves a callback path and a POS path (even with a path parameter, which the firewall refuses) are served and never touched by the security chain. ArchitectureGateTest.s5_*: the application layer knows no web framework, and an inbound adapter never touches storage or the record that carries a password hash.
  • The built console is served from a directory (gateway.admin.console-dir, default ./console/dist; the Windows service points it at the deployed copy): the simplest thing that keeps Node out of the Maven build and the jar. A missing directory only means "the console is not installed" (a 404 with a message); the API still works. Client-side routes fall back to index.html; an unknown /admin/api/** path is a 404 JSON, never the page. The files are public (the login page must load); every call they make needs the session. Headers: no caching, X-Content-Type-Options, no framing, Content-Security-Policy: default-src 'self' (the console uses no inline script or style, no CDN, no web fonts). The directory must be dedicated to the build: startup is refused when it, or anything up to six levels below, is a config directory, an application*.yml/.yaml/.properties, a jar, a key or keystore or a .env file (the files are public, so the repository root would publish the database password), and only html js mjs css svg png jpg jpeg gif webp ico woff woff2 ttf are served (no source maps, no JSON, no text), never through a link out of the directory (ConsoleControllerTest).

Authentication: own users in the database (human decision, 2026-10-04)

All of it sits behind one seam, application.admin.AdminAuthentication (login, lockout, password change, "is this open session still valid"); the web adapter only turns its answer into a session. Nothing is decided by the adapter.

  • Users live in admin_user (V1): username (unique, case-insensitive, 3 to 50 of [A-Za-z0-9._-]), a hash (never the password; never logged, returned or audited), role, enabled, failed_attempts, locked_until, last_login_at. There is no default user and no default password: until the first ADMIN exists nobody can log in (the console is closed, not open).
  • Hash: Spring Security DelegatingPasswordEncoder, BCrypt (gateway.admin.password-hash-cost, 12 by default, 4 to 16). A hash is stored as {bcrypt}$2a$..., so the algorithm can rotate without a migration: register another encoder id in DelegatingPasswordHasher, make it the id to encode with, and each user is rehashed at their next login (a raised cost does the same; DelegatingPasswordHasherTest). Argon2id needs the BouncyCastle library, which is not a dependency yet (D-S5-4).
  • Password policy: at least 12 characters, at most 72 bytes (BCrypt reads no more), not blank, not the username (PasswordPolicy). Users change their own password (the current one is asked again); an ADMIN resets anyone's.
  • One error for everything: an unknown user, a wrong password, a disabled user and a locked one are the same 401 with the same text, and all cost one hash verification (a dummy hash for an unknown user), outside any transaction (AdminAuthenticationTest).
  • Lockout: after gateway.admin.max-failed-attempts (5) wrong passwords in a row the user is locked for gateway.admin.lockout (15 min). The attempt is taken before the password is checked, in one SQL statement judged by database time (no node's clock decides): it succeeds only for an enabled user who is not locked, counts the attempt and sets the lock when the count reaches the limit. So parallel guesses cannot evaluate more than the limit's worth of passwords per lock, whatever they read first, and a login that was being checked when the lock was set cannot undo it: its success is honoured only by a statement that finds the user enabled and not locked by somebody else's attempt (AdminLoginRaceIT, AdminPersistenceIT.s5_*, AdminAuthenticationTest). The count restarts when the lock is set; an attempt of a locked or disabled user is neither counted nor audited (a known name cannot flood the audit); a success or an ADMIN's password reset clears it (AdminApiIT.s5_afterThreeWrongPasswords*).
  • Hashing is bounded: at most gateway.admin.max-concurrent-logins (4) passwords are hashed at the same moment in all; a login that cannot get a place within a second is a 503 with Retry-After (not a 401: it says nothing about the credentials). The admin connector shares the CPU and the connection pool with the payment path, so a flood of logins cannot starve it (AdminAuthenticationTest.s5_whenAllThePlaces*).
  • Session: a JSON POST /auth/login opens an HTTP session; the cookie GPQR_ADMIN_SESSION is HttpOnly, SameSite=Strict, Path=/admin, and Secure whenever the request came over HTTPS; idle timeout gateway.admin.session-timeout (30 min); the session id changes at login and at a password change. POST /auth/logout ends it. AdminSessionFilter re-reads the user on every request: a disabled user is signed out at their next click and a changed role applies at once (a lock does not end a session).
  • CSRF: every state-changing request, the login and the logout included, needs the X-XSRF-TOKEN header equal to the XSRF-TOKEN cookie (SameSite=Strict, readable by the console's script, Secure on HTTPS). The console's first call (GET /auth/session) gets the cookie (AdminApiIT.s5_aStateChangingRequestWithoutTheCsrfHeader*).
  • First ADMIN: the one-shot command of docs/RUNBOOK.md section 12 (gateway.admin.bootstrap.username, the password from the process's environment variable GPQR_ADMIN_BOOTSTRAP_PASSWORD (never a -D system property or a file) or a prompt, never a flag). It creates one ADMIN and ends the process, and refuses while an enabled ADMIN exists (one INSERT ... WHERE NOT EXISTS with lock hints, so two runs at once create one). Likewise "at least one enabled ADMIN stays": the count is read with locks held until the transaction ends, so two ADMINs who disable each other at once cannot both pass it. Tested: AdminBootstrapTest, AdminBootstrapRunnerTest, AdminBootstrapIT, AdminUsersRaceIT.

Roles (origin: agent, confirmed: 2026-10-04)

Role May
ADMIN everything: the configuration (merchants, branches, checkouts, terminals, establishments, accepted methods), the plans (create, edit, disable, delete) and the plan simulator, the users, the payment search and trail, the dashboard, the audit and (on a developer machine) the emulator catalog
OPERATOR read-only: the payment search and trail (GET /payments, /payments/lookups, /payments/{id}), the dashboard (GET /dashboard: counts, no payment data), the plans (GET /plans, /plans/{id}, /plans/scopes) and the plan simulator (GET /plan-simulation), and their own session and password

Enforced on the server for every endpoint, whatever the console shows (AdminSecurityConfiguration, rules by role and method; AdminControllersTest walks every handler mapping and checks anonymous, OPERATOR and ADMIN, so a new endpoint cannot be forgotten; AdminApiIT.s5_anOperator*). An OPERATOR cannot read the configuration: GET /payments/lookups and GET /plans/scopes are the endpoints that list merchants, branches and checkouts, and only their names, numbers and (for the scopes) the source of the plans, so that the search filters and the plan screens can be filled. The console hides what a role cannot use (no "Nuevo plan", "Editar" or "Deshabilitar" for an OPERATOR) but never relies on it: the server answers 403 to every plan write of an OPERATOR (AdminControllersTest matrix, PlanAdminApiIT.ac29_anOperatorReads*).

The admin API

  • Plain JDBC behind application ports (ConfigurationStore, AdminUsers, PaymentQueries): no JPA entity (INV-09), and the answers are explicit records. Paging is ?page=0&size=20 (size 1 to 100) and answers {items, page, size, total}. A PUT replaces: it must say enabled (a 400 naming the field otherwise), so an omission never re-enables what was disabled; a POST that omits it creates an enabled entity. The payment trail's two long lists (notifications and wire log) hold the newest 500 rows, oldest of those first, and truncated names the list that had more (AdminPersistenceIT.ac29_aLongTrail*); the console says so. The trail also lists the payment's wallet charges (S4: wallet_charge, the unit a reversal returns, with the one the POS saw approved marked sale), each reversal with the charge it returns and when it was sent and accepted, and each compensation task with its kind and the reversal it works (AdminPersistenceIT.ac29_theTrailHoldsEveryThing*).
  • 400 vs 409: a value that breaks a rule the database would also enforce (a CUIT that is not 11 digits, a terminal number that is not 8 letters or digits, a bad plan source, a missing field) is a 400 naming the field ({status, message, field}); a duplicate (a CUIT, a branch number, a terminal number, a second terminal for a checkout) or a delete that something still depends on is a 409 naming what clashed, never echoing the value. Messages are the Spanish text the console shows. Uniqueness is the database's to judge (race-free): the store maps the name of the constraint to the message.
  • Delete is delete only when nothing points at it: a merchant, branch or checkout with children, payments or snapshots, and a terminal with numbered offers (INV-05), answer 409 ("deshabilítelo en su lugar"): they are disabled (enabled=false). Establishments and accepted methods are deleted for real.
  • Every write is audited in the same transaction as the write (admin_audit: actor, action, entity, before and after as JSON, database time). The audit holds the fields the console manages, never a password, hash or apikey; a failed write leaves no audit; logins (LOGIN, LOGIN_FAILED, LOGIN_LOCKED), password changes and resets and the bootstrap are audited too. The terminal's trace and ticket counters are read-only in the console (INV-05).
  • A terminal is renamed or deleted only while it never numbered an offer (both sequences 0 and no complete_snapshot_method row, judged in the same SQL statement as the write; otherwise 409): Prisma has seen the number of any other, and a terminal created with it would send (number, trace 1, ticket 1) a second time (AdminPersistenceIT.inv05_*). The console offers neither button for it.
  • The plans and the plan simulator are the next section.

The plans and the plan simulator (S5 batch 3, AC-29, AC-13)

PlansController over PlanAdminService (writes, audit), PlanSimulator (the simulator) and the port PlanAdminStore (JdbcPlanAdminStore, plain JDBC over installment_plan). Both roles read, only an ADMIN writes.

Call Who What
GET /plans?merchantId&branchId&enabled&page&size both a page of plans, newest first, each with its merchant and branch names and weekdays as ISO days
GET /plans/{id}, GET /plans/scopes both one plan; every merchant with its plan source and branch numbers, to choose from
POST /plans, PUT /plans/{id}, DELETE /plans/{id} ADMIN create (the merchant is in the body), replace (a PUT must say enabled, like the others), delete
GET /plan-simulation?merchantId&bin&amount[&branchId&paymentMethodId&bankId&date] both what the wallet would be offered, and why
  • The engine's own rules, not a copy. A write builds the domain's InstallmentPlan from the body (PlanInput.toPlan) and the record's constructor is the one place that refuses: a surcharge of 1 installment, a surcharge whose TNA or CFT is below 0.01 as sent (two decimals, half up: 0.004 would go out as 0.00), a CFT below the TNA, rates on a plan without surcharge, a discount of 100 % (after the POS rounding of the percentage), a MiPyME code with the wrong installments, bounds of a BIN range, the weekday mask, the window and the minimum. The 400 names the form field and is worded in Spanish by PlanRules (a table of fragments of the domain's messages; PlanAdminServiceTest has one case per rule, D-S5-20). PlanInput itself checks only what the columns hold (4 decimals and 3 integer digits for a percentage or a rate, 2 and 11 for money, days 1 to 7) and refuses instead of rounding in silence. A branch must exist and be of the merchant.
  • AC-13, the console refuses a tie. PlanTies.conflict(candidate, others) (pure, in the domain, next to the selection it protects): two enabled plans of one merchant tie when they have the same branch scope (both the merchant's, or both of one branch), payment method and number of installments, the same card specificity (BIN range, bank, method alone), a card both accept (the same bank or one without bank, and BIN ranges that share a BIN of 6 or 8 digits, BinMatcher.overlap), a day in both windows and a weekday in both masks; amounts never separate them (a minimum is a lower bound). A plan that is kept but never offered still ties (it claims its installments); a disabled one neither ties nor is tied with, so disabling is never refused and enabling a plan is checked like a create. The answer is a 409 whose body carries conflictingPlanId and a message that names that plan (its installments, method, bank, BIN range, branch and window); the console shows it as "Conflicto con el plan N". It is stricter than the engine in one case (D-S5-17).
  • Under a lock, so two creates cannot both pass. The write takes PlanAdminStore.lockMerchant (the merchant row read WITH (UPDLOCK, HOLDLOCK), held until the transaction ends), then reads the merchant's plans, checks, writes and audits, all in one unit of work. The second of two concurrent writes of one merchant waits for the first to commit and then sees its plan (PlanCreateRaceIT, which holds the audit of each write at a barrier so that both transactions are open at once: without the lock it fails). Other merchants do not wait (D-S5-19). The order is validate (no lock) → lock → read plans → check → write → audit.
  • Audit: INSTALLMENT_PLAN, CREATE/UPDATE/DELETE, before and after as JSON (decimals without trailing zeros, dates as ISO text), in the same transaction; a refused write leaves none.
  • The simulator is the real thing, read only. PlanSimulator builds the offer with CompleteOffer.assemble over a real MerchantPlanSource (so the plans of the merchant of the checkout decide), fed with the merchant's stored plans, the methods it accepts and their establishments: the classes BinsWorker calls, with a catalog that answers from the stored rows instead of a checkout. The verdict on each plan comes from GatewayConfiguredPlanSource.explain, which shares its candidates and its ordering with plansFor (the same code, not a second implementation); InstallmentPlan.whyNotFor is also what appliesTo asks. A verdict is one of OFFERED, NOT_OFFERABLE, OUTRANKED (by plan N), TIE (with plan N), OTHER_BRANCH, DISABLED, OTHER_METHOD (not listed), OTHER_BANK, OTHER_BIN, BEFORE_VALIDITY, AFTER_VALIDITY, OTHER_WEEKDAY, BELOW_MINIMUM, NOT_FOR_TRANSFER, UNREADABLE. When the real offer cannot be assembled (a tie, or a method without establishment) the answer carries failure (TIE or NO_OFFER, with the engine's text) and the cards keep their verdicts but no offers: the gateway would offer nothing and hand the payment over. It runs in a read-only unit of work, takes no lock and writes nothing (PlanSimulatorIT.ac29_aSimulationWritesNothing), and PlanSimulatorIT.ac29_theSimulatorOffersExactlyWhatTheBinsWorkerSentToTheWalletForTheSameSale compares it, plan by plan and cent by cent, with the complete intention that the emulated wallet received for the same merchant, branch, card and amount. What it cannot know is in D-S5-16.

The dashboard (GET /dashboard, both roles)

One read-only answer, DashboardService over DashboardQueries (JdbcDashboardQueries), read in one read-only unit of work. Every window comes from the Clock and is a parameter of the query; the numbers are counts that an index answers each (DashboardQueriesIT, FlywayBaselineMigrationIT.s5_theDashboardIndexesExist).

Block What it counts Window Index
Payments by merchant and state payments created in the business day the day of gateway.admin.business-zone (default America/Argentina/Buenos_Aires), [from, to) ix_payment_created_at (new: created_at including state, checkout_id)
Compensation tasks PENDING + IN_PROGRESS, and COMPENSATION_FAILED, and of those the REVERSE_CHARGE ones (S4: a customer's money being returned, or still charged) apart from the CANCEL_INTENTION ones all of them (a failed task has no "handled" mark yet) ix_compensation_task_due
Inbox rows not processed; rows finished ABANDONED or UNCORRELATED unprocessed: all; the others: last 24 h ix_inbound_notification_unprocessed; ix_inbound_notification_attention (new, filtered, costs the insert path nothing)
Past deadline payments in a waiting state whose wait_deadline_at passed more than 60 s ago and that have no compensation_task; up to 10 ids to open their trail now ix_payment_state_updated_at
Authorizer calls we made (wire_log OUT): total, failed (no answer or 5xx), refused (4xx), per operation last hour ix_wire_log_created_at (new, covering)
  • "Today" is the business day of a zone, not the UTC day: an evening sale in Buenos Aires is already the next day in UTC, and a UTC "today" is empty every evening. The answer carries the zone and both instants so the screen says what it counts. The payment search keeps UTC days (its hint says so), so the dashboard has no drill-down link by day.
  • Approval rate = payments the wallet paid / payments that ended in a yes or a no for the POS. Paid: APPROVED, ANNULLED, REFUNDED. A no: REJECTED, INTENT_FAILED, COMPLETE_FAILED, COMPENSATION_PENDING, COMPENSATED, COMPENSATION_FAILED. Not an answer, so left out: ID_ISSUED, the four waiting states, SUPERSEDED, CANCELLED, EXPIRED. With nothing answered the rate is null (a dash), never 0 %. A state this code does not know is counted and is not an answer (DashboardServiceTest).
  • The past-deadline block is the INV-02 signal that the database can show (D-105): a wait that ended with nobody handing the payment over. It cannot see the other D-105 case (an approval another node committed before the deadline while the POS was told "denied"): only the INV02_UNPERSISTED_DENIAL alert records that. The block is a signal for a person, not the reconciliation.
  • The authorizer's 4xx are counted apart because some belong to the normal flow (a complete intention that arrives late is a 404): the error rate is failed / calls.

The audit screen (GET /audit, ADMIN only)

AuditAdminService over AuditQueries (JdbcAuditQueries): a filtered, paged, newest-first read of admin_audit (actor, action, entity type, entity id, UTC days). Before and after are the stored JSON texts, which never held a password, hash or apikey (INV-07; AdminApiIT.s5_theAuditIs* creates a user and resets a password, then reads the audit and finds no secret). There is no retention rule yet (D-S5-5).

The emulator catalog (GET /emulator/catalog, ADMIN only, developer machines only)

The emulator has a read-only GET /emulator/catalog (EmulatorCatalog: every wallet scenario, operation and failure mode with a description; EmulatorCatalogTest fails when an enum value has none). The gateway reads it through EmulatorCatalogSource (HttpEmulatorCatalog: a GET, 3 s timeouts, no redirects, a body of at most 256 KiB, one exception that quotes nothing of what the other side said). Fail closed:

  • the address is gateway.admin.emulator-url, from the configuration and never from a request; unset (the default) means no bean, no controller, a 404, and the session tells the console not to offer the page (EmulatorCatalogDisabledTest, AdminApiIT.s5_withoutAnEmulator*);
  • ProductionProfileGuard refuses to start when it is set under any profile but local or test, with no profile, or from an environment variable (ProductionProfileGuardTest.s5_*): a production gateway cannot be pointed at an emulator, whatever else is configured;
  • the console's page is read-only: scenarios are started and failures injected through the emulator's control API, not from the console.