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

205 lines
7.9 KiB
JavaScript

"use strict";
/**
* Approved manual ledger credits (bonus / admin adjustment).
* Sole authorized path for crediting user balances outside deposits, games, and transfers.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminCreditError = void 0;
exports.grantLedgerCredit = grantLedgerCredit;
exports.listLedgerCredits = listLedgerCredits;
const connection_1 = require("../db/connection");
const ledgerAdjustmentRepository = __importStar(require("../repositories/ledgerAdjustmentRepository"));
const userRepository = __importStar(require("../repositories/userRepository"));
const walletRepository = __importStar(require("../repositories/walletRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const securityService_1 = require("./securityService");
const userAdminStatsService_1 = require("./userAdminStatsService");
const crypto_1 = require("../utils/crypto");
class AdminCreditError extends Error {
constructor(message) {
super(message);
this.name = 'AdminCreditError';
}
}
exports.AdminCreditError = AdminCreditError;
async function grantLedgerCredit(input) {
if (!securityService_1.AUTHORIZED_LEDGER_TYPES.has(input.adjustmentType)) {
throw new AdminCreditError(`Invalid adjustment type: ${input.adjustmentType}`);
}
const reason = input.reason?.trim();
if (!reason || reason.length < 3) {
throw new AdminCreditError('A reason of at least 3 characters is required');
}
let amount;
try {
amount = BigInt(input.amountRaw);
}
catch {
throw new AdminCreditError('Invalid amount');
}
if (amount <= 0n) {
throw new AdminCreditError('Amount must be positive');
}
const user = await userRepository.findById(input.userId);
if (!user)
throw new AdminCreditError('User not found');
const walletTypes = await walletRepository.getWalletTypes();
const walletType = walletTypes.find((w) => w.id === input.walletTypeId);
if (!walletType)
throw new AdminCreditError('Wallet type not found');
const accountKind = input.adjustmentType === 'bonus' ? 'bonus' : 'main';
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
await client.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`, [input.userId, input.walletTypeId, accountKind]);
const accountResult = await client.query(`SELECT id, available_balance::text
FROM ledger_accounts
WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3
FOR UPDATE`, [input.userId, input.walletTypeId, accountKind]);
const account = accountResult.rows[0];
if (!account) {
throw new AdminCreditError('Ledger account not found');
}
const adjustmentResult = await client.query(`INSERT INTO ledger_adjustments (user_id, wallet_type_id, adjustment_type, amount, reason_encrypted, approved_by)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id`, [
input.userId,
input.walletTypeId,
input.adjustmentType,
amount.toString(),
(0, crypto_1.encryptSensitive)(reason),
input.approvedBy,
]);
const adjustmentId = adjustmentResult.rows[0]?.id;
if (!adjustmentId)
throw new AdminCreditError('Failed to record adjustment');
const txResult = await client.query(`INSERT INTO transactions (user_id, wallet_type_id, type, amount, status, metadata)
VALUES ($1, $2, $3, $4, 'completed', $5)
RETURNING id`, [
input.userId,
input.walletTypeId,
input.adjustmentType,
amount.toString(),
JSON.stringify({
adjustment_id: adjustmentId,
approved_by: input.approvedBy,
reason_summary: reason.slice(0, 120),
}),
]);
const transactionId = txResult.rows[0]?.id;
if (!transactionId)
throw new AdminCreditError('Failed to record transaction');
await client.query('UPDATE ledger_adjustments SET transaction_id = $1 WHERE id = $2', [
transactionId,
adjustmentId,
]);
const newBalance = BigInt(account.available_balance) + amount;
await client.query(`UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2`, [newBalance.toString(), account.id]);
await client.query(`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
VALUES ($1, $2, $3, $4, 'ledger_adjustment', $5)`, [
account.id,
input.adjustmentType,
amount.toString(),
newBalance.toString(),
adjustmentId,
]);
await client.query('COMMIT');
await auditLogRepository.create({
userId: input.approvedBy,
action: 'admin_ledger_credit',
resourceType: 'ledger_adjustment',
resourceId: adjustmentId,
metadata: {
target_user_id: input.userId,
wallet_type_id: input.walletTypeId,
account_kind: accountKind,
adjustment_type: input.adjustmentType,
amount_raw: amount.toString(),
transaction_id: transactionId,
available_balance_raw: newBalance.toString(),
},
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(input.userId);
return {
adjustmentId,
transactionId,
accountKind,
availableBalanceRaw: newBalance.toString(),
};
}
catch (e) {
await client.query('ROLLBACK');
if (e instanceof AdminCreditError)
throw e;
const msg = e instanceof Error ? e.message : 'Credit failed';
throw new AdminCreditError(msg);
}
finally {
client.release();
}
}
async function listLedgerCredits(opts) {
const result = await ledgerAdjustmentRepository.listAdjustments(opts);
return {
items: result.items.map((a) => ({
id: a.id,
userId: a.user_id,
walletTypeId: a.wallet_type_id,
adjustmentType: a.adjustment_type,
amount: a.amount,
approvedBy: a.approved_by,
transactionId: a.transaction_id,
createdAt: a.created_at,
})),
total: result.total,
};
}
//# sourceMappingURL=adminCreditService.js.map