aboutsummaryrefslogtreecommitdiff
path: root/api/src/modules/one-time-expenses/one-time-expenses.routes.ts
blob: 0658cfc158d5ddb9ce02ba394fa63e462e001cb2 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import type { FastifyPluginAsync } from 'fastify';
import { ZodError } from 'zod';
import {
  createOneTimeExpenseSchema,
  oneTimeExpenseParamsSchema,
  oneTimeExpenseQuerySchema,
  oneTimeExpenseUserParamsSchema,
  updateOneTimeExpenseSchema,
} from './one-time-expenses.schema';
import * as oneTimeService from './one-time-expenses.service';

const oneTimeExpensesRoutes: FastifyPluginAsync = async (fastify) => {
  /**
   * GET /users/:userId/one-time-expenses
   * Lista gastos avulsos do usuário.
   * Query params: ?month=6&year=2025
   */
  fastify.get<{ Params: { userId: string }; Querystring: Record<string, string> }>(
    '/users/:userId/one-time-expenses',
    async (request, reply) => {
      const { userId } = oneTimeExpenseUserParamsSchema.parse(request.params);
      const query = oneTimeExpenseQuerySchema.parse(request.query);
      const result = await oneTimeService.findOneTimeExpensesByUser(userId, query);
      return reply.send({ data: result });
    },
  );

  /** GET /users/:userId/one-time-expenses/:id — Busca um gasto avulso específico */
  fastify.get<{ Params: { userId: string; id: string } }>(
    '/users/:userId/one-time-expenses/:id',
    async (request, reply) => {
      const { userId, id } = oneTimeExpenseParamsSchema.parse(request.params);
      const expense = await oneTimeService.findOneTimeExpenseById(userId, id);

      if (!expense) {
        return reply.status(404).send({ error: 'Gasto avulso não encontrado.' });
      }
      return reply.send({ data: expense });
    },
  );

  /** POST /users/:userId/one-time-expenses — Adiciona um gasto avulso */
  fastify.post<{ Params: { userId: string } }>(
    '/users/:userId/one-time-expenses',
    async (request, reply) => {
      try {
        const { userId } = oneTimeExpenseUserParamsSchema.parse(request.params);
        const body = createOneTimeExpenseSchema.parse(request.body);
        const expense = await oneTimeService.createOneTimeExpense(userId, body);
        return reply.status(201).send({ data: expense });
      } catch (err) {
        if (err instanceof ZodError) {
          return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors });
        }
        throw err;
      }
    },
  );

  /** PUT /users/:userId/one-time-expenses/:id — Atualiza um gasto avulso */
  fastify.put<{ Params: { userId: string; id: string } }>(
    '/users/:userId/one-time-expenses/:id',
    async (request, reply) => {
      try {
        const { userId, id } = oneTimeExpenseParamsSchema.parse(request.params);
        const body = updateOneTimeExpenseSchema.parse(request.body);
        const expense = await oneTimeService.updateOneTimeExpense(userId, id, body);

        if (!expense) {
          return reply.status(404).send({ error: 'Gasto avulso não encontrado.' });
        }
        return reply.send({ data: expense });
      } catch (err) {
        if (err instanceof ZodError) {
          return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors });
        }
        throw err;
      }
    },
  );

  /** DELETE /users/:userId/one-time-expenses/:id — Remove um gasto avulso */
  fastify.delete<{ Params: { userId: string; id: string } }>(
    '/users/:userId/one-time-expenses/:id',
    async (request, reply) => {
      const { userId, id } = oneTimeExpenseParamsSchema.parse(request.params);
      const deleted = await oneTimeService.deleteOneTimeExpense(userId, id);

      if (!deleted) {
        return reply.status(404).send({ error: 'Gasto avulso não encontrado.' });
      }
      return reply.status(200).send({ data: deleted, message: 'Gasto avulso removido com sucesso.' });
    },
  );
};

export default oneTimeExpensesRoutes;