Saltar a contenido

Reverse-engineering snapshot of tipre/GatewayQR (branch feat/base-amount), generated 2026-10-01. Line numbers refer to that working tree.

GatewayQR reverse-engineering report

feat/base-amount = main + 5 commits. One uncommitted change: TrxResource.java:963 has auditBaseAmountEcho(...) commented out, with its test.

1. Architecture, layout, conventions

Stack: JHipster 4.14.5 monolith, Spring Boot 1.5.15, Java 8, Maven, WAR on Undertow. AngularJS 1 + gulp/bower/yarn. JWT admin auth, i18n es/en. SQL Server (mssql-jdbc, SQLServer2012Dialect, Hikari, ddl-auto: none). Hibernate Envers on Trx.

Schema management: Liquibase present but disabled (liquibase.enabled: false). Changes applied by hand with idempotent SQL scripts (e.g. db-migracion-trx-mensaje-varios-500.sql); gwdb_create.sql is a 2023-03-16 SSMS dump. Changelog is stale (missing 3 autorizador columns), so @SpringBootTest IntTests fail. The new base_amount changelog never runs → prod needs manual DDL and no script exists.

Packages (com.tipre.gatewayqr): - web/rest/*Resource: JHipster CRUD (Autorizador, Comercio, Comercioautorizadormdep, Parametro, Pos, Sucursal, Terminal) + hand-written TrxResource (1534 lines, the payment brain). - web/rest/util: EnviarIntencion, ConsultarTransaccion, ComputeMdePUtil, BeneficiosCenterClient, EmuladorBeneficioUtil. - domain: entities + wire POJOs (TrxRtaPos, Trxid, Trxiprta, Payment_methods_data, Installment, CMHashMapResponse). - helper: MyServerError*, AutorizadorRespuesta, TraficoLog, MyCurrentDateTime, MyGatewayQRCMHashMap. - EmuladorAutorizaciones at package root.

Layering: fat controller, no service layer; TrxResource injects repositories and Environment directly. The Trx entity is the @RequestBody. No @Transactional on the payment path. Outbound clients created with new, new RestTemplate per call. BeneficiosCenterClient is the only well-structured client (@Component, @Value, prebuilt RestTemplates, bounded executor).

Naming: mixed Spanish/English, lowercase-glued (autorizadorintencionid, trxidoriginal), snake_case for authorizer-derived fields (payment_method_id, importe_final, importe_recdesc), My* helpers, some PascalCase methods, SCREAMING_SNAKE Spanish states.

Config: profiles dev/prod; WAR excludes internal yml; real config is external config/application-{dev,prod}.yml (gitignored, .example templates with CHANGE_ME). Custom namespaces misuse server.* (server.intenciondepago.*, server.autorizaciondepago.*, server.consulta.*, server.apikey.tecso, server.emulador.*), plus app.beneficioscenter.* and application.permitecashout. Endpoint paths are property-driven (trxpago, trxanulacion, trxwebhook, trxwebhook_anulacion); boot fails if the external file is missing.

2. POS-facing API contract

No POS authentication. SecurityConfiguration.java:100-135 permits /api/trxid/**, /api/trxes/**, the pay/annul/webhook paths and /api/emulador_*. /api/trxes also exposes the full paginated Trx (CUIT, CBU, raw JSON).

JSON names are Jackson defaults from getters; base_amount needs explicit @JsonProperty.

2.1 POST /api/trxid (TrxResource.java:262-335)

Request {comercio (name), sucursal (int), pos (int)}, id must be null. Looks up enabled comercio → sucursal → pos; creates Trx with cuit, cbu, branch, checkout, mpposid, estado=OBTENCIONIDTRX. Response 201 Trxid {id, pos, sucursal, comercio, tipoAutorizadores[], mpposid}. Errors: 400 missing fields, 404 not found/disabled, 500 DB.

2.2 POST /api/trxpago (:337-626) — synchronous, blocking

Request: id, importe, tipoautorizador (TECSO|PRISMA|MERCADOPAGO|MODO) required; nropv, nroticketfiscal, totalcashback, base_amount optional.

Stored estado Behaviour
OBTENCIONIDTRX New payment
INTENCION_DE_PAGO_ENVIADA, ..._RECIBIDA_APROBADA, AUTORIZACION_DE_PAGO_SINRESPUESTA Do not resend; resume waiting on same intention
AUTORIZACION_DE_PAGO_APROBADA 200 with stored TrxRtaPos (idempotent)
denied states 400

Resolves autorizador (enabled), terminal by (autorizador, pos), comercioautorizadormdep (payment-method list JSON). Then ComputeMdePUtil.generate + EnviarIntencion.send.

Waiting: polls a static ConcurrentHashMap<Long,CMHashMapResponse> keyed by autorizadorintencionid every 100 ms, up to server.autorizaciondepago.read-timeout (default 60 s, dev 120 s). On timeout: optional sleep, one CONSULTA: 0 → APROBADA, 1 → DENEGADA, -1 → AUTORIZACION_DE_PAGO_SINRESPUESTA returned as HTTP 200 (code comment: "dice ok, pero en realidad sera rechazada").

Response TrxRtaPos: id, autorizadorintencionid, autorizadortrxid, estado, statuscode, importe, payment_method_id, importe_final, importe_recdesc, payment_method_type, mensajevarios. statuscode 0 OK / 1 denied; after SINRESPUESTA it stays 0 → the POS must read estado.

Undocumented critical contract: importe_recdesc is stored negative (TrxResource.java:961); the POS (pos_mppo.cpp PagoQR_ImputarDescuento) negates it, rejects positive values as surcharge, and checks importe + importe_recdesc == importe_final.

Error shape for hand-written endpoints: {status, message} (not RFC 7807 like the CRUD ones).

2.3 POST /api/trxanulacion (:630-816)

Request {id (fresh from /trxid), trxidoriginal}. Original AUTORIZACION_DE_PAGO_APROBADA → motivo=REFUND; original sent/received/SINRESPUESTA → motivo=ANNULMENT; denied → 400. Duplicate guard only catches already-approved cancellations. Clones the original row onto the new id, sends, waits webhook like pay, no CONSULTA fallback; timeout → AUTORIZACION_DE_ANULACION_SINRESPUESTA with 200.

2.4 Read endpoints

GET /api/trxes/{id}, /api/trxes/local/{id} → TrxRtaPos (not-found raised as a 500-class error). GET /api/trxes/remote/{intentionId} → live CONSULTA. GET /api/trxes paginated entity list.

3. Authorizer-facing integration

3.1 Outbound

  • URLs from the autorizador row (urlintencionpago, urlintencionanulacion, urlconsulta; notification URLs stored but unused; columns only 100 chars).
  • Headers: Content-Type, Apikey: <server.apikey.tecso> (one global key), a pointless Strict-Transport-Security request header.
  • Timeouts: connect 5 s / read 10 s default (dev 10/120). No retries.

Payment intention payload (ComputeMdePUtil.generate, :35-150):

{integrator_intention_id: trx.id, cuit, branch, cbu, checkout, terminal_number,
 intention_type: "payment", currency: "ARS", original_amount, pos_id: mpposid,
 payment_methods_data: [{payment_method_id, establishment_id, trace_number, ticket_number,
   installments: [{bank_id?, quantity, total_amount, amount_per_installment, cft, tna}]}],
 benefits_methods_data?: [...], cashout?: totalcashback}
- Payment methods from comercioautorizadormdep.listamdep (JSON). - trace_number/ticket_number from terminal.nrotrace/nroticket, incremented per payment method with a non-atomic read-modify-write. - amount_per_installment = importe/quantity, scale 2, HALF_EVEN (plan 002 fix).

Cancellation payload (generateAnulacion), the authorizer calls it forcedannulments:

{intention_id: <original>, cuit, terminal_number,
 payment_methods_data: [{payment_method_id, establishment_id, trace_number, ticket_number}],
 motivo: "REFUND" | "ANNULMENT"}

Response parsing: 2xx with status in (approved, created, refund_annulment_in_progress) = approved; stores intention_id, intention_datetime, integrator, integrator_intention_id. Row saved as "sent" before the HTTP call. 4xx → error_type + validation_errors[0] into mensajevarios.

CONSULTA: GET {urlconsulta}?intention_id= → status==approved 0 / other 2xx 1 / error -1; reads payment method, installments, amount, benefits_data.discounted_amount (negated), id, datetime.

3.2 Inbound webhooks

  • Auth: header APIKEY vs server.apikey.tecso, constant-time MessageDigest.isEqual, fail-closed (plan 001, commit 3149414).
  • POST /api/trxwebhook (:854-1005): requires id, intention_id, transaction_datetime, payment_method_id, payment_method_type, amount, installments, status (422 if missing). Lookup by intention id; state guard: sent/received → process; APROBADA → 208; RECIBIDA_DENEGADA → 409; DENEGADA → 406; SINRESPUESTA → 504 (late result dropped, plan 004 TODO). Stores payment method, cuotas, importe_final, autorizadortrxid, raw body; discount from benefits_data.discounted_amount (fallback top-level) as -|x|; card_authorization_code into mensajevarios. Wakes the waiting POS thread, fires BeneficiosCenter /resultado. Responds 200 {"status":200,"message":"OK"}.
  • POST /api/trxwebhook_anulacion (:1112-1223): similar; lookup OrderByIdDesc because the cancel row clones the original's intention id (fragile); accepts SINRESPUESTA; no BeneficiosCenter notification.

3.3 BeneficiosCenter

  • Resolve POST {base-url}/api/v1/beneficios/resolver (X-Api-Key), called before the intention is built. Body {requestId, transaction{datetime, amount, currency, base_amount?}, merchant{branchId, posId, salesPointId:null}, invoice{all null}}. Maps benefits[] to benefits_methods_data[] (establishment_id, benefits_card{code,description}, benefit_id, discount{percentage, maximum_discount_amount, amount, type, base_amount}). Timeouts 300 ms / 800 ms.
  • Result POST /api/v1/beneficios/resultado fire-and-forget on a bounded daemon pool (core 2, max 4, queue 50, DiscardPolicy). Only from the webhook, not from CONSULTA recovery.
  • Never blocks or fails a payment; feature flag app.beneficioscenter.enabled.

3.4 Idempotency and reversals

State-based on row id; duplicate webhooks rejected by status code. No idempotency keys, no unique constraint on autorizadorintencionid, no locking (CONCURRENCY-01). DEVOLUCION, ANULACIONFORZADA, ANULACION_DEVOLUCION enumerated but unimplemented. No background reconciliation; SINRESPUESTA never reconciled.

3.5 Emulator

Flag server.emulador.habilitado; POST /api/emulador_pago, /api/emulador_anulacion, GET /api/emulador_consulta. A @Scheduled job posts the simulated webhook back. EmuladorBeneficioUtil simulates a DINI account discount with the real TECSO benefits_data shape. Likely mis-wired: setup-emulador-qa.sql points urlconsulta at /api/trxes (the list endpoint) instead of /api/emulador_consulta (not verified at runtime).

4. Domain model

Trx (one wide row for pay and cancel, @Audited): - identity/time: id, trxfecha, operacion (PAGO|ANULACION|...), estado, statuscode - original link: trxidoriginal, trxfechaoriginal, autorizadorintencionidoriginal - authorizer ids: autorizadorintencionid (correlation key), autorizadorintencionfecha, autorizadortrxid, autorizadortrxfecha, integrador - routing denormalized: comercio, sucursal, pos, comercioid, posid, terminalid, terminal (8), branch, checkout, mpposid (NOT NULL, MP remnant), cuitcomercio, cbucomercio, tipoautorizador - amounts decimal(13,2): importe, base_amount, importe_final, importe_recdesc, totalcashback, cuotas - raw payloads (5000 chars, silently limited): jsonreqpos, jsonrtapos, jsonreqintencion, jsonrtaintencion, jsonreqautorizacion, jsonrtaautorizacion (jsonreqpos/jsonrtapos are toString(), not JSON) - misc: nropv, nroticketfiscal, clienteid, mensaje_varios (500)

Config entities: Comercio(nombre, habilitado, cuit, cbu) 1:N Sucursal(nombre, habilitado, numero, branch) 1:N Pos(numero, habilitado, checkout, mpposid) (unique pos(numero, sucursal_id)). Autorizador(nombre, habilitado, tipoautorizador, url*). Terminal(terminal[8], nroticket, nrotrace, autorizador, pos). Comercioautorizadormdep(listamdep[5000], autorizador, comercio). Parametro unused.

Enums: StatusTypes (25 values, 4 families × 6; only PAGO and ANULACION used). TipoAutorizador {TECSO, PRISMA, MERCADOPAGO, MODO} (JDL stale).

stateDiagram-v2
    [*] --> OBTENCIONIDTRX: POST /trxid
    OBTENCIONIDTRX --> INTENCION_DE_PAGO_ENVIADA: POST /trxpago (saved before HTTP call)
    INTENCION_DE_PAGO_ENVIADA --> INTENCION_DE_PAGO_RECIBIDA_APROBADA: 2xx approved/created
    INTENCION_DE_PAGO_ENVIADA --> INTENCION_DE_PAGO_RECIBIDA_DENEGADA: 4xx / error
    INTENCION_DE_PAGO_RECIBIDA_APROBADA --> AUTORIZACION_DE_PAGO_APROBADA: webhook approved / CONSULTA 0
    INTENCION_DE_PAGO_RECIBIDA_APROBADA --> AUTORIZACION_DE_PAGO_DENEGADA: webhook other / CONSULTA 1
    INTENCION_DE_PAGO_RECIBIDA_APROBADA --> AUTORIZACION_DE_PAGO_SINRESPUESTA: timeout + CONSULTA -1
    AUTORIZACION_DE_PAGO_SINRESPUESTA --> [*]: late webhook rejected 504
    AUTORIZACION_DE_PAGO_APROBADA --> [*]
    AUTORIZACION_DE_PAGO_DENEGADA --> [*]
    INTENCION_DE_PAGO_RECIBIDA_DENEGADA --> [*]

Cancellation follows the same pattern with *_ANULACION_* states on a cloned row; AUTORIZACION_DE_ANULACION_SINRESPUESTA accepts a late webhook.

5. Cross-cutting

  • Logging: logs/gatewayQr.log rolling; traffic.log (TraficoLog): async, never-blocking, one line per JSON crossing a boundary (origen/destino/ctx/body), truncated at 8000 chars, wrapped in try/catch. Excellent pattern.
  • StartupConfigLogger dumps effective config with keys masked to the last 4 chars.
  • Security: JWT admin; POS endpoints open; single shared webhook APIKEY; trust-all TLS for the MP POS-id lookup; SEC-02..07 deferred.
  • Jobs: only JHipster user cleanup and the emulator. No reconciliation.
  • Multi-tenancy: data-only (Comercio → Sucursal → Pos); one authorizer row per type; one global API key and webhook path.
  • In-memory state: static map → single node only, lost on restart, no TTL.
  • Admin UI: AngularJS CRUD; Trx read-only; Pos creation calls GatewayMP for mpposid. WARs committed under releases/.

6. Branches

  • origin/JH8: JHipster 8.4.0 skeleton (Boot 3.2.5, Java 17) generated 2024-06-10 from the first commit; entities regenerated, no payment logic ported; abandoned.
  • origin/PQR-4: strict ancestor of main (tip v20250919); production baseline before Sept 2026 work (MVP 2023, anulación, mpposid, cashout 2025).
  • origin/develop: initial JHipster generation only.
  • main vs PQR-4 (24 commits, 2026-09-11..10-01): BeneficiosCenter integration, SEC-01 and CORR-01 fixes, negative importe_recdesc, traffic log, startup config logger, externalized config, emulator fixes, nested benefits_data.discounted_amount, plain-unit tests.
  • feat/base-amount: optional base_amount end to end.

7. plans/

plans/README.md (2026-09-12): "7 days to prod" on Boot 1.5 / Java 8; defers framework migration and broad hardening.

Plan Subject Status
001 Webhook APIKEY fails closed DONE
002 Installment divide crash + rounding DONE
003 discounted_amount: null dropping approved webhooks TODO (different fix landed)
004 Accept late webhook after SINRESPUESTA TODO
005 Cancellation duplicate guard for in-flight states TODO
006 Log-only coherence check importe + recdesc == final TODO

No ADRs; no written POS contract (it lives in code comments, test javadocs and pos_mppo.cpp).

8. Weaknesses and strengths

Weaknesses (avoid): 1. God controller; entity as DTO (mass assignment) and as public output. 2. Unauthenticated POS API; /api/trxes/** leaks data. 3. Blocking long-poll on an in-JVM map; single node; HTTP 200 with statuscode=0 on "unknown". 4. No reconciliation; late webhooks rejected; CONSULTA only once and not for cancellations. 5. No locking; non-atomic trace/ticket counters; duplicate-cancel guard misses in-flight rows. 6. Cancellation by cloning the payment row. 7. State machine as scattered switches; 25 states, 12 unused; estado and statuscode overlap. 8. Swallowed exceptions; 500 for not-found; mixed error shapes. 9. Hand-built org.json → real bugs (null guard, nested vs flat discount, dropped base_amount). 10. Config smells (server.*, "length > 3" presence checks, per-call Environment reads, one global key, secrets in yml). 11. Liquibase disabled and stale; manual SQL; broken IntTests; stale JDL; untracked prod DDL. 12. Money types inconsistent (cft/tna as Float; Integer == comparisons). 13. Mixed naming; dead code; MercadoPago vestiges (mpposid NOT NULL, trust-all TLS). 14. BeneficiosCenter result not sent from the CONSULTA path. 15. WARs, .bak, curl.exe and DLLs in git; no CI.

Strengths (preserve): - Simple POS contract: trxid → trxpago / trxanulacion, single TrxRtaPos; property-driven endpoint names. - Two-phase id model and state-aware trxpago resume. - Full request/response JSON per hop + Envers history. - traffic.log, masked startup config dump, no keys in logs. - Resilient-sidecar contract of BeneficiosCenterClient (tight timeouts, never blocks, fire-and-forget, feature flag). - Fail-closed constant-time webhook auth. - Emulator in the box with the real authorizer shape + QA seed script. - Data-driven routing (comercio, sucursal, pos, terminal, autorizador, mdep). - AutorizadorRespuesta tolerant-reader pattern with unit tests. - Written plans with drift checks and STOP conditions. - The importe_recdesc sign convention and the coherence rule (should become a written contract).

Key files: web/rest/TrxResource.java, web/rest/util/{EnviarIntencion,ConsultarTransaccion,ComputeMdePUtil,BeneficiosCenterClient,EmuladorBeneficioUtil}.java, helper/{MyGatewayQRCMHashMap,TraficoLog,AutorizadorRespuesta}.java, domain/{Trx,TrxRtaPos,Trxid}.java, config/SecurityConfiguration.java, config/application-*.yml.example, plans/README.md, setup-emulador-qa.sql, src/test/.../TrxResourceWebHookTest.java.