472 lines
14 KiB
TypeScript
472 lines
14 KiB
TypeScript
/**
|
|
* Admin user management service.
|
|
* Orchestrates user repository access, email decryption, and wallet balances for admin APIs.
|
|
*/
|
|
|
|
import * as userRepository from '../repositories/userRepository';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import * as walletService from './walletService';
|
|
import * as adminCreditService from './adminCreditService';
|
|
import { decrypt } from '../utils/crypto';
|
|
import { RoleName } from '../models';
|
|
import type { AdminSortBy, UserActivityFilter } from '../repositories/userRepository';
|
|
|
|
/** Query options for the admin user list. */
|
|
export type AdminListUsersOptions = {
|
|
search?: string;
|
|
roleName?: RoleName;
|
|
emailVerified?: boolean;
|
|
country?: string;
|
|
inactiveSinceDays?: number;
|
|
activityFilter?: UserActivityFilter;
|
|
activityPeriodFrom?: string;
|
|
activityPeriodTo?: string;
|
|
minMainBalance?: string;
|
|
maxMainBalance?: string;
|
|
minBonusReceived?: string;
|
|
maxBonusReceived?: string;
|
|
accountStatus?: 'active' | 'disabled' | 'suspended';
|
|
hasReceivedBonus?: boolean;
|
|
createdFrom?: string;
|
|
createdTo?: string;
|
|
minAge?: number;
|
|
maxAge?: number;
|
|
totpEnabled?: boolean;
|
|
underSurveillance?: boolean;
|
|
sortBy?: AdminSortBy;
|
|
sortDir?: 'asc' | 'desc';
|
|
limit: number;
|
|
offset?: number;
|
|
cursor?: string;
|
|
includeTotal?: boolean;
|
|
userIds?: string[];
|
|
};
|
|
|
|
/** API-facing user row with decrypted email (admin list). */
|
|
export type AdminUserListItem = {
|
|
id: string;
|
|
email: string | null;
|
|
first_name: string | null;
|
|
middle_name: string | null;
|
|
last_name: string | null;
|
|
date_of_birth: string | null;
|
|
role_id: number;
|
|
role_name: string;
|
|
email_verified: boolean;
|
|
totp_enabled: boolean;
|
|
is_enabled: boolean;
|
|
is_account_non_expired: boolean;
|
|
is_account_non_locked: boolean;
|
|
is_credentials_non_expired: boolean;
|
|
country_of_residence: string | null;
|
|
nationality: string | null;
|
|
referral_code: string | null;
|
|
first_deposit_at: Date | null;
|
|
first_deposit_transaction_id: string | null;
|
|
withdrawals_suspended: boolean;
|
|
under_surveillance: boolean;
|
|
security_suspended_at: Date | null;
|
|
created_at: Date;
|
|
updated_at: Date;
|
|
main_balance_raw: string;
|
|
bonus_balance_raw: string;
|
|
total_bonus_received_raw: string;
|
|
prediction_count: number;
|
|
total_stake_raw: string;
|
|
total_payout_raw: string;
|
|
net_pnl_raw: string;
|
|
last_login_at: Date | null;
|
|
last_activity_at: Date;
|
|
account_status: 'active' | 'disabled' | 'suspended';
|
|
};
|
|
|
|
/** Account flags accepted from the admin API (camelCase). */
|
|
export type AdminAccountFlagsInput = {
|
|
isEnabled?: boolean;
|
|
isAccountNonExpired?: boolean;
|
|
isAccountNonLocked?: boolean;
|
|
isCredentialsNonExpired?: boolean;
|
|
};
|
|
|
|
export type BatchOperationResult = {
|
|
succeeded: string[];
|
|
failed: Array<{ userId: string; error: string }>;
|
|
};
|
|
|
|
function parseOptionalBigInt(value?: string): bigint | undefined {
|
|
if (!value?.trim()) return undefined;
|
|
try {
|
|
return BigInt(value.trim());
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
function decryptEmail(encrypted: string | null): string | null {
|
|
if (!encrypted) return null;
|
|
try {
|
|
return decrypt(encrypted);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function deriveAccountStatus(row: {
|
|
is_enabled: boolean;
|
|
is_account_non_expired: boolean;
|
|
is_account_non_locked: boolean;
|
|
is_credentials_non_expired: boolean;
|
|
withdrawals_suspended: boolean;
|
|
under_surveillance: boolean;
|
|
}): 'active' | 'disabled' | 'suspended' {
|
|
if (!row.is_enabled) return 'disabled';
|
|
if (
|
|
!row.is_account_non_locked ||
|
|
!row.is_account_non_expired ||
|
|
!row.is_credentials_non_expired ||
|
|
row.withdrawals_suspended ||
|
|
row.under_surveillance
|
|
) {
|
|
return 'suspended';
|
|
}
|
|
return 'active';
|
|
}
|
|
|
|
/**
|
|
* Lists users for the admin panel with decrypted emails and aggregated stats.
|
|
*/
|
|
export async function listUsers(
|
|
options: AdminListUsersOptions
|
|
): Promise<{
|
|
users: AdminUserListItem[];
|
|
total: number | null;
|
|
totalIsExact: boolean;
|
|
nextCursor: string | null;
|
|
hasMore: boolean;
|
|
}> {
|
|
const result = await userRepository.listForAdmin({
|
|
search: options.search,
|
|
roleName: options.roleName,
|
|
emailVerified: options.emailVerified,
|
|
country: options.country,
|
|
inactiveSinceDays: options.inactiveSinceDays,
|
|
activityFilter: options.activityFilter,
|
|
activityPeriodFrom: options.activityPeriodFrom,
|
|
activityPeriodTo: options.activityPeriodTo,
|
|
minMainBalance: parseOptionalBigInt(options.minMainBalance),
|
|
maxMainBalance: parseOptionalBigInt(options.maxMainBalance),
|
|
minBonusReceived: parseOptionalBigInt(options.minBonusReceived),
|
|
maxBonusReceived: parseOptionalBigInt(options.maxBonusReceived),
|
|
accountStatus: options.accountStatus,
|
|
hasReceivedBonus: options.hasReceivedBonus,
|
|
createdFrom: options.createdFrom,
|
|
createdTo: options.createdTo,
|
|
minAge: options.minAge,
|
|
maxAge: options.maxAge,
|
|
totpEnabled: options.totpEnabled,
|
|
underSurveillance: options.underSurveillance,
|
|
userIds: options.userIds,
|
|
sortBy: options.sortBy,
|
|
sortDir: options.sortDir,
|
|
limit: options.limit,
|
|
offset: options.offset,
|
|
cursor: options.cursor,
|
|
includeTotal: options.includeTotal,
|
|
});
|
|
return {
|
|
total: result.total,
|
|
totalIsExact: result.totalIsExact,
|
|
nextCursor: result.nextCursor,
|
|
hasMore: result.hasMore,
|
|
users: result.users.map((u) => ({
|
|
id: u.id,
|
|
email: decryptEmail(u.email_encrypted),
|
|
first_name: u.first_name,
|
|
middle_name: u.middle_name,
|
|
last_name: u.last_name,
|
|
date_of_birth: u.date_of_birth,
|
|
role_id: u.role_id,
|
|
role_name: u.role_name,
|
|
email_verified: u.email_verified,
|
|
totp_enabled: u.totp_enabled,
|
|
is_enabled: u.is_enabled,
|
|
is_account_non_expired: u.is_account_non_expired,
|
|
is_account_non_locked: u.is_account_non_locked,
|
|
is_credentials_non_expired: u.is_credentials_non_expired,
|
|
country_of_residence: u.country_of_residence,
|
|
nationality: u.nationality,
|
|
referral_code: u.referral_code,
|
|
first_deposit_at: u.first_deposit_at,
|
|
first_deposit_transaction_id: u.first_deposit_transaction_id,
|
|
withdrawals_suspended: u.withdrawals_suspended,
|
|
under_surveillance: u.under_surveillance,
|
|
security_suspended_at: u.security_suspended_at,
|
|
created_at: u.created_at,
|
|
updated_at: u.updated_at,
|
|
main_balance_raw: u.main_balance_raw,
|
|
bonus_balance_raw: u.bonus_balance_raw,
|
|
total_bonus_received_raw: u.total_bonus_received_raw,
|
|
prediction_count: u.prediction_count,
|
|
total_stake_raw: u.total_stake_raw,
|
|
total_payout_raw: u.total_payout_raw,
|
|
net_pnl_raw: u.net_pnl_raw,
|
|
last_login_at: u.last_login_at,
|
|
last_activity_at: u.last_activity_at,
|
|
account_status: deriveAccountStatus(u),
|
|
})),
|
|
};
|
|
}
|
|
|
|
export async function updateUserAccountFlags(
|
|
userId: string,
|
|
flags: AdminAccountFlagsInput
|
|
): Promise<void> {
|
|
const repoFlags: Parameters<typeof userRepository.updateAccountFlags>[1] = {};
|
|
if (typeof flags.isEnabled === 'boolean') repoFlags.is_enabled = flags.isEnabled;
|
|
if (typeof flags.isAccountNonExpired === 'boolean') {
|
|
repoFlags.is_account_non_expired = flags.isAccountNonExpired;
|
|
}
|
|
if (typeof flags.isAccountNonLocked === 'boolean') {
|
|
repoFlags.is_account_non_locked = flags.isAccountNonLocked;
|
|
}
|
|
if (typeof flags.isCredentialsNonExpired === 'boolean') {
|
|
repoFlags.is_credentials_non_expired = flags.isCredentialsNonExpired;
|
|
}
|
|
if (Object.keys(repoFlags).length === 0) {
|
|
throw new Error('At least one flag required');
|
|
}
|
|
const existing = await userRepository.findById(userId);
|
|
if (!existing) {
|
|
throw new Error('User not found');
|
|
}
|
|
await userRepository.updateAccountFlags(userId, repoFlags);
|
|
}
|
|
|
|
export async function batchUpdateUserAccountFlags(
|
|
userIds: string[],
|
|
flags: AdminAccountFlagsInput
|
|
): Promise<BatchOperationResult> {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result: BatchOperationResult = { succeeded: [], failed: [] };
|
|
for (const userId of unique) {
|
|
try {
|
|
await updateUserAccountFlags(userId, flags);
|
|
result.succeeded.push(userId);
|
|
} catch (e) {
|
|
result.failed.push({
|
|
userId,
|
|
error: e instanceof Error ? e.message : 'Update failed',
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export async function batchUpdateUserSecurity(
|
|
userIds: string[],
|
|
body: {
|
|
withdrawalsSuspended?: boolean;
|
|
underSurveillance?: boolean;
|
|
reactivateWithdrawals?: boolean;
|
|
reason?: string;
|
|
}
|
|
): Promise<BatchOperationResult> {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result: BatchOperationResult = { succeeded: [], failed: [] };
|
|
|
|
for (const userId of unique) {
|
|
try {
|
|
if (body.reactivateWithdrawals) {
|
|
await userRepository.updateSecurityFlags(userId, {
|
|
withdrawals_suspended: false,
|
|
under_surveillance: false,
|
|
clear_security_reason: true,
|
|
});
|
|
} else {
|
|
const flags: Parameters<typeof userRepository.updateSecurityFlags>[1] = {};
|
|
if (typeof body.withdrawalsSuspended === 'boolean') {
|
|
flags.withdrawals_suspended = body.withdrawalsSuspended;
|
|
}
|
|
if (typeof body.underSurveillance === 'boolean') {
|
|
flags.under_surveillance = body.underSurveillance;
|
|
}
|
|
if (body.reason) flags.security_reason_encrypted = body.reason;
|
|
if (body.withdrawalsSuspended || body.underSurveillance) {
|
|
flags.set_suspended_at = true;
|
|
}
|
|
if (Object.keys(flags).length === 0) {
|
|
throw new Error('No security flags provided');
|
|
}
|
|
await userRepository.updateSecurityFlags(userId, flags);
|
|
}
|
|
result.succeeded.push(userId);
|
|
} catch (e) {
|
|
result.failed.push({
|
|
userId,
|
|
error: e instanceof Error ? e.message : 'Security update failed',
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export async function batchGrantLedgerCredit(
|
|
userIds: string[],
|
|
input: {
|
|
walletTypeId: number;
|
|
adjustmentType: 'bonus' | 'admin_adjustment';
|
|
amountRaw: string;
|
|
reason: string;
|
|
},
|
|
approvedBy: string
|
|
): Promise<BatchOperationResult> {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result: BatchOperationResult = { succeeded: [], failed: [] };
|
|
|
|
for (const userId of unique) {
|
|
try {
|
|
await adminCreditService.grantLedgerCredit({
|
|
userId,
|
|
walletTypeId: input.walletTypeId,
|
|
adjustmentType: input.adjustmentType,
|
|
amountRaw: input.amountRaw,
|
|
reason: input.reason,
|
|
approvedBy,
|
|
});
|
|
result.succeeded.push(userId);
|
|
} catch (e) {
|
|
result.failed.push({
|
|
userId,
|
|
error: e instanceof Error ? e.message : 'Credit failed',
|
|
});
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Marks a user's email as verified (admin support action).
|
|
*/
|
|
export async function markUserEmailVerified(
|
|
userId: string,
|
|
adminUserId: string
|
|
): Promise<{ message: string; emailVerified: boolean }> {
|
|
const user = await userRepository.findById(userId);
|
|
if (!user) {
|
|
throw new Error('User not found');
|
|
}
|
|
if (!user.email_verified) {
|
|
await userRepository.setEmailVerified(userId, true);
|
|
await auditLogRepository.create({
|
|
userId: adminUserId,
|
|
action: 'admin_email_verified',
|
|
resourceType: 'user',
|
|
resourceId: userId,
|
|
});
|
|
}
|
|
return { message: 'Email marked as verified', emailVerified: true };
|
|
}
|
|
|
|
/**
|
|
* Loads full admin user details including wallet balances.
|
|
*/
|
|
export async function getUserDetails(userId: string): Promise<{
|
|
user: {
|
|
id: string;
|
|
email: string | null;
|
|
role_id: number;
|
|
role_name: string;
|
|
email_verified: boolean;
|
|
totp_enabled: boolean;
|
|
is_enabled: boolean;
|
|
is_account_non_expired: boolean;
|
|
is_account_non_locked: boolean;
|
|
is_credentials_non_expired: boolean;
|
|
withdrawals_suspended: boolean;
|
|
under_surveillance: boolean;
|
|
security_suspended_at: Date | null;
|
|
created_at: Date;
|
|
};
|
|
balances: Array<{
|
|
wallet_type: string;
|
|
wallet_name: string;
|
|
available: string;
|
|
locked: string;
|
|
}>;
|
|
}> {
|
|
const row = await userRepository.getForAdmin(userId);
|
|
if (!row) {
|
|
throw new Error('User not found');
|
|
}
|
|
const balances = await walletService.getUserBalances(userId);
|
|
return {
|
|
user: {
|
|
id: row.id,
|
|
email: decryptEmail(row.email_encrypted),
|
|
role_id: row.role_id,
|
|
role_name: row.role_name,
|
|
email_verified: row.email_verified,
|
|
totp_enabled: row.totp_enabled,
|
|
is_enabled: row.is_enabled,
|
|
is_account_non_expired: row.is_account_non_expired,
|
|
is_account_non_locked: row.is_account_non_locked,
|
|
is_credentials_non_expired: row.is_credentials_non_expired,
|
|
withdrawals_suspended: row.withdrawals_suspended,
|
|
under_surveillance: row.under_surveillance,
|
|
security_suspended_at: row.security_suspended_at,
|
|
created_at: row.created_at,
|
|
},
|
|
balances: balances.map((b) => ({
|
|
wallet_type: b.walletType.code,
|
|
wallet_name: b.walletType.name,
|
|
available: b.available,
|
|
locked: b.locked,
|
|
})),
|
|
};
|
|
}
|
|
|
|
export type UserRoleName = 'user' | 'moderator' | 'admin';
|
|
|
|
export async function updateUserRole(
|
|
targetUserId: string,
|
|
role: UserRoleName,
|
|
adminUserId: string
|
|
): Promise<{ userId: string; role: UserRoleName }> {
|
|
if (!['user', 'moderator', 'admin'].includes(role)) {
|
|
throw new Error('Invalid role');
|
|
}
|
|
|
|
const target = await userRepository.findById(targetUserId);
|
|
if (!target) throw new Error('User not found');
|
|
|
|
const currentRole = (await userRepository.getRoleName(target.role_id)) as UserRoleName;
|
|
const roleId = await userRepository.getRoleIdByName(role);
|
|
|
|
if (currentRole === role) {
|
|
return { userId: targetUserId, role };
|
|
}
|
|
|
|
if (currentRole === 'admin' && role !== 'admin') {
|
|
const adminCount = await userRepository.countUsersWithRole('admin');
|
|
if (adminCount <= 1) {
|
|
throw new Error('Cannot change role: at least one administrator must remain on the platform');
|
|
}
|
|
}
|
|
|
|
if (targetUserId === adminUserId && currentRole === 'admin' && role !== 'admin') {
|
|
throw new Error('You cannot remove your own administrator role');
|
|
}
|
|
|
|
await userRepository.updateUserRole(targetUserId, roleId);
|
|
|
|
await auditLogRepository.create({
|
|
userId: adminUserId,
|
|
action: 'admin_user_role_changed',
|
|
resourceType: 'user',
|
|
resourceId: targetUserId,
|
|
metadata: { from: currentRole, to: role },
|
|
});
|
|
|
|
return { userId: targetUserId, role };
|
|
}
|