Merge pull request 'Docs: backfill JSDoc, utility docs, and CLAUDE.md API/schema sections' (#6) from docs/backfill-missing-documentation into master

Reviewed-on: #6
This commit was merged in pull request #6.
This commit is contained in:
2026-03-20 08:30:46 -07:00
6 changed files with 230 additions and 11 deletions

View File

@@ -94,3 +94,87 @@ The default route `/` renders the paycheck-centric main view (`client/src/pages/
**Financing:** `GET/POST /api/financing`, `PUT/DELETE /api/financing/:id`, `PATCH /api/financing-payments/:id/paid`. Plans track a total amount, payoff due date, and `start_date`. Payment per period is auto-calculated as `(remaining balance) / (remaining periods)`. Split plans (`assigned_paycheck = null`) divide each period's payment across both paychecks. Plans auto-close when fully paid. Financing payments are included in the paycheck remaining balance. `start_date` prevents a plan from appearing on paycheck months before it was created — both virtual previews and `generate` respect this guard. **Financing:** `GET/POST /api/financing`, `PUT/DELETE /api/financing/:id`, `PATCH /api/financing-payments/:id/paid`. Plans track a total amount, payoff due date, and `start_date`. Payment per period is auto-calculated as `(remaining balance) / (remaining periods)`. Split plans (`assigned_paycheck = null`) divide each period's payment across both paychecks. Plans auto-close when fully paid. Financing payments are included in the paycheck remaining balance. `start_date` prevents a plan from appearing on paycheck months before it was created — both virtual previews and `generate` respect this guard.
**Migrations:** SQL files in `db/migrations/` are applied in filename order on server startup. Add new migrations as `00N_description.sql` — they run once and are tracked in the `migrations` table. **Migrations:** SQL files in `db/migrations/` are applied in filename order on server startup. Add new migrations as `00N_description.sql` — they run once and are tracked in the `migrations` table.
## Database Schema
Full DDL lives in `db/migrations/`. Key tables:
| Table | Description |
|---|---|
| `config` | Key/value store for app settings (paycheck days, gross/net amounts). |
| `bills` | Bill definitions: name, amount, due day, assigned paycheck, category, active flag. |
| `paychecks` | One row per paycheck per period (year + month + paycheck_number 1 or 2). |
| `paycheck_bills` | Junction between a paycheck instance and its bills; tracks paid status and amount_override. |
| `one_time_expenses` | Ad-hoc expenses attached to a specific paycheck instance. |
| `financing_plans` | Financing plans: total amount, due date, start_date, optional assigned_paycheck. |
| `financing_payments` | One payment record per plan per paycheck; tracks paid status. |
| `expense_categories` | Lookup table for variable-expense categories (Groceries, Gas, Dining, …). |
| `actuals` | Actual spending log entries linked to a paycheck, category, or bill. |
| `migrations` | Internal table tracking which migration files have been applied. |
## API Endpoints
All routes are prefixed with `/api`.
### Paychecks
| Method | Path | Description |
|---|---|---|
| `GET` | `/paychecks?year=&month=` | Return both paychecks for a month. Returns virtual data (id: null) when no DB record exists. |
| `POST` | `/paychecks/generate?year=&month=` | Upsert paycheck records and sync bills/financing for the month. |
| `GET` | `/paychecks/months` | List all months that have generated paycheck records, newest first. |
| `PATCH` | `/paychecks/:id` | Update gross and net for a specific paycheck. |
| `PATCH` | `/paycheck-bills/:id/paid` | Toggle paid status; locks amount_override on pay. |
| `PATCH` | `/paycheck-bills/:id/amount` | Set amount_override for a variable-amount bill. |
### Bills
| Method | Path | Description |
|---|---|---|
| `GET` | `/bills` | List all bills ordered by assigned_paycheck, name. |
| `POST` | `/bills` | Create a bill. |
| `GET` | `/bills/:id` | Fetch a single bill. |
| `PUT` | `/bills/:id` | Replace a bill's fields. |
| `DELETE` | `/bills/:id` | Hard-delete a bill. |
| `PATCH` | `/bills/:id/toggle` | Toggle the active flag. |
### Config
| Method | Path | Description |
|---|---|---|
| `GET` | `/config` | Return all config values as a flat object with numeric values. |
| `PUT` | `/config` | Upsert one or more config keys. Unknown keys are silently ignored. |
### One-Time Expenses
| Method | Path | Description |
|---|---|---|
| `POST` | `/one-time-expenses` | Add a one-time expense to a paycheck. |
| `DELETE` | `/one-time-expenses/:id` | Remove a one-time expense. |
| `PATCH` | `/one-time-expenses/:id/paid` | Toggle paid status. |
### Financing
| Method | Path | Description |
|---|---|---|
| `GET` | `/financing` | List all financing plans with enriched progress fields. |
| `POST` | `/financing` | Create a financing plan. |
| `GET` | `/financing/:id` | Fetch a plan with its full payment history. |
| `PUT` | `/financing/:id` | Update a financing plan. |
| `DELETE` | `/financing/:id` | Delete a financing plan and its payments. |
| `PATCH` | `/financing-payments/:id/paid` | Toggle a payment's paid status; auto-closes the plan when fully paid. |
### Actuals & Categories
| Method | Path | Description |
|---|---|---|
| `GET` | `/expense-categories` | List all expense categories. |
| `POST` | `/expense-categories` | Create a new expense category. |
| `GET` | `/actuals?paycheckId=` | List actual spending entries for a paycheck. |
| `POST` | `/actuals` | Log an actual spending entry. |
| `DELETE` | `/actuals/:id` | Remove an actual spending entry. |
### Summary
| Method | Path | Description |
|---|---|---|
| `GET` | `/summary/monthly?year=&month=` | Spending breakdown and category totals for a single month. |
| `GET` | `/summary/annual?year=` | Income vs. spending, surplus/deficit trend, and stacked variable spending for a full year. |
### Health
| Method | Path | Description |
|---|---|---|
| `GET` | `/health` | Returns `{ ok: true }`. Used by Docker healthcheck. |

View File

@@ -2,6 +2,18 @@ import { createContext, useContext, useEffect, useState } from 'react';
const ThemeContext = createContext(null); const ThemeContext = createContext(null);
/**
* Provides light/dark theme state to the component tree.
*
* On mount, the active theme is read from `localStorage`; if absent it
* falls back to the OS `prefers-color-scheme` media query. The chosen
* theme is applied as a `data-theme` attribute on `<html>` and persisted
* to `localStorage` whenever it changes.
*
* Exposes `{ theme, toggle }` via {@link useTheme}.
*
* @param {{ children: React.ReactNode }} props
*/
export function ThemeProvider({ children }) { export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(() => { const [theme, setTheme] = useState(() => {
const stored = localStorage.getItem('theme'); const stored = localStorage.getItem('theme');
@@ -25,6 +37,13 @@ export function ThemeProvider({ children }) {
); );
} }
/**
* Returns the current theme context provided by {@link ThemeProvider}.
*
* @returns {{ theme: 'light'|'dark', toggle: () => void }}
* - `theme` — the active color scheme name
* - `toggle` — flips between `'light'` and `'dark'`
*/
export function useTheme() { export function useTheme() {
return useContext(ThemeContext); return useContext(ThemeContext);
} }

View File

@@ -2,6 +2,20 @@ const express = require('express');
const router = express.Router(); const router = express.Router();
const { pool } = require('../db'); const { pool } = require('../db');
/**
* Validate the request body for bill create/update operations.
*
* Checks that all required fields are present and within acceptable ranges.
* Amount is optional when `variable_amount` is true (defaults to 0 on save).
*
* @param {object} body - Request body.
* @param {string} body.name - Bill name (non-empty).
* @param {number|string} [body.amount] - Bill amount; required when variable_amount is falsy.
* @param {number|string} body.due_day - Day of month (131).
* @param {number|string} body.assigned_paycheck - Which paycheck: 1 or 2.
* @param {boolean} [body.variable_amount] - Whether the bill amount varies each month.
* @returns {string|null} Validation error message, or null when valid.
*/
function validateBillFields(body) { function validateBillFields(body) {
const { name, amount, due_day, assigned_paycheck, variable_amount } = body; const { name, amount, due_day, assigned_paycheck, variable_amount } = body;
if (!name || name.toString().trim() === '') { if (!name || name.toString().trim() === '') {

View File

@@ -16,6 +16,22 @@ const DEFAULTS = {
paycheck2_day: 15, paycheck2_day: 15,
}; };
/**
* Fetch all application config values from the database.
*
* Reads all known `CONFIG_KEYS` from the `config` table and coerces values
* to numbers. Keys missing from the DB fall back to hard-coded `DEFAULTS`
* (paycheck1_day = 1, paycheck2_day = 15); keys with no default are null.
*
* @returns {Promise<{
* paycheck1_day: number|null,
* paycheck2_day: number|null,
* paycheck1_gross: number|null,
* paycheck1_net: number|null,
* paycheck2_gross: number|null,
* paycheck2_net: number|null
* }>}
*/
async function getAllConfig() { async function getAllConfig() {
const result = await pool.query( const result = await pool.query(
'SELECT key, value FROM config WHERE key = ANY($1)', 'SELECT key, value FROM config WHERE key = ANY($1)',

View File

@@ -4,9 +4,20 @@ const { pool } = require('../db');
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────────
// Count how many payment periods remain for a plan starting from (year, month), /**
// including that month. Each month contributes 1 or 2 periods depending on * Count the number of payment periods remaining for a plan, starting from
// whether the plan is split across both paychecks (assigned_paycheck = null). * (and including) the given year/month.
*
* Each calendar month contributes 1 period for single-paycheck plans
* (`assigned_paycheck` = 1 or 2) or 2 periods for split plans
* (`assigned_paycheck` = null). Always returns at least 1 to prevent
* division-by-zero in {@link calcPaymentAmount}.
*
* @param {{ due_date: string, assigned_paycheck: number|null }} plan
* @param {number} year - Current year.
* @param {number} month - Current month (112).
* @returns {number} Number of remaining payment periods (≥ 1).
*/
function remainingPeriods(plan, year, month) { function remainingPeriods(plan, year, month) {
const due = new Date(plan.due_date); const due = new Date(plan.due_date);
const dueYear = due.getFullYear(); const dueYear = due.getFullYear();
@@ -19,7 +30,18 @@ function remainingPeriods(plan, year, month) {
return monthsLeft * perMonth; return monthsLeft * perMonth;
} }
// Calculate the payment amount for one period. /**
* Calculate the payment amount due for a single period.
*
* Formula: `(total_amount - paid_so_far) / remainingPeriods(plan, year, month)`.
* Returns 0 when the plan is already fully paid.
*
* @param {import('pg').PoolClient} client - Active DB client (read-only query).
* @param {{ id: number, total_amount: number|string, due_date: string, assigned_paycheck: number|null }} plan
* @param {number} year - Current year for period calculation.
* @param {number} month - Current month (112) for period calculation.
* @returns {Promise<number>} Payment amount rounded to 2 decimal places, or 0.
*/
async function calcPaymentAmount(client, plan, year, month) { async function calcPaymentAmount(client, plan, year, month) {
const { rows } = await client.query( const { rows } = await client.query(
`SELECT COALESCE(SUM(fp.amount), 0) AS paid_total `SELECT COALESCE(SUM(fp.amount), 0) AS paid_total
@@ -35,7 +57,22 @@ async function calcPaymentAmount(client, plan, year, month) {
return parseFloat((remaining / periods).toFixed(2)); return parseFloat((remaining / periods).toFixed(2));
} }
// Enrich a plan row with computed progress fields. /**
* Enrich a raw `financing_plans` row with computed progress fields.
*
* Aggregates payment records to derive `paid_total`, `remaining`,
* `paid_count`, `total_count`, and `overdue`. Used by every route that
* returns a plan to the client.
*
* @param {import('pg').Pool} pool - DB pool (runs a single SELECT).
* @param {object} plan - Raw row from the `financing_plans` table.
* @returns {Promise<object>} Plan object extended with:
* - `paid_total` {number} — sum of paid payment amounts
* - `remaining` {number} — total_amount minus paid_total (≥ 0)
* - `paid_count` {number} — number of paid financing_payments rows
* - `total_count` {number} — total financing_payments rows for the plan
* - `overdue` {boolean} — true when active, remaining > 0, and due_date is in the past
*/
async function enrichPlan(pool, plan) { async function enrichPlan(pool, plan) {
const { rows } = await pool.query( const { rows } = await pool.query(
`SELECT `SELECT

View File

@@ -43,9 +43,29 @@ function pad2(n) {
return String(n).padStart(2, '0'); return String(n).padStart(2, '0');
} }
// Build virtual (unsaved) paycheck data from config + active bills. /**
// Returns the same shape as fetchPaychecksForMonth but with id: null * Build virtual (unsaved) paycheck data from config + active bills.
// and paycheck_bill_id: null — nothing is written to the DB. *
* Returns the same shape as {@link fetchPaychecksForMonth} but with
* `id: null` and `paycheck_bill_id: null` — nothing is written to the DB.
* Financing payment previews are included with `financing_payment_id: null`.
* Plans whose `start_date` is after the requested period are excluded.
*
* @param {number} year - Full four-digit year (e.g. 2025).
* @param {number} month - Month number 112.
* @returns {Promise<Array<{
* id: null,
* period_year: number,
* period_month: number,
* paycheck_number: 1|2,
* pay_date: string,
* gross: number,
* net: number,
* bills: Array<object>,
* one_time_expenses: [],
* financing: Array<object>
* }>>}
*/
async function buildVirtualPaychecks(year, month) { async function buildVirtualPaychecks(year, month) {
const config = await getConfig(); const config = await getConfig();
const paychecks = []; const paychecks = [];
@@ -137,8 +157,19 @@ async function buildVirtualPaychecks(year, month) {
return paychecks; return paychecks;
} }
// Generate (upsert) paycheck records for the given year/month. /**
// Returns the two paycheck IDs. * Generate (upsert) paycheck records for the given year/month.
*
* Inserts or updates both `paychecks` rows, syncs `paycheck_bills` for all
* active bills, and inserts `financing_payments` for active plans that have
* started by this period. All writes run inside a single transaction.
* Split financing plans (assigned_paycheck = null) get half the per-period
* amount on each paycheck.
*
* @param {number} year - Full four-digit year.
* @param {number} month - Month number 112.
* @returns {Promise<number[]>} Two-element array of paycheck IDs `[id1, id2]`.
*/
async function generatePaychecks(year, month) { async function generatePaychecks(year, month) {
const config = await getConfig(); const config = await getConfig();
@@ -221,7 +252,25 @@ async function generatePaychecks(year, month) {
} }
} }
// Fetch both paycheck records for a month with full bill and one_time_expense data. /**
* Fetch both persisted paycheck records for a month with full bill,
* one-time-expense, and financing-payment data joined in.
*
* @param {number} year - Full four-digit year.
* @param {number} month - Month number 112.
* @returns {Promise<Array<{
* id: number,
* period_year: number,
* period_month: number,
* paycheck_number: 1|2,
* pay_date: string,
* gross: number,
* net: number,
* bills: Array<object>,
* one_time_expenses: Array<object>,
* financing: Array<object>
* }>>} Empty array when no DB records exist for the given month.
*/
async function fetchPaychecksForMonth(year, month) { async function fetchPaychecksForMonth(year, month) {
const pcResult = await pool.query( const pcResult = await pool.query(
`SELECT id, period_year, period_month, paycheck_number, pay_date, gross, net `SELECT id, period_year, period_month, paycheck_number, pay_date, gross, net