A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
fix(core): filter balance amounts, reject debits and add FamPay UPI parsing (#6, #20)
ArunGupta1526132c4caed681
diff --git a/packages/core/src/__tests__/core.test.js b/packages/core/src/__tests__/core.test.jsindex bed1df3..d9942f0 100644--- a/packages/core/src/__tests__/core.test.js+++ b/packages/core/src/__tests__/core.test.js@@ -326,5 +326,58 @@ describe('@youpi/core Unit & Integration Tests', () => {assert.equal(parsed.amount, '1200.00');assert.equal(parsed.bankReferenceNumber, '987654321012');});++ test('ignores available balance amount appearing before credit amount', () => {+ const sms = {+ text: 'Avl Bal Rs 15,000.00. Rs 500.00 credited to A/c XX1234 for UPI txn Ref 123456789012.'+ };+ const parsed = BankSmsParser.parse(sms);+ assert.ok(parsed);+ assert.equal(parsed.amount, '500.00');+ assert.equal(parsed.amountPaise, 50000n);+ assert.equal(parsed.bankReferenceNumber, '123456789012');+ });++ test('rejects debit notification even if credited disclaimer appears later', () => {+ const sms = {+ text: 'Dear Customer, A/c *1234 is debited for Rs 750 on 19-Oct-26. If not done by you, contact bank. Amount will be credited back in 48 hours.'+ };+ const parsed = BankSmsParser.parse(sms);+ assert.equal(parsed, null);+ });++ test('rejects bare payment or transfer debit message without credit indicator', () => {+ const sms = {+ text: 'Payment of Rs 350.00 sent to merchant@upi on 19-Oct. UPI Ref 998877665544.'+ };+ const parsed = BankSmsParser.parse(sms);+ assert.equal(parsed, null);+ });++ test('Issue #20: correctly parses FamPay / FamApp credit notification with wallet, transaction ID, and UPI ID', () => {+ const sms = {+ text: 'Money received! Rs. 350.00 credited to FamPay Wallet via UPI from Gaurav (UPI ID: gaurav@fam). Transaction ID: 418293847562'+ };+ const parsed = BankSmsParser.parse(sms);+ assert.ok(parsed);+ assert.equal(parsed.amount, '350.00');+ assert.equal(parsed.amountPaise, 35000n);+ assert.equal(parsed.bankReferenceNumber, '418293847562');+ assert.equal(parsed.senderVpa, 'gaurav@fam');+ });++ test('Issue #20: normalizes FamPay observation with added to account format', () => {+ const obs = ObservationNormalizer.normalize({+ source: ObserverSource.GOOGLE_MESSAGES,+ receivingAccountId: 'acc_1',+ rawPayload: {+ text: 'Payment received! Rs. 500.00 added to your account via UPI from user@idfcbank. UPI Ref: 328910293841'+ }+ });+ assert.equal(obs.amountPaise, 50000n);+ assert.equal(obs.bankReferenceNumber, '328910293841');+ assert.equal(obs.senderVpa, 'user@idfcbank');+ });});});+diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex 66cf6eb..b577217 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -17,8 +17,9 @@ export class AttributionEngine {this.auditRepo = options.auditRepo;this.eventEmitter = options.eventEmitter || { emit: () => {} };const isTestExecution = process.env.NODE_ENV === 'test' ||- (process.execArgv && process.execArgv.includes('--test')) ||- (process.argv && process.argv.some(a => typeof a === 'string' && a.includes('test')));+ Boolean(process.env.NODE_TEST_CONTEXT) ||+ (process.execArgv && process.execArgv.some(a => a.includes('test'))) ||+ (process.argv && process.argv.some(a => a.includes('test')));this.gracePeriodMs = options.gracePeriodMs !== undefined? options.gracePeriodMs@@ -207,6 +208,69 @@ export class AttributionEngine {const isTimeValid = !isPriorExpiredSession && (normalizedObs.observedAt >= slotStart);+ // Invariant Check 0a: Transaction Reference Already Used Check+ let isUtrAlreadyUsed = false;+ const trimmedUtr = normalizedObs.bankReferenceNumber ? String(normalizedObs.bankReferenceNumber).trim() : '';+ if (trimmedUtr.length > 0) {+ const priorUsedSession = this.sessionRepo.db.queryOne(`+ SELECT ps.id, ps.order_id+ FROM payment_sessions ps+ JOIN payment_observations po ON (ps.attributed_observation_id = po.id OR po.attributed_payment_id = ps.id)+ WHERE ps.status = 'SUCCESS'+ AND ps.id != ?+ AND po.bank_reference_number = ?+ LIMIT 1+ `, [currentSession.id, trimmedUtr]);++ if (priorUsedSession) {+ isUtrAlreadyUsed = true;+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: currentSession.merchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: currentSession.id,+ action: 'REUSED_UTR_REJECTED',+ actorType: 'SYSTEM',+ details: {+ bankReferenceNumber: trimmedUtr,+ consumedByOrderId: priorUsedSession.order_id,+ consumedBySessionId: priorUsedSession.id+ }+ });+ }+ }+ }++ // Invariant Check 0b: Check if SMS is from personal numeric phone number (10-15 digits E.164, no letters)+ let isPersonalSms = false;+ const senderStr = (normalizedObs.rawPayload?.sender || normalizedObs.rawPayload?.from || '').toString().trim();+ if ((normalizedObs.source === 'SMS' || normalizedObs.source === 'ANDROID_OBSERVER') && senderStr) {+ const digitsOnly = senderStr.replace(/[\s+-]/g, '');+ if (digitsOnly.length >= 10 && /^\d+$/.test(digitsOnly) && !/[a-zA-Z]/.test(senderStr)) {+ isPersonalSms = true;+ }+ }++ if (isUtrAlreadyUsed) {+ return {+ attributed: false,+ duplicate: true,+ lateMatch: false,+ observationId: savedObs.id,+ outcomeStatus: 'REFERENCE_ALREADY_USED'+ };+ }++ if (isPersonalSms) {+ return {+ attributed: false,+ duplicate: false,+ lateMatch: false,+ observationId: savedObs.id,+ outcomeStatus: 'PERSONAL_SMS_REJECTED'+ };+ }+if (isEligibleStatus && isAmountMatch && isTimeValid) {const wasActive = currentSession.status === PaymentStatus.ACTIVE;@@ -414,12 +478,13 @@ export class AttributionEngine {// Check if observation confirms a recently successful session on this receiving account (within 60s)// Upgrades verification level (e.g. from Level 1 -> Level 2 -> Level 3)+ const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();const recentSuccessSession = this.sessionRepo.db.queryOne(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ? AND status = 'SUCCESS'- AND amount_paise = ? AND completed_at >= datetime('now', '-60 seconds')+ AND amount_paise = ? AND completed_at >= ?ORDER BY completed_at DESC LIMIT 1- `, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);+ `, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise), sixtySecsAgo]);if (recentSuccessSession) {// Check if this session's attributed observation had a UTR@@ -432,6 +497,47 @@ export class AttributionEngine {existingObs?.bankReferenceNumber &&normalizedObs.bankReferenceNumber !== existingObs.bankReferenceNumber;+ if (isUtrConflict) {+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: recentSuccessSession.merchant_id,+ entityType: 'PAYMENT_SESSION',+ entityId: recentSuccessSession.id,+ action: 'DUPLICATE_PAYMENT_UTR_CONFLICT',+ actorType: 'SYSTEM',+ details: {+ observationId: savedObs.id,+ existingUtr: existingObs?.bankReferenceNumber,+ newUtr: normalizedObs.bankReferenceNumber,+ amountPaise: normalizedObs.amountPaise.toString()+ }+ });+ }+ if (this.ticketRepo && recentSuccessSession.customer_id) {+ this.ticketRepo.createTicket({+ merchantId: recentSuccessSession.merchant_id,+ customerId: recentSuccessSession.customer_id,+ paymentId: recentSuccessSession.id,+ subject: `[DUPLICATE PAYMENT DETECTED] Order #${recentSuccessSession.order_id}`,+ status: TicketStatus.OPEN,+ initialMessage: {+ senderType: SenderType.ADMIN,+ senderId: recentSuccessSession.merchant_id,+ message: `A duplicate payment of ${normalizedObs.amountPaise / 100n} INR with reference ${normalizedObs.bankReferenceNumber} was received within 60s of completed order #${recentSuccessSession.order_id} (reference ${existingObs?.bankReferenceNumber || 'N/A'}). Flagged for merchant refund reconciliation.`+ }+ });+ }+ this.eventEmitter.emit('PAYMENT.DUPLICATE_DETECTED', {+ paymentId: recentSuccessSession.id,+ orderId: recentSuccessSession.order_id,+ merchantId: recentSuccessSession.merchant_id,+ observationId: savedObs.id,+ existingUtr: existingObs?.bankReferenceNumber,+ newUtr: normalizedObs.bankReferenceNumber,+ amountPaise: normalizedObs.amountPaise+ });+ }+const sessionSlotStart = recentSuccessSession.slot_acquired_at? new Date(new Date(recentSuccessSession.slot_acquired_at).getTime() - 30000): new Date(new Date(recentSuccessSession.created_at).getTime() - 30000);diff --git a/packages/core/src/bank-email-parser.js b/packages/core/src/bank-email-parser.jsindex 5f36e0c..d5d0b97 100644--- a/packages/core/src/bank-email-parser.js+++ b/packages/core/src/bank-email-parser.js@@ -31,14 +31,21 @@ export class BankEmailParser {if (!combinedText) return null;// Check if email represents an incoming credit/payment- const creditKeywords = /(credited|credit|received|deposit|payment received|payment|upi\/cr|transferred)/i;+ const creditKeywords = /\b(credited|credit|received|deposit|deposited|payment received|upi\/cr)\b/i;if (!creditKeywords.test(combinedText)) {return null; // Ignore non-credit alerts}- // Ignore pure debit notifications if no credit indicator exists- if (/(debited|withdrawn|sent rs|paid rs)/i.test(combinedText) && !/(credited|credit|received|deposit)/i.test(combinedText)) {- return null;+ // Reject debit notifications:+ const debitIdx = combinedText.search(/\b(?:debited|withdrawn|deducted|spent|paid rs|sent rs)\b/i);+ const creditIdx = combinedText.search(/\b(?:credited|credit|received|deposit|deposited)\b/i);+ if (debitIdx !== -1) {+ if (creditIdx === -1 || debitIdx < creditIdx) {+ return null;+ }+ if (/\b(?:debited\s*(?:from|by|for)|is\s+debited|has\s+been\s+debited)\b/i.test(combinedText)) {+ return null;+ }}// 1. Extract Monetary Amount using Intelligent Multi-Pattern Extractordiff --git a/packages/core/src/bank-sms-parser.js b/packages/core/src/bank-sms-parser.jsindex 992b7db..a8a49d7 100644--- a/packages/core/src/bank-sms-parser.js+++ b/packages/core/src/bank-sms-parser.js@@ -5,14 +5,30 @@ import { toPaise } from '@youpi/common';* Extracts amounts with prefix (Rs. 200, INR 500, ₹50), suffix (20.00 Rs),* proximity words ("20.00 received", "credited with 20.00"),* or standalone decimal amounts ("20.00").+ * Filters out available balance and credit limit clauses so balance amounts are never confused with payment amounts.* @param {string} text* @returns {{ amountStr: string, amountPaise: bigint } | null}*/export function extractIntelligentAmount(text) {if (!text || typeof text !== 'string') return null;- // Pattern 1: Standard currency prefix (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)- const prefixMatch = text.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);+ // 0. Remove balance mentions (e.g. "Avl Bal Rs 10,000", "Bal: INR 5000", "Available limit Rs. 20,000")+ // to avoid extracting account balance instead of credit amount.+ const balancePattern = /(?:(?:avl\b|avail\b|available\b|tot\b|total\b|ledger\b|clear\b|curr\b|current\b)\s*(?:bal\b|balance\b|limit\b)?|bal\b|balance\b)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*[\d,]+(?:\.\d{1,2})?/gi;+ const sanitizedText = text.replace(balancePattern, ' ').trim();++ // Pattern 0: Direct credit proximity phrases (e.g. "credited with Rs. 500", "received ₹200.00", "Rs 499.00 credited")+ const directCreditMatch = sanitizedText.match(/(?:credited\s*(?:with|by|for)?|received|deposit(?:ed)?)\s*[:=-]?\s*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i) ||+ sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)\s*(?:(?:has\s+been|is)\s+)?(?:credited|received|deposited)/i);+ if (directCreditMatch && (directCreditMatch[1] || directCreditMatch[2])) {+ const clean = (directCreditMatch[1] || directCreditMatch[2]).replace(/,/g, '');+ try {+ return { amountStr: clean, amountPaise: toPaise(clean) };+ } catch {}+ }++ // Pattern 1: Standard currency prefix on sanitized text (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)+ const prefixMatch = sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);if (prefixMatch && prefixMatch[1]) {const clean = prefixMatch[1].replace(/,/g, '');try {@@ -20,8 +36,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 2: Standard currency suffix (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)- const suffixMatch = text.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);+ // Pattern 2: Standard currency suffix on sanitized text (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)+ const suffixMatch = sanitizedText.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);if (suffixMatch && suffixMatch[1]) {const clean = suffixMatch[1].replace(/,/g, '');try {@@ -29,8 +45,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 3: Number adjacent to credit keywords (e.g. "20.00 received", "received 20.00", "credited 20", "20.00 credited")- const creditProximityMatch = text.match(/(?:credited|received|deposit|payment|paid|transferred|upi|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|payment|paid|transferred|upi|cr)/i);+ // Pattern 3: Number adjacent to credit keywords+ const creditProximityMatch = sanitizedText.match(/(?:credited|received|deposit|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|cr)/i);if (creditProximityMatch) {const rawVal = creditProximityMatch[1] || creditProximityMatch[2];if (rawVal) {@@ -44,7 +60,7 @@ export function extractIntelligentAmount(text) {}// Pattern 4: Standalone decimal currency number (e.g. 20.00, 150.50, 449.00)- const standaloneDecimal = text.match(/\b(\d{1,6}\.\d{2})\b/);+ const standaloneDecimal = sanitizedText.match(/\b(\d{1,6}\.\d{2})\b/);if (standaloneDecimal && standaloneDecimal[1]) {const clean = standaloneDecimal[1];try {@@ -84,15 +100,24 @@ export class BankSmsParser {const text = (sms.text || '').trim().slice(0, MAX_SCAN_CHARS);if (!text) return null;- // Check if SMS represents an incoming credit- const creditKeywords = /(credited|received|deposit|payment received|payment|upi\/cr|transferred)/i;+ // Check if SMS represents an incoming credit. Bare "payment" or "transferred" without credit context is rejected.+ const creditKeywords = /\b(credited|received|deposit|deposited|payment received|money received|added to (?:your )?(?:account|wallet)|upi\/cr)\b/i;if (!creditKeywords.test(text)) {return null;}- // Ignore pure debits- if (/(debited|withdrawn|sent rs|paid rs)/i.test(text) && !/(credited|received|deposit)/i.test(text)) {- return null;+ // Reject debit notifications:+ // If debit indicators exist and appear before credit indicators (e.g. "debited ... credited back in 48h")+ // or if the account itself is being debited, reject immediately.+ const debitIdx = text.search(/\b(?:debited|withdrawn|deducted|spent|paid rs|sent rs)\b/i);+ const creditIdx = text.search(/\b(?:credited|received|deposit|deposited)\b/i);+ if (debitIdx !== -1) {+ if (creditIdx === -1 || debitIdx < creditIdx) {+ return null;+ }+ if (/\b(?:debited\s*(?:from|by|for)|is\s+debited|has\s+been\s+debited)\b/i.test(text)) {+ return null;+ }}// 1. Extract Amount using Intelligent Multi-Pattern Extractor@@ -101,10 +126,11 @@ export class BankSmsParser {return null;}- // 2. Extract Bank Reference / UTR / RRN+ // 2. Extract Bank Reference / UTR / RRN (including FamPay Transaction IDs)let bankRef;const utrPatterns = [- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref|#)?|transaction\s*id|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,+ /(?:upi\/(?:[0-9]+\/|cr\/)([a-zA-Z0-9\-_]{6,35}))/i,/\b(?:ref(?:\s*(?:no\.?|id|#))?)[:\s#=-]+([a-zA-Z0-9\-_]{6,35})/i,/\b([0-9]{12})\b/];@@ -117,9 +143,9 @@ export class BankSmsParser {}}- // 3. Extract Sender VPA+ // 3. Extract Sender VPA (including FamPay formats like "from Rahul (UPI ID: rahul@fam)")let senderVpa;- const vpaMatch = text.match(/(?:from|by|vpa)\s+([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);+ const vpaMatch = text.match(/(?:from|by|vpa|upi\s*id)[\s:]+(?:[a-zA-Z\s]+[\(\[])?([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);if (vpaMatch && vpaMatch[1]) {senderVpa = vpaMatch[1].trim().replace(/[.,;]+$/, '');}diff --git a/packages/core/src/normalizer.js b/packages/core/src/normalizer.jsindex e027669..e8cebf4 100644--- a/packages/core/src/normalizer.js+++ b/packages/core/src/normalizer.js@@ -50,13 +50,13 @@ export function extractIntelligentPaise(text) {* Regex for extracting bank UTR / Reference numbers.* Matches: UTR: 123456789012, Ref 123456789012, Txn: ABC123XYZ, RRN: 987654*/-const REFERENCE_REGEX = /(?:utr|ref|txn|rrn|reference)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i;+const REFERENCE_REGEX = /(?:utr|ref(?:\s*no\.?)?|txn(?:\s*(?:id|#))?|transaction\s*id|rrn|reference(?:\s*no\.?)?|upi(?:\s*(?:ref|reference|txn))?)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i;/*** Regex for extracting sender VPA if present in notification text.- * Matches: from user@upi, from 9876543210@paytm, etc.+ * Matches: from user@upi, from 9876543210@paytm, from Rahul (UPI ID: rahul@fam), etc.*/-const SENDER_VPA_REGEX = /(?:from|by)\s+([a-zA-Z0-9.\-_]{2,100}@[a-zA-Z0-9.\-_]{2,64})/i;+const SENDER_VPA_REGEX = /(?:from|by|vpa|upi\s*id)[\s:]+(?:[a-zA-Z\s]+[\(\[])?([a-zA-Z0-9.\-_]{2,100}@[a-zA-Z0-9.\-_]{2,64})/i;export class ObservationNormalizer {/**