File size: 1,986 Bytes
6dd9bad
 
 
99f6bca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dd9bad
 
 
99f6bca
6dd9bad
 
 
 
 
 
 
 
99f6bca
6dd9bad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { prisma } from './prisma';

export class UserAdminService {
    static async softDeleteUser(organizationId: string, userId: string): Promise<boolean> {
        const result = await prisma.user.updateMany({
            where: { id: userId, organizationId, deletedAt: null },
            data: { deletedAt: new Date() },
        });
        return result.count > 0;
    }

    static async softDeleteEnrollment(organizationId: string, enrollmentId: string): Promise<boolean> {
        const result = await prisma.enrollment.updateMany({
            where: { id: enrollmentId, organizationId, deletedAt: null },
            data: { deletedAt: new Date() },
        });
        return result.count > 0;
    }

    static async listUsers(organizationId: string, page: number, limit: number) {
        const [users, total] = await Promise.all([
            prisma.user.findMany({
                where: { organizationId, deletedAt: null },
                orderBy: { createdAt: 'desc' },
                skip: (page - 1) * limit,
                take: limit,
                include: {
                    enrollments: { include: { track: true }, orderBy: { startedAt: 'desc' }, take: 1 },
                    _count: { select: { enrollments: true, responses: true } }
                }
            }),
            prisma.user.count({ where: { organizationId, deletedAt: null } })
        ]);

        return { users, total, page, limit };
    }

    static async getUserMessages(organizationId: string, userId: string) {
        const [messages, user] = await Promise.all([
            prisma.message.findMany({
                where: { userId, organizationId },
                orderBy: { createdAt: 'asc' },
            }),
            prisma.user.findFirst({
                where: { id: userId, organizationId },
                select: { id: true, name: true, phone: true }
            })
        ]);

        if (!user) return null;

        return { user, messages };
    }
}