diff options
Diffstat (limited to 'api/src/modules/one-time-expenses')
3 files changed, 253 insertions, 0 deletions
diff --git a/api/src/modules/one-time-expenses/one-time-expenses.routes.ts b/api/src/modules/one-time-expenses/one-time-expenses.routes.ts new file mode 100644 index 0000000..0658cfc --- /dev/null +++ b/api/src/modules/one-time-expenses/one-time-expenses.routes.ts @@ -0,0 +1,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; diff --git a/api/src/modules/one-time-expenses/one-time-expenses.schema.ts b/api/src/modules/one-time-expenses/one-time-expenses.schema.ts new file mode 100644 index 0000000..9e32c8d --- /dev/null +++ b/api/src/modules/one-time-expenses/one-time-expenses.schema.ts @@ -0,0 +1,54 @@ +import { z } from 'zod'; + +const CATEGORIES = [ + 'moradia', + 'alimentação', + 'transporte', + 'saúde', + 'educação', + 'lazer', + 'serviços', + 'outros', +] as const; + +export const categoryEnum = z.enum(CATEGORIES); +export const typeEnum = z.enum(['expense', 'income']); + +export const createOneTimeExpenseSchema = z.object({ + name: z.string().min(1, 'Nome é obrigatório').max(100), + amount: z.number().positive('Valor deve ser positivo'), + category: categoryEnum.default('outros'), + type: typeEnum.default('expense'), + /** Data do gasto no formato YYYY-MM-DD. Default: hoje. */ + expense_date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, 'Formato: YYYY-MM-DD') + .optional(), + notes: z.string().max(500).nullable().optional(), +}); + +export const updateOneTimeExpenseSchema = z.object({ + name: z.string().min(1).max(100).optional(), + amount: z.number().positive().optional(), + category: categoryEnum.optional(), + type: typeEnum.optional(), + expense_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + notes: z.string().max(500).nullable().optional(), +}); + +export const oneTimeExpenseParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), + id: z.coerce.number().int().positive(), +}); + +export const oneTimeExpenseUserParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), +}); + +export const oneTimeExpenseQuerySchema = z.object({ + month: z.coerce.number().int().min(1).max(12).optional(), + year: z.coerce.number().int().min(2020).optional(), +}); + +export type CreateOneTimeExpenseInput = z.infer<typeof createOneTimeExpenseSchema>; +export type UpdateOneTimeExpenseInput = z.infer<typeof updateOneTimeExpenseSchema>; diff --git a/api/src/modules/one-time-expenses/one-time-expenses.service.ts b/api/src/modules/one-time-expenses/one-time-expenses.service.ts new file mode 100644 index 0000000..c55640d --- /dev/null +++ b/api/src/modules/one-time-expenses/one-time-expenses.service.ts @@ -0,0 +1,102 @@ +import { and, between, eq } from 'drizzle-orm'; +import { db } from '@/db/client'; +import { oneTimeExpenses } from '@/db/schema'; +import type { + CreateOneTimeExpenseInput, + UpdateOneTimeExpenseInput, +} from './one-time-expenses.schema'; + +export async function findOneTimeExpensesByUser( + userId: number, + filters?: { month?: number; year?: number }, +) { + const conditions = [eq(oneTimeExpenses.user_id, userId)]; + + // Filtra pelo mês/ano usando range de datas no formato YYYY-MM-DD + if (filters?.month !== undefined && filters?.year !== undefined) { + const year = filters.year; + const month = filters.month; + const startDate = `${year}-${String(month).padStart(2, '0')}-01`; + // Último dia do mês: pega o dia 0 do mês seguinte + const lastDay = new Date(year, month, 0).getDate(); + const endDate = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`; + conditions.push(between(oneTimeExpenses.expense_date, startDate, endDate)); + } else if (filters?.year !== undefined) { + const year = filters.year; + conditions.push( + between(oneTimeExpenses.expense_date, `${year}-01-01`, `${year}-12-31`), + ); + } + + return db + .select() + .from(oneTimeExpenses) + .where(and(...conditions)) + .orderBy(oneTimeExpenses.expense_date); +} + +export async function findOneTimeExpenseById(userId: number, id: number) { + const result = await db + .select() + .from(oneTimeExpenses) + .where( + and(eq(oneTimeExpenses.user_id, userId), eq(oneTimeExpenses.id, id)), + ) + .limit(1); + return result[0] ?? null; +} + +export async function createOneTimeExpense( + userId: number, + data: CreateOneTimeExpenseInput, +) { + const [created] = await db + .insert(oneTimeExpenses) + .values({ + user_id: userId, + name: data.name, + amount: data.amount, + category: data.category, + type: data.type, + expense_date: data.expense_date, + notes: data.notes ?? null, + }) + .returning(); + return created; +} + +export async function updateOneTimeExpense( + userId: number, + id: number, + data: UpdateOneTimeExpenseInput, +) { + const now = new Date().toISOString(); + + const [updated] = await db + .update(oneTimeExpenses) + .set({ + ...(data.name !== undefined && { name: data.name }), + ...(data.amount !== undefined && { amount: data.amount }), + ...(data.category !== undefined && { category: data.category }), + ...(data.type !== undefined && { type: data.type }), + ...(data.expense_date !== undefined && { expense_date: data.expense_date }), + ...(data.notes !== undefined && { notes: data.notes }), + updated_at: now, + }) + .where( + and(eq(oneTimeExpenses.user_id, userId), eq(oneTimeExpenses.id, id)), + ) + .returning(); + + return updated ?? null; +} + +export async function deleteOneTimeExpense(userId: number, id: number) { + const [deleted] = await db + .delete(oneTimeExpenses) + .where( + and(eq(oneTimeExpenses.user_id, userId), eq(oneTimeExpenses.id, id)), + ) + .returning(); + return deleted ?? null; +} |