forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransactionRepository.js
More file actions
631 lines (567 loc) · 16.4 KB
/
Copy pathtransactionRepository.js
File metadata and controls
631 lines (567 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
const logger = require('../lib/logger');
const { query, pool } = require('./index');
const { client: redisClient } = require('../lib/redis');
const HISTORY_SELECT = `
SELECT t.*, c.name AS campaign_name
FROM transactions t
LEFT JOIN campaigns c ON t.campaign_id = c.id
`;
async function invalidateLeaderboardCache(txType) {
if (txType !== 'distribution' || !redisClient?.del) {
return;
}
await Promise.all([
redisClient.del('leaderboard:weekly'),
redisClient.del('leaderboard:alltime'),
]).catch((err) => logger.error('[leaderboard] cache invalidation failed', err));
}
function buildHistoryFilters({
userId,
merchantId,
type,
status,
startDate,
endDate,
reconciled,
}) {
const conditions = [];
const params = [];
if (userId !== undefined && userId !== null) {
params.push(userId);
conditions.push(`t.user_id = $${params.length}`);
}
if (merchantId !== undefined && merchantId !== null) {
params.push(merchantId);
conditions.push(`t.merchant_id = $${params.length}`);
}
if (type) {
params.push(type);
conditions.push(`t.tx_type = $${params.length}`);
}
if (status) {
params.push(status);
conditions.push(`t.status = $${params.length}`);
}
if (startDate) {
params.push(startDate);
conditions.push(`t.created_at >= $${params.length}`);
}
if (endDate) {
params.push(endDate);
conditions.push(`t.created_at <= $${params.length}`);
}
if (typeof reconciled === 'boolean') {
conditions.push(reconciled ? 't.reconciled_at IS NOT NULL' : 't.reconciled_at IS NULL');
}
return {
whereClause: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
params,
};
}
/**
* Records a transaction in the database.
*
* @param {object} params
* @param {string} params.txHash
* @param {string} params.txType
* @param {string|number} params.amount
* @param {string|null} [params.fromWallet]
* @param {string|null} [params.toWallet]
* @param {number|null} [params.merchantId]
* @param {number|null} [params.campaignId]
* @param {number|null} [params.userId]
* @param {number|null} [params.stellarLedger]
* @param {string} [params.status]
* @param {string|null} [params.referenceTxHash]
* @param {string|null} [params.refundReason]
* @param {object} [params.metadata]
* @returns {Promise<object>}
*/
async function recordTransaction({
txHash,
txType,
amount,
fromWallet = null,
toWallet = null,
merchantId = null,
campaignId = null,
userId = null,
stellarLedger = null,
status = 'completed',
referenceTxHash = null,
refundReason = null,
metadata = {},
}) {
const result = await query(
`INSERT INTO transactions
(
tx_hash,
tx_type,
amount,
from_wallet,
to_wallet,
merchant_id,
campaign_id,
user_id,
stellar_ledger,
status,
reference_tx_hash,
refund_reason,
metadata
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb)
RETURNING *`,
[
txHash,
txType,
amount,
fromWallet,
toWallet,
merchantId,
campaignId,
userId,
stellarLedger,
status,
referenceTxHash,
refundReason,
JSON.stringify(metadata || {}),
]
);
await invalidateLeaderboardCache(txType);
return result.rows[0];
}
/**
* Retrieves a transaction by hash.
*
* @param {string} txHash
* @returns {Promise<object|null>}
*/
async function getTransactionByHash(txHash) {
const result = await query(
`${HISTORY_SELECT}
WHERE t.tx_hash = $1`,
[txHash]
);
return result.rows[0] || null;
}
/**
* Returns transactions associated with a merchant.
*
* @param {number} merchantId
* @param {object} [options]
* @returns {Promise<object[]>}
*/
async function getTransactionsByMerchant(merchantId, options = {}) {
const { whereClause, params } = buildHistoryFilters({
merchantId,
type: options.type,
status: options.status,
startDate: options.startDate,
endDate: options.endDate,
reconciled: options.reconciled,
});
const result = await query(
`${HISTORY_SELECT}
${whereClause}
ORDER BY t.created_at DESC`,
params
);
return result.rows;
}
/**
* Returns the total distributed and redeemed amounts for a merchant.
*
* @param {number} merchantId
* @returns {Promise<{ totalDistributed: string, totalRedeemed: string }>}
*/
async function getMerchantTotals(merchantId) {
const result = await query(
`SELECT tx_type, COALESCE(SUM(amount), 0) AS total
FROM transactions
WHERE merchant_id = $1
AND tx_type IN ('distribution', 'redemption')
AND status <> 'failed'
GROUP BY tx_type`,
[merchantId]
);
const totalsByType = result.rows.reduce((accumulator, row) => {
accumulator[row.tx_type] = String(row.total);
return accumulator;
}, {});
return {
totalDistributed: totalsByType.distribution || '0',
totalRedeemed: totalsByType.redemption || '0',
};
}
/**
* Returns paginated transactions for a user with optional filters.
*
* @param {number} userId
* @param {object} params
* @returns {Promise<{data: object[], total: number, page: number, limit: number}>}
*/
async function getTransactionsByUser(userId, params = {}) {
return getTransactionHistory({
userId,
type: params.type,
status: params.status,
startDate: params.startDate,
endDate: params.endDate,
page: params.page,
limit: params.limit,
reconciled: params.reconciled,
});
}
/**
* Returns paginated transaction history for the supplied filters.
*
* @param {object} filters
* @returns {Promise<{data: object[], total: number, page: number, limit: number}>}
*/
async function getTransactionHistory(filters = {}) {
const page = filters.page || 1;
const limit = filters.limit || 20;
const offset = (page - 1) * limit;
const { whereClause, params } = buildHistoryFilters(filters);
const countResult = await query(
`SELECT COUNT(*) AS total
FROM transactions t
${whereClause}`,
params
);
const dataResult = await query(
`${HISTORY_SELECT}
${whereClause}
ORDER BY t.created_at DESC
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
[...params, limit, offset]
);
return {
data: dataResult.rows,
total: parseInt(countResult.rows[0].total, 10),
page,
limit,
};
}
/**
* Updates a transaction's lifecycle fields.
*
* @param {string} txHash
* @param {object} updates
* @returns {Promise<object|null>}
*/
async function updateTransaction(txHash, updates = {}) {
const allowedFields = ['status', 'refund_reason', 'reference_tx_hash', 'reconciled_at', 'metadata'];
const assignments = [];
const params = [];
for (const field of allowedFields) {
if (updates[field] === undefined) {
continue;
}
params.push(field === 'metadata' ? JSON.stringify(updates[field] || {}) : updates[field]);
const valueExpression = field === 'metadata' ? `$${params.length}::jsonb` : `$${params.length}`;
assignments.push(`${field} = ${valueExpression}`);
}
if (assignments.length === 0) {
return getTransactionByHash(txHash);
}
params.push(txHash);
const result = await query(
`UPDATE transactions
SET ${assignments.join(', ')}, updated_at = NOW()
WHERE tx_hash = $${params.length}
RETURNING *`,
params
);
return result.rows[0] || null;
}
/**
* Processes a full refund in a single database transaction.
*
* @param {object} params
* @returns {Promise<{originalTransaction: object, refundTransaction: object}>}
*/
async function processRefund({
txHash,
refundTxHash,
refundReason,
stellarLedger = null,
metadata = {},
}) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const existingRefundResult = await client.query(
`${HISTORY_SELECT}
WHERE t.tx_hash = $1`,
[refundTxHash]
);
if (existingRefundResult.rows[0]) {
const duplicateError = new Error('Refund transaction has already been recorded');
duplicateError.status = 409;
duplicateError.code = 'duplicate_transaction';
throw duplicateError;
}
const originalResult = await client.query(
`${HISTORY_SELECT}
WHERE t.tx_hash = $1
FOR UPDATE`,
[txHash]
);
const originalTransaction = originalResult.rows[0] || null;
if (!originalTransaction) {
const missingError = new Error('Transaction not found');
missingError.status = 404;
missingError.code = 'not_found';
throw missingError;
}
if (originalTransaction.tx_type === 'refund') {
const invalidError = new Error('Refund transactions cannot be refunded again');
invalidError.status = 409;
invalidError.code = 'invalid_refund_target';
throw invalidError;
}
if (originalTransaction.status === 'refunded') {
const refundedError = new Error('Transaction has already been refunded');
refundedError.status = 409;
refundedError.code = 'already_refunded';
throw refundedError;
}
const refundInsert = await client.query(
`INSERT INTO transactions
(
tx_hash,
tx_type,
amount,
from_wallet,
to_wallet,
merchant_id,
campaign_id,
user_id,
stellar_ledger,
status,
reference_tx_hash,
refund_reason,
metadata
)
VALUES ($1, 'refund', $2, $3, $4, $5, $6, $7, $8, 'completed', $9, $10, $11::jsonb)
RETURNING *`,
[
refundTxHash,
originalTransaction.amount,
originalTransaction.to_wallet,
originalTransaction.from_wallet,
originalTransaction.merchant_id,
originalTransaction.campaign_id,
originalTransaction.user_id,
stellarLedger,
originalTransaction.tx_hash,
refundReason,
JSON.stringify(metadata || {}),
]
);
const originalUpdate = await client.query(
`UPDATE transactions
SET status = 'refunded',
refund_reason = $1,
updated_at = NOW()
WHERE tx_hash = $2
RETURNING *`,
[refundReason, txHash]
);
await client.query('COMMIT');
await invalidateLeaderboardCache(refundInsert.rows[0].tx_type);
return {
originalTransaction: originalUpdate.rows[0],
refundTransaction: refundInsert.rows[0],
};
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
/**
* Marks matching transactions as reconciled and returns a summary.
*
* @param {object} filters
* @returns {Promise<{count: number, totalAmount: string, transactions: object[]}>}
*/
async function reconcileTransactions(filters = {}) {
const { whereClause, params } = buildHistoryFilters(filters);
const effectiveWhere = whereClause
? `${whereClause} AND t.reconciled_at IS NULL`
: 'WHERE t.reconciled_at IS NULL';
const result = await query(
`UPDATE transactions t
SET reconciled_at = NOW(),
updated_at = NOW(),
status = CASE WHEN t.status = 'completed' THEN 'reconciled' ELSE t.status END
${effectiveWhere}
RETURNING *`,
params
);
const totalAmount = result.rows.reduce(
(sum, row) => (Number(sum) + Number(row.amount)).toFixed(7),
'0.0000000'
);
return {
count: result.rows.length,
totalAmount,
transactions: result.rows,
};
}
/**
* Builds an aggregate report for the supplied filters.
*
* @param {object} filters
* @returns {Promise<object>}
*/
async function getTransactionReport(filters = {}) {
const { whereClause, params } = buildHistoryFilters(filters);
const summaryResult = await query(
`SELECT
COUNT(*) AS total_transactions,
COALESCE(SUM(amount), 0) AS total_amount,
COALESCE(SUM(CASE WHEN tx_type = 'refund' THEN amount ELSE 0 END), 0) AS refunded_amount,
COALESCE(SUM(CASE WHEN status = 'reconciled' THEN amount ELSE 0 END), 0) AS reconciled_amount
FROM transactions t
${whereClause}`,
params
);
const groupedResult = await query(
`SELECT tx_type, status, COUNT(*) AS transaction_count, COALESCE(SUM(amount), 0) AS total_amount
FROM transactions t
${whereClause}
GROUP BY tx_type, status
ORDER BY tx_type ASC, status ASC`,
params
);
return {
summary: summaryResult.rows[0],
breakdown: groupedResult.rows,
};
}
/**
* Cursor-paginated transaction history scoped to an authenticated user's wallet.
* Issue #866 — GET /api/transactions
*
* Cursor is a base64-encoded JSON string: { createdAt, id }
*
* @param {string} walletAddress
* @param {{ limit?: number, cursor?: string, direction?: 'asc'|'desc' }} opts
* @returns {Promise<{ data: object[], nextCursor: string|null, hasMore: boolean }>}
*/
async function getUserTransactionsCursor(walletAddress, { limit = 25, cursor, direction = 'desc' } = {}) {
const safeLimit = Math.min(Math.max(1, parseInt(limit, 10) || 25), 100);
const isAsc = direction === 'asc';
const params = [walletAddress];
let cursorClause = '';
if (cursor) {
try {
const decoded = JSON.parse(Buffer.from(cursor, 'base64').toString('utf8'));
const { createdAt, id } = decoded;
if (createdAt && id) {
params.push(createdAt, parseInt(id, 10));
cursorClause = isAsc
? `AND (t.created_at, t.id) > ($${params.length - 1}::timestamptz, $${params.length})`
: `AND (t.created_at, t.id) < ($${params.length - 1}::timestamptz, $${params.length})`;
}
} catch (_) {
// invalid cursor — start from beginning
}
}
const orderDir = isAsc ? 'ASC' : 'DESC';
const result = await query(
`SELECT t.id,
t.tx_hash,
t.tx_type,
t.amount,
t.from_wallet,
t.to_wallet,
t.status,
t.created_at,
t.updated_at,
c.name AS campaign_name,
c.id AS campaign_id
FROM transactions t
LEFT JOIN campaigns c ON t.campaign_id = c.id
WHERE (t.from_wallet = $1 OR t.to_wallet = $1)
${cursorClause}
ORDER BY t.created_at ${orderDir}, t.id ${orderDir}
LIMIT $${params.length + 1}`,
[...params, safeLimit + 1]
);
const rows = result.rows;
const hasMore = rows.length > safeLimit;
const data = hasMore ? rows.slice(0, safeLimit) : rows;
const nextCursor = hasMore
? Buffer.from(JSON.stringify({
createdAt: data[data.length - 1].created_at,
id: data[data.length - 1].id,
})).toString('base64')
: null;
return { data, nextCursor, hasMore };
}
/**
* Cursor-based rewards history for a user.
* Cursor is the base64-encoded `created_at::id` of the last seen row.
*
* @param {number} userId
* @param {{ limit?: number, cursor?: string }} opts
* @returns {Promise<{ data: object[], nextCursor: string|null }>}
*/
async function getRewardsHistoryCursor(userId, { limit = 20, cursor } = {}) {
const safeLimit = Math.min(Math.max(1, parseInt(limit, 10) || 20), 100);
const params = [userId];
let cursorClause = '';
if (cursor) {
try {
const decoded = Buffer.from(cursor, 'base64').toString('utf8');
const [ts, id] = decoded.split('::');
params.push(ts, parseInt(id, 10));
cursorClause = `AND (t.created_at, t.id) < ($${params.length - 1}::timestamptz, $${params.length})`;
} catch (_) {
// invalid cursor — ignore and start from the beginning
}
}
const result = await query(
`SELECT t.id,
t.tx_hash,
t.tx_type AS action_type,
t.amount,
t.created_at AS timestamp,
t.status,
c.name AS campaign_name,
c.id AS campaign_id
FROM transactions t
LEFT JOIN campaigns c ON t.campaign_id = c.id
WHERE t.user_id = $1
${cursorClause}
ORDER BY t.created_at DESC, t.id DESC
LIMIT $${params.length + 1}`,
[...params, safeLimit + 1]
);
const rows = result.rows;
const hasMore = rows.length > safeLimit;
const data = hasMore ? rows.slice(0, safeLimit) : rows;
const nextCursor = hasMore
? Buffer.from(`${data[data.length - 1].timestamp}::${data[data.length - 1].id}`).toString('base64')
: null;
return { data, nextCursor };
}
module.exports = {
recordTransaction,
getTransactionByHash,
getTransactionsByMerchant,
getMerchantTotals,
getTransactionsByUser,
getTransactionHistory,
getRewardsHistoryCursor,
getUserTransactionsCursor,
updateTransaction,
processRefund,
reconcileTransactions,
getTransactionReport,
};