376 lines
13 KiB
TypeScript
376 lines
13 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 {
|
|
readonly code?: string;
|
|
readonly waitLabel?: string;
|
|
|
|
constructor(message: string, opts?: { code?: string; waitLabel?: string }) {
|
|
super(message);
|
|
this.name = 'TestWalletError';
|
|
this.code = opts?.code;
|
|
this.waitLabel = opts?.waitLabel;
|
|
}
|
|
}
|
|
|
|
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,
|
|
predictionLimitEnabled: settings.prediction_limit_enabled,
|
|
maxTestPredictionsPerWindow: settings.max_test_predictions_per_window,
|
|
testPredictionWindowHours: settings.test_prediction_window_hours,
|
|
updatedAt: settings.updated_at,
|
|
};
|
|
}
|
|
|
|
export async function updateSettings(input: {
|
|
enabled?: boolean;
|
|
creditAmountRaw?: string;
|
|
maxRequestsPerUser?: number;
|
|
cooldownHours?: number;
|
|
walletTypeId?: number;
|
|
predictionLimitEnabled?: boolean;
|
|
maxTestPredictionsPerWindow?: number;
|
|
testPredictionWindowHours?: 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.maxTestPredictionsPerWindow !== undefined && input.maxTestPredictionsPerWindow < 0) {
|
|
throw new TestWalletError('maxTestPredictionsPerWindow cannot be negative');
|
|
}
|
|
if (input.testPredictionWindowHours !== undefined && input.testPredictionWindowHours < 1) {
|
|
throw new TestWalletError('testPredictionWindowHours must be at least 1');
|
|
}
|
|
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,
|
|
predictionLimitEnabled: input.predictionLimitEnabled,
|
|
maxTestPredictionsPerWindow: input.maxTestPredictionsPerWindow,
|
|
testPredictionWindowHours: input.testPredictionWindowHours,
|
|
});
|
|
return getSettingsForAdmin();
|
|
}
|
|
|
|
function formatRemainingDuration(ms: number): string {
|
|
const totalMinutes = Math.max(1, Math.ceil(ms / 60_000));
|
|
const days = Math.floor(totalMinutes / (60 * 24));
|
|
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
|
const minutes = totalMinutes % 60;
|
|
const parts: string[] = [];
|
|
if (days > 0) parts.push(`${days}d`);
|
|
if (hours > 0) parts.push(`${hours}h`);
|
|
if (minutes > 0 && days === 0) parts.push(`${minutes}m`);
|
|
if (parts.length === 0) parts.push('1m');
|
|
return parts.join(' ');
|
|
}
|
|
|
|
export type TestPredictionLimitStatus = {
|
|
enabled: boolean;
|
|
maxPerWindow: number;
|
|
windowHours: number;
|
|
usedInWindow: number;
|
|
remaining: number;
|
|
resetsAt: string | null;
|
|
canPredict: boolean;
|
|
reason: string | null;
|
|
};
|
|
|
|
export async function getTestPredictionLimitStatus(
|
|
userId: string
|
|
): Promise<TestPredictionLimitStatus> {
|
|
const settings = await testWalletRepository.getSettings();
|
|
const max = settings.max_test_predictions_per_window;
|
|
const windowHours = settings.test_prediction_window_hours;
|
|
if (!settings.prediction_limit_enabled || max <= 0) {
|
|
return {
|
|
enabled: false,
|
|
maxPerWindow: max,
|
|
windowHours,
|
|
usedInWindow: 0,
|
|
remaining: max > 0 ? max : Number.MAX_SAFE_INTEGER,
|
|
resetsAt: null,
|
|
canPredict: true,
|
|
reason: null,
|
|
};
|
|
}
|
|
|
|
const { count, oldestInWindowAt } = await testWalletRepository.countTestPredictionsInWindow(
|
|
userId,
|
|
windowHours
|
|
);
|
|
const remaining = Math.max(0, max - count);
|
|
if (count < max) {
|
|
return {
|
|
enabled: true,
|
|
maxPerWindow: max,
|
|
windowHours,
|
|
usedInWindow: count,
|
|
remaining,
|
|
resetsAt: null,
|
|
canPredict: true,
|
|
reason: null,
|
|
};
|
|
}
|
|
|
|
const resetsAt = oldestInWindowAt
|
|
? new Date(oldestInWindowAt.getTime() + windowHours * 60 * 60 * 1000)
|
|
: new Date(Date.now() + windowHours * 60 * 60 * 1000);
|
|
const remainingMs = Math.max(0, resetsAt.getTime() - Date.now());
|
|
const wait = formatRemainingDuration(remainingMs);
|
|
return {
|
|
enabled: true,
|
|
maxPerWindow: max,
|
|
windowHours,
|
|
usedInWindow: count,
|
|
remaining: 0,
|
|
resetsAt: resetsAt.toISOString(),
|
|
canPredict: false,
|
|
reason: `You have reached the maximum number of Test Wallet uses allowed (${max} per ${windowHours}h). Please try again in ${wait}.`,
|
|
};
|
|
}
|
|
|
|
/** Throws when the user may not place another Test Wallet prediction. */
|
|
export async function assertTestPredictionAllowed(userId: string): Promise<void> {
|
|
const status = await getTestPredictionLimitStatus(userId);
|
|
if (!status.canPredict) {
|
|
throw new TestWalletError(status.reason ?? 'Test Wallet prediction limit reached.', {
|
|
code: 'TEST_PREDICTION_LIMIT',
|
|
waitLabel: status.resetsAt
|
|
? formatRemainingDuration(Math.max(0, new Date(status.resetsAt).getTime() - Date.now()))
|
|
: `${status.windowHours}h`,
|
|
});
|
|
}
|
|
}
|
|
|
|
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');
|
|
const predictionLimit = await getTestPredictionLimitStatus(userId);
|
|
|
|
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,
|
|
predictionLimit,
|
|
};
|
|
}
|
|
|
|
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,
|
|
};
|
|
}
|