190 lines
9.0 KiB
JavaScript
190 lines
9.0 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.create = create;
|
|
exports.insertDepositIfNew = insertDepositIfNew;
|
|
exports.updateStatus = updateStatus;
|
|
exports.findByBlockchainTxId = findByBlockchainTxId;
|
|
exports.findById = findById;
|
|
exports.listByUserId = listByUserId;
|
|
exports.listWithdrawalsSince = listWithdrawalsSince;
|
|
exports.countByUserId = countByUserId;
|
|
exports.mergeGameStakeBetStatus = mergeGameStakeBetStatus;
|
|
exports.enrichGameStakeBetStatus = enrichGameStakeBetStatus;
|
|
const connection_1 = require("../db/connection");
|
|
function activityCategoryFilter(category) {
|
|
switch (category) {
|
|
case 'deposits':
|
|
return ` AND type IN ('deposit', 'bonus', 'admin_adjustment')`;
|
|
case 'withdrawals':
|
|
return ` AND type = 'withdrawal'`;
|
|
case 'transfers':
|
|
return ` AND type = 'transfer'`;
|
|
case 'predictions':
|
|
return ` AND type IN ('game_stake', 'game_payout', 'game_refund')`;
|
|
default:
|
|
return '';
|
|
}
|
|
}
|
|
/**
|
|
* Repository for blockchain transaction records.
|
|
* Persists deposits, withdrawals, and transfers with status and confirmation tracking.
|
|
*/
|
|
/**
|
|
* Inserts a new transaction record.
|
|
* @param data - Transaction fields to persist.
|
|
* @param data.userId - ID of the user who owns the transaction.
|
|
* @param data.walletTypeId - Wallet type for this transaction.
|
|
* @param data.type - Transaction kind: deposit, withdrawal, or transfer.
|
|
* @param data.amount - Amount in the smallest currency unit.
|
|
* @param data.fee - Optional fee amount (defaults to 0).
|
|
* @param data.status - Current transaction status.
|
|
* @param data.blockchainTxId - Optional on-chain transaction hash or ID.
|
|
* @param data.fromAddress - Optional sender address.
|
|
* @param data.toAddress - Optional recipient address.
|
|
* @param data.confirmations - Optional current confirmation count.
|
|
* @param data.requiredConfirmations - Optional confirmations required before completion.
|
|
* @param data.metadata - Optional additional context as key-value pairs.
|
|
* @returns The newly created transaction record.
|
|
*/
|
|
async function create(data) {
|
|
const rows = await (0, connection_1.query)(`INSERT INTO transactions (user_id, wallet_type_id, type, amount, fee, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
|
RETURNING id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at`, [
|
|
data.userId,
|
|
data.walletTypeId,
|
|
data.type,
|
|
data.amount.toString(),
|
|
(data.fee ?? 0).toString(),
|
|
data.status,
|
|
data.blockchainTxId ?? null,
|
|
data.fromAddress ?? null,
|
|
data.toAddress ?? null,
|
|
data.confirmations ?? null,
|
|
data.requiredConfirmations ?? null,
|
|
data.metadata ? JSON.stringify(data.metadata) : null,
|
|
]);
|
|
return rows[0];
|
|
}
|
|
/**
|
|
* Inserts a deposit transaction if the blockchain tx id is new (idempotent).
|
|
* Must run inside an authorized DB transaction started by the caller.
|
|
*/
|
|
async function insertDepositIfNew(client, data) {
|
|
const res = await client.query(`INSERT INTO transactions (
|
|
user_id, wallet_type_id, type, amount, fee, status,
|
|
blockchain_tx_id, from_address, to_address, confirmations, required_confirmations
|
|
)
|
|
VALUES ($1, $2, 'deposit', $3, 0, 'completed', $4, $5, $6, $7, $8)
|
|
ON CONFLICT (blockchain_tx_id) WHERE blockchain_tx_id IS NOT NULL
|
|
DO NOTHING
|
|
RETURNING id, user_id, wallet_type_id, type, amount::text, fee::text, status,
|
|
blockchain_tx_id, from_address, to_address, confirmations, required_confirmations,
|
|
metadata, created_at, updated_at`, [
|
|
data.userId,
|
|
data.walletTypeId,
|
|
data.amount.toString(),
|
|
data.blockchainTxId,
|
|
data.fromAddress,
|
|
data.toAddress,
|
|
data.confirmations,
|
|
data.requiredConfirmations,
|
|
]);
|
|
return res.rows[0] ?? null;
|
|
}
|
|
/**
|
|
* Updates a transaction's status and optionally its confirmations or blockchain TX ID.
|
|
* @param id - ID of the transaction to update.
|
|
* @param status - New status value.
|
|
* @param confirmations - Optional confirmation count (existing value kept if omitted).
|
|
* @param blockchainTxId - Optional blockchain TX ID (existing value kept if omitted).
|
|
* @returns Resolves when the row has been updated.
|
|
*/
|
|
async function updateStatus(id, status, confirmations, blockchainTxId) {
|
|
await (0, connection_1.query)('UPDATE transactions SET status = $1, confirmations = COALESCE($2, confirmations), blockchain_tx_id = COALESCE($3, blockchain_tx_id), updated_at = NOW() WHERE id = $4', [status, confirmations ?? null, blockchainTxId ?? null, id]);
|
|
}
|
|
/**
|
|
* Finds a transaction by its on-chain transaction ID.
|
|
* @param blockchainTxId - Blockchain transaction hash or ID.
|
|
* @returns The matching transaction, or null if not found.
|
|
*/
|
|
async function findByBlockchainTxId(blockchainTxId) {
|
|
const rows = await (0, connection_1.query)('SELECT id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at FROM transactions WHERE blockchain_tx_id = $1', [blockchainTxId]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Finds a transaction by its primary key.
|
|
* @param id - Transaction UUID.
|
|
* @returns The matching transaction, or null if not found.
|
|
*/
|
|
async function findById(id) {
|
|
const rows = await (0, connection_1.query)('SELECT id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at FROM transactions WHERE id = $1', [id]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Lists a user's transactions ordered by creation time (newest first).
|
|
* @param userId - ID of the user whose transactions to fetch.
|
|
* @param limit - Maximum number of rows to return (default 50).
|
|
* @param offset - Number of rows to skip for pagination (default 0).
|
|
* @returns Array of transaction records.
|
|
*/
|
|
async function listByUserId(userId, limit = 50, offset = 0, category) {
|
|
const categorySql = activityCategoryFilter(category);
|
|
return (0, connection_1.query)(`SELECT id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at
|
|
FROM transactions WHERE user_id = $1${categorySql} ORDER BY created_at DESC LIMIT $2 OFFSET $3`, [userId, limit, offset]);
|
|
}
|
|
/** Withdrawal rows since a UTC timestamp (for daily limit checks). */
|
|
async function listWithdrawalsSince(userId, since) {
|
|
return (0, connection_1.query)(`SELECT t.amount::text, COALESCE(t.fee, 0)::text AS fee, wt.code, wt.decimals
|
|
FROM transactions t
|
|
INNER JOIN wallet_types wt ON wt.id = t.wallet_type_id
|
|
WHERE t.user_id = $1
|
|
AND t.type = 'withdrawal'
|
|
AND t.status NOT IN ('failed', 'cancelled')
|
|
AND t.created_at >= $2`, [userId, since]);
|
|
}
|
|
/** Total transaction count for a user (pagination). */
|
|
async function countByUserId(userId, category) {
|
|
const categorySql = activityCategoryFilter(category);
|
|
const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM transactions WHERE user_id = $1${categorySql}`, [userId]);
|
|
return parseInt(rows[0]?.count ?? '0', 10);
|
|
}
|
|
/** Mirror settled bet outcome onto the original game_stake row for Wallet Activity share UX. */
|
|
async function mergeGameStakeBetStatus(betId, betStatus) {
|
|
await (0, connection_1.query)(`UPDATE transactions
|
|
SET metadata = COALESCE(metadata, '{}'::jsonb) || $2::jsonb,
|
|
updated_at = NOW()
|
|
WHERE type = 'game_stake'
|
|
AND metadata->>'bet_id' = $1`, [betId, JSON.stringify({ bet_status: betStatus })]);
|
|
}
|
|
/**
|
|
* Attach candle_predict_bets.status onto game_stake metadata as bet_status
|
|
* so clients can label losses and show share consistently (even across pages).
|
|
*/
|
|
async function enrichGameStakeBetStatus(txs) {
|
|
const betIds = [
|
|
...new Set(txs
|
|
.filter((t) => t.type === 'game_stake' && t.metadata?.bet_id)
|
|
.map((t) => String(t.metadata.bet_id))),
|
|
];
|
|
if (betIds.length === 0)
|
|
return txs;
|
|
const rows = await (0, connection_1.query)(`SELECT id::text AS id, status
|
|
FROM candle_predict_bets
|
|
WHERE id = ANY($1::uuid[])`, [betIds]);
|
|
const statusById = new Map(rows.map((r) => [r.id, r.status]));
|
|
return txs.map((tx) => {
|
|
if (tx.type !== 'game_stake')
|
|
return tx;
|
|
const betId = tx.metadata?.bet_id ? String(tx.metadata.bet_id) : '';
|
|
if (!betId)
|
|
return tx;
|
|
const status = statusById.get(betId);
|
|
if (status !== 'won' && status !== 'lost' && status !== 'refunded')
|
|
return tx;
|
|
return {
|
|
...tx,
|
|
metadata: { ...(tx.metadata ?? {}), bet_status: status },
|
|
};
|
|
});
|
|
}
|
|
//# sourceMappingURL=transactionRepository.js.map
|