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

263 lines
8.7 KiB
TypeScript

/**
* Test wallet: play-money credits for platform discovery without real funds.
*/
import { getClient, beginAuthorizedTransaction } from '../db/connection';
import * as testWalletRepository from '../repositories/testWalletRepository';
import * as ledgerRepository from '../repositories/ledgerRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { decrypt } from '../utils/crypto';
export class TestWalletError extends Error {
constructor(message: string) {
super(message);
this.name = 'TestWalletError';
}
}
async function resolveWalletType(walletTypeId: number) {
const types = await walletRepository.getWalletTypes();
return types.find((t) => t.id === walletTypeId) ?? null;
}
export 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,
};
}
export async function updateSettings(input: {
enabled?: boolean;
creditAmountRaw?: string;
maxRequestsPerUser?: number;
cooldownHours?: number;
walletTypeId?: number;
}) {
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: string) {
const settings = await testWalletRepository.getSettings();
if (!settings.enabled) {
return {
settings,
canRequest: false,
reason: 'Test wallet requests are currently disabled.',
requestsUsed: 0,
cooldownEndsAt: null as string | 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,
};
}
export async function getUserTestWalletStatus(userId: string) {
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,
};
}
export async function requestTestCredits(userId: string): Promise<{
message: string;
amountRaw: string;
balanceRaw: string;
}> {
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 getClient();
try {
await beginAuthorizedTransaction(client);
const countRes = await client.query<{ count: string }>(
'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<{ created_at: Date }>(
`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<{ id: string; available_balance: string }>(
`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<{ id: string }>(
`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();
}
}
export async function listCreditHistory(options: {
userId?: string;
limit: number;
offset: number;
}) {
const result = await testWalletRepository.listCredits(options);
return {
items: result.items.map((row) => ({
id: row.id,
userId: row.user_id,
userEmail: row.user_email ? 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,
};
}