File size: 13,131 Bytes
303c85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"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 AdminWorkspacesService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminWorkspacesService = 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 client_1 = require("@prisma/client");
const shared_types_1 = require("@micprotocol/shared-types");
const admin_permission_decorator_1 = require("../common/decorators/admin-permission.decorator");
let AdminWorkspacesService = AdminWorkspacesService_1 = class AdminWorkspacesService {
    prisma;
    audit;
    logger = new common_1.Logger(AdminWorkspacesService_1.name);
    constructor(prisma, audit) {
        this.prisma = prisma;
        this.audit = audit;
    }
    async listWorkspaces(input = {}) {
        const limit = Math.min(Math.max(input.limit ?? 50, 1), 200);
        const where = {
            ...(input.search
                ? {
                    OR: [
                        { name: { contains: input.search, mode: "insensitive" } },
                        { slug: { contains: input.search, mode: "insensitive" } },
                    ],
                }
                : {}),
            ...(input.suspended !== undefined
                ? { suspendedAt: input.suspended ? { not: null } : { equals: null } }
                : {}),
        };
        const [total, items] = await Promise.all([
            this.prisma.workspace.count({ where }),
            this.prisma.workspace.findMany({
                where,
                orderBy: { createdAt: "desc" },
                take: limit + 1,
                ...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
                select: {
                    id: true,
                    name: true,
                    slug: true,
                    subscriptionPlanId: true,
                    subscriptionStatus: true,
                    suspendedAt: true,
                    createdAt: true,
                    _count: { select: { members: true, podcasts: true } },
                },
            }),
        ]);
        const hasMore = items.length > limit;
        const page = hasMore ? items.slice(0, limit) : items;
        return {
            items: page.map((w) => ({
                id: w.id,
                name: w.name,
                slug: w.slug,
                subscriptionPlanId: w.subscriptionPlanId,
                subscriptionStatus: w.subscriptionStatus,
                suspended: !!w.suspendedAt,
                suspendedAt: w.suspendedAt,
                memberCount: w._count.members,
                podcastCount: w._count.podcasts,
                createdAt: w.createdAt,
            })),
            total,
            nextCursor: hasMore ? page[page.length - 1]?.id ?? null : null,
        };
    }
    async getWorkspace(workspaceId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: {
                id: true,
                name: true,
                slug: true,
                subscriptionPlanId: true,
                subscriptionStatus: true,
                billingSettings: true,
                suspendedAt: true,
                suspendedReason: true,
                verificationStatus: true,
                createdAt: true,
                updatedAt: true,
                _count: { select: { members: true, podcasts: true } },
            },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        return workspace;
    }
    async suspendWorkspace(workspaceId, reason, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true, name: true, suspendedAt: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        if (workspace.suspendedAt)
            throw new common_1.BadRequestException("Workspace is already suspended");
        const suspendedAt = new Date();
        const updated = await this.prisma.workspace.update({
            where: { id: workspaceId },
            data: { suspendedAt, suspendedReason: reason ?? null },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.suspend",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: {
                reason,
                before: { suspendedAt: null },
                after: { suspendedAt, suspendedReason: reason },
            },
        });
        return updated;
    }
    async reactivateWorkspace(workspaceId, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true, name: true, suspendedAt: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        if (!workspace.suspendedAt)
            throw new common_1.BadRequestException("Workspace is not suspended");
        const updated = await this.prisma.workspace.update({
            where: { id: workspaceId },
            data: { suspendedAt: null, suspendedReason: null },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.reactivate",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: {
                before: { suspendedAt: workspace.suspendedAt },
                after: { suspendedAt: null },
            },
        });
        return updated;
    }
    async overridePlan(workspaceId, planId, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true, name: true, subscriptionPlanId: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        const updated = await this.prisma.workspace.update({
            where: { id: workspaceId },
            data: { subscriptionPlanId: planId },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.plan",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: {
                before: { subscriptionPlanId: workspace.subscriptionPlanId },
                after: { subscriptionPlanId: planId },
            },
        });
        return updated;
    }
    async setCredits(workspaceId, credits, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true, name: true, billingSettings: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        const settings = (workspace.billingSettings ?? {});
        const before = settings["credits"];
        const updated = await this.prisma.workspace.update({
            where: { id: workspaceId },
            data: { billingSettings: { ...settings, credits } },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.credits",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: { before, after: credits },
        });
        return updated;
    }
    async transferOwner(workspaceId, newOwnerUserId, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true, name: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        const newMember = await this.prisma.workspaceMember.findUnique({
            where: { userId_workspaceId: { userId: newOwnerUserId, workspaceId } },
        });
        if (!newMember)
            throw new common_1.BadRequestException("Target user is not a member of this workspace");
        const currentOwners = await this.prisma.workspaceMember.findMany({
            where: { workspaceId, role: client_1.WorkspaceRole.owner },
        });
        for (const owner of currentOwners) {
            if (owner.id === newMember.id)
                continue;
            await this.prisma.workspaceMember.update({
                where: { id: owner.id },
                data: { role: client_1.WorkspaceRole.admin },
            });
        }
        await this.prisma.workspaceMember.update({
            where: { id: newMember.id },
            data: { role: client_1.WorkspaceRole.owner },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.transfer_owner",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: { newOwnerUserId, previousOwners: currentOwners.map((o) => o.userId) },
        });
        return { workspaceId, newOwnerUserId };
    }
    async addWorkspaceNote(workspaceId, body, actorUserId) {
        const workspace = await this.prisma.workspace.findUnique({
            where: { id: workspaceId },
            select: { id: true },
        });
        if (!workspace)
            throw new common_1.NotFoundException(`Workspace ${workspaceId} not found`);
        const note = await this.prisma.adminNote.create({
            data: { entityType: "Workspace", entityId: workspaceId, body, createdById: actorUserId },
        });
        await this.audit.log({
            userId: actorUserId,
            action: "admin.workspaces.notes",
            entityType: "Workspace",
            entityId: workspaceId,
            metadata: { noteId: note.id },
        });
        return note;
    }
};
exports.AdminWorkspacesService = AdminWorkspacesService;
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_SUSPEND),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "suspendWorkspace", null);
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_SUSPEND),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "reactivateWorkspace", null);
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_PLAN),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "overridePlan", null);
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_CREDITS),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Number, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "setCredits", null);
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_TRANSFER_OWNER),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "transferOwner", null);
__decorate([
    (0, admin_permission_decorator_1.requireAdminPermission)(shared_types_1.AdminPermission.WORKSPACES_NOTES),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], AdminWorkspacesService.prototype, "addWorkspaceNote", null);
exports.AdminWorkspacesService = AdminWorkspacesService = AdminWorkspacesService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService,
        audit_service_1.AuditService])
], AdminWorkspacesService);
//# sourceMappingURL=admin-workspaces.service.js.map