Compare commits
8
Commits
v0.2.3
..
9cc9fbdcff
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9cc9fbdcff | ||
|
|
9b3558f96c | ||
|
|
ca5dbcb382 | ||
|
|
4796d9d3f0 | ||
|
|
5d3835e796 | ||
|
|
516e43203e | ||
|
|
e4232138d0 | ||
|
|
d6e6c4ace5 |
+11
-8
@@ -160,8 +160,10 @@ HTTP/e2e naming и расположение — в [Testing](conventions/testing
|
|||||||
|
|
||||||
`*.module.ts` задаёт DI boundary; `*.api.ts` перечисляет используемые другими
|
`*.module.ts` задаёт DI boundary; `*.api.ts` перечисляет используемые другими
|
||||||
модулями providers, функции и типы. Внешний production import идёт через этот
|
модулями providers, функции и типы. Внешний production import идёт через этот
|
||||||
API или файл Nest module. Чистый `integrations/tbank/decimal.ts` — отдельный
|
API или файл Nest module. Чистые `integrations/tbank/decimal.ts` и
|
||||||
публичный вход для protobuf conversion: импорт арифметики не загружает DI/Prisma.
|
`modules/investments/operations/domain/operations-sync-plan.ts` — отдельные
|
||||||
|
публичные входы для protobuf conversion и interval rules: импорт расчётов
|
||||||
|
не загружает DI/Prisma.
|
||||||
Внутри модуля используй прямые локальные импорты.
|
Внутри модуля используй прямые локальные импорты.
|
||||||
Tests могут импортировать внутренний owner для проверки поведения и mocks.
|
Tests могут импортировать внутренний owner для проверки поведения и mocks.
|
||||||
Новый export требует текущего потребителя; controller и persistence остаются
|
Новый export требует текущего потребителя; controller и persistence остаются
|
||||||
@@ -233,8 +235,8 @@ protobuf units/nano conversion — T-Bank integration. Domain используе
|
|||||||
Общий выбор symbolic values и числовых policies —
|
Общий выбор symbolic values и числовых policies —
|
||||||
[Domain values](conventions/engineering.md#domain-values).
|
[Domain values](conventions/engineering.md#domain-values).
|
||||||
Сохраняй strict TS и explicit boundary types. Для недоверенного input выбирай
|
Сохраняй strict TS и explicit boundary types. Для недоверенного input выбирай
|
||||||
`unknown` + runtime narrowing; отключённый lint `no-explicit-any` не делает
|
`unknown` + runtime narrowing; ESLint запрещает explicit `any`
|
||||||
`any` нормой domain/application model. `declare` допустим для заполняемых извне
|
в domain/application model, тестах и конфигурации TypeScript. `declare` допустим для заполняемых извне
|
||||||
DTO fields, не для сокрытия неинициализированного owned state.
|
DTO fields, не для сокрытия неинициализированного owned state.
|
||||||
|
|
||||||
OpenAPI enum metadata и runtime validation должны читать тот же vocabulary,
|
OpenAPI enum metadata и runtime validation должны читать тот же vocabulary,
|
||||||
@@ -244,10 +246,11 @@ OpenAPI enum metadata и runtime validation должны читать тот ж
|
|||||||
сохраняй; generated Prisma/protocol code вручную не меняй.
|
сохраняй; generated Prisma/protocol code вручную не меняй.
|
||||||
|
|
||||||
`@typescript-eslint/no-magic-numbers` включён как error; базовое ESLint rule
|
`@typescript-eslint/no-magic-numbers` включён как error; базовое ESLint rule
|
||||||
отключено в пользу TS-версии. Исключения для очевидных чисел и их bigint форм,
|
отключено в пользу TS-версии. Общего списка `ignore` для чисел и bigint нет:
|
||||||
индексов, default values, enum/type declarations и readonly properties заданы
|
значения, проверяемые правилом, получают предметные имена у владельца.
|
||||||
в ESLint config. Test fixtures/expected values остаются inline, остальные lint
|
Исключения для индексов, default values, enum/type declarations и readonly
|
||||||
правила продолжают действовать. Numeric policy получает предметное имя и единицы;
|
properties заданы в ESLint config. Test fixtures/expected values остаются inline,
|
||||||
|
остальные lint правила продолжают действовать. Numeric policy получает предметное имя и единицы;
|
||||||
semantic magic strings проверяются conventions/review без нового инструмента.
|
semantic magic strings проверяются conventions/review без нового инструмента.
|
||||||
|
|
||||||
## Logging
|
## Logging
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ application/domain outcome → application mapping → HttpExceptionFilter
|
|||||||
```
|
```
|
||||||
|
|
||||||
Сохраняй принятый профиль RFC 9457: `status`, стабильный публичный `code`,
|
Сохраняй принятый профиль RFC 9457: `status`, стабильный публичный `code`,
|
||||||
для validation — `errors: [{ pointer, detail }]`. Точный контракт и известное
|
для validation — `errors: [{ pointer, detail }]`. Точный контракт validation
|
||||||
расхождение validation описаны в [HTTP API](http-api.md#источник-контракта).
|
описан в [HTTP API](http-api.md#источник-контракта).
|
||||||
Не добавляй `type/title/instance` как обязательные поля без contract change.
|
Не добавляй `type/title/instance` как обязательные поля без contract change.
|
||||||
|
|
||||||
Чистый domain не импортирует Nest HTTP exceptions. Существующий application
|
Чистый domain не импортирует Nest HTTP exceptions. Существующий application
|
||||||
|
|||||||
@@ -83,6 +83,6 @@ artifact отдельно; backend не читает их репозитории
|
|||||||
HTTP prefix — `/api/v1`; Swagger доступен согласно `src/config/swagger.config.ts`.
|
HTTP prefix — `/api/v1`; Swagger доступен согласно `src/config/swagger.config.ts`.
|
||||||
Общий error response — `application/problem+json` со `status` и публичным `code`.
|
Общий error response — `application/problem+json` со `status` и публичным `code`.
|
||||||
Validation требует `400 / VALIDATION_ERROR` и `errors: [{ pointer, detail }]`.
|
Validation требует `400 / VALIDATION_ERROR` и `errors: [{ pointer, detail }]`.
|
||||||
Известное ограничение: ValidationPipe сейчас формирует строковые сообщения,
|
ValidationPipe сохраняет структурированные field errors без `target/value`,
|
||||||
а filter ожидает структурированные field errors; schema parity не доказывает
|
а filter формирует JSON pointers, включая вложенные поля. Schema parity не
|
||||||
правильность `errors`. Изменение требует проверки реального HTTP pipeline.
|
доказывает правильность `errors`; изменения проверяются через реальный HTTP pipeline.
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"singleQuote": true,
|
|
||||||
"trailingComma": "all"
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,673 @@
|
|||||||
|
# Аудит backend WealthLedger и план исправлений
|
||||||
|
|
||||||
|
Дата аудита: 2026-09-27. Репозиторий: `/Users/ksv741/Project/vibe/WealthLedger/backend`.
|
||||||
|
База: `516e43203eb3fee8e6a0c7018be2fee11f1b900c`, ветка `codex/investment-contracts`.
|
||||||
|
При аудите рабочее дерево было чистым; production-код не изменялся.
|
||||||
|
Этот документ сохраняет результаты аудита и задаёт проверяемый план исправлений.
|
||||||
|
Само сохранение документа не означает выполнения исправлений.
|
||||||
|
|
||||||
|
Номера строк относятся к указанному commit. Перед изменением повторно найти
|
||||||
|
symbol и проверить актуальный flow: после предыдущих исправлений строки сдвинутся.
|
||||||
|
Все относительные пути и ссылки относятся только к backend.
|
||||||
|
|
||||||
|
## Общая оценка
|
||||||
|
|
||||||
|
Backend имеет понятных владельцев ответственности: контроллеры тонкие,
|
||||||
|
денежные расчёты преимущественно точные, транзакции и очереди сосредоточены
|
||||||
|
у своих владельцев. Массовое дробление файлов не требуется.
|
||||||
|
Наиболее проблемные области — обработка ошибок auth, проверка ответов MOEX,
|
||||||
|
согласование состояния фоновой синхронизации и временных признаков кешированных данных.
|
||||||
|
|
||||||
|
Изучены локальные [AGENTS.md](AGENTS.md), [порядок работы](.ai/conventions/engineering.md),
|
||||||
|
[архитектура](.ai/architecture.md) и активированные темы HTTP, errors, data,
|
||||||
|
testing, security, integrations и observability. Соседние репозитории не использовались.
|
||||||
|
|
||||||
|
Инвентаризированы 135 production-файлов TypeScript, 16 004 строки, 17 Nest module-файлов.
|
||||||
|
Generated Prisma, vendor protocols, миграции и тесты отделены от production-рейтинга.
|
||||||
|
|
||||||
|
Приоритеты: **высокий** — существенный риск безопасности или искажения данных;
|
||||||
|
**средний** — ограниченный дефект поведения, контракта или доказанная стоимость связности;
|
||||||
|
**низкий** — локальное упрощение. Уверенность всех перечисленных находок высокая
|
||||||
|
для описанного механизма; ограничения конкретного воспроизведения указаны отдельно.
|
||||||
|
|
||||||
|
## План выполнения и границы
|
||||||
|
|
||||||
|
1. Прочитать действующий backend AGENTS и активированные conventions; зафиксировать
|
||||||
|
текущие HEAD/status. Сохранить существующие staged/unstaged/untracked изменения.
|
||||||
|
2. Работать по находкам A01–A10 и cleanup C01–C07 ниже, в порядке пакетов из таблицы.
|
||||||
|
Перед каждым исправлением перечитать владельца целиком, callers, связанные tests
|
||||||
|
и 1–3 релевантных примера. Если факт больше не воспроизводится, отметить это
|
||||||
|
с доказательством вместо механического применения рекомендации.
|
||||||
|
3. Для дефекта сначала получить падающую проверку наблюдаемого результата на самой
|
||||||
|
дешёвой надёжной boundary. Для concurrency/atomicity использовать реальную
|
||||||
|
изолированную SQLite; mock race не доказывает DB-инвариант.
|
||||||
|
4. Исправлять у существующего владельца минимальным связанным diff. Сохранять
|
||||||
|
precision, ownership, public error codes, transaction/fencing, cache isolation,
|
||||||
|
limiter и выполняющиеся promises. Предложения ниже задают результат, а не
|
||||||
|
обязательную форму реализации.
|
||||||
|
5. После каждого пакета выполнить targeted checks; в конце — актуальные обязательные
|
||||||
|
gates по backend conventions. Перед каждой Node-командой выполнить `nvm use --silent`.
|
||||||
|
6. Сохранить исходный снимок аудита; результаты реализации записывать в таблицу
|
||||||
|
«Статус исправлений». Для каждого ID указать diff/решение, команды и результат,
|
||||||
|
остаточный риск либо точную причину невыполнения.
|
||||||
|
|
||||||
|
| Пакет | Пункты | Условие завершения |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1. Auth и безопасные ошибки | A01, A02 | Отказы хранилища не маскируются; секреты не попадают в completion log |
|
||||||
|
| 2. MOEX trust boundary | A03 | Malformed response не публикуется как полный результат; pagination завершается |
|
||||||
|
| 3. Статус синхронизации | A04 | Screen учитывает состояние successor через владельца operations |
|
||||||
|
| 4. Свечи | A05 | Force не теряется при coalescing; forced publication остаётся атомарной |
|
||||||
|
| 5. Свежесть и время | A06, A07 | Stale-флаг актуален; wire timestamp совпадает с используемым при фильтрации |
|
||||||
|
| 6. HTTP validation | A08 | Реальный pipeline возвращает структурированные field errors |
|
||||||
|
| 7. Связность и удаление legacy | A09, A10, C01–C07 | Живые boundaries сохранены; лишние реализации и exports удалены |
|
||||||
|
|
||||||
|
Пакеты независимы по цели, но могут пересекаться файлами и общими fixtures.
|
||||||
|
Параллелить только области с непересекающимся владением файлами, затем выполнить
|
||||||
|
общую проверку. A02 и A08 изменяют один HTTP filter и должны быть согласованы.
|
||||||
|
|
||||||
|
В scope входят исправления подтверждённых находок и их regression tests.
|
||||||
|
Гипотезы в конце документа не являются задачами на изменение кода.
|
||||||
|
Новые зависимости, generic repositories, scheduler framework, интерфейсы ради
|
||||||
|
паттерна, schema migrations и size-only splits для этих исправлений не требуются.
|
||||||
|
Отдельную необходимость такого расширения следует доказать до реализации.
|
||||||
|
Коммиты, push и PR выполняются только по отдельному запросу пользователя.
|
||||||
|
|
||||||
|
## Подтверждённые находки
|
||||||
|
|
||||||
|
### A01. Auth lifecycle смешивает invalid credentials и operational failure
|
||||||
|
|
||||||
|
**Приоритет:** высокий. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места и потребители:** [AuthService.logout, строки 104–126](src/modules/auth/application/auth.service.ts),
|
||||||
|
[AuthController.logout, 95–104; refresh, 85–91](src/modules/auth/presentation/auth.controller.ts).
|
||||||
|
|
||||||
|
Общий catch в logout подавляет JWT verification errors и отказ Prisma при записи
|
||||||
|
`revokedAt`. Controller затем очищает cookie и возвращает 204, хотя серверная
|
||||||
|
сессия осталась действительной. Сохранённая копия refresh token продолжает работать.
|
||||||
|
Смежное проявление: refresh controller удаляет cookie при любой ошибке, включая
|
||||||
|
временный отказ БД, без доказательства недействительности токена.
|
||||||
|
|
||||||
|
**Доказательство:** inline fault injection на настоящих AuthService, JwtService
|
||||||
|
и AuthController с синтетической сессией подтвердил:
|
||||||
|
|
||||||
|
```text
|
||||||
|
logoutResolved=true
|
||||||
|
cookieCleared=true
|
||||||
|
sessionNotRevoked=true
|
||||||
|
sameRefreshTokenStillUsable=true
|
||||||
|
unexpectedRefreshErrorPropagated=true
|
||||||
|
validCookieRemoved=true
|
||||||
|
```
|
||||||
|
|
||||||
|
Это доказательство обработки injected boundary failure, а не реального отказа БД.
|
||||||
|
[Auth HTTP suite](test/app.e2e-spec.ts) проверяет обычный logout, но не этот отказ.
|
||||||
|
Нарушен [контракт отзыва сессии](.ai/conventions/security-auth.md): идемпотентность
|
||||||
|
не превращает несостоявшуюся запись в успешную.
|
||||||
|
|
||||||
|
**Минимальное действие:** ограничить подавление ошибок logout недействительным JWT;
|
||||||
|
ошибки хранилища пробрасывать. При refresh очищать cookie только при установленном
|
||||||
|
auth failure. Существующий AuthService.refresh уже отделяет verification от DB reads;
|
||||||
|
BankCardsRepository.write также пробрасывает неизвестные ошибки.
|
||||||
|
|
||||||
|
**Приёмка:**
|
||||||
|
|
||||||
|
- Отсутствующий/недействительный/уже отозванный refresh сохраняет идемпотентный logout.
|
||||||
|
- Ошибка записи revocation не возвращает фиктивный 204.
|
||||||
|
- Успешный logout делает последующий refresh невозможным.
|
||||||
|
- Временный отказ refresh не удаляет действующую cookie, повтор после восстановления возможен.
|
||||||
|
- Проверены status/code/cookie через configured HTTP; успешный отзыв — с SQLite.
|
||||||
|
|
||||||
|
**Риск:** сохранить существующую семантику недействительных токенов. Изменение
|
||||||
|
access-JWT lifetime или введение replay history не входят в этот пункт.
|
||||||
|
|
||||||
|
### A02. Многострочное сообщение исключения попадает в completion log
|
||||||
|
|
||||||
|
**Приоритет:** высокий. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места:** [HttpExceptionFilter, 30–37](src/common/filters/http-exception.filter.ts).
|
||||||
|
**Потребители:** [RequestLoggingMiddleware, 43–57](src/common/logging/request-logging.middleware.ts),
|
||||||
|
[StructuredLogger, 47–63](src/common/logging/structured-logger.service.ts).
|
||||||
|
|
||||||
|
Фильтр удаляет только первую строку `exception.stack`. Остальные строки
|
||||||
|
многострочного Error.message сохраняются. Поле stack разрешено logger allowlist;
|
||||||
|
redaction HTTP body к нему не применяется.
|
||||||
|
|
||||||
|
**Воспроизведение:** configured HTTP app; AuthService.login выбрасывает синтетический
|
||||||
|
`Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET')`. Ответ остаётся
|
||||||
|
`500 / INTERNAL_SERVER_ERROR`, но completion log содержит вторую строку сообщения.
|
||||||
|
Реальные секреты не использовались. Существующий filter spec проверяет однострочное сообщение.
|
||||||
|
Нарушены [observability](.ai/conventions/observability.md) и security rules.
|
||||||
|
|
||||||
|
**Минимальное действие:** убрать передачу сырого stack через общую HTTP boundary,
|
||||||
|
сохранив code/request context. Если stack необходим, нужна проверенная форма кадров
|
||||||
|
без произвольного текста исключения; удаление только первой строки недостаточно.
|
||||||
|
|
||||||
|
**Приёмка:** multiline synthetic secrets отсутствуют в response и в конечном
|
||||||
|
payload logger, а status/code/correlation сохраняются. Проверить настоящий
|
||||||
|
filter → middleware → logger, не только mock вызова filter.
|
||||||
|
|
||||||
|
**Риск:** диагностическая подробность может уменьшиться; raw message возвращать нельзя.
|
||||||
|
|
||||||
|
### A03. MOEX malformed response превращается в полный пустой прогноз
|
||||||
|
|
||||||
|
**Приоритет:** высокий. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Место:** [MoexClient, 122–142 и 163–165](src/integrations/moex/moex.client.ts).
|
||||||
|
Отсутствующий запрошенный ISS block преобразуется в `[]`. Неполный cursor может
|
||||||
|
завершить чтение с частичными данными; cursor с нулевым pageSize может зациклить его.
|
||||||
|
|
||||||
|
**Реальная цепочка:** [CatalogEnrichmentService, 444 и 509–548](src/modules/investments/instruments/application/catalog-enrichment.service.ts)
|
||||||
|
публикует `bondEvents: []`; readMany считает существующий row complete;
|
||||||
|
[UpcomingEventsService, 137–197](src/modules/investments/upcoming-events/upcoming-events.service.ts)
|
||||||
|
строит пустые events/totals; [ForecastRepository, 124–150](src/modules/investments/portfolio/infrastructure/forecast.repository.ts)
|
||||||
|
может заменить прежний непустой forecast. Владелец protocol validation — integration client.
|
||||||
|
|
||||||
|
**Воспроизведение:** настоящий MoexClient с mock fetch HTTP 200 без coupons/offers
|
||||||
|
вернул `[]`. Cursor `INDEX=0,TOTAL=1,PAGESIZE=0` дал пять запросов `start=0`;
|
||||||
|
проба остановлена искусственной ошибкой. Timeout каждого fetch не ограничивает весь цикл.
|
||||||
|
|
||||||
|
**Расхождение тестов:** [moex.client.spec, 97–107](src/integrations/moex/moex.client.spec.ts)
|
||||||
|
считает отсутствующий block пустым результатом;
|
||||||
|
[upcoming-events.e2e, 439–451](test/upcoming-events.e2e-spec.ts) обещает обратное,
|
||||||
|
но подменяет весь клиент готовым rejection и не проверяет parser.
|
||||||
|
|
||||||
|
**Минимальное действие:** различать отсутствующий/повреждённый block и корректный
|
||||||
|
`data: []`; проверять структуру строк и cursor, положительный pageSize и строгое
|
||||||
|
продвижение start. Нарушение протокола → `MOEX_UNAVAILABLE`, без частичного success.
|
||||||
|
|
||||||
|
**Приёмка:**
|
||||||
|
|
||||||
|
- Malformed block/cursor не меняет сохранённый полный календарь/forecast.
|
||||||
|
- Корректный пустой block остаётся успешным пустым результатом.
|
||||||
|
- Непродвигающаяся pagination завершается ошибкой, без бесконечных fetch.
|
||||||
|
- Семантика HTTP 404 проверена отдельно и не изменена случайно.
|
||||||
|
- Downstream regression использует настоящий MoexClient с mock fetch, а не mock rejection клиента.
|
||||||
|
|
||||||
|
**Риск:** перепутать законное отсутствие данных с ошибкой protocol shape.
|
||||||
|
|
||||||
|
### A04. Screen sync сообщает succeeded до завершения successor
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места:** [TbankSyncService.status, 330–345](src/modules/investments/tbank-sync/tbank-sync.service.ts),
|
||||||
|
[TbankSyncRepository.read, 70–80](src/modules/investments/tbank-sync/tbank-sync.repository.ts).
|
||||||
|
[Operations repository, 441–445](src/modules/investments/operations/infrastructure/brokerage-operations.repository.ts)
|
||||||
|
помечает объединяемую группу `superseded` и сохраняет successorId. Владелец операций
|
||||||
|
умеет разрешать цепочку в observe, строки 564–590, но screen читает прямого child.
|
||||||
|
|
||||||
|
**Сценарий:** две активные screen-группы на части января; третья объединяет интервалы.
|
||||||
|
Screen вытесненной группы сообщает succeeded, хотя successor ещё running; его
|
||||||
|
последующая ошибка также теряется.
|
||||||
|
|
||||||
|
**Воспроизведение настоящего status с mocked persistence:**
|
||||||
|
|
||||||
|
```text
|
||||||
|
screenState=succeeded
|
||||||
|
resource.availability=missing
|
||||||
|
resource.sync.state=running
|
||||||
|
actualOperationState=running
|
||||||
|
```
|
||||||
|
|
||||||
|
SQLite bridge покрыт [operations-sync e2e, 455–474](test/tbank-operations-sync.e2e-spec.ts),
|
||||||
|
но существующая проверка наблюдает operations.observe, а не screen status.
|
||||||
|
|
||||||
|
**Минимальное действие:** разрешать operations successors через существующего
|
||||||
|
владельца перед агрегацией screen state/progress. Не копировать второй алгоритм
|
||||||
|
разрешения цепочки в screen service.
|
||||||
|
|
||||||
|
**Приёмка:** configured HTTP + SQLite bridge; задержанный successor → running,
|
||||||
|
затем успех → succeeded или отказ → failed; progress согласован, чужая revision
|
||||||
|
не видна. **Риск:** fencing, цепочки successors и корректный подсчёт progress.
|
||||||
|
|
||||||
|
### A05. Force обновления свечей теряется при coalescing
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места:** [CandleService.request/load, 326–365](src/modules/investments/instruments/application/candle.service.ts),
|
||||||
|
[CandleRepository.reserve, 76–82](src/modules/investments/instruments/infrastructure/candle.repository.ts).
|
||||||
|
Публичный caller: [TbankSyncService, 288–306](src/modules/investments/tbank-sync/tbank-sync.service.ts)
|
||||||
|
вызывает candles.request с force=true; candleRange необязателен, ключ может совпасть
|
||||||
|
с ordinary GET/prefetch.
|
||||||
|
|
||||||
|
При launch=false service возвращает существующий id без сохранения новых force/priority.
|
||||||
|
При присоединении cross-user observer требования также не повышаются.
|
||||||
|
|
||||||
|
**Воспроизведение настоящего класса с mocked repository/upstream:** январь покрыт,
|
||||||
|
ordinary period=all заблокирован перед загрузкой detail, затем приходит force all.
|
||||||
|
После release единственный RPC идёт от `2026-02-01T00:00:00.000Z` до
|
||||||
|
`2026-02-02T12:00:00.000Z`; январь не перечитан. Исправленные исторические значения
|
||||||
|
остаются прежними. Existing candle suite отдельно проверяет force и coalescing.
|
||||||
|
|
||||||
|
**Минимальное действие:** сохранить forced требование и выполнить полную reconciliation.
|
||||||
|
Если gap-план уже начат, безопасно перепланировать или выполнить следующую forced
|
||||||
|
попытку. Простого `force ||= true` после публикации первых окон недостаточно.
|
||||||
|
Аналог повышения требований есть в CatalogDiscoveryService, но его алгоритм нельзя
|
||||||
|
механически переносить на staged свечи.
|
||||||
|
|
||||||
|
**Приёмка:** ordinary load + force того же scope действительно обновляют уже
|
||||||
|
закрытую свечу. Возвращённый work ID завершается только после выполнения forced
|
||||||
|
требования с актуальным диапазоном запроса. Проверить join до запуска и после
|
||||||
|
публикации первого обычного окна, включая observer другого пользователя;
|
||||||
|
экранный запрос получает экранный приоритет. Ошибка следующего forced окна сохраняет
|
||||||
|
прежнюю историю и timestamps; user/revision fencing сохраняется.
|
||||||
|
Proof атомарности — существующая SQLite boundary.
|
||||||
|
|
||||||
|
**Риск:** высокий риск неверного локального исправления из-за staged/atomic publication.
|
||||||
|
|
||||||
|
### A06. Payout snapshot замораживает positionIsStale
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Место:** [ForecastRepository.resolve, 132–137](src/modules/investments/portfolio/infrastructure/forecast.repository.ts).
|
||||||
|
**Потребители:** [StockIncomeService, 67–87 и 161–163](src/modules/investments/instruments/stocks/application/stock-income.service.ts),
|
||||||
|
[BondIncomeService, 180–182](src/modules/investments/instruments/bonds/application/bond-income.service.ts).
|
||||||
|
|
||||||
|
Истечение 60-секундного portfolio TTL меняет isStale, но не source revision/timestamps.
|
||||||
|
Repository возвращает прежний payload вместо нового candidate. Возможны одновременно
|
||||||
|
`meta.freshness: stale` и `data.positionIsStale: false`.
|
||||||
|
|
||||||
|
**Воспроизведение:** настоящий repository с mocked transaction; candidate false,
|
||||||
|
затем true при тех же версиях → повторный результат false, всего одна запись.
|
||||||
|
Pure payout tests принимают stale input, но не проверяют aging persisted forecast.
|
||||||
|
|
||||||
|
**Минимальное действие:** вычислять возраст сохранённой позиции при выдаче по её
|
||||||
|
positionAt и действующей freshness policy. Учитывать именно позицию сохранённого
|
||||||
|
fallback, а не случайно подставлять свежесть более нового несовместимого портфеля.
|
||||||
|
Не сравнивать весь candidate без разбора: текущий calculatedAt у events вызовет
|
||||||
|
запись на каждом чтении. Не менять financial revision только из-за хода времени.
|
||||||
|
|
||||||
|
**Приёмка:** controllable clock, TTL истёк без изменения источников, sync=observe:
|
||||||
|
stale=true, суммы и source timestamps прежние, новых RPC нет; fallback остаётся
|
||||||
|
согласованным. **Риск:** смешение возраста сохранённой и текущей позиции.
|
||||||
|
|
||||||
|
### A07. Timestamp операций расходится между persistence и wire
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Место:** [brokerage-operation.mapper, 85–90](src/modules/investments/operations/infrastructure/brokerage-operation.mapper.ts)
|
||||||
|
игнорирует nanos; [repository, 653–657 и publish](src/modules/investments/operations/infrastructure/brokerage-operations.repository.ts)
|
||||||
|
учитывает миллисекунды. Consumers mapper: BrokerageOperationsService, обычный ledger
|
||||||
|
и income reads (строки 359 и 619 на базе аудита).
|
||||||
|
|
||||||
|
**Воспроизведение:** seconds=1768000000, nanos=600000000 → persistence
|
||||||
|
`2026-01-09T23:06:40.600Z`, wire `2026-01-09T23:06:40.000Z`.
|
||||||
|
Запрос from=`…40.500Z` возвращает строку с видимым временем раньше from.
|
||||||
|
Existing mapper specs проверяют money/quantity, но не это соответствие.
|
||||||
|
|
||||||
|
**Минимальное действие:** согласовать конвертацию protobuf timestamp; при возможности
|
||||||
|
использовать уже сохранённый occurredAt для wire. Предотвратить дальнейшее расхождение
|
||||||
|
реализаций без создания универсальной библиотеки дат.
|
||||||
|
|
||||||
|
**Приёмка:** subsecond mapper case и HTTP boundary внутри секунды; порядок/cursor,
|
||||||
|
обычный ledger и income используют согласованное время. **Риск:** исправляется
|
||||||
|
публичное значение timestamp; формат и точность Money сохраняются.
|
||||||
|
|
||||||
|
### A08. Configured validation response теряет ошибки полей
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места:** [configureApp, 29](src/main.ts),
|
||||||
|
[HttpExceptionFilter, 44–48 и 70–78](src/common/filters/http-exception.filter.ts).
|
||||||
|
ValidationPipe выдаёт message:string[], filter приводит его к ValidationError[]
|
||||||
|
и ищет constraints. children вложенных ошибок также не обходятся.
|
||||||
|
|
||||||
|
**Configured HTTP reproduction:** invalid email и отсутствующий password:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"status":400,"code":"VALIDATION_ERROR","errors":[]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ожидаемый [HTTP contract](.ai/conventions/http-api.md) требует pointer/detail.
|
||||||
|
Conventions уже фиксируют это известное расхождение. OpenAPI parity проверяет
|
||||||
|
schema, но не наблюдаемый response pipeline.
|
||||||
|
|
||||||
|
**Минимальное действие:** согласовать exceptionFactory и filter, сформировать
|
||||||
|
структурированные ошибки, включая вложенные поля, без target/value исходного DTO.
|
||||||
|
|
||||||
|
**Приёмка:** реальные requests credentials и nested Money дают непустые корректные
|
||||||
|
pointer/detail; status/code/content-type сохраняются; неизвестные исключения
|
||||||
|
по-прежнему безопасны. Проверить согласование с A02 и публичной metadata.
|
||||||
|
**Риск:** public error shape и корректность вложенных путей.
|
||||||
|
|
||||||
|
### A09. Planner зависит от service barrel и образует runtime import cycle
|
||||||
|
|
||||||
|
**Приоритет:** средний. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Места:** [investment-sync-plan, 3–6](src/modules/investments/investment-sync-plan.ts)
|
||||||
|
→ [operations.api](src/modules/investments/operations/operations.api.ts)
|
||||||
|
→ operations services → investment-sync-plan.
|
||||||
|
|
||||||
|
Алгоритму нужны interval rules, но barrel загружает services, TbankClient и Prisma.
|
||||||
|
[Planner spec, строка 1](src/modules/investments/investment-sync-plan.spec.ts) уже
|
||||||
|
вынужден mock Prisma. Это доказанная стоимость связности; production crash из-за
|
||||||
|
цикла не обнаружен. Type-only цикл T-Bank records — отдельный безвредный случай.
|
||||||
|
|
||||||
|
**Минимальное действие:** предоставить interval rules чистый публичный вход,
|
||||||
|
аналогичный разрешённому integrations/tbank/decimal.ts; service API оставить отдельно.
|
||||||
|
Не заменять cycle на forwardRef и не вводить новый DI слой.
|
||||||
|
|
||||||
|
**Приёмка:** planner импортируется/тестируется без Prisma mock; cycle устранён,
|
||||||
|
interval semantics и DI initialization сохранены. **Риск:** низкий, import/export surface.
|
||||||
|
|
||||||
|
### A10. Неиспользуемый legacy T-Bank access flow
|
||||||
|
|
||||||
|
**Приоритет:** низкий. **Уверенность:** высокая.
|
||||||
|
|
||||||
|
**Место:** [TbankAccessService, 255–330](src/integrations/tbank/tbank-access.service.ts).
|
||||||
|
listSupportedAccounts/withSupportedAccounts/withConnection/withAccount/
|
||||||
|
withAccountForConnection/private connection вызываются только внутри собственной
|
||||||
|
цепочки и tests. Проверены production consumers, DI и decorators.
|
||||||
|
|
||||||
|
Legacy flow поддерживает generation=hash(ciphertext), тогда как живой persisted
|
||||||
|
flow использует DB revision, local и tokenForAttempt. Поддерживаются две модели
|
||||||
|
без production-потребности; около 76 строк, context types и TbankClient dependency.
|
||||||
|
|
||||||
|
**Минимальное действие:** повторно проверить callers на актуальном HEAD, удалить
|
||||||
|
legacy-цепочку, неиспользуемые context exports и зависимость; отдельно проверить
|
||||||
|
оставшихся consumers accessibleTbankAccount до его удаления.
|
||||||
|
|
||||||
|
**Приёмка:** нет мёртвой цепочки, живые access/invalid-token/revision/fencing cases
|
||||||
|
сохранены. Перенести полезные security assertions, если они были только в удаляемых
|
||||||
|
specs. **Риск:** удалить общее правило или полезную проверку вместе с legacy.
|
||||||
|
|
||||||
|
## Локальные упрощения
|
||||||
|
|
||||||
|
Все пункты: низкий приоритет, высокая уверенность. Перед удалением повторить поиск
|
||||||
|
callers; отсутствие production callers в базе аудита не гарантирует его на новом HEAD.
|
||||||
|
|
||||||
|
| ID | Место и доказательство | Минимальное действие и приёмка |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| C01 | [portfolio.service, 515–522](src/modules/investments/portfolio/application/portfolio.service.ts): локальный decimalFromString повторяет common parser без validation; callers position/value | Импортировать существующий common owner; удалить дубликат. Exact-money tests и typecheck. Текущая ошибка сумм не доказана; проверить допустимые входы. |
|
||||||
|
| C02 | [tbank.api](src/integrations/tbank/tbank.api.ts): TbankSyncAttempt импортируют напрямую семь внешних файлов sync/instruments; enrichment также обходит API для market types | Экспортировать используемые типы, перенаправить imports через API. TbankCoupon уже экспортируется. Typecheck и поиск обходов; runtime-риск минимален. |
|
||||||
|
| C03 | [auth.service, 190–192](src/modules/auth/application/auth.service.ts): normalizeEmail возвращает аргумент; register/login вызывают его, реальная нормализация в CredentialsDto | Удалить no-op, сохранить DTO transform. Existing HTTP case/whitespace tests; дополнительную нормализацию без необходимости не вводить. |
|
||||||
|
| C04 | [bank-card.calculations, 56–76](src/modules/banking/bank-cards/domain/bank-card.calculations.ts): string period используется только tests; production summary передаёт from/to | Сузить API до рабочего диапазона; перевести полезные unit cases. Проверить границы месяца/range. |
|
||||||
|
| C05 | [instrument-market, 39–51](src/modules/investments/instruments/application/instrument-market.ts): optional без consumers; [stock-position wrapper](src/modules/investments/instruments/stocks/application/stock-position.ts) нужен только своему spec | Удалить optional, перенаправить полезные wrapper tests на instrumentPosition. Сохранить fractional/mixed/offset holdings cases. |
|
||||||
|
| C06 | [portfolio.api, 2](src/modules/investments/portfolio/portfolio.api.ts): totalsByCurrency не имеет внешнего production consumer; внутренний использует mapper напрямую | Удалить только лишний export, mapper сохранить; typecheck. |
|
||||||
|
| C07 | [auth.controller.spec, 9–20](src/modules/auth/presentation/auth.controller.spec.ts): проверяет HTTP_CODE_METADATA через prototype; те же 200 проверяются configured HTTP suite | Удалить дублирующий wiring spec только при сохранении реальных HTTP status/cookie assertions. |
|
||||||
|
|
||||||
|
## Карта ответственности и проверенные сценарии
|
||||||
|
|
||||||
|
| Область / владелец | Интерфейс и consumers | Состояние, зависимости, инварианты и эффекты |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| App/config/common/Prisma | Composition root, configureApp, Money/decimal, logging | Env validation, HTTP pipeline, DB lifecycle, request context; общая арифметика без Nest/Prisma |
|
||||||
|
| Auth | Auth HTTP; guard/AccessPayload API для protected controllers | User/Session, bcrypt/JWT, refresh hash/CAS; cookies у controller |
|
||||||
|
| Bank cards/operations/categories | BankCardsController → профильные services | Ownership, archive/version/replay/tombstones; refund budget и перевод в общей transaction boundary |
|
||||||
|
| Bank summary | Controller → use case → repository → pure calculation | Согласованное чтение и BigInt-сводка по периоду |
|
||||||
|
| Brokerage accounts | HTTP/read API для screen → service → PortfolioService | Собственной persistence нет; missing membership отличается от confirmed empty |
|
||||||
|
| Portfolio/forecast | HTTP и API для instruments/events/accounts | Private user/revision/account snapshots; mapping/decimal; aggregate completeness; atomic dependency version checks |
|
||||||
|
| Operations | HTTP/API для income/screen | Local journal, signed cursor binding; durable work/staging, intervals, recovery, atomic reconciliation |
|
||||||
|
| Income analytics | HTTP/read API → Operations API | Period roles/completeness, grouping и точные signed totals по валютам; своей DB нет |
|
||||||
|
| Upcoming events | HTTP/read API → portfolio/calendars → forecast | Events по positions; missing calendar не равен пустому; redemption исключён из income totals |
|
||||||
|
| Catalog discovery/enrichment | Stock/bond services и public source APIs | Shared identity/aliases/source rows; private work, TTL, batching, coalescing и generation-fenced publication |
|
||||||
|
| Candles | Market services/screen → CandleService/Repository | Shared candles/coverage; mutable tail, gaps, windows, очередь и staged force replacement |
|
||||||
|
| Stock/bond position/income | Controllers → application services | UID/type matching, exact weighted cost, mixed currencies, payout estimates; Portfolio/Catalog/Forecast APIs |
|
||||||
|
| T-Bank connection | Guarded GET/PUT/DELETE | Проверка токена до replacement, AES-GCM, новая revision/cascade; failed validation сохраняет connection |
|
||||||
|
| T-Bank client/access/membership/metadata | Integration API для business modules | gRPC/TLS, единые limiter/retry/deadline; credentials, account access, membership и publication fencing |
|
||||||
|
| Screen sync | POST descriptor / GET status | Orchestration через APIs; durable children/attempts; passive observation |
|
||||||
|
| MOEX/NCR | Integration APIs → enrichment | ISS parser/pagination; NCR strict registry parser/exact ISIN/shared cache |
|
||||||
|
|
||||||
|
Прослежены auth/session flows; создание/изменение карт, операций, переводов,
|
||||||
|
возвратов и summary; ledger→sync→staging→publication; portfolio→mapping→snapshot;
|
||||||
|
payouts/events→forecast; catalog/candles и screen orchestration.
|
||||||
|
|
||||||
|
Повторной регистрации владельцев caches/queues и циклов Nest modules не обнаружено.
|
||||||
|
InstrumentSourcesModule позволяет portfolio пользоваться источниками без DI-цикла
|
||||||
|
с InstrumentsModule. Type-only цикл T-Bank records не является finding.
|
||||||
|
|
||||||
|
## Размеры production-файлов
|
||||||
|
|
||||||
|
Количество строк включает comments/blank lines. Размер — основание для чтения,
|
||||||
|
а не самостоятельный дефект. Обязательные splits не обоснованы.
|
||||||
|
|
||||||
|
| Файл | Строк | Решение и причина |
|
||||||
|
| --- | ---: | --- |
|
||||||
|
| [brokerage-operations.repository](src/modules/investments/operations/infrastructure/brokerage-operations.repository.ts) | 924 | Оставить: overlap groups, staging, recovery и publication держат общий transactional invariant |
|
||||||
|
| [catalog-enrichment.service](src/modules/investments/instruments/application/catalog-enrichment.service.ts) | 665 | Упростить локально: protocol boundary/imports; сохранить producers, batching, completions вместе |
|
||||||
|
| [brokerage-operations.service](src/modules/investments/operations/application/brokerage-operations.service.ts) | 636 | Оставить: ledger/income имеют различную completeness; generic builder добавит скрытые режимы |
|
||||||
|
| [tbank-sync.service](src/modules/investments/tbank-sync/tbank-sync.service.ts) | 595 | Упростить: разрешение successors вернуть operations owner, generic job framework не нужен |
|
||||||
|
| [tbank.client](src/integrations/tbank/tbank.client.ts) | 560 | Оставить: records/RPC methods и единый limiter/retry owner |
|
||||||
|
| [portfolio.service](src/modules/investments/portfolio/application/portfolio.service.ts) | 522 | Упростить: удалить duplicate parser, scheduling state не разрывать |
|
||||||
|
| [candle.service](src/modules/investments/instruments/application/candle.service.ts) | 481 | Оставить: исправить force join, сохранить queue/publication invariant |
|
||||||
|
| [catalog-discovery.repository](src/modules/investments/instruments/infrastructure/catalog-discovery.repository.ts) | 480 | Оставить: identity/aliases/source publication и CAS связны |
|
||||||
|
| [catalog-discovery.service](src/modules/investments/instruments/application/catalog-discovery.service.ts) | 390 | Оставить: search/detail и producer lifecycle имеют одного owner |
|
||||||
|
| [bank-operations.service](src/modules/banking/bank-cards/application/bank-operations.service.ts) | 343 | Оставить: разрыв validation/refund/transfer writes повышает риск |
|
||||||
|
| [tbank-access.service](src/integrations/tbank/tbank-access.service.ts) | 331 | Упростить удалением legacy flow |
|
||||||
|
| [investment-sync-plan](src/modules/investments/investment-sync-plan.ts) | 327 | Упростить зависимость: убрать service barrel из алгоритма |
|
||||||
|
| [instrument-metadata.repository](src/integrations/tbank/instrument-metadata.repository.ts) | 320 | Оставить: identity, batching и publication согласованы |
|
||||||
|
| [income-analytics.service](src/modules/investments/income/income-analytics.service.ts) | 318 | Оставить: связные projections, выгода дополнительных моделей не доказана |
|
||||||
|
| [candle.repository](src/modules/investments/instruments/infrastructure/candle.repository.ts) | 306 | Оставить: reconciliation, coverage, fencing и stage cleanup |
|
||||||
|
| [upcoming-events.service](src/modules/investments/upcoming-events/upcoming-events.service.ts) | 297 | Оставить: один сценарий, основной дефект у MOEX boundary |
|
||||||
|
| [brokerage-operations-sync.service](src/modules/investments/operations/application/brokerage-operations-sync.service.ts) | 294 | Оставить: связный владелец durable work execution |
|
||||||
|
|
||||||
|
Отдельные категории: 37 unit specs / 3319 строк; 21 HTTP/SQLite specs / 7878 строк;
|
||||||
|
10 test support/fixtures / 1993 строки; 6 vendor proto / 3588 строк;
|
||||||
|
5 SQL migrations / 345 строк. Generated Prisma и build artifacts не ранжировались.
|
||||||
|
|
||||||
|
## Удачные решения, которые требуется сохранить
|
||||||
|
|
||||||
|
- BigInt/decimal и string Money; разные валюты не складываются неявно.
|
||||||
|
- Refresh CAS, ownership queries, версии операций, replay fingerprints/tombstones.
|
||||||
|
- Network calls отделены от DB transactions.
|
||||||
|
- Revision/attempt fencing, late-result discard, staging перед force reconciliation.
|
||||||
|
- Missing/partial/confirmed empty/saved complete различаются явно.
|
||||||
|
- Concrete providers, компактные плоские модули и разрешённый прямой Prisma
|
||||||
|
в связных CRUD/transaction services не являются автоматическими дефектами.
|
||||||
|
- SQLite behavior tests проверяют реальные денежные границы, races и rollback.
|
||||||
|
|
||||||
|
## Выполненные проверки и пределы доказательства
|
||||||
|
|
||||||
|
Перед успешными Node-командами загружалась `~/.nvm/nvm.sh`, затем `nvm use --silent`.
|
||||||
|
Первый вызов nvm без загрузки shell function завершился command not found;
|
||||||
|
после загрузки проверок это ограничение не осталось.
|
||||||
|
|
||||||
|
| Команда / проверка | Результат аудита |
|
||||||
|
| --- | --- |
|
||||||
|
| git status, git rev-parse HEAD, git diff --check | Чистое дерево, неизменный commit, diff errors отсутствуют |
|
||||||
|
| npm run lint | Успешно |
|
||||||
|
| npm run typecheck:app; npm run typecheck:test | Успешно |
|
||||||
|
| npm test -- --runInBand | 37 suites / 200 tests passed |
|
||||||
|
| Build в npm run test:e2e | Prisma generation и Nest build успешны |
|
||||||
|
| Полный e2e в sandbox | listen EPERM на localhost; не засчитан |
|
||||||
|
| LOG_LEVEL=error node test/sqlite.cjs --all, с разрешением localhost | all-accounts: 18 passed; auth-suite затем завершилась native SIGABRT |
|
||||||
|
| node test/sqlite.cjs tbank-screen-sync.e2e-spec.ts tbank-operations-persistence.e2e-spec.ts tbank-candles-persistence.e2e-spec.ts tbank-metadata-persistence.e2e-spec.ts tbank-local-reads.e2e-spec.ts openapi-contract.e2e-spec.ts | Первые три: 27 + 5 + 9 passed; metadata native abort; последующие не достигнуты |
|
||||||
|
| node test/sqlite.cjs openapi-contract.e2e-spec.ts, отдельно | 3 tests passed |
|
||||||
|
| Inline reproductions | Подтверждены описанные случаи; validation/logging через configureApp, остальные с указанными mocked boundaries |
|
||||||
|
|
||||||
|
Native abort произошёл в `node::RemoveEnvironmentCleanupHook` / `better_sqlite3.node`
|
||||||
|
на Node 24.21.0. Причина не установлена; связывать его с конкретной source-находкой
|
||||||
|
нельзя. Полный e2e gate не подтверждён. При реализации сначала повторить в штатном
|
||||||
|
окружении; если проблема остаётся, диагностировать отдельно и явно сообщить,
|
||||||
|
не отключая падающие suites и не выдавая неполную проверку за зелёную.
|
||||||
|
|
||||||
|
Логи текущей сессии (временные файлы, могут исчезнуть):
|
||||||
|
`/tmp/wealthledger-audit-e2e.log`, `/tmp/wealthledger-audit-targeted-e2e.log`,
|
||||||
|
`/tmp/wealthledger-audit-openapi.log`. Документ не зависит от сохранности этих файлов.
|
||||||
|
|
||||||
|
**Проверено:** все production-модули, composition/API, основные consumers,
|
||||||
|
значимые flows, связанные tests кандидатов. Все production auth/banking,
|
||||||
|
integrations/sync/operations и остальные investment slices прочитаны.
|
||||||
|
|
||||||
|
**Частично проверено:** весь набор HTTP fixtures и integration suites не проходил
|
||||||
|
одинаково глубокий построчный аудит; реальное выполнение e2e ограничено указанным
|
||||||
|
native abort. Schema прочитана; история миграций не проходила полный compatibility audit.
|
||||||
|
|
||||||
|
**Не проверено:** clean npm ci, полный verify с coverage как единая команда,
|
||||||
|
durability/restart/backup, container/deployment, production performance,
|
||||||
|
реальные внешние API и полная сверка vendor proto с upstream.
|
||||||
|
|
||||||
|
### Финальная проверка реализации
|
||||||
|
|
||||||
|
Использовать актуальные scripts/conventions backend. На базе аудита для code changes
|
||||||
|
требуются npm ci, npm run verify, relevant SQLite/HTTP checks; для этих HTTP изменений
|
||||||
|
также OpenAPI generation/parity. Полный npm run test:e2e нужен для итоговой проверки
|
||||||
|
совокупных изменений. Перед Node — nvm use --silent.
|
||||||
|
|
||||||
|
Автоисправления lint/format не являются доказательством. Не запускать миграции,
|
||||||
|
reset/drop или tests на пользовательской БД. Штатный SQLite runner создаёт временные
|
||||||
|
базы и защищает от использования внешнего DATABASE_URL.
|
||||||
|
|
||||||
|
По завершении повторить routing по staged/unstaged/new files, выполнить Boy Scout
|
||||||
|
и semantic review: callers, owners, money/access/atomicity/error contracts,
|
||||||
|
generation/cache/async lifecycle. Указать точные команды, outcomes и ограничения.
|
||||||
|
|
||||||
|
## Неподтверждённые гипотезы — вне scope исправлений
|
||||||
|
|
||||||
|
- Logout/refresh interleaving и browser cookie overwrite требуют явных ordering
|
||||||
|
semantics и отдельного HTTP/browser proof.
|
||||||
|
- N+1 в карточных views виден, но измеренная latency/timeout проблема не установлена.
|
||||||
|
- JSON casts внутренних сохранённых payload сами по себе не доказывают небезопасную boundary.
|
||||||
|
- Cash/accrued-interest valuation: локального контракта недостаточно для обвинения в ошибке.
|
||||||
|
- Native SQLite abort требует отдельной диагностики runtime/dependency lifecycle.
|
||||||
|
|
||||||
|
## Статус исправлений
|
||||||
|
|
||||||
|
Начало исправлений: HEAD `516e43203eb3fee8e6a0c7018be2fee11f1b900c`,
|
||||||
|
ветка `codex/investment-contracts`; `git status --short`: только
|
||||||
|
`?? BACKEND_AUDIT.md`, staged/unstaged tracked changes отсутствовали.
|
||||||
|
Исходные разделы аудита сохранены. `npm ci` успешно: 1065 packages, 44s;
|
||||||
|
manifest/lockfile не менялись. Перед Node-командами загружается `~/.nvm/nvm.sh`
|
||||||
|
и выполняется `nvm use --silent`.
|
||||||
|
|
||||||
|
Все A01–A10 и C01–C07 повторно подтверждены и реализованы в порядке пакетов.
|
||||||
|
Статусы ниже разделяют готовность исправления и полноту проверки: native abort
|
||||||
|
не засчитывается как успешный behavioral test. Неподтвердившихся и уже исправленных
|
||||||
|
на исходном HEAD пунктов не обнаружено.
|
||||||
|
|
||||||
|
| ID | Статус | Изменение / доказательство | Проверки и ограничения |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| A01 | Исправлено и проверено | Logout подавляет только JWT verification failure; refresh удаляет cookie только при UnauthorizedException. Configured HTTP red: logout 204 вместо 500, refresh удалил cookie при отказе БД. | `node test/sqlite.cjs app.e2e-spec.ts`: regression воспроизведена на временной SQLite; macOS green повтор и первый полный e2e столкнулись с native SIGABRT. Итоговый Linux e2e: auth 12/12 passed, включая revocation failure и сохранение cookie для retry. |
|
||||||
|
| A02 | Исправлено и проверено | Удалены raw stack и его неиспользуемый transport/allowlist; regression проверяет multiline synthetic secret в конечном Pino payload и correlation. | Targeted filter/logging: 3 suites / 4 tests passed, unit red → green; macOS configured HTTP runner завершился native SIGABRT; итоговый Linux auth 12/12 passed, включая настоящий filter → middleware → Pino payload. |
|
||||||
|
| A03 | Исправлено и проверено | MoexClient отклоняет отсутствующий/повреждённый block, неверную ширину row, malformed/nonprogressing cursor. Пустые блоки и 404 сохранены. | Unit red 12 failures → 21 passed; `node test/sqlite.cjs upcoming-events.e2e-spec.ts`: downstream red 2 failures → 18 passed, настоящий client + mock fetch сохраняют calendar/forecast payload/revisions/timestamps. Typecheck и scoped lint passed. |
|
||||||
|
| A04 | Исправлено и проверено | Screen status разрешает superseded child через operations.observe перед агрегацией state/progress; attempt/revision fencing сохранён. | `node test/sqlite.cjs tbank-screen-sync.e2e-spec.ts`: HTTP/SQLite red succeeded вместо running → 29 passed; successor success/failure, progress, чужой user и удалённая revision. |
|
||||||
|
| A05 | Исправлено и проверено | Каждый join повышает force/priority при более сильном требовании; идентичный join не меняет updatedAt. Load фиксирует force/now на проход, при новой forced потребности выполняет полную reconciliation. Финальная публикация и observers сериализованы с reservations; screen priority=0. | Service unit red → green (полный исторический диапазон и более поздний now); `node test/sqlite.cjs tbank-candles-persistence.e2e-spec.ts`: 14 passed на финальном коде, same/cross-user join до загрузки и после обычного окна, rollback второго forced окна, timestamps и fencing. Native abort в первом финальном запуске; единственный повтор без изменений прошёл. |
|
||||||
|
| A06 | Исправлено и проверено | ForecastService вычисляет возвращаемый positionIsStale из сохранённого positionAt через существующую portfolio TTL policy; не меняет финансовый snapshot. | `node test/sqlite.cjs upcoming-events.e2e-spec.ts`: red stock/bond false на TTL → 20 passed; TTL−1/TTL, observe без RPC, прежние суммы/revisions/timestamps, fallback при несовместимом свежем candidate. Review дополнительно воспроизвёл meta.freshness=fresh для старого fallback (2 red); freshForMs теперь учитывает сохранённый stale flag, repeat 20 passed, stateVersion рассчитывается штатно. |
|
||||||
|
| A07 | Исправлено и проверено | Одна operationTimestamp conversion у mapper для stage/publish; ledger/income wire используют сохранённый occurredAt. Missing seconds по-прежнему отклоняется. | Unit red .600→.000 → 9 passed; `node test/sqlite.cjs tbank-ledger-local.e2e-spec.ts`: HTTP red → 11 passed (from=.500, cursor .800/.600, income timestamp/exact total). Оба typecheck/lint passed. На macOS operations-persistence завершилась native SIGABRT и не засчитана. Итоговый Linux полный e2e: ledger 11/11 и operations-persistence 5/5 passed. |
|
||||||
|
| A08 | Исправлено и проверено | Global/screen ValidationPipe сохраняют structured errors без target/value; filter обходит children и экранирует JSON pointers. Удалён descriptorErrors; OpenAPI errors.items согласован с object shape. | Nested Money HTTP red errors:[] → bank22 / screen29 passed; escaped pointer и отсутствие дублей/secret проверены. Unit7 и scoped lint passed. Metadata red items:string → финальный OpenAPI parity 3 passed. На macOS auth suite native SIGABRT; итоговый Linux auth 12/12 passed, включая credential field errors без input leak. |
|
||||||
|
| A09 | Исправлено и проверено | Planner импортирует существующий чистый operations/domain/operations-sync-plan как явно документированный публичный вход; service barrel больше не экспортирует runtime interval rules. | Planner и CandleService tests выполняются без Prisma mock; targeted пакет 7 suites / 49 tests passed. DI подтверждается configured HTTP и итоговым build. |
|
||||||
|
| A10 | Исправлено и проверено | Удалены шесть legacy methods, context types, TbankClient constructor dependency и accessibleTbankAccount без живых callers; legacy-only spec удалён. | Поиск src/test не находит legacy symbols; 5 unit suites / 11 tests, оба typecheck, scoped lint/build; connection HTTP/SQLite4 passed: missing/invalid/unsupported/cross-user, replacement/deletion, revision/fencing. Token error/crypto assertions сохранены. MacOS metadata-persistence15 passed, operations-sync/catalog-discovery native SIGABRT. Итоговый Linux e2e: metadata15, operations-sync17 и catalog-discovery10 passed. |
|
||||||
|
| C01 | Исправлено и проверено | PortfolioService использует common decimalFromString; локальный parser удалён. Входы из money/formatDecimal уже canonical; текущая ошибка сумм не заявляется. | Exact-money portfolio tests в targeted49 passed; итоговые types/verify ниже. |
|
||||||
|
| C02 | Исправлено и проверено | TbankSyncAttempt/TbankLastPrice экспортируются type-only через tbank.api; семь production consumers используют API, TbankCoupon переиспользован. | Поиск прямых imports tbank-access.service/tbank-market.types в src/modules пуст; оба typecheck и scoped lint passed. |
|
||||||
|
| C03 | Исправлено и проверено | Удалён no-op normalizeEmail; CredentialsDto transform trim/lowercase сохранён. | Auth unit passed; реальные case/whitespace HTTP assertions сохранены. После macOS native SIGABRT полный Linux auth gate прошёл: 12/12. |
|
||||||
|
| C04 | Исправлено и проверено | bankSummary принимает только рабочий диапазон from/to; строковый month overload удалён, полезные unit cases переведены на диапазоны. | Targeted49 passed: month start/end, outside range, signed64/BigInt суммы и refunds. |
|
||||||
|
| C05 | Исправлено и проверено | Удалены optional без callers и stockPosition wrapper; spec перенесён к instrumentPosition, проверяет напрямую владельца. | Targeted49 passed: fractional/large quantity, weighted costs, mixed/unknown currencies, no position и offset long/short. |
|
||||||
|
| C06 | Исправлено и проверено | Удалён неиспользуемый внешний totalsByCurrency export; живой mapper и внутренний caller сохранены. | Поиск imports подтверждает единственный внутренний caller; exact-money targeted tests passed, итоговый typecheck ниже. |
|
||||||
|
| C07 | Исправлено и проверено | Удалён HTTP_CODE_METADATA wiring spec; реальные register/login/refresh status200 и logout/cookie assertions сохранены в app.e2e. | Проверены callers/оставшиеся HTTP assertions; полный Linux auth gate прошёл: 12/12. Предыдущий macOS native SIGABRT остаётся отдельным ограничением среды. |
|
||||||
|
|
||||||
|
### Gates первого прогона (macOS)
|
||||||
|
|
||||||
|
Все команды выполнены из backend на Node `v24.21.0` после `nvm use --silent`.
|
||||||
|
Проверки данных использовали штатный runner, fresh temporary SQLite и штатные
|
||||||
|
migrations; рабочая БД не использовалась. Для localhost/Prisma cache запуски
|
||||||
|
получили разрешение вне sandbox; native abort повторялся и там.
|
||||||
|
|
||||||
|
| Команда | Итог |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm ci` | PASS; manifest и lockfile без изменений. |
|
||||||
|
| `npm run verify` | PASS: lint, app/test typecheck, 36 suites / 209 unit tests с coverage, build. |
|
||||||
|
| `npm run openapi:generate` | PASS; актуальный игнорируемый `openapi.json` сформирован. |
|
||||||
|
| `npm run test:openapi-contract` | PASS: 1 suite / 3 tests, включая object shape validation errors. |
|
||||||
|
| `npx prisma validate` | PASS. Schema и migrations не менялись. |
|
||||||
|
| `npm run test:durability -- /tmp/wealthledger-fix-baseline-current-runtime-fjftdF` | PASS. Baseline `0862d56`, до последней T-Bank migration, отдельно установлен и собран на текущем Node; результат `/var/folders/j_/h2ft23gd3qq35ps3v5bcftfm0000gn/T/wealthledger-bank-durability-SIeCq0`. |
|
||||||
|
| `LOG_LEVEL=error npm run test:e2e` | INCOMPLETE, exit 1: all-accounts 18/18 passed, затем app.e2e native SIGABRT до Jest summary. Остальные suites общий gate не выполнил. |
|
||||||
|
| `node test/sqlite.cjs tbank-candles-persistence.e2e-spec.ts` | PASS на финальном коде: 14/14 после одного native abort и повтора без edits. |
|
||||||
|
| `node test/sqlite.cjs tbank-metadata-persistence.e2e-spec.ts` | PASS на финальном коде: 15/15. |
|
||||||
|
| `node test/sqlite.cjs tbank-operations-sync.e2e-spec.ts` | INCOMPLETE: native SIGABRT до summary. |
|
||||||
|
| `node test/sqlite.cjs tbank-operations-persistence.e2e-spec.ts` | INCOMPLETE: native SIGABRT до summary. |
|
||||||
|
| `node test/sqlite.cjs tbank-catalog-discovery.e2e-spec.ts` | INCOMPLETE: native SIGABRT до summary. |
|
||||||
|
| `git diff --check` | PASS. |
|
||||||
|
|
||||||
|
Логи итоговых gates: `/tmp/wealthledger-fix-verify.log`,
|
||||||
|
`/tmp/wealthledger-fix-openapi-generate.log`, `/tmp/wealthledger-fix-openapi-contract.log`,
|
||||||
|
`/tmp/wealthledger-fix-prisma-validate.log`, `/tmp/wealthledger-fix-durability.log`,
|
||||||
|
`/tmp/wealthledger-fix-final-e2e.log`. Дополнительные SQLite логи:
|
||||||
|
`/tmp/wealthledger-fix-a05-latest-sqlite-retry.log`,
|
||||||
|
`/tmp/wealthledger-fix-final-metadata-persistence.log`,
|
||||||
|
`/tmp/wealthledger-final-operations-sync.log`,
|
||||||
|
`/tmp/wealthledger-final-operations-persistence.log`,
|
||||||
|
`/tmp/wealthledger-fix-final-catalog-discovery.log`.
|
||||||
|
|
||||||
|
Native failure: assertion `(env) != nullptr` в `node::RemoveEnvironmentCleanupHook`,
|
||||||
|
stack содержит destructor из `better_sqlite3.node`. Это конкретное ограничение
|
||||||
|
текущего native runtime, уже наблюдавшееся при исходном аудите; его первопричина
|
||||||
|
в рамках исправлений не установлена. Тесты не отключались, runner/dependencies
|
||||||
|
не изменялись. Эти macOS запуски остаются INCOMPLETE. Полный Linux прогон ниже
|
||||||
|
закрыл e2e gate и auth/operations/catalog acceptance; локальный native abort
|
||||||
|
на macOS при этом не исправлен.
|
||||||
|
|
||||||
|
### Повторная полная проверка (Linux, 2026-09-27)
|
||||||
|
|
||||||
|
**PASS: 21 e2e suites / 262 tests, exit 0**, ни одного skipped/disabled test.
|
||||||
|
Выполнена вся штатная `npm run test:e2e`: build и `node test/sqlite.cjs --all`.
|
||||||
|
Каждая suite получила отдельную temporary SQLite со всеми пятью migrations.
|
||||||
|
Закрыты прежде неполные auth12, operations-persistence5, operations-sync17,
|
||||||
|
catalog-discovery10; также прошли candles14, forecast/upcoming20, screen29,
|
||||||
|
OpenAPI3 и большой read-baseline с 300 000 операций / 1 000 000 свечей.
|
||||||
|
|
||||||
|
Перед повтором зафиксирован тот же HEAD и hashes всех tracked/untracked files;
|
||||||
|
до завершения тестов ни один исходник, тест, config или audit не менялся.
|
||||||
|
Поэтому предыдущие `verify` (209 unit tests), OpenAPI и durability сохраняют
|
||||||
|
актуальность. В этом повторе изменён только статус данного документа.
|
||||||
|
|
||||||
|
MacOS `LOG_LEVEL=error node test/sqlite.cjs app.e2e-spec.ts` снова завершился
|
||||||
|
native SIGABRT. Для Linux использован существующий Dockerfile target
|
||||||
|
`development`, Node `v24.21.0` (проверен против `.nvmrc`) и неизменённый lockfile:
|
||||||
|
SHA-256 `f986979b7922d684fead3a4d32532d11f1e469cec0e35669509343be41cbb2cd`.
|
||||||
|
Image `wealthledger-backend:audit-verification-20260927`,
|
||||||
|
ID `sha256:69264cf3dba23566d99fded450104bbe56f92755604e88232beb97825155ae73`.
|
||||||
|
Сборка выполнила `npm ci`; зависимости и runner не подменялись. Test/scripts
|
||||||
|
подключались read-only, внешняя сеть отключена, host ports не публиковались;
|
||||||
|
одноразовый контейнер удалён после завершения, рабочая БД не подключалась.
|
||||||
|
|
||||||
|
Команды воспроизведения из backend (на host предварительно `source ~/.nvm/nvm.sh`
|
||||||
|
и `nvm use --silent`; внутри image закреплён тот же Node):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build --target development --tag wealthledger-backend:audit-verification-20260927 .
|
||||||
|
docker run --rm --network none \
|
||||||
|
--mount type=bind,source=/Users/ksv741/Project/vibe/WealthLedger/backend/test,target=/app/test,readonly \
|
||||||
|
--mount type=bind,source=/Users/ksv741/Project/vibe/WealthLedger/backend/scripts,target=/app/scripts,readonly \
|
||||||
|
-e LOG_LEVEL=error wealthledger-backend:audit-verification-20260927 npm run test:e2e
|
||||||
|
```
|
||||||
|
|
||||||
|
Логи: `/tmp/wealthledger-recheck-auth.log` (macOS abort),
|
||||||
|
`/tmp/wealthledger-recheck-linux-build.log` (Linux image build),
|
||||||
|
`/tmp/wealthledger-recheck-linux-e2e.log` (полный PASS).
|
||||||
|
|
||||||
|
Read-only диагностика локализовала macOS crash в GC finalizer Statement/Database
|
||||||
|
вложенного `better-sqlite3 12.11.1`, используемого Prisma adapter 7.10.0.
|
||||||
|
Node 24.21 ObjectWrap destructor вызывает RemoveEnvironmentCleanupHook, который
|
||||||
|
падает на `env != nullptr`. Связь с Jest VM context и происхождением native
|
||||||
|
binary остаётся гипотезой, а не доказанной первопричиной. Ошибка application
|
||||||
|
lifecycle не обнаружена: close/disconnect ожидаются. Linux PASS доказывает
|
||||||
|
поведение backend в этом окружении, но не устранение native crash на macOS.
|
||||||
|
|
||||||
|
### Semantic / Boy Scout review и состояние дерева
|
||||||
|
|
||||||
|
Повторный routing по staged/unstaged/new files активировал Architecture,
|
||||||
|
HTTP/errors, Data, Testing, Security, Integrations и Observability. Проверены
|
||||||
|
owners/callers и связанная документация; независимый review охватил auth/logging,
|
||||||
|
candle coalescing/publication, forecast fallback и cleanup. После устранения
|
||||||
|
найденной при review stale metadata у старого forecast fallback оставшихся
|
||||||
|
semantic замечаний нет. Проверены точная денежная арифметика, ownership,
|
||||||
|
transactions, generation fencing, сохранение cache/pending promises и отсутствие
|
||||||
|
новых дублирующих helpers.
|
||||||
|
|
||||||
|
На момент завершения проверки, до запроса публикации, HEAD оставался
|
||||||
|
`516e43203eb3fee8e6a0c7018be2fee11f1b900c`, ветка
|
||||||
|
`codex/investment-contracts`; staged files отсутствуют. Все изменения локальные,
|
||||||
|
без commit/push/PR. Новые untracked files: исходный `BACKEND_AUDIT.md`,
|
||||||
|
`src/modules/investments/instruments/application/candle.service.spec.ts` и
|
||||||
|
`src/modules/investments/instruments/application/instrument-position.spec.ts`.
|
||||||
|
Остальные изменения — tracked source/tests и три связанных convention-файла.
|
||||||
|
Новые зависимости, scripts, migrations и разделение production-файлов не добавлены.
|
||||||
|
Исходный текст до раздела «Статус исправлений» побайтово совпадает со снимком
|
||||||
|
`/tmp/wealthledger-backend-audit-before-fixes.md`.
|
||||||
|
|
||||||
|
### Подготовка публикации
|
||||||
|
|
||||||
|
После успешной полной проверки пользователь разрешил commit, PR и merge.
|
||||||
|
Ветка публикации — `codex/backend-audit-fixes` от актуального `origin/develop`
|
||||||
|
`5d3835e`; его tree совпадает с исходным HEAD проверки, поэтому исходники и
|
||||||
|
результаты gates не изменились. Pre-commit review не обнаружил посторонних
|
||||||
|
файлов, секретов или незакрытых semantic findings. PR направляется в `develop`;
|
||||||
|
merge выполняется после обязательных `verify`, `security`, `commits`.
|
||||||
@@ -105,6 +105,34 @@ Required checks настраиваются отдельно в Gitea: налич
|
|||||||
runtime-валидацию. В обычном коде нужны инициализация или сужение типа
|
runtime-валидацию. В обычном коде нужны инициализация или сужение типа
|
||||||
после проверки значения.
|
после проверки значения.
|
||||||
|
|
||||||
|
## ESLint
|
||||||
|
|
||||||
|
`npm run lint` проверяет весь authored TypeScript и JavaScript, включая scripts
|
||||||
|
и configs. `npm run lint:fix` (также `npm run format`) применяет безопасные
|
||||||
|
автоисправления. Форматирование принадлежит ESLint Stylistic: два пробела,
|
||||||
|
одинарные кавычки и точки с запятой; Prettier не используется.
|
||||||
|
|
||||||
|
Профиль: ESLint recommended, typescript-eslint recommendedTypeChecked,
|
||||||
|
Node, NestJS typed, Jest, import-x с TypeScript resolver, SonarJS, RegExp,
|
||||||
|
Security, Perfectionist recommended-natural и Stylistic customize.
|
||||||
|
NestJS проверяется в production TS, Jest — в specs/e2e; generated Prisma,
|
||||||
|
dist и coverage исключены. DI imports сохраняют runtime metadata.
|
||||||
|
|
||||||
|
Исключения конфигурации: private backend не публикуется в npm;
|
||||||
|
TS imports разрешает import-x вместо Node resolver; IsIn проверяет domain
|
||||||
|
unions. Автосортировка объектов, классов, модулей и декораторов отключена,
|
||||||
|
поскольку порядок может влиять на runtime. Остальные точечные исключения
|
||||||
|
объясняют false positives непосредственно в коде.
|
||||||
|
|
||||||
|
`eslint-suppressions.json` — штатный ESLint baseline только для существующих
|
||||||
|
SonarJS cognitive-complexity, no-nested-conditional и no-nested-template-literals.
|
||||||
|
Это отложенный refactor, а не исправленные нарушения. Baseline ограничен
|
||||||
|
файлами и количеством сообщений; новые файлы и превышение количества блокируют
|
||||||
|
lint. Он не защищает от усложнения уже учтённой функции при прежнем количестве
|
||||||
|
сообщений — это остаётся предметом review. При сокращении долга обновляйте
|
||||||
|
baseline командой `npx eslint . --prune-suppressions`; не пересоздавайте его
|
||||||
|
для обхода новых ошибок. Security, TypeScript и Jest в baseline не включены.
|
||||||
|
|
||||||
## SonarQube
|
## SonarQube
|
||||||
|
|
||||||
Проект `wealthledger-backend` на `https://sonarqube.personal.ksv741.ru`
|
Проект `wealthledger-backend` на `https://sonarqube.personal.ksv741.ru`
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
extends: ["@commitlint/config-conventional"],
|
extends: ['@commitlint/config-conventional'],
|
||||||
rules: { "type-enum": [2, "always", ["feat", "fix", "perf", "docs", "spec", "refactor", "build", "ci", "test", "style", "chore", "revert"]] },
|
rules: { 'type-enum': [2, 'always', ['feat', 'fix', 'perf', 'docs', 'spec', 'refactor', 'build', 'ci', 'test', 'style', 'chore', 'revert']] },
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
{
|
||||||
|
"src/common/decimal.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/common/logging/request-logging.middleware.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/integrations/tbank/instrument-metadata.repository.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/integrations/tbank/instrument-metadata.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/integrations/tbank/tbank.client.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/banking/bank-cards/application/bank-operations.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/banking/bank-cards/infrastructure/bank-cards.repository.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/brokerage-accounts/brokerage-accounts.service.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/income/income-analytics.service.ts": {
|
||||||
|
"sonarjs/no-nested-template-literals": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/income/income-period.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/application/candle.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 4
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-template-literals": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/application/catalog-discovery.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/application/catalog-enrichment.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 2
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/bonds/application/bond-income.service.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/bonds/application/bond.spec.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/infrastructure/candle.repository.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/infrastructure/catalog-discovery.repository.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/instruments/stocks/application/stock-income.service.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/investment-resource.mapper.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/investment-sync-plan.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/operations/application/brokerage-operations.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 2
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 9
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/operations/domain/operations-sync-plan.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/operations/infrastructure/brokerage-operation.mapper.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/operations/infrastructure/brokerage-operations.repository.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 3
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/portfolio/application/forecast.service.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/portfolio/application/portfolio.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/tbank-sync/tbank-screen.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/tbank-sync/tbank-sync.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 3
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 7
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"src/modules/investments/upcoming-events/upcoming-events.service.ts": {
|
||||||
|
"sonarjs/cognitive-complexity": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test/bank-cards-durability.cjs": {
|
||||||
|
"sonarjs/no-nested-template-literals": {
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test/sqlite-regression.cjs": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test/sqlite.cjs": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test/tbank-ledger-local.e2e-spec.ts": {
|
||||||
|
"sonarjs/no-nested-conditional": {
|
||||||
|
"count": 1
|
||||||
|
},
|
||||||
|
"sonarjs/no-nested-template-literals": {
|
||||||
|
"count": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+77
-57
@@ -1,59 +1,75 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
import nest from '@darraghor/eslint-plugin-nestjs-typed';
|
||||||
import eslint from '@eslint/js';
|
import eslint from '@eslint/js';
|
||||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
import stylistic from '@stylistic/eslint-plugin';
|
||||||
|
import { createTypeScriptImportResolver } from 'eslint-import-resolver-typescript';
|
||||||
|
import { importX } from 'eslint-plugin-import-x';
|
||||||
|
import jest from 'eslint-plugin-jest';
|
||||||
|
import node from 'eslint-plugin-n';
|
||||||
|
import perfectionist from 'eslint-plugin-perfectionist';
|
||||||
|
import regexp from 'eslint-plugin-regexp';
|
||||||
|
import security from 'eslint-plugin-security';
|
||||||
|
import sonarjs from 'eslint-plugin-sonarjs';
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||||
import globals from 'globals';
|
import globals from 'globals';
|
||||||
import tseslint from 'typescript-eslint';
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
export default tseslint.config(
|
const tests = ['**/*.spec.ts', 'test/**/*.ts'];
|
||||||
|
|
||||||
|
export default defineConfig(
|
||||||
|
globalIgnores(['dist/**', 'dist-dev/**', 'build/**', 'generated/**', 'coverage/**', 'node_modules/**']),
|
||||||
{
|
{
|
||||||
ignores: ['eslint.config.mjs', 'dist/', 'generated/'],
|
files: ['**/*.{ts,js,cjs,mjs}'],
|
||||||
},
|
extends: [
|
||||||
eslint.configs.recommended,
|
eslint.configs.recommended,
|
||||||
...tseslint.configs.recommendedTypeChecked,
|
node.configs['flat/recommended'],
|
||||||
eslintPluginPrettierRecommended,
|
importX.flatConfigs.recommended,
|
||||||
{
|
sonarjs.configs.recommended,
|
||||||
languageOptions: {
|
regexp.configs['flat/recommended'],
|
||||||
globals: {
|
security.configs.recommended,
|
||||||
...globals.node,
|
perfectionist.configs['recommended-natural'],
|
||||||
...globals.jest,
|
stylistic.configs.customize({ indent: 2, quotes: 'single', semi: true, jsx: false }),
|
||||||
},
|
],
|
||||||
sourceType: 'commonjs',
|
languageOptions: { globals: globals.node },
|
||||||
parserOptions: {
|
linterOptions: { reportUnusedDisableDirectives: 'error' },
|
||||||
projectService: true,
|
settings: {
|
||||||
tsconfigRootDir: import.meta.dirname,
|
'import-x/resolver-next': [createTypeScriptImportResolver()],
|
||||||
},
|
'node': { tryExtensions: ['.ts', '.js', '.json', '.node'], version: '24.21.0' },
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'curly': ['error', 'multi-line'],
|
||||||
|
// This private application is deployed as a whole, never published to npm.
|
||||||
|
'n/no-unpublished-import': 'off',
|
||||||
|
'n/no-unpublished-require': 'off',
|
||||||
|
// Decorator execution and object insertion order can be observable at runtime.
|
||||||
|
'perfectionist/sort-decorators': 'off',
|
||||||
|
'perfectionist/sort-objects': 'off',
|
||||||
|
'perfectionist/sort-modules': 'off',
|
||||||
|
'perfectionist/sort-classes': 'off',
|
||||||
|
'@stylistic/brace-style': ['error', '1tbs', { allowSingleLine: false }],
|
||||||
|
'@stylistic/arrow-parens': ['error', 'always'],
|
||||||
|
'@stylistic/operator-linebreak': ['error', 'after'],
|
||||||
|
'import-x/no-duplicates': ['error', { 'prefer-inline': true }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
files: ['**/*.mjs'],
|
||||||
|
extends: [node.configs['flat/recommended-module']],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.ts'],
|
||||||
|
extends: [tseslint.configs.recommendedTypeChecked, importX.flatConfigs.typescript],
|
||||||
|
languageOptions: {
|
||||||
|
sourceType: 'module',
|
||||||
|
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
|
||||||
|
},
|
||||||
rules: {
|
rules: {
|
||||||
|
// TypeScript resolves source imports; import-x checks them with the TS resolver.
|
||||||
|
'n/no-missing-import': 'off',
|
||||||
'no-magic-numbers': 'off',
|
'no-magic-numbers': 'off',
|
||||||
'@typescript-eslint/no-magic-numbers': [
|
'@typescript-eslint/no-magic-numbers': [
|
||||||
'error',
|
'error',
|
||||||
{
|
{
|
||||||
ignore: [
|
|
||||||
-60,
|
|
||||||
-24,
|
|
||||||
-10,
|
|
||||||
-2,
|
|
||||||
-1,
|
|
||||||
0,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
10,
|
|
||||||
24,
|
|
||||||
60,
|
|
||||||
'-60n',
|
|
||||||
'-24n',
|
|
||||||
'-10n',
|
|
||||||
'-2n',
|
|
||||||
'-1n',
|
|
||||||
'0n',
|
|
||||||
'1n',
|
|
||||||
'2n',
|
|
||||||
'10n',
|
|
||||||
'24n',
|
|
||||||
'60n',
|
|
||||||
],
|
|
||||||
ignoreArrayIndexes: true,
|
ignoreArrayIndexes: true,
|
||||||
ignoreDefaultValues: true,
|
ignoreDefaultValues: true,
|
||||||
ignoreEnums: true,
|
ignoreEnums: true,
|
||||||
@@ -63,24 +79,28 @@ export default tseslint.config(
|
|||||||
enforceConst: true,
|
enforceConst: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
'@typescript-eslint/no-explicit-any': 'off',
|
|
||||||
'@typescript-eslint/no-non-null-assertion': 'error',
|
'@typescript-eslint/no-non-null-assertion': 'error',
|
||||||
'no-restricted-syntax': [
|
'no-restricted-syntax': ['error', {
|
||||||
'error',
|
selector: 'PropertyDefinition[definite=true], VariableDeclarator[definite=true]',
|
||||||
{
|
message: 'Definite assignment assertions are forbidden. Initialize owned values; use declare only for externally populated DTO fields.',
|
||||||
selector:
|
}],
|
||||||
'PropertyDefinition[definite=true], VariableDeclarator[definite=true]',
|
|
||||||
message:
|
|
||||||
'Definite assignment assertions are forbidden. Initialize owned values; use declare only for externally populated DTO fields.',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
'@typescript-eslint/no-floating-promises': 'warn',
|
|
||||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
|
||||||
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
files: ['**/*.spec.ts', 'test/**/*.ts'],
|
files: ['src/**/*.ts'],
|
||||||
rules: { '@typescript-eslint/no-magic-numbers': 'off' },
|
ignores: tests,
|
||||||
|
extends: [nest.configs.flatRecommended],
|
||||||
|
rules: {
|
||||||
|
// Domain string unions are validated with IsIn rather than runtime TS enums.
|
||||||
|
'@darraghor/nestjs-typed/validated-non-primitive-property-needs-type-decorator': ['error', { additionalTypeDecorators: ['IsIn'] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: tests,
|
||||||
|
extends: [jest.configs['flat/recommended']],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-magic-numbers': 'off',
|
||||||
|
'jest/expect-expect': ['error', { assertFunctionNames: ['expect', '**.expect'] }],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
Generated
+754
-215
File diff suppressed because it is too large
Load Diff
+19
-11
@@ -11,14 +11,14 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "prisma generate && nest build",
|
"build": "prisma generate && nest build",
|
||||||
"openapi:generate": "npm run build && node scripts/generate-openapi.cjs",
|
"openapi:generate": "npm run build && node scripts/generate-openapi.cjs",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "npm run lint:fix",
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:dev": "NODE_ENV=development nest start --watch --path tsconfig.dev.json",
|
"start:dev": "NODE_ENV=development nest start --watch --path tsconfig.dev.json",
|
||||||
"start:debug": "nest start --debug --watch --path tsconfig.dev.json",
|
"start:debug": "nest start --debug --watch --path tsconfig.dev.json",
|
||||||
"start:prod": "node dist/src/main.js",
|
"start:prod": "node dist/src/main.js",
|
||||||
"lint": "npm run lint:check",
|
"lint": "npm run lint:check",
|
||||||
"lint:check": "eslint \"{src,apps,libs,test}/**/*.ts\" --max-warnings=0",
|
"lint:check": "eslint . --max-warnings=0",
|
||||||
"lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint:fix": "eslint . --fix --max-warnings=0",
|
||||||
"typecheck:app": "tsc --project tsconfig.typecheck.app.json",
|
"typecheck:app": "tsc --project tsconfig.typecheck.app.json",
|
||||||
"typecheck:test": "tsc --project tsconfig.typecheck.test.json",
|
"typecheck:test": "tsc --project tsconfig.typecheck.test.json",
|
||||||
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
||||||
@@ -30,10 +30,11 @@
|
|||||||
"test:container": "node test/container-smoke.cjs",
|
"test:container": "node test/container-smoke.cjs",
|
||||||
"test:durability": "node test/bank-cards-durability.cjs",
|
"test:durability": "node test/bank-cards-durability.cjs",
|
||||||
"test:openapi-contract": "npm run build && node test/sqlite.cjs openapi-contract.e2e-spec.ts",
|
"test:openapi-contract": "npm run build && node test/sqlite.cjs openapi-contract.e2e-spec.ts",
|
||||||
"verify": "npm run lint && npm run typecheck:app && npm run typecheck:test && npm run test:cov -- --runInBand && npm run build",
|
"verify": "npm run lint && npm run test:lint && npm run typecheck:app && npm run typecheck:test && npm run test:cov -- --runInBand && npm run build",
|
||||||
"release:preview": "release-it --dry-run --ci",
|
"release:preview": "release-it --dry-run --ci",
|
||||||
"release:prepare": "release-it --ci",
|
"release:prepare": "release-it --ci",
|
||||||
"commitlint": "commitlint"
|
"commitlint": "commitlint",
|
||||||
|
"test:lint": "node --test test/eslint-config.cjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@grpc/grpc-js": "1.14.4",
|
"@grpc/grpc-js": "1.14.4",
|
||||||
@@ -53,6 +54,7 @@
|
|||||||
"class-transformer": "0.5.1",
|
"class-transformer": "0.5.1",
|
||||||
"class-validator": "0.15.1",
|
"class-validator": "0.15.1",
|
||||||
"cookie-parser": "1.4.7",
|
"cookie-parser": "1.4.7",
|
||||||
|
"dotenv": "17.4.2",
|
||||||
"lru-cache": "11.5.2",
|
"lru-cache": "11.5.2",
|
||||||
"nestjs-pino": "5.1.0",
|
"nestjs-pino": "5.1.0",
|
||||||
"passport": "0.7.0",
|
"passport": "0.7.0",
|
||||||
@@ -65,12 +67,13 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@commitlint/cli": "21.2.2",
|
"@commitlint/cli": "21.2.2",
|
||||||
"@commitlint/config-conventional": "21.2.2",
|
"@commitlint/config-conventional": "21.2.2",
|
||||||
"@eslint/eslintrc": "3.3.7",
|
"@darraghor/eslint-plugin-nestjs-typed": "7.5.6",
|
||||||
"@eslint/js": "10.0.1",
|
"@eslint/js": "10.0.1",
|
||||||
"@nestjs/cli": "12.0.0",
|
"@nestjs/cli": "12.0.0",
|
||||||
"@nestjs/schematics": "12.0.1",
|
"@nestjs/schematics": "12.0.1",
|
||||||
"@nestjs/testing": "12.0.1",
|
"@nestjs/testing": "12.0.1",
|
||||||
"@release-it/conventional-changelog": "12.0.0",
|
"@release-it/conventional-changelog": "12.0.0",
|
||||||
|
"@stylistic/eslint-plugin": "5.10.0",
|
||||||
"@types/bcrypt": "6.0.0",
|
"@types/bcrypt": "6.0.0",
|
||||||
"@types/cookie-parser": "1.4.10",
|
"@types/cookie-parser": "1.4.10",
|
||||||
"@types/express": "5.0.6",
|
"@types/express": "5.0.6",
|
||||||
@@ -79,12 +82,17 @@
|
|||||||
"@types/passport-jwt": "4.0.1",
|
"@types/passport-jwt": "4.0.1",
|
||||||
"@types/supertest": "7.2.1",
|
"@types/supertest": "7.2.1",
|
||||||
"conventional-changelog-conventionalcommits": "10.4.0",
|
"conventional-changelog-conventionalcommits": "10.4.0",
|
||||||
"eslint": "10.10.0",
|
"eslint": "10.11.0",
|
||||||
"eslint-config-prettier": "10.1.8",
|
"eslint-import-resolver-typescript": "4.4.5",
|
||||||
"eslint-plugin-prettier": "5.5.6",
|
"eslint-plugin-import-x": "4.17.1",
|
||||||
|
"eslint-plugin-jest": "29.16.6",
|
||||||
|
"eslint-plugin-n": "18.4.0",
|
||||||
|
"eslint-plugin-perfectionist": "5.12.1",
|
||||||
|
"eslint-plugin-regexp": "3.3.1",
|
||||||
|
"eslint-plugin-security": "4.1.0",
|
||||||
|
"eslint-plugin-sonarjs": "4.2.1",
|
||||||
"globals": "17.12.0",
|
"globals": "17.12.0",
|
||||||
"jest": "30.5.1",
|
"jest": "30.5.1",
|
||||||
"prettier": "3.9.6",
|
|
||||||
"release-it": "21.0.2",
|
"release-it": "21.0.2",
|
||||||
"source-map-support": "0.5.21",
|
"source-map-support": "0.5.21",
|
||||||
"supertest": "7.2.2",
|
"supertest": "7.2.2",
|
||||||
@@ -93,7 +101,7 @@
|
|||||||
"ts-node": "10.9.2",
|
"ts-node": "10.9.2",
|
||||||
"tsconfig-paths": "4.2.0",
|
"tsconfig-paths": "4.2.0",
|
||||||
"typescript": "6.0.3",
|
"typescript": "6.0.3",
|
||||||
"typescript-eslint": "8.70.0"
|
"typescript-eslint": "8.70.1"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"@nestjs/platform-express": {
|
"@nestjs/platform-express": {
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
PRAGMA foreign_keys=OFF;
|
||||||
|
BEGIN IMMEDIATE;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankAccount" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"openedOn" TEXT,
|
||||||
|
"upstreamOrder" INTEGER NOT NULL,
|
||||||
|
"operationsRevision" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"historyFrom" DATETIME,
|
||||||
|
"historyBoundary" TEXT NOT NULL DEFAULT 'unknown',
|
||||||
|
|
||||||
|
PRIMARY KEY ("userId", "revision", "accountId"),
|
||||||
|
CONSTRAINT "TbankAccount_userId_revision_fkey" FOREIGN KEY ("userId", "revision") REFERENCES "TbankConnection" ("userId", "revision") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankPortfolio" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"mappingVersion" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("userId", "revision", "accountId"),
|
||||||
|
CONSTRAINT "TbankPortfolio_userId_revision_accountId_fkey" FOREIGN KEY ("userId", "revision", "accountId") REFERENCES "TbankAccount" ("userId", "revision", "accountId") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankOperation" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"brokerOperationId" TEXT NOT NULL,
|
||||||
|
"occurredAt" DATETIME NOT NULL,
|
||||||
|
"instrumentUid" TEXT,
|
||||||
|
"category" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"mappingVersion" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("userId", "revision", "accountId", "brokerOperationId"),
|
||||||
|
CONSTRAINT "TbankOperation_userId_revision_accountId_fkey" FOREIGN KEY ("userId", "revision", "accountId") REFERENCES "TbankAccount" ("userId", "revision", "accountId") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankOperationCoverage" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"instrumentPredicate" TEXT NOT NULL DEFAULT '',
|
||||||
|
"from" DATETIME NOT NULL,
|
||||||
|
"to" DATETIME NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"asOf" DATETIME NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY ("userId", "revision", "accountId", "instrumentPredicate", "from", "to"),
|
||||||
|
CONSTRAINT "TbankOperationCoverage_userId_revision_accountId_fkey" FOREIGN KEY ("userId", "revision", "accountId") REFERENCES "TbankAccount" ("userId", "revision", "accountId") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankForecast" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"scopeKey" TEXT NOT NULL,
|
||||||
|
"membershipRevision" INTEGER NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"dependencyRevisions" JSONB NOT NULL,
|
||||||
|
"sourceTimestamps" JSONB NOT NULL,
|
||||||
|
"calculatedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("userId", "revision", "scopeKey"),
|
||||||
|
CONSTRAINT "TbankForecast_userId_revision_fkey" FOREIGN KEY ("userId", "revision") REFERENCES "TbankConnection" ("userId", "revision") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankInstrument" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"uid" TEXT NOT NULL,
|
||||||
|
"figi" TEXT,
|
||||||
|
"ticker" TEXT,
|
||||||
|
"instrumentType" TEXT NOT NULL,
|
||||||
|
"metadata" JSONB NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "uid")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankCatalogDiscovery" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"instrumentType" TEXT NOT NULL,
|
||||||
|
"query" TEXT NOT NULL,
|
||||||
|
"instrumentUids" JSONB NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "instrumentType", "query")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankInstrumentLookup" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"identifierType" TEXT NOT NULL,
|
||||||
|
"identifier" TEXT NOT NULL,
|
||||||
|
"matchedUids" JSONB NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "identifierType", "identifier")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankInstrumentSource" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"instrumentUid" TEXT NOT NULL,
|
||||||
|
"source" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"rangeKey" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "instrumentUid", "source", "kind", "rangeKey"),
|
||||||
|
CONSTRAINT "TbankInstrumentSource_provider_instrumentUid_fkey" FOREIGN KEY ("provider", "instrumentUid") REFERENCES "TbankInstrument" ("provider", "uid") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankCandle" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"instrumentUid" TEXT NOT NULL,
|
||||||
|
"interval" TEXT NOT NULL,
|
||||||
|
"time" DATETIME NOT NULL,
|
||||||
|
"close" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"isComplete" BOOLEAN NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "instrumentUid", "interval", "time"),
|
||||||
|
CONSTRAINT "TbankCandle_provider_instrumentUid_fkey" FOREIGN KEY ("provider", "instrumentUid") REFERENCES "TbankInstrument" ("provider", "uid") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankCandleCoverage" (
|
||||||
|
"provider" TEXT NOT NULL,
|
||||||
|
"instrumentUid" TEXT NOT NULL,
|
||||||
|
"interval" TEXT NOT NULL,
|
||||||
|
"from" DATETIME NOT NULL,
|
||||||
|
"to" DATETIME NOT NULL,
|
||||||
|
"isComplete" BOOLEAN NOT NULL,
|
||||||
|
"fetchedAt" DATETIME NOT NULL,
|
||||||
|
"dataRevision" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
|
||||||
|
PRIMARY KEY ("provider", "instrumentUid", "interval", "from", "to"),
|
||||||
|
CONSTRAINT "TbankCandleCoverage_provider_instrumentUid_fkey" FOREIGN KEY ("provider", "instrumentUid") REFERENCES "TbankInstrument" ("provider", "uid") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankSyncWork" (
|
||||||
|
"id" TEXT NOT NULL PRIMARY KEY,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"scopeKey" TEXT NOT NULL,
|
||||||
|
"intent" JSONB NOT NULL,
|
||||||
|
"state" TEXT NOT NULL,
|
||||||
|
"attemptId" TEXT NOT NULL,
|
||||||
|
"processRunId" TEXT NOT NULL,
|
||||||
|
"priority" INTEGER NOT NULL,
|
||||||
|
"progress" JSONB NOT NULL,
|
||||||
|
"errorCode" TEXT,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL,
|
||||||
|
CONSTRAINT "TbankSyncWork_userId_revision_fkey" FOREIGN KEY ("userId", "revision") REFERENCES "TbankConnection" ("userId", "revision") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TbankSyncStage" (
|
||||||
|
"workId" TEXT NOT NULL,
|
||||||
|
"attemptId" TEXT NOT NULL,
|
||||||
|
"sourceKey" TEXT NOT NULL,
|
||||||
|
"itemKey" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY ("workId", "attemptId", "sourceKey", "itemKey"),
|
||||||
|
CONSTRAINT "TbankSyncStage_workId_attemptId_fkey" FOREIGN KEY ("workId", "attemptId") REFERENCES "TbankSyncWork" ("id", "attemptId") ON DELETE CASCADE ON UPDATE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- RedefineTables
|
||||||
|
CREATE TABLE "new_TbankConnection" (
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"encryptedToken" TEXT NOT NULL,
|
||||||
|
"connectedAt" DATETIME NOT NULL,
|
||||||
|
"revision" TEXT NOT NULL,
|
||||||
|
"invalidToken" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"membershipAt" DATETIME,
|
||||||
|
"membershipRevision" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
CONSTRAINT "TbankConnection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
-- Preserve credentials and assign an opaque revision to each existing connection.
|
||||||
|
INSERT INTO "new_TbankConnection" ("connectedAt", "encryptedToken", "userId", "revision") SELECT "connectedAt", "encryptedToken", "userId", lower(hex(randomblob(16))) FROM "TbankConnection";
|
||||||
|
DROP TABLE "TbankConnection";
|
||||||
|
ALTER TABLE "new_TbankConnection" RENAME TO "TbankConnection";
|
||||||
|
CREATE UNIQUE INDEX "TbankConnection_userId_key" ON "TbankConnection"("userId");
|
||||||
|
CREATE UNIQUE INDEX "TbankConnection_userId_revision_key" ON "TbankConnection"("userId", "revision");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankOperation_userId_revision_accountId_occurredAt_brokerOperationId_idx" ON "TbankOperation"("userId", "revision", "accountId", "occurredAt", "brokerOperationId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankOperation_userId_revision_accountId_instrumentUid_occurredAt_idx" ON "TbankOperation"("userId", "revision", "accountId", "instrumentUid", "occurredAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankOperation_userId_revision_accountId_category_occurredAt_idx" ON "TbankOperation"("userId", "revision", "accountId", "category", "occurredAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankInstrument_provider_figi_idx" ON "TbankInstrument"("provider", "figi");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankInstrument_provider_ticker_instrumentType_idx" ON "TbankInstrument"("provider", "ticker", "instrumentType");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TbankSyncWork_userId_revision_state_priority_idx" ON "TbankSyncWork"("userId", "revision", "state", "priority");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TbankSyncWork_userId_revision_scopeKey_key" ON "TbankSyncWork"("userId", "revision", "scopeKey");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TbankSyncWork_id_attemptId_key" ON "TbankSyncWork"("id", "attemptId");
|
||||||
|
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
PRAGMA foreign_keys=ON;
|
||||||
@@ -25,7 +25,212 @@ model TbankConnection {
|
|||||||
userId String @unique
|
userId String @unique
|
||||||
encryptedToken String
|
encryptedToken String
|
||||||
connectedAt DateTime
|
connectedAt DateTime
|
||||||
|
revision String @default(uuid())
|
||||||
|
invalidToken Boolean @default(false)
|
||||||
|
membershipAt DateTime?
|
||||||
|
membershipRevision Int @default(0)
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
accounts TbankAccount[]
|
||||||
|
forecasts TbankForecast[]
|
||||||
|
work TbankSyncWork[]
|
||||||
|
|
||||||
|
@@unique([userId, revision])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankAccount {
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
accountId String
|
||||||
|
type String
|
||||||
|
name String
|
||||||
|
openedOn String?
|
||||||
|
upstreamOrder Int
|
||||||
|
operationsRevision Int @default(0)
|
||||||
|
historyFrom DateTime?
|
||||||
|
historyBoundary String @default("unknown")
|
||||||
|
connection TbankConnection @relation(fields: [userId, revision], references: [userId, revision], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
portfolio TbankPortfolio?
|
||||||
|
operations TbankOperation[]
|
||||||
|
coverage TbankOperationCoverage[]
|
||||||
|
|
||||||
|
@@id([userId, revision, accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankPortfolio {
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
accountId String
|
||||||
|
payload Json
|
||||||
|
mappingVersion Int @default(1)
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
account TbankAccount @relation(fields: [userId, revision, accountId], references: [userId, revision, accountId], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
|
||||||
|
@@id([userId, revision, accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankOperation {
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
accountId String
|
||||||
|
brokerOperationId String
|
||||||
|
occurredAt DateTime
|
||||||
|
instrumentUid String?
|
||||||
|
category String
|
||||||
|
payload Json
|
||||||
|
mappingVersion Int @default(1)
|
||||||
|
account TbankAccount @relation(fields: [userId, revision, accountId], references: [userId, revision, accountId], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
|
||||||
|
@@id([userId, revision, accountId, brokerOperationId])
|
||||||
|
@@index([userId, revision, accountId, occurredAt, brokerOperationId])
|
||||||
|
@@index([userId, revision, accountId, instrumentUid, occurredAt])
|
||||||
|
@@index([userId, revision, accountId, category, occurredAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankOperationCoverage {
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
accountId String
|
||||||
|
instrumentPredicate String @default("")
|
||||||
|
from DateTime
|
||||||
|
to DateTime
|
||||||
|
fetchedAt DateTime
|
||||||
|
asOf DateTime
|
||||||
|
account TbankAccount @relation(fields: [userId, revision, accountId], references: [userId, revision, accountId], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
|
||||||
|
@@id([userId, revision, accountId, instrumentPredicate, from, to])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankForecast {
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
scopeKey String
|
||||||
|
membershipRevision Int
|
||||||
|
payload Json
|
||||||
|
dependencyRevisions Json
|
||||||
|
sourceTimestamps Json
|
||||||
|
calculatedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
connection TbankConnection @relation(fields: [userId, revision], references: [userId, revision], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
|
||||||
|
@@id([userId, revision, scopeKey])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankInstrument {
|
||||||
|
provider String
|
||||||
|
uid String
|
||||||
|
figi String?
|
||||||
|
ticker String?
|
||||||
|
instrumentType String
|
||||||
|
metadata Json
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
sources TbankInstrumentSource[]
|
||||||
|
candles TbankCandle[]
|
||||||
|
candleCoverage TbankCandleCoverage[]
|
||||||
|
|
||||||
|
@@id([provider, uid])
|
||||||
|
@@index([provider, figi])
|
||||||
|
@@index([provider, ticker, instrumentType])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankCatalogDiscovery {
|
||||||
|
provider String
|
||||||
|
instrumentType String
|
||||||
|
query String
|
||||||
|
instrumentUids Json
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
|
||||||
|
@@id([provider, instrumentType, query])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty and ambiguous successful UID/FIGI/ticker lookups are distinct from failures.
|
||||||
|
model TbankInstrumentLookup {
|
||||||
|
provider String
|
||||||
|
identifierType String
|
||||||
|
identifier String
|
||||||
|
matchedUids Json
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
|
||||||
|
@@id([provider, identifierType, identifier])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source records contain no holdings, personal estimates or credentials errors.
|
||||||
|
model TbankInstrumentSource {
|
||||||
|
provider String
|
||||||
|
instrumentUid String
|
||||||
|
source String
|
||||||
|
kind String
|
||||||
|
rangeKey String
|
||||||
|
payload Json
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
instrument TbankInstrument @relation(fields: [provider, instrumentUid], references: [provider, uid], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([provider, instrumentUid, source, kind, rangeKey])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankCandle {
|
||||||
|
provider String
|
||||||
|
instrumentUid String
|
||||||
|
interval String
|
||||||
|
time DateTime
|
||||||
|
close String
|
||||||
|
payload Json
|
||||||
|
isComplete Boolean
|
||||||
|
fetchedAt DateTime
|
||||||
|
instrument TbankInstrument @relation(fields: [provider, instrumentUid], references: [provider, uid], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([provider, instrumentUid, interval, time])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankCandleCoverage {
|
||||||
|
provider String
|
||||||
|
instrumentUid String
|
||||||
|
interval String
|
||||||
|
from DateTime
|
||||||
|
to DateTime
|
||||||
|
isComplete Boolean
|
||||||
|
fetchedAt DateTime
|
||||||
|
dataRevision Int @default(1)
|
||||||
|
instrument TbankInstrument @relation(fields: [provider, instrumentUid], references: [provider, uid], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([provider, instrumentUid, interval, from, to])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankSyncWork {
|
||||||
|
id String @id
|
||||||
|
userId String
|
||||||
|
revision String
|
||||||
|
scopeKey String
|
||||||
|
intent Json
|
||||||
|
state String
|
||||||
|
attemptId String
|
||||||
|
processRunId String
|
||||||
|
priority Int
|
||||||
|
progress Json
|
||||||
|
errorCode String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
connection TbankConnection @relation(fields: [userId, revision], references: [userId, revision], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
staged TbankSyncStage[]
|
||||||
|
|
||||||
|
@@unique([userId, revision, scopeKey])
|
||||||
|
@@index([userId, revision, state, priority])
|
||||||
|
@@unique([id, attemptId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model TbankSyncStage {
|
||||||
|
workId String
|
||||||
|
attemptId String
|
||||||
|
sourceKey String
|
||||||
|
itemKey String
|
||||||
|
payload Json
|
||||||
|
work TbankSyncWork @relation(fields: [workId, attemptId], references: [id, attemptId], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
|
||||||
|
@@id([workId, attemptId, sourceKey, itemKey])
|
||||||
}
|
}
|
||||||
|
|
||||||
model Session {
|
model Session {
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
const assert = require("node:assert/strict");
|
const assert = require('node:assert/strict');
|
||||||
const { execFileSync } = require("node:child_process");
|
const { execFileSync } = require('node:child_process');
|
||||||
const { version } = require("../package.json");
|
|
||||||
const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
|
|
||||||
|
|
||||||
assert.equal(git("status", "--porcelain"), "", "Commit all changes before preparing a release");
|
const { version } = require('../package.json');
|
||||||
const tags = git("tag", "--merged", "HEAD", "--list", "v[0-9]*", "--sort=-version:refname")
|
// eslint-disable-next-line sonarjs/no-os-command-from-path -- Developer-only command uses the operator PATH and fixed executable/arguments; no request input.
|
||||||
.split("\n").filter(tag => /^v\d+\.\d+\.\d+$/.test(tag));
|
const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim();
|
||||||
assert.equal(version, tags[0]?.slice(1) ?? "0.0.0",
|
|
||||||
"Version is already prepared or release tags are missing. Fetch tags; finish the existing release before preparing another.");
|
assert.equal(git('status', '--porcelain'), '', 'Commit all changes before preparing a release');
|
||||||
|
const tags = git('tag', '--merged', 'HEAD', '--list', 'v[0-9]*', '--sort=-version:refname')
|
||||||
|
.split('\n').filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag));
|
||||||
|
assert.equal(version, tags[0]?.slice(1) ?? '0.0.0',
|
||||||
|
'Version is already prepared or release tags are missing. Fetch tags; finish the existing release before preparing another.');
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ Object.assign(process.env, {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const { NestFactory } = require('@nestjs/core');
|
const { NestFactory } = require('@nestjs/core');
|
||||||
|
|
||||||
const { AppModule } = require('../dist/src/app.module.js');
|
const { AppModule } = require('../dist/src/app.module.js');
|
||||||
const { API_PREFIX, createOpenApiDocument } = require('../dist/src/openapi.js');
|
const { API_PREFIX, createOpenApiDocument } = require('../dist/src/openapi.js');
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
|||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { LoggerModule } from 'nestjs-pino';
|
import { LoggerModule } from 'nestjs-pino';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
import { LoggingModule } from './common/logging/logging.module';
|
import { LoggingModule } from './common/logging/logging.module';
|
||||||
import { Environment, validateEnv } from './config/env.validation';
|
import { Environment, validateEnv } from './config/env.validation';
|
||||||
import { AuthModule } from './modules/auth/auth.module';
|
import { AuthModule } from './modules/auth/auth.module';
|
||||||
@@ -12,6 +13,7 @@ import { InstrumentsModule } from './modules/investments/instruments/instruments
|
|||||||
import { OperationsModule } from './modules/investments/operations/operations.module';
|
import { OperationsModule } from './modules/investments/operations/operations.module';
|
||||||
import { PortfolioModule } from './modules/investments/portfolio/portfolio.module';
|
import { PortfolioModule } from './modules/investments/portfolio/portfolio.module';
|
||||||
import { TbankConnectionModule } from './modules/investments/tbank-connection/tbank-connection.module';
|
import { TbankConnectionModule } from './modules/investments/tbank-connection/tbank-connection.module';
|
||||||
|
import { TbankSyncModule } from './modules/investments/tbank-sync/tbank-sync.module';
|
||||||
import { UpcomingEventsModule } from './modules/investments/upcoming-events/upcoming-events.module';
|
import { UpcomingEventsModule } from './modules/investments/upcoming-events/upcoming-events.module';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
|
|
||||||
@@ -64,6 +66,7 @@ import { PrismaModule } from './prisma/prisma.module';
|
|||||||
UpcomingEventsModule,
|
UpcomingEventsModule,
|
||||||
InstrumentsModule,
|
InstrumentsModule,
|
||||||
TbankConnectionModule,
|
TbankConnectionModule,
|
||||||
|
TbankSyncModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
+45
-23
@@ -1,12 +1,30 @@
|
|||||||
export type Decimal = { value: bigint; scale: number };
|
export const DECIMAL_RADIX = 10n;
|
||||||
|
|
||||||
|
const SIGN_LENGTH = 1;
|
||||||
|
const NEGATIVE_SIGN = -1n;
|
||||||
|
const POSITIVE_SIGN = 1n;
|
||||||
|
const ZERO_UNITS = 0n;
|
||||||
|
const EQUAL = 0;
|
||||||
|
const GREATER_THAN = 1;
|
||||||
|
const LESS_THAN = -1;
|
||||||
|
const INTEGER_SCALE = 0;
|
||||||
|
const MIN_WHOLE_DIGITS = 1;
|
||||||
|
const DIGITS_START = 0;
|
||||||
|
const PREVIOUS_DIGIT_OFFSET = 1;
|
||||||
|
const DIGIT_STEP = 1;
|
||||||
|
const ROUNDING_DIVISOR = 2n;
|
||||||
|
|
||||||
|
export type Decimal = { scale: number; value: bigint };
|
||||||
|
|
||||||
export function decimalFromString(value: string): Decimal {
|
export function decimalFromString(value: string): Decimal {
|
||||||
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value))
|
// eslint-disable-next-line security/detect-unsafe-regex -- Anchored decimal grammar: the literal decimal point separates disjoint digit runs; backtracking is linear.
|
||||||
|
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value)) {
|
||||||
throw new Error('Invalid decimal string');
|
throw new Error('Invalid decimal string');
|
||||||
|
}
|
||||||
const negative = value.startsWith('-');
|
const negative = value.startsWith('-');
|
||||||
const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.');
|
const [whole, fraction = ''] = (negative ? value.slice(SIGN_LENGTH) : value).split('.');
|
||||||
return {
|
return {
|
||||||
value: (negative ? -1n : 1n) * BigInt(`${whole}${fraction}`),
|
value: (negative ? NEGATIVE_SIGN : POSITIVE_SIGN) * BigInt(`${whole}${fraction}`),
|
||||||
scale: fraction.length,
|
scale: fraction.length,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -15,8 +33,8 @@ export function add(left: Decimal, right: Decimal): Decimal {
|
|||||||
const scale = Math.max(left.scale, right.scale);
|
const scale = Math.max(left.scale, right.scale);
|
||||||
return {
|
return {
|
||||||
value:
|
value:
|
||||||
left.value * 10n ** BigInt(scale - left.scale) +
|
left.value * DECIMAL_RADIX ** BigInt(scale - left.scale) +
|
||||||
right.value * 10n ** BigInt(scale - right.scale),
|
right.value * DECIMAL_RADIX ** BigInt(scale - right.scale),
|
||||||
scale,
|
scale,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -30,33 +48,37 @@ export function multiply(left: Decimal, right: Decimal): Decimal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function isZero(value: Decimal): boolean {
|
export function isZero(value: Decimal): boolean {
|
||||||
return value.value === 0n;
|
return value.value === ZERO_UNITS;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function compare(left: Decimal, right: Decimal): number {
|
export function compare(left: Decimal, right: Decimal): number {
|
||||||
const difference = subtract(left, right).value;
|
const difference = subtract(left, right).value;
|
||||||
return difference === 0n ? 0 : difference > 0n ? 1 : -1;
|
return difference === ZERO_UNITS ? EQUAL : difference > ZERO_UNITS ? GREATER_THAN : LESS_THAN;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatDecimal({ value, scale }: Decimal): string {
|
export function formatDecimal({ value, scale }: Decimal): string {
|
||||||
if (value === 0n) return '0';
|
if (value === ZERO_UNITS) return '0';
|
||||||
const sign = value < 0n ? '-' : '';
|
const sign = value < ZERO_UNITS ? '-' : '';
|
||||||
if (scale === 0) return `${sign}${value < 0n ? -value : value}`;
|
if (scale === INTEGER_SCALE) return `${sign}${value < ZERO_UNITS ? -value : value}`;
|
||||||
const digits = (value < 0n ? -value : value)
|
const digits = (value < ZERO_UNITS ? -value : value)
|
||||||
.toString()
|
.toString()
|
||||||
.padStart(scale + 1, '0');
|
.padStart(scale + MIN_WHOLE_DIGITS, '0');
|
||||||
const whole = digits.slice(0, -scale) || '0';
|
const whole = digits.slice(DIGITS_START, -scale) || '0';
|
||||||
const fraction = digits.slice(-scale).replace(/0+$/, '');
|
const rawFraction = digits.slice(-scale);
|
||||||
return `${sign}${whole}${fraction ? `.${fraction}` : ''}`;
|
let fractionEnd = rawFraction.length;
|
||||||
|
while (rawFraction.charAt(fractionEnd - PREVIOUS_DIGIT_OFFSET) === '0') fractionEnd -= DIGIT_STEP;
|
||||||
|
const fraction = rawFraction.slice(DIGITS_START, fractionEnd);
|
||||||
|
const fractionalPart = fraction ? '.' + fraction : '';
|
||||||
|
return `${sign}${whole}${fractionalPart}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Round half away from zero; callers choose presentation precision explicitly.
|
// Round half away from zero; callers choose presentation precision explicitly.
|
||||||
export function divide(left: Decimal, right: Decimal, scale: number): Decimal {
|
export function divide(left: Decimal, right: Decimal, scale: number): Decimal {
|
||||||
if (right.value === 0n) throw new Error('Division by zero');
|
if (right.value === ZERO_UNITS) throw new Error('Division by zero');
|
||||||
const numerator = left.value * 10n ** BigInt(right.scale + scale);
|
const numerator = left.value * DECIMAL_RADIX ** BigInt(right.scale + scale);
|
||||||
const denominator = right.value * 10n ** BigInt(left.scale);
|
const denominator = right.value * DECIMAL_RADIX ** BigInt(left.scale);
|
||||||
const sign = numerator < 0n !== denominator < 0n ? -1n : 1n;
|
const sign = (numerator < ZERO_UNITS) !== (denominator < ZERO_UNITS) ? NEGATIVE_SIGN : POSITIVE_SIGN;
|
||||||
const n = numerator < 0n ? -numerator : numerator;
|
const n = numerator < ZERO_UNITS ? -numerator : numerator;
|
||||||
const d = denominator < 0n ? -denominator : denominator;
|
const d = denominator < ZERO_UNITS ? -denominator : denominator;
|
||||||
return { value: sign * ((n + d / 2n) / d), scale };
|
return { value: sign * ((n + d / ROUNDING_DIVISOR) / d), scale };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { HttpStatus, applyDecorators } from '@nestjs/common';
|
import { applyDecorators, HttpStatus } from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
ApiExtraModels,
|
ApiExtraModels,
|
||||||
ApiProperty,
|
ApiProperty,
|
||||||
|
ApiPropertyOptional,
|
||||||
ApiResponse,
|
ApiResponse,
|
||||||
getSchemaPath,
|
getSchemaPath,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
@@ -13,11 +14,17 @@ export class ProblemDetailsDto {
|
|||||||
@ApiProperty({ example: 'UNAUTHORIZED' })
|
@ApiProperty({ example: 'UNAUTHORIZED' })
|
||||||
declare code: string;
|
declare code: string;
|
||||||
|
|
||||||
@ApiProperty({
|
// eslint-disable-next-line @darraghor/nestjs-typed/api-property-returning-array-should-set-array -- Raw OpenAPI items schema already declares type: array.
|
||||||
required: false,
|
@ApiPropertyOptional({
|
||||||
|
type: 'array',
|
||||||
|
items: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['pointer', 'detail'],
|
||||||
|
properties: { pointer: { type: 'string' }, detail: { type: 'string' } },
|
||||||
|
},
|
||||||
example: [{ pointer: '#/email', detail: 'must be a valid email address' }],
|
example: [{ pointer: '#/email', detail: 'must be a valid email address' }],
|
||||||
})
|
})
|
||||||
errors?: { pointer: string; detail: string }[];
|
errors?: { detail: string; pointer: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
function problemResponse(status: number, description: string) {
|
function problemResponse(status: number, description: string) {
|
||||||
@@ -32,7 +39,7 @@ function problemResponse(status: number, description: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ApiProblemResponses(): MethodDecorator & ClassDecorator {
|
export function ApiProblemResponses(): ClassDecorator & MethodDecorator {
|
||||||
return applyDecorators(
|
return applyDecorators(
|
||||||
ApiExtraModels(ProblemDetailsDto),
|
ApiExtraModels(ProblemDetailsDto),
|
||||||
problemResponse(HttpStatus.BAD_REQUEST, 'Invalid request'),
|
problemResponse(HttpStatus.BAD_REQUEST, 'Invalid request'),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
||||||
|
|
||||||
import { CredentialsDto } from '../modules/auth/presentation/auth.dto';
|
import { CredentialsDto } from '../modules/auth/presentation/auth.dto';
|
||||||
import {
|
import {
|
||||||
CreateBankCardDto,
|
CreateBankCardDto,
|
||||||
@@ -6,7 +7,8 @@ import {
|
|||||||
} from '../modules/banking/bank-cards/presentation/bank-card.dto';
|
} from '../modules/banking/bank-cards/presentation/bank-card.dto';
|
||||||
|
|
||||||
describe('DTO validation', () => {
|
describe('DTO validation', () => {
|
||||||
const pipe = new ValidationPipe({ transform: true, whitelist: true });
|
const pipe = new ValidationPipe({
|
||||||
|
forbidUnknownValues: true, transform: true, whitelist: true });
|
||||||
|
|
||||||
it('requires credentials and normalizes a valid email', async () => {
|
it('requires credentials and normalizes a valid email', async () => {
|
||||||
const metadata = { type: 'body' as const, metatype: CredentialsDto };
|
const metadata = { type: 'body' as const, metatype: CredentialsDto };
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ArgumentsHost } from '@nestjs/common';
|
import { ArgumentsHost } from '@nestjs/common';
|
||||||
|
|
||||||
import { HttpExceptionFilter } from './http-exception.filter';
|
import { HttpExceptionFilter } from './http-exception.filter';
|
||||||
|
|
||||||
describe('HttpExceptionFilter', () => {
|
describe('HttpExceptionFilter', () => {
|
||||||
@@ -14,7 +15,10 @@ describe('HttpExceptionFilter', () => {
|
|||||||
}),
|
}),
|
||||||
} as unknown as ArgumentsHost;
|
} as unknown as ArgumentsHost;
|
||||||
|
|
||||||
filter.catch(new Error('database password: secret'), host);
|
filter.catch(
|
||||||
|
new Error('operation failed\npassword: SYNTHETIC_AUDIT_SECRET'),
|
||||||
|
host,
|
||||||
|
);
|
||||||
|
|
||||||
expect(status).toHaveBeenCalledWith(500);
|
expect(status).toHaveBeenCalledWith(500);
|
||||||
expect(type).toHaveBeenCalledWith('application/problem+json');
|
expect(type).toHaveBeenCalledWith('application/problem+json');
|
||||||
@@ -23,7 +27,6 @@ describe('HttpExceptionFilter', () => {
|
|||||||
code: 'INTERNAL_SERVER_ERROR',
|
code: 'INTERNAL_SERVER_ERROR',
|
||||||
});
|
});
|
||||||
expect(locals.publicErrorCode).toBe('INTERNAL_SERVER_ERROR');
|
expect(locals.publicErrorCode).toBe('INTERNAL_SERVER_ERROR');
|
||||||
expect(typeof locals.errorStack).toBe('string');
|
expect(locals.errorStack).toBeUndefined();
|
||||||
expect(locals.errorStack).not.toContain('database password: secret');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { Response } from 'express';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ArgumentsHost,
|
ArgumentsHost,
|
||||||
Catch,
|
Catch,
|
||||||
@@ -6,7 +8,6 @@ import {
|
|||||||
HttpStatus,
|
HttpStatus,
|
||||||
ValidationError,
|
ValidationError,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type { Response } from 'express';
|
|
||||||
|
|
||||||
@Catch()
|
@Catch()
|
||||||
export class HttpExceptionFilter implements ExceptionFilter {
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
@@ -14,40 +15,33 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
|||||||
const context = host.switchToHttp();
|
const context = host.switchToHttp();
|
||||||
const response = context.getResponse<Response>();
|
const response = context.getResponse<Response>();
|
||||||
const status =
|
const status =
|
||||||
exception instanceof HttpException
|
exception instanceof HttpException ?
|
||||||
? exception.getStatus()
|
exception.getStatus() :
|
||||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
|
||||||
const payload =
|
const payload =
|
||||||
exception instanceof HttpException ? exception.getResponse() : undefined;
|
exception instanceof HttpException ? exception.getResponse() : undefined;
|
||||||
const isValidation = Array.isArray(
|
const isValidation = Array.isArray(
|
||||||
(payload as { message?: unknown })?.message,
|
(payload as { message?: unknown })?.message,
|
||||||
);
|
);
|
||||||
const code = isValidation
|
const code = isValidation ?
|
||||||
? 'VALIDATION_ERROR'
|
'VALIDATION_ERROR' :
|
||||||
: this.codeFor(status, payload);
|
this.codeFor(status, payload);
|
||||||
(response.locals ??= {}).publicErrorCode = code;
|
response.locals ??= {};
|
||||||
if (
|
response.locals.publicErrorCode = code;
|
||||||
status >= Number(HttpStatus.INTERNAL_SERVER_ERROR) &&
|
|
||||||
exception instanceof Error
|
|
||||||
)
|
|
||||||
response.locals.errorStack = exception.stack
|
|
||||||
?.split('\n')
|
|
||||||
.slice(1)
|
|
||||||
.join('\n');
|
|
||||||
response
|
response
|
||||||
.status(status)
|
.status(status)
|
||||||
.type('application/problem+json')
|
.type('application/problem+json')
|
||||||
.json({
|
.json({
|
||||||
status,
|
status,
|
||||||
code,
|
code,
|
||||||
...(isValidation
|
...(isValidation ?
|
||||||
? {
|
{
|
||||||
errors: this.validationErrors(
|
errors: this.validationErrors(
|
||||||
(payload as { message: ValidationError[] }).message,
|
(payload as { message: ValidationError[] }).message,
|
||||||
),
|
),
|
||||||
}
|
} :
|
||||||
: {}),
|
{}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,6 +51,7 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
|||||||
if (typeof code === 'string') return code;
|
if (typeof code === 'string') return code;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The lookup key is a numeric HTTP status, never a property name from the request.
|
||||||
{
|
{
|
||||||
400: 'BAD_REQUEST',
|
400: 'BAD_REQUEST',
|
||||||
401: 'UNAUTHORIZED',
|
401: 'UNAUTHORIZED',
|
||||||
@@ -69,12 +64,18 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
|||||||
|
|
||||||
private validationErrors(
|
private validationErrors(
|
||||||
errors: ValidationError[],
|
errors: ValidationError[],
|
||||||
): { pointer: string; detail: string }[] {
|
prefix = '#',
|
||||||
return errors.flatMap((error) =>
|
): { detail: string; pointer: string }[] {
|
||||||
Object.values(error.constraints ?? {}).map((detail) => ({
|
return errors.flatMap((error) => {
|
||||||
pointer: `#/${error.property}`,
|
if (!error || typeof error.property !== 'string') return [];
|
||||||
detail,
|
const pointer = `${prefix}/${error.property.replaceAll('~', '~0').replaceAll('/', '~1')}`;
|
||||||
})),
|
return [
|
||||||
);
|
...Object.values(error.constraints ?? {}).map((detail) => ({
|
||||||
|
pointer,
|
||||||
|
detail,
|
||||||
|
})),
|
||||||
|
...this.validationErrors(error.children ?? [], pointer),
|
||||||
|
];
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { RequestContextService } from './request-context.service';
|
import { RequestContextService } from './request-context.service';
|
||||||
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
||||||
import { StructuredLogger } from './structured-logger.service';
|
import { StructuredLogger } from './structured-logger.service';
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||||
|
|
||||||
export type RequestLogContext = {
|
export type RequestLogContext = {
|
||||||
requestId: string;
|
|
||||||
clientRequestId?: string;
|
|
||||||
userId?: string;
|
|
||||||
brokerageAccountId?: string;
|
brokerageAccountId?: string;
|
||||||
|
clientRequestId?: string;
|
||||||
|
requestId: string;
|
||||||
|
userId?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
|
|
||||||
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
import { RequestLoggingMiddleware } from './request-logging.middleware';
|
||||||
|
|
||||||
describe('RequestLoggingMiddleware', () => {
|
describe('RequestLoggingMiddleware', () => {
|
||||||
@@ -19,11 +20,11 @@ describe('RequestLoggingMiddleware', () => {
|
|||||||
const next = jest.fn();
|
const next = jest.fn();
|
||||||
|
|
||||||
const request: {
|
const request: {
|
||||||
method: string;
|
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
route: { path: string };
|
|
||||||
header: jest.Mock<string>;
|
header: jest.Mock<string>;
|
||||||
id?: string;
|
id?: string;
|
||||||
|
method: string;
|
||||||
|
route: { path: string };
|
||||||
} = {
|
} = {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
baseUrl: '/api/v1',
|
baseUrl: '/api/v1',
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { constants as httpStatus } from 'node:http2';
|
|
||||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
||||||
import type { NextFunction, Request, Response } from 'express';
|
import type { NextFunction, Request, Response } from 'express';
|
||||||
|
|
||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { constants as httpStatus } from 'node:http2';
|
||||||
|
|
||||||
import { RequestContextService } from './request-context.service';
|
import { RequestContextService } from './request-context.service';
|
||||||
import { StructuredLogger } from './structured-logger.service';
|
import { StructuredLogger } from './structured-logger.service';
|
||||||
|
|
||||||
@@ -31,29 +33,26 @@ export class RequestLoggingMiddleware implements NestMiddleware {
|
|||||||
const routePath = (routeRequest as { route?: { path?: unknown } }).route
|
const routePath = (routeRequest as { route?: { path?: unknown } }).route
|
||||||
?.path;
|
?.path;
|
||||||
const route =
|
const route =
|
||||||
typeof routePath === 'string'
|
typeof routePath === 'string' ?
|
||||||
? `${request.baseUrl}${routePath}`
|
`${request.baseUrl}${routePath}` :
|
||||||
: '<unmatched>';
|
'<unmatched>';
|
||||||
const context = {
|
const context = {
|
||||||
method: request.method,
|
method: request.method,
|
||||||
route,
|
route,
|
||||||
status: response.statusCode,
|
status: response.statusCode,
|
||||||
durationMs: Math.round(performance.now() - startedAt),
|
durationMs: Math.round(performance.now() - startedAt),
|
||||||
...(response.locals.publicErrorCode
|
...(response.locals.publicErrorCode ?
|
||||||
? { code: response.locals.publicErrorCode as string }
|
{ code: response.locals.publicErrorCode as string } :
|
||||||
: {}),
|
{}),
|
||||||
...(response.locals.errorStack
|
|
||||||
? { stack: response.locals.errorStack as string }
|
|
||||||
: {}),
|
|
||||||
};
|
};
|
||||||
const level =
|
const level =
|
||||||
response.statusCode >= httpStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR
|
response.statusCode >= httpStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR ?
|
||||||
? 'error'
|
'error' :
|
||||||
: response.statusCode === httpStatus.HTTP_STATUS_TOO_MANY_REQUESTS ||
|
response.statusCode === httpStatus.HTTP_STATUS_TOO_MANY_REQUESTS ||
|
||||||
response.statusCode === httpStatus.HTTP_STATUS_UNAUTHORIZED ||
|
response.statusCode === httpStatus.HTTP_STATUS_UNAUTHORIZED ||
|
||||||
response.statusCode === httpStatus.HTTP_STATUS_FORBIDDEN
|
response.statusCode === httpStatus.HTTP_STATUS_FORBIDDEN ?
|
||||||
? 'warn'
|
'warn' :
|
||||||
: 'info';
|
'info';
|
||||||
this.logger.event(level, 'http.request.completed', context);
|
this.logger.event(level, 'http.request.completed', context);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
|
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
|
||||||
import { PinoLogger } from 'nestjs-pino';
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
import { RequestContextService } from './request-context.service';
|
import { RequestContextService } from './request-context.service';
|
||||||
|
|
||||||
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
type LogLevel = 'debug' | 'error' | 'info' | 'warn';
|
||||||
type LogContext = Record<string, string | number | boolean | undefined>;
|
type LogContext = Record<string, boolean | number | string | undefined>;
|
||||||
|
|
||||||
const allowedFields = new Set([
|
const allowedFields = new Set([
|
||||||
'service',
|
|
||||||
'environment',
|
|
||||||
'requestId',
|
|
||||||
'clientRequestId',
|
|
||||||
'userId',
|
|
||||||
'brokerageAccountId',
|
|
||||||
'method',
|
|
||||||
'route',
|
|
||||||
'status',
|
|
||||||
'durationMs',
|
|
||||||
'code',
|
|
||||||
'stack',
|
|
||||||
'operation',
|
|
||||||
'grpcCode',
|
|
||||||
'attempts',
|
'attempts',
|
||||||
|
'brokerageAccountId',
|
||||||
|
'clientRequestId',
|
||||||
|
'code',
|
||||||
'count',
|
'count',
|
||||||
|
'durationMs',
|
||||||
|
'environment',
|
||||||
'found',
|
'found',
|
||||||
|
'grpcCode',
|
||||||
|
'method',
|
||||||
|
'operation',
|
||||||
|
'requestId',
|
||||||
|
'route',
|
||||||
|
'service',
|
||||||
|
'status',
|
||||||
|
'userId',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -49,6 +49,7 @@ export class StructuredLogger implements OnApplicationShutdown {
|
|||||||
message: string,
|
message: string,
|
||||||
context: LogContext = {},
|
context: LogContext = {},
|
||||||
): void {
|
): void {
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The log level is restricted to the internal LogLevel union.
|
||||||
this.pino[level](
|
this.pino[level](
|
||||||
this.safeContext({ ...this.requestContext.get(), ...context }),
|
this.safeContext({ ...this.requestContext.get(), ...context }),
|
||||||
message,
|
message,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
import type { Money } from './money.types';
|
import type { Money } from './money.types';
|
||||||
|
|
||||||
export class MoneyDto implements Money {
|
export class MoneyDto implements Money {
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
|
export const ISO_DATE_LENGTH = 10;
|
||||||
|
export const ISO_DATE_START = 0;
|
||||||
export const MILLISECONDS_PER_SECOND = 1_000;
|
export const MILLISECONDS_PER_SECOND = 1_000;
|
||||||
export const MILLISECONDS_PER_DAY = 86_400_000;
|
export const MILLISECONDS_PER_DAY = 86_400_000;
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
const MIN_PORT = 1;
|
||||||
|
const MIN_REQUESTS_PER_SECOND = 1;
|
||||||
|
|
||||||
const DEFAULT_PORT = 3000;
|
const DEFAULT_PORT = 3000;
|
||||||
const DEFAULT_TBANK_RATE_LIMIT_PER_SECOND = 5;
|
const DEFAULT_TBANK_RATE_LIMIT_PER_SECOND = 5;
|
||||||
const MAX_PORT = 65_535;
|
const MAX_PORT = 65_535;
|
||||||
@@ -7,12 +10,12 @@ export interface Environment {
|
|||||||
DATABASE_URL: string;
|
DATABASE_URL: string;
|
||||||
FRONTEND_ORIGIN: string;
|
FRONTEND_ORIGIN: string;
|
||||||
JWT_SECRET: string;
|
JWT_SECRET: string;
|
||||||
|
LOG_LEVEL: 'debug' | 'error' | 'info' | 'warn';
|
||||||
PORT: number;
|
PORT: number;
|
||||||
TOKEN_ENCRYPTION_KEY: string;
|
|
||||||
TBANK_CA_CERT_PATH?: string;
|
TBANK_CA_CERT_PATH?: string;
|
||||||
TBANK_GRPC_ENDPOINT: string;
|
TBANK_GRPC_ENDPOINT: string;
|
||||||
TBANK_RATE_LIMIT_PER_SECOND: number;
|
TBANK_RATE_LIMIT_PER_SECOND: number;
|
||||||
LOG_LEVEL: 'debug' | 'info' | 'warn' | 'error';
|
TOKEN_ENCRYPTION_KEY: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateEnv(config: Record<string, unknown>): Environment {
|
export function validateEnv(config: Record<string, unknown>): Environment {
|
||||||
@@ -56,7 +59,7 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
const parsedPort = Number(port);
|
const parsedPort = Number(port);
|
||||||
if (
|
if (
|
||||||
!Number.isInteger(parsedPort) ||
|
!Number.isInteger(parsedPort) ||
|
||||||
parsedPort < 1 ||
|
parsedPort < MIN_PORT ||
|
||||||
parsedPort > MAX_PORT
|
parsedPort > MAX_PORT
|
||||||
) {
|
) {
|
||||||
throw new Error('PORT must be a valid port number');
|
throw new Error('PORT must be a valid port number');
|
||||||
@@ -71,7 +74,7 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
typeof tokenEncryptionKey !== 'string' ||
|
typeof tokenEncryptionKey !== 'string' ||
|
||||||
!/^[A-Za-z0-9+/]+={0,2}$/.test(tokenEncryptionKey) ||
|
!/^[A-Z0-9+/]+={0,2}$/i.test(tokenEncryptionKey) ||
|
||||||
Buffer.from(tokenEncryptionKey, 'base64').length !== TOKEN_KEY_BYTES
|
Buffer.from(tokenEncryptionKey, 'base64').length !== TOKEN_KEY_BYTES
|
||||||
) {
|
) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -84,7 +87,7 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsedTbankRateLimit = Number(tbankRateLimit);
|
const parsedTbankRateLimit = Number(tbankRateLimit);
|
||||||
if (!Number.isInteger(parsedTbankRateLimit) || parsedTbankRateLimit < 1) {
|
if (!Number.isInteger(parsedTbankRateLimit) || parsedTbankRateLimit < MIN_REQUESTS_PER_SECOND) {
|
||||||
throw new Error('TBANK_RATE_LIMIT_PER_SECOND must be a positive integer');
|
throw new Error('TBANK_RATE_LIMIT_PER_SECOND must be a positive integer');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +95,7 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
throw new Error('TBANK_CA_CERT_PATH must be a file path');
|
throw new Error('TBANK_CA_CERT_PATH must be a file path');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!['debug', 'info', 'warn', 'error'].includes(logLevel as string)) {
|
if (!['debug', 'error', 'info', 'warn'].includes(logLevel as string)) {
|
||||||
throw new Error('LOG_LEVEL must be debug, info, warn, or error');
|
throw new Error('LOG_LEVEL must be debug, info, warn, or error');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,9 +105,9 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
JWT_SECRET: jwtSecret,
|
JWT_SECRET: jwtSecret,
|
||||||
PORT: parsedPort,
|
PORT: parsedPort,
|
||||||
TOKEN_ENCRYPTION_KEY: tokenEncryptionKey,
|
TOKEN_ENCRYPTION_KEY: tokenEncryptionKey,
|
||||||
...(typeof tbankCaCertPath === 'string' && tbankCaCertPath
|
...(typeof tbankCaCertPath === 'string' && tbankCaCertPath ?
|
||||||
? { TBANK_CA_CERT_PATH: tbankCaCertPath }
|
{ TBANK_CA_CERT_PATH: tbankCaCertPath } :
|
||||||
: {}),
|
{}),
|
||||||
TBANK_GRPC_ENDPOINT: tbankEndpoint,
|
TBANK_GRPC_ENDPOINT: tbankEndpoint,
|
||||||
TBANK_RATE_LIMIT_PER_SECOND: parsedTbankRateLimit,
|
TBANK_RATE_LIMIT_PER_SECOND: parsedTbankRateLimit,
|
||||||
LOG_LEVEL: logLevel as Environment['LOG_LEVEL'],
|
LOG_LEVEL: logLevel as Environment['LOG_LEVEL'],
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { MoexClient } from './moex.client';
|
import { MoexClient } from './moex.client';
|
||||||
|
|
||||||
|
const emptyEvents = {
|
||||||
|
coupons: { columns: ['coupondate', 'value', 'faceunit'], data: [] },
|
||||||
|
offers: { columns: ['offerdate'], data: [] },
|
||||||
|
description: { columns: ['name', 'value'], data: [] },
|
||||||
|
};
|
||||||
|
|
||||||
describe('MoexClient', () => {
|
describe('MoexClient', () => {
|
||||||
afterEach(() => jest.restoreAllMocks());
|
afterEach(() => jest.restoreAllMocks());
|
||||||
it('uses effective yield only for the exact ISIN and board and preserves its own price and date', async () => {
|
it('uses effective yield only for the exact ISIN and board and preserves its own price and date', async () => {
|
||||||
@@ -92,17 +98,179 @@ describe('MoexClient', () => {
|
|||||||
expect(result?.value ?? null).toBe(value === null ? null : '0');
|
expect(result?.value ?? null).toBe(value === null ? null : '0');
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
it('treats a successful response without the requested block as no events', async () => {
|
it('accepts confirmed empty blocks', async () => {
|
||||||
const fetchMock = jest.spyOn(global, 'fetch').mockResolvedValue({
|
jest
|
||||||
ok: true,
|
.spyOn(global, 'fetch')
|
||||||
json: () =>
|
.mockImplementation(() => Promise.resolve(Response.json(emptyEvents)));
|
||||||
Promise.resolve({
|
|
||||||
description: { columns: ['name', 'value'], data: [] },
|
|
||||||
boards: { columns: ['secid'], data: [] },
|
|
||||||
}),
|
|
||||||
} as Response);
|
|
||||||
|
|
||||||
await expect(new MoexClient().bondEvents('BOND')).resolves.toEqual([]);
|
await expect(new MoexClient().bondEvents('BOND')).resolves.toEqual([]);
|
||||||
fetchMock.mockRestore();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('preserves not-found semantics independently of malformed HTTP 200', async () => {
|
||||||
|
jest
|
||||||
|
.spyOn(global, 'fetch')
|
||||||
|
.mockImplementation(() =>
|
||||||
|
Promise.resolve(new Response(null, { status: 404 })),
|
||||||
|
);
|
||||||
|
const client = new MoexClient();
|
||||||
|
await expect(client.bondEvents('MISSING')).resolves.toEqual([]);
|
||||||
|
await expect(
|
||||||
|
client.bondYield('MISSING', 'ISIN', 'TQOB'),
|
||||||
|
).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['missing block', { coupons: undefined }],
|
||||||
|
['missing columns', { coupons: { data: [] } }],
|
||||||
|
['invalid column', { coupons: { columns: [null], data: [] } }],
|
||||||
|
['invalid row', { coupons: { columns: ['coupondate'], data: [null] } }],
|
||||||
|
[
|
||||||
|
'short row',
|
||||||
|
{ coupons: { columns: ['coupondate', 'value'], data: [['2099-02-01']] } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'long row',
|
||||||
|
{ coupons: { columns: ['coupondate'], data: [['2099-02-01', 2]] } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'empty cursor',
|
||||||
|
{
|
||||||
|
'coupons.cursor': { columns: ['INDEX', 'TOTAL', 'PAGESIZE'], data: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'missing cursor field',
|
||||||
|
{ 'coupons.cursor': { columns: ['INDEX', 'TOTAL'], data: [[0, 1]] } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'null cursor index',
|
||||||
|
{
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[null, 0, 1]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'boolean cursor total',
|
||||||
|
{
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[0, false, 1]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'empty cursor total',
|
||||||
|
{
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[0, '', 1]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'short page',
|
||||||
|
{
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[0, 1, 1]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
])(
|
||||||
|
'rejects %s without returning a partial calendar',
|
||||||
|
async (_name, invalid) => {
|
||||||
|
jest
|
||||||
|
.spyOn(global, 'fetch')
|
||||||
|
.mockImplementation(() =>
|
||||||
|
Promise.resolve(Response.json({ ...emptyEvents, ...invalid })),
|
||||||
|
);
|
||||||
|
await expect(new MoexClient().bondEvents('BOND')).rejects.toMatchObject({
|
||||||
|
response: { code: 'MOEX_UNAVAILABLE' },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([0, -1])(
|
||||||
|
'rejects nonpositive page size %s before repeating a fetch',
|
||||||
|
async (pageSize) => {
|
||||||
|
const starts: string[] = [];
|
||||||
|
jest.spyOn(global, 'fetch').mockImplementation((input) => {
|
||||||
|
const url = new URL(input instanceof Request ? input.url : input);
|
||||||
|
if (url.searchParams.get('iss.only')?.startsWith('coupons,')) {
|
||||||
|
starts.push(url.searchParams.get('start') ?? '');
|
||||||
|
if (starts.length > 1) {
|
||||||
|
return Promise.reject(new Error('Repeated page'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.resolve(
|
||||||
|
Response.json({
|
||||||
|
...emptyEvents,
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[0, 1, pageSize]],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await expect(new MoexClient().bondEvents('BOND')).rejects.toMatchObject({
|
||||||
|
response: { code: 'MOEX_UNAVAILABLE' },
|
||||||
|
});
|
||||||
|
expect(starts).toEqual(['0']);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([false, true])(
|
||||||
|
'reads all cursor pages and rejects a repeated index: %s',
|
||||||
|
async (repeatIndex) => {
|
||||||
|
const starts: string[] = [];
|
||||||
|
jest.spyOn(global, 'fetch').mockImplementation((input) => {
|
||||||
|
const url = new URL(input instanceof Request ? input.url : input);
|
||||||
|
const start = Number(url.searchParams.get('start'));
|
||||||
|
if (url.searchParams.get('iss.only')?.startsWith('coupons,')) {
|
||||||
|
starts.push(String(start));
|
||||||
|
if (starts.length > 2) {
|
||||||
|
return Promise.reject(new Error('Repeated page'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.resolve(
|
||||||
|
Response.json({
|
||||||
|
...emptyEvents,
|
||||||
|
'coupons': {
|
||||||
|
columns: ['coupondate', 'value', 'faceunit'],
|
||||||
|
data: [[`2099-02-0${start + 1}`, '2.000000001', 'SUR']],
|
||||||
|
},
|
||||||
|
'coupons.cursor': {
|
||||||
|
columns: ['INDEX', 'TOTAL', 'PAGESIZE'],
|
||||||
|
data: [[repeatIndex ? 0 : start, 2, 1]],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const result = new MoexClient().bondEvents('BOND');
|
||||||
|
if (repeatIndex) {
|
||||||
|
// eslint-disable-next-line jest/no-conditional-expect -- The parameterized fixture chooses the scenario; each branch asserts its outcome and the test also asserts common invariants.
|
||||||
|
await expect(result).rejects.toMatchObject({
|
||||||
|
response: { code: 'MOEX_UNAVAILABLE' },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// eslint-disable-next-line jest/no-conditional-expect -- The parameterized fixture chooses the scenario; each branch asserts its outcome and the test also asserts common invariants.
|
||||||
|
await expect(result).resolves.toEqual([
|
||||||
|
{
|
||||||
|
type: 'coupon',
|
||||||
|
date: '2099-02-01',
|
||||||
|
value: '2.000000001',
|
||||||
|
currency: 'RUB',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'coupon',
|
||||||
|
date: '2099-02-02',
|
||||||
|
value: '2.000000001',
|
||||||
|
currency: 'RUB',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
expect(starts).toEqual(['0', '1']);
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { constants as httpStatus } from 'node:http2';
|
|
||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
import { constants as httpStatus } from 'node:http2';
|
||||||
|
|
||||||
|
const MIN_PRICE_PERCENT_EXCLUSIVE = 0;
|
||||||
|
const FIRST_PAGE_OFFSET = 0;
|
||||||
|
const EXPECTED_CURSOR_ROWS = 1;
|
||||||
|
const EMPTY_PAGE_SIZE = 0;
|
||||||
|
const MIN_CURSOR_VALUE = 0;
|
||||||
|
|
||||||
const FALLBACK_PAGE_SIZE = 100;
|
const FALLBACK_PAGE_SIZE = 100;
|
||||||
|
|
||||||
@@ -7,18 +13,18 @@ const baseUrl = 'https://iss.moex.com/iss';
|
|||||||
const timeoutMs = 10_000;
|
const timeoutMs = 10_000;
|
||||||
|
|
||||||
export type MoexBondEvent =
|
export type MoexBondEvent =
|
||||||
| { type: 'coupon'; date: string; value: string; currency: string }
|
| { currency: string; date: string; type: 'coupon'; value: string } |
|
||||||
| { type: 'maturity'; date: string; value: string; currency: string }
|
{ currency: string; date: string; type: 'maturity'; value: string } |
|
||||||
| { type: 'offer'; date: string };
|
{ date: string; type: 'offer' };
|
||||||
|
|
||||||
type IssBlock = { columns?: unknown; data?: unknown };
|
type IssBlock = { columns?: unknown; data?: unknown };
|
||||||
type IssResponse = Record<string, IssBlock | undefined>;
|
type IssResponse = Record<string, IssBlock | undefined>;
|
||||||
export type MoexBondYield = {
|
export type MoexBondYield = {
|
||||||
value: string;
|
|
||||||
pricePercent: string;
|
|
||||||
date: string;
|
date: string;
|
||||||
dateType: string | null;
|
dateType: null | string;
|
||||||
|
pricePercent: string;
|
||||||
tradeAt: string;
|
tradeAt: string;
|
||||||
|
value: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -52,14 +58,15 @@ export class MoexClient {
|
|||||||
if (
|
if (
|
||||||
value === null ||
|
value === null ||
|
||||||
pricePercent === null ||
|
pricePercent === null ||
|
||||||
Number(pricePercent) <= 0 ||
|
Number(pricePercent) <= MIN_PRICE_PERCENT_EXCLUSIVE ||
|
||||||
!date ||
|
!date ||
|
||||||
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
||||||
!Number.isFinite(Date.parse(date)) ||
|
!Number.isFinite(Date.parse(date)) ||
|
||||||
!tradeAt ||
|
!tradeAt ||
|
||||||
!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(tradeAt)
|
!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(tradeAt)
|
||||||
)
|
) {
|
||||||
return null;
|
return null;
|
||||||
|
}
|
||||||
const tradeIso = `${tradeAt.replace(' ', 'T')}+03:00`;
|
const tradeIso = `${tradeAt.replace(' ', 'T')}+03:00`;
|
||||||
if (!Number.isFinite(Date.parse(tradeIso))) return null;
|
if (!Number.isFinite(Date.parse(tradeIso))) return null;
|
||||||
return {
|
return {
|
||||||
@@ -70,6 +77,7 @@ export class MoexClient {
|
|||||||
tradeAt: new Date(tradeIso).toISOString(),
|
tradeAt: new Date(tradeIso).toISOString(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async bondEvents(secid: string): Promise<MoexBondEvent[]> {
|
async bondEvents(secid: string): Promise<MoexBondEvent[]> {
|
||||||
const path = `securities/${encodeURIComponent(secid)}/bondization.json`;
|
const path = `securities/${encodeURIComponent(secid)}/bondization.json`;
|
||||||
const [coupons, offers, description] = await Promise.all([
|
const [coupons, offers, description] = await Promise.all([
|
||||||
@@ -86,8 +94,9 @@ export class MoexClient {
|
|||||||
const date = text(row.coupondate);
|
const date = text(row.coupondate);
|
||||||
const value = numberText(row.value);
|
const value = numberText(row.value);
|
||||||
const currency = currencyText(row.faceunit);
|
const currency = currencyText(row.faceunit);
|
||||||
if (date && value && currency)
|
if (date && value && currency) {
|
||||||
events.push({ type: 'coupon', date, value, currency });
|
events.push({ type: 'coupon', date, value, currency });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const row of offers) {
|
for (const row of offers) {
|
||||||
const date = text(row.offerdate);
|
const date = text(row.offerdate);
|
||||||
@@ -99,8 +108,9 @@ export class MoexClient {
|
|||||||
const date = values.get('MATDATE');
|
const date = values.get('MATDATE');
|
||||||
const value = numberText(values.get('FACEVALUE'));
|
const value = numberText(values.get('FACEVALUE'));
|
||||||
const currency = currencyText(values.get('FACEUNIT'));
|
const currency = currencyText(values.get('FACEUNIT'));
|
||||||
if (date && value && currency)
|
if (date && value && currency) {
|
||||||
events.push({ type: 'maturity', date, value, currency });
|
events.push({ type: 'maturity', date, value, currency });
|
||||||
|
}
|
||||||
return events;
|
return events;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,35 +120,41 @@ export class MoexClient {
|
|||||||
paginated = true,
|
paginated = true,
|
||||||
): Promise<Record<string, unknown>[]> {
|
): Promise<Record<string, unknown>[]> {
|
||||||
const rows: Record<string, unknown>[] = [];
|
const rows: Record<string, unknown>[] = [];
|
||||||
let start = 0;
|
let start = FIRST_PAGE_OFFSET;
|
||||||
for (;;) {
|
for (;;) {
|
||||||
const query = new URLSearchParams({
|
const query = new URLSearchParams({
|
||||||
'iss.meta': 'off',
|
'iss.meta': 'off',
|
||||||
'iss.only': `${block},${block}.cursor`,
|
'iss.only': `${block},${block}.cursor`,
|
||||||
start: String(start),
|
'start': String(start),
|
||||||
});
|
});
|
||||||
const response = await this.request(`${baseUrl}/${path}?${query}`);
|
const response = await this.request(`${baseUrl}/${path}?${query}`);
|
||||||
if (!response) return rows;
|
if (!response) return rows;
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Keys are fixed MOEX block names; row indexes come from the validated columns array.
|
||||||
const current = parseRows(response[block]);
|
const current = parseRows(response[block]);
|
||||||
rows.push(...current);
|
rows.push(...current);
|
||||||
if (!paginated) return rows;
|
if (!paginated) return rows;
|
||||||
const cursorBlock = response[`${block}.cursor`];
|
const cursorBlock = response[`${block}.cursor`];
|
||||||
if (!cursorBlock) {
|
if (cursorBlock === undefined) {
|
||||||
if (current.length < FALLBACK_PAGE_SIZE) return rows;
|
if (current.length < FALLBACK_PAGE_SIZE) return rows;
|
||||||
start += FALLBACK_PAGE_SIZE;
|
start += FALLBACK_PAGE_SIZE;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const cursor = parseRows(cursorBlock)[0];
|
const cursors = parseRows(cursorBlock);
|
||||||
|
const cursor = cursors[0];
|
||||||
const index = integer(cursor?.index);
|
const index = integer(cursor?.index);
|
||||||
const total = integer(cursor?.total);
|
const total = integer(cursor?.total);
|
||||||
const pageSize = integer(cursor?.pagesize);
|
const pageSize = integer(cursor?.pagesize);
|
||||||
if (
|
if (
|
||||||
index === null ||
|
cursors.length !== EXPECTED_CURSOR_ROWS ||
|
||||||
|
index !== start ||
|
||||||
total === null ||
|
total === null ||
|
||||||
pageSize === null ||
|
pageSize === null ||
|
||||||
index + pageSize >= total
|
pageSize === EMPTY_PAGE_SIZE ||
|
||||||
)
|
current.length !== Math.min(pageSize, total - start)
|
||||||
return rows;
|
) {
|
||||||
|
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
||||||
|
}
|
||||||
|
if (index + pageSize >= total) return rows;
|
||||||
start = index + pageSize;
|
start = index + pageSize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,8 +167,9 @@ export class MoexClient {
|
|||||||
if (response.status === httpStatus.HTTP_STATUS_NOT_FOUND) return null;
|
if (response.status === httpStatus.HTTP_STATUS_NOT_FOUND) return null;
|
||||||
if (!response.ok) throw new Error(`MOEX HTTP ${response.status}`);
|
if (!response.ok) throw new Error(`MOEX HTTP ${response.status}`);
|
||||||
const body: unknown = await response.json();
|
const body: unknown = await response.json();
|
||||||
if (!body || typeof body !== 'object')
|
if (!body || typeof body !== 'object') {
|
||||||
throw new Error('MOEX malformed response');
|
throw new Error('MOEX malformed response');
|
||||||
|
}
|
||||||
return body as IssResponse;
|
return body as IssResponse;
|
||||||
} catch {
|
} catch {
|
||||||
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
||||||
@@ -161,36 +178,40 @@ export class MoexClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseRows(block: IssBlock | undefined): Record<string, unknown>[] {
|
function parseRows(block: IssBlock | undefined): Record<string, unknown>[] {
|
||||||
if (!block) return [];
|
if (!Array.isArray(block?.columns) || !Array.isArray(block?.data)) {
|
||||||
if (!Array.isArray(block.columns) || !Array.isArray(block.data))
|
|
||||||
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
||||||
|
}
|
||||||
const columns = block.columns;
|
const columns = block.columns;
|
||||||
if (!columns.every((column) => typeof column === 'string'))
|
if (!columns.every((column) => typeof column === 'string')) {
|
||||||
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
||||||
|
}
|
||||||
return block.data.map((values) => {
|
return block.data.map((values) => {
|
||||||
if (!Array.isArray(values))
|
if (!Array.isArray(values) || values.length !== columns.length) {
|
||||||
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'MOEX_UNAVAILABLE' });
|
||||||
|
}
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Keys are fixed MOEX block names; row indexes come from the validated columns array.
|
||||||
columns.map((column, index) => [column.toLowerCase(), values[index]]),
|
columns.map((column, index) => [column.toLowerCase(), values[index]]),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function text(value: unknown): string | null {
|
function text(value: unknown): null | string {
|
||||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function numberText(value: unknown): string | null {
|
function numberText(value: unknown): null | string {
|
||||||
const result = typeof value === 'number' ? String(value) : text(value);
|
const result = typeof value === 'number' ? String(value) : text(value);
|
||||||
|
// eslint-disable-next-line security/detect-unsafe-regex -- Anchored decimal grammar: the literal decimal point separates disjoint digit runs; backtracking is linear.
|
||||||
return result && /^-?\d+(?:\.\d+)?$/.test(result) ? result : null;
|
return result && /^-?\d+(?:\.\d+)?$/.test(result) ? result : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function currencyText(value: unknown): string | null {
|
function currencyText(value: unknown): null | string {
|
||||||
const result = text(value)?.toUpperCase();
|
const result = text(value)?.toUpperCase();
|
||||||
return result === 'SUR' ? 'RUB' : (result ?? null);
|
return result === 'SUR' ? 'RUB' : (result ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
function integer(value: unknown): number | null {
|
function integer(value: unknown): null | number {
|
||||||
const result = Number(value);
|
const result = Number(numberText(value) ?? NaN);
|
||||||
return Number.isSafeInteger(result) && result >= 0 ? result : null;
|
return Number.isSafeInteger(result) && result >= MIN_CURSOR_VALUE ? result : null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { MoexClient } from './moex.client';
|
import { MoexClient } from './moex.client';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
import { ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
|
||||||
import { NcrRatingsClient } from './ncr-ratings.client';
|
import { NcrRatingsClient } from './ncr-ratings.client';
|
||||||
const isin = 'RU000A10EW44';
|
const isin = 'RU000A10EW44';
|
||||||
const row = (value = 'AAA.ru', code = isin, href = '/ratings/issues/123/') =>
|
const row = (value = 'AAA.ru', code = isin, href = '/ratings/issues/123/') =>
|
||||||
@@ -65,6 +66,18 @@ describe('public NCR issue ratings', () => {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
it.each(['AA+.ru', 'B-.ru', 'BBB+.ru', 'CCC-.ru', 'CC.ru', 'D.ru'])(
|
||||||
|
'accepts the public rating grammar: %s', async (value) => {
|
||||||
|
jest.spyOn(global, 'fetch').mockResolvedValue(response(table(row(value))));
|
||||||
|
expect(await new NcrRatingsClient().rating(isin)).toMatchObject({ value });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
it.each(['AAA+.ru', 'CC-.ru', 'BBBB.ru', 'BBB++.ru'])(
|
||||||
|
'rejects invalid rating grades: %s', async (value) => {
|
||||||
|
jest.spyOn(global, 'fetch').mockResolvedValue(response(table(row(value))));
|
||||||
|
await expect(new NcrRatingsClient().rating(isin)).rejects.toBeInstanceOf(ServiceUnavailableException);
|
||||||
|
},
|
||||||
|
);
|
||||||
it('bounds outage retries then recovers without retaining a false missing rating', async () => {
|
it('bounds outage retries then recovers without retaining a false missing rating', async () => {
|
||||||
const fetchMock = jest
|
const fetchMock = jest
|
||||||
.spyOn(global, 'fetch')
|
.spyOn(global, 'fetch')
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
|||||||
import { load } from 'cheerio';
|
import { load } from 'cheerio';
|
||||||
import { LRUCache } from 'lru-cache';
|
import { LRUCache } from 'lru-cache';
|
||||||
|
|
||||||
|
import { ISO_DATE_LENGTH, ISO_DATE_START } from '../../common/time';
|
||||||
|
|
||||||
|
const EXPECTED_REGISTRY_TABLES = 1;
|
||||||
|
const RATING_COLUMN = 2;
|
||||||
|
|
||||||
const REGISTRY_CACHE_TTL_MS = 21_600_000;
|
const REGISTRY_CACHE_TTL_MS = 21_600_000;
|
||||||
const REQUEST_TIMEOUT_MS = 10_000;
|
const REQUEST_TIMEOUT_MS = 10_000;
|
||||||
const COLUMN_COUNT = 6;
|
const COLUMN_COUNT = 6;
|
||||||
@@ -11,11 +16,11 @@ const DATE_COLUMN = 5;
|
|||||||
const registryUrl = 'https://ratings.ru/ratings/issues/';
|
const registryUrl = 'https://ratings.ru/ratings/issues/';
|
||||||
export type NcrRating = {
|
export type NcrRating = {
|
||||||
agency: 'NCR';
|
agency: 'NCR';
|
||||||
value: string | null;
|
|
||||||
status: 'active' | 'withdrawn';
|
|
||||||
date: string;
|
date: string;
|
||||||
sourceUrl: string;
|
|
||||||
observedAt: string;
|
observedAt: string;
|
||||||
|
sourceUrl: string;
|
||||||
|
status: 'active' | 'withdrawn';
|
||||||
|
value: null | string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -33,8 +38,9 @@ export class NcrRatingsClient {
|
|||||||
if (!pending) {
|
if (!pending) {
|
||||||
pending = this.registry().catch(() => {
|
pending = this.registry().catch(() => {
|
||||||
// Bound outage traffic too; never present a failed download as no rating.
|
// Bound outage traffic too; never present a failed download as no rating.
|
||||||
if (this.cache.get('registry') === pending)
|
if (this.cache.get('registry') === pending) {
|
||||||
this.cache.set('registry', pending, { ttl: 60_000 });
|
this.cache.set('registry', pending, { ttl: 60_000 });
|
||||||
|
}
|
||||||
throw new ServiceUnavailableException({ code: 'NCR_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'NCR_UNAVAILABLE' });
|
||||||
});
|
});
|
||||||
this.cache.set('registry', pending);
|
this.cache.set('registry', pending);
|
||||||
@@ -54,13 +60,16 @@ export class NcrRatingsClient {
|
|||||||
.map((_, cell) => $(cell).text().trim())
|
.map((_, cell) => $(cell).text().trim())
|
||||||
.get();
|
.get();
|
||||||
if (
|
if (
|
||||||
table.length !== 1 ||
|
table.length !== EXPECTED_REGISTRY_TABLES ||
|
||||||
headings.length !== COLUMN_COUNT ||
|
headings.length !== COLUMN_COUNT ||
|
||||||
headings[2] !== 'Рейтинг' ||
|
headings[2] !== 'Рейтинг' ||
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Column indexes are local numeric constants.
|
||||||
headings[ISIN_COLUMN] !== 'ISIN' ||
|
headings[ISIN_COLUMN] !== 'ISIN' ||
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Column indexes are local numeric constants.
|
||||||
headings[DATE_COLUMN] !== 'Дата'
|
headings[DATE_COLUMN] !== 'Дата'
|
||||||
)
|
) {
|
||||||
throw new Error('NCR registry changed');
|
throw new Error('NCR registry changed');
|
||||||
|
}
|
||||||
const observedAt = new Date().toISOString();
|
const observedAt = new Date().toISOString();
|
||||||
const result = new Map<string, NcrRating>();
|
const result = new Map<string, NcrRating>();
|
||||||
table.find('tbody tr').each((_, row) => {
|
table.find('tbody tr').each((_, row) => {
|
||||||
@@ -69,27 +78,30 @@ export class NcrRatingsClient {
|
|||||||
const isin = cells.eq(ISIN_COLUMN).text().trim().toUpperCase();
|
const isin = cells.eq(ISIN_COLUMN).text().trim().toUpperCase();
|
||||||
// Unassigned issues cannot safely be matched to a held instrument.
|
// Unassigned issues cannot safely be matched to a held instrument.
|
||||||
if (!/^[A-Z]{2}[A-Z0-9]{9}\d$/.test(isin)) return;
|
if (!/^[A-Z]{2}[A-Z0-9]{9}\d$/.test(isin)) return;
|
||||||
const raw = cells.eq(2).text().replace(/\s+/g, ' ').trim();
|
const raw = cells.eq(RATING_COLUMN).text().replace(/\s+/g, ' ').trim();
|
||||||
const withdrawn = raw.toLowerCase() === 'рейтинг отозван';
|
const withdrawn = raw.toLowerCase() === 'рейтинг отозван';
|
||||||
if (
|
if (
|
||||||
!withdrawn &&
|
!withdrawn &&
|
||||||
!/^(AAA|AA[+-]?|A[+-]?|BBB[+-]?|BB[+-]?|B[+-]?|CCC[+-]?|CC|C|D)\.ru$/.test(
|
!/^(?:AAA|A{1,2}[+-]?|B{1,3}[+-]?|CCC[+-]?|C{1,2}|D)\.ru$/.test(
|
||||||
raw,
|
raw,
|
||||||
)
|
)
|
||||||
)
|
) {
|
||||||
throw new Error('NCR rating changed');
|
throw new Error('NCR rating changed');
|
||||||
|
}
|
||||||
const dateParts = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(
|
const dateParts = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(
|
||||||
cells.eq(DATE_COLUMN).text().trim(),
|
cells.eq(DATE_COLUMN).text().trim(),
|
||||||
);
|
);
|
||||||
const href = cells.eq(ISIN_COLUMN).find('a').attr('href');
|
const href = cells.eq(ISIN_COLUMN).find('a').attr('href');
|
||||||
if (!dateParts || !href || !/^\/ratings\/issues\/\d+\/$/.test(href))
|
if (!dateParts || !href || !/^\/ratings\/issues\/\d+\/$/.test(href)) {
|
||||||
throw new Error('NCR identity missing');
|
throw new Error('NCR identity missing');
|
||||||
|
}
|
||||||
const date = `${dateParts[3]}-${dateParts[2]}-${dateParts[1]}`;
|
const date = `${dateParts[3]}-${dateParts[2]}-${dateParts[1]}`;
|
||||||
if (
|
if (
|
||||||
!Number.isFinite(Date.parse(date)) ||
|
!Number.isFinite(Date.parse(date)) ||
|
||||||
new Date(date).toISOString().slice(0, 10) !== date
|
new Date(date).toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH) !== date
|
||||||
)
|
) {
|
||||||
throw new Error('NCR date invalid');
|
throw new Error('NCR date invalid');
|
||||||
|
}
|
||||||
const rating: NcrRating = {
|
const rating: NcrRating = {
|
||||||
agency: 'NCR',
|
agency: 'NCR',
|
||||||
value: withdrawn ? null : raw,
|
value: withdrawn ? null : raw,
|
||||||
@@ -103,8 +115,9 @@ export class NcrRatingsClient {
|
|||||||
previous &&
|
previous &&
|
||||||
previous.date === date &&
|
previous.date === date &&
|
||||||
(previous.value !== rating.value || previous.status !== rating.status)
|
(previous.value !== rating.value || previous.status !== rating.status)
|
||||||
)
|
) {
|
||||||
throw new Error('NCR rating ambiguous');
|
throw new Error('NCR rating ambiguous');
|
||||||
|
}
|
||||||
if (!previous || previous.date < date) result.set(isin, rating);
|
if (!previous || previous.date < date) result.set(isin, rating);
|
||||||
});
|
});
|
||||||
if (!result.size) throw new Error('NCR registry empty');
|
if (!result.size) throw new Error('NCR registry empty');
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { NcrRatingsClient } from './ncr-ratings.client';
|
import { NcrRatingsClient } from './ncr-ratings.client';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -21,3 +21,18 @@ describe('decimal', () => {
|
|||||||
).toBe('1');
|
).toBe('1');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('decimal formatting', () => {
|
||||||
|
it.each([
|
||||||
|
[120000n, 4, '12'],
|
||||||
|
[-120030n, 4, '-12.003'],
|
||||||
|
[1n, 4, '0.0001'],
|
||||||
|
[0n, 4, '0'],
|
||||||
|
])('preserves value %s at scale %s while trimming only trailing zeros', (value, scale, expected) => {
|
||||||
|
expect(formatDecimal({ value, scale })).toBe(expected);
|
||||||
|
});
|
||||||
|
it('preserves a long fraction with a trailing zero run', () => {
|
||||||
|
const significant = '1'.repeat(10_000);
|
||||||
|
expect(formatDecimal({ value: BigInt(significant + '0'.repeat(10_000)), scale: 20_000 })).toBe('0.' + significant);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { Decimal } from '../../common/decimal';
|
import { Decimal } from '../../common/decimal';
|
||||||
|
|
||||||
|
const MISSING_PROTO_COMPONENT = 0;
|
||||||
|
|
||||||
const NANO = 1_000_000_000n;
|
const NANO = 1_000_000_000n;
|
||||||
|
|
||||||
export type ProtoDecimal = { units?: string | number; nano?: string | number };
|
export type ProtoDecimal = { nano?: number | string; units?: number | string };
|
||||||
|
|
||||||
export function decimal(value: ProtoDecimal): Decimal {
|
export function decimal(value: ProtoDecimal): Decimal {
|
||||||
return {
|
return {
|
||||||
value: BigInt(value.units ?? 0) * NANO + BigInt(value.nano ?? 0),
|
value: BigInt(value.units ?? MISSING_PROTO_COMPONENT) * NANO + BigInt(value.nano ?? MISSING_PROTO_COMPONENT),
|
||||||
scale: 9,
|
scale: 9,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,335 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
|
||||||
|
import type {
|
||||||
|
TbankInstrumentLookup as MetadataLookupRow,
|
||||||
|
TbankInstrument as MetadataRow,
|
||||||
|
Prisma,
|
||||||
|
} from '../../../generated/prisma/client';
|
||||||
|
import type { TbankSyncAttempt } from './tbank-access.service';
|
||||||
|
import type { TbankInstrument } from './tbank.client';
|
||||||
|
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { tbankSourceTtlMs } from './tbank-source.policy';
|
||||||
|
|
||||||
|
const FIRST_BATCH_OFFSET = 0;
|
||||||
|
const UNCHANGED_REVISION_INCREMENT = 0;
|
||||||
|
const REVISION_INCREMENT = 1;
|
||||||
|
const MISSING_DATA_REVISION = 0;
|
||||||
|
|
||||||
|
export type MetadataIdentity = {
|
||||||
|
figi?: null | string;
|
||||||
|
instrumentUid?: null | string;
|
||||||
|
};
|
||||||
|
export type MetadataLookup = {
|
||||||
|
data: null | TbankInstrument;
|
||||||
|
id: string;
|
||||||
|
type: 'figi' | 'uid';
|
||||||
|
};
|
||||||
|
const provider = 'tbank';
|
||||||
|
// Keep IN lists below the SQLite/Prisma parameter limit, including fixed predicates.
|
||||||
|
const metadataReadBatchSize = 400;
|
||||||
|
export function metadataKey(identity: MetadataIdentity) {
|
||||||
|
return JSON.stringify([
|
||||||
|
identity.instrumentUid?.trim() || null,
|
||||||
|
identity.figi?.trim() || null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class InstrumentMetadataRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async readMany(identities: MetadataIdentity[]) {
|
||||||
|
const identifiers = identities.flatMap((identity) => [
|
||||||
|
...(identity.instrumentUid?.trim() ?
|
||||||
|
[{ identifierType: 'uid', identifier: identity.instrumentUid.trim() }] :
|
||||||
|
[]),
|
||||||
|
...(identity.figi?.trim() ?
|
||||||
|
[{ identifierType: 'figi', identifier: identity.figi.trim() }] :
|
||||||
|
[]),
|
||||||
|
]);
|
||||||
|
if (!identifiers.length) {
|
||||||
|
return new Map<string, ReturnType<typeof selectMetadata>>();
|
||||||
|
}
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
const lookups: MetadataLookupRow[] = [];
|
||||||
|
for (const identifierType of ['uid', 'figi']) {
|
||||||
|
const values = [
|
||||||
|
...new Set(
|
||||||
|
identifiers
|
||||||
|
.filter((entry) => entry.identifierType === identifierType)
|
||||||
|
.map((entry) => entry.identifier),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (
|
||||||
|
let offset = FIRST_BATCH_OFFSET;
|
||||||
|
offset < values.length;
|
||||||
|
offset += metadataReadBatchSize
|
||||||
|
) {
|
||||||
|
lookups.push(
|
||||||
|
...(await tx.tbankInstrumentLookup.findMany({
|
||||||
|
where: {
|
||||||
|
provider,
|
||||||
|
identifierType,
|
||||||
|
identifier: {
|
||||||
|
in: values.slice(offset, offset + metadataReadBatchSize),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const uids = [
|
||||||
|
...new Set(lookups.flatMap((row) => row.matchedUids as string[])),
|
||||||
|
];
|
||||||
|
const instruments: MetadataRow[] = [];
|
||||||
|
for (
|
||||||
|
let offset = FIRST_BATCH_OFFSET;
|
||||||
|
offset < uids.length;
|
||||||
|
offset += metadataReadBatchSize
|
||||||
|
) {
|
||||||
|
instruments.push(
|
||||||
|
...(await tx.tbankInstrument.findMany({
|
||||||
|
where: {
|
||||||
|
provider,
|
||||||
|
uid: { in: uids.slice(offset, offset + metadataReadBatchSize) },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const byIdentifier = new Map(
|
||||||
|
lookups.map((row) => [`${row.identifierType}:${row.identifier}`, row]),
|
||||||
|
);
|
||||||
|
const byUid = new Map(instruments.map((row) => [row.uid, row]));
|
||||||
|
return new Map(
|
||||||
|
identities.map((identity) => [
|
||||||
|
metadataKey(identity),
|
||||||
|
selectMetadata(identity, byIdentifier, byUid),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async reserve(
|
||||||
|
attemptOwner: { revision: string; userId: string },
|
||||||
|
identity: MetadataIdentity,
|
||||||
|
runId: string,
|
||||||
|
active: ReadonlySet<string>,
|
||||||
|
) {
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
const valid = await tx.tbankConnection.updateMany({
|
||||||
|
where: { ...attemptOwner, invalidToken: false },
|
||||||
|
data: { membershipRevision: { increment: 0 } },
|
||||||
|
});
|
||||||
|
if (!valid.count) return null;
|
||||||
|
const scope = {
|
||||||
|
...attemptOwner,
|
||||||
|
scopeKey: `metadata:${metadataKey(identity)}`,
|
||||||
|
};
|
||||||
|
const previous = await tx.tbankSyncWork.findUnique({
|
||||||
|
where: { userId_revision_scopeKey: scope },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
previous?.state === 'running' &&
|
||||||
|
previous.processRunId === runId &&
|
||||||
|
active.has(previous.attemptId)
|
||||||
|
) {
|
||||||
|
return { work: previous, launch: false };
|
||||||
|
}
|
||||||
|
const data = {
|
||||||
|
attemptId: randomUUID(),
|
||||||
|
processRunId: runId,
|
||||||
|
state: 'running',
|
||||||
|
priority: 1,
|
||||||
|
intent: { source: 'metadata', ...identity },
|
||||||
|
progress: {},
|
||||||
|
errorCode: null,
|
||||||
|
};
|
||||||
|
const work = await tx.tbankSyncWork.upsert({
|
||||||
|
where: { userId_revision_scopeKey: scope },
|
||||||
|
create: { ...scope, ...data, id: randomUUID() },
|
||||||
|
update: data,
|
||||||
|
});
|
||||||
|
return { work, launch: true };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
work(userId: string, revision: string, identity: MetadataIdentity) {
|
||||||
|
return this.prisma.tbankSyncWork.findUnique({
|
||||||
|
where: {
|
||||||
|
userId_revision_scopeKey: {
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
scopeKey: `metadata:${metadataKey(identity)}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
select: { id: true, state: true, errorCode: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
publish(attempt: TbankSyncAttempt, results: MetadataLookup[], now: Date) {
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
const claimed = await tx.tbankSyncWork.updateMany({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
connection: { invalidToken: false },
|
||||||
|
},
|
||||||
|
data: { state: 'complete', progress: {} },
|
||||||
|
});
|
||||||
|
if (!claimed.count) return false;
|
||||||
|
const aliases = new Map(
|
||||||
|
results.map((result) => [`${result.type}:${result.id}`, result]),
|
||||||
|
);
|
||||||
|
for (const result of results) {
|
||||||
|
if (!result.data) continue;
|
||||||
|
const uid =
|
||||||
|
result.data.uid?.trim() || (result.type === 'uid' ? result.id : null);
|
||||||
|
const figi =
|
||||||
|
result.data.figi?.trim() ||
|
||||||
|
(result.type === 'figi' ? result.id : null);
|
||||||
|
for (const [type, id] of [
|
||||||
|
['uid', uid],
|
||||||
|
['figi', figi],
|
||||||
|
] as const) {
|
||||||
|
if (id && uid && !aliases.has(`${type}:${id}`)) {
|
||||||
|
aliases.set(`${type}:${id}`, {
|
||||||
|
type,
|
||||||
|
id,
|
||||||
|
data: { ...result.data, uid },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const result of aliases.values()) {
|
||||||
|
const instrument = result.data;
|
||||||
|
const uid =
|
||||||
|
instrument?.uid?.trim() || (result.type === 'uid' ? result.id : null);
|
||||||
|
// FIGI is an alias, never a fabricated provider UID.
|
||||||
|
if (instrument && !uid) {
|
||||||
|
throw new Error('Metadata response has no instrument UID');
|
||||||
|
}
|
||||||
|
if (instrument && uid) {
|
||||||
|
const key = { provider, uid };
|
||||||
|
const previous = await tx.tbankInstrument.findUnique({
|
||||||
|
where: { provider_uid: key },
|
||||||
|
});
|
||||||
|
const payload = JSON.parse(
|
||||||
|
JSON.stringify(instrument),
|
||||||
|
) as Prisma.InputJsonObject;
|
||||||
|
const data = {
|
||||||
|
metadata: payload,
|
||||||
|
figi:
|
||||||
|
instrument.figi ?? (result.type === 'figi' ? result.id : null),
|
||||||
|
ticker: instrument.ticker ?? null,
|
||||||
|
instrumentType: instrument.instrumentType ?? '',
|
||||||
|
fetchedAt: now,
|
||||||
|
};
|
||||||
|
await tx.tbankInstrument.upsert({
|
||||||
|
where: { provider_uid: key },
|
||||||
|
create: { ...key, ...data },
|
||||||
|
update: {
|
||||||
|
...data,
|
||||||
|
dataRevision: {
|
||||||
|
increment: isDeepStrictEqual(previous?.metadata, payload) ?
|
||||||
|
UNCHANGED_REVISION_INCREMENT :
|
||||||
|
REVISION_INCREMENT,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const key = {
|
||||||
|
provider,
|
||||||
|
identifierType: result.type,
|
||||||
|
identifier: result.id,
|
||||||
|
};
|
||||||
|
const matchedUids = instrument && uid ? [uid] : [];
|
||||||
|
const previous = await tx.tbankInstrumentLookup.findUnique({
|
||||||
|
where: { provider_identifierType_identifier: key },
|
||||||
|
});
|
||||||
|
await tx.tbankInstrumentLookup.upsert({
|
||||||
|
where: { provider_identifierType_identifier: key },
|
||||||
|
create: { ...key, matchedUids, fetchedAt: now },
|
||||||
|
update: {
|
||||||
|
matchedUids,
|
||||||
|
fetchedAt: now,
|
||||||
|
dataRevision: {
|
||||||
|
increment: isDeepStrictEqual(previous?.matchedUids, matchedUids) ?
|
||||||
|
UNCHANGED_REVISION_INCREMENT :
|
||||||
|
REVISION_INCREMENT,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async finishObserver(attempt: TbankSyncAttempt, success: boolean) {
|
||||||
|
await this.prisma.tbankSyncWork.updateMany({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
...(success ? { connection: { invalidToken: false } } : {}),
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
state: success ? 'complete' : 'failed',
|
||||||
|
errorCode: success ? null : 'TBANK_UNAVAILABLE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (success) {
|
||||||
|
await this.prisma.tbankSyncWork.updateMany({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
connection: { invalidToken: true },
|
||||||
|
},
|
||||||
|
data: { state: 'failed', errorCode: 'INVALID_TBANK_TOKEN' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectMetadata(
|
||||||
|
identity: MetadataIdentity,
|
||||||
|
lookups: ReadonlyMap<string, MetadataLookupRow>,
|
||||||
|
instruments: ReadonlyMap<string, MetadataRow>,
|
||||||
|
) {
|
||||||
|
const resolve = (type: string, id: null | string | undefined) => {
|
||||||
|
const lookup = lookups.get(`${type}:${id?.trim()}`);
|
||||||
|
const uid = (lookup?.matchedUids as string[] | undefined)?.[0];
|
||||||
|
const instrument = uid ? instruments.get(uid) : undefined;
|
||||||
|
const data = instrument ? (instrument.metadata as TbankInstrument) : null;
|
||||||
|
return { lookup, instrument, data };
|
||||||
|
};
|
||||||
|
const instrumentUid = identity.instrumentUid?.trim();
|
||||||
|
const instrumentFigi = identity.figi?.trim();
|
||||||
|
const uid = resolve('uid', instrumentUid);
|
||||||
|
const figi = resolve('figi', instrumentFigi);
|
||||||
|
const usefulUid = Boolean(uid.data?.name?.trim() || uid.data?.ticker?.trim());
|
||||||
|
const used =
|
||||||
|
usefulUid || !instrumentFigi ? [uid] : instrumentUid ? [uid, figi] : [figi];
|
||||||
|
const complete = used.every((row) => Boolean(row.lookup));
|
||||||
|
const fetchedAt =
|
||||||
|
used
|
||||||
|
.flatMap((row) => (row.lookup ? [row.lookup.fetchedAt] : []))
|
||||||
|
.sort((a, b) => a.valueOf() - b.valueOf())[0] ?? null;
|
||||||
|
return {
|
||||||
|
data: usefulUid ? uid.data : (figi.data ?? uid.data),
|
||||||
|
complete,
|
||||||
|
fresh:
|
||||||
|
complete &&
|
||||||
|
// eslint-disable-next-line sonarjs/different-types-comparison -- The conditional aggregation is nullable at runtime; keep the freshness guard.
|
||||||
|
fetchedAt !== null &&
|
||||||
|
Date.now() - fetchedAt.valueOf() < tbankSourceTtlMs.metadata,
|
||||||
|
fetchedAt,
|
||||||
|
dataRevision: used
|
||||||
|
.map(
|
||||||
|
(row) =>
|
||||||
|
`${row.lookup?.dataRevision ?? MISSING_DATA_REVISION}:${row.instrument?.dataRevision ?? MISSING_DATA_REVISION}`,
|
||||||
|
)
|
||||||
|
.join('/'),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,294 +0,0 @@
|
|||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
|
||||||
import type { LRUCache } from 'lru-cache';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { InstrumentMetadataService } from './instrument-metadata.service';
|
|
||||||
import type { TbankInstrument } from './tbank.client';
|
|
||||||
|
|
||||||
describe('InstrumentMetadataService', () => {
|
|
||||||
const tbank = {
|
|
||||||
getInstrumentByFigi: jest.fn(),
|
|
||||||
getInstrumentByUid: jest.fn(),
|
|
||||||
};
|
|
||||||
const logger = { event: jest.fn() };
|
|
||||||
let service: InstrumentMetadataService;
|
|
||||||
|
|
||||||
function rememberExpired(key: string, value: TbankInstrument): void {
|
|
||||||
const cache = (
|
|
||||||
service as unknown as { metadata: LRUCache<string, TbankInstrument> }
|
|
||||||
).metadata;
|
|
||||||
cache.set(key, value, { ttl: 1, start: performance.now() - 1000 });
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.clearAllMocks();
|
|
||||||
tbank.getInstrumentByFigi.mockReset();
|
|
||||||
tbank.getInstrumentByUid.mockReset();
|
|
||||||
service = new InstrumentMetadataService(tbank as never, logger as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('prefers the instrument UID when metadata is available', async () => {
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue({
|
|
||||||
name: 'Инструмент',
|
|
||||||
brand: { logoName: 'instrument.png' },
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-1', 'figi-1'),
|
|
||||||
).resolves.toMatchObject({
|
|
||||||
brand: { logoName: 'instrument.png' },
|
|
||||||
});
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to FIGI when the UID has no matching instrument', async () => {
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue(null);
|
|
||||||
tbank.getInstrumentByFigi.mockResolvedValue({
|
|
||||||
ticker: 'SBER',
|
|
||||||
brand: { logoName: 'sber.png' },
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-1', 'figi-1'),
|
|
||||||
).resolves.toMatchObject({
|
|
||||||
ticker: 'SBER',
|
|
||||||
});
|
|
||||||
expect(tbank.getInstrumentByFigi).toHaveBeenCalledWith('token', 'figi-1');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns a nullable fallback when instrument metadata is unavailable', async () => {
|
|
||||||
tbank.getInstrumentByUid.mockRejectedValue(new Error('unavailable'));
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('caches negative lookups and avoids repeated upstream requests', async () => {
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue(null);
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toBeNull();
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toBeNull();
|
|
||||||
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('tries FIGI when UID metadata has no usable name or ticker', async () => {
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue({ name: ' ', ticker: '' });
|
|
||||||
tbank.getInstrumentByFigi.mockResolvedValue({ name: 'Облигация' });
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-1', 'figi-1'),
|
|
||||||
).resolves.toMatchObject({ name: 'Облигация' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retains expired successful metadata through temporary failures and refreshes it later', async () => {
|
|
||||||
const known = {
|
|
||||||
name: 'Облигация',
|
|
||||||
ticker: 'BOND',
|
|
||||||
brand: { logoName: 'bond.png' },
|
|
||||||
};
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValueOnce(known);
|
|
||||||
await service.resolve('token', 'uid-1', null);
|
|
||||||
rememberExpired('uid:uid-1', known);
|
|
||||||
tbank.getInstrumentByUid.mockRejectedValue(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
);
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toEqual(
|
|
||||||
known,
|
|
||||||
);
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toEqual(
|
|
||||||
known,
|
|
||||||
);
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue({
|
|
||||||
...known,
|
|
||||||
name: 'Новое название',
|
|
||||||
});
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-1', null),
|
|
||||||
).resolves.toMatchObject({ name: 'Новое название' });
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(4);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not mask an invalid token as missing metadata or retry by FIGI', async () => {
|
|
||||||
const error = new Error('INVALID_TBANK_TOKEN');
|
|
||||||
tbank.getInstrumentByUid.mockRejectedValue(error);
|
|
||||||
await expect(service.resolve('token', 'uid-1', 'figi-1')).rejects.toBe(
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps known metadata through an incomplete refresh without renewing its freshness', async () => {
|
|
||||||
const known = { name: 'Облигация', ticker: 'BOND' };
|
|
||||||
rememberExpired('uid:uid-1', known);
|
|
||||||
tbank.getInstrumentByUid
|
|
||||||
.mockResolvedValueOnce({ name: ' ', ticker: '', isin: 'RU0000000001' })
|
|
||||||
.mockRejectedValueOnce(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', 'figi-1')).resolves.toEqual(
|
|
||||||
known,
|
|
||||||
);
|
|
||||||
await expect(service.resolve('token', 'uid-1', 'figi-1')).resolves.toEqual(
|
|
||||||
known,
|
|
||||||
);
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(2);
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps a known FIGI name after partial UID metadata and does not cache the partial response', async () => {
|
|
||||||
const known = { name: 'Облигация', ticker: 'BOND' };
|
|
||||||
rememberExpired('figi:figi-1', known);
|
|
||||||
tbank.getInstrumentByUid
|
|
||||||
.mockResolvedValueOnce({ isin: 'RU0000000001' })
|
|
||||||
.mockResolvedValueOnce({ name: 'Новое название' });
|
|
||||||
tbank.getInstrumentByFigi.mockRejectedValue(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', 'figi-1')).resolves.toEqual(
|
|
||||||
known,
|
|
||||||
);
|
|
||||||
await expect(service.resolve('token', 'uid-1', 'figi-1')).resolves.toEqual({
|
|
||||||
name: 'Новое название',
|
|
||||||
});
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(2);
|
|
||||||
expect(tbank.getInstrumentByFigi).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns cold partial fields without caching them', async () => {
|
|
||||||
const partial = { isin: 'RU0000000001' };
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue(partial);
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toEqual(
|
|
||||||
partial,
|
|
||||||
);
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toEqual(
|
|
||||||
partial,
|
|
||||||
);
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('replaces an expired name with authoritative confirmed absence', async () => {
|
|
||||||
rememberExpired('uid:uid-1', { name: 'Старое название' });
|
|
||||||
tbank.getInstrumentByUid.mockResolvedValue(null);
|
|
||||||
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toBeNull();
|
|
||||||
await expect(service.resolve('token', 'uid-1', null)).resolves.toBeNull();
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('isolates in-flight credentials while sharing successful public metadata', async () => {
|
|
||||||
const error = new Error('INVALID_TBANK_TOKEN');
|
|
||||||
const known = { name: 'Облигация' };
|
|
||||||
let rejectInvalid: ((reason: Error) => void) | undefined;
|
|
||||||
tbank.getInstrumentByUid.mockImplementation((token: string) =>
|
|
||||||
token === 'invalid-token'
|
|
||||||
? new Promise((_resolve, reject) => {
|
|
||||||
rejectInvalid = reject;
|
|
||||||
})
|
|
||||||
: Promise.resolve(known),
|
|
||||||
);
|
|
||||||
|
|
||||||
const invalid = expect(
|
|
||||||
service.resolve('invalid-token', 'uid-1', null),
|
|
||||||
).rejects.toBe(error);
|
|
||||||
const valid = service.resolve('valid-token', 'uid-1', null);
|
|
||||||
assert.ok(rejectInvalid);
|
|
||||||
rejectInvalid(error);
|
|
||||||
|
|
||||||
await invalid;
|
|
||||||
await expect(valid).resolves.toEqual(known);
|
|
||||||
await expect(
|
|
||||||
service.resolve('another-token', 'uid-1', null),
|
|
||||||
).resolves.toEqual(known);
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns cached or nullable metadata without starting requests after abort', async () => {
|
|
||||||
const known = { name: 'Облигация' };
|
|
||||||
rememberExpired('figi:figi-1', known);
|
|
||||||
const controller = new AbortController();
|
|
||||||
controller.abort();
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-1', 'figi-1', controller.signal),
|
|
||||||
).resolves.toEqual(known);
|
|
||||||
await expect(
|
|
||||||
service.resolve('token', 'uid-2', 'figi-2', controller.signal),
|
|
||||||
).resolves.toBeNull();
|
|
||||||
expect(tbank.getInstrumentByUid).not.toHaveBeenCalled();
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns expired metadata promptly when the waiting caller aborts', async () => {
|
|
||||||
const known = { name: 'Облигация' };
|
|
||||||
rememberExpired('uid:uid-1', known);
|
|
||||||
tbank.getInstrumentByUid.mockReturnValue(new Promise(() => {}));
|
|
||||||
const controller = new AbortController();
|
|
||||||
const result = service.resolve(
|
|
||||||
'token',
|
|
||||||
'uid-1',
|
|
||||||
'figi-1',
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
|
|
||||||
controller.abort();
|
|
||||||
|
|
||||||
await expect(result).resolves.toEqual(known);
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps a shared fetch alive after one caller aborts and caches its result', async () => {
|
|
||||||
const known = { name: 'Облигация' };
|
|
||||||
let finish: ((value: TbankInstrument) => void) | undefined;
|
|
||||||
tbank.getInstrumentByUid.mockReturnValue(
|
|
||||||
new Promise((resolve) => {
|
|
||||||
finish = resolve;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const controller = new AbortController();
|
|
||||||
const aborted = service.resolve(
|
|
||||||
'token',
|
|
||||||
'uid-1',
|
|
||||||
'figi-1',
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
controller.abort();
|
|
||||||
await expect(aborted).resolves.toBeNull();
|
|
||||||
|
|
||||||
const waiting = service.resolve('token', 'uid-1', null);
|
|
||||||
assert.ok(finish);
|
|
||||||
finish(known);
|
|
||||||
|
|
||||||
await expect(waiting).resolves.toEqual(known);
|
|
||||||
await expect(
|
|
||||||
service.resolve('another-token', 'uid-1', null),
|
|
||||||
).resolves.toEqual(known);
|
|
||||||
expect(tbank.getInstrumentByUid).toHaveBeenCalledTimes(1);
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not start FIGI lookup after an aborted UID lookup fails later', async () => {
|
|
||||||
let fail: ((reason: Error) => void) | undefined;
|
|
||||||
tbank.getInstrumentByUid.mockReturnValue(
|
|
||||||
new Promise((_resolve, reject) => {
|
|
||||||
fail = reject;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const controller = new AbortController();
|
|
||||||
const result = service.resolve(
|
|
||||||
'token',
|
|
||||||
'uid-1',
|
|
||||||
'figi-1',
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
controller.abort();
|
|
||||||
await expect(result).resolves.toBeNull();
|
|
||||||
|
|
||||||
assert.ok(fail);
|
|
||||||
fail(new Error('INVALID_TBANK_TOKEN'));
|
|
||||||
await Promise.resolve();
|
|
||||||
await Promise.resolve();
|
|
||||||
|
|
||||||
expect(tbank.getInstrumentByFigi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,118 +1,221 @@
|
|||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { LRUCache } from 'lru-cache';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { createHash } from 'node:crypto';
|
|
||||||
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
||||||
|
import {
|
||||||
|
InstrumentMetadataRepository,
|
||||||
|
type MetadataIdentity,
|
||||||
|
metadataKey,
|
||||||
|
type MetadataLookup,
|
||||||
|
} from './instrument-metadata.repository';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
type TbankSyncAttempt,
|
||||||
|
} from './tbank-access.service';
|
||||||
import { TbankClient, type TbankInstrument } from './tbank.client';
|
import { TbankClient, type TbankInstrument } from './tbank.client';
|
||||||
|
export { metadataKey } from './instrument-metadata.repository';
|
||||||
|
export type { MetadataIdentity } from './instrument-metadata.repository';
|
||||||
|
|
||||||
const metadataForMs = 86_400_000;
|
type Producer = {
|
||||||
const maxCachedInstruments = 500;
|
attempt: TbankSyncAttempt;
|
||||||
const missingInstrument = Symbol('missingInstrument');
|
identity: MetadataIdentity;
|
||||||
|
observers: TbankSyncAttempt[];
|
||||||
|
};
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class InstrumentMetadataService {
|
export class InstrumentMetadataService {
|
||||||
private readonly metadata = new LRUCache<
|
private readonly runId = randomUUID();
|
||||||
string,
|
private readonly active = new Set<string>();
|
||||||
TbankInstrument | typeof missingInstrument
|
private readonly producers = new Map<string, Producer>();
|
||||||
>({
|
private readonly queue: Producer[] = [];
|
||||||
max: maxCachedInstruments,
|
private reservations: Promise<unknown> = Promise.resolve();
|
||||||
ttl: metadataForMs,
|
private running = false;
|
||||||
noDeleteOnStaleGet: true,
|
|
||||||
});
|
|
||||||
private readonly pending = new Map<string, Promise<TbankInstrument | null>>();
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly tbank: TbankClient,
|
private readonly tbank: TbankClient,
|
||||||
private readonly logger: StructuredLogger,
|
private readonly logger: StructuredLogger,
|
||||||
|
private readonly repository: InstrumentMetadataRepository,
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async resolve(
|
savedMany(identities: MetadataIdentity[]) {
|
||||||
token: string,
|
return this.repository.readMany(identities);
|
||||||
instrumentUid: string | null | undefined,
|
}
|
||||||
figi: string | null | undefined,
|
|
||||||
signal?: AbortSignal,
|
async read(
|
||||||
): Promise<TbankInstrument | null> {
|
userId: string,
|
||||||
const uid = instrumentUid?.trim();
|
identity: MetadataIdentity,
|
||||||
let byUid: TbankInstrument | null = null;
|
observe = false,
|
||||||
if (uid) {
|
revision?: string,
|
||||||
byUid = await this.lookup(
|
) {
|
||||||
token,
|
const connection = await this.access.local(userId);
|
||||||
`uid:${uid}`,
|
if (revision && connection.revision !== revision) return null;
|
||||||
() => this.tbank.getInstrumentByUid(token, uid),
|
const data = (await this.savedMany([identity])).get(metadataKey(identity));
|
||||||
signal,
|
if (!observe && !data?.fresh) {
|
||||||
|
await this.request(userId, connection.revision, identity);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
work: await this.repository.work(userId, connection.revision, identity),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
identity: MetadataIdentity,
|
||||||
|
force = false,
|
||||||
|
) {
|
||||||
|
identity = {
|
||||||
|
instrumentUid: identity.instrumentUid?.trim() || null,
|
||||||
|
figi: identity.figi?.trim() || null,
|
||||||
|
};
|
||||||
|
if (!identity.instrumentUid && !identity.figi) return null;
|
||||||
|
const normalized = identity;
|
||||||
|
const reserved = this.reservations.then(async () => {
|
||||||
|
const snapshot = (await this.savedMany([normalized])).get(
|
||||||
|
metadataKey(normalized),
|
||||||
);
|
);
|
||||||
if (byUid?.name?.trim() || byUid?.ticker?.trim()) return byUid;
|
if (!force && snapshot?.fresh) return null;
|
||||||
}
|
const result = await this.repository.reserve(
|
||||||
const instrumentFigi = figi?.trim();
|
{ userId, revision },
|
||||||
const byFigi = instrumentFigi
|
normalized,
|
||||||
? await this.lookup(
|
this.runId,
|
||||||
token,
|
this.active,
|
||||||
`figi:${instrumentFigi}`,
|
);
|
||||||
() => this.tbank.getInstrumentByFigi(token, instrumentFigi),
|
if (!result) return null;
|
||||||
signal,
|
const { id, attemptId } = result.work;
|
||||||
)
|
if (!result.launch) return id;
|
||||||
: null;
|
const attempt = { userId, revision, id, attemptId };
|
||||||
return byFigi ?? byUid;
|
this.active.add(attemptId);
|
||||||
}
|
const key = metadataKey(normalized);
|
||||||
|
const producer = this.producers.get(key);
|
||||||
private async lookup(
|
if (producer) producer.observers.push(attempt);
|
||||||
token: string,
|
else {
|
||||||
key: string,
|
const queued = { identity: normalized, attempt, observers: [] };
|
||||||
fetch: () => Promise<TbankInstrument | null>,
|
this.producers.set(key, queued);
|
||||||
signal?: AbortSignal,
|
this.queue.push(queued);
|
||||||
): Promise<TbankInstrument | null> {
|
}
|
||||||
const cached = this.metadata.get(key);
|
if (!this.running) {
|
||||||
if (cached !== undefined)
|
this.running = true;
|
||||||
return cached === missingInstrument ? null : cached;
|
setImmediate(() => {
|
||||||
if (signal?.aborted) return this.lastKnown(key);
|
void this.drain();
|
||||||
const owner = createHash('sha256').update(token).digest('hex');
|
});
|
||||||
const requestKey = `${owner}:${key}`;
|
}
|
||||||
let pending = this.pending.get(requestKey);
|
return id;
|
||||||
if (!pending) {
|
|
||||||
pending = this.fetch(key, fetch, this.lastKnown(key)).finally(() => {
|
|
||||||
this.pending.delete(requestKey);
|
|
||||||
});
|
|
||||||
this.pending.set(requestKey, pending);
|
|
||||||
}
|
|
||||||
if (!signal) return pending;
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const onAbort = () => resolve(this.lastKnown(key));
|
|
||||||
signal.addEventListener('abort', onAbort, { once: true });
|
|
||||||
void pending.then(resolve, reject).finally(() => {
|
|
||||||
signal.removeEventListener('abort', onAbort);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
this.reservations = reserved.catch(() => undefined);
|
||||||
|
return reserved;
|
||||||
}
|
}
|
||||||
|
|
||||||
private lastKnown(key: string): TbankInstrument | null {
|
private async drain() {
|
||||||
const value = this.metadata.peek(key, { allowStale: true });
|
|
||||||
return value === missingInstrument ? null : (value ?? null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async fetch(
|
|
||||||
key: string,
|
|
||||||
request: () => Promise<TbankInstrument | null>,
|
|
||||||
previous: TbankInstrument | null,
|
|
||||||
): Promise<TbankInstrument | null> {
|
|
||||||
try {
|
try {
|
||||||
const value = await request();
|
while (this.queue.length) {
|
||||||
const found = Boolean(value?.name?.trim() || value?.ticker?.trim());
|
const producer = this.queue.shift();
|
||||||
if (value === null || found)
|
if (!producer) break;
|
||||||
this.metadata.set(key, value ?? missingInstrument);
|
const { attempt, identity } = producer;
|
||||||
this.logger.event('debug', 'instrument-metadata.resolved', {
|
let success = false;
|
||||||
found,
|
try {
|
||||||
|
const token = await this.access.tokenForAttempt(attempt);
|
||||||
|
if (token) {
|
||||||
|
const results: MetadataLookup[] = [];
|
||||||
|
let useful = false;
|
||||||
|
let uidFailed = false;
|
||||||
|
if (identity.instrumentUid) {
|
||||||
|
let data: null | TbankInstrument | undefined;
|
||||||
|
try {
|
||||||
|
data = await this.tbank.getInstrumentByUid(
|
||||||
|
token,
|
||||||
|
identity.instrumentUid,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
!identity.figi ||
|
||||||
|
(error instanceof Error &&
|
||||||
|
error.message === 'INVALID_TBANK_TOKEN')
|
||||||
|
) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
uidFailed = true;
|
||||||
|
}
|
||||||
|
if (data?.uid && data.uid !== identity.instrumentUid) {
|
||||||
|
throw new Error('Metadata UID mismatch');
|
||||||
|
}
|
||||||
|
if (data !== undefined) {
|
||||||
|
results.push({ type: 'uid', id: identity.instrumentUid, data });
|
||||||
|
}
|
||||||
|
useful = Boolean(data?.name?.trim() || data?.ticker?.trim());
|
||||||
|
if (!useful && data && !identity.figi) {
|
||||||
|
throw new Error('Incomplete metadata');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!useful && identity.figi) {
|
||||||
|
const data = await this.tbank.getInstrumentByFigi(
|
||||||
|
token,
|
||||||
|
identity.figi,
|
||||||
|
);
|
||||||
|
if (data?.figi && data.figi !== identity.figi) {
|
||||||
|
throw new Error('Metadata FIGI mismatch');
|
||||||
|
}
|
||||||
|
if (data && !data.name?.trim() && !data.ticker?.trim()) {
|
||||||
|
throw new Error('Incomplete metadata');
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line sonarjs/different-types-comparison -- Defensive validation at an untrusted upstream boundary includes missing payloads.
|
||||||
|
if (data === undefined || (uidFailed && !data)) {
|
||||||
|
throw new Error('Metadata source unavailable');
|
||||||
|
}
|
||||||
|
results.push({ type: 'figi', id: identity.figi, data });
|
||||||
|
// A successful FIGI response identifies its canonical UID too;
|
||||||
|
// a failed UID RPC is never persisted as a negative lookup.
|
||||||
|
if (
|
||||||
|
uidFailed &&
|
||||||
|
data?.uid === identity.instrumentUid &&
|
||||||
|
identity.instrumentUid
|
||||||
|
) {
|
||||||
|
results.push({ type: 'uid', id: identity.instrumentUid, data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!results.length ||
|
||||||
|
(results.some((result) => result.data) &&
|
||||||
|
!results.some(
|
||||||
|
(result) =>
|
||||||
|
result.data?.name?.trim() || result.data?.ticker?.trim(),
|
||||||
|
))
|
||||||
|
) {
|
||||||
|
throw new Error('Incomplete metadata');
|
||||||
|
}
|
||||||
|
success = await this.repository.publish(
|
||||||
|
attempt,
|
||||||
|
results,
|
||||||
|
new Date(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN') {
|
||||||
|
await this.access.rejectMembershipToken(attempt);
|
||||||
|
} else {
|
||||||
|
this.logger.event('warn', 'instrument-metadata.failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Remove the producer before awaiting finalization: a new request cannot
|
||||||
|
// attach to a producer whose observer list has already been drained.
|
||||||
|
this.producers.delete(metadataKey(identity));
|
||||||
|
for (const observer of [attempt, ...producer.observers]) {
|
||||||
|
await this.repository.finishObserver(observer, success);
|
||||||
|
this.active.delete(observer.attemptId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
this.logger.event('error', 'instrument-metadata.persistence-failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
});
|
});
|
||||||
return found || value === null ? value : (previous ?? value);
|
this.active.clear();
|
||||||
} catch (error) {
|
this.producers.clear();
|
||||||
this.logger.event('warn', 'instrument-metadata.failed', {
|
this.queue.length = 0;
|
||||||
code:
|
} finally {
|
||||||
error instanceof Error && 'response' in error
|
this.running = false;
|
||||||
? ((error as { response?: { code?: string } }).response?.code ??
|
|
||||||
'UNKNOWN')
|
|
||||||
: 'UNKNOWN',
|
|
||||||
});
|
|
||||||
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
|
|
||||||
throw error;
|
|
||||||
return error instanceof ServiceUnavailableException ? previous : null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,162 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
NotFoundException,
|
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
|
|
||||||
jest.mock('../../prisma/prisma.service', () => ({
|
|
||||||
PrismaService: class PrismaService {},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import type { TbankAccountContext } from './tbank-access.service';
|
|
||||||
import { TbankAccessService } from './tbank-access.service';
|
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
|
||||||
|
|
||||||
describe('TbankAccessService', () => {
|
|
||||||
const prisma = { tbankConnection: { findUnique: jest.fn() } };
|
|
||||||
const token = {
|
|
||||||
decrypt: jest.fn(),
|
|
||||||
translateInvalidToken: jest.fn((operation: () => Promise<unknown>) =>
|
|
||||||
new TbankTokenService({
|
|
||||||
getOrThrow: () => 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=',
|
|
||||||
} as never).translateInvalidToken(operation),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
const tbank = { getOpenAccounts: jest.fn() };
|
|
||||||
const service = new TbankAccessService(
|
|
||||||
prisma as never,
|
|
||||||
token as never,
|
|
||||||
tbank as never,
|
|
||||||
);
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.clearAllMocks();
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: 'encrypted',
|
|
||||||
});
|
|
||||||
token.decrypt.mockReturnValue('plain-token');
|
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
|
||||||
{
|
|
||||||
id: 'account',
|
|
||||||
type: 'ACCOUNT_TYPE_TINKOFF',
|
|
||||||
name: ' Основной ',
|
|
||||||
openedDate: { seconds: '1723507200' },
|
|
||||||
},
|
|
||||||
{ id: 'debit', type: 'ACCOUNT_TYPE_DEBIT', name: 'Debit' },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lists supported accounts through the saved decrypted token', async () => {
|
|
||||||
await expect(service.listSupportedAccounts('user')).resolves.toEqual([
|
|
||||||
{
|
|
||||||
id: 'account',
|
|
||||||
type: 'BROKERAGE',
|
|
||||||
name: 'Основной',
|
|
||||||
openedOn: '2024-08-13',
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(prisma.tbankConnection.findUnique).toHaveBeenCalledWith({
|
|
||||||
where: { userId: 'user' },
|
|
||||||
});
|
|
||||||
expect(token.decrypt).toHaveBeenCalledWith('encrypted');
|
|
||||||
expect(tbank.getOpenAccounts).toHaveBeenCalledWith('plain-token');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects missing connections before calling T-Bank', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue(null);
|
|
||||||
|
|
||||||
await expect(service.listSupportedAccounts('user')).rejects.toEqual(
|
|
||||||
expect.any(ConflictException),
|
|
||||||
);
|
|
||||||
expect(tbank.getOpenAccounts).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('resolves the persisted connection generation without an upstream account call', async () => {
|
|
||||||
const context = await service.withConnection('user', (value) => value);
|
|
||||||
|
|
||||||
expect(context).toEqual({
|
|
||||||
token: 'plain-token',
|
|
||||||
generation: expect.any(String) as string,
|
|
||||||
});
|
|
||||||
expect(tbank.getOpenAccounts).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('translates invalid tokens and preserves unavailable upstream errors', async () => {
|
|
||||||
tbank.getOpenAccounts.mockRejectedValueOnce(
|
|
||||||
new Error('INVALID_TBANK_TOKEN'),
|
|
||||||
);
|
|
||||||
await expect(service.listSupportedAccounts('user')).rejects.toEqual(
|
|
||||||
expect.any(BadRequestException),
|
|
||||||
);
|
|
||||||
|
|
||||||
const unavailable = new ServiceUnavailableException({
|
|
||||||
code: 'TBANK_UNAVAILABLE',
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockRejectedValueOnce(unavailable);
|
|
||||||
await expect(service.listSupportedAccounts('user')).rejects.toBe(
|
|
||||||
unavailable,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('wraps account-scoped handlers with resolved account access', async () => {
|
|
||||||
const handler = jest.fn((context: TbankAccountContext) =>
|
|
||||||
Promise.resolve({
|
|
||||||
resolvedToken: context.token,
|
|
||||||
generation: context.generation,
|
|
||||||
accountId: context.account.id,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.withAccount('user', 'account', handler),
|
|
||||||
).resolves.toEqual({
|
|
||||||
resolvedToken: 'plain-token',
|
|
||||||
generation: expect.any(String) as string,
|
|
||||||
accountId: 'account',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('derives a stable opaque generation from each persisted encrypted payload', async () => {
|
|
||||||
const generation = () =>
|
|
||||||
service.withAccount('user', 'account', ({ generation: value }) =>
|
|
||||||
Promise.resolve(value),
|
|
||||||
);
|
|
||||||
prisma.tbankConnection.findUnique
|
|
||||||
.mockResolvedValueOnce({ encryptedToken: 'encrypted:first-nonce' })
|
|
||||||
.mockResolvedValueOnce({ encryptedToken: 'encrypted:first-nonce' })
|
|
||||||
.mockResolvedValueOnce({ encryptedToken: 'encrypted:second-nonce' });
|
|
||||||
|
|
||||||
const first = await generation();
|
|
||||||
const sameRecord = await generation();
|
|
||||||
const replaced = await generation();
|
|
||||||
|
|
||||||
expect(sameRecord).toBe(first);
|
|
||||||
expect(replaced).not.toBe(first);
|
|
||||||
expect(first).not.toContain('plain-token');
|
|
||||||
expect(first).not.toContain('encrypted:first-nonce');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects inaccessible accounts before running the handler', async () => {
|
|
||||||
const handler = jest.fn();
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.withAccount('user', 'missing', handler),
|
|
||||||
).rejects.toEqual(expect.any(NotFoundException));
|
|
||||||
expect(handler).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('translates invalid-token handler failures and preserves unrelated handler failures', async () => {
|
|
||||||
await expect(
|
|
||||||
service.withAccount('user', 'account', () =>
|
|
||||||
Promise.reject(new Error('INVALID_TBANK_TOKEN')),
|
|
||||||
),
|
|
||||||
).rejects.toEqual(expect.any(BadRequestException));
|
|
||||||
|
|
||||||
const failure = new Error('source failed');
|
|
||||||
await expect(
|
|
||||||
service.withAccount('user', 'account', () => Promise.reject(failure)),
|
|
||||||
).rejects.toBe(failure);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,25 +1,27 @@
|
|||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
ConflictException,
|
ConflictException,
|
||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { createHash } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
import type { TbankAccount } from './tbank.client';
|
||||||
|
|
||||||
import { PrismaService } from '../../prisma/prisma.service';
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
import {
|
import { supportedTbankAccounts } from './tbank-account.policy';
|
||||||
SupportedTbankAccount,
|
import { tbankSourceNeedsRefresh } from './tbank-source.policy';
|
||||||
accessibleTbankAccount,
|
|
||||||
supportedTbankAccounts,
|
|
||||||
} from './tbank-account.policy';
|
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
import { TbankTokenService } from './tbank-token.service';
|
||||||
import { TbankAccount, TbankClient } from './tbank.client';
|
|
||||||
|
|
||||||
export type TbankConnectionContext = {
|
const EXPECTED_UPDATED_CONNECTIONS = 1;
|
||||||
token: string;
|
const MEMBERSHIP_REVISION_INCREMENT = 1;
|
||||||
generation: string;
|
const UNCHANGED_MEMBERSHIP_REVISION_INCREMENT = 0;
|
||||||
};
|
|
||||||
|
|
||||||
export type TbankAccountContext = TbankConnectionContext & {
|
export type TbankSyncAttempt = {
|
||||||
account: TbankAccount;
|
attemptId: string;
|
||||||
|
id: string;
|
||||||
|
revision: string;
|
||||||
|
userId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -27,81 +29,226 @@ export class TbankAccessService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly tokens: TbankTokenService,
|
private readonly tokens: TbankTokenService,
|
||||||
private readonly tbank: TbankClient,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async listSupportedAccounts(
|
async reserveMembership(
|
||||||
userId: string,
|
userId: string,
|
||||||
): Promise<SupportedTbankAccount[]> {
|
revision: string,
|
||||||
return this.withSupportedAccounts(userId, ({ accounts }) => accounts);
|
processRunId: string,
|
||||||
}
|
active: ReadonlySet<string>,
|
||||||
|
force: boolean,
|
||||||
async withSupportedAccounts<T>(
|
) {
|
||||||
userId: string,
|
return this.prisma.$transaction(async (tx) => {
|
||||||
handler: (context: {
|
const current = await tx.tbankConnection.updateMany({
|
||||||
token: string;
|
where: { userId, revision, invalidToken: false },
|
||||||
generation: string;
|
data: { membershipRevision: { increment: 0 } },
|
||||||
accounts: SupportedTbankAccount[];
|
});
|
||||||
}) => Promise<T> | T,
|
if (!current.count) return null;
|
||||||
): Promise<T> {
|
const connection = await tx.tbankConnection.findUniqueOrThrow({
|
||||||
return this.withConnection(userId, async ({ token, generation }) =>
|
where: { userId },
|
||||||
handler({
|
});
|
||||||
token,
|
if (
|
||||||
generation,
|
!force &&
|
||||||
accounts: supportedTbankAccounts(
|
!tbankSourceNeedsRefresh(
|
||||||
await this.tbank.getOpenAccounts(token),
|
'membership',
|
||||||
),
|
connection.membershipAt,
|
||||||
}),
|
new Date(),
|
||||||
);
|
)
|
||||||
}
|
) {
|
||||||
|
return null;
|
||||||
async withConnection<T>(
|
}
|
||||||
userId: string,
|
const scope = { userId, revision, scopeKey: 'membership' };
|
||||||
handler: (context: TbankConnectionContext) => Promise<T> | T,
|
const previous = await tx.tbankSyncWork.findUnique({
|
||||||
): Promise<T> {
|
where: { userId_revision_scopeKey: scope },
|
||||||
const connection = await this.connection(userId);
|
});
|
||||||
return this.tokens.translateInvalidToken(async () => handler(connection));
|
if (
|
||||||
}
|
previous?.state === 'running' &&
|
||||||
|
previous.processRunId === processRunId &&
|
||||||
async withAccount<T>(
|
active.has(previous.attemptId)
|
||||||
userId: string,
|
) {
|
||||||
accountId: string,
|
return { work: previous, launch: false };
|
||||||
handler: (context: TbankAccountContext) => Promise<T>,
|
}
|
||||||
): Promise<T> {
|
const data = {
|
||||||
return this.withConnection(userId, (connection) =>
|
attemptId: randomUUID(),
|
||||||
this.withAccountForConnection(connection, accountId, handler),
|
processRunId,
|
||||||
);
|
state: 'running',
|
||||||
}
|
intent: { source: 'membership' },
|
||||||
|
progress: {},
|
||||||
async withAccountForConnection<T>(
|
priority: 0,
|
||||||
connection: TbankConnectionContext,
|
errorCode: null,
|
||||||
accountId: string,
|
};
|
||||||
handler: (context: TbankAccountContext) => Promise<T>,
|
const work = await tx.tbankSyncWork.upsert({
|
||||||
): Promise<T> {
|
where: { userId_revision_scopeKey: scope },
|
||||||
const { token, generation } = connection;
|
create: { ...scope, ...data, id: randomUUID() },
|
||||||
return this.tokens.translateInvalidToken(async () => {
|
update: data,
|
||||||
const account = accessibleTbankAccount(
|
});
|
||||||
await this.tbank.getOpenAccounts(token),
|
return { work, launch: true };
|
||||||
accountId,
|
|
||||||
);
|
|
||||||
if (!account) throw new NotFoundException();
|
|
||||||
return handler({ token, generation, account });
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async connection(
|
membershipWork(userId: string, revision: string) {
|
||||||
userId: string,
|
return this.prisma.tbankSyncWork.findUnique({
|
||||||
): Promise<{ token: string; generation: string }> {
|
where: {
|
||||||
|
userId_revision_scopeKey: { userId, revision, scopeKey: 'membership' },
|
||||||
|
},
|
||||||
|
select: { id: true, state: true, errorCode: true, updatedAt: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async failMembership(attempt: TbankSyncAttempt, invalidToken: boolean) {
|
||||||
|
if (invalidToken) return this.rejectMembershipToken(attempt);
|
||||||
|
const result = await this.prisma.tbankSyncWork.updateMany({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
connection: { invalidToken: false },
|
||||||
|
},
|
||||||
|
data: { state: 'failed', errorCode: 'TBANK_UNAVAILABLE' },
|
||||||
|
});
|
||||||
|
return result.count === EXPECTED_UPDATED_CONNECTIONS;
|
||||||
|
}
|
||||||
|
|
||||||
|
async tokenForAttempt(attempt: TbankSyncAttempt): Promise<null | string> {
|
||||||
|
const work = await this.prisma.tbankSyncWork.findFirst({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
connection: { invalidToken: false },
|
||||||
|
},
|
||||||
|
select: { connection: { select: { encryptedToken: true } } },
|
||||||
|
});
|
||||||
|
return work ? this.tokens.decrypt(work.connection.encryptedToken) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async publishMembership(
|
||||||
|
attempt: TbankSyncAttempt,
|
||||||
|
accounts: TbankAccount[],
|
||||||
|
fetchedAt: Date,
|
||||||
|
completeWork = false,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const supported = supportedTbankAccounts(accounts);
|
||||||
|
if (new Set(supported.map(({ id }) => id)).size !== supported.length) {
|
||||||
|
throw new Error('Duplicate T-Bank account identity');
|
||||||
|
}
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
// Acquire the write fence before reading membership. Replacement and
|
||||||
|
// attempt supersession cannot interleave with the publication below.
|
||||||
|
const claimed = await tx.tbankSyncWork.updateMany({
|
||||||
|
where: {
|
||||||
|
...attempt,
|
||||||
|
state: 'running',
|
||||||
|
connection: { invalidToken: false },
|
||||||
|
},
|
||||||
|
data: { updatedAt: new Date() },
|
||||||
|
});
|
||||||
|
if (!claimed.count) return false;
|
||||||
|
const { userId, revision } = attempt;
|
||||||
|
const previous = await tx.tbankAccount.findMany({
|
||||||
|
where: { userId, revision },
|
||||||
|
orderBy: { upstreamOrder: 'asc' },
|
||||||
|
select: { accountId: true, type: true, name: true, openedOn: true },
|
||||||
|
});
|
||||||
|
const next = supported.map(({ id, ...account }) => ({
|
||||||
|
accountId: id,
|
||||||
|
...account,
|
||||||
|
}));
|
||||||
|
const changed =
|
||||||
|
previous.length !== next.length ||
|
||||||
|
previous.some((account, index) => {
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The index comes from the paired account array iteration.
|
||||||
|
const incoming = next[index];
|
||||||
|
return (
|
||||||
|
account.accountId !== incoming.accountId ||
|
||||||
|
account.type !== incoming.type ||
|
||||||
|
account.name !== incoming.name ||
|
||||||
|
account.openedOn !== incoming.openedOn
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await tx.tbankAccount.deleteMany({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
accountId: { notIn: supported.map(({ id }) => id) },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (const [upstreamOrder, account] of next.entries()) {
|
||||||
|
await tx.tbankAccount.upsert({
|
||||||
|
where: {
|
||||||
|
userId_revision_accountId: {
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
accountId: account.accountId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: { userId, revision, ...account, upstreamOrder },
|
||||||
|
update: { ...account, upstreamOrder },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await tx.tbankConnection.update({
|
||||||
|
where: { userId_revision: { userId, revision } },
|
||||||
|
data: {
|
||||||
|
membershipAt: fetchedAt,
|
||||||
|
membershipRevision: { increment: changed ? MEMBERSHIP_REVISION_INCREMENT : UNCHANGED_MEMBERSHIP_REVISION_INCREMENT },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (completeWork) {
|
||||||
|
await tx.tbankSyncWork.update({
|
||||||
|
where: { id: attempt.id },
|
||||||
|
data: { state: 'complete', progress: { accounts: supported.length } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async rejectMembershipToken(attempt: TbankSyncAttempt): Promise<boolean> {
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
const claimed = await tx.tbankSyncWork.updateMany({
|
||||||
|
where: { ...attempt, state: 'running' },
|
||||||
|
data: { state: 'failed', errorCode: 'INVALID_TBANK_TOKEN' },
|
||||||
|
});
|
||||||
|
if (!claimed.count) return false;
|
||||||
|
await tx.tbankConnection.update({
|
||||||
|
where: {
|
||||||
|
userId_revision: {
|
||||||
|
userId: attempt.userId,
|
||||||
|
revision: attempt.revision,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
data: { invalidToken: true },
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// This boundary neither decrypts credentials nor starts discovery/sync.
|
||||||
|
// Missing membership is distinct from a successfully observed empty list.
|
||||||
|
async local(userId: string, accountId?: string) {
|
||||||
const connection = await this.prisma.tbankConnection.findUnique({
|
const connection = await this.prisma.tbankConnection.findUnique({
|
||||||
where: { userId },
|
where: { userId },
|
||||||
|
select: {
|
||||||
|
userId: true,
|
||||||
|
revision: true,
|
||||||
|
invalidToken: true,
|
||||||
|
membershipAt: true,
|
||||||
|
membershipRevision: true,
|
||||||
|
accounts: { orderBy: { upstreamOrder: 'asc' } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (!connection)
|
if (!connection) {
|
||||||
throw new ConflictException({ code: 'TBANK_NOT_CONNECTED' });
|
throw new ConflictException({ code: 'TBANK_NOT_CONNECTED' });
|
||||||
return {
|
}
|
||||||
token: this.tokens.decrypt(connection.encryptedToken),
|
if (connection.invalidToken) {
|
||||||
generation: createHash('sha256')
|
throw new BadRequestException({ code: 'INVALID_TBANK_TOKEN' });
|
||||||
.update(connection.encryptedToken)
|
}
|
||||||
.digest('base64url'),
|
if (
|
||||||
};
|
connection.membershipAt &&
|
||||||
|
accountId &&
|
||||||
|
accountId !== 'all' &&
|
||||||
|
!connection.accounts.some((account) => account.accountId === accountId)
|
||||||
|
) {
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
return connection;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { supportedTbankAccounts } from './tbank-account.policy';
|
||||||
accessibleTbankAccount,
|
|
||||||
supportedTbankAccounts,
|
|
||||||
} from './tbank-account.policy';
|
|
||||||
|
|
||||||
describe('tbank-account-policy', () => {
|
describe('tbank-account-policy', () => {
|
||||||
it('normalizes supported account types and fallback names', () => {
|
it('normalizes supported account types and fallback names', () => {
|
||||||
@@ -45,26 +42,4 @@ describe('tbank-account-policy', () => {
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('matches account-scoped access only for supported account types', () => {
|
|
||||||
expect(
|
|
||||||
accessibleTbankAccount(
|
|
||||||
[
|
|
||||||
{ id: 'account', type: 'ACCOUNT_TYPE_DEBIT', name: 'Debit' },
|
|
||||||
{ id: 'other', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Other' },
|
|
||||||
],
|
|
||||||
'account',
|
|
||||||
),
|
|
||||||
).toBeNull();
|
|
||||||
expect(
|
|
||||||
accessibleTbankAccount(
|
|
||||||
[{ id: 'account', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Brokerage' }],
|
|
||||||
'account',
|
|
||||||
),
|
|
||||||
).toEqual({
|
|
||||||
id: 'account',
|
|
||||||
type: 'ACCOUNT_TYPE_TINKOFF',
|
|
||||||
name: 'Brokerage',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { MILLISECONDS_PER_SECOND } from '../../common/time';
|
import { ISO_DATE_LENGTH, ISO_DATE_START, MILLISECONDS_PER_SECOND } from '../../common/time';
|
||||||
import { TbankAccount } from './tbank.client';
|
import { TbankAccount } from './tbank.client';
|
||||||
|
|
||||||
const accountTypes = {
|
const accountTypes = {
|
||||||
@@ -18,8 +18,8 @@ type AccountType = keyof typeof accountTypes;
|
|||||||
export type SupportedTbankAccount = {
|
export type SupportedTbankAccount = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
openedOn: null | string;
|
||||||
type: (typeof accountTypes)[AccountType]['type'];
|
type: (typeof accountTypes)[AccountType]['type'];
|
||||||
openedOn: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function supportedTbankAccounts(
|
export function supportedTbankAccounts(
|
||||||
@@ -39,20 +39,9 @@ export function supportedTbankAccounts(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function accessibleTbankAccount(
|
function openedOn(seconds: number | string | undefined): null | string {
|
||||||
accounts: TbankAccount[],
|
|
||||||
accountId: string,
|
|
||||||
): TbankAccount | null {
|
|
||||||
return (
|
|
||||||
accounts.find(
|
|
||||||
(account) => account.id === accountId && account.type in accountTypes,
|
|
||||||
) ?? null
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openedOn(seconds: string | number | undefined): string | null {
|
|
||||||
if (seconds === undefined) return null;
|
if (seconds === undefined) return null;
|
||||||
const date = new Date(Number(seconds) * MILLISECONDS_PER_SECOND);
|
const date = new Date(Number(seconds) * MILLISECONDS_PER_SECOND);
|
||||||
if (Number.isNaN(date.valueOf())) return null;
|
if (Number.isNaN(date.valueOf())) return null;
|
||||||
return date.toISOString().slice(0, 10);
|
return date.toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,23 +6,23 @@ import type {
|
|||||||
} from './tbank.client';
|
} from './tbank.client';
|
||||||
|
|
||||||
export type TbankShare = TbankInstrument & {
|
export type TbankShare = TbankInstrument & {
|
||||||
uid?: string;
|
apiTradeAvailableFlag?: boolean;
|
||||||
figi?: string;
|
|
||||||
assetUid?: string;
|
assetUid?: string;
|
||||||
classCode?: string;
|
classCode?: string;
|
||||||
realExchange?: string;
|
|
||||||
apiTradeAvailableFlag?: boolean;
|
|
||||||
currency?: string;
|
currency?: string;
|
||||||
shareType?: string;
|
figi?: string;
|
||||||
instrumentKind?: string;
|
|
||||||
sector?: string;
|
|
||||||
lot?: number;
|
|
||||||
first_1dayCandleDate?: TbankTimestamp;
|
first_1dayCandleDate?: TbankTimestamp;
|
||||||
|
instrumentKind?: string;
|
||||||
|
lot?: number;
|
||||||
|
realExchange?: string;
|
||||||
|
sector?: string;
|
||||||
|
shareType?: string;
|
||||||
|
uid?: string;
|
||||||
};
|
};
|
||||||
export type TbankCandle = {
|
export type TbankCandle = {
|
||||||
time?: TbankTimestamp;
|
|
||||||
close?: TbankDecimal;
|
close?: TbankDecimal;
|
||||||
isComplete?: boolean;
|
isComplete?: boolean;
|
||||||
|
time?: TbankTimestamp;
|
||||||
};
|
};
|
||||||
export type TbankLastPrice = {
|
export type TbankLastPrice = {
|
||||||
instrumentUid?: string;
|
instrumentUid?: string;
|
||||||
@@ -32,38 +32,38 @@ export type TbankLastPrice = {
|
|||||||
export type TbankFundamentals = {
|
export type TbankFundamentals = {
|
||||||
assetUid?: string;
|
assetUid?: string;
|
||||||
currency?: string;
|
currency?: string;
|
||||||
|
ebitdaTtm?: number;
|
||||||
marketCapitalization?: number;
|
marketCapitalization?: number;
|
||||||
|
netDebtToEbitda?: number;
|
||||||
|
netIncomeTtm?: number;
|
||||||
peRatioTtm?: number;
|
peRatioTtm?: number;
|
||||||
priceToBookTtm?: number;
|
priceToBookTtm?: number;
|
||||||
revenueTtm?: number;
|
revenueTtm?: number;
|
||||||
netIncomeTtm?: number;
|
|
||||||
ebitdaTtm?: number;
|
|
||||||
roe?: number;
|
roe?: number;
|
||||||
totalDebtMrq?: number;
|
totalDebtMrq?: number;
|
||||||
netDebtToEbitda?: number;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TbankBond = Omit<TbankShare, 'shareType'> & {
|
export type TbankBond = Omit<TbankShare, 'shareType'> & {
|
||||||
nominal?: TbankMoney;
|
|
||||||
initialNominal?: TbankMoney;
|
|
||||||
aciValue?: TbankMoney;
|
aciValue?: TbankMoney;
|
||||||
maturityDate?: TbankTimestamp;
|
amortizationFlag?: boolean;
|
||||||
|
bondType?: string;
|
||||||
callDate?: TbankTimestamp;
|
callDate?: TbankTimestamp;
|
||||||
couponQuantityPerYear?: number;
|
couponQuantityPerYear?: number;
|
||||||
floatingCouponFlag?: boolean;
|
floatingCouponFlag?: boolean;
|
||||||
|
initialNominal?: TbankMoney;
|
||||||
|
maturityDate?: TbankTimestamp;
|
||||||
|
nominal?: TbankMoney;
|
||||||
perpetualFlag?: boolean;
|
perpetualFlag?: boolean;
|
||||||
amortizationFlag?: boolean;
|
|
||||||
subordinatedFlag?: boolean;
|
|
||||||
bondType?: string;
|
|
||||||
riskLevel?: string;
|
riskLevel?: string;
|
||||||
|
subordinatedFlag?: boolean;
|
||||||
};
|
};
|
||||||
export type TbankCoupon = {
|
export type TbankCoupon = {
|
||||||
couponNumber?: string;
|
|
||||||
couponDate?: TbankTimestamp;
|
couponDate?: TbankTimestamp;
|
||||||
|
couponEndDate?: TbankTimestamp;
|
||||||
|
couponNumber?: string;
|
||||||
|
couponPeriod?: number;
|
||||||
|
couponStartDate?: TbankTimestamp;
|
||||||
|
couponType?: string;
|
||||||
fixDate?: TbankTimestamp;
|
fixDate?: TbankTimestamp;
|
||||||
payOneBond?: TbankMoney;
|
payOneBond?: TbankMoney;
|
||||||
couponType?: string;
|
|
||||||
couponStartDate?: TbankTimestamp;
|
|
||||||
couponEndDate?: TbankTimestamp;
|
|
||||||
couponPeriod?: number;
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
type TbankSyncAttempt,
|
||||||
|
} from './tbank-access.service';
|
||||||
|
import { TbankClient } from './tbank.client';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TbankMembershipService {
|
||||||
|
private readonly processRunId = randomUUID();
|
||||||
|
private readonly active = new Map<string, Promise<void>>();
|
||||||
|
private reservations: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
private readonly logger: StructuredLogger,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
request(userId: string, revision: string, force = false) {
|
||||||
|
const reservation = this.reservations.then(async () => {
|
||||||
|
const requested = await this.access.reserveMembership(
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
this.processRunId,
|
||||||
|
new Set(this.active.keys()),
|
||||||
|
force,
|
||||||
|
);
|
||||||
|
if (!requested) return null;
|
||||||
|
const { id, attemptId } = requested.work;
|
||||||
|
if (requested.launch) {
|
||||||
|
const done = new Promise<void>((resolve) => setImmediate(resolve))
|
||||||
|
.then(() => this.execute({ userId, revision, id, attemptId }))
|
||||||
|
.catch(() =>
|
||||||
|
this.logger.event('error', 'tbank.membership.persistence_failed', {
|
||||||
|
userId,
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.finally(() => this.active.delete(attemptId));
|
||||||
|
this.active.set(attemptId, done);
|
||||||
|
}
|
||||||
|
return { id, done: this.active.get(attemptId) ?? Promise.resolve() };
|
||||||
|
});
|
||||||
|
this.reservations = reservation.catch(() => undefined);
|
||||||
|
return reservation;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async execute(attempt: TbankSyncAttempt) {
|
||||||
|
try {
|
||||||
|
const token = await this.access.tokenForAttempt(attempt);
|
||||||
|
if (!token) return;
|
||||||
|
await this.access.publishMembership(
|
||||||
|
attempt,
|
||||||
|
await this.tbank.getOpenAccounts(token),
|
||||||
|
new Date(),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
await this.access.failMembership(
|
||||||
|
attempt,
|
||||||
|
error instanceof Error && error.message === 'INVALID_TBANK_TOKEN',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
tbankSourceNeedsRefresh,
|
||||||
|
tbankSourceTtlMs,
|
||||||
|
} from './tbank-source.policy';
|
||||||
|
|
||||||
|
describe('request-driven source freshness', () => {
|
||||||
|
it.each(Object.keys(tbankSourceTtlMs) as (keyof typeof tbankSourceTtlMs)[])(
|
||||||
|
'%s expires at its boundary without changing source time',
|
||||||
|
(source) => {
|
||||||
|
const fetchedAt = new Date('2026-09-01Z');
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The key comes from the local source-policy test table.
|
||||||
|
const ttl = tbankSourceTtlMs[source];
|
||||||
|
expect(
|
||||||
|
tbankSourceNeedsRefresh(
|
||||||
|
source,
|
||||||
|
fetchedAt,
|
||||||
|
new Date(fetchedAt.valueOf() + ttl - 1000),
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
tbankSourceNeedsRefresh(
|
||||||
|
source,
|
||||||
|
fetchedAt,
|
||||||
|
new Date(fetchedAt.valueOf() + ttl),
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(tbankSourceNeedsRefresh(source, fetchedAt, fetchedAt, true)).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(tbankSourceNeedsRefresh(source, null, fetchedAt)).toBe(true);
|
||||||
|
expect(fetchedAt.toISOString()).toBe('2026-09-01T00:00:00.000Z');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Freshness never establishes completeness. Immutable ranges are planned by
|
||||||
|
// their coverage owners; these TTLs apply only to mutable source snapshots.
|
||||||
|
export const tbankSourceTtlMs = {
|
||||||
|
membership: 300_000,
|
||||||
|
portfolio: 60_000,
|
||||||
|
quote: 60_000,
|
||||||
|
candleTail: 60_000,
|
||||||
|
operationsTail: 300_000,
|
||||||
|
metadata: 86_400_000,
|
||||||
|
catalog: 86_400_000,
|
||||||
|
company: 86_400_000,
|
||||||
|
calendar: 86_400_000,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function tbankSourceNeedsRefresh(
|
||||||
|
source: keyof typeof tbankSourceTtlMs,
|
||||||
|
fetchedAt: Date | null,
|
||||||
|
now: Date,
|
||||||
|
force = false,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
force ||
|
||||||
|
!fetchedAt ||
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The key is a member of the closed TbankSource union.
|
||||||
|
now.valueOf() - fetchedAt.valueOf() >= tbankSourceTtlMs[source]
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
import { Environment } from '../../config/env.validation';
|
import { Environment } from '../../config/env.validation';
|
||||||
import { TbankCrypto } from './tbank.crypto';
|
import { TbankCrypto } from './tbank.crypto';
|
||||||
|
|
||||||
@@ -25,8 +26,9 @@ export class TbankTokenService {
|
|||||||
try {
|
try {
|
||||||
return await operation();
|
return await operation();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
|
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN') {
|
||||||
throw new BadRequestException({ code: 'INVALID_TBANK_TOKEN' });
|
throw new BadRequestException({ code: 'INVALID_TBANK_TOKEN' });
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,28 @@
|
|||||||
// Public cross-module surface. Nest providers are exported by the matching module.
|
// Public cross-module surface. Nest providers are exported by the matching module.
|
||||||
export { InstrumentMetadataService } from './instrument-metadata.service';
|
export { InstrumentMetadataService } from './instrument-metadata.service';
|
||||||
|
export { metadataKey } from './instrument-metadata.service';
|
||||||
|
export type { MetadataIdentity } from './instrument-metadata.service';
|
||||||
export {
|
export {
|
||||||
TbankAccessService,
|
TbankAccessService,
|
||||||
type TbankConnectionContext,
|
type TbankSyncAttempt,
|
||||||
} from './tbank-access.service';
|
} from './tbank-access.service';
|
||||||
|
export { supportedTbankAccounts } from './tbank-account.policy';
|
||||||
export {
|
export {
|
||||||
type TbankBond,
|
type TbankBond,
|
||||||
type TbankCandle,
|
type TbankCandle,
|
||||||
|
type TbankCoupon,
|
||||||
type TbankFundamentals,
|
type TbankFundamentals,
|
||||||
|
type TbankLastPrice,
|
||||||
type TbankShare,
|
type TbankShare,
|
||||||
} from './tbank-market.types';
|
} from './tbank-market.types';
|
||||||
|
|
||||||
|
export { TbankMembershipService } from './tbank-membership.service';
|
||||||
|
|
||||||
|
export {
|
||||||
|
tbankSourceNeedsRefresh,
|
||||||
|
tbankSourceTtlMs,
|
||||||
|
} from './tbank-source.policy';
|
||||||
|
|
||||||
export { TbankTokenService } from './tbank-token.service';
|
export { TbankTokenService } from './tbank-token.service';
|
||||||
export {
|
export {
|
||||||
TbankClient,
|
TbankClient,
|
||||||
@@ -17,6 +30,7 @@ export {
|
|||||||
type TbankInstrument,
|
type TbankInstrument,
|
||||||
type TbankMoney,
|
type TbankMoney,
|
||||||
type TbankOperationItem,
|
type TbankOperationItem,
|
||||||
|
type TbankOperationsByCursorResponse,
|
||||||
type TbankPortfolio,
|
type TbankPortfolio,
|
||||||
type TbankPositions,
|
type TbankPositions,
|
||||||
type TbankTimestamp,
|
type TbankTimestamp,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { status } from '@grpc/grpc-js';
|
import { status } from '@grpc/grpc-js';
|
||||||
import { NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
import { NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
|
||||||
import { TbankClient } from './tbank.client';
|
import { TbankClient } from './tbank.client';
|
||||||
|
|
||||||
describe('TbankClient operations', () => {
|
describe('TbankClient operations', () => {
|
||||||
@@ -46,11 +47,27 @@ describe('TbankClient operations', () => {
|
|||||||
seconds: String(Math.floor(Date.parse('2026-08-19T00:00:00Z') / 1000)),
|
seconds: String(Math.floor(Date.parse('2026-08-19T00:00:00Z') / 1000)),
|
||||||
},
|
},
|
||||||
to: {
|
to: {
|
||||||
seconds: String(Math.floor(Date.parse('2026-09-18T00:00:00Z') / 1000)),
|
seconds: String(Math.floor(Date.parse('2026-09-19T00:00:00Z') / 1000)),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(['getDividends', 'getBondCoupons'] as const)(
|
||||||
|
'%s converts a leap-day calendar window to a full half-open UTC day',
|
||||||
|
async (method) => {
|
||||||
|
const client = Object.create(TbankClient.prototype) as TbankClient;
|
||||||
|
const call = jest.fn().mockResolvedValue({});
|
||||||
|
(client as unknown as { call: jest.Mock }).call = call;
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- RPC method names come from the literal test table.
|
||||||
|
await client[method]('token', 'uid', '2024-02-29', '2024-02-29');
|
||||||
|
expect(call).toHaveBeenCalledWith('token', undefined, method, {
|
||||||
|
instrumentId: 'uid',
|
||||||
|
from: { seconds: String(Date.parse('2024-02-29T00:00:00Z') / 1000) },
|
||||||
|
to: { seconds: String(Date.parse('2024-03-01T00:00:00Z') / 1000) },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('propagates the normalized upstream error', async () => {
|
it('propagates the normalized upstream error', async () => {
|
||||||
const client = Object.create(TbankClient.prototype) as TbankClient;
|
const client = Object.create(TbankClient.prototype) as TbankClient;
|
||||||
const error = new ServiceUnavailableException({
|
const error = new ServiceUnavailableException({
|
||||||
@@ -96,11 +113,10 @@ describe('TbankClient operations', () => {
|
|||||||
ok: true,
|
ok: true,
|
||||||
});
|
});
|
||||||
const failed = invoke('token', {}, 'getPortfolio', {});
|
const failed = invoke('token', {}, 'getPortfolio', {});
|
||||||
const rejected = expect(failed).rejects.toEqual(
|
await Promise.all([
|
||||||
expect.any(ServiceUnavailableException),
|
expect(failed).rejects.toEqual(expect.any(ServiceUnavailableException)),
|
||||||
);
|
jest.advanceTimersByTimeAsync(1000),
|
||||||
await jest.advanceTimersByTimeAsync(1000);
|
]);
|
||||||
await rejected;
|
|
||||||
|
|
||||||
expect(logger.event).toHaveBeenCalledWith(
|
expect(logger.event).toHaveBeenCalledWith(
|
||||||
'debug',
|
'debug',
|
||||||
@@ -125,7 +141,7 @@ describe('TbankClient metadata retries', () => {
|
|||||||
const instrument = { name: 'Облигация', ticker: 'BOND' };
|
const instrument = { name: 'Облигация', ticker: 'BOND' };
|
||||||
let client: TbankClient;
|
let client: TbankClient;
|
||||||
let requestRpc: jest.Mock;
|
let requestRpc: jest.Mock;
|
||||||
let queue: { size: number; run: jest.Mock };
|
let queue: { run: jest.Mock; size: number };
|
||||||
let logger: {
|
let logger: {
|
||||||
event: jest.Mock<void, [string, string, Record<string, unknown>]>;
|
event: jest.Mock<void, [string, string, Record<string, unknown>]>;
|
||||||
};
|
};
|
||||||
@@ -219,12 +235,10 @@ describe('TbankClient metadata retries', () => {
|
|||||||
|
|
||||||
it('stops retrying a saturated queue after three admission attempts', async () => {
|
it('stops retrying a saturated queue after three admission attempts', async () => {
|
||||||
queue.size = 50;
|
queue.size = 50;
|
||||||
const result = expect(
|
await Promise.all([
|
||||||
client.getInstrumentByUid('token', 'uid'),
|
expect(client.getInstrumentByUid('token', 'uid')).rejects.toBeInstanceOf(ServiceUnavailableException),
|
||||||
).rejects.toBeInstanceOf(ServiceUnavailableException);
|
jest.advanceTimersByTimeAsync(6000),
|
||||||
|
]);
|
||||||
await jest.advanceTimersByTimeAsync(6000);
|
|
||||||
await result;
|
|
||||||
|
|
||||||
expect(queue.run).not.toHaveBeenCalled();
|
expect(queue.run).not.toHaveBeenCalled();
|
||||||
expect(logger.event).toHaveBeenCalledTimes(3);
|
expect(logger.event).toHaveBeenCalledTimes(3);
|
||||||
@@ -238,12 +252,10 @@ describe('TbankClient metadata retries', () => {
|
|||||||
|
|
||||||
it('stops retrying an unavailable upstream after three RPCs', async () => {
|
it('stops retrying an unavailable upstream after three RPCs', async () => {
|
||||||
requestRpc.mockRejectedValue({ code: status.UNAVAILABLE });
|
requestRpc.mockRejectedValue({ code: status.UNAVAILABLE });
|
||||||
const result = expect(
|
await Promise.all([
|
||||||
client.getInstrumentByUid('token', 'uid'),
|
expect(client.getInstrumentByUid('token', 'uid')).rejects.toBeInstanceOf(ServiceUnavailableException),
|
||||||
).rejects.toBeInstanceOf(ServiceUnavailableException);
|
jest.advanceTimersByTimeAsync(6000),
|
||||||
|
]);
|
||||||
await jest.advanceTimersByTimeAsync(6000);
|
|
||||||
await result;
|
|
||||||
|
|
||||||
expect(queue.run).toHaveBeenCalledTimes(3);
|
expect(queue.run).toHaveBeenCalledTimes(3);
|
||||||
expect(jest.getTimerCount()).toBe(0);
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
@@ -267,6 +279,7 @@ describe('TbankClient metadata retries', () => {
|
|||||||
async (method) => {
|
async (method) => {
|
||||||
requestRpc.mockRejectedValue({ code: status.NOT_FOUND });
|
requestRpc.mockRejectedValue({ code: status.NOT_FOUND });
|
||||||
|
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- RPC method names come from the literal test table.
|
||||||
await expect(client[method]('token', 'instrument')).resolves.toBeNull();
|
await expect(client[method]('token', 'instrument')).resolves.toBeNull();
|
||||||
expect(requestRpc).toHaveBeenCalledTimes(1);
|
expect(requestRpc).toHaveBeenCalledTimes(1);
|
||||||
expect(jest.getTimerCount()).toBe(0);
|
expect(jest.getTimerCount()).toBe(0);
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { MILLISECONDS_PER_SECOND } from '../../common/time';
|
|
||||||
import {
|
import {
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
Client,
|
Client,
|
||||||
@@ -17,8 +16,6 @@ import {
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
|
||||||
import { Environment } from '../../config/env.validation';
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
TbankBond,
|
TbankBond,
|
||||||
@@ -29,6 +26,17 @@ import type {
|
|||||||
TbankShare,
|
TbankShare,
|
||||||
} from './tbank-market.types';
|
} from './tbank-market.types';
|
||||||
|
|
||||||
|
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
||||||
|
import { MILLISECONDS_PER_SECOND } from '../../common/time';
|
||||||
|
import { Environment } from '../../config/env.validation';
|
||||||
|
|
||||||
|
const INITIAL_REQUEST_COUNT = 0;
|
||||||
|
const MIN_RATE_DELAY_MS = 1;
|
||||||
|
const FIRST_ATTEMPT = 1;
|
||||||
|
const ATTEMPT_INCREMENT = 1;
|
||||||
|
const NO_RPC_ATTEMPTS = 0;
|
||||||
|
const NEXT_DAY_OFFSET = 1;
|
||||||
|
|
||||||
const RATE_WINDOW_MS = 1_000;
|
const RATE_WINDOW_MS = 1_000;
|
||||||
const METADATA_MAX_ATTEMPTS = 3;
|
const METADATA_MAX_ATTEMPTS = 3;
|
||||||
const RPC_MAX_ATTEMPTS = 2;
|
const RPC_MAX_ATTEMPTS = 2;
|
||||||
@@ -42,74 +50,78 @@ type Unary<Request, Response> = (
|
|||||||
request: Request,
|
request: Request,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
options: { deadline: Date },
|
options: { deadline: Date },
|
||||||
callback: (error: ServiceError | null, response: Response) => void,
|
callback: (error: null | ServiceError, response: Response) => void,
|
||||||
) => ClientUnaryCall;
|
) => ClientUnaryCall;
|
||||||
type TbankClientService = Client & Record<string, Unary<never, never>>;
|
type TbankClientService = Client & Record<string, Unary<never, never>>;
|
||||||
export type TbankDecimal = { units?: string | number; nano?: string | number };
|
export type TbankDecimal = { nano?: number | string; units?: number | string };
|
||||||
export type TbankMoney = TbankDecimal & { currency?: string };
|
export type TbankMoney = TbankDecimal & { currency?: string };
|
||||||
export type TbankAccount = {
|
export type TbankAccount = {
|
||||||
id: string;
|
id: string;
|
||||||
type: string;
|
|
||||||
name: string;
|
name: string;
|
||||||
openedDate?: { seconds?: string | number };
|
openedDate?: { seconds?: number | string };
|
||||||
|
type: string;
|
||||||
};
|
};
|
||||||
export type TbankPortfolio = {
|
export type TbankPortfolio = {
|
||||||
positions?: {
|
positions?: {
|
||||||
figi?: string;
|
|
||||||
instrumentUid?: string;
|
|
||||||
instrumentType?: string;
|
|
||||||
ticker?: string;
|
|
||||||
quantity?: TbankDecimal;
|
|
||||||
currentPrice?: TbankMoney;
|
|
||||||
averagePositionPrice?: TbankMoney;
|
averagePositionPrice?: TbankMoney;
|
||||||
|
currentPrice?: TbankMoney;
|
||||||
|
figi?: string;
|
||||||
|
instrumentType?: string;
|
||||||
|
instrumentUid?: string;
|
||||||
|
quantity?: TbankDecimal;
|
||||||
|
ticker?: string;
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
export type TbankPositions = { money?: TbankMoney[] };
|
export type TbankPositions = { money?: TbankMoney[] };
|
||||||
export type TbankInstrument = {
|
export type TbankInstrument = {
|
||||||
ticker?: string;
|
brand?: { logoName?: null | string };
|
||||||
name?: string;
|
figi?: string;
|
||||||
|
instrumentType?: string;
|
||||||
isin?: string;
|
isin?: string;
|
||||||
brand?: { logoName?: string | null };
|
name?: string;
|
||||||
|
ticker?: string;
|
||||||
|
uid?: string;
|
||||||
};
|
};
|
||||||
export type TbankDividend = {
|
export type TbankDividend = {
|
||||||
dividendNet?: TbankMoney;
|
dividendNet?: TbankMoney;
|
||||||
recordDate?: TbankTimestamp;
|
|
||||||
paymentDate?: TbankTimestamp;
|
|
||||||
lastBuyDate?: TbankTimestamp;
|
|
||||||
dividendType?: string;
|
dividendType?: string;
|
||||||
|
lastBuyDate?: TbankTimestamp;
|
||||||
|
paymentDate?: TbankTimestamp;
|
||||||
|
recordDate?: TbankTimestamp;
|
||||||
};
|
};
|
||||||
export type TbankTimestamp = { seconds?: string | number; nanos?: number };
|
export type TbankTimestamp = { nanos?: number; seconds?: number | string };
|
||||||
export type TbankOperationItem = {
|
export type TbankOperationItem = {
|
||||||
|
accruedInt?: TbankMoney;
|
||||||
|
commission?: TbankMoney;
|
||||||
cursor?: string;
|
cursor?: string;
|
||||||
id?: string;
|
|
||||||
name?: string;
|
|
||||||
date?: TbankTimestamp;
|
date?: TbankTimestamp;
|
||||||
type?: string;
|
|
||||||
description?: string;
|
description?: string;
|
||||||
figi?: string;
|
figi?: string;
|
||||||
instrumentUid?: string;
|
id?: string;
|
||||||
instrumentType?: string;
|
instrumentType?: string;
|
||||||
ticker?: string;
|
instrumentUid?: string;
|
||||||
|
name?: string;
|
||||||
payment?: TbankMoney;
|
payment?: TbankMoney;
|
||||||
price?: TbankMoney;
|
price?: TbankMoney;
|
||||||
commission?: TbankMoney;
|
quantity?: number | string;
|
||||||
accruedInt?: TbankMoney;
|
quantityDone?: number | string;
|
||||||
quantity?: string | number;
|
state?: string;
|
||||||
quantityDone?: string | number;
|
ticker?: string;
|
||||||
|
type?: string;
|
||||||
};
|
};
|
||||||
export type TbankOperationsByCursorRequest = {
|
export type TbankOperationsByCursorRequest = {
|
||||||
accountId: string;
|
accountId: string;
|
||||||
instrumentId?: string;
|
|
||||||
from?: TbankTimestamp;
|
|
||||||
to?: TbankTimestamp;
|
|
||||||
cursor?: string;
|
cursor?: string;
|
||||||
|
from?: TbankTimestamp;
|
||||||
|
instrumentId?: string;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
state: 'OPERATION_STATE_EXECUTED';
|
state: 'OPERATION_STATE_EXECUTED';
|
||||||
|
to?: TbankTimestamp;
|
||||||
};
|
};
|
||||||
export type TbankOperationsByCursorResponse = {
|
export type TbankOperationsByCursorResponse = {
|
||||||
hasNext?: boolean;
|
hasNext?: boolean;
|
||||||
nextCursor?: string;
|
|
||||||
items?: TbankOperationItem[];
|
items?: TbankOperationItem[];
|
||||||
|
nextCursor?: string;
|
||||||
};
|
};
|
||||||
type TbankNamespace = {
|
type TbankNamespace = {
|
||||||
tinkoff: {
|
tinkoff: {
|
||||||
@@ -119,7 +131,7 @@ type TbankNamespace = {
|
|||||||
|
|
||||||
class RateLimiter {
|
class RateLimiter {
|
||||||
private readonly waiting: (() => void)[] = [];
|
private readonly waiting: (() => void)[] = [];
|
||||||
private starts = 0;
|
private starts = INITIAL_REQUEST_COUNT;
|
||||||
private windowStartedAt = Date.now();
|
private windowStartedAt = Date.now();
|
||||||
|
|
||||||
constructor(private readonly perSecond: number) {}
|
constructor(private readonly perSecond: number) {}
|
||||||
@@ -144,16 +156,16 @@ class RateLimiter {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - this.windowStartedAt >= RATE_WINDOW_MS) {
|
if (now - this.windowStartedAt >= RATE_WINDOW_MS) {
|
||||||
this.windowStartedAt = now;
|
this.windowStartedAt = now;
|
||||||
this.starts = 0;
|
this.starts = INITIAL_REQUEST_COUNT;
|
||||||
}
|
}
|
||||||
while (this.starts < this.perSecond && this.waiting.length) {
|
while (this.starts < this.perSecond && this.waiting.length) {
|
||||||
this.starts += 1;
|
this.starts++;
|
||||||
this.waiting.shift()?.();
|
this.waiting.shift()?.();
|
||||||
}
|
}
|
||||||
if (this.waiting.length && this.starts === this.perSecond) {
|
if (this.waiting.length && this.starts === this.perSecond) {
|
||||||
setTimeout(
|
setTimeout(
|
||||||
() => this.drain(),
|
() => this.drain(),
|
||||||
Math.max(1, RATE_WINDOW_MS - (now - this.windowStartedAt)),
|
Math.max(MIN_RATE_DELAY_MS, RATE_WINDOW_MS - (now - this.windowStartedAt)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,12 +205,14 @@ export class TbankClient {
|
|||||||
loadPackageDefinition(definition) as unknown as TbankNamespace
|
loadPackageDefinition(definition) as unknown as TbankNamespace
|
||||||
).tinkoff.public.invest.api.contract.v1;
|
).tinkoff.public.invest.api.contract.v1;
|
||||||
const caPath = config.get<string | undefined>('TBANK_CA_CERT_PATH');
|
const caPath = config.get<string | undefined>('TBANK_CA_CERT_PATH');
|
||||||
const credentials = caPath
|
const credentials = caPath ?
|
||||||
? ChannelCredentials.createSsl(readFileSync(caPath))
|
// eslint-disable-next-line security/detect-non-literal-fs-filename -- The CA path is trusted operator configuration, never supplied by an HTTP request.
|
||||||
: ChannelCredentials.createSsl();
|
ChannelCredentials.createSsl(readFileSync(caPath)) :
|
||||||
|
ChannelCredentials.createSsl();
|
||||||
const endpoint = config.getOrThrow<string>('TBANK_GRPC_ENDPOINT');
|
const endpoint = config.getOrThrow<string>('TBANK_GRPC_ENDPOINT');
|
||||||
const create = (name: string) =>
|
const create = (name: string) =>
|
||||||
new (
|
new (
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Service and method names are internal RPC selections, not request input.
|
||||||
services[name] as new (
|
services[name] as new (
|
||||||
address: string,
|
address: string,
|
||||||
credentials: ChannelCredentials,
|
credentials: ChannelCredentials,
|
||||||
@@ -233,8 +247,8 @@ export class TbankClient {
|
|||||||
this.logger.info('tbank.client.configured');
|
this.logger.info('tbank.client.configured');
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateToken(token: string): Promise<void> {
|
validateToken(token: string): Promise<TbankAccount[]> {
|
||||||
await this.getOpenAccounts(token);
|
return this.getOpenAccounts(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
getOpenAccounts(token: string): Promise<TbankAccount[]> {
|
getOpenAccounts(token: string): Promise<TbankAccount[]> {
|
||||||
@@ -264,14 +278,14 @@ export class TbankClient {
|
|||||||
getInstrumentByFigi(
|
getInstrumentByFigi(
|
||||||
token: string,
|
token: string,
|
||||||
figi: string,
|
figi: string,
|
||||||
): Promise<TbankInstrument | null> {
|
): Promise<null | TbankInstrument> {
|
||||||
return this.getInstrument(token, 'INSTRUMENT_ID_TYPE_FIGI', figi);
|
return this.getInstrument(token, 'INSTRUMENT_ID_TYPE_FIGI', figi);
|
||||||
}
|
}
|
||||||
|
|
||||||
getInstrumentByUid(
|
getInstrumentByUid(
|
||||||
token: string,
|
token: string,
|
||||||
instrumentUid: string,
|
instrumentUid: string,
|
||||||
): Promise<TbankInstrument | null> {
|
): Promise<null | TbankInstrument> {
|
||||||
return this.getInstrument(token, 'INSTRUMENT_ID_TYPE_UID', instrumentUid);
|
return this.getInstrument(token, 'INSTRUMENT_ID_TYPE_UID', instrumentUid);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +302,7 @@ export class TbankClient {
|
|||||||
{
|
{
|
||||||
instrumentId,
|
instrumentId,
|
||||||
from: { seconds: String(utcSeconds(from)) },
|
from: { seconds: String(utcSeconds(from)) },
|
||||||
to: { seconds: String(utcSeconds(to)) },
|
to: { seconds: String(utcSeconds(to, true)) },
|
||||||
},
|
},
|
||||||
).then((response) => response.dividends ?? []);
|
).then((response) => response.dividends ?? []);
|
||||||
}
|
}
|
||||||
@@ -316,7 +330,8 @@ export class TbankClient {
|
|||||||
},
|
},
|
||||||
).then((response) => response.instruments ?? []);
|
).then((response) => response.instruments ?? []);
|
||||||
}
|
}
|
||||||
getBond(token: string, uid: string): Promise<TbankBond | null> {
|
|
||||||
|
getBond(token: string, uid: string): Promise<null | TbankBond> {
|
||||||
return this.call<{ instrument?: TbankBond }>(
|
return this.call<{ instrument?: TbankBond }>(
|
||||||
token,
|
token,
|
||||||
this.sparseInstruments,
|
this.sparseInstruments,
|
||||||
@@ -327,6 +342,7 @@ export class TbankClient {
|
|||||||
},
|
},
|
||||||
).then((response) => response.instrument ?? null);
|
).then((response) => response.instrument ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
getBondCoupons(
|
getBondCoupons(
|
||||||
token: string,
|
token: string,
|
||||||
uid: string,
|
uid: string,
|
||||||
@@ -340,12 +356,12 @@ export class TbankClient {
|
|||||||
{
|
{
|
||||||
instrumentId: uid,
|
instrumentId: uid,
|
||||||
from: { seconds: String(utcSeconds(from)) },
|
from: { seconds: String(utcSeconds(from)) },
|
||||||
to: { seconds: String(utcSeconds(to)) },
|
to: { seconds: String(utcSeconds(to, true)) },
|
||||||
},
|
},
|
||||||
).then((response) => response.events ?? []);
|
).then((response) => response.events ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
getShare(token: string, uid: string): Promise<TbankShare | null> {
|
getShare(token: string, uid: string): Promise<null | TbankShare> {
|
||||||
return this.call<{ instrument?: TbankShare }>(
|
return this.call<{ instrument?: TbankShare }>(
|
||||||
token,
|
token,
|
||||||
this.instruments,
|
this.instruments,
|
||||||
@@ -357,7 +373,7 @@ export class TbankClient {
|
|||||||
).then((response) => response.instrument ?? null);
|
).then((response) => response.instrument ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
getAssetDescription(token: string, assetUid: string): Promise<string | null> {
|
getAssetDescription(token: string, assetUid: string): Promise<null | string> {
|
||||||
return this.call<{ asset?: { description?: string } }>(
|
return this.call<{ asset?: { description?: string } }>(
|
||||||
token,
|
token,
|
||||||
this.instruments,
|
this.instruments,
|
||||||
@@ -371,7 +387,7 @@ export class TbankClient {
|
|||||||
getFundamentals(
|
getFundamentals(
|
||||||
token: string,
|
token: string,
|
||||||
assetUid: string,
|
assetUid: string,
|
||||||
): Promise<TbankFundamentals | null> {
|
): Promise<null | TbankFundamentals> {
|
||||||
return this.call<{ fundamentals?: TbankFundamentals[] }>(
|
return this.call<{ fundamentals?: TbankFundamentals[] }>(
|
||||||
token,
|
token,
|
||||||
this.sparseInstruments,
|
this.sparseInstruments,
|
||||||
@@ -395,13 +411,13 @@ export class TbankClient {
|
|||||||
).then((response) => response.lastPrices ?? []);
|
).then((response) => response.lastPrices ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
getLastPrice(token: string, uid: string): Promise<TbankLastPrice | null> {
|
getLastPrice(token: string, uid: string): Promise<null | TbankLastPrice> {
|
||||||
return this.getLastPrices(token, [uid]).then(
|
return this.getLastPrices(token, [uid]).then(
|
||||||
(prices) => prices.find((item) => item.instrumentUid === uid) ?? null,
|
(prices) => prices.find((item) => item.instrumentUid === uid) ?? null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getTradingStatus(token: string, uid: string): Promise<string | null> {
|
getTradingStatus(token: string, uid: string): Promise<null | string> {
|
||||||
return this.call<{ tradingStatus?: string }>(
|
return this.call<{ tradingStatus?: string }>(
|
||||||
token,
|
token,
|
||||||
this.marketData,
|
this.marketData,
|
||||||
@@ -438,9 +454,9 @@ export class TbankClient {
|
|||||||
|
|
||||||
private async getInstrument(
|
private async getInstrument(
|
||||||
token: string,
|
token: string,
|
||||||
idType: 'INSTRUMENT_ID_TYPE_UID' | 'INSTRUMENT_ID_TYPE_FIGI',
|
idType: 'INSTRUMENT_ID_TYPE_FIGI' | 'INSTRUMENT_ID_TYPE_UID',
|
||||||
id: string,
|
id: string,
|
||||||
): Promise<TbankInstrument | null> {
|
): Promise<null | TbankInstrument> {
|
||||||
try {
|
try {
|
||||||
const response = await this.call<{ instrument?: TbankInstrument }>(
|
const response = await this.call<{ instrument?: TbankInstrument }>(
|
||||||
token,
|
token,
|
||||||
@@ -463,12 +479,13 @@ export class TbankClient {
|
|||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const metadataCall = method === 'getInstrumentBy';
|
const metadataCall = method === 'getInstrumentBy';
|
||||||
const maxAttempts = metadataCall ? METADATA_MAX_ATTEMPTS : RPC_MAX_ATTEMPTS;
|
const maxAttempts = metadataCall ? METADATA_MAX_ATTEMPTS : RPC_MAX_ATTEMPTS;
|
||||||
for (let attempts = 1; attempts <= maxAttempts; attempts += 1) {
|
for (let attempts = FIRST_ATTEMPT; attempts <= maxAttempts; attempts += ATTEMPT_INCREMENT) {
|
||||||
const startedAt = performance.now();
|
const startedAt = performance.now();
|
||||||
const queueFull = this.queue.size >= MAX_QUEUE_SIZE;
|
const queueFull = this.queue.size >= MAX_QUEUE_SIZE;
|
||||||
try {
|
try {
|
||||||
if (queueFull)
|
if (queueFull) {
|
||||||
throw new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' });
|
||||||
|
}
|
||||||
const response = await this.queue.run(() =>
|
const response = await this.queue.run(() =>
|
||||||
this.request<Response>(token, client, method, request),
|
this.request<Response>(token, client, method, request),
|
||||||
);
|
);
|
||||||
@@ -480,15 +497,15 @@ export class TbankClient {
|
|||||||
return response;
|
return response;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const grpcCode = (error as ServiceError).code;
|
const grpcCode = (error as ServiceError).code;
|
||||||
const failureContext = queueFull
|
const failureContext = queueFull ?
|
||||||
? { code: 'TBANK_UNAVAILABLE' }
|
{ code: 'TBANK_UNAVAILABLE' } :
|
||||||
: { grpcCode };
|
{ grpcCode };
|
||||||
const retryable = queueFull
|
const retryable = queueFull ?
|
||||||
? metadataCall
|
metadataCall :
|
||||||
: [
|
[
|
||||||
status.UNAVAILABLE,
|
|
||||||
status.DEADLINE_EXCEEDED,
|
status.DEADLINE_EXCEEDED,
|
||||||
status.RESOURCE_EXHAUSTED,
|
status.RESOURCE_EXHAUSTED,
|
||||||
|
status.UNAVAILABLE,
|
||||||
].includes(grpcCode);
|
].includes(grpcCode);
|
||||||
if (retryable && attempts < maxAttempts) {
|
if (retryable && attempts < maxAttempts) {
|
||||||
this.logger.event('warn', 'tbank.rpc.retry', {
|
this.logger.event('warn', 'tbank.rpc.retry', {
|
||||||
@@ -500,9 +517,9 @@ export class TbankClient {
|
|||||||
await new Promise((resolve) =>
|
await new Promise((resolve) =>
|
||||||
setTimeout(
|
setTimeout(
|
||||||
resolve,
|
resolve,
|
||||||
metadataCall
|
metadataCall ?
|
||||||
? attempts * METADATA_RETRY_DELAY_MS
|
attempts * METADATA_RETRY_DELAY_MS :
|
||||||
: RPC_RETRY_DELAY_MS,
|
RPC_RETRY_DELAY_MS,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
@@ -510,19 +527,21 @@ export class TbankClient {
|
|||||||
this.logger.event('error', 'tbank.rpc.failed', {
|
this.logger.event('error', 'tbank.rpc.failed', {
|
||||||
operation: method,
|
operation: method,
|
||||||
...failureContext,
|
...failureContext,
|
||||||
attempts: queueFull && !metadataCall ? 0 : attempts,
|
attempts: queueFull && !metadataCall ? NO_RPC_ATTEMPTS : attempts,
|
||||||
durationMs: Math.round(performance.now() - startedAt),
|
durationMs: Math.round(performance.now() - startedAt),
|
||||||
});
|
});
|
||||||
if (
|
if (
|
||||||
[status.UNAUTHENTICATED, status.PERMISSION_DENIED].includes(grpcCode)
|
[status.PERMISSION_DENIED, status.UNAUTHENTICATED].includes(grpcCode)
|
||||||
)
|
) {
|
||||||
// eslint-disable-next-line preserve-caught-error -- Discard raw upstream authentication errors at the integration boundary.
|
// eslint-disable-next-line preserve-caught-error -- Discard raw upstream authentication errors at the integration boundary.
|
||||||
throw new Error('INVALID_TBANK_TOKEN');
|
throw new Error('INVALID_TBANK_TOKEN');
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
grpcCode === status.NOT_FOUND &&
|
grpcCode === status.NOT_FOUND &&
|
||||||
(method === 'shareBy' || metadataCall)
|
(method === 'shareBy' || metadataCall)
|
||||||
)
|
) {
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
throw new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' });
|
throw new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -538,6 +557,7 @@ export class TbankClient {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const metadata = new Metadata();
|
const metadata = new Metadata();
|
||||||
metadata.set('Authorization', `Bearer ${token}`);
|
metadata.set('Authorization', `Bearer ${token}`);
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Service and method names are internal RPC selections, not request input.
|
||||||
client[method](
|
client[method](
|
||||||
request as never,
|
request as never,
|
||||||
metadata,
|
metadata,
|
||||||
@@ -548,6 +568,9 @@ export class TbankClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function utcSeconds(date: string): number {
|
// Calendar owners supply inclusive UTC days; RPC timestamps use [from, next(to)).
|
||||||
return Math.floor(Date.parse(`${date}T00:00:00Z`) / MILLISECONDS_PER_SECOND);
|
function utcSeconds(date: string, nextDay = false): number {
|
||||||
|
const instant = new Date(`${date}T00:00:00Z`);
|
||||||
|
if (nextDay) instant.setUTCDate(instant.getUTCDate() + NEXT_DAY_OFFSET);
|
||||||
|
return Math.floor(instant.valueOf() / MILLISECONDS_PER_SECOND);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
||||||
|
|
||||||
|
const VERSION_SIZE_BYTES = 1;
|
||||||
|
|
||||||
const KEY_SIZE_BYTES = 32;
|
const KEY_SIZE_BYTES = 32;
|
||||||
|
|
||||||
const VERSION = 1;
|
const VERSION = 1;
|
||||||
@@ -11,8 +13,9 @@ export class TbankCrypto {
|
|||||||
|
|
||||||
static fromBase64(key: string): TbankCrypto {
|
static fromBase64(key: string): TbankCrypto {
|
||||||
const decoded = Buffer.from(key, 'base64');
|
const decoded = Buffer.from(key, 'base64');
|
||||||
if (decoded.length !== KEY_SIZE_BYTES)
|
if (decoded.length !== KEY_SIZE_BYTES) {
|
||||||
throw new Error('Invalid token encryption key');
|
throw new Error('Invalid token encryption key');
|
||||||
|
}
|
||||||
return new TbankCrypto(decoded);
|
return new TbankCrypto(decoded);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,15 +36,15 @@ export class TbankCrypto {
|
|||||||
|
|
||||||
decrypt(payload: string): string {
|
decrypt(payload: string): string {
|
||||||
const bytes = Buffer.from(payload, 'base64');
|
const bytes = Buffer.from(payload, 'base64');
|
||||||
if (bytes[0] !== VERSION || bytes.length < 1 + NONCE_SIZE + TAG_SIZE) {
|
if (bytes[0] !== VERSION || bytes.length < VERSION_SIZE_BYTES + NONCE_SIZE + TAG_SIZE) {
|
||||||
throw new Error('Invalid encrypted token');
|
throw new Error('Invalid encrypted token');
|
||||||
}
|
}
|
||||||
const nonce = bytes.subarray(1, 1 + NONCE_SIZE);
|
const nonce = bytes.subarray(VERSION_SIZE_BYTES, VERSION_SIZE_BYTES + NONCE_SIZE);
|
||||||
const tag = bytes.subarray(-TAG_SIZE);
|
const tag = bytes.subarray(-TAG_SIZE);
|
||||||
const decipher = createDecipheriv('aes-256-gcm', this.key, nonce);
|
const decipher = createDecipheriv('aes-256-gcm', this.key, nonce);
|
||||||
decipher.setAuthTag(tag);
|
decipher.setAuthTag(tag);
|
||||||
return Buffer.concat([
|
return Buffer.concat([
|
||||||
decipher.update(bytes.subarray(1 + NONCE_SIZE, -TAG_SIZE)),
|
decipher.update(bytes.subarray(VERSION_SIZE_BYTES + NONCE_SIZE, -TAG_SIZE)),
|
||||||
decipher.final(),
|
decipher.final(),
|
||||||
]).toString('utf8');
|
]).toString('utf8');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
|
import { InstrumentMetadataRepository } from './instrument-metadata.repository';
|
||||||
import { InstrumentMetadataService } from './instrument-metadata.service';
|
import { InstrumentMetadataService } from './instrument-metadata.service';
|
||||||
import { TbankAccessService } from './tbank-access.service';
|
import { TbankAccessService } from './tbank-access.service';
|
||||||
|
import { TbankMembershipService } from './tbank-membership.service';
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
import { TbankTokenService } from './tbank-token.service';
|
||||||
import { TbankClient } from './tbank.client';
|
import { TbankClient } from './tbank.client';
|
||||||
|
|
||||||
@@ -9,12 +12,15 @@ import { TbankClient } from './tbank.client';
|
|||||||
TbankClient,
|
TbankClient,
|
||||||
TbankTokenService,
|
TbankTokenService,
|
||||||
TbankAccessService,
|
TbankAccessService,
|
||||||
|
TbankMembershipService,
|
||||||
InstrumentMetadataService,
|
InstrumentMetadataService,
|
||||||
|
InstrumentMetadataRepository,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
TbankClient,
|
TbankClient,
|
||||||
TbankTokenService,
|
TbankTokenService,
|
||||||
TbankAccessService,
|
TbankAccessService,
|
||||||
|
TbankMembershipService,
|
||||||
InstrumentMetadataService,
|
InstrumentMetadataService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
+18
-5
@@ -1,16 +1,21 @@
|
|||||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
import {
|
||||||
import { NestFactory } from '@nestjs/core';
|
BadRequestException,
|
||||||
import cookieParser from 'cookie-parser';
|
INestApplication,
|
||||||
|
ValidationPipe,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { SwaggerModule } from '@nestjs/swagger';
|
import { SwaggerModule } from '@nestjs/swagger';
|
||||||
import { API_PREFIX, createOpenApiDocument } from './openapi';
|
import cookieParser from 'cookie-parser';
|
||||||
import { Logger } from 'nestjs-pino';
|
import { Logger } from 'nestjs-pino';
|
||||||
|
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||||
import { RequestLoggingMiddleware } from './common/logging/request-logging.middleware';
|
import { RequestLoggingMiddleware } from './common/logging/request-logging.middleware';
|
||||||
import { StructuredLogger } from './common/logging/structured-logger.service';
|
import { StructuredLogger } from './common/logging/structured-logger.service';
|
||||||
import { Environment } from './config/env.validation';
|
import { Environment } from './config/env.validation';
|
||||||
import { shouldExposeSwagger } from './config/swagger.config';
|
import { shouldExposeSwagger } from './config/swagger.config';
|
||||||
|
import { API_PREFIX, createOpenApiDocument } from './openapi';
|
||||||
|
|
||||||
export function configureApp(app: INestApplication): void {
|
export function configureApp(app: INestApplication): void {
|
||||||
const config = app.get<ConfigService<Environment, true>>(ConfigService);
|
const config = app.get<ConfigService<Environment, true>>(ConfigService);
|
||||||
@@ -26,7 +31,15 @@ export function configureApp(app: INestApplication): void {
|
|||||||
app.use(cookieParser());
|
app.use(cookieParser());
|
||||||
const requestLogging = app.get(RequestLoggingMiddleware);
|
const requestLogging = app.get(RequestLoggingMiddleware);
|
||||||
app.use(requestLogging.use.bind(requestLogging));
|
app.use(requestLogging.use.bind(requestLogging));
|
||||||
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
forbidUnknownValues: true,
|
||||||
|
transform: true,
|
||||||
|
whitelist: true,
|
||||||
|
validationError: { target: false, value: false },
|
||||||
|
exceptionFactory: (message) => new BadRequestException({ message }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
app.useGlobalFilters(new HttpExceptionFilter());
|
app.useGlobalFilters(new HttpExceptionFilter());
|
||||||
app.enableShutdownHooks();
|
app.enableShutdownHooks();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,8 +114,8 @@ describe('AuthService', () => {
|
|||||||
where,
|
where,
|
||||||
data,
|
data,
|
||||||
}: {
|
}: {
|
||||||
where: { id?: string; refreshTokenHash?: string };
|
|
||||||
data: { refreshTokenHash: string };
|
data: { refreshTokenHash: string };
|
||||||
|
where: { id?: string; refreshTokenHash?: string };
|
||||||
}) => {
|
}) => {
|
||||||
if (where.id === session.id && where.refreshTokenHash === currentHash) {
|
if (where.id === session.id && where.refreshTokenHash === currentHash) {
|
||||||
currentHash = data.refreshTokenHash;
|
currentHash = data.refreshTokenHash;
|
||||||
|
|||||||
@@ -6,16 +6,20 @@ import {
|
|||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService } from '@nestjs/jwt';
|
||||||
import * as bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
import { createHash, randomUUID } from 'crypto';
|
import { createHash, randomUUID } from 'crypto';
|
||||||
|
|
||||||
import { Session, User } from '../../../../generated/prisma/client';
|
import { Session, User } from '../../../../generated/prisma/client';
|
||||||
import { PrismaService } from '../../../prisma/prisma.service';
|
import { PrismaService } from '../../../prisma/prisma.service';
|
||||||
import { AuthUser, RefreshPayload } from './auth.types';
|
import { AuthUser, RefreshPayload } from './auth.types';
|
||||||
|
|
||||||
|
const EXPECTED_ROTATED_SESSIONS = 1;
|
||||||
|
|
||||||
const PASSWORD_HASH_ROUNDS = 12;
|
const PASSWORD_HASH_ROUNDS = 12;
|
||||||
const REFRESH_TTL_MS = 604_800_000;
|
const REFRESH_TTL_MS = 604_800_000;
|
||||||
|
|
||||||
const ACCESS_TTL = '15m';
|
const ACCESS_TTL = '15m';
|
||||||
const REFRESH_TTL = '7d';
|
const REFRESH_TTL = '7d';
|
||||||
const DUMMY_PASSWORD_HASH =
|
const DUMMY_PASSWORD_HASH =
|
||||||
|
// eslint-disable-next-line sonarjs/no-hardcoded-passwords -- Public dummy bcrypt hash preserves login timing for nonexistent users; it is not a credential.
|
||||||
'$2b$12$Z49BwJsyiUqY0ZozFzt9IeYvjhV4kbeLw9KdxOguT5bfhA1RvPCx6';
|
'$2b$12$Z49BwJsyiUqY0ZozFzt9IeYvjhV4kbeLw9KdxOguT5bfhA1RvPCx6';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -28,26 +32,27 @@ export class AuthService {
|
|||||||
async register(
|
async register(
|
||||||
email: string,
|
email: string,
|
||||||
password: string,
|
password: string,
|
||||||
): Promise<{ user: AuthUser; accessToken: string; refreshToken: string }> {
|
): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
|
||||||
const normalizedEmail = this.normalizeEmail(email);
|
|
||||||
const existing = await this.prisma.user.findUnique({
|
const existing = await this.prisma.user.findUnique({
|
||||||
where: { email: normalizedEmail },
|
where: { email },
|
||||||
});
|
});
|
||||||
if (existing)
|
if (existing) {
|
||||||
throw new ConflictException({ code: 'EMAIL_ALREADY_REGISTERED' });
|
throw new ConflictException({ code: 'EMAIL_ALREADY_REGISTERED' });
|
||||||
|
}
|
||||||
|
|
||||||
let user: User;
|
let user: User;
|
||||||
try {
|
try {
|
||||||
user = await this.prisma.user.create({
|
user = await this.prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
email: normalizedEmail,
|
email,
|
||||||
passwordHash: await bcrypt.hash(password, PASSWORD_HASH_ROUNDS),
|
passwordHash: await bcrypt.hash(password, PASSWORD_HASH_ROUNDS),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isUniqueConstraintError(error))
|
if (isUniqueConstraintError(error)) {
|
||||||
throw new ConflictException({ code: 'EMAIL_ALREADY_REGISTERED' });
|
throw new ConflictException({ code: 'EMAIL_ALREADY_REGISTERED' });
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
return this.createSession(user);
|
return this.createSession(user);
|
||||||
@@ -56,22 +61,23 @@ export class AuthService {
|
|||||||
async login(
|
async login(
|
||||||
email: string,
|
email: string,
|
||||||
password: string,
|
password: string,
|
||||||
): Promise<{ user: AuthUser; accessToken: string; refreshToken: string }> {
|
): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
|
||||||
const user = await this.prisma.user.findUnique({
|
const user = await this.prisma.user.findUnique({
|
||||||
where: { email: this.normalizeEmail(email) },
|
where: { email },
|
||||||
});
|
});
|
||||||
const valid = await bcrypt.compare(
|
const valid = await bcrypt.compare(
|
||||||
password,
|
password,
|
||||||
user?.passwordHash ?? DUMMY_PASSWORD_HASH,
|
user?.passwordHash ?? DUMMY_PASSWORD_HASH,
|
||||||
);
|
);
|
||||||
if (!user || !valid)
|
if (!user || !valid) {
|
||||||
throw new UnauthorizedException({ code: 'INVALID_CREDENTIALS' });
|
throw new UnauthorizedException({ code: 'INVALID_CREDENTIALS' });
|
||||||
|
}
|
||||||
return this.createSession(user);
|
return this.createSession(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
async refresh(
|
async refresh(
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<{ user: AuthUser; accessToken: string; refreshToken: string }> {
|
): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
|
||||||
let payload: RefreshPayload;
|
let payload: RefreshPayload;
|
||||||
try {
|
try {
|
||||||
payload = await this.jwt.verifyAsync<RefreshPayload>(token, {
|
payload = await this.jwt.verifyAsync<RefreshPayload>(token, {
|
||||||
@@ -80,8 +86,9 @@ export class AuthService {
|
|||||||
} catch {
|
} catch {
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
}
|
}
|
||||||
if (payload.type !== 'refresh')
|
if (payload.type !== 'refresh') {
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
|
}
|
||||||
const session = await this.prisma.session.findUnique({
|
const session = await this.prisma.session.findUnique({
|
||||||
where: { id: payload.sid },
|
where: { id: payload.sid },
|
||||||
include: { user: true },
|
include: { user: true },
|
||||||
@@ -92,37 +99,40 @@ export class AuthService {
|
|||||||
session.revokedAt ||
|
session.revokedAt ||
|
||||||
session.expiresAt <= new Date()
|
session.expiresAt <= new Date()
|
||||||
) {
|
) {
|
||||||
if (session && !session.revokedAt)
|
if (session && !session.revokedAt) {
|
||||||
await this.prisma.session.delete({ where: { id: session.id } });
|
await this.prisma.session.delete({ where: { id: session.id } });
|
||||||
|
}
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
}
|
}
|
||||||
if (session.refreshTokenHash !== this.hash(token))
|
if (session.refreshTokenHash !== this.hash(token)) {
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
|
}
|
||||||
return this.rotateSession(session, session.refreshTokenHash);
|
return this.rotateSession(session, session.refreshTokenHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
async logout(token?: string): Promise<void> {
|
async logout(token?: string): Promise<void> {
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
|
let payload: RefreshPayload;
|
||||||
try {
|
try {
|
||||||
const payload = await this.jwt.verifyAsync<RefreshPayload>(token, {
|
payload = await this.jwt.verifyAsync<RefreshPayload>(token, {
|
||||||
algorithms: ['HS256'],
|
algorithms: ['HS256'],
|
||||||
});
|
});
|
||||||
if (payload.type !== 'refresh') return;
|
|
||||||
const session = await this.prisma.session.findUnique({
|
|
||||||
where: { id: payload.sid },
|
|
||||||
});
|
|
||||||
if (
|
|
||||||
session &&
|
|
||||||
!session.revokedAt &&
|
|
||||||
session.refreshTokenHash === this.hash(token)
|
|
||||||
) {
|
|
||||||
await this.prisma.session.update({
|
|
||||||
where: { id: session.id },
|
|
||||||
data: { revokedAt: new Date() },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
// Logout is intentionally idempotent.
|
return;
|
||||||
|
}
|
||||||
|
if (payload.type !== 'refresh') return;
|
||||||
|
const session = await this.prisma.session.findUnique({
|
||||||
|
where: { id: payload.sid },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
session &&
|
||||||
|
!session.revokedAt &&
|
||||||
|
session.refreshTokenHash === this.hash(token)
|
||||||
|
) {
|
||||||
|
await this.prisma.session.update({
|
||||||
|
where: { id: session.id },
|
||||||
|
data: { revokedAt: new Date() },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +148,7 @@ export class AuthService {
|
|||||||
|
|
||||||
private async createSession(
|
private async createSession(
|
||||||
user: User,
|
user: User,
|
||||||
): Promise<{ user: AuthUser; accessToken: string; refreshToken: string }> {
|
): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
|
||||||
const session = await this.prisma.session.create({
|
const session = await this.prisma.session.create({
|
||||||
data: {
|
data: {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
@@ -153,7 +163,7 @@ export class AuthService {
|
|||||||
private async rotateSession(
|
private async rotateSession(
|
||||||
session: Session & { user: User },
|
session: Session & { user: User },
|
||||||
expectedRefreshTokenHash?: string,
|
expectedRefreshTokenHash?: string,
|
||||||
): Promise<{ user: AuthUser; accessToken: string; refreshToken: string }> {
|
): Promise<{ accessToken: string; refreshToken: string; user: AuthUser }> {
|
||||||
const refreshToken = await this.jwt.signAsync(
|
const refreshToken = await this.jwt.signAsync(
|
||||||
{
|
{
|
||||||
sub: session.userId,
|
sub: session.userId,
|
||||||
@@ -172,8 +182,9 @@ export class AuthService {
|
|||||||
where: { id: session.id, refreshTokenHash: expectedRefreshTokenHash },
|
where: { id: session.id, refreshTokenHash: expectedRefreshTokenHash },
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
if (updated.count !== 1)
|
if (updated.count !== EXPECTED_ROTATED_SESSIONS) {
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.prisma.session.update({ where: { id: session.id }, data });
|
await this.prisma.session.update({ where: { id: session.id }, data });
|
||||||
}
|
}
|
||||||
@@ -187,10 +198,6 @@ export class AuthService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeEmail(email: string): string {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
private hash(token: string): string {
|
private hash(token: string): string {
|
||||||
return createHash('sha256').update(token).digest('hex');
|
return createHash('sha256').update(token).digest('hex');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id: string;
|
|
||||||
email: string;
|
email: string;
|
||||||
|
id: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AccessPayload {
|
export interface AccessPayload {
|
||||||
sub: string;
|
|
||||||
sid: string;
|
sid: string;
|
||||||
|
sub: string;
|
||||||
type: 'access';
|
type: 'access';
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RefreshPayload {
|
export interface RefreshPayload {
|
||||||
sub: string;
|
|
||||||
sid: string;
|
|
||||||
type: 'refresh';
|
|
||||||
jti: string;
|
jti: string;
|
||||||
|
sid: string;
|
||||||
|
sub: string;
|
||||||
|
type: 'refresh';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ import { Module } from '@nestjs/common';
|
|||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
|
|
||||||
import { Environment } from '../../config/env.validation';
|
import { Environment } from '../../config/env.validation';
|
||||||
import { AuthController } from './presentation/auth.controller';
|
|
||||||
import { AuthService } from './application/auth.service';
|
import { AuthService } from './application/auth.service';
|
||||||
import { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
|
||||||
import { JwtStrategy } from './infrastructure/jwt.strategy';
|
import { JwtStrategy } from './infrastructure/jwt.strategy';
|
||||||
|
import { AuthController } from './presentation/auth.controller';
|
||||||
|
import { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { PassportStrategy } from '@nestjs/passport';
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
|
||||||
import { Environment } from '../../../config/env.validation';
|
import { Environment } from '../../../config/env.validation';
|
||||||
import { AccessPayload } from '../application/auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
|
|
||||||
@@ -17,8 +18,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
validate(payload: AccessPayload): AccessPayload {
|
validate(payload: AccessPayload): AccessPayload {
|
||||||
if (payload.type !== 'access')
|
if (payload.type !== 'access') {
|
||||||
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
|
}
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
import { HTTP_CODE_METADATA } from '@nestjs/common/constants';
|
|
||||||
|
|
||||||
jest.mock('../application/auth.service', () => ({
|
|
||||||
AuthService: class AuthService {},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { AuthController } from './auth.controller';
|
|
||||||
|
|
||||||
describe('AuthController response statuses', () => {
|
|
||||||
it.each(['register', 'login', 'refresh'] as const)(
|
|
||||||
'%s explicitly returns HTTP 200',
|
|
||||||
(handler) => {
|
|
||||||
// Nest stores @HttpCode metadata on the unbound handler function.
|
|
||||||
const handlerTarget = Object.getOwnPropertyDescriptor(
|
|
||||||
AuthController.prototype,
|
|
||||||
handler,
|
|
||||||
)?.value as object;
|
|
||||||
expect(Reflect.getMetadata(HTTP_CODE_METADATA, handlerTarget)).toBe(200);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { Request, Response } from 'express';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
@@ -17,11 +19,11 @@ import {
|
|||||||
ApiProperty,
|
ApiProperty,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import type { Request, Response } from 'express';
|
|
||||||
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { CredentialsDto } from './auth.dto';
|
|
||||||
import { AuthService } from '../application/auth.service';
|
import { AuthService } from '../application/auth.service';
|
||||||
import { AccessPayload } from '../application/auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
|
import { CredentialsDto } from './auth.dto';
|
||||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
|
||||||
const REFRESH_COOKIE = 'refresh_token';
|
const REFRESH_COOKIE = 'refresh_token';
|
||||||
@@ -87,7 +89,7 @@ export class AuthController {
|
|||||||
if (!token) throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
if (!token) throw new UnauthorizedException({ code: 'UNAUTHORIZED' });
|
||||||
return this.respond(response, await this.auth.refresh(token));
|
return this.respond(response, await this.auth.refresh(token));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.clearCookie(response);
|
if (error instanceof UnauthorizedException) this.clearCookie(response);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -115,9 +117,9 @@ export class AuthController {
|
|||||||
private respond(
|
private respond(
|
||||||
response: Response,
|
response: Response,
|
||||||
result: {
|
result: {
|
||||||
user: { id: string; email: string };
|
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
refreshToken: string;
|
refreshToken: string;
|
||||||
|
user: { email: string; id: string };
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
response.cookie(REFRESH_COOKIE, result.refreshToken, this.cookieOptions());
|
response.cookie(REFRESH_COOKIE, result.refreshToken, this.cookieOptions());
|
||||||
@@ -129,6 +131,7 @@ export class AuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private refreshToken(request: Request): string | undefined {
|
private refreshToken(request: Request): string | undefined {
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The cookie name is a fixed application constant; its value is narrowed below.
|
||||||
const token: unknown = request.cookies?.[REFRESH_COOKIE];
|
const token: unknown = request.cookies?.[REFRESH_COOKIE];
|
||||||
return typeof token === 'string' ? token : undefined;
|
return typeof token === 'string' ? token : undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import {
|
|||||||
ValidatorConstraint,
|
ValidatorConstraint,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
|
const EMAIL_PART_COUNT = 2;
|
||||||
|
const FIRST_CHARACTER_INDEX = 0;
|
||||||
|
|
||||||
const MAX_EMAIL_LENGTH = 254;
|
const MAX_EMAIL_LENGTH = 254;
|
||||||
const ASCII_SPACE = 32;
|
const ASCII_SPACE = 32;
|
||||||
const ASCII_DELETE = 127;
|
const ASCII_DELETE = 127;
|
||||||
@@ -19,18 +22,19 @@ class EmailConstraint {
|
|||||||
return (
|
return (
|
||||||
typeof value === 'string' &&
|
typeof value === 'string' &&
|
||||||
value.length <= MAX_EMAIL_LENGTH &&
|
value.length <= MAX_EMAIL_LENGTH &&
|
||||||
value.split('@').length === 2 &&
|
value.split('@').length === EMAIL_PART_COUNT &&
|
||||||
!value
|
!value
|
||||||
.split('')
|
.split('')
|
||||||
.some(
|
.some(
|
||||||
(character) =>
|
(character) =>
|
||||||
/\s/.test(character) ||
|
/\s/.test(character) ||
|
||||||
character.charCodeAt(0) < ASCII_SPACE ||
|
character.charCodeAt(FIRST_CHARACTER_INDEX) < ASCII_SPACE ||
|
||||||
character.charCodeAt(0) === ASCII_DELETE,
|
character.charCodeAt(FIRST_CHARACTER_INDEX) === ASCII_DELETE,
|
||||||
) &&
|
) &&
|
||||||
value.split('@').every(Boolean)
|
value.split('@').every(Boolean)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultMessage(): string {
|
defaultMessage(): string {
|
||||||
return 'must be a valid email address';
|
return 'must be a valid email address';
|
||||||
}
|
}
|
||||||
@@ -44,6 +48,7 @@ class PasswordBytesConstraint {
|
|||||||
Buffer.byteLength(value, 'utf8') <= MAX_PASSWORD_BYTES
|
Buffer.byteLength(value, 'utf8') <= MAX_PASSWORD_BYTES
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultMessage(): string {
|
defaultMessage(): string {
|
||||||
return 'must not exceed 72 UTF-8 bytes';
|
return 'must not exceed 72 UTF-8 bytes';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { ExecutionContext, Injectable } from '@nestjs/common';
|
import { ExecutionContext, Injectable } from '@nestjs/common';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
import { RequestContextService } from '../../../common/logging/request-context.service';
|
import { RequestContextService } from '../../../common/logging/request-context.service';
|
||||||
import { AccessPayload } from '../application/auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
|
|
||||||
@@ -14,8 +15,9 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
|||||||
const request = context
|
const request = context
|
||||||
.switchToHttp()
|
.switchToHttp()
|
||||||
.getRequest<{ user?: AccessPayload }>();
|
.getRequest<{ user?: AccessPayload }>();
|
||||||
if (request.user?.sub)
|
if (request.user?.sub) {
|
||||||
this.requestContext.set({ userId: request.user.sub });
|
this.requestContext.set({ userId: request.user.sub });
|
||||||
|
}
|
||||||
return Boolean(allowed);
|
return Boolean(allowed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,26 @@
|
|||||||
import {
|
|
||||||
MAX_CARD_NAME_LENGTH,
|
|
||||||
MAX_OPERATION_DESCRIPTION_LENGTH,
|
|
||||||
} from '../domain/bank-card-limits';
|
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
ConflictException,
|
ConflictException,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
|
|
||||||
|
import { ISO_DATE_LENGTH, ISO_DATE_START } from '../../../../common/time';
|
||||||
|
import {
|
||||||
|
MAX_CARD_NAME_LENGTH,
|
||||||
|
MAX_OPERATION_DESCRIPTION_LENGTH,
|
||||||
|
} from '../domain/bank-card-limits';
|
||||||
|
import { isCalendarDate, moscowToday } from '../domain/bank-card.calculations';
|
||||||
|
import { parseRubMoney } from '../domain/rub-money';
|
||||||
import {
|
import {
|
||||||
bankPaymentSystems,
|
bankPaymentSystems,
|
||||||
BankPeriodQueryDto,
|
BankPeriodQueryDto,
|
||||||
CreateBankCardDto,
|
CreateBankCardDto,
|
||||||
CreateBankOperationDto,
|
CreateBankOperationDto,
|
||||||
} from '../presentation/bank-card.dto';
|
} from '../presentation/bank-card.dto';
|
||||||
import { isCalendarDate, moscowToday } from '../domain/bank-card.calculations';
|
|
||||||
import { parseRubMoney } from '../domain/rub-money';
|
const NEXT_MONTH_OFFSET = 1;
|
||||||
|
const PREVIOUS_MONTH_LAST_DAY = 0;
|
||||||
|
|
||||||
export const BankErrorCode = {
|
export const BankErrorCode = {
|
||||||
InvalidInput: 'BANK_INVALID_INPUT',
|
InvalidInput: 'BANK_INVALID_INPUT',
|
||||||
@@ -44,8 +49,8 @@ export function periodBounds(query: BankPeriodQueryDto) {
|
|||||||
const from = `${query.month}-01`;
|
const from = `${query.month}-01`;
|
||||||
if (!isCalendarDate(from)) return fail();
|
if (!isCalendarDate(from)) return fail();
|
||||||
const end = new Date(`${from}T00:00:00Z`);
|
const end = new Date(`${from}T00:00:00Z`);
|
||||||
end.setUTCMonth(end.getUTCMonth() + 1, 0);
|
end.setUTCMonth(end.getUTCMonth() + NEXT_MONTH_OFFSET, PREVIOUS_MONTH_LAST_DAY);
|
||||||
return { from, to: end.toISOString().slice(0, 10) };
|
return { from, to: end.toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH) };
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
query.month ||
|
query.month ||
|
||||||
@@ -54,8 +59,9 @@ export function periodBounds(query: BankPeriodQueryDto) {
|
|||||||
!isCalendarDate(query.from) ||
|
!isCalendarDate(query.from) ||
|
||||||
!isCalendarDate(query.to) ||
|
!isCalendarDate(query.to) ||
|
||||||
query.from > query.to
|
query.from > query.to
|
||||||
)
|
) {
|
||||||
return fail();
|
return fail();
|
||||||
|
}
|
||||||
return { from: query.from, to: query.to };
|
return { from: query.from, to: query.to };
|
||||||
}
|
}
|
||||||
export function conflict(
|
export function conflict(
|
||||||
@@ -93,8 +99,9 @@ export function currentDate(value: string) {
|
|||||||
if (value > moscowToday()) fail(BankErrorCode.InvalidDate);
|
if (value > moscowToday()) fail(BankErrorCode.InvalidDate);
|
||||||
}
|
}
|
||||||
export function name(value: string, max: number) {
|
export function name(value: string, max: number) {
|
||||||
if (typeof value !== 'string' || !value.trim() || value.trim().length > max)
|
if (typeof value !== 'string' || !value.trim() || value.trim().length > max) {
|
||||||
fail();
|
fail();
|
||||||
|
}
|
||||||
return value.trim();
|
return value.trim();
|
||||||
}
|
}
|
||||||
export function cardInput(dto: CreateBankCardDto) {
|
export function cardInput(dto: CreateBankCardDto) {
|
||||||
@@ -104,8 +111,9 @@ export function cardInput(dto: CreateBankCardDto) {
|
|||||||
if (
|
if (
|
||||||
dto.paymentSystem != null &&
|
dto.paymentSystem != null &&
|
||||||
!bankPaymentSystems.some((system) => system === dto.paymentSystem)
|
!bankPaymentSystems.some((system) => system === dto.paymentSystem)
|
||||||
)
|
) {
|
||||||
fail();
|
fail();
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
...(dto.paymentSystem == null ? {} : { paymentSystem: dto.paymentSystem }),
|
...(dto.paymentSystem == null ? {} : { paymentSystem: dto.paymentSystem }),
|
||||||
name: name(dto.name, MAX_CARD_NAME_LENGTH),
|
name: name(dto.name, MAX_CARD_NAME_LENGTH),
|
||||||
@@ -120,8 +128,9 @@ export function operationInput(dto: CreateBankOperationDto) {
|
|||||||
dto.description != null &&
|
dto.description != null &&
|
||||||
(typeof dto.description !== 'string' ||
|
(typeof dto.description !== 'string' ||
|
||||||
dto.description.length > MAX_OPERATION_DESCRIPTION_LENGTH)
|
dto.description.length > MAX_OPERATION_DESCRIPTION_LENGTH)
|
||||||
)
|
) {
|
||||||
fail();
|
fail();
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
kind: dto.kind,
|
kind: dto.kind,
|
||||||
cardId: dto.cardId,
|
cardId: dto.cardId,
|
||||||
|
|||||||
@@ -1,24 +1,27 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
import { BankCard, Prisma } from '../../../../../generated/prisma/client';
|
import { BankCard, Prisma } from '../../../../../generated/prisma/client';
|
||||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import { bankBalance } from '../domain/bank-card.calculations';
|
||||||
|
import { rubMoney } from '../domain/rub-money';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
import {
|
import {
|
||||||
BankCardDto,
|
BankCardDto,
|
||||||
CreateBankCardDto,
|
CreateBankCardDto,
|
||||||
UpdateBankCardDto,
|
UpdateBankCardDto,
|
||||||
} from '../presentation/bank-card.dto';
|
} from '../presentation/bank-card.dto';
|
||||||
import { bankBalance } from '../domain/bank-card.calculations';
|
|
||||||
import { rubMoney } from '../domain/rub-money';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
cardInput,
|
|
||||||
BankErrorCode,
|
BankErrorCode,
|
||||||
|
cardInput,
|
||||||
conflict,
|
conflict,
|
||||||
currentDate,
|
currentDate,
|
||||||
fail,
|
fail,
|
||||||
fingerprint,
|
fingerprint,
|
||||||
missing,
|
missing,
|
||||||
} from './bank-card-input';
|
} from './bank-card-input';
|
||||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
|
||||||
|
const EXPECTED_UPDATED_CARDS = 1;
|
||||||
|
|
||||||
type Tx = Prisma.TransactionClient;
|
type Tx = Prisma.TransactionClient;
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BankCardsService {
|
export class BankCardsService {
|
||||||
@@ -26,6 +29,7 @@ export class BankCardsService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly repository: BankCardsRepository,
|
private readonly repository: BankCardsRepository,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async cardView(tx: Tx, card: BankCard): Promise<BankCardDto> {
|
private async cardView(tx: Tx, card: BankCard): Promise<BankCardDto> {
|
||||||
const rows = await tx.bankCardOperation.findMany({
|
const rows = await tx.bankCardOperation.findMany({
|
||||||
where: {
|
where: {
|
||||||
@@ -47,6 +51,7 @@ export class BankCardsService {
|
|||||||
archivedAt: card.archivedAt?.toISOString() ?? null,
|
archivedAt: card.archivedAt?.toISOString() ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
list(userId: string, includeArchived = false) {
|
list(userId: string, includeArchived = false) {
|
||||||
return this.prisma.$transaction(async (tx) =>
|
return this.prisma.$transaction(async (tx) =>
|
||||||
Promise.all(
|
Promise.all(
|
||||||
@@ -59,11 +64,13 @@ export class BankCardsService {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
get(userId: string, id: string) {
|
get(userId: string, id: string) {
|
||||||
return this.prisma.$transaction(async (tx) =>
|
return this.prisma.$transaction(async (tx) =>
|
||||||
this.cardView(tx, await this.repository.card(tx, userId, id)),
|
this.cardView(tx, await this.repository.card(tx, userId, id)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
createCard(userId: string, dto: CreateBankCardDto) {
|
createCard(userId: string, dto: CreateBankCardDto) {
|
||||||
const input = cardInput(dto),
|
const input = cardInput(dto),
|
||||||
hash = fingerprint(input);
|
hash = fingerprint(input);
|
||||||
@@ -71,8 +78,10 @@ export class BankCardsService {
|
|||||||
const existing = await tx.bankCard.findUnique({ where: { id: dto.id } });
|
const existing = await tx.bankCard.findUnique({ where: { id: dto.id } });
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (existing.userId !== userId) missing();
|
if (existing.userId !== userId) missing();
|
||||||
if (existing.createFingerprint !== hash)
|
// eslint-disable-next-line security/detect-possible-timing-attacks -- This compares an idempotency fingerprint after ownership validation, not a secret.
|
||||||
|
if (existing.createFingerprint !== hash) {
|
||||||
conflict(BankErrorCode.IntentConflict);
|
conflict(BankErrorCode.IntentConflict);
|
||||||
|
}
|
||||||
return this.cardView(tx, existing);
|
return this.cardView(tx, existing);
|
||||||
}
|
}
|
||||||
currentDate(input.openingDate);
|
currentDate(input.openingDate);
|
||||||
@@ -85,6 +94,7 @@ export class BankCardsService {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
updateCard(userId: string, id: string, dto: UpdateBankCardDto) {
|
updateCard(userId: string, id: string, dto: UpdateBankCardDto) {
|
||||||
return this.repository.write(async (tx) => {
|
return this.repository.write(async (tx) => {
|
||||||
const previous = await this.repository.card(tx, userId, id);
|
const previous = await this.repository.card(tx, userId, id);
|
||||||
@@ -93,17 +103,17 @@ export class BankCardsService {
|
|||||||
id,
|
id,
|
||||||
name: dto.name ?? previous.name,
|
name: dto.name ?? previous.name,
|
||||||
bankName:
|
bankName:
|
||||||
dto.bankName === undefined
|
dto.bankName === undefined ?
|
||||||
? (previous.bankName ?? undefined)
|
(previous.bankName ?? undefined) :
|
||||||
: (dto.bankName ?? undefined),
|
(dto.bankName ?? undefined),
|
||||||
lastFour:
|
lastFour:
|
||||||
dto.lastFour === undefined
|
dto.lastFour === undefined ?
|
||||||
? (previous.lastFour ?? undefined)
|
(previous.lastFour ?? undefined) :
|
||||||
: (dto.lastFour ?? undefined),
|
(dto.lastFour ?? undefined),
|
||||||
paymentSystem:
|
paymentSystem:
|
||||||
dto.paymentSystem === undefined
|
dto.paymentSystem === undefined ?
|
||||||
? previous.paymentSystem
|
previous.paymentSystem :
|
||||||
: dto.paymentSystem,
|
dto.paymentSystem,
|
||||||
openingBalance:
|
openingBalance:
|
||||||
dto.openingBalance ?? rubMoney(previous.openingBalanceKopecks),
|
dto.openingBalance ?? rubMoney(previous.openingBalanceKopecks),
|
||||||
openingDate: dto.openingDate ?? previous.openingDate,
|
openingDate: dto.openingDate ?? previous.openingDate,
|
||||||
@@ -111,8 +121,9 @@ export class BankCardsService {
|
|||||||
const financial =
|
const financial =
|
||||||
input.openingBalanceKopecks !== previous.openingBalanceKopecks ||
|
input.openingBalanceKopecks !== previous.openingBalanceKopecks ||
|
||||||
input.openingDate !== previous.openingDate;
|
input.openingDate !== previous.openingDate;
|
||||||
if (financial && previous.archivedAt)
|
if (financial && previous.archivedAt) {
|
||||||
conflict(BankErrorCode.CardArchived);
|
conflict(BankErrorCode.CardArchived);
|
||||||
|
}
|
||||||
currentDate(input.openingDate);
|
currentDate(input.openingDate);
|
||||||
if (
|
if (
|
||||||
await tx.bankCardOperation.findFirst({
|
await tx.bankCardOperation.findFirst({
|
||||||
@@ -123,24 +134,25 @@ export class BankCardsService {
|
|||||||
OR: [{ cardId: id }, { targetCardId: id }],
|
OR: [{ cardId: id }, { targetCardId: id }],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
)
|
) {
|
||||||
fail(BankErrorCode.OpeningDateConflict);
|
fail(BankErrorCode.OpeningDateConflict);
|
||||||
|
}
|
||||||
const changed = await tx.bankCard.updateMany({
|
const changed = await tx.bankCard.updateMany({
|
||||||
where: { id, userId, version: dto.version },
|
where: { id, userId, version: dto.version },
|
||||||
data: {
|
data: {
|
||||||
...input,
|
...input,
|
||||||
paymentSystem: input.paymentSystem ?? null,
|
paymentSystem: input.paymentSystem ?? null,
|
||||||
version: { increment: 1 },
|
version: { increment: 1 },
|
||||||
...(dto.archived === undefined
|
...(dto.archived === undefined ?
|
||||||
? {}
|
{} :
|
||||||
: {
|
{
|
||||||
archivedAt: dto.archived
|
archivedAt: dto.archived ?
|
||||||
? (previous.archivedAt ?? new Date())
|
(previous.archivedAt ?? new Date()) :
|
||||||
: null,
|
null,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (changed.count !== 1) conflict();
|
if (changed.count !== EXPECTED_UPDATED_CARDS) conflict();
|
||||||
return this.cardView(tx, await this.repository.card(tx, userId, id));
|
return this.cardView(tx, await this.repository.card(tx, userId, id));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
import { BankOperationKind } from '../domain/bank-operation-kind';
|
|
||||||
import { GoneException, Injectable } from '@nestjs/common';
|
import { GoneException, Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BankCardOperation,
|
BankCardOperation,
|
||||||
Prisma,
|
Prisma,
|
||||||
} from '../../../../../generated/prisma/client';
|
} from '../../../../../generated/prisma/client';
|
||||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import { FIRST_PAGE } from '../domain/bank-card-limits';
|
||||||
|
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||||
|
import { rubMoney, ZERO_KOPECKS } from '../domain/rub-money';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
import {
|
import {
|
||||||
BankOperationDto,
|
BankOperationDto,
|
||||||
DEFAULT_BANK_PAGE_SIZE,
|
|
||||||
BankOperationsQueryDto,
|
BankOperationsQueryDto,
|
||||||
BankPageQueryDto,
|
BankPageQueryDto,
|
||||||
CreateBankOperationDto,
|
CreateBankOperationDto,
|
||||||
|
DEFAULT_BANK_PAGE_SIZE,
|
||||||
UpdateBankOperationDto,
|
UpdateBankOperationDto,
|
||||||
} from '../presentation/bank-card.dto';
|
} from '../presentation/bank-card.dto';
|
||||||
import { rubMoney } from '../domain/rub-money';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BankErrorCode,
|
BankErrorCode,
|
||||||
conflict,
|
conflict,
|
||||||
@@ -25,7 +27,9 @@ import {
|
|||||||
operationInput,
|
operationInput,
|
||||||
periodBounds,
|
periodBounds,
|
||||||
} from './bank-card-input';
|
} from './bank-card-input';
|
||||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
|
||||||
|
const EXPECTED_UPDATED_ROWS = 1;
|
||||||
|
|
||||||
type Tx = Prisma.TransactionClient;
|
type Tx = Prisma.TransactionClient;
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BankOperationsService {
|
export class BankOperationsService {
|
||||||
@@ -33,34 +37,35 @@ export class BankOperationsService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly repository: BankCardsRepository,
|
private readonly repository: BankCardsRepository,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async operationView(
|
private async operationView(
|
||||||
tx: Tx,
|
tx: Tx,
|
||||||
row: BankCardOperation,
|
row: BankCardOperation,
|
||||||
): Promise<BankOperationDto> {
|
): Promise<BankOperationDto> {
|
||||||
const card = await this.repository.card(tx, row.userId, row.cardId);
|
const card = await this.repository.card(tx, row.userId, row.cardId);
|
||||||
const target = row.targetCardId
|
const target = row.targetCardId ?
|
||||||
? await this.repository.card(tx, row.userId, row.targetCardId)
|
await this.repository.card(tx, row.userId, row.targetCardId) :
|
||||||
: null;
|
null;
|
||||||
const source = row.originalExpenseId
|
const source = row.originalExpenseId ?
|
||||||
? await this.repository.operation(tx, row.userId, row.originalExpenseId)
|
await this.repository.operation(tx, row.userId, row.originalExpenseId) :
|
||||||
: null;
|
null;
|
||||||
const categoryId = source?.categoryId ?? row.categoryId;
|
const categoryId = source?.categoryId ?? row.categoryId;
|
||||||
const category = categoryId
|
const category = categoryId ?
|
||||||
? await tx.expenseCategory.findFirst({
|
await tx.expenseCategory.findFirst({
|
||||||
where: { id: categoryId, userId: row.userId },
|
where: { id: categoryId, userId: row.userId },
|
||||||
})
|
}) :
|
||||||
: null;
|
null;
|
||||||
const refunds =
|
const refunds =
|
||||||
row.kind === BankOperationKind.Expense || source
|
row.kind === BankOperationKind.Expense || source ?
|
||||||
? await tx.bankCardOperation.findMany({
|
await tx.bankCardOperation.findMany({
|
||||||
where: {
|
where: {
|
||||||
userId: row.userId,
|
userId: row.userId,
|
||||||
originalExpenseId: source?.id ?? row.id,
|
originalExpenseId: source?.id ?? row.id,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
...(source ? { id: { not: row.id } } : {}),
|
...(source ? { id: { not: row.id } } : {}),
|
||||||
},
|
},
|
||||||
})
|
}) :
|
||||||
: [];
|
[];
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
kind: row.kind as BankOperationDto['kind'],
|
kind: row.kind as BankOperationDto['kind'],
|
||||||
@@ -73,18 +78,19 @@ export class BankOperationsService {
|
|||||||
originalExpenseId: row.originalExpenseId,
|
originalExpenseId: row.originalExpenseId,
|
||||||
amount: rubMoney(row.amountKopecks),
|
amount: rubMoney(row.amountKopecks),
|
||||||
availableRefund:
|
availableRefund:
|
||||||
row.kind === BankOperationKind.Expense || source
|
row.kind === BankOperationKind.Expense || source ?
|
||||||
? rubMoney(
|
rubMoney(
|
||||||
(source?.amountKopecks ?? row.amountKopecks) -
|
(source?.amountKopecks ?? row.amountKopecks) -
|
||||||
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n),
|
refunds.reduce((sum, r) => sum + r.amountKopecks, ZERO_KOPECKS),
|
||||||
)
|
) :
|
||||||
: null,
|
null,
|
||||||
date: row.date,
|
date: row.date,
|
||||||
description: row.description,
|
description: row.description,
|
||||||
version: row.version,
|
version: row.version,
|
||||||
createdAt: row.createdAt.toISOString(),
|
createdAt: row.createdAt.toISOString(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async validateOperation(
|
private async validateOperation(
|
||||||
tx: Tx,
|
tx: Tx,
|
||||||
userId: string,
|
userId: string,
|
||||||
@@ -102,23 +108,26 @@ export class BankOperationsService {
|
|||||||
if (
|
if (
|
||||||
(id === input.cardId || id === input.targetCardId) &&
|
(id === input.cardId || id === input.targetCardId) &&
|
||||||
input.date < card.openingDate
|
input.date < card.openingDate
|
||||||
)
|
) {
|
||||||
fail(BankErrorCode.InvalidDate);
|
fail(BankErrorCode.InvalidDate);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
old &&
|
old &&
|
||||||
(old.kind !== input.kind ||
|
(old.kind !== input.kind ||
|
||||||
old.originalExpenseId !== input.originalExpenseId)
|
old.originalExpenseId !== input.originalExpenseId)
|
||||||
)
|
) {
|
||||||
fail(BankErrorCode.ImmutableOperation);
|
fail(BankErrorCode.ImmutableOperation);
|
||||||
|
}
|
||||||
if (input.kind === BankOperationKind.Transfer) {
|
if (input.kind === BankOperationKind.Transfer) {
|
||||||
if (
|
if (
|
||||||
!input.targetCardId ||
|
!input.targetCardId ||
|
||||||
input.targetCardId === input.cardId ||
|
input.targetCardId === input.cardId ||
|
||||||
input.categoryId ||
|
input.categoryId ||
|
||||||
input.originalExpenseId
|
input.originalExpenseId
|
||||||
)
|
) {
|
||||||
fail();
|
fail();
|
||||||
|
}
|
||||||
} else if (input.targetCardId) fail();
|
} else if (input.targetCardId) fail();
|
||||||
if (input.kind === BankOperationKind.Expense) {
|
if (input.kind === BankOperationKind.Expense) {
|
||||||
if (input.originalExpenseId) fail();
|
if (input.originalExpenseId) fail();
|
||||||
@@ -133,11 +142,13 @@ export class BankOperationsService {
|
|||||||
!(await tx.expenseCategory.findFirst({
|
!(await tx.expenseCategory.findFirst({
|
||||||
where: { userId, id: input.categoryId },
|
where: { userId, id: input.categoryId },
|
||||||
}))
|
}))
|
||||||
)
|
) {
|
||||||
missing();
|
missing();
|
||||||
|
}
|
||||||
} else if (input.categoryId) fail();
|
} else if (input.categoryId) fail();
|
||||||
if (input.kind !== BankOperationKind.Refund && input.originalExpenseId)
|
if (input.kind !== BankOperationKind.Refund && input.originalExpenseId) {
|
||||||
fail();
|
fail();
|
||||||
|
}
|
||||||
if (input.kind === BankOperationKind.Refund) {
|
if (input.kind === BankOperationKind.Refund) {
|
||||||
if (!input.originalExpenseId) fail();
|
if (!input.originalExpenseId) fail();
|
||||||
const source = await this.repository.operation(
|
const source = await this.repository.operation(
|
||||||
@@ -149,8 +160,9 @@ export class BankOperationsService {
|
|||||||
source.deletedAt ||
|
source.deletedAt ||
|
||||||
source.kind !== BankOperationKind.Expense ||
|
source.kind !== BankOperationKind.Expense ||
|
||||||
source.cardId !== input.cardId
|
source.cardId !== input.cardId
|
||||||
)
|
) {
|
||||||
fail(BankErrorCode.InvalidRefund);
|
fail(BankErrorCode.InvalidRefund);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
(
|
(
|
||||||
await tx.bankCardOperation.updateMany({
|
await tx.bankCardOperation.updateMany({
|
||||||
@@ -162,9 +174,10 @@ export class BankOperationsService {
|
|||||||
},
|
},
|
||||||
data: { version: { increment: 1 } },
|
data: { version: { increment: 1 } },
|
||||||
})
|
})
|
||||||
).count !== 1
|
).count !== EXPECTED_UPDATED_ROWS
|
||||||
)
|
) {
|
||||||
conflict();
|
conflict();
|
||||||
|
}
|
||||||
const refunds = await tx.bankCardOperation.findMany({
|
const refunds = await tx.bankCardOperation.findMany({
|
||||||
where: {
|
where: {
|
||||||
userId,
|
userId,
|
||||||
@@ -175,11 +188,12 @@ export class BankOperationsService {
|
|||||||
});
|
});
|
||||||
if (input.date < source.date) fail(BankErrorCode.InvalidDate);
|
if (input.date < source.date) fail(BankErrorCode.InvalidDate);
|
||||||
if (
|
if (
|
||||||
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n) +
|
refunds.reduce((sum, r) => sum + r.amountKopecks, ZERO_KOPECKS) +
|
||||||
input.amountKopecks >
|
input.amountKopecks >
|
||||||
source.amountKopecks
|
source.amountKopecks
|
||||||
)
|
) {
|
||||||
conflict(BankErrorCode.RefundLimit);
|
conflict(BankErrorCode.RefundLimit);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (old?.kind === BankOperationKind.Expense) {
|
if (old?.kind === BankOperationKind.Expense) {
|
||||||
const refunds = await tx.bankCardOperation.findMany({
|
const refunds = await tx.bankCardOperation.findMany({
|
||||||
@@ -189,12 +203,14 @@ export class BankOperationsService {
|
|||||||
refunds.length &&
|
refunds.length &&
|
||||||
(input.cardId !== old.cardId ||
|
(input.cardId !== old.cardId ||
|
||||||
refunds.some((row) => row.date < input.date) ||
|
refunds.some((row) => row.date < input.date) ||
|
||||||
refunds.reduce((sum, row) => sum + row.amountKopecks, 0n) >
|
refunds.reduce((sum, row) => sum + row.amountKopecks, ZERO_KOPECKS) >
|
||||||
input.amountKopecks)
|
input.amountKopecks)
|
||||||
)
|
) {
|
||||||
conflict(BankErrorCode.DependentRefunds);
|
conflict(BankErrorCode.DependentRefunds);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
createOperation(userId: string, dto: CreateBankOperationDto) {
|
createOperation(userId: string, dto: CreateBankOperationDto) {
|
||||||
const normalized = operationInput(dto),
|
const normalized = operationInput(dto),
|
||||||
hash = fingerprint(normalized);
|
hash = fingerprint(normalized);
|
||||||
@@ -204,10 +220,13 @@ export class BankOperationsService {
|
|||||||
});
|
});
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (existing.userId !== userId) missing();
|
if (existing.userId !== userId) missing();
|
||||||
if (existing.createFingerprint !== hash)
|
// eslint-disable-next-line security/detect-possible-timing-attacks -- This compares an idempotency fingerprint after ownership validation, not a secret.
|
||||||
|
if (existing.createFingerprint !== hash) {
|
||||||
conflict(BankErrorCode.IntentConflict);
|
conflict(BankErrorCode.IntentConflict);
|
||||||
if (existing.deletedAt)
|
}
|
||||||
|
if (existing.deletedAt) {
|
||||||
throw new GoneException({ code: BankErrorCode.OperationDeleted });
|
throw new GoneException({ code: BankErrorCode.OperationDeleted });
|
||||||
|
}
|
||||||
return this.operationView(tx, existing);
|
return this.operationView(tx, existing);
|
||||||
}
|
}
|
||||||
const input = { ...normalized };
|
const input = { ...normalized };
|
||||||
@@ -220,6 +239,7 @@ export class BankOperationsService {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getOperation(userId: string, id: string) {
|
getOperation(userId: string, id: string) {
|
||||||
return this.prisma.$transaction(async (tx) => {
|
return this.prisma.$transaction(async (tx) => {
|
||||||
const row = await this.repository.operation(tx, userId, id);
|
const row = await this.repository.operation(tx, userId, id);
|
||||||
@@ -227,6 +247,7 @@ export class BankOperationsService {
|
|||||||
return this.operationView(tx, row);
|
return this.operationView(tx, row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
updateOperation(userId: string, id: string, dto: UpdateBankOperationDto) {
|
updateOperation(userId: string, id: string, dto: UpdateBankOperationDto) {
|
||||||
return this.repository.write(async (tx) => {
|
return this.repository.write(async (tx) => {
|
||||||
const old = await this.repository.operation(tx, userId, id);
|
const old = await this.repository.operation(tx, userId, id);
|
||||||
@@ -251,30 +272,34 @@ export class BankOperationsService {
|
|||||||
where: { id, userId, version: dto.version, deletedAt: null },
|
where: { id, userId, version: dto.version, deletedAt: null },
|
||||||
data: { ...input, version: { increment: 1 } },
|
data: { ...input, version: { increment: 1 } },
|
||||||
})
|
})
|
||||||
).count !== 1
|
).count !== EXPECTED_UPDATED_ROWS
|
||||||
)
|
) {
|
||||||
conflict();
|
conflict();
|
||||||
|
}
|
||||||
return this.operationView(
|
return this.operationView(
|
||||||
tx,
|
tx,
|
||||||
await this.repository.operation(tx, userId, id),
|
await this.repository.operation(tx, userId, id),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteOperation(userId: string, id: string, version: number) {
|
deleteOperation(userId: string, id: string, version: number) {
|
||||||
return this.repository.write(async (tx) => {
|
return this.repository.write(async (tx) => {
|
||||||
const row = await this.repository.operation(tx, userId, id);
|
const row = await this.repository.operation(tx, userId, id);
|
||||||
if (row.deletedAt) return;
|
if (row.deletedAt) return;
|
||||||
if (row.version !== version) conflict();
|
if (row.version !== version) conflict();
|
||||||
await this.repository.card(tx, userId, row.cardId, true);
|
await this.repository.card(tx, userId, row.cardId, true);
|
||||||
if (row.targetCardId)
|
if (row.targetCardId) {
|
||||||
await this.repository.card(tx, userId, row.targetCardId, true);
|
await this.repository.card(tx, userId, row.targetCardId, true);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
row.kind === BankOperationKind.Expense &&
|
row.kind === BankOperationKind.Expense &&
|
||||||
(await tx.bankCardOperation.findFirst({
|
(await tx.bankCardOperation.findFirst({
|
||||||
where: { userId, originalExpenseId: id, deletedAt: null },
|
where: { userId, originalExpenseId: id, deletedAt: null },
|
||||||
}))
|
}))
|
||||||
)
|
) {
|
||||||
conflict(BankErrorCode.DependentRefunds);
|
conflict(BankErrorCode.DependentRefunds);
|
||||||
|
}
|
||||||
if (row.originalExpenseId) {
|
if (row.originalExpenseId) {
|
||||||
const source = await this.repository.operation(
|
const source = await this.repository.operation(
|
||||||
tx,
|
tx,
|
||||||
@@ -287,9 +312,10 @@ export class BankOperationsService {
|
|||||||
where: { id: source.id, userId, version: source.version },
|
where: { id: source.id, userId, version: source.version },
|
||||||
data: { version: { increment: 1 } },
|
data: { version: { increment: 1 } },
|
||||||
})
|
})
|
||||||
).count !== 1
|
).count !== EXPECTED_UPDATED_ROWS
|
||||||
)
|
) {
|
||||||
conflict();
|
conflict();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
(
|
(
|
||||||
@@ -297,37 +323,39 @@ export class BankOperationsService {
|
|||||||
where: { id, userId, version, deletedAt: null },
|
where: { id, userId, version, deletedAt: null },
|
||||||
data: { deletedAt: new Date(), version: { increment: 1 } },
|
data: { deletedAt: new Date(), version: { increment: 1 } },
|
||||||
})
|
})
|
||||||
).count !== 1
|
).count !== EXPECTED_UPDATED_ROWS
|
||||||
)
|
) {
|
||||||
conflict();
|
conflict();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
history(
|
history(
|
||||||
userId: string,
|
userId: string,
|
||||||
id: string,
|
id: string,
|
||||||
query: BankOperationsQueryDto | BankPageQueryDto,
|
query: BankOperationsQueryDto | BankPageQueryDto,
|
||||||
expenses = false,
|
expenses = false,
|
||||||
) {
|
) {
|
||||||
const period = expenses
|
const period = expenses ?
|
||||||
? undefined
|
undefined :
|
||||||
: periodBounds(query as BankOperationsQueryDto);
|
periodBounds(query as BankOperationsQueryDto);
|
||||||
return this.prisma.$transaction(async (tx) => {
|
return this.prisma.$transaction(async (tx) => {
|
||||||
await this.repository.card(tx, userId, id);
|
await this.repository.card(tx, userId, id);
|
||||||
const page = query.page ?? 1,
|
const limit = query.limit ?? DEFAULT_BANK_PAGE_SIZE,
|
||||||
limit = query.limit ?? DEFAULT_BANK_PAGE_SIZE;
|
page = query.page ?? FIRST_PAGE;
|
||||||
const where: Prisma.BankCardOperationWhereInput = {
|
const where: Prisma.BankCardOperationWhereInput = {
|
||||||
userId,
|
userId,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
OR: [{ cardId: id }, { targetCardId: id }],
|
OR: [{ cardId: id }, { targetCardId: id }],
|
||||||
...(period
|
...(period ?
|
||||||
? { date: { gte: period.from, lte: period.to } }
|
{ date: { gte: period.from, lte: period.to } } :
|
||||||
: { kind: BankOperationKind.Expense }),
|
{ kind: BankOperationKind.Expense }),
|
||||||
};
|
};
|
||||||
const total = await tx.bankCardOperation.count({ where });
|
const total = await tx.bankCardOperation.count({ where });
|
||||||
const rows = await tx.bankCardOperation.findMany({
|
const rows = await tx.bankCardOperation.findMany({
|
||||||
where,
|
where,
|
||||||
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||||
skip: (page - 1) * limit,
|
skip: (page - FIRST_PAGE) * limit,
|
||||||
take: limit,
|
take: limit,
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,16 +1,21 @@
|
|||||||
import { MAX_CATEGORY_NAME_LENGTH } from '../domain/bank-card-limits';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
|
||||||
|
|
||||||
import { conflict, missing, name } from './bank-card-input';
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import { MAX_CATEGORY_NAME_LENGTH } from '../domain/bank-card-limits';
|
||||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
import { conflict, missing, name } from './bank-card-input';
|
||||||
|
|
||||||
|
const EXPECTED_UPDATED_CATEGORIES = 1;
|
||||||
|
const VERSION_INCREMENT = 1;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ExpenseCategoriesService {
|
export class ExpenseCategoriesService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly repository: BankCardsRepository,
|
private readonly repository: BankCardsRepository,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async categories(userId: string) {
|
async categories(userId: string) {
|
||||||
return (
|
return (
|
||||||
await this.prisma.expenseCategory.findMany({
|
await this.prisma.expenseCategory.findMany({
|
||||||
@@ -24,6 +29,7 @@ export class ExpenseCategoriesService {
|
|||||||
version,
|
version,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
createCategory(userId: string, value: string) {
|
createCategory(userId: string, value: string) {
|
||||||
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||||
return this.repository.write(async (tx) => {
|
return this.repository.write(async (tx) => {
|
||||||
@@ -44,6 +50,7 @@ export class ExpenseCategoriesService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
updateCategory(userId: string, id: string, value: string, version: number) {
|
updateCategory(userId: string, id: string, value: string, version: number) {
|
||||||
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||||
return this.repository.write(async (tx) => {
|
return this.repository.write(async (tx) => {
|
||||||
@@ -59,14 +66,15 @@ export class ExpenseCategoriesService {
|
|||||||
version: { increment: 1 },
|
version: { increment: 1 },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
).count !== 1
|
).count !== EXPECTED_UPDATED_CATEGORIES
|
||||||
)
|
) {
|
||||||
conflict();
|
conflict();
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
name: label,
|
name: label,
|
||||||
isDefault: row.seedKey === 'other',
|
isDefault: row.seedKey === 'other',
|
||||||
version: version + 1,
|
version: version + VERSION_INCREMENT,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { BankSummaryQueryDto } from '../presentation/bank-card.dto';
|
|
||||||
import { bankSummary } from '../domain/bank-card.calculations';
|
import { bankSummary } from '../domain/bank-card.calculations';
|
||||||
import { rubMoney } from '../domain/rub-money';
|
import { rubMoney } from '../domain/rub-money';
|
||||||
|
|
||||||
import { periodBounds } from './bank-card-input';
|
|
||||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
import { BankSummaryQueryDto } from '../presentation/bank-card.dto';
|
||||||
|
import { periodBounds } from './bank-card-input';
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class GetBankSummaryUseCase {
|
export class GetBankSummaryUseCase {
|
||||||
constructor(private readonly repository: BankCardsRepository) {}
|
constructor(private readonly repository: BankCardsRepository) {}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { AuthModule } from '../../auth/auth.module';
|
import { AuthModule } from '../../auth/auth.module';
|
||||||
import { BankCardsController } from './presentation/bank-cards.controller';
|
|
||||||
import { BankCardsRepository } from './infrastructure/bank-cards.repository';
|
|
||||||
import { BankCardsService } from './application/bank-cards.service';
|
import { BankCardsService } from './application/bank-cards.service';
|
||||||
import { BankOperationsService } from './application/bank-operations.service';
|
import { BankOperationsService } from './application/bank-operations.service';
|
||||||
import { ExpenseCategoriesService } from './application/expense-categories.service';
|
import { ExpenseCategoriesService } from './application/expense-categories.service';
|
||||||
import { GetBankSummaryUseCase } from './application/get-bank-summary.use-case';
|
import { GetBankSummaryUseCase } from './application/get-bank-summary.use-case';
|
||||||
|
import { BankCardsRepository } from './infrastructure/bank-cards.repository';
|
||||||
|
import { BankCardsController } from './presentation/bank-cards.controller';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [AuthModule],
|
imports: [AuthModule],
|
||||||
controllers: [BankCardsController],
|
controllers: [BankCardsController],
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
export const FIRST_PAGE = 1;
|
||||||
|
|
||||||
|
export const MIN_ENTITY_VERSION = 1;
|
||||||
|
|
||||||
|
export const MIN_CATEGORY_NAME_LENGTH = 1;
|
||||||
|
|
||||||
|
export const MIN_CARD_NAME_LENGTH = 1;
|
||||||
export const MAX_CARD_NAME_LENGTH = 100;
|
export const MAX_CARD_NAME_LENGTH = 100;
|
||||||
export const MAX_CATEGORY_NAME_LENGTH = 80;
|
export const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||||
export const MAX_OPERATION_DESCRIPTION_LENGTH = 500;
|
export const MAX_OPERATION_DESCRIPTION_LENGTH = 500;
|
||||||
|
|||||||
@@ -116,7 +116,9 @@ describe('bank card calculations', () => {
|
|||||||
amountKopecks: 5000n,
|
amountKopecks: 5000n,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
expect(bankSummary('2026-09', operations)).toEqual({
|
expect(
|
||||||
|
bankSummary({ from: '2026-09-01', to: '2026-09-30' }, operations),
|
||||||
|
).toEqual({
|
||||||
expenses: 120n,
|
expenses: 120n,
|
||||||
refunds: 500n,
|
refunds: 500n,
|
||||||
net: -380n,
|
net: -380n,
|
||||||
@@ -125,7 +127,9 @@ describe('bank card calculations', () => {
|
|||||||
{ categoryId: 'travel', expenses: 20n, refunds: 0n, net: 20n },
|
{ categoryId: 'travel', expenses: 20n, refunds: 0n, net: 20n },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
expect(bankSummary('2026-07', operations)).toEqual({
|
expect(
|
||||||
|
bankSummary({ from: '2026-07-01', to: '2026-07-31' }, operations),
|
||||||
|
).toEqual({
|
||||||
expenses: 0n,
|
expenses: 0n,
|
||||||
refunds: 0n,
|
refunds: 0n,
|
||||||
net: 0n,
|
net: 0n,
|
||||||
@@ -141,7 +145,12 @@ describe('bank card calculations', () => {
|
|||||||
amountKopecks: 2n ** 63n - 1n,
|
amountKopecks: 2n ** 63n - 1n,
|
||||||
};
|
};
|
||||||
const total = 2n * (2n ** 63n - 1n);
|
const total = 2n * (2n ** 63n - 1n);
|
||||||
expect(bankSummary('2026-09', [operation, operation])).toEqual({
|
expect(
|
||||||
|
bankSummary({ from: '2026-09-01', to: '2026-09-30' }, [
|
||||||
|
operation,
|
||||||
|
operation,
|
||||||
|
]),
|
||||||
|
).toEqual({
|
||||||
expenses: total,
|
expenses: total,
|
||||||
refunds: 0n,
|
refunds: 0n,
|
||||||
net: total,
|
net: total,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
import { ISO_DATE_LENGTH, ISO_DATE_START } from '../../../../common/time';
|
||||||
import { BankOperationKind } from './bank-operation-kind';
|
import { BankOperationKind } from './bank-operation-kind';
|
||||||
|
import { ZERO_KOPECKS } from './rub-money';
|
||||||
|
|
||||||
const ISO_MONTH_LENGTH = 7;
|
|
||||||
export function moscowToday(now = new Date()): string {
|
export function moscowToday(now = new Date()): string {
|
||||||
return new Intl.DateTimeFormat('en-CA', {
|
return new Intl.DateTimeFormat('en-CA', {
|
||||||
timeZone: 'Europe/Moscow',
|
timeZone: 'Europe/Moscow',
|
||||||
@@ -11,11 +12,11 @@ export function moscowToday(now = new Date()): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function isCalendarDate(value: string): boolean {
|
export function isCalendarDate(value: string): boolean {
|
||||||
if (value.length !== 10 || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
if (value.length !== ISO_DATE_LENGTH || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||||
if (value.startsWith('0000')) return false;
|
if (value.startsWith('0000')) return false;
|
||||||
const date = new Date(`${value}T00:00:00.000Z`);
|
const date = new Date(`${value}T00:00:00.000Z`);
|
||||||
return (
|
return (
|
||||||
!Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value
|
!Number.isNaN(date.getTime()) && date.toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH) === value
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,10 +24,10 @@ export function bankBalance(
|
|||||||
cardId: string,
|
cardId: string,
|
||||||
opening: bigint,
|
opening: bigint,
|
||||||
operations: Array<{
|
operations: Array<{
|
||||||
kind: string;
|
|
||||||
cardId: string;
|
|
||||||
targetCardId: string | null;
|
|
||||||
amountKopecks: bigint;
|
amountKopecks: bigint;
|
||||||
|
cardId: string;
|
||||||
|
kind: string;
|
||||||
|
targetCardId: null | string;
|
||||||
}>,
|
}>,
|
||||||
): bigint {
|
): bigint {
|
||||||
// ponytail: O(N) history fold; optimize only after measuring growing histories.
|
// ponytail: O(N) history fold; optimize only after measuring growing histories.
|
||||||
@@ -36,67 +37,65 @@ export function bankBalance(
|
|||||||
if (
|
if (
|
||||||
operation.kind === BankOperationKind.Expense ||
|
operation.kind === BankOperationKind.Expense ||
|
||||||
operation.kind === BankOperationKind.Transfer
|
operation.kind === BankOperationKind.Transfer
|
||||||
)
|
) {
|
||||||
balance -= operation.amountKopecks;
|
balance -= operation.amountKopecks;
|
||||||
else if (
|
} else if (
|
||||||
operation.kind === BankOperationKind.Topup ||
|
operation.kind === BankOperationKind.Topup ||
|
||||||
operation.kind === BankOperationKind.Refund
|
operation.kind === BankOperationKind.Refund
|
||||||
)
|
) {
|
||||||
balance += operation.amountKopecks;
|
balance += operation.amountKopecks;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
operation.kind === BankOperationKind.Transfer &&
|
operation.kind === BankOperationKind.Transfer &&
|
||||||
operation.targetCardId === cardId
|
operation.targetCardId === cardId
|
||||||
)
|
) {
|
||||||
balance += operation.amountKopecks;
|
balance += operation.amountKopecks;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return balance;
|
return balance;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function bankSummary(
|
export function bankSummary(
|
||||||
period: string | { from: string; to: string },
|
period: { from: string; to: string },
|
||||||
operations: Array<{
|
operations: Array<{
|
||||||
kind: string;
|
|
||||||
date: string;
|
|
||||||
amountKopecks: bigint;
|
amountKopecks: bigint;
|
||||||
categoryId: string | null;
|
categoryId: null | string;
|
||||||
|
date: string;
|
||||||
|
kind: string;
|
||||||
}>,
|
}>,
|
||||||
) {
|
) {
|
||||||
let expenses = 0n;
|
let expenses = ZERO_KOPECKS;
|
||||||
let refunds = 0n;
|
let refunds = ZERO_KOPECKS;
|
||||||
const categories = new Map<
|
const categories = new Map<
|
||||||
string,
|
string,
|
||||||
{ categoryId: string; expenses: bigint; refunds: bigint; net: bigint }
|
{ categoryId: string; expenses: bigint; net: bigint; refunds: bigint }
|
||||||
>();
|
>();
|
||||||
// ponytail: O(N) history fold; optimize only after measuring growing histories.
|
// ponytail: O(N) history fold; optimize only after measuring growing histories.
|
||||||
for (const operation of operations) {
|
for (const operation of operations) {
|
||||||
if (
|
if (operation.date < period.from || operation.date > period.to) continue;
|
||||||
typeof period === 'string'
|
|
||||||
? operation.date.slice(0, ISO_MONTH_LENGTH) !== period
|
|
||||||
: operation.date < period.from || operation.date > period.to
|
|
||||||
)
|
|
||||||
continue;
|
|
||||||
if (
|
if (
|
||||||
operation.kind !== BankOperationKind.Expense &&
|
operation.kind !== BankOperationKind.Expense &&
|
||||||
operation.kind !== BankOperationKind.Refund
|
operation.kind !== BankOperationKind.Refund
|
||||||
)
|
) {
|
||||||
continue;
|
continue;
|
||||||
|
}
|
||||||
const expense =
|
const expense =
|
||||||
operation.kind === BankOperationKind.Expense
|
operation.kind === BankOperationKind.Expense ?
|
||||||
? operation.amountKopecks
|
operation.amountKopecks :
|
||||||
: 0n;
|
ZERO_KOPECKS;
|
||||||
const refund =
|
const refund =
|
||||||
operation.kind === BankOperationKind.Refund
|
operation.kind === BankOperationKind.Refund ?
|
||||||
? operation.amountKopecks
|
operation.amountKopecks :
|
||||||
: 0n;
|
ZERO_KOPECKS;
|
||||||
expenses += expense;
|
expenses += expense;
|
||||||
refunds += refund;
|
refunds += refund;
|
||||||
if (operation.categoryId !== null) {
|
if (operation.categoryId !== null) {
|
||||||
const category = categories.get(operation.categoryId) ?? {
|
const category = categories.get(operation.categoryId) ?? {
|
||||||
categoryId: operation.categoryId,
|
categoryId: operation.categoryId,
|
||||||
expenses: 0n,
|
expenses: ZERO_KOPECKS,
|
||||||
refunds: 0n,
|
refunds: ZERO_KOPECKS,
|
||||||
net: 0n,
|
net: ZERO_KOPECKS,
|
||||||
};
|
};
|
||||||
category.expenses += expense;
|
category.expenses += expense;
|
||||||
category.refunds += refund;
|
category.refunds += refund;
|
||||||
|
|||||||
@@ -39,8 +39,9 @@ describe('RUB money', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('requires positive operation amounts, including at the maximum', () => {
|
it('requires positive operation amounts, including at the maximum', () => {
|
||||||
for (const value of ['0', '-0.00', '-0.01'])
|
for (const value of ['0', '-0.00', '-0.01']) {
|
||||||
expect(() => parseRubMoney({ currency: 'RUB', value }, true)).toThrow();
|
expect(() => parseRubMoney({ currency: 'RUB', value }, true)).toThrow();
|
||||||
|
}
|
||||||
expect(parseRubMoney({ currency: 'RUB', value: '0.01' }, true)).toBe(1n);
|
expect(parseRubMoney({ currency: 'RUB', value: '0.01' }, true)).toBe(1n);
|
||||||
expect(
|
expect(
|
||||||
parseRubMoney({ currency: 'RUB', value: '92233720368547758.07' }, true),
|
parseRubMoney({ currency: 'RUB', value: '92233720368547758.07' }, true),
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { decimalFromString, formatDecimal } from '../../../../common/decimal';
|
|
||||||
import type { Money } from '../../../../common/money.types';
|
import type { Money } from '../../../../common/money.types';
|
||||||
|
|
||||||
|
import { DECIMAL_RADIX, decimalFromString, formatDecimal } from '../../../../common/decimal';
|
||||||
|
|
||||||
|
export const ZERO_KOPECKS = 0n;
|
||||||
|
|
||||||
|
const RUB_DECIMAL_PLACES = 2;
|
||||||
|
|
||||||
const MIN_KOPECKS = -9_223_372_036_854_775_808n;
|
const MIN_KOPECKS = -9_223_372_036_854_775_808n;
|
||||||
const MAX_KOPECKS = 9_223_372_036_854_775_807n;
|
const MAX_KOPECKS = 9_223_372_036_854_775_807n;
|
||||||
|
|
||||||
@@ -9,22 +14,26 @@ export function parseRubMoney(money: Money, positive = false): bigint {
|
|||||||
money?.currency !== 'RUB' ||
|
money?.currency !== 'RUB' ||
|
||||||
typeof money.value !== 'string' ||
|
typeof money.value !== 'string' ||
|
||||||
money.value !== money.value.trim()
|
money.value !== money.value.trim()
|
||||||
)
|
) {
|
||||||
throw new TypeError('Expected RUB money with a decimal string');
|
throw new TypeError('Expected RUB money with a decimal string');
|
||||||
|
}
|
||||||
const amount = decimalFromString(money.value);
|
const amount = decimalFromString(money.value);
|
||||||
if (amount.scale > 2)
|
if (amount.scale > RUB_DECIMAL_PLACES) {
|
||||||
throw new RangeError('RUB money supports at most two decimal places');
|
throw new RangeError('RUB money supports at most two decimal places');
|
||||||
const kopecks = amount.value * 10n ** BigInt(2 - amount.scale);
|
}
|
||||||
if (kopecks < MIN_KOPECKS || kopecks > MAX_KOPECKS)
|
const kopecks = amount.value * DECIMAL_RADIX ** BigInt(RUB_DECIMAL_PLACES - amount.scale);
|
||||||
|
if (kopecks < MIN_KOPECKS || kopecks > MAX_KOPECKS) {
|
||||||
throw new RangeError('RUB money is outside the signed 64-bit range');
|
throw new RangeError('RUB money is outside the signed 64-bit range');
|
||||||
if (positive && kopecks <= 0n)
|
}
|
||||||
|
if (positive && kopecks <= ZERO_KOPECKS) {
|
||||||
throw new RangeError('Operation amount must be positive');
|
throw new RangeError('Operation amount must be positive');
|
||||||
|
}
|
||||||
return kopecks;
|
return kopecks;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function rubMoney(kopecks: bigint): Money {
|
export function rubMoney(kopecks: bigint): Money {
|
||||||
return {
|
return {
|
||||||
currency: 'RUB',
|
currency: 'RUB',
|
||||||
value: formatDecimal({ value: kopecks, scale: 2 }),
|
value: formatDecimal({ value: kopecks, scale: RUB_DECIMAL_PLACES }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
import { BankOperationKind } from '../domain/bank-operation-kind';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
import { Prisma } from '../../../../../generated/prisma/client';
|
import { Prisma } from '../../../../../generated/prisma/client';
|
||||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BankErrorCode,
|
BankErrorCode,
|
||||||
conflict,
|
conflict,
|
||||||
missing,
|
missing,
|
||||||
} from '../application/bank-card-input';
|
} from '../application/bank-card-input';
|
||||||
|
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||||
|
|
||||||
|
const INITIAL_RETRY_COUNT = 0;
|
||||||
|
const LAST_SEED_OFFSET = 1;
|
||||||
|
|
||||||
type Tx = Prisma.TransactionClient;
|
type Tx = Prisma.TransactionClient;
|
||||||
const TRANSACTION_MAX_WAIT_MS = 10_000;
|
const TRANSACTION_MAX_WAIT_MS = 10_000;
|
||||||
const TRANSACTION_TIMEOUT_MS = 15_000;
|
const TRANSACTION_TIMEOUT_MS = 15_000;
|
||||||
@@ -28,7 +32,7 @@ const seeds = [
|
|||||||
export class BankCardsRepository {
|
export class BankCardsRepository {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
async write<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
async write<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
||||||
for (let attempt = 0; ; attempt++) {
|
for (let attempt = INITIAL_RETRY_COUNT; ; attempt++) {
|
||||||
try {
|
try {
|
||||||
return await this.prisma.$transaction(run, {
|
return await this.prisma.$transaction(run, {
|
||||||
maxWait: TRANSACTION_MAX_WAIT_MS,
|
maxWait: TRANSACTION_MAX_WAIT_MS,
|
||||||
@@ -36,41 +40,45 @@ export class BankCardsRepository {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const code =
|
const code =
|
||||||
error instanceof Prisma.PrismaClientKnownRequestError
|
error instanceof Prisma.PrismaClientKnownRequestError ?
|
||||||
? error.code
|
error.code :
|
||||||
: '';
|
'';
|
||||||
const busy =
|
const busy =
|
||||||
code === 'P2034' ||
|
code === 'P2034' ||
|
||||||
code === 'P2028' ||
|
code === 'P2028' ||
|
||||||
(error instanceof Error &&
|
(error instanceof Error &&
|
||||||
/SQLITE_BUSY|database is locked/.test(error.message));
|
/SQLITE_BUSY|database is locked/.test(error.message));
|
||||||
if ((busy || code === 'P2002') && attempt < MAX_WRITE_RETRY_COUNT)
|
if ((busy || code === 'P2002') && attempt < MAX_WRITE_RETRY_COUNT) {
|
||||||
continue;
|
continue;
|
||||||
|
}
|
||||||
if (busy) conflict(BankErrorCode.WriteConflict);
|
if (busy) conflict(BankErrorCode.WriteConflict);
|
||||||
if (code === 'P2002') conflict(BankErrorCode.DuplicateCategory);
|
if (code === 'P2002') conflict(BankErrorCode.DuplicateCategory);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async card(tx: Tx, userId: string, id: string, active = false) {
|
async card(tx: Tx, userId: string, id: string, active = false) {
|
||||||
const card = await tx.bankCard.findFirst({ where: { id, userId } });
|
const card = await tx.bankCard.findFirst({ where: { id, userId } });
|
||||||
if (!card) return missing();
|
if (!card) return missing();
|
||||||
if (active && card.archivedAt) conflict(BankErrorCode.CardArchived);
|
if (active && card.archivedAt) conflict(BankErrorCode.CardArchived);
|
||||||
return card;
|
return card;
|
||||||
}
|
}
|
||||||
|
|
||||||
async operation(tx: Tx, userId: string, id: string) {
|
async operation(tx: Tx, userId: string, id: string) {
|
||||||
const row = await tx.bankCardOperation.findFirst({ where: { id, userId } });
|
const row = await tx.bankCardOperation.findFirst({ where: { id, userId } });
|
||||||
if (!row) return missing();
|
if (!row) return missing();
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
async seed(tx: Tx, userId: string) {
|
async seed(tx: Tx, userId: string) {
|
||||||
for (const [index, label] of seeds.entries()) {
|
for (const [index, label] of seeds.entries()) {
|
||||||
const seedKey = index === seeds.length - 1 ? 'other' : String(index);
|
const seedKey = index === seeds.length - LAST_SEED_OFFSET ? 'other' : String(index);
|
||||||
if (
|
if (
|
||||||
!(await tx.expenseCategory.findUnique({
|
!(await tx.expenseCategory.findUnique({
|
||||||
where: { userId_seedKey: { userId, seedKey } },
|
where: { userId_seedKey: { userId, seedKey } },
|
||||||
}))
|
}))
|
||||||
)
|
) {
|
||||||
await tx.expenseCategory.create({
|
await tx.expenseCategory.create({
|
||||||
data: {
|
data: {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
@@ -80,8 +88,10 @@ export class BankCardsRepository {
|
|||||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
summaryData(
|
summaryData(
|
||||||
userId: string,
|
userId: string,
|
||||||
period: { from: string; to: string },
|
period: { from: string; to: string },
|
||||||
|
|||||||
@@ -1,9 +1,3 @@
|
|||||||
import {
|
|
||||||
MAX_CARD_NAME_LENGTH,
|
|
||||||
MAX_CATEGORY_NAME_LENGTH,
|
|
||||||
MAX_OPERATION_DESCRIPTION_LENGTH,
|
|
||||||
} from '../domain/bank-card-limits';
|
|
||||||
import { BankOperationKind } from '../domain/bank-operation-kind';
|
|
||||||
import {
|
import {
|
||||||
ApiProperty,
|
ApiProperty,
|
||||||
ApiPropertyOptional,
|
ApiPropertyOptional,
|
||||||
@@ -28,7 +22,20 @@ import {
|
|||||||
ValidateIf,
|
ValidateIf,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
import { MoneyDto } from '../../../../common/money.dto';
|
import { MoneyDto } from '../../../../common/money.dto';
|
||||||
|
import {
|
||||||
|
FIRST_PAGE,
|
||||||
|
MAX_CARD_NAME_LENGTH,
|
||||||
|
MAX_CATEGORY_NAME_LENGTH,
|
||||||
|
MAX_OPERATION_DESCRIPTION_LENGTH,
|
||||||
|
MIN_CARD_NAME_LENGTH,
|
||||||
|
MIN_CATEGORY_NAME_LENGTH,
|
||||||
|
MIN_ENTITY_VERSION,
|
||||||
|
} from '../domain/bank-card-limits';
|
||||||
|
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||||
|
|
||||||
|
const MIN_PAGE_SIZE = 1;
|
||||||
|
|
||||||
export const DEFAULT_BANK_PAGE_SIZE = 50;
|
export const DEFAULT_BANK_PAGE_SIZE = 50;
|
||||||
const MAX_BANK_PAGE_SIZE = 100;
|
const MAX_BANK_PAGE_SIZE = 100;
|
||||||
@@ -41,17 +48,19 @@ export class RubMoneyInputDto {
|
|||||||
@ApiProperty({ enum: ['RUB'] }) @IsIn(['RUB']) declare currency: string;
|
@ApiProperty({ enum: ['RUB'] }) @IsIn(['RUB']) declare currency: string;
|
||||||
@ApiProperty({ pattern: '^-?[0-9]+(\\.[0-9]{1,2})?$' })
|
@ApiProperty({ pattern: '^-?[0-9]+(\\.[0-9]{1,2})?$' })
|
||||||
@IsString()
|
@IsString()
|
||||||
|
// eslint-disable-next-line security/detect-unsafe-regex -- Anchored decimal grammar: the literal decimal point separates disjoint digit runs; backtracking is linear.
|
||||||
@Matches(/^-?\d+(\.\d{1,2})?$/)
|
@Matches(/^-?\d+(\.\d{1,2})?$/)
|
||||||
declare value: string;
|
declare value: string;
|
||||||
}
|
}
|
||||||
export class CreateBankCardDto {
|
export class CreateBankCardDto {
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
||||||
@ApiProperty({ minLength: 1, maxLength: MAX_CARD_NAME_LENGTH })
|
@ApiProperty({ minLength: MIN_CARD_NAME_LENGTH, maxLength: MAX_CARD_NAME_LENGTH })
|
||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(1)
|
@MinLength(MIN_CARD_NAME_LENGTH)
|
||||||
@MaxLength(MAX_CARD_NAME_LENGTH)
|
@MaxLength(MAX_CARD_NAME_LENGTH)
|
||||||
declare name: string;
|
declare name: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
type: String,
|
type: String,
|
||||||
nullable: true,
|
nullable: true,
|
||||||
@@ -61,20 +70,24 @@ export class CreateBankCardDto {
|
|||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(MAX_CARD_NAME_LENGTH)
|
@MaxLength(MAX_CARD_NAME_LENGTH)
|
||||||
bankName?: string | null;
|
bankName?: null | string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ type: String, nullable: true, pattern: '^[0-9]{4}$' })
|
@ApiPropertyOptional({ type: String, nullable: true, pattern: '^[0-9]{4}$' })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Matches(/^[0-9]{4}$/)
|
@Matches(/^\d{4}$/)
|
||||||
lastFour?: string | null;
|
lastFour?: null | string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ enum: bankPaymentSystems, nullable: true })
|
@ApiPropertyOptional({ enum: bankPaymentSystems, nullable: true })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(bankPaymentSystems)
|
@IsIn(bankPaymentSystems)
|
||||||
paymentSystem?: string | null;
|
paymentSystem?: null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: RubMoneyInputDto })
|
@ApiProperty({ type: RubMoneyInputDto })
|
||||||
@IsDefined()
|
@IsDefined()
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@Type(() => RubMoneyInputDto)
|
@Type(() => RubMoneyInputDto)
|
||||||
declare openingBalance: MoneyDto;
|
declare openingBalance: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ format: 'date' })
|
@ApiProperty({ format: 'date' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||||
@@ -84,50 +97,56 @@ export class UpdateBankCardDto extends PartialType(
|
|||||||
OmitType(CreateBankCardDto, ['id'] as const),
|
OmitType(CreateBankCardDto, ['id'] as const),
|
||||||
{ skipNullProperties: false },
|
{ skipNullProperties: false },
|
||||||
) {
|
) {
|
||||||
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) declare version: number;
|
@ApiProperty({ minimum: MIN_ENTITY_VERSION }) @IsInt() @Min(MIN_ENTITY_VERSION) declare version: number;
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
archived?: boolean;
|
archived?: boolean;
|
||||||
}
|
}
|
||||||
export class CategoryNameDto {
|
export class CategoryNameDto {
|
||||||
@ApiProperty({ minLength: 1, maxLength: MAX_CATEGORY_NAME_LENGTH })
|
@ApiProperty({ minLength: MIN_CATEGORY_NAME_LENGTH, maxLength: MAX_CATEGORY_NAME_LENGTH })
|
||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(1)
|
@MinLength(MIN_CATEGORY_NAME_LENGTH)
|
||||||
@MaxLength(MAX_CATEGORY_NAME_LENGTH)
|
@MaxLength(MAX_CATEGORY_NAME_LENGTH)
|
||||||
declare name: string;
|
declare name: string;
|
||||||
}
|
}
|
||||||
export class UpdateExpenseCategoryDto extends CategoryNameDto {
|
export class UpdateExpenseCategoryDto extends CategoryNameDto {
|
||||||
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) declare version: number;
|
@ApiProperty({ minimum: MIN_ENTITY_VERSION }) @IsInt() @Min(MIN_ENTITY_VERSION) declare version: number;
|
||||||
}
|
}
|
||||||
export class CreateBankOperationDto {
|
export class CreateBankOperationDto {
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
||||||
@ApiProperty({ enum: bankOperationKinds })
|
@ApiProperty({ enum: bankOperationKinds })
|
||||||
@IsIn(bankOperationKinds)
|
@IsIn(bankOperationKinds)
|
||||||
declare kind: BankOperationKind;
|
declare kind: BankOperationKind;
|
||||||
|
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() declare cardId: string;
|
@ApiProperty({ format: 'uuid' }) @IsUUID() declare cardId: string;
|
||||||
@ApiPropertyOptional({ format: 'uuid' })
|
@ApiPropertyOptional({ format: 'uuid' })
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
targetCardId?: string;
|
targetCardId?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ format: 'uuid' })
|
@ApiPropertyOptional({ format: 'uuid' })
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
categoryId?: string;
|
categoryId?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ format: 'uuid' })
|
@ApiPropertyOptional({ format: 'uuid' })
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
originalExpenseId?: string;
|
originalExpenseId?: string;
|
||||||
|
|
||||||
@ApiProperty({ type: RubMoneyInputDto })
|
@ApiProperty({ type: RubMoneyInputDto })
|
||||||
@IsDefined()
|
@IsDefined()
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@Type(() => RubMoneyInputDto)
|
@Type(() => RubMoneyInputDto)
|
||||||
declare amount: MoneyDto;
|
declare amount: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ format: 'date' })
|
@ApiProperty({ format: 'date' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||||
declare date: string;
|
declare date: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ maxLength: MAX_OPERATION_DESCRIPTION_LENGTH })
|
@ApiPropertyOptional({ maxLength: MAX_OPERATION_DESCRIPTION_LENGTH })
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -138,7 +157,7 @@ export class UpdateBankOperationDto extends PartialType(
|
|||||||
OmitType(CreateBankOperationDto, ['id'] as const),
|
OmitType(CreateBankOperationDto, ['id'] as const),
|
||||||
{ skipNullProperties: false },
|
{ skipNullProperties: false },
|
||||||
) {
|
) {
|
||||||
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) declare version: number;
|
@ApiProperty({ minimum: MIN_ENTITY_VERSION }) @IsInt() @Min(MIN_ENTITY_VERSION) declare version: number;
|
||||||
}
|
}
|
||||||
export class BankCardsQueryDto {
|
export class BankCardsQueryDto {
|
||||||
@ApiPropertyOptional({ enum: ['true', 'false'] })
|
@ApiPropertyOptional({ enum: ['true', 'false'] })
|
||||||
@@ -147,21 +166,22 @@ export class BankCardsQueryDto {
|
|||||||
includeArchived?: string;
|
includeArchived?: string;
|
||||||
}
|
}
|
||||||
export class BankPageQueryDto {
|
export class BankPageQueryDto {
|
||||||
@ApiPropertyOptional({ minimum: 1, default: 1 })
|
@ApiPropertyOptional({ minimum: FIRST_PAGE, default: FIRST_PAGE })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(FIRST_PAGE)
|
||||||
page?: number;
|
page?: number;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
minimum: 1,
|
minimum: MIN_PAGE_SIZE,
|
||||||
maximum: MAX_BANK_PAGE_SIZE,
|
maximum: MAX_BANK_PAGE_SIZE,
|
||||||
default: DEFAULT_BANK_PAGE_SIZE,
|
default: DEFAULT_BANK_PAGE_SIZE,
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(MIN_PAGE_SIZE)
|
||||||
@Max(MAX_BANK_PAGE_SIZE)
|
@Max(MAX_BANK_PAGE_SIZE)
|
||||||
limit?: number;
|
limit?: number;
|
||||||
}
|
}
|
||||||
@@ -173,6 +193,7 @@ export class BankPeriodQueryDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/)
|
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/)
|
||||||
month?: string;
|
month?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
format: 'date',
|
format: 'date',
|
||||||
description: 'Inclusive start date; requires to.',
|
description: 'Inclusive start date; requires to.',
|
||||||
@@ -180,6 +201,7 @@ export class BankPeriodQueryDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||||
from?: string;
|
from?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
format: 'date',
|
format: 'date',
|
||||||
description: 'Inclusive end date; requires from.',
|
description: 'Inclusive end date; requires from.',
|
||||||
@@ -199,10 +221,10 @@ export class BankSummaryQueryDto extends BankPeriodQueryDto {
|
|||||||
cardId?: string;
|
cardId?: string;
|
||||||
}
|
}
|
||||||
export class BankVersionQueryDto {
|
export class BankVersionQueryDto {
|
||||||
@ApiProperty({ minimum: 1 })
|
@ApiProperty({ minimum: MIN_ENTITY_VERSION })
|
||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(MIN_ENTITY_VERSION)
|
||||||
declare version: number;
|
declare version: number;
|
||||||
}
|
}
|
||||||
export class ExpenseCategoryDto {
|
export class ExpenseCategoryDto {
|
||||||
@@ -215,16 +237,20 @@ export class BankCardDto {
|
|||||||
@ApiProperty({ type: String }) declare id: string;
|
@ApiProperty({ type: String }) declare id: string;
|
||||||
@ApiProperty({ type: String }) declare name: string;
|
@ApiProperty({ type: String }) declare name: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) declare bankName:
|
@ApiProperty({ type: String, nullable: true }) declare bankName:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true }) declare lastFour:
|
@ApiProperty({ type: String, nullable: true }) declare lastFour:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ enum: bankPaymentSystems, nullable: true })
|
@ApiProperty({ enum: bankPaymentSystems, nullable: true })
|
||||||
declare paymentSystem: string | null;
|
declare paymentSystem: null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto }) declare openingBalance: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare openingBalance: MoneyDto;
|
||||||
@ApiProperty({ type: String }) declare openingDate: string;
|
@ApiProperty({ type: String }) declare openingDate: string;
|
||||||
@ApiProperty({ type: MoneyDto }) declare balance: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare balance: MoneyDto;
|
||||||
@ApiProperty({ type: String, nullable: true }) declare archivedAt:
|
@ApiProperty({ type: String, nullable: true }) declare archivedAt:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: Number }) declare version: number;
|
@ApiProperty({ type: Number }) declare version: number;
|
||||||
}
|
}
|
||||||
export class BankOperationDto {
|
export class BankOperationDto {
|
||||||
@@ -233,27 +259,35 @@ export class BankOperationDto {
|
|||||||
@ApiProperty({ type: String }) declare cardId: string;
|
@ApiProperty({ type: String }) declare cardId: string;
|
||||||
@ApiProperty({ type: String }) declare cardName: string;
|
@ApiProperty({ type: String }) declare cardName: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) declare targetCardId:
|
@ApiProperty({ type: String, nullable: true }) declare targetCardId:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true }) declare targetCardName:
|
@ApiProperty({ type: String, nullable: true }) declare targetCardName:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true }) declare categoryId:
|
@ApiProperty({ type: String, nullable: true }) declare categoryId:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true }) declare categoryName:
|
@ApiProperty({ type: String, nullable: true }) declare categoryName:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true }) declare originalExpenseId:
|
@ApiProperty({ type: String, nullable: true }) declare originalExpenseId:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto }) declare amount: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare amount: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto, nullable: true })
|
@ApiProperty({ type: MoneyDto, nullable: true })
|
||||||
declare availableRefund: MoneyDto | null;
|
declare availableRefund: MoneyDto | null;
|
||||||
|
|
||||||
@ApiProperty({ type: String }) declare date: string;
|
@ApiProperty({ type: String }) declare date: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) declare description:
|
@ApiProperty({ type: String, nullable: true }) declare description:
|
||||||
string | null;
|
null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: Number }) declare version: number;
|
@ApiProperty({ type: Number }) declare version: number;
|
||||||
@ApiProperty({ type: String }) declare createdAt: string;
|
@ApiProperty({ type: String }) declare createdAt: string;
|
||||||
}
|
}
|
||||||
export class BankOperationsPageDto {
|
export class BankOperationsPageDto {
|
||||||
@ApiProperty({ type: BankOperationDto, isArray: true })
|
@ApiProperty({ type: BankOperationDto, isArray: true })
|
||||||
declare items: BankOperationDto[];
|
declare items: BankOperationDto[];
|
||||||
|
|
||||||
@ApiProperty({ type: Number }) declare page: number;
|
@ApiProperty({ type: Number }) declare page: number;
|
||||||
@ApiProperty({ type: Number }) declare total: number;
|
@ApiProperty({ type: Number }) declare total: number;
|
||||||
@ApiProperty({ type: Boolean }) declare hasNext: boolean;
|
@ApiProperty({ type: Boolean }) declare hasNext: boolean;
|
||||||
@@ -269,7 +303,7 @@ export class BankSummaryDto {
|
|||||||
@ApiPropertyOptional({ type: String }) month?: string;
|
@ApiPropertyOptional({ type: String }) month?: string;
|
||||||
@ApiPropertyOptional({ format: 'date' }) from?: string;
|
@ApiPropertyOptional({ format: 'date' }) from?: string;
|
||||||
@ApiPropertyOptional({ format: 'date' }) to?: string;
|
@ApiPropertyOptional({ format: 'date' }) to?: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) declare cardId: string | null;
|
@ApiProperty({ type: String, nullable: true }) declare cardId: null | string;
|
||||||
@ApiProperty({ type: MoneyDto }) declare expenses: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare expenses: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) declare refunds: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare refunds: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) declare net: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare net: MoneyDto;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { Request } from 'express';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
@@ -21,12 +23,16 @@ import {
|
|||||||
ApiTags,
|
ApiTags,
|
||||||
getSchemaPath,
|
getSchemaPath,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import type { Request } from 'express';
|
|
||||||
import {
|
import {
|
||||||
ApiProblemResponses,
|
ApiProblemResponses,
|
||||||
ProblemDetailsDto,
|
ProblemDetailsDto,
|
||||||
} from '../../../../common/decorators/api-safe-error-response.decorator';
|
} from '../../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { AccessPayload, JwtAuthGuard } from '../../../auth/auth.api';
|
import { AccessPayload, JwtAuthGuard } from '../../../auth/auth.api';
|
||||||
|
import { BankCardsService } from '../application/bank-cards.service';
|
||||||
|
import { BankOperationsService } from '../application/bank-operations.service';
|
||||||
|
import { ExpenseCategoriesService } from '../application/expense-categories.service';
|
||||||
|
import { GetBankSummaryUseCase } from '../application/get-bank-summary.use-case';
|
||||||
import {
|
import {
|
||||||
BankCardDto,
|
BankCardDto,
|
||||||
BankCardsQueryDto,
|
BankCardsQueryDto,
|
||||||
@@ -45,10 +51,6 @@ import {
|
|||||||
UpdateBankOperationDto,
|
UpdateBankOperationDto,
|
||||||
UpdateExpenseCategoryDto,
|
UpdateExpenseCategoryDto,
|
||||||
} from './bank-card.dto';
|
} from './bank-card.dto';
|
||||||
import { BankCardsService } from '../application/bank-cards.service';
|
|
||||||
import { BankOperationsService } from '../application/bank-operations.service';
|
|
||||||
import { ExpenseCategoriesService } from '../application/expense-categories.service';
|
|
||||||
import { GetBankSummaryUseCase } from '../application/get-bank-summary.use-case';
|
|
||||||
type AuthRequest = Request & { user: AccessPayload };
|
type AuthRequest = Request & { user: AccessPayload };
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 409,
|
status: 409,
|
||||||
@@ -82,26 +84,31 @@ export class BankCardsController {
|
|||||||
private readonly expenseCategories: ExpenseCategoriesService,
|
private readonly expenseCategories: ExpenseCategoriesService,
|
||||||
private readonly bankSummary: GetBankSummaryUseCase,
|
private readonly bankSummary: GetBankSummaryUseCase,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@ApiOkResponse({ type: BankCardDto, isArray: true })
|
@ApiOkResponse({ type: BankCardDto, isArray: true })
|
||||||
list(@Req() req: AuthRequest, @Query() query: BankCardsQueryDto) {
|
list(@Req() req: AuthRequest, @Query() query: BankCardsQueryDto) {
|
||||||
return this.cards.list(req.user.sub, query.includeArchived === 'true');
|
return this.cards.list(req.user.sub, query.includeArchived === 'true');
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@ApiCreatedResponse({ type: BankCardDto })
|
@ApiCreatedResponse({ type: BankCardDto })
|
||||||
create(@Req() req: AuthRequest, @Body() body: CreateBankCardDto) {
|
create(@Req() req: AuthRequest, @Body() body: CreateBankCardDto) {
|
||||||
return this.cards.createCard(req.user.sub, body);
|
return this.cards.createCard(req.user.sub, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('categories')
|
@Get('categories')
|
||||||
@ApiOkResponse({ type: ExpenseCategoryDto, isArray: true })
|
@ApiOkResponse({ type: ExpenseCategoryDto, isArray: true })
|
||||||
categories(@Req() req: AuthRequest) {
|
categories(@Req() req: AuthRequest) {
|
||||||
return this.expenseCategories.categories(req.user.sub);
|
return this.expenseCategories.categories(req.user.sub);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('categories')
|
@Post('categories')
|
||||||
@ApiCreatedResponse({ type: ExpenseCategoryDto })
|
@ApiCreatedResponse({ type: ExpenseCategoryDto })
|
||||||
createCategory(@Req() req: AuthRequest, @Body() body: CategoryNameDto) {
|
createCategory(@Req() req: AuthRequest, @Body() body: CategoryNameDto) {
|
||||||
return this.expenseCategories.createCategory(req.user.sub, body.name);
|
return this.expenseCategories.createCategory(req.user.sub, body.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch('categories/:id')
|
@Patch('categories/:id')
|
||||||
@ApiOkResponse({ type: ExpenseCategoryDto })
|
@ApiOkResponse({ type: ExpenseCategoryDto })
|
||||||
updateCategory(
|
updateCategory(
|
||||||
@@ -116,11 +123,13 @@ export class BankCardsController {
|
|||||||
body.version,
|
body.version,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('summary')
|
@Get('summary')
|
||||||
@ApiOkResponse({ type: BankSummaryDto })
|
@ApiOkResponse({ type: BankSummaryDto })
|
||||||
summary(@Req() req: AuthRequest, @Query() query: BankSummaryQueryDto) {
|
summary(@Req() req: AuthRequest, @Query() query: BankSummaryQueryDto) {
|
||||||
return this.bankSummary.execute(req.user.sub, query);
|
return this.bankSummary.execute(req.user.sub, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('operations')
|
@Post('operations')
|
||||||
@ApiCreatedResponse({ type: BankOperationDto })
|
@ApiCreatedResponse({ type: BankOperationDto })
|
||||||
createOperation(
|
createOperation(
|
||||||
@@ -129,11 +138,13 @@ export class BankCardsController {
|
|||||||
) {
|
) {
|
||||||
return this.operations.createOperation(req.user.sub, body);
|
return this.operations.createOperation(req.user.sub, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('operations/:id')
|
@Get('operations/:id')
|
||||||
@ApiOkResponse({ type: BankOperationDto })
|
@ApiOkResponse({ type: BankOperationDto })
|
||||||
operation(@Req() req: AuthRequest, @Param('id') id: string) {
|
operation(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||||
return this.operations.getOperation(req.user.sub, id);
|
return this.operations.getOperation(req.user.sub, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch('operations/:id')
|
@Patch('operations/:id')
|
||||||
@ApiOkResponse({ type: BankOperationDto })
|
@ApiOkResponse({ type: BankOperationDto })
|
||||||
updateOperation(
|
updateOperation(
|
||||||
@@ -143,6 +154,7 @@ export class BankCardsController {
|
|||||||
) {
|
) {
|
||||||
return this.operations.updateOperation(req.user.sub, id, body);
|
return this.operations.updateOperation(req.user.sub, id, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete('operations/:id')
|
@Delete('operations/:id')
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
@ApiNoContentResponse()
|
@ApiNoContentResponse()
|
||||||
@@ -153,6 +165,7 @@ export class BankCardsController {
|
|||||||
) {
|
) {
|
||||||
return this.operations.deleteOperation(req.user.sub, id, query.version);
|
return this.operations.deleteOperation(req.user.sub, id, query.version);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id/operations')
|
@Get(':id/operations')
|
||||||
@ApiOkResponse({ type: BankOperationsPageDto })
|
@ApiOkResponse({ type: BankOperationsPageDto })
|
||||||
history(
|
history(
|
||||||
@@ -162,6 +175,7 @@ export class BankCardsController {
|
|||||||
) {
|
) {
|
||||||
return this.operations.history(req.user.sub, id, query);
|
return this.operations.history(req.user.sub, id, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id/expenses')
|
@Get(':id/expenses')
|
||||||
@ApiOkResponse({ type: BankOperationsPageDto })
|
@ApiOkResponse({ type: BankOperationsPageDto })
|
||||||
expenses(
|
expenses(
|
||||||
@@ -171,11 +185,13 @@ export class BankCardsController {
|
|||||||
) {
|
) {
|
||||||
return this.operations.history(req.user.sub, id, query, true);
|
return this.operations.history(req.user.sub, id, query, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@ApiOkResponse({ type: BankCardDto })
|
@ApiOkResponse({ type: BankCardDto })
|
||||||
get(@Req() req: AuthRequest, @Param('id') id: string) {
|
get(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||||
return this.cards.get(req.user.sub, id);
|
return this.cards.get(req.user.sub, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
@ApiOkResponse({ type: BankCardDto })
|
@ApiOkResponse({ type: BankCardDto })
|
||||||
update(
|
update(
|
||||||
|
|||||||
@@ -1,429 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
|
|
||||||
jest.mock('../../integrations/tbank/tbank-access.service', () => ({
|
|
||||||
TbankAccessService: class {},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import type { TbankConnectionContext } from '../../integrations/tbank/tbank-access.service';
|
|
||||||
import { IncomeAnalyticsService } from './income/income-analytics.service';
|
|
||||||
import { BrokerageOperationsService } from './operations/application/brokerage-operations.service';
|
|
||||||
import { PortfolioService } from './portfolio/application/portfolio.service';
|
|
||||||
import { UpcomingEventsService } from './upcoming-events/upcoming-events.service';
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const context = {
|
|
||||||
token: 'token',
|
|
||||||
generation: 'first',
|
|
||||||
accounts: [
|
|
||||||
{ id: 'a', name: 'Основной', openedOn: '2020-01-01' },
|
|
||||||
{ id: 'b', name: 'ИИС', openedOn: '2026-01-01' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
const access = {
|
|
||||||
withSupportedAccounts: jest.fn(
|
|
||||||
(_user: string, handler: (value: typeof context) => unknown) =>
|
|
||||||
handler(context),
|
|
||||||
),
|
|
||||||
withAccountForConnection: jest.fn(
|
|
||||||
(
|
|
||||||
_connection: TbankConnectionContext,
|
|
||||||
_id: string,
|
|
||||||
handler: () => unknown,
|
|
||||||
) => handler(),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
const tbank = {
|
|
||||||
getOperationsByCursor: jest.fn(),
|
|
||||||
getPortfolio: jest.fn().mockResolvedValue({ positions: [] }),
|
|
||||||
getPositions: jest.fn().mockResolvedValue({ money: [] }),
|
|
||||||
getDividends: jest.fn().mockResolvedValue([]),
|
|
||||||
getInstrumentByFigi: jest.fn().mockResolvedValue({ name: 'Облигация' }),
|
|
||||||
};
|
|
||||||
const metadata = { resolve: jest.fn().mockResolvedValue(null) };
|
|
||||||
const requestContext = { set: jest.fn() };
|
|
||||||
const operations = new BrokerageOperationsService(
|
|
||||||
access as never,
|
|
||||||
tbank as never,
|
|
||||||
requestContext as never,
|
|
||||||
metadata as never,
|
|
||||||
);
|
|
||||||
const portfolio = new PortfolioService(
|
|
||||||
access as never,
|
|
||||||
tbank as never,
|
|
||||||
requestContext as never,
|
|
||||||
metadata as never,
|
|
||||||
);
|
|
||||||
const moex = { bondEvents: jest.fn().mockResolvedValue([]) };
|
|
||||||
const events = new UpcomingEventsService(
|
|
||||||
access as never,
|
|
||||||
tbank as never,
|
|
||||||
moex as never,
|
|
||||||
requestContext as never,
|
|
||||||
{ info: jest.fn(), event: jest.fn() } as never,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
context,
|
|
||||||
access,
|
|
||||||
tbank,
|
|
||||||
operations,
|
|
||||||
portfolio,
|
|
||||||
events,
|
|
||||||
moex,
|
|
||||||
income: new IncomeAnalyticsService(operations),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const operation = (
|
|
||||||
id: string,
|
|
||||||
second: number,
|
|
||||||
type = 'OPERATION_TYPE_COUPON',
|
|
||||||
value = 1,
|
|
||||||
) => ({
|
|
||||||
id,
|
|
||||||
date: { seconds: String(second) },
|
|
||||||
type,
|
|
||||||
payment: { currency: 'RUB', units: value },
|
|
||||||
});
|
|
||||||
const query = { from: '2025-01-01', to: '2026-12-31', limit: 2 };
|
|
||||||
|
|
||||||
describe('All accounts', () => {
|
|
||||||
it('does not truncate instrument history when an account opening date is missing', async () => {
|
|
||||||
const { context, operations, tbank } = setup();
|
|
||||||
Object.assign(context.accounts[0], { openedOn: null });
|
|
||||||
tbank.getOperationsByCursor.mockResolvedValue({ items: [] });
|
|
||||||
await operations.getAll('user', { instrumentUid: 'common' });
|
|
||||||
expect(tbank.getOperationsByCursor).toHaveBeenCalledWith(
|
|
||||||
'token',
|
|
||||||
expect.objectContaining({
|
|
||||||
from: { seconds: '0' },
|
|
||||||
instrumentId: 'common',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('filters upstream by UID, keeps sold-position history and binds continuations to the instrument', async () => {
|
|
||||||
const { operations, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockImplementation(
|
|
||||||
(
|
|
||||||
_token: string,
|
|
||||||
request: { instrumentId: string; accountId: string },
|
|
||||||
) => ({
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
...operation(
|
|
||||||
request.accountId + '-dividend',
|
|
||||||
9,
|
|
||||||
'OPERATION_TYPE_DIVIDEND',
|
|
||||||
),
|
|
||||||
instrumentUid: request.instrumentId,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
...operation('wrong-paper', 8, 'OPERATION_TYPE_DIVIDEND'),
|
|
||||||
instrumentUid: 'preferred',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const first = await operations.getAll('user', {
|
|
||||||
instrumentUid: 'common',
|
|
||||||
limit: 1,
|
|
||||||
});
|
|
||||||
assert.ok(first.nextCursor);
|
|
||||||
expect(first.items).toHaveLength(1);
|
|
||||||
expect(first.items[0].instrumentUid).toBe('common');
|
|
||||||
expect(tbank.getOperationsByCursor).toHaveBeenCalledWith(
|
|
||||||
'token',
|
|
||||||
expect.objectContaining({
|
|
||||||
instrumentId: 'common',
|
|
||||||
from: { seconds: '1577836800' },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
operations.getAll('user', {
|
|
||||||
instrumentUid: 'preferred',
|
|
||||||
limit: 1,
|
|
||||||
cursor: first.nextCursor,
|
|
||||||
}),
|
|
||||||
).rejects.toBeInstanceOf(BadRequestException);
|
|
||||||
const second = await operations.getAll('user', {
|
|
||||||
instrumentUid: 'common',
|
|
||||||
limit: 1,
|
|
||||||
cursor: first.nextCursor,
|
|
||||||
});
|
|
||||||
expect(second.items[0].instrumentUid).toBe('common');
|
|
||||||
expect(second.items[0].id).not.toBe(first.items[0].id);
|
|
||||||
expect(second.hasNext).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => jest.useRealTimers());
|
|
||||||
|
|
||||||
it('merges exact amounts by currency and keeps equal instruments on different accounts', async () => {
|
|
||||||
const { portfolio, tbank } = setup();
|
|
||||||
tbank.getPortfolio.mockResolvedValue({
|
|
||||||
positions: [
|
|
||||||
{
|
|
||||||
figi: 'SAME',
|
|
||||||
instrumentType: 'share',
|
|
||||||
quantity: { units: 1 },
|
|
||||||
currentPrice: { currency: 'RUB', nano: 100000000 },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
tbank.getPositions.mockImplementation((_token: string, id: string) => ({
|
|
||||||
money: [{ currency: id === 'a' ? 'RUB' : 'USD', nano: 200000000 }],
|
|
||||||
}));
|
|
||||||
const result = await portfolio.getAll('user');
|
|
||||||
expect(result.structure.currencies).toMatchObject([
|
|
||||||
{
|
|
||||||
currency: 'RUB',
|
|
||||||
totalValue: '0.4',
|
|
||||||
categories: [
|
|
||||||
{ type: 'STOCK', value: '0.2', sharePercent: '50' },
|
|
||||||
{ type: 'BOND', value: '0' },
|
|
||||||
{ type: 'OTHER', value: '0' },
|
|
||||||
{ type: 'CASH', value: '0.2', sharePercent: '50' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{ currency: 'USD', totalValue: '0.2' },
|
|
||||||
]);
|
|
||||||
expect(result.totalsByCurrency).toEqual([
|
|
||||||
{ currency: 'RUB', value: '0.4' },
|
|
||||||
{ currency: 'USD', value: '0.2' },
|
|
||||||
]);
|
|
||||||
expect(result.cashBalances).toEqual([
|
|
||||||
{ currency: 'RUB', value: '0.2' },
|
|
||||||
{ currency: 'USD', value: '0.2' },
|
|
||||||
]);
|
|
||||||
expect(result.positions.map((position) => position.account?.id)).toEqual([
|
|
||||||
'a',
|
|
||||||
'b',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects missing access and a partial portfolio instead of publishing incomplete totals', async () => {
|
|
||||||
const { portfolio, access, tbank } = setup();
|
|
||||||
access.withSupportedAccounts.mockImplementationOnce(() => {
|
|
||||||
throw new ConflictException({ code: 'TBANK_NOT_CONNECTED' });
|
|
||||||
});
|
|
||||||
await expect(portfolio.getAll('user')).rejects.toBeInstanceOf(
|
|
||||||
ConflictException,
|
|
||||||
);
|
|
||||||
expect(tbank.getPortfolio).not.toHaveBeenCalled();
|
|
||||||
tbank.getPortfolio.mockRejectedValueOnce(new ServiceUnavailableException());
|
|
||||||
await expect(portfolio.getAll('user')).rejects.toBeInstanceOf(
|
|
||||||
ServiceUnavailableException,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('marks an aggregate stale and uses its oldest snapshot timestamp', async () => {
|
|
||||||
jest.useFakeTimers().setSystemTime(new Date('2026-09-01T10:00:00Z'));
|
|
||||||
const { portfolio, tbank } = setup();
|
|
||||||
const first = await portfolio.getAll('user');
|
|
||||||
jest.setSystemTime(new Date('2026-09-01T10:01:00Z'));
|
|
||||||
tbank.getPortfolio.mockRejectedValueOnce(new ServiceUnavailableException());
|
|
||||||
const result = await portfolio.getAll('user');
|
|
||||||
expect(result.isStale).toBe(true);
|
|
||||||
expect(result.lastSuccessfulAt).toBe(first.lastSuccessfulAt);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('paginates interleaved streams without dropping buffered rows, preserving duplicate IDs', async () => {
|
|
||||||
const { operations, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockImplementation(
|
|
||||||
(
|
|
||||||
_token: string,
|
|
||||||
{ accountId, cursor }: { accountId: string; cursor?: string },
|
|
||||||
) => {
|
|
||||||
if (accountId === 'a')
|
|
||||||
return cursor
|
|
||||||
? { items: [operation('last', 3)] }
|
|
||||||
: {
|
|
||||||
items: [operation('same', 9), operation('a2', 5)],
|
|
||||||
hasNext: true,
|
|
||||||
nextCursor: 'a-next',
|
|
||||||
};
|
|
||||||
return { items: [operation('same', 8), operation('b2', 4)] };
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const first = await operations.getAll('user', query);
|
|
||||||
assert.ok(first.nextCursor);
|
|
||||||
const second = await operations.getAll('user', {
|
|
||||||
...query,
|
|
||||||
cursor: first.nextCursor,
|
|
||||||
});
|
|
||||||
const repeated = await operations.getAll('user', {
|
|
||||||
...query,
|
|
||||||
cursor: first.nextCursor,
|
|
||||||
});
|
|
||||||
assert.ok(second.nextCursor);
|
|
||||||
const third = await operations.getAll('user', {
|
|
||||||
...query,
|
|
||||||
cursor: second.nextCursor,
|
|
||||||
});
|
|
||||||
expect(first.items.map((item) => [item.id, item.account?.id])).toEqual([
|
|
||||||
['same', 'a'],
|
|
||||||
['same', 'b'],
|
|
||||||
]);
|
|
||||||
expect(second.items.map((item) => item.id)).toEqual(['a2', 'b2']);
|
|
||||||
expect(repeated).toEqual(second);
|
|
||||||
expect(third.items.map((item) => item.id)).toEqual(['last']);
|
|
||||||
expect(third.hasNext).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('continues through empty filtered pages and breaks ties by account', async () => {
|
|
||||||
const { operations, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockImplementation(
|
|
||||||
(_token: string, { cursor }: { cursor?: string }) =>
|
|
||||||
cursor
|
|
||||||
? { items: [operation('income', 5)] }
|
|
||||||
: {
|
|
||||||
items: [operation('fee', 8, 'OPERATION_TYPE_BROKER_FEE')],
|
|
||||||
hasNext: true,
|
|
||||||
nextCursor: 'next',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const page = await operations.getAll('user', {
|
|
||||||
...query,
|
|
||||||
categories: ['income'],
|
|
||||||
});
|
|
||||||
expect(page.items.map((item) => item.account?.id)).toEqual(['a', 'b']);
|
|
||||||
expect(page.items.every((item) => item.category === 'income')).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects damaged cursor chains and partial streams', async () => {
|
|
||||||
const { operations, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockResolvedValue({
|
|
||||||
items: [],
|
|
||||||
hasNext: true,
|
|
||||||
nextCursor: 'loop',
|
|
||||||
});
|
|
||||||
await expect(operations.getAll('user', query)).rejects.toBeInstanceOf(
|
|
||||||
ServiceUnavailableException,
|
|
||||||
);
|
|
||||||
tbank.getOperationsByCursor.mockRejectedValue(
|
|
||||||
new ServiceUnavailableException(),
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
operations.getAll('another-user', query),
|
|
||||||
).rejects.toBeInstanceOf(ServiceUnavailableException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('binds continuations to user, connection, accounts and filters', async () => {
|
|
||||||
const { operations, context, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockResolvedValue({
|
|
||||||
items: [operation('first', 8), operation('last', 4)],
|
|
||||||
});
|
|
||||||
const first = await operations.getAll('user', query);
|
|
||||||
assert.ok(first.nextCursor);
|
|
||||||
const next = { ...query, cursor: first.nextCursor };
|
|
||||||
await expect(operations.getAll('other', next)).rejects.toBeInstanceOf(
|
|
||||||
BadRequestException,
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
operations.getAll('user', { ...next, categories: ['fee'] }),
|
|
||||||
).rejects.toBeInstanceOf(BadRequestException);
|
|
||||||
context.generation = 'replaced';
|
|
||||||
await expect(operations.getAll('user', next)).rejects.toBeInstanceOf(
|
|
||||||
BadRequestException,
|
|
||||||
);
|
|
||||||
context.generation = 'first';
|
|
||||||
context.accounts.pop();
|
|
||||||
await expect(operations.getAll('user', next)).rejects.toBeInstanceOf(
|
|
||||||
BadRequestException,
|
|
||||||
);
|
|
||||||
expect(tbank.getOperationsByCursor).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('collects income across the same cohort and computes comparisons from all receipts', async () => {
|
|
||||||
const { income, tbank } = setup();
|
|
||||||
tbank.getOperationsByCursor.mockImplementation(
|
|
||||||
(
|
|
||||||
_token: string,
|
|
||||||
{ accountId, from }: { accountId: string; from: { seconds: string } },
|
|
||||||
) => {
|
|
||||||
const year = new Date(Number(from.seconds) * 1000).getUTCFullYear();
|
|
||||||
const second =
|
|
||||||
Date.parse(
|
|
||||||
year === 2025 ? '2025-08-15T12:00:00Z' : '2026-08-15T12:00:00Z',
|
|
||||||
) / 1000;
|
|
||||||
return {
|
|
||||||
items:
|
|
||||||
year === 2025 && accountId === 'b'
|
|
||||||
? []
|
|
||||||
: [
|
|
||||||
operation(
|
|
||||||
'same',
|
|
||||||
second,
|
|
||||||
'OPERATION_TYPE_COUPON',
|
|
||||||
year === 2025 ? 2 : 3,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const result = await income.analytics(
|
|
||||||
'user',
|
|
||||||
'all',
|
|
||||||
'2026-08-01',
|
|
||||||
'2026-08-31',
|
|
||||||
);
|
|
||||||
expect(result.totalsByCurrency[0].total.value).toBe('6');
|
|
||||||
expect(
|
|
||||||
result.yearComparison?.totalsByCurrency[0].compared.total.value,
|
|
||||||
).toBe('2');
|
|
||||||
expect(
|
|
||||||
result.yearComparison?.totalsByCurrency[0].difference.total.value,
|
|
||||||
).toBe('4');
|
|
||||||
expect(result.entries.map((entry) => entry.account?.id)).toEqual([
|
|
||||||
'a',
|
|
||||||
'b',
|
|
||||||
]);
|
|
||||||
expect(
|
|
||||||
new Set(result.entries.map((entry) => entry.instrumentKey)).size,
|
|
||||||
).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves separate future events and fails the section when one source fails', async () => {
|
|
||||||
const { events, tbank, moex } = setup();
|
|
||||||
const today = new Date().toISOString().slice(0, 10);
|
|
||||||
tbank.getPortfolio.mockResolvedValue({
|
|
||||||
positions: [
|
|
||||||
{
|
|
||||||
figi: 'BOND',
|
|
||||||
ticker: 'BOND',
|
|
||||||
instrumentType: 'bond',
|
|
||||||
quantity: { units: 2 },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
moex.bondEvents.mockResolvedValue([
|
|
||||||
{ type: 'coupon', date: today, value: '0.1', currency: 'RUB' },
|
|
||||||
]);
|
|
||||||
const result = await events.getAll('user');
|
|
||||||
expect(result.events.map((event) => event.account?.id)).toEqual(['a', 'b']);
|
|
||||||
expect(result.incomeTotalsByCurrency).toEqual([
|
|
||||||
{ currency: 'RUB', value: '0.4' },
|
|
||||||
]);
|
|
||||||
tbank.getPortfolio
|
|
||||||
.mockResolvedValueOnce({ positions: [] })
|
|
||||||
.mockRejectedValueOnce(new ServiceUnavailableException());
|
|
||||||
await expect(events.getAll('user')).rejects.toBeInstanceOf(
|
|
||||||
ServiceUnavailableException,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns valid empty results for an empty account set', async () => {
|
|
||||||
const { context, portfolio, operations, income, events, tbank } = setup();
|
|
||||||
context.accounts = [];
|
|
||||||
expect((await portfolio.getAll('user')).positions).toEqual([]);
|
|
||||||
expect((await operations.getAll('user', query)).hasNext).toBe(false);
|
|
||||||
expect((await income.summary('user', 'all')).totalsByCurrency).toEqual([]);
|
|
||||||
expect((await events.getAll('user')).events).toEqual([]);
|
|
||||||
expect(tbank.getOperationsByCursor).not.toHaveBeenCalled();
|
|
||||||
expect(tbank.getPortfolio).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
import { MoneyDto } from '../../../common/money.dto';
|
import { MoneyDto } from '../../../common/money.dto';
|
||||||
|
import { InvestmentResourceMetaDto } from '../investment-resource.dto';
|
||||||
|
|
||||||
export class PortfolioSummaryDto {
|
export class PortfolioSummaryDto {
|
||||||
@ApiProperty({ type: MoneyDto, isArray: true })
|
@ApiProperty({ type: MoneyDto, isArray: true })
|
||||||
@@ -39,8 +41,18 @@ export class BrokerageAccountDto {
|
|||||||
'BROKERAGE' | 'INDIVIDUAL_INVESTMENT' | 'INVEST_BOX' | 'MONEY_MARKET_FUND';
|
'BROKERAGE' | 'INDIVIDUAL_INVESTMENT' | 'INVEST_BOX' | 'MONEY_MARKET_FUND';
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true, format: 'date' })
|
@ApiProperty({ type: String, nullable: true, format: 'date' })
|
||||||
declare openedOn: string | null;
|
declare openedOn: null | string;
|
||||||
|
|
||||||
|
// eslint-disable-next-line @darraghor/nestjs-typed/api-property-matches-property-optionality -- Preserve the published required nullable schema; partial internal models may omit the field.
|
||||||
@ApiProperty({ type: PortfolioSummaryDto, nullable: true })
|
@ApiProperty({ type: PortfolioSummaryDto, nullable: true })
|
||||||
portfolioSummary?: PortfolioSummaryDto | null;
|
portfolioSummary?: null | PortfolioSummaryDto;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BrokerageAccountsResourceDto {
|
||||||
|
// eslint-disable-next-line @darraghor/nestjs-typed/api-property-returning-array-should-set-array -- Nullable array union requires isArray in the explicit wire schema.
|
||||||
|
@ApiProperty({ type: BrokerageAccountDto, isArray: true, nullable: true })
|
||||||
|
declare data: BrokerageAccountDto[] | null;
|
||||||
|
|
||||||
|
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||||
|
declare meta: InvestmentResourceMetaDto;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
|
|
||||||
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
|
|
||||||
|
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||||
|
|
||||||
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
||||||
import { BrokerageAccountDto } from './brokerage-account.dto';
|
import { InvestmentReadQueryDto } from '../investment-resource.dto';
|
||||||
|
import { BrokerageAccountsResourceDto } from './brokerage-account.dto';
|
||||||
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
|
|
||||||
@ApiTags('brokerage-accounts')
|
@ApiTags('brokerage-accounts')
|
||||||
@@ -15,8 +18,11 @@ export class BrokerageAccountsController {
|
|||||||
constructor(private readonly accounts: BrokerageAccountsService) {}
|
constructor(private readonly accounts: BrokerageAccountsService) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@ApiOkResponse({ type: BrokerageAccountDto, isArray: true })
|
@ApiOkResponse({ type: BrokerageAccountsResourceDto })
|
||||||
list(@Req() request: Request & { user: AccessPayload }) {
|
list(
|
||||||
return this.accounts.list(request.user.sub);
|
@Req() request: Request & { user: AccessPayload },
|
||||||
|
@Query() query: InvestmentReadQueryDto,
|
||||||
|
) {
|
||||||
|
return this.accounts.list(request.user.sub, query.sync === 'observe');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { TbankModule } from '../../../integrations/tbank/tbank.module';
|
import { TbankModule } from '../../../integrations/tbank/tbank.module';
|
||||||
import { AuthModule } from '../../auth/auth.module';
|
import { AuthModule } from '../../auth/auth.module';
|
||||||
|
import { PortfolioModule } from '../portfolio/portfolio.module';
|
||||||
import { BrokerageAccountsController } from './brokerage-accounts.controller';
|
import { BrokerageAccountsController } from './brokerage-accounts.controller';
|
||||||
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [AuthModule, TbankModule],
|
imports: [AuthModule, TbankModule, PortfolioModule],
|
||||||
controllers: [BrokerageAccountsController],
|
controllers: [BrokerageAccountsController],
|
||||||
providers: [BrokerageAccountsService],
|
providers: [BrokerageAccountsService],
|
||||||
|
exports: [BrokerageAccountsService],
|
||||||
})
|
})
|
||||||
export class BrokerageAccountsModule {}
|
export class BrokerageAccountsModule {}
|
||||||
|
|||||||
@@ -1,249 +1,70 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
|
|
||||||
jest.mock('../../../prisma/prisma.service', () => ({
|
jest.mock('../../../prisma/prisma.service', () => ({
|
||||||
PrismaService: class PrismaService {},
|
PrismaService: class {},
|
||||||
}));
|
}));
|
||||||
|
import { investmentResourceMeta } from '../investment-resource.mapper';
|
||||||
import { TbankAccessService } from '../../../integrations/tbank/tbank-access.service';
|
|
||||||
import { TbankTokenService } from '../../../integrations/tbank/tbank-token.service';
|
|
||||||
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
|
|
||||||
describe('BrokerageAccountsService', () => {
|
jest.mock('../portfolio/application/portfolio.service', () => ({
|
||||||
const encryptionKey = 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=';
|
PortfolioService: class PortfolioService {},
|
||||||
const prisma = { tbankConnection: { findUnique: jest.fn() } };
|
}));
|
||||||
const config = { getOrThrow: jest.fn(() => encryptionKey) };
|
|
||||||
const tbank = {
|
|
||||||
getOpenAccounts: jest.fn(),
|
|
||||||
getPortfolio: jest.fn(),
|
|
||||||
getPositions: jest.fn(),
|
|
||||||
};
|
|
||||||
const tokens = new TbankTokenService(config as never);
|
|
||||||
const access = new TbankAccessService(
|
|
||||||
prisma as never,
|
|
||||||
tokens,
|
|
||||||
tbank as never,
|
|
||||||
);
|
|
||||||
const service = new BrokerageAccountsService(access, tbank as never);
|
|
||||||
|
|
||||||
beforeEach(() => {
|
const meta = investmentResourceMeta({
|
||||||
jest.clearAllMocks();
|
resourceKey: 'membership',
|
||||||
tbank.getPortfolio.mockResolvedValue({ positions: [] });
|
dataRevision: '1',
|
||||||
tbank.getPositions.mockResolvedValue({ money: [] });
|
availability: 'complete',
|
||||||
});
|
fetchedAt: new Date(),
|
||||||
|
freshForMs: 300_000,
|
||||||
|
work: null,
|
||||||
|
});
|
||||||
|
|
||||||
it('does not call T-Bank without a connection', async () => {
|
describe('saved brokerage account projection', () => {
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue(null);
|
const portfolio = { saved: jest.fn() };
|
||||||
|
const service = new BrokerageAccountsService(portfolio as never);
|
||||||
|
|
||||||
await expect(service.list('user-1')).rejects.toEqual(
|
it('distinguishes unknown membership from a confirmed empty list', async () => {
|
||||||
expect.any(ConflictException),
|
portfolio.saved.mockResolvedValueOnce({
|
||||||
);
|
membership: { ...meta, availability: 'missing' },
|
||||||
expect(tbank.getOpenAccounts).not.toHaveBeenCalled();
|
accounts: [],
|
||||||
});
|
|
||||||
|
|
||||||
it('normalizes supported accounts and ignores unsupported ones', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
});
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
expect((await service.list('owner', true)).data).toBeNull();
|
||||||
{
|
portfolio.saved.mockResolvedValueOnce({ membership: meta, accounts: [] });
|
||||||
id: 'brokerage',
|
expect((await service.list('owner', true)).data).toEqual([]);
|
||||||
type: 'ACCOUNT_TYPE_TINKOFF',
|
|
||||||
name: ' Основной ',
|
|
||||||
openedDate: { seconds: '1723507200' },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'debit',
|
|
||||||
type: 'ACCOUNT_TYPE_DEBIT',
|
|
||||||
name: 'Дебетовый',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'iis',
|
|
||||||
type: 'ACCOUNT_TYPE_TINKOFF_IIS',
|
|
||||||
name: ' ',
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).resolves.toEqual([
|
|
||||||
{
|
|
||||||
id: 'brokerage',
|
|
||||||
type: 'BROKERAGE',
|
|
||||||
name: 'Основной',
|
|
||||||
openedOn: '2024-08-13',
|
|
||||||
portfolioSummary: {
|
|
||||||
totalsByCurrency: [],
|
|
||||||
stockPositionCount: 0,
|
|
||||||
bondPositionCount: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'iis',
|
|
||||||
type: 'INDIVIDUAL_INVESTMENT',
|
|
||||||
name: 'ИИС',
|
|
||||||
openedOn: null,
|
|
||||||
portfolioSummary: {
|
|
||||||
totalsByCurrency: [],
|
|
||||||
stockPositionCount: 0,
|
|
||||||
bondPositionCount: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps upstream order and adds exact summaries without loading metadata', async () => {
|
it('keeps exact saved totals and independent missing summaries', async () => {
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
portfolio.saved.mockResolvedValue({
|
||||||
encryptedToken: tokens.encrypt('token'),
|
membership: meta,
|
||||||
});
|
accounts: [
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
{
|
||||||
{ id: 'first', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Первый' },
|
id: 'a',
|
||||||
{ id: 'second', type: 'ACCOUNT_TYPE_TINKOFF_IIS', name: 'Второй' },
|
name: 'A',
|
||||||
]);
|
type: 'BROKERAGE',
|
||||||
tbank.getPortfolio
|
openedOn: null,
|
||||||
.mockResolvedValueOnce({
|
meta,
|
||||||
positions: [
|
snapshot: {
|
||||||
{
|
totalsByCurrency: [
|
||||||
quantity: { units: 2 },
|
{ currency: 'RUB', value: '100000000.000000001' },
|
||||||
currentPrice: { currency: 'rub', units: 3 },
|
],
|
||||||
|
positions: [{ type: 'STOCK' }, { type: 'BOND' }],
|
||||||
},
|
},
|
||||||
],
|
|
||||||
})
|
|
||||||
.mockResolvedValueOnce({ positions: [] });
|
|
||||||
tbank.getPositions
|
|
||||||
.mockResolvedValueOnce({ money: [{ currency: 'RUB', nano: 500000000 }] })
|
|
||||||
.mockResolvedValueOnce({ money: [{ currency: 'USD', units: 4 }] });
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).resolves.toEqual([
|
|
||||||
{
|
|
||||||
id: 'first',
|
|
||||||
type: 'BROKERAGE',
|
|
||||||
name: 'Первый',
|
|
||||||
openedOn: null,
|
|
||||||
portfolioSummary: {
|
|
||||||
totalsByCurrency: [{ currency: 'RUB', value: '6.5' }],
|
|
||||||
stockPositionCount: 0,
|
|
||||||
bondPositionCount: 0,
|
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
id: 'b',
|
||||||
id: 'second',
|
name: 'B',
|
||||||
type: 'INDIVIDUAL_INVESTMENT',
|
type: 'BROKERAGE',
|
||||||
name: 'Второй',
|
openedOn: null,
|
||||||
openedOn: null,
|
meta: { ...meta, availability: 'missing' },
|
||||||
portfolioSummary: {
|
snapshot: null,
|
||||||
totalsByCurrency: [{ currency: 'USD', value: '4' }],
|
|
||||||
stockPositionCount: 0,
|
|
||||||
bondPositionCount: 0,
|
|
||||||
},
|
},
|
||||||
},
|
|
||||||
]);
|
|
||||||
expect(tbank.getPortfolio).toHaveBeenCalledWith('token', 'first');
|
|
||||||
expect(tbank.getPositions).toHaveBeenCalledWith('token', 'second');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('counts non-zero stock and bond positions even without a valuation', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
|
||||||
{ id: 'account', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Основной' },
|
|
||||||
]);
|
|
||||||
tbank.getPortfolio.mockResolvedValue({
|
|
||||||
positions: [
|
|
||||||
{ instrumentType: 'share', quantity: { units: 200 } },
|
|
||||||
{ instrumentType: 'SHARE', quantity: { units: -5 } },
|
|
||||||
{ instrumentType: 'share', quantity: { units: 0, nano: 1 } },
|
|
||||||
{ instrumentType: 'bond', quantity: { units: 80 } },
|
|
||||||
{ instrumentType: 'bond', quantity: { units: 0 } },
|
|
||||||
{ instrumentType: 'share' },
|
|
||||||
{ instrumentType: 'etf', quantity: { units: 10 } },
|
|
||||||
{ instrumentType: 'currency', quantity: { units: 100 } },
|
|
||||||
{ quantity: { units: 1 } },
|
|
||||||
],
|
],
|
||||||
virtualPositions: [{ instrumentType: 'bond', quantity: { units: 1 } }],
|
|
||||||
});
|
});
|
||||||
|
const response = await service.list('owner', true);
|
||||||
await expect(service.list('user-1')).resolves.toMatchObject([
|
expect(response.data?.[0].portfolioSummary).toEqual({
|
||||||
{
|
totalsByCurrency: [{ currency: 'RUB', value: '100000000.000000001' }],
|
||||||
portfolioSummary: {
|
stockPositionCount: 1,
|
||||||
totalsByCurrency: [],
|
bondPositionCount: 1,
|
||||||
stockPositionCount: 3,
|
|
||||||
bondPositionCount: 1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('localizes an unavailable summary without suppressing another account', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
});
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
expect(response.data?.[1].portfolioSummary).toBeNull();
|
||||||
{ id: 'unavailable', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Первый' },
|
expect(response.meta.availability).toBe('partial');
|
||||||
{ id: 'available', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Второй' },
|
|
||||||
]);
|
|
||||||
tbank.getPortfolio
|
|
||||||
.mockRejectedValueOnce(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
)
|
|
||||||
.mockResolvedValueOnce({ positions: [] });
|
|
||||||
tbank.getPositions.mockResolvedValue({ money: [] });
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).resolves.toMatchObject([
|
|
||||||
{ id: 'unavailable', portfolioSummary: null },
|
|
||||||
{ id: 'available', portfolioSummary: { totalsByCurrency: [] } },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not mask an invalid token when the other summary input is unavailable', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockResolvedValue([
|
|
||||||
{ id: 'account', type: 'ACCOUNT_TYPE_TINKOFF', name: 'Основной' },
|
|
||||||
]);
|
|
||||||
tbank.getPortfolio.mockRejectedValue(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
);
|
|
||||||
tbank.getPositions.mockRejectedValue(new Error('INVALID_TBANK_TOKEN'));
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).rejects.toEqual(
|
|
||||||
expect.any(BadRequestException),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retains the connection when T-Bank rejects its token', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockRejectedValue(new Error('INVALID_TBANK_TOKEN'));
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).rejects.toEqual(
|
|
||||||
expect.any(BadRequestException),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns an empty list from T-Bank unchanged', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockResolvedValue([]);
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).resolves.toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates an unavailable T-Bank response', async () => {
|
|
||||||
prisma.tbankConnection.findUnique.mockResolvedValue({
|
|
||||||
encryptedToken: tokens.encrypt('token'),
|
|
||||||
});
|
|
||||||
tbank.getOpenAccounts.mockRejectedValue(
|
|
||||||
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.list('user-1')).rejects.toEqual(
|
|
||||||
expect.any(ServiceUnavailableException),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,80 +1,66 @@
|
|||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { isZero } from '../../../common/decimal';
|
import { createHash } from 'node:crypto';
|
||||||
import {
|
|
||||||
TbankAccessService,
|
import { investmentResourceMeta } from '../investment-resource.mapper';
|
||||||
TbankClient,
|
import { PortfolioService } from '../portfolio/portfolio.api';
|
||||||
} from '../../../integrations/tbank/tbank.api';
|
|
||||||
import { decimal } from '../../../integrations/tbank/decimal';
|
|
||||||
import { totalsByCurrency } from '../portfolio/portfolio.api';
|
|
||||||
import { BrokerageAccountDto } from './brokerage-account.dto';
|
import { BrokerageAccountDto } from './brokerage-account.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BrokerageAccountsService {
|
export class BrokerageAccountsService {
|
||||||
constructor(
|
constructor(private readonly portfolio: PortfolioService) {}
|
||||||
private readonly access: TbankAccessService,
|
|
||||||
private readonly tbank: TbankClient,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async list(userId: string): Promise<BrokerageAccountDto[]> {
|
async list(userId: string, observe = false) {
|
||||||
return this.access.withSupportedAccounts(
|
const saved = await this.portfolio.saved(userId, 'all', observe);
|
||||||
userId,
|
const data: BrokerageAccountDto[] | null =
|
||||||
async ({ token, accounts }) =>
|
saved.membership.availability === 'missing' ?
|
||||||
Promise.all(
|
null :
|
||||||
accounts.map(async (account) => {
|
saved.accounts.map((account) => ({
|
||||||
const [portfolioResult, positionsResult] = await Promise.allSettled(
|
id: account.id,
|
||||||
[
|
name: account.name,
|
||||||
this.tbank.getPortfolio(token, account.id),
|
type: account.type as BrokerageAccountDto['type'],
|
||||||
this.tbank.getPositions(token, account.id),
|
openedOn: account.openedOn,
|
||||||
],
|
portfolioSummary: account.snapshot ?
|
||||||
);
|
{
|
||||||
if (
|
totalsByCurrency: account.snapshot.totalsByCurrency,
|
||||||
portfolioResult.status === 'rejected' &&
|
stockPositionCount: account.snapshot.positions.filter(
|
||||||
!isTbankUnavailable(portfolioResult.reason)
|
(position) => position.type === 'STOCK',
|
||||||
)
|
).length,
|
||||||
throw portfolioResult.reason;
|
bondPositionCount: account.snapshot.positions.filter(
|
||||||
if (
|
(position) => position.type === 'BOND',
|
||||||
positionsResult.status === 'rejected' &&
|
).length,
|
||||||
!isTbankUnavailable(positionsResult.reason)
|
} :
|
||||||
)
|
null,
|
||||||
throw positionsResult.reason;
|
}));
|
||||||
if (
|
return {
|
||||||
portfolioResult.status === 'rejected' ||
|
data,
|
||||||
positionsResult.status === 'rejected'
|
meta: investmentResourceMeta({
|
||||||
)
|
resourceKey: 'accounts',
|
||||||
return { ...account, portfolioSummary: null };
|
dataRevision: createHash('sha256')
|
||||||
const positions = portfolioResult.value.positions ?? [];
|
.update(
|
||||||
let stockPositionCount = 0;
|
JSON.stringify([
|
||||||
let bondPositionCount = 0;
|
saved.membership.dataRevision,
|
||||||
for (const position of positions) {
|
saved.accounts.map((account) => [
|
||||||
if (isZero(decimal(position.quantity ?? {}))) continue;
|
account.id,
|
||||||
const type = position.instrumentType?.toLowerCase();
|
account.meta.dataRevision,
|
||||||
if (type === 'share') stockPositionCount += 1;
|
]),
|
||||||
if (type === 'bond') bondPositionCount += 1;
|
]),
|
||||||
}
|
)
|
||||||
return {
|
.digest('base64url'),
|
||||||
...account,
|
availability:
|
||||||
portfolioSummary: {
|
data === null ?
|
||||||
totalsByCurrency: totalsByCurrency(
|
'missing' :
|
||||||
positions,
|
saved.accounts.some((account) => !account.snapshot) ?
|
||||||
positionsResult.value.money ?? [],
|
'partial' :
|
||||||
),
|
'complete',
|
||||||
stockPositionCount,
|
fetchedAt: saved.membership.lastSuccessfulAt ?
|
||||||
bondPositionCount,
|
new Date(saved.membership.lastSuccessfulAt) :
|
||||||
},
|
null,
|
||||||
};
|
freshForMs: 300_000,
|
||||||
}),
|
work: saved.membership.sync.id ?
|
||||||
),
|
{ ...saved.membership.sync, id: saved.membership.sync.id } :
|
||||||
);
|
null,
|
||||||
|
dependencies: saved.accounts.map((account) => account.meta),
|
||||||
|
}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isTbankUnavailable(error: unknown): boolean {
|
|
||||||
if (!(error instanceof ServiceUnavailableException)) return false;
|
|
||||||
const response = error.getResponse();
|
|
||||||
return (
|
|
||||||
typeof response === 'object' &&
|
|
||||||
response !== null &&
|
|
||||||
'code' in response &&
|
|
||||||
response.code === 'TBANK_UNAVAILABLE'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
|
import type { Request } from 'express';
|
||||||
|
|
||||||
import { Controller, Get, Param, Query, Req, UseGuards } from '@nestjs/common';
|
import { Controller, Get, Param, Query, Req, UseGuards } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||||
import type { Request } from 'express';
|
|
||||||
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
||||||
|
import { InvestmentReadQueryDto } from '../investment-resource.dto';
|
||||||
import {
|
import {
|
||||||
IncomeAnalyticsDto,
|
|
||||||
IncomeAnalyticsQueryDto,
|
IncomeAnalyticsQueryDto,
|
||||||
IncomeSummaryDto,
|
IncomeAnalyticsResourceDto,
|
||||||
|
IncomeSummaryResourceDto,
|
||||||
} from './income-analytics.dto';
|
} from './income-analytics.dto';
|
||||||
import { IncomeAnalyticsService } from './income-analytics.service';
|
import { IncomeAnalyticsService } from './income-analytics.service';
|
||||||
|
|
||||||
@@ -19,31 +22,49 @@ export class IncomeAnalyticsController {
|
|||||||
constructor(private readonly income: IncomeAnalyticsService) {}
|
constructor(private readonly income: IncomeAnalyticsService) {}
|
||||||
|
|
||||||
@Get('all/income-summary')
|
@Get('all/income-summary')
|
||||||
@ApiOkResponse({ type: IncomeSummaryDto })
|
@ApiOkResponse({ type: IncomeSummaryResourceDto })
|
||||||
allSummary(@Req() request: Request & { user: AccessPayload }) {
|
allSummary(
|
||||||
return this.income.summary(request.user.sub, 'all');
|
@Req() request: Request & { user: AccessPayload },
|
||||||
|
@Query() query: InvestmentReadQueryDto,
|
||||||
|
) {
|
||||||
|
return this.income.summary(
|
||||||
|
request.user.sub,
|
||||||
|
'all',
|
||||||
|
query.sync === 'observe',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('all/income-analytics')
|
@Get('all/income-analytics')
|
||||||
@ApiOkResponse({ type: IncomeAnalyticsDto })
|
@ApiOkResponse({ type: IncomeAnalyticsResourceDto })
|
||||||
allAnalytics(
|
allAnalytics(
|
||||||
@Req() request: Request & { user: AccessPayload },
|
@Req() request: Request & { user: AccessPayload },
|
||||||
@Query() query: IncomeAnalyticsQueryDto,
|
@Query() query: IncomeAnalyticsQueryDto,
|
||||||
) {
|
) {
|
||||||
return this.income.analytics(request.user.sub, 'all', query.from, query.to);
|
return this.income.analytics(
|
||||||
|
request.user.sub,
|
||||||
|
'all',
|
||||||
|
query.from,
|
||||||
|
query.to,
|
||||||
|
query.sync === 'observe',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':accountId/income-summary')
|
@Get(':accountId/income-summary')
|
||||||
@ApiOkResponse({ type: IncomeSummaryDto })
|
@ApiOkResponse({ type: IncomeSummaryResourceDto })
|
||||||
summary(
|
summary(
|
||||||
@Req() request: Request & { user: AccessPayload },
|
@Req() request: Request & { user: AccessPayload },
|
||||||
@Param('accountId') accountId: string,
|
@Param('accountId') accountId: string,
|
||||||
|
@Query() query: InvestmentReadQueryDto,
|
||||||
) {
|
) {
|
||||||
return this.income.summary(request.user.sub, accountId);
|
return this.income.summary(
|
||||||
|
request.user.sub,
|
||||||
|
accountId,
|
||||||
|
query.sync === 'observe',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':accountId/income-analytics')
|
@Get(':accountId/income-analytics')
|
||||||
@ApiOkResponse({ type: IncomeAnalyticsDto })
|
@ApiOkResponse({ type: IncomeAnalyticsResourceDto })
|
||||||
analytics(
|
analytics(
|
||||||
@Req() request: Request & { user: AccessPayload },
|
@Req() request: Request & { user: AccessPayload },
|
||||||
@Param('accountId') accountId: string,
|
@Param('accountId') accountId: string,
|
||||||
@@ -54,6 +75,7 @@ export class IncomeAnalyticsController {
|
|||||||
accountId,
|
accountId,
|
||||||
query.from,
|
query.from,
|
||||||
query.to,
|
query.to,
|
||||||
|
query.sync === 'observe',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,31 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { IsOptional, Matches } from 'class-validator';
|
import { IsOptional, Matches } from 'class-validator';
|
||||||
|
|
||||||
import { MoneyDto } from '../../../common/money.dto';
|
import { MoneyDto } from '../../../common/money.dto';
|
||||||
|
import {
|
||||||
|
InvestmentDependencyDto,
|
||||||
|
InvestmentReadQueryDto,
|
||||||
|
InvestmentResourceMetaDto,
|
||||||
|
} from '../investment-resource.dto';
|
||||||
import { BrokerageOperationDto } from '../operations/operations.api';
|
import { BrokerageOperationDto } from '../operations/operations.api';
|
||||||
|
|
||||||
const dateOnly = /^\d{4}-\d{2}-\d{2}$/;
|
const dateOnly = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
export class IncomeAnalyticsQueryDto {
|
export class IncomeAnalyticsQueryDto extends InvestmentReadQueryDto {
|
||||||
@ApiPropertyOptional({ format: 'date' })
|
@ApiPropertyOptional({
|
||||||
|
format: 'date',
|
||||||
|
description:
|
||||||
|
'Inclusive calendar date in Europe/Moscow. Supply both from/to or neither.',
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Matches(dateOnly)
|
@Matches(dateOnly)
|
||||||
from?: string;
|
from?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ format: 'date' })
|
@ApiPropertyOptional({
|
||||||
|
format: 'date',
|
||||||
|
description:
|
||||||
|
'Inclusive calendar date in Europe/Moscow, no later than today. Supply both from/to or neither.',
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Matches(dateOnly)
|
@Matches(dateOnly)
|
||||||
to?: string;
|
to?: string;
|
||||||
@@ -88,16 +102,16 @@ export class IncomeInstrumentDto {
|
|||||||
declare key: string;
|
declare key: string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
declare figi: string | null;
|
declare figi: null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
declare instrumentUid: string | null;
|
declare instrumentUid: null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
declare ticker: string | null;
|
declare ticker: null | string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
declare instrumentType: string | null;
|
declare instrumentType: null | string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
declare displayName: string;
|
declare displayName: string;
|
||||||
@@ -121,14 +135,14 @@ export class IncomeAnalyticsEntryDto extends BrokerageOperationDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeAnalyticsDto extends IncomeSummaryDto {
|
export class IncomeAnalyticsDto extends IncomeSummaryDto {
|
||||||
@ApiProperty({ type: IncomeComparisonDto })
|
@ApiProperty({ type: IncomeComparisonDto, nullable: true })
|
||||||
declare previous: IncomeComparisonDto;
|
declare previous: IncomeComparisonDto | null;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeComparisonDto, nullable: true })
|
@ApiProperty({ type: IncomeComparisonDto, nullable: true })
|
||||||
declare yearComparison: IncomeComparisonDto | null;
|
declare yearComparison: IncomeComparisonDto | null;
|
||||||
|
|
||||||
@ApiProperty({ enum: ['day', 'week', 'month'] })
|
@ApiProperty({ enum: ['day', 'week', 'month'] })
|
||||||
declare bucketGranularity: 'day' | 'week' | 'month';
|
declare bucketGranularity: 'day' | 'month' | 'week';
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeBucketDto, isArray: true })
|
@ApiProperty({ type: IncomeBucketDto, isArray: true })
|
||||||
declare buckets: IncomeBucketDto[];
|
declare buckets: IncomeBucketDto[];
|
||||||
@@ -139,3 +153,38 @@ export class IncomeAnalyticsDto extends IncomeSummaryDto {
|
|||||||
@ApiProperty({ type: IncomeAnalyticsEntryDto, isArray: true })
|
@ApiProperty({ type: IncomeAnalyticsEntryDto, isArray: true })
|
||||||
declare entries: IncomeAnalyticsEntryDto[];
|
declare entries: IncomeAnalyticsEntryDto[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class IncomeSummaryResourceDto {
|
||||||
|
@ApiProperty({ type: IncomeSummaryDto, nullable: true })
|
||||||
|
declare data: IncomeSummaryDto | null;
|
||||||
|
|
||||||
|
@ApiProperty({ type: InvestmentResourceMetaDto })
|
||||||
|
declare meta: InvestmentResourceMetaDto;
|
||||||
|
}
|
||||||
|
|
||||||
|
const incomeDependencyRoles = ['selected', 'previous', 'year'] as const;
|
||||||
|
|
||||||
|
export class IncomeDependencyDto extends InvestmentDependencyDto {
|
||||||
|
@ApiProperty({ enum: incomeDependencyRoles })
|
||||||
|
declare role: (typeof incomeDependencyRoles)[number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class IncomeAnalyticsMetaDto extends InvestmentResourceMetaDto {
|
||||||
|
// eslint-disable-next-line @darraghor/nestjs-typed/api-property-matches-property-optionality -- Overrides optional dependencies inherited from InvestmentResourceMetaDto.
|
||||||
|
@ApiProperty({
|
||||||
|
type: IncomeDependencyDto,
|
||||||
|
isArray: true,
|
||||||
|
required: true,
|
||||||
|
description:
|
||||||
|
'Dependencies identified by role, not array order or resourceKey. A missing role is unavailable.',
|
||||||
|
})
|
||||||
|
declare dependencies: IncomeDependencyDto[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class IncomeAnalyticsResourceDto {
|
||||||
|
@ApiProperty({ type: IncomeAnalyticsDto, nullable: true })
|
||||||
|
declare data: IncomeAnalyticsDto | null;
|
||||||
|
|
||||||
|
@ApiProperty({ type: IncomeAnalyticsMetaDto })
|
||||||
|
declare meta: IncomeAnalyticsMetaDto;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
|
jest.mock('../../../prisma/prisma.service', () => ({
|
||||||
|
PrismaService: class {},
|
||||||
|
}));
|
||||||
jest.mock('../operations/application/brokerage-operations.service', () => ({
|
jest.mock('../operations/application/brokerage-operations.service', () => ({
|
||||||
BrokerageOperationsService: class BrokerageOperationsService {},
|
BrokerageOperationsService: class BrokerageOperationsService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
|
import { investmentResourceMeta } from '../investment-resource.mapper';
|
||||||
import { BrokerageOperationDto } from '../operations/presentation/brokerage-operation.dto';
|
import { BrokerageOperationDto } from '../operations/presentation/brokerage-operation.dto';
|
||||||
import { IncomeAnalyticsService } from './income-analytics.service';
|
import { IncomeAnalyticsService } from './income-analytics.service';
|
||||||
|
|
||||||
@@ -11,6 +17,44 @@ describe('IncomeAnalyticsService', () => {
|
|||||||
|
|
||||||
beforeEach(() => jest.clearAllMocks());
|
beforeEach(() => jest.clearAllMocks());
|
||||||
|
|
||||||
|
it('labels each comparison dependency independently of its resource key', async () => {
|
||||||
|
seed([]);
|
||||||
|
const response = await service.analytics(
|
||||||
|
'user',
|
||||||
|
'account',
|
||||||
|
'2026-01-01',
|
||||||
|
'2026-01-31',
|
||||||
|
);
|
||||||
|
expect(response.meta.dependencies).toEqual([
|
||||||
|
expect.objectContaining({ role: 'selected', resourceKey: 'period/0' }),
|
||||||
|
expect.objectContaining({ role: 'previous', resourceKey: 'period/1' }),
|
||||||
|
expect.objectContaining({ role: 'year', resourceKey: 'period/2' }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('labels an unavailable leap-day comparison as year', async () => {
|
||||||
|
operations.collectRanges.mockImplementation(
|
||||||
|
(_user: string, _account: string, build: () => unknown[]) =>
|
||||||
|
build().map((_, index) => ({ items: [], meta: completeMeta(index) })),
|
||||||
|
);
|
||||||
|
const response = await service.analytics(
|
||||||
|
'user',
|
||||||
|
'account',
|
||||||
|
'2024-02-29',
|
||||||
|
'2024-02-29',
|
||||||
|
);
|
||||||
|
expect(response.meta.dependencies).toEqual([
|
||||||
|
expect.objectContaining({ role: 'selected' }),
|
||||||
|
expect.objectContaining({ role: 'previous' }),
|
||||||
|
expect.objectContaining({
|
||||||
|
role: 'year',
|
||||||
|
availability: 'missing',
|
||||||
|
unavailableReason: 'CALENDAR_OR_ACCOUNT_HISTORY',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
expect(response.data?.yearComparison).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
function seed(items: BrokerageOperationDto[]) {
|
function seed(items: BrokerageOperationDto[]) {
|
||||||
operations.collectRanges.mockImplementation(
|
operations.collectRanges.mockImplementation(
|
||||||
(
|
(
|
||||||
@@ -19,7 +63,10 @@ describe('IncomeAnalyticsService', () => {
|
|||||||
build: (opened?: Date) => unknown[],
|
build: (opened?: Date) => unknown[],
|
||||||
) => {
|
) => {
|
||||||
build(undefined);
|
build(undefined);
|
||||||
return { pages: [[{ items }], [{ items: [] }], [{ items: [] }]] };
|
return [items, [], []].map((items, index) => ({
|
||||||
|
items,
|
||||||
|
meta: completeMeta(index),
|
||||||
|
}));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -57,13 +104,15 @@ describe('IncomeAnalyticsService', () => {
|
|||||||
};
|
};
|
||||||
seed([payment]);
|
seed([payment]);
|
||||||
|
|
||||||
const result = await service.analytics(
|
const response = await service.analytics(
|
||||||
'user',
|
'user',
|
||||||
'account',
|
'account',
|
||||||
'2026-01-01',
|
'2026-01-01',
|
||||||
'2026-01-31',
|
'2026-01-31',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const result = response.data;
|
||||||
|
assert(result);
|
||||||
expect(result.entries).toEqual([{ ...payment, instrumentKey: key }]);
|
expect(result.entries).toEqual([{ ...payment, instrumentKey: key }]);
|
||||||
expect(result.instruments).toEqual([
|
expect(result.instruments).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
@@ -92,13 +141,15 @@ describe('IncomeAnalyticsService', () => {
|
|||||||
];
|
];
|
||||||
seed(selected);
|
seed(selected);
|
||||||
|
|
||||||
const result = await service.analytics(
|
const response = await service.analytics(
|
||||||
'user',
|
'user',
|
||||||
'account',
|
'account',
|
||||||
'2026-01-01',
|
'2026-01-01',
|
||||||
'2026-01-31',
|
'2026-01-31',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const result = response.data;
|
||||||
|
assert(result);
|
||||||
expect(result.entries).toEqual(
|
expect(result.entries).toEqual(
|
||||||
selected.map((item) => ({
|
selected.map((item) => ({
|
||||||
...item,
|
...item,
|
||||||
@@ -146,37 +197,28 @@ describe('IncomeAnalyticsService', () => {
|
|||||||
build: (opened?: Date) => unknown[],
|
build: (opened?: Date) => unknown[],
|
||||||
) => {
|
) => {
|
||||||
build(undefined);
|
build(undefined);
|
||||||
return {
|
return [
|
||||||
pages: [
|
[
|
||||||
[
|
entry('coupon', 'OPERATION_TYPE_COUPON', '10.25', 'RUB'),
|
||||||
{
|
entry('dividend', 'OPERATION_TYPE_DIVIDEND', '-2.5', 'RUB'),
|
||||||
items: [
|
entry('transfer', 'OPERATION_TYPE_DIVIDEND_TRANSFER', '99', 'RUB'),
|
||||||
entry('coupon', 'OPERATION_TYPE_COUPON', '10.25', 'RUB'),
|
entry('usd', 'OPERATION_TYPE_COUPON', '1', 'USD'),
|
||||||
entry('dividend', 'OPERATION_TYPE_DIVIDEND', '-2.5', 'RUB'),
|
|
||||||
entry(
|
|
||||||
'transfer',
|
|
||||||
'OPERATION_TYPE_DIVIDEND_TRANSFER',
|
|
||||||
'99',
|
|
||||||
'RUB',
|
|
||||||
),
|
|
||||||
entry('usd', 'OPERATION_TYPE_COUPON', '1', 'USD'),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[{ items: [] }],
|
|
||||||
[{ items: [] }],
|
|
||||||
],
|
],
|
||||||
};
|
[],
|
||||||
|
[],
|
||||||
|
].map((items, index) => ({ items, meta: completeMeta(index) }));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = await service.analytics(
|
const response = await service.analytics(
|
||||||
'user',
|
'user',
|
||||||
'account',
|
'account',
|
||||||
'2026-01-01',
|
'2026-01-01',
|
||||||
'2026-01-31',
|
'2026-01-31',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const result = response.data;
|
||||||
|
assert(result);
|
||||||
expect(result.totalsByCurrency).toEqual([
|
expect(result.totalsByCurrency).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
currency: 'RUB',
|
currency: 'RUB',
|
||||||
@@ -222,3 +264,14 @@ function entry(
|
|||||||
commission: null,
|
commission: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function completeMeta(index: number) {
|
||||||
|
return investmentResourceMeta({
|
||||||
|
resourceKey: `period/${index}`,
|
||||||
|
dataRevision: '1',
|
||||||
|
availability: 'complete',
|
||||||
|
fetchedAt: new Date('2026-02-01Z'),
|
||||||
|
freshForMs: Infinity,
|
||||||
|
work: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
add,
|
add,
|
||||||
compare,
|
compare,
|
||||||
@@ -7,18 +9,20 @@ import {
|
|||||||
subtract,
|
subtract,
|
||||||
} from '../../../common/decimal';
|
} from '../../../common/decimal';
|
||||||
import { DateOnlyRange, moscowDate } from '../investment-calendar';
|
import { DateOnlyRange, moscowDate } from '../investment-calendar';
|
||||||
|
import { investmentResourceMeta } from '../investment-resource.mapper';
|
||||||
import {
|
import {
|
||||||
BrokerageOperationDto,
|
BrokerageOperationDto,
|
||||||
BrokerageOperationsService,
|
BrokerageOperationsService,
|
||||||
} from '../operations/operations.api';
|
} from '../operations/operations.api';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
IncomeAnalyticsDto,
|
|
||||||
IncomeAnalyticsEntryDto,
|
IncomeAnalyticsEntryDto,
|
||||||
|
IncomeAnalyticsResourceDto,
|
||||||
IncomeComparisonDto,
|
IncomeComparisonDto,
|
||||||
IncomeCurrencySummaryDto,
|
IncomeCurrencySummaryDto,
|
||||||
|
IncomeDependencyDto,
|
||||||
IncomeInstrumentDto,
|
IncomeInstrumentDto,
|
||||||
IncomeSummaryDto,
|
IncomeSummaryDto,
|
||||||
|
IncomeSummaryResourceDto,
|
||||||
} from './income-analytics.dto';
|
} from './income-analytics.dto';
|
||||||
import {
|
import {
|
||||||
IncomeBucketGranularity,
|
IncomeBucketGranularity,
|
||||||
@@ -26,6 +30,8 @@ import {
|
|||||||
rangeBuckets,
|
rangeBuckets,
|
||||||
} from './income-period';
|
} from './income-period';
|
||||||
|
|
||||||
|
const STALE_FRESHNESS_MS = 0;
|
||||||
|
|
||||||
type Total = {
|
type Total = {
|
||||||
coupon: ReturnType<typeof decimalFromString>;
|
coupon: ReturnType<typeof decimalFromString>;
|
||||||
dividend: ReturnType<typeof decimalFromString>;
|
dividend: ReturnType<typeof decimalFromString>;
|
||||||
@@ -35,24 +41,32 @@ type Total = {
|
|||||||
export class IncomeAnalyticsService {
|
export class IncomeAnalyticsService {
|
||||||
constructor(private readonly operations: BrokerageOperationsService) {}
|
constructor(private readonly operations: BrokerageOperationsService) {}
|
||||||
|
|
||||||
async summary(userId: string, accountId: string): Promise<IncomeSummaryDto> {
|
async summary(
|
||||||
let plan: ReturnType<typeof planIncomePeriod> | undefined;
|
userId: string,
|
||||||
const collected = await this.operations.collectRanges(
|
accountId: string,
|
||||||
|
observe = false,
|
||||||
|
): Promise<IncomeSummaryResourceDto> {
|
||||||
|
let plan = planIncomePeriod(undefined, undefined);
|
||||||
|
const [selected] = await this.operations.collectRanges(
|
||||||
userId,
|
userId,
|
||||||
accountId,
|
accountId,
|
||||||
(openedAt) => {
|
(openedAt) => {
|
||||||
const planned = planIncomePeriod(undefined, undefined, openedAt);
|
plan = planIncomePeriod(undefined, undefined, openedAt);
|
||||||
plan = planned;
|
return [plan.selected];
|
||||||
return [planned.selected];
|
|
||||||
},
|
},
|
||||||
|
observe,
|
||||||
);
|
);
|
||||||
if (!plan) throw new Error('Income period was not planned');
|
if (selected.items === null) return { data: null, meta: selected.meta };
|
||||||
return summaryResponse(
|
assert(selected.meta.lastSuccessfulAt);
|
||||||
accountId,
|
return {
|
||||||
plan.selected,
|
data: summaryResponse(
|
||||||
qualifying(collected.pages[0].flatMap((page) => page.items)),
|
accountId,
|
||||||
new Date().toISOString(),
|
plan.selected,
|
||||||
);
|
qualifying(selected.items),
|
||||||
|
selected.meta.lastSuccessfulAt,
|
||||||
|
),
|
||||||
|
meta: selected.meta,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async analytics(
|
async analytics(
|
||||||
@@ -60,52 +74,89 @@ export class IncomeAnalyticsService {
|
|||||||
accountId: string,
|
accountId: string,
|
||||||
from: string | undefined,
|
from: string | undefined,
|
||||||
to: string | undefined,
|
to: string | undefined,
|
||||||
): Promise<IncomeAnalyticsDto> {
|
observe = false,
|
||||||
let plan: ReturnType<typeof planIncomePeriod> | undefined;
|
): Promise<IncomeAnalyticsResourceDto> {
|
||||||
const collected = await this.operations.collectRanges(
|
let plan = planIncomePeriod(from, to);
|
||||||
|
const periods = await this.operations.collectRanges(
|
||||||
userId,
|
userId,
|
||||||
accountId,
|
accountId,
|
||||||
(openedAt) => {
|
(openedAt) => {
|
||||||
const planned = planIncomePeriod(from, to, openedAt);
|
plan = planIncomePeriod(from, to, openedAt);
|
||||||
plan = planned;
|
|
||||||
return [
|
return [
|
||||||
planned.selected,
|
plan.selected,
|
||||||
planned.previous,
|
plan.previous,
|
||||||
...(planned.yearAgo ? [planned.yearAgo] : []),
|
...(plan.yearAgo ? [plan.yearAgo] : []),
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
|
observe,
|
||||||
);
|
);
|
||||||
if (!plan) throw new Error('Income period was not planned');
|
const [current, prior, year] = periods;
|
||||||
const selected = qualifying(
|
// Preserve the legacy order while consumers migrate to explicit roles.
|
||||||
collected.pages[0].flatMap((page) => page.items),
|
const dependencies: IncomeDependencyDto[] = [
|
||||||
).map((entry) => ({
|
{ ...current.meta, role: 'selected' },
|
||||||
|
{ ...prior.meta, role: 'previous' },
|
||||||
|
{
|
||||||
|
...(plan.yearAgo && year ?
|
||||||
|
year.meta :
|
||||||
|
investmentResourceMeta({
|
||||||
|
resourceKey: 'income/yearAgo', // gitleaks:allow public resource identifier
|
||||||
|
dataRevision: 'unavailable',
|
||||||
|
availability: 'missing',
|
||||||
|
fetchedAt: null,
|
||||||
|
freshForMs: 0,
|
||||||
|
work: null,
|
||||||
|
unavailableReason: 'CALENDAR_OR_ACCOUNT_HISTORY',
|
||||||
|
})),
|
||||||
|
role: 'year',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const states = periods.map((period) => period.meta.sync);
|
||||||
|
const work =
|
||||||
|
states.find((state) => state.state === 'running') ??
|
||||||
|
states.find((state) => state.state === 'failed');
|
||||||
|
const meta = {
|
||||||
|
...investmentResourceMeta({
|
||||||
|
resourceKey: `income/${accountId}/${plan.selected.from}/${plan.selected.to}`,
|
||||||
|
dataRevision: current.meta.dataRevision,
|
||||||
|
availability: current.meta.availability,
|
||||||
|
fetchedAt: current.meta.lastSuccessfulAt ?
|
||||||
|
new Date(current.meta.lastSuccessfulAt) :
|
||||||
|
null,
|
||||||
|
freshForMs: current.meta.freshness === 'fresh' ? Infinity : STALE_FRESHNESS_MS,
|
||||||
|
work: work?.id ? { ...work, id: work.id } : null,
|
||||||
|
coverage: current.meta.coverage,
|
||||||
|
dependencies,
|
||||||
|
}),
|
||||||
|
dependencies,
|
||||||
|
};
|
||||||
|
if (current.items === null) return { data: null, meta };
|
||||||
|
assert(current.meta.lastSuccessfulAt);
|
||||||
|
const selected = qualifying(current.items).map((entry) => ({
|
||||||
...entry,
|
...entry,
|
||||||
instrumentKey: `${instrumentKey(entry)}:${entry.payment?.currency ?? ''}`,
|
instrumentKey: `${instrumentKey(entry)}:${entry.payment?.currency ?? ''}`,
|
||||||
}));
|
}));
|
||||||
const previous = qualifying(
|
|
||||||
collected.pages[1].flatMap((page) => page.items),
|
|
||||||
);
|
|
||||||
const yearAgo = plan.yearAgo
|
|
||||||
? qualifying(collected.pages[2].flatMap((page) => page.items))
|
|
||||||
: null;
|
|
||||||
const calculatedAt = new Date().toISOString();
|
|
||||||
const base = summaryResponse(
|
|
||||||
accountId,
|
|
||||||
plan.selected,
|
|
||||||
selected,
|
|
||||||
calculatedAt,
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
...base,
|
data: {
|
||||||
previous: comparison(selected, plan.previous, previous),
|
...summaryResponse(
|
||||||
yearComparison:
|
accountId,
|
||||||
plan.yearAgo && yearAgo
|
plan.selected,
|
||||||
? comparison(selected, plan.yearAgo, yearAgo)
|
selected,
|
||||||
: null,
|
current.meta.lastSuccessfulAt,
|
||||||
bucketGranularity: plan.granularity,
|
),
|
||||||
buckets: buckets(plan.selected, plan.granularity, selected),
|
previous:
|
||||||
instruments: instruments(selected),
|
prior.items === null ?
|
||||||
entries: selected,
|
null :
|
||||||
|
comparison(selected, plan.previous, qualifying(prior.items)),
|
||||||
|
yearComparison:
|
||||||
|
plan.yearAgo && year?.items !== null && year ?
|
||||||
|
comparison(selected, plan.yearAgo, qualifying(year.items)) :
|
||||||
|
null,
|
||||||
|
bucketGranularity: plan.granularity,
|
||||||
|
buckets: buckets(plan.selected, plan.granularity, selected),
|
||||||
|
instruments: instruments(selected),
|
||||||
|
entries: selected,
|
||||||
|
},
|
||||||
|
meta,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,9 +184,9 @@ function totals(entries: BrokerageOperationDto[]): IncomeCurrencySummaryDto[] {
|
|||||||
if (!entry.payment) continue;
|
if (!entry.payment) continue;
|
||||||
const total = values.get(entry.payment.currency) ?? zeroTotal();
|
const total = values.get(entry.payment.currency) ?? zeroTotal();
|
||||||
const value = decimalFromString(entry.payment.value);
|
const value = decimalFromString(entry.payment.value);
|
||||||
if (entry.type === 'OPERATION_TYPE_COUPON')
|
if (entry.type === 'OPERATION_TYPE_COUPON') {
|
||||||
total.coupon = add(total.coupon, value);
|
total.coupon = add(total.coupon, value);
|
||||||
else total.dividend = add(total.dividend, value);
|
} else total.dividend = add(total.dividend, value);
|
||||||
values.set(entry.payment.currency, total);
|
values.set(entry.payment.currency, total);
|
||||||
}
|
}
|
||||||
return [...values]
|
return [...values]
|
||||||
@@ -156,6 +207,7 @@ function comparison(
|
|||||||
);
|
);
|
||||||
const currencies = [
|
const currencies = [
|
||||||
...new Set([...selected.keys(), ...compared.keys()]),
|
...new Set([...selected.keys(), ...compared.keys()]),
|
||||||
|
// eslint-disable-next-line sonarjs/no-alphabetical-sort -- Code-unit ordering is intentional for canonical keys and ISO dates; locale collation would change persisted bindings.
|
||||||
].sort();
|
].sort();
|
||||||
return {
|
return {
|
||||||
period: comparedPeriod,
|
period: comparedPeriod,
|
||||||
@@ -228,8 +280,9 @@ function instruments(
|
|||||||
function instrumentKey(entry: BrokerageOperationDto): string {
|
function instrumentKey(entry: BrokerageOperationDto): string {
|
||||||
if (entry.instrumentUid) return `uid:${entry.instrumentUid}`;
|
if (entry.instrumentUid) return `uid:${entry.instrumentUid}`;
|
||||||
if (entry.figi) return `figi:${entry.figi}`;
|
if (entry.figi) return `figi:${entry.figi}`;
|
||||||
if (entry.ticker || entry.instrumentType)
|
if (entry.ticker || entry.instrumentType) {
|
||||||
return `ticker:${entry.ticker ?? ''}:${entry.instrumentType ?? ''}`;
|
return `ticker:${entry.ticker ?? ''}:${entry.instrumentType ?? ''}`;
|
||||||
|
}
|
||||||
return `operation:${entry.account ? `${entry.account.id}:` : ''}${entry.id}`;
|
return `operation:${entry.account ? `${entry.account.id}:` : ''}${entry.id}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { BadRequestException } from '@nestjs/common';
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
|
||||||
import { dateOnlyBounds } from '../investment-calendar';
|
import { dateOnlyBounds } from '../investment-calendar';
|
||||||
import { planIncomePeriod, rangeBuckets } from './income-period';
|
import { planIncomePeriod, rangeBuckets } from './income-period';
|
||||||
|
|
||||||
@@ -17,8 +18,9 @@ describe('income period planning', () => {
|
|||||||
['2026-03-02', '2026-03-01'],
|
['2026-03-02', '2026-03-01'],
|
||||||
['2026-01-01', '2027-01-02'],
|
['2026-01-01', '2027-01-02'],
|
||||||
['2026-01-01', '2026-04-01'],
|
['2026-01-01', '2026-04-01'],
|
||||||
])
|
]) {
|
||||||
expect(() => planIncomePeriod(from, to)).toThrow(BadRequestException);
|
expect(() => planIncomePeriod(from, to)).toThrow(BadRequestException);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses a full previous month, skips impossible year-ago dates, and keeps empty buckets', () => {
|
it('uses a full previous month, skips impossible year-ago dates, and keeps empty buckets', () => {
|
||||||
@@ -53,4 +55,18 @@ describe('income period planning', () => {
|
|||||||
to: new Date('2026-08-27T21:44:18.510Z'),
|
to: new Date('2026-08-27T21:44:18.510Z'),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
it.each([
|
||||||
|
['2024-02-29', '2024-02-28T21:00:00.000Z', '2024-02-29T21:00:00.000Z'],
|
||||||
|
['2025-12-31', '2025-12-30T21:00:00.000Z', '2025-12-31T21:00:00.000Z'],
|
||||||
|
])('maps inclusive %s to one full half-open Moscow day', (date, from, to) => {
|
||||||
|
expect(
|
||||||
|
dateOnlyBounds(
|
||||||
|
{ from: date, to: date },
|
||||||
|
new Date('2026-01-01T12:00:00Z'),
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
from: new Date(from),
|
||||||
|
to: new Date(to),
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { MILLISECONDS_PER_DAY } from '../../../common/time';
|
|
||||||
import { BadRequestException } from '@nestjs/common';
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
|
||||||
|
import { ISO_DATE_LENGTH, ISO_DATE_START, MILLISECONDS_PER_DAY } from '../../../common/time';
|
||||||
import {
|
import {
|
||||||
DateOnlyRange,
|
DateOnlyRange,
|
||||||
dateParts,
|
dateParts,
|
||||||
@@ -7,47 +8,55 @@ import {
|
|||||||
utcDate,
|
utcDate,
|
||||||
} from '../investment-calendar';
|
} from '../investment-calendar';
|
||||||
|
|
||||||
|
const MONDAY_WEEKDAY_INDEX = 1;
|
||||||
|
const INCLUSIVE_DAY_OFFSET = 1;
|
||||||
|
const NEXT_DAY_OFFSET = 1;
|
||||||
|
const PREVIOUS_MONTH_LAST_DAY = 0;
|
||||||
|
const PREVIOUS_DAY_OFFSET = -1;
|
||||||
|
const PREVIOUS_YEAR_OFFSET = 1;
|
||||||
|
const DATE_COMPONENT_DIGITS = 2;
|
||||||
|
|
||||||
const DAILY_BUCKET_MAX_DAYS = 45;
|
const DAILY_BUCKET_MAX_DAYS = 45;
|
||||||
const WEEKLY_BUCKET_MAX_DAYS = 180;
|
const WEEKLY_BUCKET_MAX_DAYS = 180;
|
||||||
const DAYS_PER_WEEK = 7;
|
const DAYS_PER_WEEK = 7;
|
||||||
const ISO_MONTH_LENGTH = 7;
|
const ISO_MONTH_LENGTH = 7;
|
||||||
const ISO_YEAR_LENGTH = 4;
|
const ISO_YEAR_LENGTH = 4;
|
||||||
|
|
||||||
export type IncomeBucketGranularity = 'day' | 'week' | 'month';
|
export type IncomeBucketGranularity = 'day' | 'month' | 'week';
|
||||||
|
|
||||||
export function planIncomePeriod(
|
export function planIncomePeriod(
|
||||||
from: string | undefined,
|
from: string | undefined,
|
||||||
to: string | undefined,
|
to: string | undefined,
|
||||||
openedDate?: Date,
|
openedDate?: Date,
|
||||||
): {
|
): {
|
||||||
selected: DateOnlyRange;
|
|
||||||
previous: DateOnlyRange;
|
|
||||||
yearAgo: DateOnlyRange | null;
|
|
||||||
granularity: IncomeBucketGranularity;
|
granularity: IncomeBucketGranularity;
|
||||||
|
previous: DateOnlyRange;
|
||||||
|
selected: DateOnlyRange;
|
||||||
|
yearAgo: DateOnlyRange | null;
|
||||||
} {
|
} {
|
||||||
if (Boolean(from) !== Boolean(to)) throw invalidPeriod();
|
if (Boolean(from) !== Boolean(to)) throw invalidPeriod();
|
||||||
const today = moscowDate(new Date());
|
const today = moscowDate(new Date());
|
||||||
const selected =
|
const selected =
|
||||||
from && to ? { from, to } : { from: firstOfMonth(today), to: today };
|
from && to ? { from, to } : { from: firstOfMonth(today), to: today };
|
||||||
assertRange(selected, today);
|
assertRange(selected, today);
|
||||||
const previous = isFullMonth(selected)
|
const previous = isFullMonth(selected) ?
|
||||||
? previousMonth(selected.from)
|
previousMonth(selected.from) :
|
||||||
: shiftDays(selected, -rangeDays(selected));
|
shiftDays(selected, -rangeDays(selected));
|
||||||
const candidate = yearAgo(selected);
|
const candidate = yearAgo(selected);
|
||||||
const yearAgoRange =
|
const yearAgoRange =
|
||||||
candidate && (!openedDate || candidate.from >= moscowDate(openedDate))
|
candidate && (!openedDate || candidate.from >= moscowDate(openedDate)) ?
|
||||||
? candidate
|
candidate :
|
||||||
: null;
|
null;
|
||||||
return {
|
return {
|
||||||
selected,
|
selected,
|
||||||
previous,
|
previous,
|
||||||
yearAgo: yearAgoRange,
|
yearAgo: yearAgoRange,
|
||||||
granularity:
|
granularity:
|
||||||
rangeDays(selected) <= DAILY_BUCKET_MAX_DAYS
|
rangeDays(selected) <= DAILY_BUCKET_MAX_DAYS ?
|
||||||
? 'day'
|
'day' :
|
||||||
: rangeDays(selected) <= WEEKLY_BUCKET_MAX_DAYS
|
rangeDays(selected) <= WEEKLY_BUCKET_MAX_DAYS ?
|
||||||
? 'week'
|
'week' :
|
||||||
: 'month',
|
'month',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,29 +64,30 @@ export function rangeBuckets(
|
|||||||
range: DateOnlyRange,
|
range: DateOnlyRange,
|
||||||
granularity: IncomeBucketGranularity,
|
granularity: IncomeBucketGranularity,
|
||||||
): DateOnlyRange[] {
|
): DateOnlyRange[] {
|
||||||
if (granularity === 'day')
|
if (granularity === 'day') {
|
||||||
return dates(range).map((date) => ({ from: date, to: date }));
|
return dates(range).map((date) => ({ from: date, to: date }));
|
||||||
|
}
|
||||||
const buckets: DateOnlyRange[] = [];
|
const buckets: DateOnlyRange[] = [];
|
||||||
let cursor =
|
let cursor =
|
||||||
granularity === 'week'
|
granularity === 'week' ?
|
||||||
? addDays(
|
addDays(
|
||||||
range.from,
|
range.from,
|
||||||
-(
|
-(
|
||||||
(utcDate(range.from).getUTCDay() + DAYS_PER_WEEK - 1) %
|
(utcDate(range.from).getUTCDay() + DAYS_PER_WEEK - MONDAY_WEEKDAY_INDEX) %
|
||||||
DAYS_PER_WEEK
|
DAYS_PER_WEEK
|
||||||
),
|
),
|
||||||
)
|
) :
|
||||||
: `${range.from.slice(0, ISO_MONTH_LENGTH)}-01`;
|
`${range.from.slice(ISO_DATE_START, ISO_MONTH_LENGTH)}-01`;
|
||||||
while (cursor <= range.to) {
|
while (cursor <= range.to) {
|
||||||
const end =
|
const end =
|
||||||
granularity === 'week'
|
granularity === 'week' ?
|
||||||
? addDays(cursor, DAYS_PER_WEEK - 1)
|
addDays(cursor, DAYS_PER_WEEK - INCLUSIVE_DAY_OFFSET) :
|
||||||
: endOfMonth(cursor);
|
endOfMonth(cursor);
|
||||||
buckets.push({
|
buckets.push({
|
||||||
from: cursor < range.from ? range.from : cursor,
|
from: cursor < range.from ? range.from : cursor,
|
||||||
to: end > range.to ? range.to : end,
|
to: end > range.to ? range.to : end,
|
||||||
});
|
});
|
||||||
cursor = addDays(end, 1);
|
cursor = addDays(end, NEXT_DAY_OFFSET);
|
||||||
}
|
}
|
||||||
return buckets;
|
return buckets;
|
||||||
}
|
}
|
||||||
@@ -86,8 +96,8 @@ export function rangeDays(range: DateOnlyRange): number {
|
|||||||
return (
|
return (
|
||||||
Math.round(
|
Math.round(
|
||||||
(utcDate(range.to).valueOf() - utcDate(range.from).valueOf()) /
|
(utcDate(range.to).valueOf() - utcDate(range.from).valueOf()) /
|
||||||
MILLISECONDS_PER_DAY,
|
MILLISECONDS_PER_DAY,
|
||||||
) + 1
|
) + INCLUSIVE_DAY_OFFSET
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,23 +114,24 @@ function assertRange(range: DateOnlyRange, today: string): void {
|
|||||||
function addDays(value: string, days: number): string {
|
function addDays(value: string, days: number): string {
|
||||||
const date = utcDate(value);
|
const date = utcDate(value);
|
||||||
date.setUTCDate(date.getUTCDate() + days);
|
date.setUTCDate(date.getUTCDate() + days);
|
||||||
return date.toISOString().slice(0, 10);
|
return date.toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
function dates(range: DateOnlyRange): string[] {
|
function dates(range: DateOnlyRange): string[] {
|
||||||
const result: string[] = [];
|
const result: string[] = [];
|
||||||
for (let date = range.from; date <= range.to; date = addDays(date, 1))
|
for (let date = range.from; date <= range.to; date = addDays(date, NEXT_DAY_OFFSET)) {
|
||||||
result.push(date);
|
result.push(date);
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function firstOfMonth(value: string): string {
|
function firstOfMonth(value: string): string {
|
||||||
return `${value.slice(0, ISO_MONTH_LENGTH)}-01`;
|
return `${value.slice(ISO_DATE_START, ISO_MONTH_LENGTH)}-01`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function endOfMonth(value: string): string {
|
function endOfMonth(value: string): string {
|
||||||
const [year, month] = dateParts(firstOfMonth(value));
|
const [year, month] = dateParts(firstOfMonth(value));
|
||||||
return new Date(Date.UTC(year, month, 0)).toISOString().slice(0, 10);
|
return new Date(Date.UTC(year, month, PREVIOUS_MONTH_LAST_DAY)).toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isFullMonth(range: DateOnlyRange): boolean {
|
function isFullMonth(range: DateOnlyRange): boolean {
|
||||||
@@ -130,7 +141,7 @@ function isFullMonth(range: DateOnlyRange): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function previousMonth(from: string): DateOnlyRange {
|
function previousMonth(from: string): DateOnlyRange {
|
||||||
const last = addDays(firstOfMonth(from), -1);
|
const last = addDays(firstOfMonth(from), PREVIOUS_DAY_OFFSET);
|
||||||
return { from: firstOfMonth(last), to: last };
|
return { from: firstOfMonth(last), to: last };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,10 +152,10 @@ function shiftDays(range: DateOnlyRange, days: number): DateOnlyRange {
|
|||||||
function yearAgo(range: DateOnlyRange): DateOnlyRange | null {
|
function yearAgo(range: DateOnlyRange): DateOnlyRange | null {
|
||||||
const shift = (value: string) => {
|
const shift = (value: string) => {
|
||||||
const [year, month, day] = dateParts(value);
|
const [year, month, day] = dateParts(value);
|
||||||
const result = `${String(year - 1).padStart(ISO_YEAR_LENGTH, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
const result = `${String(year - PREVIOUS_YEAR_OFFSET).padStart(ISO_YEAR_LENGTH, '0')}-${String(month).padStart(DATE_COMPONENT_DIGITS, '0')}-${String(day).padStart(DATE_COMPONENT_DIGITS, '0')}`;
|
||||||
return utcDate(result).toISOString().slice(0, 10) === result
|
return utcDate(result).toISOString().slice(ISO_DATE_START, ISO_DATE_LENGTH) === result ?
|
||||||
? result
|
result :
|
||||||
: null;
|
null;
|
||||||
};
|
};
|
||||||
const from = shift(range.from);
|
const from = shift(range.from);
|
||||||
const to = shift(range.to);
|
const to = shift(range.to);
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { IncomeAnalyticsService } from './income-analytics.service';
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { planIncomePeriod } from './income-period';
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
import { AuthModule } from '../../auth/auth.module';
|
import { AuthModule } from '../../auth/auth.module';
|
||||||
import { OperationsModule } from '../operations/operations.module';
|
import { OperationsModule } from '../operations/operations.module';
|
||||||
import { IncomeAnalyticsController } from './income-analytics.controller';
|
import { IncomeAnalyticsController } from './income-analytics.controller';
|
||||||
@@ -8,5 +9,6 @@ import { IncomeAnalyticsService } from './income-analytics.service';
|
|||||||
imports: [AuthModule, OperationsModule],
|
imports: [AuthModule, OperationsModule],
|
||||||
controllers: [IncomeAnalyticsController],
|
controllers: [IncomeAnalyticsController],
|
||||||
providers: [IncomeAnalyticsService],
|
providers: [IncomeAnalyticsService],
|
||||||
|
exports: [IncomeAnalyticsService],
|
||||||
})
|
})
|
||||||
export class IncomeModule {}
|
export class IncomeModule {}
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export const MIN_INSTRUMENT_QUERY_LENGTH = 2;
|
||||||
|
export const MAX_INSTRUMENT_QUERY_LENGTH = 80;
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
jest.mock('../infrastructure/candle.repository', () => ({
|
||||||
|
CandleRepository: class {},
|
||||||
|
}));
|
||||||
|
jest.mock('./catalog-enrichment.service', () => ({
|
||||||
|
CatalogEnrichmentService: class {},
|
||||||
|
}));
|
||||||
|
jest.mock('../../../../integrations/tbank/tbank.api', () => ({
|
||||||
|
TbankAccessService: class {},
|
||||||
|
TbankClient: class {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { CandleService } from './candle.service';
|
||||||
|
|
||||||
|
describe('CandleService forced demand', () => {
|
||||||
|
it.each([false, true])(
|
||||||
|
'reconciles the full range through the latest forced timestamp while force=%s is loading',
|
||||||
|
async (initialForce) => {
|
||||||
|
let entered = () => {};
|
||||||
|
let release = () => {};
|
||||||
|
let complete = () => {};
|
||||||
|
const started = new Promise<void>((resolve) => (entered = resolve));
|
||||||
|
const blocked = new Promise<void>((resolve) => (release = resolve));
|
||||||
|
const finished = new Promise<void>((resolve) => (complete = resolve));
|
||||||
|
let completed = 0;
|
||||||
|
const work = { id: 'work', attemptId: 'attempt' };
|
||||||
|
const repository = {
|
||||||
|
reserve: jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce({ work, launch: true })
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
work: { id: 'other', attemptId: 'other-attempt' },
|
||||||
|
launch: true,
|
||||||
|
})
|
||||||
|
.mockResolvedValue({ work, launch: false }),
|
||||||
|
read: jest.fn().mockResolvedValue({
|
||||||
|
coverage: [
|
||||||
|
{
|
||||||
|
from: new Date('2026-01-01Z'),
|
||||||
|
to: new Date('2026-02-01Z'),
|
||||||
|
isComplete: true,
|
||||||
|
fetchedAt: new Date('2026-02-01Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
stage: jest.fn().mockResolvedValue(true),
|
||||||
|
publish: jest.fn((_attempt, _intent, done = true) => {
|
||||||
|
if (done && ++completed === 2) complete();
|
||||||
|
return Promise.resolve(true);
|
||||||
|
}),
|
||||||
|
fail: jest.fn(),
|
||||||
|
};
|
||||||
|
const sources = {
|
||||||
|
ensureDetail: jest.fn().mockResolvedValue({
|
||||||
|
first_1dayCandleDate: {
|
||||||
|
seconds: String(Date.parse('2026-01-01Z') / 1000),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const upstream = { getCandles: jest.fn().mockResolvedValue([]) };
|
||||||
|
upstream.getCandles.mockImplementationOnce(async () => {
|
||||||
|
entered();
|
||||||
|
await blocked;
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
const service = new CandleService(
|
||||||
|
repository as never,
|
||||||
|
sources as never,
|
||||||
|
{ tokenForAttempt: jest.fn().mockResolvedValue('token') } as never,
|
||||||
|
upstream as never,
|
||||||
|
{ event: jest.fn() } as never,
|
||||||
|
);
|
||||||
|
const input = {
|
||||||
|
uid: 'uid',
|
||||||
|
instrumentType: 'share' as const,
|
||||||
|
period: 'all' as const,
|
||||||
|
};
|
||||||
|
await service.request(
|
||||||
|
'owner',
|
||||||
|
'revision',
|
||||||
|
input,
|
||||||
|
new Date('2026-02-02T12:00:00Z'),
|
||||||
|
initialForce,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
await started;
|
||||||
|
const latest = new Date('2026-02-02T13:00:00Z');
|
||||||
|
await service.request(
|
||||||
|
'owner',
|
||||||
|
'revision',
|
||||||
|
{ ...input, uid: 'other' },
|
||||||
|
latest,
|
||||||
|
false,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await service.request('owner', 'revision', input, latest, true, 0),
|
||||||
|
).toBe('work');
|
||||||
|
release();
|
||||||
|
await finished;
|
||||||
|
|
||||||
|
expect(upstream.getCandles).toHaveBeenCalledWith(
|
||||||
|
'token',
|
||||||
|
'uid',
|
||||||
|
new Date('2026-01-01Z'),
|
||||||
|
latest,
|
||||||
|
);
|
||||||
|
expect(repository.fail).not.toHaveBeenCalled();
|
||||||
|
expect(
|
||||||
|
upstream.getCandles.mock.calls.map((call: unknown[]) => call[1]),
|
||||||
|
).toEqual(['uid', 'uid', 'other']);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,535 @@
|
|||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
ServiceUnavailableException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
import { formatDecimal } from '../../../../common/decimal';
|
||||||
|
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
|
||||||
|
import { MILLISECONDS_PER_DAY } from '../../../../common/time';
|
||||||
|
import { decimal } from '../../../../integrations/tbank/decimal';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
TbankClient,
|
||||||
|
type TbankShare,
|
||||||
|
type TbankSyncAttempt,
|
||||||
|
} from '../../../../integrations/tbank/tbank.api';
|
||||||
|
import { investmentResourceMeta } from '../../investment-resource.mapper';
|
||||||
|
import { planInvestmentScreen } from '../../investment-sync-plan';
|
||||||
|
import {
|
||||||
|
candleGaps,
|
||||||
|
type CandleRange,
|
||||||
|
candleWindows,
|
||||||
|
utcDay,
|
||||||
|
} from '../domain/candle-coverage';
|
||||||
|
import { CandleRepository } from '../infrastructure/candle.repository';
|
||||||
|
import { CatalogEnrichmentService } from './catalog-enrichment.service';
|
||||||
|
import { timestamp } from './instrument-market';
|
||||||
|
|
||||||
|
const FIRST_BATCH_OFFSET = 0;
|
||||||
|
const BACKGROUND_SYNC_PRIORITY = 2;
|
||||||
|
const REPLACED_WINDOW_COUNT = 1;
|
||||||
|
const NEXT_WINDOW_OFFSET = 1;
|
||||||
|
|
||||||
|
type CandleInput = {
|
||||||
|
instrumentType: 'bond' | 'share';
|
||||||
|
period: 'all' | 'halfYear' | 'month' | 'year';
|
||||||
|
range?: CandleRange;
|
||||||
|
uid: string;
|
||||||
|
};
|
||||||
|
type Producer = {
|
||||||
|
attempt: TbankSyncAttempt;
|
||||||
|
force: boolean;
|
||||||
|
input: CandleInput;
|
||||||
|
now: Date;
|
||||||
|
observers: TbankSyncAttempt[];
|
||||||
|
pass?: {
|
||||||
|
force: boolean;
|
||||||
|
nextWindow: number;
|
||||||
|
now: Date;
|
||||||
|
ranges: CandleRange[];
|
||||||
|
};
|
||||||
|
priority: number;
|
||||||
|
};
|
||||||
|
const months = { month: 1, halfYear: 6, year: 12 };
|
||||||
|
const tailFreshForMs = 60_000;
|
||||||
|
const prefetchReadBatchSize = 100;
|
||||||
|
function scope(input: CandleInput) {
|
||||||
|
return `candles:${input.uid}:${input.period}${input.range ? `:${input.range.from.toISOString()}/${input.range.to.toISOString()}` : ''}`;
|
||||||
|
}
|
||||||
|
function rangeFor(
|
||||||
|
input: CandleInput,
|
||||||
|
instrument: TbankShare,
|
||||||
|
now: Date,
|
||||||
|
): CandleRange {
|
||||||
|
if (input.range) return input.range;
|
||||||
|
const from = utcDay(now);
|
||||||
|
const history = timestamp(instrument.first_1dayCandleDate);
|
||||||
|
if (input.period === 'all') {
|
||||||
|
if (!history) {
|
||||||
|
throw new ServiceUnavailableException({
|
||||||
|
code:
|
||||||
|
input.instrumentType === 'share' ?
|
||||||
|
'STOCK_HISTORY_START_UNAVAILABLE' :
|
||||||
|
'BOND_HISTORY_START_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
from.setTime(utcDay(new Date(history)).valueOf());
|
||||||
|
} else {
|
||||||
|
from.setUTCMonth(from.getUTCMonth() - months[input.period]);
|
||||||
|
if (history && Date.parse(history) > from.valueOf()) {
|
||||||
|
from.setTime(utcDay(new Date(history)).valueOf());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { from, to: new Date(utcDay(now).valueOf() + MILLISECONDS_PER_DAY) };
|
||||||
|
}
|
||||||
|
@Injectable()
|
||||||
|
export class CandleService {
|
||||||
|
private readonly runId = randomUUID();
|
||||||
|
private readonly active = new Set<string>();
|
||||||
|
private readonly producers = new Map<string, Producer>();
|
||||||
|
private readonly queue: Producer[] = [];
|
||||||
|
private reservations: Promise<unknown> = Promise.resolve();
|
||||||
|
private running = false;
|
||||||
|
private readonly prefetches = new Map<string, Promise<void>>();
|
||||||
|
constructor(
|
||||||
|
private readonly repository: CandleRepository,
|
||||||
|
private readonly sources: CatalogEnrichmentService,
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
private readonly logger: StructuredLogger,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async read(userId: string, input: CandleInput, observe = false) {
|
||||||
|
const { revision } = await this.access.local(userId);
|
||||||
|
const [detail] = await this.sources.readMany(
|
||||||
|
userId,
|
||||||
|
input.instrumentType,
|
||||||
|
[input.uid],
|
||||||
|
true,
|
||||||
|
['detail'],
|
||||||
|
);
|
||||||
|
if (detail.meta.availability === 'complete' && !detail.instrument) {
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
const now = new Date();
|
||||||
|
const range = detail.instrument ?
|
||||||
|
rangeFor(input, detail.instrument, now) :
|
||||||
|
null;
|
||||||
|
const saved = range ? await this.repository.read(input.uid, range) : null;
|
||||||
|
const gaps = range && saved ? candleGaps(range, saved.coverage, now) : [];
|
||||||
|
if (!observe && (!saved || gaps.length)) {
|
||||||
|
await this.request(userId, revision, input, now);
|
||||||
|
}
|
||||||
|
const work = await this.repository.work(userId, revision, scope(input));
|
||||||
|
const fetchedAt =
|
||||||
|
saved?.coverage
|
||||||
|
.map((row) => row.fetchedAt)
|
||||||
|
.sort((a, b) => a.valueOf() - b.valueOf())[0] ?? null;
|
||||||
|
const covered = saved?.coverage.length ? true : false;
|
||||||
|
const completeCoverage = (saved?.coverage ?? [])
|
||||||
|
.filter((row) => row.isComplete || row.from >= utcDay(now))
|
||||||
|
.map((row) => ({ ...row, isComplete: true }));
|
||||||
|
const missing = range ? candleGaps(range, completeCoverage, now) : [];
|
||||||
|
const complete = Boolean(saved && range && !missing.length);
|
||||||
|
const publicRange = (value: CandleRange) => ({
|
||||||
|
from: value.from.toISOString(),
|
||||||
|
to: value.to.toISOString(),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
data:
|
||||||
|
!saved || !covered ?
|
||||||
|
null :
|
||||||
|
{
|
||||||
|
candles: saved.data,
|
||||||
|
currency:
|
||||||
|
input.instrumentType === 'share' ?
|
||||||
|
detail.instrument?.currency?.toUpperCase() || null :
|
||||||
|
null,
|
||||||
|
historyFrom: timestamp(detail?.instrument?.first_1dayCandleDate),
|
||||||
|
observedAt: fetchedAt?.toISOString() ?? now.toISOString(),
|
||||||
|
},
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: scope(input),
|
||||||
|
dataRevision: saved?.dataRevision ?? '0',
|
||||||
|
availability: !covered ? 'missing' : complete ? 'complete' : 'partial',
|
||||||
|
fetchedAt,
|
||||||
|
freshForMs: Number.POSITIVE_INFINITY,
|
||||||
|
work,
|
||||||
|
coverage: {
|
||||||
|
requested: range ? [publicRange(range)] : [],
|
||||||
|
completeRanges: range ?
|
||||||
|
completeCoverage.flatMap((row) => {
|
||||||
|
const from = new Date(
|
||||||
|
Math.max(row.from.valueOf(), range.from.valueOf()),
|
||||||
|
);
|
||||||
|
const to = new Date(
|
||||||
|
Math.min(row.to.valueOf(), range.to.valueOf()),
|
||||||
|
);
|
||||||
|
return from < to ? [publicRange({ from, to })] : [];
|
||||||
|
}) :
|
||||||
|
[],
|
||||||
|
missingRanges: missing.map(publicRange),
|
||||||
|
asOf: fetchedAt?.toISOString() ?? null,
|
||||||
|
historyBoundary: timestamp(detail?.instrument?.first_1dayCandleDate) ?
|
||||||
|
'known' :
|
||||||
|
'unknown',
|
||||||
|
historyState: complete ?
|
||||||
|
'complete' :
|
||||||
|
work?.state === 'failed' ?
|
||||||
|
'failed' :
|
||||||
|
work?.state === 'running' ?
|
||||||
|
'loading' :
|
||||||
|
covered ?
|
||||||
|
'partial' :
|
||||||
|
'missing',
|
||||||
|
},
|
||||||
|
dependencies: [
|
||||||
|
detail.meta,
|
||||||
|
...(saved?.coverage ?? []).map((row) =>
|
||||||
|
investmentResourceMeta({
|
||||||
|
resourceKey: `${scope(input)}/${row.from.toISOString()}/${row.to.toISOString()}`,
|
||||||
|
dataRevision: String(row.dataRevision),
|
||||||
|
availability: 'complete',
|
||||||
|
fetchedAt: row.fetchedAt,
|
||||||
|
freshForMs: row.isComplete ?
|
||||||
|
Number.POSITIVE_INFINITY :
|
||||||
|
tailFreshForMs,
|
||||||
|
work: null,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
prefetch(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
positions: { instrumentUid?: null | string; type: string }[],
|
||||||
|
) {
|
||||||
|
const key = JSON.stringify([
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
positions
|
||||||
|
.map((position) => [position.instrumentUid, position.type])
|
||||||
|
// eslint-disable-next-line sonarjs/no-alphabetical-sort -- Code-unit ordering is intentional for canonical keys and ISO dates; locale collation would change persisted bindings.
|
||||||
|
.sort(),
|
||||||
|
]);
|
||||||
|
const existing = this.prefetches.get(key);
|
||||||
|
if (existing) return existing;
|
||||||
|
const work = this.prefetchPositions(userId, revision, positions).finally(
|
||||||
|
() => this.prefetches.delete(key),
|
||||||
|
);
|
||||||
|
this.prefetches.set(key, work);
|
||||||
|
return work;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async prefetchPositions(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
positions: { instrumentUid?: null | string; type: string }[],
|
||||||
|
) {
|
||||||
|
const now = new Date();
|
||||||
|
const unique = new Map(
|
||||||
|
positions
|
||||||
|
.filter(
|
||||||
|
(position) =>
|
||||||
|
position.instrumentUid && ['BOND', 'STOCK'].includes(position.type),
|
||||||
|
)
|
||||||
|
.map((position) => [position.instrumentUid ?? '', position]),
|
||||||
|
);
|
||||||
|
const details: Awaited<ReturnType<CatalogEnrichmentService['readMany']>> =
|
||||||
|
[];
|
||||||
|
const coverage: Awaited<ReturnType<CandleRepository['coverage']>> = [];
|
||||||
|
for (const instrumentType of ['share', 'bond'] as const) {
|
||||||
|
const uids = [...unique]
|
||||||
|
.filter(
|
||||||
|
([, position]) =>
|
||||||
|
position.type === (instrumentType === 'share' ? 'STOCK' : 'BOND'),
|
||||||
|
)
|
||||||
|
.map(([uid]) => uid);
|
||||||
|
for (
|
||||||
|
let offset = FIRST_BATCH_OFFSET;
|
||||||
|
offset < uids.length;
|
||||||
|
offset += prefetchReadBatchSize
|
||||||
|
) {
|
||||||
|
const batch = uids.slice(offset, offset + prefetchReadBatchSize);
|
||||||
|
details.push(
|
||||||
|
...(await this.sources.readMany(userId, instrumentType, batch, true, [
|
||||||
|
'detail',
|
||||||
|
])),
|
||||||
|
);
|
||||||
|
coverage.push(...(await this.repository.coverage(batch)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const byUid = new Map(details.map((detail) => [detail.input.uid, detail]));
|
||||||
|
for (const [uid, position] of unique) {
|
||||||
|
const instrumentType: CandleInput['instrumentType'] =
|
||||||
|
position.type === 'STOCK' ? 'share' : 'bond';
|
||||||
|
const detail = byUid.get(uid);
|
||||||
|
const history = timestamp(detail?.instrument?.first_1dayCandleDate);
|
||||||
|
const plan = planInvestmentScreen(
|
||||||
|
{ screen: 'account' },
|
||||||
|
{
|
||||||
|
membershipKnown: true,
|
||||||
|
accounts: [],
|
||||||
|
instruments: [
|
||||||
|
{
|
||||||
|
uid,
|
||||||
|
type: position.type as 'BOND' | 'STOCK',
|
||||||
|
historyFrom: history ? new Date(history) : null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!detail?.instrument ||
|
||||||
|
plan.sources.some((source) => source.kind === 'candles')
|
||||||
|
) {
|
||||||
|
const input = { uid, instrumentType, period: 'all' as const };
|
||||||
|
const range =
|
||||||
|
detail?.instrument && history ?
|
||||||
|
rangeFor(input, detail.instrument, now) :
|
||||||
|
null;
|
||||||
|
if (
|
||||||
|
!range ||
|
||||||
|
candleGaps(
|
||||||
|
range,
|
||||||
|
coverage.filter((row) => row.instrumentUid === uid),
|
||||||
|
now,
|
||||||
|
).length
|
||||||
|
) {
|
||||||
|
await this.request(userId, revision, input, now, false, BACKGROUND_SYNC_PRIORITY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
request(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
input: CandleInput,
|
||||||
|
now = new Date(),
|
||||||
|
force = false,
|
||||||
|
priority = 1,
|
||||||
|
) {
|
||||||
|
const pending = this.reservations.then(async () => {
|
||||||
|
const reserved = await this.repository.reserve(
|
||||||
|
{ userId, revision },
|
||||||
|
scope(input),
|
||||||
|
{
|
||||||
|
uid: input.uid,
|
||||||
|
instrumentType: input.instrumentType,
|
||||||
|
ranges: [],
|
||||||
|
period: input.period,
|
||||||
|
now: now.toISOString(),
|
||||||
|
force,
|
||||||
|
},
|
||||||
|
this.runId,
|
||||||
|
this.active,
|
||||||
|
priority,
|
||||||
|
);
|
||||||
|
if (!reserved) return null;
|
||||||
|
const attempt = {
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
id: reserved.work.id,
|
||||||
|
attemptId: reserved.work.attemptId,
|
||||||
|
};
|
||||||
|
const producer = this.producers.get(scope(input));
|
||||||
|
if (producer) {
|
||||||
|
producer.force ||= force;
|
||||||
|
producer.priority = Math.min(producer.priority, priority);
|
||||||
|
if (force && now > producer.now) producer.now = now;
|
||||||
|
}
|
||||||
|
if (reserved.launch) {
|
||||||
|
this.active.add(attempt.attemptId);
|
||||||
|
if (producer) producer.observers.push(attempt);
|
||||||
|
else {
|
||||||
|
const next = { input, attempt, now, force, priority, observers: [] };
|
||||||
|
this.producers.set(scope(input), next);
|
||||||
|
this.queue.push(next);
|
||||||
|
}
|
||||||
|
if (!this.running) {
|
||||||
|
this.running = true;
|
||||||
|
setImmediate(() => {
|
||||||
|
void this.drain();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return attempt.id;
|
||||||
|
});
|
||||||
|
this.reservations = pending.catch(() => undefined);
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async load(producer: Producer) {
|
||||||
|
const { input, attempt } = producer;
|
||||||
|
const instrument = await this.sources.ensureDetail(
|
||||||
|
attempt.userId,
|
||||||
|
attempt.revision,
|
||||||
|
input.instrumentType,
|
||||||
|
input.uid,
|
||||||
|
);
|
||||||
|
if (!instrument) throw new NotFoundException();
|
||||||
|
let pass = producer.pass;
|
||||||
|
if (!pass || (producer.force && (!pass.force || producer.now > pass.now))) {
|
||||||
|
const { now, force } = producer;
|
||||||
|
const range = rangeFor(input, instrument, now);
|
||||||
|
const saved = await this.repository.read(input.uid, range);
|
||||||
|
pass = producer.pass = {
|
||||||
|
now,
|
||||||
|
force,
|
||||||
|
ranges: (force ? [range] : candleGaps(range, saved.coverage, now))
|
||||||
|
.flatMap(candleWindows)
|
||||||
|
.reverse(),
|
||||||
|
nextWindow: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { ranges, now, force } = pass;
|
||||||
|
const index = pass.nextWindow;
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The index is the internal numeric window cursor.
|
||||||
|
let window = ranges[index];
|
||||||
|
if (window && !force) {
|
||||||
|
const latest = await this.repository.read(input.uid, window);
|
||||||
|
const gaps = candleGaps(window, latest.coverage, now)
|
||||||
|
.flatMap(candleWindows)
|
||||||
|
.reverse();
|
||||||
|
ranges.splice(index, REPLACED_WINDOW_COUNT, ...gaps);
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- The index is the internal numeric window cursor.
|
||||||
|
window = ranges[index];
|
||||||
|
}
|
||||||
|
if (window) {
|
||||||
|
const token = await this.access.tokenForAttempt(attempt);
|
||||||
|
if (!token) return false;
|
||||||
|
const candles = await this.tbank.getCandles(
|
||||||
|
token,
|
||||||
|
input.uid,
|
||||||
|
window.from,
|
||||||
|
new Date(Math.min(window.to.valueOf(), now.valueOf())),
|
||||||
|
);
|
||||||
|
const rows = candles.flatMap((candle) => {
|
||||||
|
const time = timestamp(candle.time);
|
||||||
|
if (!time || !candle.close) throw new Error('Invalid candle response');
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
time,
|
||||||
|
close: formatDecimal(decimal(candle.close)),
|
||||||
|
isComplete: candle.isComplete === true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
if (!(await this.repository.stage(attempt, window, rows, now))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!force &&
|
||||||
|
!(await this.repository.publish(
|
||||||
|
attempt,
|
||||||
|
{ uid: input.uid, ranges: [window] },
|
||||||
|
false,
|
||||||
|
))
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
pass.nextWindow = index + NEXT_WINDOW_OFFSET;
|
||||||
|
if (pass.nextWindow < ranges.length) return null;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async drain() {
|
||||||
|
try {
|
||||||
|
while (this.queue.length) {
|
||||||
|
this.queue.sort((a, b) => a.priority - b.priority);
|
||||||
|
const producer = this.queue.shift();
|
||||||
|
if (!producer) break;
|
||||||
|
let success = false;
|
||||||
|
let code = 'TBANK_UNAVAILABLE';
|
||||||
|
try {
|
||||||
|
const result = await this.load(producer);
|
||||||
|
if (result === null) {
|
||||||
|
this.queue.push(producer);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
success = result;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN') {
|
||||||
|
await this.access.rejectMembershipToken(producer.attempt);
|
||||||
|
}
|
||||||
|
if (error instanceof ServiceUnavailableException) {
|
||||||
|
const response = error.getResponse();
|
||||||
|
if (
|
||||||
|
typeof response === 'object' &&
|
||||||
|
'code' in response &&
|
||||||
|
typeof response.code === 'string'
|
||||||
|
) {
|
||||||
|
code = response.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Seal publication with reservations so a late forced join cannot be
|
||||||
|
// acknowledged after the final demand check but before work completion.
|
||||||
|
const finished = this.reservations.then(async () => {
|
||||||
|
const pass = producer.pass;
|
||||||
|
if (success && pass) {
|
||||||
|
if (producer.force && (!pass.force || producer.now > pass.now)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
success = await this.repository.publish(producer.attempt, {
|
||||||
|
uid: producer.input.uid,
|
||||||
|
ranges: pass.force ? pass.ranges : [],
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!success) await this.repository.fail(producer.attempt, code);
|
||||||
|
this.active.delete(producer.attempt.attemptId);
|
||||||
|
for (const observer of producer.observers) {
|
||||||
|
if (
|
||||||
|
!success ||
|
||||||
|
!(await this.repository.completeObserver(
|
||||||
|
observer,
|
||||||
|
producer.attempt,
|
||||||
|
))
|
||||||
|
) {
|
||||||
|
await this.repository.fail(observer, code);
|
||||||
|
}
|
||||||
|
this.active.delete(observer.attemptId);
|
||||||
|
}
|
||||||
|
this.producers.delete(scope(producer.input));
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
this.reservations = finished.catch(() => undefined);
|
||||||
|
if (!(await finished)) {
|
||||||
|
this.queue.push(producer);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (success && !producer.force && producer.input.period !== 'all') {
|
||||||
|
await this.request(
|
||||||
|
producer.attempt.userId,
|
||||||
|
producer.attempt.revision,
|
||||||
|
{ ...producer.input, period: 'all' },
|
||||||
|
producer.now,
|
||||||
|
false,
|
||||||
|
BACKGROUND_SYNC_PRIORITY,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
this.logger.event('error', 'candles.persistence-failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
this.active.clear();
|
||||||
|
this.producers.clear();
|
||||||
|
this.queue.length = 0;
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,404 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
TbankClient,
|
||||||
|
tbankSourceNeedsRefresh,
|
||||||
|
tbankSourceTtlMs,
|
||||||
|
type TbankSyncAttempt,
|
||||||
|
} from '../../../../integrations/tbank/tbank.api';
|
||||||
|
import { investmentResourceMeta } from '../../investment-resource.mapper';
|
||||||
|
import {
|
||||||
|
CatalogDiscoveryRepository,
|
||||||
|
catalogQuery,
|
||||||
|
type CatalogQuery,
|
||||||
|
catalogScope,
|
||||||
|
} from '../infrastructure/catalog-discovery.repository';
|
||||||
|
import { CatalogEnrichmentService } from './catalog-enrichment.service';
|
||||||
|
import {
|
||||||
|
catalogSearchLimit,
|
||||||
|
selectCatalogInstruments,
|
||||||
|
} from './catalog-selection';
|
||||||
|
|
||||||
|
const UNAMBIGUOUS_MATCH_COUNT = 1;
|
||||||
|
const NO_MATCHES = 0;
|
||||||
|
const FIRST_RESULT_OFFSET = 0;
|
||||||
|
|
||||||
|
const tickerAmbiguityLimit = 2;
|
||||||
|
|
||||||
|
type Producer = {
|
||||||
|
attempt: TbankSyncAttempt;
|
||||||
|
force: boolean;
|
||||||
|
input: CatalogQuery;
|
||||||
|
observers: TbankSyncAttempt[];
|
||||||
|
};
|
||||||
|
@Injectable()
|
||||||
|
export class CatalogDiscoveryService {
|
||||||
|
private readonly runId = randomUUID();
|
||||||
|
private readonly active = new Set<string>();
|
||||||
|
private readonly producers = new Map<string, Producer>();
|
||||||
|
private readonly queue: Producer[] = [];
|
||||||
|
private reservations: Promise<unknown> = Promise.resolve();
|
||||||
|
private running = false;
|
||||||
|
private readonly completions = new Map<
|
||||||
|
string,
|
||||||
|
{ done: Promise<void>; resolve: () => void; workId: string }
|
||||||
|
>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly repository: CatalogDiscoveryRepository,
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
private readonly logger: StructuredLogger,
|
||||||
|
private readonly enrichment: CatalogEnrichmentService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async read(userId: string, input: CatalogQuery, observe = false) {
|
||||||
|
input = catalogQuery(input);
|
||||||
|
const connection = await this.access.local(userId);
|
||||||
|
const saved = await this.repository.read(input);
|
||||||
|
if (!observe) await this.request(userId, connection.revision, input);
|
||||||
|
return {
|
||||||
|
data: saved.data,
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: catalogScope(input),
|
||||||
|
dataRevision: saved.dataRevision,
|
||||||
|
availability: saved.data === null ? 'missing' : 'complete',
|
||||||
|
fetchedAt: saved.fetchedAt,
|
||||||
|
freshForMs: tbankSourceTtlMs.catalog,
|
||||||
|
work: await this.repository.work(userId, connection.revision, input),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async search(userId: string, input: CatalogQuery, observe = false) {
|
||||||
|
const discovery = await this.read(userId, input, observe);
|
||||||
|
const sources = discovery.data ?
|
||||||
|
await this.enrichment.readMany(
|
||||||
|
userId,
|
||||||
|
input.instrumentType,
|
||||||
|
discovery.data.map((item) => item.uid),
|
||||||
|
observe,
|
||||||
|
) :
|
||||||
|
[];
|
||||||
|
const dependencies = [
|
||||||
|
discovery.meta,
|
||||||
|
...sources.map((source) => source.meta),
|
||||||
|
];
|
||||||
|
return {
|
||||||
|
data:
|
||||||
|
discovery.data?.map((short) => ({
|
||||||
|
...short,
|
||||||
|
detail:
|
||||||
|
sources.find(
|
||||||
|
(source) =>
|
||||||
|
source.input.uid === short.uid &&
|
||||||
|
source.input.kind === 'detail',
|
||||||
|
)?.instrument ?? null,
|
||||||
|
price:
|
||||||
|
sources.find(
|
||||||
|
(source) =>
|
||||||
|
source.input.uid === short.uid &&
|
||||||
|
source.input.kind === 'last-price',
|
||||||
|
)?.price ?? null,
|
||||||
|
})) ?? null,
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: `search:${catalogScope(catalogQuery(input))}`,
|
||||||
|
dataRevision: dependencies
|
||||||
|
.map((dependency) => dependency.dataRevision)
|
||||||
|
.join('/'),
|
||||||
|
availability:
|
||||||
|
discovery.data === null ?
|
||||||
|
'missing' :
|
||||||
|
sources.every((source) => source.meta.availability === 'complete') ?
|
||||||
|
'complete' :
|
||||||
|
'partial',
|
||||||
|
fetchedAt: discovery.meta.lastSuccessfulAt ?
|
||||||
|
new Date(discovery.meta.lastSuccessfulAt) :
|
||||||
|
null,
|
||||||
|
freshForMs: tbankSourceTtlMs.catalog,
|
||||||
|
work: discovery.meta.sync.id ?
|
||||||
|
{
|
||||||
|
id: discovery.meta.sync.id,
|
||||||
|
state: discovery.meta.sync.state,
|
||||||
|
errorCode: discovery.meta.sync.errorCode,
|
||||||
|
} :
|
||||||
|
null,
|
||||||
|
dependencies,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async detail(
|
||||||
|
userId: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uid: string,
|
||||||
|
observe = false,
|
||||||
|
) {
|
||||||
|
const sources = await this.enrichment.readMany(
|
||||||
|
userId,
|
||||||
|
instrumentType,
|
||||||
|
[uid],
|
||||||
|
observe,
|
||||||
|
['detail'],
|
||||||
|
);
|
||||||
|
const source = sources[0];
|
||||||
|
if (source.meta.availability === 'complete' && !source.instrument) {
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
const instrument = source.instrument;
|
||||||
|
let slug = uid;
|
||||||
|
const dependencies = [source.meta];
|
||||||
|
if (
|
||||||
|
instrument?.ticker &&
|
||||||
|
/^[A-Z0-9][\w.@+-]{0,79}$/i.test(instrument.ticker)
|
||||||
|
) {
|
||||||
|
const alias = await this.read(
|
||||||
|
userId,
|
||||||
|
{ instrumentType, query: instrument.ticker, exactTicker: true },
|
||||||
|
observe,
|
||||||
|
);
|
||||||
|
if (alias.data?.length === UNAMBIGUOUS_MATCH_COUNT && alias.data[0].uid === uid) {
|
||||||
|
slug = instrument.ticker.toUpperCase();
|
||||||
|
}
|
||||||
|
dependencies.push(alias.meta);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
data: instrument ? { ...instrument, uid, slug } : null,
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: `${instrumentType}/detail/${uid}`,
|
||||||
|
dataRevision: dependencies
|
||||||
|
.map((dependency) => dependency.dataRevision)
|
||||||
|
.join('/'),
|
||||||
|
availability: source.meta.availability,
|
||||||
|
fetchedAt: source.meta.lastSuccessfulAt ?
|
||||||
|
new Date(source.meta.lastSuccessfulAt) :
|
||||||
|
null,
|
||||||
|
freshForMs: tbankSourceTtlMs.metadata,
|
||||||
|
work: source.meta.sync.id ?
|
||||||
|
{
|
||||||
|
id: source.meta.sync.id,
|
||||||
|
state: source.meta.sync.state,
|
||||||
|
errorCode: source.meta.sync.errorCode,
|
||||||
|
} :
|
||||||
|
null,
|
||||||
|
dependencies,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async byTicker(
|
||||||
|
userId: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
ticker: string,
|
||||||
|
observe = false,
|
||||||
|
) {
|
||||||
|
const lookup = await this.read(
|
||||||
|
userId,
|
||||||
|
{ instrumentType, query: ticker, exactTicker: true },
|
||||||
|
observe,
|
||||||
|
);
|
||||||
|
if (lookup.data?.length === NO_MATCHES) throw new NotFoundException();
|
||||||
|
if (lookup.data && lookup.data.length > UNAMBIGUOUS_MATCH_COUNT) {
|
||||||
|
throw new ConflictException({
|
||||||
|
code:
|
||||||
|
instrumentType === 'share' ?
|
||||||
|
'STOCK_TICKER_AMBIGUOUS' :
|
||||||
|
'BOND_TICKER_AMBIGUOUS',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const result = lookup.data ?
|
||||||
|
await this.detail(userId, instrumentType, lookup.data[0].uid, observe) :
|
||||||
|
null;
|
||||||
|
const dependencies = [lookup.meta, ...(result ? [result.meta] : [])];
|
||||||
|
return {
|
||||||
|
data: result?.data ?
|
||||||
|
{ ...result.data, slug: ticker.trim().toUpperCase() } :
|
||||||
|
null,
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: `${instrumentType}/ticker/${ticker.trim().toUpperCase()}`,
|
||||||
|
dataRevision: dependencies
|
||||||
|
.map((dependency) => dependency.dataRevision)
|
||||||
|
.join('/'),
|
||||||
|
availability: result?.meta.availability ?? 'missing',
|
||||||
|
fetchedAt: lookup.meta.lastSuccessfulAt ?
|
||||||
|
new Date(lookup.meta.lastSuccessfulAt) :
|
||||||
|
null,
|
||||||
|
freshForMs: tbankSourceTtlMs.metadata,
|
||||||
|
work: lookup.meta.sync.id ?
|
||||||
|
{
|
||||||
|
id: lookup.meta.sync.id,
|
||||||
|
state: lookup.meta.sync.state,
|
||||||
|
errorCode: lookup.meta.sync.errorCode,
|
||||||
|
} :
|
||||||
|
null,
|
||||||
|
dependencies,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
request(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
query: CatalogQuery,
|
||||||
|
force = false,
|
||||||
|
) {
|
||||||
|
const input = catalogQuery(query);
|
||||||
|
const reserved = this.reservations.then(async () => {
|
||||||
|
const saved = await this.repository.read(input);
|
||||||
|
if (
|
||||||
|
!tbankSourceNeedsRefresh('catalog', saved.fetchedAt, new Date(), force)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const reservation = await this.repository.reserve(
|
||||||
|
{ userId, revision },
|
||||||
|
input,
|
||||||
|
this.runId,
|
||||||
|
this.active,
|
||||||
|
);
|
||||||
|
if (!reservation) return null;
|
||||||
|
const { id, attemptId } = reservation.work;
|
||||||
|
if (!reservation.launch) {
|
||||||
|
const current = this.producers.get(catalogScope(input));
|
||||||
|
if (current) current.force ||= force;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
const attempt = { userId, revision, id, attemptId };
|
||||||
|
this.active.add(attemptId);
|
||||||
|
let resolve = () => {};
|
||||||
|
const done = new Promise<void>((finish) => {
|
||||||
|
resolve = finish;
|
||||||
|
});
|
||||||
|
this.completions.set(attemptId, { workId: id, done, resolve });
|
||||||
|
const key = catalogScope(input);
|
||||||
|
const producer = this.producers.get(key);
|
||||||
|
if (producer) {
|
||||||
|
producer.observers.push(attempt);
|
||||||
|
producer.force ||= force;
|
||||||
|
} else {
|
||||||
|
const queued = { input, attempt, observers: [], force };
|
||||||
|
this.producers.set(key, queued);
|
||||||
|
this.queue.push(queued);
|
||||||
|
}
|
||||||
|
if (!this.running) {
|
||||||
|
this.running = true;
|
||||||
|
setImmediate(() => {
|
||||||
|
void this.drain();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
});
|
||||||
|
this.reservations = reserved.catch(() => undefined);
|
||||||
|
return reserved;
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh(userId: string, revision: string, query: CatalogQuery) {
|
||||||
|
const id = await this.request(userId, revision, query, true);
|
||||||
|
if (id) {
|
||||||
|
await Promise.all(
|
||||||
|
[...this.completions.values()]
|
||||||
|
.filter((entry) => entry.workId === id)
|
||||||
|
.map((entry) => entry.done),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const saved = await this.repository.read(catalogQuery(query));
|
||||||
|
const sources = await this.enrichment.readMany(
|
||||||
|
userId,
|
||||||
|
query.instrumentType,
|
||||||
|
saved.data?.map((item) => item.uid) ?? [],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
return [
|
||||||
|
...(id ? [id] : []),
|
||||||
|
...sources.flatMap((source) =>
|
||||||
|
source.meta.sync.id ? [source.meta.sync.id] : [],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async drain() {
|
||||||
|
try {
|
||||||
|
while (this.queue.length) {
|
||||||
|
const producer = this.queue.shift();
|
||||||
|
if (!producer) break;
|
||||||
|
const { input, attempt } = producer;
|
||||||
|
let success = false;
|
||||||
|
try {
|
||||||
|
const token = await this.access.tokenForAttempt(attempt);
|
||||||
|
if (token) {
|
||||||
|
const found =
|
||||||
|
input.instrumentType === 'share' ?
|
||||||
|
await this.tbank.findShares(token, input.query) :
|
||||||
|
await this.tbank.findBonds(token, input.query);
|
||||||
|
success = await this.repository.publish(
|
||||||
|
attempt,
|
||||||
|
input,
|
||||||
|
selectCatalogInstruments(
|
||||||
|
input.exactTicker ?
|
||||||
|
found.filter(
|
||||||
|
(item) =>
|
||||||
|
item.ticker?.trim().toUpperCase() === input.query,
|
||||||
|
) :
|
||||||
|
found,
|
||||||
|
input.query,
|
||||||
|
input.instrumentType,
|
||||||
|
).slice(
|
||||||
|
FIRST_RESULT_OFFSET,
|
||||||
|
input.exactTicker ? tickerAmbiguityLimit : catalogSearchLimit,
|
||||||
|
),
|
||||||
|
new Date(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN') {
|
||||||
|
await this.access.rejectMembershipToken(attempt);
|
||||||
|
} else {
|
||||||
|
this.logger.event('warn', 'catalog-discovery.failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (success) {
|
||||||
|
const saved = await this.repository.read(input);
|
||||||
|
for (const observer of [attempt, ...producer.observers]) {
|
||||||
|
if (!input.exactTicker || saved.data?.length === UNAMBIGUOUS_MATCH_COUNT) {
|
||||||
|
await this.enrichment.requestMany(
|
||||||
|
observer.userId,
|
||||||
|
observer.revision,
|
||||||
|
input.instrumentType,
|
||||||
|
saved.data?.map((item) => item.uid) ?? [],
|
||||||
|
producer.force,
|
||||||
|
input.exactTicker ? ['detail'] : ['last-price', 'detail'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.producers.delete(catalogScope(input));
|
||||||
|
for (const observer of [attempt, ...producer.observers]) {
|
||||||
|
await this.repository.finish(observer, success);
|
||||||
|
this.active.delete(observer.attemptId);
|
||||||
|
this.completions.get(observer.attemptId)?.resolve();
|
||||||
|
this.completions.delete(observer.attemptId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
for (const completion of this.completions.values()) completion.resolve();
|
||||||
|
this.completions.clear();
|
||||||
|
this.active.clear();
|
||||||
|
this.producers.clear();
|
||||||
|
this.queue.length = 0;
|
||||||
|
this.logger.event('error', 'catalog-discovery.persistence-failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,688 @@
|
|||||||
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
import {
|
||||||
|
decimalFromString,
|
||||||
|
divide,
|
||||||
|
formatDecimal,
|
||||||
|
} from '../../../../common/decimal';
|
||||||
|
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
|
||||||
|
import {
|
||||||
|
MILLISECONDS_PER_DAY,
|
||||||
|
MILLISECONDS_PER_SECOND,
|
||||||
|
} from '../../../../common/time';
|
||||||
|
import { type MoexBondEvent, MoexClient } from '../../../../integrations/moex/moex.api';
|
||||||
|
import { NcrRatingsClient } from '../../../../integrations/ncr/ncr.api';
|
||||||
|
import { decimal } from '../../../../integrations/tbank/decimal';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
type TbankBond,
|
||||||
|
type TbankCandle,
|
||||||
|
TbankClient,
|
||||||
|
type TbankCoupon,
|
||||||
|
type TbankDividend,
|
||||||
|
type TbankFundamentals,
|
||||||
|
type TbankLastPrice,
|
||||||
|
type TbankShare,
|
||||||
|
tbankSourceNeedsRefresh,
|
||||||
|
tbankSourceTtlMs,
|
||||||
|
type TbankSyncAttempt,
|
||||||
|
} from '../../../../integrations/tbank/tbank.api';
|
||||||
|
import { investmentResourceMeta } from '../../investment-resource.mapper';
|
||||||
|
import { candleGaps, utcDay } from '../domain/candle-coverage';
|
||||||
|
import { CandleRepository } from '../infrastructure/candle.repository';
|
||||||
|
import {
|
||||||
|
CatalogDiscoveryRepository,
|
||||||
|
catalogScope,
|
||||||
|
type CatalogSource,
|
||||||
|
} from '../infrastructure/catalog-discovery.repository';
|
||||||
|
import { catalogSearchLimit } from './catalog-selection';
|
||||||
|
import { previousClose, timestamp } from './instrument-market';
|
||||||
|
|
||||||
|
const MISSING_DATA_REVISION = 0;
|
||||||
|
const FIRST_QUEUE_INDEX = 0;
|
||||||
|
const DEQUEUED_ITEM_COUNT = 1;
|
||||||
|
|
||||||
|
type Producer = {
|
||||||
|
attempt: TbankSyncAttempt;
|
||||||
|
input: CatalogSource;
|
||||||
|
observers: { attempt: TbankSyncAttempt; input: CatalogSource }[];
|
||||||
|
};
|
||||||
|
@Injectable()
|
||||||
|
export class CatalogEnrichmentService {
|
||||||
|
private readonly runId = randomUUID();
|
||||||
|
private readonly active = new Set<string>();
|
||||||
|
private readonly producers = new Map<string, Producer>();
|
||||||
|
private readonly queue: Producer[] = [];
|
||||||
|
private reservations: Promise<unknown> = Promise.resolve();
|
||||||
|
private running = false;
|
||||||
|
private readonly completions = new Map<
|
||||||
|
string,
|
||||||
|
{ done: Promise<void>; resolve: () => void; workId: string }
|
||||||
|
>();
|
||||||
|
|
||||||
|
async ensureDetail(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uid: string,
|
||||||
|
) {
|
||||||
|
const ids = await this.requestMany(
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
instrumentType,
|
||||||
|
[uid],
|
||||||
|
false,
|
||||||
|
['detail'],
|
||||||
|
);
|
||||||
|
await Promise.all(
|
||||||
|
[...this.completions.values()]
|
||||||
|
.filter((entry) => ids.includes(entry.workId))
|
||||||
|
.map((entry) => entry.done),
|
||||||
|
);
|
||||||
|
const rows = await this.repository.readSources([
|
||||||
|
{ instrumentType, uid, kind: 'detail' },
|
||||||
|
]);
|
||||||
|
if (!rows.length) throw new Error('Instrument dependency missing');
|
||||||
|
return (rows[0].payload as CatalogPayload).instrument ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly repository: CatalogDiscoveryRepository,
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
private readonly logger: StructuredLogger,
|
||||||
|
private readonly moex: MoexClient,
|
||||||
|
private readonly ratings: NcrRatingsClient,
|
||||||
|
private readonly candles: CandleRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async readMany(
|
||||||
|
userId: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uids: string[],
|
||||||
|
observe: boolean,
|
||||||
|
kinds: CatalogSource['kind'][] = ['last-price', 'detail'],
|
||||||
|
range?: {
|
||||||
|
from: string;
|
||||||
|
ticker?: string;
|
||||||
|
tickers?: Record<string, string>;
|
||||||
|
to: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { revision } = await this.access.local(userId);
|
||||||
|
const inputs = sourceInputs(instrumentType, uids, kinds, range);
|
||||||
|
const rows = inputs.length ? await this.repository.readSources(inputs) : [];
|
||||||
|
if (!observe) {
|
||||||
|
await this.requestMany(
|
||||||
|
userId,
|
||||||
|
revision,
|
||||||
|
instrumentType,
|
||||||
|
uids,
|
||||||
|
false,
|
||||||
|
kinds,
|
||||||
|
range,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const work = inputs.length ?
|
||||||
|
await this.repository.workMany(userId, revision, inputs) :
|
||||||
|
[];
|
||||||
|
const byScope = new Map(work.map((row) => [row.scopeKey, row]));
|
||||||
|
return inputs.map((input) => {
|
||||||
|
const row = rows.find(
|
||||||
|
(entry) =>
|
||||||
|
entry.instrumentUid === input.uid && entry.kind === input.kind,
|
||||||
|
);
|
||||||
|
const payload = row?.payload as CatalogPayload | undefined;
|
||||||
|
return {
|
||||||
|
input,
|
||||||
|
version: row ?
|
||||||
|
{
|
||||||
|
instrumentUid: row.instrumentUid,
|
||||||
|
source: row.source,
|
||||||
|
kind: row.kind,
|
||||||
|
rangeKey: row.rangeKey,
|
||||||
|
dataRevision: row.dataRevision,
|
||||||
|
fetchedAt: row.fetchedAt,
|
||||||
|
} :
|
||||||
|
null,
|
||||||
|
payload,
|
||||||
|
instrument: payload?.instrument ?? null,
|
||||||
|
price: payload?.price ?? null,
|
||||||
|
meta: investmentResourceMeta({
|
||||||
|
resourceKey: catalogScope(input),
|
||||||
|
dataRevision: String(row?.dataRevision ?? MISSING_DATA_REVISION),
|
||||||
|
availability: row ? 'complete' : 'missing',
|
||||||
|
fetchedAt: row?.fetchedAt ?? null,
|
||||||
|
freshForMs: tbankSourceTtlMs[sourcePolicy(input.kind)],
|
||||||
|
work: byScope.get(catalogScope(input)) ?? null,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
requestMany(
|
||||||
|
userId: string,
|
||||||
|
revision: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uids: string[],
|
||||||
|
force = false,
|
||||||
|
kinds: CatalogSource['kind'][] = ['last-price', 'detail'],
|
||||||
|
range?: {
|
||||||
|
from: string;
|
||||||
|
ticker?: string;
|
||||||
|
tickers?: Record<string, string>;
|
||||||
|
to: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const inputs = sourceInputs(instrumentType, uids, kinds, range);
|
||||||
|
const reservation = this.reservations.then(async () => {
|
||||||
|
const rows = inputs.length ?
|
||||||
|
await this.repository.readSources(inputs) :
|
||||||
|
[];
|
||||||
|
const ids: string[] = [];
|
||||||
|
for (const input of inputs) {
|
||||||
|
const row = rows.find(
|
||||||
|
(entry) =>
|
||||||
|
entry.instrumentUid === input.uid && entry.kind === input.kind,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!tbankSourceNeedsRefresh(
|
||||||
|
sourcePolicy(input.kind),
|
||||||
|
row?.fetchedAt ?? null,
|
||||||
|
new Date(),
|
||||||
|
force,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const reserved = await this.repository.reserve(
|
||||||
|
{ userId, revision },
|
||||||
|
input,
|
||||||
|
this.runId,
|
||||||
|
this.active,
|
||||||
|
);
|
||||||
|
if (!reserved) continue;
|
||||||
|
const { id, attemptId } = reserved.work;
|
||||||
|
ids.push(id);
|
||||||
|
if (!reserved.launch) continue;
|
||||||
|
const attempt = { userId, revision, id, attemptId };
|
||||||
|
this.active.add(attemptId);
|
||||||
|
let resolve = () => {};
|
||||||
|
const done = new Promise<void>((finish) => {
|
||||||
|
resolve = finish;
|
||||||
|
});
|
||||||
|
this.completions.set(attemptId, { workId: id, done, resolve });
|
||||||
|
const key = producerKey(input);
|
||||||
|
const producer = this.producers.get(key);
|
||||||
|
if (producer) producer.observers.push({ attempt, input });
|
||||||
|
else {
|
||||||
|
const queued = { input, attempt, observers: [] };
|
||||||
|
this.producers.set(key, queued);
|
||||||
|
this.queue.push(queued);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.queue.length && !this.running) {
|
||||||
|
this.running = true;
|
||||||
|
setImmediate(() => {
|
||||||
|
void this.drain();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
});
|
||||||
|
this.reservations = reservation.catch(() => undefined);
|
||||||
|
return reservation;
|
||||||
|
}
|
||||||
|
|
||||||
|
async section(
|
||||||
|
userId: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uid: string,
|
||||||
|
section: 'company' | 'metrics' | 'quote',
|
||||||
|
observe = false,
|
||||||
|
) {
|
||||||
|
const kinds: CatalogSource['kind'][] =
|
||||||
|
section === 'company' ?
|
||||||
|
['detail', 'description', 'fundamentals'] :
|
||||||
|
[
|
||||||
|
...(instrumentType === 'bond' ?
|
||||||
|
['bond-current' as const] :
|
||||||
|
['detail' as const]),
|
||||||
|
'last-price',
|
||||||
|
'trading-status',
|
||||||
|
'comparison',
|
||||||
|
...(section === 'metrics' ?
|
||||||
|
['coupons' as const, 'yield' as const, 'rating' as const] :
|
||||||
|
[]),
|
||||||
|
];
|
||||||
|
const sources = await this.readMany(
|
||||||
|
userId,
|
||||||
|
instrumentType,
|
||||||
|
[uid],
|
||||||
|
observe,
|
||||||
|
kinds,
|
||||||
|
);
|
||||||
|
const first = sources[0];
|
||||||
|
if (first.meta.availability === 'complete' && !first.instrument) {
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
const values = sources.reduce<CatalogPayload>(
|
||||||
|
(result, source) => ({ ...result, ...source.payload }),
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
const dependencies = sources.map((source) => source.meta);
|
||||||
|
const complete = dependencies.every(
|
||||||
|
(dependency) => dependency.availability === 'complete',
|
||||||
|
);
|
||||||
|
const meta = investmentResourceMeta({
|
||||||
|
resourceKey: `${instrumentType}/${section}/${uid}`,
|
||||||
|
dataRevision: dependencies
|
||||||
|
.map((dependency) => dependency.dataRevision)
|
||||||
|
.join('/'),
|
||||||
|
availability: !first.instrument ?
|
||||||
|
'missing' :
|
||||||
|
complete ?
|
||||||
|
'complete' :
|
||||||
|
'partial',
|
||||||
|
fetchedAt: first.meta.lastSuccessfulAt ?
|
||||||
|
new Date(first.meta.lastSuccessfulAt) :
|
||||||
|
null,
|
||||||
|
freshForMs:
|
||||||
|
section === 'company' ?
|
||||||
|
tbankSourceTtlMs.company :
|
||||||
|
tbankSourceTtlMs.quote,
|
||||||
|
work: null,
|
||||||
|
dependencies,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
values,
|
||||||
|
meta,
|
||||||
|
unavailable: sources
|
||||||
|
.filter(
|
||||||
|
(source) =>
|
||||||
|
source.meta.availability !== 'complete' ||
|
||||||
|
source.meta.sync.state === 'failed',
|
||||||
|
)
|
||||||
|
.map((source) => source.input.kind),
|
||||||
|
observedAt: meta.lastSuccessfulAt ?? new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async load(
|
||||||
|
input: CatalogSource,
|
||||||
|
token: string,
|
||||||
|
attempt: TbankSyncAttempt,
|
||||||
|
): Promise<CatalogPayload> {
|
||||||
|
if (input.kind === 'detail' || input.kind === 'bond-current') {
|
||||||
|
const instrument =
|
||||||
|
input.instrumentType === 'share' ?
|
||||||
|
await this.tbank.getShare(token, input.uid) :
|
||||||
|
await this.tbank.getBond(token, input.uid);
|
||||||
|
if (instrument && instrument.uid !== input.uid) {
|
||||||
|
throw new Error('Catalog UID mismatch');
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line sonarjs/different-types-comparison -- Defensive validation rejects missing upstream payloads instead of caching them as absence.
|
||||||
|
if (instrument === undefined) throw new Error('Missing catalog response');
|
||||||
|
return { instrument: instrument ? publicInstrument(instrument) : null };
|
||||||
|
}
|
||||||
|
if (input.kind === 'trading-status') {
|
||||||
|
return {
|
||||||
|
tradingStatus: await this.tbank.getTradingStatus(token, input.uid),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.kind === 'comparison') {
|
||||||
|
const prices = await this.repository.readSources([
|
||||||
|
{ ...input, kind: 'last-price', rangeKey: undefined },
|
||||||
|
]);
|
||||||
|
if (!prices.length) throw new Error('Price dependency missing');
|
||||||
|
const price = (prices[0].payload as CatalogPayload).price;
|
||||||
|
const priceAt = timestamp(price?.time);
|
||||||
|
if (!priceAt) return { candle: null };
|
||||||
|
const now = new Date();
|
||||||
|
const range = {
|
||||||
|
from: utcDay(new Date(Date.parse(priceAt) - previousCloseLookbackMs)),
|
||||||
|
to: new Date(priceAt),
|
||||||
|
};
|
||||||
|
const saved = await this.candles.read(input.uid, range);
|
||||||
|
const gaps = candleGaps(range, saved.coverage, now);
|
||||||
|
for (const gap of gaps) {
|
||||||
|
const response = await this.tbank.getCandles(
|
||||||
|
token,
|
||||||
|
input.uid,
|
||||||
|
gap.from,
|
||||||
|
gap.to,
|
||||||
|
);
|
||||||
|
const rows = response.map((candle) => {
|
||||||
|
const time = timestamp(candle.time);
|
||||||
|
if (!time || !candle.close) {
|
||||||
|
throw new Error('Invalid candle response');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
time,
|
||||||
|
close: formatDecimal(decimal(candle.close)),
|
||||||
|
isComplete: candle.isComplete === true,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (!(await this.candles.stage(attempt, gap, rows, now))) {
|
||||||
|
throw new Error('Cancelled candle comparison');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
gaps.length &&
|
||||||
|
!(await this.candles.publish(
|
||||||
|
attempt,
|
||||||
|
{ uid: input.uid, ranges: gaps },
|
||||||
|
false,
|
||||||
|
))
|
||||||
|
) {
|
||||||
|
throw new Error('Cancelled candle comparison');
|
||||||
|
}
|
||||||
|
const values = (await this.candles.read(input.uid, range)).data.map(
|
||||||
|
(row) => {
|
||||||
|
const value = divide(
|
||||||
|
decimalFromString(row.close),
|
||||||
|
decimalFromString('1'),
|
||||||
|
quotationScale,
|
||||||
|
).value;
|
||||||
|
return {
|
||||||
|
time: {
|
||||||
|
seconds: String(Date.parse(row.time) / MILLISECONDS_PER_SECOND),
|
||||||
|
},
|
||||||
|
close: {
|
||||||
|
units: String(value / quotationUnits),
|
||||||
|
nano: Number(value % quotationUnits),
|
||||||
|
},
|
||||||
|
isComplete: row.isComplete,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return { candle: previousClose(values, priceAt) };
|
||||||
|
}
|
||||||
|
const details = await this.repository.readSources([
|
||||||
|
{ ...input, kind: 'detail', rangeKey: undefined },
|
||||||
|
...(input.instrumentType === 'bond' ?
|
||||||
|
[{ ...input, kind: 'bond-current' as const, rangeKey: undefined }] :
|
||||||
|
[]),
|
||||||
|
]);
|
||||||
|
const instrument = details
|
||||||
|
.map((row) => (row.payload as CatalogPayload).instrument)
|
||||||
|
.find(Boolean);
|
||||||
|
if (
|
||||||
|
!instrument &&
|
||||||
|
!['bond-events', 'coupons', 'dividends'].includes(input.kind)
|
||||||
|
) {
|
||||||
|
throw new Error('Instrument dependency missing');
|
||||||
|
}
|
||||||
|
if (input.kind === 'description') {
|
||||||
|
return {
|
||||||
|
description: instrument?.assetUid ?
|
||||||
|
await this.tbank.getAssetDescription(token, instrument?.assetUid) :
|
||||||
|
null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.kind === 'fundamentals') {
|
||||||
|
return {
|
||||||
|
fundamentals: instrument?.assetUid ?
|
||||||
|
await this.tbank.getFundamentals(token, instrument?.assetUid) :
|
||||||
|
null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.kind === 'coupons' || input.kind === 'dividends') {
|
||||||
|
const year = Number(input.rangeKey);
|
||||||
|
const [from, to] = input.rangeKey?.startsWith('[') ?
|
||||||
|
(JSON.parse(input.rangeKey) as [string, string]) :
|
||||||
|
[
|
||||||
|
`${year - payoutHistoryYears}-01-01`,
|
||||||
|
`${year + payoutFutureYears}-01-01`,
|
||||||
|
];
|
||||||
|
return input.kind === 'coupons' ?
|
||||||
|
{
|
||||||
|
coupons: await this.tbank.getBondCoupons(
|
||||||
|
token,
|
||||||
|
input.uid,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
),
|
||||||
|
} :
|
||||||
|
{
|
||||||
|
dividends: await this.tbank.getDividends(
|
||||||
|
token,
|
||||||
|
input.uid,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.kind === 'bond-events') {
|
||||||
|
const ticker = instrument?.ticker || input.ticker;
|
||||||
|
if (!ticker) throw new Error('Bond ticker missing');
|
||||||
|
return { bondEvents: await this.moex.bondEvents(ticker) };
|
||||||
|
}
|
||||||
|
if (input.kind === 'yield') {
|
||||||
|
return {
|
||||||
|
effectiveYield:
|
||||||
|
instrument?.ticker && instrument.isin && instrument.classCode ?
|
||||||
|
await this.moex.bondYield(
|
||||||
|
instrument.ticker,
|
||||||
|
instrument.isin,
|
||||||
|
instrument.classCode,
|
||||||
|
) :
|
||||||
|
null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.kind === 'rating') {
|
||||||
|
return {
|
||||||
|
creditRating: instrument?.isin ?
|
||||||
|
await this.ratings.rating(instrument.isin) :
|
||||||
|
null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error('Unsupported catalog source');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async drain() {
|
||||||
|
try {
|
||||||
|
while (this.queue.length) {
|
||||||
|
const producer = this.queue.shift();
|
||||||
|
if (!producer) break;
|
||||||
|
const batch = [producer];
|
||||||
|
// One batch RPC for queued prices sharing the same authorized producer.
|
||||||
|
if (producer.input.kind === 'last-price') {
|
||||||
|
for (
|
||||||
|
let i = FIRST_QUEUE_INDEX;
|
||||||
|
i < this.queue.length && batch.length < catalogSearchLimit;
|
||||||
|
) {
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Numeric queue indexes and validated instrument UIDs select internal data only.
|
||||||
|
const next = this.queue[i];
|
||||||
|
if (
|
||||||
|
next.input.kind === 'last-price' &&
|
||||||
|
next.attempt.userId === producer.attempt.userId &&
|
||||||
|
next.attempt.revision === producer.attempt.revision
|
||||||
|
) {
|
||||||
|
batch.push(next);
|
||||||
|
this.queue.splice(i, DEQUEUED_ITEM_COUNT);
|
||||||
|
} else i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let prices: TbankLastPrice[] | undefined;
|
||||||
|
let payload: CatalogPayload | undefined;
|
||||||
|
let failed = false;
|
||||||
|
try {
|
||||||
|
const token = await this.access.tokenForAttempt(producer.attempt);
|
||||||
|
if (!token) failed = true;
|
||||||
|
else if (producer.input.kind === 'last-price') {
|
||||||
|
prices = await this.tbank.getLastPrices(
|
||||||
|
token,
|
||||||
|
batch.map((item) => item.input.uid),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
payload = await this.load(producer.input, token, producer.attempt);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
failed = true;
|
||||||
|
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN') {
|
||||||
|
await this.access.rejectMembershipToken(producer.attempt);
|
||||||
|
} else {
|
||||||
|
this.logger.event('warn', 'catalog-enrichment.failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const item of batch) {
|
||||||
|
const price =
|
||||||
|
prices?.find((entry) => entry.instrumentUid === item.input.uid) ??
|
||||||
|
null;
|
||||||
|
const value =
|
||||||
|
item.input.kind === 'last-price' ?
|
||||||
|
{
|
||||||
|
price: price ?
|
||||||
|
{
|
||||||
|
instrumentUid: item.input.uid,
|
||||||
|
price: price.price,
|
||||||
|
time: price.time,
|
||||||
|
} :
|
||||||
|
null,
|
||||||
|
} :
|
||||||
|
payload;
|
||||||
|
// Keep accepting observers while publication awaits SQLite.
|
||||||
|
item.observers.unshift({ attempt: item.attempt, input: item.input });
|
||||||
|
for (const observer of item.observers) {
|
||||||
|
const success =
|
||||||
|
!failed &&
|
||||||
|
value !== undefined &&
|
||||||
|
(await this.repository.publishSource(
|
||||||
|
observer.attempt,
|
||||||
|
observer.input,
|
||||||
|
value,
|
||||||
|
new Date(),
|
||||||
|
producer.attempt,
|
||||||
|
));
|
||||||
|
await this.repository.finish(observer.attempt, success);
|
||||||
|
this.active.delete(observer.attempt.attemptId);
|
||||||
|
this.completions.get(observer.attempt.attemptId)?.resolve();
|
||||||
|
this.completions.delete(observer.attempt.attemptId);
|
||||||
|
}
|
||||||
|
this.producers.delete(producerKey(item.input));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
for (const completion of this.completions.values()) completion.resolve();
|
||||||
|
this.completions.clear();
|
||||||
|
this.active.clear();
|
||||||
|
this.producers.clear();
|
||||||
|
this.queue.length = 0;
|
||||||
|
this.logger.event('error', 'catalog-enrichment.persistence-failed', {
|
||||||
|
code: 'TBANK_UNAVAILABLE',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function sourceInputs(
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
uids: string[],
|
||||||
|
kinds: CatalogSource['kind'][],
|
||||||
|
range?: {
|
||||||
|
from: string;
|
||||||
|
ticker?: string;
|
||||||
|
tickers?: Record<string, string>;
|
||||||
|
to: string;
|
||||||
|
},
|
||||||
|
): CatalogSource[] {
|
||||||
|
return kinds.flatMap((kind) =>
|
||||||
|
[...new Set(uids)].map((uid) => ({
|
||||||
|
instrumentType,
|
||||||
|
uid,
|
||||||
|
kind,
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Numeric queue indexes and validated instrument UIDs select internal data only.
|
||||||
|
...(kind === 'bond-events' && (range?.tickers?.[uid] || range?.ticker) ?
|
||||||
|
// eslint-disable-next-line security/detect-object-injection -- Numeric queue indexes and validated instrument UIDs select internal data only.
|
||||||
|
{ ticker: range?.tickers?.[uid] || range?.ticker } :
|
||||||
|
{}),
|
||||||
|
...(['coupons', 'dividends'].includes(kind) ?
|
||||||
|
{
|
||||||
|
rangeKey: range ?
|
||||||
|
JSON.stringify([range.from, range.to]) :
|
||||||
|
String(new Date().getUTCFullYear()),
|
||||||
|
} :
|
||||||
|
{}),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function publicInstrument(value: TbankBond | TbankShare) {
|
||||||
|
const bond = value as TbankBond;
|
||||||
|
return {
|
||||||
|
uid: value.uid,
|
||||||
|
figi: value.figi,
|
||||||
|
assetUid: value.assetUid,
|
||||||
|
name: value.name,
|
||||||
|
ticker: value.ticker,
|
||||||
|
isin: value.isin,
|
||||||
|
classCode: value.classCode,
|
||||||
|
realExchange: value.realExchange,
|
||||||
|
apiTradeAvailableFlag: value.apiTradeAvailableFlag,
|
||||||
|
currency: value.currency,
|
||||||
|
shareType: (value as TbankShare).shareType,
|
||||||
|
sector: value.sector,
|
||||||
|
lot: value.lot,
|
||||||
|
brand: value.brand ? { logoName: value.brand.logoName } : undefined,
|
||||||
|
first_1dayCandleDate: value.first_1dayCandleDate,
|
||||||
|
nominal: bond.nominal,
|
||||||
|
initialNominal: bond.initialNominal,
|
||||||
|
aciValue: bond.aciValue,
|
||||||
|
maturityDate: bond.maturityDate,
|
||||||
|
callDate: bond.callDate,
|
||||||
|
couponQuantityPerYear: bond.couponQuantityPerYear,
|
||||||
|
floatingCouponFlag: bond.floatingCouponFlag,
|
||||||
|
perpetualFlag: bond.perpetualFlag,
|
||||||
|
amortizationFlag: bond.amortizationFlag,
|
||||||
|
subordinatedFlag: bond.subordinatedFlag,
|
||||||
|
bondType: bond.bondType,
|
||||||
|
riskLevel: bond.riskLevel,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousCloseLookbackDays = 20;
|
||||||
|
const previousCloseLookbackMs =
|
||||||
|
previousCloseLookbackDays * MILLISECONDS_PER_DAY;
|
||||||
|
const payoutHistoryYears = 5;
|
||||||
|
const payoutFutureYears = 2;
|
||||||
|
export type CatalogPayload = {
|
||||||
|
bondEvents?: MoexBondEvent[];
|
||||||
|
candle?: null | TbankCandle;
|
||||||
|
coupons?: TbankCoupon[];
|
||||||
|
creditRating?: Awaited<ReturnType<NcrRatingsClient['rating']>>;
|
||||||
|
description?: null | string;
|
||||||
|
dividends?: TbankDividend[];
|
||||||
|
effectiveYield?: Awaited<ReturnType<MoexClient['bondYield']>>;
|
||||||
|
fundamentals?: null | TbankFundamentals;
|
||||||
|
instrument?: null | TbankBond | TbankShare;
|
||||||
|
price?: null | TbankLastPrice;
|
||||||
|
tradingStatus?: null | string;
|
||||||
|
};
|
||||||
|
function sourcePolicy(kind: CatalogSource['kind']) {
|
||||||
|
if (
|
||||||
|
[
|
||||||
|
'bond-current',
|
||||||
|
'comparison',
|
||||||
|
'last-price',
|
||||||
|
'trading-status',
|
||||||
|
'yield',
|
||||||
|
].includes(kind)
|
||||||
|
) {
|
||||||
|
return 'quote';
|
||||||
|
}
|
||||||
|
if (kind === 'description' || kind === 'fundamentals') return 'company';
|
||||||
|
if (['bond-events', 'coupons', 'dividends'].includes(kind)) return 'calendar';
|
||||||
|
return 'metadata';
|
||||||
|
}
|
||||||
|
function producerKey(input: CatalogSource) {
|
||||||
|
return input.instrumentType === 'bond' &&
|
||||||
|
(input.kind === 'detail' || input.kind === 'bond-current') ?
|
||||||
|
`bond-metadata:${input.uid}` :
|
||||||
|
catalogScope(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
const quotationScale = 9;
|
||||||
|
const quotationUnits = 1_000_000_000n;
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type { TbankShare } from '../../../../integrations/tbank/tbank.api';
|
||||||
|
|
||||||
|
export const catalogSearchLimit = 30;
|
||||||
|
|
||||||
|
export function selectCatalogInstruments<T extends TbankShare>(
|
||||||
|
found: T[],
|
||||||
|
query: string,
|
||||||
|
instrumentType: 'bond' | 'share',
|
||||||
|
): (T & { uid: string })[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const kind =
|
||||||
|
instrumentType === 'share' ?
|
||||||
|
'INSTRUMENT_TYPE_SHARE' :
|
||||||
|
'INSTRUMENT_TYPE_BOND';
|
||||||
|
const preferredClass = instrumentType === 'share' ? 'TQBR' : 'TQOB';
|
||||||
|
return found
|
||||||
|
.filter(
|
||||||
|
(instrument): instrument is T & { uid: string } =>
|
||||||
|
Boolean(instrument.uid?.trim()) && instrument.instrumentKind === kind,
|
||||||
|
)
|
||||||
|
.sort(
|
||||||
|
(a, b) =>
|
||||||
|
Number(b.apiTradeAvailableFlag === true) -
|
||||||
|
Number(a.apiTradeAvailableFlag === true) ||
|
||||||
|
Number(b.ticker?.toUpperCase() === query.toUpperCase()) -
|
||||||
|
Number(a.ticker?.toUpperCase() === query.toUpperCase()) ||
|
||||||
|
Number(b.classCode === preferredClass) -
|
||||||
|
Number(a.classCode === preferredClass) ||
|
||||||
|
a.uid.localeCompare(b.uid),
|
||||||
|
)
|
||||||
|
.filter((instrument) => {
|
||||||
|
const key = instrument.isin?.trim() ?
|
||||||
|
`isin:${instrument.isin.trim().toUpperCase()}` :
|
||||||
|
`uid:${instrument.uid}`;
|
||||||
|
if (seen.has(key)) return false;
|
||||||
|
seen.add(key);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user