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

252 lines
11 KiB
JavaScript

"use strict";
/**
* Test wallet: play-money credits for platform discovery without real funds.
*/
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.TestWalletError = void 0;
exports.getSettingsForAdmin = getSettingsForAdmin;
exports.updateSettings = updateSettings;
exports.getUserTestWalletStatus = getUserTestWalletStatus;
exports.requestTestCredits = requestTestCredits;
exports.listCreditHistory = listCreditHistory;
const connection_1 = require("../db/connection");
const testWalletRepository = __importStar(require("../repositories/testWalletRepository"));
const ledgerRepository = __importStar(require("../repositories/ledgerRepository"));
const walletRepository = __importStar(require("../repositories/walletRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const crypto_1 = require("../utils/crypto");
class TestWalletError extends Error {
constructor(message) {
super(message);
this.name = 'TestWalletError';
}
}
exports.TestWalletError = TestWalletError;
async function resolveWalletType(walletTypeId) {
const types = await walletRepository.getWalletTypes();
return types.find((t) => t.id === walletTypeId) ?? null;
}
async function getSettingsForAdmin() {
const settings = await testWalletRepository.getSettings();
const walletType = await resolveWalletType(settings.wallet_type_id);
return {
enabled: settings.enabled,
creditAmountRaw: settings.credit_amount_raw,
maxRequestsPerUser: settings.max_requests_per_user,
cooldownHours: settings.cooldown_hours,
walletTypeId: settings.wallet_type_id,
walletCode: walletType?.code ?? null,
updatedAt: settings.updated_at,
};
}
async function updateSettings(input) {
if (input.creditAmountRaw !== undefined) {
const amount = BigInt(input.creditAmountRaw);
if (amount <= 0n)
throw new TestWalletError('creditAmountRaw must be positive');
}
if (input.maxRequestsPerUser !== undefined && input.maxRequestsPerUser < 0) {
throw new TestWalletError('maxRequestsPerUser cannot be negative');
}
if (input.cooldownHours !== undefined && input.cooldownHours < 0) {
throw new TestWalletError('cooldownHours cannot be negative');
}
if (input.walletTypeId !== undefined) {
const wt = await resolveWalletType(input.walletTypeId);
if (!wt)
throw new TestWalletError('Wallet type not found');
}
await testWalletRepository.updateSettings({
enabled: input.enabled,
creditAmountRaw: input.creditAmountRaw,
maxRequestsPerUser: input.maxRequestsPerUser,
cooldownHours: input.cooldownHours,
walletTypeId: input.walletTypeId,
});
return getSettingsForAdmin();
}
async function evaluateEligibility(userId) {
const settings = await testWalletRepository.getSettings();
if (!settings.enabled) {
return {
settings,
canRequest: false,
reason: 'Test wallet requests are currently disabled.',
requestsUsed: 0,
cooldownEndsAt: null,
};
}
const requestsUsed = await testWalletRepository.countUserCredits(userId);
if (settings.max_requests_per_user > 0 && requestsUsed >= settings.max_requests_per_user) {
return {
settings,
canRequest: false,
reason: 'You have reached the maximum number of test credit requests.',
requestsUsed,
cooldownEndsAt: null,
};
}
const lastAt = await testWalletRepository.getLastCreditAt(userId);
if (lastAt && settings.cooldown_hours > 0) {
const cooldownEnds = new Date(lastAt.getTime() + settings.cooldown_hours * 60 * 60 * 1000);
if (cooldownEnds > new Date()) {
return {
settings,
canRequest: false,
reason: 'Please wait before requesting test credits again.',
requestsUsed,
cooldownEndsAt: cooldownEnds.toISOString(),
};
}
}
return {
settings,
canRequest: true,
reason: null,
requestsUsed,
cooldownEndsAt: null,
};
}
async function getUserTestWalletStatus(userId) {
const eligibility = await evaluateEligibility(userId);
const { settings } = eligibility;
const walletType = await resolveWalletType(settings.wallet_type_id);
const testAccount = await ledgerRepository.getAccount(userId, settings.wallet_type_id, 'test');
return {
enabled: settings.enabled,
balanceRaw: testAccount?.available_balance ?? '0',
walletTypeId: settings.wallet_type_id,
walletCode: walletType?.code ?? null,
decimals: walletType?.decimals ?? 6,
creditAmountRaw: settings.credit_amount_raw,
maxRequests: settings.max_requests_per_user,
requestsUsed: eligibility.requestsUsed,
canRequest: eligibility.canRequest,
reason: eligibility.reason,
cooldownEndsAt: eligibility.cooldownEndsAt,
};
}
async function requestTestCredits(userId) {
const eligibility = await evaluateEligibility(userId);
if (!eligibility.canRequest) {
throw new TestWalletError(eligibility.reason ?? 'Test credit request not allowed');
}
const { settings } = eligibility;
const amount = BigInt(settings.credit_amount_raw);
if (amount <= 0n) {
throw new TestWalletError('Test credit amount is not configured');
}
const client = await (0, connection_1.getClient)();
try {
await (0, connection_1.beginAuthorizedTransaction)(client);
const countRes = await client.query('SELECT COUNT(*)::text AS count FROM test_wallet_credits WHERE user_id = $1', [userId]);
const requestsUsed = parseInt(countRes.rows[0]?.count ?? '0', 10) || 0;
if (settings.max_requests_per_user > 0 && requestsUsed >= settings.max_requests_per_user) {
throw new TestWalletError('You have reached the maximum number of test credit requests.');
}
if (settings.cooldown_hours > 0) {
const lastRes = await client.query(`SELECT created_at FROM test_wallet_credits
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT 1`, [userId]);
const lastAt = lastRes.rows[0]?.created_at;
if (lastAt) {
const cooldownEnds = new Date(lastAt.getTime() + settings.cooldown_hours * 60 * 60 * 1000);
if (cooldownEnds > new Date()) {
throw new TestWalletError('Please wait before requesting test credits again.');
}
}
}
await client.query(`INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind)
VALUES ($1, $2, 'test')
ON CONFLICT (user_id, wallet_type_id, account_kind) DO NOTHING`, [userId, settings.wallet_type_id]);
const accRes = await client.query(`SELECT id, available_balance::text AS available_balance
FROM ledger_accounts
WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = 'test'
FOR UPDATE`, [userId, settings.wallet_type_id]);
if (!accRes.rows[0])
throw new TestWalletError('Failed to open test wallet account');
const accountId = accRes.rows[0].id;
const creditRes = await client.query(`INSERT INTO test_wallet_credits (user_id, wallet_type_id, amount_raw)
VALUES ($1, $2, $3)
RETURNING id`, [userId, settings.wallet_type_id, amount.toString()]);
const creditId = creditRes.rows[0]?.id;
if (!creditId)
throw new TestWalletError('Failed to record test credit');
const newBalance = BigInt(accRes.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, 'test_credit', $2, $3, 'test_wallet_credit', $4)`, [accountId, amount.toString(), newBalance.toString(), creditId]);
await client.query('COMMIT');
await auditLogRepository.create({
userId,
action: 'test_wallet_credit_requested',
resourceType: 'test_wallet_credit',
resourceId: creditId ?? userId,
metadata: { amountRaw: amount.toString() },
});
return {
message: 'Test credits added to your test wallet.',
amountRaw: amount.toString(),
balanceRaw: newBalance.toString(),
};
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
}
async function listCreditHistory(options) {
const result = await testWalletRepository.listCredits(options);
return {
items: result.items.map((row) => ({
id: row.id,
userId: row.user_id,
userEmail: row.user_email ? (0, crypto_1.decrypt)(row.user_email) : null,
walletTypeId: row.wallet_type_id,
walletCode: row.wallet_code,
amountRaw: row.amount_raw,
createdAt: row.created_at,
})),
total: result.total,
limit: options.limit,
offset: options.offset,
};
}
//# sourceMappingURL=testWalletService.js.map