-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathadmin.service.ts
More file actions
660 lines (551 loc) · 19.3 KB
/
admin.service.ts
File metadata and controls
660 lines (551 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import {
BadGatewayException,
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, Repository } from 'typeorm';
import { AnalyticsService } from '../analytics/analytics.service';
import { ActivityLog } from '../analytics/entities/activity-log.entity';
import { CompetitionParticipant } from '../competitions/entities/competition-participant.entity';
import { Competition } from '../competitions/entities/competition.entity';
import { ListFlagsQueryDto } from '../flags/dto/list-flags-query.dto';
import { ResolveFlagDto } from '../flags/dto/resolve-flag.dto';
import { FlagsService } from '../flags/flags.service';
import { Comment } from '../markets/entities/comment.entity';
import { Market } from '../markets/entities/market.entity';
import { NotificationType } from '../notifications/entities/notification.entity';
import { NotificationsService } from '../notifications/notifications.service';
import { Prediction } from '../predictions/entities/prediction.entity';
import { SorobanService } from '../soroban/soroban.service';
import { User } from '../users/entities/user.entity';
import { ActivityLogQueryDto } from './dto/activity-log-query.dto';
import { ListUsersQueryDto } from './dto/list-users-query.dto';
import {
ReportFormat,
ReportQueryDto,
ReportTimeframe,
} from './dto/report-query.dto';
import { ResolveMarketDto } from './dto/resolve-market.dto';
import { StatsResponseDto } from './dto/stats-response.dto';
import { UpdateUserRoleDto } from './dto/update-user-role.dto';
import { SystemConfig } from './entities/system-config.entity';
import {
DEFAULT_CONFIG,
SystemConfigValues,
UpdateSystemConfigDto,
} from './dto/system-config.dto';
@Injectable()
export class AdminService {
private readonly logger = new Logger(AdminService.name);
private configCache: SystemConfigValues | null = null;
constructor(
@InjectRepository(User)
private readonly usersRepository: Repository<User>,
@InjectRepository(Market)
private readonly marketsRepository: Repository<Market>,
@InjectRepository(Comment)
private readonly commentsRepository: Repository<Comment>,
@InjectRepository(Prediction)
private readonly predictionsRepository: Repository<Prediction>,
@InjectRepository(Competition)
private readonly competitionsRepository: Repository<Competition>,
@InjectRepository(CompetitionParticipant)
private readonly competitionParticipantsRepository: Repository<CompetitionParticipant>,
@InjectRepository(ActivityLog)
private readonly activityLogsRepository: Repository<ActivityLog>,
@InjectRepository(SystemConfig)
private readonly systemConfigRepository: Repository<SystemConfig>,
private readonly analyticsService: AnalyticsService,
private readonly notificationsService: NotificationsService,
private readonly sorobanService: SorobanService,
private readonly flagsService: FlagsService,
) {}
async getConfig(): Promise<SystemConfigValues> {
if (this.configCache) return this.configCache;
const rows = await this.systemConfigRepository.find();
const config = { ...DEFAULT_CONFIG };
for (const row of rows) {
if (row.key in config) {
(config as Record<string, unknown>)[row.key] = row.value;
}
}
this.configCache = config;
return config;
}
async updateConfig(
dto: UpdateSystemConfigDto,
adminId: string,
): Promise<SystemConfigValues> {
const updates = Object.entries(dto).filter(([, v]) => v !== undefined);
for (const [key, value] of updates) {
await this.systemConfigRepository.save({ key, value });
}
this.configCache = null;
await this.analyticsService.logActivity(adminId, 'SYSTEM_CONFIG_UPDATED', {
updated_keys: updates.map(([k]) => k),
});
return this.getConfig();
}
async getStats(): Promise<StatsResponseDto> {
const now = new Date();
const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const total_users = await this.usersRepository.count();
const active_users_24h = await this.usersRepository.count({
where: { updated_at: Between(twentyFourHoursAgo, now) },
});
const active_users_7d = await this.usersRepository.count({
where: { updated_at: Between(sevenDaysAgo, now) },
});
const total_markets = await this.marketsRepository.count();
const active_markets = await this.marketsRepository.count({
where: { is_resolved: false, is_cancelled: false },
});
const resolved_markets = await this.marketsRepository.count({
where: { is_resolved: true },
});
const total_predictions = await this.predictionsRepository.count();
const volumeResult = (await this.marketsRepository
.createQueryBuilder('market')
.select('SUM(CAST(market.total_pool_stroops AS DECIMAL))', 'total')
.getRawOne()) as { total: string | null };
const total_volume_stroops = volumeResult?.total || '0';
const total_competitions = await this.competitionsRepository.count();
// Platform revenue (2% fee of total volume as an example)
const platform_revenue_stroops = (
(BigInt(total_volume_stroops.split('.')[0]) * BigInt(2)) /
BigInt(100)
).toString();
return {
total_users,
active_users_24h,
active_users_7d,
total_markets,
active_markets,
resolved_markets,
total_predictions,
total_volume_stroops,
total_competitions,
platform_revenue_stroops,
};
}
async listUsers(query: ListUsersQueryDto) {
const {
page = 1,
limit = 10,
search,
role,
sortBy = 'created_at',
sortOrder = 'DESC',
} = query;
const skip = (page - 1) * limit;
const queryBuilder = this.usersRepository.createQueryBuilder('user');
if (search) {
queryBuilder.where(
'user.username ILIKE :search OR user.stellar_address ILIKE :search',
{
search: `%${search}%`,
},
);
}
if (role) {
queryBuilder.andWhere('user.role = :role', { role });
}
queryBuilder.orderBy(`user.${sortBy}`, sortOrder).skip(skip).take(limit);
const [users, total] = await queryBuilder.getManyAndCount();
return {
data: users,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
async banUser(id: string, reason: string, adminId: string): Promise<User> {
const user = await this.usersRepository.findOne({ where: { id } });
if (!user) throw new NotFoundException('User not found');
user.is_banned = true;
user.ban_reason = reason;
user.banned_at = new Date();
user.banned_by = adminId;
await this.usersRepository.save(user);
await this.analyticsService.logActivity(user.id, 'USER_BANNED', {
reason,
banned_by: adminId,
});
return user;
}
async unbanUser(id: string, adminId: string): Promise<User> {
const user = await this.usersRepository.findOne({ where: { id } });
if (!user) throw new NotFoundException('User not found');
user.is_banned = false;
user.ban_reason = null;
user.banned_at = null;
user.banned_by = null;
await this.usersRepository.save(user);
await this.analyticsService.logActivity(user.id, 'USER_UNBANNED', {
unbanned_by: adminId,
});
return user;
}
async updateUserRole(
id: string,
dto: UpdateUserRoleDto,
adminId: string,
): Promise<User> {
if (id === adminId) {
throw new BadRequestException('You cannot change your own role');
}
const user = await this.usersRepository.findOne({ where: { id } });
if (!user) throw new NotFoundException('User not found');
const previousRole = user.role;
user.role = dto.role;
await this.usersRepository.save(user);
await this.analyticsService.logActivity(adminId, 'USER_ROLE_CHANGED', {
target_user_id: id,
previous_role: previousRole,
new_role: dto.role,
});
this.logger.log(
`Admin ${adminId} changed role of user ${id} from "${previousRole}" to "${dto.role}"`,
);
return user;
}
async getUserActivity(userId: string, query: ActivityLogQueryDto) {
const { page = 1, limit = 10, actionType, startDate, endDate } = query;
const skip = (page - 1) * limit;
const queryBuilder = this.activityLogsRepository.createQueryBuilder('log');
queryBuilder.where('log.userId = :userId', { userId });
if (actionType) {
queryBuilder.andWhere('log.actionType = :actionType', { actionType });
}
if (startDate && endDate) {
queryBuilder.andWhere('log.timestamp BETWEEN :startDate AND :endDate', {
startDate: new Date(startDate),
endDate: new Date(endDate),
});
}
queryBuilder.orderBy('log.timestamp', 'DESC').skip(skip).take(limit);
const [logs, total] = await queryBuilder.getManyAndCount();
return {
data: logs,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
async listFlags(query: ListFlagsQueryDto) {
return this.flagsService.listFlags(query);
}
async resolveFlag(
flagId: string,
resolveFlagDto: ResolveFlagDto,
adminId: string,
) {
return this.flagsService.resolveFlag(flagId, resolveFlagDto, adminId);
}
async adminResolveMarket(
id: string,
dto: ResolveMarketDto,
adminId: string,
): Promise<Market> {
const market = await this.marketsRepository.findOne({
where: [{ id }, { on_chain_market_id: id }],
});
if (!market) {
throw new NotFoundException(`Market "${id}" not found`);
}
if (market.is_resolved) {
throw new ConflictException('Market is already resolved');
}
if (market.is_cancelled) {
throw new BadRequestException('Cannot resolve a cancelled market');
}
if (!market.outcome_options.includes(dto.resolved_outcome)) {
throw new BadRequestException(
`Invalid outcome "${dto.resolved_outcome}". Valid options: ${market.outcome_options.join(', ')}`,
);
}
// Trigger payout distribution on-chain
try {
await this.sorobanService.resolveMarket(
market.on_chain_market_id,
dto.resolved_outcome,
);
} catch (err) {
this.logger.error(
'Soroban resolveMarket failed during admin resolution',
err,
);
throw new BadGatewayException('Failed to resolve market on Soroban');
}
market.is_resolved = true;
market.resolved_outcome = dto.resolved_outcome;
const saved = await this.marketsRepository.save(market);
// Notify all participants
const predictions = await this.predictionsRepository.find({
where: { market: { id: market.id } },
relations: ['user'],
});
await Promise.all(
predictions.map((p) =>
this.notificationsService.create(
p.user.id,
NotificationType.MarketResolved,
'Market Resolved',
`The market "${market.title}" has been resolved. Winning outcome: ${dto.resolved_outcome}.`,
{
market_id: market.id,
resolved_outcome: dto.resolved_outcome,
your_prediction: p.chosen_outcome,
won: p.chosen_outcome === dto.resolved_outcome,
...(dto.resolution_note
? { resolution_note: dto.resolution_note }
: {}),
},
),
),
);
// Log admin action
await this.analyticsService.logActivity(
adminId,
'MARKET_RESOLVED_BY_ADMIN',
{
market_id: market.id,
resolved_outcome: dto.resolved_outcome,
resolution_note: dto.resolution_note ?? null,
},
);
this.logger.log(
`Admin ${adminId} resolved market "${market.title}" (${market.id}) with outcome "${dto.resolved_outcome}"`,
);
return saved;
}
async adminCancelCompetition(
competitionId: string,
adminId: string,
): Promise<Competition> {
const competition = await this.competitionsRepository.findOne({
where: { id: competitionId },
});
if (!competition) {
throw new NotFoundException(
`Competition with ID "${competitionId}" not found`,
);
}
if (competition.is_cancelled) {
throw new ConflictException('Competition is already cancelled');
}
if (competition.is_finalized) {
throw new ConflictException('Finalized competitions cannot be cancelled');
}
const participants = await this.competitionParticipantsRepository.find({
where: { competition_id: competition.id },
relations: ['user'],
});
const totalPool = BigInt(competition.prize_pool_stroops);
const participantCount = participants.length;
const shouldRefund = totalPool > 0n && participantCount > 0;
const refundAllocations = new Map<string, string>();
if (shouldRefund) {
const baseRefund = totalPool / BigInt(participantCount);
let remainder = totalPool % BigInt(participantCount);
for (const participant of participants) {
const hasAddress = Boolean(participant.user?.stellar_address);
if (!hasAddress) {
refundAllocations.set(participant.user_id, '0');
continue;
}
let refundAmount = baseRefund;
if (remainder > 0n) {
refundAmount += 1n;
remainder -= 1n;
}
refundAllocations.set(participant.user_id, refundAmount.toString());
try {
await this.sorobanService.refundCompetitionParticipant(
participant.user.stellar_address,
competition.id,
refundAmount.toString(),
);
} catch (err) {
this.logger.error('Soroban competition refund failed', err);
throw new BadGatewayException(
'Failed to refund participants on Soroban',
);
}
}
}
competition.is_cancelled = true;
const savedCompetition =
await this.competitionsRepository.save(competition);
await Promise.all(
participants.map((participant) =>
this.notificationsService.create(
participant.user_id,
NotificationType.System,
'Competition Cancelled',
`The competition "${competition.title}" has been cancelled by an administrator.${
shouldRefund ? ' Any applicable refunds have been initiated.' : ''
}`,
{
competition_id: competition.id,
is_cancelled: true,
refunded_stroops: refundAllocations.get(participant.user_id) ?? '0',
},
),
),
);
await this.analyticsService.logActivity(
adminId,
'COMPETITION_CANCELLED_BY_ADMIN',
{
competition_id: competition.id,
participants_notified: participants.length,
refunds_initiated: shouldRefund,
},
);
this.logger.log(
`Admin ${adminId} cancelled competition "${competition.title}" (${competition.id})`,
);
return savedCompetition;
}
async moderateComment(
commentId: string,
isModerated: boolean,
reason?: string,
): Promise<Comment> {
const comment = await this.commentsRepository.findOne({
where: { id: commentId },
});
if (!comment) {
throw new NotFoundException(`Comment with ID "${commentId}" not found`);
}
comment.is_moderated = isModerated;
comment.moderation_reason = reason ?? null;
return await this.commentsRepository.save(comment);
}
async featureMarket(marketId: string, adminId: string): Promise<Market> {
const market = await this.marketsRepository.findOne({
where: [{ id: marketId }, { on_chain_market_id: marketId }],
});
if (!market) {
throw new NotFoundException(`Market "${marketId}" not found`);
}
if (market.is_featured) {
throw new ConflictException('Market is already featured');
}
market.is_featured = true;
market.featured_at = new Date();
const saved = await this.marketsRepository.save(market);
// Log admin action
await this.analyticsService.logActivity(
adminId,
'MARKET_FEATURED_BY_ADMIN',
{
market_id: market.id,
featured_at: market.featured_at,
},
);
this.logger.log(
`Admin ${adminId} featured market "${market.title}" (${market.id})`,
);
return saved;
}
async unfeatureMarket(marketId: string, adminId: string): Promise<Market> {
const market = await this.marketsRepository.findOne({
where: [{ id: marketId }, { on_chain_market_id: marketId }],
});
if (!market) {
throw new NotFoundException(`Market "${marketId}" not found`);
}
if (!market.is_featured) {
throw new ConflictException('Market is not featured');
}
market.is_featured = false;
market.featured_at = null;
const saved = await this.marketsRepository.save(market);
// Log admin action
await this.analyticsService.logActivity(
adminId,
'MARKET_UNFEATURED_BY_ADMIN',
{
market_id: market.id,
unfeatured_at: new Date(),
},
);
this.logger.log(
`Admin ${adminId} unfeatured market "${market.title}" (${market.id})`,
);
return saved;
}
async getActivityReport(query: ReportQueryDto) {
const { timeframe, format } = query;
const now = new Date();
let startDate: Date;
switch (timeframe) {
case ReportTimeframe.Daily:
startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
break;
case ReportTimeframe.Weekly:
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
break;
case ReportTimeframe.Monthly:
startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
break;
default:
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
}
// User Growth
const userGrowth = await this.usersRepository.count({
where: { created_at: Between(startDate, now) },
});
// Market Creation Trends
const marketsCreated = await this.marketsRepository.count({
where: { created_at: Between(startDate, now) },
});
// Platform Revenue (accumulated in this period)
const volumeResult = (await this.marketsRepository
.createQueryBuilder('market')
.select('SUM(CAST(market.total_pool_stroops AS DECIMAL))', 'total')
.where('market.created_at BETWEEN :startDate AND :endDate', {
startDate,
endDate: now,
})
.getRawOne()) as { total: string | null };
const periodVolume = volumeResult?.total || '0';
const periodRevenue = (
(BigInt(periodVolume.split('.')[0]) * BigInt(2)) /
BigInt(100)
).toString();
// Predictions activity
const predictionsCount = await this.predictionsRepository.count({
where: { submitted_at: Between(startDate, now) },
});
const reportData = {
timeframe,
period_start: startDate.toISOString(),
period_end: now.toISOString(),
user_growth: userGrowth,
markets_created: marketsCreated,
total_predictions: predictionsCount,
period_volume_stroops: periodVolume,
platform_revenue_stroops: periodRevenue,
};
if (format === ReportFormat.CSV) {
const headers = Object.keys(reportData).join(',');
const values = Object.values(reportData).join(',');
return `${headers}\n${values}`;
}
return reportData;
}
}