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
feat(payments): separate observer matches from statement reconciliation
Mani Kf1d25b159bb5
diff --git a/apps/android-observer-app/__tests__/android-observer.test.js b/apps/android-observer-app/__tests__/android-observer.test.jsindex f59161e..7d2df68 100644--- a/apps/android-observer-app/__tests__/android-observer.test.js+++ b/apps/android-observer-app/__tests__/android-observer.test.js@@ -88,11 +88,11 @@ describe('Android Payment Observer Integration Tests', () => {assert.equal(res.body.accepted, true);assert.equal(res.body.attribution.attributed, true);assert.equal(res.body.attribution.paymentSessionId, session.id);- assert.equal(res.body.attribution.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(res.body.attribution.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);// 3. Verify session in DB updated to SUCCESSconst updated = apiInstance.app.context.sessionRepo.findById(session.id);- assert.equal(updated.status, PaymentStatus.SUCCESS);+ assert.equal(updated.status, PaymentStatus.OBSERVED_SUCCESS);});test('Issue #61: rejects notification observation when rawNotification has missing or empty package', async () => {diff --git a/apps/checkout-portal/src/sdk/youpi-checkout.js b/apps/checkout-portal/src/sdk/youpi-checkout.jsindex 121471f..3dc1d13 100644--- a/apps/checkout-portal/src/sdk/youpi-checkout.js+++ b/apps/checkout-portal/src/sdk/youpi-checkout.js@@ -428,6 +428,29 @@}});}, 1500);+ } else if (event === 'youpi.payment_observed' || event === 'youpi.payment_reconciled' || event === 'youpi.payment_manual_review') {+ const payload = e.data.data || {};+ const status = event === 'youpi.payment_reconciled'+ ? 'RECONCILED'+ : (event === 'youpi.payment_manual_review' ? 'MANUAL_REVIEW' : 'OBSERVED_SUCCESS');+ const result = {+ status,+ order_id: payload.orderId || this.options.orderId || this.options.order_id,+ payment_mode: payload.method || 'UPI',+ amount_received: Number(payload.amount || this.options.amount || 0),+ utr: payload.bankRef || payload.utr || payload.reference || '',+ timestamp: payload.completedAt || new Date().toISOString(),+ metadata: payload.metadata || this.options.metadata || {},+ settlement_state: payload.settlementState || (status === 'RECONCILED' ? 'RECONCILED' : (status === 'MANUAL_REVIEW' ? 'MANUAL_REVIEW' : 'NOT_RECONCILED')),+ raw: payload+ };+ const domEvent = status === 'RECONCILED'+ ? 'youpi:payment:success'+ : (status === 'MANUAL_REVIEW' ? 'youpi:payment:suspicious' : 'youpi:payment:observed');+ YoupiCheckout._emitEvent(domEvent, result);+ YoupiCheckout._emitEvent('youpi:payment:result', result);+ if (typeof this.options.handler === 'function') this.options.handler(result);+ if (status === 'RECONCILED' && typeof this.options.onSuccess === 'function') this.options.onSuccess(result);} else if (event === 'youpi.payment_failed') {const payload = e.data.data || e.data || {};const result = {diff --git a/apps/checkout-portal/src/sdk/youpi.js b/apps/checkout-portal/src/sdk/youpi.jsindex 3e0fede..1616905 100644--- a/apps/checkout-portal/src/sdk/youpi.js+++ b/apps/checkout-portal/src/sdk/youpi.js@@ -426,6 +426,29 @@}});}, 1500);+ } else if (event === 'youpi.payment_observed' || event === 'youpi.payment_reconciled' || event === 'youpi.payment_manual_review') {+ const payload = e.data.data || {};+ const status = event === 'youpi.payment_reconciled'+ ? 'RECONCILED'+ : (event === 'youpi.payment_manual_review' ? 'MANUAL_REVIEW' : 'OBSERVED_SUCCESS');+ const result = {+ status,+ order_id: payload.orderId || this.options.orderId || this.options.order_id,+ payment_mode: payload.method || 'UPI',+ amount_received: Number(payload.amount || this.options.amount || 0),+ utr: payload.bankRef || payload.utr || payload.reference || '',+ timestamp: payload.completedAt || new Date().toISOString(),+ metadata: payload.metadata || this.options.metadata || {},+ settlement_state: payload.settlementState || (status === 'RECONCILED' ? 'RECONCILED' : (status === 'MANUAL_REVIEW' ? 'MANUAL_REVIEW' : 'NOT_RECONCILED')),+ raw: payload+ };+ const domEvent = status === 'RECONCILED'+ ? 'youpi:payment:success'+ : (status === 'MANUAL_REVIEW' ? 'youpi:payment:suspicious' : 'youpi:payment:observed');+ YoupiCheckout._emitEvent(domEvent, result);+ YoupiCheckout._emitEvent('youpi:payment:result', result);+ if (typeof this.options.handler === 'function') this.options.handler(result);+ if (status === 'RECONCILED' && typeof this.options.onSuccess === 'function') this.options.onSuccess(result);} else if (event === 'youpi.payment_failed') {const payload = e.data.data || e.data || {};const result = {diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.htmlindex 0e40a14..6caae6e 100644--- a/apps/checkout-portal/src/views/checkout.html+++ b/apps/checkout-portal/src/views/checkout.html@@ -1857,7 +1857,7 @@}// --- 2. TERMINAL PAYMENT STATES (TERMINAL & OVER) ---- if (['SUCCESS', 'CANCELLED', 'EXPIRED', 'FAILED'].includes(data.status)) {+ if (['SUCCESS', 'OBSERVED_SUCCESS', 'RECONCILED', 'MANUAL_REVIEW', 'CANCELLED', 'EXPIRED', 'FAILED'].includes(data.status)) {if (queuePollTimer) { clearInterval(queuePollTimer); queuePollTimer = null; }if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }setGatewayAuthMode(false);@@ -1933,7 +1933,27 @@return;}- if (data.status === 'SUCCESS') {+ if (data.status === 'MANUAL_REVIEW') {+ closeProcessingModal();+ closeCancelPaymentModal();+ const bar = document.getElementById('paymentMethodSelectorBar');+ if (bar) bar.style.display = 'none';+ hideAllContent();+ const failedView = document.getElementById('viewFailedContent');+ if (failedView) failedView.hidden = false;+ const footer = document.getElementById('ypgStickyFooter');+ if (footer) footer.style.display = 'none';+ const titleEl = document.getElementById('failedTitleText');+ if (titleEl) titleEl.textContent = 'Payment held for review';+ const descEl = document.getElementById('failedDescriptionText');+ if (descEl) descEl.textContent = 'This alert matched more than one payment, or it was flagged. It is not confirmed and no order should be fulfilled yet.';+ try {+ postToMerchant({ event: 'youpi.payment_manual_review', data: data });+ } catch (e) { }+ return;+ }++ if (data.status === 'SUCCESS' || data.status === 'OBSERVED_SUCCESS' || data.status === 'RECONCILED') {closeProcessingModal();closeCancelPaymentModal();const bar = document.getElementById('paymentMethodSelectorBar');@@ -1960,17 +1980,28 @@codApiBox.style.display = 'block';codApiUrl.textContent = `${API_BASE}/api/v1/orders/${data.orderId}/cod`;}+ } else if (data.status === 'OBSERVED_SUCCESS') {+ if (titleEl) titleEl.textContent = 'Payment observed';+ if (descEl) descEl.textContent = 'A bank alert matched this payment. It is not confirmed against a bank statement yet.';+ if (codApiBox) codApiBox.style.display = 'none';+ } else if (data.status === 'RECONCILED') {+ if (titleEl) titleEl.textContent = 'Payment reconciled';+ if (descEl) descEl.textContent = 'This payment was matched to a bank statement.';+ if (codApiBox) codApiBox.style.display = 'none';} else {if (titleEl) titleEl.textContent = 'Payment Successful!';if (descEl) descEl.textContent = 'Your payment was automatically verified by YouPI PG banking observers.';if (codApiBox) codApiBox.style.display = 'none';}- emitTriggerHook('PAYMENT_COMPLETED', { amount: data.amount, method: data.method, isCod: isCodOrder });+ emitTriggerHook('PAYMENT_COMPLETED', { amount: data.amount, method: data.method, isCod: isCodOrder, status: data.status });try {+ const merchantEvent = data.status === 'OBSERVED_SUCCESS'+ ? 'youpi.payment_observed'+ : (data.status === 'RECONCILED' ? 'youpi.payment_reconciled' : 'youpi.payment_success');postToMerchant({- event: 'youpi.payment_success',+ event: merchantEvent,data: data});} catch (e) { }@@ -2701,7 +2732,7 @@// Continuous 2-second fallback polling: guarantees instant response when cashier confirms/declines or queues clearsetInterval(() => {- if (state && (state.status === 'SUCCESS' || state.status === 'FAILED' || state.status === 'EXPIRED' || state.status === 'BLOCKED' || state.isBanned)) {+ if (state && (state.status === 'SUCCESS' || state.status === 'OBSERVED_SUCCESS' || state.status === 'RECONCILED' || state.status === 'MANUAL_REVIEW' || state.status === 'FAILED' || state.status === 'EXPIRED' || state.status === 'BLOCKED' || state.isBanned)) {return;}loadState();diff --git a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.jsindex f9317c2..418075f 100644--- a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js+++ b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js@@ -113,7 +113,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {assert.ok(checkoutRes.body.checkoutUrl.includes('/checkout/'));});- test('POST /api/webhook processes signed SUCCESS event and credits wallet coins', async () => {+ test('POST /api/webhook credits coins only on a signed RECONCILED event', async () => {const initialCoins = storeInstance.server.walletCoins;storeInstance.server.orders.set('COIN-ORD-555', {@@ -126,8 +126,27 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {});storeInstance.server.orderPayments.set('COIN-ORD-555', 'pay_coin_test_123');+ const observed = JSON.stringify({+ event: 'OBSERVED_SUCCESS',+ paymentId: 'pay_coin_test_123',+ orderId: 'COIN-ORD-555',+ amount: '449.00',+ amountPaise: 44900,+ currency: 'INR',+ method: 'UPI'+ });+ const observedRes = await request('/api/webhook', {+ method: 'POST',+ headers: gatewayHeaders(observed),+ body: observed+ });+ assert.equal(observedRes.status, 200);+ assert.equal(observedRes.body.credited, false);+ assert.equal(observedRes.body.settlementState, 'NOT_RECONCILED');+ assert.equal(storeInstance.server.walletCoins, initialCoins);+const payloadObj = {- event: 'SUCCESS',+ event: 'RECONCILED',paymentId: 'pay_coin_test_123',orderId: 'COIN-ORD-555',amount: '449.00',@@ -166,7 +185,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {// 1. Unknown orderId rejected with 404const unknownPayload = JSON.stringify({- event: 'SUCCESS',+ event: 'RECONCILED',paymentId: 'pay_unknown_999',orderId: 'COIN-ORD-UNKNOWN-999',amount: '1.00',@@ -192,7 +211,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {const { orderId, paymentId } = checkout.body;const mismatchPayload = JSON.stringify({- event: 'SUCCESS',+ event: 'RECONCILED',paymentId,orderId,amount: '1.00',@@ -211,7 +230,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {// 3. Matching amountPaise credits local order.coins (10), ignoring inflated metadata.coins (99999)const validPayload = JSON.stringify({- event: 'SUCCESS',+ event: 'RECONCILED',paymentId,orderId,amount: '10.00',@@ -271,7 +290,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {// Simulate signed webhook receiptconst payloadObj = {- event: 'SUCCESS',+ event: 'RECONCILED',paymentId: checkoutRes.body.paymentId,orderId,amount: '250.00',@@ -313,7 +332,7 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {const orderId = checkoutRes.body.orderId;const payloadObj = {- event: 'SUCCESS',+ event: 'RECONCILED',paymentId: checkoutRes.body.paymentId,orderId,amount: '1.00',@@ -376,28 +395,26 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {assert.equal(storeInstance.server.walletCoins, before);});- test('POST /api/verify-payment credits coins only after the gateway reports SUCCESS, and is idempotent', async () => {+ test('POST /api/verify-payment never grants coins from a browser callback', async () => {const initialCoins = storeInstance.server.walletCoins;const checkout = await request('/api/checkout', { method: 'POST', body: { price: 100, coins: 100, packName: 'Starter Pack' } });assert.equal(checkout.status, 200);const { orderId, paymentId } = checkout.body;- // Simulate the gateway verification engine completing this UPI payment.testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', method = 'UPI' WHERE id = ?", [paymentId]);-- const verifyRes = await request('/api/verify-payment', {+ const successRes = await request('/api/verify-payment', {method: 'POST',body: { orderId, coins: 999999, packName: 'Ignored' }});- assert.equal(verifyRes.status, 200);- assert.equal(verifyRes.body.success, true);- // Client-supplied coin counts are ignored: the gateway session metadata wins.- assert.equal(storeInstance.server.walletCoins, initialCoins + 100);-- const dupRes = await request('/api/verify-payment', { method: 'POST', body: { orderId } });- assert.equal(dupRes.status, 200);- assert.equal(dupRes.body.message, 'Already credited');- assert.equal(storeInstance.server.walletCoins, initialCoins + 100);+ assert.equal(successRes.status, 202);+ assert.equal(successRes.body.credited, false);+ assert.equal(storeInstance.server.walletCoins, initialCoins);++ testDb.execute("UPDATE payment_sessions SET status = 'RECONCILED', method = 'UPI' WHERE id = ?", [paymentId]);+ const reconciledRes = await request('/api/verify-payment', { method: 'POST', body: { orderId } });+ assert.equal(reconciledRes.status, 202);+ assert.equal(reconciledRes.body.credited, false);+ assert.equal(storeInstance.server.walletCoins, initialCoins);});test('GET /order-success renders verified payment page with parameters', async () => {diff --git a/apps/coin-wallet-store/src/server.js b/apps/coin-wallet-store/src/server.jsindex 5ab5d11..5e967e7 100644--- a/apps/coin-wallet-store/src/server.js+++ b/apps/coin-wallet-store/src/server.js@@ -2,6 +2,7 @@ import http from 'node:http';import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { DatabaseSync } from 'node:sqlite';import { YoupiPaymentClient } from '@youpi/merchant-sdk';import { getCoinStoreWebhookSecret } from '@youpi/common';@@ -109,11 +110,15 @@ export class CoinWalletStoreServer {// orderId -> gateway paymentId for orders this store created (used to verify payments server-side)this.orderPayments = new Map();- // orderId -> { orderId, paymentId, amountPaise, coins, packName, createdAt }this.orders = new Map();- // Recently processed X-Gateway-Delivery-Id values, used to reject replayed webhooks.- this.seenDeliveryIds = new Map();+ const underTest = process.env.NODE_ENV === 'test' || Boolean(process.env.NODE_TEST_CONTEXT);+ this.idempotencyPath = options.idempotencyPath+ || process.env.COIN_STORE_IDEMPOTENCY_PATH+ || (underTest+ ? ':memory:'+ : path.resolve(__dirname, '../../../data/coin-wallet-fulfillment.sqlite'));+ this.openFulfillmentLedger();this.paymentClient = new YoupiPaymentClient({apiUrl: this.gatewayApiUrl,@@ -121,9 +126,9 @@ export class CoinWalletStoreServer {webhookSecret: this.webhookSecret});- // In-memory persistent wallet balance & ledger for demo store- this.walletCoins = 50; // default starting balance- this.transactionHistory = [];+ // Starting balance plus durable reconciled grants. Observer matches do not add coins.+ this.walletCoins = 50 + this.sumClaimedCoins();+ this.transactionHistory = this.loadClaimHistory();this.storeHtml = fs.readFileSync(path.join(__dirname, 'store.html'), 'utf8');this.walletHtml = fs.readFileSync(path.join(__dirname, 'wallet.html'), 'utf8');@@ -134,6 +139,93 @@ export class CoinWalletStoreServer {this.orderCancelledHtml = fs.readFileSync(path.join(__dirname, 'order-cancelled.html'), 'utf8');}+ openFulfillmentLedger() {+ if (this.idempotencyPath !== ':memory:') {+ fs.mkdirSync(path.dirname(this.idempotencyPath), { recursive: true });+ }+ this.ledger = new DatabaseSync(this.idempotencyPath);+ this.ledger.exec(`+ CREATE TABLE IF NOT EXISTS webhook_receipts (+ delivery_id TEXT PRIMARY KEY,+ event_type TEXT NOT NULL,+ order_id TEXT,+ created_at TEXT NOT NULL+ );+ CREATE TABLE IF NOT EXISTS fulfillment_claims (+ order_id TEXT PRIMARY KEY,+ delivery_id TEXT UNIQUE,+ payment_id TEXT,+ amount_paise INTEGER NOT NULL,+ coins INTEGER NOT NULL,+ pack_name TEXT,+ created_at TEXT NOT NULL+ );+ `);+ }++ sumClaimedCoins() {+ const row = this.ledger.prepare('SELECT COALESCE(SUM(coins), 0) AS total FROM fulfillment_claims').get();+ return Number(row?.total || 0);+ }++ loadClaimHistory() {+ const rows = this.ledger.prepare(+ 'SELECT order_id, coins, pack_name, created_at FROM fulfillment_claims ORDER BY created_at DESC'+ ).all();+ return rows.map(row => ({+ orderId: row.order_id,+ coins: row.coins,+ packName: row.pack_name || 'Coin Pack',+ status: 'CREDITED',+ timestamp: row.created_at+ }));+ }++ receiptSeen(deliveryId) {+ if (!deliveryId) return false;+ return Boolean(this.ledger.prepare('SELECT delivery_id FROM webhook_receipts WHERE delivery_id = ?').get(deliveryId));+ }++ noteReceipt(deliveryId, eventType, orderId) {+ if (!deliveryId) return;+ this.ledger.prepare(+ 'INSERT OR IGNORE INTO webhook_receipts (delivery_id, event_type, order_id, created_at) VALUES (?, ?, ?, ?)'+ ).run(deliveryId, String(eventType || ''), orderId || null, new Date().toISOString());+ }++ /**+ * Durable once-only grant. A second delivery id or a process restart cannot grant again.+ * @returns {{ claimed: boolean }}+ */+ claimFulfillment({ orderId, deliveryId, paymentId, amountPaise, coins, packName }) {+ this.ledger.exec('BEGIN IMMEDIATE');+ try {+ const existing = this.ledger.prepare('SELECT order_id FROM fulfillment_claims WHERE order_id = ?').get(orderId);+ if (existing) {+ this.ledger.exec('ROLLBACK');+ return { claimed: false };+ }+ this.ledger.prepare(`+ INSERT INTO fulfillment_claims (order_id, delivery_id, payment_id, amount_paise, coins, pack_name, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ `).run(+ orderId,+ deliveryId || null,+ paymentId || null,+ Number(amountPaise),+ Number(coins),+ packName || 'Coin Pack',+ new Date().toISOString()+ );+ this.ledger.exec('COMMIT');+ return { claimed: true };+ } catch (err) {+ try { this.ledger.exec('ROLLBACK'); } catch {}+ if (String(err.message || '').includes('UNIQUE')) return { claimed: false };+ throw err;+ }+ }+creditCoins(orderId, coins, packName) {this.walletCoins += Number(coins);this.transactionHistory.unshift({@@ -145,13 +237,9 @@ export class CoinWalletStoreServer {});}- /** Records a processed delivery id and prunes entries older than the accepted skew window. */+ /** Records a processed delivery id. Kept for callers; persistence is the ledger. */rememberDeliveryId(deliveryId) {- const now = Date.now();- for (const [id, seenAt] of this.seenDeliveryIds) {- if (now - seenAt > WEBHOOK_MAX_SKEW_MS * 2) this.seenDeliveryIds.delete(id);- }- this.seenDeliveryIds.set(deliveryId, now);+ this.noteReceipt(deliveryId, 'SEEN', null);}createServer() {@@ -563,7 +651,7 @@ export class CoinWalletStoreServer {return;}- if (!session || session.status !== 'SUCCESS' || session.method !== 'UPI') {+ if (!session || session.method !== 'UPI') {sendJson(402, { error: 'Payment not completed', status: session?.status || 'UNKNOWN' });return;}@@ -577,33 +665,26 @@ export class CoinWalletStoreServer {}const orderId = session.orderId;- if (this.transactionHistory.some(t => t.orderId === orderId)) {- sendJson(200, { success: true, coins: this.walletCoins, message: 'Already credited' });+ const existingClaim = this.ledger.prepare('SELECT coins FROM fulfillment_claims WHERE order_id = ?').get(orderId);+ if (existingClaim) {+ sendJson(200, { success: true, coins: this.walletCoins, credited: false, message: 'Already credited' });return;}- // Always derive credited coins from the authoritative local order record (or paid amountPaise),- // never from untrusted client parameters or out-of-band metadata.- const paidPaise = Number(localOrder?.amountPaise ?? session.amountPaise);- const derivedFromAmount = Number.isFinite(paidPaise) && paidPaise > 0- ? Math.min(Math.max(1, Math.round(paidPaise / 100)), MAX_TOPUP_RUPEES)- : 1;- const creditedCoins = localOrder ? localOrder.coins : derivedFromAmount;- const finalPackName = sanitizePackName(localOrder?.packName || session.metadata?.packName || 'Coin Pack');-- this.creditCoins(orderId, creditedCoins, finalPackName);- console.log(`[Coin Wallet Store] Verified & credited ${creditedCoins} coins for Order ${orderId}. New balance: ${this.walletCoins}`);+ const closedEvidence = ['OBSERVED_SUCCESS', 'SUCCESS', 'RECONCILED', 'MANUAL_REVIEW'].includes(session.status);+ if (!closedEvidence) {+ sendJson(402, { error: 'Payment not completed', status: session.status, credited: false });+ return;+ }- res.writeHead(200, {- 'Content-Type': 'application/json',- 'Access-Control-Allow-Origin': '*'+ // The browser callback is never a grant. Coins move only on a signed RECONCILED webhook.+ sendJson(202, {+ success: false,+ credited: false,+ status: session.status,+ settlementState: session.status === 'RECONCILED' ? 'RECONCILED_AWAITING_WEBHOOK' : 'NOT_RECONCILED',+ error: 'Browser confirmation does not grant coins. Coins are granted only from a signed RECONCILED webhook.'});- res.end(JSON.stringify({- success: true,- coins: this.walletCoins,- credited: creditedCoins,- packName: finalPackName- }));} catch (err) {res.writeHead(500, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ error: err.message }));@@ -631,17 +712,16 @@ export class CoinWalletStoreServer {const deliveryId = req.headers['x-gateway-delivery-id'] || '';const timestamp = req.headers['x-gateway-timestamp'] || '';- // Reject a replayed delivery. Without this, one captured request can be resent- // indefinitely and re-credited after the in-memory dedupe is lost on restart.+ // Reject a replayed delivery. The receipt row survives process restarts.const ts = Number(timestamp);if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > WEBHOOK_MAX_SKEW_MS) {res.writeHead(401, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ error: 'Webhook timestamp missing or outside the accepted window.' }));return;}- if (deliveryId && this.seenDeliveryIds.has(deliveryId)) {+ if (deliveryId && this.receiptSeen(deliveryId)) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ received: true, duplicate: true }));+ res.end(JSON.stringify({ received: true, duplicate: true, credited: false }));return;}@@ -653,36 +733,72 @@ export class CoinWalletStoreServer {});const paidMethod = event.method || event.data?.method;- // COD / counter 'SUCCESS' means an order was placed, not that money arrived.- if ((event.event === 'SUCCESS' || event.status === 'SUCCESS') && paidMethod === 'UPI') {- const orderId = event.orderId || event.data?.orderId;+ const eventName = event.event || event.status;+ const orderId = event.orderId || event.data?.orderId;+ const currency = event.currency || event.data?.currency || 'INR';+ if (deliveryId) this.noteReceipt(deliveryId, eventName, orderId);++ // UPI SUCCESS and OBSERVED_SUCCESS are observer evidence. They do not grant coins.+ if ((eventName === 'SUCCESS' || eventName === 'OBSERVED_SUCCESS') && paidMethod === 'UPI') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ received: true, credited: false, settlementState: 'NOT_RECONCILED' }));+ return;+ }++ // Coins move only after a signed RECONCILED webhook for the same order, amount, and payment.+ if (eventName === 'RECONCILED' && paidMethod === 'UPI') {const localOrder = orderId ? this.orders.get(orderId) : undefined;if (!localOrder && (!orderId || !this.orderPayments.has(orderId))) {res.writeHead(404, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ error: 'Unknown order' }));return;}+ if (currency !== 'INR') {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Webhook currency is not INR' }));+ return;+ }const eventAmountPaise = Number(event.amountPaise ?? event.data?.amountPaise);if (localOrder && (!Number.isFinite(eventAmountPaise) || eventAmountPaise !== Number(localOrder.amountPaise))) {res.writeHead(400, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ error: 'Webhook amount does not match order' }));return;}+ const eventPaymentId = event.paymentId || event.data?.paymentId;+ if (localOrder?.paymentId && eventPaymentId && eventPaymentId !== localOrder.paymentId) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Webhook paymentId does not match order' }));+ return;+ }- const alreadyCredited = this.transactionHistory.some(t => t.orderId === orderId);- if (!alreadyCredited) {- const coinsToAdd = localOrder- ? localOrder.coins- : Math.min(Math.max(1, Math.round(eventAmountPaise / 100)), MAX_TOPUP_RUPEES);- const packName = sanitizePackName(localOrder?.packName || event.metadata?.packName || event.data?.metadata?.packName);+ const coinsToAdd = localOrder+ ? localOrder.coins+ : Math.min(Math.max(1, Math.round(eventAmountPaise / 100)), MAX_TOPUP_RUPEES);+ const packName = sanitizePackName(localOrder?.packName || event.metadata?.packName || event.data?.metadata?.packName);+ const claim = this.claimFulfillment({+ orderId,+ deliveryId: deliveryId || null,+ paymentId: eventPaymentId || localOrder?.paymentId || null,+ amountPaise: eventAmountPaise,+ coins: coinsToAdd,+ packName+ });+ if (claim.claimed) {this.creditCoins(orderId, coinsToAdd, packName);- console.log(`[Coin Wallet Store] Webhook received! Credited ${coinsToAdd} coins for Order ${orderId}. New balance: ${this.walletCoins}`);+ console.log(`[Coin Wallet Store] Reconciled webhook credited ${coinsToAdd} coins for Order ${orderId}. New balance: ${this.walletCoins}`);}+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ received: true,+ credited: claim.claimed,+ duplicate: !claim.claimed,+ settlementState: 'RECONCILED'+ }));+ return;}- if (deliveryId) this.rememberDeliveryId(deliveryId);res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ received: true, credited: true }));+ res.end(JSON.stringify({ received: true, credited: false }));} catch (err) {console.error('[Coin Wallet Store] Webhook verification failed:', err.message);res.writeHead(401, { 'Content-Type': 'application/json' });diff --git a/apps/gmail-observer/src/__tests__/gmail-observer.test.js b/apps/gmail-observer/src/__tests__/gmail-observer.test.jsindex 93a18d6..fdb7229 100644--- a/apps/gmail-observer/src/__tests__/gmail-observer.test.js+++ b/apps/gmail-observer/src/__tests__/gmail-observer.test.js@@ -145,7 +145,7 @@ describe('Gmail Payment Observer Integration Tests', () => {// Verify session updated to SUCCESS in DBconst updated = apiInstance.app.context.sessionRepo.findById(session.id);- assert.equal(updated.status, PaymentStatus.SUCCESS);+ assert.equal(updated.status, PaymentStatus.OBSERVED_SUCCESS);});});});diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex 981401d..df11c62 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -4437,7 +4437,7 @@let dualVerify = 0;payments.forEach(p => {- if (p.status === 'SUCCESS') {+ if (p.status === 'RECONCILED' || p.status === 'SUCCESS') {successCount++;successVol += Number(p.amountPaise);if (p.verificationLevel >= 2) dualVerify++;@@ -4625,7 +4625,7 @@tbody.innerHTML = (data.payments || []).map(p => {let verifyBadge = '<span style="color:var(--text-muted); font-size:0.75rem;">-</span>';- if (p.status === 'SUCCESS') {+ if (p.status === 'SUCCESS' || p.status === 'OBSERVED_SUCCESS' || p.status === 'RECONCILED' || p.status === 'MANUAL_REVIEW') {const tag = p.verificationTag || (p.verificationLevel >= 2 ? 'Dual Verification' : 'Single Verification');if (p.verificationLevel >= 2) {verifyBadge = `<span class="badge badge-success">✓✓ ${escapeHtmlValue(tag)}</span>`;@@ -4644,7 +4644,7 @@<td><code>${p.id}</code></td><td>₹${(Number(p.amountPaise) / 100).toFixed(2)}</td><td>${escapeHtmlValue(p.method)}</td>- <td><span class="badge ${p.status === 'SUCCESS' ? 'badge-success' : (p.status === 'ACTIVE' ? 'badge-info' : 'badge-danger')}">${escapeHtmlValue(p.status)}</span></td>+ <td><span class="badge ${p.status === 'RECONCILED' || p.status === 'SUCCESS' ? 'badge-success' : (p.status === 'OBSERVED_SUCCESS' ? 'badge-warning' : (p.status === 'MANUAL_REVIEW' ? 'badge-danger' : (p.status === 'ACTIVE' ? 'badge-info' : 'badge-danger')))}">${escapeHtmlValue(p.status === 'OBSERVED_SUCCESS' ? 'Observed (not reconciled)' : p.status)}</span></td><td>${verifyBadge}</td><td>${sourcesChips}</td><td>${escapeHtmlValue(new Date(p.createdAt).toLocaleTimeString())}</td>@@ -6751,7 +6751,9 @@let badgeBg = '#1e293b';if (s.status === 'ACTIVE') { badgeColor = '#0f172a'; badgeBg = '#22c55e'; }else if (s.status === 'PROCESSING') { badgeColor = '#0f172a'; badgeBg = '#fbbf24'; }- else if (s.status === 'SUCCESS') { badgeColor = '#ffffff'; badgeBg = '#059669'; }+ else if (s.status === 'RECONCILED' || s.status === 'SUCCESS') { badgeColor = '#ffffff'; badgeBg = '#059669'; }+ else if (s.status === 'OBSERVED_SUCCESS') { badgeColor = '#78350f'; badgeBg = '#fcd34d'; }+ else if (s.status === 'MANUAL_REVIEW') { badgeColor = '#ffffff'; badgeBg = '#b45309'; }else if (s.status === 'CANCELLED' || s.status === 'EXPIRED' || s.status === 'FAILED') { badgeColor = '#ffffff'; badgeBg = '#ef4444'; }return `@@ -6834,7 +6836,7 @@const btnSms = document.getElementById('simBtnPushSms');const btnGmail = document.getElementById('simBtnPushGmail');- const isTerminal = ['SUCCESS', 'FAILED', 'EXPIRED', 'CANCELLED'].includes(sess.status);+ const isTerminal = ['SUCCESS', 'OBSERVED_SUCCESS', 'RECONCILED', 'MANUAL_REVIEW', 'FAILED', 'EXPIRED', 'CANCELLED'].includes(sess.status);if (isTerminal) {if (notice) notice.style.display = 'block';if (btnSms) { btnSms.disabled = true; btnSms.style.opacity = '0.5'; btnSms.style.cursor = 'not-allowed'; }diff --git a/apps/payment-api/src/__tests__/developer-payment-simulator.test.js b/apps/payment-api/src/__tests__/developer-payment-simulator.test.jsindex 7c102aa..a5862b6 100644--- a/apps/payment-api/src/__tests__/developer-payment-simulator.test.js+++ b/apps/payment-api/src/__tests__/developer-payment-simulator.test.js@@ -616,12 +616,12 @@ describe('Feature 65: Developer Payment Simulator Integration & Acceptance Suite// Verify session in database transitioned to SUCCESSconst sessionDb = testDb.db.prepare('SELECT status FROM payment_sessions WHERE id = ?').get(sessId);- assert.equal(sessionDb.status, 'SUCCESS');+ assert.equal(sessionDb.status, 'OBSERVED_SUCCESS');// Normal checkout state now reports SUCCESSconst stateAfter = await request(`/api/v1/checkout/${sessId}/state`);assert.equal(stateAfter.status, 200);- assert.equal(stateAfter.body.status, 'SUCCESS');+ assert.equal(stateAfter.body.status, 'OBSERVED_SUCCESS');});test('33. Simulation event is audit logged with full evidence and accessible via history', async () => {diff --git a/apps/payment-api/src/__tests__/developer-test-mode.test.js b/apps/payment-api/src/__tests__/developer-test-mode.test.jsindex 80289a4..8ad84b7 100644--- a/apps/payment-api/src/__tests__/developer-test-mode.test.js+++ b/apps/payment-api/src/__tests__/developer-test-mode.test.js@@ -159,7 +159,7 @@ describe('Section 12: Developer Test Mode Acceptance Tests (All 29 Points)', ()// Confirm state machine moved sessionconst updated = sessionRepo.findById(s1.id);- assert.ok([PaymentStatus.SUCCESS, PaymentStatus.PROCESSING].includes(updated.status));+ assert.ok([PaymentStatus.OBSERVED_SUCCESS, PaymentStatus.PROCESSING].includes(updated.status));});// ---------------------------------------------------------------------------diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 918652f..9a6dc14 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -157,13 +157,14 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(obsRes.status, 200);assert.equal(obsRes.body.attribution.attributed, true);- assert.equal(obsRes.body.attribution.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(obsRes.body.attribution.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);assert.equal(obsRes.body.attribution.paymentSessionId, paymentIdA);- // 6. Verify Payment A is SUCCESS via public API+ // 6. Verify Payment A is observed, not bank-reconciled, via public APIconst verifyA = await request(`/api/v1/payments/${paymentIdA}`);assert.equal(verifyA.status, 200);- assert.equal(verifyA.body.status, 'SUCCESS');+ assert.equal(verifyA.body.status, 'OBSERVED_SUCCESS');+ assert.equal(verifyA.body.settlementState, 'NOT_RECONCILED');assert.ok(verifyA.body.completedAt);// 7. Verify Payment B has been automatically promoted to ACTIVE in the queue!@@ -572,7 +573,8 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// Check payment status: must be SUCCESS with Level 1const checkL1 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });- assert.equal(checkL1.body.status, 'SUCCESS');+ assert.equal(checkL1.body.status, 'OBSERVED_SUCCESS');+ assert.equal(checkL1.body.settlementState, 'NOT_RECONCILED');assert.equal(checkL1.body.verificationLevel, 1);assert.deepEqual(checkL1.body.verificationSources, ['GOOGLE_MESSAGES']);@@ -946,17 +948,18 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// Payment MUST be immediately SUCCESS for customerconst checkAfterObs1 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });- assert.equal(checkAfterObs1.body.status, 'SUCCESS');+ assert.equal(checkAfterObs1.body.status, 'OBSERVED_SUCCESS');assert.equal(checkAfterObs1.body.verificationLevel, 1);// Checkout state MUST reflect SUCCESS immediatelyconst stateAfterObs1 = await request(`/api/v1/checkout/${paymentId}/state`);- assert.equal(stateAfterObs1.body.status, 'SUCCESS');+ assert.equal(stateAfterObs1.body.status, 'OBSERVED_SUCCESS');// Wait 150ms for webhook dispatchawait new Promise(r => setTimeout(r, 150));assert.equal(webhookDeliveries.length, 1);- assert.equal(webhookDeliveries[0].body.event, 'SUCCESS');+ assert.equal(webhookDeliveries[0].body.event, 'OBSERVED_SUCCESS');+ assert.equal(webhookDeliveries[0].body.settlementState, 'NOT_RECONCILED');assert.equal(webhookDeliveries[0].body.orderId, 'AUTODETECT-ORD-777');assert.equal(webhookDeliveries[0].body.amount, '320.00');diff --git a/apps/payment-api/src/__tests__/phase1-observed-success.test.js b/apps/payment-api/src/__tests__/phase1-observed-success.test.jsnew file mode 100644index 0000000..665b8ea--- /dev/null+++ b/apps/payment-api/src/__tests__/phase1-observed-success.test.js@@ -0,0 +1,232 @@+import { test, describe, before, after, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import http from 'node:http';+import { Database, runMigrations, PaymentSessionRepository, ObservationRepository, SupportTicketRepository, AuditLogRepository } from '@youpi/db';+import { PaymentStatus, ObservationAttributionStatus } from '@youpi/common';+import { AttributionEngine, ObservationNormalizer } from '@youpi/core';+import { startServer as startPaymentApi } from '../index.js';+import { CoinWalletStoreServer } from '../../../coin-wallet-store/src/server.js';+import { authHeadersFor } from '../../../../scripts/test-support.js';++describe('Phase 1 observed success and matching safety', () => {+ describe('ambiguous alerts are not auto-attributed', () => {+ let db;+ let sessionRepo;+ let attributionEngine;+ let emittedEvents;+ const accountId = '00000000-0000-0000-0000-000000000002';++ let merchantId;++ beforeEach(() => {+ db = new Database({ inMemory: true });+ const seed = runMigrations(db);+ merchantId = seed.defaultMerchant.id;+ sessionRepo = new PaymentSessionRepository(db);+ emittedEvents = [];+ attributionEngine = new AttributionEngine({+ sessionRepo,+ obsRepo: new ObservationRepository(db),+ ticketRepo: new SupportTicketRepository(db),+ auditRepo: new AuditLogRepository(db),+ eventEmitter: { emit: (event, payload) => emittedEvents.push({ event, payload }) }+ });+ });++ afterEach(() => db.close());++ function activate(orderId) {+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: accountId,+ orderId,+ amountPaise: 20000n+ });+ sessionRepo.acquireSlotAtomic(session.id, accountId, 300000);+ sessionRepo.transitionToProcessing(session.id, 30000);+ return sessionRepo.findById(session.id);+ }++ test('a live session plus a recent same-amount expiry is held for manual review', () => {+ const expired = activate('ORD-EXPIRED-SAME');+ sessionRepo.transitionToTerminal(expired.id, PaymentStatus.EXPIRED, { reason: 'WINDOW_ELAPSED' });+ const live = activate('ORD-LIVE-SAME');+ assert.ok(live.slotAcquiredAt);++ const obs = ObservationNormalizer.normalize({+ source: 'GOOGLE_MESSAGES',+ receivingAccountId: accountId,+ amountPaise: 20000n,+ bankReferenceNumber: 'UTR-AMBIGUOUS-1',+ observedAt: new Date(live.slotAcquiredAt.getTime() - 60_000),+ rawPayload: { text: 'Received Rs 200' }+ });+ const result = attributionEngine.processObservation(obs);++ assert.equal(result.attributed, false);+ assert.equal(result.ambiguous, true);+ assert.equal(result.outcomeStatus, PaymentStatus.MANUAL_REVIEW);+ assert.equal(sessionRepo.findById(live.id).status, PaymentStatus.MANUAL_REVIEW);+ assert.equal(sessionRepo.findById(expired.id).status, PaymentStatus.EXPIRED);+ assert.equal(emittedEvents.some(e => e.event === 'PAYMENT.OBSERVED_SUCCESS'), false);+ const stored = db.queryOne('SELECT attribution_status FROM payment_observations WHERE id = ?', [result.observationId]);+ assert.equal(stored.attribution_status, ObservationAttributionStatus.AMBIGUOUS);+ });++ test('two recent same-amount expiries are not resolved by picking the newest', () => {+ const older = activate('ORD-LATE-OLD');+ sessionRepo.transitionToTerminal(older.id, PaymentStatus.EXPIRED);+ const newer = activate('ORD-LATE-NEW');+ sessionRepo.transitionToTerminal(newer.id, PaymentStatus.EXPIRED);++ const obs = ObservationNormalizer.normalize({+ source: 'GOOGLE_MESSAGES',+ receivingAccountId: accountId,+ amountPaise: 20000n,+ bankReferenceNumber: 'UTR-LATE-MULTI',+ observedAt: new Date(),+ rawPayload: { text: 'Received Rs 200' }+ });+ const result = attributionEngine.processObservation(obs);++ assert.equal(result.ambiguous, true);+ assert.equal(result.attributed, false);+ assert.equal(sessionRepo.findById(older.id).status, PaymentStatus.EXPIRED);+ assert.equal(sessionRepo.findById(newer.id).status, PaymentStatus.EXPIRED);+ assert.equal(db.queryOne("SELECT COUNT(*) AS n FROM payment_sessions WHERE status = 'RECONCILED'").n, 0);+ });++ test('a single matching alert becomes OBSERVED_SUCCESS and is not RECONCILED', () => {+ const live = activate('ORD-OBSERVED-ONLY');+ const obs = ObservationNormalizer.normalize({+ source: 'GOOGLE_MESSAGES',+ receivingAccountId: accountId,+ amountPaise: 20000n,+ bankReferenceNumber: 'UTR-OBSERVED-1',+ observedAt: new Date(),+ rawPayload: { text: 'Received Rs 200' }+ });+ const result = attributionEngine.processObservation(obs);+ assert.equal(result.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);+ assert.equal(sessionRepo.findById(live.id).status, PaymentStatus.OBSERVED_SUCCESS);+ assert.equal(db.queryOne("SELECT COUNT(*) AS n FROM payment_sessions WHERE status = 'RECONCILED'").n, 0);+ });+ });++ describe('new UPI sessions require a live SMS observer', () => {+ let apiInstance;+ let testDb;+ let baseUrl;+ const previousFlag = process.env.YOUPI_ENFORCE_OBSERVER_HEALTH;+ const previousSms = process.env.SMS_OBSERVER_PORT;+ const previousGmail = process.env.GMAIL_OBSERVER_PORT;++ before(async () => {+ process.env.YOUPI_ENFORCE_OBSERVER_HEALTH = 'true';+ process.env.SMS_OBSERVER_PORT = '5991';+ process.env.GMAIL_OBSERVER_PORT = '5992';+ testDb = new Database({ inMemory: true });+ apiInstance = await startPaymentApi(6211, testDb);+ baseUrl = `http://127.0.0.1:${apiInstance.port}`;+ });++ after(async () => {+ if (previousFlag === undefined) delete process.env.YOUPI_ENFORCE_OBSERVER_HEALTH;+ else process.env.YOUPI_ENFORCE_OBSERVER_HEALTH = previousFlag;+ if (previousSms === undefined) delete process.env.SMS_OBSERVER_PORT;+ else process.env.SMS_OBSERVER_PORT = previousSms;+ if (previousGmail === undefined) delete process.env.GMAIL_OBSERVER_PORT;+ else process.env.GMAIL_OBSERVER_PORT = previousGmail;+ await apiInstance.close();+ testDb.close();+ });++ function request(pathname, options = {}) {+ return new Promise((resolve, reject) => {+ const url = new URL(pathname, baseUrl);+ const req = http.request(url, {+ method: options.method || 'GET',+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(pathname), ...(options.headers || {}) }+ }, res => {+ let data = '';+ res.on('data', chunk => { data += chunk; });+ res.on('end', () => {+ let body;+ try { body = JSON.parse(data); } catch { body = data; }+ resolve({ status: res.statusCode, body });+ });+ });+ req.on('error', reject);+ if (options.body) req.write(JSON.stringify(options.body));+ req.end();+ });+ }++ test('refuses a new UPI session when the SMS heartbeat is stale, then accepts one after a fresh heartbeat', async () => {+ testDb.execute('DELETE FROM android_devices');+ const blocked = await request('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'ORD-OBSERVER-DOWN', amount: '25.00', currency: 'INR' }+ });+ assert.equal(blocked.status, 503);+ assert.equal(blocked.body.code, 'OBSERVERS_UNHEALTHY');++ const cod = await request('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'ORD-COD-WHILE-DOWN', amount: '25.00', method: 'COD' }+ });+ assert.equal(cod.status, 201);++ testDb.execute(`+ INSERT INTO android_devices (id, merchant_id, device_name, device_model, signing_key_hash, is_active, last_heartbeat_at, created_at)+ VALUES ('dev-phase1', '00000000-0000-0000-0000-000000000001', 'Pixel', 'Pixel', 'hash', 1, datetime('now'), datetime('now'))+ `);+ const allowed = await request('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'ORD-OBSERVER-UP', amount: '26.00', currency: 'INR' }+ });+ assert.equal(allowed.status, 201);+ assert.equal(allowed.body.status, 'INITIATED');+ });+ });++ describe('demo store fulfillment survives restart', () => {+ test('a second process cannot grant the same order again', () => {+ const file = path.join(os.tmpdir(), `youpi-phase1-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`);+ const first = new CoinWalletStoreServer({ idempotencyPath: file, webhookSecret: 'phase1-secret' });+ const claim = first.claimFulfillment({+ orderId: 'ORD-RESTART',+ deliveryId: 'delivery-1',+ paymentId: 'pay-1',+ amountPaise: 10000,+ coins: 100,+ packName: 'Pack'+ });+ assert.equal(claim.claimed, true);+ first.creditCoins('ORD-RESTART', 100, 'Pack');+ assert.equal(first.walletCoins, 150);+ first.ledger.close();++ const second = new CoinWalletStoreServer({ idempotencyPath: file, webhookSecret: 'phase1-secret' });+ assert.equal(second.walletCoins, 150);+ const replay = second.claimFulfillment({+ orderId: 'ORD-RESTART',+ deliveryId: 'delivery-2',+ paymentId: 'pay-1',+ amountPaise: 10000,+ coins: 100,+ packName: 'Pack'+ });+ assert.equal(replay.claimed, false);+ assert.equal(second.walletCoins, 150);+ assert.equal(second.receiptSeen('delivery-1'), false);+ second.noteReceipt('delivery-1', 'RECONCILED', 'ORD-RESTART');+ assert.equal(second.receiptSeen('delivery-1'), true);+ second.ledger.close();+ fs.rmSync(file, { force: true });+ });+ });+});diff --git a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.jsindex 93f805b..414b62a 100644--- a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js+++ b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js@@ -337,7 +337,7 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Cawait new Promise(r => setTimeout(r, 6500));const state = await request(`/api/v1/payments/${paymentId}`, { headers: { 'X-Merchant-Key': merchantSecret } });- assert.equal(state.body.status, 'SUCCESS');+ assert.equal(state.body.status, 'OBSERVED_SUCCESS');// Restarting a paid order must fail cleanly. It reuses the merchant's order reference,// and the unique (merchant_id, order_id) index would otherwise reject the duplicate rowdiff --git a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.jsindex 6e08d37..62b3f16 100644--- a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js+++ b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js@@ -211,7 +211,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',// Verify session in DB is now SUCCESS and Level 2const sUpdated = sessionRepo.findById(s450.id);- assert.equal(sUpdated.status, PaymentStatus.SUCCESS);+ assert.equal(sUpdated.status, PaymentStatus.OBSERVED_SUCCESS);assert.equal(sUpdated.verificationLevel, 2);});diff --git a/apps/payment-api/src/__tests__/statement-import.test.js b/apps/payment-api/src/__tests__/statement-import.test.jsnew file mode 100644index 0000000..1ab0668--- /dev/null+++ b/apps/payment-api/src/__tests__/statement-import.test.js@@ -0,0 +1,70 @@+import { test, describe, before, after } from 'node:test';+import assert from 'node:assert/strict';+import { Database } from '@youpi/db';+import { PaymentStatus, ObserverSource } from '@youpi/common';+import { ObservationNormalizer } from '@youpi/core';+import { startServer as startPaymentApi } from '../index.js';+import { TEST_ADMIN_TOKEN, TEST_OBSERVER_TOKEN } from '../../../../scripts/test-support.js';++describe('admin bank-statement import', () => {+ let api;+ let db;+ const accountId = '00000000-0000-0000-0000-000000000002';++ before(async () => {+ db = new Database({ inMemory: true });+ api = await startPaymentApi(6212, db);+ });++ after(async () => {+ await api.close();+ db.close();+ });++ function post(token, body) {+ return fetch(`http://127.0.0.1:${api.port}/api/v1/admin/statements/import`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { Authorization: `Bearer ${token}` } : {})+ },+ body: JSON.stringify(body)+ });+ }++ test('requires the admin token and reconciles one observed session', async () => {+ assert.equal((await post(null, { receivingAccountId: accountId, csv: 'x' })).status, 401);+ assert.equal((await post(TEST_OBSERVER_TOKEN, { receivingAccountId: accountId, csv: 'x' })).status, 401);++ const ctx = api.app.context;+ const session = ctx.sessionRepo.create({+ merchantId: '00000000-0000-0000-0000-000000000001',+ receivingAccountId: accountId,+ orderId: 'ORD-ADMIN-STMT',+ amountPaise: 49900n+ });+ ctx.sessionRepo.acquireSlotAtomic(session.id, accountId, 300000);+ ctx.sessionRepo.transitionToProcessing(session.id, 30000);+ ctx.attributionEngine.processObservation(ObservationNormalizer.normalize({+ source: ObserverSource.GOOGLE_MESSAGES,+ receivingAccountId: accountId,+ amountPaise: 49900n,+ bankReferenceNumber: '423456789012',+ observedAt: new Date(),+ rawPayload: { text: 'credit 423456789012' }+ }));++ const ist = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Kolkata' }).format(new Date());+ const [year, month, day] = ist.split('-');+ const slash = `${day}/${month}/${year}`;+ const csv = [+ 'Date,Narration,Chq./Ref.No.,Value Dt,Withdrawal Amt.,Deposit Amt.,Closing Balance',+ `${slash},"UPI-TEST PAYER-payer@okhdfcbank-HDFC0000001-423456789012-ORDER",0,${slash},,"499.00",10000.00`+ ].join('\n');+ const response = await post(TEST_ADMIN_TOKEN, { receivingAccountId: accountId, csv });+ assert.equal(response.status, 200);+ const body = await response.json();+ assert.equal(body.reconciled, 1);+ assert.equal(ctx.sessionRepo.findById(session.id).status, PaymentStatus.RECONCILED);+ });+});diff --git a/apps/payment-api/src/__tests__/verification-fallthrough.test.js b/apps/payment-api/src/__tests__/verification-fallthrough.test.jsindex e888bd2..5cde2e6 100644--- a/apps/payment-api/src/__tests__/verification-fallthrough.test.js+++ b/apps/payment-api/src/__tests__/verification-fallthrough.test.js@@ -380,7 +380,7 @@ describe('Verification Pipeline & Fall-Through Protection (#22)', () => {timingEngine,eventEmitter: {emit: (event) => {- if (event === 'PAYMENT.SUCCESS') successFired = true;+ if (event === 'PAYMENT.OBSERVED_SUCCESS') successFired = true;}}});@@ -388,8 +388,8 @@ describe('Verification Pipeline & Fall-Through Protection (#22)', () => {const stats = recovery.recover();const updated = sessionRepo.findById(session.id);- assert.equal(updated.status, PaymentStatus.SUCCESS, 'Attributed PROCESSING session must recover to SUCCESS');- assert.ok(successFired, 'PAYMENT.SUCCESS event must fire on recovery of attributed session');+ assert.equal(updated.status, PaymentStatus.OBSERVED_SUCCESS, 'Attributed PROCESSING session must recover to OBSERVED_SUCCESS');+ assert.ok(successFired, 'PAYMENT.OBSERVED_SUCCESS event must fire on recovery of attributed session');});test('Issue #60: Missing rawText is rejected with HTTP 400 and does not bypass pipeline', async () => {@@ -541,7 +541,7 @@ describe('Verification Pipeline & Fall-Through Protection (#22)', () => {const s1Fresh = sessionRepo.findById(s1.id);const s2Fresh = sessionRepo.findById(s2.id);const sessionStatuses = [s1Fresh.status, s2Fresh.status].sort();- assert.deepEqual(sessionStatuses, [PaymentStatus.ACTIVE, PaymentStatus.SUCCESS]);+ assert.deepEqual(sessionStatuses, [PaymentStatus.ACTIVE, PaymentStatus.OBSERVED_SUCCESS]);});});diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex 62a4551..d159ac2 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -45,6 +45,7 @@ import { registerPaymentRoutes } from './routes/payments.routes.js';import { registerCheckoutRoutes } from './routes/checkout.routes.js';import { registerPollerRoutes } from './routes/pollers.routes.js';import { registerAdminRoutes } from './routes/admin.routes.js';+import { registerStatementRoutes } from './routes/statement.routes.js';import { registerCustomerRoutes } from './routes/customer.routes.js';import { registerDeviceRoutes } from './routes/device.routes.js';import { getWhatsAppBerryService, WhatsAppBerryService } from './services/whatsapp-berry.service.js';@@ -168,6 +169,46 @@ export function createPaymentApp(customDb = null, options = {}) {return promoted;}+ eventEmitter.on('PAYMENT.OBSERVED_SUCCESS', (data) => {+ const session = sessionRepo.findById(data.paymentId);+ if (session) {+ server.broadcastSse(session.id, 'status_change', {+ status: PaymentStatus.OBSERVED_SUCCESS,+ settlementState: 'NOT_RECONCILED',+ verificationLevel: data.verificationLevel || session.verificationLevel || 1,+ verificationTag: data.verificationTag || session.verificationTag,+ sources: data.sources || session.verificationSources+ });+ webhookEngine.dispatch('OBSERVED_SUCCESS', session).catch(() => {});+ handleSlotFreedAndPromote(session.receivingAccountId);+ }+ });++ eventEmitter.on('PAYMENT.MANUAL_REVIEW', (data) => {+ const session = sessionRepo.findById(data.paymentId);+ if (session) {+ server.broadcastSse(session.id, 'status_change', {+ status: PaymentStatus.MANUAL_REVIEW,+ settlementState: 'MANUAL_REVIEW',+ reason: data.reason || null+ });+ webhookEngine.dispatch('MANUAL_REVIEW', session).catch(() => {});+ handleSlotFreedAndPromote(session.receivingAccountId);+ }+ });++ eventEmitter.on('PAYMENT.RECONCILED', (data) => {+ const session = sessionRepo.findById(data.paymentId);+ if (session && session.status === PaymentStatus.RECONCILED) {+ server.broadcastSse(session.id, 'status_change', {+ status: PaymentStatus.RECONCILED,+ settlementState: 'RECONCILED',+ statementLineId: data.statementLineId || null+ });+ webhookEngine.dispatch('RECONCILED', session).catch(() => {});+ }+ });+// When a payment succeeds, fails, expires, or cancels: dispatch webhook & promote next queued customereventEmitter.on('PAYMENT.SUCCESS', (data) => {const session = sessionRepo.findById(data.paymentId);@@ -386,6 +427,7 @@ export function createPaymentApp(customDb = null, options = {}) {registerCheckoutRoutes(server, context);registerPollerRoutes(server, context);registerAdminRoutes(server, context);+ registerStatementRoutes(server, context);registerCustomerRoutes(server, context);registerDeviceRoutes(server, context);diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex b167bbc..0113f60 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -3,6 +3,16 @@ import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERimport { validateSessionDeviceAccess, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';+const CLOSED_CHECKOUT_STATES = [+ PaymentStatus.SUCCESS,+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.RECONCILED,+ PaymentStatus.MANUAL_REVIEW,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+];+/*** Validates device access to an active payment session.* Enforces:@@ -11,7 +21,7 @@ import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';*/function checkSessionDeviceAccess(session, req, body = null, ctx = null) {// If session is already in a terminal state, allow access so terminal status can be rendered- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.SUSPICIOUS].includes(session.status)) {+ if (CLOSED_CHECKOUT_STATES.includes(session.status)) {return { allowed: true, boundDeviceId: session.deviceId, isTerminal: true };}@@ -149,19 +159,33 @@ function sanitizePublicBranding(raw = {}) {* }} ctx*//**- * Determines whether UPI pollers / observers (Android SMS, Google Messages, Gmail) are active.- * Strict Rule: Healthy (WORKING) ONLY IF:- * 1. Gmail OAuth is configured AND Gmail observer is actively polling.- * 2. SMS Gateway is connected (Android app or Google Messages) AND actively polling / reflecting messages.- * If either is missing, unconfigured, or offline, status is ISSUES with downtime warning.+ * New UPI sessions require a live SMS observer (Android heartbeat within 5 minutes,+ * or Google Messages connected). Gmail alone is supporting evidence and is not enough.+ * The gate is always on outside tests. Tests opt in with YOUPI_ENFORCE_OBSERVER_HEALTH=true.+ * Recovery: the next create succeeds once a heartbeat is fresh. In-flight sessions are not cancelled.+ */+export function observerHealthEnforced() {+ if (process.env.YOUPI_ENFORCE_OBSERVER_HEALTH === 'true') return true;+ if (process.env.NODE_ENV === 'test') return false;+ return true;+}++export function upiObserversAcceptingPayments(health) {+ return health?.smsHealthy === true && health?.isFalseNarrative !== true;+}++/**+ * Healthy (WORKING) only when both Gmail and an SMS observer are up.+ * New UPI payments additionally require smsHealthy. Gmail alone does not accept new sessions.*/-async function checkUpiServerHealth(ctx, enabledMethods = [], sellingMode = 'OFFLINE', merchantId = '00000000-0000-0000-0000-000000000001') {+export async function checkUpiServerHealth(ctx, enabledMethods = [], sellingMode = 'OFFLINE', merchantId = '00000000-0000-0000-0000-000000000001') {// 0. Check False Narrative Dev Switch (Active for 10 minutes from enabling time)+ const productionLock = process.env.NODE_ENV === 'production' || process.env.YOUPI_MODE === 'production';try {const merchant = ctx.merchantRepo?.findById ? ctx.merchantRepo.findById(merchantId) : null;const falseNarrativeUntil = merchant?.branding?.falseNarrativeUntil;const falseNarrativeMode = (merchant?.branding?.falseNarrativeMode || 'GREEN').toUpperCase();- if (falseNarrativeUntil && Number(falseNarrativeUntil) > Date.now()) {+ if (!productionLock && falseNarrativeUntil && Number(falseNarrativeUntil) > Date.now()) {const remainingSeconds = Math.max(0, Math.round((Number(falseNarrativeUntil) - Date.now()) / 1000));if (falseNarrativeMode === 'GREEN') {return {@@ -432,7 +456,7 @@ export function registerCheckoutRoutes(server, ctx) {}// Terminal session handling: if session is terminal, return terminal state directly (CASE 4)- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if ([PaymentStatus.SUCCESS, PaymentStatus.OBSERVED_SUCCESS, PaymentStatus.RECONCILED, PaymentStatus.MANUAL_REVIEW, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {const merchant = ctx.merchantRepo.findById(session.merchantId);const branding = sanitizePublicBranding(merchant?.branding || {});HttpServer.json(res, 200, {@@ -909,7 +933,7 @@ export function registerCheckoutRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if (CLOSED_CHECKOUT_STATES.includes(session.status)) {HttpServer.json(res, 400, { error: `Cannot retry payment for terminal session in status '${session.status}'` });return;}@@ -1076,7 +1100,7 @@ export function registerCheckoutRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if (CLOSED_CHECKOUT_STATES.includes(session.status)) {HttpServer.json(res, 200, {paymentId: session.id,status: session.status@@ -1135,7 +1159,7 @@ export function registerCheckoutRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if (CLOSED_CHECKOUT_STATES.includes(session.status)) {HttpServer.json(res, 400, { error: `Cannot switch payment method for session in status '${session.status}'` });return;}@@ -1357,7 +1381,7 @@ export function registerCheckoutRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if (CLOSED_CHECKOUT_STATES.includes(session.status)) {HttpServer.json(res, 400, { error: `Cannot place COD order for terminal session in status '${session.status}'` });return;}@@ -1695,13 +1719,18 @@ export function registerCheckoutRoutes(server, ctx) {// merchant's order reference, and the unique (merchant_id, order_id) index rejects a// second row for an order that already succeeded — which surfaced as a 500. Refuse with a// clear conflict instead of attempting the duplicate.- const paidSession = [sourceSession, targetSession, session].find(s => s && s.status === PaymentStatus.SUCCESS);+ const paidSession = [sourceSession, targetSession, session].find(s => s && (+ s.status === PaymentStatus.SUCCESS+ || s.status === PaymentStatus.OBSERVED_SUCCESS+ || s.status === PaymentStatus.RECONCILED+ || s.status === PaymentStatus.MANUAL_REVIEW+ ));if (paidSession) {HttpServer.json(res, 409, {error: 'ORDER_ALREADY_PAID',- message: 'This order has already been paid and cannot be restarted.',+ message: 'This order is already closed and cannot be restarted.',orderId: paidSession.orderId,- status: PaymentStatus.SUCCESS+ status: paidSession.status});return;}@@ -1767,11 +1796,7 @@ export function registerCheckoutRoutes(server, ctx) {// 1. Identify ALL sessions on old/other devices that must be cancelled (excluding PROCESSING and terminal states)const NON_CANCELLABLE_STATES = [PaymentStatus.PROCESSING,- PaymentStatus.CANCELLED,- PaymentStatus.EXPIRED,- PaymentStatus.FAILED,- PaymentStatus.SUCCESS,- PaymentStatus.SUSPICIOUS+ ...CLOSED_CHECKOUT_STATES];const sessionsToTerminate = new Map();diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 9a2f0cc..977c265 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -1,7 +1,8 @@import { HttpServer } from '../server.js';import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual, verifyHmac } from '@youpi/common';-import { isTerminalStatus, toPublicOutcome, verifyRegisteredDeviceCredentials } from '@youpi/core';+import { isTerminalStatus, toPublicOutcome, settlementStateFor, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';+import { checkUpiServerHealth, observerHealthEnforced, upiObserversAcceptingPayments } from './checkout.routes.js';/*** Registers merchant-facing payment routes.@@ -176,7 +177,10 @@ export function registerPaymentRoutes(server, ctx) {}// If SUCCESS: order is already paid, return existing completed session- if (existing.status === PaymentStatus.SUCCESS) {+ if (existing.status === PaymentStatus.SUCCESS+ || existing.status === PaymentStatus.OBSERVED_SUCCESS+ || existing.status === PaymentStatus.RECONCILED+ || existing.status === PaymentStatus.MANUAL_REVIEW) {HttpServer.json(res, 200, {paymentId: existing.id,orderId: existing.orderId,@@ -249,6 +253,21 @@ export function registerPaymentRoutes(server, ctx) {}const isCounterPayment = body.method === 'CASH_COUNTER' || body.method === 'CARD_COUNTER';+ const isCod = body.method === 'COD';+ if (!isCounterPayment && !isCod && observerHealthEnforced()) {+ const health = await checkUpiServerHealth(ctx, [], 'ONLINE', merchant.id);+ if (!upiObserversAcceptingPayments(health)) {+ HttpServer.json(res, 503, {+ error: 'UPI observers are offline. New payments are not accepted until the SMS observer heartbeat is fresh.',+ code: 'OBSERVERS_UNHEALTHY',+ smsHealthy: Boolean(health.smsHealthy),+ gmailHealthy: Boolean(health.gmailHealthy),+ retryAfterSeconds: 60,+ recovery: 'Pair or reconnect the Android or Google Messages observer. A heartbeat within 5 minutes allows new UPI sessions. In-flight sessions are left to their existing timers.'+ });+ return;+ }+ }let receivingAccountId = null;let receivingAccountSnapshot = null;@@ -394,6 +413,7 @@ export function registerPaymentRoutes(server, ctx) {amountPaise: session.amountPaise.toString(),currency: session.currency,status: publicStatus,+ settlementState: settlementStateFor(publicStatus),method: session.method,completedAt: session.completedAt ? session.completedAt.toISOString() : null};diff --git a/apps/payment-api/src/routes/statement.routes.js b/apps/payment-api/src/routes/statement.routes.jsnew file mode 100644index 0000000..878c4d4--- /dev/null+++ b/apps/payment-api/src/routes/statement.routes.js@@ -0,0 +1,57 @@+import { HttpServer } from '../server.js';+import { StatementReconciliation } from '@youpi/core';++/**+ * Operator import of a downloaded bank statement. This is not a bank API+ * and it does not run on a timer. A line reconciles a payment only inside+ * StatementReconciliation.+ */+export function registerStatementRoutes(server, ctx) {+ server.post('/api/v1/admin/statements/import', async (req, res) => {+ let body;+ try {+ body = await HttpServer.parseBody(req);+ } catch (err) {+ const tooLarge = err.message === 'Payload Too Large';+ HttpServer.json(res, tooLarge ? 413 : 400, { error: err.message });+ return;+ }++ const receivingAccountId = body?.receivingAccountId;+ const csv = body?.csv;+ if (!receivingAccountId || typeof csv !== 'string' || !csv.trim()) {+ HttpServer.json(res, 400, { error: 'receivingAccountId and csv are required.' });+ return;+ }+ const account = ctx.accountRepo.findById(receivingAccountId);+ if (!account) {+ HttpServer.json(res, 404, { error: 'Receiving account not found.' });+ return;+ }++ const engine = new StatementReconciliation({+ db: ctx.db,+ sessionRepo: ctx.sessionRepo,+ auditRepo: ctx.auditRepo,+ eventEmitter: ctx.eventEmitter+ });+ const result = engine.importCsv({ receivingAccountId, csvText: csv });+ if (result.error) {+ HttpServer.json(res, 400, result);+ return;+ }+ HttpServer.json(res, 200, {+ reconciled: result.reconciled,+ conflicts: result.conflicts,+ unmatched: result.unmatched,+ lines: result.lines.map(line => ({+ outcome: line.outcome,+ matchStatus: line.matchStatus,+ matchReason: line.matchReason,+ paymentSessionId: line.paymentSessionId,+ statementLineId: line.statementLineId,+ utr: line.utr || null+ }))+ });+ });+}diff --git a/apps/sms-observer/src/__tests__/sms-observer.test.js b/apps/sms-observer/src/__tests__/sms-observer.test.jsindex a435a43..6b95ff7 100644--- a/apps/sms-observer/src/__tests__/sms-observer.test.js+++ b/apps/sms-observer/src/__tests__/sms-observer.test.js@@ -119,11 +119,11 @@ describe('Google Messages / SMS Payment Observer Integration Tests', () => {assert.equal(result.accepted, true);assert.equal(result.attribution.attributed, true);assert.equal(result.attribution.paymentSessionId, session.id);- assert.equal(result.attribution.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(result.attribution.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);// 3. Verify session in DB updated to SUCCESSconst updated = apiInstance.app.context.sessionRepo.findById(session.id);- assert.equal(updated.status, PaymentStatus.SUCCESS);+ assert.equal(updated.status, PaymentStatus.OBSERVED_SUCCESS);});});});diff --git a/docs/MERCHANT_INTEGRATION.md b/docs/MERCHANT_INTEGRATION.mdindex b00b3ad..6ee1b15 100644--- a/docs/MERCHANT_INTEGRATION.md+++ b/docs/MERCHANT_INTEGRATION.md@@ -3,11 +3,18 @@## 1. OverviewThe YOUPI PG public contract is designed to be minimal and robust. Merchant systems do not need to understand queue mechanics, five-minute timers, 30-second verification windows, or multi-channel observation.-Merchants interact with only **four public outcomes**:-- `SUCCESS`: Payment observed and verified.-- `FAILED`: 30-second verification window elapsed with no matching observation.-- `EXPIRED`: 5-minute payment window elapsed without customer initiating verification.-- `CANCELLED`: Customer explicitly cancelled checkout.+An observer match is not a bank settlement. UPI alerts move a session to `OBSERVED_SUCCESS` with `settlementState: NOT_RECONCILED`. `RECONCILED` is emitted only after an admin imports a bank-statement CSV and one line matches that session on receiving account, amount in paise, and 12-digit reference. There is no bank API and no scheduled pull. Do not fulfill a UPI order on `SUCCESS` or `OBSERVED_SUCCESS`.++Public outcomes:+- `OBSERVED_SUCCESS`: A bank alert was attributed to this UPI session. Not statement-reconciled.+- `RECONCILED`: A downloaded statement line matched this UPI session. This is not sent for an observer alert alone.+- `MANUAL_REVIEW`: More than one session could explain the alert, or the payment was flagged. Do not fulfill.+- `SUCCESS`: Cash on delivery or a counter payment was placed. This is not a UPI bank settlement (`settlementState: NOT_BANK_SETTLEMENT`).+- `FAILED`: Verification window elapsed with no matching observation.+- `EXPIRED`: Payment window elapsed.+- `CANCELLED`: Customer cancelled checkout.++Breaking change: UPI observer webhooks now send `X-Gateway-Event: OBSERVED_SUCCESS` and `event: "OBSERVED_SUCCESS"`. Older integrations that treated UPI `SUCCESS` as paid must switch. `SUCCESS` remains the COD and counter event.---@@ -59,9 +66,19 @@ app.post('/api/payment/webhook', express.raw({ type: 'application/json' }), (reqconst event = client.verifyWebhook(rawBody, signature);switch (event.event) {+ case 'OBSERVED_SUCCESS':+ // Alert matched. Do not fulfill. Wait for RECONCILED.+ break;+ case 'RECONCILED':+ if (event.method === 'UPI' && event.settlementState === 'RECONCILED') {+ unlockServiceForCustomer(event.orderId, event.metadata);+ }+ break;+ case 'MANUAL_REVIEW':+ // Hold the order. Do not fulfill.+ break;case 'SUCCESS':- // Fulfill customer order- unlockServiceForCustomer(event.orderId, event.metadata);+ // COD or counter order placed. Check event.method before treating it as paid.break;case 'FAILED':// Mark order as failed, notify customer to retrydiff --git a/packages/common/src/enums.js b/packages/common/src/enums.jsindex 37f94be..26e23ae 100644--- a/packages/common/src/enums.js+++ b/packages/common/src/enums.js@@ -6,6 +6,13 @@ export const PaymentStatus = Object.freeze({QUEUED: 'QUEUED',ACTIVE: 'ACTIVE',PROCESSING: 'PROCESSING',+ /** Observer alert matched. Not a bank-statement confirmation. Do not fulfill. */+ OBSERVED_SUCCESS: 'OBSERVED_SUCCESS',+ /** Reserved for a future statement-import match. Observers must not set this. */+ RECONCILED: 'RECONCILED',+ /** Ambiguous or suspicious evidence. Not payable. */+ MANUAL_REVIEW: 'MANUAL_REVIEW',+ /** COD or counter order placed. Not an observer settlement. */SUCCESS: 'SUCCESS',FAILED: 'FAILED',EXPIRED: 'EXPIRED',@@ -16,6 +23,9 @@ export const PaymentStatus = Object.freeze({* Public-facing payment outcomes consumed by external merchants.*/export const PublicPaymentOutcome = Object.freeze({+ OBSERVED_SUCCESS: 'OBSERVED_SUCCESS',+ RECONCILED: 'RECONCILED',+ MANUAL_REVIEW: 'MANUAL_REVIEW',SUCCESS: 'SUCCESS',FAILED: 'FAILED',EXPIRED: 'EXPIRED',@@ -59,7 +69,8 @@ export const ObservationAttributionStatus = Object.freeze({UNATTRIBUTED: 'UNATTRIBUTED',ATTRIBUTED: 'ATTRIBUTED',LATE_UNMATCHED: 'LATE_UNMATCHED',- DUPLICATE_IGNORED: 'DUPLICATE_IGNORED'+ DUPLICATE_IGNORED: 'DUPLICATE_IGNORED',+ AMBIGUOUS: 'AMBIGUOUS'});/**diff --git a/packages/common/src/state-transitions.js b/packages/common/src/state-transitions.jsindex 6f1d285..5869ed5 100644--- a/packages/common/src/state-transitions.js+++ b/packages/common/src/state-transitions.js@@ -16,6 +16,7 @@ export const VALID_TRANSITIONS = Object.freeze({PaymentStatus.QUEUED,PaymentStatus.CANCELLED,PaymentStatus.EXPIRED,+ PaymentStatus.MANUAL_REVIEW,// COD: placing a Cash-on-Delivery order is a business success even before any UPI// slot is acquired, so an order that was never activated still terminates as SUCCESS.PaymentStatus.SUCCESS@@ -24,32 +25,71 @@ export const VALID_TRANSITIONS = Object.freeze({PaymentStatus.ACTIVE,PaymentStatus.CANCELLED,PaymentStatus.EXPIRED,+ PaymentStatus.MANUAL_REVIEW,// COD: a queued UPI order can be converted to a placed COD order.PaymentStatus.SUCCESS],[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.+ // Observer match. Not a bank-statement confirmation.+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.MANUAL_REVIEW,+ // COD / cashier confirmation only. UPI alert code must not use SUCCESS.PaymentStatus.SUCCESS,PaymentStatus.FAILED,PaymentStatus.EXPIRED,PaymentStatus.CANCELLED],[PaymentStatus.PROCESSING]: [+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.MANUAL_REVIEW,PaymentStatus.SUCCESS,PaymentStatus.FAILED,PaymentStatus.EXPIRED],+ [PaymentStatus.OBSERVED_SUCCESS]: [+ PaymentStatus.RECONCILED,+ PaymentStatus.MANUAL_REVIEW+ ],+ [PaymentStatus.MANUAL_REVIEW]: [+ PaymentStatus.RECONCILED+ ],+ [PaymentStatus.RECONCILED]: [],[PaymentStatus.SUCCESS]: [],[PaymentStatus.FAILED]: [],[PaymentStatus.EXPIRED]: [],[PaymentStatus.CANCELLED]: []});-/** States that can never change again. */+/** Slot-releasing outcomes. OBSERVED_SUCCESS is not bank settlement. */+export const SLOT_RELEASE_STATES = Object.freeze([+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.RECONCILED,+ PaymentStatus.MANUAL_REVIEW,+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+]);++/**+ * Public/dispatch outcomes. OBSERVED_SUCCESS and MANUAL_REVIEW are included so webhooks+ * and the queue treat them as closed, but they are not immutable: a future statement+ * match may move them to RECONCILED. No observer path performs that move.+ */export const TERMINAL_STATES = Object.freeze([+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.RECONCILED,+ PaymentStatus.MANUAL_REVIEW,+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+]);++/** States that must not change again. */+export const IMMUTABLE_STATES = Object.freeze([+ PaymentStatus.RECONCILED,PaymentStatus.SUCCESS,PaymentStatus.FAILED,PaymentStatus.EXPIRED,diff --git a/packages/core/src/__tests__/core.test.js b/packages/core/src/__tests__/core.test.jsindex 7a71af8..2ac8703 100644--- a/packages/core/src/__tests__/core.test.js+++ b/packages/core/src/__tests__/core.test.js@@ -31,6 +31,13 @@ describe('@youpi/core Unit & Integration Tests', () => {assert.equal(isValidTransition(PaymentStatus.INITIATED, PaymentStatus.ACTIVE), true);assert.equal(isValidTransition(PaymentStatus.ACTIVE, PaymentStatus.PROCESSING), true);assert.equal(isValidTransition(PaymentStatus.PROCESSING, PaymentStatus.SUCCESS), true);+ assert.equal(isValidTransition(PaymentStatus.ACTIVE, PaymentStatus.OBSERVED_SUCCESS), true);+ assert.equal(isValidTransition(PaymentStatus.PROCESSING, PaymentStatus.OBSERVED_SUCCESS), true);+ assert.equal(isValidTransition(PaymentStatus.OBSERVED_SUCCESS, PaymentStatus.RECONCILED), true);+ assert.equal(isValidTransition(PaymentStatus.MANUAL_REVIEW, PaymentStatus.RECONCILED), true);+ assert.equal(isValidTransition(PaymentStatus.ACTIVE, PaymentStatus.RECONCILED), false);+ assert.equal(isValidTransition(PaymentStatus.OBSERVED_SUCCESS, PaymentStatus.SUCCESS), false);+ assert.equal(isValidTransition(PaymentStatus.RECONCILED, PaymentStatus.OBSERVED_SUCCESS), false);assert.equal(isValidTransition(PaymentStatus.PROCESSING, PaymentStatus.FAILED), true);assert.equal(isValidTransition(PaymentStatus.ACTIVE, PaymentStatus.EXPIRED), true);assert.equal(isValidTransition(PaymentStatus.ACTIVE, PaymentStatus.CANCELLED), true);@@ -55,6 +62,9 @@ describe('@youpi/core Unit & Integration Tests', () => {test('maps internal terminal states to public contract outcomes', () => {assert.equal(toPublicOutcome(PaymentStatus.SUCCESS), PublicPaymentOutcome.SUCCESS);+ assert.equal(toPublicOutcome(PaymentStatus.OBSERVED_SUCCESS), PublicPaymentOutcome.OBSERVED_SUCCESS);+ assert.equal(toPublicOutcome(PaymentStatus.RECONCILED), PublicPaymentOutcome.RECONCILED);+ assert.equal(toPublicOutcome(PaymentStatus.MANUAL_REVIEW), PublicPaymentOutcome.MANUAL_REVIEW);assert.equal(toPublicOutcome(PaymentStatus.FAILED), PublicPaymentOutcome.FAILED);assert.equal(toPublicOutcome(PaymentStatus.EXPIRED), PublicPaymentOutcome.EXPIRED);assert.equal(toPublicOutcome(PaymentStatus.CANCELLED), PublicPaymentOutcome.CANCELLED);@@ -173,16 +183,16 @@ describe('@youpi/core Unit & Integration Tests', () => {const result = attributionEngine.processObservation(normObs);assert.equal(result.attributed, true);- assert.equal(result.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(result.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);assert.equal(result.paymentSessionId, session.id);// Verify session updated to SUCCESS in DBconst updatedSession = sessionRepo.findById(session.id);- assert.equal(updatedSession.status, PaymentStatus.SUCCESS);+ assert.equal(updatedSession.status, PaymentStatus.OBSERVED_SUCCESS);assert.ok(updatedSession.completedAt);// Verify event was emitted- assert.ok(emittedEvents.some(e => e.event === 'PAYMENT.SUCCESS'));+ assert.ok(emittedEvents.some(e => e.event === 'PAYMENT.OBSERVED_SUCCESS'));});test('deduplicates multi-channel observations (SMS + Gmail)', () => {@@ -205,7 +215,7 @@ describe('@youpi/core Unit & Integration Tests', () => {});const res1 = attributionEngine.processObservation(obsSms);assert.equal(res1.attributed, true);- assert.equal(res1.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(res1.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);assert.equal(res1.verificationLevel, 1);// Method 2: Gmail observes same payment from independent channel -> Upgrades to Level 2 (L2 Dual Verification)@@ -227,7 +237,7 @@ describe('@youpi/core Unit & Integration Tests', () => {assert.equal(resSmsDup.outcomeStatus, ObservationAttributionStatus.DUPLICATE_IGNORED);// Exactly ONE success event was emitted (subsequent multi-channel confirmations were verification upgrades)!- const successEvents = emittedEvents.filter(e => e.event === 'PAYMENT.SUCCESS');+ const successEvents = emittedEvents.filter(e => e.event === 'PAYMENT.OBSERVED_SUCCESS');assert.equal(successEvents.length, 1);const upgradeEvents = emittedEvents.filter(e => e.event === 'PAYMENT.VERIFICATION_UPGRADED');assert.equal(upgradeEvents.length, 1);@@ -279,23 +289,20 @@ describe('@youpi/core Unit & Integration Tests', () => {rawPayload: { text: 'Delayed bank email' }});- // Customer B is in ACTIVE, but has NOT clicked Payment Done (not in PROCESSING).- // Even if Customer B were in PROCESSING, late observation check detects expired A!+ // Customer B is live at the same amount as expired Customer A.+ // The alert could belong to either session, so it must not be given to B+ // and B must be held for manual review instead of staying payable.const lateRes = attributionEngine.processObservation(lateObs);- // Observation must NOT be given to Customer B!assert.equal(lateRes.attributed, false);- assert.equal(lateRes.lateMatch, true);- assert.equal(lateRes.paymentSessionId, sessionA.id);+ assert.equal(lateRes.ambiguous, true);+ assert.equal(lateRes.outcomeStatus, PaymentStatus.MANUAL_REVIEW);- // Customer B remains ACTIVE, not falsely completed!const checkB = sessionRepo.findById(sessionB.id);- assert.equal(checkB.status, PaymentStatus.ACTIVE);-- // A support ticket must be raised for Customer A's late payment- const tickets = ticketRepo.findTicketsByCustomer(customerA.id);- assert.equal(tickets.length, 1);- assert.ok(tickets[0].subject.includes('LATE PAYMENT DETECTED'));+ assert.equal(checkB.status, PaymentStatus.MANUAL_REVIEW);+ const checkA = sessionRepo.findById(sessionA.id);+ assert.equal(checkA.status, PaymentStatus.EXPIRED);+ assert.equal(emittedEvents.some(e => e.event === 'PAYMENT.OBSERVED_SUCCESS'), false);});});@@ -442,6 +449,7 @@ describe('Issue #4: Terminal State Invariants and Re-activation Guards', () => {test('strictly forbids all transitions out of terminal states in the state machine', () => {const terminalStates = [PaymentStatus.SUCCESS,+ PaymentStatus.RECONCILED,PaymentStatus.FAILED,PaymentStatus.EXPIRED,PaymentStatus.CANCELLED@@ -453,6 +461,9 @@ describe('Issue #4: Terminal State Invariants and Re-activation Guards', () => {PaymentStatus.ACTIVE,PaymentStatus.PROCESSING,PaymentStatus.SUCCESS,+ PaymentStatus.OBSERVED_SUCCESS,+ PaymentStatus.RECONCILED,+ PaymentStatus.MANUAL_REVIEW,PaymentStatus.FAILED,PaymentStatus.EXPIRED,PaymentStatus.CANCELLED@@ -672,10 +683,10 @@ describe('Issue #4: Terminal State Invariants and Re-activation Guards', () => {assert.ok(ticket);assert.ok(ticket.subject.includes('[LATE PAYMENT DETECTED]'));- // Verify PAYMENT.LATE_DETECTED was emitted and not PAYMENT.SUCCESS+ // Verify PAYMENT.LATE_DETECTED was emitted and not PAYMENT.OBSERVED_SUCCESSconst 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);+ const successEvents = emittedEvents.filter(e => e.event === 'PAYMENT.OBSERVED_SUCCESS' && e.payload.paymentId === expiredSession.id);assert.equal(successEvents.length, 0);});});diff --git a/packages/core/src/__tests__/statement-reconciliation.test.js b/packages/core/src/__tests__/statement-reconciliation.test.jsnew file mode 100644index 0000000..1fd0309--- /dev/null+++ b/packages/core/src/__tests__/statement-reconciliation.test.js@@ -0,0 +1,225 @@+import { test, describe, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { Database, runMigrations, PaymentSessionRepository, ObservationRepository, SupportTicketRepository, AuditLogRepository } from '@youpi/db';+import { PaymentStatus, ObserverSource } from '@youpi/common';+import { AttributionEngine, ObservationNormalizer, StatementReconciliation, parseStatementCsv, rupeesToPaise } from '@youpi/core';++const ACCOUNT_ID = '00000000-0000-0000-0000-000000000002';++function istDate(value = new Date()) {+ return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Kolkata' }).format(value);+}++function istSlash(value = new Date()) {+ const [year, month, day] = istDate(value).split('-');+ return `${day}/${month}/${year}`;+}++function hdfcCsv(dataRows) {+ return [+ 'HDFC Bank Limited',+ 'Account Number: 50100123456789',+ 'Date,Narration,Chq./Ref.No.,Value Dt,Withdrawal Amt.,Deposit Amt.,Closing Balance',+ ...dataRows+ ].join('\n');+}++function creditRow({ utr = '123456789012', deposit = '499.00', date = istSlash(), narration } = {}) {+ const text = narration || `UPI-TEST PAYER-payer@okhdfcbank-HDFC0000001-${utr}-ORDER 1001`;+ return `${date},"${text}",0,${date},,"${deposit}",10000.00`;+}++describe('bank statement reconciliation', () => {+ let db;+ let sessionRepo;+ let engine;+ let events;+ let merchantId;++ beforeEach(() => {+ db = new Database({ inMemory: true });+ merchantId = runMigrations(db).defaultMerchant.id;+ sessionRepo = new PaymentSessionRepository(db);+ events = [];+ engine = new StatementReconciliation({+ db,+ sessionRepo,+ auditRepo: new AuditLogRepository(db),+ eventEmitter: { emit: (event, payload) => events.push({ event, payload }) }+ });+ });++ afterEach(() => db.close());++ function observe(orderId, amountPaise, utr) {+ const attribution = new AttributionEngine({+ sessionRepo,+ obsRepo: new ObservationRepository(db),+ ticketRepo: new SupportTicketRepository(db),+ auditRepo: new AuditLogRepository(db),+ eventEmitter: { emit: () => {} }+ });+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: ACCOUNT_ID,+ orderId,+ amountPaise+ });+ sessionRepo.acquireSlotAtomic(session.id, ACCOUNT_ID, 300000);+ sessionRepo.transitionToProcessing(session.id, 30000);+ const result = attribution.processObservation(ObservationNormalizer.normalize({+ source: ObserverSource.GOOGLE_MESSAGES,+ receivingAccountId: ACCOUNT_ID,+ amountPaise,+ bankReferenceNumber: utr,+ observedAt: new Date(),+ rawPayload: { text: `Received ${utr} ${orderId}` }+ }));+ assert.equal(result.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);+ return sessionRepo.findById(session.id);+ }++ test('parses an HDFC credit, an Indian-grouped amount, and a quoted comma', () => {+ assert.equal(rupeesToPaise('1,499.50'), 149950);+ const parsed = parseStatementCsv(hdfcCsv([+ creditRow({ deposit: '1,499.50', narration: 'UPI-TEST, PAYER-payer@okhdfcbank-HDFC0000001-123456789012-NOTE' })+ ]));+ assert.equal(parsed.error, undefined);+ assert.equal(parsed.lines.length, 1);+ assert.equal(parsed.lines[0].amountPaise, 149950);+ assert.equal(parsed.lines[0].utr, '123456789012');+ assert.equal(parsed.lines[0].direction, 'CREDIT');+ assert.equal(parsed.lines[0].bookedOn, istDate());+ });++ test('a matching HDFC credit reconciles the observed session once', () => {+ const session = observe('ORD-STMT-1', 49900n, '123456789012');+ const csv = hdfcCsv([creditRow()]);+ const first = engine.importCsv({ receivingAccountId: ACCOUNT_ID, csvText: csv });+ assert.equal(first.reconciled, 1);+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.RECONCILED);+ assert.equal(events.filter(event => event.event === 'PAYMENT.RECONCILED').length, 1);++ const second = engine.importCsv({ receivingAccountId: ACCOUNT_ID, csvText: csv });+ assert.equal(second.lines[0].outcome, 'DUPLICATE');+ assert.equal(events.filter(event => event.event === 'PAYMENT.RECONCILED').length, 1);+ assert.equal(db.queryOne("SELECT COUNT(*) AS n FROM payment_sessions WHERE status = 'RECONCILED'").n, 1);+ });++ test('a debit, a missing reference, and an unmatched credit do not reconcile', () => {+ const session = observe('ORD-STMT-2', 49900n, '123456789012');+ const csv = hdfcCsv([+ '23/10/2026,"UPI-OUT-payer@okhdfcbank-HDFC0000001-123456789012-OUT",0,23/10/2026,100.00,,9000.00',+ '23/10/2026,"SALARY CREDIT",0,23/10/2026,,25000.00,34000.00',+ creditRow({ utr: '999999999999' })+ ]);+ const result = engine.importCsv({ receivingAccountId: ACCOUNT_ID, csvText: csv });+ assert.equal(result.reconciled, 0);+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.OBSERVED_SUCCESS);+ assert.equal(result.lines[0].matchReason, 'DEBIT');+ assert.equal(result.lines[1].matchReason, 'MISSING_REFERENCE');+ assert.equal(result.lines[2].outcome, 'UNMATCHED');+ });++ test('amount and date disagreements move the session to manual review', () => {+ const amountSession = observe('ORD-STMT-AMT', 49900n, '123456789012');+ const amountResult = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow({ deposit: '500.00' })])+ });+ assert.equal(amountResult.reconciled, 0);+ assert.equal(amountResult.lines[0].matchReason, 'AMOUNT_MISMATCH');+ assert.equal(sessionRepo.findById(amountSession.id).status, PaymentStatus.MANUAL_REVIEW);++ const dateSession = observe('ORD-STMT-DATE', 49900n, '223456789012');+ const dateResult = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow({ utr: '223456789012', date: '01/10/2026' })])+ });+ assert.equal(dateResult.lines[0].matchReason, 'STATEMENT_DATE_OUTSIDE_WINDOW');+ assert.equal(sessionRepo.findById(dateSession.id).status, PaymentStatus.MANUAL_REVIEW);+ assert.equal(db.queryOne("SELECT COUNT(*) AS n FROM payment_sessions WHERE status = 'RECONCILED'").n, 0);+ });++ test('two held sessions for one statement reference are not picked apart', () => {+ const obsRepo = new ObservationRepository(db);+ function hold(orderId) {+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: ACCOUNT_ID,+ orderId,+ amountPaise: 49900n+ });+ sessionRepo.acquireSlotAtomic(session.id, ACCOUNT_ID, 300000);+ sessionRepo.transitionToTerminal(session.id, PaymentStatus.MANUAL_REVIEW);+ return session.id;+ }+ const firstId = hold('ORD-HOLD-1');+ const secondId = hold('ORD-HOLD-2');+ obsRepo.create({+ receivingAccountId: ACCOUNT_ID,+ source: 'GOOGLE_MESSAGES',+ amountPaise: 49900n,+ observedAt: new Date(),+ bankReferenceNumber: '323456789012',+ fingerprintHash: 'fp-hold-statement',+ rawPayload: {}+ });++ const result = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow({ utr: '323456789012' })])+ });+ assert.equal(result.lines[0].matchReason, 'MULTIPLE_SESSIONS');+ assert.equal(sessionRepo.findById(firstId).status, PaymentStatus.MANUAL_REVIEW);+ assert.equal(sessionRepo.findById(secondId).status, PaymentStatus.MANUAL_REVIEW);+ });++ test('one held session is reconciled when the statement reference matches its alert', () => {+ const obsRepo = new ObservationRepository(db);+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: ACCOUNT_ID,+ orderId: 'ORD-HOLD-ONE',+ amountPaise: 49900n+ });+ sessionRepo.acquireSlotAtomic(session.id, ACCOUNT_ID, 300000);+ sessionRepo.transitionToTerminal(session.id, PaymentStatus.MANUAL_REVIEW);+ obsRepo.create({+ receivingAccountId: ACCOUNT_ID,+ source: 'GOOGLE_MESSAGES',+ amountPaise: 49900n,+ observedAt: new Date(),+ bankReferenceNumber: '523456789012',+ fingerprintHash: 'fp-hold-one',+ rawPayload: {}+ });+ const result = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow({ utr: '523456789012' })])+ });+ assert.equal(result.reconciled, 1);+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.RECONCILED);+ });++ test('a statement line does not settle a session that was never observed', () => {+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: ACCOUNT_ID,+ orderId: 'ORD-UNOBSERVED',+ amountPaise: 49900n+ });+ sessionRepo.acquireSlotAtomic(session.id, ACCOUNT_ID, 300000);+ const result = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow()])+ });+ assert.equal(result.lines[0].outcome, 'UNMATCHED');+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.ACTIVE);+ });++ test('rejects a file that has no statement header', () => {+ const result = engine.importCsv({ receivingAccountId: ACCOUNT_ID, csvText: 'hello,world\n1,2\n' });+ assert.equal(result.error, 'UNSUPPORTED_STATEMENT');+ });+});diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex db8b0df..798dd87 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -37,6 +37,68 @@ export class AttributionEngine {this.pendingGraceTimers.clear();}+ /**+ * More than one session could explain this alert. Do not pick one.+ * Live sessions move to MANUAL_REVIEW. The observation is kept as evidence.+ */+ holdAmbiguous(savedObs, sessions, reason) {+ this.obsRepo.markAmbiguous(savedObs.id);+ const ids = [];+ for (const session of sessions) {+ if (!session?.id) continue;+ ids.push(session.id);+ const live = session.status === PaymentStatus.ACTIVE+ || session.status === PaymentStatus.PROCESSING+ || session.status === PaymentStatus.OBSERVED_SUCCESS;+ if (!live) continue;+ try {+ this.sessionRepo.transitionToTerminal(session.id, PaymentStatus.MANUAL_REVIEW, { reason });+ this.eventEmitter.emit('PAYMENT.MANUAL_REVIEW', {+ paymentId: session.id,+ orderId: session.orderId || session.order_id,+ merchantId: session.merchantId || session.merchant_id,+ observationId: savedObs.id,+ reason+ });+ } catch (err) {+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: session.merchantId || session.merchant_id,+ entityType: 'PAYMENT_SESSION',+ entityId: session.id,+ action: 'AMBIGUOUS_MATCH_TRANSITION_FAILED',+ actorType: 'SYSTEM',+ details: { reason, error: err.message, observationId: savedObs.id }+ });+ }+ }+ }+ if (this.auditRepo && sessions[0]) {+ this.auditRepo.log({+ merchantId: sessions[0].merchantId || sessions[0].merchant_id,+ entityType: 'PAYMENT_OBSERVATION',+ entityId: savedObs.id,+ action: 'AMBIGUOUS_MATCH_MANUAL_REVIEW',+ actorType: 'SYSTEM',+ details: {+ reason,+ observationId: savedObs.id,+ sessionIds: ids,+ amountPaise: savedObs.amountPaise?.toString?.() || String(savedObs.amount_paise || '')+ }+ });+ }+ return {+ attributed: false,+ duplicate: false,+ lateMatch: false,+ ambiguous: true,+ observationId: savedObs.id,+ outcomeStatus: PaymentStatus.MANUAL_REVIEW,+ reason+ };+ }+/*** Processes a normalized canonical observation through the attribution pipeline.* @param {ReturnType<typeof import('./normalizer.js').ObservationNormalizer.normalize>} normalizedObs@@ -81,7 +143,12 @@ export class AttributionEngine {// 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 closedWithoutUpgrade = targetSession+ && isTerminalStatus(targetSession.status)+ && targetSession.status !== PaymentStatus.SUCCESS+ && targetSession.status !== PaymentStatus.OBSERVED_SUCCESS+ && targetSession.status !== PaymentStatus.RECONCILED;+ if (closedWithoutUpgrade) {const savedObs = this.obsRepo.create(normalizedObs);this.obsRepo.markLateUnmatched(savedObs.id);if (this.auditRepo) {@@ -184,7 +251,7 @@ export class AttributionEngine {}if (verifyResult.isFirstSuccess) {- this.eventEmitter.emit('PAYMENT.SUCCESS', {+ this.eventEmitter.emit('PAYMENT.OBSERVED_SUCCESS', {paymentId: existing.attributedPaymentId,orderId: verifyResult.session.orderId,merchantId: verifyResult.session.merchantId,@@ -209,7 +276,7 @@ export class AttributionEngine {lateMatch: false,paymentSessionId: existing.attributedPaymentId,observationId: savedObs.id,- outcomeStatus: PaymentStatus.SUCCESS,+ outcomeStatus: PaymentStatus.OBSERVED_SUCCESS,verificationLevel: verifyResult.level,verificationTag: verifyResult.tag,verificationSources: verifyResult.sources@@ -229,30 +296,40 @@ export class AttributionEngine {currentSession = this.sessionRepo.findCurrentActiveOrProcessing(normalizedObs.receivingAccountId);}if (currentSession && currentSession.amountPaise !== normalizedObs.amountPaise) {- const matchRow = this.sessionRepo.db.queryOne(`+ const matchRows = this.sessionRepo.db.query(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?- ORDER BY created_at DESC- LIMIT 1`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);- if (matchRow) {- currentSession = this.sessionRepo.mapRow(matchRow);+ if (matchRows.length > 1) {+ return this.holdAmbiguous(+ savedObs,+ matchRows.map(row => this.sessionRepo.mapRow(row)),+ 'MULTIPLE_LIVE_AMOUNT_MATCHES'+ );+ }+ if (matchRows.length === 1) {+ currentSession = this.sessionRepo.mapRow(matchRows[0]);}}if (!currentSession) {// Fallback: match the amount, but only inside the receiving account the observer// reported. Matching "any ACTIVE session on the gateway with this amount" could settle a// different merchant's live payment (cross-merchant hijack), so it is intentionally gone.- const scopedRow = this.sessionRepo.db.queryOne(`+ const candidates = this.sessionRepo.db.query(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ?AND status IN ('ACTIVE', 'PROCESSING')AND amount_paise = ?- ORDER BY created_at DESC- LIMIT 1`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);- if (scopedRow) {- currentSession = this.sessionRepo.mapRow(scopedRow);+ if (candidates.length > 1) {+ return this.holdAmbiguous(+ savedObs,+ candidates.map(row => this.sessionRepo.mapRow(row)),+ 'MULTIPLE_LIVE_AMOUNT_MATCHES'+ );+ }+ if (candidates.length === 1) {+ currentSession = this.sessionRepo.mapRow(candidates[0]);}}@@ -323,6 +400,10 @@ export class AttributionEngine {}}+ if (isPriorExpiredSession && isEligibleStatus && isAmountMatch) {+ return this.holdAmbiguous(savedObs, [currentSession], 'LIVE_AND_RECENT_SAME_AMOUNT');+ }+if (isUtrAlreadyUsed) {return {attributed: false,@@ -414,7 +495,7 @@ export class AttributionEngine {});}- this.eventEmitter.emit('PAYMENT.SUCCESS', {+ this.eventEmitter.emit('PAYMENT.OBSERVED_SUCCESS', {paymentId: currentSession.id,orderId: currentSession.orderId,merchantId: currentSession.merchantId,@@ -440,7 +521,7 @@ export class AttributionEngine {wasActive,paymentSessionId: currentSession.id,observationId: savedObs.id,- outcomeStatus: PaymentStatus.SUCCESS,+ outcomeStatus: PaymentStatus.OBSERVED_SUCCESS,verificationLevel: 2,verificationTag: verifyResult.tag,verificationSources: verifyResult.sources@@ -523,7 +604,7 @@ export class AttributionEngine {savedObs.id,{ finalizeSuccess: true });- this.eventEmitter.emit('PAYMENT.SUCCESS', {+ this.eventEmitter.emit('PAYMENT.OBSERVED_SUCCESS', {paymentId: currentSession.id,orderId: currentSession.orderId,merchantId: currentSession.merchantId,@@ -541,7 +622,7 @@ export class AttributionEngine {wasActive,paymentSessionId: currentSession.id,observationId: savedObs.id,- outcomeStatus: PaymentStatus.SUCCESS,+ outcomeStatus: PaymentStatus.OBSERVED_SUCCESS,verificationLevel: finalResult.level,verificationTag: finalResult.tag,verificationSources: finalResult.sources@@ -560,7 +641,12 @@ export class AttributionEngine {this.pendingGraceTimers.delete(targetSessionId);// Check if session became terminal during the grace windowconst latestSession = this.sessionRepo.findById(targetSessionId);- if (!latestSession || (isTerminalStatus(latestSession.status) && latestSession.status !== PaymentStatus.SUCCESS)) {+ const alreadyObserved = latestSession && (+ latestSession.status === PaymentStatus.SUCCESS+ || latestSession.status === PaymentStatus.OBSERVED_SUCCESS+ || latestSession.status === PaymentStatus.RECONCILED+ );+ if (!latestSession || (isTerminalStatus(latestSession.status) && !alreadyObserved)) {const sessionStatus = latestSession ? latestSession.status : 'EXPIRED';this.obsRepo.markLateUnmatched(targetObsId);if (this.auditRepo) {@@ -601,7 +687,7 @@ export class AttributionEngine {return;}- if (latestSession.status === PaymentStatus.SUCCESS) {+ if (alreadyObserved) {return;}@@ -629,7 +715,7 @@ export class AttributionEngine {});}- this.eventEmitter.emit('PAYMENT.SUCCESS', {+ this.eventEmitter.emit('PAYMENT.OBSERVED_SUCCESS', {paymentId: targetSessionId,orderId: targetOrderId,merchantId: targetMerchantId,@@ -664,7 +750,7 @@ export class AttributionEngine {const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();const recentSuccessSession = this.sessionRepo.db.queryOne(`SELECT * FROM payment_sessions- WHERE receiving_account_id = ? AND status = 'SUCCESS'+ WHERE receiving_account_id = ? AND status IN ('SUCCESS', 'OBSERVED_SUCCESS')AND amount_paise = ? AND completed_at >= ?ORDER BY completed_at DESC LIMIT 1`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise), sixtySecsAgo]);@@ -770,7 +856,7 @@ export class AttributionEngine {lateMatch: false,paymentSessionId: recentSuccessSession.id,observationId: savedObs.id,- outcomeStatus: PaymentStatus.SUCCESS,+ outcomeStatus: PaymentStatus.OBSERVED_SUCCESS,verificationLevel: verifyResult.level,verificationTag: verifyResult.tag,verificationSources: verifyResult.sources@@ -786,7 +872,11 @@ export class AttributionEngine {thirtyMinutesAgo);- const lateMatchedSession = recentExpired.find(s => s.amountPaise === normalizedObs.amountPaise);+ const lateMatches = recentExpired.filter(s => s.amountPaise === normalizedObs.amountPaise);+ if (lateMatches.length > 1) {+ return this.holdAmbiguous(savedObs, lateMatches, 'MULTIPLE_LATE_AMOUNT_MATCHES');+ }+ const lateMatchedSession = lateMatches[0];if (lateMatchedSession) {// Mark observation as LATE_UNMATCHEDdiff --git a/packages/core/src/index.js b/packages/core/src/index.jsindex d66df4d..668f1d7 100644--- a/packages/core/src/index.js+++ b/packages/core/src/index.js@@ -9,5 +9,7 @@ export * from './bank-sms-parser.js';export * from './bank-email-parser.js';export * from './qr.js';export * from './verification-pipeline.js';+export * from './statement-parser.js';+export * from './statement-reconciliation.js';export * from './device-security.js';diff --git a/packages/core/src/recovery-engine.js b/packages/core/src/recovery-engine.jsindex 73e0ae1..63929b8 100644--- a/packages/core/src/recovery-engine.js+++ b/packages/core/src/recovery-engine.js@@ -49,17 +49,17 @@ export class RecoveryEngine {for (const row of overdueProcessing) {if (row.verification_level >= 1 || row.attributed_observation_id) {- this.sessionRepo.transitionToTerminal(row.id, PaymentStatus.SUCCESS);+ this.sessionRepo.transitionToTerminal(row.id, PaymentStatus.OBSERVED_SUCCESS);if (this.auditRepo) {this.auditRepo.log({entityType: 'PAYMENT_SESSION',entityId: row.id,- action: 'CRASH_RECOVERY_ATTRIBUTED_SUCCESS',+ action: 'CRASH_RECOVERY_ATTRIBUTED_OBSERVED',actorType: 'SYSTEM'});}if (this.eventEmitter) {- this.eventEmitter.emit('PAYMENT.SUCCESS', {+ this.eventEmitter.emit('PAYMENT.OBSERVED_SUCCESS', {paymentId: row.id,orderId: row.order_id,merchantId: row.merchant_iddiff --git a/packages/core/src/state-machine.js b/packages/core/src/state-machine.jsindex 7ca0aff..d051582 100644--- a/packages/core/src/state-machine.js+++ b/packages/core/src/state-machine.js@@ -1,11 +1,11 @@-import { isValidTransition, isTerminalStatus, VALID_TRANSITIONS } from '@youpi/common';+import { isValidTransition, isTerminalStatus, VALID_TRANSITIONS, IMMUTABLE_STATES } from '@youpi/common';/*** The transition graph and helpers live in `@youpi/common` so the database layer can enforce* them too (`@youpi/db` cannot import `@youpi/core`). They are re-exported here to keep* `@youpi/core` the canonical import site for engine consumers.*/-export { VALID_TRANSITIONS, isValidTransition, isTerminalStatus };+export { VALID_TRANSITIONS, isValidTransition, isTerminalStatus, IMMUTABLE_STATES };/*** Asserts a valid transition, throwing a detailed domain error if violated.@@ -28,6 +28,12 @@ export function assertValidTransition(currentState, nextState) {*/export function toPublicOutcome(status) {switch (status) {+ case 'OBSERVED_SUCCESS':+ return 'OBSERVED_SUCCESS';+ case 'RECONCILED':+ return 'RECONCILED';+ case 'MANUAL_REVIEW':+ return 'MANUAL_REVIEW';case 'SUCCESS':return 'SUCCESS';case 'FAILED':@@ -39,4 +45,25 @@ export function toPublicOutcome(status) {default:throw new Error(`Status '${status}' is an internal non-terminal state and cannot be mapped to a public outcome.`);}+}++/** True when a webhook may be dispatched for this status. */+export function isDispatchableOutcome(status) {+ return isTerminalStatus(status);+}++/** Bank-statement posture carried on webhook payloads. Observer matches are never reconciled. */+export function settlementStateFor(status) {+ switch (status) {+ case 'RECONCILED':+ return 'RECONCILED';+ case 'OBSERVED_SUCCESS':+ return 'NOT_RECONCILED';+ case 'MANUAL_REVIEW':+ return 'MANUAL_REVIEW';+ case 'SUCCESS':+ return 'NOT_BANK_SETTLEMENT';+ default:+ return 'NOT_APPLICABLE';+ }}\ No newline at end of filediff --git a/packages/core/src/statement-parser.js b/packages/core/src/statement-parser.jsnew file mode 100644index 0000000..c27d805--- /dev/null+++ b/packages/core/src/statement-parser.js@@ -0,0 +1,166 @@+/**+ * Parses an operator-downloaded bank statement CSV.+ *+ * HDFC netbanking statements use Date, Narration, Chq./Ref.No., Value Dt,+ * Withdrawal Amt., Deposit Amt., Closing Balance. A UPI credit narration is+ * dash-separated and carries one 12-digit reference, for example+ * UPI-PAYEE-name@upi-IFSC-401537805904-NOTE.+ * Other INR exports are accepted when the header names a date, a narration,+ * and a deposit/credit column. There is no bank-feed client here.+ */++const MAX_STATEMENT_ROWS = 2000;++function parseCsv(text) {+ const rows = [];+ let row = [];+ let cell = '';+ let inQuotes = false;+ const src = String(text || '').replace(/^\uFEFF/, '');+ for (let i = 0; i < src.length; i++) {+ const c = src[i];+ if (inQuotes) {+ if (c === '"') {+ if (src[i + 1] === '"') {+ cell += '"';+ i += 1;+ } else {+ inQuotes = false;+ }+ } else {+ cell += c;+ }+ continue;+ }+ if (c === '"') {+ inQuotes = true;+ } else if (c === ',') {+ row.push(cell);+ cell = '';+ } else if (c === '\n') {+ row.push(cell);+ rows.push(row);+ row = [];+ cell = '';+ } else if (c !== '\r') {+ cell += c;+ }+ }+ if (cell.length > 0 || row.length > 0) {+ row.push(cell);+ rows.push(row);+ }+ return rows;+}++function headerKey(value) {+ return String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();+}++function classifyHeader(value) {+ const h = headerKey(value);+ if (!h) return null;+ if (h === 'date' || h === 'txn date' || h === 'transaction date' || h === 'tran date') return 'date';+ if (h === 'value dt' || h === 'value date' || h.startsWith('value dt')) return 'valueDate';+ if (h === 'narration' || h === 'description' || h.includes('particular') || h.includes('remark')) return 'narration';+ if (h.includes('withdrawal') || h === 'debit' || h.startsWith('debit ')) return 'debit';+ if (h.includes('deposit') || h === 'credit' || h.startsWith('credit ')) return 'credit';+ if (h.includes('chq') || h.includes('ref')) return 'ref';+ return null;+}++function columnMap(headerRow) {+ const map = {};+ headerRow.forEach((cell, index) => {+ const kind = classifyHeader(cell);+ if (kind && map[kind] === undefined) map[kind] = index;+ });+ if (map.date === undefined || map.narration === undefined || map.credit === undefined) return null;+ return map;+}++export function rupeesToPaise(raw) {+ const text = String(raw ?? '').trim();+ if (!text || text === '-' || text === '0' || text === '0.00' || text === '0.0') return 0;+ const cleaned = text.replace(/[₹,\s]/g, '').replace(/(cr|dr)$/i, '');+ if (!/^\d+(\.\d{1,2})?$/.test(cleaned)) return null;+ const [whole, frac = ''] = cleaned.split('.');+ return Number(whole) * 100 + Number(frac.padEnd(2, '0'));+}++export function parseStatementDate(raw) {+ const text = String(raw || '').trim();+ let match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);+ if (match) return `${match[1]}-${match[2]}-${match[3]}`;+ match = /^(\d{2})[/-](\d{2})[/-](\d{4})$/.exec(text);+ if (match) return `${match[3]}-${match[2]}-${match[1]}`;+ match = /^(\d{2})[/-](\d{2})[/-](\d{2})$/.exec(text);+ if (match) {+ const year = Number(match[3]) < 70 ? 2000 + Number(match[3]) : 1900 + Number(match[3]);+ return `${year}-${match[2]}-${match[1]}`;+ }+ return null;+}++export function extractTwelveDigitReferences(narration, ref) {+ const found = `${ref || ''} ${narration || ''}`.match(/\d{12}/g) || [];+ return [...new Set(found)];+}++/**+ * @param {string} csvText+ * @returns {{ error?: string, lines: Array<{+ * bookedOn: string|null, amountPaise: number, direction: 'CREDIT'|'DEBIT',+ * utr: string|null, referenceCount: number, narration: string, ref: string+ * }> }}+ */+export function parseStatementCsv(csvText) {+ const rows = parseCsv(csvText);+ let headerAt = -1;+ let columns = null;+ const scanLimit = Math.min(rows.length, 40);+ for (let i = 0; i < scanLimit; i++) {+ const mapped = columnMap(rows[i]);+ if (mapped) {+ headerAt = i;+ columns = mapped;+ break;+ }+ }+ if (!columns) {+ return {+ error: 'UNSUPPORTED_STATEMENT',+ lines: []+ };+ }++ const lines = [];+ for (let i = headerAt + 1; i < rows.length; i++) {+ if (lines.length >= MAX_STATEMENT_ROWS) {+ return { error: 'STATEMENT_TOO_LARGE', lines: [] };+ }+ const row = rows[i];+ const bookedOn = parseStatementDate(row[columns.valueDate ?? columns.date] || row[columns.date]);+ const narration = String(row[columns.narration] || '').trim();+ const ref = columns.ref === undefined ? '' : String(row[columns.ref] || '').trim();+ if (!bookedOn && !narration) continue;+ const creditPaise = rupeesToPaise(row[columns.credit]);+ const debitPaise = columns.debit === undefined ? 0 : rupeesToPaise(row[columns.debit]);+ if (creditPaise === null || debitPaise === null || !bookedOn) continue;+ const credit = creditPaise > 0 ? creditPaise : 0;+ const debit = debitPaise > 0 ? debitPaise : 0;+ if (credit > 0 && debit > 0) continue;+ if (credit === 0 && debit === 0) continue;+ const references = extractTwelveDigitReferences(narration, ref);+ lines.push({+ bookedOn,+ amountPaise: credit > 0 ? credit : debit,+ direction: credit > 0 ? 'CREDIT' : 'DEBIT',+ utr: references.length === 1 ? references[0] : null,+ referenceCount: references.length,+ narration,+ ref+ });+ }+ return { lines };+}diff --git a/packages/core/src/statement-reconciliation.js b/packages/core/src/statement-reconciliation.jsnew file mode 100644index 0000000..cce4d64--- /dev/null+++ b/packages/core/src/statement-reconciliation.js@@ -0,0 +1,263 @@+import crypto from 'node:crypto';+import { PaymentStatus } from '@youpi/common';+import { parseStatementCsv } from './statement-parser.js';++/** Statement value date may post on the observation day or the next two calendar days. */+export const STATEMENT_POSTING_DAYS = 2;++export function calendarDateInIndia(value) {+ const date = value instanceof Date ? value : new Date(value);+ if (Number.isNaN(date.getTime())) return null;+ return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Kolkata' }).format(date);+}++function addCalendarDays(isoDate, days) {+ const [year, month, day] = isoDate.split('-').map(Number);+ const date = new Date(Date.UTC(year, month - 1, day));+ date.setUTCDate(date.getUTCDate() + days);+ return date.toISOString().slice(0, 10);+}++function sourceHash(receivingAccountId, line) {+ return crypto.createHash('sha256').update([+ receivingAccountId,+ line.bookedOn || '',+ String(line.amountPaise),+ line.direction,+ line.utr || '',+ line.referenceCount,+ line.narration+ ].join('|')).digest('hex');+}++function sameAmount(session, amountPaise) {+ return BigInt(session.amountPaise) === BigInt(amountPaise);+}++/**+ * Applies operator-imported statement lines. An observer alert cannot call this.+ * RECONCILED is written only when one session on the same receiving account has+ * the same paise amount and the same 12-digit reference, inside the posting window.+ */+export class StatementReconciliation {+ constructor({ db, sessionRepo, auditRepo = null, eventEmitter = null }) {+ this.db = db;+ this.sessionRepo = sessionRepo;+ this.auditRepo = auditRepo;+ this.eventEmitter = eventEmitter;+ }++ importCsv({ receivingAccountId, csvText }) {+ const parsed = parseStatementCsv(csvText);+ if (parsed.error) return { error: parsed.error, lines: [] };+ const lines = parsed.lines.map(line => this.applyLine(receivingAccountId, line));+ return {+ lines,+ reconciled: lines.filter(line => line.outcome === 'RECONCILED').length,+ conflicts: lines.filter(line => line.outcome === 'CONFLICT').length,+ unmatched: lines.filter(line => line.outcome === 'UNMATCHED').length+ };+ }++ applyLine(receivingAccountId, line) {+ const hash = sourceHash(receivingAccountId, line);+ const existing = this.db.queryOne(+ 'SELECT * FROM bank_statement_lines WHERE receiving_account_id = ? AND source_hash = ?',+ [receivingAccountId, hash]+ );+ if (existing && existing.match_status === 'RECONCILED') {+ return {+ outcome: 'DUPLICATE',+ matchStatus: 'RECONCILED',+ paymentSessionId: existing.payment_session_id,+ statementLineId: existing.id,+ utr: existing.utr+ };+ }++ const rowId = existing?.id || crypto.randomUUID();+ if (!existing) {+ this.db.execute(`+ INSERT INTO bank_statement_lines (+ id, receiving_account_id, source_hash, booked_on, amount_paise, currency,+ direction, utr, narration, match_status, match_reason, payment_session_id, imported_at+ ) VALUES (?, ?, ?, ?, ?, 'INR', ?, ?, ?, 'UNMATCHED', NULL, NULL, ?)+ `, [+ rowId,+ receivingAccountId,+ hash,+ line.bookedOn,+ line.amountPaise,+ line.direction,+ line.utr,+ line.narration,+ new Date().toISOString()+ ]);+ }++ if (line.direction !== 'CREDIT') {+ return this.finish(rowId, 'IGNORED', 'DEBIT', null);+ }+ if (!line.utr) {+ const reason = line.referenceCount > 1 ? 'AMBIGUOUS_REFERENCE' : 'MISSING_REFERENCE';+ return this.finish(rowId, 'CONFLICT', reason, null);+ }++ const already = this.findReconciled(receivingAccountId, line);+ if (already) {+ return this.finish(rowId, 'RECONCILED', 'ALREADY_RECONCILED', already.id, { emit: false });+ }++ const attributed = this.findAttributed(receivingAccountId, line.utr)+ .filter(session => session.currency === 'INR' || !session.currency);+ const exact = attributed.filter(session => sameAmount(session, line.amountPaise));+ const amountConflicts = attributed.filter(session => !sameAmount(session, line.amountPaise));++ if (exact.length > 1 || amountConflicts.length > 0) {+ this.holdAll([...exact, ...amountConflicts], 'STATEMENT_AMOUNT_OR_DUPLICATE');+ return this.finish(rowId, 'CONFLICT', exact.length > 1 ? 'MULTIPLE_SESSIONS' : 'AMOUNT_MISMATCH', null);+ }+ if (exact.length === 1) {+ const session = exact[0];+ const observedOn = this.observedCalendarDate(session);+ if (!observedOn || !this.withinPostingWindow(observedOn, line.bookedOn)) {+ this.holdAll([session], 'STATEMENT_DATE_OUTSIDE_WINDOW');+ return this.finish(rowId, 'CONFLICT', 'STATEMENT_DATE_OUTSIDE_WINDOW', null);+ }+ return this.reconcile(rowId, session);+ }++ const held = this.findManualReviewByAmount(receivingAccountId, line.amountPaise);+ const seen = this.observationsForReference(receivingAccountId, line);+ if (held.length === 1 && seen.length >= 1) {+ const observedOn = calendarDateInIndia(seen[0].observed_at);+ if (!observedOn || !this.withinPostingWindow(observedOn, line.bookedOn)) {+ return this.finish(rowId, 'CONFLICT', 'STATEMENT_DATE_OUTSIDE_WINDOW', null);+ }+ return this.reconcile(rowId, held[0]);+ }+ if (held.length > 1 && seen.length >= 1) {+ return this.finish(rowId, 'CONFLICT', 'MULTIPLE_SESSIONS', null);+ }+ return this.finish(rowId, 'UNMATCHED', 'NO_OBSERVED_SESSION', null);+ }++ withinPostingWindow(observedOn, bookedOn) {+ return bookedOn >= observedOn && bookedOn <= addCalendarDays(observedOn, STATEMENT_POSTING_DAYS);+ }++ observedCalendarDate(session) {+ const row = this.db.queryOne(+ 'SELECT observed_at FROM payment_observations WHERE id = ? OR attributed_payment_id = ? ORDER BY observed_at ASC LIMIT 1',+ [session.attributedObservationId || '', session.id]+ );+ return calendarDateInIndia(row?.observed_at || session.completedAt || session.createdAt);+ }++ findAttributed(receivingAccountId, utr) {+ const rows = this.db.query(`+ SELECT DISTINCT ps.*+ FROM payment_sessions ps+ JOIN payment_observations po+ ON po.attributed_payment_id = ps.id OR ps.attributed_observation_id = po.id+ WHERE ps.receiving_account_id = ?+ AND ps.status IN ('OBSERVED_SUCCESS', 'MANUAL_REVIEW')+ AND po.bank_reference_number = ?+ `, [receivingAccountId, utr]);+ return rows.map(row => this.sessionRepo.mapRow(row));+ }++ findReconciled(receivingAccountId, line) {+ const row = this.db.queryOne(`+ SELECT ps.*+ FROM payment_sessions ps+ JOIN payment_observations po+ ON po.attributed_payment_id = ps.id OR ps.attributed_observation_id = po.id+ WHERE ps.receiving_account_id = ?+ AND ps.status = 'RECONCILED'+ AND ps.amount_paise = ?+ AND po.bank_reference_number = ?+ LIMIT 1+ `, [receivingAccountId, line.amountPaise, line.utr]);+ return row ? this.sessionRepo.mapRow(row) : null;+ }++ findManualReviewByAmount(receivingAccountId, amountPaise) {+ const rows = this.db.query(`+ SELECT * FROM payment_sessions+ WHERE receiving_account_id = ? AND status = 'MANUAL_REVIEW' AND amount_paise = ?+ `, [receivingAccountId, amountPaise]);+ return rows.map(row => this.sessionRepo.mapRow(row));+ }++ observationsForReference(receivingAccountId, line) {+ return this.db.query(`+ SELECT id, observed_at FROM payment_observations+ WHERE receiving_account_id = ? AND bank_reference_number = ? AND amount_paise = ?+ `, [receivingAccountId, line.utr, line.amountPaise]);+ }++ holdAll(sessions, reason) {+ for (const session of sessions) {+ if (session.status !== PaymentStatus.OBSERVED_SUCCESS && session.status !== PaymentStatus.MANUAL_REVIEW) continue;+ const before = session.status;+ try {+ const updated = this.sessionRepo.transitionToTerminal(session.id, PaymentStatus.MANUAL_REVIEW);+ if (before !== PaymentStatus.MANUAL_REVIEW && updated.status === PaymentStatus.MANUAL_REVIEW) {+ this.eventEmitter?.emit('PAYMENT.MANUAL_REVIEW', {+ paymentId: session.id,+ orderId: session.orderId,+ merchantId: session.merchantId,+ reason+ });+ }+ } catch {+ // An illegal edge leaves the session unreconciled. The statement row records the conflict.+ }+ }+ }++ reconcile(rowId, session) {+ const before = session.status;+ const updated = this.sessionRepo.transitionToTerminal(session.id, PaymentStatus.RECONCILED);+ if (updated.status !== PaymentStatus.RECONCILED) {+ return this.finish(rowId, 'CONFLICT', 'TRANSITION_REJECTED', null);+ }+ const emit = before !== PaymentStatus.RECONCILED;+ return this.finish(rowId, 'RECONCILED', 'BANK_STATEMENT_MATCH', updated.id, { emit, session: updated });+ }++ finish(rowId, matchStatus, matchReason, paymentSessionId, options = {}) {+ this.db.execute(`+ UPDATE bank_statement_lines+ SET match_status = ?, match_reason = ?, payment_session_id = ?+ WHERE id = ?+ `, [matchStatus, matchReason, paymentSessionId, rowId]);+ if (options.emit && options.session) {+ this.auditRepo?.log({+ merchantId: options.session.merchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: options.session.id,+ action: 'BANK_STATEMENT_RECONCILED',+ actorType: 'ADMIN',+ details: { statementLineId: rowId, amountPaise: options.session.amountPaise.toString() }+ });+ this.eventEmitter?.emit('PAYMENT.RECONCILED', {+ paymentId: options.session.id,+ orderId: options.session.orderId,+ merchantId: options.session.merchantId,+ amountPaise: options.session.amountPaise,+ statementLineId: rowId+ });+ }+ return {+ outcome: matchStatus === 'RECONCILED' && options.emit === false && matchReason === 'ALREADY_RECONCILED'+ ? 'DUPLICATE'+ : matchStatus,+ matchStatus,+ matchReason,+ paymentSessionId,+ statementLineId: rowId+ };+ }+}diff --git a/packages/core/src/timing-engine.js b/packages/core/src/timing-engine.jsindex 105d135..ddf6363 100644--- a/packages/core/src/timing-engine.js+++ b/packages/core/src/timing-engine.js@@ -203,7 +203,7 @@ export class TimingEngine {const session = this.sessionRepo.findById(sessionId);if (!session) return null;- if ([PaymentStatus.PROCESSING, PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.SUSPICIOUS].includes(session.status)) {+ if ([PaymentStatus.PROCESSING, PaymentStatus.SUCCESS, PaymentStatus.OBSERVED_SUCCESS, PaymentStatus.RECONCILED, PaymentStatus.MANUAL_REVIEW, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {return session; // cannot cancel in-flight PROCESSING or already terminal sessions}diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.jsindex 9c0fa66..bd0fa96 100644--- a/packages/core/src/verification-pipeline.js+++ b/packages/core/src/verification-pipeline.js@@ -272,7 +272,7 @@ export class PaymentVerificationPipeline {if (!session && input.receivingAccountId) {const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();const row = this.db.queryOne(- `SELECT * FROM payment_sessions WHERE receiving_account_id = ? AND status = 'SUCCESS' AND completed_at >= ? ORDER BY completed_at DESC LIMIT 1`,+ `SELECT * FROM payment_sessions WHERE receiving_account_id = ? AND status IN ('SUCCESS', 'OBSERVED_SUCCESS', 'RECONCILED') AND completed_at >= ? ORDER BY completed_at DESC LIMIT 1`,[input.receivingAccountId, sixtySecsAgo]);if (row) session = this.sessionRepo.mapRow(row);@@ -780,7 +780,7 @@ export class PaymentVerificationPipeline {SELECT ps.id, ps.order_idFROM payment_sessions psJOIN payment_observations po ON ps.attributed_observation_id = po.id- WHERE ps.status = 'SUCCESS'+ WHERE ps.status IN ('SUCCESS', 'OBSERVED_SUCCESS', 'RECONCILED')AND ps.id != ?AND po.bank_reference_number = ?LIMIT 1@@ -1081,12 +1081,19 @@ export class PaymentVerificationPipeline {stage: 6,name: 'ATTRIBUTION',status: 'FLAGGED_SUSPICIOUS',- outcomeStatus: 'SUSPICIOUS',- details: 'Payment held in SUSPICIOUS state (DO NOT PAY). Observation flagged for security review.'+ outcomeStatus: PaymentStatus.MANUAL_REVIEW,+ details: 'Payment held for manual review. Observation flagged for security review. Not bank-confirmed.'};+ if (session?.id && this.sessionRepo && [PaymentStatus.ACTIVE, PaymentStatus.PROCESSING, PaymentStatus.INITIATED, PaymentStatus.QUEUED].includes(session.status)) {+ try {+ this.sessionRepo.transitionToTerminal(session.id, PaymentStatus.MANUAL_REVIEW, { reason: 'FRAUDULENT_PAYMENT_INJECTION' });+ session.status = PaymentStatus.MANUAL_REVIEW;+ } catch {}+ }+return buildResult({- finalStatus: 'SUSPICIOUS',+ finalStatus: PaymentStatus.MANUAL_REVIEW,failingStage: 5,failingCondition: 'FRAUDULENT_PAYMENT_INJECTION',failingReason: securityDiagnostic,diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 8ca9fc8..de047b5 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -1,6 +1,6 @@import crypto from 'node:crypto';import { generateHmac, toRupeesString, validateOutboundWebhookUrl } from '@youpi/common';-import { isTerminalStatus, toPublicOutcome } from './state-machine.js';+import { toPublicOutcome, isDispatchableOutcome, settlementStateFor } from './state-machine.js';export class WebhookEngine {/**@@ -28,7 +28,7 @@ export class WebhookEngine {return { delivered: false, deliveryId: '', error: 'No webhook URL configured for merchant.' };}- const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;+ const publicOutcome = isDispatchableOutcome(event) ? toPublicOutcome(event) : event;const nowIso = new Date().toISOString();// 1. Up-front secret validation: if webhookSecret is missing, persist a failed row so it is auditable@@ -106,6 +106,7 @@ export class WebhookEngine {utr: String(utr || ''),verificationTag: session.verificationTag || session.verification_tag || (session.method === 'COD' ? 'COD_ORDER_PLACED' : 'UNVERIFIED'),verificationLevel: session.verificationLevel != null ? Number(session.verificationLevel) : (session.verification_level != null ? Number(session.verification_level) : (session.method === 'COD' ? 1 : 0)),+ settlementState: settlementStateFor(publicOutcome),completedAt: session.completedAt ? (typeof session.completedAt.toISOString === 'function' ? session.completedAt.toISOString() : String(session.completedAt)) : new Date().toISOString(),metadata: session.metadata || {}};diff --git a/packages/db/src/__tests__/auth-matrix.test.js b/packages/db/src/__tests__/auth-matrix.test.jsindex 8241686..4bff294 100644--- a/packages/db/src/__tests__/auth-matrix.test.js+++ b/packages/db/src/__tests__/auth-matrix.test.js@@ -408,7 +408,7 @@ test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrix});assert.equal(obs.attributed, true);assert.equal(obs.paymentSessionId, unauthPayment.paymentId);- assert.equal(obs.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(obs.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);// --- DEMO STORE (37 - 40) ---// 37 & 38. Demo Purchase redirects without storefront authdiff --git a/packages/db/src/repositories/observation.repository.js b/packages/db/src/repositories/observation.repository.jsindex 59fe69a..2bcba78 100644--- a/packages/db/src/repositories/observation.repository.js+++ b/packages/db/src/repositories/observation.repository.js@@ -94,6 +94,16 @@ export class ObservationRepository {return this.findById(id);}+ markAmbiguous(id) {+ this.db.execute(`+ UPDATE payment_observations+ SET attribution_status = ?+ WHERE id = ?+ `, [ObservationAttributionStatus.AMBIGUOUS, id]);++ return this.findById(id);+ }+markLateUnmatched(id) {this.db.execute(`UPDATE payment_observationsdiff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex 7e67671..c7de288 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -1,5 +1,5 @@import crypto from 'node:crypto';-import { PaymentStatus, PaymentMethod, isValidTransition, TERMINAL_STATES } from '@youpi/common';+import { PaymentStatus, PaymentMethod, isValidTransition, TERMINAL_STATES, IMMUTABLE_STATES } from '@youpi/common';export class PaymentSessionRepository {/**@@ -229,20 +229,12 @@ export class PaymentSessionRepository {const session = this.findById(sessionId);if (!session) throw new Error(`Session not found: ${sessionId}`);- // Terminal states are final- const terminalStates = [- PaymentStatus.SUCCESS,- PaymentStatus.FAILED,- PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED- ];-- if (terminalStates.includes(session.status)) {- return session; // already terminal, idempotent+ // Immutable outcomes stay put. OBSERVED_SUCCESS and MANUAL_REVIEW may still+ // move to RECONCILED later, but only by an explicit statement workflow.+ if (IMMUTABLE_STATES.includes(session.status) || session.status === targetStatus) {+ return session;}- // The state machine is enforced here rather than merely documented: without this,- // any caller could move a live session straight to SUCCESS and bypass verification.if (!TERMINAL_STATES.includes(targetStatus)) {throw new Error(`Not a terminal target status: ${targetStatus}`);}@@ -251,6 +243,7 @@ export class PaymentSessionRepository {}const now = new Date().toISOString();+ const completedAtIso = session.completedAt ? new Date(session.completedAt).toISOString() : now;const attributedObsId = options.attributedObservationId || session.attributedObservationId || null;let metadata = session.metadata || {};@@ -271,7 +264,7 @@ export class PaymentSessionRepository {UPDATE payment_sessionsSET status = ?, completed_at = ?, attributed_observation_id = ?, metadata = ?, updated_at = ?WHERE id = ?- `, [targetStatus, now, attributedObsId, JSON.stringify(metadata), now, sessionId]);+ `, [targetStatus, completedAtIso, attributedObsId, JSON.stringify(metadata), now, sessionId]);// Release slot on receiving account if this session owned itif (session.receivingAccountId) {@@ -496,7 +489,9 @@ export class PaymentSessionRepository {const DEAD_STATES = [PaymentStatus.FAILED,PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED+ PaymentStatus.CANCELLED,+ PaymentStatus.MANUAL_REVIEW,+ PaymentStatus.RECONCILED];if (DEAD_STATES.includes(session.status)) {return {@@ -525,13 +520,19 @@ export class PaymentSessionRepository {tag = `Dual Verification (${sourceLabels.join(' + ')})`;}+ const alreadyClosed = session.status === PaymentStatus.OBSERVED_SUCCESS+ || session.status === PaymentStatus.SUCCESS+ || session.status === PaymentStatus.RECONCILED;const shouldFinalize = options.finalizeSuccess !== false;- const wantsSuccess = shouldFinalize && level >= 1;- if (wantsSuccess && session.status !== PaymentStatus.SUCCESS && !isValidTransition(session.status, PaymentStatus.SUCCESS)) {- throw new Error(`Illegal payment state transition: cannot move from '${session.status}' to 'SUCCESS'.`);+ const wantsObserved = shouldFinalize && level >= 1 && !alreadyClosed;+ if (wantsObserved && !isValidTransition(session.status, PaymentStatus.OBSERVED_SUCCESS)) {+ throw new Error(`Illegal payment state transition: cannot move from '${session.status}' to 'OBSERVED_SUCCESS'.`);+ }+ const isFirstSuccess = wantsObserved;+ const targetStatus = wantsObserved ? PaymentStatus.OBSERVED_SUCCESS : session.status;+ if (wantsObserved) {+ tag = `${tag} | OBSERVED_NOT_RECONCILED`;}- const isFirstSuccess = wantsSuccess && session.status !== PaymentStatus.SUCCESS;- const targetStatus = wantsSuccess ? PaymentStatus.SUCCESS : session.status;const now = new Date().toISOString();this.db.execute(`@@ -550,13 +551,13 @@ export class PaymentSessionRepository {JSON.stringify(sources),tag,observationId,- targetStatus === PaymentStatus.SUCCESS ? now : null,+ targetStatus === PaymentStatus.OBSERVED_SUCCESS ? now : null,now,sessionId]);// If this transition made it terminal SUCCESS, release slot on receiving account- if (targetStatus === PaymentStatus.SUCCESS && session.receivingAccountId) {+ if (targetStatus === PaymentStatus.OBSERVED_SUCCESS && session.receivingAccountId) {this.db.execute(`UPDATE payment_receiving_accountsSET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ?diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sqlindex 344fb6c..0fdb281 100644--- a/packages/db/src/schema.sql+++ b/packages/db/src/schema.sql@@ -264,4 +264,26 @@ CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (custCREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);+-- 11. Bank statement lines imported by an operator. Observers do not write this table.+CREATE TABLE IF NOT EXISTS bank_statement_lines (+ id TEXT PRIMARY KEY,+ receiving_account_id TEXT NOT NULL REFERENCES payment_receiving_accounts(id) ON DELETE CASCADE,+ source_hash VARCHAR(64) NOT NULL,+ booked_on DATE NOT NULL,+ amount_paise BIGINT NOT NULL,+ currency VARCHAR(3) NOT NULL DEFAULT 'INR',+ direction VARCHAR(10) NOT NULL,+ utr VARCHAR(32),+ narration TEXT NOT NULL DEFAULT '',+ match_status VARCHAR(32) NOT NULL,+ match_reason VARCHAR(64),+ payment_session_id TEXT REFERENCES payment_sessions(id),+ imported_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_statement_lines_source+ ON bank_statement_lines (receiving_account_id, source_hash);+CREATE INDEX IF NOT EXISTS idx_statement_lines_utr+ ON bank_statement_lines (receiving_account_id, utr);+diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex 0a02841..b5331bf 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -267,5 +267,27 @@ CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (custCREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);+-- 11. Bank statement lines imported by an operator. Observers do not write this table.+CREATE TABLE IF NOT EXISTS bank_statement_lines (+ id TEXT PRIMARY KEY,+ receiving_account_id TEXT NOT NULL REFERENCES payment_receiving_accounts(id) ON DELETE CASCADE,+ source_hash TEXT NOT NULL,+ booked_on TEXT NOT NULL,+ amount_paise INTEGER NOT NULL,+ currency TEXT NOT NULL DEFAULT 'INR',+ direction TEXT NOT NULL,+ utr TEXT,+ narration TEXT NOT NULL DEFAULT '',+ match_status TEXT NOT NULL,+ match_reason TEXT,+ payment_session_id TEXT REFERENCES payment_sessions(id),+ imported_at TEXT NOT NULL DEFAULT (datetime('now'))+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_statement_lines_source+ ON bank_statement_lines (receiving_account_id, source_hash);+CREATE INDEX IF NOT EXISTS idx_statement_lines_utr+ ON bank_statement_lines (receiving_account_id, utr);+diff --git a/packages/merchant-sdk/src/youpi-checkout.js b/packages/merchant-sdk/src/youpi-checkout.jsindex 62bbedb..11cdc45 100644--- a/packages/merchant-sdk/src/youpi-checkout.js+++ b/packages/merchant-sdk/src/youpi-checkout.js@@ -464,6 +464,29 @@ _isSafeRedirect(url) {}});}, 1500);+ } else if (event === 'youpi.payment_observed' || event === 'youpi.payment_reconciled' || event === 'youpi.payment_manual_review') {+ const payload = e.data.data || {};+ const status = event === 'youpi.payment_reconciled'+ ? 'RECONCILED'+ : (event === 'youpi.payment_manual_review' ? 'MANUAL_REVIEW' : 'OBSERVED_SUCCESS');+ const result = {+ status,+ order_id: payload.orderId || this.options.orderId || this.options.order_id,+ payment_mode: payload.method || 'UPI',+ amount_received: Number(payload.amount || this.options.amount || 0),+ utr: payload.bankRef || payload.utr || payload.reference || '',+ timestamp: payload.completedAt || new Date().toISOString(),+ metadata: payload.metadata || this.options.metadata || {},+ settlement_state: payload.settlementState || (status === 'RECONCILED' ? 'RECONCILED' : (status === 'MANUAL_REVIEW' ? 'MANUAL_REVIEW' : 'NOT_RECONCILED')),+ raw: payload+ };+ const domEvent = status === 'RECONCILED'+ ? 'youpi:payment:success'+ : (status === 'MANUAL_REVIEW' ? 'youpi:payment:suspicious' : 'youpi:payment:observed');+ YoupiCheckout._emitEvent(domEvent, result);+ YoupiCheckout._emitEvent('youpi:payment:result', result);+ if (typeof this.options.handler === 'function') this.options.handler(result);+ if (status === 'RECONCILED' && typeof this.options.onSuccess === 'function') this.options.onSuccess(result);} else if (event === 'youpi.payment_failed') {const payload = e.data.data || e.data || {};const result = {diff --git a/packages/merchant-sdk/src/youpi.js b/packages/merchant-sdk/src/youpi.jsindex 0bf5006..deeddc5 100644--- a/packages/merchant-sdk/src/youpi.js+++ b/packages/merchant-sdk/src/youpi.js@@ -471,6 +471,29 @@ _isSafeRedirect(url) {}});}, 1500);+ } else if (event === 'youpi.payment_observed' || event === 'youpi.payment_reconciled' || event === 'youpi.payment_manual_review') {+ const payload = e.data.data || {};+ const status = event === 'youpi.payment_reconciled'+ ? 'RECONCILED'+ : (event === 'youpi.payment_manual_review' ? 'MANUAL_REVIEW' : 'OBSERVED_SUCCESS');+ const result = {+ status,+ order_id: payload.orderId || this.options.orderId || this.options.order_id,+ payment_mode: payload.method || 'UPI',+ amount_received: Number(payload.amount || this.options.amount || 0),+ utr: payload.bankRef || payload.utr || payload.reference || '',+ timestamp: payload.completedAt || new Date().toISOString(),+ metadata: payload.metadata || this.options.metadata || {},+ settlement_state: payload.settlementState || (status === 'RECONCILED' ? 'RECONCILED' : (status === 'MANUAL_REVIEW' ? 'MANUAL_REVIEW' : 'NOT_RECONCILED')),+ raw: payload+ };+ const domEvent = status === 'RECONCILED'+ ? 'youpi:payment:success'+ : (status === 'MANUAL_REVIEW' ? 'youpi:payment:suspicious' : 'youpi:payment:observed');+ YoupiCheckout._emitEvent(domEvent, result);+ YoupiCheckout._emitEvent('youpi:payment:result', result);+ if (typeof this.options.handler === 'function') this.options.handler(result);+ if (status === 'RECONCILED' && typeof this.options.onSuccess === 'function') this.options.onSuccess(result);} else if (event === 'youpi.payment_failed') {const payload = e.data.data || e.data || {};const result = {diff --git a/scripts/chaos-concurrency.test.js b/scripts/chaos-concurrency.test.jsindex 0cb65ae..b65d56d 100644--- a/scripts/chaos-concurrency.test.js+++ b/scripts/chaos-concurrency.test.js@@ -179,7 +179,7 @@ describe('Phase 16: Comprehensive Chaos & Concurrency Verification', () => {// Multi-channel flood confirms payment at Level 1, then upgrades to Level 2 (Dual Verification)!assert.equal(resSms.attributed, true);- assert.equal(resSms.outcomeStatus, PaymentStatus.SUCCESS);+ assert.equal(resSms.outcomeStatus, PaymentStatus.OBSERVED_SUCCESS);assert.equal(resSms.verificationLevel, 1);assert.equal(resGmail.attributed, true);@@ -193,7 +193,7 @@ describe('Phase 16: Comprehensive Chaos & Concurrency Verification', () => {// Session transitions to SUCCESSconst checkDb = sessionRepo.findById(activeSession.id);- assert.equal(checkDb.status, PaymentStatus.SUCCESS);+ assert.equal(checkDb.status, PaymentStatus.OBSERVED_SUCCESS);});test('CHAOS 4: Promotion cascade: completed session immediately unblocks waiting queue in order', () => {@@ -245,13 +245,13 @@ describe('Phase 16: Comprehensive Chaos & Concurrency Verification', () => {const lateResult = attributionEngine.processObservation(delayedObs);- // MUST NOT attribute to Active Customer B!+ // MUST NOT attribute to Active Customer B. Same amount as a recent expiry is manual review.assert.equal(lateResult.attributed, false);- assert.equal(lateResult.lateMatch, true);- assert.equal(lateResult.paymentSessionId, expiredSession.id);+ assert.equal(lateResult.ambiguous, true);+ assert.equal(lateResult.outcomeStatus, PaymentStatus.MANUAL_REVIEW);- // Customer B must still be ACTIVEconst checkB = sessionRepo.findById(activeCustomerB.id);- assert.equal(checkB.status, PaymentStatus.ACTIVE);+ assert.equal(checkB.status, PaymentStatus.MANUAL_REVIEW);+ assert.equal(sessionRepo.findById(expiredSession.id).status, PaymentStatus.EXPIRED);});});diff --git a/scripts/test-all.js b/scripts/test-all.jsindex 6f9ea7d..61b5120 100644--- a/scripts/test-all.js+++ b/scripts/test-all.js@@ -7,6 +7,7 @@ const testFiles = ['packages/db/src/__tests__/db.test.js','packages/db/src/__tests__/schema-parity.test.js','packages/core/src/__tests__/core.test.js',+ 'packages/core/src/__tests__/statement-reconciliation.test.js','packages/core/src/__tests__/queue-timing.test.js','packages/core/src/__tests__/webhook-engine.test.js','packages/merchant-sdk/src/__tests__/merchant-sdk.test.js',@@ -23,6 +24,8 @@ const testFiles = ['apps/android-observer-app/__tests__/android-observer.test.js','apps/control-center/src/__tests__/control-center.test.js','apps/payment-api/src/__tests__/payment-api.test.js',+ 'apps/payment-api/src/__tests__/phase1-observed-success.test.js',+ 'apps/payment-api/src/__tests__/statement-import.test.js','apps/payment-api/src/__tests__/auth-guard.test.js','apps/payment-api/src/__tests__/counter-payments.test.js','apps/payment-api/src/__tests__/selling-modes-and-cod.test.js',