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,208 +1,251 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
decimalFromString,
|
||||
divide,
|
||||
formatDecimal,
|
||||
multiply,
|
||||
divide,
|
||||
} from '../../../../../common/decimal';
|
||||
import { MoexClient } from '../../../../../integrations/moex/moex.api';
|
||||
import { NcrRatingsClient } from '../../../../../integrations/ncr/ncr.api';
|
||||
import {
|
||||
TbankClient,
|
||||
type TbankConnectionContext,
|
||||
TbankAccessService,
|
||||
type TbankCoupon,
|
||||
type TbankBond,
|
||||
} from '../../../../../integrations/tbank/tbank.api';
|
||||
import { PortfolioService } from '../../../portfolio/portfolio.api';
|
||||
import {
|
||||
moscowDay,
|
||||
optional,
|
||||
timestamp,
|
||||
} from '../../application/instrument-market';
|
||||
PortfolioService,
|
||||
ForecastService,
|
||||
} from '../../../portfolio/portfolio.api';
|
||||
import {
|
||||
CatalogEnrichmentService,
|
||||
type CatalogPayload,
|
||||
} from '../../application/catalog-enrichment.service';
|
||||
import { moscowDay, timestamp } from '../../application/instrument-market';
|
||||
import { instrumentPosition } from '../../application/instrument-position';
|
||||
import {
|
||||
BondCouponsDto,
|
||||
BondMetricsDto,
|
||||
BondCouponsResourceDto,
|
||||
BondPositionDto,
|
||||
BondMetricsDto,
|
||||
BondMetricsResourceDto,
|
||||
} from '../presentation/bond.dto';
|
||||
|
||||
import { BondMarketService } from './bond-market.service';
|
||||
import { money } from '../infrastructure/bond-money.mapper';
|
||||
import { BondCatalogService } from './bond-catalog.service';
|
||||
|
||||
import { bondQuote } from './bond-market.service';
|
||||
const ISO_YEAR_LENGTH = 4;
|
||||
const INCOME_HISTORY_YEARS = 5;
|
||||
const COUPON_YIELD_DECIMAL_PLACES = 4;
|
||||
@Injectable()
|
||||
export class BondIncomeService {
|
||||
constructor(
|
||||
private readonly catalog: BondCatalogService,
|
||||
private readonly tbank: TbankClient,
|
||||
private readonly portfolios: PortfolioService,
|
||||
private readonly market: BondMarketService,
|
||||
private readonly moex: MoexClient,
|
||||
private readonly ratings: NcrRatingsClient,
|
||||
private readonly sources: CatalogEnrichmentService,
|
||||
private readonly access: TbankAccessService,
|
||||
private readonly forecasts: ForecastService,
|
||||
) {}
|
||||
metrics(userId: string, uid: string): Promise<BondMetricsDto> {
|
||||
return this.catalog.cached(userId, `metrics:${uid}`, async (connection) => {
|
||||
const instrument = await this.catalog.bond(userId, connection, uid);
|
||||
const { ticker, isin, classCode } = instrument;
|
||||
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, quote, effectiveYield, creditRating] = await Promise.all([
|
||||
optional(
|
||||
() => this.couponEvents(userId, connection, uid, from, to),
|
||||
'coupons',
|
||||
unavailable,
|
||||
),
|
||||
optional(() => this.market.quote(userId, uid), 'quote', unavailable),
|
||||
ticker && isin && classCode
|
||||
? optional(
|
||||
() => this.moex.bondYield(ticker, isin, classCode),
|
||||
'yield',
|
||||
unavailable,
|
||||
)
|
||||
: null,
|
||||
isin
|
||||
? optional(() => this.ratings.rating(isin), 'rating', unavailable)
|
||||
: null,
|
||||
]);
|
||||
const next = events
|
||||
?.filter((event) => {
|
||||
const date = timestamp(event.couponDate)?.slice(0, 10);
|
||||
return date && date >= today;
|
||||
})
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(a.couponDate?.seconds) - Number(b.couponDate?.seconds),
|
||||
)[0];
|
||||
const coupon = money(next?.payOneBond);
|
||||
const period = next?.couponPeriod;
|
||||
const couponPeriodDays =
|
||||
period && Number.isInteger(period) && period > 0 ? period : null;
|
||||
const clean = quote?.cleanPrice;
|
||||
const couponYieldPercent =
|
||||
coupon &&
|
||||
couponPeriodDays &&
|
||||
clean &&
|
||||
coupon.currency === clean.currency &&
|
||||
decimalFromString(coupon.value).value >= 0n &&
|
||||
decimalFromString(clean.value).value > 0n
|
||||
? formatDecimal(
|
||||
divide(
|
||||
multiply(
|
||||
decimalFromString(coupon.value),
|
||||
decimalFromString('36500'),
|
||||
),
|
||||
multiply(
|
||||
decimalFromString(String(couponPeriodDays)),
|
||||
decimalFromString(clean.value),
|
||||
),
|
||||
COUPON_YIELD_DECIMAL_PLACES,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const couponType =
|
||||
next?.couponType && next.couponType !== 'COUPON_TYPE_UNSPECIFIED'
|
||||
? next.couponType
|
||||
: instrument.floatingCouponFlag === true
|
||||
? 'COUPON_TYPE_FLOATING'
|
||||
: null;
|
||||
return {
|
||||
creditRating,
|
||||
coupon,
|
||||
couponDate: timestamp(next?.couponDate)?.slice(0, 10) ?? null,
|
||||
couponType,
|
||||
couponPeriodDays,
|
||||
couponYieldPercent,
|
||||
couponYieldPriceAt:
|
||||
couponYieldPercent !== null ? (quote?.priceAt ?? null) : null,
|
||||
effectiveYield,
|
||||
unavailable,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
}
|
||||
private couponEvents(
|
||||
async metrics(
|
||||
userId: string,
|
||||
connection: TbankConnectionContext,
|
||||
uid: string,
|
||||
from: string,
|
||||
to: string,
|
||||
) {
|
||||
return this.catalog.cachedForConnection(
|
||||
observe = false,
|
||||
): Promise<BondMetricsResourceDto> {
|
||||
const result = await this.sources.section(
|
||||
userId,
|
||||
connection,
|
||||
`coupon-events:${uid}:${from}:${to}`,
|
||||
() => this.tbank.getBondCoupons(connection.token, uid, from, to),
|
||||
'bond',
|
||||
uid,
|
||||
'metrics',
|
||||
observe,
|
||||
);
|
||||
return {
|
||||
data: result.values.instrument
|
||||
? bondMetrics(result.values, result.unavailable, result.observedAt)
|
||||
: null,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
coupons(userId: string, uid: string): Promise<BondCouponsDto> {
|
||||
return this.catalog.cached(userId, `coupons:${uid}`, async (connection) => {
|
||||
await this.catalog.bond(userId, connection, 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.couponEvents(userId, connection, uid, from, to),
|
||||
optional(() => this.position(userId, uid), 'position', unavailable),
|
||||
]);
|
||||
const quantity =
|
||||
position?.accounts.length &&
|
||||
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
|
||||
? decimalFromString(position.quantity)
|
||||
: null;
|
||||
const coupons = events
|
||||
.map((event) => {
|
||||
const paymentDate = timestamp(event.couponDate)?.slice(0, 10) ?? null;
|
||||
const recordDate = timestamp(event.fixDate)?.slice(0, 10) ?? null;
|
||||
const perBond = money(event.payOneBond);
|
||||
const timing = !paymentDate
|
||||
? ('undated' as const)
|
||||
: paymentDate >= today
|
||||
? ('upcoming' as const)
|
||||
: ('past' as const);
|
||||
return {
|
||||
number: event.couponNumber ?? null,
|
||||
paymentDate,
|
||||
recordDate,
|
||||
perBond,
|
||||
couponType: event.couponType ?? null,
|
||||
periodDays: event.couponPeriod ?? null,
|
||||
timing,
|
||||
estimatedAmount:
|
||||
quantity &&
|
||||
perBond &&
|
||||
timing === 'upcoming' &&
|
||||
recordDate &&
|
||||
recordDate >= today
|
||||
? {
|
||||
currency: perBond.currency,
|
||||
value: formatDecimal(
|
||||
multiply(quantity, decimalFromString(perBond.value)),
|
||||
),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
})
|
||||
.sort((a, b) =>
|
||||
(a.paymentDate ?? '').localeCompare(b.paymentDate ?? ''),
|
||||
);
|
||||
return {
|
||||
coupons,
|
||||
from,
|
||||
to,
|
||||
observedAt: new Date().toISOString(),
|
||||
positionAt: quantity ? (position?.observedAt ?? null) : null,
|
||||
estimateUnavailable: unavailable.length > 0,
|
||||
positionIsStale: position?.isStale ?? false,
|
||||
};
|
||||
|
||||
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, 'BOND') : null,
|
||||
meta: { ...saved.meta, resourceKey: `bond/position/${uid}` },
|
||||
};
|
||||
}
|
||||
async coupons(
|
||||
userId: string,
|
||||
uid: string,
|
||||
observe = false,
|
||||
): Promise<BondCouponsResourceDto> {
|
||||
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,
|
||||
'bond',
|
||||
[uid],
|
||||
observe,
|
||||
['detail', 'coupons'],
|
||||
{ from, to },
|
||||
);
|
||||
if (sources[0].meta.availability === 'complete' && !sources[0].instrument)
|
||||
throw new NotFoundException();
|
||||
const events = sources[1].payload?.coupons;
|
||||
const position = portfolio.data
|
||||
? instrumentPosition(portfolio.data, uid, 'BOND')
|
||||
: null;
|
||||
const projected = events
|
||||
? bondCoupons(
|
||||
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: `bond/coupons/${JSON.stringify([uid, from, to])}`,
|
||||
portfolio: portfolio.meta,
|
||||
sources,
|
||||
candidate:
|
||||
portfolio.data && sources[0].instrument ? projected : undefined,
|
||||
});
|
||||
}
|
||||
async position(userId: string, uid: string): Promise<BondPositionDto> {
|
||||
return this.catalog.cached(userId, `position:${uid}`, async () =>
|
||||
instrumentPosition(await this.portfolios.getAll(userId), uid, 'BOND'),
|
||||
);
|
||||
return result.data || !projected
|
||||
? result
|
||||
: {
|
||||
data: bondCoupons(
|
||||
events ?? [],
|
||||
null,
|
||||
{ from, to, today },
|
||||
projected.observedAt,
|
||||
true,
|
||||
),
|
||||
meta: { ...result.meta, availability: 'partial' },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function bondCoupons(
|
||||
events: TbankCoupon[],
|
||||
position: BondPositionDto | null,
|
||||
window: { from: string; to: string; today: string },
|
||||
observedAt: string,
|
||||
positionUnavailable: boolean,
|
||||
): BondCouponsDto {
|
||||
const { from, to, today } = window;
|
||||
const quantity =
|
||||
position?.accounts.length &&
|
||||
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
|
||||
? decimalFromString(position.quantity)
|
||||
: null;
|
||||
const coupons = events
|
||||
.map((event) => {
|
||||
const paymentDate = timestamp(event.couponDate)?.slice(0, 10) ?? null;
|
||||
const recordDate = timestamp(event.fixDate)?.slice(0, 10) ?? null;
|
||||
const perBond = money(event.payOneBond);
|
||||
const timing = !paymentDate
|
||||
? ('undated' as const)
|
||||
: paymentDate >= today
|
||||
? ('upcoming' as const)
|
||||
: ('past' as const);
|
||||
return {
|
||||
number: event.couponNumber ?? null,
|
||||
paymentDate,
|
||||
recordDate,
|
||||
perBond,
|
||||
couponType: event.couponType ?? null,
|
||||
periodDays: event.couponPeriod ?? null,
|
||||
timing,
|
||||
estimatedAmount:
|
||||
quantity &&
|
||||
perBond &&
|
||||
timing === 'upcoming' &&
|
||||
recordDate &&
|
||||
recordDate >= today
|
||||
? {
|
||||
currency: perBond.currency,
|
||||
value: formatDecimal(
|
||||
multiply(quantity, decimalFromString(perBond.value)),
|
||||
),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (a.paymentDate ?? '').localeCompare(b.paymentDate ?? ''));
|
||||
return {
|
||||
coupons,
|
||||
from,
|
||||
to,
|
||||
observedAt: observedAt,
|
||||
positionAt: quantity ? (position?.observedAt ?? null) : null,
|
||||
estimateUnavailable: positionUnavailable,
|
||||
positionIsStale: position?.isStale ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
export function bondMetrics(
|
||||
values: CatalogPayload,
|
||||
unavailable: string[],
|
||||
observedAt: string,
|
||||
): BondMetricsDto {
|
||||
const instrument = values.instrument as TbankBond;
|
||||
const events = values.coupons;
|
||||
const quote = bondQuote(values, unavailable, observedAt);
|
||||
const effectiveYield = values.effectiveYield ?? null;
|
||||
const creditRating = values.creditRating ?? null;
|
||||
const today = moscowDay(new Date().toISOString());
|
||||
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||
const next = events
|
||||
?.filter((event) => {
|
||||
const date = timestamp(event.couponDate)?.slice(0, 10);
|
||||
return date && date >= today && date <= to;
|
||||
})
|
||||
.sort(
|
||||
(a, b) => Number(a.couponDate?.seconds) - Number(b.couponDate?.seconds),
|
||||
)[0];
|
||||
const coupon = money(next?.payOneBond);
|
||||
const period = next?.couponPeriod;
|
||||
const couponPeriodDays =
|
||||
period && Number.isInteger(period) && period > 0 ? period : null;
|
||||
const clean = quote?.cleanPrice;
|
||||
const couponYieldPercent =
|
||||
coupon &&
|
||||
couponPeriodDays &&
|
||||
clean &&
|
||||
coupon.currency === clean.currency &&
|
||||
decimalFromString(coupon.value).value >= 0n &&
|
||||
decimalFromString(clean.value).value > 0n
|
||||
? formatDecimal(
|
||||
divide(
|
||||
multiply(
|
||||
decimalFromString(coupon.value),
|
||||
decimalFromString('36500'),
|
||||
),
|
||||
multiply(
|
||||
decimalFromString(String(couponPeriodDays)),
|
||||
decimalFromString(clean.value),
|
||||
),
|
||||
COUPON_YIELD_DECIMAL_PLACES,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const couponType =
|
||||
next?.couponType && next.couponType !== 'COUPON_TYPE_UNSPECIFIED'
|
||||
? next.couponType
|
||||
: instrument.floatingCouponFlag === true
|
||||
? 'COUPON_TYPE_FLOATING'
|
||||
: null;
|
||||
return {
|
||||
creditRating,
|
||||
coupon,
|
||||
couponDate: timestamp(next?.couponDate)?.slice(0, 10) ?? null,
|
||||
couponType,
|
||||
couponPeriodDays,
|
||||
couponYieldPercent,
|
||||
couponYieldPriceAt:
|
||||
couponYieldPercent !== null ? (quote?.priceAt ?? null) : null,
|
||||
effectiveYield,
|
||||
unavailable,
|
||||
observedAt,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user