fix: reconcile split broker withdrawals

This commit is contained in:
admin committed 2026-08-28 23:52:53 +03:00
1 parent 19a924647e
commit 22e9656e92
5 files changed
+43 -15

No files matched your search

+6
View File
@@ -1,5 +1,11 @@
# Changelog
## [Backend 0.15.4] - 2026-08-28
### Fixed
- Reconcile split broker withdrawals with one aggregated transfer to a family account.
## [Backend 0.15.3] - 2026-08-28
### Fixed
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-budget/backend",
"version": "0.15.3",
"version": "0.15.4",
"private": true,
"scripts": {
"dev": "tsx watch src/app.ts",
+28 -12
View File
@@ -30,7 +30,7 @@ type PortfolioHistoryRow = {
total_valuation: string | number | null;
};
type PerformanceCashRow = { id: number | string; account_id: number | string; alias: string | null; bank: string; account_number: string; account_type: string | null; operation_at: string; amount_signed: number | string; description: string };
export type PerformanceCashRow = { id: number | string; account_id: number | string; alias: string | null; bank: string; account_number: string; account_type: string | null; operation_at: string; amount_signed: number | string; description: string };
type PerformanceTradeRow = { account_id: number | string; side: string; quantity: string | number; settlement_amount: string | number | null; settlement_commission: string | number | null; trade_commission: string | number | null; isin: string | null; instrument: string };
type PerformancePositionRow = { account_id: number | string; quantity: string | number; valuation: string | number | null; isin: string | null; instrument: string };
@@ -50,6 +50,31 @@ export function sumKnownPortfolioValuations(values: Array<number | null>): numbe
return known.length > 0 ? known.reduce((sum, value) => sum + value, 0) : null;
}
export function matchExternalCashTransfers(rows: PerformanceCashRow[]): Set<number | string> {
const broker = rows.filter((row) => ['brokerage', 'iis'].includes(row.account_type ?? ''));
const external = rows.filter((row) => !['brokerage', 'iis'].includes(row.account_type ?? ''));
const matchedBroker = new Set<number | string>();
const matchedExternal = new Set<number | string>();
for (const target of external) {
const targetAmount = Math.round(Number(target.amount_signed));
if (!targetAmount || matchedExternal.has(target.id)) continue;
const candidates = broker.filter((row) => !matchedBroker.has(row.id) && Math.sign(Number(row.amount_signed)) === -Math.sign(targetAmount) && Math.abs(Math.round(Number(row.amount_signed))) <= Math.abs(targetAmount) && Math.abs(Date.parse(row.operation_at) - Date.parse(target.operation_at)) <= 3 * 24 * 60 * 60 * 1000 && /вывод|сальдо расчетов|перевод|перечисление/.test(row.description.toLowerCase()));
const exact = candidates.find((row) => Math.round(Number(row.amount_signed)) === -targetAmount);
let group: PerformanceCashRow[] = exact ? [exact] : [];
if (group.length === 0) {
for (let index = 0; index < candidates.length && group.length === 0; index += 1) {
for (const second of candidates.slice(index + 1)) {
if (Math.round(Number(candidates[index].amount_signed)) + Math.round(Number(second.amount_signed)) === -targetAmount) { group = [candidates[index], second]; break; }
}
}
}
if (group.length === 0) continue;
matchedExternal.add(target.id);
group.forEach((row) => matchedBroker.add(row.id));
}
return matchedBroker;
}
function decimalValue(value: unknown, field: string, required = false): string | null {
if (value == null || value === '') {
if (required) throw new Error(`${field} is required`);
@@ -336,21 +361,12 @@ export async function getPortfolioPerformance(): Promise<PortfolioPerformanceRes
]);
const tradeMap = calculatePortfolioTradeResults(tradeResult.rows, positionResult.rows);
const accounts = new Map<number, PortfolioPerformanceResponse['accounts'][number]>();
const matchedExternalTransfers = new Set<number | string>();
const externalCash = cashResult.rows.filter((row) => !['brokerage', 'iis'].includes(row.account_type ?? ''));
const hasExternalTransfer = (row: PerformanceCashRow): boolean => {
const target = -Number(row.amount_signed);
const at = Date.parse(row.operation_at);
const match = externalCash.find((candidate) => !matchedExternalTransfers.has(candidate.id) && Number(candidate.amount_signed) === target && Math.abs(Date.parse(candidate.operation_at) - at) <= 3 * 24 * 60 * 60 * 1000 && /перевод|перечисление|счет|сч[её]т/.test(candidate.description.toLowerCase()));
if (!match) return false;
matchedExternalTransfers.add(match.id);
return true;
};
const matchedBrokerTransfers = matchExternalCashTransfers(cashResult.rows);
for (const row of cashResult.rows.filter((item) => ['brokerage', 'iis'].includes(item.account_type ?? ''))) {
const accountId = Number(row.account_id);
const account = accounts.get(accountId) ?? { accountId, accountName: row.alias || `${row.bank} · ${maskAccountNumber(row.account_number)}`, contributions: 0, withdrawals: 0, income: 0, fees: 0, realizedResult: 0, unrealizedResult: null };
const amount = Number(row.amount_signed);
const kind = classifyPortfolioCash(amount, row.description, hasExternalTransfer(row));
const kind = classifyPortfolioCash(amount, row.description, matchedBrokerTransfers.has(row.id));
if (kind === 'income') account.income += amount;
else if (kind === 'contribution') account.contributions += amount;
else if (kind === 'withdrawal') account.withdrawals += -amount;
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import { calculatePortfolioTradeResults, classifyPortfolioCash, sumKnownPortfolioValuations, toPortfolioHistory, toPortfolioOverview } from './portfolio';
import { calculatePortfolioTradeResults, classifyPortfolioCash, matchExternalCashTransfers, sumKnownPortfolioValuations, toPortfolioHistory, toPortfolioOverview } from './portfolio';
const result = toPortfolioOverview([
{ account_id: '1', alias: 'ИИС', bank: 'ВТБ', account_number: '123456', report_period_to: '2026-08-26', total_valuation: '150.50', instrument: 'Облигация', isin: 'RU0000000001', quantity: '1', price: '100', valuation: '100' },
@@ -35,4 +35,10 @@ assert.equal(classifyPortfolioCash(52000, 'Пополнение брокерск
assert.equal(classifyPortfolioCash(-129000, 'Вывод ДС под нерассчитанные сделки', true), 'withdrawal');
assert.equal(classifyPortfolioCash(-129000, 'Сальдо расчетов по сделкам с ценными бумагами', true), 'withdrawal');
assert.equal(sumKnownPortfolioValuations([100, null, 25]), 125);
const matched = matchExternalCashTransfers([
{ id: 1, account_id: 1, alias: null, bank: 'VTB', account_number: 'broker', account_type: 'brokerage', operation_at: '2026-05-12T00:00:00+03:00', amount_signed: '-5102321', description: 'Вывод ДС под нерассчитанные сделки' },
{ id: 2, account_id: 1, alias: null, bank: 'VTB', account_number: 'broker', account_type: 'brokerage', operation_at: '2026-05-13T00:00:00+03:00', amount_signed: '-4885479', description: 'Вывод ДС под нерассчитанные сделки' },
{ id: 3, account_id: 2, alias: null, bank: 'VTB', account_number: 'current', account_type: 'current', operation_at: '2026-05-12T00:00:00+03:00', amount_signed: '9987800', description: 'Вывод денежных средств с брокерского счета' },
]);
assert.deepEqual([...matched], [1, 2]);
console.log('portfolio cash classification: OK');
+1 -1
View File
@@ -15,7 +15,7 @@
},
"backend": {
"name": "@family-budget/backend",
"version": "0.15.3",
"version": "0.15.4",
"dependencies": {
"@family-budget/shared": "*",
"cookie-parser": "^1.4.7",