| 1 | import {
|
| 2 | Activity,
|
| 3 | Appointment,
|
| 4 | CareAction,
|
| 5 | MedicineLog,
|
| 6 | MedicineRegimen,
|
| 7 | Mood,
|
| 8 | MoodComponent,
|
| 9 | SleepRecord,
|
| 10 | Trigger,
|
| 11 | TriggerMoodLink,
|
| 12 | User,
|
| 13 | } from "@prisma/client";
|
| 14 |
|
| 15 | import { prisma } from "@app/lib/prisma";
|
| 16 | import { findUserById } from "@app/services/user.service";
|
| 17 |
|
| 18 | export type ExportData = {
|
| 19 | user: User;
|
| 20 | moods: Mood[];
|
| 21 | moodComponents: MoodComponent[];
|
| 22 | sleepRecords: SleepRecord[];
|
| 23 | triggers: Trigger[];
|
| 24 | triggerMoodLinks: TriggerMoodLink[];
|
| 25 | careActions: CareAction[];
|
| 26 | medicineLogs: MedicineLog[];
|
| 27 | appointments: Appointment[];
|
| 28 | activities: Activity[];
|
| 29 | medicineRegimens: MedicineRegimen[];
|
| 30 | };
|
| 31 |
|
| 32 | export async function gatherExportData(userId: number): Promise<ExportData> {
|
| 33 | const user = await findUserById(userId);
|
| 34 |
|
| 35 | if (!user) {
|
| 36 | throw new Error(`Usuário ${userId} não encontrado para exportação`);
|
| 37 | }
|
| 38 |
|
| 39 | const [
|
| 40 | moods,
|
| 41 | sleepRecords,
|
| 42 | triggers,
|
| 43 | triggerMoodLinks,
|
| 44 | careActions,
|
| 45 | medicineRegimens,
|
| 46 | ] = await Promise.all([
|
| 47 | prisma.mood.findMany({
|
| 48 | where: { userId },
|
| 49 | include: { moodComponents: true },
|
| 50 | orderBy: { moment: "asc" },
|
| 51 | }),
|
| 52 | prisma.sleepRecord.findMany({
|
| 53 | where: { userId },
|
| 54 | orderBy: { date: "asc" },
|
| 55 | }),
|
| 56 | prisma.trigger.findMany({
|
| 57 | where: { userId },
|
| 58 | orderBy: { moment: "asc" },
|
| 59 | }),
|
| 60 | prisma.triggerMoodLink.findMany({
|
| 61 | where: { trigger: { userId } },
|
| 62 | orderBy: { linkedAt: "asc" },
|
| 63 | }),
|
| 64 | prisma.careAction.findMany({
|
| 65 | where: { userId },
|
| 66 | include: { medicineLog: true, appointment: true, activity: true },
|
| 67 | orderBy: { moment: "asc" },
|
| 68 | }),
|
| 69 | prisma.medicineRegimen.findMany({
|
| 70 | where: { userId },
|
| 71 | orderBy: { createdAt: "asc" },
|
| 72 | }),
|
| 73 | ]);
|
| 74 |
|
| 75 | return {
|
| 76 | user,
|
| 77 | moods,
|
| 78 | moodComponents: moods.flatMap((mood) => mood.moodComponents),
|
| 79 | sleepRecords,
|
| 80 | triggers,
|
| 81 | triggerMoodLinks,
|
| 82 | careActions,
|
| 83 | medicineLogs: careActions.flatMap((action) =>
|
| 84 | action.medicineLog ? [action.medicineLog] : [],
|
| 85 | ),
|
| 86 | appointments: careActions.flatMap((action) =>
|
| 87 | action.appointment ? [action.appointment] : [],
|
| 88 | ),
|
| 89 | activities: careActions.flatMap((action) =>
|
| 90 | action.activity ? [action.activity] : [],
|
| 91 | ),
|
| 92 | medicineRegimens,
|
| 93 | };
|
| 94 | }
|