rpay-sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,367 @@
1
+ import { resolveBankSpec, resolveUsdtNetworkSpec } from "./constants.mjs";
2
+ import { normalizeTransferText } from "./matcher.mjs";
3
+
4
+ /**
5
+ * Detects whether an input object or code targets `"bank"` (VND) or `"usdt"` (USDT/USDC).
6
+ *
7
+ * @param {Record<string, any> | string} inputOrCode
8
+ * @param {"bank" | "usdt"} [fallback="bank"]
9
+ * @returns {"bank" | "usdt"}
10
+ */
11
+ export function detectPaymentChannel(inputOrCode, fallback = "bank") {
12
+ if (typeof inputOrCode === "string") {
13
+ const code = inputOrCode.trim().toUpperCase();
14
+ if (
15
+ code.startsWith("USINV") ||
16
+ code.startsWith("USTX") ||
17
+ code.startsWith("USDT") ||
18
+ code.startsWith("USDC")
19
+ ) {
20
+ return "usdt";
21
+ }
22
+ if (code.startsWith("RPINV") || code.startsWith("RPAY")) {
23
+ return "bank";
24
+ }
25
+ return fallback;
26
+ }
27
+
28
+ if (!inputOrCode || typeof inputOrCode !== "object") {
29
+ return fallback;
30
+ }
31
+
32
+ const explicitType = String(
33
+ inputOrCode.channel || inputOrCode.type || inputOrCode.paymentType || ""
34
+ )
35
+ .trim()
36
+ .toLowerCase();
37
+ if (explicitType === "usdt" || explicitType === "usdc" || explicitType === "crypto") {
38
+ return "usdt";
39
+ }
40
+ if (explicitType === "bank" || explicitType === "vietqr" || explicitType === "vnd") {
41
+ return "bank";
42
+ }
43
+
44
+ const currency = String(inputOrCode.currency || inputOrCode.token || "")
45
+ .trim()
46
+ .toUpperCase();
47
+ if (currency === "USDT" || currency === "USDC") {
48
+ return "usdt";
49
+ }
50
+ if (currency === "VND") {
51
+ return "bank";
52
+ }
53
+
54
+ if (
55
+ inputOrCode.amountUsdt !== undefined ||
56
+ (inputOrCode.network && resolveUsdtNetworkSpec(inputOrCode.network)) ||
57
+ inputOrCode.walletAddress ||
58
+ inputOrCode.trans_id
59
+ ) {
60
+ return "usdt";
61
+ }
62
+
63
+ if (
64
+ inputOrCode.amountVnd !== undefined ||
65
+ inputOrCode.bank ||
66
+ inputOrCode.bankBin ||
67
+ inputOrCode.bankNumber ||
68
+ inputOrCode.accountNumber
69
+ ) {
70
+ return "bank";
71
+ }
72
+
73
+ return fallback;
74
+ }
75
+
76
+ /**
77
+ * Normalizes a raw invoice status string from either Bank or USDT into a unified status:
78
+ * `"pending" | "paid" | "expired" | "cancelled"`
79
+ *
80
+ * @param {string} [rawStatus]
81
+ * @returns {"pending" | "paid" | "expired" | "cancelled"}
82
+ */
83
+ export function normalizeInvoiceStatus(rawStatus) {
84
+ const s = String(rawStatus || "pending").trim().toLowerCase();
85
+ if (
86
+ s === "paid" ||
87
+ s === "reconciled" ||
88
+ s === "completed" ||
89
+ s === "success" ||
90
+ s === "underpaid_settled" ||
91
+ s === "settled"
92
+ ) {
93
+ return "paid";
94
+ }
95
+ if (s === "expired" || s === "timeout") {
96
+ return "expired";
97
+ }
98
+ if (s === "cancelled" || s === "canceled" || s === "failed") {
99
+ return "cancelled";
100
+ }
101
+ return "pending";
102
+ }
103
+
104
+ /**
105
+ * Normalizes either a Bank Invoice response or a USDT Invoice response (Public REST or Standard AddInvoice)
106
+ * into a unified `UnifiedInvoiceDTO` structure that works identically for both Bank & USDT.
107
+ *
108
+ * @param {any} rawResponse
109
+ * @param {"bank" | "usdt"} [hintChannel]
110
+ */
111
+ export function normalizeUnifiedInvoice(rawResponse, hintChannel) {
112
+ const data =
113
+ rawResponse && typeof rawResponse === "object" && "data" in rawResponse && rawResponse.data
114
+ ? rawResponse.data
115
+ : rawResponse || {};
116
+
117
+ const channel =
118
+ hintChannel ||
119
+ (data.currency === "VND" || data.amountVnd !== undefined || data.beneficiary
120
+ ? "bank"
121
+ : "usdt");
122
+
123
+ if (channel === "bank") {
124
+ const status = normalizeInvoiceStatus(data.status);
125
+ return {
126
+ channel: /** @type {"bank"} */ ("bank"),
127
+ invoiceId: String(data.invoiceId || data.id || data.invoiceCode || ""),
128
+ invoiceCode: String(data.invoiceCode || ""),
129
+ orderId: String(data.orderId || ""),
130
+ status,
131
+ rawStatus: String(data.status || "pending"),
132
+ isPaid: status === "paid",
133
+ amount: Number(data.amountVnd ?? data.amount ?? 0),
134
+ paidAmount: Number(data.paidAmountVnd ?? (status === "paid" ? data.amountVnd : 0) ?? 0),
135
+ currency: "VND",
136
+ networkOrBank: String(data.beneficiary?.bankCode || data.provider || "BANK"),
137
+ bankBin: String(data.beneficiary?.bankBin || ""),
138
+ recipientAddress: String(data.beneficiary?.accountNumber || ""),
139
+ recipientName: String(data.beneficiary?.accountHolder || ""),
140
+ transferContent: String(data.transferContent || ""),
141
+ description: String(data.description || ""),
142
+ paymentUrl: String(data.paymentUrl || data.checkoutUrl || ""),
143
+ qrContent: String(data.qr?.content || ""),
144
+ qrImageUrl: String(data.qr?.imageUrl || ""),
145
+ qrDataUrl: String(data.qr?.dataUrl || ""),
146
+ cancelToken: data.cancelToken ? String(data.cancelToken) : undefined,
147
+ transactionId: data.matchedTransactionId ? String(data.matchedTransactionId) : undefined,
148
+ remainingSeconds: Number(data.remainingSeconds ?? 0),
149
+ expiresAt: data.expiresAt ? String(data.expiresAt) : undefined,
150
+ paidAt: data.paidAt ? String(data.paidAt) : undefined,
151
+ raw: data,
152
+ };
153
+ }
154
+
155
+ // USDT / USDC Invoice (supports both `/api/public/usdt-invoices` and `/api/AddInvoice`)
156
+ const status = normalizeInvoiceStatus(data.status);
157
+ const invoiceCode = String(data.invoiceCode || data.invoice_code || data.trans_id || data.txCode || "");
158
+ const txCode = String(data.txCode || data.trans_id || invoiceCode);
159
+ const amount = Number(data.amountUsdt ?? data.amount ?? 0);
160
+ const paidAmount = Number(
161
+ data.receivedUsdt ?? data.receivedAmountUsdt ?? data.received ?? (status === "paid" ? amount : 0) ?? 0
162
+ );
163
+
164
+ return {
165
+ channel: /** @type {"usdt"} */ ("usdt"),
166
+ invoiceId: String(data.id || data.invoiceId || txCode || invoiceCode),
167
+ invoiceCode: invoiceCode || txCode,
168
+ txCode,
169
+ orderId: String(data.orderId || data.request_id || data.orderCode || ""),
170
+ status,
171
+ rawStatus: String(data.status || "waiting"),
172
+ isPaid: status === "paid",
173
+ amount,
174
+ paidAmount,
175
+ currency: String(data.token || "USDT").toUpperCase(),
176
+ networkOrBank: String(data.network || "TRC20").toUpperCase(),
177
+ bankBin: "",
178
+ recipientAddress: String(data.walletAddress || data.address || ""),
179
+ recipientName: String(data.networkName || data.network || "USDT Wallet"),
180
+ transferContent: String(data.orderId || data.request_id || invoiceCode),
181
+ description: String(data.description || ""),
182
+ paymentUrl: String(data.paymentUrl || data.checkoutUrl || data.url_payment || ""),
183
+ qrContent: String(data.qrContent || data.walletAddress || data.address || ""),
184
+ qrImageUrl: String(data.qrImageUrl || data.qrcode || data.qr_code || ""),
185
+ qrDataUrl: String(data.qrDataUrl || data.qrcode || data.qr_code || ""),
186
+ transactionId: String(data.txHash || data.transaction_id || "") || undefined,
187
+ remainingSeconds: Number(data.remainingSeconds ?? 0),
188
+ expiresAt: data.expiresAt ? String(data.expiresAt) : undefined,
189
+ paidAt: data.paidAt || data.completedAt || data.update_gettime || undefined,
190
+ raw: data,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Normalizes a single Bank transaction (V2/V3/POS) or USDT invoice/transaction item
196
+ * into a unified `UnifiedTransactionDTO` for LSGD queries.
197
+ *
198
+ * @param {any} rawTx
199
+ * @param {"bank" | "usdt"} channel
200
+ * @param {object} [context]
201
+ * @param {string} [context.bankCode]
202
+ * @param {string} [context.accountNumber]
203
+ */
204
+ export function normalizeUnifiedTransaction(rawTx, channel, context = {}) {
205
+ if (channel === "bank") {
206
+ const numericAmount = Number(String(rawTx?.amount ?? "0").replace(/,/g, "").trim()) || 0;
207
+ const txType = String(rawTx?.type || "IN").trim().toUpperCase();
208
+ return {
209
+ channel: /** @type {"bank"} */ ("bank"),
210
+ transactionID: String(rawTx?.transactionID || rawTx?.id || ""),
211
+ invoiceCode: "",
212
+ orderId: "",
213
+ type: /** @type {"IN" | "OUT"} */ (txType === "OUT" ? "OUT" : "IN"),
214
+ status: /** @type {"completed"} */ ("completed"),
215
+ amount: numericAmount,
216
+ currency: "VND",
217
+ networkOrBank: String(rawTx?.bankCode || context.bankCode || "BANK"),
218
+ recipientAddress: String(rawTx?.accountNumber || context.accountNumber || ""),
219
+ senderAddress: "",
220
+ description: String(rawTx?.description || ""),
221
+ transactionDate: String(rawTx?.transactionDate || ""),
222
+ txHash: "",
223
+ raw: rawTx,
224
+ };
225
+ }
226
+
227
+ // USDT transaction / invoice history item
228
+ const rawStatus = String(rawTx?.status || "completed").toLowerCase();
229
+ const normalizedStatus = normalizeInvoiceStatus(rawStatus);
230
+ const amount = Number(rawTx?.received || rawTx?.receivedUsdt || rawTx?.amount || rawTx?.amountUsdt || 0);
231
+ const txId = String(
232
+ rawTx?.transaction_id ||
233
+ rawTx?.txHash ||
234
+ rawTx?.trans_id ||
235
+ rawTx?.txCode ||
236
+ rawTx?.invoice_code ||
237
+ rawTx?.invoiceCode ||
238
+ ""
239
+ );
240
+
241
+ return {
242
+ channel: /** @type {"usdt"} */ ("usdt"),
243
+ transactionID: txId,
244
+ invoiceCode: String(rawTx?.invoice_code || rawTx?.invoiceCode || rawTx?.trans_id || ""),
245
+ orderId: String(rawTx?.request_id || rawTx?.orderId || ""),
246
+ type: /** @type {"IN" | "OUT"} */ ("IN"),
247
+ status: /** @type {"completed" | "pending" | "expired" | "cancelled"} */ (
248
+ normalizedStatus === "paid" ? "completed" : normalizedStatus
249
+ ),
250
+ amount,
251
+ currency: String(rawTx?.token || "USDT").toUpperCase(),
252
+ networkOrBank: String(rawTx?.network || "TRC20").toUpperCase(),
253
+ recipientAddress: String(rawTx?.address || rawTx?.walletAddress || ""),
254
+ senderAddress: String(rawTx?.from_address || rawTx?.fromAddress || ""),
255
+ description: String(
256
+ rawTx?.description ||
257
+ rawTx?.request_id ||
258
+ rawTx?.orderId ||
259
+ rawTx?.invoice_code ||
260
+ ""
261
+ ),
262
+ transactionDate: String(
263
+ rawTx?.update_gettime ||
264
+ rawTx?.create_gettime ||
265
+ rawTx?.completedAt ||
266
+ rawTx?.createdAt ||
267
+ ""
268
+ ),
269
+ txHash: String(rawTx?.transaction_id || rawTx?.txHash || ""),
270
+ raw: rawTx,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Matches unified transactions (both Bank VND and Crypto USDT/USDC) against expected payment criteria
276
+ * with idempotent `processedIds` deduplication.
277
+ *
278
+ * @param {Array<ReturnType<typeof normalizeUnifiedTransaction>>} unifiedTransactions
279
+ * @param {object} criteria
280
+ * @param {"bank" | "usdt" | "all"} [criteria.channel="all"]
281
+ * @param {number | string} [criteria.expectedAmount]
282
+ * @param {string} [criteria.orderCode]
283
+ * @param {string} [criteria.orderId]
284
+ * @param {string} [criteria.transferContent]
285
+ * @param {string} [criteria.txHash]
286
+ * @param {boolean} [criteria.exactAmount=false]
287
+ * @param {Iterable<string>} [criteria.processedIds]
288
+ * @param {boolean} [criteria.mutateProcessedIds=false]
289
+ */
290
+ export function matchUnifiedTransactions(unifiedTransactions, criteria = {}) {
291
+ if (!Array.isArray(unifiedTransactions) || unifiedTransactions.length === 0) {
292
+ return [];
293
+ }
294
+
295
+ const filterChannel = String(criteria.channel || "all").toLowerCase();
296
+ const expectedAmount = Number(criteria.expectedAmount ?? 0);
297
+ const needleRaw = String(
298
+ criteria.orderCode ?? criteria.orderId ?? criteria.transferContent ?? ""
299
+ ).trim();
300
+ const needleUpper = needleRaw.toUpperCase();
301
+ const needleCompact = needleRaw ? normalizeTransferText(needleRaw, true) : "";
302
+ const txHashNeedle = String(criteria.txHash || "").trim().toLowerCase();
303
+ const exactAmount = Boolean(criteria.exactAmount);
304
+
305
+ const processedSet =
306
+ criteria.processedIds instanceof Set
307
+ ? criteria.processedIds
308
+ : new Set(Array.isArray(criteria.processedIds) ? criteria.processedIds.map(String) : []);
309
+
310
+ const matches = [];
311
+ for (const item of unifiedTransactions) {
312
+ if (!item || typeof item !== "object") {
313
+ continue;
314
+ }
315
+ if (filterChannel !== "all" && item.channel !== filterChannel) {
316
+ continue;
317
+ }
318
+
319
+ const id = String(item.transactionID || item.invoiceCode || "").trim();
320
+ if (!id || processedSet.has(id)) {
321
+ continue;
322
+ }
323
+
324
+ if (item.type !== "IN" || (item.status !== "completed" && item.status !== "paid")) {
325
+ continue;
326
+ }
327
+
328
+ if (expectedAmount > 0) {
329
+ if (exactAmount && item.amount !== expectedAmount) {
330
+ continue;
331
+ }
332
+ if (!exactAmount && item.amount < expectedAmount) {
333
+ continue;
334
+ }
335
+ }
336
+
337
+ if (txHashNeedle && String(item.txHash || "").toLowerCase() !== txHashNeedle) {
338
+ continue;
339
+ }
340
+
341
+ if (needleRaw) {
342
+ const desc = String(item.description || "");
343
+ const orderId = String(item.orderId || "");
344
+ const invCode = String(item.invoiceCode || "");
345
+
346
+ const directHit =
347
+ desc.toUpperCase().includes(needleUpper) ||
348
+ orderId.toUpperCase() === needleUpper ||
349
+ invCode.toUpperCase() === needleUpper;
350
+ const compactHit =
351
+ needleCompact.length > 0 &&
352
+ (normalizeTransferText(desc, true).includes(needleCompact) ||
353
+ normalizeTransferText(orderId, true) === needleCompact);
354
+
355
+ if (!directHit && !compactHit) {
356
+ continue;
357
+ }
358
+ }
359
+
360
+ matches.push(item);
361
+ if (criteria.mutateProcessedIds && criteria.processedIds instanceof Set) {
362
+ criteria.processedIds.add(id);
363
+ }
364
+ }
365
+
366
+ return matches;
367
+ }