diff options
Diffstat (limited to 'api/src/modules')
17 files changed, 1216 insertions, 0 deletions
diff --git a/api/src/modules/auth/auth.routes.ts b/api/src/modules/auth/auth.routes.ts new file mode 100644 index 0000000..d388694 --- /dev/null +++ b/api/src/modules/auth/auth.routes.ts @@ -0,0 +1,40 @@ +import type { FastifyPluginAsync } from 'fastify'; +import { ZodError } from 'zod'; +import { loginSchema, registerSchema } from './auth.schema'; +import * as authService from './auth.service'; + +const authRoutes: FastifyPluginAsync = async (fastify) => { + fastify.post('/auth/register', async (request, reply) => { + try { + const body = registerSchema.parse(request.body); + const user = await authService.registerUser(body); + + const token = fastify.jwt.sign({ sub: user.id }); + + return reply.status(201).send({ data: { user, token } }); + } catch (err: any) { + if (err instanceof ZodError) { + return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors }); + } + return reply.status(400).send({ error: err.message }); + } + }); + + fastify.post('/auth/login', async (request, reply) => { + try { + const body = loginSchema.parse(request.body); + const user = await authService.loginUser(body); + + const token = fastify.jwt.sign({ sub: user.id }); + + return reply.send({ data: { user, token } }); + } catch (err: any) { + if (err instanceof ZodError) { + return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors }); + } + return reply.status(401).send({ error: err.message }); + } + }); +}; + +export default authRoutes; diff --git a/api/src/modules/auth/auth.schema.ts b/api/src/modules/auth/auth.schema.ts new file mode 100644 index 0000000..550c670 --- /dev/null +++ b/api/src/modules/auth/auth.schema.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; + +export const registerSchema = z.object({ + name: z.string().min(2, 'Nome deve ter pelo menos 2 caracteres'), + email: z.string().email('Email inválido'), + password: z.string().min(6, 'Senha deve ter pelo menos 6 caracteres'), + gross_salary: z.coerce.number().min(0).optional(), +}); + +export const loginSchema = z.object({ + email: z.string().email('Email inválido'), + password: z.string().min(6, 'Senha inválida'), +}); + +export type RegisterData = z.infer<typeof registerSchema>; +export type LoginData = z.infer<typeof loginSchema>; diff --git a/api/src/modules/auth/auth.service.ts b/api/src/modules/auth/auth.service.ts new file mode 100644 index 0000000..c874b05 --- /dev/null +++ b/api/src/modules/auth/auth.service.ts @@ -0,0 +1,41 @@ +import bcrypt from 'bcryptjs'; +import { eq } from 'drizzle-orm'; +import { db } from '../../db/client'; +import { users } from '../../db/schema/users'; +import type { LoginData, RegisterData } from './auth.schema'; + +export async function registerUser(data: RegisterData) { + const existingUser = await db.select().from(users).where(eq(users.email, data.email)).limit(1); + if (existingUser.length > 0) { + throw new Error('Email já está em uso.'); + } + + const salt = await bcrypt.genSalt(10); + const passwordHash = await bcrypt.hash(data.password, salt); + + const [newUser] = await db.insert(users).values({ + name: data.name, + email: data.email, + password_hash: passwordHash, + gross_salary: data.gross_salary || 0, + }).returning(); + + const { password_hash, ...userWithoutPassword } = newUser; + return userWithoutPassword; +} + +export async function loginUser(data: LoginData) { + const [user] = await db.select().from(users).where(eq(users.email, data.email)).limit(1); + + if (!user) { + throw new Error('Email ou senha inválidos.'); + } + + const isValid = await bcrypt.compare(data.password, user.password_hash); + if (!isValid) { + throw new Error('Email ou senha inválidos.'); + } + + const { password_hash, ...userWithoutPassword } = user; + return userWithoutPassword; +} diff --git a/api/src/modules/dashboard/dashboard.routes.ts b/api/src/modules/dashboard/dashboard.routes.ts new file mode 100644 index 0000000..d579ef2 --- /dev/null +++ b/api/src/modules/dashboard/dashboard.routes.ts @@ -0,0 +1,50 @@ +import type { FastifyPluginAsync } from 'fastify'; +import { z } from 'zod'; +import * as dashboardService from './dashboard.service'; + +const dashboardQuerySchema = z.object({ + month: z.coerce.number().int().min(1).max(12).optional(), + year: z.coerce.number().int().min(2020).optional(), +}); + +const dashboardParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), +}); + +const dashboardRoutes: FastifyPluginAsync = async (fastify) => { + /** + * GET /users/:userId/dashboard + * Retorna o resumo financeiro completo do mês. + * + * Query params (opcionais): + * ?month=6&year=2025 → mês/ano específico + * Sem params → mês/ano atual + * + * Resposta: + * - Dados do usuário e salário + * - Lista de gastos recorrentes ativos + * - Lista de gastos avulsos do mês + * - Saldo disponível e percentual comprometido + */ + fastify.get<{ Params: { userId: string }; Querystring: Record<string, string> }>( + '/users/:userId/dashboard', + async (request, reply) => { + const { userId } = dashboardParamsSchema.parse(request.params); + const query = dashboardQuerySchema.parse(request.query); + + const now = new Date(); + const month = query.month ?? now.getMonth() + 1; + const year = query.year ?? now.getFullYear(); + + const data = await dashboardService.getDashboard(userId, month, year); + + if (!data) { + return reply.status(404).send({ error: 'Usuário não encontrado.' }); + } + + return reply.send({ data }); + }, + ); +}; + +export default dashboardRoutes; diff --git a/api/src/modules/dashboard/dashboard.service.ts b/api/src/modules/dashboard/dashboard.service.ts new file mode 100644 index 0000000..78b1d1b --- /dev/null +++ b/api/src/modules/dashboard/dashboard.service.ts @@ -0,0 +1,177 @@ +import { and, eq, gte, lte, sql } from 'drizzle-orm'; +import { db } from '@/db/client'; +import { incomes, oneTimeExpenses, recurringExpenses, users } from '@/db/schema'; +import { calcularSalarioLiquido } from '@/utils/tax-calculator'; + +export interface DashboardData { + user: { + id: number; + name: string; + gross_salary: number; + net_salary_override: number | null; + }; + period: { + month: number; + year: number; + }; + salary: { + gross: number; + calculated_net: number; + effective_net: number; + inss_discount: number; + irrf_discount: number; + has_override: boolean; + }; + expenses: { + recurring_total: number; + one_time_total: number; + total: number; + recurring_list: { id: number; name: string; amount: number; category: string }[]; + one_time_list: { + id: number; + name: string; + amount: number; + category: string; + expense_date: string; + }[]; + }; + balance: { + available: number; + /** Percentual do salário líquido comprometido com despesas (0-100) */ + expense_ratio: number; + }; +} + +export async function getDashboard( + userId: number, + referenceMonth: number, + referenceYear: number, +): Promise<DashboardData | null> { + // 1. Busca o usuário + const [user] = await db + .select() + .from(users) + .where(eq(users.id, userId)) + .limit(1); + + if (!user) return null; + + // 2. Calcula o salário via tabela INSS/IRRF + const taxResult = calcularSalarioLiquido(user.gross_salary); + + // 3. Salário efetivo: usa override do usuário ou o calculado + const effectiveNet = user.net_salary_override ?? taxResult.salarioLiquidoCalculado; + + // 4. Tenta encontrar um registro de renda para o mês/ano pedido + const [incomeRecord] = await db + .select() + .from(incomes) + .where( + and( + eq(incomes.user_id, userId), + eq(incomes.reference_month, referenceMonth), + eq(incomes.reference_year, referenceYear), + ), + ) + .limit(1); + + // Se existir registro de renda para o mês, usa os valores dele + const salaryData = incomeRecord + ? { + gross: incomeRecord.gross_salary, + calculated_net: incomeRecord.calculated_net_salary, + effective_net: incomeRecord.effective_net_salary, + inss_discount: + incomeRecord.gross_salary - incomeRecord.calculated_net_salary - 0, // simplificado + irrf_discount: 0, + has_override: incomeRecord.effective_net_salary !== incomeRecord.calculated_net_salary, + } + : { + gross: user.gross_salary, + calculated_net: taxResult.salarioLiquidoCalculado, + effective_net: effectiveNet, + inss_discount: taxResult.descontoINSS, + irrf_discount: taxResult.descontoIRRF, + has_override: user.net_salary_override !== null, + }; + + // 5. Busca gastos recorrentes ATIVOS e vigentes no mês/ano pedido + const refDateStr = `${referenceYear}-${String(referenceMonth).padStart(2, '0')}-01`; + const lastDay = new Date(referenceYear, referenceMonth, 0).getDate(); + const refDateEndStr = `${referenceYear}-${String(referenceMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`; + + const recurringList = await db + .select() + .from(recurringExpenses) + .where( + and( + eq(recurringExpenses.user_id, userId), + eq(recurringExpenses.is_active, true), + lte(recurringExpenses.starts_at, refDateEndStr), + // ends_at IS NULL ou ends_at >= início do mês + sql`(${recurringExpenses.ends_at} IS NULL OR ${recurringExpenses.ends_at} >= ${refDateStr})`, + ), + ); + + // 6. Busca gastos avulsos do mês/ano pedido + const oneTimeList = await db + .select() + .from(oneTimeExpenses) + .where( + and( + eq(oneTimeExpenses.user_id, userId), + gte(oneTimeExpenses.expense_date, refDateStr), + lte(oneTimeExpenses.expense_date, refDateEndStr), + ), + ) + .orderBy(oneTimeExpenses.expense_date); + + // 7. Calcula totais + const recurringTotal = recurringList.reduce((sum, e) => { + return sum + (e.type === 'income' ? -e.amount : e.amount); + }, 0); + const oneTimeTotal = oneTimeList.reduce((sum, e) => { + return sum + (e.type === 'income' ? -e.amount : e.amount); + }, 0); + const totalExpenses = parseFloat((recurringTotal + oneTimeTotal).toFixed(2)); + const available = parseFloat((salaryData.effective_net - totalExpenses).toFixed(2)); + const expenseRatio = + salaryData.effective_net > 0 + ? parseFloat(((totalExpenses / salaryData.effective_net) * 100).toFixed(1)) + : 0; + + return { + user: { + id: user.id, + name: user.name, + gross_salary: user.gross_salary, + net_salary_override: user.net_salary_override, + }, + period: { month: referenceMonth, year: referenceYear }, + salary: salaryData, + expenses: { + recurring_total: parseFloat(recurringTotal.toFixed(2)), + one_time_total: parseFloat(oneTimeTotal.toFixed(2)), + total: totalExpenses, + recurring_list: recurringList.map((e) => ({ + id: e.id, + name: e.name, + amount: e.amount, + category: e.category, + type: e.type, + })), + one_time_list: oneTimeList.map((e) => ({ + id: e.id, + name: e.name, + amount: e.amount, + category: e.category, + type: e.type, + expense_date: e.expense_date, + })), + }, + balance: { + available, + expense_ratio: expenseRatio, + }, + }; +} diff --git a/api/src/modules/incomes/incomes.routes.ts b/api/src/modules/incomes/incomes.routes.ts new file mode 100644 index 0000000..7932d18 --- /dev/null +++ b/api/src/modules/incomes/incomes.routes.ts @@ -0,0 +1,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; diff --git a/api/src/modules/incomes/incomes.schema.ts b/api/src/modules/incomes/incomes.schema.ts new file mode 100644 index 0000000..cc661fd --- /dev/null +++ b/api/src/modules/incomes/incomes.schema.ts @@ -0,0 +1,38 @@ +import { z } from 'zod'; + +export const createIncomeSchema = z.object({ + gross_salary: z.number().positive('Salário bruto deve ser positivo'), + /** + * Salário líquido efetivo (após override do usuário). + * Deve ser enviado pelo app após o cálculo de INSS/IRRF. + */ + calculated_net_salary: z.number().nonnegative(), + effective_net_salary: z.number().nonnegative(), + reference_month: z.number().int().min(1).max(12), + reference_year: z.number().int().min(2020).max(2100), + description: z.string().max(255).nullable().optional(), +}); + +export const updateIncomeSchema = z.object({ + gross_salary: z.number().positive().optional(), + calculated_net_salary: z.number().nonnegative().optional(), + effective_net_salary: z.number().nonnegative().optional(), + description: z.string().max(255).nullable().optional(), +}); + +export const incomeParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), + id: z.coerce.number().int().positive(), +}); + +export const incomeUserParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), +}); + +export const incomeQuerySchema = z.object({ + month: z.coerce.number().int().min(1).max(12).optional(), + year: z.coerce.number().int().min(2020).optional(), +}); + +export type CreateIncomeInput = z.infer<typeof createIncomeSchema>; +export type UpdateIncomeInput = z.infer<typeof updateIncomeSchema>; diff --git a/api/src/modules/incomes/incomes.service.ts b/api/src/modules/incomes/incomes.service.ts new file mode 100644 index 0000000..0a9ea84 --- /dev/null +++ b/api/src/modules/incomes/incomes.service.ts @@ -0,0 +1,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; +} 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; +} diff --git a/api/src/modules/recurring-expenses/recurring-expenses.routes.ts b/api/src/modules/recurring-expenses/recurring-expenses.routes.ts new file mode 100644 index 0000000..73594e8 --- /dev/null +++ b/api/src/modules/recurring-expenses/recurring-expenses.routes.ts @@ -0,0 +1,108 @@ +import type { FastifyPluginAsync } from 'fastify'; +import { ZodError } from 'zod'; +import { + createRecurringExpenseSchema, + recurringExpenseParamsSchema, + recurringExpenseUserParamsSchema, + updateRecurringExpenseSchema, +} from './recurring-expenses.schema'; +import * as recurringService from './recurring-expenses.service'; + +const recurringExpensesRoutes: FastifyPluginAsync = async (fastify) => { + /** GET /users/:userId/recurring-expenses — Lista todos os gastos recorrentes */ + fastify.get<{ Params: { userId: string } }>( + '/users/:userId/recurring-expenses', + async (request, reply) => { + const { userId } = recurringExpenseUserParamsSchema.parse(request.params); + const result = await recurringService.findRecurringExpensesByUser(userId); + return reply.send({ data: result }); + }, + ); + + /** GET /users/:userId/recurring-expenses/:id — Busca um gasto recorrente específico */ + fastify.get<{ Params: { userId: string; id: string } }>( + '/users/:userId/recurring-expenses/:id', + async (request, reply) => { + const { userId, id } = recurringExpenseParamsSchema.parse(request.params); + const expense = await recurringService.findRecurringExpenseById(userId, id); + + if (!expense) { + return reply.status(404).send({ error: 'Gasto recorrente não encontrado.' }); + } + return reply.send({ data: expense }); + }, + ); + + /** POST /users/:userId/recurring-expenses — Cadastra um novo gasto fixo */ + fastify.post<{ Params: { userId: string } }>( + '/users/:userId/recurring-expenses', + async (request, reply) => { + try { + const { userId } = recurringExpenseUserParamsSchema.parse(request.params); + const body = createRecurringExpenseSchema.parse(request.body); + const expense = await recurringService.createRecurringExpense(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/recurring-expenses/:id — Atualiza um gasto recorrente */ + fastify.put<{ Params: { userId: string; id: string } }>( + '/users/:userId/recurring-expenses/:id', + async (request, reply) => { + try { + const { userId, id } = recurringExpenseParamsSchema.parse(request.params); + const body = updateRecurringExpenseSchema.parse(request.body); + const expense = await recurringService.updateRecurringExpense(userId, id, body); + + if (!expense) { + return reply.status(404).send({ error: 'Gasto recorrente 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; + } + }, + ); + + /** + * PATCH /users/:userId/recurring-expenses/:id/toggle + * Ativa ou desativa um gasto recorrente sem precisar deletar. + */ + fastify.patch<{ Params: { userId: string; id: string } }>( + '/users/:userId/recurring-expenses/:id/toggle', + async (request, reply) => { + const { userId, id } = recurringExpenseParamsSchema.parse(request.params); + const expense = await recurringService.toggleRecurringExpense(userId, id); + + if (!expense) { + return reply.status(404).send({ error: 'Gasto recorrente não encontrado.' }); + } + return reply.send({ data: expense }); + }, + ); + + /** DELETE /users/:userId/recurring-expenses/:id — Remove um gasto recorrente */ + fastify.delete<{ Params: { userId: string; id: string } }>( + '/users/:userId/recurring-expenses/:id', + async (request, reply) => { + const { userId, id } = recurringExpenseParamsSchema.parse(request.params); + const deleted = await recurringService.deleteRecurringExpense(userId, id); + + if (!deleted) { + return reply.status(404).send({ error: 'Gasto recorrente não encontrado.' }); + } + return reply.status(200).send({ data: deleted, message: 'Gasto recorrente removido com sucesso.' }); + }, + ); +}; + +export default recurringExpensesRoutes; diff --git a/api/src/modules/recurring-expenses/recurring-expenses.schema.ts b/api/src/modules/recurring-expenses/recurring-expenses.schema.ts new file mode 100644 index 0000000..8f9d473 --- /dev/null +++ b/api/src/modules/recurring-expenses/recurring-expenses.schema.ts @@ -0,0 +1,49 @@ +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 createRecurringExpenseSchema = 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'), + due_day: z.number().int().min(1).max(31).nullable().optional(), + is_active: z.boolean().default(true), + starts_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Formato: YYYY-MM-DD').optional(), + ends_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Formato: YYYY-MM-DD').nullable().optional(), +}); + +export const updateRecurringExpenseSchema = z.object({ + name: z.string().min(1).max(100).optional(), + amount: z.number().positive().optional(), + category: categoryEnum.optional(), + type: typeEnum.optional(), + due_day: z.number().int().min(1).max(31).nullable().optional(), + is_active: z.boolean().optional(), + starts_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + ends_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(), +}); + +export const recurringExpenseParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), + id: z.coerce.number().int().positive(), +}); + +export const recurringExpenseUserParamsSchema = z.object({ + userId: z.coerce.number().int().positive(), +}); + +export type CreateRecurringExpenseInput = z.infer<typeof createRecurringExpenseSchema>; +export type UpdateRecurringExpenseInput = z.infer<typeof updateRecurringExpenseSchema>; diff --git a/api/src/modules/recurring-expenses/recurring-expenses.service.ts b/api/src/modules/recurring-expenses/recurring-expenses.service.ts new file mode 100644 index 0000000..2bb9720 --- /dev/null +++ b/api/src/modules/recurring-expenses/recurring-expenses.service.ts @@ -0,0 +1,115 @@ +import { and, eq } from 'drizzle-orm'; +import { db } from '@/db/client'; +import { recurringExpenses } from '@/db/schema'; +import type { + CreateRecurringExpenseInput, + UpdateRecurringExpenseInput, +} from './recurring-expenses.schema'; + +export async function findRecurringExpensesByUser(userId: number) { + return db + .select() + .from(recurringExpenses) + .where(eq(recurringExpenses.user_id, userId)) + .orderBy(recurringExpenses.name); +} + +export async function findRecurringExpenseById(userId: number, id: number) { + const result = await db + .select() + .from(recurringExpenses) + .where( + and( + eq(recurringExpenses.user_id, userId), + eq(recurringExpenses.id, id), + ), + ) + .limit(1); + return result[0] ?? null; +} + +export async function createRecurringExpense( + userId: number, + data: CreateRecurringExpenseInput, +) { + const [created] = await db + .insert(recurringExpenses) + .values({ + user_id: userId, + name: data.name, + amount: data.amount, + category: data.category, + type: data.type, + due_day: data.due_day ?? null, + is_active: data.is_active, + starts_at: data.starts_at, + ends_at: data.ends_at ?? null, + }) + .returning(); + return created; +} + +export async function updateRecurringExpense( + userId: number, + id: number, + data: UpdateRecurringExpenseInput, +) { + const now = new Date().toISOString(); + + const [updated] = await db + .update(recurringExpenses) + .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.due_day !== undefined && { due_day: data.due_day }), + ...(data.is_active !== undefined && { is_active: data.is_active }), + ...(data.starts_at !== undefined && { starts_at: data.starts_at }), + ...(data.ends_at !== undefined && { ends_at: data.ends_at }), + updated_at: now, + }) + .where( + and( + eq(recurringExpenses.user_id, userId), + eq(recurringExpenses.id, id), + ), + ) + .returning(); + + return updated ?? null; +} + +export async function toggleRecurringExpense(userId: number, id: number) { + const expense = await findRecurringExpenseById(userId, id); + if (!expense) return null; + + const [updated] = await db + .update(recurringExpenses) + .set({ + is_active: !expense.is_active, + updated_at: new Date().toISOString(), + }) + .where( + and( + eq(recurringExpenses.user_id, userId), + eq(recurringExpenses.id, id), + ), + ) + .returning(); + + return updated ?? null; +} + +export async function deleteRecurringExpense(userId: number, id: number) { + const [deleted] = await db + .delete(recurringExpenses) + .where( + and( + eq(recurringExpenses.user_id, userId), + eq(recurringExpenses.id, id), + ), + ) + .returning(); + return deleted ?? null; +} diff --git a/api/src/modules/users/users.routes.ts b/api/src/modules/users/users.routes.ts new file mode 100644 index 0000000..28cf584 --- /dev/null +++ b/api/src/modules/users/users.routes.ts @@ -0,0 +1,73 @@ +import type { FastifyPluginAsync } from 'fastify'; +import { ZodError } from 'zod'; +import { + createUserSchema, + updateUserSchema, + userParamsSchema, +} from './users.schema'; +import * as usersService from './users.service'; + +const usersRoutes: FastifyPluginAsync = async (fastify) => { + /** GET /users — Lista todos os usuários */ + fastify.get('/users', async (_request, reply) => { + const result = await usersService.findAllUsers(); + return reply.send({ data: result }); + }); + + /** GET /users/:id — Busca um usuário pelo ID */ + fastify.get<{ Params: { id: string } }>('/users/:id', async (request, reply) => { + const { id } = userParamsSchema.parse(request.params); + const user = await usersService.findUserById(id); + + if (!user) { + return reply.status(404).send({ error: 'Usuário não encontrado.' }); + } + return reply.send({ data: user }); + }); + + /** POST /users — Cria um novo usuário */ + fastify.post('/users', async (request, reply) => { + try { + const body = createUserSchema.parse(request.body); + const user = await usersService.createUser(body); + return reply.status(201).send({ data: user }); + } catch (err) { + if (err instanceof ZodError) { + return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors }); + } + throw err; + } + }); + + /** PUT /users/:id — Atualiza um usuário (incluindo salário e override) */ + fastify.put<{ Params: { id: string } }>('/users/:id', async (request, reply) => { + try { + const { id } = userParamsSchema.parse(request.params); + const body = updateUserSchema.parse(request.body); + const user = await usersService.updateUser(id, body); + + if (!user) { + return reply.status(404).send({ error: 'Usuário não encontrado.' }); + } + return reply.send({ data: user }); + } catch (err) { + if (err instanceof ZodError) { + return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors }); + } + throw err; + } + }); + + /** DELETE /users/:id — Remove um usuário (cascade nos gastos) */ + fastify.delete<{ Params: { id: string } }>('/users/:id', async (request, reply) => { + const { id } = userParamsSchema.parse(request.params); + const deleted = await usersService.deleteUser(id); + + if (!deleted) { + return reply.status(404).send({ error: 'Usuário não encontrado.' }); + } + return reply.status(200).send({ data: deleted, message: 'Usuário removido com sucesso.' }); + }); +}; + +export default usersRoutes; diff --git a/api/src/modules/users/users.schema.ts b/api/src/modules/users/users.schema.ts new file mode 100644 index 0000000..62ab514 --- /dev/null +++ b/api/src/modules/users/users.schema.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; + +export const createUserSchema = z.object({ + name: z.string().min(1, 'Nome é obrigatório').max(100), + gross_salary: z.number().nonnegative('Salário bruto deve ser >= 0'), + net_salary_override: z.number().nonnegative().nullable().optional(), +}); + +export const updateUserSchema = z.object({ + name: z.string().min(1).max(100).optional(), + gross_salary: z.number().nonnegative().optional(), + /** + * Envia `null` para limpar o override e voltar ao valor calculado automaticamente. + */ + net_salary_override: z.number().nonnegative().nullable().optional(), +}); + +export const userParamsSchema = z.object({ + id: z.coerce.number().int().positive(), +}); + +export type CreateUserInput = z.infer<typeof createUserSchema>; +export type UpdateUserInput = z.infer<typeof updateUserSchema>; diff --git a/api/src/modules/users/users.service.ts b/api/src/modules/users/users.service.ts new file mode 100644 index 0000000..a0fda40 --- /dev/null +++ b/api/src/modules/users/users.service.ts @@ -0,0 +1,53 @@ +import { eq } from 'drizzle-orm'; +import { db } from '@/db/client'; +import { users } from '@/db/schema'; +import type { CreateUserInput, UpdateUserInput } from './users.schema'; + +export async function findAllUsers() { + return db.select().from(users); +} + +export async function findUserById(id: number) { + const result = await db.select().from(users).where(eq(users.id, id)).limit(1); + return result[0] ?? null; +} + +export async function createUser(data: CreateUserInput) { + const [created] = await db + .insert(users) + .values({ + name: data.name, + gross_salary: data.gross_salary, + net_salary_override: data.net_salary_override ?? null, + }) + .returning(); + return created; +} + +export async function updateUser(id: number, data: UpdateUserInput) { + const now = new Date().toISOString(); + + const [updated] = await db + .update(users) + .set({ + ...(data.name !== undefined && { name: data.name }), + ...(data.gross_salary !== undefined && { gross_salary: data.gross_salary }), + // Permite setar null explicitamente (para remover o override) + ...(data.net_salary_override !== undefined && { + net_salary_override: data.net_salary_override, + }), + updated_at: now, + }) + .where(eq(users.id, id)) + .returning(); + + return updated ?? null; +} + +export async function deleteUser(id: number) { + const [deleted] = await db + .delete(users) + .where(eq(users.id, id)) + .returning(); + return deleted ?? null; +} |