eletrotupi / tcc/ api/src/services/careAction.service.ts04084150bf5e7e1867221dfcc35651e6d37ad766
5.4 KB | 231 lines Raw
1
import { prisma } from '@app/lib/prisma';
2
import { CareAction, CareActionType } from '@prisma/client';
3
import { CreateCareActionInput, PatchCareActionInput } from '@app/schemas';
4
import { syncMedicineReminderJobs } from '@app/services/medicineReminder.sync';
5

6
const careActionIncludes = {
7
  medicineLog: { include: { regimen: true } },
8
  appointment: true,
9
  activity: true,
10
} as const;
11

12
export const getCareActionsByUserId = async (
13
  userId: number,
14
  params?: {
15
    type?: CareActionType;
16
    from?: string;
17
    to?: string;
18
    page?: number;
19
    limit?: number;
20
  },
21
) => {
22
  const page = params?.page ?? 1;
23
  const limit = params?.limit ?? 20;
24
  const skip = (page - 1) * limit;
25

26
  const where = {
27
    userId,
28
    ...(params?.type ? { type: params.type } : {}),
29
    ...(params?.from || params?.to
30
      ? {
31
          moment: {
32
            ...(params?.from && { gte: new Date(params.from) }),
33
            ...(params?.to && { lte: new Date(params.to) }),
34
          },
35
        }
36
      : {}),
37
  };
38

39
  const [entries, total] = await Promise.all([
40
    prisma.careAction.findMany({
41
      where,
42
      include: careActionIncludes,
43
      orderBy: { moment: 'desc' },
44
      take: limit,
45
      skip,
46
    }),
47

48
    prisma.careAction.count({ where }),
49
  ]);
50

51
  const totalPages = Math.ceil(total / limit);
52

53
  return {
54
    entries,
55
    total,
56
    page,
57
    nextPage: page < totalPages ? page + 1 : null,
58
  };
59
};
60

61
export const getCareActionById = async (userId: number, id: number) => {
62
  return prisma.careAction.findUnique({
63
    where: { id, userId },
64
    include: careActionIncludes,
65
  });
66
};
67

68
export const destroyCareActionById = async (
69
  userId: number,
70
  id: number,
71
): Promise<CareAction> => {
72
  return prisma.careAction.delete({
73
    where: { id, userId },
74
  });
75
};
76

77
export const patchCareActionById = async (
78
  userId: number,
79
  id: number,
80
  data: PatchCareActionInput,
81
) => {
82
  return prisma.careAction.update({
83
    where: { id, userId },
84
    data,
85
    include: careActionIncludes,
86
  });
87
};
88

89
export const createCareAction = async (
90
  userId: number,
91
  input: CreateCareActionInput,
92
) => {
93
  if (input.type === CareActionType.MEDICINE) {
94
    if (input.regimenId) {
95
      const regimenId = input.regimenId;
96

97
      const [careAction] = await prisma.$transaction([
98
        prisma.careAction.create({
99
          data: {
100
            userId,
101
            type: input.type,
102
            moment: input.moment,
103
            triggerId: input.triggerId,
104
            moodId: input.moodId,
105
            medicineLog: {
106
              create: { regimenId },
107
            },
108
          },
109
          include: careActionIncludes,
110
        }),
111
      ]);
112

113
      return careAction;
114
    }
115

116
    if (input.medicine) {
117
      const med = input.medicine;
118

119
      const [careAction] = await prisma.$transaction([
120
        prisma.careAction.create({
121
          data: {
122
            userId,
123
            type: input.type,
124
            moment: input.moment,
125
            triggerId: input.triggerId,
126
            moodId: input.moodId,
127
            medicineLog: {
128
              create: {
129
                regimen: {
130
                  create: {
131
                    name: med.name,
132
                    dosage: med.dosage,
133
                    periodicity: med.periodicity,
134
                    scheduledAt: med.scheduledAt,
135
                    userId,
136
                  },
137
                },
138
              },
139
            },
140
          },
141
          include: careActionIncludes,
142
        }),
143
      ]);
144

145
      if (careAction.medicineLog?.regimen) {
146
        await syncMedicineReminderJobs(careAction.medicineLog.regimen as any);
147
      }
148

149
      return careAction;
150
    }
151

152
    // MEDICINE with no regimen info: create action without log
153
    const [careAction] = await prisma.$transaction([
154
      prisma.careAction.create({
155
        data: {
156
          userId,
157
          type: input.type,
158
          moment: input.moment,
159
          triggerId: input.triggerId,
160
          moodId: input.moodId,
161
        },
162
        include: careActionIncludes,
163
      }),
164
    ]);
165

166
    return careAction;
167
  }
168

169
  if (input.type === CareActionType.APPOINTMENT && input.appointment) {
170
    const appt = input.appointment;
171

172
    const [careAction] = await prisma.$transaction([
173
      prisma.careAction.create({
174
        data: {
175
          userId,
176
          type: input.type,
177
          moment: input.moment,
178
          triggerId: input.triggerId,
179
          moodId: input.moodId,
180
          appointment: {
181
            create: {
182
              type: appt.type,
183
              duration: appt.duration,
184
              note: appt.note,
185
            },
186
          },
187
        },
188
        include: careActionIncludes,
189
      }),
190
    ]);
191

192
    return careAction;
193
  }
194

195
  if (input.type === CareActionType.ACTIVITY && input.activity) {
196
    const act = input.activity;
197

198
    const [careAction] = await prisma.$transaction([
199
      prisma.careAction.create({
200
        data: {
201
          userId,
202
          type: input.type,
203
          moment: input.moment,
204
          triggerId: input.triggerId,
205
          moodId: input.moodId,
206
          activity: {
207
            create: {
208
              type: act.type,
209
              duration: act.duration,
210
            },
211
          },
212
        },
213
        include: careActionIncludes,
214
      }),
215
    ]);
216

217
    return careAction;
218
  }
219

220
  // Fallback: create without subtype
221
  return prisma.careAction.create({
222
    data: {
223
      userId,
224
      type: input.type,
225
      moment: input.moment,
226
      triggerId: input.triggerId,
227
      moodId: input.moodId,
228
    },
229
    include: careActionIncludes,
230
  });
231
};