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:
+33
-41
@@ -1,50 +1,42 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { TbankFundamentals } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { optional } from '../../application/instrument-market';
|
||||
import { StockCompanyDto, StockMetricDto } from '../presentation/stock.dto';
|
||||
|
||||
import { StockCatalogService } from './stock-catalog.service';
|
||||
import { CatalogEnrichmentService } from '../../application/catalog-enrichment.service';
|
||||
import {
|
||||
StockCompanyResourceDto,
|
||||
StockMetricDto,
|
||||
} from '../presentation/stock.dto';
|
||||
@Injectable()
|
||||
export class GetStockCompanyUseCase {
|
||||
constructor(
|
||||
private readonly catalog: StockCatalogService,
|
||||
private readonly tbank: TbankClient,
|
||||
) {}
|
||||
execute(userId: string, uid: string): Promise<StockCompanyDto> {
|
||||
return this.catalog.cached(userId, `company:${uid}`, async (token) => {
|
||||
const share = await this.catalog.share(token, uid);
|
||||
const unavailable: string[] = [];
|
||||
const assetUid = share.assetUid;
|
||||
if (!assetUid)
|
||||
return {
|
||||
description: null,
|
||||
metrics: [],
|
||||
unavailable,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
const [description, fundamentals] = await Promise.all([
|
||||
optional(
|
||||
() => this.tbank.getAssetDescription(token, assetUid),
|
||||
'description',
|
||||
unavailable,
|
||||
),
|
||||
optional(
|
||||
() => this.tbank.getFundamentals(token, assetUid),
|
||||
'fundamentals',
|
||||
unavailable,
|
||||
),
|
||||
]);
|
||||
return {
|
||||
description,
|
||||
metrics: metrics(fundamentals, share.sector),
|
||||
unavailable,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
constructor(private readonly sources: CatalogEnrichmentService) {}
|
||||
async execute(
|
||||
userId: string,
|
||||
uid: string,
|
||||
observe = false,
|
||||
): Promise<StockCompanyResourceDto> {
|
||||
const result = await this.sources.section(
|
||||
userId,
|
||||
'share',
|
||||
uid,
|
||||
'company',
|
||||
observe,
|
||||
);
|
||||
return {
|
||||
data: result.values.instrument
|
||||
? {
|
||||
description: result.values.description ?? null,
|
||||
metrics: metrics(
|
||||
result.values.fundamentals ?? null,
|
||||
result.values.instrument.sector,
|
||||
),
|
||||
unavailable: result.unavailable,
|
||||
observedAt: result.observedAt,
|
||||
}
|
||||
: null,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
}
|
||||
function metrics(
|
||||
export function metrics(
|
||||
values: TbankFundamentals | null,
|
||||
sector?: string,
|
||||
): StockMetricDto[] {
|
||||
|
||||
@@ -1,185 +1,87 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { LRUCache } from 'lru-cache';
|
||||
import { CatalogDiscoveryService } from '../../application/catalog-discovery.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { formatDecimal } from '../../../../../common/decimal';
|
||||
import type { TbankShare } from '../../../../../integrations/tbank/tbank.api';
|
||||
import {
|
||||
TbankAccessService,
|
||||
TbankClient,
|
||||
} from '../../../../../integrations/tbank/tbank.api';
|
||||
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||
import { optional, timestamp } from '../../application/instrument-market';
|
||||
import { StockDto, StockSearchResultDto } from '../presentation/stock.dto';
|
||||
|
||||
const SEARCH_RESULTS_LIMIT = 30;
|
||||
import { timestamp } from '../../application/instrument-market';
|
||||
import {
|
||||
StockDto,
|
||||
StockResourceDto,
|
||||
StockSearchResourceDto,
|
||||
} from '../presentation/stock.dto';
|
||||
|
||||
type IdentifiedShare = TbankShare & { uid: string };
|
||||
|
||||
@Injectable()
|
||||
export class StockCatalogService {
|
||||
private readonly cache = new LRUCache<string, Promise<object>>({
|
||||
max: 300,
|
||||
ttl: 30_000,
|
||||
});
|
||||
constructor(
|
||||
private readonly access: TbankAccessService,
|
||||
private readonly tbank: TbankClient,
|
||||
) {}
|
||||
search(userId: string, query: string): Promise<StockSearchResultDto[]> {
|
||||
return this.cached(userId, `search:${query}`, async (token) => {
|
||||
const found = await this.tbank.findShares(token, query);
|
||||
const shares = selectShares(found, query).slice(0, SEARCH_RESULTS_LIMIT);
|
||||
if (!shares.length) return [];
|
||||
// One market-data request for the list; failed enrichment must not hide a catalog result.
|
||||
const [details, prices] = await Promise.all([
|
||||
Promise.all(
|
||||
shares.map(
|
||||
async (share) =>
|
||||
(await optional(
|
||||
() =>
|
||||
this.get(userId, share.uid).catch((error: unknown) => {
|
||||
if (error instanceof NotFoundException) return stock(share);
|
||||
throw error;
|
||||
}),
|
||||
'details',
|
||||
[],
|
||||
)) ?? stock(share),
|
||||
),
|
||||
),
|
||||
optional(
|
||||
() =>
|
||||
this.tbank.getLastPrices(
|
||||
token,
|
||||
shares.map((share) => share.uid),
|
||||
),
|
||||
'prices',
|
||||
[],
|
||||
),
|
||||
]);
|
||||
return details.map((detail, index) => {
|
||||
const short = stock(shares[index]);
|
||||
const last = prices?.find(
|
||||
(price) => price.instrumentUid === detail.instrumentUid,
|
||||
);
|
||||
return {
|
||||
...detail,
|
||||
classCode: detail.classCode ?? short.classCode,
|
||||
isin: detail.isin ?? short.isin,
|
||||
apiTradeAvailable: short.apiTradeAvailable,
|
||||
price:
|
||||
last?.price && detail.currency
|
||||
? {
|
||||
currency: detail.currency,
|
||||
value: formatDecimal(decimal(last.price)),
|
||||
}
|
||||
: null,
|
||||
priceAt: timestamp(last?.time),
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
get(userId: string, uid: string): Promise<StockDto> {
|
||||
return this.cached(userId, `share:${uid}`, async (token) => {
|
||||
const result = stock(await this.share(token, uid));
|
||||
if (
|
||||
!result.ticker ||
|
||||
!/^[A-Za-z0-9][A-Za-z0-9._@+-]{0,79}$/.test(result.ticker)
|
||||
)
|
||||
return result;
|
||||
try {
|
||||
const match = await this.tickerMatch(userId, result.ticker);
|
||||
if (match.uid === uid) result.slug = result.ticker.toUpperCase();
|
||||
} catch (error) {
|
||||
// A readable alias is optional for an exact UID URL, never a reason to substitute another listing.
|
||||
if (
|
||||
!(error instanceof NotFoundException) &&
|
||||
!(error instanceof ConflictException) &&
|
||||
!(error instanceof ServiceUnavailableException)
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
async getByTicker(userId: string, ticker: string): Promise<StockDto> {
|
||||
const match = await this.tickerMatch(userId, ticker);
|
||||
constructor(private readonly discovery: CatalogDiscoveryService) {}
|
||||
async search(
|
||||
userId: string,
|
||||
query: string,
|
||||
observe = false,
|
||||
): Promise<StockSearchResourceDto> {
|
||||
const result = await this.discovery.search(
|
||||
userId,
|
||||
{ instrumentType: 'share', query },
|
||||
observe,
|
||||
);
|
||||
return {
|
||||
...(await this.get(userId, match.uid)),
|
||||
slug: ticker.trim().toUpperCase(),
|
||||
...result,
|
||||
data:
|
||||
result.data?.map((item) => {
|
||||
const short = stock(item);
|
||||
const detail = item.detail
|
||||
? stock({ ...item.detail, uid: item.uid })
|
||||
: short;
|
||||
const last = item.price;
|
||||
return {
|
||||
...detail,
|
||||
classCode: detail.classCode ?? short.classCode,
|
||||
isin: detail.isin ?? short.isin,
|
||||
apiTradeAvailable: short.apiTradeAvailable,
|
||||
price:
|
||||
last?.price && detail.currency
|
||||
? {
|
||||
currency: detail.currency,
|
||||
value: formatDecimal(decimal(last.price)),
|
||||
}
|
||||
: null,
|
||||
priceAt: timestamp(last?.time),
|
||||
};
|
||||
}) ?? null,
|
||||
};
|
||||
}
|
||||
private tickerMatch(
|
||||
async get(
|
||||
userId: string,
|
||||
uid: string,
|
||||
observe = false,
|
||||
): Promise<StockResourceDto> {
|
||||
const result = await this.discovery.detail(userId, 'share', uid, observe);
|
||||
return {
|
||||
...result,
|
||||
data: result.data
|
||||
? { ...stock(result.data), slug: result.data.slug }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
async getByTicker(
|
||||
userId: string,
|
||||
ticker: string,
|
||||
): Promise<IdentifiedShare> {
|
||||
const normalized = ticker.trim().toUpperCase();
|
||||
return this.cached(userId, `ticker:${normalized}`, async (token) => {
|
||||
const found = await this.tbank.findShares(token, normalized);
|
||||
const matches = selectShares(
|
||||
found.filter(
|
||||
(item) => item.ticker?.trim().toUpperCase() === normalized,
|
||||
),
|
||||
normalized,
|
||||
);
|
||||
if (!matches.length) throw new NotFoundException();
|
||||
if (matches.length > 1)
|
||||
throw new ConflictException({ code: 'STOCK_TICKER_AMBIGUOUS' });
|
||||
return matches[0];
|
||||
});
|
||||
observe = false,
|
||||
): Promise<StockResourceDto> {
|
||||
const result = await this.discovery.byTicker(
|
||||
userId,
|
||||
'share',
|
||||
ticker,
|
||||
observe,
|
||||
);
|
||||
return {
|
||||
...result,
|
||||
data: result.data
|
||||
? { ...stock(result.data), slug: result.data.slug }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
async share(token: string, uid: string): Promise<IdentifiedShare> {
|
||||
const share = await this.tbank.getShare(token, uid);
|
||||
if (!share || share.uid !== uid) throw new NotFoundException();
|
||||
return { ...share, uid };
|
||||
}
|
||||
cached<T extends object>(
|
||||
userId: string,
|
||||
key: string,
|
||||
operation: (token: string) => Promise<T>,
|
||||
): Promise<T> {
|
||||
return this.access.withConnection(userId, ({ token, generation }) => {
|
||||
const cacheKey = JSON.stringify([userId, generation, key]);
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached) return cached as Promise<T>;
|
||||
const pending = operation(token);
|
||||
this.cache.set(cacheKey, pending);
|
||||
return pending.catch((error) => {
|
||||
if (this.cache.get(cacheKey) === pending) this.cache.delete(cacheKey);
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function selectShares(found: TbankShare[], query: string): IdentifiedShare[] {
|
||||
const seen = new Set<string>();
|
||||
return found
|
||||
.filter(
|
||||
(share): share is IdentifiedShare =>
|
||||
Boolean(share.uid) && share.instrumentKind === 'INSTRUMENT_TYPE_SHARE',
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(b.apiTradeAvailableFlag === true) -
|
||||
Number(a.apiTradeAvailableFlag === true) ||
|
||||
Number(b.ticker?.toUpperCase() === query.toUpperCase()) -
|
||||
Number(a.ticker?.toUpperCase() === query.toUpperCase()) ||
|
||||
Number(b.classCode === 'TQBR') - Number(a.classCode === 'TQBR') ||
|
||||
a.uid.localeCompare(b.uid),
|
||||
)
|
||||
.filter((share) => {
|
||||
// A missing ISIN must not collapse unrelated catalog instruments.
|
||||
const key = share.isin?.trim()
|
||||
? `isin:${share.isin.trim().toUpperCase()}`
|
||||
: `uid:${share.uid}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function stock(share: IdentifiedShare): StockDto {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { CandleService } from '../../application/candle.service';
|
||||
import {
|
||||
CatalogEnrichmentService,
|
||||
type CatalogPayload,
|
||||
} from '../../application/catalog-enrichment.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
decimalFromString,
|
||||
divide,
|
||||
@@ -6,180 +11,101 @@ import {
|
||||
multiply,
|
||||
subtract,
|
||||
} from '../../../../../common/decimal';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||
import { timestamp } from '../../application/instrument-market';
|
||||
import {
|
||||
optional,
|
||||
previousClose,
|
||||
timestamp,
|
||||
} from '../../application/instrument-market';
|
||||
import {
|
||||
StockCandlesDto,
|
||||
StockCandlesQueryDto,
|
||||
StockQuoteDto,
|
||||
StockQuoteResourceDto,
|
||||
} from '../presentation/stock.dto';
|
||||
|
||||
const dayMs = 86_400_000;
|
||||
|
||||
import { StockCatalogService } from './stock-catalog.service';
|
||||
|
||||
const PREVIOUS_CLOSE_LOOKBACK_DAYS = 20;
|
||||
const HALF_YEAR_MONTHS = 6;
|
||||
const YEAR_MONTHS = 12;
|
||||
const CANDLE_WINDOW_DAYS = 365;
|
||||
const CHANGE_PERCENT_DECIMAL_PLACES = 6;
|
||||
@Injectable()
|
||||
export class StockMarketService {
|
||||
constructor(
|
||||
private readonly catalog: StockCatalogService,
|
||||
private readonly tbank: TbankClient,
|
||||
private readonly history: CandleService,
|
||||
private readonly sources: CatalogEnrichmentService,
|
||||
) {}
|
||||
quote(userId: string, uid: string): Promise<StockQuoteDto> {
|
||||
return this.catalog.cached(userId, `quote:${uid}`, async (token) => {
|
||||
const share = await this.catalog.share(token, uid);
|
||||
const unavailable: string[] = [];
|
||||
const [last, tradingStatus] = await Promise.all([
|
||||
optional(
|
||||
() => this.tbank.getLastPrice(token, uid),
|
||||
'price',
|
||||
unavailable,
|
||||
),
|
||||
optional(
|
||||
() => this.tbank.getTradingStatus(token, uid),
|
||||
'status',
|
||||
unavailable,
|
||||
),
|
||||
]);
|
||||
const priceAt = timestamp(last?.time);
|
||||
const currency = share.currency?.toUpperCase();
|
||||
const price =
|
||||
last?.price && currency
|
||||
? { currency, value: formatDecimal(decimal(last.price)) }
|
||||
: null;
|
||||
const previous = priceAt
|
||||
? await optional(
|
||||
async () => {
|
||||
const end = new Date(priceAt);
|
||||
return previousClose(
|
||||
await this.tbank.getCandles(
|
||||
token,
|
||||
uid,
|
||||
new Date(
|
||||
end.valueOf() - PREVIOUS_CLOSE_LOOKBACK_DAYS * dayMs,
|
||||
),
|
||||
end,
|
||||
),
|
||||
priceAt,
|
||||
);
|
||||
},
|
||||
'comparison',
|
||||
unavailable,
|
||||
)
|
||||
: null;
|
||||
const previousPrice =
|
||||
previous?.close && currency
|
||||
? { currency, value: formatDecimal(decimal(previous.close)) }
|
||||
: null;
|
||||
const difference =
|
||||
price && previousPrice
|
||||
? subtract(
|
||||
decimalFromString(price.value),
|
||||
decimalFromString(previousPrice.value),
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
price,
|
||||
priceAt,
|
||||
tradingStatus,
|
||||
previousCloseDate: timestamp(previous?.time)?.slice(0, 10) ?? null,
|
||||
previousClose: previousPrice,
|
||||
change:
|
||||
difference && currency
|
||||
? { currency, value: formatDecimal(difference) }
|
||||
: null,
|
||||
changePercent:
|
||||
difference &&
|
||||
previousPrice &&
|
||||
decimalFromString(previousPrice.value).value > 0n
|
||||
? formatDecimal(
|
||||
divide(
|
||||
multiply(difference, decimalFromString('100')),
|
||||
decimalFromString(previousPrice.value),
|
||||
CHANGE_PERCENT_DECIMAL_PLACES,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
unavailable,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
async quote(
|
||||
userId: string,
|
||||
uid: string,
|
||||
observe = false,
|
||||
): Promise<StockQuoteResourceDto> {
|
||||
const result = await this.sources.section(
|
||||
userId,
|
||||
'share',
|
||||
uid,
|
||||
'quote',
|
||||
observe,
|
||||
);
|
||||
return {
|
||||
data: result.values.instrument
|
||||
? stockQuote(result.values, result.unavailable, result.observedAt)
|
||||
: null,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
candles(
|
||||
userId: string,
|
||||
uid: string,
|
||||
period: StockCandlesQueryDto['period'] = 'month',
|
||||
): Promise<StockCandlesDto> {
|
||||
return this.catalog.cached(
|
||||
observe = false,
|
||||
) {
|
||||
return this.history.read(
|
||||
userId,
|
||||
`candles:${uid}:${period}`,
|
||||
async (token) => {
|
||||
const share = await this.catalog.share(token, uid);
|
||||
const historyFrom = timestamp(share.first_1dayCandleDate);
|
||||
const to = new Date();
|
||||
const from = new Date(to);
|
||||
from.setUTCMonth(
|
||||
from.getUTCMonth() -
|
||||
(period === 'month'
|
||||
? 1
|
||||
: period === 'halfYear'
|
||||
? HALF_YEAR_MONTHS
|
||||
: YEAR_MONTHS),
|
||||
);
|
||||
if (period === 'all') {
|
||||
if (!historyFrom)
|
||||
throw new ServiceUnavailableException({
|
||||
code: 'STOCK_HISTORY_START_UNAVAILABLE',
|
||||
});
|
||||
from.setTime(Date.parse(historyFrom));
|
||||
} else if (historyFrom && Date.parse(historyFrom) > from.valueOf())
|
||||
from.setTime(Date.parse(historyFrom));
|
||||
const collected = new Map<string, StockCandlesDto['candles'][number]>();
|
||||
// Conservative one-year windows also work with older deployed RPC limits.
|
||||
for (let start = from.valueOf(); start < to.valueOf();) {
|
||||
const end = Math.min(
|
||||
start + CANDLE_WINDOW_DAYS * dayMs,
|
||||
to.valueOf(),
|
||||
);
|
||||
for (const candle of await this.tbank.getCandles(
|
||||
token,
|
||||
uid,
|
||||
new Date(start),
|
||||
new Date(end),
|
||||
)) {
|
||||
const time = timestamp(candle.time);
|
||||
if (
|
||||
time &&
|
||||
candle.close &&
|
||||
Date.parse(time) >= from.valueOf() - dayMs &&
|
||||
Date.parse(time) <= to.valueOf()
|
||||
)
|
||||
collected.set(time, {
|
||||
time,
|
||||
close: formatDecimal(decimal(candle.close)),
|
||||
isComplete: candle.isComplete === true,
|
||||
});
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return {
|
||||
candles: [...collected.values()].sort((a, b) =>
|
||||
a.time.localeCompare(b.time),
|
||||
),
|
||||
currency: share.currency?.toUpperCase() || null,
|
||||
historyFrom,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
{ uid, instrumentType: 'share', period },
|
||||
observe,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function stockQuote(
|
||||
values: CatalogPayload,
|
||||
unavailable: string[],
|
||||
observedAt: string,
|
||||
): StockQuoteDto {
|
||||
const { price: last, candle: previous, tradingStatus = null } = values;
|
||||
const share = values.instrument;
|
||||
const priceAt = timestamp(last?.time);
|
||||
const currency = share?.currency?.toUpperCase();
|
||||
const price =
|
||||
last?.price && currency
|
||||
? { currency, value: formatDecimal(decimal(last.price)) }
|
||||
: null;
|
||||
const previousPrice =
|
||||
previous?.close && currency
|
||||
? { currency, value: formatDecimal(decimal(previous.close)) }
|
||||
: null;
|
||||
const difference =
|
||||
price && previousPrice
|
||||
? subtract(
|
||||
decimalFromString(price.value),
|
||||
decimalFromString(previousPrice.value),
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
price,
|
||||
priceAt,
|
||||
tradingStatus,
|
||||
previousCloseDate: timestamp(previous?.time)?.slice(0, 10) ?? null,
|
||||
previousClose: previousPrice,
|
||||
change:
|
||||
difference && currency
|
||||
? { currency, value: formatDecimal(difference) }
|
||||
: null,
|
||||
changePercent:
|
||||
difference &&
|
||||
previousPrice &&
|
||||
decimalFromString(previousPrice.value).value > 0n
|
||||
? formatDecimal(
|
||||
divide(
|
||||
multiply(difference, decimalFromString('100')),
|
||||
decimalFromString(previousPrice.value),
|
||||
CHANGE_PERCENT_DECIMAL_PLACES,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
unavailable,
|
||||
observedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,375 +1,70 @@
|
||||
import {
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { TbankAccessService } from '../../../../../integrations/tbank/tbank-access.service';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.client';
|
||||
import { PortfolioService } from '../../../portfolio/application/portfolio.service';
|
||||
import { GetStockCompanyUseCase } from './get-stock-company.use-case';
|
||||
import { StockIncomeService } from './stock-income.service';
|
||||
import { StockMarketService } from './stock-market.service';
|
||||
import { StockCatalogService } from './stock-catalog.service';
|
||||
import { metrics } from './get-stock-company.use-case';
|
||||
import { stockDividends } from './stock-income.service';
|
||||
import { stockQuote } from './stock-market.service';
|
||||
import { previousClose } from '../../application/instrument-market';
|
||||
jest.mock('../../../../../integrations/tbank/tbank-access.service', () => ({
|
||||
TbankAccessService: class TbankAccessService {},
|
||||
jest.mock('../../../../../prisma/prisma.service', () => ({
|
||||
PrismaService: class {},
|
||||
}));
|
||||
const time = (date: string) => ({ seconds: String(Date.parse(date) / 1000) });
|
||||
const share = {
|
||||
uid: 'uid',
|
||||
assetUid: 'asset',
|
||||
currency: 'rub',
|
||||
sector: 'financial',
|
||||
first_1dayCandleDate: time('2025-11-20'),
|
||||
};
|
||||
function setup() {
|
||||
let generation = 'a';
|
||||
const tbank = {
|
||||
findShares: jest.fn().mockResolvedValue([]),
|
||||
getLastPrices: jest.fn().mockResolvedValue([]),
|
||||
getShare: jest.fn().mockResolvedValue(share),
|
||||
getCandles: jest.fn().mockResolvedValue([]),
|
||||
getAssetDescription: jest.fn().mockResolvedValue('Company'),
|
||||
getFundamentals: jest.fn().mockResolvedValue({
|
||||
assetUid: 'asset',
|
||||
currency: 'rub',
|
||||
peRatioTtm: 6,
|
||||
netIncomeTtm: 10,
|
||||
}),
|
||||
getDividends: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const access = {
|
||||
withConnection: jest.fn(
|
||||
(user: string, handler: (context: unknown) => unknown) =>
|
||||
handler({ token: user, generation }),
|
||||
),
|
||||
};
|
||||
const portfolios = {
|
||||
getAll: jest.fn().mockResolvedValue({
|
||||
positions: [],
|
||||
lastSuccessfulAt: '2026-09-10T00:00:00Z',
|
||||
isStale: false,
|
||||
}),
|
||||
};
|
||||
const service = new StockCatalogService(
|
||||
access as unknown as TbankAccessService,
|
||||
tbank as unknown as TbankClient,
|
||||
);
|
||||
const market = new StockMarketService(
|
||||
service,
|
||||
tbank as unknown as TbankClient,
|
||||
);
|
||||
const income = new StockIncomeService(
|
||||
service,
|
||||
tbank as unknown as TbankClient,
|
||||
portfolios as unknown as PortfolioService,
|
||||
);
|
||||
const companyInfo = new GetStockCompanyUseCase(
|
||||
service,
|
||||
tbank as unknown as TbankClient,
|
||||
);
|
||||
return {
|
||||
market,
|
||||
income,
|
||||
companyInfo,
|
||||
service,
|
||||
tbank,
|
||||
portfolios,
|
||||
changeGeneration: () => {
|
||||
generation = 'b';
|
||||
},
|
||||
};
|
||||
}
|
||||
describe('stock market use case', () => {
|
||||
beforeEach(() =>
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-09-10T10:00:00Z')),
|
||||
);
|
||||
afterEach(() => jest.useRealTimers());
|
||||
it('returns unique ISINs, keeps preferred shares separate and matches prices by selected UID', async () => {
|
||||
const { service, tbank } = setup();
|
||||
const listings = [
|
||||
{
|
||||
uid: 'special',
|
||||
ticker: 'SBER',
|
||||
classCode: 'SPEQ',
|
||||
apiTradeAvailableFlag: false,
|
||||
},
|
||||
{
|
||||
uid: 'preferred',
|
||||
ticker: 'SBERP',
|
||||
classCode: 'TQBR',
|
||||
apiTradeAvailableFlag: true,
|
||||
},
|
||||
{
|
||||
uid: 'common',
|
||||
ticker: 'SBER',
|
||||
classCode: 'TQBR',
|
||||
apiTradeAvailableFlag: true,
|
||||
},
|
||||
].map((item) => ({
|
||||
...item,
|
||||
name: 'Сбербанк',
|
||||
isin: item.uid === 'preferred' ? 'ISINP' : 'ISIN',
|
||||
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
|
||||
}));
|
||||
tbank.findShares.mockResolvedValue([
|
||||
...listings,
|
||||
{ uid: 'bond', instrumentKind: 'INSTRUMENT_TYPE_BOND' },
|
||||
{ instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
|
||||
{ uid: '', instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
|
||||
]);
|
||||
tbank.getShare.mockImplementation((_token: string, uid: string) =>
|
||||
Promise.resolve({
|
||||
...listings.find((item) => item.uid === uid),
|
||||
currency: 'rub',
|
||||
brand: { logoName: 'sber.png' },
|
||||
shareType:
|
||||
uid === 'preferred' ? 'SHARE_TYPE_PREFERRED' : 'SHARE_TYPE_COMMON',
|
||||
}),
|
||||
const time = (value: string) => ({ seconds: String(Date.parse(value) / 1000) });
|
||||
describe('stock financial projections', () => {
|
||||
it('keeps raw public payouts when holdings are unavailable and omits cancelled events', () => {
|
||||
const result = stockDividends(
|
||||
[
|
||||
{
|
||||
dividendNet: { currency: 'rub', units: '32', nano: 880000000 },
|
||||
recordDate: time('2026-10-13'),
|
||||
paymentDate: time('2026-10-27'),
|
||||
},
|
||||
{ dividendType: 'Cancelled', recordDate: time('2026-10-14') },
|
||||
],
|
||||
null,
|
||||
{ from: '2021-09-10', to: '2027-09-10', today: '2026-09-10' },
|
||||
'source-time',
|
||||
true,
|
||||
);
|
||||
tbank.getLastPrices.mockResolvedValue([
|
||||
expect(result.dividends).toEqual([
|
||||
{
|
||||
instrumentUid: 'preferred',
|
||||
price: { units: '305' },
|
||||
time: time('2026-09-09'),
|
||||
},
|
||||
{
|
||||
instrumentUid: 'common',
|
||||
price: { units: '306', nano: 120000000 },
|
||||
time: time('2026-09-10'),
|
||||
perShare: { currency: 'RUB', value: '32.88' },
|
||||
recordDate: '2026-10-13',
|
||||
paymentDate: '2026-10-27',
|
||||
lastBuyDate: null,
|
||||
timing: 'upcoming',
|
||||
estimatedAmount: null,
|
||||
},
|
||||
]);
|
||||
const result = await service.search('user', 'SBER');
|
||||
expect(result.map((item) => item.instrumentUid)).toEqual([
|
||||
'common',
|
||||
'preferred',
|
||||
]);
|
||||
expect(result[0]).toMatchObject({
|
||||
classCode: 'TQBR',
|
||||
isin: 'ISIN',
|
||||
logoName: 'sber.png',
|
||||
price: { currency: 'RUB', value: '306.12' },
|
||||
priceAt: '2026-09-10T00:00:00.000Z',
|
||||
});
|
||||
expect(result[1]).toMatchObject({
|
||||
shareType: 'SHARE_TYPE_PREFERRED',
|
||||
price: { value: '305' },
|
||||
});
|
||||
expect(tbank.getLastPrices).toHaveBeenCalledTimes(1);
|
||||
expect(result.estimateUnavailable).toBe(true);
|
||||
expect(result.observedAt).toBe('source-time');
|
||||
});
|
||||
it('prefers TQBR among equally available listings, deduplicates before the limit and keeps missing ISINs separate', async () => {
|
||||
const { service, tbank } = setup();
|
||||
const hit = {
|
||||
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
|
||||
ticker: 'SBER',
|
||||
apiTradeAvailableFlag: true,
|
||||
};
|
||||
tbank.findShares.mockResolvedValue([
|
||||
...Array.from({ length: 35 }, (_, i) => ({
|
||||
...hit,
|
||||
uid: `alternate-${i}`,
|
||||
isin: ' isin ',
|
||||
classCode: 'SPEQ',
|
||||
})),
|
||||
{ ...hit, uid: 'common', isin: 'ISIN', classCode: 'TQBR' },
|
||||
{
|
||||
...hit,
|
||||
uid: 'preferred',
|
||||
ticker: 'SBERP',
|
||||
isin: 'ISINP',
|
||||
classCode: 'TQBR',
|
||||
},
|
||||
{ ...hit, uid: 'unknown-a', isin: '' },
|
||||
{ ...hit, uid: 'unknown-b' },
|
||||
]);
|
||||
tbank.getShare.mockResolvedValue(null);
|
||||
const result = await service.search('user', 'SBER');
|
||||
expect(result.map((item) => item.instrumentUid)).toEqual([
|
||||
'common',
|
||||
'unknown-a',
|
||||
'unknown-b',
|
||||
'preferred',
|
||||
]);
|
||||
expect(tbank.getShare).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
it('retains catalog identity when enrichment is unavailable, but propagates auth errors', async () => {
|
||||
const { service, tbank } = setup();
|
||||
tbank.findShares.mockResolvedValue([
|
||||
{
|
||||
uid: 'uid',
|
||||
ticker: 'SBER',
|
||||
classCode: 'TQBR',
|
||||
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
|
||||
},
|
||||
]);
|
||||
tbank.getShare.mockRejectedValue(new ServiceUnavailableException());
|
||||
tbank.getLastPrices.mockRejectedValue(new ServiceUnavailableException());
|
||||
expect(await service.search('user', 'SBER')).toEqual([
|
||||
expect.objectContaining({
|
||||
instrumentUid: 'uid',
|
||||
classCode: 'TQBR',
|
||||
price: null,
|
||||
logoName: null,
|
||||
}),
|
||||
]);
|
||||
tbank.getShare.mockResolvedValue(null);
|
||||
expect(await service.search('user', 'sber')).toEqual([
|
||||
expect.objectContaining({ instrumentUid: 'uid' }),
|
||||
]);
|
||||
tbank.getShare.mockRejectedValue(new UnauthorizedException());
|
||||
await expect(service.search('another-user', 'SBER')).rejects.toBeInstanceOf(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
it('skips enrichment for an empty catalog result', async () => {
|
||||
const { service, tbank } = setup();
|
||||
expect(await service.search('user', 'none')).toEqual([]);
|
||||
expect(tbank.getShare).not.toHaveBeenCalled();
|
||||
expect(tbank.getLastPrices).not.toHaveBeenCalled();
|
||||
});
|
||||
it('resolves an exact ticker, preserves other listing UIDs and does not confuse SBER with SBERP', async () => {
|
||||
const { service, tbank } = setup();
|
||||
const listings = [
|
||||
{
|
||||
uid: 'common',
|
||||
ticker: 'SBER',
|
||||
isin: 'COMMON',
|
||||
classCode: 'TQBR',
|
||||
apiTradeAvailableFlag: true,
|
||||
},
|
||||
{
|
||||
uid: 'special',
|
||||
ticker: 'SBER',
|
||||
isin: 'COMMON',
|
||||
classCode: 'SPEQ',
|
||||
apiTradeAvailableFlag: false,
|
||||
},
|
||||
{
|
||||
uid: 'preferred',
|
||||
ticker: 'SBERP',
|
||||
isin: 'PREFERRED',
|
||||
classCode: 'TQBR',
|
||||
apiTradeAvailableFlag: true,
|
||||
},
|
||||
].map((item) => ({ ...item, instrumentKind: 'INSTRUMENT_TYPE_SHARE' }));
|
||||
tbank.findShares.mockResolvedValue(listings);
|
||||
tbank.getShare.mockImplementation((_token: string, uid: string) =>
|
||||
Promise.resolve(listings.find((item) => item.uid === uid)),
|
||||
);
|
||||
expect(await service.getByTicker('user', 'sberp')).toMatchObject({
|
||||
instrumentUid: 'preferred',
|
||||
slug: 'SBERP',
|
||||
});
|
||||
expect(await service.get('user', 'common')).toMatchObject({
|
||||
instrumentUid: 'common',
|
||||
slug: 'SBER',
|
||||
});
|
||||
expect(await service.get('user', 'special')).toMatchObject({
|
||||
instrumentUid: 'special',
|
||||
slug: 'special',
|
||||
});
|
||||
await expect(service.getByTicker('user', 'SB')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
it('refuses ambiguous tickers while keeping exact UID pages accessible', async () => {
|
||||
const { service, tbank } = setup();
|
||||
const listings = ['one', 'two'].map((uid) => ({
|
||||
uid,
|
||||
ticker: 'SAME',
|
||||
isin: uid,
|
||||
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
|
||||
}));
|
||||
tbank.findShares.mockResolvedValue(listings);
|
||||
tbank.getShare.mockResolvedValue(listings[0]);
|
||||
await expect(service.getByTicker('user', 'SAME')).rejects.toBeInstanceOf(
|
||||
ConflictException,
|
||||
);
|
||||
expect(await service.get('user', 'one')).toMatchObject({
|
||||
instrumentUid: 'one',
|
||||
slug: 'one',
|
||||
});
|
||||
});
|
||||
it('keeps exact pages if alias lookup fails and partitions ticker resolution by connection', async () => {
|
||||
const { service, tbank, changeGeneration } = setup();
|
||||
tbank.getShare.mockResolvedValue({ ...share, ticker: 'F' });
|
||||
tbank.findShares.mockRejectedValueOnce(new ServiceUnavailableException());
|
||||
expect(await service.get('user', 'uid')).toMatchObject({ slug: 'uid' });
|
||||
tbank.findShares.mockResolvedValue([
|
||||
{ ...share, ticker: 'F', instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
|
||||
]);
|
||||
expect(await service.getByTicker('user', 'F')).toMatchObject({
|
||||
instrumentUid: 'uid',
|
||||
slug: 'F',
|
||||
});
|
||||
changeGeneration();
|
||||
expect(await service.getByTicker('user', 'F')).toMatchObject({ slug: 'F' });
|
||||
expect(tbank.findShares).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it('uses a complete previous trading day, never today’s main close', () => {
|
||||
it('uses the last complete previous trading day', () => {
|
||||
const candles = [
|
||||
{ time: time('2026-09-09'), close: { units: '10' }, isComplete: true },
|
||||
{ time: time('2026-09-10'), close: { units: '11' }, isComplete: true },
|
||||
{ time: time('2026-09-08'), close: { units: '9' }, isComplete: false },
|
||||
{ time: time('2026-09-10'), close: { units: '11' }, isComplete: false },
|
||||
];
|
||||
expect(previousClose(candles, '2026-09-10T18:00:00Z')).toEqual(candles[0]);
|
||||
expect(previousClose(candles, '2026-09-09T22:00:00Z')).toEqual(candles[0]);
|
||||
});
|
||||
it('starts all-history at listing, keeps incomplete candles and deduplicates boundaries', async () => {
|
||||
const { tbank, market } = setup();
|
||||
tbank.getCandles.mockResolvedValue([
|
||||
{ time: time('2026-09-09'), close: { units: '10' }, isComplete: false },
|
||||
]);
|
||||
const result = await market.candles('user', 'uid', 'all');
|
||||
expect(tbank.getCandles).toHaveBeenCalledWith(
|
||||
'user',
|
||||
'uid',
|
||||
new Date('2025-11-20'),
|
||||
expect.any(Date),
|
||||
);
|
||||
expect(result.candles).toHaveLength(1);
|
||||
expect(result.candles[0].isComplete).toBe(false);
|
||||
});
|
||||
it('does not manufacture zero fundamentals and isolates optional failures', async () => {
|
||||
const { tbank, companyInfo } = setup();
|
||||
tbank.getAssetDescription.mockRejectedValue(
|
||||
new ServiceUnavailableException(),
|
||||
);
|
||||
const result = await companyInfo.execute('user', 'uid');
|
||||
expect(result.description).toBeNull();
|
||||
expect(result.unavailable).toEqual(['description']);
|
||||
expect(result.metrics.map((item) => item.key)).toEqual([
|
||||
'peRatioTtm',
|
||||
'netIncomeTtm',
|
||||
]);
|
||||
});
|
||||
it('isolates cache by user and connection generation', async () => {
|
||||
const { service, tbank, changeGeneration } = setup();
|
||||
await service.get('a', 'uid');
|
||||
await service.get('a', 'uid');
|
||||
expect(tbank.getShare).toHaveBeenCalledTimes(1);
|
||||
await service.get('b', 'uid');
|
||||
changeGeneration();
|
||||
await service.get('a', 'uid');
|
||||
expect(tbank.getShare).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it('keeps public dividends when there is no holding or position retrieval fails', async () => {
|
||||
const { tbank, portfolios, income } = setup();
|
||||
portfolios.getAll.mockRejectedValue(new ServiceUnavailableException());
|
||||
tbank.getDividends.mockResolvedValue([
|
||||
{
|
||||
dividendNet: { currency: 'rub', units: '32', nano: 880000000 },
|
||||
recordDate: time('2026-10-13'),
|
||||
paymentDate: time('2026-10-27'),
|
||||
},
|
||||
]);
|
||||
const result = await income.dividends('user', 'uid');
|
||||
expect(result.estimateUnavailable).toBe(true);
|
||||
expect(result.dividends[0]).toMatchObject({
|
||||
perShare: { currency: 'RUB', value: '32.88' },
|
||||
estimatedAmount: null,
|
||||
timing: 'upcoming',
|
||||
it('retains stock price precision and percent change without inventing unavailable fundamentals', () => {
|
||||
expect(
|
||||
stockQuote(
|
||||
{
|
||||
instrument: { currency: 'rub' },
|
||||
price: { price: { units: '11', nano: 1 } },
|
||||
candle: { close: { units: '10' } },
|
||||
},
|
||||
[],
|
||||
'time',
|
||||
),
|
||||
).toMatchObject({
|
||||
price: { currency: 'RUB', value: '11.000000001' },
|
||||
change: { currency: 'RUB', value: '1.000000001' },
|
||||
changePercent: '10',
|
||||
});
|
||||
expect(metrics(null, 'financial')).toEqual([]);
|
||||
expect(
|
||||
metrics(
|
||||
{ peRatioTtm: 6, netIncomeTtm: 10, revenueTtm: 100, currency: 'rub' },
|
||||
'financial',
|
||||
).map((item) => item.key),
|
||||
).toEqual(['peRatioTtm', 'netIncomeTtm']);
|
||||
expect(metrics({ netIncomeTtm: 10 })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { InvestmentReadQueryDto } from '../../../investment-resource.dto';
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
@@ -15,15 +16,15 @@ import { GetStockCompanyUseCase } from '../application/get-stock-company.use-cas
|
||||
import { StockIncomeService } from '../application/stock-income.service';
|
||||
import { StockMarketService } from '../application/stock-market.service';
|
||||
import {
|
||||
StockCandlesDto,
|
||||
StockCandlesResourceDto,
|
||||
StockCandlesQueryDto,
|
||||
StockCompanyDto,
|
||||
StockDividendsDto,
|
||||
StockDto,
|
||||
StockPositionDto,
|
||||
StockQuoteDto,
|
||||
StockCompanyResourceDto,
|
||||
StockDividendsResourceDto,
|
||||
StockResourceDto,
|
||||
StockPositionResourceDto,
|
||||
StockQuoteResourceDto,
|
||||
StockSearchQueryDto,
|
||||
StockSearchResultDto,
|
||||
StockSearchResourceDto,
|
||||
StockTickerParamsDto,
|
||||
} from './stock.dto';
|
||||
import { StockCatalogService } from '../application/stock-catalog.service';
|
||||
@@ -41,68 +42,99 @@ export class StockController {
|
||||
private readonly companyInfo: GetStockCompanyUseCase,
|
||||
) {}
|
||||
@Get()
|
||||
@ApiOkResponse({ type: [StockSearchResultDto] })
|
||||
@ApiOkResponse({ type: StockSearchResourceDto })
|
||||
search(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Query() query: StockSearchQueryDto,
|
||||
) {
|
||||
return this.stocks.search(request.user.sub, query.query);
|
||||
return this.stocks.search(
|
||||
request.user.sub,
|
||||
query.query,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
@Get('by-ticker/:ticker')
|
||||
@ApiOkResponse({ type: StockDto })
|
||||
@ApiOkResponse({ type: StockResourceDto })
|
||||
getByTicker(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param() params: StockTickerParamsDto,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.stocks.getByTicker(request.user.sub, params.ticker);
|
||||
return this.stocks.getByTicker(
|
||||
request.user.sub,
|
||||
params.ticker,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
@Get(':uid')
|
||||
@ApiOkResponse({ type: StockDto })
|
||||
@ApiOkResponse({ type: StockResourceDto })
|
||||
get(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.stocks.get(request.user.sub, uid);
|
||||
return this.stocks.get(request.user.sub, uid, query.sync === 'observe');
|
||||
}
|
||||
@Get(':uid/quote')
|
||||
@ApiOkResponse({ type: StockQuoteDto })
|
||||
@ApiOkResponse({ type: StockQuoteResourceDto })
|
||||
quote(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.market.quote(request.user.sub, uid);
|
||||
return this.market.quote(request.user.sub, uid, query.sync === 'observe');
|
||||
}
|
||||
@Get(':uid/candles')
|
||||
@ApiOkResponse({ type: StockCandlesDto })
|
||||
@ApiOkResponse({ type: StockCandlesResourceDto })
|
||||
candles(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: StockCandlesQueryDto,
|
||||
) {
|
||||
return this.market.candles(request.user.sub, uid, query.period);
|
||||
return this.market.candles(
|
||||
request.user.sub,
|
||||
uid,
|
||||
query.period,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
@Get(':uid/position')
|
||||
@ApiOkResponse({ type: StockPositionDto })
|
||||
@ApiOkResponse({ type: StockPositionResourceDto })
|
||||
position(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.income.position(request.user.sub, uid);
|
||||
return this.income.readPosition(
|
||||
request.user.sub,
|
||||
uid,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
@Get(':uid/company')
|
||||
@ApiOkResponse({ type: StockCompanyDto })
|
||||
@ApiOkResponse({ type: StockCompanyResourceDto })
|
||||
company(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.companyInfo.execute(request.user.sub, uid);
|
||||
return this.companyInfo.execute(
|
||||
request.user.sub,
|
||||
uid,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
@Get(':uid/dividends')
|
||||
@ApiOkResponse({ type: StockDividendsDto })
|
||||
@ApiOkResponse({ type: StockDividendsResourceDto })
|
||||
dividends(
|
||||
@Req() request: Request & { user: AccessPayload },
|
||||
@Param('uid', new ParseUUIDPipe()) uid: string,
|
||||
@Query() query: InvestmentReadQueryDto,
|
||||
) {
|
||||
return this.income.dividends(request.user.sub, uid);
|
||||
return this.income.dividends(
|
||||
request.user.sub,
|
||||
uid,
|
||||
query.sync === 'observe',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
InvestmentReadQueryDto,
|
||||
InvestmentResourceMetaDto,
|
||||
} from '../../../investment-resource.dto';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
@@ -13,7 +17,7 @@ import { PortfolioPositionDto } from '../../../portfolio/portfolio.api';
|
||||
|
||||
const MAX_INSTRUMENT_QUERY_LENGTH = 80;
|
||||
|
||||
export class StockSearchQueryDto {
|
||||
export class StockSearchQueryDto extends InvestmentReadQueryDto {
|
||||
@ApiProperty({ minLength: 2, maxLength: MAX_INSTRUMENT_QUERY_LENGTH })
|
||||
@Transform(({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' ? value.trim() : value,
|
||||
@@ -35,7 +39,7 @@ export class StockTickerParamsDto {
|
||||
@Matches(/^[A-Za-z0-9][A-Za-z0-9._@+-]*$/)
|
||||
declare ticker: string;
|
||||
}
|
||||
export class StockCandlesQueryDto {
|
||||
export class StockCandlesQueryDto extends InvestmentReadQueryDto {
|
||||
@ApiPropertyOptional({
|
||||
enum: ['month', 'halfYear', 'year', 'all'],
|
||||
default: 'month',
|
||||
@@ -168,3 +172,52 @@ export class StockDividendsDto {
|
||||
@ApiProperty() declare estimateUnavailable: boolean;
|
||||
@ApiProperty() declare positionIsStale: boolean;
|
||||
}
|
||||
|
||||
export class StockPositionResourceDto {
|
||||
@ApiProperty({ type: StockPositionDto, nullable: true })
|
||||
declare data: StockPositionDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockSearchResourceDto {
|
||||
@ApiProperty({ type: StockSearchResultDto, isArray: true, nullable: true })
|
||||
declare data: StockSearchResultDto[] | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockResourceDto {
|
||||
@ApiProperty({ type: StockDto, nullable: true })
|
||||
declare data: StockDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockQuoteResourceDto {
|
||||
@ApiProperty({ type: StockQuoteDto, nullable: true })
|
||||
declare data: StockQuoteDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockCompanyResourceDto {
|
||||
@ApiProperty({ type: StockCompanyDto, nullable: true })
|
||||
declare data: StockCompanyDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockCandlesResourceDto {
|
||||
@ApiProperty({ type: StockCandlesDto, nullable: true })
|
||||
declare data: StockCandlesDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
export class StockDividendsResourceDto {
|
||||
@ApiProperty({ type: StockDividendsDto, nullable: true })
|
||||
declare data: StockDividendsDto | null;
|
||||
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||
declare meta: InvestmentResourceMetaDto;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user