eletrotupi / tcc/ api/src/services/insight.service.tsb36ca93521cd90a436cca219f26ba8cb906448f4
1.0 KB | 40 lines Raw
1
import { prisma } from "@app/lib/prisma";
2
import { appDayWindow } from "@app/lib/queue/processors/insights/utils";
3
import { Prisma, Insight, InsightType, InsightPeriod } from "@prisma/client";
4

5
export const getInsightsByUserId = async (
6
  userId: number,
7
  params?: {
8
    type?: InsightType;
9
    period?: InsightPeriod;
10
    limit?: number;
11
    day?: Date;
12
  },
13
): Promise<Insight[]> => {
14
  const where: Prisma.InsightWhereInput = {
15
    userId,
16
    ...(params?.type && { type: params.type }),
17
    ...(params?.period && { period: params.period }),
18
  };
19

20
  if (params?.day) {
21
    const { start, end } = appDayWindow(params.day);
22
    where.periodStart = { gte: start, lt: end };
23
  }
24

25
  return prisma.insight.findMany({
26
    where,
27
    orderBy: { generatedAt: "desc" },
28
    take: params?.limit ?? 10,
29
  });
30
};
31

32
export const getLatestInsightByType = async (
33
  userId: number,
34
  type: InsightType,
35
): Promise<Insight | null> => {
36
  return prisma.insight.findFirst({
37
    where: { userId, type },
38
    orderBy: { generatedAt: "desc" },
39
  });
40
};