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,109 +1,165 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
decimalFromString,
|
||||
formatDecimal,
|
||||
multiply,
|
||||
} from '../../../../../common/decimal';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||
import { PortfolioService } from '../../../portfolio/portfolio.api';
|
||||
import {
|
||||
moscowDay,
|
||||
optional,
|
||||
timestamp,
|
||||
} from '../../application/instrument-market';
|
||||
import { stockPosition } from './stock-position';
|
||||
TbankAccessService,
|
||||
type TbankDividend,
|
||||
} from '../../../../../integrations/tbank/tbank.api';
|
||||
import {
|
||||
PortfolioService,
|
||||
ForecastService,
|
||||
} from '../../../portfolio/portfolio.api';
|
||||
import { CatalogEnrichmentService } from '../../application/catalog-enrichment.service';
|
||||
import { moscowDay, timestamp } from '../../application/instrument-market';
|
||||
import { instrumentPosition } from '../../application/instrument-position';
|
||||
import {
|
||||
StockDividendDto,
|
||||
StockDividendsDto,
|
||||
StockDividendsResourceDto,
|
||||
StockPositionDto,
|
||||
StockDividendDto,
|
||||
} from '../presentation/stock.dto';
|
||||
|
||||
import { StockCatalogService } from './stock-catalog.service';
|
||||
|
||||
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||
const ISO_YEAR_LENGTH = 4;
|
||||
const INCOME_HISTORY_YEARS = 5;
|
||||
@Injectable()
|
||||
export class StockIncomeService {
|
||||
constructor(
|
||||
private readonly catalog: StockCatalogService,
|
||||
private readonly tbank: TbankClient,
|
||||
private readonly portfolios: PortfolioService,
|
||||
private readonly sources: CatalogEnrichmentService,
|
||||
private readonly access: TbankAccessService,
|
||||
private readonly forecasts: ForecastService,
|
||||
) {}
|
||||
async position(userId: string, uid: string): Promise<StockPositionDto> {
|
||||
return this.catalog.cached(userId, `position:${uid}`, async () =>
|
||||
stockPosition(await this.portfolios.getAll(userId), uid),
|
||||
);
|
||||
|
||||
async readPosition(userId: string, uid: string, observe = false) {
|
||||
const saved = await this.portfolios.read(userId, 'all', observe);
|
||||
return {
|
||||
data: saved.data ? instrumentPosition(saved.data, uid, 'STOCK') : null,
|
||||
meta: { ...saved.meta, resourceKey: `stock/position/${uid}` },
|
||||
};
|
||||
}
|
||||
dividends(userId: string, uid: string): Promise<StockDividendsDto> {
|
||||
return this.catalog.cached(userId, `dividends:${uid}`, async (token) => {
|
||||
await this.catalog.share(token, uid);
|
||||
const today = moscowDay(new Date().toISOString());
|
||||
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||
const unavailable: string[] = [];
|
||||
const [events, position] = await Promise.all([
|
||||
this.tbank.getDividends(token, uid, from, to),
|
||||
optional(() => this.position(userId, uid), 'position', unavailable),
|
||||
]);
|
||||
const quantity =
|
||||
position &&
|
||||
position.accounts.length &&
|
||||
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
|
||||
? decimalFromString(position.quantity)
|
||||
: null;
|
||||
const dividends: StockDividendDto[] = events
|
||||
.filter((event) => event.dividendType?.toLowerCase() !== 'cancelled')
|
||||
.map((event) => {
|
||||
const recordDate = timestamp(event.recordDate)?.slice(0, 10) ?? null;
|
||||
const paymentDate =
|
||||
timestamp(event.paymentDate)?.slice(0, 10) ?? null;
|
||||
const lastBuyDate =
|
||||
timestamp(event.lastBuyDate)?.slice(0, 10) ?? null;
|
||||
const currency = event.dividendNet?.currency?.toUpperCase();
|
||||
const perShare =
|
||||
currency && event.dividendNet
|
||||
? { currency, value: formatDecimal(decimal(event.dividendNet)) }
|
||||
: null;
|
||||
// A future payment can have an already-fixed register: keep the event, but do not estimate entitlement from today's holding.
|
||||
const eventDate = paymentDate ?? recordDate;
|
||||
const timing: StockDividendDto['timing'] = eventDate
|
||||
? eventDate >= today
|
||||
? 'upcoming'
|
||||
: 'past'
|
||||
: 'undated';
|
||||
const estimatedAmount =
|
||||
quantity &&
|
||||
perShare &&
|
||||
recordDate &&
|
||||
recordDate >= today &&
|
||||
timing === 'upcoming'
|
||||
? {
|
||||
currency: perShare.currency,
|
||||
value: formatDecimal(
|
||||
multiply(quantity, decimalFromString(perShare.value)),
|
||||
),
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
perShare,
|
||||
recordDate,
|
||||
lastBuyDate,
|
||||
paymentDate,
|
||||
timing,
|
||||
estimatedAmount,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (b.recordDate ?? '').localeCompare(a.recordDate ?? ''));
|
||||
return {
|
||||
dividends,
|
||||
from,
|
||||
to,
|
||||
observedAt: new Date().toISOString(),
|
||||
positionAt: quantity ? (position?.observedAt ?? null) : null,
|
||||
estimateUnavailable: unavailable.length > 0,
|
||||
positionIsStale: position?.isStale ?? false,
|
||||
};
|
||||
async dividends(
|
||||
userId: string,
|
||||
uid: string,
|
||||
observe = false,
|
||||
): Promise<StockDividendsResourceDto> {
|
||||
const connection = await this.access.local(userId);
|
||||
const today = moscowDay(new Date().toISOString());
|
||||
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||
const portfolio = await this.portfolios.read(userId, 'all', observe);
|
||||
const sources = await this.sources.readMany(
|
||||
userId,
|
||||
'share',
|
||||
[uid],
|
||||
observe,
|
||||
['detail', 'dividends'],
|
||||
{ from, to },
|
||||
);
|
||||
if (sources[0].meta.availability === 'complete' && !sources[0].instrument)
|
||||
throw new NotFoundException();
|
||||
const events = sources[1].payload?.dividends;
|
||||
const position = portfolio.data
|
||||
? instrumentPosition(portfolio.data, uid, 'STOCK')
|
||||
: null;
|
||||
const projected = events
|
||||
? stockDividends(
|
||||
events,
|
||||
position,
|
||||
{ from, to, today },
|
||||
sources[1].meta.lastSuccessfulAt ?? new Date().toISOString(),
|
||||
!portfolio.data,
|
||||
)
|
||||
: undefined;
|
||||
const result = await this.forecasts.result({
|
||||
userId,
|
||||
revision: connection.revision,
|
||||
membershipRevision: connection.membershipRevision,
|
||||
scopeKey: `stock/dividends/${JSON.stringify([uid, from, to])}`,
|
||||
portfolio: portfolio.meta,
|
||||
sources,
|
||||
candidate:
|
||||
portfolio.data && sources[0].instrument ? projected : undefined,
|
||||
});
|
||||
return result.data || !projected
|
||||
? result
|
||||
: {
|
||||
data: stockDividends(
|
||||
events ?? [],
|
||||
null,
|
||||
{ from, to, today },
|
||||
projected.observedAt,
|
||||
true,
|
||||
),
|
||||
meta: { ...result.meta, availability: 'partial' },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function stockDividends(
|
||||
events: TbankDividend[],
|
||||
position: StockPositionDto | null,
|
||||
window: { from: string; to: string; today: string },
|
||||
observedAt: string,
|
||||
positionUnavailable: boolean,
|
||||
): StockDividendsDto {
|
||||
const { from, to, today } = window;
|
||||
const quantity =
|
||||
position &&
|
||||
position.accounts.length &&
|
||||
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
|
||||
? decimalFromString(position.quantity)
|
||||
: null;
|
||||
const dividends: StockDividendDto[] = events
|
||||
.filter((event) => event.dividendType?.toLowerCase() !== 'cancelled')
|
||||
.map((event) => {
|
||||
const recordDate = timestamp(event.recordDate)?.slice(0, 10) ?? null;
|
||||
const paymentDate = timestamp(event.paymentDate)?.slice(0, 10) ?? null;
|
||||
const lastBuyDate = timestamp(event.lastBuyDate)?.slice(0, 10) ?? null;
|
||||
const currency = event.dividendNet?.currency?.toUpperCase();
|
||||
const perShare =
|
||||
currency && event.dividendNet
|
||||
? { currency, value: formatDecimal(decimal(event.dividendNet)) }
|
||||
: null;
|
||||
// A future payment can have an already-fixed register: keep the event, but do not estimate entitlement from today's holding.
|
||||
const eventDate = paymentDate ?? recordDate;
|
||||
const timing: StockDividendDto['timing'] = eventDate
|
||||
? eventDate >= today
|
||||
? 'upcoming'
|
||||
: 'past'
|
||||
: 'undated';
|
||||
const estimatedAmount =
|
||||
quantity &&
|
||||
perShare &&
|
||||
recordDate &&
|
||||
recordDate >= today &&
|
||||
timing === 'upcoming'
|
||||
? {
|
||||
currency: perShare.currency,
|
||||
value: formatDecimal(
|
||||
multiply(quantity, decimalFromString(perShare.value)),
|
||||
),
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
perShare,
|
||||
recordDate,
|
||||
lastBuyDate,
|
||||
paymentDate,
|
||||
timing,
|
||||
estimatedAmount,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (b.recordDate ?? '').localeCompare(a.recordDate ?? ''));
|
||||
return {
|
||||
dividends,
|
||||
from,
|
||||
to,
|
||||
observedAt: observedAt,
|
||||
positionAt: quantity ? (position?.observedAt ?? null) : null,
|
||||
estimateUnavailable: positionUnavailable,
|
||||
positionIsStale: position?.isStale ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user