feat!: persist T-Bank data and synchronize reads
Backend security / security (push) Successful in 8s
Backend verify / verify (push) Failing after 10m45s
Conventional commits / commits (pull_request) Successful in 29s
Backend security / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Failing after 10m37s

Store account membership, portfolio, operations, forecasts and market sources in SQLite.
Coalesce scoped refreshes, fence connection revisions, preserve complete financial
snapshots and stabilize operation period state.

BREAKING CHANGE: investment reads return data/meta resource envelopes and locally
persisted snapshots; consumers must use the matching OpenAPI contract and explicit
synchronization endpoints.
This commit is contained in:
2026-09-26 21:29:15 +03:00
parent 0862d56c4e
commit d6e6c4ace5
116 changed files with 18321 additions and 5409 deletions
@@ -1,3 +1,4 @@
import { InvestmentResourceMetaDto } from '../investment-resource.dto';
import { ApiProperty } from '@nestjs/swagger';
import { MoneyDto } from '../../../common/money.dto';
@@ -44,3 +45,10 @@ export class BrokerageAccountDto {
@ApiProperty({ type: PortfolioSummaryDto, nullable: true })
portfolioSummary?: PortfolioSummaryDto | null;
}
export class BrokerageAccountsResourceDto {
@ApiProperty({ type: BrokerageAccountDto, isArray: true, nullable: true })
declare data: BrokerageAccountDto[] | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
@@ -0,0 +1 @@
export { BrokerageAccountsService } from './brokerage-accounts.service';
@@ -1,9 +1,10 @@
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { InvestmentReadQueryDto } from '../investment-resource.dto';
import { Controller, Get, Req, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import type { Request } from 'express';
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
import { BrokerageAccountDto } from './brokerage-account.dto';
import { BrokerageAccountsResourceDto } from './brokerage-account.dto';
import { BrokerageAccountsService } from './brokerage-accounts.service';
@ApiTags('brokerage-accounts')
@@ -15,8 +16,11 @@ export class BrokerageAccountsController {
constructor(private readonly accounts: BrokerageAccountsService) {}
@Get()
@ApiOkResponse({ type: BrokerageAccountDto, isArray: true })
list(@Req() request: Request & { user: AccessPayload }) {
return this.accounts.list(request.user.sub);
@ApiOkResponse({ type: BrokerageAccountsResourceDto })
list(
@Req() request: Request & { user: AccessPayload },
@Query() query: InvestmentReadQueryDto,
) {
return this.accounts.list(request.user.sub, query.sync === 'observe');
}
}
@@ -1,3 +1,4 @@
import { PortfolioModule } from '../portfolio/portfolio.module';
import { Module } from '@nestjs/common';
import { TbankModule } from '../../../integrations/tbank/tbank.module';
import { AuthModule } from '../../auth/auth.module';
@@ -5,8 +6,9 @@ import { BrokerageAccountsController } from './brokerage-accounts.controller';
import { BrokerageAccountsService } from './brokerage-accounts.service';
@Module({
imports: [AuthModule, TbankModule],
imports: [AuthModule, TbankModule, PortfolioModule],
controllers: [BrokerageAccountsController],
providers: [BrokerageAccountsService],
exports: [BrokerageAccountsService],
})
export class BrokerageAccountsModule {}
@@ -1,249 +1,70 @@
import {
BadRequestException,
ConflictException,
ServiceUnavailableException,
} from '@nestjs/common';
jest.mock('../../../prisma/prisma.service', () => ({
PrismaService: class PrismaService {},
PrismaService: class {},
}));
import { BrokerageAccountsService } from './brokerage-accounts.service';
import { investmentResourceMeta } from '../investment-resource.mapper';
jest.mock('../portfolio/application/portfolio.service', () => ({
PortfolioService: class PortfolioService {},
}));
import { TbankAccessService } from '../../../integrations/tbank/tbank-access.service';
import { TbankTokenService } from '../../../integrations/tbank/tbank-token.service';
import { BrokerageAccountsService } from './brokerage-accounts.service';
const meta = investmentResourceMeta({
resourceKey: 'membership',
dataRevision: '1',
availability: 'complete',
fetchedAt: new Date(),
freshForMs: 300_000,
work: null,
});
describe('BrokerageAccountsService', () => {
const encryptionKey = 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=';
const prisma = { tbankConnection: { findUnique: jest.fn() } };
const config = { getOrThrow: jest.fn(() => encryptionKey) };
const tbank = {
getOpenAccounts: jest.fn(),
getPortfolio: jest.fn(),
getPositions: jest.fn(),
};
const tokens = new TbankTokenService(config as never);
const access = new TbankAccessService(
prisma as never,
tokens,
tbank as never,
);
const service = new BrokerageAccountsService(access, tbank as never);
describe('saved brokerage account projection', () => {
const portfolio = { saved: jest.fn() };
const service = new BrokerageAccountsService(portfolio as never);
beforeEach(() => {
jest.clearAllMocks();
tbank.getPortfolio.mockResolvedValue({ positions: [] });
tbank.getPositions.mockResolvedValue({ money: [] });
});
it('does not call T-Bank without a connection', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue(null);
await expect(service.list('user-1')).rejects.toEqual(
expect.any(ConflictException),
);
expect(tbank.getOpenAccounts).not.toHaveBeenCalled();
});
it('normalizes supported accounts and ignores unsupported ones', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
it('distinguishes unknown membership from a confirmed empty list', async () => {
portfolio.saved.mockResolvedValueOnce({
membership: { ...meta, availability: 'missing' },
accounts: [],
});
tbank.getOpenAccounts.mockResolvedValue([
{
id: 'brokerage',
type: 'ACCOUNT_TYPE_TINKOFF',
name: ' Основной ',
openedDate: { seconds: '1723507200' },
},
{
id: 'debit',
type: 'ACCOUNT_TYPE_DEBIT',
name: 'Дебетовый',
},
{
id: 'iis',
type: 'ACCOUNT_TYPE_TINKOFF_IIS',
name: ' ',
},
]);
await expect(service.list('user-1')).resolves.toEqual([
{
id: 'brokerage',
type: 'BROKERAGE',
name: 'Основной',
openedOn: '2024-08-13',
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 0,
bondPositionCount: 0,
},
},
{
id: 'iis',
type: 'INDIVIDUAL_INVESTMENT',
name: 'ИИС',
openedOn: null,
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 0,
bondPositionCount: 0,
},
},
]);
expect((await service.list('owner', true)).data).toBeNull();
portfolio.saved.mockResolvedValueOnce({ membership: meta, accounts: [] });
expect((await service.list('owner', true)).data).toEqual([]);
});
it('keeps upstream order and adds exact summaries without loading metadata', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockResolvedValue([
{ id: 'first', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Первый' },
{ id: 'second', type: 'ACCOUNT_TYPE_TINKOFF_IIS', name: 'Второй' },
]);
tbank.getPortfolio
.mockResolvedValueOnce({
positions: [
{
quantity: { units: 2 },
currentPrice: { currency: 'rub', units: 3 },
it('keeps exact saved totals and independent missing summaries', async () => {
portfolio.saved.mockResolvedValue({
membership: meta,
accounts: [
{
id: 'a',
name: 'A',
type: 'BROKERAGE',
openedOn: null,
meta,
snapshot: {
totalsByCurrency: [
{ currency: 'RUB', value: '100000000.000000001' },
],
positions: [{ type: 'STOCK' }, { type: 'BOND' }],
},
],
})
.mockResolvedValueOnce({ positions: [] });
tbank.getPositions
.mockResolvedValueOnce({ money: [{ currency: 'RUB', nano: 500000000 }] })
.mockResolvedValueOnce({ money: [{ currency: 'USD', units: 4 }] });
await expect(service.list('user-1')).resolves.toEqual([
{
id: 'first',
type: 'BROKERAGE',
name: 'Первый',
openedOn: null,
portfolioSummary: {
totalsByCurrency: [{ currency: 'RUB', value: '6.5' }],
stockPositionCount: 0,
bondPositionCount: 0,
},
},
{
id: 'second',
type: 'INDIVIDUAL_INVESTMENT',
name: 'Второй',
openedOn: null,
portfolioSummary: {
totalsByCurrency: [{ currency: 'USD', value: '4' }],
stockPositionCount: 0,
bondPositionCount: 0,
{
id: 'b',
name: 'B',
type: 'BROKERAGE',
openedOn: null,
meta: { ...meta, availability: 'missing' },
snapshot: null,
},
},
]);
expect(tbank.getPortfolio).toHaveBeenCalledWith('token', 'first');
expect(tbank.getPositions).toHaveBeenCalledWith('token', 'second');
});
it('counts non-zero stock and bond positions even without a valuation', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockResolvedValue([
{ id: 'account', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Основной' },
]);
tbank.getPortfolio.mockResolvedValue({
positions: [
{ instrumentType: 'share', quantity: { units: 200 } },
{ instrumentType: 'SHARE', quantity: { units: -5 } },
{ instrumentType: 'share', quantity: { units: 0, nano: 1 } },
{ instrumentType: 'bond', quantity: { units: 80 } },
{ instrumentType: 'bond', quantity: { units: 0 } },
{ instrumentType: 'share' },
{ instrumentType: 'etf', quantity: { units: 10 } },
{ instrumentType: 'currency', quantity: { units: 100 } },
{ quantity: { units: 1 } },
],
virtualPositions: [{ instrumentType: 'bond', quantity: { units: 1 } }],
});
await expect(service.list('user-1')).resolves.toMatchObject([
{
portfolioSummary: {
totalsByCurrency: [],
stockPositionCount: 3,
bondPositionCount: 1,
},
},
]);
});
it('localizes an unavailable summary without suppressing another account', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
const response = await service.list('owner', true);
expect(response.data?.[0].portfolioSummary).toEqual({
totalsByCurrency: [{ currency: 'RUB', value: '100000000.000000001' }],
stockPositionCount: 1,
bondPositionCount: 1,
});
tbank.getOpenAccounts.mockResolvedValue([
{ id: 'unavailable', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Первый' },
{ id: 'available', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Второй' },
]);
tbank.getPortfolio
.mockRejectedValueOnce(
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
)
.mockResolvedValueOnce({ positions: [] });
tbank.getPositions.mockResolvedValue({ money: [] });
await expect(service.list('user-1')).resolves.toMatchObject([
{ id: 'unavailable', portfolioSummary: null },
{ id: 'available', portfolioSummary: { totalsByCurrency: [] } },
]);
});
it('does not mask an invalid token when the other summary input is unavailable', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockResolvedValue([
{ id: 'account', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Основной' },
]);
tbank.getPortfolio.mockRejectedValue(
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
);
tbank.getPositions.mockRejectedValue(new Error('INVALID_TBANK_TOKEN'));
await expect(service.list('user-1')).rejects.toEqual(
expect.any(BadRequestException),
);
});
it('retains the connection when T-Bank rejects its token', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockRejectedValue(new Error('INVALID_TBANK_TOKEN'));
await expect(service.list('user-1')).rejects.toEqual(
expect.any(BadRequestException),
);
});
it('returns an empty list from T-Bank unchanged', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockResolvedValue([]);
await expect(service.list('user-1')).resolves.toEqual([]);
});
it('propagates an unavailable T-Bank response', async () => {
prisma.tbankConnection.findUnique.mockResolvedValue({
encryptedToken: tokens.encrypt('token'),
});
tbank.getOpenAccounts.mockRejectedValue(
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
);
await expect(service.list('user-1')).rejects.toEqual(
expect.any(ServiceUnavailableException),
);
expect(response.data?.[1].portfolioSummary).toBeNull();
expect(response.meta.availability).toBe('partial');
});
});
@@ -1,80 +1,65 @@
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { isZero } from '../../../common/decimal';
import {
TbankAccessService,
TbankClient,
} from '../../../integrations/tbank/tbank.api';
import { decimal } from '../../../integrations/tbank/decimal';
import { totalsByCurrency } from '../portfolio/portfolio.api';
import { Injectable } from '@nestjs/common';
import { createHash } from 'node:crypto';
import { PortfolioService } from '../portfolio/portfolio.api';
import { investmentResourceMeta } from '../investment-resource.mapper';
import { BrokerageAccountDto } from './brokerage-account.dto';
@Injectable()
export class BrokerageAccountsService {
constructor(
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
) {}
constructor(private readonly portfolio: PortfolioService) {}
async list(userId: string): Promise<BrokerageAccountDto[]> {
return this.access.withSupportedAccounts(
userId,
async ({ token, accounts }) =>
Promise.all(
accounts.map(async (account) => {
const [portfolioResult, positionsResult] = await Promise.allSettled(
[
this.tbank.getPortfolio(token, account.id),
this.tbank.getPositions(token, account.id),
],
);
if (
portfolioResult.status === 'rejected' &&
!isTbankUnavailable(portfolioResult.reason)
)
throw portfolioResult.reason;
if (
positionsResult.status === 'rejected' &&
!isTbankUnavailable(positionsResult.reason)
)
throw positionsResult.reason;
if (
portfolioResult.status === 'rejected' ||
positionsResult.status === 'rejected'
)
return { ...account, portfolioSummary: null };
const positions = portfolioResult.value.positions ?? [];
let stockPositionCount = 0;
let bondPositionCount = 0;
for (const position of positions) {
if (isZero(decimal(position.quantity ?? {}))) continue;
const type = position.instrumentType?.toLowerCase();
if (type === 'share') stockPositionCount += 1;
if (type === 'bond') bondPositionCount += 1;
}
return {
...account,
portfolioSummary: {
totalsByCurrency: totalsByCurrency(
positions,
positionsResult.value.money ?? [],
),
stockPositionCount,
bondPositionCount,
},
};
}),
),
);
async list(userId: string, observe = false) {
const saved = await this.portfolio.saved(userId, 'all', observe);
const data: BrokerageAccountDto[] | null =
saved.membership.availability === 'missing'
? null
: saved.accounts.map((account) => ({
id: account.id,
name: account.name,
type: account.type as BrokerageAccountDto['type'],
openedOn: account.openedOn,
portfolioSummary: account.snapshot
? {
totalsByCurrency: account.snapshot.totalsByCurrency,
stockPositionCount: account.snapshot.positions.filter(
(position) => position.type === 'STOCK',
).length,
bondPositionCount: account.snapshot.positions.filter(
(position) => position.type === 'BOND',
).length,
}
: null,
}));
return {
data,
meta: investmentResourceMeta({
resourceKey: 'accounts',
dataRevision: createHash('sha256')
.update(
JSON.stringify([
saved.membership.dataRevision,
saved.accounts.map((account) => [
account.id,
account.meta.dataRevision,
]),
]),
)
.digest('base64url'),
availability:
data === null
? 'missing'
: saved.accounts.some((account) => !account.snapshot)
? 'partial'
: 'complete',
fetchedAt: saved.membership.lastSuccessfulAt
? new Date(saved.membership.lastSuccessfulAt)
: null,
freshForMs: 300_000,
work: saved.membership.sync.id
? { ...saved.membership.sync, id: saved.membership.sync.id }
: null,
dependencies: saved.accounts.map((account) => account.meta),
}),
};
}
}
function isTbankUnavailable(error: unknown): boolean {
if (!(error instanceof ServiceUnavailableException)) return false;
const response = error.getResponse();
return (
typeof response === 'object' &&
response !== null &&
'code' in response &&
response.code === 'TBANK_UNAVAILABLE'
);
}