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(core): harden cross-channel deduplication, ambiguous manual review holds, and unmatched reconciliation (#130)
Harsh0750e1926f7f
diff --git a/packages/core/src/__tests__/fail-closed-attribution.test.js b/packages/core/src/__tests__/fail-closed-attribution.test.jsindex 3b30543..427c91e 100644--- a/packages/core/src/__tests__/fail-closed-attribution.test.js+++ b/packages/core/src/__tests__/fail-closed-attribution.test.js@@ -436,4 +436,154 @@ describe('Phase 9A Fail-Closed Payment Attribution Hardening Suite', () => {assert.equal(promoted.id, s2.id);assert.equal(sessionRepo.findById(s2.id).status, PaymentStatus.ACTIVE);});++ test('9. Cross-channel vs same-channel-family deduplication: SMS_GATEWAY + ANDROID_OBSERVER does not falsely upgrade to Level 2', () => {+ const session = sessionRepo.create({+ merchantId: merchantA.id,+ receivingAccountId: accountA.id,+ orderId: 'ORD-SAME-FAMILY-DEDUP',+ amountPaise: 25000n+ });+ sessionRepo.acquireSlotAtomic(session.id, accountA.id, 300000);++ // 1st SMS observation via SMS_GATEWAY+ const smsRes = pipeline.process({+ source: 'SMS_GATEWAY',+ rawText: 'Received Rs 250.00 on UPI. Ref: 888877776666',+ sender: 'HDFCBK',+ receivingAccountId: accountA.id+ });+ assert.equal(smsRes.status, 'VERIFIED');+ assert.equal(sessionRepo.findById(session.id).verificationLevel, 1);++ // 2nd observation of the same SMS via ANDROID_OBSERVER (same SMS channel family, NOT Gmail)+ const androidDupRes = pipeline.process({+ source: 'ANDROID_OBSERVER',+ rawText: 'Received Rs 250.00 on UPI. Ref: 888877776666',+ sender: 'HDFCBK',+ receivingAccountId: accountA.id+ });+ assert.equal(androidDupRes.status, 'REJECTED');+ assert.equal(androidDupRes.failingCondition, 'DUPLICATE_OBSERVATION');+ assert.equal(sessionRepo.findById(session.id).verificationLevel, 1, 'Same-family SMS replay must not upgrade to Level 2');++ // 3rd observation via independent GMAIL channel upgrades to Level 2 Dual Verification+ const gmailRes = pipeline.process({+ source: 'GMAIL',+ rawText: 'Dear Customer, Rs 250.00 has been credited to your account via UPI. Ref: 888877776666',+ sender: '[email protected]',+ receivingAccountId: accountA.id+ });+ assert.equal(gmailRes.status, 'VERIFIED');+ const updated = sessionRepo.findById(session.id);+ assert.equal(updated.verificationLevel, 2);+ assert.match(updated.verificationTag, /Dual Verification/);+ });++ test('10. Conflicting UTR during in-flight grace window holds session in MANUAL_REVIEW instead of upgrading to Level 2', () => {+ const graceEngine = new AttributionEngine({+ sessionRepo,+ obsRepo,+ ticketRepo,+ auditRepo,+ gracePeriodMs: 5000+ });++ try {+ const session = sessionRepo.create({+ merchantId: merchantA.id,+ receivingAccountId: accountA.id,+ orderId: 'ORD-CONFLICT-GRACE',+ amountPaise: 30000n+ });+ sessionRepo.acquireSlotAtomic(session.id, accountA.id, 300000);++ // 1st observation starts 5s grace window with UTR 111122223333+ const obs1 = graceEngine.processObservation(ObservationNormalizer.normalize({+ receivingAccountId: accountA.id,+ source: ObserverSource.SMS_GATEWAY,+ amountPaise: 30000n,+ bankReferenceNumber: '111122223333',+ observedAt: new Date()+ }));+ assert.equal(obs1.attributed, true);+ assert.equal(obs1.outcomeStatus, 'VERIFYING');++ // 2nd observation arrives during grace window for same amount but CONFLICTING UTR 444455556666+ const obs2 = graceEngine.processObservation(ObservationNormalizer.normalize({+ receivingAccountId: accountA.id,+ source: ObserverSource.GMAIL,+ amountPaise: 30000n,+ bankReferenceNumber: '444455556666',+ observedAt: new Date()+ }));+ assert.equal(obs2.attributed, false);+ assert.equal(obs2.ambiguous, true);+ assert.equal(obs2.outcomeStatus, PaymentStatus.MANUAL_REVIEW);+ assert.equal(obs2.reason, 'CONFLICTING_UTR_ON_SESSION');++ const heldSession = sessionRepo.findById(session.id);+ assert.equal(heldSession.status, PaymentStatus.MANUAL_REVIEW);++ // Subsequent observer alerts cannot move a MANUAL_REVIEW session to OBSERVED_SUCCESS+ const obs3 = graceEngine.processObservation(ObservationNormalizer.normalize({+ receivingAccountId: accountA.id,+ source: ObserverSource.GMAIL,+ amountPaise: 30000n,+ bankReferenceNumber: '111122223333',+ observedAt: new Date()+ }));+ assert.equal(obs3.attributed, false);+ assert.equal(obs3.outcomeStatus, PaymentStatus.MANUAL_REVIEW);+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.MANUAL_REVIEW);+ } finally {+ graceEngine.destroy();+ }+ });++ test('11. Delayed and unmatched observations are reconciled into LATE_UNMATCHED with audit trail and support tickets', () => {+ const customer = customerRepo.create({+ name: 'Delayed Payer',+ email: '[email protected]',+ mobileNumber: '9876500001'+ });+ const session = sessionRepo.create({+ merchantId: merchantA.id,+ receivingAccountId: accountA.id,+ customerId: customer.id,+ orderId: 'ORD-DELAYED-RECON',+ amountPaise: 42000n+ });+ sessionRepo.acquireSlotAtomic(session.id, accountA.id, 300000);++ // 1. Unmatched observation arrives while session is not yet expired (or stored as UNATTRIBUTED first)+ const rawUnattributed = obsRepo.create({+ receivingAccountId: accountA.id,+ source: ObserverSource.SMS_GATEWAY,+ amountPaise: 42000n,+ bankReferenceNumber: '909090121212',+ fingerprintHash: 'fp-unmatched-recon-420',+ observedAt: new Date()+ });+ assert.equal(rawUnattributed.attributionStatus, ObservationAttributionStatus.UNATTRIBUTED);++ // 2. Session expires before attribution+ sessionRepo.transitionToTerminal(session.id, PaymentStatus.EXPIRED);++ // 3. Reconciling unmatched observations links it to the expired session as LATE_UNMATCHED and opens a ticket+ const reconSummary = attributionEngine.reconcileUnmatchedObservations(accountA.id);+ assert.equal(reconSummary.processed, 1);+ assert.equal(reconSummary.reconciledCount, 1);+ assert.equal(reconSummary.results[0].outcomeStatus, ObservationAttributionStatus.LATE_UNMATCHED);+ assert.equal(reconSummary.results[0].paymentSessionId, session.id);++ const updatedObs = obsRepo.findById(rawUnattributed.id);+ assert.equal(updatedObs.attributionStatus, ObservationAttributionStatus.LATE_UNMATCHED);+ assert.equal(updatedObs.rawPayload.lateMatchedSessionId, session.id);+ assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.EXPIRED, 'Expired session must remain EXPIRED');++ const tickets = db.query('SELECT * FROM support_tickets WHERE payment_id = ?', [session.id]);+ assert.equal(tickets.length, 1);+ assert.match(tickets[0].subject, /LATE PAYMENT DETECTED/);+ });});diff --git a/packages/core/src/__tests__/statement-reconciliation.test.js b/packages/core/src/__tests__/statement-reconciliation.test.jsindex 1fd0309..4f353e3 100644--- a/packages/core/src/__tests__/statement-reconciliation.test.js+++ b/packages/core/src/__tests__/statement-reconciliation.test.js@@ -199,7 +199,43 @@ describe('bank statement reconciliation', () => {csvText: hdfcCsv([creditRow({ utr: '523456789012' })])});assert.equal(result.reconciled, 1);- assert.equal(sessionRepo.findById(session.id).status, PaymentStatus.RECONCILED);+ const reconciledSession = sessionRepo.findById(session.id);+ assert.equal(reconciledSession.status, PaymentStatus.RECONCILED);+ assert.ok(reconciledSession.attributedObservationId, 'Reconciled MANUAL_REVIEW session must link attributedObservationId');+ });++ test('corroborates LATE_UNMATCHED observations during statement import and emits PAYMENT.UNMATCHED_RECONCILIATION_NEEDED', () => {+ const obsRepo = new ObservationRepository(db);+ const expiredSession = sessionRepo.create({+ merchantId,+ receivingAccountId: ACCOUNT_ID,+ orderId: 'ORD-LATE-STMT-1',+ amountPaise: 49900n+ });+ sessionRepo.acquireSlotAtomic(expiredSession.id, ACCOUNT_ID, 300000);+ sessionRepo.transitionToTerminal(expiredSession.id, PaymentStatus.EXPIRED);++ const lateObs = obsRepo.create({+ receivingAccountId: ACCOUNT_ID,+ source: 'GOOGLE_MESSAGES',+ amountPaise: 49900n,+ observedAt: new Date(),+ bankReferenceNumber: '623456789012',+ fingerprintHash: 'fp-late-unmatched-stmt',+ rawPayload: {}+ });+ obsRepo.markLateUnmatched(lateObs.id, expiredSession.id);++ const result = engine.importCsv({+ receivingAccountId: ACCOUNT_ID,+ csvText: hdfcCsv([creditRow({ utr: '623456789012' })])+ });+ assert.equal(result.unmatched, 1);+ assert.equal(result.lines[0].outcome, 'UNMATCHED');+ assert.equal(result.lines[0].observationId, lateObs.id);+ assert.equal(result.lines[0].candidatePaymentSessionId, expiredSession.id);+ assert.equal(sessionRepo.findById(expiredSession.id).status, PaymentStatus.EXPIRED);+ assert.equal(events.filter(e => e.event === 'PAYMENT.UNMATCHED_RECONCILIATION_NEEDED').length, 1);});test('a statement line does not settle a session that was never observed', () => {diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex 2068078..6382476 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -1,4 +1,13 @@-import { PaymentStatus, ObservationAttributionStatus, TicketStatus, SenderType, isTerminalStatus } from '@youpi/common';+import { PaymentStatus, ObservationAttributionStatus, TicketStatus, SenderType, isTerminalStatus, calculateObservationFingerprint } from '@youpi/common';++export function getChannelFamily(source) {+ const normalized = String(source || '').trim().toUpperCase();+ if (normalized === 'GMAIL') return 'GMAIL';+ if (['SMS', 'SMS_GATEWAY', 'GOOGLE_MESSAGES', 'ANDROID_OBSERVER'].includes(normalized)) {+ return 'SMS';+ }+ return normalized || 'SMS';+}export class AttributionEngine {/**@@ -118,22 +127,51 @@ export class AttributionEngine {if (normalizedObs && normalizedObs.amountPaise !== undefined && typeof normalizedObs.amountPaise !== 'bigint') {normalizedObs = { ...normalizedObs, amountPaise: BigInt(normalizedObs.amountPaise) };}+ if (normalizedObs && !(normalizedObs.observedAt instanceof Date)) {+ const parsedDate = normalizedObs.observedAt ? new Date(normalizedObs.observedAt) : new Date();+ normalizedObs = {+ ...normalizedObs,+ observedAt: Number.isNaN(parsedDate.getTime()) ? new Date() : parsedDate+ };+ }+ if (normalizedObs && !normalizedObs.fingerprintHash) {+ normalizedObs = {+ ...normalizedObs,+ fingerprintHash: calculateObservationFingerprint({+ receivingAccountId: normalizedObs.receivingAccountId,+ amountPaise: normalizedObs.amountPaise,+ source: normalizedObs.source,+ bankReferenceNumber: normalizedObs.bankReferenceNumber,+ observedAt: normalizedObs.observedAt+ })+ };+ }++ const incomingFamily = getChannelFamily(normalizedObs.source);// Tier 1: Check fingerprint for deduplication- // Look up this channel first: once a second channel has upgraded the payment, the- // fingerprint has one row per channel and the unfiltered lookup may return the other one.- const existing = this.obsRepo.findByFingerprint(normalizedObs.fingerprintHash, normalizedObs.source)- || this.obsRepo.findByFingerprint(normalizedObs.fingerprintHash);+ // Look up this channel family first: once a second channel family has upgraded the payment, the+ // fingerprint has one row per channel family and the unfiltered lookup may return the other one.+ const existingSameFamily = this.obsRepo.findByFingerprintOrFamily+ ? this.obsRepo.findByFingerprintOrFamily(normalizedObs.fingerprintHash, normalizedObs.source)+ : this.obsRepo.findByFingerprint(normalizedObs.fingerprintHash, normalizedObs.source);+ const existing = existingSameFamily || this.obsRepo.findByFingerprint(normalizedObs.fingerprintHash);if (existing) {- // If observation came from the SAME source, drop as redundant duplicate- if (existing.source === normalizedObs.source) {+ // If observation came from the SAME channel family (e.g. SMS_GATEWAY + ANDROID_OBSERVER or GOOGLE_MESSAGES),+ // drop as a redundant duplicate so same-channel-family events never falsely upgrade to Level 2.+ if (existing.source === normalizedObs.source || getChannelFamily(existing.source) === incomingFamily) {if (this.auditRepo) {this.auditRepo.log({entityType: 'PAYMENT_OBSERVATION',entityId: existing.id,action: 'DUPLICATE_OBSERVATION_DROPPED',actorType: 'OBSERVER',- details: { fingerprintHash: normalizedObs.fingerprintHash, source: normalizedObs.source }+ details: {+ fingerprintHash: normalizedObs.fingerprintHash,+ source: normalizedObs.source,+ existingSource: existing.source,+ channelFamily: incomingFamily+ }});}return {@@ -146,10 +184,38 @@ export class AttributionEngine {};}- // If observation came from a NEW, DIFFERENT channel and payment was already attributed:+ // If observation came from a NEW, INDEPENDENT channel family (SMS vs GMAIL) and payment was already attributed:// Upgrade verification tier to Level 2 (Dual Verification)!if (existing.attributedPaymentId) {const targetSession = this.sessionRepo.findById(existing.attributedPaymentId);+ // Keep MANUAL_REVIEW sessions held until verified by authoritative bank statement+ if (targetSession && targetSession.status === PaymentStatus.MANUAL_REVIEW) {+ return {+ attributed: false,+ duplicate: false,+ lateMatch: false,+ ambiguous: true,+ paymentSessionId: targetSession.id,+ observationId: existing.id,+ outcomeStatus: PaymentStatus.MANUAL_REVIEW,+ reason: 'SESSION_HELD_IN_MANUAL_REVIEW'+ };+ }+ // If target session already has a verification source from this channel family, drop as duplicate+ if (+ targetSession &&+ Array.isArray(targetSession.verificationSources) &&+ targetSession.verificationSources.some(s => getChannelFamily(s) === incomingFamily)+ ) {+ return {+ attributed: false,+ duplicate: true,+ lateMatch: false,+ paymentSessionId: targetSession.id,+ observationId: existing.id,+ outcomeStatus: ObservationAttributionStatus.DUPLICATE_IGNORED+ };+ }const closedWithoutUpgrade = targetSession&& isTerminalStatus(targetSession.status)&& targetSession.status !== PaymentStatus.SUCCESS@@ -157,7 +223,7 @@ export class AttributionEngine {&& targetSession.status !== PaymentStatus.RECONCILED;if (closedWithoutUpgrade) {const savedObs = this.obsRepo.create(normalizedObs);- this.obsRepo.markLateUnmatched(savedObs.id);+ this.obsRepo.markLateUnmatched(savedObs.id, targetSession.id);if (this.auditRepo) {this.auditRepo.log({merchantId: targetSession.merchantId,@@ -298,11 +364,21 @@ export class AttributionEngine {let currentSession = null;if (normalizedObs.rawPayload?.targetSessionId) {currentSession = this.sessionRepo.findById(normalizedObs.rawPayload.targetSessionId);+ if (currentSession && currentSession.status === PaymentStatus.MANUAL_REVIEW) {+ this.obsRepo.markAmbiguous(savedObs.id);+ return {+ attributed: false,+ duplicate: false,+ lateMatch: false,+ ambiguous: true,+ paymentSessionId: currentSession.id,+ observationId: savedObs.id,+ outcomeStatus: PaymentStatus.MANUAL_REVIEW,+ reason: 'SESSION_HELD_IN_MANUAL_REVIEW'+ };+ }}if (!currentSession || (currentSession.amountPaise !== normalizedObs.amountPaise)) {- currentSession = this.sessionRepo.findCurrentActiveOrProcessing(normalizedObs.receivingAccountId);- }- if (currentSession && currentSession.amountPaise !== normalizedObs.amountPaise) {const matchRows = this.sessionRepo.db.query(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?@@ -316,28 +392,22 @@ export class AttributionEngine {}if (matchRows.length === 1) {currentSession = this.sessionRepo.mapRow(matchRows[0]);+ } else if (!currentSession) {+ currentSession = this.sessionRepo.findCurrentActiveOrProcessing(normalizedObs.receivingAccountId);}- }- 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 candidates = this.sessionRepo.db.query(`+ } else if (!normalizedObs.rawPayload?.targetSessionId) {+ // Even if targetSessionId was not specified and currentSession matched amount, verify no other live session shares this amount+ const matchRows = this.sessionRepo.db.query(`SELECT * FROM payment_sessions- WHERE receiving_account_id = ?- AND status IN ('ACTIVE', 'PROCESSING')- AND amount_paise = ?+ WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);- if (candidates.length > 1) {+ if (matchRows.length > 1) {return this.holdAmbiguous(savedObs,- candidates.map(row => this.sessionRepo.mapRow(row)),+ matchRows.map(row => this.sessionRepo.mapRow(row)),'MULTIPLE_LIVE_AMOUNT_MATCHES');}- if (candidates.length === 1) {- currentSession = this.sessionRepo.mapRow(candidates[0]);- }}if (currentSession) {@@ -434,13 +504,46 @@ export class AttributionEngine {if (isEligibleStatus && isAmountMatch && isTimeValid) {const wasActive = currentSession.status === PaymentStatus.ACTIVE;+ // Check if currentSession already has an attributed primary observation (e.g. during grace window or REQUIRE_DUAL_CHANNEL)+ const primaryObs = currentSession.attributedObservationId+ ? this.obsRepo.findById(currentSession.attributedObservationId)+ : null;++ if (primaryObs) {+ const hasConflictingUtr = Boolean(+ primaryObs.bankReferenceNumber &&+ savedObs.bankReferenceNumber &&+ String(primaryObs.bankReferenceNumber).trim() !== String(savedObs.bankReferenceNumber).trim()+ );+ if (hasConflictingUtr) {+ const pendingGrace = this.pendingGraceTimers.get(currentSession.id);+ if (pendingGrace) {+ clearTimeout(pendingGrace);+ this.pendingGraceTimers.delete(currentSession.id);+ }+ return this.holdAmbiguous(savedObs, [currentSession], 'CONFLICTING_UTR_ON_SESSION');+ }++ if (getChannelFamily(primaryObs.source) === incomingFamily) {+ this.obsRepo.markDuplicate(savedObs.id);+ return {+ attributed: false,+ duplicate: true,+ lateMatch: false,+ paymentSessionId: currentSession.id,+ observationId: savedObs.id,+ outcomeStatus: ObservationAttributionStatus.DUPLICATE_IGNORED+ };+ }+ }+// Check if there is already an active grace period awaiting second source for this sessionconst pendingGrace = this.pendingGraceTimers.get(currentSession.id);if (pendingGrace) {clearTimeout(pendingGrace);this.pendingGraceTimers.delete(currentSession.id);- // Second source confirmed within 5-second grace window -> LEVEL 2 DUAL VERIFICATION!+ // Second independent source confirmed within 5-second grace window -> LEVEL 2 DUAL VERIFICATION!let verifyResult;try {verifyResult = this.sessionRepo.recordVerificationSource(@@ -450,10 +553,6 @@ export class AttributionEngine {{ finalizeSuccess: true });- // Check if primary observation already holds the attributed bank_reference_number- const primaryObs = currentSession.attributedObservationId- ? this.obsRepo.findById(currentSession.attributedObservationId)- : null;const sameUtrAsPrimary = Boolean(primaryObs &&primaryObs.bankReferenceNumber &&@@ -838,6 +937,22 @@ export class AttributionEngine {// Temporal check: observation must have been observed during this session's windowif (!isUtrConflict && normalizedObs.observedAt >= sessionSlotStart && normalizedObs.observedAt <= sessionCompleted) {+ const mappedRecentSession = this.sessionRepo.mapRow(recentSuccessSession);+ if (+ Array.isArray(mappedRecentSession.verificationSources) &&+ mappedRecentSession.verificationSources.some(s => getChannelFamily(s) === incomingFamily)+ ) {+ this.obsRepo.markDuplicate(savedObs.id);+ return {+ attributed: false,+ duplicate: true,+ lateMatch: false,+ paymentSessionId: recentSuccessSession.id,+ observationId: savedObs.id,+ outcomeStatus: ObservationAttributionStatus.DUPLICATE_IGNORED+ };+ }+const verifyResult = this.sessionRepo.recordVerificationSource(recentSuccessSession.id,normalizedObs.source,@@ -901,8 +1016,8 @@ export class AttributionEngine {const lateMatchedSession = lateMatches[0];if (lateMatchedSession) {- // Mark observation as LATE_UNMATCHED- this.obsRepo.markLateUnmatched(savedObs.id);+ // Mark observation as LATE_UNMATCHED and preserve candidate session ID in raw_payload+ this.obsRepo.markLateUnmatched(savedObs.id, lateMatchedSession.id);if (this.auditRepo) {this.auditRepo.log({@@ -964,4 +1079,104 @@ export class AttributionEngine {outcomeStatus: ObservationAttributionStatus.UNATTRIBUTED};}++ /**+ * Re-evaluates unmatched (UNATTRIBUTED / LATE_UNMATCHED) observations for a receiving account+ * against eligible sessions to surface late-payment correlation or manual review holds.+ * Never auto-confirms an immutable terminal session (EXPIRED/FAILED/CANCELLED).+ * @param {string} receivingAccountId+ */+ reconcileUnmatchedObservations(receivingAccountId) {+ const unattributed = this.obsRepo.findUnattributed(receivingAccountId);+ const results = [];++ for (const obs of unattributed) {+ // 1. Check live sessions with matching amount+ const liveRows = this.sessionRepo.db.query(`+ SELECT * FROM payment_sessions+ WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?+ `, [receivingAccountId, Number(obs.amountPaise)]);++ if (liveRows.length > 1) {+ const held = this.holdAmbiguous(+ obs,+ liveRows.map(r => this.sessionRepo.mapRow(r)),+ 'MULTIPLE_LIVE_AMOUNT_MATCHES'+ );+ results.push({ observationId: obs.id, action: 'HELD_AMBIGUOUS', ...held });+ continue;+ }++ // 2. Check recently expired or failed sessions (< 30 mins)+ const thirtyMinutesAgo = new Date(Date.now() - 30 * 60 * 1000);+ const recentExpired = this.sessionRepo.findRecentlyExpiredOrFailed(receivingAccountId, thirtyMinutesAgo);+ const lateMatches = recentExpired.filter(s => s.amountPaise === obs.amountPaise);++ if (lateMatches.length > 1) {+ const held = this.holdAmbiguous(obs, lateMatches, 'MULTIPLE_LATE_AMOUNT_MATCHES');+ results.push({ observationId: obs.id, action: 'HELD_AMBIGUOUS', ...held });+ continue;+ }++ if (lateMatches.length === 1) {+ const lateSession = lateMatches[0];+ this.obsRepo.markLateUnmatched(obs.id, lateSession.id);+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: lateSession.merchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: lateSession.id,+ action: 'LATE_OBSERVATION_RECONCILED_TO_TICKET',+ actorType: 'SYSTEM',+ details: {+ observationId: obs.id,+ source: obs.source,+ amountPaise: obs.amountPaise.toString(),+ sessionStatus: lateSession.status+ }+ });+ }+ if (this.ticketRepo && lateSession.customerId) {+ this.ticketRepo.createTicket({+ merchantId: lateSession.merchantId,+ customerId: lateSession.customerId,+ paymentId: lateSession.id,+ subject: `[LATE PAYMENT DETECTED] Order #${lateSession.orderId}`,+ status: TicketStatus.OPEN,+ initialMessage: {+ senderType: SenderType.ADMIN,+ senderId: lateSession.merchantId,+ message: `A delayed payment observation of ${obs.amountPaise / 100n} INR was matched during unmatched reconciliation after session ${lateSession.id} ended with status ${lateSession.status}.`+ }+ });+ }+ this.eventEmitter.emit('PAYMENT.LATE_DETECTED', {+ paymentId: lateSession.id,+ orderId: lateSession.orderId,+ merchantId: lateSession.merchantId,+ amountPaise: obs.amountPaise,+ observationId: obs.id+ });+ results.push({+ observationId: obs.id,+ action: 'MARKED_LATE_UNMATCHED',+ paymentSessionId: lateSession.id,+ outcomeStatus: ObservationAttributionStatus.LATE_UNMATCHED+ });+ continue;+ }++ results.push({+ observationId: obs.id,+ action: 'REMAINS_UNATTRIBUTED',+ outcomeStatus: ObservationAttributionStatus.UNATTRIBUTED+ });+ }++ return {+ processed: unattributed.length,+ reconciledCount: results.filter(r => r.action !== 'REMAINS_UNATTRIBUTED').length,+ results+ };+ }}diff --git a/packages/core/src/statement-reconciliation.js b/packages/core/src/statement-reconciliation.jsindex cce4d64..f3643a1 100644--- a/packages/core/src/statement-reconciliation.js+++ b/packages/core/src/statement-reconciliation.js@@ -134,11 +134,48 @@ export class StatementReconciliation {if (!observedOn || !this.withinPostingWindow(observedOn, line.bookedOn)) {return this.finish(rowId, 'CONFLICT', 'STATEMENT_DATE_OUTSIDE_WINDOW', null);}- return this.reconcile(rowId, held[0]);+ return this.reconcile(rowId, held[0], seen[0]);}if (held.length > 1 && seen.length >= 1) {return this.finish(rowId, 'CONFLICT', 'MULTIPLE_SESSIONS', null);}+ if (seen.length >= 1) {+ let candidateSessionId = seen[0].attributed_payment_id || null;+ if (!candidateSessionId && seen[0].raw_payload) {+ try {+ const parsedPayload = typeof seen[0].raw_payload === 'string'+ ? JSON.parse(seen[0].raw_payload)+ : seen[0].raw_payload;+ candidateSessionId = parsedPayload?.lateMatchedSessionId || parsedPayload?.targetSessionId || null;+ } catch {}+ }+ this.auditRepo?.log({+ entityType: 'PAYMENT_OBSERVATION',+ entityId: seen[0].id,+ action: 'UNMATCHED_STATEMENT_OBSERVATION_CORROBORATED',+ actorType: 'ADMIN',+ details: {+ statementLineId: rowId,+ receivingAccountId,+ utr: line.utr,+ amountPaise: String(line.amountPaise),+ attributionStatus: seen[0].attribution_status,+ candidatePaymentSessionId: candidateSessionId+ }+ });+ this.eventEmitter?.emit('PAYMENT.UNMATCHED_RECONCILIATION_NEEDED', {+ receivingAccountId,+ observationId: seen[0].id,+ candidatePaymentSessionId: candidateSessionId,+ utr: line.utr,+ amountPaise: BigInt(line.amountPaise),+ statementLineId: rowId+ });+ return this.finish(rowId, 'UNMATCHED', 'NO_OBSERVED_SESSION', null, {+ observationId: seen[0].id,+ candidatePaymentSessionId: candidateSessionId+ });+ }return this.finish(rowId, 'UNMATCHED', 'NO_OBSERVED_SESSION', null);}@@ -192,8 +229,10 @@ export class StatementReconciliation {observationsForReference(receivingAccountId, line) {return this.db.query(`- SELECT id, observed_at FROM payment_observations+ SELECT id, observed_at, attribution_status, attributed_payment_id, raw_payload+ FROM payment_observationsWHERE receiving_account_id = ? AND bank_reference_number = ? AND amount_paise = ?+ ORDER BY observed_at ASC`, [receivingAccountId, line.utr, line.amountPaise]);}@@ -217,12 +256,35 @@ export class StatementReconciliation {}}- reconcile(rowId, session) {+ reconcile(rowId, session, matchedObs = null) {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);}+ if (matchedObs?.id) {+ try {+ this.db.execute(+ `UPDATE payment_observations+ SET attribution_status = 'ATTRIBUTED',+ attributed_payment_id = COALESCE(attributed_payment_id, ?)+ WHERE id = ?`,+ [session.id, matchedObs.id]+ );+ this.db.execute(+ `UPDATE payment_sessions+ SET attributed_observation_id = COALESCE(attributed_observation_id, ?)+ WHERE id = ?`,+ [matchedObs.id, session.id]+ );+ } catch {+ // If another observation already holds the unique UTR attribution index, still mark ATTRIBUTED+ this.db.execute(+ `UPDATE payment_observations SET attribution_status = 'ATTRIBUTED' WHERE id = ?`,+ [matchedObs.id]+ );+ }+ }const emit = before !== PaymentStatus.RECONCILED;return this.finish(rowId, 'RECONCILED', 'BANK_STATEMENT_MATCH', updated.id, { emit, session: updated });}@@ -257,7 +319,9 @@ export class StatementReconciliation {matchStatus,matchReason,paymentSessionId,- statementLineId: rowId+ statementLineId: rowId,+ ...(options.observationId ? { observationId: options.observationId } : {}),+ ...(options.candidatePaymentSessionId ? { candidatePaymentSessionId: options.candidatePaymentSessionId } : {})};}}diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.jsindex 6373419..a3c2c9b 100644--- a/packages/core/src/verification-pipeline.js+++ b/packages/core/src/verification-pipeline.js@@ -611,6 +611,27 @@ export class PaymentVerificationPipeline {// [ STAGE 4 ]: Payment Verification// =========================================================================let stage4;+ const hasExplicitSessionId = Boolean(input.paymentSessionId);+ let hasMultipleLiveAmountMatches = false;++ if (!hasExplicitSessionId && parsedData?.amountPaise) {+ const targetAccountId = session?.receivingAccountId || input.receivingAccountId;+ if (targetAccountId) {+ const liveAmountRows = this.db.query(`+ SELECT * FROM payment_sessions+ WHERE receiving_account_id = ?+ AND status IN ('ACTIVE', 'PROCESSING')+ AND amount_paise = ?+ ORDER BY created_at DESC+ `, [targetAccountId, Number(parsedData.amountPaise)]);+ if (liveAmountRows.length > 1) {+ hasMultipleLiveAmountMatches = true;+ session = this.sessionRepo.mapRow(liveAmountRows[0]);+ } else if (liveAmountRows.length === 1) {+ session = this.sessionRepo.mapRow(liveAmountRows[0]);+ }+ }+ }if (!session && parsedData?.amountPaise) {// Amount alone is not an identifier: two merchants can legitimately have an identical@@ -618,16 +639,19 @@ export class PaymentVerificationPipeline {// and then only within that VPA's merchant.const scopeByVpa = observedVpa || (parsedData.vpa ? String(parsedData.vpa).toLowerCase() : null);if (scopeByVpa) {- const matchRow = this.db.queryOne(`+ const matchRows = this.db.query(`SELECT ps.* FROM payment_sessions psJOIN payment_receiving_accounts ra ON ps.receiving_account_id = ra.idWHERE ps.status IN ('ACTIVE', 'PROCESSING')AND ps.amount_paise = ?AND LOWER(ra.upi_id) = ?- ORDER BY ps.created_at DESC LIMIT 1+ ORDER BY ps.created_at DESC`, [Number(parsedData.amountPaise), scopeByVpa]);- if (matchRow) {- session = this.sessionRepo.mapRow(matchRow);+ if (matchRows.length > 1) {+ hasMultipleLiveAmountMatches = true;+ }+ if (matchRows.length >= 1) {+ session = this.sessionRepo.mapRow(matchRows[0]);}}}@@ -759,7 +783,9 @@ export class PaymentVerificationPipeline {observedAt: receivedAt});- const existingObs = this.obsRepo.findByFingerprint(fingerprint, observerSourceEnum);+ const existingObs = this.obsRepo.findByFingerprintOrFamily+ ? this.obsRepo.findByFingerprintOrFamily(fingerprint, observerSourceEnum)+ : this.obsRepo.findByFingerprint(fingerprint, observerSourceEnum);if (existingObs) {stage4 = {stage: 4,@@ -1121,7 +1147,7 @@ export class PaymentVerificationPipeline {...observation,raw: rawText,is_test: isTest,- targetSessionId: session?.id+ targetSessionId: hasMultipleLiveAmountMatches ? undefined : (hasExplicitSessionId ? session?.id : session?.id)},amountPaise: parsedData.amountPaise,amount: parsedData.amount,@@ -1141,13 +1167,22 @@ export class PaymentVerificationPipeline {verificationTag: 'DEFAULT'};+ const isAmbiguousHold = Boolean(+ attributionResult.ambiguous ||+ attributionResult.outcomeStatus === PaymentStatus.MANUAL_REVIEW+ );+stage6 = {stage: 6,name: 'ATTRIBUTION',- status: attributionResult.attributed ? 'ATTRIBUTED' : 'UNRESOLVED',+ status: attributionResult.attributed+ ? 'ATTRIBUTED'+ : (isAmbiguousHold ? 'AMBIGUOUS_HELD' : 'UNRESOLVED'),outcomeStatus: attributionResult.outcomeStatus,details: {attributed: attributionResult.attributed,+ ambiguous: Boolean(attributionResult.ambiguous),+ reason: attributionResult.reason || null,paymentSessionId: attributionResult.paymentSessionId,observationId: attributionResult.observationId,attributedSessionId: attributionResult.paymentSessionId,@@ -1157,13 +1192,22 @@ export class PaymentVerificationPipeline {}};- const finalStatus = attributionResult.attributed ? 'VERIFIED' : 'UNRESOLVED';+ const finalStatus = attributionResult.attributed+ ? 'VERIFIED'+ : (isAmbiguousHold ? PaymentStatus.MANUAL_REVIEW : 'UNRESOLVED');// Refresh session state after attributionconst updatedSession = this.sessionRepo.findById(session.id);return buildResult({finalStatus,+ failingStage: attributionResult.attributed ? null : 6,+ failingCondition: attributionResult.attributed+ ? null+ : (attributionResult.reason || attributionResult.outcomeStatus || null),+ failingReason: isAmbiguousHold+ ? `Payment held in MANUAL_REVIEW due to ambiguous session match (${attributionResult.reason || 'AMBIGUOUS_SESSION_MATCH'}).`+ : null,stage2,stage3,stage4,diff --git a/packages/db/src/repositories/observation.repository.js b/packages/db/src/repositories/observation.repository.jsindex 21248b8..ec94cf0 100644--- a/packages/db/src/repositories/observation.repository.js+++ b/packages/db/src/repositories/observation.repository.js@@ -61,6 +61,29 @@ export class ObservationRepository {return this.mapRow(row);}+ /**+ * Finds an existing observation with the same fingerprint within the same independent+ * channel family ('GMAIL' vs SMS/device channels 'SMS', 'SMS_GATEWAY', 'GOOGLE_MESSAGES', 'ANDROID_OBSERVER').+ * @param {string} fingerprintHash+ * @param {string} source+ */+ findByFingerprintOrFamily(fingerprintHash, source) {+ const normalized = String(source || '').trim().toUpperCase();+ if (!normalized) return this.findByFingerprint(fingerprintHash);+ if (normalized === 'GMAIL') {+ return this.findByFingerprint(fingerprintHash, 'GMAIL');+ }+ const row = this.db.queryOne(+ `SELECT * FROM payment_observations+ WHERE fingerprint_hash = ?+ AND UPPER(source) IN ('SMS', 'SMS_GATEWAY', 'GOOGLE_MESSAGES', 'ANDROID_OBSERVER')+ LIMIT 1`,+ [fingerprintHash]+ );+ if (!row) return null;+ return this.mapRow(row);+ }+findUnattributed(receivingAccountId) {const rows = this.db.query(`SELECT * FROM payment_observations@@ -71,6 +94,22 @@ export class ObservationRepository {return rows.map(r => this.mapRow(r));}+ findUnmatchedForReconciliation(receivingAccountId) {+ const rows = this.db.query(`+ SELECT * FROM payment_observations+ WHERE receiving_account_id = ?+ AND attribution_status IN (?, ?, ?)+ ORDER BY observed_at ASC+ `, [+ receivingAccountId,+ ObservationAttributionStatus.UNATTRIBUTED,+ ObservationAttributionStatus.LATE_UNMATCHED,+ ObservationAttributionStatus.AMBIGUOUS+ ]);++ return rows.map(r => this.mapRow(r));+ }+findByReceivingAccount(receivingAccountId, limit = 50) {const rows = this.db.query(`SELECT * FROM payment_observations@@ -83,6 +122,30 @@ export class ObservationRepository {}markAttributed(id, paymentId) {+ const current = this.findById(id);+ if (current?.bankReferenceNumber) {+ const existingSameSession = this.db.queryOne(+ `SELECT id FROM payment_observations+ WHERE bank_reference_number = ?+ AND attributed_payment_id = ?+ AND id != ?+ LIMIT 1`,+ [current.bankReferenceNumber, paymentId, id]+ );+ if (existingSameSession) {+ const updatedPayload = {+ ...(current.rawPayload || {}),+ corroboratedPaymentId: paymentId+ };+ this.db.execute(`+ UPDATE payment_observations+ SET attribution_status = ?, raw_payload = ?+ WHERE id = ?+ `, [ObservationAttributionStatus.ATTRIBUTED, JSON.stringify(updatedPayload), id]);+ return this.findById(id);+ }+ }+this.db.execute(`UPDATE payment_observationsSET attribution_status = ?, attributed_payment_id = ?@@ -112,7 +175,21 @@ export class ObservationRepository {return this.findById(id);}- markLateUnmatched(id) {+ markLateUnmatched(id, candidatePaymentId = null) {+ if (candidatePaymentId) {+ const current = this.findById(id);+ const updatedPayload = {+ ...(current?.rawPayload || {}),+ lateMatchedSessionId: candidatePaymentId+ };+ this.db.execute(`+ UPDATE payment_observations+ SET attribution_status = ?, raw_payload = ?+ WHERE id = ?+ `, [ObservationAttributionStatus.LATE_UNMATCHED, JSON.stringify(updatedPayload), id]);+ return this.findById(id);+ }+this.db.execute(`UPDATE payment_observationsSET attribution_status = ?diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex 0967ca6..430a728 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -535,12 +535,15 @@ export class PaymentSessionRepository {sourcesSet.add(source);const sources = Array.from(sourcesSet);- const level = Math.min(2, sources.length); // 1 or 2 (2-Layer Engine: SMS + Gmail)- const sourceLabels = sources.map(s => {+ const channelFamilies = new Set(+ sources.map(s => (String(s || '').trim().toUpperCase() === 'GMAIL' ? 'GMAIL' : 'SMS'))+ );+ const level = Math.min(2, channelFamilies.size); // 1 or 2 (2-Layer Engine: independent SMS + Gmail families)+ const sourceLabels = Array.from(new Set(sources.map(s => {if (s === 'GOOGLE_MESSAGES') return 'SMS';if (s === 'GMAIL') return 'Gmail';return s;- });+ })));let tag = `Single Verification (${sourceLabels.join(', ')})`;if (level >= 2) {