games_app/backend/src/controllers/candlePredictController.ts

578 lines
11 KiB
TypeScript

import { Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as candlePredictService from '../services/candlePredictService';
import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation';
import { readIdempotencyKey, sendPlaceBetResult } from '../utils/placeBetResponse';
function parseIntervalMinutes(value: unknown): number | undefined {
if (value == null || value === '') return undefined;
const n = Number(value);
return Number.isFinite(n) ? n : undefined;
}
export async function getState(req: AuthRequest, res: Response): Promise<void> {
try {
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
const includeInternal = req.user?.role === 'admin';
const state = await candlePredictService.getGameState(req.user?.userId, intervalMinutes, {
includeInternal,
});
res.json(state);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load game state';
res.status(500).json({ error: msg });
}
}
export async function getCandles(req: AuthRequest, res: Response): Promise<void> {
try {
const limit = parseInt((req.query.limit as string) || '0', 10);
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
const beforeRaw = req.query.beforeOpenMs as string | undefined;
const beforeOpenMs =
beforeRaw != null && beforeRaw !== '' && Number.isFinite(Number(beforeRaw))
? Number(beforeRaw)
: undefined;
const page = await candlePredictService.getCandlesPage({
limit: limit > 0 ? limit : undefined,
intervalMinutes,
beforeOpenMs,
includeInternal: req.user?.role === 'admin',
});
res.json(page);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load candles';
res.status(500).json({ error: msg });
}
}
export async function placeBet(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const { direction, stakeAmount, intervalMinutes, stakeAccountKind } = req.body as {
direction?: string;
stakeAmount?: unknown;
intervalMinutes?: number;
stakeAccountKind?: 'main' | 'bonus' | 'test';
};
if (stakeAmount === undefined || stakeAmount === null) {
res.status(400).json({ error: 'stakeAmount is required' });
return;
}
const parsedStake = parseStakeAmountFromBody(stakeAmount);
const result = await candlePredictService.placeBet(
req.user.userId,
direction ?? '',
parsedStake,
intervalMinutes,
stakeAccountKind,
{
idempotencyKey: readIdempotencyKey(req, req.body as Record<string, unknown>),
source: 'http',
}
);
sendPlaceBetResult(res, result);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to place prediction';
res.status(400).json({ error: msg });
}
}
export async function getBetOutcome(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const idempotencyKey = String(req.params.idempotencyKey ?? '').trim();
if (!idempotencyKey) {
res.status(400).json({ error: 'idempotencyKey is required' });
return;
}
const record = await candlePredictService.getBetIdempotency(idempotencyKey);
if (!record) {
res.status(404).json({ error: 'Bet outcome not found' });
return;
}
if (record.status === 'accepted') {
const betUserId = String(record.bet.user_id ?? record.bet.userId ?? '').trim();
if (betUserId && betUserId !== req.user.userId) {
res.status(403).json({ error: 'Forbidden' });
return;
}
res.json({ status: 'accepted', bet: record.bet });
return;
}
if (record.status === 'rejected') {
res.json({ status: 'rejected', error: record.error });
return;
}
res.json({ status: 'processing' });
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load bet outcome';
res.status(500).json({ error: msg });
}
}
export async function getMyBets(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const page = Math.max(1, parseInt((req.query.page as string) || '1', 10));
const pageSize = Math.min(50, Math.max(1, parseInt((req.query.pageSize as string) || '10', 10)));
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
const predictions = await candlePredictService.getRecentPredictions(
req.user.userId,
page,
pageSize,
intervalMinutes
);
res.json(predictions);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load predictions';
res.status(500).json({ error: msg });
}
}
export async function getAutoSettings(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const settings = await candlePredictService.getAutoSettings(req.user.userId);
res.json(settings);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load auto settings';
res.status(500).json({ error: msg });
}
}
export async function updateAutoSettings(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const settings = await candlePredictService.saveAutoSettings(
req.user.userId,
req.body as Record<string, unknown>
);
res.json(settings);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to update auto settings';
res.status(400).json({ error: msg });
}
}
export async function getAdminConfig(req: AuthRequest, res: Response): Promise<void> {
try {
const config = await candlePredictService.getPublicConfig();
res.json(config);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load config';
res.status(500).json({ error: msg });
}
}
export async function updateAdminConfig(req: AuthRequest, res: Response): Promise<void> {
try {
const config = await candlePredictService.updateAdminConfig(req.body as Record<string, unknown>);
res.json(config);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to update config';
res.status(400).json({ error: msg });
}
}
export async function listAdminIntervals(req: AuthRequest, res: Response): Promise<void> {
try {
const intervals = await candlePredictService.listAdminIntervals();
res.json(intervals);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load intervals';
res.status(500).json({ error: msg });
}
}
export async function createAdminInterval(req: AuthRequest, res: Response): Promise<void> {
try {
const interval = await candlePredictService.createAdminInterval(
req.body as Record<string, unknown>
);
res.status(201).json(interval);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to create interval';
res.status(400).json({ error: msg });
}
}
export async function updateAdminInterval(req: AuthRequest, res: Response): Promise<void> {
try {
const id = Number(req.params.id);
if (!Number.isFinite(id)) {
res.status(400).json({ error: 'Invalid interval id' });
return;
}
const interval = await candlePredictService.updateAdminInterval(
id,
req.body as Record<string, unknown>
);
res.json(interval);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to update interval';
res.status(400).json({ error: msg });
}
}
export async function deleteAdminInterval(req: AuthRequest, res: Response): Promise<void> {
try {
const id = Number(req.params.id);
if (!Number.isFinite(id)) {
res.status(400).json({ error: 'Invalid interval id' });
return;
}
const result = await candlePredictService.deleteAdminInterval(id);
res.json(result);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to delete interval';
res.status(400).json({ error: msg });
}
}
export async function placeMultiBet(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.user?.userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const { level, sequence, stakeAmount, intervalMinutes, stakeAccountKind } = req.body as {
level?: number;
sequence?: string[];
stakeAmount?: unknown;
intervalMinutes?: number;
stakeAccountKind?: 'main' | 'bonus' | 'test';
};
if (stakeAmount === undefined || stakeAmount === null) {
res.status(400).json({ error: 'stakeAmount is required' });
return;
}
if (level == null || !Number.isFinite(Number(level))) {
res.status(400).json({ error: 'level is required' });
return;
}
if (!Array.isArray(sequence) || sequence.length === 0) {
res.status(400).json({ error: 'sequence is required' });
return;
}
const parsedStake = parseStakeAmountFromBody(stakeAmount);
const directions = sequence.filter(
(d): d is 'short' | 'long' => d === 'short' || d === 'long'
);
const bet = await candlePredictService.placeMultiCandleBet(req.user.userId, {
level: Number(level),
sequence: directions,
stakeDisplay: parsedStake,
intervalMinutes,
stakeAccountKind,
});
res.status(201).json(bet);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to place multi-candle prediction';
res.status(400).json({ error: msg });
}
}
export async function listAdminMultiLevels(req: AuthRequest, res: Response): Promise<void> {
try {
const levels = await candlePredictService.listAdminMultiLevels();
res.json(levels);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to load multi levels';
res.status(500).json({ error: msg });
}
}
export async function updateAdminMultiLevels(req: AuthRequest, res: Response): Promise<void> {
try {
const levels = await candlePredictService.updateAdminMultiLevels(
req.body as Record<string, unknown>
);
res.json(levels);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to update multi levels';
res.status(400).json({ error: msg });
}
}