aboutsummaryrefslogtreecommitdiff
path: root/api/src/modules/incomes/incomes.routes.ts
blob: 7932d18b1cc7d7b24d3940a1edabe15aedd37b98 (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 {
  createIncomeSchema,
  incomeParamsSchema,
  incomeQuerySchema,
  incomeUserParamsSchema,
  updateIncomeSchema,
} from './incomes.schema';
import * as incomesService from './incomes.service';

const incomesRoutes: FastifyPluginAsync = async (fastify) => {
  /**
   * GET /users/:userId/incomes
   * Lista todas as rendas de um usuário.
   * Query params: ?month=6&year=2025
   */
  fastify.get<{ Params: { userId: string }; Querystring: Record<string, string> }>(
    '/users/:userId/incomes',
    async (request, reply) => {
      const { userId } = incomeUserParamsSchema.parse(request.params);
      const query = incomeQuerySchema.parse(request.query);
      const result = await incomesService.findIncomesByUser(userId, query);
      return reply.send({ data: result });
    },
  );

  /** GET /users/:userId/incomes/:id — Busca uma renda específica */
  fastify.get<{ Params: { userId: string; id: string } }>(
    '/users/:userId/incomes/:id',
    async (request, reply) => {
      const { userId, id } = incomeParamsSchema.parse(request.params);
      const income = await incomesService.findIncomeById(userId, id);

      if (!income) {
        return reply.status(404).send({ error: 'Renda não encontrada.' });
      }
      return reply.send({ data: income });
    },
  );

  /** POST /users/:userId/incomes — Registra a renda de um mês */
  fastify.post<{ Params: { userId: string } }>(
    '/users/:userId/incomes',
    async (request, reply) => {
      try {
        const { userId } = incomeUserParamsSchema.parse(request.params);
        const body = createIncomeSchema.parse(request.body);
        const income = await incomesService.createIncome(userId, body);
        return reply.status(201).send({ data: income });
      } catch (err) {
        if (err instanceof ZodError) {
          return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors });
        }
        throw err;
      }
    },
  );

  /** PUT /users/:userId/incomes/:id — Atualiza uma renda */
  fastify.put<{ Params: { userId: string; id: string } }>(
    '/users/:userId/incomes/:id',
    async (request, reply) => {
      try {
        const { userId, id } = incomeParamsSchema.parse(request.params);
        const body = updateIncomeSchema.parse(request.body);
        const income = await incomesService.updateIncome(userId, id, body);

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

  /** DELETE /users/:userId/incomes/:id — Remove uma renda */
  fastify.delete<{ Params: { userId: string; id: string } }>(
    '/users/:userId/incomes/:id',
    async (request, reply) => {
      const { userId, id } = incomeParamsSchema.parse(request.params);
      const deleted = await incomesService.deleteIncome(userId, id);

      if (!deleted) {
        return reply.status(404).send({ error: 'Renda não encontrada.' });
      }
      return reply.status(200).send({ data: deleted, message: 'Renda removida com sucesso.' });
    },
  );
};

export default incomesRoutes;