aboutsummaryrefslogtreecommitdiff
path: root/api/src/modules/incomes/incomes.service.ts
blob: 0a9ea842c8911cb37d3759248b5358111715c2db (plain)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { and, eq } from 'drizzle-orm';
import { db } from '@/db/client';
import { incomes } from '@/db/schema';
import type { CreateIncomeInput, UpdateIncomeInput } from './incomes.schema';

export async function findIncomesByUser(
  userId: number,
  filters?: { month?: number; year?: number },
) {
  const conditions = [eq(incomes.user_id, userId)];

  if (filters?.month !== undefined) {
    conditions.push(eq(incomes.reference_month, filters.month));
  }
  if (filters?.year !== undefined) {
    conditions.push(eq(incomes.reference_year, filters.year));
  }

  return db
    .select()
    .from(incomes)
    .where(and(...conditions))
    .orderBy(incomes.reference_year, incomes.reference_month);
}

export async function findIncomeById(userId: number, id: number) {
  const result = await db
    .select()
    .from(incomes)
    .where(and(eq(incomes.user_id, userId), eq(incomes.id, id)))
    .limit(1);
  return result[0] ?? null;
}

export async function createIncome(userId: number, data: CreateIncomeInput) {
  const [created] = await db
    .insert(incomes)
    .values({
      user_id: userId,
      gross_salary: data.gross_salary,
      calculated_net_salary: data.calculated_net_salary,
      effective_net_salary: data.effective_net_salary,
      reference_month: data.reference_month,
      reference_year: data.reference_year,
      description: data.description ?? null,
    })
    .returning();
  return created;
}

export async function updateIncome(
  userId: number,
  id: number,
  data: UpdateIncomeInput,
) {
  const now = new Date().toISOString();

  const [updated] = await db
    .update(incomes)
    .set({
      ...(data.gross_salary !== undefined && { gross_salary: data.gross_salary }),
      ...(data.calculated_net_salary !== undefined && {
        calculated_net_salary: data.calculated_net_salary,
      }),
      ...(data.effective_net_salary !== undefined && {
        effective_net_salary: data.effective_net_salary,
      }),
      ...(data.description !== undefined && { description: data.description }),
      updated_at: now,
    })
    .where(and(eq(incomes.user_id, userId), eq(incomes.id, id)))
    .returning();

  return updated ?? null;
}

export async function deleteIncome(userId: number, id: number) {
  const [deleted] = await db
    .delete(incomes)
    .where(and(eq(incomes.user_id, userId), eq(incomes.id, id)))
    .returning();
  return deleted ?? null;
}