Compare commits
1 Commits
master
...
security/f
| Author | SHA1 | Date | |
|---|---|---|---|
| 481b5a536b |
@@ -24,22 +24,7 @@
|
|||||||
"Bash(npm run:*)",
|
"Bash(npm run:*)",
|
||||||
"Bash(/home/christian/.nvm/versions/node/v24.14.0/bin/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\" 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
2
.gitignore
vendored
@@ -41,5 +41,3 @@ Thumbs.db
|
|||||||
|
|
||||||
# Coverage
|
# Coverage
|
||||||
coverage/
|
coverage/
|
||||||
# Nightshift plan artifacts (keep out of version control)
|
|
||||||
.nightshift-plan
|
|
||||||
|
|||||||
86
CLAUDE.md
86
CLAUDE.md
@@ -77,8 +77,6 @@ cd client && npm run test:watch
|
|||||||
- Export pure functions (validators, formatters, etc.) for direct testing
|
- Export pure functions (validators, formatters, etc.) for direct testing
|
||||||
- Run `npm test` in both `server/` and `client/` before committing
|
- 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
|
## 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=`.
|
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=`.
|
||||||
@@ -97,86 +95,4 @@ The default route `/` renders the paycheck-centric main view (`client/src/pages/
|
|||||||
|
|
||||||
**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
|
**Security hardening:** `server/src/app.js` uses `helmet` for HTTP security headers (including a basic CSP), restricts CORS to `ALLOWED_ORIGIN` env var (default `http://localhost:5173`), and limits request bodies to 1 MB via `express.json({ limit: '1mb' })`. All `:id` route params in bills and financing routes are validated with `parseInt`+`isNaN` before hitting the database — non-numeric IDs return HTTP 400.
|
||||||
|
|
||||||
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. |
|
|
||||||
|
|||||||
@@ -2,18 +2,6 @@ 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');
|
||||||
@@ -37,13 +25,6 @@ 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,32 @@ import {
|
|||||||
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
|
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
|
||||||
Cell, ResponsiveContainer, ReferenceLine,
|
Cell, ResponsiveContainer, ReferenceLine,
|
||||||
} from 'recharts';
|
} from 'recharts';
|
||||||
import { MONTH_NAMES, PALETTE, fmt, formatCurrencyShort } from '../utils/formatting.js';
|
|
||||||
|
const MONTH_NAMES = [
|
||||||
|
'January', 'February', 'March', 'April', 'May', 'June',
|
||||||
|
'July', 'August', 'September', 'October', 'November', 'December',
|
||||||
|
];
|
||||||
|
|
||||||
const MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
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) {
|
function surplusClass(value) {
|
||||||
if (value == null || isNaN(Number(value))) return '';
|
if (value == null || isNaN(Number(value))) return '';
|
||||||
return Number(value) >= 0 ? 'text-success' : 'text-danger';
|
return Number(value) >= 0 ? 'text-success' : 'text-danger';
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { formatCurrency, ordinal } from '../utils/formatting.js';
|
|
||||||
|
|
||||||
const CATEGORIES = [
|
const CATEGORIES = [
|
||||||
'Housing', 'Utilities', 'Subscriptions', 'Insurance',
|
'Housing', 'Utilities', 'Subscriptions', 'Insurance',
|
||||||
@@ -15,6 +14,19 @@ const EMPTY_FORM = {
|
|||||||
variable_amount: false,
|
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() {
|
function Bills() {
|
||||||
const [bills, setBills] = useState([]);
|
const [bills, setBills] = useState([]);
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { fmt } from '../utils/formatting.js';
|
|
||||||
|
function fmt(value) {
|
||||||
|
const num = parseFloat(value) || 0;
|
||||||
|
return '$' + num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
|
}
|
||||||
|
|
||||||
function ProgressBar({ paid, total }) {
|
function ProgressBar({ paid, total }) {
|
||||||
const pct = total > 0 ? Math.min(100, (paid / total) * 100) : 0;
|
const pct = total > 0 ? Math.min(100, (paid / total) * 100) : 0;
|
||||||
|
|||||||
@@ -3,7 +3,25 @@ import {
|
|||||||
PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer,
|
PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer,
|
||||||
BarChart, Bar, XAxis, YAxis, CartesianGrid,
|
BarChart, Bar, XAxis, YAxis, CartesianGrid,
|
||||||
} from 'recharts';
|
} from 'recharts';
|
||||||
import { MONTH_NAMES, PALETTE, formatCurrency, formatCurrencyShort } from '../utils/formatting.js';
|
|
||||||
|
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'];
|
||||||
|
|
||||||
function StatCard({ label, value, valueClass }) {
|
function StatCard({ label, value, valueClass }) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,5 +1,20 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { MONTH_NAMES, formatCurrency, ordinal } from '../utils/formatting.js';
|
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
|
||||||
function formatPayDate(dateStr) {
|
function formatPayDate(dateStr) {
|
||||||
const [year, month, day] = dateStr.split('-').map(Number);
|
const [year, month, day] = dateStr.split('-').map(Number);
|
||||||
@@ -14,7 +29,7 @@ export { ordinal, formatCurrency, formatPayDate };
|
|||||||
|
|
||||||
// ─── PaycheckColumn ───────────────────────────────────────────────────────────
|
// ─── PaycheckColumn ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggle, onOteDelete, onOteAdd, onPaycheckGenerate, onPaycheckAmountSave, onBillAmountSave, onFinancingPaidToggle }) {
|
function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggle, onOteDelete, onOteAdd, onGenerate, onAmountSave, onBillAmountSave, onFinancingPaidToggle }) {
|
||||||
const [newOteName, setNewOteName] = useState('');
|
const [newOteName, setNewOteName] = useState('');
|
||||||
const [newOteAmount, setNewOteAmount] = useState('');
|
const [newOteAmount, setNewOteAmount] = useState('');
|
||||||
const [actuals, setActuals] = useState([]);
|
const [actuals, setActuals] = useState([]);
|
||||||
@@ -80,7 +95,7 @@ function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggl
|
|||||||
// Lazy generate if this is a virtual paycheck
|
// Lazy generate if this is a virtual paycheck
|
||||||
let paycheckId = paycheck.id;
|
let paycheckId = paycheck.id;
|
||||||
if (!paycheckId) {
|
if (!paycheckId) {
|
||||||
const generated = await onPaycheckGenerate();
|
const generated = await onGenerate();
|
||||||
paycheckId = generated.find(p => p.paycheck_number === paycheck.paycheck_number).id;
|
paycheckId = generated.find(p => p.paycheck_number === paycheck.paycheck_number).id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,7 +151,7 @@ function PaycheckColumn({ paycheck, onBillPaidToggle, categories, onOtePaidToggl
|
|||||||
setAmountSaving(true);
|
setAmountSaving(true);
|
||||||
setAmountError(null);
|
setAmountError(null);
|
||||||
try {
|
try {
|
||||||
await onPaycheckAmountSave(paycheck.paycheck_number, parseFloat(editGross) || 0, parseFloat(editNet) || 0);
|
await onAmountSave(paycheck.paycheck_number, parseFloat(editGross) || 0, parseFloat(editNet) || 0);
|
||||||
setEditingAmounts(false);
|
setEditingAmounts(false);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setAmountError(err.message);
|
setAmountError(err.message);
|
||||||
@@ -740,8 +755,8 @@ function PaycheckView() {
|
|||||||
onOteDelete={handleOteDelete}
|
onOteDelete={handleOteDelete}
|
||||||
onOteAdd={handleOteAdd}
|
onOteAdd={handleOteAdd}
|
||||||
categories={categories}
|
categories={categories}
|
||||||
onPaycheckGenerate={generateMonth}
|
onGenerate={generateMonth}
|
||||||
onPaycheckAmountSave={handleAmountSave}
|
onAmountSave={handleAmountSave}
|
||||||
onBillAmountSave={handleBillAmountSave}
|
onBillAmountSave={handleBillAmountSave}
|
||||||
onFinancingPaidToggle={handleFinancingPaidToggle}
|
onFinancingPaidToggle={handleFinancingPaidToggle}
|
||||||
/>
|
/>
|
||||||
@@ -752,8 +767,8 @@ function PaycheckView() {
|
|||||||
onOteDelete={handleOteDelete}
|
onOteDelete={handleOteDelete}
|
||||||
onOteAdd={handleOteAdd}
|
onOteAdd={handleOteAdd}
|
||||||
categories={categories}
|
categories={categories}
|
||||||
onPaycheckGenerate={generateMonth}
|
onGenerate={generateMonth}
|
||||||
onPaycheckAmountSave={handleAmountSave}
|
onAmountSave={handleAmountSave}
|
||||||
onBillAmountSave={handleBillAmountSave}
|
onBillAmountSave={handleBillAmountSave}
|
||||||
onFinancingPaidToggle={handleFinancingPaidToggle}
|
onFinancingPaidToggle={handleFinancingPaidToggle}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
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}`;
|
|
||||||
}
|
|
||||||
10
server/package-lock.json
generated
10
server/package-lock.json
generated
@@ -11,6 +11,7 @@
|
|||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.4.5",
|
"dotenv": "^16.4.5",
|
||||||
"express": "^4.19.2",
|
"express": "^4.19.2",
|
||||||
|
"helmet": "^8.1.0",
|
||||||
"pg": "^8.11.5"
|
"pg": "^8.11.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -1282,6 +1283,15 @@
|
|||||||
"node": ">= 0.4"
|
"node": ">= 0.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/helmet": {
|
||||||
|
"version": "8.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz",
|
||||||
|
"integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/http-errors": {
|
"node_modules/http-errors": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.4.5",
|
"dotenv": "^16.4.5",
|
||||||
"express": "^4.19.2",
|
"express": "^4.19.2",
|
||||||
|
"helmet": "^8.1.0",
|
||||||
"pg": "^8.11.5"
|
"pg": "^8.11.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -131,3 +131,35 @@ describe('PATCH /api/bills/:id/toggle', () => {
|
|||||||
expect(res.body).toEqual(toggled);
|
expect(res.body).toEqual(toggled);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ID validation — bills routes', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
db.pool.query.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/bills/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app).get('/api/bills/abc');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('PUT /api/bills/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.put('/api/bills/abc')
|
||||||
|
.send({ name: 'X', amount: 10, due_day: 1, assigned_paycheck: 1 });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DELETE /api/bills/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app).delete('/api/bills/abc');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('PATCH /api/bills/:id/toggle returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app).patch('/api/bills/abc/toggle');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -338,4 +338,39 @@ describe('PATCH /api/financing-payments/:id/paid', () => {
|
|||||||
expect(res.status).toBe(404);
|
expect(res.status).toBe(404);
|
||||||
expect(res.body).toEqual({ error: 'Payment not found' });
|
expect(res.body).toEqual({ error: 'Payment not found' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('returns 400 for non-numeric payment id', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.patch('/api/financing-payments/abc/paid')
|
||||||
|
.send({ paid: true });
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ID validation — financing routes', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/financing/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app).get('/api/financing/abc');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('PUT /api/financing/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.put('/api/financing/abc')
|
||||||
|
.send({ name: 'X', total_amount: 100, due_date: '2027-01-01' });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DELETE /api/financing/:id returns 400 for non-numeric id', async () => {
|
||||||
|
const res = await request(app).delete('/api/financing/abc');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body).toEqual({ error: 'Invalid id' });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
|
const helmet = require('helmet');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const healthRouter = require('./routes/health');
|
const healthRouter = require('./routes/health');
|
||||||
const configRouter = require('./routes/config');
|
const configRouter = require('./routes/config');
|
||||||
@@ -12,8 +13,20 @@ const { router: financingRouter } = require('./routes/financing');
|
|||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
app.use(cors());
|
const allowedOrigin = process.env.ALLOWED_ORIGIN || 'http://localhost:5173';
|
||||||
app.use(express.json());
|
app.use(cors({ origin: allowedOrigin }));
|
||||||
|
app.use(helmet({
|
||||||
|
contentSecurityPolicy: {
|
||||||
|
directives: {
|
||||||
|
defaultSrc: ["'self'"],
|
||||||
|
scriptSrc: ["'self'"],
|
||||||
|
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||||
|
imgSrc: ["'self'", 'data:'],
|
||||||
|
connectSrc: ["'self'"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
app.use(express.json({ limit: '1mb' }));
|
||||||
|
|
||||||
// API routes
|
// API routes
|
||||||
app.use('/api', healthRouter);
|
app.use('/api', healthRouter);
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const CONFIG_KEYS = [
|
|
||||||
'paycheck1_day',
|
|
||||||
'paycheck2_day',
|
|
||||||
'paycheck1_gross',
|
|
||||||
'paycheck1_net',
|
|
||||||
'paycheck2_gross',
|
|
||||||
'paycheck2_net',
|
|
||||||
];
|
|
||||||
|
|
||||||
module.exports = { CONFIG_KEYS };
|
|
||||||
@@ -2,20 +2,6 @@ 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 (1–31).
|
|
||||||
* @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() === '') {
|
||||||
@@ -99,8 +85,10 @@ router.post('/bills', async (req, res) => {
|
|||||||
|
|
||||||
// GET /api/bills/:id — get single bill
|
// GET /api/bills/:id — get single bill
|
||||||
router.get('/bills/:id', async (req, res) => {
|
router.get('/bills/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
try {
|
try {
|
||||||
const result = await pool.query('SELECT * FROM bills WHERE id = $1', [req.params.id]);
|
const result = await pool.query('SELECT * FROM bills WHERE id = $1', [id]);
|
||||||
if (result.rows.length === 0) {
|
if (result.rows.length === 0) {
|
||||||
return res.status(404).json({ error: 'Bill not found' });
|
return res.status(404).json({ error: 'Bill not found' });
|
||||||
}
|
}
|
||||||
@@ -113,6 +101,9 @@ router.get('/bills/:id', async (req, res) => {
|
|||||||
|
|
||||||
// PUT /api/bills/:id — update bill
|
// PUT /api/bills/:id — update bill
|
||||||
router.put('/bills/:id', async (req, res) => {
|
router.put('/bills/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
|
|
||||||
const validationError = validateBillFields(req.body);
|
const validationError = validateBillFields(req.body);
|
||||||
if (validationError) {
|
if (validationError) {
|
||||||
return res.status(400).json({ error: validationError });
|
return res.status(400).json({ error: validationError });
|
||||||
@@ -143,7 +134,7 @@ router.put('/bills/:id', async (req, res) => {
|
|||||||
category || 'General',
|
category || 'General',
|
||||||
active !== undefined ? active : true,
|
active !== undefined ? active : true,
|
||||||
Boolean(variable_amount),
|
Boolean(variable_amount),
|
||||||
req.params.id,
|
id,
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
if (result.rows.length === 0) {
|
if (result.rows.length === 0) {
|
||||||
@@ -158,10 +149,12 @@ router.put('/bills/:id', async (req, res) => {
|
|||||||
|
|
||||||
// DELETE /api/bills/:id — hard delete
|
// DELETE /api/bills/:id — hard delete
|
||||||
router.delete('/bills/:id', async (req, res) => {
|
router.delete('/bills/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
try {
|
try {
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
'DELETE FROM bills WHERE id = $1 RETURNING id',
|
'DELETE FROM bills WHERE id = $1 RETURNING id',
|
||||||
[req.params.id]
|
[id]
|
||||||
);
|
);
|
||||||
if (result.rows.length === 0) {
|
if (result.rows.length === 0) {
|
||||||
return res.status(404).json({ error: 'Bill not found' });
|
return res.status(404).json({ error: 'Bill not found' });
|
||||||
@@ -175,10 +168,12 @@ router.delete('/bills/:id', async (req, res) => {
|
|||||||
|
|
||||||
// PATCH /api/bills/:id/toggle — toggle active field
|
// PATCH /api/bills/:id/toggle — toggle active field
|
||||||
router.patch('/bills/:id/toggle', async (req, res) => {
|
router.patch('/bills/:id/toggle', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
try {
|
try {
|
||||||
const result = await pool.query(
|
const result = await pool.query(
|
||||||
'UPDATE bills SET active = NOT active WHERE id = $1 RETURNING *',
|
'UPDATE bills SET active = NOT active WHERE id = $1 RETURNING *',
|
||||||
[req.params.id]
|
[id]
|
||||||
);
|
);
|
||||||
if (result.rows.length === 0) {
|
if (result.rows.length === 0) {
|
||||||
return res.status(404).json({ error: 'Bill not found' });
|
return res.status(404).json({ error: 'Bill not found' });
|
||||||
|
|||||||
@@ -1,29 +1,21 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { pool } = require('../db');
|
const { pool } = require('../db');
|
||||||
const { CONFIG_KEYS } = require('../constants');
|
|
||||||
|
const CONFIG_KEYS = [
|
||||||
|
'paycheck1_day',
|
||||||
|
'paycheck2_day',
|
||||||
|
'paycheck1_gross',
|
||||||
|
'paycheck1_net',
|
||||||
|
'paycheck2_gross',
|
||||||
|
'paycheck2_net',
|
||||||
|
];
|
||||||
|
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
paycheck1_day: 1,
|
paycheck1_day: 1,
|
||||||
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)',
|
||||||
|
|||||||
@@ -4,20 +4,9 @@ const { pool } = require('../db');
|
|||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
// Count how many payment periods remain for a plan starting from (year, month),
|
||||||
* Count the number of payment periods remaining for a plan, starting from
|
// including that month. Each month contributes 1 or 2 periods depending on
|
||||||
* (and including) the given year/month.
|
// whether the plan is split across both paychecks (assigned_paycheck = null).
|
||||||
*
|
|
||||||
* 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 (1–12).
|
|
||||||
* @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();
|
||||||
@@ -30,18 +19,7 @@ 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 (1–12) 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
|
||||||
@@ -57,22 +35,7 @@ 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
|
||||||
@@ -146,9 +109,11 @@ router.post('/financing', async (req, res) => {
|
|||||||
|
|
||||||
// GET /api/financing/:id
|
// GET /api/financing/:id
|
||||||
router.get('/financing/:id', async (req, res) => {
|
router.get('/financing/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
try {
|
try {
|
||||||
const { rows } = await pool.query(
|
const { rows } = await pool.query(
|
||||||
'SELECT * FROM financing_plans WHERE id = $1', [req.params.id]
|
'SELECT * FROM financing_plans WHERE id = $1', [id]
|
||||||
);
|
);
|
||||||
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
||||||
|
|
||||||
@@ -173,6 +138,9 @@ router.get('/financing/:id', async (req, res) => {
|
|||||||
|
|
||||||
// PUT /api/financing/:id
|
// PUT /api/financing/:id
|
||||||
router.put('/financing/:id', async (req, res) => {
|
router.put('/financing/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
|
|
||||||
const { name, total_amount, due_date, assigned_paycheck, start_date } = req.body;
|
const { name, total_amount, due_date, assigned_paycheck, start_date } = req.body;
|
||||||
if (!name || !total_amount || !due_date) {
|
if (!name || !total_amount || !due_date) {
|
||||||
return res.status(400).json({ error: 'name, total_amount, and due_date are required' });
|
return res.status(400).json({ error: 'name, total_amount, and due_date are required' });
|
||||||
@@ -182,7 +150,7 @@ router.put('/financing/:id', async (req, res) => {
|
|||||||
const { rows } = await pool.query(
|
const { rows } = await pool.query(
|
||||||
`UPDATE financing_plans SET name=$1, total_amount=$2, due_date=$3, assigned_paycheck=$4, start_date=$5
|
`UPDATE financing_plans SET name=$1, total_amount=$2, due_date=$3, assigned_paycheck=$4, start_date=$5
|
||||||
WHERE id=$6 RETURNING *`,
|
WHERE id=$6 RETURNING *`,
|
||||||
[name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), req.params.id]
|
[name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), id]
|
||||||
);
|
);
|
||||||
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
||||||
res.json(await enrichPlan(pool, rows[0]));
|
res.json(await enrichPlan(pool, rows[0]));
|
||||||
@@ -194,9 +162,11 @@ router.put('/financing/:id', async (req, res) => {
|
|||||||
|
|
||||||
// DELETE /api/financing/:id
|
// DELETE /api/financing/:id
|
||||||
router.delete('/financing/:id', async (req, res) => {
|
router.delete('/financing/:id', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
try {
|
try {
|
||||||
const { rows } = await pool.query(
|
const { rows } = await pool.query(
|
||||||
'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [req.params.id]
|
'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [id]
|
||||||
);
|
);
|
||||||
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
||||||
res.json({ deleted: true });
|
res.json({ deleted: true });
|
||||||
@@ -209,6 +179,7 @@ router.delete('/financing/:id', async (req, res) => {
|
|||||||
// PATCH /api/financing-payments/:id/paid
|
// PATCH /api/financing-payments/:id/paid
|
||||||
router.patch('/financing-payments/:id/paid', async (req, res) => {
|
router.patch('/financing-payments/:id/paid', async (req, res) => {
|
||||||
const id = parseInt(req.params.id, 10);
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
|
||||||
const { paid } = req.body;
|
const { paid } = req.body;
|
||||||
if (typeof paid !== 'boolean') {
|
if (typeof paid !== 'boolean') {
|
||||||
return res.status(400).json({ error: 'paid must be a boolean' });
|
return res.status(400).json({ error: 'paid must be a boolean' });
|
||||||
|
|||||||
@@ -2,7 +2,15 @@ const express = require('express');
|
|||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { pool } = require('../db');
|
const { pool } = require('../db');
|
||||||
const { calcPaymentAmount } = require('./financing');
|
const { calcPaymentAmount } = require('./financing');
|
||||||
const { CONFIG_KEYS } = require('../constants');
|
|
||||||
|
const CONFIG_KEYS = [
|
||||||
|
'paycheck1_day',
|
||||||
|
'paycheck2_day',
|
||||||
|
'paycheck1_gross',
|
||||||
|
'paycheck1_net',
|
||||||
|
'paycheck2_gross',
|
||||||
|
'paycheck2_net',
|
||||||
|
];
|
||||||
|
|
||||||
const CONFIG_DEFAULTS = {
|
const CONFIG_DEFAULTS = {
|
||||||
paycheck1_day: 1,
|
paycheck1_day: 1,
|
||||||
@@ -35,29 +43,9 @@ function pad2(n) {
|
|||||||
return String(n).padStart(2, '0');
|
return String(n).padStart(2, '0');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Build virtual (unsaved) paycheck data from config + active bills.
|
||||||
* 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.
|
||||||
* 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 1–12.
|
|
||||||
* @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 = [];
|
||||||
@@ -149,19 +137,8 @@ async function buildVirtualPaychecks(year, month) {
|
|||||||
return paychecks;
|
return paychecks;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Generate (upsert) paycheck records for the given year/month.
|
||||||
* Generate (upsert) paycheck records for the given year/month.
|
// Returns the two paycheck IDs.
|
||||||
*
|
|
||||||
* 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 1–12.
|
|
||||||
* @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();
|
||||||
|
|
||||||
@@ -244,25 +221,7 @@ 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 1–12.
|
|
||||||
* @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
|
||||||
|
|||||||
Reference in New Issue
Block a user