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
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:
@@ -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'
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user