"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var AdminSupervisionService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.AdminSupervisionService = void 0; const common_1 = require("@nestjs/common"); const prisma_service_1 = require("../prisma/prisma.service"); const audit_service_1 = require("../audit/audit.service"); const admin_operations_service_1 = require("./admin-operations.service"); const shared_types_1 = require("@micprotocol/shared-types"); const admin_permission_decorator_1 = require("../common/decorators/admin-permission.decorator"); let AdminSupervisionService = AdminSupervisionService_1 = class AdminSupervisionService { prisma; audit; operations; logger = new common_1.Logger(AdminSupervisionService_1.name); STALE_SUBSCRIPTION_DAYS = 30; constructor(prisma, audit, operations) { this.prisma = prisma; this.audit = audit; this.operations = operations; } async runSupervision(kind = "other", triggeredById = null) { const run = await this.prisma.supervisionRun.create({ data: { kind: kind, status: "running", startedAt: new Date(), triggeredById, }, }); const findings = []; const cutoff = new Date(Date.now() - this.STALE_SUBSCRIPTION_DAYS * 86_400_000); const stale = await this.prisma.workspace.findMany({ where: { subscriptionStatus: "past_due", updatedAt: { lt: cutoff }, }, select: { id: true, name: true, subscriptionPlanId: true, updatedAt: true }, }); for (const w of stale) { findings.push({ kind: "stale_subscription", severity: "high", title: `Past-due subscription for ${w.name}`, details: { plan: w.subscriptionPlanId, pastDueSince: w.updatedAt }, entityType: "Workspace", entityId: w.id, }); } const since24h = new Date(Date.now() - 24 * 60 * 60 * 1000); const failedWebhooks = await this.prisma.webhookDelivery.findMany({ where: { status: "failed", createdAt: { gte: since24h } }, select: { id: true, event: true, endpointId: true, responseStatus: true, createdAt: true }, take: 50, }); for (const w of failedWebhooks) { findings.push({ kind: "failed_webhook", severity: "medium", title: `Failed webhook delivery: ${w.event}`, details: { endpointId: w.endpointId, responseStatus: w.responseStatus, createdAt: w.createdAt }, entityType: "WebhookDelivery", entityId: w.id, }); } const orphaned = await this.prisma.workspace.findMany({ where: { members: { none: {} } }, select: { id: true, name: true, slug: true }, }); for (const w of orphaned) { findings.push({ kind: "orphaned_record", severity: "medium", title: `Orphaned workspace with no members: ${w.name}`, details: { slug: w.slug }, entityType: "Workspace", entityId: w.id, }); } const queueHealth = await this.operations.getQueueHealth(); for (const q of queueHealth) { if (q.failed > 0) { findings.push({ kind: "queue_failure", severity: q.failed > 10 ? "critical" : "high", title: `Queue ${q.name} has ${q.failed} failed jobs`, details: { queue: q.name, failed: q.failed, waiting: q.waiting }, entityType: "Queue", entityId: q.name, }); } } for (const f of findings) { await this.prisma.supervisionFinding.create({ data: { runId: run.id, kind: f.kind, severity: f.severity, title: f.title, details: f.details, entityType: f.entityType, entityId: f.entityId, status: "open", }, }); } const finished = await this.prisma.supervisionRun.update({ where: { id: run.id }, data: { status: "completed", finishedAt: new Date(), summary: { findingCount: findings.length, byKind: findings.reduce((acc, f) => { acc[f.kind] = (acc[f.kind] ?? 0) + 1; return acc; }, {}), }, }, }); await this.audit.log({ userId: triggeredById ?? undefined, action: "admin.supervision.run", entityType: "SupervisionRun", entityId: run.id, metadata: { kind, findingCount: findings.length }, }); return { run: finished, findingCount: findings.length }; } async listRuns() { const runs = await this.prisma.supervisionRun.findMany({ orderBy: { startedAt: "desc" }, include: { _count: { select: { findings: true } } }, }); return runs.map((r) => ({ id: r.id, kind: r.kind, status: r.status, startedAt: r.startedAt, finishedAt: r.finishedAt, summary: r.summary, triggeredById: r.triggeredById, findingCount: r._count.findings, })); } async listFindings(runId, status) { return this.prisma.supervisionFinding.findMany({ where: { ...(runId ? { runId } : {}), ...(status ? { status: status } : {}) }, orderBy: { createdAt: "desc" }, }); } async acknowledgeFinding(findingId, assignedToId) { const finding = await this.prisma.supervisionFinding.findUnique({ where: { id: findingId } }); if (!finding) throw new common_1.NotFoundException(`Finding ${findingId} not found`); return this.prisma.supervisionFinding.update({ where: { id: findingId }, data: { status: "acknowledged", assignedToId }, }); } async resolveFinding(findingId) { const finding = await this.prisma.supervisionFinding.findUnique({ where: { id: findingId } }); if (!finding) throw new common_1.NotFoundException(`Finding ${findingId} not found`); return this.prisma.supervisionFinding.update({ where: { id: findingId }, data: { status: "resolved", resolvedAt: new Date() }, }); } }; exports.AdminSupervisionService = AdminSupervisionService; __decorate([ (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.SUPERVISION_RUN), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], AdminSupervisionService.prototype, "runSupervision", null); __decorate([ (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.SUPERVISION_RUN), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", Promise) ], AdminSupervisionService.prototype, "acknowledgeFinding", null); __decorate([ (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.SUPERVISION_RUN), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise) ], AdminSupervisionService.prototype, "resolveFinding", null); exports.AdminSupervisionService = AdminSupervisionService = AdminSupervisionService_1 = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [prisma_service_1.PrismaService, audit_service_1.AuditService, admin_operations_service_1.AdminOperationsService]) ], AdminSupervisionService); //# sourceMappingURL=admin-supervision.service.js.map