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