8 Commits

Author SHA1 Message Date
d5326b359e Merge pull request 'Normalize callback prop naming to on[Noun][Verb] convention' (#3) from event-taxonomy-normalizer into master
Reviewed-on: #3
2026-03-20 08:32:12 -07:00
2902b95800 Merge pull request 'Chore: task groomer — add 4 new backlog tasks' (#2) from task/groomer-new-tasks into master
Reviewed-on: #2
2026-03-20 08:31:52 -07:00
6344a6f7d5 Merge pull request 'Remove duplicate utility code via shared formatting module' (#1) from dead-code/remove-duplicate-utilities into master
Reviewed-on: #1
2026-03-20 08:31:11 -07:00
48dd5a51bc 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
2026-03-20 08:30:46 -07:00
11476086cd Docs: backfill JSDoc, utility docs, and CLAUDE.md API/schema sections
- Add JSDoc to paychecks.js helpers: buildVirtualPaychecks, generatePaychecks, fetchPaychecksForMonth
- Add JSDoc to financing.js helpers: remainingPeriods, calcPaymentAmount, enrichPlan
- Add JSDoc to validateBillFields (bills.js) and getAllConfig (config.js)
- Add JSDoc to ThemeProvider and useTheme in ThemeContext.jsx
- Add Database Schema reference table to CLAUDE.md
- Add complete API Endpoints reference section to CLAUDE.md covering all routes

Nightshift-Task: docs-backfill
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:54:45 -04:00
c69984898b Remove duplicate utility code via shared formatting module
Consolidate MONTH_NAMES, PALETTE, formatCurrency, formatCurrencyShort,
ordinal, and fmt into client/src/utils/formatting.js. Consolidate
CONFIG_KEYS into server/src/constants.js. All consumer files updated
to import from these shared modules. PaycheckView re-exports formatCurrency,
ordinal, and formatPayDate for backward compatibility with existing tests.

Nightshift-Task: dead-code
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:22:04 -04:00
9c3331090e Chore: task groomer — add 4 new backlog tasks
Gap analysis identified missing test coverage for actuals/expense-categories
routes, and no implementation for savings_goals (schema exists) or expense
category management UI in Settings. Four tasks created in td to address these
gaps: td-61fdb0, td-c04994, td-55695f, td-a94ef7.

Also commit pre-existing .gitignore and settings.local.json changes.

Nightshift-Task: task-groomer
Nightshift-Ref: https://github.com/marcus/nightshift
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 02:16:32 -04:00
963652bc61 Normalize callback prop naming to on[Noun][Verb] convention
Rename onAmountSave → onPaycheckAmountSave and onGenerate →
onPaycheckGenerate in PaycheckColumn to match the on[Noun][Verb]
pattern used by all other callback props (onBillPaidToggle,
onBillAmountSave, etc.). Document the convention in CLAUDE.md.

Nightshift-Task: event-taxonomy
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:12:33 -04:00
20 changed files with 310 additions and 1709 deletions

View File

@@ -24,7 +24,22 @@
"Bash(npm run:*)",
"Bash(/home/christian/.nvm/versions/node/v24.14.0/bin/npm run:*)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm run build 2>&1)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npx vite build 2>&1)"
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npx vite build 2>&1)",
"Bash(sqlite3 /home/christian/projects/budget/.todos/issues.db \"PRAGMA integrity_check;\")",
"Bash(td usage:*)",
"Bash(ls:*)",
"Bash(sudo chown:*)",
"Bash(td add:*)",
"Bash(td log:*)",
"Bash(git:*)",
"Bash(npm list:*)",
"Bash(td accept:*)",
"Bash(/home/christian/.nvm/versions/node/v24.14.0/bin/npm test:*)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm test)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm --prefix /home/christian/projects/budget/server test 2>&1)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm --prefix /home/christian/projects/budget/client test 2>&1)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm --prefix /home/christian/projects/budget/client test)",
"Bash(PATH=\"/home/christian/.nvm/versions/node/v24.14.0/bin:$PATH\" npm --prefix /home/christian/projects/budget/client test -- --reporter=verbose)"
]
}
}

2
.gitignore vendored
View File

@@ -41,3 +41,5 @@ Thumbs.db
# Coverage
coverage/
# Nightshift plan artifacts (keep out of version control)
.nightshift-plan

View File

@@ -77,6 +77,8 @@ cd client && npm run test:watch
- Export pure functions (validators, formatters, etc.) for direct testing
- Run `npm test` in both `server/` and `client/` before committing
**Callback prop naming convention:** React callback props follow `on[Noun][Verb]` (e.g., `onBillPaidToggle`, `onPaycheckAmountSave`, `onPaycheckGenerate`). Event handler functions in the parent component use the `handle[Action]` prefix (e.g., `handleAmountSave`, `handleBillPaidToggle`).
## Application Structure
The default route `/` renders the paycheck-centric main view (`client/src/pages/PaycheckView.jsx`). It shows the current month's two paychecks side-by-side with bills, paid status, one-time expenses, and remaining balance. Month navigation (prev/next) fetches data via `GET /api/paychecks?year=&month=`.
@@ -94,3 +96,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.
**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);
/**
* 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 }) {
const [theme, setTheme] = useState(() => {
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() {
return useContext(ThemeContext);
}

View File

@@ -3,32 +3,10 @@ import {
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
Cell, ResponsiveContainer, ReferenceLine,
} from 'recharts';
const MONTH_NAMES = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
import { MONTH_NAMES, PALETTE, fmt, formatCurrencyShort } from '../utils/formatting.js';
const MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const PALETTE = ['#3b82f6', '#8b5cf6', '#ec4899', '#f97316', '#22c55e', '#14b8a6', '#eab308', '#64748b'];
function fmt(value) {
if (value == null) return '—';
const num = Number(value);
if (isNaN(num)) return '—';
const abs = Math.abs(num).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
return num < 0 ? `-$${abs}` : `$${abs}`;
}
function formatCurrencyShort(value) {
if (value == null || isNaN(value)) return '';
const abs = Math.abs(value);
const sign = value < 0 ? '-' : '';
if (abs >= 1000) return `${sign}$${(abs / 1000).toFixed(1)}k`;
return `${sign}$${abs.toFixed(0)}`;
}
function surplusClass(value) {
if (value == null || isNaN(Number(value))) return '';
return Number(value) >= 0 ? 'text-success' : 'text-danger';

View File

@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { formatCurrency, ordinal } from '../utils/formatting.js';
const CATEGORIES = [
'Housing', 'Utilities', 'Subscriptions', 'Insurance',
@@ -14,19 +15,6 @@ const EMPTY_FORM = {
variable_amount: false,
};
function formatCurrency(value) {
const num = parseFloat(value);
if (isNaN(num)) return '$0.00';
return num.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
function ordinal(n) {
const int = parseInt(n, 10);
if (isNaN(int)) return n;
const suffix = ['th', 'st', 'nd', 'rd'];
const v = int % 100;
return int + (suffix[(v - 20) % 10] || suffix[v] || suffix[0]);
}
function Bills() {
const [bills, setBills] = useState([]);

View File

@@ -1,9 +1,5 @@
import { useState, useEffect } from 'react';
function fmt(value) {
const num = parseFloat(value) || 0;
return '$' + num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
import { fmt } from '../utils/formatting.js';
function ProgressBar({ paid, total }) {
const pct = total > 0 ? Math.min(100, (paid / total) * 100) : 0;

View File

@@ -3,25 +3,7 @@ import {
PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer,
BarChart, Bar, XAxis, YAxis, CartesianGrid,
} from 'recharts';
const MONTH_NAMES = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
function formatCurrency(value) {
const num = parseFloat(value) || 0;
return '$' + num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function formatCurrencyShort(value) {
const num = parseFloat(value) || 0;
if (Math.abs(num) >= 1000) return '$' + (num / 1000).toFixed(1) + 'k';
return '$' + num.toFixed(0);
}
// Accessible palette that works in light and dark
const PALETTE = ['#3b82f6', '#8b5cf6', '#ec4899', '#f97316', '#22c55e', '#14b8a6', '#eab308', '#64748b'];
import { MONTH_NAMES, PALETTE, formatCurrency, formatCurrencyShort } from '../utils/formatting.js';
function StatCard({ label, value, valueClass }) {
return (

View File

@@ -1,20 +1,5 @@
import { useState, useEffect } from 'react';
const MONTH_NAMES = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
function ordinal(n) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function formatCurrency(value) {
const num = parseFloat(value) || 0;
return '$' + num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
import { MONTH_NAMES, formatCurrency, ordinal } from '../utils/formatting.js';
function formatPayDate(dateStr) {
const [year, month, day] = dateStr.split('-').map(Number);
@@ -29,7 +14,7 @@ export { ordinal, formatCurrency, formatPayDate };
// ─── PaycheckColumn ───────────────────────────────────────────────────────────
function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggle, onOteDelete, onOteAdd, onGenerate, onAmountSave, onBillAmountSave, onFinancingPaidToggle }) {
function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggle, onOteDelete, onOteAdd, onPaycheckGenerate, onPaycheckAmountSave, onBillAmountSave, onFinancingPaidToggle }) {
const [newOteName, setNewOteName] = useState('');
const [newOteAmount, setNewOteAmount] = useState('');
const [actuals, setActuals] = useState([]);
@@ -95,7 +80,7 @@ function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggl
// Lazy generate if this is a virtual paycheck
let paycheckId = paycheck.id;
if (!paycheckId) {
const generated = await onGenerate();
const generated = await onPaycheckGenerate();
paycheckId = generated.find(p => p.paycheck_number === paycheck.paycheck_number).id;
}
@@ -151,7 +136,7 @@ function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggl
setAmountSaving(true);
setAmountError(null);
try {
await onAmountSave(paycheck.paycheck_number, parseFloat(editGross) || 0, parseFloat(editNet) || 0);
await onPaycheckAmountSave(paycheck.paycheck_number, parseFloat(editGross) || 0, parseFloat(editNet) || 0);
setEditingAmounts(false);
} catch (err) {
setAmountError(err.message);
@@ -755,8 +740,8 @@ function PaycheckView() {
onOteDelete={handleOteDelete}
onOteAdd={handleOteAdd}
categories={categories}
onGenerate={generateMonth}
onAmountSave={handleAmountSave}
onPaycheckGenerate={generateMonth}
onPaycheckAmountSave={handleAmountSave}
onBillAmountSave={handleBillAmountSave}
onFinancingPaidToggle={handleFinancingPaidToggle}
/>
@@ -767,8 +752,8 @@ function PaycheckView() {
onOteDelete={handleOteDelete}
onOteAdd={handleOteAdd}
categories={categories}
onGenerate={generateMonth}
onAmountSave={handleAmountSave}
onPaycheckGenerate={generateMonth}
onPaycheckAmountSave={handleAmountSave}
onBillAmountSave={handleBillAmountSave}
onFinancingPaidToggle={handleFinancingPaidToggle}
/>

View File

@@ -0,0 +1,34 @@
export const MONTH_NAMES = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
// Accessible palette that works in light and dark
export const PALETTE = ['#3b82f6', '#8b5cf6', '#ec4899', '#f97316', '#22c55e', '#14b8a6', '#eab308', '#64748b'];
export function formatCurrency(value) {
const num = parseFloat(value) || 0;
return '$' + num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
export function formatCurrencyShort(value) {
if (value == null || isNaN(value)) return '';
const abs = Math.abs(value);
const sign = value < 0 ? '-' : '';
if (abs >= 1000) return `${sign}$${(abs / 1000).toFixed(1)}k`;
return `${sign}$${abs.toFixed(0)}`;
}
export function ordinal(n) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
export function fmt(value) {
if (value == null) return '—';
const num = Number(value);
if (isNaN(num)) return '—';
const abs = Math.abs(num).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
return num < 0 ? `-$${abs}` : `$${abs}`;
}

View File

@@ -1,213 +0,0 @@
#!/usr/bin/env node
/**
* Bus-Factor Analyzer
* Analyzes code ownership concentration by examining git commit history.
* Usage: node scripts/bus-factor.js [--json] [--min-commits N] [--threshold N] [--top N]
*/
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
import path from 'path';
// --- Pure analysis functions (exported for testing) ---
/**
* Parse raw `git log --numstat` output into a map of file -> author -> commitCount.
* @param {string} rawLog - Output from git log --numstat
* @returns {Object} { [filePath]: { [author]: number } }
*/
export function parseGitLog(rawLog) {
const ownership = {};
const lines = rawLog.split('\n');
let currentAuthor = null;
for (const line of lines) {
// Commit header line: "commit <hash>"
if (line.startsWith('commit ')) {
currentAuthor = null;
continue;
}
// Author line: "Author: Name <email>"
const authorMatch = line.match(/^Author:\s+(.+?)\s+<[^>]+>/);
if (authorMatch) {
currentAuthor = authorMatch[1].trim();
continue;
}
// Numstat line: "<added>\t<deleted>\t<filename>"
if (currentAuthor && /^\d+\t\d+\t/.test(line)) {
const parts = line.split('\t');
if (parts.length < 3) continue;
// Handle rename: "old/path => new/path" or "{old => new}/suffix"
let filePath = parts[2];
if (filePath.includes('{') && filePath.includes('=>')) {
filePath = filePath.replace(/\{([^}]*?)\s*=>\s*([^}]*?)\}/g, '$2').replace(/\s+/g, '');
} else if (filePath.includes(' => ')) {
filePath = filePath.split(' => ')[1].trim();
}
filePath = filePath.trim();
if (!filePath) continue;
if (!ownership[filePath]) ownership[filePath] = {};
ownership[filePath][currentAuthor] = (ownership[filePath][currentAuthor] || 0) + 1;
}
}
return ownership;
}
/**
* Compute ownership metrics for a single file.
* @param {Object} authorCounts - { [author]: commitCount }
* @param {number} ownershipThreshold - min fraction to count toward bus-factor (default 0.1)
* @returns {Object} { totalCommits, authors, busFactor, primaryOwner }
*/
export function computeOwnership(authorCounts, ownershipThreshold = 0.1) {
const entries = Object.entries(authorCounts).sort((a, b) => b[1] - a[1]);
const totalCommits = entries.reduce((sum, [, n]) => sum + n, 0);
const authors = entries.map(([name, commits]) => ({
name,
commits,
pct: totalCommits > 0 ? commits / totalCommits : 0,
}));
const busFactor = authors.filter(a => a.pct >= ownershipThreshold).length;
const primaryOwner = authors[0] || null;
return { totalCommits, authors, busFactor, primaryOwner };
}
/**
* Score all files and return sorted results.
* @param {Object} ownership - Output from parseGitLog
* @param {Object} options
* @returns {Array} Sorted file entries with ownership metrics
*/
export function scoreFiles(ownership, { minCommits = 2, ownershipThreshold = 0.1 } = {}) {
const results = [];
for (const [filePath, authorCounts] of Object.entries(ownership)) {
const metrics = computeOwnership(authorCounts, ownershipThreshold);
if (metrics.totalCommits < minCommits) continue;
results.push({ file: filePath, ...metrics });
}
// Sort: lowest bus-factor first, then most commits (highest risk first)
results.sort((a, b) => {
if (a.busFactor !== b.busFactor) return a.busFactor - b.busFactor;
return b.totalCommits - a.totalCommits;
});
return results;
}
/**
* Compute overall repo stats (weighted average bus-factor, high-risk count).
*/
export function repoStats(scoredFiles) {
if (scoredFiles.length === 0) return { avgBusFactor: 0, highRiskCount: 0, totalFiles: 0 };
const totalCommits = scoredFiles.reduce((s, f) => s + f.totalCommits, 0);
const weightedBf = scoredFiles.reduce((s, f) => s + f.busFactor * f.totalCommits, 0);
const avgBusFactor = totalCommits > 0 ? weightedBf / totalCommits : 0;
const highRiskCount = scoredFiles.filter(f => f.busFactor === 1).length;
return { avgBusFactor, highRiskCount, totalFiles: scoredFiles.length };
}
// --- CLI ---
function collectGitLog(repoRoot) {
const dirs = ['server/src', 'client/src', 'db/migrations'];
const cmd = `git -C "${repoRoot}" log --numstat -- ${dirs.join(' ')}`;
return execSync(cmd, { maxBuffer: 50 * 1024 * 1024 }).toString();
}
function formatReport(scoredFiles, stats, topN = 10) {
const lines = [];
lines.push('');
lines.push('=== Bus-Factor Analysis ===');
lines.push('');
lines.push(`Files analyzed : ${stats.totalFiles}`);
lines.push(`High-risk files: ${stats.highRiskCount} (bus-factor = 1)`);
lines.push(`Avg bus-factor : ${stats.avgBusFactor.toFixed(2)} (weighted by commits)`);
lines.push('');
const highRisk = scoredFiles.filter(f => f.busFactor === 1);
if (highRisk.length === 0) {
lines.push('No high-risk files found.');
} else {
lines.push(`--- Top ${Math.min(topN, highRisk.length)} High-Risk Files (bus-factor = 1) ---`);
lines.push('');
for (const f of highRisk.slice(0, topN)) {
const owner = f.primaryOwner;
lines.push(` ${f.file}`);
lines.push(` commits: ${f.totalCommits} owner: ${owner.name} (${(owner.pct * 100).toFixed(0)}%)`);
if (f.authors.length > 1) {
const others = f.authors.slice(1, 3).map(a => `${a.name} ${(a.pct * 100).toFixed(0)}%`).join(', ');
lines.push(` others: ${others}`);
}
lines.push('');
}
}
lines.push('--- Author Contribution Summary ---');
lines.push('');
const authorTotals = {};
for (const f of scoredFiles) {
for (const a of f.authors) {
authorTotals[a.name] = (authorTotals[a.name] || 0) + a.commits;
}
}
const totalAll = Object.values(authorTotals).reduce((s, n) => s + n, 0);
const sorted = Object.entries(authorTotals).sort((a, b) => b[1] - a[1]);
for (const [name, commits] of sorted) {
const pct = totalAll > 0 ? (commits / totalAll * 100).toFixed(1) : '0.0';
lines.push(` ${name.padEnd(30)} ${String(commits).padStart(5)} commits (${pct}%)`);
}
lines.push('');
return lines.join('\n');
}
// Detect if running as main script (ESM equivalent of require.main === module)
const isMain = process.argv[1] === fileURLToPath(import.meta.url);
if (isMain) {
const args = process.argv.slice(2);
const jsonMode = args.includes('--json');
const minCommitsIdx = args.indexOf('--min-commits');
const minCommits = minCommitsIdx !== -1 ? parseInt(args[minCommitsIdx + 1], 10) : 2;
const thresholdIdx = args.indexOf('--threshold');
const threshold = thresholdIdx !== -1 ? parseFloat(args[thresholdIdx + 1]) : 0.1;
const topIdx = args.indexOf('--top');
const topN = topIdx !== -1 ? parseInt(args[topIdx + 1], 10) : 10;
const repoRoot = path.resolve(fileURLToPath(import.meta.url), '..', '..');
let rawLog;
try {
rawLog = collectGitLog(repoRoot);
} catch (err) {
process.stderr.write(`Error running git log: ${err.message}\n`);
process.exit(1);
}
const ownership = parseGitLog(rawLog);
const scoredFiles = scoreFiles(ownership, { minCommits, ownershipThreshold: threshold });
const stats = repoStats(scoredFiles);
if (jsonMode) {
process.stdout.write(JSON.stringify({ stats, files: scoredFiles }, null, 2) + '\n');
} else {
process.stdout.write(formatReport(scoredFiles, stats, topN));
}
}

View File

@@ -1,202 +0,0 @@
import { describe, it, expect } from 'vitest';
import { parseGitLog, computeOwnership, scoreFiles, repoStats } from './bus-factor.mjs';
// --- parseGitLog ---
describe('parseGitLog', () => {
it('parses a single commit with one file', () => {
const raw = `commit abc123
Author: Alice <alice@example.com>
Date: Mon Jan 1 00:00:00 2024
Initial commit
5\t2\tserver/src/index.js
`;
const result = parseGitLog(raw);
expect(result['server/src/index.js']).toEqual({ Alice: 1 });
});
it('accumulates multiple commits by the same author', () => {
const raw = `commit aaa
Author: Alice <alice@example.com>
Date: Mon Jan 1 00:00:00 2024
First
3\t0\tserver/src/app.js
commit bbb
Author: Alice <alice@example.com>
Date: Tue Jan 2 00:00:00 2024
Second
1\t1\tserver/src/app.js
`;
const result = parseGitLog(raw);
expect(result['server/src/app.js']['Alice']).toBe(2);
});
it('tracks multiple authors for the same file', () => {
const raw = `commit aaa
Author: Alice <alice@example.com>
Date: Mon Jan 1 00:00:00 2024
Alice commit
2\t0\tclient/src/App.jsx
commit bbb
Author: Bob <bob@example.com>
Date: Tue Jan 2 00:00:00 2024
Bob commit
1\t0\tclient/src/App.jsx
`;
const result = parseGitLog(raw);
expect(result['client/src/App.jsx']['Alice']).toBe(1);
expect(result['client/src/App.jsx']['Bob']).toBe(1);
});
it('handles multiple files per commit', () => {
const raw = `commit aaa
Author: Alice <alice@example.com>
Date: Mon Jan 1 00:00:00 2024
Multi-file commit
2\t0\tserver/src/a.js
3\t1\tserver/src/b.js
`;
const result = parseGitLog(raw);
expect(result['server/src/a.js']['Alice']).toBe(1);
expect(result['server/src/b.js']['Alice']).toBe(1);
});
it('handles rename syntax (old => new)', () => {
const raw = `commit aaa
Author: Alice <alice@example.com>
Date: Mon Jan 1 00:00:00 2024
Rename
2\t0\told/path.js => new/path.js
`;
const result = parseGitLog(raw);
expect(result['new/path.js']).toBeDefined();
expect(result['old/path.js']).toBeUndefined();
});
it('returns empty object for empty log', () => {
expect(parseGitLog('')).toEqual({});
});
});
// --- computeOwnership ---
describe('computeOwnership', () => {
it('computes bus-factor of 1 for a solo author', () => {
const result = computeOwnership({ Alice: 10 });
expect(result.busFactor).toBe(1);
expect(result.totalCommits).toBe(10);
expect(result.primaryOwner.name).toBe('Alice');
expect(result.primaryOwner.pct).toBe(1);
});
it('computes bus-factor of 2 when two authors each own >= 10%', () => {
const result = computeOwnership({ Alice: 8, Bob: 2 });
expect(result.busFactor).toBe(2);
});
it('does not count authors below the threshold', () => {
// Bob has 5% — below default 10% threshold
const result = computeOwnership({ Alice: 19, Bob: 1 });
expect(result.busFactor).toBe(1);
});
it('respects a custom ownership threshold', () => {
// With 20% threshold, Bob (10%) doesn't count
const result = computeOwnership({ Alice: 9, Bob: 1 }, 0.2);
expect(result.busFactor).toBe(1);
});
it('sorts authors by commit count descending', () => {
const result = computeOwnership({ Alice: 3, Bob: 7, Carol: 5 });
expect(result.authors[0].name).toBe('Bob');
expect(result.authors[1].name).toBe('Carol');
expect(result.authors[2].name).toBe('Alice');
});
it('handles empty author counts gracefully', () => {
const result = computeOwnership({});
expect(result.totalCommits).toBe(0);
expect(result.busFactor).toBe(0);
expect(result.primaryOwner).toBeNull();
});
});
// --- scoreFiles ---
describe('scoreFiles', () => {
const ownership = {
'server/src/risk.js': { Alice: 9, Bob: 1 }, // bus-factor 1 (Bob < 10%)
'server/src/shared.js': { Alice: 5, Bob: 5 }, // bus-factor 2
'server/src/tiny.js': { Alice: 1 }, // below minCommits=2, filtered
};
it('filters files below minCommits', () => {
const results = scoreFiles(ownership, { minCommits: 2 });
expect(results.find(f => f.file === 'server/src/tiny.js')).toBeUndefined();
});
it('includes files at or above minCommits', () => {
const results = scoreFiles(ownership, { minCommits: 2 });
const files = results.map(f => f.file);
expect(files).toContain('server/src/risk.js');
expect(files).toContain('server/src/shared.js');
});
it('sorts lowest bus-factor first', () => {
const results = scoreFiles(ownership, { minCommits: 2 });
expect(results[0].file).toBe('server/src/risk.js');
expect(results[1].file).toBe('server/src/shared.js');
});
it('returns empty array for empty ownership', () => {
expect(scoreFiles({}, {})).toEqual([]);
});
});
// --- repoStats ---
describe('repoStats', () => {
it('returns zeros for empty input', () => {
const stats = repoStats([]);
expect(stats.avgBusFactor).toBe(0);
expect(stats.highRiskCount).toBe(0);
expect(stats.totalFiles).toBe(0);
});
it('counts high-risk files (busFactor === 1)', () => {
const files = [
{ busFactor: 1, totalCommits: 10, authors: [] },
{ busFactor: 2, totalCommits: 5, authors: [] },
{ busFactor: 1, totalCommits: 3, authors: [] },
];
const stats = repoStats(files);
expect(stats.highRiskCount).toBe(2);
expect(stats.totalFiles).toBe(3);
});
it('computes weighted average bus-factor', () => {
const files = [
{ busFactor: 1, totalCommits: 10, authors: [] },
{ busFactor: 3, totalCommits: 10, authors: [] },
];
const stats = repoStats(files);
// (1*10 + 3*10) / 20 = 2
expect(stats.avgBusFactor).toBe(2);
});
});

1161
scripts/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +0,0 @@
{
"name": "budget-scripts",
"version": "1.0.0",
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"bus-factor": "node bus-factor.mjs"
},
"devDependencies": {
"vitest": "^4.1.0"
}
}

View File

@@ -1,8 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
},
});

12
server/src/constants.js Normal file
View File

@@ -0,0 +1,12 @@
'use strict';
const CONFIG_KEYS = [
'paycheck1_day',
'paycheck2_day',
'paycheck1_gross',
'paycheck1_net',
'paycheck2_gross',
'paycheck2_net',
];
module.exports = { CONFIG_KEYS };

View File

@@ -2,6 +2,20 @@ const express = require('express');
const router = express.Router();
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) {
const { name, amount, due_day, assigned_paycheck, variable_amount } = body;
if (!name || name.toString().trim() === '') {

View File

@@ -1,21 +1,29 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const CONFIG_KEYS = [
'paycheck1_day',
'paycheck2_day',
'paycheck1_gross',
'paycheck1_net',
'paycheck2_gross',
'paycheck2_net',
];
const { CONFIG_KEYS } = require('../constants');
const DEFAULTS = {
paycheck1_day: 1,
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() {
const result = await pool.query(
'SELECT key, value FROM config WHERE key = ANY($1)',

View File

@@ -4,9 +4,20 @@ const { pool } = require('../db');
// ─── 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
// whether the plan is split across both paychecks (assigned_paycheck = null).
/**
* Count the number of payment periods remaining for a plan, starting from
* (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) {
const due = new Date(plan.due_date);
const dueYear = due.getFullYear();
@@ -19,7 +30,18 @@ function remainingPeriods(plan, year, month) {
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) {
const { rows } = await client.query(
`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));
}
// 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) {
const { rows } = await pool.query(
`SELECT

View File

@@ -2,15 +2,7 @@ const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const { calcPaymentAmount } = require('./financing');
const CONFIG_KEYS = [
'paycheck1_day',
'paycheck2_day',
'paycheck1_gross',
'paycheck1_net',
'paycheck2_gross',
'paycheck2_net',
];
const { CONFIG_KEYS } = require('../constants');
const CONFIG_DEFAULTS = {
paycheck1_day: 1,
@@ -43,9 +35,29 @@ function pad2(n) {
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
// and paycheck_bill_id: null — nothing is written to the DB.
/**
* Build virtual (unsaved) paycheck data from config + active bills.
*
* 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) {
const config = await getConfig();
const paychecks = [];
@@ -137,8 +149,19 @@ async function buildVirtualPaychecks(year, month) {
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) {
const config = await getConfig();
@@ -221,7 +244,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) {
const pcResult = await pool.query(
`SELECT id, period_year, period_month, paycheck_number, pay_date, gross, net