Compare commits
1 Commits
security/f
...
metrics-co
| Author | SHA1 | Date | |
|---|---|---|---|
| a1d7f55772 |
@@ -94,5 +94,3 @@ 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.
|
||||||
|
|
||||||
**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.
|
|
||||||
|
|||||||
251
scripts/metrics-coverage.js
Normal file
251
scripts/metrics-coverage.js
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* metrics-coverage.js — Static analysis script for metrics/logging instrumentation coverage.
|
||||||
|
*
|
||||||
|
* Scans all Express route files in server/src/routes/*.js and app.js to measure
|
||||||
|
* how many route handlers contain logging calls (console.error/console.warn/console.log).
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node scripts/metrics-coverage.js # JSON output (default)
|
||||||
|
* node scripts/metrics-coverage.js --format=text # Human-readable table
|
||||||
|
*
|
||||||
|
* Sample output (captured 2026-03-20):
|
||||||
|
* {
|
||||||
|
* "files": [
|
||||||
|
* { "file": "actuals.js", "total": 5, "logged": 5, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "bills.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "config.js", "total": 2, "logged": 2, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "financing.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "health.js", "total": 1, "logged": 0, "unlogged": 1, "coverage": 0 },
|
||||||
|
* { "file": "one-time-expenses.js", "total": 3, "logged": 3, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "paychecks.js", "total": 6, "logged": 6, "unlogged": 0, "coverage": 100 },
|
||||||
|
* { "file": "summary.js", "total": 2, "logged": 2, "unlogged": 0, "coverage": 100 }
|
||||||
|
* ],
|
||||||
|
* "app": {
|
||||||
|
* "has_request_timing_middleware": false,
|
||||||
|
* "has_error_handling_middleware": false,
|
||||||
|
* "middleware_count": 11
|
||||||
|
* },
|
||||||
|
* "aggregate": {
|
||||||
|
* "total_handlers": 31,
|
||||||
|
* "logged_handlers": 30,
|
||||||
|
* "unlogged_handlers": 1,
|
||||||
|
* "coverage_pct": 96.77
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ROUTES_DIR = path.resolve(__dirname, '../server/src/routes');
|
||||||
|
const APP_FILE = path.resolve(__dirname, '../server/src/app.js');
|
||||||
|
|
||||||
|
// Regex patterns for route handler definitions.
|
||||||
|
// Matches: router.get/post/put/patch/delete( and app.get/post/put/patch/delete(
|
||||||
|
const ROUTE_DEF_RE = /\b(?:router|app)\.(get|post|put|patch|delete)\s*\(/g;
|
||||||
|
|
||||||
|
// Logging call patterns
|
||||||
|
const LOG_RE = /\bconsole\.(error|warn|log)\s*\(/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract individual route handler bodies from source.
|
||||||
|
* Strategy: find each route definition, then walk forward counting
|
||||||
|
* braces to find the closing of the outermost async/function callback.
|
||||||
|
*/
|
||||||
|
function extractHandlerBodies(src) {
|
||||||
|
const handlers = [];
|
||||||
|
let match;
|
||||||
|
ROUTE_DEF_RE.lastIndex = 0;
|
||||||
|
|
||||||
|
while ((match = ROUTE_DEF_RE.exec(src)) !== null) {
|
||||||
|
const startIdx = match.index;
|
||||||
|
// Find the opening paren of the route call
|
||||||
|
const parenOpen = src.indexOf('(', startIdx);
|
||||||
|
if (parenOpen === -1) continue;
|
||||||
|
|
||||||
|
// Walk from the paren open, tracking paren depth to find the matching close.
|
||||||
|
// The handler callback body will be inside the outer parens.
|
||||||
|
let depth = 0;
|
||||||
|
let bodyStart = -1;
|
||||||
|
let bodyEnd = -1;
|
||||||
|
let inString = false;
|
||||||
|
let stringChar = '';
|
||||||
|
let i = parenOpen;
|
||||||
|
|
||||||
|
while (i < src.length) {
|
||||||
|
const ch = src[i];
|
||||||
|
|
||||||
|
// Basic string tracking (skip contents of string literals)
|
||||||
|
if (!inString && (ch === '"' || ch === "'" || ch === '`')) {
|
||||||
|
inString = true;
|
||||||
|
stringChar = ch;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (inString) {
|
||||||
|
if (ch === '\\') { i += 2; continue; } // skip escape
|
||||||
|
if (ch === stringChar) inString = false;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch === '(') {
|
||||||
|
depth++;
|
||||||
|
if (depth === 1) {
|
||||||
|
// This is the opening of the route call args
|
||||||
|
}
|
||||||
|
} else if (ch === ')') {
|
||||||
|
depth--;
|
||||||
|
if (depth === 0) {
|
||||||
|
bodyEnd = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if (ch === '{' && depth >= 1 && bodyStart === -1) {
|
||||||
|
// First brace inside the outer parens — start of the handler body
|
||||||
|
bodyStart = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bodyStart !== -1 && bodyEnd !== -1) {
|
||||||
|
handlers.push(src.slice(bodyStart, bodyEnd));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return handlers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyse a single route file.
|
||||||
|
*/
|
||||||
|
function analyseRouteFile(filePath) {
|
||||||
|
const src = fs.readFileSync(filePath, 'utf8');
|
||||||
|
const handlers = extractHandlerBodies(src);
|
||||||
|
|
||||||
|
const logged = handlers.filter(body => LOG_RE.test(body));
|
||||||
|
|
||||||
|
return {
|
||||||
|
file: path.basename(filePath),
|
||||||
|
total: handlers.length,
|
||||||
|
logged: logged.length,
|
||||||
|
unlogged: handlers.length - logged.length,
|
||||||
|
coverage: handlers.length === 0
|
||||||
|
? null
|
||||||
|
: Math.round((logged.length / handlers.length) * 10000) / 100,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyse app.js for middleware-level instrumentation.
|
||||||
|
*/
|
||||||
|
function analyseApp(filePath) {
|
||||||
|
const src = fs.readFileSync(filePath, 'utf8');
|
||||||
|
|
||||||
|
// Request timing: morgan, custom middleware checking req.method, Date.now() at top-level use()
|
||||||
|
const hasRequestTiming =
|
||||||
|
/\brequire\s*\(\s*['"]morgan['"]\s*\)/.test(src) ||
|
||||||
|
/app\.use\s*\(.*Date\.now\(\)/.test(src) ||
|
||||||
|
/app\.use\s*\(.*req,\s*res,\s*next/.test(src) && /Date\.now|performance\.now/.test(src);
|
||||||
|
|
||||||
|
// Error handling middleware: app.use((err, req, res, next) => ...)
|
||||||
|
const hasErrorHandling = /app\.use\s*\(\s*(?:\S+\s*,\s*)?\(\s*err\s*,/.test(src);
|
||||||
|
|
||||||
|
// Count top-level app.use() calls (middleware registrations)
|
||||||
|
const middlewareMatches = src.match(/app\.use\s*\(/g) || [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
has_request_timing_middleware: hasRequestTiming,
|
||||||
|
has_error_handling_middleware: hasErrorHandling,
|
||||||
|
middleware_count: middlewareMatches.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function run() {
|
||||||
|
const format = process.argv.includes('--format=text') ? 'text' : 'json';
|
||||||
|
|
||||||
|
// Analyse all route files
|
||||||
|
const routeFiles = fs.readdirSync(ROUTES_DIR)
|
||||||
|
.filter(f => f.endsWith('.js'))
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
const fileResults = routeFiles.map(f =>
|
||||||
|
analyseRouteFile(path.join(ROUTES_DIR, f))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Aggregate
|
||||||
|
const totalHandlers = fileResults.reduce((s, r) => s + r.total, 0);
|
||||||
|
const loggedHandlers = fileResults.reduce((s, r) => s + r.logged, 0);
|
||||||
|
|
||||||
|
const aggregate = {
|
||||||
|
total_handlers: totalHandlers,
|
||||||
|
logged_handlers: loggedHandlers,
|
||||||
|
unlogged_handlers: totalHandlers - loggedHandlers,
|
||||||
|
coverage_pct: totalHandlers === 0
|
||||||
|
? null
|
||||||
|
: Math.round((loggedHandlers / totalHandlers) * 10000) / 100,
|
||||||
|
};
|
||||||
|
|
||||||
|
const appInfo = analyseApp(APP_FILE);
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
files: fileResults,
|
||||||
|
app: appInfo,
|
||||||
|
aggregate,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (format === 'json') {
|
||||||
|
console.log(JSON.stringify(result, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text table
|
||||||
|
const COL_FILE = 28;
|
||||||
|
const COL_TOTAL = 7;
|
||||||
|
const COL_LOGGED = 8;
|
||||||
|
const COL_COVER = 10;
|
||||||
|
|
||||||
|
const pad = (s, n) => String(s).padEnd(n);
|
||||||
|
const lpad = (s, n) => String(s).padStart(n);
|
||||||
|
|
||||||
|
const hr = '-'.repeat(COL_FILE + COL_TOTAL + COL_LOGGED + COL_COVER + 6);
|
||||||
|
|
||||||
|
console.log('\nMetrics Instrumentation Coverage\n');
|
||||||
|
console.log(
|
||||||
|
pad('Route File', COL_FILE) +
|
||||||
|
lpad('Handlers', COL_TOTAL) +
|
||||||
|
lpad('Logged', COL_LOGGED) +
|
||||||
|
lpad('Coverage', COL_COVER)
|
||||||
|
);
|
||||||
|
console.log(hr);
|
||||||
|
|
||||||
|
for (const r of fileResults) {
|
||||||
|
const cov = r.coverage === null ? 'N/A' : `${r.coverage}%`;
|
||||||
|
console.log(
|
||||||
|
pad(r.file, COL_FILE) +
|
||||||
|
lpad(r.total, COL_TOTAL) +
|
||||||
|
lpad(r.logged, COL_LOGGED) +
|
||||||
|
lpad(cov, COL_COVER)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(hr);
|
||||||
|
const aggCov = aggregate.coverage_pct === null ? 'N/A' : `${aggregate.coverage_pct}%`;
|
||||||
|
console.log(
|
||||||
|
pad('TOTAL', COL_FILE) +
|
||||||
|
lpad(aggregate.total_handlers, COL_TOTAL) +
|
||||||
|
lpad(aggregate.logged_handlers, COL_LOGGED) +
|
||||||
|
lpad(aggCov, COL_COVER)
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('\napp.js middleware:');
|
||||||
|
console.log(` Request timing middleware : ${appInfo.has_request_timing_middleware}`);
|
||||||
|
console.log(` Error handling middleware : ${appInfo.has_error_handling_middleware}`);
|
||||||
|
console.log(` app.use() call count : ${appInfo.middleware_count}`);
|
||||||
|
console.log('');
|
||||||
|
}
|
||||||
|
|
||||||
|
run();
|
||||||
10
server/package-lock.json
generated
10
server/package-lock.json
generated
@@ -11,7 +11,6 @@
|
|||||||
"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": {
|
||||||
@@ -1283,15 +1282,6 @@
|
|||||||
"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,7 +12,6 @@
|
|||||||
"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,35 +131,3 @@ 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,39 +338,4 @@ 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,6 +1,5 @@
|
|||||||
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');
|
||||||
@@ -13,20 +12,8 @@ const { router: financingRouter } = require('./routes/financing');
|
|||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
const allowedOrigin = process.env.ALLOWED_ORIGIN || 'http://localhost:5173';
|
app.use(cors());
|
||||||
app.use(cors({ origin: allowedOrigin }));
|
app.use(express.json());
|
||||||
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);
|
||||||
|
|||||||
@@ -85,10 +85,8 @@ 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', [id]);
|
const result = await pool.query('SELECT * FROM bills WHERE id = $1', [req.params.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' });
|
||||||
}
|
}
|
||||||
@@ -101,9 +99,6 @@ 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 });
|
||||||
@@ -134,7 +129,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),
|
||||||
id,
|
req.params.id,
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
if (result.rows.length === 0) {
|
if (result.rows.length === 0) {
|
||||||
@@ -149,12 +144,10 @@ 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',
|
||||||
[id]
|
[req.params.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' });
|
||||||
@@ -168,12 +161,10 @@ 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 *',
|
||||||
[id]
|
[req.params.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' });
|
||||||
|
|||||||
@@ -109,11 +109,9 @@ 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', [id]
|
'SELECT * FROM financing_plans WHERE id = $1', [req.params.id]
|
||||||
);
|
);
|
||||||
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
||||||
|
|
||||||
@@ -138,9 +136,6 @@ 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' });
|
||||||
@@ -150,7 +145,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), id]
|
[name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), req.params.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]));
|
||||||
@@ -162,11 +157,9 @@ 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', [id]
|
'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [req.params.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 });
|
||||||
@@ -179,7 +172,6 @@ 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' });
|
||||||
|
|||||||
Reference in New Issue
Block a user