From 8d91bea7a9a867b99f2ef989a7f0be9616a6ee8f Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 20 Aug 2026 14:55:53 +0300 Subject: [PATCH 1/4] feat: add broker portfolio import --- CHANGELOG.md | 6 +++ backend/package.json | 2 +- backend/src/app.ts | 2 + backend/src/db/migrate.ts | 49 ++++++++++++++++++ backend/src/routes/portfolio.ts | 22 ++++++++ backend/src/services/portfolio.ts | 86 +++++++++++++++++++++++++++++++ shared/package.json | 2 +- shared/src/types/import.ts | 47 +++++++++++++++++ shared/src/types/index.ts | 4 ++ 9 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 backend/src/routes/portfolio.ts create mode 100644 backend/src/services/portfolio.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 84d40e8..ccad5d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Backend 0.8.0 / Shared 0.4.0] - 2026-08-20 + +### Added + +- Added portfolio JSON import for broker reports with idempotent trades, position snapshots, and separate portfolio tables. + ## [Backend 0.7.5 / Shared 0.3.1] - 2026-08-20 ### Added diff --git a/backend/package.json b/backend/package.json index 8d3a241..011f346 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "@family-budget/backend", - "version": "0.7.5", + "version": "0.8.0", "private": true, "scripts": { "dev": "tsx watch src/app.ts", diff --git a/backend/src/app.ts b/backend/src/app.ts index c38a6d4..4e2113f 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -19,6 +19,7 @@ import accountsRouter from './routes/accounts'; import categoriesRouter from './routes/categories'; import categoryRulesRouter from './routes/categoryRules'; import analyticsRouter from './routes/analytics'; +import portfolioRouter from './routes/portfolio'; const app = express(); app.set('trust proxy', 1); @@ -43,6 +44,7 @@ app.use('/api/accounts', accountsRouter); app.use('/api/categories', categoriesRouter); app.use('/api/category-rules', categoryRulesRouter); app.use('/api/analytics', analyticsRouter); +app.use('/api/import/portfolio', portfolioRouter); app.use( ( diff --git a/backend/src/db/migrate.ts b/backend/src/db/migrate.ts index f4abed1..2085a3c 100644 --- a/backend/src/db/migrate.ts +++ b/backend/src/db/migrate.ts @@ -238,6 +238,55 @@ const migrations: { name: string; sql: string }[] = [ CHECK (status IN ('active', 'closed')); `, }, + { + name: '008_portfolio_tables', + sql: ` + CREATE TABLE IF NOT EXISTS portfolio_reports ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id), + source_hash TEXT NOT NULL, + report_period_from DATE NOT NULL, + report_period_to DATE NOT NULL, + reported_at TIMESTAMPTZ, + imported_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (account_id, source_hash) + ); + CREATE TABLE IF NOT EXISTS portfolio_positions ( + id BIGSERIAL PRIMARY KEY, + report_id BIGINT NOT NULL REFERENCES portfolio_reports(id) ON DELETE CASCADE, + instrument TEXT NOT NULL, + isin TEXT, + quantity NUMERIC NOT NULL, + price NUMERIC, + valuation NUMERIC + ); + CREATE TABLE IF NOT EXISTS portfolio_trades ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id), + source_id TEXT NOT NULL, + operation_id UUID NOT NULL, + instrument TEXT NOT NULL, + isin TEXT, + concluded_at TIMESTAMPTZ NOT NULL, + side TEXT NOT NULL, + quantity NUMERIC NOT NULL, + price_currency TEXT, + price NUMERIC, + settlement_currency TEXT, + settlement_amount NUMERIC, + nkd NUMERIC, + settlement_commission NUMERIC, + trade_commission NUMERIC, + order_id TEXT, + trade_id TEXT, + venue TEXT, + comment TEXT, + UNIQUE (account_id, source_id) + ); + CREATE INDEX IF NOT EXISTS ix_portfolio_trades_account_date + ON portfolio_trades(account_id, concluded_at DESC); + `, + }, ]; export async function runMigrations(): Promise { diff --git a/backend/src/routes/portfolio.ts b/backend/src/routes/portfolio.ts new file mode 100644 index 0000000..0bccd4b --- /dev/null +++ b/backend/src/routes/portfolio.ts @@ -0,0 +1,22 @@ +import { Router } from 'express'; +import { asyncHandler } from '../utils'; +import * as portfolioService from '../services/portfolio'; + +const router = Router(); + +router.post( + '/', + asyncHandler(async (req, res) => { + try { + res.status(201).json(await portfolioService.importPortfolio(req.body)); + } catch (error) { + if (error instanceof Error && /Invalid|Duplicate|must be|required|numeric/.test(error.message)) { + res.status(422).json({ error: 'VALIDATION_ERROR', message: error.message }); + return; + } + throw error; + } + }), +); + +export default router; diff --git a/backend/src/services/portfolio.ts b/backend/src/services/portfolio.ts new file mode 100644 index 0000000..98c0c9e --- /dev/null +++ b/backend/src/services/portfolio.ts @@ -0,0 +1,86 @@ +import crypto from 'crypto'; +import { pool } from '../db/pool'; +import type { ImportPortfolioResponse, PortfolioFile, PortfolioTrade } from '@family-budget/shared'; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +function numberValue(value: unknown, field: string, required = false): number | null { + if (value == null || value === '') { + if (required) throw new Error(`${field} is required`); + return null; + } + const result = typeof value === 'number' ? value : Number(String(value).replace(/\s/g, '').replace(',', '.')); + if (!Number.isFinite(result)) throw new Error(`${field} must be numeric`); + return result; +} + +function validate(data: PortfolioFile): void { + if (data.schemaVersion !== 'broker-portfolio-1.0' || !data.bank || !data.accountNumber) throw new Error('Invalid portfolio file'); + if (!data.reportPeriod?.from || !data.reportPeriod?.to || Number.isNaN(Date.parse(data.reportPeriod.from)) || Number.isNaN(Date.parse(data.reportPeriod.to))) throw new Error('Invalid report period'); + if (!Array.isArray(data.positions) || !Array.isArray(data.trades)) throw new Error('positions and trades must be arrays'); + const sourceIds = new Set(); + for (const trade of data.trades) { + if (!trade.sourceId || !trade.instrument || !trade.concludedAt || !trade.side) throw new Error('Invalid trade'); + if (sourceIds.has(trade.sourceId)) throw new Error(`Duplicate sourceId: ${trade.sourceId}`); + sourceIds.add(trade.sourceId); + if (trade.operationId && !UUID_RE.test(trade.operationId)) throw new Error(`Invalid operationId: ${trade.sourceId}`); + numberValue(trade.quantity, 'quantity', true); + } + for (const position of data.positions) numberValue(position.quantity, 'position.quantity', true); +} + +export async function importPortfolio(body: unknown): Promise { + const data = body as PortfolioFile; + validate(data); + const sourceHash = crypto.createHash('sha256').update(JSON.stringify(data)).digest('hex'); + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const accountResult = await client.query( + `INSERT INTO accounts (bank, account_number, currency, account_type) + VALUES ($1, $2, 'RUB', 'brokerage') + ON CONFLICT (bank, account_number) DO UPDATE SET account_type = COALESCE(accounts.account_type, 'brokerage') + RETURNING id`, + [data.bank, data.accountNumber], + ); + const accountId = Number(accountResult.rows[0].id); + const reportResult = await client.query( + `INSERT INTO portfolio_reports (account_id, source_hash, report_period_from, report_period_to, reported_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (account_id, source_hash) DO NOTHING + RETURNING id`, + [accountId, sourceHash, data.reportPeriod.from, data.reportPeriod.to, data.reportedAt], + ); + if (reportResult.rows.length === 0) { + const existing = await client.query('SELECT id FROM portfolio_reports WHERE account_id = $1 AND source_hash = $2', [accountId, sourceHash]); + await client.query('COMMIT'); + return { accountId, reportId: Number(existing.rows[0].id), importedTrades: 0, duplicateTrades: data.trades.length, positions: 0 }; + } + const reportId = Number(reportResult.rows[0].id); + for (const position of data.positions) { + await client.query( + `INSERT INTO portfolio_positions (report_id, instrument, isin, quantity, price, valuation) + VALUES ($1, $2, $3, $4, $5, $6)`, + [reportId, position.instrument, position.isin ?? null, numberValue(position.quantity, 'position.quantity', true), numberValue(position.price, 'position.price'), numberValue(position.valuation, 'position.valuation')], + ); + } + let importedTrades = 0; + for (const trade of data.trades) { + const result = await client.query( + `INSERT INTO portfolio_trades + (account_id, source_id, operation_id, instrument, isin, concluded_at, side, quantity, price_currency, price, settlement_currency, settlement_amount, nkd, settlement_commission, trade_commission, order_id, trade_id, venue, comment) + VALUES ($1, $2, COALESCE($3::uuid, gen_random_uuid()), $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19) + ON CONFLICT (account_id, source_id) DO NOTHING`, + [accountId, trade.sourceId, trade.operationId ?? null, trade.instrument, trade.isin ?? null, trade.concludedAt, trade.side, numberValue(trade.quantity, 'quantity', true), trade.priceCurrency ?? null, numberValue(trade.price, 'price'), trade.settlementCurrency ?? null, numberValue(trade.settlementAmount, 'settlementAmount'), numberValue(trade.nkd, 'nkd'), numberValue(trade.settlementCommission, 'settlementCommission'), numberValue(trade.tradeCommission, 'tradeCommission'), trade.orderId ?? null, trade.tradeId ?? null, trade.venue ?? null, trade.comment ?? null], + ); + importedTrades += result.rowCount ?? 0; + } + await client.query('COMMIT'); + return { accountId, reportId, importedTrades, duplicateTrades: data.trades.length - importedTrades, positions: data.positions.length }; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} diff --git a/shared/package.json b/shared/package.json index e8be15f..a065070 100644 --- a/shared/package.json +++ b/shared/package.json @@ -1,6 +1,6 @@ { "name": "@family-budget/shared", - "version": "0.3.1", + "version": "0.4.0", "private": true, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/shared/src/types/import.ts b/shared/src/types/import.ts index d477af7..89161bc 100644 --- a/shared/src/types/import.ts +++ b/shared/src/types/import.ts @@ -46,3 +46,50 @@ export interface ImportStatementResponse { duplicatesSkipped: number; totalInFile: number; } + +export interface PortfolioFile { + schemaVersion: 'broker-portfolio-1.0'; + bank: string; + accountNumber: string; + reportPeriod: { from: string; to: string }; + reportedAt: string | null; + positions: PortfolioPosition[]; + trades: PortfolioTrade[]; +} + +export interface PortfolioPosition { + instrument: string; + isin?: string | null; + quantity: string | number; + price?: string | number | null; + valuation?: string | number | null; +} + +export interface PortfolioTrade { + sourceId: string; + operationId?: string; + instrument: string; + isin?: string | null; + concludedAt: string; + side: string; + quantity: string | number; + priceCurrency?: string | null; + price?: string | number | null; + settlementCurrency?: string | null; + settlementAmount?: string | number | null; + nkd?: string | number | null; + settlementCommission?: string | number | null; + tradeCommission?: string | number | null; + orderId?: string | null; + tradeId?: string | null; + venue?: string | null; + comment?: string | null; +} + +export interface ImportPortfolioResponse { + accountId: number; + reportId: number; + importedTrades: number; + duplicateTrades: number; + positions: number; +} diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index eaed6fa..c349e01 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -39,6 +39,10 @@ export type { StatementTransaction, ImportStatementResponse, Import, + PortfolioFile, + PortfolioPosition, + PortfolioTrade, + ImportPortfolioResponse, } from './import'; export type { -- 2.54.0 From e0da7e86ad19f3f58a915f22561c54e761c74bd4 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 20 Aug 2026 15:01:54 +0300 Subject: [PATCH 2/4] fix: harden portfolio import --- CHANGELOG.md | 6 ++++ backend/package.json | 3 +- backend/src/services/portfolio.test.ts | 12 +++++++ backend/src/services/portfolio.ts | 45 +++++++++++++++++--------- shared/src/types/import.ts | 2 +- 5 files changed, 51 insertions(+), 17 deletions(-) create mode 100644 backend/src/services/portfolio.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ccad5d6..c1232a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Backend 0.8.1] - 2026-08-20 + +### Fixed + +- Hardened portfolio import validation, preserved decimal precision, added fallback trade keys, and covered validation with a runnable test. + ## [Backend 0.8.0 / Shared 0.4.0] - 2026-08-20 ### Added diff --git a/backend/package.json b/backend/package.json index 011f346..3a3aab9 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "@family-budget/backend", - "version": "0.8.0", + "version": "0.8.1", "private": true, "scripts": { "dev": "tsx watch src/app.ts", @@ -9,6 +9,7 @@ "migrate": "tsx src/db/migrate.ts", "migrate:prod": "node dist/db/migrate.js", "test:analytics": "tsx src/services/analyticsSemantics.test.ts", + "test:portfolio": "tsx src/services/portfolio.test.ts", "test:analytics:db": "NODE_ENV=test tsx src/services/analytics.integration.test.ts", "test:import:db": "NODE_ENV=test tsx src/services/import.integration.test.ts", "test:llm": "tsx src/scripts/testLlm.ts" diff --git a/backend/src/services/portfolio.test.ts b/backend/src/services/portfolio.test.ts new file mode 100644 index 0000000..3ad6c11 --- /dev/null +++ b/backend/src/services/portfolio.test.ts @@ -0,0 +1,12 @@ +import assert from 'node:assert/strict'; +import { deriveTradeSourceId, validatePortfolio } from './portfolio'; + +const trade = { + instrument: 'Bond', isin: 'RU0000000001', concludedAt: '2026-08-20T10:00:00+03:00', + side: 'Покупка', quantity: '1.000', settlementAmount: '1234.50', +}; + +assert.equal(deriveTradeSourceId(trade), 'RU0000000001|2026-08-20T10:00:00+03:00|Покупка|1.000|1234.50'); +assert.throws(() => validatePortfolio(null), /object/); +assert.throws(() => validatePortfolio({ ...{ schemaVersion: 'broker-portfolio-1.0', bank: 'B', accountNumber: 'A', reportPeriod: { from: '2026-08-21', to: '2026-08-20' }, reportedAt: null, positions: [], trades: [] } }), /period/); +console.log('portfolio validation: OK'); diff --git a/backend/src/services/portfolio.ts b/backend/src/services/portfolio.ts index 98c0c9e..bdecec2 100644 --- a/backend/src/services/portfolio.ts +++ b/backend/src/services/portfolio.ts @@ -4,34 +4,48 @@ import type { ImportPortfolioResponse, PortfolioFile, PortfolioTrade } from '@fa const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -function numberValue(value: unknown, field: string, required = false): number | null { +function decimalValue(value: unknown, field: string, required = false): string | null { if (value == null || value === '') { if (required) throw new Error(`${field} is required`); return null; } - const result = typeof value === 'number' ? value : Number(String(value).replace(/\s/g, '').replace(',', '.')); - if (!Number.isFinite(result)) throw new Error(`${field} must be numeric`); + const result = String(value).replace(/\s/g, '').replace(',', '.'); + if (!/^-?(?:\d+\.?\d*|\.\d+)$/.test(result)) throw new Error(`${field} must be numeric`); return result; } -function validate(data: PortfolioFile): void { - if (data.schemaVersion !== 'broker-portfolio-1.0' || !data.bank || !data.accountNumber) throw new Error('Invalid portfolio file'); - if (!data.reportPeriod?.from || !data.reportPeriod?.to || Number.isNaN(Date.parse(data.reportPeriod.from)) || Number.isNaN(Date.parse(data.reportPeriod.to))) throw new Error('Invalid report period'); +export function deriveTradeSourceId(trade: PortfolioTrade): string { + if (trade.sourceId?.trim()) return trade.sourceId.trim(); + return [trade.isin || trade.instrument, trade.concludedAt, trade.side, decimalValue(trade.quantity, 'quantity', true), decimalValue(trade.settlementAmount, 'settlementAmount') || ''].join('|'); +} + +export function validatePortfolio(body: unknown): asserts body is PortfolioFile { + if (!body || typeof body !== 'object') throw new Error('Portfolio file must be an object'); + const data = body as PortfolioFile; + if (data.schemaVersion !== 'broker-portfolio-1.0' || typeof data.bank !== 'string' || !data.bank.trim() || typeof data.accountNumber !== 'string' || !data.accountNumber.trim()) throw new Error('Invalid portfolio file'); + if (!data.reportPeriod?.from || !data.reportPeriod?.to || Number.isNaN(Date.parse(data.reportPeriod.from)) || Number.isNaN(Date.parse(data.reportPeriod.to)) || data.reportPeriod.from > data.reportPeriod.to) throw new Error('Invalid report period'); + if (data.reportedAt !== null && (typeof data.reportedAt !== 'string' || Number.isNaN(Date.parse(data.reportedAt)))) throw new Error('Invalid reportedAt'); if (!Array.isArray(data.positions) || !Array.isArray(data.trades)) throw new Error('positions and trades must be arrays'); const sourceIds = new Set(); for (const trade of data.trades) { - if (!trade.sourceId || !trade.instrument || !trade.concludedAt || !trade.side) throw new Error('Invalid trade'); - if (sourceIds.has(trade.sourceId)) throw new Error(`Duplicate sourceId: ${trade.sourceId}`); - sourceIds.add(trade.sourceId); + if (!trade || typeof trade.instrument !== 'string' || !trade.instrument.trim() || typeof trade.concludedAt !== 'string' || Number.isNaN(Date.parse(trade.concludedAt)) || typeof trade.side !== 'string' || !trade.side.trim()) throw new Error('Invalid trade'); + const sourceId = deriveTradeSourceId(trade); + if (sourceIds.has(sourceId)) throw new Error(`Duplicate sourceId: ${sourceId}`); + sourceIds.add(sourceId); if (trade.operationId && !UUID_RE.test(trade.operationId)) throw new Error(`Invalid operationId: ${trade.sourceId}`); - numberValue(trade.quantity, 'quantity', true); + decimalValue(trade.quantity, 'quantity', true); + } + for (const position of data.positions) { + if (!position || typeof position.instrument !== 'string' || !position.instrument.trim()) throw new Error('Invalid position'); + decimalValue(position.quantity, 'position.quantity', true); + decimalValue(position.price, 'position.price'); + decimalValue(position.valuation, 'position.valuation'); } - for (const position of data.positions) numberValue(position.quantity, 'position.quantity', true); } export async function importPortfolio(body: unknown): Promise { - const data = body as PortfolioFile; - validate(data); + validatePortfolio(body); + const data = body; const sourceHash = crypto.createHash('sha256').update(JSON.stringify(data)).digest('hex'); const client = await pool.connect(); try { @@ -61,17 +75,18 @@ export async function importPortfolio(body: unknown): Promise Date: Thu, 20 Aug 2026 15:02:47 +0300 Subject: [PATCH 3/4] test: cover portfolio import idempotency --- CHANGELOG.md | 6 ++++ backend/package.json | 3 +- .../services/portfolio.integration.test.ts | 29 +++++++++++++++++++ backend/src/services/portfolio.ts | 4 +-- 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 backend/src/services/portfolio.integration.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c1232a2..5ecfebd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Backend 0.8.2] - 2026-08-20 + +### Added + +- Added a database integration test for repeated portfolio imports and trade deduplication. + ## [Backend 0.8.1] - 2026-08-20 ### Fixed diff --git a/backend/package.json b/backend/package.json index 3a3aab9..8b96d02 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "@family-budget/backend", - "version": "0.8.1", + "version": "0.8.2", "private": true, "scripts": { "dev": "tsx watch src/app.ts", @@ -10,6 +10,7 @@ "migrate:prod": "node dist/db/migrate.js", "test:analytics": "tsx src/services/analyticsSemantics.test.ts", "test:portfolio": "tsx src/services/portfolio.test.ts", + "test:portfolio:db": "NODE_ENV=test tsx src/services/portfolio.integration.test.ts", "test:analytics:db": "NODE_ENV=test tsx src/services/analytics.integration.test.ts", "test:import:db": "NODE_ENV=test tsx src/services/import.integration.test.ts", "test:llm": "tsx src/scripts/testLlm.ts" diff --git a/backend/src/services/portfolio.integration.test.ts b/backend/src/services/portfolio.integration.test.ts new file mode 100644 index 0000000..e6cf4bf --- /dev/null +++ b/backend/src/services/portfolio.integration.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { pool } from '../db/pool'; +import { importPortfolio } from './portfolio'; + +const payload = { + schemaVersion: 'broker-portfolio-1.0', bank: 'PORTFOLIO_TEST', accountNumber: 'portfolio-test', + reportPeriod: { from: '2026-08-01', to: '2026-08-20' }, reportedAt: '2026-08-20T00:00:00+03:00', + positions: [{ instrument: 'Test Bond', isin: 'RU0000000001', quantity: '1.000', price: '100.123456', valuation: '100.123456' }], + trades: [{ instrument: 'Test Bond', isin: 'RU0000000001', concludedAt: '2026-08-10T10:00:00+03:00', side: 'Покупка', quantity: '1.000', settlementAmount: '100.123456' }], +}; + +async function run(): Promise { + try { + const first = await importPortfolio(payload); + const second = await importPortfolio(payload); + assert.equal(first.importedTrades, 1); + assert.equal(second.duplicateTrades, 1); + const rows = await pool.query('SELECT COUNT(*)::int AS count FROM portfolio_trades WHERE account_id = $1', [first.accountId]); + assert.equal(rows.rows[0].count, 1); + console.log('portfolio import SQL: OK'); + } finally { + await pool.query("DELETE FROM portfolio_trades WHERE account_id IN (SELECT id FROM accounts WHERE bank = 'PORTFOLIO_TEST' AND account_number = 'portfolio-test')"); + await pool.query("DELETE FROM portfolio_reports WHERE account_id IN (SELECT id FROM accounts WHERE bank = 'PORTFOLIO_TEST' AND account_number = 'portfolio-test')"); + await pool.query("DELETE FROM accounts WHERE bank = 'PORTFOLIO_TEST' AND account_number = 'portfolio-test'"); + await pool.end(); + } +} + +run(); diff --git a/backend/src/services/portfolio.ts b/backend/src/services/portfolio.ts index bdecec2..da406f1 100644 --- a/backend/src/services/portfolio.ts +++ b/backend/src/services/portfolio.ts @@ -43,11 +43,11 @@ export function validatePortfolio(body: unknown): asserts body is PortfolioFile } } -export async function importPortfolio(body: unknown): Promise { +export async function importPortfolio(body: unknown, db: Pick = pool): Promise { validatePortfolio(body); const data = body; const sourceHash = crypto.createHash('sha256').update(JSON.stringify(data)).digest('hex'); - const client = await pool.connect(); + const client = await db.connect(); try { await client.query('BEGIN'); const accountResult = await client.query( -- 2.54.0 From d2354a61ed57fd1296df3baa5a3c8cbce8d88472 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 20 Aug 2026 15:04:04 +0300 Subject: [PATCH 4/4] fix: validate portfolio trade identifiers --- CHANGELOG.md | 6 ++++++ backend/package.json | 2 +- backend/src/services/portfolio.test.ts | 1 + backend/src/services/portfolio.ts | 2 ++ 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ecfebd..faec18f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Backend 0.8.3] - 2026-08-20 + +### Fixed + +- Invalid non-string trade identifiers now return validation errors instead of server errors. + ## [Backend 0.8.2] - 2026-08-20 ### Added diff --git a/backend/package.json b/backend/package.json index 8b96d02..7dbc83a 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "@family-budget/backend", - "version": "0.8.2", + "version": "0.8.3", "private": true, "scripts": { "dev": "tsx watch src/app.ts", diff --git a/backend/src/services/portfolio.test.ts b/backend/src/services/portfolio.test.ts index 3ad6c11..ef5f73e 100644 --- a/backend/src/services/portfolio.test.ts +++ b/backend/src/services/portfolio.test.ts @@ -8,5 +8,6 @@ const trade = { assert.equal(deriveTradeSourceId(trade), 'RU0000000001|2026-08-20T10:00:00+03:00|Покупка|1.000|1234.50'); assert.throws(() => validatePortfolio(null), /object/); +assert.throws(() => validatePortfolio({ schemaVersion: 'broker-portfolio-1.0', bank: 'B', accountNumber: 'A', reportPeriod: { from: '2026-08-20', to: '2026-08-20' }, reportedAt: null, positions: [], trades: [{ ...trade, sourceId: 42 }] }), /sourceId/); assert.throws(() => validatePortfolio({ ...{ schemaVersion: 'broker-portfolio-1.0', bank: 'B', accountNumber: 'A', reportPeriod: { from: '2026-08-21', to: '2026-08-20' }, reportedAt: null, positions: [], trades: [] } }), /period/); console.log('portfolio validation: OK'); diff --git a/backend/src/services/portfolio.ts b/backend/src/services/portfolio.ts index da406f1..19ceb3c 100644 --- a/backend/src/services/portfolio.ts +++ b/backend/src/services/portfolio.ts @@ -29,6 +29,8 @@ export function validatePortfolio(body: unknown): asserts body is PortfolioFile const sourceIds = new Set(); for (const trade of data.trades) { if (!trade || typeof trade.instrument !== 'string' || !trade.instrument.trim() || typeof trade.concludedAt !== 'string' || Number.isNaN(Date.parse(trade.concludedAt)) || typeof trade.side !== 'string' || !trade.side.trim()) throw new Error('Invalid trade'); + if (trade.sourceId !== undefined && typeof trade.sourceId !== 'string') throw new Error('sourceId must be a string'); + if (trade.operationId !== undefined && typeof trade.operationId !== 'string') throw new Error('operationId must be a string'); const sourceId = deriveTradeSourceId(trade); if (sourceIds.has(sourceId)) throw new Error(`Duplicate sourceId: ${sourceId}`); sourceIds.add(sourceId); -- 2.54.0