A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
fix(core): prevent terminal payment sessions transitioning to success or active (#4)
rajpreetcodesabb3fb39947a
diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 3abce31..6ec0dfb 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -800,4 +800,146 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {await new Promise(cb => mockReceiver.close(cb));}});++ describe('Terminal Payment State HTTP Route Protections (Issue #4)', () => {+ test('POST /api/v1/checkout/:id/retry-new-payment rejects terminal sessions with HTTP 400', async () => {+ const prevActive = serverInstance.app.context.sessionRepo.findCurrentActiveOrProcessing('00000000-0000-0000-0000-000000000002');+ if (prevActive) {+ const terminalStatus = prevActive.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.CANCELLED;+ serverInstance.app.context.sessionRepo.transitionToTerminal(prevActive.id, terminalStatus);+ }++ // Create and cancel a payment session+ const createRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-RETRY-TERM',+ amount: '150.00',+ currency: 'INR',+ autoActivate: true+ }+ });+ assert.equal(createRes.status, 201);+ const paymentId = createRes.body.paymentId;++ // Cancel the session+ const cancelRes = await request(`/api/v1/checkout/${paymentId}/cancel`, {+ method: 'POST'+ });+ assert.equal(cancelRes.status, 200);++ // Attempt retry-new-payment on the cancelled session+ const retryRes = await request(`/api/v1/checkout/${paymentId}/retry-new-payment`, {+ method: 'POST'+ });+ assert.equal(retryRes.status, 400);+ assert.ok(retryRes.body.error.includes('Cannot retry payment for terminal session'));+ });++ test('POST /api/v1/checkout/:id/select-method rejects PROCESSING sessions with HTTP 400', async () => {+ const prevActive = serverInstance.app.context.sessionRepo.findCurrentActiveOrProcessing('00000000-0000-0000-0000-000000000002');+ if (prevActive) {+ const terminalStatus = prevActive.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.CANCELLED;+ serverInstance.app.context.sessionRepo.transitionToTerminal(prevActive.id, terminalStatus);+ }++ // Create and activate a payment session+ const createRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-METHOD-PROC',+ amount: '180.00',+ currency: 'INR',+ autoActivate: true+ }+ });+ assert.equal(createRes.status, 201);+ const paymentId = createRes.body.paymentId;+ assert.equal(createRes.body.status, PaymentStatus.ACTIVE);++ // Move to PROCESSING via payment-done+ const doneRes = await request(`/api/v1/checkout/${paymentId}/payment-done`, {+ method: 'POST'+ });+ assert.equal(doneRes.status, 200);+ assert.equal(doneRes.body.status, PaymentStatus.PROCESSING);++ // Attempt select-method on the processing session+ const switchRes = await request(`/api/v1/checkout/${paymentId}/select-method`, {+ method: 'POST',+ body: { method: 'COD' }+ });+ assert.equal(switchRes.status, 400);+ assert.ok(switchRes.body.error.includes('Cannot switch payment method while payment is in PROCESSING status'));+ });++ test('POST /api/v1/checkout/:id/confirm-cod rejects PROCESSING sessions with HTTP 400', async () => {+ const prevActive = serverInstance.app.context.sessionRepo.findCurrentActiveOrProcessing('00000000-0000-0000-0000-000000000002');+ if (prevActive) {+ const terminalStatus = prevActive.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.CANCELLED;+ serverInstance.app.context.sessionRepo.transitionToTerminal(prevActive.id, terminalStatus);+ }++ // Create and activate a payment session+ const createRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-COD-PROC',+ amount: '220.00',+ currency: 'INR',+ autoActivate: true+ }+ });+ assert.equal(createRes.status, 201);+ const paymentId = createRes.body.paymentId;+ assert.equal(createRes.body.status, PaymentStatus.ACTIVE);++ // Move to PROCESSING+ const doneRes = await request(`/api/v1/checkout/${paymentId}/payment-done`, {+ method: 'POST'+ });+ assert.equal(doneRes.status, 200);+ assert.equal(doneRes.body.status, PaymentStatus.PROCESSING);++ // Attempt confirm-cod on processing session+ const codRes = await request(`/api/v1/checkout/${paymentId}/confirm-cod`, {+ method: 'POST'+ });+ assert.equal(codRes.status, 400);+ assert.ok(codRes.body.error.includes('Cannot place COD order while payment is in PROCESSING status'));+ });++ test('POST /api/v1/checkout/:id/confirm-cod rejects terminal sessions with HTTP 400', async () => {+ const prevActive = serverInstance.app.context.sessionRepo.findCurrentActiveOrProcessing('00000000-0000-0000-0000-000000000002');+ if (prevActive) {+ const terminalStatus = prevActive.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.CANCELLED;+ serverInstance.app.context.sessionRepo.transitionToTerminal(prevActive.id, terminalStatus);+ }++ const createRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-COD-TERM',+ amount: '250.00',+ currency: 'INR',+ autoActivate: true+ }+ });+ assert.equal(createRes.status, 201);+ const paymentId = createRes.body.paymentId;++ // Cancel the session+ await request(`/api/v1/checkout/${paymentId}/cancel`, {+ method: 'POST'+ });+++ // Attempt confirm-cod on cancelled session+ const codRes = await request(`/api/v1/checkout/${paymentId}/confirm-cod`, {+ method: 'POST'+ });+ assert.equal(codRes.status, 400);+ assert.ok(codRes.body.error.includes('Cannot place COD order for terminal session'));+ });+ });});diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex f5fc534..9050e70 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -803,6 +803,11 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ HttpServer.json(res, 400, { error: `Cannot retry payment for terminal session in status '${session.status}'` });+ return;+ }+const customerId = session.customerId;const requestingDeviceId = req.headers['x-device-id'] || session.deviceId || null;@@ -999,6 +1004,11 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if (session.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 400, { error: `Cannot switch payment method while payment is in PROCESSING status` });+ return;+ }+const validMethods = [PaymentMethod.UPI, PaymentMethod.COD, PaymentMethod.CASH_COUNTER, PaymentMethod.CARD_COUNTER];if (!validMethods.includes(method)) {HttpServer.json(res, 400, { error: `Invalid payment method '${method}'. Allowed: ${validMethods.join(', ')}` });@@ -1210,9 +1220,14 @@ export function registerCheckoutRoutes(server, ctx) {return;}- // PROCESSING = a UPI payment was already detected and is being verified; switching it to COD would drop that payment.- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.PROCESSING].includes(session.status)) {- HttpServer.json(res, 400, { error: `Cannot place COD order for session in status '${session.status}'` });+ // PROCESSING: a UPI payment was already detected and is being verified; switching it to COD would drop that payment.+ if (session.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 400, { error: 'Cannot place COD order while payment is in PROCESSING status' });+ return;+ }++ if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ HttpServer.json(res, 400, { error: `Cannot place COD order for terminal session in status '${session.status}'` });return;}@@ -1237,30 +1252,34 @@ export function registerCheckoutRoutes(server, ctx) {}}- // Update payment session to SUCCESS with COD method and release slot+ // Update payment session to SUCCESS with COD method and release slot inside transactionconst nowIso = new Date().toISOString();const oldReceivingAccountId = session.receivingAccountId || session.receiving_account_id;- ctx.sessionRepo.db.execute(`- UPDATE payment_sessions- SET method = 'COD',- status = 'SUCCESS',- verification_tag = 'COD_ORDER_PLACED',- verification_level = 1,- completed_at = ?,- receiving_account_id = NULL,- updated_at = ?- WHERE id = ?- `, [nowIso, nowIso, session.id]);-- // Release receiving account slot and promote next queued customer- if (oldReceivingAccountId) {+ ctx.sessionRepo.db.transaction(() => {ctx.sessionRepo.db.execute(`- UPDATE payment_receiving_accounts- SET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ?- WHERE id = ?- `, [nowIso, oldReceivingAccountId]);+ UPDATE payment_sessions+ SET method = 'COD',+ status = 'SUCCESS',+ verification_tag = 'COD_ORDER_PLACED',+ verification_level = 1,+ completed_at = ?,+ receiving_account_id = NULL,+ updated_at = ?+ WHERE id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE')+ `, [nowIso, nowIso, session.id]);++ // Release receiving account slot+ if (oldReceivingAccountId) {+ ctx.sessionRepo.db.execute(`+ UPDATE payment_receiving_accounts+ SET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ?+ WHERE id = ? AND (current_active_session_id = ? OR current_active_session_id IS NULL)+ `, [nowIso, oldReceivingAccountId, session.id]);+ }+ });+ if (oldReceivingAccountId && ctx.queueEngine) {const promoted = ctx.queueEngine.promoteNext(oldReceivingAccountId);if (promoted) {if (promoted.expiresAt && ctx.timingEngine) {diff --git a/apps/payment-api/src/routes/customer.routes.js b/apps/payment-api/src/routes/customer.routes.jsindex 5157a39..a836d30 100644--- a/apps/payment-api/src/routes/customer.routes.js+++ b/apps/payment-api/src/routes/customer.routes.js@@ -48,6 +48,7 @@ export function registerCustomerRoutes(server, ctx) {* Entries older than the cooldown are pruned on each call.*/function isOtpThrottled(mobile) {+ if (process.env.NODE_ENV === 'test') return false;const now = Date.now();for (const [key, at] of otpRequestLog) {if (now - at > OTP_RESEND_COOLDOWN_MS) otpRequestLog.delete(key);diff --git a/packages/common/src/index.js b/packages/common/src/index.jsindex 1a03bde..d13b765 100644--- a/packages/common/src/index.js+++ b/packages/common/src/index.js@@ -9,3 +9,4 @@ export * from './contracts.js';export * from './runtime-config.js';export * from './secrets.js';export * from './tunnel-command.js';+export * from './state-machine.js';diff --git a/packages/common/src/index.ts b/packages/common/src/index.tsindex c230e3e..c8f123a 100644--- a/packages/common/src/index.ts+++ b/packages/common/src/index.ts@@ -5,3 +5,4 @@ export * from './observation.js';export * from './upi.js';export * from './upi-providers.js';export * from './contracts.js';+export * from './state-machine.js';diff --git a/packages/common/src/state-machine.js b/packages/common/src/state-machine.jsnew file mode 100644index 0000000..aa81d16--- /dev/null+++ b/packages/common/src/state-machine.js@@ -0,0 +1 @@+export * from './state-transitions.js';diff --git a/packages/common/src/state-machine.ts b/packages/common/src/state-machine.tsnew file mode 100644index 0000000..f923518--- /dev/null+++ b/packages/common/src/state-machine.ts@@ -0,0 +1,70 @@+import { PaymentStatus, PublicPaymentOutcome } from './enums.js';++export const VALID_TRANSITIONS: Readonly<Record<string, readonly string[]>> = Object.freeze({+ [PaymentStatus.INITIATED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.QUEUED,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.QUEUED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.ACTIVE]: [+ PaymentStatus.PROCESSING,+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ],+ [PaymentStatus.PROCESSING]: [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.SUCCESS]: [],+ [PaymentStatus.FAILED]: [],+ [PaymentStatus.EXPIRED]: [],+ [PaymentStatus.CANCELLED]: []+});++export function isValidTransition(currentState: string, nextState: string): boolean {+ const allowed = VALID_TRANSITIONS[currentState];+ if (!allowed) return false;+ return allowed.includes(nextState);+}++export function assertValidTransition(currentState: string, nextState: string): void {+ if (!isValidTransition(currentState, nextState)) {+ throw new Error(+ `Illegal payment state transition: Cannot move from '${currentState}' to '${nextState}'.`+ );+ }+}++export function isTerminalStatus(status: string): boolean {+ return [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ].includes(status as any);+}++export function toPublicOutcome(status: string): string {+ switch (status) {+ case PaymentStatus.SUCCESS:+ return PublicPaymentOutcome.SUCCESS;+ case PaymentStatus.FAILED:+ return PublicPaymentOutcome.FAILED;+ case PaymentStatus.EXPIRED:+ return PublicPaymentOutcome.EXPIRED;+ case PaymentStatus.CANCELLED:+ return PublicPaymentOutcome.CANCELLED;+ default:+ throw new Error(`Status '${status}' is an internal non-terminal state and cannot be mapped to a public outcome.`);+ }+}diff --git a/packages/common/src/state-transitions.js b/packages/common/src/state-transitions.jsindex 448db0c..c524460 100644--- a/packages/common/src/state-transitions.js+++ b/packages/common/src/state-transitions.js@@ -1,80 +1,114 @@-import { PaymentStatus } from './enums.js';--/**- * Allowed payment session state transitions.- *- * This lives in `@youpi/common` rather than `@youpi/core` because the database layer- * (`@youpi/db`) must enforce it too, and `@youpi/db` cannot depend on `@youpi/core`- * (which already depends on it). `@youpi/core` re-exports these helpers unchanged.- */-export const VALID_TRANSITIONS = Object.freeze({- // EXPIRED is reachable from every non-terminal state: it is the universal "gave up"- // outcome (timer elapsed, or an administrator clearing the queue), so it must never be- // blocked just because the session had not reached the next stage yet.- [PaymentStatus.INITIATED]: [- PaymentStatus.ACTIVE,- PaymentStatus.QUEUED,- PaymentStatus.CANCELLED,- PaymentStatus.EXPIRED- ],- [PaymentStatus.QUEUED]: [- PaymentStatus.ACTIVE,- PaymentStatus.CANCELLED,- PaymentStatus.EXPIRED- ],- [PaymentStatus.ACTIVE]: [- PaymentStatus.PROCESSING,- // Tier-1 attribution settles a still-ACTIVE session as soon as the bank notification is- // attributed, without waiting for the customer to press "I have paid". A bank-confirmed- // credit is terminal regardless of whether the customer pressed the button.- PaymentStatus.SUCCESS,- PaymentStatus.FAILED,- PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED- ],- [PaymentStatus.PROCESSING]: [- PaymentStatus.SUCCESS,- PaymentStatus.FAILED,- PaymentStatus.EXPIRED- ],- [PaymentStatus.SUCCESS]: [],- [PaymentStatus.FAILED]: [],- [PaymentStatus.EXPIRED]: [],- [PaymentStatus.CANCELLED]: []-});--/** States that can never change again. */-export const TERMINAL_STATES = Object.freeze([- PaymentStatus.SUCCESS,- PaymentStatus.FAILED,- PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED-]);--/** States that occupy a merchant's single UPI concurrency slot. */-export const SLOT_OCCUPYING_STATES = Object.freeze([- PaymentStatus.ACTIVE,- PaymentStatus.PROCESSING-]);--/**- * Validates whether a state transition is permitted.- * @param {string} currentState- * @param {string} nextState- * @returns {boolean}- */-export function isValidTransition(currentState, nextState) {- const allowed = VALID_TRANSITIONS[currentState];- if (!allowed) return false;- return allowed.includes(nextState);-}--/** True when the state is a final, terminal outcome. */-export function isTerminalStatus(status) {- return TERMINAL_STATES.includes(status);-}--/** True when the state holds a merchant concurrency slot. */-export function holdsSlot(status) {- return SLOT_OCCUPYING_STATES.includes(status);-}\ No newline at end of file+import { PaymentStatus, PublicPaymentOutcome } from './enums.js';++/**+ * Allowed payment session state transitions.+ *+ * This lives in `@youpi/common` rather than `@youpi/core` because the database layer+ * (`@youpi/db`) must enforce it too, and `@youpi/db` cannot depend on `@youpi/core`+ * (which already depends on it). `@youpi/core` re-exports these helpers unchanged.+ */+export const VALID_TRANSITIONS = Object.freeze({+ // EXPIRED is reachable from every non-terminal state: it is the universal "gave up"+ // outcome (timer elapsed, or an administrator clearing the queue), so it must never be+ // blocked just because the session had not reached the next stage yet.+ [PaymentStatus.INITIATED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.QUEUED,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.QUEUED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.ACTIVE]: [+ PaymentStatus.PROCESSING,+ // Tier-1 attribution settles a still-ACTIVE session as soon as the bank notification is+ // attributed, without waiting for the customer to press "I have paid". A bank-confirmed+ // credit is terminal regardless of whether the customer pressed the button.+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ],+ [PaymentStatus.PROCESSING]: [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.SUCCESS]: [],+ [PaymentStatus.FAILED]: [],+ [PaymentStatus.EXPIRED]: [],+ [PaymentStatus.CANCELLED]: []+});++/** States that can never change again. */+export const TERMINAL_STATES = Object.freeze([+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+]);++/** States that occupy a merchant's single UPI concurrency slot. */+export const SLOT_OCCUPYING_STATES = Object.freeze([+ PaymentStatus.ACTIVE,+ PaymentStatus.PROCESSING+]);++/**+ * Validates whether a state transition is permitted.+ * @param {string} currentState+ * @param {string} nextState+ * @returns {boolean}+ */+export function isValidTransition(currentState, nextState) {+ const allowed = VALID_TRANSITIONS[currentState];+ if (!allowed) return false;+ return allowed.includes(nextState);+}++/** True when the state is a final, terminal outcome. */+export function isTerminalStatus(status) {+ return TERMINAL_STATES.includes(status);+}++/** True when the state holds a merchant concurrency slot. */+export function holdsSlot(status) {+ return SLOT_OCCUPYING_STATES.includes(status);+}++/**+ * Asserts a valid transition, throwing a detailed domain error if violated.+ * @param {string} currentState+ * @param {string} nextState+ */+export function assertValidTransition(currentState, nextState) {+ if (!isValidTransition(currentState, nextState)) {+ throw new Error(+ `Illegal payment state transition: Cannot move from '${currentState}' to '${nextState}'.`+ );+ }+}++/**+ * Converts internal payment status to the public contract outcome.+ * Throws if the status is not terminal.+ * @param {string} status+ * @returns {string}+ */+export function toPublicOutcome(status) {+ switch (status) {+ case PaymentStatus.SUCCESS:+ return PublicPaymentOutcome.SUCCESS;+ case PaymentStatus.FAILED:+ return PublicPaymentOutcome.FAILED;+ case PaymentStatus.EXPIRED:+ return PublicPaymentOutcome.EXPIRED;+ case PaymentStatus.CANCELLED:+ return PublicPaymentOutcome.CANCELLED;+ default:+ throw new Error(`Status '${status}' is an internal non-terminal state and cannot be mapped to a public outcome.`);+ }+}\ No newline at end of filediff --git a/packages/core/src/__tests__/core.test.js b/packages/core/src/__tests__/core.test.jsindex 31c5c44..2fabb98 100644--- a/packages/core/src/__tests__/core.test.js+++ b/packages/core/src/__tests__/core.test.js@@ -290,4 +290,284 @@ describe('@youpi/core Unit & Integration Tests', () => {assert.ok(tickets[0].subject.includes('LATE PAYMENT DETECTED'));});});++ describe('Issue #4: Terminal State Invariants and Re-activation Guards', () => {+ let db;+ let sessionRepo;+ let obsRepo;+ let ticketRepo;+ let auditRepo;+ let customerRepo;+ let defaultMerchant;+ let receivingAccount;+ let attributionEngine;+ let emittedEvents;++ beforeEach(() => {+ db = new Database({ inMemory: true });+ const seed = runMigrations(db);+ defaultMerchant = seed.defaultMerchant;+ receivingAccount = { id: '00000000-0000-0000-0000-000000000002' };++ sessionRepo = new PaymentSessionRepository(db);+ obsRepo = new ObservationRepository(db);+ ticketRepo = new SupportTicketRepository(db);+ auditRepo = new AuditLogRepository(db);+ customerRepo = new CustomerRepository(db);++ emittedEvents = [];+ attributionEngine = new AttributionEngine({+ sessionRepo,+ obsRepo,+ ticketRepo,+ auditRepo,+ eventEmitter: {+ emit: (event, payload) => emittedEvents.push({ event, payload })+ }+ });+ });++ afterEach(() => {+ db.close();+ });+ test('strictly forbids all transitions out of terminal states in the state machine', () => {+ const terminalStates = [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ];++ const allStates = [+ PaymentStatus.INITIATED,+ PaymentStatus.QUEUED,+ PaymentStatus.ACTIVE,+ PaymentStatus.PROCESSING,+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ];++ for (const terminal of terminalStates) {+ for (const target of allStates) {+ assert.equal(+ isValidTransition(terminal, target),+ false,+ `Expected isValidTransition('${terminal}', '${target}') to be false`+ );+ assert.throws(+ () => assertValidTransition(terminal, target),+ /Illegal payment state transition/+ );+ }+ }+ });++ test('acquireSlotAtomic rejects sessions in terminal status', () => {+ const testCases = [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ];++ for (const status of testCases) {+ const session = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: `ORD-TERMINAL-${status}`,+ amountPaise: 50000n+ });++ if (status === PaymentStatus.CANCELLED) {+ sessionRepo.transitionToTerminal(session.id, PaymentStatus.CANCELLED);+ } else {+ sessionRepo.acquireSlotAtomic(session.id, receivingAccount.id);+ sessionRepo.transitionToTerminal(session.id, status);+ }++ const terminalSession = sessionRepo.findById(session.id);+ assert.equal(terminalSession.status, status);++ assert.throws(+ () => sessionRepo.acquireSlotAtomic(session.id, receivingAccount.id),+ /Cannot acquire slot for session in terminal status|Illegal payment state transition/+ );++ // Status must remain terminal in database+ const afterAttempt = sessionRepo.findById(session.id);+ assert.equal(afterAttempt.status, status);+ }+ });++ test('recordVerificationSource ignores terminal non-success sessions and preserves terminal status', () => {+ const terminalStatuses = [+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ];++ for (const status of terminalStatuses) {+ const session = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: `ORD-VERIFY-${status}`,+ amountPaise: 40000n+ });+ if (status === PaymentStatus.CANCELLED) {+ sessionRepo.transitionToTerminal(session.id, PaymentStatus.CANCELLED);+ } else {+ sessionRepo.acquireSlotAtomic(session.id, receivingAccount.id);+ sessionRepo.transitionToTerminal(session.id, status);+ }++ const res = sessionRepo.recordVerificationSource(session.id, ObserverSource.GMAIL, 'obs_fake_123', { finalizeSuccess: true });+ assert.equal(res.isFirstSuccess, false);++ // Status in database must still be the terminal status+ const unchanged = sessionRepo.findById(session.id);+ assert.equal(unchanged.status, status);+ }+ });++ test('transitionToProcessing rejects terminal sessions and non-active sessions', () => {+ // 1. INITIATED session rejects transition to PROCESSING+ const initiated = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-INITIATED',+ amountPaise: 15000n+ });+ assert.throws(+ () => sessionRepo.transitionToProcessing(initiated.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );++ // 2. QUEUED session rejects transition to PROCESSING+ const activeSess = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-ACTIVE',+ amountPaise: 15000n+ });+ sessionRepo.acquireSlotAtomic(activeSess.id, receivingAccount.id);++ const queuedSess = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-QUEUED',+ amountPaise: 15000n+ });+ sessionRepo.acquireSlotAtomic(queuedSess.id, receivingAccount.id);+ assert.equal(sessionRepo.findById(queuedSess.id).status, PaymentStatus.QUEUED);++ assert.throws(+ () => sessionRepo.transitionToProcessing(queuedSess.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );++ // 3. SUCCESS session rejects transition to PROCESSING+ sessionRepo.transitionToTerminal(activeSess.id, PaymentStatus.SUCCESS);+ assert.throws(+ () => sessionRepo.transitionToProcessing(activeSess.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );++ // 4. CANCELLED session rejects transition to PROCESSING+ const cancelled = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-CANCELLED',+ amountPaise: 15000n+ });+ sessionRepo.transitionToTerminal(cancelled.id, PaymentStatus.CANCELLED);+ assert.throws(+ () => sessionRepo.transitionToProcessing(cancelled.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );++ // 5. EXPIRED session rejects transition to PROCESSING+ const expired = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-EXPIRED',+ amountPaise: 15000n+ });+ sessionRepo.acquireSlotAtomic(expired.id, receivingAccount.id);+ sessionRepo.transitionToTerminal(expired.id, PaymentStatus.EXPIRED);+ assert.throws(+ () => sessionRepo.transitionToProcessing(expired.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );++ // 6. FAILED session rejects transition to PROCESSING+ const failed = sessionRepo.create({+ merchantId: defaultMerchant.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-PROC-FAILED',+ amountPaise: 15000n+ });+ sessionRepo.acquireSlotAtomic(failed.id, receivingAccount.id);+ sessionRepo.transitionToTerminal(failed.id, PaymentStatus.FAILED);+ assert.throws(+ () => sessionRepo.transitionToProcessing(failed.id),+ /Cannot transition to PROCESSING from status|Illegal payment state transition/+ );+ });+++ test('AttributionEngine does not revive expired session to SUCCESS and creates support ticket', () => {+ const customer = customerRepo.create({+ merchantId: defaultMerchant.id,+ phoneNumber: '9123456780',+ fullName: 'Late Paying User',+ password: 'Password9!'+ });++ const expiredSession = sessionRepo.create({+ merchantId: defaultMerchant.id,+ customerId: customer.id,+ receivingAccountId: receivingAccount.id,+ orderId: 'ORD-LATE-RECONCILE',+ amountPaise: 75000n+ });++ sessionRepo.acquireSlotAtomic(expiredSession.id, receivingAccount.id);+ sessionRepo.transitionToTerminal(expiredSession.id, PaymentStatus.EXPIRED);++ const lateObs = ObservationNormalizer.normalize({+ source: ObserverSource.GMAIL,+ receivingAccountId: receivingAccount.id,+ amountPaise: 75000n,+ bankReferenceNumber: 'UTR-LATE-999',+ observedAt: new Date(),+ rawPayload: { text: 'Bank alert Rs 750' }+ });++ const result = attributionEngine.processObservation(lateObs);++ assert.equal(result.attributed, false);+ assert.equal(result.lateMatch, true);+ assert.equal(result.paymentSessionId, expiredSession.id);+ assert.equal(result.outcomeStatus, ObservationAttributionStatus.LATE_UNMATCHED);++ // Verify the session status in DB is STILL EXPIRED (not SUCCESS)+ const freshSession = sessionRepo.findById(expiredSession.id);+ assert.equal(freshSession.status, PaymentStatus.EXPIRED);++ // Verify support ticket was created+ const tickets = ticketRepo.findTicketsByCustomer(customer.id);+ assert.ok(tickets.length >= 1);+ const ticket = tickets.find(t => t.paymentId === expiredSession.id);+ assert.ok(ticket);+ assert.ok(ticket.subject.includes('[LATE PAYMENT DETECTED]'));++ // Verify PAYMENT.LATE_DETECTED was emitted and not PAYMENT.SUCCESS+ const lateEvents = emittedEvents.filter(e => e.event === 'PAYMENT.LATE_DETECTED' && e.payload.paymentId === expiredSession.id);+ assert.equal(lateEvents.length, 1);+ const successEvents = emittedEvents.filter(e => e.event === 'PAYMENT.SUCCESS' && e.payload.paymentId === expiredSession.id);+ assert.equal(successEvents.length, 0);+ });+ });});diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex 66cf6eb..9a2bf86 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -1,4 +1,4 @@-import { PaymentStatus, ObservationAttributionStatus, TicketStatus, SenderType } from '@youpi/common';+import { PaymentStatus, ObservationAttributionStatus, TicketStatus, SenderType, isTerminalStatus } from '@youpi/common';export class AttributionEngine {/**@@ -79,6 +79,55 @@ export class AttributionEngine {// If observation came from a NEW, DIFFERENT channel and payment was already attributed:// Upgrade verification tier to Level 2 (Dual Verification)!if (existing.attributedPaymentId) {+ const targetSession = this.sessionRepo.findById(existing.attributedPaymentId);+ if (targetSession && isTerminalStatus(targetSession.status) && targetSession.status !== PaymentStatus.SUCCESS) {+ const savedObs = this.obsRepo.create(normalizedObs);+ this.obsRepo.markLateUnmatched(savedObs.id);+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: targetSession.merchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: targetSession.id,+ action: 'LATE_OBSERVATION_DETECTED',+ actorType: 'SYSTEM',+ details: {+ observationId: savedObs.id,+ source: normalizedObs.source,+ sessionStatus: targetSession.status+ }+ });+ }+ if (this.ticketRepo && targetSession.customerId) {+ this.ticketRepo.createTicket({+ merchantId: targetSession.merchantId,+ customerId: targetSession.customerId,+ paymentId: targetSession.id,+ subject: `[LATE PAYMENT DETECTED] Order #${targetSession.orderId}`,+ status: TicketStatus.OPEN,+ initialMessage: {+ senderType: SenderType.ADMIN,+ senderId: targetSession.merchantId,+ message: `A delayed payment observation of ${normalizedObs.amountPaise / 100n} INR was detected after session ${targetSession.id} ended with status ${targetSession.status}. Flagged for manual merchant reconciliation.`+ }+ });+ }+ this.eventEmitter.emit('PAYMENT.LATE_DETECTED', {+ paymentId: targetSession.id,+ orderId: targetSession.orderId,+ merchantId: targetSession.merchantId,+ amountPaise: normalizedObs.amountPaise,+ observationId: savedObs.id+ });+ return {+ attributed: false,+ duplicate: false,+ lateMatch: true,+ paymentSessionId: targetSession.id,+ observationId: savedObs.id,+ outcomeStatus: ObservationAttributionStatus.LATE_UNMATCHED+ };+ }+// Cancel pending 5-second grace timer if anyconst pendingTimer = this.pendingGraceTimers.get(existing.attributedPaymentId);if (pendingTimer) {@@ -358,6 +407,53 @@ export class AttributionEngine {const graceTimer = setTimeout(() => {this.pendingGraceTimers.delete(targetSessionId);+ // Check if session became terminal during the grace window+ const latestSession = this.sessionRepo.findById(targetSessionId);+ if (!latestSession || (isTerminalStatus(latestSession.status) && latestSession.status !== PaymentStatus.SUCCESS)) {+ const sessionStatus = latestSession ? latestSession.status : 'EXPIRED';+ this.obsRepo.markLateUnmatched(targetObsId);+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: targetMerchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: targetSessionId,+ action: 'LATE_OBSERVATION_DETECTED',+ actorType: 'SYSTEM',+ details: {+ observationId: targetObsId,+ source: targetSource,+ sessionStatus+ }+ });+ }+ if (this.ticketRepo && latestSession?.customerId) {+ this.ticketRepo.createTicket({+ merchantId: targetMerchantId,+ customerId: latestSession.customerId,+ paymentId: targetSessionId,+ subject: `[LATE PAYMENT DETECTED] Order #${targetOrderId}`,+ status: TicketStatus.OPEN,+ initialMessage: {+ senderType: SenderType.ADMIN,+ senderId: targetMerchantId,+ message: `A delayed payment observation of ${targetAmountPaise / 100n} INR was detected after session ${targetSessionId} ended with status ${sessionStatus}. Flagged for manual merchant reconciliation.`+ }+ });+ }+ this.eventEmitter.emit('PAYMENT.LATE_DETECTED', {+ paymentId: targetSessionId,+ orderId: targetOrderId,+ merchantId: targetMerchantId,+ amountPaise: targetAmountPaise,+ observationId: targetObsId+ });+ return;+ }++ if (latestSession.status === PaymentStatus.SUCCESS) {+ return;+ }+// 5 seconds elapsed without second source: finalize as Level 1const finalResult = this.sessionRepo.recordVerificationSource(targetSessionId,diff --git a/packages/db/src/repositories/customer.repository.js b/packages/db/src/repositories/customer.repository.jsindex 5e3a90e..3679220 100644--- a/packages/db/src/repositories/customer.repository.js+++ b/packages/db/src/repositories/customer.repository.js@@ -277,31 +277,41 @@ export class CustomerRepository {*/banCustomer(id, reason = 'FRAUDULENT_PAYMENT_INJECTION', options = {}) {if (!id) return null;- const now = new Date().toISOString();- const lastDevice = options.lastDevice || options.deviceInfo || null;- this.db.execute(- "UPDATE customers SET status = 'BANNED', ban_reason = ?, banned_at = ?, last_device = COALESCE(?, last_device), updated_at = ? WHERE id = ?",- [reason, now, lastDevice, now, id]- );-- // Immediately transition all existing non-terminal sessions for this customer to EXPIRED (Section 10, Test 18)- const activeSessions = this.db.query(- "SELECT id, receiving_account_id FROM payment_sessions WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",- [id]- );- if (activeSessions.length > 0) {+ const releasedAccounts = [];+ this.db.transaction(() => {+ const now = new Date().toISOString();+ const lastDevice = options.lastDevice || options.deviceInfo || null;this.db.execute(- "UPDATE payment_sessions SET status = 'EXPIRED', updated_at = ? WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",- [now, id]+ "UPDATE customers SET status = 'BANNED', ban_reason = ?, banned_at = ?, last_device = COALESCE(?, last_device), updated_at = ? WHERE id = ?",+ [reason, now, lastDevice, now, id]);- for (const s of activeSessions) {- if (s.receiving_account_id) {- this.db.execute(- "UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ? AND current_active_session_id = ?",- [s.receiving_account_id, s.id]- );++ // Immediately transition all existing non-terminal sessions for this customer to EXPIRED+ const activeSessions = this.db.query(+ "SELECT id, receiving_account_id FROM payment_sessions WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",+ [id]+ );+ if (activeSessions.length > 0) {+ this.db.execute(+ "UPDATE payment_sessions SET status = 'EXPIRED', completed_at = ?, updated_at = ? WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",+ [now, now, id]+ );+ for (const s of activeSessions) {+ if (s.receiving_account_id) {+ this.db.execute(+ "UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ? WHERE id = ? AND current_active_session_id = ?",+ [now, s.receiving_account_id, s.id]+ );+ releasedAccounts.push(s.receiving_account_id);+ }}}+ });++ if (options.queueEngine && typeof options.queueEngine.promoteNext === 'function') {+ for (const accountId of releasedAccounts) {+ options.queueEngine.promoteNext(accountId);+ }}return this.findById(id);