File size: 8,141 Bytes
675f6bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { DisputesService } from '../disputes/disputes.service';
import { ResolveDisputeDto } from './dto/resolve-dispute.dto';
import { DisputeResolution } from '../disputes/dto/resolve-dispute.dto';
import { TransactionType } from '@common/enums/transaction-type.enum';

@Injectable()
export class AdminService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly disputesService: DisputesService,
  ) {}

  // PUT /admin/projects/:id/suspend-spec
  async suspendSpec(projectId: string) {
    const project = await this.prisma.project.findUnique({ where: { id: projectId } });
    if (!project) {
      throw new NotFoundException('Project not found.');
    }
    
    return this.prisma.$transaction(async (tx) => {
      const updated = await tx.project.update({
        where: { id: projectId },
        data: { state: 'SUSPENDED' }
      });

      await tx.platformDecision.create({
        data: {
          decisionType: 'SPEC_AUTO_RETURN',
          entityType: 'projects',
          entityId: projectId,
          decision: 'SUSPENDED',
          advisoryNote: 'Admin suspension',
        }
      });

      return updated;
    });
  }

  // PUT /admin/users/:id/suspend
  async suspendUser(userId: string) {
    const user = await this.prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      throw new NotFoundException('User not found.');
    }
    
    return this.prisma.user.update({
      where: { id: userId },
      data: { isActive: false },
    });
  }

  async getDisputesQueue(adminUserId: string, state?: string) {
    return this.disputesService.findAll(
      { id: adminUserId, activeRole: 'ADMIN' },
      { state },
    );
  }

  async resolveDispute(disputeId: string, dto: ResolveDisputeDto, adminUserId: string) {
    const resolution: DisputeResolution = {
      decision: dto.decision,
    };
    await this.disputesService.applyResolution(disputeId, resolution, undefined, adminUserId);
    return { success: true };
  }

  // GET /admin/decisions
  async getDecisions(filters?: { decisionType?: string; entityType?: string }) {
    return this.prisma.platformDecision.findMany({
      where: {
        ...(filters?.decisionType ? { decisionType: filters.decisionType } : {}),
        ...(filters?.entityType   ? { entityType: filters.entityType }     : {}),
      },
      orderBy: { createdAt: 'desc' },
      take: 200,
    });
  }

  // GET /admin/transactions
  async getTransactions(filters?: { type?: string; userId?: string }) {
    const transactions = await this.prisma.walletTransaction.findMany({
      where: {
        ...(filters?.type ? { transactionType: filters.type } : {}),
        ...(filters?.userId ? { wallet: { userId: filters.userId } } : {}),
      },
      include: {
        wallet: {
          select: {
            user: { select: { email: true, fullName: true } },
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 200,
    });

    return transactions.map((t) => ({
      id:               t.id,
      amount:           Number(t.amount),
      transactionType:  t.transactionType,
      referenceId:      t.referenceId,
      createdAt:        t.createdAt,
      userEmail:        t.wallet.user.email,
      userFullName:     t.wallet.user.fullName,
    }));
  }

  // GET /admin/analytics
  async getAnalytics() {
    const [
      projectsByArchetype,
      totalSessions,
      completedSessions,
      totalPortfolioSubmissions,
      approvedPortfolioSubmissions,
      totalDisputes,
      autoResolvedDisputes,
      totalMilestones,
      releasedMilestones,
    ] = await Promise.all([
      this.prisma.project.groupBy({
        by: ['archetype', 'tier'],
        _count: true,
        where: { state: 'PUBLISHED' },
      }),
      this.prisma.elicitationSession.count(),
      this.prisma.elicitationSession.count({ where: { state: 'COMPLETED' } }),
      this.prisma.portfolioSubmission.count(),
      this.prisma.portfolioSubmission.count({ where: { status: 'APPROVED' } }),
      this.prisma.dispute.count(),
      this.prisma.dispute.count({ where: { state: 'AUTO_RESOLVED' } }),
      this.prisma.milestone.count(),
      this.prisma.milestone.count({ where: { state: 'RELEASED' } }),
    ]);

    const safeRate = (numerator: number, denominator: number) =>
      denominator > 0 ? Math.round((numerator / denominator) * 1000) / 10 : 0;

    return {
      active_projects_by_archetype_tier: projectsByArchetype,
      elicitation_completion_rate_pct:   safeRate(completedSessions, totalSessions),
      portfolio_auto_upgrade_rate_pct:   safeRate(approvedPortfolioSubmissions, totalPortfolioSubmissions),
      dispute_rate_pct:                  safeRate(totalDisputes, totalMilestones),
      dispute_auto_resolve_rate_pct:     safeRate(autoResolvedDisputes, totalDisputes),
      milestone_completion_rate_pct:     safeRate(releasedMilestones, totalMilestones),
    };
  }

  async completeWithdrawal(withdrawalId: string) {
    const withdrawal = await this.prisma.withdrawalRequest.findUnique({
      where: { id: withdrawalId },
    });
    if (!withdrawal) {
      throw new NotFoundException('Withdrawal request not found.');
    }
    if (withdrawal.status !== 'PENDING') {
      throw new ConflictException(`Withdrawal is in status ${withdrawal.status}; cannot complete.`);
    }
 
    if (withdrawal.type !== 'MILESTONE_RELEASE' || !withdrawal.milestoneId) {
      return this.prisma.withdrawalRequest.update({
        where: { id: withdrawalId },
        data: { status: 'COMPLETED', confirmedAt: new Date() },
      });
    }
 
    return this.prisma.$transaction(async (tx) => {
      const updated = await tx.withdrawalRequest.update({
        where: { id: withdrawalId },
        data: { status: 'COMPLETED', confirmedAt: new Date() },
      });
 
      const milestone = await tx.milestone.findUnique({
        where: { id: withdrawal.milestoneId! },
      });
 
      if (milestone && milestone.state === 'APPROVED') {
        await tx.milestone.update({
          where: { id: milestone.id },
          data: { state: 'RELEASED', releasedAt: new Date() },
        });
 
        const unreleased = await tx.milestone.count({
          where: { engagementId: milestone.engagementId, state: { not: 'RELEASED' } },
        });
 
        if (unreleased === 0) {
          await tx.engagement.update({
            where: { id: milestone.engagementId },
            data: { state: 'CLOSED' },
          });
        }
      }
 
      return updated;
    });
  }

  async failWithdrawal(withdrawalId: string) {
    const withdrawal = await this.prisma.withdrawalRequest.findUnique({
      where: { id: withdrawalId },
    });
    if (!withdrawal) {
      throw new NotFoundException('Withdrawal request not found.');
    }
    if (withdrawal.status !== 'PENDING') {
      throw new ConflictException(`Withdrawal is in status ${withdrawal.status}; cannot fail.`);
    }

    return this.prisma.$transaction(async (tx) => {
      const wallet = await tx.wallet.findUnique({ where: { userId: withdrawal.expertId } });
      if (!wallet) {
        throw new NotFoundException('Wallet not found.');
      }

      await tx.wallet.update({
        where: { id: wallet.id },
        data: { availableBalance: { increment: withdrawal.amount } },
      });

      await tx.walletTransaction.create({
        data: {
          walletId:        wallet.id,
          amount:          withdrawal.amount,
          transactionType: TransactionType.WITHDRAWAL,
          referenceId:     `WD-${withdrawal.id}-REVERSAL`,
        },
      });

      return tx.withdrawalRequest.update({
        where: { id: withdrawalId },
        data: { status: 'FAILED' },
      });
    });
  }

  // GET /admin/withdrawals — queue for the actions above
  async getWithdrawalsQueue(status?: string) {
    return this.prisma.withdrawalRequest.findMany({
      where: status ? { status } : undefined,
      orderBy: { requestedAt: 'desc' },
    });
  }
}