aboutsummaryrefslogtreecommitdiff
path: root/api/src
diff options
context:
space:
mode:
authorLucas Faria Mendes <lucas.fariamo08@gmail.com>2026-08-16 23:17:42 +0000
committerLucas Faria Mendes <lucas.fariamo08@gmail.com>2026-08-16 23:17:42 +0000
commit375482e654a01615683867e732ac9e458c7cbe74 (patch)
tree12d1b31b8deb6bf8590bcdbc2cfb52dcc553e006 /api/src
parent2c2dfba45357bbd205a59145ae55a2779c911ae0 (diff)
downloadyaba-master.tar.gz
yaba-master.zip
feat: upload yaba srcHEADmaster
Signed-off-by: Lucas Faria Mendes <lucas.fariamo08@gmail.com>
Diffstat (limited to 'api/src')
-rw-r--r--api/src/db/client.ts23
-rw-r--r--api/src/db/schema/incomes.ts51
-rw-r--r--api/src/db/schema/index.ts11
-rw-r--r--api/src/db/schema/one-time-expenses.ts53
-rw-r--r--api/src/db/schema/recurring-expenses.ts69
-rw-r--r--api/src/db/schema/users.ts37
-rw-r--r--api/src/modules/auth/auth.routes.ts40
-rw-r--r--api/src/modules/auth/auth.schema.ts16
-rw-r--r--api/src/modules/auth/auth.service.ts41
-rw-r--r--api/src/modules/dashboard/dashboard.routes.ts50
-rw-r--r--api/src/modules/dashboard/dashboard.service.ts177
-rw-r--r--api/src/modules/incomes/incomes.routes.ts97
-rw-r--r--api/src/modules/incomes/incomes.schema.ts38
-rw-r--r--api/src/modules/incomes/incomes.service.ts83
-rw-r--r--api/src/modules/one-time-expenses/one-time-expenses.routes.ts97
-rw-r--r--api/src/modules/one-time-expenses/one-time-expenses.schema.ts54
-rw-r--r--api/src/modules/one-time-expenses/one-time-expenses.service.ts102
-rw-r--r--api/src/modules/recurring-expenses/recurring-expenses.routes.ts108
-rw-r--r--api/src/modules/recurring-expenses/recurring-expenses.schema.ts49
-rw-r--r--api/src/modules/recurring-expenses/recurring-expenses.service.ts115
-rw-r--r--api/src/modules/users/users.routes.ts73
-rw-r--r--api/src/modules/users/users.schema.ts23
-rw-r--r--api/src/modules/users/users.service.ts53
-rw-r--r--api/src/plugins/cors.ts18
-rw-r--r--api/src/server.ts89
-rw-r--r--api/src/utils/tax-calculator.ts111
26 files changed, 1678 insertions, 0 deletions
diff --git a/api/src/db/client.ts b/api/src/db/client.ts
new file mode 100644
index 0000000..5e9673f
--- /dev/null
+++ b/api/src/db/client.ts
@@ -0,0 +1,23 @@
+import { Database } from 'bun:sqlite';
+import { drizzle } from 'drizzle-orm/bun-sqlite';
+import * as schema from './schema';
+
+/**
+ * Instância única do banco de dados SQLite via Drizzle ORM.
+ * Utiliza o driver nativo do Bun para máxima performance.
+ *
+ * O caminho do arquivo pode ser configurado via variável de ambiente DATABASE_URL.
+ * Quando não definida, usa 'yaba.db' na raiz do projeto.
+ */
+const sqlite = new Database(process.env.DATABASE_URL ?? 'yaba.db');
+
+/**
+ * Habilita WAL mode para melhor performance em leituras concorrentes.
+ * @see https://www.sqlite.org/wal.html
+ */
+sqlite.exec('PRAGMA journal_mode = WAL;');
+sqlite.exec('PRAGMA foreign_keys = ON;');
+
+export const db = drizzle(sqlite, { schema });
+
+export type DB = typeof db;
diff --git a/api/src/db/schema/incomes.ts b/api/src/db/schema/incomes.ts
new file mode 100644
index 0000000..f502cb9
--- /dev/null
+++ b/api/src/db/schema/incomes.ts
@@ -0,0 +1,51 @@
+import { sql } from 'drizzle-orm';
+import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+import { users } from './users';
+
+/**
+ * Tabela de rendas/salários.
+ * Armazena o histórico de salários por mês/ano, permitindo que o usuário
+ * tenha registros diferentes para cada período (ex: aumento de salário em julho).
+ */
+export const incomes = sqliteTable('incomes', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+
+ user_id: integer('user_id')
+ .notNull()
+ .references(() => users.id, { onDelete: 'cascade' }),
+
+ /** Salário bruto do período (em R$) */
+ gross_salary: real('gross_salary').notNull(),
+
+ /**
+ * Salário líquido calculado automaticamente pelo app (INSS + IRRF).
+ * Armazenado para fins de histórico e auditoria.
+ */
+ calculated_net_salary: real('calculated_net_salary').notNull(),
+
+ /**
+ * Salário líquido efetivo usado no cálculo do saldo.
+ * Pode diferir do calculado caso o usuário tenha feito um override manual.
+ */
+ effective_net_salary: real('effective_net_salary').notNull(),
+
+ /** Mês de referência (1-12) */
+ reference_month: integer('reference_month').notNull(),
+
+ /** Ano de referência (ex: 2025) */
+ reference_year: integer('reference_year').notNull(),
+
+ /** Observações opcionais (ex: "13º salário", "PLR") */
+ description: text('description'),
+
+ created_at: text('created_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+
+ updated_at: text('updated_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+});
+
+export type Income = typeof incomes.$inferSelect;
+export type NewIncome = typeof incomes.$inferInsert;
diff --git a/api/src/db/schema/index.ts b/api/src/db/schema/index.ts
new file mode 100644
index 0000000..72cf261
--- /dev/null
+++ b/api/src/db/schema/index.ts
@@ -0,0 +1,11 @@
+/**
+ * Ponto central de exportação de todos os schemas do Drizzle.
+ * Importe sempre a partir deste arquivo para evitar imports circulares.
+ *
+ * Uso:
+ * import { users, incomes, recurringExpenses, oneTimeExpenses } from '@/db/schema';
+ */
+export * from './users';
+export * from './incomes';
+export * from './recurring-expenses';
+export * from './one-time-expenses';
diff --git a/api/src/db/schema/one-time-expenses.ts b/api/src/db/schema/one-time-expenses.ts
new file mode 100644
index 0000000..10c9c01
--- /dev/null
+++ b/api/src/db/schema/one-time-expenses.ts
@@ -0,0 +1,53 @@
+import { sql } from 'drizzle-orm';
+import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+import { users } from './users';
+
+/**
+ * Tabela de gastos avulsos (despesas pontuais).
+ * Ex: Cinema, iFood, Uber, Farmácia.
+ * Cada registro representa um gasto único em uma data específica.
+ * O valor é subtraído do saldo disponível do mês em que a despesa ocorreu.
+ */
+export const oneTimeExpenses = sqliteTable('one_time_expenses', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+
+ user_id: integer('user_id')
+ .notNull()
+ .references(() => users.id, { onDelete: 'cascade' }),
+
+ /** Nome/descrição do gasto (ex: "Cinema com a família", "iFood jantar") */
+ name: text('name').notNull(),
+
+ /** Valor do gasto (em R$) */
+ amount: real('amount').notNull(),
+
+ /**
+ * Categoria do gasto para organização e futuros relatórios.
+ * Ex: "alimentação", "lazer", "saúde", "transporte", "educação", "outros"
+ */
+ category: text('category').notNull().default('outros'),
+
+ /** Tipo do lançamento: 'expense' (despesa) ou 'income' (receita) */
+ type: text('type').notNull().default('expense'),
+
+ /**
+ * Data em que o gasto ocorreu.
+ * Formato ISO 8601 (YYYY-MM-DD). Usado para atribuir o gasto ao mês correto.
+ * Default: data atual no momento da inserção.
+ */
+ expense_date: text('expense_date').notNull().default(sql`(date('now'))`),
+
+ /** Observações opcionais (ex: "Split 50/50 com João") */
+ notes: text('notes'),
+
+ created_at: text('created_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+
+ updated_at: text('updated_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+});
+
+export type OneTimeExpense = typeof oneTimeExpenses.$inferSelect;
+export type NewOneTimeExpense = typeof oneTimeExpenses.$inferInsert;
diff --git a/api/src/db/schema/recurring-expenses.ts b/api/src/db/schema/recurring-expenses.ts
new file mode 100644
index 0000000..8a0a1df
--- /dev/null
+++ b/api/src/db/schema/recurring-expenses.ts
@@ -0,0 +1,69 @@
+import { sql } from 'drizzle-orm';
+import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+import { users } from './users';
+
+/**
+ * Tabela de gastos recorrentes (despesas fixas mensais).
+ * Ex: Aluguel, Internet, Streaming, Academia.
+ * Estes gastos são deduzidos automaticamente do saldo todo mês,
+ * sem precisar recadastrar.
+ */
+export const recurringExpenses = sqliteTable('recurring_expenses', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+
+ user_id: integer('user_id')
+ .notNull()
+ .references(() => users.id, { onDelete: 'cascade' }),
+
+ /** Nome/descrição do gasto (ex: "Aluguel", "Netflix") */
+ name: text('name').notNull(),
+
+ /** Valor mensal do gasto (em R$) */
+ amount: real('amount').notNull(),
+
+ /**
+ * Categoria do gasto para organização e futuros relatórios.
+ * Ex: "moradia", "alimentação", "lazer", "saúde", "transporte", "educação", "outros"
+ */
+ category: text('category').notNull().default('outros'),
+
+ /** Tipo do lançamento: 'expense' (despesa) ou 'income' (receita) */
+ type: text('type').notNull().default('expense'),
+
+ /**
+ * Dia do mês em que a despesa costuma vencer (1-31).
+ * Opcional — usado apenas para informação ao usuário.
+ */
+ due_day: integer('due_day'),
+
+ /**
+ * Indica se o gasto está ativo.
+ * Quando false, não é deduzido do saldo (útil para pausar sem deletar).
+ * Armazenado como integer (0 = false, 1 = true) por limitação do SQLite.
+ */
+ is_active: integer('is_active', { mode: 'boolean' }).notNull().default(true),
+
+ /**
+ * Data a partir da qual este gasto passa a ser contabilizado.
+ * Formato ISO 8601 (YYYY-MM-DD).
+ */
+ starts_at: text('starts_at').notNull().default(sql`(date('now'))`),
+
+ /**
+ * Data em que este gasto deixa de ser contabilizado (opcional).
+ * Útil para despesas com prazo definido (ex: parcelamento de 12x).
+ * Formato ISO 8601 (YYYY-MM-DD).
+ */
+ ends_at: text('ends_at'),
+
+ created_at: text('created_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+
+ updated_at: text('updated_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+});
+
+export type RecurringExpense = typeof recurringExpenses.$inferSelect;
+export type NewRecurringExpense = typeof recurringExpenses.$inferInsert;
diff --git a/api/src/db/schema/users.ts b/api/src/db/schema/users.ts
new file mode 100644
index 0000000..636ad2d
--- /dev/null
+++ b/api/src/db/schema/users.ts
@@ -0,0 +1,37 @@
+import { sql } from 'drizzle-orm';
+import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+
+/**
+ * Tabela de usuários.
+ * Por ora, suporta um único usuário local (single-user app).
+ * O campo `net_salary_override` permite que o usuário edite manualmente
+ * o salário líquido calculado, para cobrir descontos extras (plano de saúde, VT, etc.).
+ */
+export const users = sqliteTable('users', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+
+ name: text('name').notNull(),
+ email: text('email').unique().notNull(),
+ password_hash: text('password_hash').notNull(),
+
+ /** Salário bruto informado pelo usuário (em R$) */
+ gross_salary: real('gross_salary').notNull().default(0),
+
+ /**
+ * Override manual do salário líquido.
+ * Quando NULL, o app usa o valor calculado automaticamente (INSS + IRRF).
+ * Quando preenchido, este valor é usado como base para o saldo disponível.
+ */
+ net_salary_override: real('net_salary_override'),
+
+ created_at: text('created_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+
+ updated_at: text('updated_at')
+ .notNull()
+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
+});
+
+export type User = typeof users.$inferSelect;
+export type NewUser = typeof users.$inferInsert;
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;
+}
diff --git a/api/src/plugins/cors.ts b/api/src/plugins/cors.ts
new file mode 100644
index 0000000..5398e39
--- /dev/null
+++ b/api/src/plugins/cors.ts
@@ -0,0 +1,18 @@
+import cors from '@fastify/cors';
+import type { FastifyPluginAsync } from 'fastify';
+
+/**
+ * Plugin de CORS para o Fastify.
+ * Em produção, substitua o `origin: true` pelo domínio/IP do seu app mobile
+ * ou pelo endereço da sua VPS.
+ */
+const corsPlugin: FastifyPluginAsync = async (fastify) => {
+ fastify.register(cors, {
+ // Em dev: aceita qualquer origem
+ // Em prod: restrinja para o IP/domínio conhecido
+ origin: process.env.CORS_ORIGIN ?? true,
+ methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
+ });
+};
+
+export default corsPlugin;
diff --git a/api/src/server.ts b/api/src/server.ts
new file mode 100644
index 0000000..6b3fd46
--- /dev/null
+++ b/api/src/server.ts
@@ -0,0 +1,89 @@
+import Fastify from 'fastify';
+import corsPlugin from './plugins/cors';
+import fastifyJwt from '@fastify/jwt';
+import authRoutes from './modules/auth/auth.routes';
+import dashboardRoutes from './modules/dashboard/dashboard.routes';
+import incomesRoutes from './modules/incomes/incomes.routes';
+import oneTimeExpensesRoutes from './modules/one-time-expenses/one-time-expenses.routes';
+import recurringExpensesRoutes from './modules/recurring-expenses/recurring-expenses.routes';
+import usersRoutes from './modules/users/users.routes';
+
+const PORT = Number(process.env.PORT) || 3333;
+const HOST = process.env.HOST ?? '0.0.0.0';
+
+const fastify = Fastify({
+ logger: {
+ transport:
+ process.env.NODE_ENV === 'development'
+ ? { target: 'pino-pretty', options: { colorize: true } }
+ : undefined,
+ },
+});
+
+// ---------------------------------------------------------------------------
+// Plugins globais
+// ---------------------------------------------------------------------------
+fastify.register(corsPlugin);
+
+fastify.register(fastifyJwt, {
+ secret: process.env.JWT_SECRET || 'super-secret-yaba-jwt-key-2026',
+});
+
+// ---------------------------------------------------------------------------
+// JWT Middleware
+// ---------------------------------------------------------------------------
+fastify.addHook('onRequest', async (request, reply) => {
+ if (request.url.includes('/api/v1/auth') || request.url.startsWith('/health')) {
+ return; // Pula autenticação para rotas públicas
+ }
+ try {
+ await request.jwtVerify();
+ } catch (err) {
+ return reply.status(401).send({ error: 'Não autorizado.' });
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Rotas com prefixo /api/v1
+// ---------------------------------------------------------------------------
+const API_PREFIX = '/api/v1';
+
+fastify.register(authRoutes, { prefix: API_PREFIX });
+fastify.register(usersRoutes, { prefix: API_PREFIX });
+fastify.register(incomesRoutes, { prefix: API_PREFIX });
+fastify.register(recurringExpensesRoutes, { prefix: API_PREFIX });
+fastify.register(oneTimeExpensesRoutes, { prefix: API_PREFIX });
+fastify.register(dashboardRoutes, { prefix: API_PREFIX });
+
+// ---------------------------------------------------------------------------
+// Health check
+// ---------------------------------------------------------------------------
+fastify.get('/health', async () => ({
+ status: 'ok',
+ timestamp: new Date().toISOString(),
+ version: '1.0.0',
+}));
+
+// ---------------------------------------------------------------------------
+// Handler de erros global
+// ---------------------------------------------------------------------------
+fastify.setErrorHandler((error, _request, reply) => {
+ fastify.log.error(error);
+ const statusCode = error.statusCode ?? 500;
+ reply.status(statusCode).send({
+ error: statusCode >= 500 ? 'Erro interno do servidor.' : error.message,
+ ...(process.env.NODE_ENV === 'development' && { stack: error.stack }),
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Start
+// ---------------------------------------------------------------------------
+try {
+ await fastify.listen({ port: PORT, host: HOST });
+ console.log(`🚀 YABA API rodando em http://${HOST}:${PORT}`);
+ console.log(`📖 Health check: http://${HOST}:${PORT}/health`);
+} catch (err) {
+ fastify.log.error(err);
+ process.exit(1);
+}
diff --git a/api/src/utils/tax-calculator.ts b/api/src/utils/tax-calculator.ts
new file mode 100644
index 0000000..36ffc7e
--- /dev/null
+++ b/api/src/utils/tax-calculator.ts
@@ -0,0 +1,111 @@
+/**
+ * Calculadora de impostos brasileiros (INSS + IRRF).
+ * Tabelas vigentes: 2025.
+ *
+ * IMPORTANTE: As alíquotas e faixas mudam anualmente por decreto.
+ * Verifique a legislação vigente a cada ano fiscal.
+ *
+ * Fonte: Portaria MPS / IN RFB 2.141/2023 e atualizações.
+ */
+
+// ---------------------------------------------------------------------------
+// INSS — Tabela Progressiva 2025
+// ---------------------------------------------------------------------------
+const INSS_TABLE = [
+ { upTo: 1_518.0, rate: 0.075 },
+ { upTo: 2_793.88, rate: 0.09 },
+ { upTo: 4_190.83, rate: 0.12 },
+ { upTo: 8_157.41, rate: 0.14 },
+] as const;
+
+const INSS_TETO = 908.86; // Valor máximo de desconto do INSS
+
+/**
+ * Calcula o desconto do INSS com a tabela progressiva.
+ * Cada faixa incide apenas sobre a parte do salário dentro dela.
+ */
+export function calcularINSS(salarioBruto: number): number {
+ if (salarioBruto <= 0) return 0;
+ if (salarioBruto > INSS_TABLE[INSS_TABLE.length - 1].upTo) return INSS_TETO;
+
+ let inss = 0;
+ let salarioRestante = salarioBruto;
+ let limiteAnterior = 0;
+
+ for (const faixa of INSS_TABLE) {
+ if (salarioRestante <= 0) break;
+
+ const baseNaFaixa = Math.min(salarioBruto, faixa.upTo) - limiteAnterior;
+ inss += baseNaFaixa * faixa.rate;
+
+ salarioRestante -= baseNaFaixa;
+ limiteAnterior = faixa.upTo;
+ }
+
+ return parseFloat(inss.toFixed(2));
+}
+
+// ---------------------------------------------------------------------------
+// IRRF — Tabela Progressiva 2025
+// ---------------------------------------------------------------------------
+interface FaixaIRRF {
+ upTo: number | null; // null = sem limite superior
+ rate: number;
+ deduction: number;
+}
+
+const IRRF_TABLE: FaixaIRRF[] = [
+ { upTo: 2_259.2, rate: 0, deduction: 0 },
+ { upTo: 2_826.65, rate: 0.075, deduction: 169.44 },
+ { upTo: 3_751.05, rate: 0.15, deduction: 381.44 },
+ { upTo: 4_664.68, rate: 0.225, deduction: 662.77 },
+ { upTo: null, rate: 0.275, deduction: 896.0 },
+];
+
+/**
+ * Calcula o desconto do IRRF.
+ * Base de cálculo: Salário Bruto − INSS (sem considerar dependentes).
+ */
+export function calcularIRRF(salarioBruto: number, inss: number): number {
+ const baseCalculo = salarioBruto - inss;
+ if (baseCalculo <= 0) return 0;
+
+ const faixa = IRRF_TABLE.find(
+ (f) => f.upTo === null || baseCalculo <= f.upTo,
+ )!;
+
+ const irrf = baseCalculo * faixa.rate - faixa.deduction;
+ return parseFloat(Math.max(0, irrf).toFixed(2));
+}
+
+// ---------------------------------------------------------------------------
+// Resultado consolidado
+// ---------------------------------------------------------------------------
+export interface ResultadoCalculo {
+ salarioBruto: number;
+ descontoINSS: number;
+ descontoIRRF: number;
+ totalDescontos: number;
+ salarioLiquidoCalculado: number;
+}
+
+/**
+ * Calcula o salário líquido completo a partir do salário bruto.
+ * Retorna um objeto com o detalhamento de cada desconto.
+ */
+export function calcularSalarioLiquido(salarioBruto: number): ResultadoCalculo {
+ const descontoINSS = calcularINSS(salarioBruto);
+ const descontoIRRF = calcularIRRF(salarioBruto, descontoINSS);
+ const totalDescontos = parseFloat((descontoINSS + descontoIRRF).toFixed(2));
+ const salarioLiquidoCalculado = parseFloat(
+ (salarioBruto - totalDescontos).toFixed(2),
+ );
+
+ return {
+ salarioBruto,
+ descontoINSS,
+ descontoIRRF,
+ totalDescontos,
+ salarioLiquidoCalculado,
+ };
+}