games_app/backend/dist/repositories/ledgerRepository.js
2026-06-29 15:01:23 +02:00

296 lines
15 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrCreateAccount = getOrCreateAccount;
exports.getOrCreateMainAccount = getOrCreateMainAccount;
exports.getOrCreateBonusAccount = getOrCreateBonusAccount;
exports.getOrCreateTestAccount = getOrCreateTestAccount;
exports.getAccount = getAccount;
exports.credit = credit;
exports.debit = debit;
exports.lockBalance = lockBalance;
exports.unlockBalance = unlockBalance;
exports.deductLocked = deductLocked;
exports.transferBetweenAccounts = transferBetweenAccounts;
exports.finalizeWithdrawalFromLocked = finalizeWithdrawalFromLocked;
exports.listAllAccountsForIntegrity = listAllAccountsForIntegrity;
exports.listUnauthorizedEntryTypes = listUnauthorizedEntryTypes;
const connection_1 = require("../db/connection");
/**
* Repository for double-entry ledger accounts and balance operations.
* Manages available and locked balances with transactional credit, debit, and transfer flows.
*/
/**
* Ensures a ledger account exists for a user and wallet type, then returns it.
* @param userId - ID of the account owner.
* @param walletTypeId - Wallet type for the account.
* @returns The ledger account record (created if it did not exist).
*/
async function getOrCreateAccount(userId, walletTypeId, accountKind = 'main') {
await (0, connection_1.query)(`INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind)
VALUES ($1, $2, $3)
ON CONFLICT (user_id, wallet_type_id, account_kind) DO NOTHING`, [userId, walletTypeId, accountKind]);
const rows = await (0, connection_1.query)(`SELECT id, user_id, wallet_type_id, available_balance::text, locked_balance::text, updated_at
FROM ledger_accounts WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3`, [userId, walletTypeId, accountKind]);
return rows[0];
}
/**
* @deprecated Use getOrCreateAccount with accountKind. Kept for backward compatibility.
*/
async function getOrCreateMainAccount(userId, walletTypeId) {
return getOrCreateAccount(userId, walletTypeId, 'main');
}
async function getOrCreateBonusAccount(userId, walletTypeId) {
return getOrCreateAccount(userId, walletTypeId, 'bonus');
}
async function getOrCreateTestAccount(userId, walletTypeId) {
return getOrCreateAccount(userId, walletTypeId, 'test');
}
/**
* Retrieves an existing ledger account without creating one.
* @param userId - ID of the account owner.
* @param walletTypeId - Wallet type for the account.
* @returns The ledger account record, or null if it does not exist.
*/
async function getAccount(userId, walletTypeId, accountKind = 'main') {
const rows = await (0, connection_1.query)(`SELECT id, user_id, wallet_type_id, available_balance::text, locked_balance::text, updated_at
FROM ledger_accounts WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3`, [userId, walletTypeId, accountKind]);
return rows[0] || null;
}
/**
* Adds funds to an account's available balance and records a ledger entry.
* Runs inside a database transaction with row-level locking.
* @param accountId - ID of the ledger account to credit.
* @param amount - Amount to add in the smallest currency unit.
* @param type - Ledger entry type identifier.
* @param referenceType - Optional reference entity type (e.g. transaction).
* @param referenceId - Optional reference entity ID.
* @returns Resolves when the balance and entry have been committed.
* @throws Error if the account is not found.
*/
async function credit(accountId, amount, type, referenceType, referenceId) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT available_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const newBalance = BigInt(acc.rows[0].available_balance) + amount;
await client.query('UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2', [newBalance.toString(), accountId]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, $2, $3, $4, $5, $6)`, [accountId, type, amount.toString(), newBalance.toString(), referenceType, referenceId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Removes funds from an account's available balance and records a ledger entry.
* Runs inside a database transaction with row-level locking.
* @param accountId - ID of the ledger account to debit.
* @param amount - Amount to subtract in the smallest currency unit.
* @param type - Ledger entry type identifier.
* @param referenceType - Optional reference entity type (e.g. transaction).
* @param referenceId - Optional reference entity ID.
* @returns Resolves when the balance and entry have been committed.
* @throws Error if the account is not found or available balance is insufficient.
*/
async function debit(accountId, amount, type, referenceType, referenceId) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const available = BigInt(acc.rows[0].available_balance);
if (available < amount)
throw new Error('Insufficient balance');
const newBalance = available - amount;
await client.query('UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2', [newBalance.toString(), accountId]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, $2, $3, $4, $5, $6)`, [accountId, type, (-amount).toString(), newBalance.toString(), referenceType, referenceId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Moves funds from available balance to locked balance (e.g. pending withdrawal).
* @param accountId - ID of the ledger account.
* @param amount - Amount to lock in the smallest currency unit.
* @returns Resolves when the balance transfer has been committed.
* @throws Error if the account is not found or available balance is insufficient.
*/
async function lockBalance(accountId, amount) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const available = BigInt(acc.rows[0].available_balance);
const locked = BigInt(acc.rows[0].locked_balance);
if (available < amount)
throw new Error('Insufficient balance');
await client.query('UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW() WHERE id = $3', [(available - amount).toString(), (locked + amount).toString(), accountId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Moves funds from locked balance back to available balance (e.g. cancelled withdrawal).
* @param accountId - ID of the ledger account.
* @param amount - Amount to unlock in the smallest currency unit.
* @returns Resolves when the balance transfer has been committed.
* @throws Error if the account is not found.
*/
async function unlockBalance(accountId, amount) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const locked = BigInt(acc.rows[0].locked_balance);
const newLocked = locked - amount;
const avail = await client.query('SELECT available_balance FROM ledger_accounts WHERE id = $1', [accountId]);
const newAvail = BigInt(avail.rows[0].available_balance) + amount;
await client.query('UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW() WHERE id = $3', [newAvail.toString(), newLocked.toString(), accountId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Permanently removes funds from locked balance (e.g. completed withdrawal).
* @param accountId - ID of the ledger account.
* @param amount - Amount to deduct from locked balance in the smallest currency unit.
* @returns Resolves when the deduction has been committed.
* @throws Error if the account is not found or locked balance is insufficient.
*/
async function deductLocked(accountId, amount) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const locked = BigInt(acc.rows[0].locked_balance);
if (locked < amount)
throw new Error('Locked balance too low');
await client.query('UPDATE ledger_accounts SET locked_balance = $1, updated_at = NOW() WHERE id = $2', [(locked - amount).toString(), accountId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Debits the sender and credits the receiver in a single atomic transaction.
* Used for internal transfers between ledger accounts.
* @param senderAccountId - ID of the account to debit.
* @param receiverAccountId - ID of the account to credit.
* @param amount - Transfer amount in the smallest currency unit.
* @param referenceType - Reference entity type shared by both ledger entries.
* @param referenceId - Reference entity ID shared by both ledger entries.
* @returns Resolves when both balance updates and entries have been committed.
* @throws Error if either account is not found or the sender has insufficient balance.
*/
async function transferBetweenAccounts(senderAccountId, receiverAccountId, amount, referenceType, referenceId) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const sender = await client.query('SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [senderAccountId]);
if (!sender.rows[0])
throw new Error('Sender account not found');
const available = BigInt(sender.rows[0].available_balance);
if (available < amount)
throw new Error('Insufficient balance');
const senderNew = available - amount;
await client.query('UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2', [senderNew.toString(), senderAccountId]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, $2, $3, $4, $5, $6)`, [senderAccountId, referenceType, (-amount).toString(), senderNew.toString(), referenceType, referenceId]);
const receiver = await client.query('SELECT available_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [receiverAccountId]);
if (!receiver.rows[0])
throw new Error('Recipient account not found');
const receiverNew = BigInt(receiver.rows[0].available_balance) + amount;
await client.query('UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2', [receiverNew.toString(), receiverAccountId]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, $2, $3, $4, $5, $6)`, [receiverAccountId, referenceType, amount.toString(), receiverNew.toString(), referenceType, referenceId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
/**
* Finalizes a withdrawal after on-chain broadcast: removes locked funds and records ledger entry.
* Does not debit available again (funds were moved to locked during initiation).
*/
async function finalizeWithdrawalFromLocked(accountId, amount, transactionId) {
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const acc = await client.query('SELECT available_balance, locked_balance FROM ledger_accounts WHERE id = $1 FOR UPDATE', [accountId]);
if (!acc.rows[0])
throw new Error('Account not found');
const locked = BigInt(acc.rows[0].locked_balance);
const available = BigInt(acc.rows[0].available_balance);
if (locked < amount)
throw new Error('Locked balance too low');
const newLocked = locked - amount;
await client.query('UPDATE ledger_accounts SET locked_balance = $1, updated_at = NOW() WHERE id = $2', [newLocked.toString(), accountId]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, 'withdrawal', $2, $3, 'transaction', $4)`, [accountId, (-amount).toString(), available.toString(), transactionId]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
async function listAllAccountsForIntegrity() {
return (0, connection_1.query)(`SELECT la.id, la.user_id, la.wallet_type_id,
la.available_balance::text, la.locked_balance::text,
COALESCE(SUM(le.amount), 0)::text AS entries_sum
FROM ledger_accounts la
LEFT JOIN ledger_entries le ON le.account_id = la.id
GROUP BY la.id`);
}
async function listUnauthorizedEntryTypes(accountId, allowedTypes) {
const rows = await (0, connection_1.query)(`SELECT DISTINCT type FROM ledger_entries
WHERE account_id = $1 AND NOT (type = ANY($2::text[]))`, [accountId, allowedTypes]);
return rows.map((r) => r.type);
}
//# sourceMappingURL=ledgerRepository.js.map