Compare commits
64 Commits
codex/mcp-
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 40ef3e9059 | |||
| d8070209ed | |||
| 3281866c43 | |||
| 8b24d8b82b | |||
| d21e2411b8 | |||
| ff0e11b303 | |||
| c4b93f9f0c | |||
| 3fdceb9438 | |||
| fee179d8e9 | |||
| 58b8075583 | |||
| d7b65e256f | |||
| b12c2741cd | |||
| a1377fa5c2 | |||
| 27fb6e77be | |||
| 94f8bb876d | |||
| 3bad694dce | |||
| 21df354df6 | |||
| 0a1ae0552c | |||
| 1a2937ad58 | |||
| af0aaeda9d | |||
| ae207b0cb3 | |||
| d4d1dd980e | |||
| 0116c34a9f | |||
| d804d43616 | |||
| 8df94a51dd | |||
| c429d6a43a | |||
| 49dac140ff | |||
| 8dab915edd | |||
| bbbdca30f6 | |||
| 99a917392a | |||
| 47e65c9b46 | |||
| 7af8691e0c | |||
| 4cb0b8d450 | |||
| 293838ba68 | |||
| b27d6ad836 | |||
| 53bab79c5f | |||
| 0e7ecbb1ef | |||
| b87ed761ed | |||
| fe938b2706 | |||
| af0c93fd34 | |||
| db28f46481 | |||
| 0e8f65c457 | |||
| 120db3c2ab | |||
| 58ddb10a92 | |||
| 4ed6e0ce20 | |||
| 75fead68b8 | |||
| d2457d13af | |||
| 238836c850 | |||
| 6e8efd2b80 | |||
| 9f85dc5dde | |||
| 3b919ecdc6 | |||
| ccb1082535 | |||
| 8d6410b37b | |||
| 1fc7386568 | |||
| e69f183372 | |||
| b092caf8d6 | |||
| 3a89cef76c | |||
| 659be4636c | |||
| de776f477c | |||
| 194a8be3e4 | |||
| 95e9e7f71f | |||
| ba0a4cbfef | |||
| f2fe6a4829 | |||
| f0b6785540 |
2
.gitignore
vendored
2
.gitignore
vendored
@ -14,4 +14,4 @@ apps/docs/build/
|
||||
.playwright-mcp
|
||||
.opencode
|
||||
dev.db
|
||||
graphify-out/cache/
|
||||
graphify-out/
|
||||
|
||||
18
AGENTS.md
18
AGENTS.md
@ -507,13 +507,19 @@ roadmap.md и inbox.md никогда не являются основанием
|
||||
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
This project has a knowledge graph in `graphify-out/` with god nodes, community structure, and cross-file relationships. The graph is a local artifact, not a tracked repo asset.
|
||||
|
||||
When the user types `/graphify`, invoke the `skill` tool with `skill: "graphify"` before doing anything else.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- Dirty graphify-out/ files are expected after hooks or incremental updates; dirty graph files are not a reason to skip graphify. Only skip graphify if the task is about stale or incorrect graph output, or the user explicitly says not to use it.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
- Используй `graphify` в первую очередь, когда задача связана с архитектурой, границами модулей, кросс-файловым влиянием или трассировкой потока данных.
|
||||
- Для таких вопросов сначала запускай `graphify query "<question>"`, если существует `graphify-out/graph.json`. Для связей используй `graphify path "<A>" "<B>"`, для точечных концептов — `graphify explain "<concept>"`. Обычно это даёт гораздо более узкий подграф, чем `GRAPH_REPORT.md` или raw grep.
|
||||
- Предпочитай `graphify query` перед raw grep, когда нужен кратчайший путь между концептами, мост между комьюнити или трассировка того, как один подсистемный блок достигает другого.
|
||||
- Для отладки багов начинай с симптома и спрашивай у graphify путь зависимости, bridge nodes или модули, которые могут объяснить неожиданное поведение.
|
||||
- Если `graphify` возвращает только общую структуру, переходи к `serena` за символ-уровневыми фактами и затем повторяй `graphify` с более узким вопросом, где названы конкретные файлы, модули или сервисы.
|
||||
- Dirty `graphify-out/` после хуков или инкрементальных обновлений считаются нормой; грязные файлы графа не повод пропускать `graphify`. Пропускать его можно только если задача именно про устаревший или некорректный граф, либо если пользователь прямо попросил не использовать его.
|
||||
- В новом `worktree` сначала заново создай локальный граф командой `graphify extract .`.
|
||||
- После первой сборки в этом `worktree` обновляй граф командой `graphify update .`.
|
||||
- Если существует `graphify-out/wiki/index.md`, используй его для широкого обзора вместо ручного просмотра исходников.
|
||||
- `graphify-out/GRAPH_REPORT.md` читай только для широкого архитектурного обзора или когда `query/path/explain` не дают достаточно контекста.
|
||||
- После изменений в коде запускай `graphify update .`, чтобы держать граф актуальным (только AST, без затрат на LLM).
|
||||
|
||||
@ -125,6 +125,8 @@ docs/
|
||||
| `npm run format` | Prettier для всех `*.{ts,tsx}` |
|
||||
| `npm run codegen -w apps/frontend` | `openapi-typescript` из запущенного локального Swagger → `src/api/types.ts` |
|
||||
|
||||
`graphify-out/` — локальный артефакт знания, он не хранится в git. В новом `worktree` сначала собери его заново: `graphify extract .`; дальше обновляй инкрементально: `graphify update .`. Для вопросов по коду используй `graphify query "..."`.
|
||||
|
||||
Docusaurus (`apps/docs`) — опубликованная документация для пользователей. Storybook (`packages/design-system`) — инженерный workbench для разработки компонентов.
|
||||
|
||||
Интеграционные тесты с MOEX: `npm run test:integration -w apps/backend`.
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { CacheModule } from './modules/cache/cache.module';
|
||||
import { MoexClientModule } from './modules/moex-client/moex-client.module';
|
||||
@ -11,6 +11,7 @@ import { PortfolioModule } from './modules/portfolio/portfolio.module';
|
||||
import { PrismaModule } from './modules/prisma/prisma.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { TBankModule } from './modules/tbank/tbank.module';
|
||||
import { RequestLoggingMiddleware } from './common/middleware/request-logging.middleware';
|
||||
import configuration from './config/configuration';
|
||||
|
||||
@Module({
|
||||
@ -29,4 +30,8 @@ import configuration from './config/configuration';
|
||||
TBankModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
export class AppModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(RequestLoggingMiddleware).forRoutes('*');
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,6 +13,14 @@ export class ApiResponseMeta {
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiEnvelopePayload<T> {
|
||||
constructor(
|
||||
public readonly data: T,
|
||||
public readonly fromCache: boolean,
|
||||
public readonly cachedAt: string | null,
|
||||
) {}
|
||||
}
|
||||
|
||||
export class ApiResponse<T> {
|
||||
data: T;
|
||||
meta: ApiResponseMeta;
|
||||
|
||||
8
apps/backend/src/common/exceptions/domain.exception.ts
Normal file
8
apps/backend/src/common/exceptions/domain.exception.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export abstract class DomainException extends HttpException {
|
||||
constructor(message: string, status: HttpStatus) {
|
||||
super(message, status);
|
||||
this.name = this.constructor.name;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { DomainException } from './domain.exception';
|
||||
|
||||
export class EntityNotFoundException extends DomainException {
|
||||
constructor(entity: string, id: string | number) {
|
||||
super(`${entity} ${id} not found`, HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
8
apps/backend/src/common/exceptions/moex-api.exception.ts
Normal file
8
apps/backend/src/common/exceptions/moex-api.exception.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { DomainException } from './domain.exception';
|
||||
|
||||
export class MoexApiException extends DomainException {
|
||||
constructor(message: string) {
|
||||
super(`MOEX API error: ${message}`, HttpStatus.BAD_GATEWAY);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { DomainException } from './domain.exception';
|
||||
|
||||
export class PortfolioAccessDeniedException extends DomainException {
|
||||
constructor(portfolioId: number) {
|
||||
super(`Access denied to portfolio ${portfolioId}`, HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
14
apps/backend/src/common/exceptions/tbank-api.exception.ts
Normal file
14
apps/backend/src/common/exceptions/tbank-api.exception.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { DomainException } from './domain.exception';
|
||||
|
||||
export class TBankApiException extends DomainException {
|
||||
constructor(message: string) {
|
||||
super(`T-Bank API error: ${message}`, HttpStatus.BAD_GATEWAY);
|
||||
}
|
||||
}
|
||||
|
||||
export class TBankNotConfiguredException extends DomainException {
|
||||
constructor() {
|
||||
super('T-Bank integration is not configured', HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
import { ArgumentsHost, BadRequestException, HttpStatus } from '@nestjs/common';
|
||||
import { HttpExceptionFilter } from './http-exception.filter';
|
||||
|
||||
describe('HttpExceptionFilter', () => {
|
||||
const createHost = () => {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
const host = {
|
||||
switchToHttp: () => ({
|
||||
getResponse: () => ({ status }),
|
||||
getRequest: () => ({ url: '/api/v1/test' }),
|
||||
}),
|
||||
} as unknown as ArgumentsHost;
|
||||
|
||||
return { host, status, json };
|
||||
};
|
||||
|
||||
it('does not expose internal Error.message for unhandled exceptions', () => {
|
||||
const filter = new HttpExceptionFilter();
|
||||
const { host, status, json } = createHost();
|
||||
|
||||
filter.catch(new Error('Prisma failed at file:///secret/path'), host);
|
||||
|
||||
expect(status).toHaveBeenCalledWith(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
expect(json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'Internal server error',
|
||||
error: 'Internal Server Error',
|
||||
path: '/api/v1/test',
|
||||
}),
|
||||
);
|
||||
expect(json.mock.calls[0][0].message).not.toContain('Prisma failed');
|
||||
});
|
||||
|
||||
it('returns safe defaults for non-Error thrown values', () => {
|
||||
const filter = new HttpExceptionFilter();
|
||||
const { host, status, json } = createHost();
|
||||
|
||||
filter.catch('some string error', host);
|
||||
|
||||
expect(status).toHaveBeenCalledWith(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
expect(json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'Internal server error',
|
||||
error: 'Internal Server Error',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps HttpException response messages intact', () => {
|
||||
const filter = new HttpExceptionFilter();
|
||||
const { host, status, json } = createHost();
|
||||
|
||||
filter.catch(new BadRequestException('Invalid request'), host);
|
||||
|
||||
expect(status).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
|
||||
expect(json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'Invalid request',
|
||||
error: 'Bad Request',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -1,8 +1,10 @@
|
||||
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, Logger } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(HttpExceptionFilter.name);
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
@ -24,7 +26,9 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
||||
error = (r.error as string) || exception.name;
|
||||
}
|
||||
} else if (exception instanceof Error) {
|
||||
message = exception.message;
|
||||
this.logger.error(`Unhandled exception: ${exception.message}`, exception.stack);
|
||||
} else {
|
||||
this.logger.error(`Unhandled non-error exception: ${String(exception)}`);
|
||||
}
|
||||
|
||||
response.status(status).json({
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiResponse } from '../dto/api-response.dto';
|
||||
import { ApiEnvelopePayload, ApiResponse } from '../dto/api-response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
|
||||
@ -9,6 +9,9 @@ export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T
|
||||
return next.handle().pipe(
|
||||
map((data) => {
|
||||
if (data instanceof ApiResponse) return data;
|
||||
if (data instanceof ApiEnvelopePayload) {
|
||||
return new ApiResponse(data.data, data.fromCache, data.cachedAt);
|
||||
}
|
||||
return new ApiResponse(data, false, null);
|
||||
}),
|
||||
);
|
||||
|
||||
76
apps/backend/src/config/backend-runtime-config.spec.ts
Normal file
76
apps/backend/src/config/backend-runtime-config.spec.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
describe('backend runtime configuration', () => {
|
||||
const OLD_ENV = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
process.env = { ...OLD_ENV };
|
||||
delete process.env.JWT_SECRET;
|
||||
delete process.env.JWT_REFRESH_SECRET;
|
||||
delete process.env.BACKEND_CORS_ORIGINS;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = OLD_ENV;
|
||||
});
|
||||
|
||||
it('keeps dev auth defaults outside production', async () => {
|
||||
const configuration = (await import('./configuration')).default;
|
||||
|
||||
expect(configuration().auth).toMatchObject({
|
||||
jwtSecret: 'dev-jwt-secret-change-in-production',
|
||||
jwtRefreshSecret: 'dev-refresh-secret-change-in-production',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses backend CORS origins from comma-separated env', async () => {
|
||||
process.env.BACKEND_CORS_ORIGINS = 'https://app.example.com, http://localhost:5173 ';
|
||||
const configuration = (await import('./configuration')).default;
|
||||
|
||||
expect(configuration().cors.origins).toEqual([
|
||||
'https://app.example.com',
|
||||
'http://localhost:5173',
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects production defaults for JWT secrets', async () => {
|
||||
const { assertSafeProductionConfig } = await import('../main');
|
||||
|
||||
expect(() =>
|
||||
assertSafeProductionConfig({
|
||||
nodeEnv: 'production',
|
||||
jwtSecret: 'dev-jwt-secret-change-in-production',
|
||||
jwtRefreshSecret: 'custom-refresh-secret',
|
||||
corsOrigins: ['https://app.example.com'],
|
||||
}),
|
||||
).toThrow('JWT_SECRET must be set to a non-default value in production');
|
||||
});
|
||||
|
||||
it('rejects production credentialed CORS without explicit origins', async () => {
|
||||
const { assertSafeProductionConfig } = await import('../main');
|
||||
|
||||
expect(() =>
|
||||
assertSafeProductionConfig({
|
||||
nodeEnv: 'production',
|
||||
jwtSecret: 'custom-access-secret',
|
||||
jwtRefreshSecret: 'custom-refresh-secret',
|
||||
corsOrigins: [],
|
||||
}),
|
||||
).toThrow('BACKEND_CORS_ORIGINS must contain at least one origin in production');
|
||||
});
|
||||
|
||||
it('allows development with reflected CORS', async () => {
|
||||
const { buildCorsOrigin } = await import('../main');
|
||||
|
||||
expect(buildCorsOrigin('development', [])).toBe(true);
|
||||
});
|
||||
|
||||
it('uses explicit production CORS origins', async () => {
|
||||
const { buildCorsOrigin } = await import('../main');
|
||||
|
||||
expect(buildCorsOrigin('production', ['https://app.example.com'])).toEqual([
|
||||
'https://app.example.com',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@ -1,5 +1,14 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export const DEV_JWT_SECRET = 'dev-jwt-secret-change-in-production';
|
||||
export const DEV_JWT_REFRESH_SECRET = 'dev-refresh-secret-change-in-production';
|
||||
|
||||
const parseCsv = (value: string | undefined): string[] =>
|
||||
(value ?? '')
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
export default registerAs('app', () => ({
|
||||
port: parseInt(process.env.PORT || '3000', 10),
|
||||
database: {
|
||||
@ -29,6 +38,7 @@ export default registerAs('app', () => ({
|
||||
candlesTtl: parseInt(process.env.CACHE_CANDLES_TTL || '3600', 10),
|
||||
securityTtl: parseInt(process.env.CACHE_SECURITY_TTL || '86400', 10),
|
||||
searchTtl: parseInt(process.env.CACHE_SEARCH_TTL || '3600', 10),
|
||||
screenerTtl: parseInt(process.env.CACHE_SCREENER_TTL || '900', 10),
|
||||
dividendsTtl: parseInt(process.env.CACHE_DIVIDENDS_TTL || '86400', 10),
|
||||
tbankAccountsTtl: parseInt(process.env.CACHE_TBANK_ACCOUNTS_TTL || '3600', 10),
|
||||
tbankPortfolioTtl: parseInt(process.env.CACHE_TBANK_PORTFOLIO_TTL || '60', 10),
|
||||
@ -37,6 +47,9 @@ export default registerAs('app', () => ({
|
||||
tbankInstrumentTtl: parseInt(process.env.CACHE_TBANK_INSTRUMENT_TTL || '86400', 10),
|
||||
tbankAnalyticsTtl: parseInt(process.env.CACHE_TBANK_ANALYTICS_TTL || '300', 10),
|
||||
},
|
||||
cors: {
|
||||
origins: parseCsv(process.env.BACKEND_CORS_ORIGINS),
|
||||
},
|
||||
auth: {
|
||||
jwtSecret: process.env.JWT_SECRET || 'dev-jwt-secret-change-in-production',
|
||||
jwtRefreshSecret: process.env.JWT_REFRESH_SECRET || 'dev-refresh-secret-change-in-production',
|
||||
|
||||
63
apps/backend/src/envelope-contract.spec.ts
Normal file
63
apps/backend/src/envelope-contract.spec.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import 'reflect-metadata'
|
||||
import { Test, type TestingModule } from '@nestjs/testing'
|
||||
import type { INestApplication } from '@nestjs/common'
|
||||
import { ConfigModule } from '@nestjs/config'
|
||||
import { HealthModule } from './modules/health/health.module'
|
||||
import { PrismaModule } from './modules/prisma/prisma.module'
|
||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor'
|
||||
import configuration from './config/configuration'
|
||||
|
||||
describe('API envelope contract', () => {
|
||||
let app: INestApplication
|
||||
let baseUrl: string
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [ConfigModule.forRoot({ load: [configuration], isGlobal: true, envFilePath: '.env' }), PrismaModule, HealthModule],
|
||||
}).compile()
|
||||
|
||||
app = module.createNestApplication()
|
||||
app.setGlobalPrefix('api/v1')
|
||||
app.useGlobalInterceptors(new TransformInterceptor())
|
||||
await app.init()
|
||||
await app.listen(0)
|
||||
|
||||
const address = app.getHttpServer().address()
|
||||
if (typeof address === 'object' && address && 'port' in address) {
|
||||
baseUrl = `http://127.0.0.1:${address.port}`
|
||||
}
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('returns a proper envelope with checks from the public health endpoint', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/v1/health`)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const body = (await response.json()) as {
|
||||
data: { status: string; timestamp: string; uptime: number; checks: Array<{ name: string; status: string }> }
|
||||
meta: { fromCache: boolean; cachedAt: string | null }
|
||||
}
|
||||
|
||||
expect(body).toMatchObject({
|
||||
data: {
|
||||
status: expect.any(String),
|
||||
timestamp: expect.any(String),
|
||||
uptime: expect.any(Number),
|
||||
checks: expect.arrayContaining([
|
||||
expect.objectContaining({ name: 'prisma', status: expect.any(String) }),
|
||||
expect.objectContaining({ name: 'moex', status: expect.any(String) }),
|
||||
expect.objectContaining({ name: 'tbank', status: expect.any(String) }),
|
||||
]),
|
||||
},
|
||||
meta: {
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
},
|
||||
})
|
||||
expect(body.data).not.toHaveProperty('data')
|
||||
expect(body.data).not.toHaveProperty('meta')
|
||||
})
|
||||
})
|
||||
@ -4,9 +4,37 @@ import { AppModule } from './app.module';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||
import { RequestLoggingMiddleware } from './common/middleware/request-logging.middleware';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import { DEV_JWT_SECRET, DEV_JWT_REFRESH_SECRET } from './config/configuration';
|
||||
|
||||
export type BackendRuntimeConfig = {
|
||||
nodeEnv: string;
|
||||
jwtSecret: string;
|
||||
jwtRefreshSecret: string;
|
||||
corsOrigins: string[];
|
||||
};
|
||||
|
||||
export function assertSafeProductionConfig(config: BackendRuntimeConfig): void {
|
||||
if (config.nodeEnv !== 'production') return;
|
||||
|
||||
if (!config.jwtSecret || config.jwtSecret === DEV_JWT_SECRET) {
|
||||
throw new Error('JWT_SECRET must be set to a non-default value in production');
|
||||
}
|
||||
|
||||
if (!config.jwtRefreshSecret || config.jwtRefreshSecret === DEV_JWT_REFRESH_SECRET) {
|
||||
throw new Error('JWT_REFRESH_SECRET must be set to a non-default value in production');
|
||||
}
|
||||
|
||||
if (config.corsOrigins.length === 0) {
|
||||
throw new Error('BACKEND_CORS_ORIGINS must contain at least one origin in production');
|
||||
}
|
||||
}
|
||||
|
||||
export function buildCorsOrigin(nodeEnv: string, corsOrigins: string[]): boolean | string[] {
|
||||
return nodeEnv === 'production' ? corsOrigins : true;
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
@ -18,10 +46,20 @@ async function bootstrap() {
|
||||
app.useGlobalInterceptors(new TransformInterceptor());
|
||||
app.use(cookieParser());
|
||||
|
||||
const reqLogMiddleware = new RequestLoggingMiddleware();
|
||||
app.use(reqLogMiddleware.use.bind(reqLogMiddleware));
|
||||
const configService = app.get(ConfigService);
|
||||
const runtimeConfig: BackendRuntimeConfig = {
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
jwtSecret: configService.get<string>('app.auth.jwtSecret', ''),
|
||||
jwtRefreshSecret: configService.get<string>('app.auth.jwtRefreshSecret', ''),
|
||||
corsOrigins: configService.get<string[]>('app.cors.origins', []),
|
||||
};
|
||||
|
||||
app.enableCors({ origin: true, credentials: true });
|
||||
assertSafeProductionConfig(runtimeConfig);
|
||||
|
||||
app.enableCors({
|
||||
origin: buildCorsOrigin(runtimeConfig.nodeEnv, runtimeConfig.corsOrigins),
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('MoexVibe API')
|
||||
@ -36,4 +74,7 @@ async function bootstrap() {
|
||||
console.log(`MoexVibe API running on http://localhost:${port}/api/v1`);
|
||||
console.log(`Swagger docs: http://localhost:${port}/api/docs`);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
void bootstrap();
|
||||
}
|
||||
|
||||
@ -41,13 +41,7 @@ export class AuthController {
|
||||
async register(@Body() dto: RegisterDto, @Res({ passthrough: true }) res: Response) {
|
||||
const result = await this.authService.register(dto);
|
||||
res.cookie(REFRESH_COOKIE, result.refreshToken, COOKIE_OPTIONS);
|
||||
return {
|
||||
data: {
|
||||
user: result.user,
|
||||
accessToken: result.accessToken,
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return { user: result.user, accessToken: result.accessToken };
|
||||
}
|
||||
|
||||
@Public()
|
||||
@ -57,13 +51,7 @@ export class AuthController {
|
||||
async login(@Body() dto: LoginDto, @Res({ passthrough: true }) res: Response) {
|
||||
const result = await this.authService.login(dto);
|
||||
res.cookie(REFRESH_COOKIE, result.refreshToken, COOKIE_OPTIONS);
|
||||
return {
|
||||
data: {
|
||||
user: result.user,
|
||||
accessToken: result.accessToken,
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return { user: result.user, accessToken: result.accessToken };
|
||||
}
|
||||
|
||||
@Public()
|
||||
@ -75,13 +63,7 @@ export class AuthController {
|
||||
const token = req.cookies?.[REFRESH_COOKIE];
|
||||
const result = await this.authService.refresh(token);
|
||||
res.cookie(REFRESH_COOKIE, result.refreshToken, COOKIE_OPTIONS);
|
||||
return {
|
||||
data: {
|
||||
user: result.user,
|
||||
accessToken: result.accessToken,
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return { user: result.user, accessToken: result.accessToken };
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@ -92,10 +74,7 @@ export class AuthController {
|
||||
async logout(@CurrentUser() user: JwtPayload, @Res({ passthrough: true }) res: Response) {
|
||||
await this.authService.logout(user.sub);
|
||||
res.clearCookie(REFRESH_COOKIE, { path: '/api/v1/auth' });
|
||||
return {
|
||||
data: { message: 'Logged out successfully' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return { message: 'Logged out successfully' };
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@ -103,11 +82,7 @@ export class AuthController {
|
||||
@ApiOperation({ summary: 'Get current user profile' })
|
||||
@ApiOkResponse({ type: AuthProfileResponseDto })
|
||||
async getProfile(@CurrentUser() user: JwtPayload) {
|
||||
const profile = await this.authService.getProfile(user.sub);
|
||||
return {
|
||||
data: profile,
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return this.authService.getProfile(user.sub);
|
||||
}
|
||||
|
||||
@Patch('me')
|
||||
@ -115,10 +90,6 @@ export class AuthController {
|
||||
@ApiOperation({ summary: 'Update current user profile' })
|
||||
@ApiOkResponse({ type: AuthProfileResponseDto })
|
||||
async updateProfile(@CurrentUser() user: JwtPayload, @Body() dto: UpdateProfileDto) {
|
||||
const profile = await this.authService.updateProfile(user.sub, dto);
|
||||
return {
|
||||
data: profile,
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
};
|
||||
return this.authService.updateProfile(user.sub, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,12 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
class AuthResponseMetaDto {
|
||||
@ApiProperty({ type: String, nullable: true })
|
||||
cachedAt!: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
fromCache!: boolean;
|
||||
}
|
||||
import { ApiResponseMeta } from '../../../common/dto/api-response.dto';
|
||||
|
||||
class AuthUserDto {
|
||||
@ApiProperty()
|
||||
@ -39,22 +32,22 @@ export class AuthTokenResponseDto {
|
||||
@ApiProperty({ type: AuthTokenDataDto })
|
||||
data!: AuthTokenDataDto;
|
||||
|
||||
@ApiProperty({ type: AuthResponseMetaDto })
|
||||
meta!: AuthResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class AuthProfileResponseDto {
|
||||
@ApiProperty({ type: AuthUserDto })
|
||||
data!: AuthUserDto;
|
||||
|
||||
@ApiProperty({ type: AuthResponseMetaDto })
|
||||
meta!: AuthResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class AuthLogoutResponseDto {
|
||||
@ApiProperty({ type: LogoutDataDto })
|
||||
data!: LogoutDataDto;
|
||||
|
||||
@ApiProperty({ type: AuthResponseMetaDto })
|
||||
meta!: AuthResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MoexClientModule } from '../moex-client/moex-client.module';
|
||||
import { BondsController } from './bonds.controller';
|
||||
import { BondsService } from './bonds.service';
|
||||
|
||||
@Module({
|
||||
imports: [MoexClientModule],
|
||||
controllers: [BondsController],
|
||||
providers: [BondsService],
|
||||
exports: [BondsService],
|
||||
|
||||
@ -1,16 +1,17 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
import { BondsService } from './bonds.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexHistoryClient } from '../moex-client/moex-history.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
|
||||
describe('BondsService', () => {
|
||||
let service: BondsService;
|
||||
let moexClient: Pick<MoexClientService, 'getBondData' | 'getBondMarketData'>;
|
||||
let moexMarketData: Pick<MoexMarketDataClient, 'getBondData' | 'getBondMarketData'>;
|
||||
let cache: Pick<CacheService, 'getOrFetch'>;
|
||||
|
||||
beforeEach(async () => {
|
||||
moexClient = {
|
||||
moexMarketData = {
|
||||
getBondData: vi.fn(),
|
||||
getBondMarketData: vi.fn(),
|
||||
};
|
||||
@ -25,7 +26,8 @@ describe('BondsService', () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
BondsService,
|
||||
{ provide: MoexClientService, useValue: moexClient },
|
||||
{ provide: MoexMarketDataClient, useValue: moexMarketData },
|
||||
{ provide: MoexHistoryClient, useValue: { getBondHistory: vi.fn() } },
|
||||
{ provide: CacheService, useValue: cache },
|
||||
],
|
||||
}).compile();
|
||||
@ -34,7 +36,7 @@ describe('BondsService', () => {
|
||||
});
|
||||
|
||||
it('returns normalized SU26238RMFS5 bond spec and market data without live MOEX dependency', async () => {
|
||||
vi.mocked(moexClient.getBondData).mockResolvedValue({
|
||||
vi.mocked(moexMarketData.getBondData).mockResolvedValue({
|
||||
secid: 'SU26238RMFS5',
|
||||
boardid: 'TQCB',
|
||||
shortName: 'ОФЗ 26238',
|
||||
@ -57,7 +59,7 @@ describe('BondsService', () => {
|
||||
bondSubType: 'fixed',
|
||||
listLevel: 1,
|
||||
});
|
||||
vi.mocked(moexClient.getBondMarketData).mockResolvedValue({
|
||||
vi.mocked(moexMarketData.getBondMarketData).mockResolvedValue({
|
||||
secid: 'SU26238RMFS5',
|
||||
bid: 72.9,
|
||||
offer: 73.1,
|
||||
@ -92,8 +94,8 @@ describe('BondsService', () => {
|
||||
expect.any(Function),
|
||||
'marketDataTtl',
|
||||
);
|
||||
expect(moexClient.getBondData).toHaveBeenCalledWith('SU26238RMFS5');
|
||||
expect(moexClient.getBondMarketData).toHaveBeenCalledWith('SU26238RMFS5');
|
||||
expect(moexMarketData.getBondData).toHaveBeenCalledWith('SU26238RMFS5');
|
||||
expect(moexMarketData.getBondMarketData).toHaveBeenCalledWith('SU26238RMFS5');
|
||||
expect(result).toMatchObject({
|
||||
data: {
|
||||
secid: 'SU26238RMFS5',
|
||||
@ -129,19 +131,17 @@ describe('BondsService', () => {
|
||||
volume: 10000,
|
||||
},
|
||||
},
|
||||
meta: {
|
||||
fromCache: false,
|
||||
cachedAt: '2026-06-15T00:00:00.000Z',
|
||||
},
|
||||
fromCache: false,
|
||||
cachedAt: '2026-06-15T00:00:00.000Z',
|
||||
});
|
||||
expect(result.data.marketData.updatedAt).toMatch(/T18:45:00$/);
|
||||
});
|
||||
|
||||
it('throws NotFoundException when bond data is missing', async () => {
|
||||
vi.mocked(moexClient.getBondData).mockResolvedValue(null);
|
||||
it('throws EntityNotFoundException when bond data is missing', async () => {
|
||||
vi.mocked(moexMarketData.getBondData).mockResolvedValue(null);
|
||||
|
||||
await expect(service.getBond('UNKNOWN')).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.getBond('UNKNOWN')).rejects.toBeInstanceOf(EntityNotFoundException);
|
||||
expect(cache.getOrFetch).toHaveBeenCalledTimes(1);
|
||||
expect(moexClient.getBondMarketData).not.toHaveBeenCalled();
|
||||
expect(moexMarketData.getBondMarketData).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,11 +1,15 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexHistoryClient } from '../moex-client/moex-history.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { ApiEnvelopePayload } from '../../common/dto/api-response.dto';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
|
||||
@Injectable()
|
||||
export class BondsService {
|
||||
constructor(
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexMarketData: MoexMarketDataClient,
|
||||
private readonly moexHistory: MoexHistoryClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
@ -17,23 +21,23 @@ export class BondsService {
|
||||
} = await this.cache.getOrFetch(
|
||||
'bond',
|
||||
[secid],
|
||||
() => this.moexClient.getBondData(secid),
|
||||
() => this.moexMarketData.getBondData(secid),
|
||||
'securityTtl',
|
||||
);
|
||||
|
||||
if (!bond) {
|
||||
throw new NotFoundException(`Bond ${secid} not found`);
|
||||
throw new EntityNotFoundException('Bond', secid);
|
||||
}
|
||||
|
||||
const { data: mkt } = await this.cache.getOrFetch(
|
||||
'marketdata',
|
||||
['bonds', secid],
|
||||
() => this.moexClient.getBondMarketData(secid),
|
||||
() => this.moexMarketData.getBondMarketData(secid),
|
||||
'marketDataTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: {
|
||||
return new ApiEnvelopePayload(
|
||||
{
|
||||
secid: bond.secid,
|
||||
isin: bond.isin,
|
||||
name: bond.shortName,
|
||||
@ -70,8 +74,9 @@ export class BondsService {
|
||||
: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
|
||||
async getMarketData(secid: string) {
|
||||
@ -82,16 +87,16 @@ export class BondsService {
|
||||
} = await this.cache.getOrFetch(
|
||||
'marketdata',
|
||||
['bonds', secid],
|
||||
() => this.moexClient.getBondMarketData(secid),
|
||||
() => this.moexMarketData.getBondMarketData(secid),
|
||||
'marketDataTtl',
|
||||
);
|
||||
|
||||
if (!mkt) {
|
||||
throw new NotFoundException(`Market data for bond ${secid} not found`);
|
||||
throw new EntityNotFoundException('MarketData', `bond ${secid}`);
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
return new ApiEnvelopePayload(
|
||||
{
|
||||
price: mkt.last ?? 0,
|
||||
yieldToMaturity: mkt.yield ?? null,
|
||||
duration: mkt.duration ?? null,
|
||||
@ -107,26 +112,28 @@ export class BondsService {
|
||||
? new Date().toISOString().split('T')[0] + 'T' + mkt.updateTime
|
||||
: new Date().toISOString(),
|
||||
},
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
|
||||
async getHistory(secid: string, from: string, till: string) {
|
||||
const { data, fromCache, cachedAt } = await this.cache.getOrFetch(
|
||||
'history',
|
||||
['bonds', secid, from, till],
|
||||
() => this.moexClient.getBondHistory(secid, from, till),
|
||||
() => this.moexHistory.getBondHistory(secid, from, till),
|
||||
'historyTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: data.map((h) => ({
|
||||
return new ApiEnvelopePayload(
|
||||
data.map((h) => ({
|
||||
date: h.tradeDate,
|
||||
closePrice: h.legalClosePrice ?? h.close ?? 0,
|
||||
yieldClose: h.yieldClose ?? null,
|
||||
duration: h.duration ?? null,
|
||||
})),
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
65
apps/backend/src/modules/cache/cache.service.spec.ts
vendored
Normal file
65
apps/backend/src/modules/cache/cache.service.spec.ts
vendored
Normal file
@ -0,0 +1,65 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { CacheService } from './cache.service';
|
||||
|
||||
describe('CacheService', () => {
|
||||
const configService = {
|
||||
get: vi.fn((_key: string, fallback?: unknown) => fallback),
|
||||
} as unknown as ConfigService;
|
||||
|
||||
const createCache = () => ({
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
});
|
||||
|
||||
it('stores data with cachedAt metadata on cache miss', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-06-25T10:00:00.000Z'));
|
||||
const cache = createCache();
|
||||
cache.get.mockResolvedValue(undefined);
|
||||
const service = new CacheService(cache as never, configService);
|
||||
|
||||
try {
|
||||
const result = await service.getOrFetch('prefix', ['a'], async () => ({ value: 1 }), 'ttlKey');
|
||||
|
||||
expect(result).toEqual({
|
||||
data: { value: 1 },
|
||||
fromCache: false,
|
||||
cachedAt: '2026-06-25T10:00:00.000Z',
|
||||
});
|
||||
expect(cache.set).toHaveBeenCalledWith(
|
||||
'prefix:a',
|
||||
{ data: { value: 1 }, cachedAt: '2026-06-25T10:00:00.000Z' },
|
||||
900,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns cachedAt metadata on cache hit', async () => {
|
||||
const cache = createCache();
|
||||
cache.get.mockResolvedValue({
|
||||
data: { value: 1 },
|
||||
cachedAt: '2026-06-25T10:00:00.000Z',
|
||||
});
|
||||
const service = new CacheService(cache as never, configService);
|
||||
|
||||
const result = await service.getOrFetch('prefix', ['a'], async () => ({ value: 2 }), 'ttlKey');
|
||||
|
||||
expect(result).toEqual({
|
||||
data: { value: 1 },
|
||||
fromCache: true,
|
||||
cachedAt: '2026-06-25T10:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('supports legacy raw cache values during rollout', async () => {
|
||||
const cache = createCache();
|
||||
cache.get.mockResolvedValue({ value: 1 });
|
||||
const service = new CacheService(cache as never, configService);
|
||||
|
||||
const result = await service.getOrFetch('prefix', ['a'], async () => ({ value: 2 }), 'ttlKey');
|
||||
|
||||
expect(result).toEqual({ data: { value: 1 }, fromCache: true, cachedAt: null });
|
||||
});
|
||||
});
|
||||
28
apps/backend/src/modules/cache/cache.service.ts
vendored
28
apps/backend/src/modules/cache/cache.service.ts
vendored
@ -3,6 +3,11 @@ import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||
import { Cache } from 'cache-manager';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
type CacheEntry<T> = {
|
||||
data: T;
|
||||
cachedAt: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class CacheService {
|
||||
constructor(
|
||||
@ -18,6 +23,16 @@ export class CacheService {
|
||||
await this.cacheManager.set(key, value, ttl);
|
||||
}
|
||||
|
||||
private isCacheEntry<T>(value: unknown): value is CacheEntry<T> {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'data' in value &&
|
||||
'cachedAt' in value &&
|
||||
typeof (value as { cachedAt?: unknown }).cachedAt === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
private buildKey(...parts: string[]): string {
|
||||
return parts.join(':');
|
||||
}
|
||||
@ -31,14 +46,19 @@ export class CacheService {
|
||||
const key = this.buildKey(keyPrefix, ...keyParts);
|
||||
const ttl = this.configService.get<number>(`app.cache.${ttlConfigKey}`, 900);
|
||||
|
||||
const cached = await this.get<T>(key);
|
||||
const cached = await this.get<CacheEntry<T> | T>(key);
|
||||
if (cached !== undefined) {
|
||||
return { data: cached, fromCache: true, cachedAt: null };
|
||||
if (this.isCacheEntry<T>(cached)) {
|
||||
return { data: cached.data, fromCache: true, cachedAt: cached.cachedAt };
|
||||
}
|
||||
|
||||
return { data: cached as T, fromCache: true, cachedAt: null };
|
||||
}
|
||||
|
||||
const data = await fetchFn();
|
||||
await this.set(key, data, ttl);
|
||||
const cachedAt = new Date().toISOString();
|
||||
await this.set(key, { data, cachedAt }, ttl);
|
||||
|
||||
return { data, fromCache: false, cachedAt: new Date().toISOString() };
|
||||
return { data, fromCache: false, cachedAt };
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MoexClientModule } from '../moex-client/moex-client.module';
|
||||
import { CandlesController } from './candles.controller';
|
||||
import { CandlesService } from './candles.service';
|
||||
|
||||
@Module({
|
||||
imports: [MoexClientModule],
|
||||
controllers: [CandlesController],
|
||||
providers: [CandlesService],
|
||||
exports: [CandlesService],
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { CandlesService } from './candles.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexCandlesClient } from '../moex-client/moex-candles.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { CandleInterval } from './dto/candles-query.dto';
|
||||
|
||||
describe('CandlesService', () => {
|
||||
let service: CandlesService;
|
||||
let moexClient: Pick<MoexClientService, 'getCandles'>;
|
||||
let moexCandles: Pick<MoexCandlesClient, 'getCandles'>;
|
||||
let cache: Pick<CacheService, 'getOrFetch'>;
|
||||
|
||||
beforeEach(async () => {
|
||||
moexClient = {
|
||||
moexCandles = {
|
||||
getCandles: vi.fn(),
|
||||
};
|
||||
cache = {
|
||||
@ -24,7 +24,7 @@ describe('CandlesService', () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
CandlesService,
|
||||
{ provide: MoexClientService, useValue: moexClient },
|
||||
{ provide: MoexCandlesClient, useValue: moexCandles },
|
||||
{ provide: CacheService, useValue: cache },
|
||||
],
|
||||
}).compile();
|
||||
@ -33,7 +33,7 @@ describe('CandlesService', () => {
|
||||
});
|
||||
|
||||
it('uses MOEX interval 24 for daily share candles and maps output envelope', async () => {
|
||||
vi.mocked(moexClient.getCandles).mockResolvedValue([
|
||||
vi.mocked(moexCandles.getCandles).mockResolvedValue([
|
||||
{
|
||||
open: 320,
|
||||
high: 325,
|
||||
@ -60,7 +60,7 @@ describe('CandlesService', () => {
|
||||
expect.any(Function),
|
||||
'candlesTtl',
|
||||
);
|
||||
expect(moexClient.getCandles).toHaveBeenCalledWith(
|
||||
expect(moexCandles.getCandles).toHaveBeenCalledWith(
|
||||
'stock',
|
||||
'shares',
|
||||
'SBER',
|
||||
@ -81,15 +81,13 @@ describe('CandlesService', () => {
|
||||
end: '2026-05-01 23:59:59',
|
||||
},
|
||||
],
|
||||
meta: {
|
||||
fromCache: false,
|
||||
cachedAt: '2026-06-15T00:00:00.000Z',
|
||||
},
|
||||
fromCache: false,
|
||||
cachedAt: '2026-06-15T00:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses MOEX interval 60 for hourly bond candles without live MOEX dependency', async () => {
|
||||
vi.mocked(moexClient.getCandles).mockResolvedValue([]);
|
||||
vi.mocked(moexCandles.getCandles).mockResolvedValue([]);
|
||||
|
||||
await service.getCandles(
|
||||
'bonds',
|
||||
@ -105,7 +103,7 @@ describe('CandlesService', () => {
|
||||
expect.any(Function),
|
||||
'candlesTtl',
|
||||
);
|
||||
expect(moexClient.getCandles).toHaveBeenCalledWith(
|
||||
expect(moexCandles.getCandles).toHaveBeenCalledWith(
|
||||
'stock',
|
||||
'bonds',
|
||||
'SU26238RMFS5',
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexCandlesClient } from '../moex-client/moex-candles.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { CandleInterval } from './dto/candles-query.dto';
|
||||
import { ApiEnvelopePayload } from '../../common/dto/api-response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class CandlesService {
|
||||
constructor(
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexCandles: MoexCandlesClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
@ -25,12 +26,12 @@ export class CandlesService {
|
||||
const { data, fromCache, cachedAt } = await this.cache.getOrFetch(
|
||||
'candles',
|
||||
[market, secid, String(moexInterval), from, till],
|
||||
() => this.moexClient.getCandles('stock', market, secid, moexInterval, from, till),
|
||||
() => this.moexCandles.getCandles('stock', market, secid, moexInterval, from, till),
|
||||
'candlesTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: data.map((c) => ({
|
||||
return new ApiEnvelopePayload(
|
||||
data.map((c) => ({
|
||||
open: c.open,
|
||||
high: c.high,
|
||||
low: c.low,
|
||||
@ -40,7 +41,8 @@ export class CandlesService {
|
||||
begin: c.begin,
|
||||
end: c.end,
|
||||
})),
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,15 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
class HealthCheckResultDto {
|
||||
@ApiProperty({ example: 'prisma' })
|
||||
name!: string;
|
||||
|
||||
@ApiProperty({ enum: ['ok', 'error'] })
|
||||
status!: 'ok' | 'error';
|
||||
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export class HealthResponseDto {
|
||||
@ApiProperty({ example: 'ok' })
|
||||
@ -9,4 +20,7 @@ export class HealthResponseDto {
|
||||
|
||||
@ApiProperty({ example: 12345 })
|
||||
uptime!: number;
|
||||
|
||||
@ApiProperty({ type: [HealthCheckResultDto] })
|
||||
checks!: HealthCheckResultDto[];
|
||||
}
|
||||
|
||||
@ -3,20 +3,19 @@ import { ApiTags, ApiOperation, ApiOkResponse, ApiExtraModels } from '@nestjs/sw
|
||||
import { ApiResponseMeta } from '../../common/dto/api-response.dto';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
import { HealthEnvelopeDto } from './dto/health-envelope.dto';
|
||||
import { HealthService } from './health.service';
|
||||
|
||||
@ApiTags('Health')
|
||||
@ApiExtraModels(ApiResponseMeta)
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@Get()
|
||||
@Public()
|
||||
@ApiOperation({ summary: 'Проверка состояния сервиса' })
|
||||
@ApiOkResponse({ type: HealthEnvelopeDto })
|
||||
check() {
|
||||
return {
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
uptime: process.uptime(),
|
||||
};
|
||||
async check() {
|
||||
return this.healthService.check();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
import { HealthService } from './health.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
|
||||
68
apps/backend/src/modules/health/health.service.spec.ts
Normal file
68
apps/backend/src/modules/health/health.service.spec.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { HealthService } from './health.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('HealthService', () => {
|
||||
let service: HealthService;
|
||||
const prisma = { $queryRaw: vi.fn() } as any;
|
||||
const config = {
|
||||
get: vi.fn((key: string, fallback?: unknown) => {
|
||||
const values: Record<string, unknown> = {
|
||||
'app.moex.baseUrl': 'https://iss.moex.test/iss',
|
||||
'app.tbank.token': 'token-1',
|
||||
};
|
||||
|
||||
return values[key] ?? fallback;
|
||||
}),
|
||||
} as unknown as ConfigService;
|
||||
const fetchMock = vi.fn();
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
fetchMock.mockResolvedValue({ ok: true, status: 200 });
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
HealthService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: ConfigService, useValue: config },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<HealthService>(HealthService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('returns ok when all dependencies are healthy', async () => {
|
||||
prisma.$queryRaw.mockResolvedValue([{ 1: 1 }]);
|
||||
|
||||
const result = await service.check();
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.checks).toHaveLength(3);
|
||||
expect(result.checks.find((c) => c.name === 'prisma')!.status).toBe('ok');
|
||||
});
|
||||
|
||||
it('returns degraded when prisma is down', async () => {
|
||||
prisma.$queryRaw.mockRejectedValue(new Error('connection refused'));
|
||||
|
||||
const result = await service.check();
|
||||
|
||||
expect(result.status).toBe('degraded');
|
||||
expect(result.checks.find((c) => c.name === 'prisma')!.status).toBe('error');
|
||||
});
|
||||
|
||||
it('includes timestamp and uptime', async () => {
|
||||
prisma.$queryRaw.mockResolvedValue([{ 1: 1 }]);
|
||||
|
||||
const result = await service.check();
|
||||
|
||||
expect(result.timestamp).toEqual(expect.any(String));
|
||||
expect(result.uptime).toEqual(expect.any(Number));
|
||||
});
|
||||
});
|
||||
72
apps/backend/src/modules/health/health.service.ts
Normal file
72
apps/backend/src/modules/health/health.service.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface HealthCheckResult {
|
||||
name: string;
|
||||
status: 'ok' | 'error';
|
||||
error?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class HealthService {
|
||||
private readonly logger = new Logger(HealthService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
async check(): Promise<{ status: string; timestamp: string; uptime: number; checks: HealthCheckResult[] }> {
|
||||
const checks = await Promise.all([
|
||||
this.checkPrisma(),
|
||||
this.checkMoex(),
|
||||
this.checkTBank(),
|
||||
]);
|
||||
|
||||
const allOk = checks.every((c) => c.status === 'ok');
|
||||
|
||||
return {
|
||||
status: allOk ? 'ok' : 'degraded',
|
||||
timestamp: new Date().toISOString(),
|
||||
uptime: process.uptime(),
|
||||
checks,
|
||||
};
|
||||
}
|
||||
|
||||
private async checkPrisma(): Promise<HealthCheckResult> {
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
return { name: 'prisma', status: 'ok' };
|
||||
} catch {
|
||||
return { name: 'prisma', status: 'error', error: 'Database unreachable' };
|
||||
}
|
||||
}
|
||||
|
||||
private async checkMoex(): Promise<HealthCheckResult> {
|
||||
try {
|
||||
const baseUrl = this.config.get<string>('app.moex.baseUrl', 'https://iss.moex.com/iss');
|
||||
const res = await fetch(`${baseUrl}/engines/stock/quotes.json?iss.meta=off&limit=1`, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
return { name: 'moex', status: 'error', error: `HTTP ${res.status}` };
|
||||
}
|
||||
return { name: 'moex', status: 'ok' };
|
||||
} catch (err) {
|
||||
return { name: 'moex', status: 'error', error: 'MOEX API unreachable' };
|
||||
}
|
||||
}
|
||||
|
||||
private async checkTBank(): Promise<HealthCheckResult> {
|
||||
try {
|
||||
const token = this.config.get<string>('app.tbank.token', '');
|
||||
if (!token) {
|
||||
return { name: 'tbank', status: 'error', error: 'Not configured' };
|
||||
}
|
||||
return { name: 'tbank', status: 'ok' };
|
||||
} catch {
|
||||
return { name: 'tbank', status: 'error', error: 'T-Bank API unreachable' };
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
import 'reflect-metadata';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexCandlesClient } from './moex-candles.client';
|
||||
|
||||
describe('MoexCandlesClient', () => {
|
||||
let client: MoexCandlesClient;
|
||||
let request: ReturnType<typeof vi.fn>;
|
||||
let extractTable: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
request = vi.fn();
|
||||
extractTable = vi.fn();
|
||||
client = new MoexCandlesClient({ request, extractTable } as unknown as MoexHttpClient);
|
||||
});
|
||||
|
||||
it('возвращает свечи для заданного инструмента', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValue([
|
||||
{ open: '320', close: '322', high: '323', low: '319', value: '100000', volume: '3000', begin: '2025-01-10 10:00:00', end: '2025-01-10 10:59:59' },
|
||||
]);
|
||||
|
||||
const result = await client.getCandles('stock', 'shares', 'SBER', 60, '2025-01-10', '2025-01-11');
|
||||
|
||||
expect(request).toHaveBeenCalledWith('/engines/stock/markets/shares/securities/SBER/candles', {
|
||||
interval: '60', from: '2025-01-10', till: '2025-01-11',
|
||||
});
|
||||
expect(result).toEqual([
|
||||
{ open: 320, close: 322, high: 323, low: 319, value: 100000, volume: 3000, begin: '2025-01-10 10:00:00', end: '2025-01-10 10:59:59' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
36
apps/backend/src/modules/moex-client/moex-candles.client.ts
Normal file
36
apps/backend/src/modules/moex-client/moex-candles.client.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexCandle } from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexCandlesClient {
|
||||
constructor(private readonly http: MoexHttpClient) {}
|
||||
|
||||
async getCandles(
|
||||
engine: 'stock',
|
||||
market: 'shares' | 'bonds',
|
||||
secid: string,
|
||||
interval: 1 | 10 | 60 | 24,
|
||||
from: string,
|
||||
till: string,
|
||||
): Promise<MoexCandle[]> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/${engine}/markets/${market}/securities/${secid}/candles`,
|
||||
{
|
||||
interval: String(interval),
|
||||
from,
|
||||
till,
|
||||
},
|
||||
);
|
||||
return this.http.extractTable(data, 'candles').map((c) => ({
|
||||
open: parseFloat(c.open as string),
|
||||
close: parseFloat(c.close as string),
|
||||
high: parseFloat(c.high as string),
|
||||
low: parseFloat(c.low as string),
|
||||
value: parseFloat(c.value as string),
|
||||
volume: parseInt(c.volume as string, 10),
|
||||
begin: c.begin as string,
|
||||
end: c.end as string,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,26 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { MoexClientService } from './moex-client.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexSecuritiesClient } from './moex-securities.client';
|
||||
import { MoexMarketDataClient } from './moex-market-data.client';
|
||||
import { MoexCandlesClient } from './moex-candles.client';
|
||||
import { MoexHistoryClient } from './moex-history.client';
|
||||
import { MoexDividendsClient } from './moex-dividends.client';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [MoexClientService],
|
||||
exports: [MoexClientService],
|
||||
providers: [
|
||||
MoexHttpClient,
|
||||
MoexSecuritiesClient,
|
||||
MoexMarketDataClient,
|
||||
MoexCandlesClient,
|
||||
MoexHistoryClient,
|
||||
MoexDividendsClient,
|
||||
],
|
||||
exports: [
|
||||
MoexSecuritiesClient,
|
||||
MoexMarketDataClient,
|
||||
MoexCandlesClient,
|
||||
MoexHistoryClient,
|
||||
MoexDividendsClient,
|
||||
],
|
||||
})
|
||||
export class MoexClientModule {}
|
||||
|
||||
@ -1,32 +1,35 @@
|
||||
import 'reflect-metadata';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { MoexClientService } from './moex-client.service';
|
||||
import { MoexClientModule } from './moex-client.module';
|
||||
import { MoexSecuritiesClient } from './moex-securities.client';
|
||||
import { MoexMarketDataClient } from './moex-market-data.client';
|
||||
import configuration from '../../config/configuration';
|
||||
|
||||
describe.skipIf(process.env.MOEX_LIVE_TESTS !== '1')(
|
||||
'MoexClientService live MOEX integration',
|
||||
'MoexClient live MOEX integration',
|
||||
() => {
|
||||
let service: MoexClientService;
|
||||
let moexSecurities: MoexSecuritiesClient;
|
||||
let moexMarketData: MoexMarketDataClient;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [ConfigModule.forRoot({ load: [configuration] })],
|
||||
providers: [MoexClientService],
|
||||
imports: [ConfigModule.forRoot({ load: [configuration] }), MoexClientModule],
|
||||
}).compile();
|
||||
|
||||
service = module.get<MoexClientService>(MoexClientService);
|
||||
moexSecurities = module.get<MoexSecuritiesClient>(MoexSecuritiesClient);
|
||||
moexMarketData = module.get<MoexMarketDataClient>(MoexMarketDataClient);
|
||||
});
|
||||
|
||||
it('возвращает результаты поиска для SBER из live MOEX', async () => {
|
||||
const results = await service.searchSecurities('SBER');
|
||||
const results = await moexSecurities.searchSecurities('SBER');
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results[0].secid).toBeDefined();
|
||||
}, 15000);
|
||||
|
||||
it('возвращает рыночные данные SBER из live MOEX', async () => {
|
||||
const data = await service.getShareMarketData('SBER');
|
||||
const data = await moexMarketData.getShareMarketData('SBER');
|
||||
|
||||
expect(data).toBeDefined();
|
||||
expect(data!.secid).toBe('SBER');
|
||||
|
||||
@ -1,186 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import axios from 'axios';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MoexClientService } from './moex-client.service';
|
||||
|
||||
vi.mock('axios', () => ({
|
||||
default: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('MoexClientService', () => {
|
||||
let service: MoexClientService;
|
||||
let getMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
getMock = vi.fn();
|
||||
vi.mocked(axios.create).mockReturnValue({ get: getMock } as never);
|
||||
|
||||
service = new MoexClientService({
|
||||
get: vi.fn((key: string, fallback?: unknown) => {
|
||||
const values: Record<string, unknown> = {
|
||||
'app.moex.baseUrl': 'https://iss.moex.test/iss',
|
||||
'app.moex.circuitBreakerThreshold': 5,
|
||||
'app.moex.circuitBreakerResetSeconds': 30,
|
||||
'app.moex.rateLimit': 10,
|
||||
};
|
||||
return values[key] ?? fallback;
|
||||
}),
|
||||
} as unknown as ConfigService);
|
||||
});
|
||||
|
||||
it('создаётся с настроенным MOEX client', () => {
|
||||
expect(service).toBeDefined();
|
||||
expect(axios.create).toHaveBeenCalledWith({
|
||||
baseURL: 'https://iss.moex.test/iss',
|
||||
timeout: 10000,
|
||||
paramsSerializer: { indexes: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('нормализует результаты поиска из ISS table format', async () => {
|
||||
getMock.mockResolvedValueOnce({
|
||||
data: {
|
||||
securities: {
|
||||
columns: [
|
||||
'secid',
|
||||
'isin',
|
||||
'name',
|
||||
'shortName',
|
||||
'latName',
|
||||
'listLevel',
|
||||
'issuesize',
|
||||
'facevalue',
|
||||
'faceunit',
|
||||
'issuedate',
|
||||
'typename',
|
||||
'group',
|
||||
'type',
|
||||
'isqualifiedinvestors',
|
||||
'morningsession',
|
||||
'eveningsession',
|
||||
],
|
||||
data: [
|
||||
[
|
||||
'SBER',
|
||||
'RU0009029540',
|
||||
'Сбербанк России ПАО ао',
|
||||
'Сбербанк',
|
||||
'Sberbank',
|
||||
'1',
|
||||
'21586948000',
|
||||
'3',
|
||||
'SUR',
|
||||
'2007-07-20',
|
||||
'Акция обыкновенная',
|
||||
'stock_shares',
|
||||
'common_share',
|
||||
'0',
|
||||
'1',
|
||||
'1',
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const results = await service.searchSecurities('SBER');
|
||||
|
||||
expect(getMock).toHaveBeenCalledWith('/securities.json', {
|
||||
params: { q: 'SBER', 'iss.meta': 'off' },
|
||||
});
|
||||
expect(results).toEqual([
|
||||
{
|
||||
secid: 'SBER',
|
||||
isin: 'RU0009029540',
|
||||
name: 'Сбербанк России ПАО ао',
|
||||
shortName: 'Сбербанк',
|
||||
latName: 'Sberbank',
|
||||
listLevel: 1,
|
||||
issueSize: 21586948000,
|
||||
faceValue: 3,
|
||||
faceUnit: 'SUR',
|
||||
issueDate: '2007-07-20',
|
||||
typeName: 'Акция обыкновенная',
|
||||
group: 'stock_shares',
|
||||
type: 'common_share',
|
||||
isQualifiedInvestors: false,
|
||||
morningSession: true,
|
||||
eveningSession: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('нормализует market data акции без live MOEX запроса', async () => {
|
||||
getMock.mockResolvedValueOnce({
|
||||
data: {
|
||||
securities: {
|
||||
columns: ['SECID', 'BOARDID', 'SHORTNAME', 'PREVPRICE'],
|
||||
data: [['SBER', 'TQBR', 'Сбербанк', '320.10']],
|
||||
},
|
||||
marketdata: {
|
||||
columns: [
|
||||
'SECID',
|
||||
'BOARDID',
|
||||
'BID',
|
||||
'OFFER',
|
||||
'OPEN',
|
||||
'LOW',
|
||||
'HIGH',
|
||||
'LAST',
|
||||
'LASTCHANGE',
|
||||
'LASTCHANGEPRCNT',
|
||||
'VOLTODAY',
|
||||
'VALTODAY',
|
||||
'WAPRICE',
|
||||
'NUMTRADES',
|
||||
'ISSUECAPITALIZATION',
|
||||
'TRADINGSTATUS',
|
||||
'UPDATETIME',
|
||||
],
|
||||
data: [
|
||||
[
|
||||
'SBER',
|
||||
'TQBR',
|
||||
'321',
|
||||
'322',
|
||||
'320',
|
||||
'319',
|
||||
'323',
|
||||
'322.35',
|
||||
'1.15',
|
||||
'0.36',
|
||||
'1925163',
|
||||
'620184479',
|
||||
'321.9',
|
||||
'12345',
|
||||
'6958336818320',
|
||||
'T',
|
||||
'10:30:00',
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const data = await service.getShareMarketData('SBER');
|
||||
|
||||
expect(getMock).toHaveBeenCalledWith('/engines/stock/markets/shares/securities/SBER.json', {
|
||||
params: { boards: 'TQBR', 'iss.meta': 'off' },
|
||||
});
|
||||
expect(data).toMatchObject({
|
||||
secid: 'SBER',
|
||||
boardid: 'TQBR',
|
||||
shortName: 'Сбербанк',
|
||||
last: 322.35,
|
||||
lastChange: 1.15,
|
||||
lastChangePrcnt: 0.36,
|
||||
volume: 1925163,
|
||||
value: 620184479,
|
||||
issueCapitalization: 6958336818320,
|
||||
tradingStatus: 'T',
|
||||
updateTime: '10:30:00',
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,423 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import PQueue from 'p-queue';
|
||||
import {
|
||||
MoexSecurityDescription,
|
||||
MoexShareMarketData,
|
||||
MoexBondData,
|
||||
MoexBondMarketData,
|
||||
MoexBondPositionData,
|
||||
MoexDividend,
|
||||
MoexCandle,
|
||||
MoexHistoryEntry,
|
||||
MoexBondHistoryEntry,
|
||||
} from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexClientService {
|
||||
private readonly logger = new Logger(MoexClientService.name);
|
||||
private readonly client: AxiosInstance;
|
||||
private readonly queue: PQueue;
|
||||
private circuitOpen = false;
|
||||
private circuitErrorCount = 0;
|
||||
private readonly threshold: number;
|
||||
private readonly resetMs: number;
|
||||
|
||||
constructor(private configService: ConfigService) {
|
||||
const baseUrl = this.configService.get<string>('app.moex.baseUrl')!;
|
||||
this.threshold = this.configService.get<number>('app.moex.circuitBreakerThreshold', 5);
|
||||
this.resetMs = this.configService.get<number>('app.moex.circuitBreakerResetSeconds', 30) * 1000;
|
||||
const rateLimit = this.configService.get<number>('app.moex.rateLimit', 10);
|
||||
|
||||
this.client = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 10000,
|
||||
paramsSerializer: { indexes: null },
|
||||
});
|
||||
|
||||
this.queue = new PQueue({
|
||||
interval: 1000,
|
||||
intervalCap: rateLimit,
|
||||
});
|
||||
}
|
||||
|
||||
private async request<T>(path: string, params?: Record<string, string>): Promise<T> {
|
||||
if (this.circuitOpen) {
|
||||
throw new Error('Circuit breaker is open — MOEX requests paused');
|
||||
}
|
||||
|
||||
return this.queue.add(async () => {
|
||||
try {
|
||||
const jsonPath = path + '.json';
|
||||
const response = await this.client.get(jsonPath, {
|
||||
params: { ...params, 'iss.meta': 'off' },
|
||||
});
|
||||
this.circuitErrorCount = 0;
|
||||
return response.data as T;
|
||||
} catch (error) {
|
||||
this.circuitErrorCount++;
|
||||
if (this.circuitErrorCount >= this.threshold) {
|
||||
this.circuitOpen = true;
|
||||
this.logger.warn(`Circuit breaker opened after ${this.threshold} errors`);
|
||||
setTimeout(() => {
|
||||
this.circuitOpen = false;
|
||||
this.circuitErrorCount = 0;
|
||||
this.logger.log('Circuit breaker reset');
|
||||
}, this.resetMs);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}) as Promise<T>;
|
||||
}
|
||||
|
||||
private extractTable(data: Record<string, unknown>, name: string): Record<string, unknown>[] {
|
||||
const table = data[name] as Record<string, unknown> | undefined;
|
||||
if (!table || !table.columns || !table.data) return [];
|
||||
const columns = table.columns as string[];
|
||||
const rows = table.data as unknown[][];
|
||||
return rows.map((row) => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
columns.forEach((col, i) => {
|
||||
obj[col] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
async searchSecurities(query: string): Promise<MoexSecurityDescription[]> {
|
||||
const data = await this.request<Record<string, unknown>>('/securities', {
|
||||
q: query,
|
||||
});
|
||||
return this.extractTable(data, 'securities').map((s) => ({
|
||||
secid: s.secid as string,
|
||||
isin: s.isin as string,
|
||||
name: s.name as string,
|
||||
shortName: s.shortName as string,
|
||||
latName: (s.latName as string) || null,
|
||||
listLevel: parseInt(s.listLevel as string, 10) || 0,
|
||||
issueSize: parseInt(s.issuesize as string, 10) || 0,
|
||||
faceValue: parseFloat(s.facevalue as string) || 0,
|
||||
faceUnit: (s.faceunit as string) || '',
|
||||
issueDate: (s.issuedate as string) || '',
|
||||
typeName: (s.typename as string) || '',
|
||||
group: (s.group as string) || '',
|
||||
type: (s.type as string) || '',
|
||||
isQualifiedInvestors: (s.isqualifiedinvestors as string) === '1',
|
||||
morningSession: (s.morningsession as string) === '1',
|
||||
eveningSession: (s.eveningsession as string) === '1',
|
||||
}));
|
||||
}
|
||||
|
||||
async getSecurityDescription(secid: string): Promise<MoexSecurityDescription | null> {
|
||||
const data = await this.request<Record<string, unknown>>(`/securities/${secid}`);
|
||||
const rows = this.extractTable(data, 'description');
|
||||
if (rows.length === 0) return null;
|
||||
const map = new Map(rows.map((r) => [r.name, r.value]));
|
||||
return {
|
||||
secid,
|
||||
isin: (map.get('ISIN') as string) || '',
|
||||
name: (map.get('NAME') as string) || '',
|
||||
shortName: (map.get('SHORTNAME') as string) || '',
|
||||
latName: (map.get('LATNAME') as string) || null,
|
||||
listLevel: parseInt((map.get('LISTLEVEL') as string) || '0', 10),
|
||||
issueSize: parseInt((map.get('ISSUESIZE') as string) || '0', 10),
|
||||
faceValue: parseFloat((map.get('FACEVALUE') as string) || '0'),
|
||||
faceUnit: (map.get('FACEUNIT') as string) || '',
|
||||
issueDate: (map.get('ISSUEDATE') as string) || '',
|
||||
typeName: (map.get('TYPENAME') as string) || '',
|
||||
group: (map.get('GROUP') as string) || '',
|
||||
type: (map.get('TYPE') as string) || '',
|
||||
isQualifiedInvestors: (map.get('ISQUALIFIEDINVESTORS') as string) === '1',
|
||||
morningSession: (map.get('MORNINGSESSION') as string) === '1',
|
||||
eveningSession: (map.get('EVENINGSESSION') as string) === '1',
|
||||
};
|
||||
}
|
||||
|
||||
async getShareMarketData(secid: string, boardId = 'TQBR'): Promise<MoexShareMarketData | null> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const rows = this.extractTable(data, 'securities');
|
||||
const share = rows.find((r) => r.BOARDID === boardId);
|
||||
if (!share) return null;
|
||||
|
||||
const mktRows = this.extractTable(data, 'marketdata');
|
||||
const mkt = mktRows.find((r) => r.BOARDID === boardId);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (share?.SHORTNAME as string) || '',
|
||||
bid: mkt ? parseFloat((mkt.BID as string) || '') : null,
|
||||
offer: mkt ? parseFloat((mkt.OFFER as string) || '') : null,
|
||||
open: mkt ? parseFloat((mkt.OPEN as string) || '') : null,
|
||||
low: mkt ? parseFloat((mkt.LOW as string) || '') : null,
|
||||
high: mkt ? parseFloat((mkt.HIGH as string) || '') : null,
|
||||
last: mkt
|
||||
? parseFloat((mkt.LAST as string) || '')
|
||||
: parseFloat((share.PREVPRICE as string) || ''),
|
||||
lastChange: mkt ? parseFloat((mkt.LASTCHANGE as string) || '') : null,
|
||||
lastChangePrcnt: mkt ? parseFloat((mkt.LASTCHANGEPRCNT as string) || '') : null,
|
||||
volume: mkt ? parseInt((mkt.VOLTODAY as string) || '0', 10) : 0,
|
||||
value: mkt ? parseFloat((mkt.VALTODAY as string) || '0') : 0,
|
||||
waprice: mkt ? parseFloat((mkt.WAPRICE as string) || '') : null,
|
||||
numtrades: mkt ? parseInt((mkt.NUMTRADES as string) || '0', 10) : 0,
|
||||
issueCapitalization: mkt ? parseFloat((mkt.ISSUECAPITALIZATION as string) || '') : null,
|
||||
tradingStatus: (mkt?.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt?.UPDATETIME as string) || '',
|
||||
};
|
||||
}
|
||||
|
||||
async getShareMarketDataBatch(
|
||||
secids: string[],
|
||||
boardId = 'TQBR',
|
||||
): Promise<MoexShareMarketData[]> {
|
||||
const params: Record<string, string> = { boards: boardId };
|
||||
if (secids.length > 0) {
|
||||
params.securities = secids.join(',');
|
||||
}
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities`,
|
||||
params,
|
||||
);
|
||||
const securities = this.extractTable(data, 'securities');
|
||||
const marketdata = this.extractTable(data, 'marketdata');
|
||||
|
||||
const secidSet = secids.length > 0 ? new Set(secids) : null;
|
||||
const filteredSecurities = secidSet
|
||||
? securities.filter((r) => secidSet.has(r.SECID as string))
|
||||
: securities;
|
||||
|
||||
return filteredSecurities.map((sec) => {
|
||||
const secid = sec.SECID as string;
|
||||
const mkt =
|
||||
marketdata.find((r) => r.SECID === secid && r.BOARDID === boardId) ||
|
||||
marketdata.find((r) => r.SECID === secid);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (sec?.SHORTNAME as string) || '',
|
||||
bid: mkt ? parseFloat((mkt.BID as string) || '') : null,
|
||||
offer: mkt ? parseFloat((mkt.OFFER as string) || '') : null,
|
||||
open: mkt ? parseFloat((mkt.OPEN as string) || '') : null,
|
||||
low: mkt ? parseFloat((mkt.LOW as string) || '') : null,
|
||||
high: mkt ? parseFloat((mkt.HIGH as string) || '') : null,
|
||||
last: mkt
|
||||
? parseFloat((mkt.LAST as string) || '')
|
||||
: parseFloat((sec?.PREVPRICE as string) || ''),
|
||||
lastChange: mkt ? parseFloat((mkt.LASTCHANGE as string) || '') : null,
|
||||
lastChangePrcnt: mkt ? parseFloat((mkt.LASTCHANGEPRCNT as string) || '') : null,
|
||||
volume: mkt ? parseInt((mkt.VOLTODAY as string) || '0', 10) : 0,
|
||||
value: mkt ? parseFloat((mkt.VALTODAY as string) || '0') : 0,
|
||||
waprice: mkt ? parseFloat((mkt.WAPRICE as string) || '') : null,
|
||||
numtrades: mkt ? parseInt((mkt.NUMTRADES as string) || '0', 10) : 0,
|
||||
issueCapitalization: mkt ? parseFloat((mkt.ISSUECAPITALIZATION as string) || '') : null,
|
||||
tradingStatus: (mkt?.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt?.UPDATETIME as string) || '',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async getBondPositionDataBatch(
|
||||
secids: string[],
|
||||
boardId = 'TQCB',
|
||||
): Promise<MoexBondPositionData[]> {
|
||||
const params: Record<string, string> = { boards: boardId };
|
||||
if (secids.length > 0) {
|
||||
params.securities = secids.join(',');
|
||||
}
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities`,
|
||||
params,
|
||||
);
|
||||
const securities = this.extractTable(data, 'securities');
|
||||
const marketdata = this.extractTable(data, 'marketdata');
|
||||
|
||||
const secidSet = secids.length > 0 ? new Set(secids) : null;
|
||||
const filteredSecurities = secidSet
|
||||
? securities.filter((r) => secidSet.has(r.SECID as string))
|
||||
: securities;
|
||||
|
||||
return filteredSecurities.map((bond) => {
|
||||
const secid = bond.SECID as string;
|
||||
const mkt =
|
||||
marketdata.find((r) => r.SECID === secid && r.BOARDID === boardId && r.LAST != null) ||
|
||||
marketdata.find((r) => r.SECID === secid && r.LAST != null) ||
|
||||
marketdata.find((r) => r.SECID === secid);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: (bond.BOARDID as string) || boardId,
|
||||
shortName: (bond?.SHORTNAME as string) || '',
|
||||
price: mkt?.LAST != null ? parseFloat(mkt.LAST as string) : null,
|
||||
yieldToMaturity: mkt?.YIELD != null ? parseFloat(mkt.YIELD as string) : null,
|
||||
duration: mkt?.DURATION != null ? parseFloat(mkt.DURATION as string) : null,
|
||||
couponValue: bond?.COUPONVALUE != null ? parseFloat(bond.COUPONVALUE as string) : null,
|
||||
couponPercent:
|
||||
bond?.COUPONPERCENT != null ? parseFloat(bond.COUPONPERCENT as string) : null,
|
||||
nextCouponDate: (bond?.NEXTCOUPON as string) || null,
|
||||
matDate: (bond?.MATDATE as string) || null,
|
||||
accruedInt: bond?.ACCRUEDINT != null ? parseFloat(bond.ACCRUEDINT as string) : null,
|
||||
faceValue: parseFloat((bond?.FACEVALUE as string) || '1000'),
|
||||
bid: mkt?.BID != null ? parseFloat(mkt.BID as string) : null,
|
||||
offer: mkt?.OFFER != null ? parseFloat(mkt.OFFER as string) : null,
|
||||
couponPeriod: parseInt((bond?.COUPONPERIOD as string) || '0', 10),
|
||||
bondType: (bond?.BONDTYPE as string) || null,
|
||||
offerDate: (bond?.OFFERDATE as string) || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async getBondData(secid: string, boardId = 'TQCB'): Promise<MoexBondData | null> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const rows = this.extractTable(data, 'securities');
|
||||
const bond =
|
||||
rows.find((r) => r.BOARDID === boardId && r.PREVWAPRICE != null) ||
|
||||
rows.find((r) => r.PREVWAPRICE != null) ||
|
||||
rows[0];
|
||||
if (!bond) return null;
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (bond.SHORTNAME as string) || '',
|
||||
prevWaprice: parseFloat((bond.PREVWAPRICE as string) || '') || null,
|
||||
yieldAtPrevWaprice: parseFloat((bond.YIELDATPREVWAPRICE as string) || '') || null,
|
||||
couponValue: bond.COUPONVALUE != null ? parseFloat(bond.COUPONVALUE as string) : null,
|
||||
nextCoupon: (bond.NEXTCOUPON as string) || null,
|
||||
accruedInt: bond.ACCRUEDINT != null ? parseFloat(bond.ACCRUEDINT as string) : null,
|
||||
prevPrice: parseFloat((bond.PREVPRICE as string) || '') || null,
|
||||
lotSize: parseInt((bond.LOTSIZE as string) || '1', 10),
|
||||
faceValue: parseFloat((bond.FACEVALUE as string) || '1000'),
|
||||
matDate: (bond.MATDATE as string) || '',
|
||||
couponPeriod: parseInt((bond.COUPONPERIOD as string) || '0', 10),
|
||||
issueSize: parseInt((bond.ISSUESIZE as string) || '0', 10),
|
||||
isin: (bond.ISIN as string) || '',
|
||||
couponPercent: bond.COUPONPERCENT != null ? parseFloat(bond.COUPONPERCENT as string) : null,
|
||||
offerDate: (bond.OFFERDATE as string) || null,
|
||||
buybackDate: (bond.BUYBACKDATE as string) || null,
|
||||
bondType: (bond.BONDTYPE as string) || '',
|
||||
bondSubType: (bond.BONDSUBTYPE as string) || '',
|
||||
listLevel: parseInt((bond.LISTLEVEL as string) || '0', 10),
|
||||
};
|
||||
}
|
||||
|
||||
async getBondMarketData(secid: string, boardId = 'TQCB'): Promise<MoexBondMarketData | null> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const mktRows = this.extractTable(data, 'marketdata');
|
||||
const mkt =
|
||||
mktRows.find((r) => r.BOARDID === boardId && r.LAST != null) ||
|
||||
mktRows.find((r) => r.LAST != null) ||
|
||||
mktRows.find((r) => r.SECID === secid);
|
||||
if (!mkt) return null;
|
||||
|
||||
return {
|
||||
secid,
|
||||
bid: mkt.BID != null ? parseFloat(mkt.BID as string) : null,
|
||||
offer: mkt.OFFER != null ? parseFloat(mkt.OFFER as string) : null,
|
||||
open: mkt.OPEN != null ? parseFloat(mkt.OPEN as string) : null,
|
||||
low: mkt.LOW != null ? parseFloat(mkt.LOW as string) : null,
|
||||
high: mkt.HIGH != null ? parseFloat(mkt.HIGH as string) : null,
|
||||
last: mkt.LAST != null ? parseFloat(mkt.LAST as string) : null,
|
||||
yield: mkt.YIELD != null ? parseFloat(mkt.YIELD as string) : null,
|
||||
waprice: mkt.WAPRICE != null ? parseFloat(mkt.WAPRICE as string) : null,
|
||||
yieldAtWaprice: mkt.YIELDATWAPRICE != null ? parseFloat(mkt.YIELDATWAPRICE as string) : null,
|
||||
duration: mkt.DURATION != null ? parseFloat(mkt.DURATION as string) : null,
|
||||
volume: parseInt((mkt.VOLTODAY as string) || '0', 10),
|
||||
value: parseFloat((mkt.VALTODAY as string) || '0'),
|
||||
numtrades: parseInt((mkt.NUMTRADES as string) || '0', 10),
|
||||
tradingStatus: (mkt.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt.UPDATETIME as string) || '',
|
||||
};
|
||||
}
|
||||
|
||||
async getDividends(secid: string): Promise<MoexDividend[]> {
|
||||
const data = await this.request<Record<string, unknown>>(`/securities/${secid}/dividends`);
|
||||
return this.extractTable(data, 'dividends').map((d) => ({
|
||||
secid: d.secid as string,
|
||||
isin: d.isin as string,
|
||||
registryCloseDate: d.registryclosedate as string,
|
||||
value: parseFloat(d.value as string),
|
||||
currencyId: (d.currencyid as string) || 'RUB',
|
||||
}));
|
||||
}
|
||||
|
||||
async getCandles(
|
||||
engine: 'stock',
|
||||
market: 'shares' | 'bonds',
|
||||
secid: string,
|
||||
interval: 1 | 10 | 60 | 24,
|
||||
from: string,
|
||||
till: string,
|
||||
): Promise<MoexCandle[]> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/${engine}/markets/${market}/securities/${secid}/candles`,
|
||||
{
|
||||
interval: String(interval),
|
||||
from,
|
||||
till,
|
||||
},
|
||||
);
|
||||
return this.extractTable(data, 'candles').map((c) => ({
|
||||
open: parseFloat(c.open as string),
|
||||
close: parseFloat(c.close as string),
|
||||
high: parseFloat(c.high as string),
|
||||
low: parseFloat(c.low as string),
|
||||
value: parseFloat(c.value as string),
|
||||
volume: parseInt(c.volume as string, 10),
|
||||
begin: c.begin as string,
|
||||
end: c.end as string,
|
||||
}));
|
||||
}
|
||||
|
||||
async getHistory(secid: string, from: string, till: string): Promise<MoexHistoryEntry[]> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities/${secid}`,
|
||||
{ from, till },
|
||||
);
|
||||
const tableName = Object.keys(data).find(
|
||||
(k) => k.startsWith('history') && !k.includes('cursor'),
|
||||
);
|
||||
if (!tableName) return [];
|
||||
return this.extractTable(data, tableName).map((h) => ({
|
||||
tradeDate: h.TRADEDATE as string,
|
||||
open: h.OPEN != null ? parseFloat(h.OPEN as string) : null,
|
||||
low: h.LOW != null ? parseFloat(h.LOW as string) : null,
|
||||
high: h.HIGH != null ? parseFloat(h.HIGH as string) : null,
|
||||
close: h.CLOSE != null ? parseFloat(h.CLOSE as string) : null,
|
||||
waprice: h.WAPRICE != null ? parseFloat(h.WAPRICE as string) : null,
|
||||
volume: parseInt((h.VOLUME as string) || '0', 10),
|
||||
value: parseFloat((h.VALUE as string) || '0'),
|
||||
numtrades: parseInt((h.NUMTRADES as string) || '0', 10),
|
||||
}));
|
||||
}
|
||||
|
||||
async getBondHistory(secid: string, from: string, till: string): Promise<MoexBondHistoryEntry[]> {
|
||||
const data = await this.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ from, till },
|
||||
);
|
||||
const tableName = Object.keys(data).find(
|
||||
(k) => k.startsWith('history') && !k.includes('cursor'),
|
||||
);
|
||||
if (!tableName) return [];
|
||||
return this.extractTable(data, tableName).map((h) => ({
|
||||
tradeDate: h.TRADEDATE as string,
|
||||
close: h.CLOSE != null ? parseFloat(h.CLOSE as string) : null,
|
||||
legalClosePrice: h.LEGALCLOSEPRICE != null ? parseFloat(h.LEGALCLOSEPRICE as string) : null,
|
||||
waprice: h.WAPRICE != null ? parseFloat(h.WAPRICE as string) : null,
|
||||
yieldClose: h.YIELDCLOSE != null ? parseFloat(h.YIELDCLOSE as string) : null,
|
||||
duration: h.DURATION != null ? parseFloat(h.DURATION as string) : null,
|
||||
accruedInt: h.ACCINT != null ? parseFloat(h.ACCINT as string) : null,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
import 'reflect-metadata';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexDividendsClient } from './moex-dividends.client';
|
||||
|
||||
describe('MoexDividendsClient', () => {
|
||||
let client: MoexDividendsClient;
|
||||
let request: ReturnType<typeof vi.fn>;
|
||||
let extractTable: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
request = vi.fn();
|
||||
extractTable = vi.fn();
|
||||
client = new MoexDividendsClient({ request, extractTable } as unknown as MoexHttpClient);
|
||||
});
|
||||
|
||||
it('возвращает дивиденды для бумаги', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValue([
|
||||
{ secid: 'SBER', isin: 'RU0009029540', registryclosedate: '2025-07-10', value: '33.3', currencyid: 'RUB' },
|
||||
]);
|
||||
|
||||
const result = await client.getDividends('SBER');
|
||||
|
||||
expect(request).toHaveBeenCalledWith('/securities/SBER/dividends');
|
||||
expect(result).toEqual([
|
||||
{ secid: 'SBER', isin: 'RU0009029540', registryCloseDate: '2025-07-10', value: 33.3, currencyId: 'RUB' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexDividend } from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexDividendsClient {
|
||||
constructor(private readonly http: MoexHttpClient) {}
|
||||
|
||||
async getDividends(secid: string): Promise<MoexDividend[]> {
|
||||
const data = await this.http.request<Record<string, unknown>>(`/securities/${secid}/dividends`);
|
||||
return this.http.extractTable(data, 'dividends').map((d) => ({
|
||||
secid: d.secid as string,
|
||||
isin: d.isin as string,
|
||||
registryCloseDate: d.registryclosedate as string,
|
||||
value: parseFloat(d.value as string),
|
||||
currencyId: (d.currencyid as string) || 'RUB',
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
import 'reflect-metadata';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexHistoryClient } from './moex-history.client';
|
||||
|
||||
describe('MoexHistoryClient', () => {
|
||||
let client: MoexHistoryClient;
|
||||
let request: ReturnType<typeof vi.fn>;
|
||||
let extractTable: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
request = vi.fn();
|
||||
extractTable = vi.fn();
|
||||
client = new MoexHistoryClient({ request, extractTable } as unknown as MoexHttpClient);
|
||||
});
|
||||
|
||||
describe('getHistory', () => {
|
||||
it('возвращает историю торгов для акции', async () => {
|
||||
request.mockResolvedValue({ history: { columns: ['TRADEDATE', 'CLOSE'], data: [['2025-01-10', '322']] } });
|
||||
extractTable.mockReturnValue([{ TRADEDATE: '2025-01-10', CLOSE: '322' }]);
|
||||
|
||||
const result = await client.getHistory('SBER', '2025-01-10', '2025-01-11');
|
||||
|
||||
expect(request).toHaveBeenCalledWith('/engines/stock/markets/shares/securities/SBER', { from: '2025-01-10', till: '2025-01-11' });
|
||||
expect(result).toEqual([
|
||||
{ tradeDate: '2025-01-10', open: null, low: null, high: null, close: 322, waprice: null, volume: 0, value: 0, numtrades: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('возвращает пустой массив если history таблица не найдена', async () => {
|
||||
request.mockResolvedValue({});
|
||||
|
||||
const result = await client.getHistory('SBER', '2025-01-10', '2025-01-11');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBondHistory', () => {
|
||||
it('возвращает историю торгов для облигации', async () => {
|
||||
request.mockResolvedValue({ 'history:': { columns: ['TRADEDATE', 'CLOSE'], data: [['2025-01-10', '98.5']] } });
|
||||
extractTable.mockReturnValue([{ TRADEDATE: '2025-01-10', CLOSE: '98.5' }]);
|
||||
|
||||
const result = await client.getBondHistory('SU26238RMFS4', '2025-01-10', '2025-01-11');
|
||||
|
||||
expect(result).toEqual([
|
||||
{ tradeDate: '2025-01-10', close: 98.5, legalClosePrice: null, waprice: null, yieldClose: null, duration: null, accruedInt: null },
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
50
apps/backend/src/modules/moex-client/moex-history.client.ts
Normal file
50
apps/backend/src/modules/moex-client/moex-history.client.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexHistoryEntry, MoexBondHistoryEntry } from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexHistoryClient {
|
||||
constructor(private readonly http: MoexHttpClient) {}
|
||||
|
||||
async getHistory(secid: string, from: string, till: string): Promise<MoexHistoryEntry[]> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities/${secid}`,
|
||||
{ from, till },
|
||||
);
|
||||
const tableName = Object.keys(data).find(
|
||||
(k) => k.startsWith('history') && !k.includes('cursor'),
|
||||
);
|
||||
if (!tableName) return [];
|
||||
return this.http.extractTable(data, tableName).map((h) => ({
|
||||
tradeDate: h.TRADEDATE as string,
|
||||
open: h.OPEN != null ? parseFloat(h.OPEN as string) : null,
|
||||
low: h.LOW != null ? parseFloat(h.LOW as string) : null,
|
||||
high: h.HIGH != null ? parseFloat(h.HIGH as string) : null,
|
||||
close: h.CLOSE != null ? parseFloat(h.CLOSE as string) : null,
|
||||
waprice: h.WAPRICE != null ? parseFloat(h.WAPRICE as string) : null,
|
||||
volume: parseInt((h.VOLUME as string) || '0', 10),
|
||||
value: parseFloat((h.VALUE as string) || '0'),
|
||||
numtrades: parseInt((h.NUMTRADES as string) || '0', 10),
|
||||
}));
|
||||
}
|
||||
|
||||
async getBondHistory(secid: string, from: string, till: string): Promise<MoexBondHistoryEntry[]> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ from, till },
|
||||
);
|
||||
const tableName = Object.keys(data).find(
|
||||
(k) => k.startsWith('history') && !k.includes('cursor'),
|
||||
);
|
||||
if (!tableName) return [];
|
||||
return this.http.extractTable(data, tableName).map((h) => ({
|
||||
tradeDate: h.TRADEDATE as string,
|
||||
close: h.CLOSE != null ? parseFloat(h.CLOSE as string) : null,
|
||||
legalClosePrice: h.LEGALCLOSEPRICE != null ? parseFloat(h.LEGALCLOSEPRICE as string) : null,
|
||||
waprice: h.WAPRICE != null ? parseFloat(h.WAPRICE as string) : null,
|
||||
yieldClose: h.YIELDCLOSE != null ? parseFloat(h.YIELDCLOSE as string) : null,
|
||||
duration: h.DURATION != null ? parseFloat(h.DURATION as string) : null,
|
||||
accruedInt: h.ACCINT != null ? parseFloat(h.ACCINT as string) : null,
|
||||
}));
|
||||
}
|
||||
}
|
||||
132
apps/backend/src/modules/moex-client/moex-http.client.spec.ts
Normal file
132
apps/backend/src/modules/moex-client/moex-http.client.spec.ts
Normal file
@ -0,0 +1,132 @@
|
||||
import 'reflect-metadata';
|
||||
import axios from 'axios';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
|
||||
vi.mock('axios', () => ({
|
||||
default: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('MoexHttpClient', () => {
|
||||
let client: MoexHttpClient;
|
||||
let getMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
const mockConfig = {
|
||||
get: vi.fn((key: string, fallback?: unknown) => {
|
||||
const values: Record<string, unknown> = {
|
||||
'app.moex.baseUrl': 'https://iss.moex.test/iss',
|
||||
'app.moex.circuitBreakerThreshold': 5,
|
||||
'app.moex.circuitBreakerResetSeconds': 30,
|
||||
'app.moex.rateLimit': 10,
|
||||
};
|
||||
return values[key] ?? fallback;
|
||||
}),
|
||||
} as unknown as ConfigService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
getMock = vi.fn();
|
||||
vi.mocked(axios.create).mockReturnValue({ get: getMock } as never);
|
||||
client = new MoexHttpClient(mockConfig);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('создаёт axios instance с параметрами из конфига', () => {
|
||||
expect(axios.create).toHaveBeenCalledWith({
|
||||
baseURL: 'https://iss.moex.test/iss',
|
||||
timeout: 10000,
|
||||
paramsSerializer: { indexes: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('request', () => {
|
||||
it('выполняет GET запрос с .json суффиксом и iss.meta=off', async () => {
|
||||
getMock.mockResolvedValueOnce({ data: { some: 'data' } });
|
||||
|
||||
const result = await client.request<{ some: string }>('/securities', { q: 'SBER' });
|
||||
|
||||
expect(getMock).toHaveBeenCalledWith('/securities.json', {
|
||||
params: { q: 'SBER', 'iss.meta': 'off' },
|
||||
});
|
||||
expect(result).toEqual({ some: 'data' });
|
||||
});
|
||||
|
||||
it('открывает circuit breaker после заданного числа ошибок', async () => {
|
||||
getMock.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await expect(client.request('/test')).rejects.toThrow();
|
||||
}
|
||||
|
||||
await expect(client.request('/test')).rejects.toThrow('Circuit breaker is open');
|
||||
expect(getMock).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it('закрывает circuit breaker после resetMs', async () => {
|
||||
getMock.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await expect(client.request('/test')).rejects.toThrow();
|
||||
}
|
||||
|
||||
await expect(client.request('/test')).rejects.toThrow('Circuit breaker is open');
|
||||
|
||||
vi.advanceTimersByTime(30000);
|
||||
|
||||
getMock.mockResolvedValue({ data: 'ok' });
|
||||
const result = await client.request('/test');
|
||||
expect(result).toBe('ok');
|
||||
});
|
||||
|
||||
it('сбрасывает errorCount при успешном запросе', async () => {
|
||||
getMock
|
||||
.mockRejectedValueOnce(new Error('fail'))
|
||||
.mockRejectedValueOnce(new Error('fail'))
|
||||
.mockResolvedValueOnce({ data: 'ok' });
|
||||
|
||||
await expect(client.request('/test')).rejects.toThrow('fail');
|
||||
await expect(client.request('/test')).rejects.toThrow('fail');
|
||||
const result = await client.request('/test');
|
||||
expect(result).toBe('ok');
|
||||
expect(getMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractTable', () => {
|
||||
it('преобразует ISS columns/data формат в массив объектов', () => {
|
||||
const data = {
|
||||
securities: {
|
||||
columns: ['secid', 'name'],
|
||||
data: [
|
||||
['SBER', 'Сбербанк'],
|
||||
['VTBR', 'ВТБ'],
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = client.extractTable(data as Record<string, unknown>, 'securities');
|
||||
|
||||
expect(result).toEqual([
|
||||
{ secid: 'SBER', name: 'Сбербанк' },
|
||||
{ secid: 'VTBR', name: 'ВТБ' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('возвращает пустой массив если таблица не найдена', () => {
|
||||
const result = client.extractTable({}, 'nonexistent');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('возвращает пустой массив если нет columns', () => {
|
||||
const result = client.extractTable({ securities: { data: [] } } as unknown as Record<string, unknown>, 'securities');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
76
apps/backend/src/modules/moex-client/moex-http.client.ts
Normal file
76
apps/backend/src/modules/moex-client/moex-http.client.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import PQueue from 'p-queue';
|
||||
|
||||
@Injectable()
|
||||
export class MoexHttpClient {
|
||||
private readonly logger = new Logger(MoexHttpClient.name);
|
||||
private readonly client: AxiosInstance;
|
||||
private readonly queue: PQueue;
|
||||
private circuitOpen = false;
|
||||
private circuitErrorCount = 0;
|
||||
private readonly threshold: number;
|
||||
private readonly resetMs: number;
|
||||
|
||||
constructor(private configService: ConfigService) {
|
||||
const baseUrl = this.configService.get<string>('app.moex.baseUrl')!;
|
||||
this.threshold = this.configService.get<number>('app.moex.circuitBreakerThreshold', 5);
|
||||
this.resetMs = this.configService.get<number>('app.moex.circuitBreakerResetSeconds', 30) * 1000;
|
||||
const rateLimit = this.configService.get<number>('app.moex.rateLimit', 10);
|
||||
|
||||
this.client = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 10000,
|
||||
paramsSerializer: { indexes: null },
|
||||
});
|
||||
|
||||
this.queue = new PQueue({
|
||||
interval: 1000,
|
||||
intervalCap: rateLimit,
|
||||
});
|
||||
}
|
||||
|
||||
async request<T>(path: string, params?: Record<string, string>): Promise<T> {
|
||||
if (this.circuitOpen) {
|
||||
throw new Error('Circuit breaker is open — MOEX requests paused');
|
||||
}
|
||||
|
||||
return this.queue.add(async () => {
|
||||
try {
|
||||
const jsonPath = path + '.json';
|
||||
const response = await this.client.get(jsonPath, {
|
||||
params: { ...params, 'iss.meta': 'off' },
|
||||
});
|
||||
this.circuitErrorCount = 0;
|
||||
return response.data as T;
|
||||
} catch (error) {
|
||||
this.circuitErrorCount++;
|
||||
if (this.circuitErrorCount >= this.threshold) {
|
||||
this.circuitOpen = true;
|
||||
this.logger.warn(`Circuit breaker opened after ${this.threshold} errors`);
|
||||
setTimeout(() => {
|
||||
this.circuitOpen = false;
|
||||
this.circuitErrorCount = 0;
|
||||
this.logger.log('Circuit breaker reset');
|
||||
}, this.resetMs);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}) as Promise<T>;
|
||||
}
|
||||
|
||||
extractTable(data: Record<string, unknown>, name: string): Record<string, unknown>[] {
|
||||
const table = data[name] as Record<string, unknown> | undefined;
|
||||
if (!table || !table.columns || !table.data) return [];
|
||||
const columns = table.columns as string[];
|
||||
const rows = table.data as unknown[][];
|
||||
return rows.map((row) => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
columns.forEach((col, i) => {
|
||||
obj[col] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,118 @@
|
||||
import 'reflect-metadata';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexMarketDataClient } from './moex-market-data.client';
|
||||
|
||||
describe('MoexMarketDataClient', () => {
|
||||
let client: MoexMarketDataClient;
|
||||
let request: ReturnType<typeof vi.fn>;
|
||||
let extractTable: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
request = vi.fn();
|
||||
extractTable = vi.fn();
|
||||
client = new MoexMarketDataClient({ request, extractTable } as unknown as MoexHttpClient);
|
||||
});
|
||||
|
||||
describe('getShareMarketData', () => {
|
||||
it('возвращает рыночные данные акции из securities и marketdata таблиц', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable
|
||||
.mockReturnValueOnce([{ SECID: 'SBER', BOARDID: 'TQBR', SHORTNAME: 'Сбербанк', PREVPRICE: '320' }])
|
||||
.mockReturnValueOnce([{ SECID: 'SBER', BOARDID: 'TQBR', BID: '321', OFFER: '322', OPEN: '320', LOW: '319', HIGH: '323', LAST: '322.35', LASTCHANGE: '1.15', LASTCHANGEPRCNT: '0.36', VOLTODAY: '1925163', VALTODAY: '620184479', WAPRICE: '321.9', NUMTRADES: '12345', ISSUECAPITALIZATION: '6958336818320', TRADINGSTATUS: 'T', UPDATETIME: '10:30:00' }]);
|
||||
|
||||
const result = await client.getShareMarketData('SBER');
|
||||
|
||||
expect(request).toHaveBeenCalledWith('/engines/stock/markets/shares/securities/SBER', { boards: 'TQBR' });
|
||||
expect(result).toMatchObject({ secid: 'SBER', boardid: 'TQBR', shortName: 'Сбербанк', last: 322.35, bid: 321, offer: 322 });
|
||||
});
|
||||
|
||||
it('возвращает null если бумага не найдена', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValueOnce([]).mockReturnValueOnce([]);
|
||||
|
||||
const result = await client.getShareMarketData('INVALID');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getShareMarketDataBatch', () => {
|
||||
it('возвращает массив рыночных данных для нескольких бумаг', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable
|
||||
.mockReturnValueOnce([
|
||||
{ SECID: 'SBER', BOARDID: 'TQBR', SHORTNAME: 'Сбербанк', PREVPRICE: '320' },
|
||||
{ SECID: 'VTBR', BOARDID: 'TQBR', SHORTNAME: 'ВТБ', PREVPRICE: '50' },
|
||||
])
|
||||
.mockReturnValueOnce([
|
||||
{ SECID: 'SBER', BOARDID: 'TQBR', LAST: '322', BID: '321', OFFER: '323' },
|
||||
{ SECID: 'VTBR', BOARDID: 'TQBR', LAST: '50.5', BID: '50.1', OFFER: '50.8' },
|
||||
]);
|
||||
|
||||
const results = await client.getShareMarketDataBatch(['SBER', 'VTBR']);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].secid).toBe('SBER');
|
||||
expect(results[1].secid).toBe('VTBR');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBondData', () => {
|
||||
it('возвращает данные облигации из securities таблицы', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValueOnce([
|
||||
{ SECID: 'SU26238RMFS4', BOARDID: 'TQCB', SHORTNAME: 'ОФЗ 26238', PREVWAPRICE: '98.5', COUPONVALUE: '34.5', NEXTCOUPON: '2025-01-15', MATDATE: '2041-05-15', FACEVALUE: '1000', ISIN: 'RU000A1038T7' },
|
||||
]);
|
||||
|
||||
const result = await client.getBondData('SU26238RMFS4');
|
||||
|
||||
expect(request).toHaveBeenCalledWith('/engines/stock/markets/bonds/securities/SU26238RMFS4', { boards: 'TQCB' });
|
||||
expect(result).toMatchObject({ secid: 'SU26238RMFS4', shortName: 'ОФЗ 26238' });
|
||||
});
|
||||
|
||||
it('возвращает null если облигация не найдена', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValueOnce([]);
|
||||
|
||||
const result = await client.getBondData('INVALID');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBondMarketData', () => {
|
||||
it('возвращает рыночные данные облигации из marketdata таблицы', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValueOnce([{ SECID: 'SU26238RMFS4', BOARDID: 'TQCB', LAST: '98.5', BID: '98', OFFER: '99', YIELD: '7.5', DURATION: '1500', VOLTODAY: '1000', VALTODAY: '98500', NUMTRADES: '50', TRADINGSTATUS: 'T', UPDATETIME: '10:30:00' }]);
|
||||
|
||||
const result = await client.getBondMarketData('SU26238RMFS4');
|
||||
|
||||
expect(result).toMatchObject({ secid: 'SU26238RMFS4', last: 98.5, bid: 98, offer: 99, yield: 7.5 });
|
||||
});
|
||||
|
||||
it('возвращает null если marketdata не найдена', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable.mockReturnValueOnce([]);
|
||||
|
||||
const result = await client.getBondMarketData('INVALID');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBondPositionDataBatch', () => {
|
||||
it('возвращает массив позиций по облигациям', async () => {
|
||||
request.mockResolvedValue({});
|
||||
extractTable
|
||||
.mockReturnValueOnce([
|
||||
{ SECID: 'SU26238RMFS4', BOARDID: 'TQCB', SHORTNAME: 'ОФЗ 26238', COUPONVALUE: '34.5', COUPONPERCENT: '7', NEXTCOUPON: '2025-01-15', MATDATE: '2041-05-15', FACEVALUE: '1000', ISIN: 'RU000A1038T7' },
|
||||
])
|
||||
.mockReturnValueOnce([
|
||||
{ SECID: 'SU26238RMFS4', BOARDID: 'TQCB', LAST: '98.5', YIELD: '7.5', DURATION: '1500', BID: '98', OFFER: '99' },
|
||||
]);
|
||||
|
||||
const results = await client.getBondPositionDataBatch(['SU26238RMFS4']);
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].secid).toBe('SU26238RMFS4');
|
||||
expect(results[0].price).toBe(98.5);
|
||||
});
|
||||
});
|
||||
});
|
||||
219
apps/backend/src/modules/moex-client/moex-market-data.client.ts
Normal file
219
apps/backend/src/modules/moex-client/moex-market-data.client.ts
Normal file
@ -0,0 +1,219 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import {
|
||||
MoexShareMarketData,
|
||||
MoexBondData,
|
||||
MoexBondMarketData,
|
||||
MoexBondPositionData,
|
||||
} from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexMarketDataClient {
|
||||
constructor(private readonly http: MoexHttpClient) {}
|
||||
|
||||
async getShareMarketData(secid: string, boardId = 'TQBR'): Promise<MoexShareMarketData | null> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const rows = this.http.extractTable(data, 'securities');
|
||||
const share = rows.find((r) => r.BOARDID === boardId);
|
||||
if (!share) return null;
|
||||
|
||||
const mktRows = this.http.extractTable(data, 'marketdata');
|
||||
const mkt = mktRows.find((r) => r.BOARDID === boardId);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (share?.SHORTNAME as string) || '',
|
||||
bid: mkt ? parseFloat((mkt.BID as string) || '') : null,
|
||||
offer: mkt ? parseFloat((mkt.OFFER as string) || '') : null,
|
||||
open: mkt ? parseFloat((mkt.OPEN as string) || '') : null,
|
||||
low: mkt ? parseFloat((mkt.LOW as string) || '') : null,
|
||||
high: mkt ? parseFloat((mkt.HIGH as string) || '') : null,
|
||||
last: mkt
|
||||
? parseFloat((mkt.LAST as string) || '')
|
||||
: parseFloat((share.PREVPRICE as string) || ''),
|
||||
lastChange: mkt ? parseFloat((mkt.LASTCHANGE as string) || '') : null,
|
||||
lastChangePrcnt: mkt ? parseFloat((mkt.LASTCHANGEPRCNT as string) || '') : null,
|
||||
volume: mkt ? parseInt((mkt.VOLTODAY as string) || '0', 10) : 0,
|
||||
value: mkt ? parseFloat((mkt.VALTODAY as string) || '0') : 0,
|
||||
waprice: mkt ? parseFloat((mkt.WAPRICE as string) || '') : null,
|
||||
numtrades: mkt ? parseInt((mkt.NUMTRADES as string) || '0', 10) : 0,
|
||||
issueCapitalization: mkt ? parseFloat((mkt.ISSUECAPITALIZATION as string) || '') : null,
|
||||
tradingStatus: (mkt?.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt?.UPDATETIME as string) || '',
|
||||
};
|
||||
}
|
||||
|
||||
async getShareMarketDataBatch(
|
||||
secids: string[],
|
||||
boardId = 'TQBR',
|
||||
): Promise<MoexShareMarketData[]> {
|
||||
const params: Record<string, string> = { boards: boardId };
|
||||
if (secids.length > 0) {
|
||||
params.securities = secids.join(',');
|
||||
}
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/shares/securities`,
|
||||
params,
|
||||
);
|
||||
const securities = this.http.extractTable(data, 'securities');
|
||||
const marketdata = this.http.extractTable(data, 'marketdata');
|
||||
|
||||
const secidSet = secids.length > 0 ? new Set(secids) : null;
|
||||
const filteredSecurities = secidSet
|
||||
? securities.filter((r) => secidSet.has(r.SECID as string))
|
||||
: securities;
|
||||
|
||||
return filteredSecurities.map((sec) => {
|
||||
const secid = sec.SECID as string;
|
||||
const mkt =
|
||||
marketdata.find((r) => r.SECID === secid && r.BOARDID === boardId) ||
|
||||
marketdata.find((r) => r.SECID === secid);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (sec?.SHORTNAME as string) || '',
|
||||
bid: mkt ? parseFloat((mkt.BID as string) || '') : null,
|
||||
offer: mkt ? parseFloat((mkt.OFFER as string) || '') : null,
|
||||
open: mkt ? parseFloat((mkt.OPEN as string) || '') : null,
|
||||
low: mkt ? parseFloat((mkt.LOW as string) || '') : null,
|
||||
high: mkt ? parseFloat((mkt.HIGH as string) || '') : null,
|
||||
last: mkt
|
||||
? parseFloat((mkt.LAST as string) || '')
|
||||
: parseFloat((sec?.PREVPRICE as string) || ''),
|
||||
lastChange: mkt ? parseFloat((mkt.LASTCHANGE as string) || '') : null,
|
||||
lastChangePrcnt: mkt ? parseFloat((mkt.LASTCHANGEPRCNT as string) || '') : null,
|
||||
volume: mkt ? parseInt((mkt.VOLTODAY as string) || '0', 10) : 0,
|
||||
value: mkt ? parseFloat((mkt.VALTODAY as string) || '0') : 0,
|
||||
waprice: mkt ? parseFloat((mkt.WAPRICE as string) || '') : null,
|
||||
numtrades: mkt ? parseInt((mkt.NUMTRADES as string) || '0', 10) : 0,
|
||||
issueCapitalization: mkt ? parseFloat((mkt.ISSUECAPITALIZATION as string) || '') : null,
|
||||
tradingStatus: (mkt?.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt?.UPDATETIME as string) || '',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async getBondData(secid: string, boardId = 'TQCB'): Promise<MoexBondData | null> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const rows = this.http.extractTable(data, 'securities');
|
||||
const bond =
|
||||
rows.find((r) => r.BOARDID === boardId && r.PREVWAPRICE != null) ||
|
||||
rows.find((r) => r.PREVWAPRICE != null) ||
|
||||
rows[0];
|
||||
if (!bond) return null;
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: boardId,
|
||||
shortName: (bond.SHORTNAME as string) || '',
|
||||
prevWaprice: parseFloat((bond.PREVWAPRICE as string) || '') || null,
|
||||
yieldAtPrevWaprice: parseFloat((bond.YIELDATPREVWAPRICE as string) || '') || null,
|
||||
couponValue: bond.COUPONVALUE != null ? parseFloat(bond.COUPONVALUE as string) : null,
|
||||
nextCoupon: (bond.NEXTCOUPON as string) || null,
|
||||
accruedInt: bond.ACCRUEDINT != null ? parseFloat(bond.ACCRUEDINT as string) : null,
|
||||
prevPrice: parseFloat((bond.PREVPRICE as string) || '') || null,
|
||||
lotSize: parseInt((bond.LOTSIZE as string) || '1', 10),
|
||||
faceValue: parseFloat((bond.FACEVALUE as string) || '1000'),
|
||||
matDate: (bond.MATDATE as string) || '',
|
||||
couponPeriod: parseInt((bond.COUPONPERIOD as string) || '0', 10),
|
||||
issueSize: parseInt((bond.ISSUESIZE as string) || '0', 10),
|
||||
isin: (bond.ISIN as string) || '',
|
||||
couponPercent: bond.COUPONPERCENT != null ? parseFloat(bond.COUPONPERCENT as string) : null,
|
||||
offerDate: (bond.OFFERDATE as string) || null,
|
||||
buybackDate: (bond.BUYBACKDATE as string) || null,
|
||||
bondType: (bond.BONDTYPE as string) || '',
|
||||
bondSubType: (bond.BONDSUBTYPE as string) || '',
|
||||
listLevel: parseInt((bond.LISTLEVEL as string) || '0', 10),
|
||||
};
|
||||
}
|
||||
|
||||
async getBondMarketData(secid: string, boardId = 'TQCB'): Promise<MoexBondMarketData | null> {
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities/${secid}`,
|
||||
{ boards: boardId },
|
||||
);
|
||||
const mktRows = this.http.extractTable(data, 'marketdata');
|
||||
const mkt =
|
||||
mktRows.find((r) => r.BOARDID === boardId && r.LAST != null) ||
|
||||
mktRows.find((r) => r.LAST != null) ||
|
||||
mktRows.find((r) => r.SECID === secid);
|
||||
if (!mkt) return null;
|
||||
|
||||
return {
|
||||
secid,
|
||||
bid: mkt.BID != null ? parseFloat(mkt.BID as string) : null,
|
||||
offer: mkt.OFFER != null ? parseFloat(mkt.OFFER as string) : null,
|
||||
open: mkt.OPEN != null ? parseFloat(mkt.OPEN as string) : null,
|
||||
low: mkt.LOW != null ? parseFloat(mkt.LOW as string) : null,
|
||||
high: mkt.HIGH != null ? parseFloat(mkt.HIGH as string) : null,
|
||||
last: mkt.LAST != null ? parseFloat(mkt.LAST as string) : null,
|
||||
yield: mkt.YIELD != null ? parseFloat(mkt.YIELD as string) : null,
|
||||
waprice: mkt.WAPRICE != null ? parseFloat(mkt.WAPRICE as string) : null,
|
||||
yieldAtWaprice: mkt.YIELDATWAPRICE != null ? parseFloat(mkt.YIELDATWAPRICE as string) : null,
|
||||
duration: mkt.DURATION != null ? parseFloat(mkt.DURATION as string) : null,
|
||||
volume: parseInt((mkt.VOLTODAY as string) || '0', 10),
|
||||
value: parseFloat((mkt.VALTODAY as string) || '0'),
|
||||
numtrades: parseInt((mkt.NUMTRADES as string) || '0', 10),
|
||||
tradingStatus: (mkt.TRADINGSTATUS as string) || '',
|
||||
updateTime: (mkt.UPDATETIME as string) || '',
|
||||
};
|
||||
}
|
||||
|
||||
async getBondPositionDataBatch(
|
||||
secids: string[],
|
||||
boardId = 'TQCB',
|
||||
): Promise<MoexBondPositionData[]> {
|
||||
const params: Record<string, string> = { boards: boardId };
|
||||
if (secids.length > 0) {
|
||||
params.securities = secids.join(',');
|
||||
}
|
||||
const data = await this.http.request<Record<string, unknown>>(
|
||||
`/engines/stock/markets/bonds/securities`,
|
||||
params,
|
||||
);
|
||||
const securities = this.http.extractTable(data, 'securities');
|
||||
const marketdata = this.http.extractTable(data, 'marketdata');
|
||||
|
||||
const secidSet = secids.length > 0 ? new Set(secids) : null;
|
||||
const filteredSecurities = secidSet
|
||||
? securities.filter((r) => secidSet.has(r.SECID as string))
|
||||
: securities;
|
||||
|
||||
return filteredSecurities.map((bond) => {
|
||||
const secid = bond.SECID as string;
|
||||
const mkt =
|
||||
marketdata.find((r) => r.SECID === secid && r.BOARDID === boardId && r.LAST != null) ||
|
||||
marketdata.find((r) => r.SECID === secid && r.LAST != null) ||
|
||||
marketdata.find((r) => r.SECID === secid);
|
||||
|
||||
return {
|
||||
secid,
|
||||
boardid: (bond.BOARDID as string) || boardId,
|
||||
shortName: (bond?.SHORTNAME as string) || '',
|
||||
price: mkt?.LAST != null ? parseFloat(mkt.LAST as string) : null,
|
||||
yieldToMaturity: mkt?.YIELD != null ? parseFloat(mkt.YIELD as string) : null,
|
||||
duration: mkt?.DURATION != null ? parseFloat(mkt.DURATION as string) : null,
|
||||
couponValue: bond?.COUPONVALUE != null ? parseFloat(bond.COUPONVALUE as string) : null,
|
||||
couponPercent:
|
||||
bond?.COUPONPERCENT != null ? parseFloat(bond.COUPONPERCENT as string) : null,
|
||||
nextCouponDate: (bond?.NEXTCOUPON as string) || null,
|
||||
matDate: (bond?.MATDATE as string) || null,
|
||||
accruedInt: bond?.ACCRUEDINT != null ? parseFloat(bond.ACCRUEDINT as string) : null,
|
||||
faceValue: parseFloat((bond?.FACEVALUE as string) || '1000'),
|
||||
bid: mkt?.BID != null ? parseFloat(mkt.BID as string) : null,
|
||||
offer: mkt?.OFFER != null ? parseFloat(mkt.OFFER as string) : null,
|
||||
couponPeriod: parseInt((bond?.COUPONPERIOD as string) || '0', 10),
|
||||
bondType: (bond?.BONDTYPE as string) || null,
|
||||
offerDate: (bond?.OFFERDATE as string) || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
import 'reflect-metadata';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexSecuritiesClient } from './moex-securities.client';
|
||||
|
||||
describe('MoexSecuritiesClient', () => {
|
||||
let client: MoexSecuritiesClient;
|
||||
let httpMock: { request: ReturnType<typeof vi.fn>; extractTable: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
httpMock = {
|
||||
request: vi.fn(),
|
||||
extractTable: vi.fn(),
|
||||
};
|
||||
client = new MoexSecuritiesClient(httpMock as unknown as MoexHttpClient);
|
||||
});
|
||||
|
||||
describe('searchSecurities', () => {
|
||||
it('выполняет поиск по запросу и нормализует результаты', async () => {
|
||||
httpMock.request.mockResolvedValue({});
|
||||
httpMock.extractTable.mockReturnValue([
|
||||
{
|
||||
secid: 'SBER', isin: 'RU0009029540', name: 'Сбербанк России ПАО ао',
|
||||
shortName: 'Сбербанк', latName: 'Sberbank', listLevel: '1', issuesize: '21586948000',
|
||||
facevalue: '3', faceunit: 'SUR', issuedate: '2007-07-20', typename: 'Акция обыкновенная',
|
||||
group: 'stock_shares', type: 'common_share', isqualifiedinvestors: '0',
|
||||
morningsession: '1', eveningsession: '1',
|
||||
},
|
||||
]);
|
||||
|
||||
const results = await client.searchSecurities('SBER');
|
||||
|
||||
expect(httpMock.request).toHaveBeenCalledWith('/securities', { q: 'SBER' });
|
||||
expect(results).toEqual([
|
||||
{
|
||||
secid: 'SBER', isin: 'RU0009029540', name: 'Сбербанк России ПАО ао',
|
||||
shortName: 'Сбербанк', latName: 'Sberbank', listLevel: 1, issueSize: 21586948000,
|
||||
faceValue: 3, faceUnit: 'SUR', issueDate: '2007-07-20', typeName: 'Акция обыкновенная',
|
||||
group: 'stock_shares', type: 'common_share', isQualifiedInvestors: false,
|
||||
morningSession: true, eveningSession: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSecurityDescription', () => {
|
||||
it('возвращает описание бумаги из description таблицы', async () => {
|
||||
httpMock.request.mockResolvedValue({});
|
||||
httpMock.extractTable.mockReturnValue([
|
||||
{ name: 'ISIN', value: 'RU0009029540' },
|
||||
{ name: 'SHORTNAME', value: 'Сбербанк' },
|
||||
]);
|
||||
|
||||
const result = await client.getSecurityDescription('SBER');
|
||||
|
||||
expect(httpMock.request).toHaveBeenCalledWith('/securities/SBER');
|
||||
expect(result).toMatchObject({ secid: 'SBER', isin: 'RU0009029540', shortName: 'Сбербанк' });
|
||||
});
|
||||
|
||||
it('возвращает null если description пуст', async () => {
|
||||
httpMock.request.mockResolvedValue({});
|
||||
httpMock.extractTable.mockReturnValue([]);
|
||||
|
||||
const result = await client.getSecurityDescription('INVALID');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,55 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexHttpClient } from './moex-http.client';
|
||||
import { MoexSecurityDescription } from './moex-client.types';
|
||||
|
||||
@Injectable()
|
||||
export class MoexSecuritiesClient {
|
||||
constructor(private readonly http: MoexHttpClient) {}
|
||||
|
||||
async searchSecurities(query: string): Promise<MoexSecurityDescription[]> {
|
||||
const data = await this.http.request<Record<string, unknown>>('/securities', { q: query });
|
||||
return this.http.extractTable(data, 'securities').map((s) => ({
|
||||
secid: s.secid as string,
|
||||
isin: s.isin as string,
|
||||
name: s.name as string,
|
||||
shortName: s.shortName as string,
|
||||
latName: (s.latName as string) || null,
|
||||
listLevel: parseInt(s.listLevel as string, 10) || 0,
|
||||
issueSize: parseInt(s.issuesize as string, 10) || 0,
|
||||
faceValue: parseFloat(s.facevalue as string) || 0,
|
||||
faceUnit: (s.faceunit as string) || '',
|
||||
issueDate: (s.issuedate as string) || '',
|
||||
typeName: (s.typename as string) || '',
|
||||
group: (s.group as string) || '',
|
||||
type: (s.type as string) || '',
|
||||
isQualifiedInvestors: (s.isqualifiedinvestors as string) === '1',
|
||||
morningSession: (s.morningsession as string) === '1',
|
||||
eveningSession: (s.eveningsession as string) === '1',
|
||||
}));
|
||||
}
|
||||
|
||||
async getSecurityDescription(secid: string): Promise<MoexSecurityDescription | null> {
|
||||
const data = await this.http.request<Record<string, unknown>>(`/securities/${secid}`);
|
||||
const rows = this.http.extractTable(data, 'description');
|
||||
if (rows.length === 0) return null;
|
||||
const map = new Map(rows.map((r) => [r.name, r.value]));
|
||||
return {
|
||||
secid,
|
||||
isin: (map.get('ISIN') as string) || '',
|
||||
name: (map.get('NAME') as string) || '',
|
||||
shortName: (map.get('SHORTNAME') as string) || '',
|
||||
latName: (map.get('LATNAME') as string) || null,
|
||||
listLevel: parseInt((map.get('LISTLEVEL') as string) || '0', 10),
|
||||
issueSize: parseInt((map.get('ISSUESIZE') as string) || '0', 10),
|
||||
faceValue: parseFloat((map.get('FACEVALUE') as string) || '0'),
|
||||
faceUnit: (map.get('FACEUNIT') as string) || '',
|
||||
issueDate: (map.get('ISSUEDATE') as string) || '',
|
||||
typeName: (map.get('TYPENAME') as string) || '',
|
||||
group: (map.get('GROUP') as string) || '',
|
||||
type: (map.get('TYPE') as string) || '',
|
||||
isQualifiedInvestors: (map.get('ISQUALIFIEDINVESTORS') as string) === '1',
|
||||
morningSession: (map.get('MORNINGSESSION') as string) === '1',
|
||||
eveningSession: (map.get('EVENINGSESSION') as string) === '1',
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -8,6 +8,7 @@ import {
|
||||
IsIn,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
IsDateString,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
@ -31,7 +32,7 @@ export class AddPositionDto {
|
||||
|
||||
@ApiProperty({ example: 10 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Min(1)
|
||||
quantity!: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 250.5 })
|
||||
@ -41,7 +42,7 @@ export class AddPositionDto {
|
||||
buyPrice?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: '2026-06-01' })
|
||||
@IsString()
|
||||
@IsDateString()
|
||||
@IsOptional()
|
||||
buyDate?: string;
|
||||
|
||||
|
||||
@ -11,6 +11,24 @@ export class PortfolioSummaryDto {
|
||||
@ApiProperty({ type: Number, nullable: true }) totalReturnPercent!: number | null;
|
||||
@ApiProperty() positionCount!: number;
|
||||
@ApiProperty({ type: Number, nullable: true }) weightedYield!: number | null;
|
||||
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
targetSharesPercent?: number | null;
|
||||
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
targetBondsPercent?: number | null;
|
||||
|
||||
@ApiProperty()
|
||||
actualSharesPercent!: number;
|
||||
|
||||
@ApiProperty()
|
||||
actualBondsPercent!: number;
|
||||
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
sharesDeviation?: number | null;
|
||||
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
bondsDeviation?: number | null;
|
||||
}
|
||||
|
||||
export class AnalyticsResponseDto {
|
||||
|
||||
@ -1,53 +1,46 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ApiResponseMeta } from '../../../common/dto/api-response.dto';
|
||||
import { AnalyticsResponseDto } from './analytics-response.dto';
|
||||
import { PortfolioListResponseDto } from './portfolio-list-response.dto';
|
||||
import { PortfolioDetailResponseDto, PortfolioResponseDto } from './portfolio-response.dto';
|
||||
import { PositionResponseDto } from './position-response.dto';
|
||||
|
||||
export class PortfolioResponseMetaDto {
|
||||
@ApiProperty({ type: String, nullable: true })
|
||||
cachedAt!: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
fromCache!: boolean;
|
||||
}
|
||||
|
||||
export class PortfolioListEnvelopeDto {
|
||||
@ApiProperty({ type: [PortfolioListResponseDto] })
|
||||
data!: PortfolioListResponseDto[];
|
||||
|
||||
@ApiProperty({ type: PortfolioResponseMetaDto })
|
||||
meta!: PortfolioResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class PortfolioEnvelopeDto {
|
||||
@ApiProperty({ type: PortfolioResponseDto })
|
||||
data!: PortfolioResponseDto;
|
||||
|
||||
@ApiProperty({ type: PortfolioResponseMetaDto })
|
||||
meta!: PortfolioResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class PortfolioDetailEnvelopeDto {
|
||||
@ApiProperty({ type: PortfolioDetailResponseDto })
|
||||
data!: PortfolioDetailResponseDto;
|
||||
|
||||
@ApiProperty({ type: PortfolioResponseMetaDto })
|
||||
meta!: PortfolioResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class PositionEnvelopeDto {
|
||||
@ApiProperty({ type: PositionResponseDto })
|
||||
data!: PositionResponseDto;
|
||||
|
||||
@ApiProperty({ type: PortfolioResponseMetaDto })
|
||||
meta!: PortfolioResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class AnalyticsEnvelopeDto {
|
||||
@ApiProperty({ type: AnalyticsResponseDto })
|
||||
data!: AnalyticsResponseDto;
|
||||
|
||||
@ApiProperty({ type: PortfolioResponseMetaDto })
|
||||
meta!: PortfolioResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
@ -9,6 +9,16 @@ export class PortfolioResponseDto {
|
||||
@ApiProperty({ default: 'RUB' }) currency!: string;
|
||||
@ApiProperty() createdAt!: string;
|
||||
@ApiProperty() updatedAt!: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: 'object',
|
||||
properties: {
|
||||
sharesPercent: { type: 'number' },
|
||||
bondsPercent: { type: 'number' },
|
||||
},
|
||||
nullable: true,
|
||||
})
|
||||
targets!: { sharesPercent: number; bondsPercent: number } | null;
|
||||
}
|
||||
|
||||
export class PortfolioDetailResponseDto extends PortfolioResponseDto {
|
||||
|
||||
43
apps/backend/src/modules/portfolio/dto/position.dto.spec.ts
Normal file
43
apps/backend/src/modules/portfolio/dto/position.dto.spec.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import 'reflect-metadata';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { AddPositionDto } from './add-position.dto';
|
||||
import { UpdatePositionDto } from './update-position.dto';
|
||||
|
||||
describe('position DTO validation', () => {
|
||||
const validateDto = async <T extends object>(cls: new () => T, payload: Record<string, unknown>) =>
|
||||
validate(plainToInstance(cls, payload));
|
||||
|
||||
it('rejects zero quantity when adding a position', async () => {
|
||||
const errors = await validateDto(AddPositionDto, { secid: 'SBER', quantity: 0 });
|
||||
|
||||
expect(errors.some((error) => error.property === 'quantity')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects zero quantity when updating a position', async () => {
|
||||
const errors = await validateDto(UpdatePositionDto, { quantity: 0 });
|
||||
|
||||
expect(errors.some((error) => error.property === 'quantity')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid buyDate values', async () => {
|
||||
const addErrors = await validateDto(AddPositionDto, {
|
||||
secid: 'SBER',
|
||||
quantity: 1,
|
||||
buyDate: 'not-a-date',
|
||||
});
|
||||
const updateErrors = await validateDto(UpdatePositionDto, { buyDate: 'not-a-date' });
|
||||
|
||||
expect(addErrors.some((error) => error.property === 'buyDate')).toBe(true);
|
||||
expect(updateErrors.some((error) => error.property === 'buyDate')).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts valid position payloads', async () => {
|
||||
await expect(
|
||||
validateDto(AddPositionDto, { secid: 'SBER', quantity: 1, buyDate: '2026-06-01' }),
|
||||
).resolves.toHaveLength(0);
|
||||
await expect(
|
||||
validateDto(UpdatePositionDto, { quantity: 2, buyDate: '2026-06-15' }),
|
||||
).resolves.toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@ -1,8 +1,34 @@
|
||||
import { IsString, IsOptional, IsIn, MaxLength, MinLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsIn,
|
||||
IsObject,
|
||||
IsNumber,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
Min,
|
||||
Max,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
const CURRENCIES = ['RUB', 'USD', 'EUR', 'CNY', 'KZT', 'BYN'] as const;
|
||||
|
||||
export class PortfolioTargetsDto {
|
||||
@ApiProperty({ example: 70 })
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
sharesPercent!: number;
|
||||
|
||||
@ApiProperty({ example: 30 })
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
bondsPercent!: number;
|
||||
}
|
||||
|
||||
export class UpdatePortfolioDto {
|
||||
@ApiPropertyOptional({ example: 'Мой портфель' })
|
||||
@IsString()
|
||||
@ -22,4 +48,11 @@ export class UpdatePortfolioDto {
|
||||
@IsIn(CURRENCIES)
|
||||
@IsOptional()
|
||||
currency?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: { sharesPercent: 70, bondsPercent: 30 } })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
@ValidateNested()
|
||||
@Type(() => PortfolioTargetsDto)
|
||||
targets?: PortfolioTargetsDto;
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ import {
|
||||
IsArray,
|
||||
IsIn,
|
||||
MaxLength,
|
||||
IsDateString,
|
||||
} from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
@ -24,7 +25,7 @@ const TAGS = [
|
||||
export class UpdatePositionDto {
|
||||
@ApiPropertyOptional({ example: 15 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Min(1)
|
||||
@IsOptional()
|
||||
quantity?: number;
|
||||
|
||||
@ -35,7 +36,7 @@ export class UpdatePositionDto {
|
||||
buyPrice?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: '2026-06-15' })
|
||||
@IsString()
|
||||
@IsDateString()
|
||||
@IsOptional()
|
||||
buyDate?: string;
|
||||
|
||||
|
||||
@ -13,32 +13,28 @@ import { CreatePortfolioDto } from './dto/create-portfolio.dto';
|
||||
import { UpdatePortfolioDto } from './dto/update-portfolio.dto';
|
||||
import { AddPositionDto } from './dto/add-position.dto';
|
||||
import { UpdatePositionDto } from './dto/update-position.dto';
|
||||
import { ApiResponseMeta } from '../../common/dto/api-response.dto';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import {
|
||||
AnalyticsEnvelopeDto,
|
||||
PortfolioDetailEnvelopeDto,
|
||||
PortfolioEnvelopeDto,
|
||||
PortfolioListEnvelopeDto,
|
||||
PortfolioResponseMetaDto,
|
||||
PositionEnvelopeDto,
|
||||
} from './dto/portfolio-envelope.dto';
|
||||
|
||||
const nullDataEnvelopeSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
data: {
|
||||
type: 'null',
|
||||
},
|
||||
meta: {
|
||||
$ref: getSchemaPath(PortfolioResponseMetaDto),
|
||||
},
|
||||
data: { type: 'null' },
|
||||
meta: { $ref: getSchemaPath(ApiResponseMeta) },
|
||||
},
|
||||
required: ['data', 'meta'],
|
||||
};
|
||||
|
||||
@ApiTags('Portfolios')
|
||||
@ApiBearerAuth()
|
||||
@ApiExtraModels(PortfolioResponseMetaDto)
|
||||
@ApiExtraModels(ApiResponseMeta)
|
||||
@Controller('portfolios')
|
||||
export class PortfolioController {
|
||||
constructor(private readonly portfolioService: PortfolioService) {}
|
||||
@ -47,24 +43,21 @@ export class PortfolioController {
|
||||
@ApiOperation({ summary: 'Get all portfolios for current user' })
|
||||
@ApiOkResponse({ type: PortfolioListEnvelopeDto })
|
||||
async findAll(@CurrentUser() user: { sub: number }) {
|
||||
const portfolios = await this.portfolioService.findAll(user.sub);
|
||||
return { data: portfolios, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.findAll(user.sub);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new portfolio' })
|
||||
@ApiCreatedResponse({ type: PortfolioEnvelopeDto })
|
||||
async create(@CurrentUser() user: { sub: number }, @Body() dto: CreatePortfolioDto) {
|
||||
const portfolio = await this.portfolioService.create(user.sub, dto);
|
||||
return { data: portfolio, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.create(user.sub, dto);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get portfolio details with positions and prices' })
|
||||
@ApiOkResponse({ type: PortfolioDetailEnvelopeDto })
|
||||
async findOne(@CurrentUser() user: { sub: number }, @Param('id', ParseIntPipe) id: number) {
|
||||
const portfolio = await this.portfolioService.findOne(user.sub, id);
|
||||
return { data: portfolio, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.findOne(user.sub, id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ -75,8 +68,7 @@ export class PortfolioController {
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdatePortfolioDto,
|
||||
) {
|
||||
const portfolio = await this.portfolioService.update(user.sub, id, dto);
|
||||
return { data: portfolio, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.update(user.sub, id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ -84,7 +76,7 @@ export class PortfolioController {
|
||||
@ApiOkResponse({ schema: nullDataEnvelopeSchema })
|
||||
async remove(@CurrentUser() user: { sub: number }, @Param('id', ParseIntPipe) id: number) {
|
||||
await this.portfolioService.remove(user.sub, id);
|
||||
return { data: null, meta: { cachedAt: null, fromCache: false } };
|
||||
return null;
|
||||
}
|
||||
|
||||
@Post(':id/positions')
|
||||
@ -95,8 +87,7 @@ export class PortfolioController {
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: AddPositionDto,
|
||||
) {
|
||||
const position = await this.portfolioService.addPosition(user.sub, id, dto);
|
||||
return { data: position, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.addPosition(user.sub, id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/positions/:positionId')
|
||||
@ -108,16 +99,14 @@ export class PortfolioController {
|
||||
@Param('positionId', ParseIntPipe) positionId: number,
|
||||
@Body() dto: UpdatePositionDto,
|
||||
) {
|
||||
const position = await this.portfolioService.updatePosition(user.sub, id, positionId, dto);
|
||||
return { data: position, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.updatePosition(user.sub, id, positionId, dto);
|
||||
}
|
||||
|
||||
@Get(':id/analytics')
|
||||
@ApiOperation({ summary: 'Get portfolio analytics with PnL' })
|
||||
@ApiOkResponse({ type: AnalyticsEnvelopeDto })
|
||||
async getAnalytics(@CurrentUser() user: { sub: number }, @Param('id', ParseIntPipe) id: number) {
|
||||
const result = await this.portfolioService.getAnalytics(user.sub, id);
|
||||
return { data: result, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.portfolioService.getAnalytics(user.sub, id);
|
||||
}
|
||||
|
||||
@Delete(':id/positions/:positionId')
|
||||
@ -129,6 +118,6 @@ export class PortfolioController {
|
||||
@Param('positionId', ParseIntPipe) positionId: number,
|
||||
) {
|
||||
await this.portfolioService.removePosition(user.sub, id, positionId);
|
||||
return { data: null, meta: { cachedAt: null, fromCache: false } };
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MoexClientModule } from '../moex-client/moex-client.module';
|
||||
import { PortfolioController } from './portfolio.controller';
|
||||
import { PortfolioService } from './portfolio.service';
|
||||
|
||||
@Module({
|
||||
imports: [MoexClientModule],
|
||||
controllers: [PortfolioController],
|
||||
providers: [PortfolioService],
|
||||
exports: [PortfolioService],
|
||||
|
||||
@ -2,15 +2,18 @@ import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { PortfolioService } from './portfolio.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../moex-client/moex-dividends.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import configuration from '../../config/configuration';
|
||||
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
import { PortfolioAccessDeniedException } from '../../common/exceptions/portfolio-access.exception';
|
||||
|
||||
describe('PortfolioService', () => {
|
||||
let service: PortfolioService;
|
||||
let prisma: PrismaService;
|
||||
let moexClient: MoexClientService;
|
||||
let moexMarketData: MoexMarketDataClient;
|
||||
let module: TestingModule;
|
||||
|
||||
const mockPortfolio = (overrides: Record<string, unknown> = {}) => ({
|
||||
@ -65,13 +68,20 @@ describe('PortfolioService', () => {
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MoexClientService,
|
||||
provide: MoexSecuritiesClient,
|
||||
useValue: { getSecurityDescription: vi.fn() },
|
||||
},
|
||||
{
|
||||
provide: MoexMarketDataClient,
|
||||
useValue: {
|
||||
getShareMarketDataBatch: vi.fn(),
|
||||
getBondPositionDataBatch: vi.fn(),
|
||||
getSecurityDescription: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MoexDividendsClient,
|
||||
useValue: { getDividends: vi.fn() },
|
||||
},
|
||||
{
|
||||
provide: CacheService,
|
||||
useValue: {
|
||||
@ -83,7 +93,7 @@ describe('PortfolioService', () => {
|
||||
|
||||
service = module.get<PortfolioService>(PortfolioService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
moexClient = module.get<MoexClientService>(MoexClientService);
|
||||
moexMarketData = module.get<MoexMarketDataClient>(MoexMarketDataClient);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@ -137,11 +147,11 @@ describe('PortfolioService', () => {
|
||||
mockPortfolio({ positions: [sharePosition, bondPosition] }) as any,
|
||||
]);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 250, lastChange: 5, lastChangePrcnt: 2 },
|
||||
] as any);
|
||||
|
||||
vi.mocked(moexClient.getBondPositionDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getBondPositionDataBatch).mockResolvedValue([
|
||||
{
|
||||
secid: 'SU26238RMFS5',
|
||||
shortName: 'OFZ 26238',
|
||||
@ -203,14 +213,14 @@ describe('PortfolioService', () => {
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should throw NotFoundException for non-existent portfolio', async () => {
|
||||
it('should throw EntityNotFoundException for non-existent portfolio', async () => {
|
||||
vi.mocked(prisma.portfolio.findUnique).mockResolvedValue(null);
|
||||
await expect(service.findOne(1, 999)).rejects.toThrow(NotFoundException);
|
||||
await expect(service.findOne(1, 999)).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException for wrong user', async () => {
|
||||
it('should throw PortfolioAccessDeniedException for wrong user', async () => {
|
||||
vi.mocked(prisma.portfolio.findUnique).mockResolvedValue(mockPortfolio({ userId: 2 }) as any);
|
||||
await expect(service.findOne(1, 1)).rejects.toThrow(ForbiddenException);
|
||||
await expect(service.findOne(1, 1)).rejects.toThrow(PortfolioAccessDeniedException);
|
||||
});
|
||||
|
||||
it('should return portfolio with enriched positions and analytics summary', async () => {
|
||||
@ -235,7 +245,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 250 },
|
||||
] as any);
|
||||
|
||||
@ -281,7 +291,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 250, lastChange: 5, lastChangePrcnt: 2 },
|
||||
] as any);
|
||||
|
||||
@ -323,7 +333,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getBondPositionDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getBondPositionDataBatch).mockResolvedValue([
|
||||
{
|
||||
secid: 'SU26238RMFS5',
|
||||
shortName: 'OFZ 26238',
|
||||
@ -367,7 +377,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 250 },
|
||||
] as any);
|
||||
|
||||
@ -403,7 +413,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([] as any);
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([] as any);
|
||||
|
||||
const result = await service.getPositionsWithPrices(1);
|
||||
|
||||
@ -459,7 +469,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 250, lastChange: 5, lastChangePrcnt: 2 },
|
||||
{ secid: 'GAZP', shortName: 'Gazprom', last: 160, lastChange: 3, lastChangePrcnt: 1.5 },
|
||||
] as any);
|
||||
@ -511,7 +521,7 @@ describe('PortfolioService', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mocked(moexClient.getShareMarketDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getShareMarketDataBatch).mockResolvedValue([
|
||||
{ secid: 'SBER', shortName: 'Sberbank', last: 120 },
|
||||
{ secid: 'GAZP', shortName: 'Gazprom', last: 180 },
|
||||
] as any);
|
||||
@ -524,16 +534,16 @@ describe('PortfolioService', () => {
|
||||
expect(result.summary.weightedYield).toBeCloseTo(0, 1);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException if portfolio belongs to another user', async () => {
|
||||
it('should throw PortfolioAccessDeniedException if portfolio belongs to another user', async () => {
|
||||
vi.mocked(prisma.portfolio.findUnique).mockResolvedValue(mockPortfolio({ userId: 2 }) as any);
|
||||
|
||||
await expect(service.getAnalytics(1, 1)).rejects.toThrow(ForbiddenException);
|
||||
await expect(service.getAnalytics(1, 1)).rejects.toThrow(PortfolioAccessDeniedException);
|
||||
});
|
||||
|
||||
it('should throw NotFoundException if portfolio does not exist', async () => {
|
||||
it('should throw EntityNotFoundException if portfolio does not exist', async () => {
|
||||
vi.mocked(prisma.portfolio.findUnique).mockResolvedValue(null);
|
||||
|
||||
await expect(service.getAnalytics(1, 999)).rejects.toThrow(NotFoundException);
|
||||
await expect(service.getAnalytics(1, 999)).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,13 +1,19 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../moex-client/moex-dividends.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import type { MoexShareMarketData, MoexBondPositionData } from '../moex-client/moex-client.types';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
import { PortfolioAccessDeniedException } from '../../common/exceptions/portfolio-access.exception';
|
||||
import type {
|
||||
MoexShareMarketData,
|
||||
MoexBondPositionData,
|
||||
MoexDividend,
|
||||
} from '../moex-client/moex-client.types';
|
||||
import { CreatePortfolioDto } from './dto/create-portfolio.dto';
|
||||
import { UpdatePortfolioDto } from './dto/update-portfolio.dto';
|
||||
import { AddPositionDto } from './dto/add-position.dto';
|
||||
@ -54,12 +60,14 @@ export interface EnrichedPosition {
|
||||
export class PortfolioService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexSecurities: MoexSecuritiesClient,
|
||||
private readonly moexMarketData: MoexMarketDataClient,
|
||||
private readonly moexDividends: MoexDividendsClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
async create(userId: number, dto: CreatePortfolioDto) {
|
||||
return this.prisma.portfolio.create({
|
||||
const portfolio = await this.prisma.portfolio.create({
|
||||
data: {
|
||||
userId,
|
||||
name: dto.name,
|
||||
@ -67,6 +75,8 @@ export class PortfolioService {
|
||||
currency: dto.currency ?? 'RUB',
|
||||
},
|
||||
});
|
||||
|
||||
return { ...portfolio, targets: null };
|
||||
}
|
||||
|
||||
async findAll(userId: number) {
|
||||
@ -89,6 +99,7 @@ export class PortfolioService {
|
||||
positionCount: 0,
|
||||
shareCount: 0,
|
||||
bondCount: 0,
|
||||
targets: p.targets ? JSON.parse(p.targets) : null,
|
||||
}));
|
||||
}
|
||||
|
||||
@ -117,6 +128,7 @@ export class PortfolioService {
|
||||
positionCount: positions.length,
|
||||
shareCount: positions.filter((pos) => pos.type === 'share').length,
|
||||
bondCount: positions.filter((pos) => pos.type === 'bond').length,
|
||||
targets: p.targets ? JSON.parse(p.targets) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
@ -127,8 +139,8 @@ export class PortfolioService {
|
||||
include: { positions: true },
|
||||
});
|
||||
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${id} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', id);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(id);
|
||||
|
||||
const positionsWithPrices = await this.enrichPositions(portfolio.positions, id);
|
||||
|
||||
@ -154,28 +166,35 @@ export class PortfolioService {
|
||||
positions: positionsWithWeights,
|
||||
totalValue: Math.round(totalValue * 100) / 100,
|
||||
analytics: analytics.summary,
|
||||
targets: portfolio.targets ? JSON.parse(portfolio.targets) : null,
|
||||
};
|
||||
}
|
||||
|
||||
async update(userId: number, id: number, dto: UpdatePortfolioDto) {
|
||||
const portfolio = await this.prisma.portfolio.findUnique({ where: { id } });
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${id} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', id);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(id);
|
||||
|
||||
return this.prisma.portfolio.update({
|
||||
const updated = await this.prisma.portfolio.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(dto.name !== undefined && { name: dto.name }),
|
||||
...(dto.description !== undefined && { description: dto.description }),
|
||||
...(dto.currency !== undefined && { currency: dto.currency }),
|
||||
...(dto.targets !== undefined && { targets: JSON.stringify(dto.targets) }),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...updated,
|
||||
targets: updated.targets ? JSON.parse(updated.targets) : null,
|
||||
};
|
||||
}
|
||||
|
||||
async remove(userId: number, id: number) {
|
||||
const portfolio = await this.prisma.portfolio.findUnique({ where: { id } });
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${id} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', id);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(id);
|
||||
|
||||
await this.prisma.portfolio.delete({ where: { id } });
|
||||
}
|
||||
@ -185,8 +204,8 @@ export class PortfolioService {
|
||||
where: { id: portfolioId },
|
||||
include: { positions: true },
|
||||
});
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${portfolioId} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', portfolioId);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(portfolioId);
|
||||
|
||||
const exists = portfolio.positions.find((p) => p.secid === dto.secid);
|
||||
if (exists)
|
||||
@ -194,7 +213,7 @@ export class PortfolioService {
|
||||
|
||||
if (dto.quantity === 0) throw new BadRequestException('Quantity must be greater than 0');
|
||||
|
||||
const desc = await this.moexClient.getSecurityDescription(dto.secid);
|
||||
const desc = await this.moexSecurities.getSecurityDescription(dto.secid);
|
||||
if (!desc) throw new BadRequestException(`Security ${dto.secid} not found in MOEX`);
|
||||
|
||||
const type = desc.group === 'stock_bonds' ? 'bond' : 'share';
|
||||
@ -220,12 +239,12 @@ export class PortfolioService {
|
||||
dto: UpdatePositionDto,
|
||||
) {
|
||||
const portfolio = await this.prisma.portfolio.findUnique({ where: { id: portfolioId } });
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${portfolioId} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', portfolioId);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(portfolioId);
|
||||
|
||||
const position = await this.prisma.position.findUnique({ where: { id: positionId } });
|
||||
if (!position || position.portfolioId !== portfolioId) {
|
||||
throw new NotFoundException(`Position ${positionId} not found`);
|
||||
throw new EntityNotFoundException('Position', positionId);
|
||||
}
|
||||
|
||||
return this.prisma.position.update({
|
||||
@ -242,12 +261,12 @@ export class PortfolioService {
|
||||
|
||||
async removePosition(userId: number, portfolioId: number, positionId: number) {
|
||||
const portfolio = await this.prisma.portfolio.findUnique({ where: { id: portfolioId } });
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${portfolioId} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException('Access denied');
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', portfolioId);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(portfolioId);
|
||||
|
||||
const position = await this.prisma.position.findUnique({ where: { id: positionId } });
|
||||
if (!position || position.portfolioId !== portfolioId) {
|
||||
throw new NotFoundException(`Position ${positionId} not found`);
|
||||
throw new EntityNotFoundException('Position', positionId);
|
||||
}
|
||||
|
||||
await this.prisma.position.delete({ where: { id: positionId } });
|
||||
@ -272,9 +291,10 @@ export class PortfolioService {
|
||||
const shareSecids = [...new Set(sharePositions.map((p) => p.secid))].sort();
|
||||
const bondSecids = [...new Set(bondPositions.map((p) => p.secid))].sort();
|
||||
|
||||
const [shareDataBySecid, bondDataBySecid] = await Promise.all([
|
||||
const [shareDataBySecid, bondDataBySecid, dividendsBySecid] = await Promise.all([
|
||||
this.fetchShareBatch(shareSecids, portfolioId),
|
||||
this.fetchBondBatch(bondSecids, portfolioId),
|
||||
this.fetchDividendsBatch(shareSecids, portfolioId),
|
||||
]);
|
||||
|
||||
const enriched: EnrichedPosition[] = [];
|
||||
@ -305,7 +325,9 @@ export class PortfolioService {
|
||||
if (pos.type === 'bond') {
|
||||
enriched.push(this.buildBondPosition(pos, base, bondDataBySecid.get(pos.secid)));
|
||||
} else {
|
||||
enriched.push(this.buildSharePosition(pos, base, shareDataBySecid.get(pos.secid)));
|
||||
enriched.push(
|
||||
this.buildSharePosition(pos, base, shareDataBySecid.get(pos.secid), dividendsBySecid.get(pos.secid)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -321,7 +343,7 @@ export class PortfolioService {
|
||||
const { data } = await this.cache.getOrFetch(
|
||||
'batchdata',
|
||||
['shares', cacheKey],
|
||||
() => this.moexClient.getShareMarketDataBatch(secids),
|
||||
() => this.moexMarketData.getShareMarketDataBatch(secids),
|
||||
'marketDataTtl',
|
||||
);
|
||||
return new Map(data.map((d) => [d.secid, d]));
|
||||
@ -336,12 +358,32 @@ export class PortfolioService {
|
||||
const { data } = await this.cache.getOrFetch(
|
||||
'batchdata',
|
||||
['bonds', cacheKey],
|
||||
() => this.moexClient.getBondPositionDataBatch(secids),
|
||||
() => this.moexMarketData.getBondPositionDataBatch(secids),
|
||||
'marketDataTtl',
|
||||
);
|
||||
return new Map(data.map((d) => [d.secid, d]));
|
||||
}
|
||||
|
||||
private async fetchDividendsBatch(
|
||||
secids: string[],
|
||||
portfolioId?: number,
|
||||
): Promise<Map<string, MoexDividend[]>> {
|
||||
if (secids.length === 0) return new Map();
|
||||
const results = await Promise.all(
|
||||
secids.map(async (secid) => {
|
||||
const cacheKey = portfolioId ? `pf:${portfolioId}:${secid}` : secid;
|
||||
const { data } = await this.cache.getOrFetch(
|
||||
'dividends',
|
||||
[cacheKey],
|
||||
() => this.moexDividends.getDividends(secid),
|
||||
'marketDataTtl',
|
||||
);
|
||||
return { secid, dividends: data };
|
||||
}),
|
||||
);
|
||||
return new Map(results.map((r) => [r.secid, r.dividends]));
|
||||
}
|
||||
|
||||
private buildSharePosition(
|
||||
pos: {
|
||||
id: number;
|
||||
@ -352,9 +394,16 @@ export class PortfolioService {
|
||||
},
|
||||
base: EnrichedPosition,
|
||||
data: MoexShareMarketData | undefined,
|
||||
dividends?: MoexDividend[],
|
||||
): EnrichedPosition {
|
||||
const totalCost = pos.buyPrice !== null ? pos.buyPrice * pos.quantity : null;
|
||||
const dividendIncome = 0;
|
||||
let dividendIncome = 0;
|
||||
if (pos.buyDate && dividends && dividends.length > 0) {
|
||||
const buyDateStr = pos.buyDate.toISOString().split('T')[0];
|
||||
dividendIncome = dividends
|
||||
.filter((d) => d.registryCloseDate >= buyDateStr)
|
||||
.reduce((sum, d) => sum + d.value * pos.quantity, 0);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return {
|
||||
@ -472,8 +521,8 @@ export class PortfolioService {
|
||||
|
||||
async getAnalytics(userId: number, portfolioId: number): Promise<AnalyticsResponseDto> {
|
||||
const portfolio = await this.prisma.portfolio.findUnique({ where: { id: portfolioId } });
|
||||
if (!portfolio) throw new NotFoundException(`Portfolio ${portfolioId} not found`);
|
||||
if (portfolio.userId !== userId) throw new ForbiddenException();
|
||||
if (!portfolio) throw new EntityNotFoundException('Portfolio', portfolioId);
|
||||
if (portfolio.userId !== userId) throw new PortfolioAccessDeniedException(portfolioId);
|
||||
|
||||
const enrichedPositions = await this.getPositionsWithPrices(portfolioId);
|
||||
|
||||
@ -494,6 +543,32 @@ export class PortfolioService {
|
||||
)
|
||||
: null;
|
||||
|
||||
let targetSharesPercent: number | null = null;
|
||||
let targetBondsPercent: number | null = null;
|
||||
if (portfolio.targets) {
|
||||
const targets = JSON.parse(portfolio.targets);
|
||||
targetSharesPercent = targets.sharesPercent;
|
||||
targetBondsPercent = targets.bondsPercent;
|
||||
}
|
||||
|
||||
let actualSharesPercent = 0;
|
||||
let actualBondsPercent = 0;
|
||||
if (totalValue > 0) {
|
||||
const shareValue = enrichedPositions
|
||||
.filter((p) => p.type === 'share')
|
||||
.reduce((sum, p) => sum + (p.currentValue ?? 0), 0);
|
||||
const bondValue = enrichedPositions
|
||||
.filter((p) => p.type === 'bond')
|
||||
.reduce((sum, p) => sum + (p.currentValue ?? 0), 0);
|
||||
actualSharesPercent = Math.round((shareValue / totalValue) * 10000) / 100;
|
||||
actualBondsPercent = Math.round((bondValue / totalValue) * 10000) / 100;
|
||||
}
|
||||
|
||||
const sharesDeviation =
|
||||
targetSharesPercent !== null ? Math.round((actualSharesPercent - targetSharesPercent) * 100) / 100 : null;
|
||||
const bondsDeviation =
|
||||
targetBondsPercent !== null ? Math.round((actualBondsPercent - targetBondsPercent) * 100) / 100 : null;
|
||||
|
||||
const summary = {
|
||||
totalInvested,
|
||||
totalValue,
|
||||
@ -504,6 +579,12 @@ export class PortfolioService {
|
||||
totalReturnPercent,
|
||||
positionCount,
|
||||
weightedYield,
|
||||
targetSharesPercent,
|
||||
targetBondsPercent,
|
||||
actualSharesPercent,
|
||||
actualBondsPercent,
|
||||
sharesDeviation,
|
||||
bondsDeviation,
|
||||
};
|
||||
|
||||
return { positions: enrichedPositions, summary };
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { ApiResponseMeta } from '../../../common/dto/api-response.dto';
|
||||
|
||||
export class ScreenerItemDto {
|
||||
@ApiProperty({ example: 'SBER' })
|
||||
@ -70,18 +71,10 @@ export class ScreenerResultDto {
|
||||
totalPages!: number;
|
||||
}
|
||||
|
||||
class ScreenerResponseMetaDto {
|
||||
@ApiProperty({ type: String, nullable: true })
|
||||
cachedAt!: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
fromCache!: boolean;
|
||||
}
|
||||
|
||||
export class ScreenerResponseDto {
|
||||
@ApiProperty({ type: ScreenerResultDto })
|
||||
data!: ScreenerResultDto;
|
||||
|
||||
@ApiProperty({ type: ScreenerResponseMetaDto })
|
||||
meta!: ScreenerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
@ -1,30 +1,21 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ScreenerService } from './screener.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { ScreenerType } from './dto/screener-query.dto';
|
||||
|
||||
describe('ScreenerService', () => {
|
||||
let service: ScreenerService;
|
||||
let cache: CacheService;
|
||||
const moexMarketData = { getShareMarketDataBatch: vi.fn(), getBondPositionDataBatch: vi.fn() };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ScreenerService,
|
||||
{
|
||||
provide: MoexClientService,
|
||||
useValue: {
|
||||
getShareMarketDataBatch: vi.fn(),
|
||||
getBondPositionDataBatch: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: CacheService,
|
||||
useValue: {
|
||||
getOrFetch: vi.fn(),
|
||||
},
|
||||
},
|
||||
{ provide: MoexMarketDataClient, useValue: moexMarketData },
|
||||
{ provide: CacheService, useValue: { getOrFetch: vi.fn() } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@ -37,6 +28,30 @@ describe('ScreenerService', () => {
|
||||
});
|
||||
|
||||
describe('screen', () => {
|
||||
it('should cache full dataset with screenerTtl config', async () => {
|
||||
const mockShares = [{
|
||||
secid: 'SBER', shortName: 'Sberbank', last: 250, volume: 1000000,
|
||||
lastChange: 5, lastChangePrcnt: 2, issueCapitalization: 1e9,
|
||||
}];
|
||||
|
||||
moexMarketData.getShareMarketDataBatch.mockResolvedValue(mockShares);
|
||||
|
||||
vi.mocked(cache.getOrFetch).mockImplementation(async (_prefix, _keys, fetchFn) => ({
|
||||
data: await fetchFn(),
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
}));
|
||||
|
||||
await service.screen({ type: ScreenerType.SHARE });
|
||||
|
||||
expect(cache.getOrFetch).toHaveBeenCalledWith(
|
||||
'screener',
|
||||
[ScreenerType.SHARE],
|
||||
expect.any(Function),
|
||||
'screenerTtl',
|
||||
);
|
||||
});
|
||||
|
||||
it('should filter and sort shares', async () => {
|
||||
const mockShares = [
|
||||
{
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { ScreenerQueryDto, ScreenerType } from './dto/screener-query.dto';
|
||||
import { ScreenerItemDto, ScreenerResultDto } from './dto/screener-response.dto';
|
||||
@ -7,7 +7,7 @@ import { ScreenerItemDto, ScreenerResultDto } from './dto/screener-response.dto'
|
||||
@Injectable()
|
||||
export class ScreenerService {
|
||||
constructor(
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexMarketData: MoexMarketDataClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
@ -38,7 +38,7 @@ export class ScreenerService {
|
||||
[type],
|
||||
async () => {
|
||||
if (type === ScreenerType.SHARE) {
|
||||
const shares = await this.moexClient.getShareMarketDataBatch([]);
|
||||
const shares = await this.moexMarketData.getShareMarketDataBatch([]);
|
||||
return shares.map(
|
||||
(s): ScreenerItemDto => ({
|
||||
secid: s.secid,
|
||||
@ -61,7 +61,7 @@ export class ScreenerService {
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const bonds = await this.moexClient.getBondPositionDataBatch([]);
|
||||
const bonds = await this.moexMarketData.getBondPositionDataBatch([]);
|
||||
return bonds.map(
|
||||
(b): ScreenerItemDto => ({
|
||||
secid: b.secid,
|
||||
@ -85,7 +85,7 @@ export class ScreenerService {
|
||||
);
|
||||
}
|
||||
},
|
||||
'marketDataTtl',
|
||||
'screenerTtl',
|
||||
);
|
||||
|
||||
return data;
|
||||
|
||||
@ -47,7 +47,7 @@ describe('SecuritiesController', () => {
|
||||
|
||||
it('should return search results', async () => {
|
||||
const result = await controller.search({ q: 'SBER', type: SecurityType.ALL, limit: 5 });
|
||||
expect(result.data).toEqual(mockResults);
|
||||
expect(result).toEqual(mockResults);
|
||||
expect(service.search).toHaveBeenCalledWith('SBER', SecurityType.ALL, 5);
|
||||
});
|
||||
});
|
||||
|
||||
@ -21,19 +21,17 @@ export class SecuritiesController {
|
||||
@ApiOperation({ summary: 'Поиск по инструментам' })
|
||||
@ApiOkResponse({ type: SearchEnvelopeDto })
|
||||
async search(@Query(ValidationPipe) query: SearchQueryDto) {
|
||||
const results = await this.securitiesService.search(
|
||||
return this.securitiesService.search(
|
||||
query.q,
|
||||
query.type || SecurityType.ALL,
|
||||
query.limit || 20,
|
||||
);
|
||||
return { data: results, meta: { cachedAt: null, fromCache: false } };
|
||||
}
|
||||
|
||||
@Get('screener')
|
||||
@ApiOperation({ summary: 'Фильтр ценных бумаг по параметрам' })
|
||||
@ApiOkResponse({ type: ScreenerResponseDto })
|
||||
async screener(@Query(ValidationPipe) query: ScreenerQueryDto) {
|
||||
const result = await this.screenerService.screen(query);
|
||||
return { data: result, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.screenerService.screen(query);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CacheModule } from '../cache/cache.module';
|
||||
import { MoexClientModule } from '../moex-client/moex-client.module';
|
||||
import { SecuritiesController } from './securities.controller';
|
||||
import { SecuritiesService } from './securities.service';
|
||||
import { ScreenerService } from './screener.service';
|
||||
|
||||
@Module({
|
||||
imports: [CacheModule],
|
||||
imports: [MoexClientModule],
|
||||
controllers: [SecuritiesController],
|
||||
providers: [SecuritiesService, ScreenerService],
|
||||
exports: [SecuritiesService],
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { SecuritiesService } from './securities.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { SecurityType } from './dto/search-query.dto';
|
||||
|
||||
describe('SecuritiesService', () => {
|
||||
let service: SecuritiesService;
|
||||
let moexClient: Pick<MoexClientService, 'searchSecurities'>;
|
||||
let moexSecurities: Pick<MoexSecuritiesClient, 'searchSecurities'>;
|
||||
let cache: Pick<CacheService, 'getOrFetch'>;
|
||||
|
||||
beforeEach(async () => {
|
||||
moexClient = {
|
||||
moexSecurities = {
|
||||
searchSecurities: vi.fn(),
|
||||
};
|
||||
cache = {
|
||||
@ -24,7 +24,7 @@ describe('SecuritiesService', () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
SecuritiesService,
|
||||
{ provide: MoexClientService, useValue: moexClient },
|
||||
{ provide: MoexSecuritiesClient, useValue: moexSecurities },
|
||||
{ provide: CacheService, useValue: cache },
|
||||
],
|
||||
}).compile();
|
||||
@ -33,7 +33,7 @@ describe('SecuritiesService', () => {
|
||||
});
|
||||
|
||||
it('returns supported securities only and normalizes SUR currency to RUB', async () => {
|
||||
vi.mocked(moexClient.searchSecurities).mockResolvedValue([
|
||||
vi.mocked(moexSecurities.searchSecurities).mockResolvedValue([
|
||||
{
|
||||
secid: 'SBER',
|
||||
isin: 'RU0009029540',
|
||||
@ -118,7 +118,7 @@ describe('SecuritiesService', () => {
|
||||
expect.any(Function),
|
||||
'searchTtl',
|
||||
);
|
||||
expect(moexClient.searchSecurities).toHaveBeenCalledWith('SbEr');
|
||||
expect(moexSecurities.searchSecurities).toHaveBeenCalledWith('SbEr');
|
||||
});
|
||||
|
||||
it('filters by type and applies limit without live MOEX dependency', async () => {
|
||||
@ -169,6 +169,6 @@ describe('SecuritiesService', () => {
|
||||
price: null,
|
||||
},
|
||||
]);
|
||||
expect(moexClient.searchSecurities).not.toHaveBeenCalled();
|
||||
expect(moexSecurities.searchSecurities).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { SecurityType } from './dto/search-query.dto';
|
||||
|
||||
@ -16,7 +16,7 @@ export interface SearchResultItem {
|
||||
@Injectable()
|
||||
export class SecuritiesService {
|
||||
constructor(
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexSecurities: MoexSecuritiesClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
@ -25,7 +25,7 @@ export class SecuritiesService {
|
||||
'search',
|
||||
[query.toLowerCase()],
|
||||
async () => {
|
||||
const results = await this.moexClient.searchSecurities(query);
|
||||
const results = await this.moexSecurities.searchSecurities(query);
|
||||
return results
|
||||
.map((s): SearchResultItem | null => {
|
||||
const type =
|
||||
@ -64,7 +64,7 @@ export class SecuritiesService {
|
||||
|
||||
async getShareBrief(secid: string): Promise<SearchResultItem | null> {
|
||||
try {
|
||||
const desc = await this.moexClient.getSecurityDescription(secid);
|
||||
const desc = await this.moexSecurities.getSecurityDescription(secid);
|
||||
if (!desc) return null;
|
||||
return {
|
||||
secid: desc.secid,
|
||||
|
||||
@ -19,8 +19,7 @@ export class SharesController {
|
||||
@ApiOperation({ summary: 'Получить спецификацию акции' })
|
||||
@ApiOkResponse({ type: ShareEnvelopeDto })
|
||||
async getShare(@Param('secid') secid: string) {
|
||||
const share = await this.sharesService.getShare(secid);
|
||||
return { data: share, meta: { cachedAt: null, fromCache: false } };
|
||||
return this.sharesService.getShare(secid);
|
||||
}
|
||||
|
||||
@Get(':secid/marketdata')
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MoexClientModule } from '../moex-client/moex-client.module';
|
||||
import { SharesController } from './shares.controller';
|
||||
import { SharesService } from './shares.service';
|
||||
|
||||
@Module({
|
||||
imports: [MoexClientModule],
|
||||
controllers: [SharesController],
|
||||
providers: [SharesService],
|
||||
exports: [SharesService],
|
||||
|
||||
@ -1,17 +1,23 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
import { SharesService } from './shares.service';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../moex-client/moex-dividends.client';
|
||||
import { MoexHistoryClient } from '../moex-client/moex-history.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
|
||||
describe('SharesService', () => {
|
||||
let service: SharesService;
|
||||
let moexClient: Pick<MoexClientService, 'getSecurityDescription' | 'getShareMarketData'>;
|
||||
let moexSecurities: Pick<MoexSecuritiesClient, 'getSecurityDescription'>;
|
||||
let moexMarketData: Pick<MoexMarketDataClient, 'getShareMarketData'>;
|
||||
let cache: Pick<CacheService, 'getOrFetch'>;
|
||||
|
||||
beforeEach(async () => {
|
||||
moexClient = {
|
||||
moexSecurities = {
|
||||
getSecurityDescription: vi.fn(),
|
||||
};
|
||||
moexMarketData = {
|
||||
getShareMarketData: vi.fn(),
|
||||
};
|
||||
cache = {
|
||||
@ -25,7 +31,10 @@ describe('SharesService', () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
SharesService,
|
||||
{ provide: MoexClientService, useValue: moexClient },
|
||||
{ provide: MoexSecuritiesClient, useValue: moexSecurities },
|
||||
{ provide: MoexMarketDataClient, useValue: moexMarketData },
|
||||
{ provide: MoexDividendsClient, useValue: { getDividends: vi.fn() } },
|
||||
{ provide: MoexHistoryClient, useValue: { getHistory: vi.fn() } },
|
||||
{ provide: CacheService, useValue: cache },
|
||||
],
|
||||
}).compile();
|
||||
@ -34,7 +43,7 @@ describe('SharesService', () => {
|
||||
});
|
||||
|
||||
it('returns normalized SBER share spec and market data without live MOEX dependency', async () => {
|
||||
vi.mocked(moexClient.getSecurityDescription).mockResolvedValue({
|
||||
vi.mocked(moexSecurities.getSecurityDescription).mockResolvedValue({
|
||||
secid: 'SBER',
|
||||
isin: 'RU0009029540',
|
||||
name: 'Сбербанк России ПАО ао',
|
||||
@ -52,7 +61,7 @@ describe('SharesService', () => {
|
||||
morningSession: true,
|
||||
eveningSession: true,
|
||||
});
|
||||
vi.mocked(moexClient.getShareMarketData).mockResolvedValue({
|
||||
vi.mocked(moexMarketData.getShareMarketData).mockResolvedValue({
|
||||
secid: 'SBER',
|
||||
boardid: 'TQBR',
|
||||
shortName: 'Сбербанк',
|
||||
@ -75,15 +84,15 @@ describe('SharesService', () => {
|
||||
|
||||
const result = await service.getShare('SBER');
|
||||
|
||||
expect(moexClient.getSecurityDescription).toHaveBeenCalledWith('SBER');
|
||||
expect(moexSecurities.getSecurityDescription).toHaveBeenCalledWith('SBER');
|
||||
expect(cache.getOrFetch).toHaveBeenCalledWith(
|
||||
'marketdata',
|
||||
['shares', 'SBER'],
|
||||
expect.any(Function),
|
||||
'marketDataTtl',
|
||||
);
|
||||
expect(moexClient.getShareMarketData).toHaveBeenCalledWith('SBER');
|
||||
expect(result).toMatchObject({
|
||||
expect(moexMarketData.getShareMarketData).toHaveBeenCalledWith('SBER');
|
||||
expect(result.data).toMatchObject({
|
||||
secid: 'SBER',
|
||||
isin: 'RU0009029540',
|
||||
name: 'Сбербанк России ПАО ао',
|
||||
@ -106,11 +115,11 @@ describe('SharesService', () => {
|
||||
issueCapitalization: 6900000000000,
|
||||
},
|
||||
});
|
||||
expect(result.marketData.updatedAt).toMatch(/T18:45:00$/);
|
||||
expect(result.data.marketData.updatedAt).toMatch(/T18:45:00$/);
|
||||
});
|
||||
|
||||
it('throws NotFoundException for non-share security', async () => {
|
||||
vi.mocked(moexClient.getSecurityDescription).mockResolvedValue({
|
||||
it('throws EntityNotFoundException for non-share security', async () => {
|
||||
vi.mocked(moexSecurities.getSecurityDescription).mockResolvedValue({
|
||||
secid: 'SU26238RMFS5',
|
||||
isin: 'RU000A1038V6',
|
||||
name: 'ОФЗ 26238',
|
||||
@ -129,7 +138,7 @@ describe('SharesService', () => {
|
||||
eveningSession: false,
|
||||
});
|
||||
|
||||
await expect(service.getShare('SU26238RMFS5')).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.getShare('SU26238RMFS5')).rejects.toBeInstanceOf(EntityNotFoundException);
|
||||
expect(cache.getOrFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,16 +1,24 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { MoexClientService } from '../moex-client/moex-client.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MoexSecuritiesClient } from '../moex-client/moex-securities.client';
|
||||
import { MoexMarketDataClient } from '../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../moex-client/moex-dividends.client';
|
||||
import { MoexHistoryClient } from '../moex-client/moex-history.client';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { ApiEnvelopePayload } from '../../common/dto/api-response.dto';
|
||||
import { EntityNotFoundException } from '../../common/exceptions/entity-not-found.exception';
|
||||
|
||||
@Injectable()
|
||||
export class SharesService {
|
||||
constructor(
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexSecurities: MoexSecuritiesClient,
|
||||
private readonly moexMarketData: MoexMarketDataClient,
|
||||
private readonly moexDividends: MoexDividendsClient,
|
||||
private readonly moexHistory: MoexHistoryClient,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
async getShare(secid: string) {
|
||||
const desc = await this.moexClient.getSecurityDescription(secid);
|
||||
const desc = await this.moexSecurities.getSecurityDescription(secid);
|
||||
if (
|
||||
!desc ||
|
||||
!(
|
||||
@ -19,13 +27,17 @@ export class SharesService {
|
||||
desc.type === 'preferred_share'
|
||||
)
|
||||
) {
|
||||
throw new NotFoundException(`Share ${secid} not found`);
|
||||
throw new EntityNotFoundException('Share', secid);
|
||||
}
|
||||
|
||||
const { data: marketData } = await this.cache.getOrFetch(
|
||||
const {
|
||||
data: marketData,
|
||||
fromCache,
|
||||
cachedAt,
|
||||
} = await this.cache.getOrFetch(
|
||||
'marketdata',
|
||||
['shares', secid],
|
||||
() => this.moexClient.getShareMarketData(secid),
|
||||
() => this.moexMarketData.getShareMarketData(secid),
|
||||
'marketDataTtl',
|
||||
);
|
||||
|
||||
@ -33,32 +45,36 @@ export class SharesService {
|
||||
const change = marketData?.lastChange ?? 0;
|
||||
const changePercent = marketData?.lastChangePrcnt ?? 0;
|
||||
|
||||
return {
|
||||
secid: desc.secid,
|
||||
isin: desc.isin,
|
||||
name: desc.name,
|
||||
shortName: desc.shortName,
|
||||
latName: desc.latName,
|
||||
listLevel: desc.listLevel,
|
||||
issueSize: desc.issueSize,
|
||||
faceValue: desc.faceValue,
|
||||
faceUnit: desc.faceUnit === 'SUR' ? 'RUB' : desc.faceUnit,
|
||||
type: desc.type,
|
||||
marketData: {
|
||||
price: price ?? 0,
|
||||
change,
|
||||
changePercent,
|
||||
open: marketData?.open ?? 0,
|
||||
high: marketData?.high ?? null,
|
||||
low: marketData?.low ?? null,
|
||||
volume: marketData?.volume ?? 0,
|
||||
value: marketData?.value ?? 0,
|
||||
issueCapitalization: marketData?.issueCapitalization ?? null,
|
||||
updatedAt: marketData?.updateTime
|
||||
? new Date().toISOString().split('T')[0] + 'T' + marketData.updateTime
|
||||
: new Date().toISOString(),
|
||||
return new ApiEnvelopePayload(
|
||||
{
|
||||
secid: desc.secid,
|
||||
isin: desc.isin,
|
||||
name: desc.name,
|
||||
shortName: desc.shortName,
|
||||
latName: desc.latName,
|
||||
listLevel: desc.listLevel,
|
||||
issueSize: desc.issueSize,
|
||||
faceValue: desc.faceValue,
|
||||
faceUnit: desc.faceUnit === 'SUR' ? 'RUB' : desc.faceUnit,
|
||||
type: desc.type,
|
||||
marketData: {
|
||||
price: price ?? 0,
|
||||
change,
|
||||
changePercent,
|
||||
open: marketData?.open ?? 0,
|
||||
high: marketData?.high ?? null,
|
||||
low: marketData?.low ?? null,
|
||||
volume: marketData?.volume ?? 0,
|
||||
value: marketData?.value ?? 0,
|
||||
issueCapitalization: marketData?.issueCapitalization ?? null,
|
||||
updatedAt: marketData?.updateTime
|
||||
? new Date().toISOString().split('T')[0] + 'T' + marketData.updateTime
|
||||
: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
|
||||
async getMarketData(secid: string) {
|
||||
@ -69,16 +85,16 @@ export class SharesService {
|
||||
} = await this.cache.getOrFetch(
|
||||
'marketdata',
|
||||
['shares', secid],
|
||||
() => this.moexClient.getShareMarketData(secid),
|
||||
() => this.moexMarketData.getShareMarketData(secid),
|
||||
'marketDataTtl',
|
||||
);
|
||||
|
||||
if (!marketData) {
|
||||
throw new NotFoundException(`Market data for ${secid} not found`);
|
||||
throw new EntityNotFoundException('MarketData', secid);
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
return new ApiEnvelopePayload(
|
||||
{
|
||||
price: marketData.last ?? 0,
|
||||
change: marketData.lastChange ?? 0,
|
||||
changePercent: marketData.lastChangePrcnt ?? 0,
|
||||
@ -92,38 +108,40 @@ export class SharesService {
|
||||
? new Date().toISOString().split('T')[0] + 'T' + marketData.updateTime
|
||||
: new Date().toISOString(),
|
||||
},
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
|
||||
async getDividends(secid: string) {
|
||||
const { data, fromCache, cachedAt } = await this.cache.getOrFetch(
|
||||
'dividends',
|
||||
[secid],
|
||||
() => this.moexClient.getDividends(secid),
|
||||
() => this.moexDividends.getDividends(secid),
|
||||
'dividendsTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: data.map((d) => ({
|
||||
return new ApiEnvelopePayload(
|
||||
data.map((d) => ({
|
||||
registryCloseDate: d.registryCloseDate,
|
||||
value: d.value,
|
||||
currency: d.currencyId,
|
||||
})),
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
|
||||
async getHistory(secid: string, from: string, till: string) {
|
||||
const { data, fromCache, cachedAt } = await this.cache.getOrFetch(
|
||||
'history',
|
||||
['shares', secid, from, till],
|
||||
() => this.moexClient.getHistory(secid, from, till),
|
||||
() => this.moexHistory.getHistory(secid, from, till),
|
||||
'historyTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: data.map((h) => ({
|
||||
return new ApiEnvelopePayload(
|
||||
data.map((h) => ({
|
||||
date: h.tradeDate,
|
||||
open: h.open ?? 0,
|
||||
high: h.high ?? 0,
|
||||
@ -132,7 +150,8 @@ export class SharesService {
|
||||
volume: h.volume,
|
||||
value: h.value,
|
||||
})),
|
||||
meta: { fromCache, cachedAt },
|
||||
};
|
||||
fromCache,
|
||||
cachedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,6 +19,12 @@ export class BrokerAnalyticsDto {
|
||||
@ApiProperty()
|
||||
totalReceived!: number;
|
||||
|
||||
@ApiProperty()
|
||||
totalFees!: number;
|
||||
|
||||
@ApiProperty()
|
||||
totalTaxesPaid!: number;
|
||||
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
totalReturnPercent!: number | null;
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ApiResponseMeta } from '../../../common/dto/api-response.dto';
|
||||
import { BrokerAccountResponseDto } from './broker-account-response.dto';
|
||||
import { BrokerEventsDataDto } from './broker-events-response.dto';
|
||||
import { BrokerOperationSyncResponseDto } from './broker-operation-sync-query.dto';
|
||||
@ -6,67 +7,68 @@ import { BrokerOperationsPageResponseDto } from './broker-operation-response.dto
|
||||
import { BrokerPositionsPageResponseDto } from './broker-positions-page-response.dto';
|
||||
import { BrokerPortfolioResponseDto } from './broker-portfolio-response.dto';
|
||||
import { BrokerAnalyticsDto } from './broker-analytics-response.dto';
|
||||
|
||||
export class BrokerResponseMetaDto {
|
||||
@ApiProperty({ nullable: true })
|
||||
cachedAt!: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
fromCache!: boolean;
|
||||
}
|
||||
import { BrokerPortfolioHistoryDataDto } from './broker-portfolio-history-response.dto';
|
||||
|
||||
export class BrokerAccountsEnvelopeDto {
|
||||
@ApiProperty({ type: [BrokerAccountResponseDto] })
|
||||
data!: BrokerAccountResponseDto[];
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerPortfolioEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerPortfolioResponseDto })
|
||||
data!: BrokerPortfolioResponseDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerOperationsEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerOperationsPageResponseDto })
|
||||
data!: BrokerOperationsPageResponseDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerPositionsEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerPositionsPageResponseDto })
|
||||
data!: BrokerPositionsPageResponseDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerOperationSyncEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerOperationSyncResponseDto })
|
||||
data!: BrokerOperationSyncResponseDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerAnalyticsEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerAnalyticsDto })
|
||||
data!: BrokerAnalyticsDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerEventsEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerEventsDataDto })
|
||||
data!: BrokerEventsDataDto;
|
||||
|
||||
@ApiProperty({ type: BrokerResponseMetaDto })
|
||||
meta!: BrokerResponseMetaDto;
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
export class BrokerPortfolioHistoryEnvelopeDto {
|
||||
@ApiProperty({ type: BrokerPortfolioHistoryDataDto })
|
||||
data!: BrokerPortfolioHistoryDataDto;
|
||||
|
||||
@ApiProperty({ type: ApiResponseMeta })
|
||||
meta!: ApiResponseMeta;
|
||||
}
|
||||
|
||||
@ -40,4 +40,9 @@ export class BrokerOperationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
state?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Comma-separated category filter: trade,income,tax,fee,transfer,other' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categories?: string;
|
||||
}
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { BrokerMoneyDto } from './broker-money.dto';
|
||||
|
||||
export class BrokerPortfolioHistoryPointDto {
|
||||
@ApiProperty()
|
||||
month!: string;
|
||||
|
||||
@ApiProperty()
|
||||
label!: string;
|
||||
|
||||
@ApiProperty({ type: BrokerMoneyDto })
|
||||
value!: BrokerMoneyDto;
|
||||
}
|
||||
|
||||
export class BrokerPortfolioHistoryDataDto {
|
||||
@ApiProperty()
|
||||
accountId!: string;
|
||||
|
||||
@ApiProperty({ type: [BrokerPortfolioHistoryPointDto] })
|
||||
points!: BrokerPortfolioHistoryPointDto[];
|
||||
|
||||
@ApiProperty()
|
||||
asOf!: string;
|
||||
}
|
||||
@ -4,7 +4,7 @@ import { CacheService } from '../../cache/cache.service';
|
||||
|
||||
describe('BrokerAccountsService', () => {
|
||||
const client = {
|
||||
getServiceClient: vi.fn(),
|
||||
getUsersClient: vi.fn(),
|
||||
callUnary: vi.fn(),
|
||||
} as unknown as TBankClientService;
|
||||
const cache = {
|
||||
@ -23,7 +23,7 @@ describe('BrokerAccountsService', () => {
|
||||
cachedAt: '2026-06-16T02:30:00.000Z',
|
||||
}),
|
||||
);
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({ getAccounts: vi.fn() } as any);
|
||||
vi.mocked(client.getUsersClient).mockReturnValue({ getAccounts: vi.fn() } as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValue({
|
||||
accounts: [
|
||||
{ id: '1', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Broker', status: 'ACCOUNT_STATUS_OPEN' },
|
||||
@ -38,7 +38,7 @@ describe('BrokerAccountsService', () => {
|
||||
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.data.map((account) => account.type)).toEqual(['brokerage', 'iis']);
|
||||
expect(result.meta.fromCache).toBe(false);
|
||||
expect(result.fromCache).toBe(false);
|
||||
expect(cache.getOrFetch).toHaveBeenCalledWith(
|
||||
'tbank:accounts',
|
||||
['open-brokerage-iis'],
|
||||
|
||||
@ -5,6 +5,7 @@ import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import type { BrokerAccount } from '../types/broker.types';
|
||||
import type { TBankAccountsResponse } from '../types/tbank-proto.types';
|
||||
import { TBankClientService } from './tbank-client.service';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BrokerAccountsService {
|
||||
@ -13,10 +14,7 @@ export class BrokerAccountsService {
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
|
||||
async findAll(): Promise<{
|
||||
data: BrokerAccount[];
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
async findAll(): Promise<ApiEnvelopePayload<BrokerAccount[]>> {
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
TBANK_CACHE_KEYS.accounts,
|
||||
['open-brokerage-iis'],
|
||||
@ -24,10 +22,7 @@ export class BrokerAccountsService {
|
||||
'tbankAccountsTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
async findById(accountId: string): Promise<BrokerAccount | null> {
|
||||
@ -37,9 +32,9 @@ export class BrokerAccountsService {
|
||||
}
|
||||
|
||||
private async fetchAccounts(): Promise<BrokerAccount[]> {
|
||||
const usersClient = this.tbankClient.getServiceClient('UsersService') as any;
|
||||
const usersClient = this.tbankClient.getUsersClient();
|
||||
const response = await this.tbankClient.callUnary<
|
||||
Record<string, string>,
|
||||
{ status: string },
|
||||
TBankAccountsResponse
|
||||
>(
|
||||
'UsersService/GetAccounts',
|
||||
|
||||
@ -1,12 +1,16 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerAnalyticsService } from './broker-analytics.service';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TBankClientService } from './tbank-client.service';
|
||||
import type { TBankOperationsByCursorResponse, TBankPortfolioResponse, TBankOperationItem } from '../types/tbank-proto.types';
|
||||
|
||||
describe('BrokerAnalyticsService', () => {
|
||||
const accounts = { findById: vi.fn() } as unknown as BrokerAccountsService;
|
||||
const prisma = { brokerOperation: { findMany: vi.fn() } } as unknown as PrismaService;
|
||||
const tbankClient = {
|
||||
getOperationsClient: vi.fn(),
|
||||
callUnary: vi.fn(),
|
||||
} as unknown as TBankClientService;
|
||||
const cache = { getOrFetch: vi.fn() } as unknown as CacheService;
|
||||
|
||||
const acc1 = {
|
||||
@ -18,6 +22,8 @@ describe('BrokerAnalyticsService', () => {
|
||||
accessLevel: null,
|
||||
};
|
||||
|
||||
const mockClient = { getPortfolio: vi.fn(), getOperationsByCursor: vi.fn() };
|
||||
|
||||
function mockCachePassthrough() {
|
||||
vi.mocked(cache.getOrFetch).mockImplementation(
|
||||
async (_prefix: string, _parts: string[], fetchFn: () => Promise<unknown>) => ({
|
||||
@ -28,27 +34,55 @@ describe('BrokerAnalyticsService', () => {
|
||||
);
|
||||
}
|
||||
|
||||
function makeOp(type: string, value: number, state?: string | null) {
|
||||
return { type, payment: JSON.stringify({ value, currency: 'RUB' }), state } as any;
|
||||
function mockPortfolio(expectedYield?: { units?: number | string; nano?: number }): TBankPortfolioResponse {
|
||||
const response: TBankPortfolioResponse = { accountId: 'acc-1' };
|
||||
if (expectedYield) response.expectedYield = expectedYield;
|
||||
return response;
|
||||
}
|
||||
|
||||
function makeItem(type: string, value: number, state = 'OPERATION_STATE_EXECUTED'): TBankOperationItem {
|
||||
return {
|
||||
type,
|
||||
payment: { currency: 'RUB', units: Math.floor(Math.abs(value)), nano: Math.round((Math.abs(value) % 1) * 1e9) },
|
||||
state,
|
||||
id: `${type}-${value}`,
|
||||
cursor: '',
|
||||
brokerAccountId: 'acc-1',
|
||||
};
|
||||
}
|
||||
|
||||
function mockOpsResponse(items: TBankOperationItem[], hasNext = false, nextCursor = ''): TBankOperationsByCursorResponse {
|
||||
return { items, hasNext, nextCursor };
|
||||
}
|
||||
|
||||
function setupMocks(ops: TBankOperationItem[], portfolio?: TBankPortfolioResponse) {
|
||||
vi.mocked(tbankClient.callUnary).mockImplementation(
|
||||
async (label: string) => {
|
||||
if (label.includes('GetPortfolio')) return (portfolio ?? mockPortfolio()) as any;
|
||||
if (label.includes('GetOperationsByCursor')) return mockOpsResponse(ops) as any;
|
||||
throw new Error(`Unexpected call: ${label}`);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(tbankClient.getOperationsClient).mockReturnValue(mockClient as any);
|
||||
});
|
||||
|
||||
it('throws 404 for missing account', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(null);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
await expect(service.getAnalytics('missing')).rejects.toThrow(NotFoundException);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
await expect(service.getAnalytics('missing')).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('returns zeros for account with no operations', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([]);
|
||||
setupMocks([]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data).toEqual({
|
||||
@ -59,6 +93,8 @@ describe('BrokerAnalyticsService', () => {
|
||||
totalCoupons: 0,
|
||||
totalReceived: 0,
|
||||
totalReturnPercent: null,
|
||||
totalFees: 0,
|
||||
totalTaxesPaid: 0,
|
||||
currency: 'RUB',
|
||||
});
|
||||
});
|
||||
@ -66,17 +102,17 @@ describe('BrokerAnalyticsService', () => {
|
||||
it('aggregates deposit types correctly', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_INPUT', 1000),
|
||||
makeOp('OPERATION_TYPE_INPUT_SWIFT', 500),
|
||||
makeOp('OPERATION_TYPE_INP_MULTI', 200),
|
||||
makeOp('OPERATION_TYPE_OVER_PLACEMENT', 300),
|
||||
makeOp('OPERATION_TYPE_TRANS_IIS_BS', 100),
|
||||
makeOp('OPERATION_TYPE_TRANS_BS_BS', 50),
|
||||
makeOp('OPERATION_TYPE_INPUT_ACQUIRING', 150),
|
||||
setupMocks([
|
||||
makeItem('OPERATION_TYPE_INPUT', 1000),
|
||||
makeItem('OPERATION_TYPE_INPUT_SWIFT', 500),
|
||||
makeItem('OPERATION_TYPE_INP_MULTI', 200),
|
||||
makeItem('OPERATION_TYPE_OVER_PLACEMENT', 300),
|
||||
makeItem('OPERATION_TYPE_TRANS_IIS_BS', 100),
|
||||
makeItem('OPERATION_TYPE_TRANS_BS_BS', 50),
|
||||
makeItem('OPERATION_TYPE_INPUT_ACQUIRING', 150),
|
||||
]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDeposits).toBe(2300);
|
||||
@ -87,15 +123,15 @@ describe('BrokerAnalyticsService', () => {
|
||||
it('aggregates withdrawal types with absolute value', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_OUTPUT', -500),
|
||||
makeOp('OPERATION_TYPE_OUTPUT_SWIFT', -200),
|
||||
makeOp('OPERATION_TYPE_OUTPUT_ACQUIRING', -100),
|
||||
makeOp('OPERATION_TYPE_OUT_MULTI', -50),
|
||||
makeOp('OPERATION_TYPE_INPUT', 1000),
|
||||
setupMocks([
|
||||
makeItem('OPERATION_TYPE_OUTPUT', -500),
|
||||
makeItem('OPERATION_TYPE_OUTPUT_SWIFT', -200),
|
||||
makeItem('OPERATION_TYPE_OUTPUT_ACQUIRING', -100),
|
||||
makeItem('OPERATION_TYPE_OUT_MULTI', -50),
|
||||
makeItem('OPERATION_TYPE_INPUT', 1000),
|
||||
]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDeposits).toBe(1000);
|
||||
@ -106,14 +142,14 @@ describe('BrokerAnalyticsService', () => {
|
||||
it('aggregates dividend and coupon types', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_DIVIDEND', 300),
|
||||
makeOp('OPERATION_TYPE_DIV_EXT', 150),
|
||||
makeOp('OPERATION_TYPE_COUPON', 75),
|
||||
makeOp('OPERATION_TYPE_COUPON', 25),
|
||||
setupMocks([
|
||||
makeItem('OPERATION_TYPE_DIVIDEND', 300),
|
||||
makeItem('OPERATION_TYPE_DIV_EXT', 150),
|
||||
makeItem('OPERATION_TYPE_COUPON', 75),
|
||||
makeItem('OPERATION_TYPE_COUPON', 25),
|
||||
]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDividends).toBe(450);
|
||||
@ -121,82 +157,64 @@ describe('BrokerAnalyticsService', () => {
|
||||
expect(result.data.totalReceived).toBe(550);
|
||||
});
|
||||
|
||||
it('calculates totalReturnPercent correctly', async () => {
|
||||
it('uses expectedYield from portfolio for totalReturnPercent', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_INPUT', 10000),
|
||||
makeOp('OPERATION_TYPE_DIVIDEND', 500),
|
||||
makeOp('OPERATION_TYPE_COUPON', 200),
|
||||
]);
|
||||
setupMocks(
|
||||
[
|
||||
makeItem('OPERATION_TYPE_INPUT', 10000),
|
||||
makeItem('OPERATION_TYPE_DIVIDEND', 500),
|
||||
makeItem('OPERATION_TYPE_COUPON', 200),
|
||||
],
|
||||
mockPortfolio({ units: 7, nano: 0 }),
|
||||
);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.netInvested).toBe(10000);
|
||||
expect(result.data.totalReceived).toBe(700);
|
||||
expect(result.data.totalReturnPercent).toBe(7);
|
||||
});
|
||||
|
||||
it('returns null totalReturnPercent when netInvested <= 0', async () => {
|
||||
it('returns null totalReturnPercent when portfolio has no expectedYield', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_OUTPUT', -500),
|
||||
makeOp('OPERATION_TYPE_DIVIDEND', 100),
|
||||
]);
|
||||
setupMocks([makeItem('OPERATION_TYPE_OUTPUT', -500)]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.netInvested).toBe(-500);
|
||||
expect(result.data.totalReturnPercent).toBeNull();
|
||||
});
|
||||
|
||||
it('handles malformed payment JSON gracefully', async () => {
|
||||
it('aggregates fee and tax categories from operations', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
{ type: 'OPERATION_TYPE_INPUT', payment: 'invalid-json', state: 'OPERATION_STATE_EXECUTED' },
|
||||
{ type: 'OPERATION_TYPE_INPUT', payment: JSON.stringify({ value: 500, currency: 'RUB' }), state: 'OPERATION_STATE_EXECUTED' },
|
||||
] as any);
|
||||
setupMocks([
|
||||
makeItem('OPERATION_TYPE_SERVICE_FEE', -100),
|
||||
makeItem('OPERATION_TYPE_BROKER_FEE', -50),
|
||||
makeItem('OPERATION_TYPE_TAX', -200),
|
||||
makeItem('OPERATION_TYPE_DIVIDEND_TAX', -30),
|
||||
makeItem('OPERATION_TYPE_INPUT', 1000),
|
||||
]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDeposits).toBe(500);
|
||||
});
|
||||
|
||||
it('ignores non-executed and non-null state operations', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
await service.getAnalytics('acc-1');
|
||||
|
||||
expect(prisma.brokerOperation.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
accountId: 'acc-1',
|
||||
type: { in: expect.any(Array) },
|
||||
payment: { not: null },
|
||||
OR: [
|
||||
{ state: 'OPERATION_STATE_EXECUTED' },
|
||||
{ state: null },
|
||||
],
|
||||
},
|
||||
select: { type: true, payment: true },
|
||||
});
|
||||
expect(result.data.totalDeposits).toBe(1000);
|
||||
expect(result.data.totalFees).toBe(150);
|
||||
expect(result.data.totalTaxesPaid).toBe(230);
|
||||
expect(result.data.netInvested).toBe(1000);
|
||||
});
|
||||
|
||||
it('rounds all monetary values to 2 decimal places', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
vi.mocked(prisma.brokerOperation.findMany).mockResolvedValue([
|
||||
makeOp('OPERATION_TYPE_INPUT', 100.336),
|
||||
makeOp('OPERATION_TYPE_DIVIDEND', 50.789),
|
||||
setupMocks([
|
||||
makeItem('OPERATION_TYPE_INPUT', 100.336),
|
||||
makeItem('OPERATION_TYPE_DIVIDEND', 50.789),
|
||||
]);
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDeposits).toBe(100.34);
|
||||
@ -216,17 +234,47 @@ describe('BrokerAnalyticsService', () => {
|
||||
totalCoupons: 0,
|
||||
totalReceived: 0,
|
||||
totalReturnPercent: null,
|
||||
totalFees: 0,
|
||||
totalTaxesPaid: 0,
|
||||
currency: 'RUB',
|
||||
},
|
||||
fromCache: true,
|
||||
cachedAt: '2026-06-24T10:00:00.000Z',
|
||||
});
|
||||
|
||||
const service = new BrokerAnalyticsService(prisma, accounts, cache);
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.netInvested).toBe(1000);
|
||||
expect(result.meta.fromCache).toBe(true);
|
||||
expect(result.meta.cachedAt).toBe('2026-06-24T10:00:00.000Z');
|
||||
expect(result.fromCache).toBe(true);
|
||||
expect(result.cachedAt).toBe('2026-06-24T10:00:00.000Z');
|
||||
});
|
||||
|
||||
it('paginates through multiple pages of operations', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(acc1);
|
||||
mockCachePassthrough();
|
||||
|
||||
let callCount = 0;
|
||||
vi.mocked(tbankClient.callUnary).mockImplementation(
|
||||
async (label: string) => {
|
||||
if (label.includes('GetPortfolio')) return mockPortfolio({ units: 5, nano: 0 }) as any;
|
||||
if (label.includes('GetOperationsByCursor')) {
|
||||
callCount++;
|
||||
if (callCount === 1) {
|
||||
return mockOpsResponse([makeItem('OPERATION_TYPE_INPUT', 1000)], true, 'cursor-1') as any;
|
||||
}
|
||||
return mockOpsResponse([makeItem('OPERATION_TYPE_DIVIDEND', 500)], false, '') as any;
|
||||
}
|
||||
throw new Error(`Unexpected call: ${label}`);
|
||||
},
|
||||
);
|
||||
|
||||
const service = new BrokerAnalyticsService(accounts, tbankClient, cache);
|
||||
const result = await service.getAnalytics('acc-1');
|
||||
|
||||
expect(result.data.totalDeposits).toBe(1000);
|
||||
expect(result.data.totalDividends).toBe(500);
|
||||
expect(result.data.totalReceived).toBe(500);
|
||||
expect(callCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,9 +1,14 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { BrokerAnalyticsDto } from '../dto/broker-analytics-response.dto';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import { BrokerAnalyticsDto } from '../dto/broker-analytics-response.dto';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { TBankClientService, type TBankPortfolioRequest } from './tbank-client.service';
|
||||
import type { BrokerOperation } from '../types/broker.types';
|
||||
import { mapOperationsPage } from '../mappers/operation.mapper';
|
||||
import type { TBankOperationsByCursorResponse, TBankPortfolioResponse } from '../types/tbank-proto.types';
|
||||
|
||||
const DEPOSIT_TYPES = new Set([
|
||||
'OPERATION_TYPE_INPUT',
|
||||
@ -26,27 +31,21 @@ const DIVIDEND_TYPES = new Set(['OPERATION_TYPE_DIVIDEND', 'OPERATION_TYPE_DIV_E
|
||||
|
||||
const COUPON_TYPES = new Set(['OPERATION_TYPE_COUPON']);
|
||||
|
||||
const ANALYTICS_TYPES = new Set([
|
||||
...DEPOSIT_TYPES,
|
||||
...WITHDRAWAL_TYPES,
|
||||
...DIVIDEND_TYPES,
|
||||
...COUPON_TYPES,
|
||||
]);
|
||||
const MAX_FETCH_PAGES = 50;
|
||||
|
||||
@Injectable()
|
||||
export class BrokerAnalyticsService {
|
||||
private readonly logger = new Logger(BrokerAnalyticsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly accountsService: BrokerAccountsService,
|
||||
private readonly tbankClient: TBankClientService,
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
|
||||
async getAnalytics(accountId: string): Promise<{
|
||||
data: BrokerAnalyticsDto;
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
async getAnalytics(accountId: string): Promise<ApiEnvelopePayload<BrokerAnalyticsDto>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new NotFoundException('Broker account not found');
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
TBANK_CACHE_KEYS.analytics,
|
||||
@ -55,41 +54,30 @@ export class BrokerAnalyticsService {
|
||||
'tbankAnalyticsTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
private async computeAnalytics(accountId: string): Promise<BrokerAnalyticsDto> {
|
||||
const operations = await this.prisma.brokerOperation.findMany({
|
||||
where: {
|
||||
accountId,
|
||||
type: { in: Array.from(ANALYTICS_TYPES) },
|
||||
payment: { not: null },
|
||||
OR: [
|
||||
{ state: 'OPERATION_STATE_EXECUTED' },
|
||||
{ state: null },
|
||||
],
|
||||
},
|
||||
select: { type: true, payment: true },
|
||||
});
|
||||
const [portfolio, allOperations] = await Promise.all([
|
||||
this.fetchPortfolio(accountId),
|
||||
this.fetchAllOperations(accountId),
|
||||
]);
|
||||
|
||||
let totalDeposits = 0;
|
||||
let totalWithdrawn = 0;
|
||||
let totalDividends = 0;
|
||||
let totalCoupons = 0;
|
||||
let totalFees = 0;
|
||||
let totalTaxesPaid = 0;
|
||||
|
||||
for (const op of operations) {
|
||||
let value = 0;
|
||||
try {
|
||||
const payment = JSON.parse(op.payment!);
|
||||
value = payment.value ?? 0;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const op of allOperations) {
|
||||
const value = op.payment?.value ?? 0;
|
||||
|
||||
if (DEPOSIT_TYPES.has(op.type)) {
|
||||
if (op.category === 'fee') {
|
||||
totalFees += Math.abs(value);
|
||||
} else if (op.category === 'tax') {
|
||||
totalTaxesPaid += Math.abs(value);
|
||||
} else if (DEPOSIT_TYPES.has(op.type)) {
|
||||
totalDeposits += value;
|
||||
} else if (WITHDRAWAL_TYPES.has(op.type)) {
|
||||
totalWithdrawn += Math.abs(value);
|
||||
@ -102,8 +90,11 @@ export class BrokerAnalyticsService {
|
||||
|
||||
const netInvested = totalDeposits - totalWithdrawn;
|
||||
const totalReceived = totalDividends + totalCoupons;
|
||||
const totalReturnPercent =
|
||||
netInvested > 0 ? Math.round((totalReceived / netInvested) * 10000) / 100 : null;
|
||||
|
||||
const portfolioYield = portfolio.expectedYield;
|
||||
const expectedYieldPercent = portfolioYield
|
||||
? Math.round((Number(portfolioYield.units ?? 0) + (portfolioYield.nano ?? 0) / 1e9) * 100) / 100
|
||||
: null;
|
||||
|
||||
return {
|
||||
totalDeposits: Math.round(totalDeposits * 100) / 100,
|
||||
@ -112,8 +103,66 @@ export class BrokerAnalyticsService {
|
||||
totalDividends: Math.round(totalDividends * 100) / 100,
|
||||
totalCoupons: Math.round(totalCoupons * 100) / 100,
|
||||
totalReceived: Math.round(totalReceived * 100) / 100,
|
||||
totalReturnPercent,
|
||||
totalFees: Math.round(totalFees * 100) / 100,
|
||||
totalTaxesPaid: Math.round(totalTaxesPaid * 100) / 100,
|
||||
totalReturnPercent: expectedYieldPercent,
|
||||
currency: 'RUB',
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchPortfolio(accountId: string): Promise<TBankPortfolioResponse> {
|
||||
const operationsClient = this.tbankClient.getOperationsClient();
|
||||
const response = await this.tbankClient.callUnary<
|
||||
TBankPortfolioRequest,
|
||||
TBankPortfolioResponse
|
||||
>(
|
||||
'OperationsService/GetPortfolio',
|
||||
operationsClient.getPortfolio.bind(operationsClient),
|
||||
{ accountId, currency: 'RUB' },
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private async fetchAllOperations(accountId: string): Promise<BrokerOperation[]> {
|
||||
const allOps: BrokerOperation[] = [];
|
||||
let cursor: string | undefined;
|
||||
let pageCount = 0;
|
||||
|
||||
do {
|
||||
if (pageCount >= MAX_FETCH_PAGES) {
|
||||
this.logger.warn(`Reached max fetch pages (${MAX_FETCH_PAGES}) for account ${accountId}`);
|
||||
break;
|
||||
}
|
||||
|
||||
const request: Record<string, unknown> = {
|
||||
accountId,
|
||||
state: 'OPERATION_STATE_EXECUTED',
|
||||
limit: 1000,
|
||||
withoutCommissions: false,
|
||||
withoutTrades: false,
|
||||
withoutOvernights: false,
|
||||
};
|
||||
|
||||
if (cursor) request.cursor = cursor;
|
||||
|
||||
const operationsClient = this.tbankClient.getOperationsClient();
|
||||
const response = await this.tbankClient.callUnary<
|
||||
Record<string, unknown>,
|
||||
TBankOperationsByCursorResponse
|
||||
>(
|
||||
'OperationsService/GetOperationsByCursor',
|
||||
operationsClient.getOperationsByCursor.bind(operationsClient),
|
||||
request,
|
||||
);
|
||||
|
||||
const page = mapOperationsPage(accountId, response);
|
||||
allOps.push(...page.items);
|
||||
pageCount++;
|
||||
|
||||
cursor = page.hasNext ? (page.nextCursor ?? undefined) : undefined;
|
||||
} while (cursor);
|
||||
|
||||
return allOps;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { MoexClientService } from '../../moex-client/moex-client.service';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { MoexMarketDataClient } from '../../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../../moex-client/moex-dividends.client';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerEventsService } from './broker-events.service';
|
||||
import { BrokerOperationsService } from './broker-operations.service';
|
||||
@ -9,10 +10,8 @@ import { BrokerPortfolioService } from './broker-portfolio.service';
|
||||
describe('BrokerEventsService', () => {
|
||||
const accounts = { findById: vi.fn() } as unknown as BrokerAccountsService;
|
||||
const portfolio = { getPositionsWithInstruments: vi.fn() } as unknown as BrokerPortfolioService;
|
||||
const moex = {
|
||||
getDividends: vi.fn(),
|
||||
getBondPositionDataBatch: vi.fn(),
|
||||
} as unknown as MoexClientService;
|
||||
const moexMarketData = { getBondPositionDataBatch: vi.fn() } as unknown as MoexMarketDataClient;
|
||||
const moexDividends = { getDividends: vi.fn() } as unknown as MoexDividendsClient;
|
||||
const operations = { getOperations: vi.fn() } as unknown as BrokerOperationsService;
|
||||
const cache = { getOrFetch: vi.fn() } as unknown as CacheService;
|
||||
|
||||
@ -42,10 +41,10 @@ describe('BrokerEventsService', () => {
|
||||
it('throws 404 for missing account', async () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(null);
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
await expect(
|
||||
service.getEvents('missing', { from: '2026-06-01', to: '2026-07-01' }),
|
||||
).rejects.toThrow(NotFoundException);
|
||||
).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('returns empty events for account with no positions', async () => {
|
||||
@ -58,10 +57,11 @@ describe('BrokerEventsService', () => {
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-01' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-01', to: '2026-07-01' });
|
||||
|
||||
expect(result.data.items).toEqual([]);
|
||||
@ -86,7 +86,7 @@ describe('BrokerEventsService', () => {
|
||||
],
|
||||
instruments: new Map([['uid-sber', { name: 'Sberbank', currency: 'RUB' }]]),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockResolvedValue([
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValue([
|
||||
{
|
||||
secid: 'SBER',
|
||||
isin: 'RU000A0JS',
|
||||
@ -112,10 +112,11 @@ describe('BrokerEventsService', () => {
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-10' });
|
||||
|
||||
expect(result.data.items).toHaveLength(1);
|
||||
@ -142,7 +143,7 @@ describe('BrokerEventsService', () => {
|
||||
],
|
||||
instruments: new Map([['uid-bond-1', { name: 'OFZ 26248', currency: 'RUB' }]]),
|
||||
});
|
||||
vi.mocked(moex.getBondPositionDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getBondPositionDataBatch).mockResolvedValue([
|
||||
{
|
||||
secid: 'SU26248RMFS4',
|
||||
couponValue: 35.4,
|
||||
@ -166,10 +167,11 @@ describe('BrokerEventsService', () => {
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-10' });
|
||||
|
||||
expect(result.data.items).toHaveLength(3);
|
||||
@ -204,17 +206,18 @@ describe('BrokerEventsService', () => {
|
||||
['uid-2', { name: 'Working' }],
|
||||
]),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockRejectedValueOnce(new Error('MOEX error'));
|
||||
vi.mocked(moex.getDividends).mockResolvedValueOnce([
|
||||
vi.mocked(moexDividends.getDividends).mockRejectedValueOnce(new Error('MOEX error'));
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValueOnce([
|
||||
{ secid: 'GOOD', isin: 'RU', registryCloseDate: '2026-06-25', value: 20, currencyId: 'RUB' },
|
||||
]);
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-10' });
|
||||
|
||||
expect(result.data.items).toHaveLength(1);
|
||||
@ -235,16 +238,17 @@ describe('BrokerEventsService', () => {
|
||||
],
|
||||
instruments: new Map([['uid-1', { name: 'No Amount' }]]),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockResolvedValue([
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValue([
|
||||
{ secid: 'NO_AMT', isin: 'RU', registryCloseDate: '2026-06-25', value: 0, currencyId: 'RUB' },
|
||||
]);
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-10' });
|
||||
|
||||
expect(result.data.items).toHaveLength(1);
|
||||
@ -274,10 +278,10 @@ describe('BrokerEventsService', () => {
|
||||
['uid-2', { name: 'OFZ' }],
|
||||
]),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockResolvedValue([
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValue([
|
||||
{ secid: 'SBER', isin: 'RU1', registryCloseDate: '2026-06-25', value: 30, currencyId: 'RUB' },
|
||||
]);
|
||||
vi.mocked(moex.getBondPositionDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getBondPositionDataBatch).mockResolvedValue([
|
||||
{
|
||||
secid: 'BOND1',
|
||||
couponValue: 50,
|
||||
@ -301,10 +305,11 @@ describe('BrokerEventsService', () => {
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-10' });
|
||||
|
||||
expect(result.data.summary.eventCount).toBe(3);
|
||||
@ -331,7 +336,7 @@ describe('BrokerEventsService', () => {
|
||||
],
|
||||
instruments: new Map([['uid-1', { name: 'Sber' }]]),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockResolvedValue([
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValue([
|
||||
{ secid: 'SBER', isin: 'RU', registryCloseDate: '2026-06-20', value: 10, currencyId: 'RUB' },
|
||||
{ secid: 'SBER', isin: 'RU', registryCloseDate: '2026-07-29', value: 10, currencyId: 'RUB' },
|
||||
{ secid: 'SBER', isin: 'RU', registryCloseDate: '2026-07-30', value: 10, currencyId: 'RUB' },
|
||||
@ -339,10 +344,11 @@ describe('BrokerEventsService', () => {
|
||||
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', { from: '2026-06-20', to: '2026-07-29' });
|
||||
|
||||
expect(result.data.items).toHaveLength(2);
|
||||
@ -370,10 +376,10 @@ describe('BrokerEventsService', () => {
|
||||
],
|
||||
instruments: new Map(),
|
||||
});
|
||||
vi.mocked(moex.getDividends).mockResolvedValue([
|
||||
vi.mocked(moexDividends.getDividends).mockResolvedValue([
|
||||
{ secid: 'SBER', isin: 'RU', registryCloseDate: '2026-06-25', value: 30, currencyId: 'RUB' },
|
||||
]);
|
||||
vi.mocked(moex.getBondPositionDataBatch).mockResolvedValue([
|
||||
vi.mocked(moexMarketData.getBondPositionDataBatch).mockResolvedValue([
|
||||
{
|
||||
secid: 'BOND1',
|
||||
couponValue: 50,
|
||||
@ -396,10 +402,11 @@ describe('BrokerEventsService', () => {
|
||||
]);
|
||||
vi.mocked(operations.getOperations).mockResolvedValue({
|
||||
data: { accountId: 'acc-1', items: [], nextCursor: null, hasNext: false, asOf: '2026-06-20' },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', {
|
||||
from: '2026-06-20',
|
||||
to: '2026-07-10',
|
||||
@ -455,10 +462,11 @@ describe('BrokerEventsService', () => {
|
||||
hasNext: false,
|
||||
asOf: '2026-06-19T00:00:00.000Z',
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerEventsService(accounts, portfolio, moex, operations, cache);
|
||||
const service = new BrokerEventsService(accounts, portfolio, moexMarketData, moexDividends, operations, cache);
|
||||
const result = await service.getEvents('acc-1', {
|
||||
from: '2026-06-15',
|
||||
to: '2026-06-20',
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { MoexClientService } from '../../moex-client/moex-client.service';
|
||||
import { MoexMarketDataClient } from '../../moex-client/moex-market-data.client';
|
||||
import { MoexDividendsClient } from '../../moex-client/moex-dividends.client';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import { mapQuotationToNumber } from '../mappers/money.mapper';
|
||||
import type {
|
||||
@ -44,7 +47,8 @@ export class BrokerEventsService {
|
||||
constructor(
|
||||
private readonly accountsService: BrokerAccountsService,
|
||||
private readonly portfolioService: BrokerPortfolioService,
|
||||
private readonly moexClient: MoexClientService,
|
||||
private readonly moexMarketData: MoexMarketDataClient,
|
||||
private readonly moexDividends: MoexDividendsClient,
|
||||
private readonly operationsService: BrokerOperationsService,
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
@ -52,12 +56,9 @@ export class BrokerEventsService {
|
||||
async getEvents(
|
||||
accountId: string,
|
||||
query: BrokerEventsQuery,
|
||||
): Promise<{
|
||||
data: BrokerEventsData;
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
): Promise<ApiEnvelopePayload<BrokerEventsData>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new NotFoundException('Broker account not found');
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const eventTypes = this.parseEventTypes(query.types);
|
||||
const eventTypeKey = Array.from(eventTypes).join(',');
|
||||
@ -68,10 +69,7 @@ export class BrokerEventsService {
|
||||
'tbankPortfolioTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
private async buildEvents(
|
||||
@ -143,7 +141,7 @@ export class BrokerEventsService {
|
||||
|
||||
let dividends: { registryCloseDate: string; value: number; currencyId: string }[];
|
||||
try {
|
||||
dividends = await this.moexClient.getDividends(ticker);
|
||||
dividends = await this.moexDividends.getDividends(ticker);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@ -203,7 +201,7 @@ export class BrokerEventsService {
|
||||
faceValue: number;
|
||||
}[];
|
||||
try {
|
||||
bondData = await this.moexClient.getBondPositionDataBatch(secids);
|
||||
bondData = await this.moexMarketData.getBondPositionDataBatch(secids);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ export class BrokerInstrumentsService {
|
||||
}
|
||||
|
||||
private async fetchByUid(instrumentUid: string): Promise<TBankInstrument | null> {
|
||||
const instrumentsClient = this.tbankClient.getServiceClient('InstrumentsService') as any;
|
||||
const instrumentsClient = this.tbankClient.getInstrumentsClient();
|
||||
const response = await this.tbankClient.callUnary<
|
||||
{ idType: string; id: string },
|
||||
TBankInstrumentResponse
|
||||
|
||||
@ -48,11 +48,13 @@ describe('BrokerOperationSyncService', () => {
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
data: { accountId: 'acc-1', hasNext: false, nextCursor: null, asOf: 'now', items: [] },
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerOperationSyncService(operations, prisma);
|
||||
@ -115,7 +117,8 @@ describe('BrokerOperationSyncService', () => {
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerOperationSyncService(operations, prisma);
|
||||
@ -142,7 +145,8 @@ describe('BrokerOperationSyncService', () => {
|
||||
asOf: '2026-06-16T00:00:00.000Z',
|
||||
items: [],
|
||||
},
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
fromCache: false,
|
||||
cachedAt: null,
|
||||
});
|
||||
|
||||
const service = new BrokerOperationSyncService(operations, prisma);
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerOperationsService } from './broker-operations.service';
|
||||
import { TBankClientService } from './tbank-client.service';
|
||||
|
||||
describe('BrokerOperationsService', () => {
|
||||
const accounts = { findById: vi.fn() } as unknown as BrokerAccountsService;
|
||||
const client = { getServiceClient: vi.fn(), callUnary: vi.fn() } as unknown as TBankClientService;
|
||||
const client = { getOperationsClient: vi.fn(), callUnary: vi.fn() } as unknown as TBankClientService;
|
||||
const cache = { getOrFetch: vi.fn() } as unknown as CacheService;
|
||||
|
||||
beforeEach(() => {
|
||||
@ -17,7 +17,7 @@ describe('BrokerOperationsService', () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(null);
|
||||
const service = new BrokerOperationsService(accounts, client, cache);
|
||||
|
||||
await expect(service.getOperations('missing', {})).rejects.toThrow(NotFoundException);
|
||||
await expect(service.getOperations('missing', {})).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('builds cursor request and maps operation page', async () => {
|
||||
@ -36,7 +36,7 @@ describe('BrokerOperationsService', () => {
|
||||
cachedAt: null,
|
||||
}),
|
||||
);
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({ getOperationsByCursor: vi.fn() } as any);
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({ getOperationsByCursor: vi.fn() } as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValue({
|
||||
hasNext: false,
|
||||
items: [{ cursor: 'c1', brokerAccountId: 'acc-1', type: 'OPERATION_TYPE_BUY' }],
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
import type { BrokerOperationQueryDto } from '../dto/broker-operation-query.dto';
|
||||
import { mapOperationsPage } from '../mappers/operation.mapper';
|
||||
import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import type { BrokerOperationsPage } from '../types/broker.types';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import type { BrokerOperation, BrokerOperationsPage } from '../types/broker.types';
|
||||
import type { TBankOperationsByCursorResponse } from '../types/tbank-proto.types';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { TBankClientService } from './tbank-client.service';
|
||||
@ -19,12 +21,9 @@ export class BrokerOperationsService {
|
||||
async getOperations(
|
||||
accountId: string,
|
||||
query: BrokerOperationQueryDto,
|
||||
): Promise<{
|
||||
data: BrokerOperationsPage;
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
): Promise<ApiEnvelopePayload<BrokerOperationsPage>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new NotFoundException('Broker account not found');
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const request = this.buildRequest(accountId, query);
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
@ -34,10 +33,20 @@ export class BrokerOperationsService {
|
||||
'tbankOperationsTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
if (query.categories) {
|
||||
const allowedCategories = query.categories
|
||||
.split(',')
|
||||
.map((c) => c.trim() as BrokerOperation['category'])
|
||||
.filter((c) => ['trade', 'income', 'tax', 'fee', 'transfer', 'other'].includes(c));
|
||||
|
||||
if (allowedCategories.length > 0) {
|
||||
result.data.items = result.data.items.filter((item) =>
|
||||
allowedCategories.includes(item.category),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
private buildRequest(accountId: string, query: BrokerOperationQueryDto): Record<string, unknown> {
|
||||
@ -73,7 +82,7 @@ export class BrokerOperationsService {
|
||||
accountId: string,
|
||||
request: Record<string, unknown>,
|
||||
): Promise<BrokerOperationsPage> {
|
||||
const operationsClient = this.tbankClient.getServiceClient('OperationsService') as any;
|
||||
const operationsClient = this.tbankClient.getOperationsClient();
|
||||
const response = await this.tbankClient.callUnary<
|
||||
Record<string, unknown>,
|
||||
TBankOperationsByCursorResponse
|
||||
|
||||
@ -0,0 +1,72 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerPortfolioService } from './broker-portfolio.service';
|
||||
import type { BrokerPortfolioHistoryDataDto, BrokerPortfolioHistoryPointDto } from '../dto/broker-portfolio-history-response.dto';
|
||||
import type { BrokerMoney } from '../types/broker.types';
|
||||
|
||||
const RUSSIAN_MONTHS = [
|
||||
'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн',
|
||||
'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class BrokerPortfolioHistoryService {
|
||||
constructor(
|
||||
private readonly accountsService: BrokerAccountsService,
|
||||
private readonly portfolioService: BrokerPortfolioService,
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
|
||||
async getHistory(
|
||||
accountId: string,
|
||||
months: number,
|
||||
): Promise<ApiEnvelopePayload<BrokerPortfolioHistoryDataDto>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
TBANK_CACHE_KEYS.portfolio,
|
||||
[accountId, 'history', String(months)],
|
||||
() => this.computeHistory(accountId, months),
|
||||
'tbankPortfolioTtl',
|
||||
);
|
||||
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
private async computeHistory(
|
||||
accountId: string,
|
||||
months: number,
|
||||
): Promise<BrokerPortfolioHistoryDataDto> {
|
||||
const portfolioEnvelope = await this.portfolioService.getPortfolio(accountId);
|
||||
const currentValue = portfolioEnvelope.data.totals.portfolio;
|
||||
|
||||
const defaultMoney: BrokerMoney = currentValue ?? {
|
||||
currency: 'RUB',
|
||||
units: '0',
|
||||
nano: 0,
|
||||
value: 0,
|
||||
};
|
||||
|
||||
const now = new Date();
|
||||
const points: BrokerPortfolioHistoryPointDto[] = [];
|
||||
|
||||
for (let i = months - 1; i >= 0; i--) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const month = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
const label = RUSSIAN_MONTHS[d.getMonth()];
|
||||
|
||||
points.push({ month, label, value: { ...defaultMoney } });
|
||||
}
|
||||
|
||||
return {
|
||||
accountId,
|
||||
points,
|
||||
asOf: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerInstrumentsService } from './broker-instruments.service';
|
||||
import { BrokerPortfolioService } from './broker-portfolio.service';
|
||||
@ -8,7 +8,7 @@ import { TBankClientService } from './tbank-client.service';
|
||||
describe('BrokerPortfolioService', () => {
|
||||
const accounts = { findById: vi.fn() } as unknown as BrokerAccountsService;
|
||||
const instruments = { findByInstrumentUid: vi.fn() } as unknown as BrokerInstrumentsService;
|
||||
const client = { getServiceClient: vi.fn(), callUnary: vi.fn() } as unknown as TBankClientService;
|
||||
const client = { getOperationsClient: vi.fn(), callUnary: vi.fn() } as unknown as TBankClientService;
|
||||
const cache = { getOrFetch: vi.fn() } as unknown as CacheService;
|
||||
|
||||
beforeEach(() => {
|
||||
@ -19,7 +19,7 @@ describe('BrokerPortfolioService', () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(null);
|
||||
const service = new BrokerPortfolioService(accounts, instruments, client, cache);
|
||||
|
||||
await expect(service.getPortfolio('missing')).rejects.toThrow(NotFoundException);
|
||||
await expect(service.getPortfolio('missing')).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('fetches portfolio through cache without positions', async () => {
|
||||
@ -38,7 +38,7 @@ describe('BrokerPortfolioService', () => {
|
||||
cachedAt: null,
|
||||
}),
|
||||
);
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
getPositions: vi.fn(),
|
||||
} as any);
|
||||
@ -98,13 +98,13 @@ describe('BrokerPortfolioService', () => {
|
||||
vi.mocked(accounts.findById).mockResolvedValue(null);
|
||||
const service = new BrokerPortfolioService(accounts, instruments, client, cache);
|
||||
|
||||
await expect(service.getPositions('missing')).rejects.toThrow(NotFoundException);
|
||||
await expect(service.getPositions('missing')).rejects.toThrow(EntityNotFoundException);
|
||||
});
|
||||
|
||||
it('returns first page of positions', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
@ -139,7 +139,7 @@ describe('BrokerPortfolioService', () => {
|
||||
it('paginates using cursor', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
@ -179,7 +179,7 @@ describe('BrokerPortfolioService', () => {
|
||||
it('returns last page with hasNext=false', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
@ -206,7 +206,7 @@ describe('BrokerPortfolioService', () => {
|
||||
it('caches positions with cursor/limit/type in key and tbankPositionsTtl', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
@ -229,7 +229,7 @@ describe('BrokerPortfolioService', () => {
|
||||
it('filters by instrument type and caches with type in key', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
@ -279,7 +279,7 @@ describe('BrokerPortfolioService', () => {
|
||||
it('returns empty items when type filter matches nothing', async () => {
|
||||
mockAccount();
|
||||
mockCache();
|
||||
vi.mocked(client.getServiceClient).mockReturnValue({
|
||||
vi.mocked(client.getOperationsClient).mockReturnValue({
|
||||
getPortfolio: vi.fn(),
|
||||
} as any);
|
||||
vi.mocked(client.callUnary).mockResolvedValueOnce({
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CacheService } from '../../cache/cache.service';
|
||||
import { mapBrokerPortfolio, mapBrokerPositionsPage } from '../mappers/portfolio.mapper';
|
||||
import { TBANK_CACHE_KEYS } from '../tbank.config';
|
||||
import { EntityNotFoundException } from '../../../common/exceptions/entity-not-found.exception';
|
||||
import type { BrokerPortfolio, BrokerPositionsPage } from '../types/broker.types';
|
||||
import type {
|
||||
TBankInstrument,
|
||||
@ -12,6 +13,7 @@ import type {
|
||||
import { BrokerAccountsService } from './broker-accounts.service';
|
||||
import { BrokerInstrumentsService } from './broker-instruments.service';
|
||||
import { TBankClientService } from './tbank-client.service';
|
||||
import { ApiEnvelopePayload } from '../../../common/dto/api-response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BrokerPortfolioService {
|
||||
@ -22,12 +24,9 @@ export class BrokerPortfolioService {
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
|
||||
async getPortfolio(accountId: string): Promise<{
|
||||
data: BrokerPortfolio;
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
async getPortfolio(accountId: string): Promise<ApiEnvelopePayload<BrokerPortfolio>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new NotFoundException('Broker account not found');
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
TBANK_CACHE_KEYS.portfolio,
|
||||
@ -43,10 +42,7 @@ export class BrokerPortfolioService {
|
||||
'tbankPortfolioTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
async getPositions(
|
||||
@ -54,12 +50,9 @@ export class BrokerPortfolioService {
|
||||
cursor?: string,
|
||||
limit = 10,
|
||||
type?: string,
|
||||
): Promise<{
|
||||
data: BrokerPositionsPage;
|
||||
meta: { fromCache: boolean; cachedAt: string | null };
|
||||
}> {
|
||||
): Promise<ApiEnvelopePayload<BrokerPositionsPage>> {
|
||||
const account = await this.accountsService.findById(accountId);
|
||||
if (!account) throw new NotFoundException('Broker account not found');
|
||||
if (!account) throw new EntityNotFoundException('BrokerAccount', accountId);
|
||||
|
||||
const result = await this.cacheService.getOrFetch(
|
||||
TBANK_CACHE_KEYS.positions,
|
||||
@ -87,10 +80,7 @@ export class BrokerPortfolioService {
|
||||
'tbankPositionsTtl',
|
||||
);
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
meta: { fromCache: result.fromCache, cachedAt: result.cachedAt },
|
||||
};
|
||||
return new ApiEnvelopePayload(result.data, result.fromCache, result.cachedAt);
|
||||
}
|
||||
|
||||
private async buildInstrumentMap(
|
||||
@ -130,7 +120,7 @@ export class BrokerPortfolioService {
|
||||
'tbank:raw-portfolio',
|
||||
[accountId],
|
||||
async () => {
|
||||
const operationsClient = this.tbankClient.getServiceClient('OperationsService') as any;
|
||||
const operationsClient = this.tbankClient.getOperationsClient();
|
||||
return this.tbankClient.callUnary<
|
||||
{ accountId: string; currency: string },
|
||||
TBankPortfolioResponse
|
||||
@ -149,7 +139,7 @@ export class BrokerPortfolioService {
|
||||
}
|
||||
|
||||
private async fetchPositions(accountId: string): Promise<TBankPositionsResponse> {
|
||||
const operationsClient = this.tbankClient.getServiceClient('OperationsService') as any;
|
||||
const operationsClient = this.tbankClient.getOperationsClient();
|
||||
return this.tbankClient.callUnary<{ accountId: string }, TBankPositionsResponse>(
|
||||
'OperationsService/GetPositions',
|
||||
operationsClient.getPositions.bind(operationsClient),
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { ServiceUnavailableException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TBankNotConfiguredException } from '../../../common/exceptions/tbank-api.exception';
|
||||
import { ChannelCredentials, ClientUnaryCall, Metadata, ServiceError, status } from '@grpc/grpc-js';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
@ -44,6 +44,16 @@ describe('TBankClientService', () => {
|
||||
expect(() => service.getServiceClient('UsersService')).not.toThrow();
|
||||
});
|
||||
|
||||
it('exposes typed service-client facades for broker services', () => {
|
||||
const service = new TBankClientService(config);
|
||||
|
||||
expect(service.getUsersClient()).toHaveProperty('getAccounts');
|
||||
expect(service.getOperationsClient()).toHaveProperty('getPortfolio');
|
||||
expect(service.getOperationsClient()).toHaveProperty('getPositions');
|
||||
expect(service.getOperationsClient()).toHaveProperty('getOperationsByCursor');
|
||||
expect(service.getInstrumentsClient()).toHaveProperty('getInstrumentBy');
|
||||
});
|
||||
|
||||
it('creates grpc SSL credentials with configured custom CA certificate', () => {
|
||||
const caPath = join(mkdtempSync(join(tmpdir(), 'tbank-ca-')), 'root.pem');
|
||||
writeFileSync(caPath, '-----BEGIN CERTIFICATE-----\ntest-ca\n-----END CERTIFICATE-----\n');
|
||||
@ -85,7 +95,7 @@ describe('TBankClientService', () => {
|
||||
},
|
||||
{},
|
||||
),
|
||||
).rejects.toThrow(ServiceUnavailableException);
|
||||
).rejects.toThrow(TBankNotConfiguredException);
|
||||
});
|
||||
|
||||
it('wraps grpc errors with status code and tracking id', async () => {
|
||||
@ -107,9 +117,7 @@ describe('TBankClientService', () => {
|
||||
{},
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
response: expect.objectContaining({
|
||||
message: expect.stringContaining('T-Bank upstream error'),
|
||||
}),
|
||||
response: expect.stringContaining('T-Bank upstream error'),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@ -1,10 +1,13 @@
|
||||
import {
|
||||
BadGatewayException,
|
||||
Injectable,
|
||||
Logger,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TBankNotConfiguredException, TBankApiException } from '../../../common/exceptions/tbank-api.exception';
|
||||
import type {
|
||||
TBankAccountsResponse,
|
||||
TBankInstrumentResponse,
|
||||
TBankOperationsByCursorResponse,
|
||||
TBankPortfolioResponse,
|
||||
TBankPositionsResponse,
|
||||
} from '../types/tbank-proto.types';
|
||||
import {
|
||||
CallOptions,
|
||||
ChannelCredentials,
|
||||
@ -30,6 +33,25 @@ type GrpcUnary<TRequest, TResponse> = (
|
||||
|
||||
type GrpcServiceConstructor = new (address: string, credentials: ChannelCredentials) => Client;
|
||||
|
||||
type TBankAccountsRequest = { status: string };
|
||||
export type TBankPortfolioRequest = { accountId: string; currency: string };
|
||||
type TBankPositionsRequest = { accountId: string };
|
||||
type TBankInstrumentRequest = { idType: string; id: string };
|
||||
|
||||
export type TBankUsersClient = Client & {
|
||||
getAccounts: GrpcUnary<TBankAccountsRequest, TBankAccountsResponse>;
|
||||
};
|
||||
|
||||
export type TBankOperationsClient = Client & {
|
||||
getPortfolio: GrpcUnary<TBankPortfolioRequest, TBankPortfolioResponse>;
|
||||
getPositions: GrpcUnary<TBankPositionsRequest, TBankPositionsResponse>;
|
||||
getOperationsByCursor: GrpcUnary<Record<string, unknown>, TBankOperationsByCursorResponse>;
|
||||
};
|
||||
|
||||
export type TBankInstrumentsClient = Client & {
|
||||
getInstrumentBy: GrpcUnary<TBankInstrumentRequest, TBankInstrumentResponse>;
|
||||
};
|
||||
|
||||
type QueueName = 'operations' | 'instruments' | 'users';
|
||||
|
||||
@Injectable()
|
||||
@ -79,7 +101,7 @@ export class TBankClientService {
|
||||
createMetadata(): Metadata {
|
||||
const token = this.configService.get<string>('app.tbank.token', '');
|
||||
if (!token) {
|
||||
throw new ServiceUnavailableException('T-Bank integration is not configured');
|
||||
throw new TBankNotConfiguredException();
|
||||
}
|
||||
|
||||
const metadata = new Metadata();
|
||||
@ -124,6 +146,18 @@ export class TBankClientService {
|
||||
return client;
|
||||
}
|
||||
|
||||
getUsersClient(): TBankUsersClient {
|
||||
return this.getServiceClient('UsersService') as TBankUsersClient;
|
||||
}
|
||||
|
||||
getOperationsClient(): TBankOperationsClient {
|
||||
return this.getServiceClient('OperationsService') as TBankOperationsClient;
|
||||
}
|
||||
|
||||
getInstrumentsClient(): TBankInstrumentsClient {
|
||||
return this.getServiceClient('InstrumentsService') as TBankInstrumentsClient;
|
||||
}
|
||||
|
||||
async callUnary<TRequest, TResponse>(
|
||||
label: string,
|
||||
method: GrpcUnary<TRequest, TResponse>,
|
||||
@ -169,7 +203,7 @@ export class TBankClientService {
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
throw new ServiceUnavailableException('T-Bank CA certificate is not readable');
|
||||
throw new TBankApiException('T-Bank CA certificate is not readable');
|
||||
}
|
||||
}
|
||||
|
||||
@ -191,10 +225,9 @@ export class TBankClientService {
|
||||
}),
|
||||
);
|
||||
|
||||
return new BadGatewayException({
|
||||
message: publicMessage,
|
||||
trackingId: trackingId ? String(trackingId) : null,
|
||||
retryAfter: retryAfter ? String(retryAfter) : null,
|
||||
});
|
||||
const detail = [publicMessage, trackingId && `trackingId:${trackingId}`, retryAfter && `retryAfter:${retryAfter}`]
|
||||
.filter(Boolean)
|
||||
.join('; ');
|
||||
return new TBankApiException(detail);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import { ROLES_KEY } from '../auth/decorators/roles.decorator';
|
||||
import { ApiResponse } from '../../common/dto/api-response.dto';
|
||||
import { ApiEnvelopePayload } from '../../common/dto/api-response.dto';
|
||||
import { TBankController } from './tbank.controller';
|
||||
import { BrokerAccountsService } from './services/broker-accounts.service';
|
||||
import { BrokerAnalyticsService } from './services/broker-analytics.service';
|
||||
import { BrokerEventsService } from './services/broker-events.service';
|
||||
import { BrokerOperationSyncService } from './services/broker-operation-sync.service';
|
||||
import { BrokerOperationsService } from './services/broker-operations.service';
|
||||
import { BrokerPortfolioHistoryService } from './services/broker-portfolio-history.service';
|
||||
import { BrokerPortfolioService } from './services/broker-portfolio.service';
|
||||
|
||||
describe('TBankController', () => {
|
||||
@ -15,6 +16,7 @@ describe('TBankController', () => {
|
||||
const events = { getEvents: vi.fn() } as unknown as BrokerEventsService;
|
||||
const operations = { getOperations: vi.fn() } as unknown as BrokerOperationsService;
|
||||
const sync = { syncAccount: vi.fn() } as unknown as BrokerOperationSyncService;
|
||||
const portfolioHistory = { getHistory: vi.fn() } as unknown as BrokerPortfolioHistoryService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@ -25,32 +27,36 @@ describe('TBankController', () => {
|
||||
});
|
||||
|
||||
it('returns accounts in a single API envelope', async () => {
|
||||
vi.mocked(accounts.findAll).mockResolvedValueOnce({
|
||||
data: [
|
||||
{
|
||||
id: 'acc-1',
|
||||
type: 'brokerage',
|
||||
name: 'Broker',
|
||||
status: 'ACCOUNT_STATUS_OPEN',
|
||||
openedAt: null,
|
||||
accessLevel: null,
|
||||
},
|
||||
],
|
||||
meta: { fromCache: true, cachedAt: '2026-06-17T00:00:00.000Z' },
|
||||
});
|
||||
vi.mocked(accounts.findAll).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(
|
||||
[
|
||||
{
|
||||
id: 'acc-1',
|
||||
type: 'brokerage',
|
||||
name: 'Broker',
|
||||
status: 'ACCOUNT_STATUS_OPEN',
|
||||
openedAt: null,
|
||||
accessLevel: null,
|
||||
},
|
||||
],
|
||||
true,
|
||||
'2026-06-17T00:00:00.000Z',
|
||||
),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics);
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const response = await controller.getAccounts();
|
||||
|
||||
expect(response).toBeInstanceOf(ApiResponse);
|
||||
expect(response).toBeInstanceOf(ApiEnvelopePayload);
|
||||
expect(response.data).toHaveLength(1);
|
||||
expect(response.meta).toEqual({ fromCache: true, cachedAt: '2026-06-17T00:00:00.000Z' });
|
||||
expect(response.fromCache).toBe(true);
|
||||
expect(response.cachedAt).toBe('2026-06-17T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('exposes a sync trigger for durable operation history', async () => {
|
||||
vi.mocked(sync.syncAccount).mockResolvedValueOnce({ upserted: 2 });
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics);
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const response = await controller.syncOperations('acc-1', {
|
||||
from: '2026-06-01T00:00:00.000Z',
|
||||
to: '2026-06-17T00:00:00.000Z',
|
||||
@ -60,7 +66,7 @@ describe('TBankController', () => {
|
||||
from: '2026-06-01T00:00:00.000Z',
|
||||
to: '2026-06-17T00:00:00.000Z',
|
||||
});
|
||||
expect(response.data).toEqual({ upserted: 2 });
|
||||
expect(response).toEqual({ upserted: 2 });
|
||||
});
|
||||
|
||||
it('exposes analytics endpoint through controller', async () => {
|
||||
@ -72,20 +78,83 @@ describe('TBankController', () => {
|
||||
totalCoupons: 50,
|
||||
totalReceived: 200,
|
||||
totalReturnPercent: 25,
|
||||
totalFees: 0,
|
||||
totalTaxesPaid: 0,
|
||||
currency: 'RUB',
|
||||
};
|
||||
vi.mocked(analytics.getAnalytics).mockResolvedValueOnce({
|
||||
data: analyticsData,
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
});
|
||||
vi.mocked(analytics.getAnalytics).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(analyticsData, false, null),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics);
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const response = await controller.getAnalytics('acc-1');
|
||||
|
||||
expect(analytics.getAnalytics).toHaveBeenCalledWith('acc-1');
|
||||
expect(response).toBeInstanceOf(ApiResponse);
|
||||
expect(response).toBeInstanceOf(ApiEnvelopePayload);
|
||||
expect(response.data).toEqual(analyticsData);
|
||||
expect(response.meta).toEqual({ fromCache: false, cachedAt: null });
|
||||
expect(response.fromCache).toBe(false);
|
||||
expect(response.cachedAt).toBeNull();
|
||||
});
|
||||
|
||||
it('returns portfolio history with correct shape and points', async () => {
|
||||
const historyData = {
|
||||
accountId: 'acc-1',
|
||||
points: [
|
||||
{ month: '2026-01', label: 'Янв', value: { currency: 'RUB', units: '100000', nano: 0, value: 100000 } },
|
||||
{ month: '2026-02', label: 'Фев', value: { currency: 'RUB', units: '100000', nano: 0, value: 100000 } },
|
||||
],
|
||||
asOf: '2026-06-22T00:00:00.000Z',
|
||||
};
|
||||
vi.mocked(portfolioHistory.getHistory).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(historyData, false, '2026-06-22T00:00:00.000Z'),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const response = await controller.getPortfolioHistory('acc-1', 6);
|
||||
|
||||
expect(portfolioHistory.getHistory).toHaveBeenCalledWith('acc-1', 6);
|
||||
expect(response).toBeInstanceOf(ApiEnvelopePayload);
|
||||
expect(response.data).toEqual(historyData);
|
||||
expect(response.data.points).toHaveLength(2);
|
||||
expect(response.data.points[0].month).toBe('2026-01');
|
||||
expect(response.data.points[0].label).toBe('Янв');
|
||||
});
|
||||
|
||||
it('passes categories filter query to operations service', async () => {
|
||||
const pageData = {
|
||||
accountId: 'acc-1',
|
||||
items: [],
|
||||
nextCursor: null,
|
||||
hasNext: false,
|
||||
asOf: '2026-06-22T00:00:00.000Z',
|
||||
};
|
||||
vi.mocked(operations.getOperations).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(pageData, false, null),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const query = { from: '2026-06-01', to: '2026-06-30', categories: 'fee,tax' };
|
||||
const response = await controller.getOperations('acc-1', query);
|
||||
|
||||
expect(operations.getOperations).toHaveBeenCalledWith('acc-1', query);
|
||||
expect(response.data.accountId).toBe('acc-1');
|
||||
});
|
||||
|
||||
it('uses default months parameter when not provided', async () => {
|
||||
const historyData = {
|
||||
accountId: 'acc-1',
|
||||
points: [],
|
||||
asOf: '2026-06-22T00:00:00.000Z',
|
||||
};
|
||||
vi.mocked(portfolioHistory.getHistory).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(historyData, false, null),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const response = await controller.getPortfolioHistory('acc-1');
|
||||
|
||||
expect(portfolioHistory.getHistory).toHaveBeenCalledWith('acc-1', 6);
|
||||
expect(response.data.points).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('forwards events query and wraps response', async () => {
|
||||
@ -106,17 +175,16 @@ describe('TBankController', () => {
|
||||
},
|
||||
asOf: '2026-06-22T00:00:00.000Z',
|
||||
};
|
||||
vi.mocked(events.getEvents).mockResolvedValueOnce({
|
||||
data: eventsData,
|
||||
meta: { fromCache: false, cachedAt: '2026-06-22T00:00:00.000Z' },
|
||||
});
|
||||
vi.mocked(events.getEvents).mockResolvedValueOnce(
|
||||
new ApiEnvelopePayload(eventsData, false, '2026-06-22T00:00:00.000Z'),
|
||||
);
|
||||
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics);
|
||||
const controller = new TBankController(accounts, portfolio, events, operations, sync, analytics, portfolioHistory);
|
||||
const query = { from: '2026-06-22', to: '2026-07-29', types: 'dividend,coupon' };
|
||||
const response = await controller.getEvents('acc-1', query);
|
||||
|
||||
expect(events.getEvents).toHaveBeenCalledWith('acc-1', query);
|
||||
expect(response).toBeInstanceOf(ApiResponse);
|
||||
expect(response).toBeInstanceOf(ApiEnvelopePayload);
|
||||
expect(response.data).toEqual(eventsData);
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiResponse } from '../../common/dto/api-response.dto';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import {
|
||||
BrokerAccountsEnvelopeDto,
|
||||
@ -9,6 +8,7 @@ import {
|
||||
BrokerOperationSyncEnvelopeDto,
|
||||
BrokerOperationsEnvelopeDto,
|
||||
BrokerPortfolioEnvelopeDto,
|
||||
BrokerPortfolioHistoryEnvelopeDto,
|
||||
BrokerPositionsEnvelopeDto,
|
||||
} from './dto/broker-envelope.dto';
|
||||
import { BrokerEventsQueryDto } from './dto/broker-events-query.dto';
|
||||
@ -16,10 +16,11 @@ import { BrokerPositionQueryDto } from './dto/broker-position-query.dto';
|
||||
import { BrokerOperationQueryDto } from './dto/broker-operation-query.dto';
|
||||
import { BrokerOperationSyncQueryDto } from './dto/broker-operation-sync-query.dto';
|
||||
import { BrokerAccountsService } from './services/broker-accounts.service';
|
||||
import { BrokerAnalyticsService } from './services/broker-analytics.service';
|
||||
import { BrokerEventsService } from './services/broker-events.service';
|
||||
import { BrokerOperationSyncService } from './services/broker-operation-sync.service';
|
||||
import { BrokerOperationsService } from './services/broker-operations.service';
|
||||
import { BrokerAnalyticsService } from './services/broker-analytics.service';
|
||||
import { BrokerPortfolioHistoryService } from './services/broker-portfolio-history.service';
|
||||
import { BrokerPortfolioService } from './services/broker-portfolio.service';
|
||||
|
||||
@ApiTags('Broker')
|
||||
@ -34,22 +35,21 @@ export class TBankController {
|
||||
private readonly brokerOperationsService: BrokerOperationsService,
|
||||
private readonly brokerOperationSyncService: BrokerOperationSyncService,
|
||||
private readonly brokerAnalyticsService: BrokerAnalyticsService,
|
||||
private readonly brokerPortfolioHistoryService: BrokerPortfolioHistoryService,
|
||||
) {}
|
||||
|
||||
@Get('accounts')
|
||||
@ApiOperation({ summary: 'Get open T-Bank brokerage and IIS accounts' })
|
||||
@ApiOkResponse({ type: BrokerAccountsEnvelopeDto })
|
||||
async getAccounts() {
|
||||
const result = await this.brokerAccountsService.findAll();
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
return this.brokerAccountsService.findAll();
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/portfolio')
|
||||
@ApiOperation({ summary: 'Get T-Bank broker account portfolio with cash and positions' })
|
||||
@ApiOkResponse({ type: BrokerPortfolioEnvelopeDto })
|
||||
async getPortfolio(@Param('accountId') accountId: string) {
|
||||
const result = await this.brokerPortfolioService.getPortfolio(accountId);
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
return this.brokerPortfolioService.getPortfolio(accountId);
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/positions')
|
||||
@ -59,13 +59,12 @@ export class TBankController {
|
||||
@Param('accountId') accountId: string,
|
||||
@Query() query: BrokerPositionQueryDto,
|
||||
) {
|
||||
const result = await this.brokerPortfolioService.getPositions(
|
||||
return this.brokerPortfolioService.getPositions(
|
||||
accountId,
|
||||
query.cursor,
|
||||
query.limit,
|
||||
query.type,
|
||||
);
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/operations')
|
||||
@ -75,24 +74,31 @@ export class TBankController {
|
||||
@Param('accountId') accountId: string,
|
||||
@Query() query: BrokerOperationQueryDto,
|
||||
) {
|
||||
const result = await this.brokerOperationsService.getOperations(accountId, query);
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
return this.brokerOperationsService.getOperations(accountId, query);
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/events')
|
||||
@ApiOperation({ summary: 'Get broker account calendar events and cashflow' })
|
||||
@ApiOkResponse({ type: BrokerEventsEnvelopeDto })
|
||||
async getEvents(@Param('accountId') accountId: string, @Query() query: BrokerEventsQueryDto) {
|
||||
const result = await this.brokerEventsService.getEvents(accountId, query);
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
return this.brokerEventsService.getEvents(accountId, query);
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/portfolio/history')
|
||||
@ApiOperation({ summary: 'Get portfolio value history for last N months' })
|
||||
@ApiOkResponse({ type: BrokerPortfolioHistoryEnvelopeDto })
|
||||
async getPortfolioHistory(
|
||||
@Param('accountId') accountId: string,
|
||||
@Query('months') months?: number,
|
||||
) {
|
||||
return this.brokerPortfolioHistoryService.getHistory(accountId, months ?? 6);
|
||||
}
|
||||
|
||||
@Get('accounts/:accountId/analytics')
|
||||
@ApiOperation({ summary: 'Get broker account profitability analytics' })
|
||||
@ApiOkResponse({ type: BrokerAnalyticsEnvelopeDto })
|
||||
async getAnalytics(@Param('accountId') accountId: string) {
|
||||
const result = await this.brokerAnalyticsService.getAnalytics(accountId);
|
||||
return new ApiResponse(result.data, result.meta.fromCache, result.meta.cachedAt);
|
||||
return this.brokerAnalyticsService.getAnalytics(accountId);
|
||||
}
|
||||
|
||||
@Post('accounts/:accountId/operations/sync')
|
||||
@ -102,7 +108,6 @@ export class TBankController {
|
||||
@Param('accountId') accountId: string,
|
||||
@Query() query: BrokerOperationSyncQueryDto,
|
||||
) {
|
||||
const result = await this.brokerOperationSyncService.syncAccount(accountId, query);
|
||||
return new ApiResponse(result);
|
||||
return this.brokerOperationSyncService.syncAccount(accountId, query);
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ import { BrokerInstrumentsService } from './services/broker-instruments.service'
|
||||
import { BrokerEventsService } from './services/broker-events.service';
|
||||
import { BrokerOperationSyncService } from './services/broker-operation-sync.service';
|
||||
import { BrokerOperationsService } from './services/broker-operations.service';
|
||||
import { BrokerPortfolioHistoryService } from './services/broker-portfolio-history.service';
|
||||
import { BrokerPortfolioService } from './services/broker-portfolio.service';
|
||||
import { TBankClientService } from './services/tbank-client.service';
|
||||
|
||||
@ -22,6 +23,7 @@ import { TBankClientService } from './services/tbank-client.service';
|
||||
BrokerOperationsService,
|
||||
BrokerOperationSyncService,
|
||||
BrokerAnalyticsService,
|
||||
BrokerPortfolioHistoryService,
|
||||
],
|
||||
exports: [
|
||||
TBankClientService,
|
||||
|
||||
27
apps/backend/src/openapi-artifacts.spec.ts
Normal file
27
apps/backend/src/openapi-artifacts.spec.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
describe('checked-in OpenAPI artifacts', () => {
|
||||
const rootDir = resolve(process.cwd(), '../..');
|
||||
const frontendTypes = readFileSync(join(rootDir, 'apps/frontend/src/shared/api/types.ts'), 'utf8');
|
||||
|
||||
const requiredPaths = [
|
||||
'/api/v1/auth/register',
|
||||
'/api/v1/auth/login',
|
||||
'/api/v1/auth/refresh',
|
||||
'/api/v1/auth/logout',
|
||||
'/api/v1/auth/me',
|
||||
'/api/v1/securities/screener',
|
||||
'/api/v1/portfolios',
|
||||
'/api/v1/portfolios/{id}',
|
||||
'/api/v1/portfolios/{id}/positions',
|
||||
'/api/v1/portfolios/{id}/positions/{positionId}',
|
||||
'/api/v1/portfolios/{id}/analytics',
|
||||
];
|
||||
|
||||
it('frontend generated types include current protected domains', () => {
|
||||
for (const path of requiredPaths) {
|
||||
expect(frontendTypes).toContain(`'${path}'`);
|
||||
}
|
||||
});
|
||||
});
|
||||
63
apps/docs/docs/adr/ADR-020-moex-client-split.md
Normal file
63
apps/docs/docs/adr/ADR-020-moex-client-split.md
Normal file
@ -0,0 +1,63 @@
|
||||
# ADR-020: Разделение MoexClientService на доменные клиенты
|
||||
|
||||
**Дата:** 2026-06-25
|
||||
**Статус:** Принято
|
||||
**Автор:** AI Agent (codex/backend-architecture-improvements)
|
||||
|
||||
## Контекст
|
||||
|
||||
`MoexClientService` в `apps/backend/src/modules/moex-client/moex-client.service.ts` (423 строки, 11 публичных методов) со временем стал God Service:
|
||||
|
||||
- Нарушает SRP — содержит логику работы с акциями, облигациями, свечами, историей, дивидендами и поиском в одном классе
|
||||
- Инфраструктура (rate limiter, circuit breaker) смешана с бизнес-логикой
|
||||
- Все 11 методов используют один шаблон: `request()` → `extractTable()` → map, но каждый с разными endpoint-ами и типами
|
||||
- Потребители (shares, bonds, candles, portfolio, securities, screener, tbank/events) получают весь сервис целиком, а не только нужную функциональность
|
||||
- Тестирование затруднено: любой тест одного метода тянет весь сервис
|
||||
|
||||
## Рассмотренные варианты
|
||||
|
||||
### A. Полный сплит по доменам (выбран)
|
||||
|
||||
Выделить инфраструктурный слой (`MoexHttpClient`) и 5 доменных клиентов — по одному на группу MOEX-запросов.
|
||||
|
||||
### B. Минимальный сплит
|
||||
|
||||
Вынести только `MoexHttpClient` (request + extractTable + circuit breaker + rate limiter), оставить все методы в одном сервисе с делегированием через DI.
|
||||
|
||||
Отклонён: не решает проблему God Service — один сервис всё ещё содержит всю доменную логику.
|
||||
|
||||
### C. Оставить как есть
|
||||
|
||||
Отклонён: противоречит результатам аудита, 423-строчный сервис ухудшает поддерживаемость.
|
||||
|
||||
## Решение
|
||||
|
||||
Выбран вариант A — полный сплит по доменам:
|
||||
|
||||
- `MoexHttpClient` — инфраструктура (axios, PQueue, circuit breaker, `request()`, `extractTable()`)
|
||||
- `MoexSecuritiesClient` — `searchSecurities()`, `getSecurityDescription()`
|
||||
- `MoexMarketDataClient` — `getShareMarketData()`, `getShareMarketDataBatch()`, `getBondData()`, `getBondMarketData()`, `getBondPositionDataBatch()`
|
||||
- `MoexCandlesClient` — `getCandles()`
|
||||
- `MoexHistoryClient` — `getHistory()`, `getBondHistory()`
|
||||
- `MoexDividendsClient` — `getDividends()`
|
||||
|
||||
Модуль теряет `@Global()` — каждый потребитель явно импортирует `MoexClientModule`.
|
||||
|
||||
## Последствия
|
||||
|
||||
### Положительные
|
||||
- Чёткое разделение ответственности — каждый клиент отвечает за один домен MOEX API
|
||||
- Возможность мокать только нужный клиент в тестах потребителей
|
||||
- `MoexHttpClient` — внутренняя деталь, не экспортируется из модуля
|
||||
- Явные зависимости через imports модулей вместо одного God Service
|
||||
|
||||
### Риски
|
||||
- Миграция всех 7 потребителей в одном коммите (нельзя оставить половинчатое состояние)
|
||||
- Каждый потребитель должен импортировать `MoexClientModule` — больше boilerplate
|
||||
- Необходимость обновить все тесты потребителей (DI-инъекция меняется)
|
||||
|
||||
## Связанные документы
|
||||
- ADR-003: Стратегия rate limiting (остаётся актуальной, инфраструктура переносится в MoexHttpClient)
|
||||
- ADR-004: Feature modules (принцип явных зависимостей)
|
||||
- `docs/features/backend-architecture-improvements/plan.md` (Iteration 6)
|
||||
- `docs/features/backend-architecture-improvements/tasks.md` (Iteration 6)
|
||||
@ -92,9 +92,17 @@
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"timestamp": "2026-06-13T12:00:00.000Z",
|
||||
"uptime": 1234.56
|
||||
"data": {
|
||||
"status": "ok",
|
||||
"timestamp": "2026-06-25T12:00:00.000Z",
|
||||
"uptime": 1234.56,
|
||||
"checks": [
|
||||
{ "name": "database", "status": "ok" },
|
||||
{ "name": "moex", "status": "ok" },
|
||||
{ "name": "tbank", "status": "ok" }
|
||||
]
|
||||
},
|
||||
"meta": { "fromCache": false, "cachedAt": null }
|
||||
}
|
||||
```
|
||||
|
||||
@ -403,5 +411,5 @@ codegen types.
|
||||
| `/api/v1/broker/accounts/:accountId/portfolio` | GET | Портфель счёта: позиции, cash, метаданные |
|
||||
| `/api/v1/broker/accounts/:accountId/events` | GET | События и будущие выплаты (дивиденды, купоны) с фильтром по датам |
|
||||
| `/api/v1/broker/accounts/:accountId/operations` | GET | История операций (cursor pagination) |
|
||||
| `/api/v1/broker/accounts/:accountId/operations/refresh` | POST | Принудительная синхронизация операций из T-Bank |
|
||||
| `/api/v1/broker/accounts/:accountId/operations/sync` | POST | Принудительная синхронизация операций из T-Bank |
|
||||
| `/api/v1/broker/accounts/:accountId/positions` | GET | Позиции счёта (с пагинацией) |
|
||||
|
||||
@ -83,10 +83,12 @@ export class CacheModule {}
|
||||
| Позиции T-Bank | `tbankPositionsTtl` | 60s (1 мин) | `CACHE_TBANK_POSITIONS_TTL` |
|
||||
| Операции T-Bank | `tbankOperationsTtl` | 300s (5 мин) | `CACHE_TBANK_OPERATIONS_TTL` |
|
||||
| Инструменты T-Bank | `tbankInstrumentTtl` | 86400s (24 ч) | `CACHE_TBANK_INSTRUMENT_TTL` |
|
||||
| События и прогноз выплат T-Bank | `tbankEventsTtl` | 300s (5 мин) | `CACHE_TBANK_EVENTS_TTL` |
|
||||
|
||||
## T-Bank cache
|
||||
|
||||
`TBankModule` использует те же механики `CacheService`, но с отдельными key prefixes
|
||||
`tbank:accounts`, `tbank:portfolio`, `tbank:positions`, `tbank:operations` и `tbank:instrument`.
|
||||
`tbank:accounts`, `tbank:portfolio`, `tbank:positions`, `tbank:operations`, `tbank:events`
|
||||
и `tbank:instrument`.
|
||||
Это позволяет держать агрессивно короткий TTL для текущего портфеля и более длинный TTL для
|
||||
справочных данных инструментов.
|
||||
|
||||
@ -25,20 +25,20 @@ flowchart TB
|
||||
|
||||
PrismaService["PrismaService"]
|
||||
CacheService["CacheService"]
|
||||
MoexClientService["MoexClientService"]
|
||||
MoexHttpClient["MoexHttpClient"]
|
||||
TBankClientService["TBankClientService"]
|
||||
|
||||
PrismaModule --> PrismaService
|
||||
CacheModule --> CacheService
|
||||
MoexClientModule --> MoexClientService
|
||||
MoexClientModule --> MoexHttpClient
|
||||
|
||||
AuthModule --> PrismaService
|
||||
PortfolioModule --> PrismaService
|
||||
PortfolioModule --> CacheService
|
||||
PortfolioModule --> MoexClientService
|
||||
PortfolioModule --> MoexHttpClient
|
||||
|
||||
MarketModules --> CacheService
|
||||
MarketModules --> MoexClientService
|
||||
MarketModules --> MoexHttpClient
|
||||
|
||||
TBankModule --> CacheService
|
||||
TBankModule --> PrismaService
|
||||
@ -51,7 +51,7 @@ flowchart TB
|
||||
|---|---|---|---|
|
||||
| `PrismaModule` | Да | `modules/prisma/` | Prisma client для SQLite |
|
||||
| `CacheModule` | Да | `modules/cache/` | In-memory cache через cache-manager |
|
||||
| `MoexClientModule` | Да | `modules/moex-client/` | HTTP-клиент MOEX ISS |
|
||||
| `MoexClientModule` | Нет | `modules/moex-client/` | HTTP- и domain-клиенты MOEX ISS |
|
||||
| `HealthModule` | Нет | `modules/health/` | Health check endpoint |
|
||||
| `AuthModule` | Нет | `modules/auth/` | JWT auth, refresh cookie, guards |
|
||||
| `SecuritiesModule` | Нет | `modules/securities/` | Поиск инструментов |
|
||||
@ -79,17 +79,17 @@ flowchart TB
|
||||
|
||||
### MoexClientModule
|
||||
|
||||
Глобальный HTTP-клиент для MOEX ISS.
|
||||
Модуль для MOEX ISS, разделённый на `MoexHttpClient` и domain-specific клиенты.
|
||||
|
||||
- Rate limiter: p-queue (10 req/s по умолчанию, настраивается через `MOEX_RATE_LIMIT`)
|
||||
- Circuit breaker: открывается после 5 ошибок, сбрасывается через 30s
|
||||
- Все ответы нормализуются из табличного формата MOEX в доменные типы
|
||||
- `MoexHttpClient` — rate limiter (p-queue, 10 req/s), circuit breaker (5 errors → 30s open), ISS JSON parsing.
|
||||
- Domain clients — `MoexSecuritiesClient`, `MoexMarketDataClient`, `MoexCandlesClient`, `MoexHistoryClient`, `MoexDividendsClient`.
|
||||
- Все ответы нормализуются из табличного формата MOEX в доменные типы.
|
||||
|
||||
### HealthModule
|
||||
|
||||
Проверка состояния сервиса.
|
||||
|
||||
- `GET /api/v1/health` → `{ status: 'ok', timestamp, uptime }`
|
||||
- `GET /api/v1/health` → `{ data: { status, timestamp, uptime, checks }, meta }`
|
||||
|
||||
### AuthModule
|
||||
|
||||
|
||||
@ -2,9 +2,21 @@
|
||||
|
||||
## Обзор
|
||||
|
||||
`MoexClientService` (`apps/backend/src/modules/moex-client/moex-client.service.ts`) — HTTP-клиент для MOEX ISS API.
|
||||
MOEX integration is split into a shared HTTP infrastructure client and focused domain clients under
|
||||
`apps/backend/src/modules/moex-client/`:
|
||||
|
||||
## Rate limiting
|
||||
- `MoexHttpClient` — request queue, rate limiting, circuit breaker, ISS JSON parsing.
|
||||
- `MoexSecuritiesClient` — security search and descriptions.
|
||||
- `MoexMarketDataClient` — share/bond market data and batch position enrichment.
|
||||
- `MoexCandlesClient` — candle history.
|
||||
- `MoexHistoryClient` — share and bond history.
|
||||
- `MoexDividendsClient` — dividend calendar.
|
||||
|
||||
## `MoexHttpClient`
|
||||
|
||||
Базовый HTTP-клиент, используемый всеми domain-клиентами. Реализован в `moex-http-client.service.ts`.
|
||||
|
||||
### Rate limiting
|
||||
|
||||
Использует `p-queue`:
|
||||
|
||||
@ -17,7 +29,7 @@ this.queue = new PQueue({
|
||||
|
||||
Все запросы к MOEX проходят через очередь — не более `MOEX_RATE_LIMIT` запросов в секунду.
|
||||
|
||||
## Circuit breaker
|
||||
### Circuit breaker
|
||||
|
||||
Состояние: закрыт → открыт → полуоткрыт (через таймаут).
|
||||
|
||||
@ -30,7 +42,7 @@ private circuitErrorCount = 0;
|
||||
- В открытом состоянии все запросы мгновенно падают с ошибкой `"Circuit breaker is open"`
|
||||
- Через `MOEX_CIRCUIT_BREAKER_RESET_SECONDS` (30) автоматически сбрасывается
|
||||
|
||||
## Метод request
|
||||
### Метод request
|
||||
|
||||
```typescript
|
||||
private async request<T>(path: string, params?: Record<string, string>): Promise<T>
|
||||
@ -40,7 +52,7 @@ private async request<T>(path: string, params?: Record<string, string>): Promise
|
||||
- Устанавливает `iss.meta=off` (отключает метаданные)
|
||||
- Таймаут: 10s
|
||||
|
||||
## Разбор response
|
||||
### Разбор response
|
||||
|
||||
MOEX возвращает данные в табличном формате:
|
||||
|
||||
@ -55,19 +67,17 @@ MOEX возвращает данные в табличном формате:
|
||||
|
||||
Метод `extractTable` преобразует это в массив объектов по колонкам.
|
||||
|
||||
## Доступные методы MOEX
|
||||
## Domain clients
|
||||
|
||||
| Метод | MOEX path | Описание |
|
||||
|---|---|---|
|
||||
| `searchSecurities` | `/securities?q=` | Поиск инструментов |
|
||||
| `getSecurityDescription` | `/securities/{secid}` | Спецификация |
|
||||
| `getShareMarketData` | `/engines/stock/markets/shares/securities/{secid}` | Рыночные данные акции (board: TQBR) |
|
||||
| `getBondData` | `/engines/stock/markets/bonds/securities/{secid}` | Данные облигации (board: TQCB) |
|
||||
| `getBondMarketData` | `/engines/stock/markets/bonds/securities/{secid}` | Рыночные данные облигации |
|
||||
| `getDividends` | `/securities/{secid}/dividends` | Дивиденды |
|
||||
| `getCandles` | `/engines/{engine}/markets/{market}/securities/{secid}/candles` | Свечи |
|
||||
| `getHistory` | `/engines/stock/markets/shares/securities/{secid}` | История акций |
|
||||
| `getBondHistory` | `/engines/stock/markets/bonds/securities/{secid}` | История облигаций |
|
||||
Каждый domain-клиент использует `MoexHttpClient` для HTTP и предоставляет свои методы:
|
||||
|
||||
| Client | Методы |
|
||||
|---|---|
|
||||
| `MoexSecuritiesClient` | `searchSecurities`, `getSecurityDescription` |
|
||||
| `MoexMarketDataClient` | `getShareMarketData`, `getShareMarketDataBatch`, `getBondData`, `getBondMarketData`, `getBondPositionDataBatch` |
|
||||
| `MoexCandlesClient` | `getCandles` |
|
||||
| `MoexHistoryClient` | `getShareHistory`, `getBondHistory` |
|
||||
| `MoexDividendsClient` | `getDividends` |
|
||||
|
||||
## MOEX ISS types
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
export function envelope(data: unknown) {
|
||||
return {
|
||||
data: { data, meta: { fromCache: false, cachedAt: null } },
|
||||
data,
|
||||
meta: { fromCache: false, cachedAt: null },
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user