File size: 1,697 Bytes
4339e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { prisma } from './prisma';
import { logger } from '../logger';

export interface ResolvedEntity {
    user: any | null;
    contact: any | null;
    organization: any | null;
    activeEnrollment: any | null;
}

export class EntityResolver {
    /**
     * Resolves User, Contact, Organization and Active Enrollment for a given phone number and organization.
     */
    static async resolve(phone: string, organizationId: string): Promise<ResolvedEntity> {
        try {
            const [user, contact, organization] = await Promise.all([
                prisma.user.findFirst({ 
                    where: { phone, organizationId },
                    include: { organization: true } 
                }),
                prisma.contact.findFirst({ 
                    where: { phoneNumber: phone, organizationId } 
                }),
                prisma.organization.findUnique({ 
                    where: { id: organizationId } 
                })
            ]);

            let activeEnrollment = null;
            if (user) {
                activeEnrollment = await prisma.enrollment.findFirst({
                    where: { userId: user.id, status: 'ACTIVE' },
                    include: { track: true }
                });
            }

            return {
                user,
                contact,
                organization: organization || user?.organization || null,
                activeEnrollment
            };
        } catch (err) {
            logger.error({ err, phone, organizationId }, '[EntityResolver] Failed to resolve entity');
            return { user: null, contact: null, organization: null, activeEnrollment: null };
        }
    }
}