Compare commits
6
Commits
3cf883efbc
...
197ffe2136
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
197ffe2136 | ||
|
|
ce24a84b7f | ||
|
|
8637ad2f34 | ||
|
|
8ba005346d | ||
|
|
7fde3ece6e | ||
|
|
346a6f0057 |
+4
-3
@@ -6,12 +6,13 @@
|
|||||||
|
|
||||||
| Решение / сигнал | Читать |
|
| Решение / сигнал | Читать |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Новый module/provider/service; бизнес-логика; перенос responsibility | [Architecture](conventions/backend-architecture.md) |
|
| Новый файл/suffix/layer; поиск feature owner; progressive structure; перенос responsibility | [Architecture](conventions/backend-architecture.md) |
|
||||||
|
| TS vocabulary, domain literals, magic values | [Domain literals](conventions/backend-architecture.md#domain-literals-and-magic-values) |
|
||||||
| Controller, DTO, route/status, validation/exception, публичная HTTP-семантика | [HTTP API](conventions/backend-http-api.md) |
|
| Controller, DTO, route/status, validation/exception, публичная HTTP-семантика | [HTTP API](conventions/backend-http-api.md) |
|
||||||
| Prisma/schema/query/persistence, transaction, migration, atomic write | [Data](conventions/backend-data.md) |
|
| Repository/data access; Prisma/schema/query, transaction, migration, atomic write | [Data](conventions/backend-data.md) |
|
||||||
| Тесты или behavior с testing risk | [Testing](conventions/backend-testing.md) |
|
| Тесты или behavior с testing risk | [Testing](conventions/backend-testing.md) |
|
||||||
| JWT, cookie, login/refresh/logout, guard/access, token encryption, sensitive logs | [Security](conventions/security-auth.md) |
|
| JWT, cookie, login/refresh/logout, guard/access, token encryption, sensitive logs | [Security](conventions/security-auth.md) |
|
||||||
| T-Bank/gRPC/proto, upstream retry/rate limit/cache, MoexClient | [Integrations](conventions/backend-integrations.md) |
|
| External client/integration boundary; T-Bank/gRPC/proto, retry/rate limit/cache | [Integrations](conventions/backend-integrations.md) |
|
||||||
| Logging/request context без изменения secrets/auth | [Logging](conventions/backend-architecture.md#logging) |
|
| Logging/request context без изменения secrets/auth | [Logging](conventions/backend-architecture.md#logging) |
|
||||||
| Новый abstraction/dependency, refactor, неясный scope | [Общий выбор реализации](../../docs/development/engineering-governance.md#выбор-реализации) |
|
| Новый abstraction/dependency, refactor, неясный scope | [Общий выбор реализации](../../docs/development/engineering-governance.md#выбор-реализации) |
|
||||||
| Изменение request/response/route/status/error shape или Swagger metadata | HTTP API + [общий contract workflow](../../docs/development/runtime-openapi-verification.md) |
|
| Изменение request/response/route/status/error shape или Swagger metadata | HTTP API + [общий contract workflow](../../docs/development/runtime-openapi-verification.md) |
|
||||||
|
|||||||
@@ -1,39 +1,257 @@
|
|||||||
# Backend architecture
|
# Backend architecture
|
||||||
|
|
||||||
## Выбор владельца
|
## Module-first organization
|
||||||
|
|
||||||
Найди существующий use case, его collaborators и tests до создания module/service.
|
Backend — domain-oriented modular monolith с лёгким разделением
|
||||||
Сохрани ответственность в текущем module, если новая возможность относится к нему.
|
по ответственности. `src/modules` группирует код по бизнес-возможности: `auth`, `banking/bank-cards`, области `investments`.
|
||||||
Module — граница связного набора providers, а не папка для каждого endpoint.
|
В инвестициях отдельные Nest modules владеют `brokerage-accounts`, `portfolio`,
|
||||||
|
`operations`, `income`, `upcoming-events`, `instruments`, `tbank-connection`.
|
||||||
|
`instruments/stocks` и `instruments/bonds` — slices внутри одного модуля.
|
||||||
|
|
||||||
| Решение | Owner |
|
### Progressive structure
|
||||||
|
|
||||||
|
Три уровня организации: business module → responsibility layer → technical grouping
|
||||||
|
при реальной необходимости. Компактный module с понятными controller/DTO/service
|
||||||
|
может оставаться плоским. Ориентир 5–7 файлов не является порогом: учитывай число
|
||||||
|
ответственностей, наличие domain/repository/use cases и удобство просмотра каталога.
|
||||||
|
|
||||||
|
Когда в module смешаны несколько services, transport, расчёты и persistence,
|
||||||
|
группируй файлы по ответственности:
|
||||||
|
|
||||||
|
```text
|
||||||
|
feature/
|
||||||
|
├── feature.module.ts
|
||||||
|
├── feature.api.ts # только при существующих внешних потребителях
|
||||||
|
├── presentation/ # HTTP, DTO, guards
|
||||||
|
├── application/ # сценарии, orchestration, application input
|
||||||
|
├── domain/ # чистые бизнес-правила и расчёты
|
||||||
|
└── infrastructure/ # persistence, framework и boundary mapping
|
||||||
|
```
|
||||||
|
|
||||||
|
Создавай только нужные слои. В корне сложного module оставляй composition и
|
||||||
|
публичную boundary; production code и colocated tests размещай в слое владельца.
|
||||||
|
Внутри business slice действует то же правило, без отдельного Nest module ради папок.
|
||||||
|
`controllers/`, `dto/`, `services/`, `use-cases/`, `persistence/`, `mappers/`
|
||||||
|
допустимы только внутри слоя, когда множество однотипных файлов мешает навигации.
|
||||||
|
Для одного controller или пары DTO дополнительная поддиректория не нужна.
|
||||||
|
Пустые папки, новые barrels, CQRS и interfaces не требуются для этой организации.
|
||||||
|
|
||||||
|
В текущем коде слои используют `auth`, `bank-cards`, `portfolio`, `operations`
|
||||||
|
и slices `instruments/stocks`, `instruments/bonds`. Общие application helpers
|
||||||
|
инструментов находятся в `instruments/application`; `instruments.module.ts`
|
||||||
|
компонует оба slice. `stock-position.ts` и `instrument-position.ts` формируют
|
||||||
|
результат из portfolio DTO; `instrument-market.ts` обрабатывает внешние данные
|
||||||
|
и ошибки Nest. Это application code, а не независимая domain model.
|
||||||
|
`brokerage-accounts`, `income`, `upcoming-events`, `tbank-connection` остаются
|
||||||
|
компактными плоскими modules. Наличие tests само по себе не требует слоёв.
|
||||||
|
|
||||||
|
## Поиск и создание файла
|
||||||
|
|
||||||
|
При работе над feature проходи владельцев в порядке:
|
||||||
|
|
||||||
|
1. Найди business module.
|
||||||
|
2. Прочитай его `*.module.ts` (для slice — composition родительского module).
|
||||||
|
3. Проверь `presentation/`: controller и transport contract.
|
||||||
|
4. Проследи вызовы в `application/`: сценарии и services.
|
||||||
|
5. Проверь используемые правила в `domain/`.
|
||||||
|
6. Проверь `infrastructure/`: repository и технические реализации.
|
||||||
|
7. По обнаруженным зависимостям переходи в `integrations/` и `common/`.
|
||||||
|
|
||||||
|
В плоском module классифицируй файлы по suffix и следуй их ответственности.
|
||||||
|
Отсутствующий слой пропускай. Если business owner известен, начинай локально,
|
||||||
|
а не с repository-wide search.
|
||||||
|
|
||||||
|
**Rule of locality:** code that belongs to one business capability stays inside
|
||||||
|
that capability unless it is cross-cutting. Например, расчёты карт принадлежат
|
||||||
|
bank-cards/domain, даже если реализованы обычными функциями.
|
||||||
|
|
||||||
|
Перед созданием файла определи:
|
||||||
|
|
||||||
|
1. Какой business module владеет изменением? Сначала owner, затем common при
|
||||||
|
подтверждённой общей потребности.
|
||||||
|
2. Какова ответственность: HTTP/DTO/guard → presentation; сценарий/orchestration →
|
||||||
|
application; чистое business rule/calculation → domain; persistence или
|
||||||
|
module-specific technical implementation → infrastructure; внешний протокол → integrations.
|
||||||
|
3. Какой approved suffix из таблицы соответствует этой ответственности?
|
||||||
|
4. Какой слой владеет файлом? В компактном плоском module сохрани размещение рядом
|
||||||
|
с owner; в слоистом используй соответствующий слой.
|
||||||
|
5. Достаточно ли colocate файл рядом с существующими? Level 3 grouping создавай
|
||||||
|
только при заметном улучшении навигации по множеству однотипных файлов.
|
||||||
|
|
||||||
|
Если owner или роль не определены, сначала установи ответственность. Generic
|
||||||
|
`utils.ts`, `helpers.ts`, `manager.ts`, `handler.ts` и arbitrary directory её не заменяют.
|
||||||
|
|
||||||
|
## Naming & File Suffix Convention
|
||||||
|
|
||||||
|
Имена файлов — `kebab-case`. File suffix определяет responsibility, directory
|
||||||
|
определяет architectural layer. Размещение в таблице предпочтительно для
|
||||||
|
слоистого module; компактный плоский module сохраняет файлы в корне.
|
||||||
|
Cross-module consumers во всех строках ограничены публичной границей ниже.
|
||||||
|
|
||||||
|
| Suffix | Когда использовать | Где | Кто зависит | Когда не использовать |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `*.controller.ts` | HTTP endpoint / transport | presentation | Nest wiring | DB, расчёты, SDK, сложная оркестрация |
|
||||||
|
| `*.dto.ts` | Request/response, validation, OpenAPI | presentation | Controller; application boundary при совпадении shape | Универсальная domain model |
|
||||||
|
| `*.use-case.ts` | Один самостоятельный application scenario | application | Controller, другой orchestrator | Prisma queries, Request/Response, SDK implementation |
|
||||||
|
| `*.service.ts` | Конкретная cohesive reusable capability | рядом с owner; application/domain/integration по роли | Сценарии и services; domain — только от чистого domain service | Свалка несвязанных сценариев |
|
||||||
|
| `*.repository.ts` | Persistence queries и согласованные DB reads/writes | infrastructure | Application service/use case | Domain calculations, HTTP request, external transport |
|
||||||
|
| `*.client.ts` | Низкоуровневый внешний HTTP/gRPC/SDK | integrations или infrastructure | Application orchestration, boundary mapper | Пользовательский lifecycle и domain rules |
|
||||||
|
| `*.mapper.ts` | Meaningful conversion между моделями | обычно infrastructure у преобразуемой boundary | Код соответствующей boundary | Формальное копирование нескольких одинаковых полей |
|
||||||
|
| `*.policy.ts` | Cohesive decision rule | domain/application/integration по входным данным | Владелец правила; domain — от чистой policy | Persistence, transport, generic strategy |
|
||||||
|
| `*.guard.ts` | Nest guard | presentation | Nest/controller | Основная account authorization и финансовые правила |
|
||||||
|
| `*.strategy.ts` | Framework strategy, например JWT | infrastructure | Framework wiring | Обычный service без strategy contract |
|
||||||
|
| `*.module.ts` | Nest imports/providers/controllers/exports | module root | Composition root, importing module | Бизнес-логика |
|
||||||
|
| `*.types.ts` | Малая группа связанных TS types | рядом с owner | Потребители модели на разрешённых слоях | Глобальные types всего module, runtime validation |
|
||||||
|
| `*.api.ts` | Явный список публичных exports | root конкретного module/integration | Другие modules | DTO/client/service implementation или generic API logic |
|
||||||
|
| `*-input.ts` | Application input: нормализация и проверка формы, отличающейся от wire DTO | application | Application code | Копия DTO под новым именем; вариант `*.input.ts` |
|
||||||
|
| `*.calculations.ts`, `*.rules.ts` или предметное имя | Чистые бизнес-расчёты, value semantics | domain | Application и domain | Nest/Prisma/HTTP/SDK зависимости |
|
||||||
|
| `*.spec.ts` | Существующая unit/component проверка поведения | рядом с owner/slice | Test runner | Архитектурные проверки папок и trivial wiring |
|
||||||
|
|
||||||
|
`bank-card-input.ts` использует выбранный `*-input.ts`: переводит Money в
|
||||||
|
копейки, нормализует значения и проверяет application input. DTO не дублируется
|
||||||
|
отдельным Input type. `rub-money.ts` — domain-правила RUB; `bond-money.mapper.ts`
|
||||||
|
— преобразование ответа клиента. Эти роли не определяются словом money в имени.
|
||||||
|
|
||||||
|
Технические framework suffixes (`*.filter.ts`, `*.middleware.ts`,
|
||||||
|
`*.decorator.ts`, `*.config.ts`, `*.validation.ts`) сохраняют соответствующие
|
||||||
|
существующие роли в common/config. `tbank.crypto.ts` — локальная реализация
|
||||||
|
шифрования токена; имя не является разрешением создавать generic crypto layer.
|
||||||
|
HTTP/e2e naming и расположение — в [Testing](backend-testing.md).
|
||||||
|
|
||||||
|
Без зафиксированной необходимости не вводи `*.helper.ts`, `*.utils.ts`,
|
||||||
|
`*.manager.ts`, `*.processor.ts`, `*.handler.ts`, `*.provider.ts`, `*.factory.ts`.
|
||||||
|
Новая naming convention сначала получает конкретную роль и обоснование здесь.
|
||||||
|
Для data access выбран только `*.repository.ts`, не persistence/store/dao.
|
||||||
|
|
||||||
|
## Публичные границы
|
||||||
|
|
||||||
|
`*.module.ts` задаёт DI boundary; `*.api.ts` перечисляет используемые другими
|
||||||
|
модулями providers, функции и типы. Внешний production import идёт через этот
|
||||||
|
API или файл Nest module. Чистый `integrations/tbank/decimal.ts` — отдельный
|
||||||
|
публичный вход для protobuf conversion: импорт арифметики не загружает DI/Prisma.
|
||||||
|
Внутри модуля используй прямые локальные импорты.
|
||||||
|
Tests могут импортировать внутренний owner для проверки поведения и mocks.
|
||||||
|
Новый export требует текущего потребителя; controller и persistence остаются
|
||||||
|
приватными. Не добавляй `index.ts` на каждом уровне.
|
||||||
|
|
||||||
|
Каждый provider регистрируется у одного владельца. Потребители импортируют
|
||||||
|
его module, а не повторяют provider: это сохраняет единственный кэш и лимитер.
|
||||||
|
`AuthModule` экспортирует guard; наличие JWT не заменяет account access check.
|
||||||
|
|
||||||
|
- `income` читает операции через `operations.api.ts`.
|
||||||
|
- `instruments` получает личные позиции через `portfolio.api.ts`.
|
||||||
|
- `tbank-connection` использует T-Bank integration и публичный сброс портфеля.
|
||||||
|
- `portfolio` и другие инвестиционные модули используют `TbankModule`, который
|
||||||
|
не зависит от business modules. Так управление подключением не образует цикл.
|
||||||
|
- `investment-calendar.ts` и `account-reference.dto.ts` разделяются только
|
||||||
|
инвестиционными областями; это не глобальная библиотека бизнес-правил.
|
||||||
|
|
||||||
|
## Ответственность и направление зависимостей
|
||||||
|
|
||||||
|
| Владелец | Ответственность |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Route, request/response mapping, status/cookie | Controller, [HTTP rules](backend-http-api.md) |
|
| Controller / presentation | Route, verified identity, transport DTO, validation, status/cookie; вызов сценария |
|
||||||
| Business use case, orchestration, domain validation | Feature service |
|
| Use case / application service | Оркестрация, business validation, доступ и согласованность результата |
|
||||||
| Input shape/format | DTO + configured ValidationPipe |
|
| Domain | Чистые правила и расчёты; без NestJS, Prisma, HTTP/Swagger и внешних SDK |
|
||||||
| Атомарность/DB query | Сервис use case через PrismaService, [Data](backend-data.md) |
|
| Persistence / infrastructure | Запросы, транзакции, технические реализации границ |
|
||||||
| Внешний protocol, deadline/retry/limiting | Existing client, [Integrations](backend-integrations.md) |
|
| `src/integrations/{tbank,moex,ncr}` | Внешние протоколы, декодирование, retry/deadline/cache; без зависимостей от HTTP DTO business modules |
|
||||||
| Чистое вычисление/mapper без lifecycle и DI | Обычная функция рядом с domain owner |
|
| `src/prisma` | Общий DB provider и lifecycle; не generic repository |
|
||||||
| Bootstrap/config/global cross-cutting concern | AppModule, config, существующий common owner |
|
|
||||||
|
|
||||||
**Безопасный путь:** расширь текущий owner; выделяй collaborator, когда он скрывает
|
Основной вызов: presentation → application → domain; application использует
|
||||||
самостоятельный инвариант или координацию. Не вводи CQRS, generic repository,
|
конкретные infrastructure providers, зарегистрированные module. Infrastructure
|
||||||
interface с одной реализацией или base controller только ради шаблона Nest.
|
может использовать application types/input и domain rules; новые interfaces
|
||||||
Не превращай common в хранилище бизнес-логики и не переноси frontend модели сюда.
|
ради инверсии зависимостей не обязательны. Domain не импортирует presentation или
|
||||||
|
infrastructure. Существующие связные CRUD/transaction services могут сохранять прямые queries
|
||||||
|
по [Data](backend-data.md); use case получает данные через repository и сам
|
||||||
|
Prisma queries не выполняет. Entity/interface на каждую таблицу не требуется.
|
||||||
|
DTO остаются транспортными runtime classes; существующее использование DTO
|
||||||
|
на application boundary допустимо по [HTTP API](backend-http-api.md).
|
||||||
|
|
||||||
## Существующие seams
|
Сохраняй существующий error contract: HTTP exceptions остаются на application/
|
||||||
|
transport boundary. Чистому расчёту не нужен новый framework ошибок.
|
||||||
|
Точные ограничения — [HTTP](backend-http-api.md), [Data](backend-data.md),
|
||||||
|
[Security](security-auth.md), [Integrations](backend-integrations.md).
|
||||||
|
|
||||||
`TbankConnectionModule` уже объединяет счета, портфель, операции, доходы и события.
|
## Сценарии и размер сервисов
|
||||||
Новый связанный use case обычно добавляется в него; создание отдельного module
|
|
||||||
требует собственной ответственности, не только нового файла.
|
|
||||||
|
|
||||||
- [BrokerageOperationsController](../../src/tbank/brokerage-operations.controller.ts) передаёт user/account/query в service, без финансовых вычислений в controller.
|
Разделяй независимые операции, а не строки. `BankCardsService` отвечает за карты,
|
||||||
- [TbankAccessService](../../src/tbank/tbank-access.service.ts) владеет connection/account access и generation; новые account use cases используют его вместо копирования guard/decrypt logic.
|
`BankOperationsService` — журнал/переводы/возвраты, `ExpenseCategoriesService` —
|
||||||
- [decimal.ts](../../src/tbank/decimal.ts) — пример pure domain helper; Injectable и adapter для арифметики не нужны.
|
категории, `GetBankSummaryUseCase` — сводку. `BankCardsRepository` сохраняет
|
||||||
|
общий transaction retry и owner lookup; денежные транзакции не разрываются.
|
||||||
|
Чистые расчёты банковских карт находятся в `domain` этого модуля.
|
||||||
|
|
||||||
Наличие guard подтверждает session, но не владение account. При пересечении
|
У инструментов `StockCatalogService` / `BondCatalogService` хранят идентичность
|
||||||
access boundary добавь [Security](security-auth.md). Ошибка upstream не должна
|
листинга и общий кэш slice; market service — котировки/свечи, income service — выплаты/личные позиции.
|
||||||
обходить общий HTTP filter или превращать чужой account в доступный.
|
`GetStockCompanyUseCase` владеет сведениями об эмитенте. Ключи, TTL и pending
|
||||||
|
promises разделяют прежний экземпляр кэша; extract не должен менять generation.
|
||||||
|
Portfolio и operations сохраняют связную координацию снимков/страниц и кэшей.
|
||||||
|
Расчёты портфеля находятся в `portfolio/domain`; преобразование брокерских
|
||||||
|
позиций — в `tbank-portfolio.mapper.ts`. `bond-money.mapper.ts` преобразует
|
||||||
|
ответ клиента и не является value object.
|
||||||
|
|
||||||
|
Выбирай обычную функцию для чистого вычисления; repository contract — только
|
||||||
|
для реальной границы. CQRS/buses/events, BaseRepository/BaseService, DI token
|
||||||
|
для каждого класса, mapper/presenter для каждого DTO и новые dependencies
|
||||||
|
не нужны для структурного переноса.
|
||||||
|
|
||||||
|
## Common
|
||||||
|
|
||||||
|
`common` содержит общий error filter, logging, API decorators, тип `Money`,
|
||||||
|
его HTTP `MoneyDto` и точную decimal-арифметику, используемые несколькими областями. Код одного
|
||||||
|
модуля принадлежит этому модулю: например, RUB/kopecks rules — банковским картам,
|
||||||
|
protobuf units/nano conversion — T-Bank integration. Domain использует
|
||||||
|
`money.types.ts`, а не Swagger DTO; это общая форма денег для карт и портфеля.
|
||||||
|
Давай функциям предметные имена; не создавай глобальные `utils.ts`/`helpers.ts`.
|
||||||
|
|
||||||
|
## Domain literals and magic values
|
||||||
|
|
||||||
|
Finite business vocabulary must be modeled explicitly; incidental implementation
|
||||||
|
literals stay inline. Это относится к error codes, statuses, operation/account/
|
||||||
|
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
|
||||||
|
|
||||||
|
Перед новым определением найди existing owner/type/value. В branching и comparisons
|
||||||
|
используй символическое значение владельца; не повторяй raw domain literals.
|
||||||
|
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
|
||||||
|
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
|
||||||
|
без подходящего аналога используй `as const` с derived union:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const BankErrorCode = {
|
||||||
|
InvalidDate: "BANK_INVALID_DATE",
|
||||||
|
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
|
||||||
|
} as const;
|
||||||
|
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||||
|
|
||||||
|
// Вместо code === "BANK_INVALID_DATE":
|
||||||
|
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
|
||||||
|
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
|
||||||
|
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
|
||||||
|
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
|
||||||
|
`percentage * 100` и очевидные локальные детали без semantic benefit.
|
||||||
|
При неясном owner/смысле оставь значение и укажи ограничение в review.
|
||||||
|
|
||||||
|
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
|
||||||
|
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
|
||||||
|
custom lint/AST rules, generation/validation scripts или тесты существования
|
||||||
|
констант. Semantic review проверяет ownership, единое написание и неизменность
|
||||||
|
wire values; обычные behavior tests проверяют поведение.
|
||||||
|
|
||||||
|
OpenAPI enum metadata и runtime validation должны читать тот же vocabulary,
|
||||||
|
что application/domain. Например, `BankOperationKind` принадлежит bank-cards/domain,
|
||||||
|
а DTO получает допустимые значения через `Object.values(BankOperationKind)`.
|
||||||
|
Frontend переиспользует generated OpenAPI types/values по возможностям генератора,
|
||||||
|
а не определяет независимый backend-owned словарь. Внешние/generated enums
|
||||||
|
сохраняй; generated Prisma/protocol code вручную не меняй.
|
||||||
|
|
||||||
|
`@typescript-eslint/no-magic-numbers` включён как error; базовое ESLint rule
|
||||||
|
отключено в пользу TS-версии. Исключения для очевидных чисел и их bigint форм,
|
||||||
|
индексов, default values, enum/type declarations и readonly properties заданы
|
||||||
|
в ESLint config. Test fixtures/expected values остаются inline, остальные lint
|
||||||
|
правила продолжают действовать. Numeric policy получает предметное имя и единицы;
|
||||||
|
semantic magic strings проверяются conventions/review без нового инструмента.
|
||||||
|
|
||||||
## Logging
|
## Logging
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,33 @@ PrismaService — существующий shared DB provider с lifecycle пр
|
|||||||
|
|
||||||
| Ситуация | Решение |
|
| Ситуация | Решение |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Один query/write конкретного use case | Existing service + PrismaService |
|
| Данные для use case | Concrete repository; use case не импортирует PrismaService/Prisma и не строит queries |
|
||||||
| Несколько записей обязаны выполниться вместе | Database transaction вокруг инварианта |
|
| Несколько записей обязаны выполниться вместе | Database transaction вокруг инварианта |
|
||||||
| Конкурентная смена одного значения | Atomic conditional update/constraint с проверкой результата |
|
| Конкурентная смена одного значения | Atomic conditional update/constraint с проверкой результата |
|
||||||
| Независимые reads | Не добавляй transaction ради внешнего вида |
|
| Независимые reads | Не добавляй transaction ради внешнего вида |
|
||||||
| Общая persistence abstraction | Только при реальной общей ответственности; generic repository для одной Prisma реализации не нужен |
|
| Общая persistence abstraction | Только при реальной общей ответственности; generic repository для одной Prisma реализации не нужен |
|
||||||
|
|
||||||
|
Размещение repository определяется [Architecture](backend-architecture.md):
|
||||||
|
в слоистом module это `infrastructure/`.
|
||||||
|
Repository — конкретный класс `*.repository.ts` у business owner, без обязательных
|
||||||
|
interface/port/adapter. Он владеет queries, includes/filtering, DB mapping и
|
||||||
|
согласованным чтением. Суффиксы `*.persistence.ts`, `*.store.ts`, `*.dao.ts`
|
||||||
|
для той же роли не используем. Nest module регистрирует repository приватно.
|
||||||
|
|
||||||
|
`BankCardsRepository.summaryData` проверяет владельца карты и получает операции
|
||||||
|
с категориями в одной read transaction. `GetBankSummaryUseCase` выбирает период,
|
||||||
|
вызывает repository, затем чистый `bankSummary` и формирует ответ. Prisma records
|
||||||
|
не становятся domain entities: расчёт получает только нужные ему значения.
|
||||||
|
|
||||||
|
Не создавай обёртку на каждый вызов Prisma. Существующие связные CRUD/transaction
|
||||||
|
services (auth, lifecycle подключения, изменения карт/операций/категорий)
|
||||||
|
сохраняют queries рядом с CAS и проверками инварианта, если их перенос требует
|
||||||
|
лишь набора pass-through методов. Новая самостоятельная read/write capability
|
||||||
|
получает repository method; самостоятельный use case не выполняет Prisma queries.
|
||||||
|
`BankCardsRepository.write` сохраняет общую retry/transaction boundary для
|
||||||
|
существующих banking services. Такой callback с Prisma transaction client —
|
||||||
|
локальная техническая граница этих services, не API для domain или use cases.
|
||||||
|
|
||||||
Выбирай только нужные данные, сохраняй user/account ownership в запросах и
|
Выбирай только нужные данные, сохраняй user/account ownership в запросах и
|
||||||
application checks. Предварительный lookup не заменяет unique constraint при race.
|
application checks. Предварительный lookup не заменяет unique constraint при race.
|
||||||
Пример: AuthService обрабатывает P2002 и использует conditional `updateMany`
|
Пример: AuthService обрабатывает P2002 и использует conditional `updateMany`
|
||||||
|
|||||||
@@ -16,16 +16,23 @@ use case. Для route/request/response/status/error shape читай
|
|||||||
| HTTP envelope/безопасная ошибка | Общий HttpExceptionFilter |
|
| HTTP envelope/безопасная ошибка | Общий HttpExceptionFilter |
|
||||||
|
|
||||||
Controller объявляет contract и делегирует; не обращается напрямую к Prisma/gRPC
|
Controller объявляет contract и делегирует; не обращается напрямую к Prisma/gRPC
|
||||||
ради обхода service. Request identity берётся из verified `request.user`, не из
|
и не выполняет финансовые расчёты или сложную оркестрацию.
|
||||||
body/userId, предоставленного клиентом. Access rules активируют Security.
|
Controller вызывает application use case/service. Identity берётся из verified
|
||||||
|
`request.user`, не из body/userId, предоставленного клиентом. Access rules активируют Security.
|
||||||
|
|
||||||
## DTO и errors
|
## DTO и errors
|
||||||
|
|
||||||
DTO — runtime class: TS interface не предоставляет validation metadata.
|
DTO — runtime class: TS interface не предоставляет validation metadata.
|
||||||
|
`*.controller.ts` и `*.dto.ts` остаются около HTTP boundary, в root компактного
|
||||||
|
module или presentation. DTO можно передать application boundary при совпадении
|
||||||
|
формы; отдельный Input с теми же полями не нужен. Domain не импортирует DTO:
|
||||||
|
например, чистые денежные расчёты используют `Money`, а Swagger — `MoneyDto`.
|
||||||
|
Нормализованная форма input нужна только при смысловом отличии от wire contract;
|
||||||
|
выбор suffix принадлежит [Architecture](backend-architecture.md).
|
||||||
ValidationPipe уже настроен в `configureApp` (`transform`, `whitelist`).
|
ValidationPipe уже настроен в `configureApp` (`transform`, `whitelist`).
|
||||||
Не обещай rejection неизвестных fields: `forbidNonWhitelisted` не включён.
|
Не обещай rejection неизвестных fields: `forbidNonWhitelisted` не включён.
|
||||||
Для query numbers/arrays выбирай явное преобразование и валидаторы, как в
|
Для query numbers/arrays выбирай явное преобразование и валидаторы, как в
|
||||||
[operations DTO](../../src/tbank/brokerage-operation.dto.ts). Swagger metadata
|
[operations DTO](../../src/modules/investments/operations/presentation/brokerage-operation.dto.ts). Swagger metadata
|
||||||
описывает те же required/optional/nullable/enum/range значения.
|
описывает те же required/optional/nullable/enum/range значения.
|
||||||
|
|
||||||
Используй типизированные response DTO, `ApiOkResponse`/другой фактический status
|
Используй типизированные response DTO, `ApiOkResponse`/другой фактический status
|
||||||
@@ -40,7 +47,7 @@ raw upstream error, Prisma record с secrets или stack. Текущая фор
|
|||||||
|
|
||||||
## Пример и проверка
|
## Пример и проверка
|
||||||
|
|
||||||
[Operations controller](../../src/tbank/brokerage-operations.controller.ts)
|
[Operations controller](../../src/modules/investments/operations/presentation/brokerage-operations.controller.ts)
|
||||||
показывает guard, user.sub, DTO query и service delegation.
|
показывает guard, user.sub, DTO query и service delegation.
|
||||||
Для нового field обновляй canonical source и generated artifacts в определённом
|
Для нового field обновляй canonical source и generated artifacts в определённом
|
||||||
направлении; body type frontend не исправляется вручную.
|
направлении; body type frontend не исправляется вручную.
|
||||||
|
|||||||
@@ -3,14 +3,34 @@
|
|||||||
## Выбор boundary
|
## Выбор boundary
|
||||||
|
|
||||||
T-Bank gRPC принадлежит TbankClient; MOEX metadata — MoexClient. Сервисы use case
|
T-Bank gRPC принадлежит TbankClient; MOEX metadata — MoexClient. Сервисы use case
|
||||||
получают нормализованный результат через эти clients. Frontend не вызывает
|
используют объявленные клиентом records; SDK clients, metadata и transport errors
|
||||||
|
остаются внутри integration. Frontend не вызывает
|
||||||
T-Bank и не получает credentials/proto client. Reference source —
|
T-Bank и не получает credentials/proto client. Reference source —
|
||||||
[ADR 003](../../../docs/adr/003-tbank-server-side-grpc-boundary.md) и
|
[ADR 003](../../../docs/adr/003-tbank-server-side-grpc-boundary.md) и
|
||||||
[connection behavior](../../../docs/integrations/tbank.md).
|
[connection behavior](../../../docs/integrations/tbank.md).
|
||||||
|
|
||||||
|
`modules/investments/tbank-connection` — пользовательская capability чтения,
|
||||||
|
создания/замены и удаления подключения. `integrations/tbank` — технические
|
||||||
|
RPC, credentials/access и resilience. Эти владельцы не объединяются из-за имени
|
||||||
|
поставщика; низкоуровневый client не зависит от пользовательского module.
|
||||||
|
|
||||||
|
`*.client.ts` содержит transport и его retries; `*.api.ts` только перечисляет
|
||||||
|
публичные exports. Все шесть `auth/operations/portfolio/tbank/moex/ncr.api.ts`
|
||||||
|
имеют одинаковую роль программной границы, определённую в
|
||||||
|
[Architecture](backend-architecture.md). Логика, DTO definitions и HTTP routes
|
||||||
|
в эти файлы не помещаются. Type exports обозначаются `export type`.
|
||||||
|
|
||||||
|
Преобразование provider records происходит на boundary: например,
|
||||||
|
`tbank-portfolio.mapper.ts` и `bond-money.mapper.ts`; protobuf decimal helper
|
||||||
|
остаётся отдельным чистым входом integration. Domain получает внутренние
|
||||||
|
значения и не импортирует gRPC/SDK types. Не добавляй новый adapter на каждый
|
||||||
|
client или mapper для простого копирования полей. Даты/units/nano разбираются
|
||||||
|
на границе клиента/его mapping, а не становятся моделью чистых расчётов.
|
||||||
|
|
||||||
Для нового account use case сначала используй TbankAccessService: access,
|
Для нового account use case сначала используй TbankAccessService: access,
|
||||||
connection generation и invalid-token translation не дублируются в callers.
|
connection generation и invalid-token translation не дублируются в callers.
|
||||||
Чистый mapper финансового значения остаётся рядом с domain owner.
|
Mapper внешних финансовых значений остаётся внутри business capability,
|
||||||
|
обычно в infrastructure по [Architecture](backend-architecture.md).
|
||||||
|
|
||||||
## Retry, cache и protocol
|
## Retry, cache и protocol
|
||||||
|
|
||||||
@@ -30,7 +50,7 @@ cache/stale policy; semantics конкретного use case читай чер
|
|||||||
raw gRPC exception не уходит клиенту. Existing translation — в TbankTokenService
|
raw gRPC exception не уходит клиенту. Existing translation — в TbankTokenService
|
||||||
и общем HTTP boundary. Для HTTP error change читай HTTP API/Security по trigger.
|
и общем HTTP boundary. Для HTTP error change читай HTTP API/Security по trigger.
|
||||||
|
|
||||||
Vendor proto хранится в `src/tbank/proto/contracts`; для обновления сверяй
|
Vendor proto хранится в `src/integrations/tbank/proto/contracts`; для обновления сверяй
|
||||||
официальный source и влияние на loader/DTO, не редактируй read-only references.
|
официальный source и влияние на loader/DTO, не редактируй read-only references.
|
||||||
Generated artifacts, если есть, создавай из source, без ручной подгонки вывода.
|
Generated artifacts, если есть, создавай из source, без ручной подгонки вывода.
|
||||||
|
|
||||||
@@ -40,7 +60,7 @@ Generated artifacts, если есть, создавай из source, без р
|
|||||||
ответственного service. Отдельный abstraction/adapter оправдан новой
|
ответственного service. Отдельный abstraction/adapter оправдан новой
|
||||||
ответственностью или несовместимым protocol, не только вторым методом.
|
ответственностью или несовместимым protocol, не только вторым методом.
|
||||||
|
|
||||||
[TbankClient tests](../../src/tbank/tbank.client.spec.ts) — пример controlled
|
[TbankClient tests](../../src/integrations/tbank/tbank.client.spec.ts) — пример controlled
|
||||||
upstream responses. Проверь queue/deadline/retry limit, token translation,
|
upstream responses. Проверь queue/deadline/retry limit, token translation,
|
||||||
cache isolation и late response для затронутых ветвей. Fixtures синтетические;
|
cache isolation и late response для затронутых ветвей. Fixtures синтетические;
|
||||||
реальная сеть, секреты и пользовательские accounts не нужны.
|
реальная сеть, секреты и пользовательские accounts не нужны.
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ Unit specs colocated в `src/**/*.spec.ts`; HTTP/integration — `test/`.
|
|||||||
|
|
||||||
## Случаи и примеры
|
## Случаи и примеры
|
||||||
|
|
||||||
- [BrokerageAccountsService tests](../../src/tbank/brokerage-accounts.service.spec.ts): отсутствие connection не вызывает upstream, нормализация и точные суммы.
|
- [BrokerageAccountsService tests](../../src/modules/investments/brokerage-accounts/brokerage-accounts.service.spec.ts): отсутствие connection не вызывает upstream, нормализация и точные суммы.
|
||||||
- [AuthService tests](../../src/auth/auth.service.spec.ts): invalid/expired/superseded token и concurrent rotation; mock race test не является доказательством DB transaction.
|
- [AuthService tests](../../src/modules/auth/application/auth.service.spec.ts): invalid/expired/superseded token и concurrent rotation; mock race test не является доказательством DB transaction.
|
||||||
- [HTTP filter tests](../../src/common/filters/http-exception.filter.spec.ts): безопасный error envelope.
|
- [HTTP filter tests](../../src/common/filters/http-exception.filter.spec.ts): безопасный error envelope.
|
||||||
- [OpenAPI integration](../../test/openapi-contract.e2e-spec.ts): configured app + frontend snapshot, без записи snapshot и без T-Bank.
|
- [OpenAPI integration](../../test/openapi-contract.e2e-spec.ts): configured app + frontend snapshot, без записи snapshot и без T-Bank.
|
||||||
|
|
||||||
@@ -36,11 +36,15 @@ Unit specs colocated в `src/**/*.spec.ts`; HTTP/integration — `test/`.
|
|||||||
Полный `npm run verify` включает lint, оба typecheck, Jest и build.
|
Полный `npm run verify` включает lint, оба typecheck, Jest и build.
|
||||||
`npm run test:openapi-contract` — отдельный required check при wire contract change.
|
`npm run test:openapi-contract` — отдельный required check при wire contract change.
|
||||||
|
|
||||||
`npm run test:e2e` существует, но известный Prisma migration blocker описан в
|
`npm run test:e2e` запускает все HTTP suites через изолированный SQLite runner;
|
||||||
[ограничении сквозной проверки](../../../docs/development/verification.md#известное-ограничение-сквозной-проверки) и WL-P2-05
|
`npm run test:sqlite` — только auth/cards. Каждая suite получает новую временную
|
||||||
[registry](../../../docs/development/audit-remediation.md). Скрипт использует
|
базу со штатными migrations. Прямой Jest без runner отклоняется до DB-запросов.
|
||||||
фиксированную `/tmp/wealth-ledger-e2e.db`; не запускай его конкурентно как
|
`prisma.config.ts` исключает влияние унаследованного `RUST_LOG=warn/error`,
|
||||||
независимые DB tests. Для isolation выбери отдельную test DB и runner configuration.
|
вызывающего ошибку fresh migration на Prisma 7.9.1. Подробности и регрессия запуска —
|
||||||
Если задаче нужна HTTP/DB proof, установи применимость blocker и выполни доступную
|
[Backend README](../../README.md#реальная-sqlite-и-сохранность-данных).
|
||||||
изолированную проверку. Не объявляй покрытым то, что до tests не запустилось;
|
HTTP suites требуют разрешения открывать локальные порты. Ошибка sandbox
|
||||||
сохрани точный failure и оставшуюся проверку. Unit/Swagger success не заменяет e2e.
|
не считается успешным тестом; повторите проверку в подходящем окружении.
|
||||||
|
|
||||||
|
Для schema/data changes дополнительно `npm run test:durability -- <baseline>`.
|
||||||
|
Матрица рисков и подготовка совместимой предыдущей сборки — в том же README.
|
||||||
|
Mock Prisma не заменяет доказательство реальной DB concurrency.
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ TbankTokenService/TbankCrypto. Расширяй существующую boundar
|
|||||||
[ADR 006](../../../docs/adr/006-auth-session-policy.md)/[009](../../../docs/adr/009-concurrent-refresh-rotation-policy.md)
|
[ADR 006](../../../docs/adr/006-auth-session-policy.md)/[009](../../../docs/adr/009-concurrent-refresh-rotation-policy.md)
|
||||||
задают session semantics. Access хранится только в памяти frontend; refresh
|
задают session semantics. Access хранится только в памяти frontend; refresh
|
||||||
передаётся httpOnly cookie. Source code конфигурации cookie —
|
передаётся httpOnly cookie. Source code конфигурации cookie —
|
||||||
[AuthController](../../src/auth/auth.controller.ts); изменение flags/path требует
|
[AuthController](../../src/modules/auth/presentation/auth.controller.ts); изменение flags/path требует
|
||||||
проверки browser/HTTP поведения, не только TypeScript.
|
проверки browser/HTTP поведения, не только TypeScript.
|
||||||
|
|
||||||
Refresh rotation атомарна: один победитель, проигравший/superseded token получает
|
Refresh rotation атомарна: один победитель, проигравший/superseded token получает
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ zero-warning ESLint, application/test TypeScript, Jest и build.
|
|||||||
|
|
||||||
HTTP contract changes дополнительно проходят общий
|
HTTP contract changes дополнительно проходят общий
|
||||||
[contract workflow](../docs/development/runtime-openapi-verification.md).
|
[contract workflow](../docs/development/runtime-openapi-verification.md).
|
||||||
Общий e2e имеет известный environment blocker; применимость и маршрут проверки
|
Общий e2e запускается на отдельных временных DB; применимость и маршрут проверки
|
||||||
описаны в [backend testing](.ai/conventions/backend-testing.md).
|
описаны в [backend testing](.ai/conventions/backend-testing.md).
|
||||||
Generated Prisma client не редактируется вручную. Credentials, авторизация
|
Generated Prisma client не редактируется вручную. Credentials, авторизация
|
||||||
доступа к счетам и внешние интеграции остаются server-side.
|
доступа к счетам и внешние интеграции остаются server-side.
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ NestJS API WealthLedger. Backend владеет auth, SQLite-данными и s
|
|||||||
|
|
||||||
## Быстрый старт
|
## Быстрый старт
|
||||||
|
|
||||||
Требуется Node 22 (`.nvmrc`). Создайте `.env` из примера, замените placeholder
|
Требуется Node 24 (`.nvmrc`). Создайте `.env` из примера, замените placeholder
|
||||||
секреты и установите зависимости строго из lockfile:
|
секреты и установите зависимости строго из lockfile:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
nvm use --silent
|
nvm use --silent
|
||||||
npm ci
|
npm ci
|
||||||
|
npx prisma migrate deploy
|
||||||
npm run start:dev
|
npm run start:dev
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -31,9 +32,19 @@ npm run verify
|
|||||||
Он запускает zero-warning lint,
|
Он запускает zero-warning lint,
|
||||||
application/test typechecks, Jest и build. `npm run lint:fix` — отдельная
|
application/test typechecks, Jest и build. `npm run lint:fix` — отдельная
|
||||||
записывающая команда, `npm run test:cov` — диагностика без общего числового
|
записывающая команда, `npm run test:cov` — диагностика без общего числового
|
||||||
threshold. `npm run test:e2e` пока не является passing gate: Prisma schema
|
threshold. `npm run test:e2e` отдельно проверяет все HTTP suites на новых базах
|
||||||
engine останавливает migration до запуска Jest. Точный статус и trigger
|
и runtime OpenAPI с соседним frontend checkout. Для полной backend-проверки
|
||||||
пересмотра находятся в [remediation registry](../docs/development/audit-remediation.md).
|
выполните обе команды. Результаты — в
|
||||||
|
[remediation registry](../docs/development/audit-remediation.md).
|
||||||
|
|
||||||
|
Общий `tsconfig.json` включает `strict: true` и `noFallthroughCasesInSwitch`
|
||||||
|
для приложения, тестов и сборок. ESLint запрещает non-null assertions
|
||||||
|
(`value!`) и definite-assignment assertions (`field!: Type`).
|
||||||
|
Поля DTO, заполняемые вне конструктора, описываются через `declare`:
|
||||||
|
входные значения заполняет и проверяет Nest, ответные DTO описывают форму
|
||||||
|
возвращаемых объектов. `declare` не создаёт значение и не заменяет
|
||||||
|
runtime-валидацию. В обычном коде нужны инициализация или сужение типа
|
||||||
|
после проверки значения.
|
||||||
|
|
||||||
## Документация
|
## Документация
|
||||||
|
|
||||||
@@ -59,3 +70,66 @@ npm run test:openapi-contract
|
|||||||
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит
|
Разработка идёт напрямую по задаче пользователя. Каждый affected repo проходит
|
||||||
свой verify; при изменении wire contract дополнительно выполняется contract check.
|
свой verify; при изменении wire contract дополнительно выполняется contract check.
|
||||||
Обязательного OpenSpec/SDD lifecycle нет.
|
Обязательного OpenSpec/SDD lifecycle нет.
|
||||||
|
|
||||||
|
## Реальная SQLite и сохранность данных
|
||||||
|
|
||||||
|
После `nvm use --silent` запускайте `npm run test:sqlite` при изменении auth,
|
||||||
|
карточных операций или DB boundary, `npm run test:e2e` — для всех HTTP suites.
|
||||||
|
Обе команды используют один runner: отдельный каталог `wealthledger-e2e-*`
|
||||||
|
в системном temp на каждую suite, один `DATABASE_URL` для migrations и Jest.
|
||||||
|
Внешний `DATABASE_URL` заменяется временным; `.env` и пользовательские данные
|
||||||
|
не изменяются. Прямой Jest без runner отклоняется до обращения к базе.
|
||||||
|
При ошибке migration/Jest или SIGINT/SIGTERM runner останавливает дочерние
|
||||||
|
процессы, удаляет свой каталог и возвращает ненулевой exit code.
|
||||||
|
Нужен доступ к локальным HTTP-портам; sandbox может его запрещать.
|
||||||
|
|
||||||
|
`prisma.config.ts` удаляет унаследованный `RUST_LOG` только в процессе Prisma CLI:
|
||||||
|
на Prisma 7.9.1 уровни `warn`/`error` вызывают пустой `Schema engine error`
|
||||||
|
при fresh migration, без переменной миграция проходит. Постоянный
|
||||||
|
`RUST_LOG=info` и обновление зависимостей не нужны. Logging приложения
|
||||||
|
настраивается отдельно. История migrations применяется штатным `migrate deploy`.
|
||||||
|
|
||||||
|
Регрессия самого запуска: `node test/sqlite-regression.cjs`. Она выполняет
|
||||||
|
три последовательных и два параллельных полных e2e, проверяет уникальность DB,
|
||||||
|
сохранность вымышленного внешнего файла, отказ migration и SIGINT/SIGTERM cleanup.
|
||||||
|
Логи остаются в каталоге из вывода. Для одной suite:
|
||||||
|
`node test/sqlite.cjs app.e2e-spec.ts`.
|
||||||
|
|
||||||
|
| Риск | Проверка реальной DB |
|
||||||
|
| --- | --- |
|
||||||
|
| Чужой пользователь | `bank-cards.e2e-spec.ts`: owner каждой карты, категории, покупки и стороны перевода |
|
||||||
|
| Повтор и конкурентный update | Те же tests: fingerprint, tombstone, версии, один refund в пределах покупки, archive/write |
|
||||||
|
| Конкурентный refresh | `app.e2e-spec.ts`: оба запроса читают прежний hash до CAS; один 200, один 401, cookie победителя работает после replay |
|
||||||
|
| Rollback и деньги | Карточные tests: откат source lock, атомарный перевод, точные суммы выше 2^53 и границы signed64 |
|
||||||
|
| Migration, restart, backup/restore | `test:durability`: прежнее приложение, новая schema, история, откат приложения и восстановление backup |
|
||||||
|
|
||||||
|
Prisma в этих suites не заменяется mocks. В refresh тесте барьер задерживает
|
||||||
|
настоящую подпись JWT, чтобы оба запроса дошли до реальной конкурентной записи.
|
||||||
|
Unit tests с mocks отдельно проверяют orchestration и не доказывают DB concurrency.
|
||||||
|
|
||||||
|
При изменении schema/migrations или сохранения данных дополнительно выполните
|
||||||
|
`npm run test:durability -- /absolute/path/to/baseline`. Он не входит в lint/verify.
|
||||||
|
Baseline — отдельная сборка до проверяемых миграций с неизменённым префиксом
|
||||||
|
migration history. Для текущей карточной схемы подходит revision
|
||||||
|
`8ec172f48eefa2237dc0c16919fbb2e726b39a65` (до добавления карт):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Из backend; экспорт не содержит .env или локальную базу.
|
||||||
|
baseline_dir=$(mktemp -d /tmp/wealthledger-baseline-XXXXXX)
|
||||||
|
git archive 8ec172f48eefa2237dc0c16919fbb2e726b39a65 | tar -x -C "$baseline_dir"
|
||||||
|
(
|
||||||
|
cd "$baseline_dir"
|
||||||
|
nvm use --silent
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
)
|
||||||
|
nvm use --silent
|
||||||
|
npm run build
|
||||||
|
npm run test:durability -- "$baseline_dir"
|
||||||
|
```
|
||||||
|
|
||||||
|
Не подменяйте baseline текущей сборкой: runner отвергает тот же путь,
|
||||||
|
отсутствующую сборку и неподходящую migration history. Для следующей schema
|
||||||
|
выберите совместимую предыдущую revision и проверьте её API-сценарии runner.
|
||||||
|
Durability оставляет временные DB, логи и `result.json` по пути из вывода для
|
||||||
|
диагностики; он не откатывает schema пользовательской базы.
|
||||||
|
|||||||
+52
-1
@@ -26,10 +26,61 @@ export default tseslint.config(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
rules: {
|
rules: {
|
||||||
|
'no-magic-numbers': 'off',
|
||||||
|
'@typescript-eslint/no-magic-numbers': [
|
||||||
|
'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,
|
||||||
|
ignoreDefaultValues: true,
|
||||||
|
ignoreEnums: true,
|
||||||
|
ignoreNumericLiteralTypes: true,
|
||||||
|
ignoreReadonlyClassProperties: true,
|
||||||
|
ignoreTypeIndexes: true,
|
||||||
|
enforceConst: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-non-null-assertion': 'error',
|
||||||
|
'no-restricted-syntax': [
|
||||||
|
'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.',
|
||||||
|
},
|
||||||
|
],
|
||||||
'@typescript-eslint/no-floating-promises': 'warn',
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.spec.ts', 'test/**/*.ts'],
|
||||||
|
rules: { '@typescript-eslint/no-magic-numbers': 'off' },
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"deleteOutDir": true,
|
"deleteOutDir": true,
|
||||||
"assets": [
|
"assets": [
|
||||||
{ "include": "tbank/proto/contracts/**/*.proto", "watchAssets": true }
|
{ "include": "integrations/tbank/proto/contracts/**/*.proto", "watchAssets": true }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+405
-9
@@ -44,7 +44,7 @@
|
|||||||
"@types/cookie-parser": "^1.4.10",
|
"@types/cookie-parser": "^1.4.10",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^22.10.7",
|
"@types/node": "^24.13.3",
|
||||||
"@types/passport-jwt": "^4.0.1",
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/supertest": "^6.0.2",
|
"@types/supertest": "^6.0.2",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
@@ -64,7 +64,7 @@
|
|||||||
"typescript-eslint": "^8.20.0"
|
"typescript-eslint": "^8.20.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "22.x"
|
"node": "24.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@angular-devkit/core": {
|
"node_modules/@angular-devkit/core": {
|
||||||
@@ -812,6 +812,40 @@
|
|||||||
"@electric-sql/pglite": "0.4.3"
|
"@electric-sql/pglite": "0.4.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@emnapi/core": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||||
|
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/wasi-threads": "1.2.1",
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@emnapi/runtime": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
|
||||||
|
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@emnapi/wasi-threads": {
|
||||||
|
"version": "1.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
|
||||||
|
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@eslint-community/eslint-utils": {
|
"node_modules/@eslint-community/eslint-utils": {
|
||||||
"version": "4.10.1",
|
"version": "4.10.1",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
||||||
@@ -2135,6 +2169,28 @@
|
|||||||
"integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==",
|
"integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@napi-rs/wasm-runtime": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@tybys/wasm-util": "^0.10.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4",
|
||||||
|
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@nestjs/cli": {
|
"node_modules/@nestjs/cli": {
|
||||||
"version": "11.0.24",
|
"version": "11.0.24",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.24.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.24.tgz",
|
||||||
@@ -3251,6 +3307,17 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@tybys/wasm-util": {
|
||||||
|
"version": "0.10.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
|
||||||
|
"integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/babel__core": {
|
"node_modules/@types/babel__core": {
|
||||||
"version": "7.20.5",
|
"version": "7.20.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||||
@@ -3577,12 +3644,12 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "22.20.1",
|
"version": "24.13.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
|
||||||
"integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
|
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~6.21.0"
|
"undici-types": "~7.18.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@types/passport": {
|
"node_modules/@types/passport": {
|
||||||
@@ -4005,6 +4072,34 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-android-arm-eabi": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-g5T90pqg1bo/7mytQx6F4iBNC0Wsh9cu+z9veDbFjc7HjpesJFWD7QMS0NGStXM075+7dJPPVvBbpZlnrdpi/w==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-android-arm64": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-YGCRZv/9GLhwmz6mYDeTsm/92BAyR28l6c2ReweVW5pWgfsitWLY8upvfRlGdoyD8HjeTHSYJWyZGD4KJA/nFQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
]
|
||||||
|
},
|
||||||
"node_modules/@unrs/resolver-binding-darwin-arm64": {
|
"node_modules/@unrs/resolver-binding-darwin-arm64": {
|
||||||
"version": "1.12.2",
|
"version": "1.12.2",
|
||||||
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.12.2.tgz",
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.12.2.tgz",
|
||||||
@@ -4019,6 +4114,307 @@
|
|||||||
"darwin"
|
"darwin"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-darwin-x64": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-f7rPLi/T1HVKZu/u6t87lroib16n8vrSzcyxI7lg4BGO9UF26KhQL44sd9eOUgrTYhvRXtWOIZT5PejdPyJfUA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-freebsd-x64": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-BpcOjWCJub6nRZUS2zA20pmLvjtqAtGejETaIyRLiZiQf++cbrjltLA5NN/xaXfqeOBOSlMFbemIl5/S5tljmg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-vZTDvdSISZjJx66OzJqtsOhzifbqRjbmI1Mnu49fQDwog5GtDI4QidRiEAYbZCRj9C8YZEW+3ZjqsyS9GR4k2A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-arm-musleabihf": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-BiPI+IrIlwcW4nLLMM21+B1dFPzd55yAVgVGrdgDjNef+ch03GdxrcyaIz8X9SsQirh/kCQ7mviyWlMxdh2D7g==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-arm64-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-arm64-musl": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-loong64-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-gnu/-/resolver-binding-linux-loong64-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-loong64-musl": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-musl/-/resolver-binding-linux-loong64-musl-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-ppc64-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-riscv64-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-riscv64-musl": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-s390x-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-x64-gnu": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-linux-x64-musl": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-openharmony-arm64": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-openharmony-arm64/-/resolver-binding-openharmony-arm64-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openharmony"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-wasm32-wasi": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-tYFDIkMxSflfEc/h92ZWNsZlHSwgimbNHSO3PL2JWQHfCuC2q316jMyYU9TIWZsFK2bQwyK5VAdYgn8ygPj69A==",
|
||||||
|
"cpu": [
|
||||||
|
"wasm32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/core": "1.10.0",
|
||||||
|
"@emnapi/runtime": "1.10.0",
|
||||||
|
"@napi-rs/wasm-runtime": "^1.1.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-win32-arm64-msvc": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-qzNyg3xL0VPQmCaUh+N5jSitce6k+uCBfMDesWRnlULOZaqUkaJ0ybdT+UqlAWJoQjuqfIU/0Ptx9bteN4D82g==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-win32-ia32-msvc": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-WD9sY00OfpHVGfsnHZoA8jVT+esS/Bg8z8jzxp5BnDCjjwsuKsPQrzswwpFy4J1AUJbXPRfkpcX0mXrzeXW79g==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/@unrs/resolver-binding-win32-x64-msvc": {
|
||||||
|
"version": "1.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.12.2.tgz",
|
||||||
|
"integrity": "sha512-nAB74NfSNKknqQ1RrYj6uz8FcXEomu/MATJZxh/x+BArzN2U3JbOYC0APYzUIGhVY3m5hRxA8VPNdPBoG8txlA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
]
|
||||||
|
},
|
||||||
"node_modules/@visx/curve": {
|
"node_modules/@visx/curve": {
|
||||||
"version": "4.0.1-alpha.0",
|
"version": "4.0.1-alpha.0",
|
||||||
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz",
|
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.1-alpha.0.tgz",
|
||||||
@@ -12059,9 +12455,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/undici-types": {
|
"node_modules/undici-types": {
|
||||||
"version": "6.21.0",
|
"version": "7.18.2",
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
|
||||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/universalify": {
|
"node_modules/universalify": {
|
||||||
|
|||||||
+15
-4
@@ -6,7 +6,7 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "22.x"
|
"node": "24.x"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "prisma generate && nest build",
|
"build": "prisma generate && nest build",
|
||||||
@@ -24,8 +24,10 @@
|
|||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
"test:cov": "jest --coverage",
|
"test:cov": "jest --coverage",
|
||||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
"test:e2e": "DATABASE_URL=file:/tmp/wealth-ledger-e2e.db prisma migrate deploy && NODE_ENV=development NODE_OPTIONS=--experimental-vm-modules jest --config ./test/jest-e2e.json",
|
"test:e2e": "node test/sqlite.cjs --all",
|
||||||
"test:openapi-contract": "NODE_OPTIONS=--experimental-vm-modules jest --config ./test/jest-e2e.json --runInBand openapi-contract.e2e-spec.ts",
|
"test:sqlite": "node test/sqlite.cjs",
|
||||||
|
"test:durability": "node test/bank-cards-durability.cjs",
|
||||||
|
"test:openapi-contract": "node test/sqlite.cjs openapi-contract.e2e-spec.ts",
|
||||||
"verify": "npm run lint && npm run typecheck:app && npm run typecheck:test && npm test -- --runInBand && npm run build"
|
"verify": "npm run lint && npm run typecheck:app && npm run typecheck:test && npm test -- --runInBand && npm run build"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -64,7 +66,7 @@
|
|||||||
"@types/cookie-parser": "^1.4.10",
|
"@types/cookie-parser": "^1.4.10",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^22.10.7",
|
"@types/node": "^24.13.3",
|
||||||
"@types/passport-jwt": "^4.0.1",
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/supertest": "^6.0.2",
|
"@types/supertest": "^6.0.2",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
@@ -104,5 +106,14 @@
|
|||||||
],
|
],
|
||||||
"coverageDirectory": "../coverage",
|
"coverageDirectory": "../coverage",
|
||||||
"testEnvironment": "node"
|
"testEnvironment": "node"
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"@prisma/engines@7.9.1": true,
|
||||||
|
"prisma@7.9.1": true,
|
||||||
|
"bcrypt@6.0.0": true,
|
||||||
|
"better-sqlite3@12.11.1": true,
|
||||||
|
"fsevents@2.3.3": true,
|
||||||
|
"protobufjs@7.6.5": true,
|
||||||
|
"unrs-resolver@1.12.2": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import 'dotenv/config';
|
import 'dotenv/config';
|
||||||
import { defineConfig } from 'prisma/config';
|
import { defineConfig } from 'prisma/config';
|
||||||
|
|
||||||
|
// Prisma 7.9.1 fresh SQLite migration fails with inherited RUST_LOG=warn/error.
|
||||||
|
// Use the engine default; application logging is configured separately.
|
||||||
|
delete process.env.RUST_LOG;
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
schema: 'prisma/schema.prisma',
|
schema: 'prisma/schema.prisma',
|
||||||
datasource: {
|
datasource: {
|
||||||
|
|||||||
+16
-4
@@ -1,13 +1,19 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { LoggerModule } from 'nestjs-pino';
|
import { LoggerModule } from 'nestjs-pino';
|
||||||
import { BankCardsModule } from './bank-cards/bank-cards.module';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { AuthModule } from './auth/auth.module';
|
|
||||||
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 { BankCardsModule } from './modules/banking/bank-cards/bank-cards.module';
|
||||||
|
import { BrokerageAccountsModule } from './modules/investments/brokerage-accounts/brokerage-accounts.module';
|
||||||
|
import { IncomeModule } from './modules/investments/income/income.module';
|
||||||
|
import { InstrumentsModule } from './modules/investments/instruments/instruments.module';
|
||||||
|
import { OperationsModule } from './modules/investments/operations/operations.module';
|
||||||
|
import { PortfolioModule } from './modules/investments/portfolio/portfolio.module';
|
||||||
|
import { TbankConnectionModule } from './modules/investments/tbank-connection/tbank-connection.module';
|
||||||
|
import { UpcomingEventsModule } from './modules/investments/upcoming-events/upcoming-events.module';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
import { TbankConnectionModule } from './tbank/tbank-connection.module';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -51,6 +57,12 @@ import { TbankConnectionModule } from './tbank/tbank-connection.module';
|
|||||||
PrismaModule,
|
PrismaModule,
|
||||||
AuthModule,
|
AuthModule,
|
||||||
BankCardsModule,
|
BankCardsModule,
|
||||||
|
BrokerageAccountsModule,
|
||||||
|
PortfolioModule,
|
||||||
|
OperationsModule,
|
||||||
|
IncomeModule,
|
||||||
|
UpcomingEventsModule,
|
||||||
|
InstrumentsModule,
|
||||||
TbankConnectionModule,
|
TbankConnectionModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { BankCardsController } from './bank-cards.controller';
|
|
||||||
import { BankCardsService } from './bank-cards.service';
|
|
||||||
@Module({ controllers: [BankCardsController], providers: [BankCardsService] })
|
|
||||||
export class BankCardsModule {}
|
|
||||||
@@ -1,708 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
GoneException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { createHash, randomUUID } from 'node:crypto';
|
|
||||||
import {
|
|
||||||
Prisma,
|
|
||||||
BankCard,
|
|
||||||
BankCardOperation,
|
|
||||||
} from '../../generated/prisma/client';
|
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
|
||||||
import { parseRubMoney, rubMoney } from '../common/rub-money';
|
|
||||||
import {
|
|
||||||
bankBalance,
|
|
||||||
bankSummary,
|
|
||||||
isCalendarDate,
|
|
||||||
moscowToday,
|
|
||||||
} from './bank-card.calculations';
|
|
||||||
import {
|
|
||||||
bankPaymentSystems,
|
|
||||||
BankCardDto,
|
|
||||||
BankOperationDto,
|
|
||||||
BankOperationsQueryDto,
|
|
||||||
BankPageQueryDto,
|
|
||||||
BankPeriodQueryDto,
|
|
||||||
BankSummaryQueryDto,
|
|
||||||
CreateBankCardDto,
|
|
||||||
CreateBankOperationDto,
|
|
||||||
UpdateBankCardDto,
|
|
||||||
UpdateBankOperationDto,
|
|
||||||
} from './bank-card.dto';
|
|
||||||
|
|
||||||
type Tx = Prisma.TransactionClient;
|
|
||||||
const seeds = [
|
|
||||||
'Продукты',
|
|
||||||
'Кафе',
|
|
||||||
'Такси',
|
|
||||||
'Транспорт',
|
|
||||||
'Жильё',
|
|
||||||
'Здоровье',
|
|
||||||
'Покупки',
|
|
||||||
'Развлечения',
|
|
||||||
'Другое',
|
|
||||||
];
|
|
||||||
const fail = (code = 'BANK_INVALID_INPUT'): never => {
|
|
||||||
throw new BadRequestException({ code });
|
|
||||||
};
|
|
||||||
function periodBounds(query: BankPeriodQueryDto) {
|
|
||||||
if (query.month && !query.from && !query.to) {
|
|
||||||
const from = `${query.month}-01`;
|
|
||||||
if (!isCalendarDate(from)) return fail();
|
|
||||||
const end = new Date(`${from}T00:00:00Z`);
|
|
||||||
end.setUTCMonth(end.getUTCMonth() + 1, 0);
|
|
||||||
return { from, to: end.toISOString().slice(0, 10) };
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
query.month ||
|
|
||||||
!query.from ||
|
|
||||||
!query.to ||
|
|
||||||
!isCalendarDate(query.from) ||
|
|
||||||
!isCalendarDate(query.to) ||
|
|
||||||
query.from > query.to
|
|
||||||
)
|
|
||||||
return fail();
|
|
||||||
return { from: query.from, to: query.to };
|
|
||||||
}
|
|
||||||
const conflict = (code = 'BANK_VERSION_CONFLICT'): never => {
|
|
||||||
throw new ConflictException({ code });
|
|
||||||
};
|
|
||||||
const missing = (): never => {
|
|
||||||
throw new NotFoundException({ code: 'BANK_NOT_FOUND' });
|
|
||||||
};
|
|
||||||
const fingerprint = (value: unknown) =>
|
|
||||||
createHash('sha256')
|
|
||||||
.update(
|
|
||||||
JSON.stringify(value, (_key, item: unknown) =>
|
|
||||||
typeof item === 'bigint' ? item.toString() : item,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.digest('hex');
|
|
||||||
function amount(value: Parameters<typeof parseRubMoney>[0], positive = false) {
|
|
||||||
try {
|
|
||||||
return parseRubMoney(value, positive);
|
|
||||||
} catch {
|
|
||||||
return fail('BANK_INVALID_MONEY');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function calendar(value: string) {
|
|
||||||
if (!isCalendarDate(value)) fail('BANK_INVALID_DATE');
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function currentDate(value: string) {
|
|
||||||
calendar(value);
|
|
||||||
if (value > moscowToday()) fail('BANK_INVALID_DATE');
|
|
||||||
}
|
|
||||||
function name(value: string, max: number) {
|
|
||||||
if (typeof value !== 'string' || !value.trim() || value.trim().length > max)
|
|
||||||
fail();
|
|
||||||
return value.trim();
|
|
||||||
}
|
|
||||||
function cardInput(dto: CreateBankCardDto) {
|
|
||||||
const bankName = dto.bankName?.trim() || null;
|
|
||||||
if (bankName && bankName.length > 100) fail();
|
|
||||||
if (dto.lastFour != null && !/^\d{4}$/.test(dto.lastFour)) fail();
|
|
||||||
if (
|
|
||||||
dto.paymentSystem != null &&
|
|
||||||
!bankPaymentSystems.some((system) => system === dto.paymentSystem)
|
|
||||||
)
|
|
||||||
fail();
|
|
||||||
return {
|
|
||||||
...(dto.paymentSystem == null ? {} : { paymentSystem: dto.paymentSystem }),
|
|
||||||
name: name(dto.name, 100),
|
|
||||||
bankName,
|
|
||||||
lastFour: dto.lastFour || null,
|
|
||||||
openingBalanceKopecks: amount(dto.openingBalance),
|
|
||||||
openingDate: calendar(dto.openingDate),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function operationInput(dto: CreateBankOperationDto) {
|
|
||||||
if (
|
|
||||||
dto.description != null &&
|
|
||||||
(typeof dto.description !== 'string' || dto.description.length > 500)
|
|
||||||
)
|
|
||||||
fail();
|
|
||||||
return {
|
|
||||||
kind: dto.kind,
|
|
||||||
cardId: dto.cardId,
|
|
||||||
targetCardId: dto.targetCardId ?? null,
|
|
||||||
categoryId: dto.categoryId ?? null,
|
|
||||||
originalExpenseId: dto.originalExpenseId ?? null,
|
|
||||||
amountKopecks: amount(dto.amount, true),
|
|
||||||
date: calendar(dto.date),
|
|
||||||
description: dto.description || null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BankCardsService {
|
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
|
||||||
private async write<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
|
||||||
for (let attempt = 0; ; attempt++) {
|
|
||||||
try {
|
|
||||||
return await this.prisma.$transaction(run, {
|
|
||||||
maxWait: 10000,
|
|
||||||
timeout: 15000,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
const code =
|
|
||||||
error instanceof Prisma.PrismaClientKnownRequestError
|
|
||||||
? error.code
|
|
||||||
: '';
|
|
||||||
const busy =
|
|
||||||
code === 'P2034' ||
|
|
||||||
code === 'P2028' ||
|
|
||||||
(error instanceof Error &&
|
|
||||||
/SQLITE_BUSY|database is locked/.test(error.message));
|
|
||||||
if ((busy || code === 'P2002') && attempt < 2) continue;
|
|
||||||
if (busy) conflict('BANK_WRITE_CONFLICT');
|
|
||||||
if (code === 'P2002') conflict('BANK_DUPLICATE_CATEGORY');
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private async card(tx: Tx, userId: string, id: string, active = false) {
|
|
||||||
const card = await tx.bankCard.findFirst({ where: { id, userId } });
|
|
||||||
if (!card) return missing();
|
|
||||||
if (active && card.archivedAt) conflict('BANK_CARD_ARCHIVED');
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
private async operation(tx: Tx, userId: string, id: string) {
|
|
||||||
const row = await tx.bankCardOperation.findFirst({ where: { id, userId } });
|
|
||||||
if (!row) return missing();
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
private async seed(tx: Tx, userId: string) {
|
|
||||||
for (const [index, label] of seeds.entries()) {
|
|
||||||
const seedKey = index === 8 ? 'other' : String(index);
|
|
||||||
if (
|
|
||||||
!(await tx.expenseCategory.findUnique({
|
|
||||||
where: { userId_seedKey: { userId, seedKey } },
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
await tx.expenseCategory.create({
|
|
||||||
data: {
|
|
||||||
id: randomUUID(),
|
|
||||||
userId,
|
|
||||||
seedKey,
|
|
||||||
name: label,
|
|
||||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private async cardView(tx: Tx, card: BankCard): Promise<BankCardDto> {
|
|
||||||
const rows = await tx.bankCardOperation.findMany({
|
|
||||||
where: {
|
|
||||||
userId: card.userId,
|
|
||||||
deletedAt: null,
|
|
||||||
OR: [{ cardId: card.id }, { targetCardId: card.id }],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
id: card.id,
|
|
||||||
name: card.name,
|
|
||||||
bankName: card.bankName,
|
|
||||||
lastFour: card.lastFour,
|
|
||||||
paymentSystem: card.paymentSystem,
|
|
||||||
openingDate: card.openingDate,
|
|
||||||
openingBalance: rubMoney(card.openingBalanceKopecks),
|
|
||||||
balance: rubMoney(bankBalance(card.id, card.openingBalanceKopecks, rows)),
|
|
||||||
version: card.version,
|
|
||||||
archivedAt: card.archivedAt?.toISOString() ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
private async operationView(
|
|
||||||
tx: Tx,
|
|
||||||
row: BankCardOperation,
|
|
||||||
): Promise<BankOperationDto> {
|
|
||||||
const card = await this.card(tx, row.userId, row.cardId);
|
|
||||||
const target = row.targetCardId
|
|
||||||
? await this.card(tx, row.userId, row.targetCardId)
|
|
||||||
: null;
|
|
||||||
const source = row.originalExpenseId
|
|
||||||
? await this.operation(tx, row.userId, row.originalExpenseId)
|
|
||||||
: null;
|
|
||||||
const categoryId = source?.categoryId ?? row.categoryId;
|
|
||||||
const category = categoryId
|
|
||||||
? await tx.expenseCategory.findFirst({
|
|
||||||
where: { id: categoryId, userId: row.userId },
|
|
||||||
})
|
|
||||||
: null;
|
|
||||||
const refunds =
|
|
||||||
row.kind === 'expense' || source
|
|
||||||
? await tx.bankCardOperation.findMany({
|
|
||||||
where: {
|
|
||||||
userId: row.userId,
|
|
||||||
originalExpenseId: source?.id ?? row.id,
|
|
||||||
deletedAt: null,
|
|
||||||
...(source ? { id: { not: row.id } } : {}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
return {
|
|
||||||
id: row.id,
|
|
||||||
kind: row.kind as BankOperationDto['kind'],
|
|
||||||
cardId: row.cardId,
|
|
||||||
cardName: card.name,
|
|
||||||
targetCardId: row.targetCardId,
|
|
||||||
targetCardName: target?.name ?? null,
|
|
||||||
categoryId,
|
|
||||||
categoryName: category?.name ?? null,
|
|
||||||
originalExpenseId: row.originalExpenseId,
|
|
||||||
amount: rubMoney(row.amountKopecks),
|
|
||||||
availableRefund:
|
|
||||||
row.kind === 'expense' || source
|
|
||||||
? rubMoney(
|
|
||||||
(source?.amountKopecks ?? row.amountKopecks) -
|
|
||||||
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n),
|
|
||||||
)
|
|
||||||
: null,
|
|
||||||
date: row.date,
|
|
||||||
description: row.description,
|
|
||||||
version: row.version,
|
|
||||||
createdAt: row.createdAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
list(userId: string, includeArchived = false) {
|
|
||||||
return this.prisma.$transaction(async (tx) =>
|
|
||||||
Promise.all(
|
|
||||||
(
|
|
||||||
await tx.bankCard.findMany({
|
|
||||||
where: { userId, ...(includeArchived ? {} : { archivedAt: null }) },
|
|
||||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
|
||||||
})
|
|
||||||
).map((card) => this.cardView(tx, card)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
get(userId: string, id: string) {
|
|
||||||
return this.prisma.$transaction(async (tx) =>
|
|
||||||
this.cardView(tx, await this.card(tx, userId, id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
createCard(userId: string, dto: CreateBankCardDto) {
|
|
||||||
const input = cardInput(dto),
|
|
||||||
hash = fingerprint(input);
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const existing = await tx.bankCard.findUnique({ where: { id: dto.id } });
|
|
||||||
if (existing) {
|
|
||||||
if (existing.userId !== userId) missing();
|
|
||||||
if (existing.createFingerprint !== hash)
|
|
||||||
conflict('BANK_INTENT_CONFLICT');
|
|
||||||
return this.cardView(tx, existing);
|
|
||||||
}
|
|
||||||
currentDate(input.openingDate);
|
|
||||||
await this.seed(tx, userId);
|
|
||||||
return this.cardView(
|
|
||||||
tx,
|
|
||||||
await tx.bankCard.create({
|
|
||||||
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
updateCard(userId: string, id: string, dto: UpdateBankCardDto) {
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const previous = await this.card(tx, userId, id);
|
|
||||||
if (previous.version !== dto.version) conflict();
|
|
||||||
const input = cardInput({
|
|
||||||
id,
|
|
||||||
name: dto.name ?? previous.name,
|
|
||||||
bankName:
|
|
||||||
dto.bankName === undefined
|
|
||||||
? (previous.bankName ?? undefined)
|
|
||||||
: (dto.bankName ?? undefined),
|
|
||||||
lastFour:
|
|
||||||
dto.lastFour === undefined
|
|
||||||
? (previous.lastFour ?? undefined)
|
|
||||||
: (dto.lastFour ?? undefined),
|
|
||||||
paymentSystem:
|
|
||||||
dto.paymentSystem === undefined
|
|
||||||
? previous.paymentSystem
|
|
||||||
: dto.paymentSystem,
|
|
||||||
openingBalance:
|
|
||||||
dto.openingBalance ?? rubMoney(previous.openingBalanceKopecks),
|
|
||||||
openingDate: dto.openingDate ?? previous.openingDate,
|
|
||||||
});
|
|
||||||
const financial =
|
|
||||||
input.openingBalanceKopecks !== previous.openingBalanceKopecks ||
|
|
||||||
input.openingDate !== previous.openingDate;
|
|
||||||
if (financial && previous.archivedAt) conflict('BANK_CARD_ARCHIVED');
|
|
||||||
currentDate(input.openingDate);
|
|
||||||
if (
|
|
||||||
await tx.bankCardOperation.findFirst({
|
|
||||||
where: {
|
|
||||||
userId,
|
|
||||||
deletedAt: null,
|
|
||||||
date: { lt: input.openingDate },
|
|
||||||
OR: [{ cardId: id }, { targetCardId: id }],
|
|
||||||
},
|
|
||||||
})
|
|
||||||
)
|
|
||||||
fail('BANK_OPENING_DATE_CONFLICT');
|
|
||||||
const changed = await tx.bankCard.updateMany({
|
|
||||||
where: { id, userId, version: dto.version },
|
|
||||||
data: {
|
|
||||||
...input,
|
|
||||||
paymentSystem: input.paymentSystem ?? null,
|
|
||||||
version: { increment: 1 },
|
|
||||||
...(dto.archived === undefined
|
|
||||||
? {}
|
|
||||||
: {
|
|
||||||
archivedAt: dto.archived
|
|
||||||
? (previous.archivedAt ?? new Date())
|
|
||||||
: null,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (changed.count !== 1) conflict();
|
|
||||||
return this.cardView(tx, await this.card(tx, userId, id));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async categories(userId: string) {
|
|
||||||
return (
|
|
||||||
await this.prisma.expenseCategory.findMany({
|
|
||||||
where: { userId },
|
|
||||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
|
||||||
})
|
|
||||||
).map(({ id, name, seedKey, version }) => ({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
isDefault: seedKey === 'other',
|
|
||||||
version,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
createCategory(userId: string, value: string) {
|
|
||||||
const label = name(value, 80);
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
await this.seed(tx, userId);
|
|
||||||
const row = await tx.expenseCategory.create({
|
|
||||||
data: {
|
|
||||||
id: randomUUID(),
|
|
||||||
userId,
|
|
||||||
name: label,
|
|
||||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
id: row.id,
|
|
||||||
name: row.name,
|
|
||||||
isDefault: false,
|
|
||||||
version: row.version,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
updateCategory(userId: string, id: string, value: string, version: number) {
|
|
||||||
const label = name(value, 80);
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const row = await tx.expenseCategory.findFirst({ where: { id, userId } });
|
|
||||||
if (!row) missing();
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await tx.expenseCategory.updateMany({
|
|
||||||
where: { id, userId, version },
|
|
||||||
data: {
|
|
||||||
name: label,
|
|
||||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
|
||||||
version: { increment: 1 },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
).count !== 1
|
|
||||||
)
|
|
||||||
conflict();
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name: label,
|
|
||||||
isDefault: row!.seedKey === 'other',
|
|
||||||
version: version + 1,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
private async validateOperation(
|
|
||||||
tx: Tx,
|
|
||||||
userId: string,
|
|
||||||
input: ReturnType<typeof operationInput>,
|
|
||||||
old?: BankCardOperation,
|
|
||||||
) {
|
|
||||||
const cards = new Set(
|
|
||||||
[input.cardId, input.targetCardId, old?.cardId, old?.targetCardId].filter(
|
|
||||||
(id): id is string => Boolean(id),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
currentDate(input.date);
|
|
||||||
for (const id of cards) {
|
|
||||||
const card = await this.card(tx, userId, id, true);
|
|
||||||
if (
|
|
||||||
(id === input.cardId || id === input.targetCardId) &&
|
|
||||||
input.date < card.openingDate
|
|
||||||
)
|
|
||||||
fail('BANK_INVALID_DATE');
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
old &&
|
|
||||||
(old.kind !== input.kind ||
|
|
||||||
old.originalExpenseId !== input.originalExpenseId)
|
|
||||||
)
|
|
||||||
fail('BANK_IMMUTABLE_OPERATION');
|
|
||||||
if (input.kind === 'transfer') {
|
|
||||||
if (
|
|
||||||
!input.targetCardId ||
|
|
||||||
input.targetCardId === input.cardId ||
|
|
||||||
input.categoryId ||
|
|
||||||
input.originalExpenseId
|
|
||||||
)
|
|
||||||
fail();
|
|
||||||
} else if (input.targetCardId) fail();
|
|
||||||
if (input.kind === 'expense') {
|
|
||||||
if (input.originalExpenseId) fail();
|
|
||||||
if (!input.categoryId) {
|
|
||||||
const category = await tx.expenseCategory.findUnique({
|
|
||||||
where: { userId_seedKey: { userId, seedKey: 'other' } },
|
|
||||||
});
|
|
||||||
if (!category) missing();
|
|
||||||
input.categoryId = category!.id;
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
!(await tx.expenseCategory.findFirst({
|
|
||||||
where: { userId, id: input.categoryId },
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
missing();
|
|
||||||
} else if (input.categoryId) fail();
|
|
||||||
if (input.kind !== 'refund' && input.originalExpenseId) fail();
|
|
||||||
if (input.kind === 'refund') {
|
|
||||||
if (!input.originalExpenseId) fail();
|
|
||||||
const source = await this.operation(tx, userId, input.originalExpenseId!);
|
|
||||||
if (
|
|
||||||
source.deletedAt ||
|
|
||||||
source.kind !== 'expense' ||
|
|
||||||
source.cardId !== input.cardId
|
|
||||||
)
|
|
||||||
fail('BANK_INVALID_REFUND');
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await tx.bankCardOperation.updateMany({
|
|
||||||
where: {
|
|
||||||
id: source.id,
|
|
||||||
userId,
|
|
||||||
version: source.version,
|
|
||||||
deletedAt: null,
|
|
||||||
},
|
|
||||||
data: { version: { increment: 1 } },
|
|
||||||
})
|
|
||||||
).count !== 1
|
|
||||||
)
|
|
||||||
conflict();
|
|
||||||
const refunds = await tx.bankCardOperation.findMany({
|
|
||||||
where: {
|
|
||||||
userId,
|
|
||||||
originalExpenseId: source.id,
|
|
||||||
deletedAt: null,
|
|
||||||
...(old ? { id: { not: old.id } } : {}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (input.date < source.date) fail('BANK_INVALID_DATE');
|
|
||||||
if (
|
|
||||||
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n) +
|
|
||||||
input.amountKopecks >
|
|
||||||
source.amountKopecks
|
|
||||||
)
|
|
||||||
conflict('BANK_REFUND_LIMIT');
|
|
||||||
}
|
|
||||||
if (old?.kind === 'expense') {
|
|
||||||
const refunds = await tx.bankCardOperation.findMany({
|
|
||||||
where: { userId, originalExpenseId: old.id, deletedAt: null },
|
|
||||||
});
|
|
||||||
if (
|
|
||||||
refunds.length &&
|
|
||||||
(input.cardId !== old.cardId ||
|
|
||||||
refunds.some((row) => row.date < input.date) ||
|
|
||||||
refunds.reduce((sum, row) => sum + row.amountKopecks, 0n) >
|
|
||||||
input.amountKopecks)
|
|
||||||
)
|
|
||||||
conflict('BANK_DEPENDENT_REFUNDS');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
createOperation(userId: string, dto: CreateBankOperationDto) {
|
|
||||||
const normalized = operationInput(dto),
|
|
||||||
hash = fingerprint(normalized);
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const existing = await tx.bankCardOperation.findUnique({
|
|
||||||
where: { id: dto.id },
|
|
||||||
});
|
|
||||||
if (existing) {
|
|
||||||
if (existing.userId !== userId) missing();
|
|
||||||
if (existing.createFingerprint !== hash)
|
|
||||||
conflict('BANK_INTENT_CONFLICT');
|
|
||||||
if (existing.deletedAt)
|
|
||||||
throw new GoneException({ code: 'BANK_OPERATION_DELETED' });
|
|
||||||
return this.operationView(tx, existing);
|
|
||||||
}
|
|
||||||
const input = { ...normalized };
|
|
||||||
await this.validateOperation(tx, userId, input);
|
|
||||||
return this.operationView(
|
|
||||||
tx,
|
|
||||||
await tx.bankCardOperation.create({
|
|
||||||
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
getOperation(userId: string, id: string) {
|
|
||||||
return this.prisma.$transaction(async (tx) => {
|
|
||||||
const row = await this.operation(tx, userId, id);
|
|
||||||
if (row.deletedAt) missing();
|
|
||||||
return this.operationView(tx, row);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
updateOperation(userId: string, id: string, dto: UpdateBankOperationDto) {
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const old = await this.operation(tx, userId, id);
|
|
||||||
if (old.deletedAt) missing();
|
|
||||||
if (old.version !== dto.version) conflict();
|
|
||||||
const input = operationInput({
|
|
||||||
id,
|
|
||||||
kind: dto.kind ?? (old.kind as CreateBankOperationDto['kind']),
|
|
||||||
cardId: dto.cardId ?? old.cardId,
|
|
||||||
targetCardId: dto.targetCardId ?? old.targetCardId ?? undefined,
|
|
||||||
categoryId: dto.categoryId ?? old.categoryId ?? undefined,
|
|
||||||
originalExpenseId:
|
|
||||||
dto.originalExpenseId ?? old.originalExpenseId ?? undefined,
|
|
||||||
amount: dto.amount ?? rubMoney(old.amountKopecks),
|
|
||||||
date: dto.date ?? old.date,
|
|
||||||
description: dto.description ?? old.description ?? undefined,
|
|
||||||
});
|
|
||||||
await this.validateOperation(tx, userId, input, old);
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await tx.bankCardOperation.updateMany({
|
|
||||||
where: { id, userId, version: dto.version, deletedAt: null },
|
|
||||||
data: { ...input, version: { increment: 1 } },
|
|
||||||
})
|
|
||||||
).count !== 1
|
|
||||||
)
|
|
||||||
conflict();
|
|
||||||
return this.operationView(tx, await this.operation(tx, userId, id));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
deleteOperation(userId: string, id: string, version: number) {
|
|
||||||
return this.write(async (tx) => {
|
|
||||||
const row = await this.operation(tx, userId, id);
|
|
||||||
if (row.deletedAt) return;
|
|
||||||
if (row.version !== version) conflict();
|
|
||||||
await this.card(tx, userId, row.cardId, true);
|
|
||||||
if (row.targetCardId) await this.card(tx, userId, row.targetCardId, true);
|
|
||||||
if (
|
|
||||||
row.kind === 'expense' &&
|
|
||||||
(await tx.bankCardOperation.findFirst({
|
|
||||||
where: { userId, originalExpenseId: id, deletedAt: null },
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
conflict('BANK_DEPENDENT_REFUNDS');
|
|
||||||
if (row.originalExpenseId) {
|
|
||||||
const source = await this.operation(tx, userId, row.originalExpenseId);
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await tx.bankCardOperation.updateMany({
|
|
||||||
where: { id: source.id, userId, version: source.version },
|
|
||||||
data: { version: { increment: 1 } },
|
|
||||||
})
|
|
||||||
).count !== 1
|
|
||||||
)
|
|
||||||
conflict();
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
(
|
|
||||||
await tx.bankCardOperation.updateMany({
|
|
||||||
where: { id, userId, version, deletedAt: null },
|
|
||||||
data: { deletedAt: new Date(), version: { increment: 1 } },
|
|
||||||
})
|
|
||||||
).count !== 1
|
|
||||||
)
|
|
||||||
conflict();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
history(
|
|
||||||
userId: string,
|
|
||||||
id: string,
|
|
||||||
query: BankOperationsQueryDto | BankPageQueryDto,
|
|
||||||
expenses = false,
|
|
||||||
) {
|
|
||||||
const period = expenses
|
|
||||||
? undefined
|
|
||||||
: periodBounds(query as BankOperationsQueryDto);
|
|
||||||
return this.prisma.$transaction(async (tx) => {
|
|
||||||
await this.card(tx, userId, id);
|
|
||||||
const page = query.page ?? 1,
|
|
||||||
limit = query.limit ?? 50;
|
|
||||||
const where: Prisma.BankCardOperationWhereInput = {
|
|
||||||
userId,
|
|
||||||
deletedAt: null,
|
|
||||||
OR: [{ cardId: id }, { targetCardId: id }],
|
|
||||||
...(expenses
|
|
||||||
? { kind: 'expense' }
|
|
||||||
: { date: { gte: period!.from, lte: period!.to } }),
|
|
||||||
};
|
|
||||||
const total = await tx.bankCardOperation.count({ where });
|
|
||||||
const rows = await tx.bankCardOperation.findMany({
|
|
||||||
where,
|
|
||||||
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
|
||||||
skip: (page - 1) * limit,
|
|
||||||
take: limit,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
items: await Promise.all(
|
|
||||||
rows.map((row) => this.operationView(tx, row)),
|
|
||||||
),
|
|
||||||
total,
|
|
||||||
page,
|
|
||||||
hasNext: page * limit < total,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
summary(userId: string, query: BankSummaryQueryDto) {
|
|
||||||
const period = periodBounds(query);
|
|
||||||
return this.prisma.$transaction(async (tx) => {
|
|
||||||
if (query.cardId) await this.card(tx, userId, query.cardId);
|
|
||||||
const rows = await tx.bankCardOperation.findMany({
|
|
||||||
where: {
|
|
||||||
userId,
|
|
||||||
deletedAt: null,
|
|
||||||
date: { gte: period.from, lte: period.to },
|
|
||||||
kind: { in: ['expense', 'refund'] },
|
|
||||||
...(query.cardId ? { cardId: query.cardId } : {}),
|
|
||||||
},
|
|
||||||
include: { originalExpense: { select: { categoryId: true } } },
|
|
||||||
});
|
|
||||||
const totals = bankSummary(
|
|
||||||
period,
|
|
||||||
rows.map((row) => ({
|
|
||||||
...row,
|
|
||||||
categoryId: row.originalExpense?.categoryId ?? row.categoryId,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
const categories = await tx.expenseCategory.findMany({
|
|
||||||
where: { userId },
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
month: query.month,
|
|
||||||
...period,
|
|
||||||
cardId: query.cardId ?? null,
|
|
||||||
expenses: rubMoney(totals.expenses),
|
|
||||||
refunds: rubMoney(totals.refunds),
|
|
||||||
net: rubMoney(totals.net),
|
|
||||||
categories: totals.categories.map((row) => ({
|
|
||||||
categoryId: row.categoryId,
|
|
||||||
categoryName: categories.find((c) => c.id === row.categoryId)!.name,
|
|
||||||
expenses: rubMoney(row.expenses),
|
|
||||||
refunds: rubMoney(row.refunds),
|
|
||||||
net: rubMoney(row.net),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { applyDecorators } from '@nestjs/common';
|
import { HttpStatus, applyDecorators } from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
ApiExtraModels,
|
ApiExtraModels,
|
||||||
ApiProperty,
|
ApiProperty,
|
||||||
@@ -8,10 +8,10 @@ import {
|
|||||||
|
|
||||||
export class ProblemDetailsDto {
|
export class ProblemDetailsDto {
|
||||||
@ApiProperty({ example: 401 })
|
@ApiProperty({ example: 401 })
|
||||||
status: number;
|
declare status: number;
|
||||||
|
|
||||||
@ApiProperty({ example: 'UNAUTHORIZED' })
|
@ApiProperty({ example: 'UNAUTHORIZED' })
|
||||||
code: string;
|
declare code: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
required: false,
|
required: false,
|
||||||
@@ -35,10 +35,13 @@ function problemResponse(status: number, description: string) {
|
|||||||
export function ApiProblemResponses(): MethodDecorator & ClassDecorator {
|
export function ApiProblemResponses(): MethodDecorator & ClassDecorator {
|
||||||
return applyDecorators(
|
return applyDecorators(
|
||||||
ApiExtraModels(ProblemDetailsDto),
|
ApiExtraModels(ProblemDetailsDto),
|
||||||
problemResponse(400, 'Invalid request'),
|
problemResponse(HttpStatus.BAD_REQUEST, 'Invalid request'),
|
||||||
problemResponse(401, 'Authentication required'),
|
problemResponse(HttpStatus.UNAUTHORIZED, 'Authentication required'),
|
||||||
problemResponse(404, 'Resource not found'),
|
problemResponse(HttpStatus.NOT_FOUND, 'Resource not found'),
|
||||||
problemResponse(503, 'Upstream service unavailable'),
|
problemResponse(
|
||||||
problemResponse(500, 'Internal server error'),
|
HttpStatus.SERVICE_UNAVAILABLE,
|
||||||
|
'Upstream service unavailable',
|
||||||
|
),
|
||||||
|
problemResponse(HttpStatus.INTERNAL_SERVER_ERROR, 'Internal server error'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
||||||
|
import { CredentialsDto } from '../modules/auth/presentation/auth.dto';
|
||||||
|
import {
|
||||||
|
CreateBankCardDto,
|
||||||
|
UpdateBankCardDto,
|
||||||
|
} from '../modules/banking/bank-cards/presentation/bank-card.dto';
|
||||||
|
|
||||||
|
describe('DTO validation', () => {
|
||||||
|
const pipe = new ValidationPipe({ transform: true, whitelist: true });
|
||||||
|
|
||||||
|
it('requires credentials and normalizes a valid email', async () => {
|
||||||
|
const metadata = { type: 'body' as const, metatype: CredentialsDto };
|
||||||
|
await expect(pipe.transform({}, metadata)).rejects.toBeInstanceOf(
|
||||||
|
BadRequestException,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
pipe.transform({ email: 'user@example.com' }, metadata),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
await expect(
|
||||||
|
pipe.transform(
|
||||||
|
{ email: ' User@Example.com ', password: 'long-enough-password' },
|
||||||
|
metadata,
|
||||||
|
),
|
||||||
|
).resolves.toEqual({
|
||||||
|
email: 'user@example.com',
|
||||||
|
password: 'long-enough-password',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires and validates nested money in a new card', async () => {
|
||||||
|
const metadata = { type: 'body' as const, metatype: CreateBankCardDto };
|
||||||
|
const card = {
|
||||||
|
id: '00000000-0000-4000-8000-000000000001',
|
||||||
|
name: 'Everyday',
|
||||||
|
openingDate: '2026-09-13',
|
||||||
|
};
|
||||||
|
for (const openingBalance of [undefined, null, {}, { currency: 'RUB' }]) {
|
||||||
|
await expect(
|
||||||
|
pipe.transform({ ...card, openingBalance }, metadata),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
}
|
||||||
|
const valid = {
|
||||||
|
...card,
|
||||||
|
openingBalance: { currency: 'RUB', value: '100.00' },
|
||||||
|
};
|
||||||
|
await expect(pipe.transform(valid, metadata)).resolves.toEqual(valid);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps update fields optional while requiring version and rejecting null', async () => {
|
||||||
|
const metadata = { type: 'body' as const, metatype: UpdateBankCardDto };
|
||||||
|
await expect(pipe.transform({}, metadata)).rejects.toBeInstanceOf(
|
||||||
|
BadRequestException,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
pipe.transform({ version: 1, name: null }, metadata),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
await expect(
|
||||||
|
pipe.transform({ version: 1 }, metadata),
|
||||||
|
).resolves.toMatchObject({ version: 1 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { constants as httpStatus } from 'node:http2';
|
||||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
import type { NextFunction, Request, Response } from 'express';
|
import type { NextFunction, Request, Response } from 'express';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
@@ -46,11 +47,11 @@ export class RequestLoggingMiddleware implements NestMiddleware {
|
|||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
const level =
|
const level =
|
||||||
response.statusCode >= 500
|
response.statusCode >= httpStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR
|
||||||
? 'error'
|
? 'error'
|
||||||
: response.statusCode === 429 ||
|
: response.statusCode === httpStatus.HTTP_STATUS_TOO_MANY_REQUESTS ||
|
||||||
response.statusCode === 401 ||
|
response.statusCode === httpStatus.HTTP_STATUS_UNAUTHORIZED ||
|
||||||
response.statusCode === 403
|
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,9 +1,10 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import type { Money } from './money.types';
|
||||||
|
|
||||||
export class MoneyDto {
|
export class MoneyDto implements Money {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
currency: string;
|
declare currency: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
value: string;
|
declare value: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export type Money = { currency: string; value: string };
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export const MILLISECONDS_PER_SECOND = 1_000;
|
||||||
|
export const MILLISECONDS_PER_DAY = 86_400_000;
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
const DEFAULT_PORT = 3000;
|
||||||
|
const DEFAULT_TBANK_RATE_LIMIT_PER_SECOND = 5;
|
||||||
|
const MAX_PORT = 65_535;
|
||||||
|
const MIN_JWT_SECRET_LENGTH = 32;
|
||||||
|
const TOKEN_KEY_BYTES = 32;
|
||||||
export interface Environment {
|
export interface Environment {
|
||||||
DATABASE_URL: string;
|
DATABASE_URL: string;
|
||||||
FRONTEND_ORIGIN: string;
|
FRONTEND_ORIGIN: string;
|
||||||
@@ -13,12 +18,14 @@ export interface Environment {
|
|||||||
export function validateEnv(config: Record<string, unknown>): Environment {
|
export function validateEnv(config: Record<string, unknown>): Environment {
|
||||||
const databaseUrl = config['DATABASE_URL'];
|
const databaseUrl = config['DATABASE_URL'];
|
||||||
const frontendOrigin = config['FRONTEND_ORIGIN'];
|
const frontendOrigin = config['FRONTEND_ORIGIN'];
|
||||||
const port = config['PORT'] ?? 3000;
|
const port = config['PORT'] ?? DEFAULT_PORT;
|
||||||
const jwtSecret = config['JWT_SECRET'];
|
const jwtSecret = config['JWT_SECRET'];
|
||||||
const tokenEncryptionKey = config['TOKEN_ENCRYPTION_KEY'];
|
const tokenEncryptionKey = config['TOKEN_ENCRYPTION_KEY'];
|
||||||
const tbankEndpoint =
|
const tbankEndpoint =
|
||||||
config['TBANK_GRPC_ENDPOINT'] ?? 'invest-public-api.tbank.ru:443';
|
config['TBANK_GRPC_ENDPOINT'] ?? 'invest-public-api.tbank.ru:443';
|
||||||
const tbankRateLimit = config['TBANK_RATE_LIMIT_PER_SECOND'] ?? 5;
|
const tbankRateLimit =
|
||||||
|
config['TBANK_RATE_LIMIT_PER_SECOND'] ??
|
||||||
|
DEFAULT_TBANK_RATE_LIMIT_PER_SECOND;
|
||||||
const tbankCaCertPath = config['TBANK_CA_CERT_PATH'];
|
const tbankCaCertPath = config['TBANK_CA_CERT_PATH'];
|
||||||
const logLevel = config['LOG_LEVEL'] ?? 'info';
|
const logLevel = config['LOG_LEVEL'] ?? 'info';
|
||||||
|
|
||||||
@@ -47,18 +54,25 @@ export function validateEnv(config: Record<string, unknown>): Environment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsedPort = Number(port);
|
const parsedPort = Number(port);
|
||||||
if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
|
if (
|
||||||
|
!Number.isInteger(parsedPort) ||
|
||||||
|
parsedPort < 1 ||
|
||||||
|
parsedPort > MAX_PORT
|
||||||
|
) {
|
||||||
throw new Error('PORT must be a valid port number');
|
throw new Error('PORT must be a valid port number');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof jwtSecret !== 'string' || jwtSecret.length < 32) {
|
if (
|
||||||
|
typeof jwtSecret !== 'string' ||
|
||||||
|
jwtSecret.length < MIN_JWT_SECRET_LENGTH
|
||||||
|
) {
|
||||||
throw new Error('JWT_SECRET must be at least 32 characters long');
|
throw new Error('JWT_SECRET must be at least 32 characters long');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
typeof tokenEncryptionKey !== 'string' ||
|
typeof tokenEncryptionKey !== 'string' ||
|
||||||
!/^[A-Za-z0-9+/]+={0,2}$/.test(tokenEncryptionKey) ||
|
!/^[A-Za-z0-9+/]+={0,2}$/.test(tokenEncryptionKey) ||
|
||||||
Buffer.from(tokenEncryptionKey, 'base64').length !== 32
|
Buffer.from(tokenEncryptionKey, 'base64').length !== TOKEN_KEY_BYTES
|
||||||
) {
|
) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'TOKEN_ENCRYPTION_KEY must be a base64-encoded 32-byte key',
|
'TOKEN_ENCRYPTION_KEY must be a base64-encoded 32-byte key',
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Public cross-module surface. Nest providers are exported by the matching module.
|
||||||
|
export { type MoexBondEvent, MoexClient } from './moex.client';
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
import { constants as httpStatus } from 'node:http2';
|
||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
|
||||||
|
const FALLBACK_PAGE_SIZE = 100;
|
||||||
|
|
||||||
const baseUrl = 'https://iss.moex.com/iss';
|
const baseUrl = 'https://iss.moex.com/iss';
|
||||||
const timeoutMs = 10_000;
|
const timeoutMs = 10_000;
|
||||||
|
|
||||||
@@ -121,8 +124,8 @@ export class MoexClient {
|
|||||||
if (!paginated) return rows;
|
if (!paginated) return rows;
|
||||||
const cursorBlock = response[`${block}.cursor`];
|
const cursorBlock = response[`${block}.cursor`];
|
||||||
if (!cursorBlock) {
|
if (!cursorBlock) {
|
||||||
if (current.length < 100) return rows;
|
if (current.length < FALLBACK_PAGE_SIZE) return rows;
|
||||||
start += 100;
|
start += FALLBACK_PAGE_SIZE;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const cursor = parseRows(cursorBlock)[0];
|
const cursor = parseRows(cursorBlock)[0];
|
||||||
@@ -145,7 +148,7 @@ export class MoexClient {
|
|||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
signal: AbortSignal.timeout(timeoutMs),
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
});
|
});
|
||||||
if (response.status === 404) 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')
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { MoexClient } from './moex.client';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [MoexClient],
|
||||||
|
exports: [MoexClient],
|
||||||
|
})
|
||||||
|
export class MoexModule {}
|
||||||
@@ -2,6 +2,12 @@ import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
|||||||
import { load } from 'cheerio';
|
import { load } from 'cheerio';
|
||||||
import { LRUCache } from 'lru-cache';
|
import { LRUCache } from 'lru-cache';
|
||||||
|
|
||||||
|
const REGISTRY_CACHE_TTL_MS = 21_600_000;
|
||||||
|
const REQUEST_TIMEOUT_MS = 10_000;
|
||||||
|
const COLUMN_COUNT = 6;
|
||||||
|
const ISIN_COLUMN = 3;
|
||||||
|
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';
|
||||||
@@ -18,7 +24,7 @@ export class NcrRatingsClient {
|
|||||||
private readonly cache = new LRUCache<
|
private readonly cache = new LRUCache<
|
||||||
string,
|
string,
|
||||||
Promise<Map<string, NcrRating>>
|
Promise<Map<string, NcrRating>>
|
||||||
>({ max: 1, ttl: 6 * 60 * 60_000 });
|
>({ max: 1, ttl: REGISTRY_CACHE_TTL_MS });
|
||||||
|
|
||||||
async rating(isin: string): Promise<NcrRating | null> {
|
async rating(isin: string): Promise<NcrRating | null> {
|
||||||
const key = isin.trim().toUpperCase();
|
const key = isin.trim().toUpperCase();
|
||||||
@@ -38,7 +44,7 @@ export class NcrRatingsClient {
|
|||||||
|
|
||||||
private async registry(): Promise<Map<string, NcrRating>> {
|
private async registry(): Promise<Map<string, NcrRating>> {
|
||||||
const response = await fetch(registryUrl, {
|
const response = await fetch(registryUrl, {
|
||||||
signal: AbortSignal.timeout(10_000),
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error('NCR unavailable');
|
if (!response.ok) throw new Error('NCR unavailable');
|
||||||
const $ = load(await response.text());
|
const $ = load(await response.text());
|
||||||
@@ -49,18 +55,18 @@ export class NcrRatingsClient {
|
|||||||
.get();
|
.get();
|
||||||
if (
|
if (
|
||||||
table.length !== 1 ||
|
table.length !== 1 ||
|
||||||
headings.length !== 6 ||
|
headings.length !== COLUMN_COUNT ||
|
||||||
headings[2] !== 'Рейтинг' ||
|
headings[2] !== 'Рейтинг' ||
|
||||||
headings[3] !== 'ISIN' ||
|
headings[ISIN_COLUMN] !== 'ISIN' ||
|
||||||
headings[5] !== 'Дата'
|
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) => {
|
||||||
const cells = $(row).find('td');
|
const cells = $(row).find('td');
|
||||||
if (cells.length !== 6) throw new Error('NCR row changed');
|
if (cells.length !== COLUMN_COUNT) throw new Error('NCR row changed');
|
||||||
const isin = cells.eq(3).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(2).text().replace(/\s+/g, ' ').trim();
|
||||||
@@ -73,9 +79,9 @@ export class NcrRatingsClient {
|
|||||||
)
|
)
|
||||||
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(5).text().trim(),
|
cells.eq(DATE_COLUMN).text().trim(),
|
||||||
);
|
);
|
||||||
const href = cells.eq(3).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]}`;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Public cross-module surface. Nest providers are exported by the matching module.
|
||||||
|
export { NcrRatingsClient } from './ncr-ratings.client';
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { NcrRatingsClient } from './ncr-ratings.client';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [NcrRatingsClient],
|
||||||
|
exports: [NcrRatingsClient],
|
||||||
|
})
|
||||||
|
export class NcrModule {}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { add, formatDecimal, multiply, subtract } from '../common/decimal';
|
import { add, formatDecimal, multiply, subtract } from '../../common/decimal';
|
||||||
import { decimal } from './decimal';
|
import { decimal } from './decimal';
|
||||||
|
|
||||||
describe('decimal', () => {
|
describe('decimal', () => {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Decimal } from '../common/decimal';
|
import { Decimal } from '../../common/decimal';
|
||||||
|
|
||||||
const NANO = 1_000_000_000n;
|
const NANO = 1_000_000_000n;
|
||||||
|
|
||||||
+8
-4
@@ -1,6 +1,7 @@
|
|||||||
import { InstrumentMetadataService } from './instrument-metadata.service';
|
|
||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
import { ServiceUnavailableException } from '@nestjs/common';
|
||||||
import type { LRUCache } from 'lru-cache';
|
import type { LRUCache } from 'lru-cache';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { InstrumentMetadataService } from './instrument-metadata.service';
|
||||||
import type { TbankInstrument } from './tbank.client';
|
import type { TbankInstrument } from './tbank.client';
|
||||||
|
|
||||||
describe('InstrumentMetadataService', () => {
|
describe('InstrumentMetadataService', () => {
|
||||||
@@ -178,7 +179,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
it('isolates in-flight credentials while sharing successful public metadata', async () => {
|
it('isolates in-flight credentials while sharing successful public metadata', async () => {
|
||||||
const error = new Error('INVALID_TBANK_TOKEN');
|
const error = new Error('INVALID_TBANK_TOKEN');
|
||||||
const known = { name: 'Облигация' };
|
const known = { name: 'Облигация' };
|
||||||
let rejectInvalid!: (reason: Error) => void;
|
let rejectInvalid: ((reason: Error) => void) | undefined;
|
||||||
tbank.getInstrumentByUid.mockImplementation((token: string) =>
|
tbank.getInstrumentByUid.mockImplementation((token: string) =>
|
||||||
token === 'invalid-token'
|
token === 'invalid-token'
|
||||||
? new Promise((_resolve, reject) => {
|
? new Promise((_resolve, reject) => {
|
||||||
@@ -191,6 +192,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
service.resolve('invalid-token', 'uid-1', null),
|
service.resolve('invalid-token', 'uid-1', null),
|
||||||
).rejects.toBe(error);
|
).rejects.toBe(error);
|
||||||
const valid = service.resolve('valid-token', 'uid-1', null);
|
const valid = service.resolve('valid-token', 'uid-1', null);
|
||||||
|
assert.ok(rejectInvalid);
|
||||||
rejectInvalid(error);
|
rejectInvalid(error);
|
||||||
|
|
||||||
await invalid;
|
await invalid;
|
||||||
@@ -237,7 +239,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
|
|
||||||
it('keeps a shared fetch alive after one caller aborts and caches its result', async () => {
|
it('keeps a shared fetch alive after one caller aborts and caches its result', async () => {
|
||||||
const known = { name: 'Облигация' };
|
const known = { name: 'Облигация' };
|
||||||
let finish!: (value: TbankInstrument) => void;
|
let finish: ((value: TbankInstrument) => void) | undefined;
|
||||||
tbank.getInstrumentByUid.mockReturnValue(
|
tbank.getInstrumentByUid.mockReturnValue(
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
finish = resolve;
|
finish = resolve;
|
||||||
@@ -254,6 +256,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
await expect(aborted).resolves.toBeNull();
|
await expect(aborted).resolves.toBeNull();
|
||||||
|
|
||||||
const waiting = service.resolve('token', 'uid-1', null);
|
const waiting = service.resolve('token', 'uid-1', null);
|
||||||
|
assert.ok(finish);
|
||||||
finish(known);
|
finish(known);
|
||||||
|
|
||||||
await expect(waiting).resolves.toEqual(known);
|
await expect(waiting).resolves.toEqual(known);
|
||||||
@@ -265,7 +268,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not start FIGI lookup after an aborted UID lookup fails later', async () => {
|
it('does not start FIGI lookup after an aborted UID lookup fails later', async () => {
|
||||||
let fail!: (reason: Error) => void;
|
let fail: ((reason: Error) => void) | undefined;
|
||||||
tbank.getInstrumentByUid.mockReturnValue(
|
tbank.getInstrumentByUid.mockReturnValue(
|
||||||
new Promise((_resolve, reject) => {
|
new Promise((_resolve, reject) => {
|
||||||
fail = reject;
|
fail = reject;
|
||||||
@@ -281,6 +284,7 @@ describe('InstrumentMetadataService', () => {
|
|||||||
controller.abort();
|
controller.abort();
|
||||||
await expect(result).resolves.toBeNull();
|
await expect(result).resolves.toBeNull();
|
||||||
|
|
||||||
|
assert.ok(fail);
|
||||||
fail(new Error('INVALID_TBANK_TOKEN'));
|
fail(new Error('INVALID_TBANK_TOKEN'));
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||||
import { LRUCache } from 'lru-cache';
|
import { LRUCache } from 'lru-cache';
|
||||||
import { createHash } 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 { TbankClient, type TbankInstrument } from './tbank.client';
|
import { TbankClient, type TbankInstrument } from './tbank.client';
|
||||||
|
|
||||||
const metadataForMs = 86_400_000;
|
const metadataForMs = 86_400_000;
|
||||||
+2
-2
@@ -5,12 +5,12 @@ import {
|
|||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
|
||||||
jest.mock('../prisma/prisma.service', () => ({
|
jest.mock('../../prisma/prisma.service', () => ({
|
||||||
PrismaService: class PrismaService {},
|
PrismaService: class PrismaService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
import { TbankAccessService } from './tbank-access.service';
|
|
||||||
import type { TbankAccountContext } from './tbank-access.service';
|
import type { TbankAccountContext } from './tbank-access.service';
|
||||||
|
import { TbankAccessService } from './tbank-access.service';
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
import { TbankTokenService } from './tbank-token.service';
|
||||||
|
|
||||||
describe('TbankAccessService', () => {
|
describe('TbankAccessService', () => {
|
||||||
@@ -4,14 +4,14 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
import { BrokerageAccountDto } from './brokerage-account.dto';
|
|
||||||
import {
|
import {
|
||||||
|
SupportedTbankAccount,
|
||||||
accessibleTbankAccount,
|
accessibleTbankAccount,
|
||||||
supportedTbankAccounts,
|
supportedTbankAccounts,
|
||||||
} from './tbank-account-policy';
|
} from './tbank-account.policy';
|
||||||
import { TbankClient, TbankAccount } from './tbank.client';
|
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
import { TbankTokenService } from './tbank-token.service';
|
||||||
|
import { TbankAccount, TbankClient } from './tbank.client';
|
||||||
|
|
||||||
export type TbankConnectionContext = {
|
export type TbankConnectionContext = {
|
||||||
token: string;
|
token: string;
|
||||||
@@ -30,7 +30,9 @@ export class TbankAccessService {
|
|||||||
private readonly tbank: TbankClient,
|
private readonly tbank: TbankClient,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async listSupportedAccounts(userId: string): Promise<BrokerageAccountDto[]> {
|
async listSupportedAccounts(
|
||||||
|
userId: string,
|
||||||
|
): Promise<SupportedTbankAccount[]> {
|
||||||
return this.withSupportedAccounts(userId, ({ accounts }) => accounts);
|
return this.withSupportedAccounts(userId, ({ accounts }) => accounts);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +41,7 @@ export class TbankAccessService {
|
|||||||
handler: (context: {
|
handler: (context: {
|
||||||
token: string;
|
token: string;
|
||||||
generation: string;
|
generation: string;
|
||||||
accounts: BrokerageAccountDto[];
|
accounts: SupportedTbankAccount[];
|
||||||
}) => Promise<T> | T,
|
}) => Promise<T> | T,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
return this.withConnection(userId, async ({ token, generation }) =>
|
return this.withConnection(userId, async ({ token, generation }) =>
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
accessibleTbankAccount,
|
accessibleTbankAccount,
|
||||||
supportedTbankAccounts,
|
supportedTbankAccounts,
|
||||||
} from './tbank-account-policy';
|
} 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', () => {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { BrokerageAccountDto } from './brokerage-account.dto';
|
import { MILLISECONDS_PER_SECOND } from '../../common/time';
|
||||||
import { TbankAccount } from './tbank.client';
|
import { TbankAccount } from './tbank.client';
|
||||||
|
|
||||||
const accountTypes = {
|
const accountTypes = {
|
||||||
@@ -15,10 +15,16 @@ const accountTypes = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
type AccountType = keyof typeof accountTypes;
|
type AccountType = keyof typeof accountTypes;
|
||||||
|
export type SupportedTbankAccount = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: (typeof accountTypes)[AccountType]['type'];
|
||||||
|
openedOn: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
export function supportedTbankAccounts(
|
export function supportedTbankAccounts(
|
||||||
accounts: TbankAccount[],
|
accounts: TbankAccount[],
|
||||||
): BrokerageAccountDto[] {
|
): SupportedTbankAccount[] {
|
||||||
return accounts.flatMap((account) => {
|
return accounts.flatMap((account) => {
|
||||||
const details = accountTypes[account.type as AccountType];
|
const details = accountTypes[account.type as AccountType];
|
||||||
if (!details) return [];
|
if (!details) return [];
|
||||||
@@ -46,7 +52,7 @@ export function accessibleTbankAccount(
|
|||||||
|
|
||||||
function openedOn(seconds: string | number | undefined): string | 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) * 1000);
|
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(0, 10);
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
TbankDecimal,
|
TbankDecimal,
|
||||||
TbankMoney,
|
|
||||||
TbankInstrument,
|
TbankInstrument,
|
||||||
|
TbankMoney,
|
||||||
TbankTimestamp,
|
TbankTimestamp,
|
||||||
} from './tbank.client';
|
} from './tbank.client';
|
||||||
|
|
||||||
@@ -1,6 +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';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Public cross-module surface. Nest providers are exported by the matching module.
|
||||||
|
export { InstrumentMetadataService } from './instrument-metadata.service';
|
||||||
|
export {
|
||||||
|
TbankAccessService,
|
||||||
|
type TbankConnectionContext,
|
||||||
|
} from './tbank-access.service';
|
||||||
|
export {
|
||||||
|
type TbankBond,
|
||||||
|
type TbankCandle,
|
||||||
|
type TbankFundamentals,
|
||||||
|
type TbankShare,
|
||||||
|
} from './tbank-market.types';
|
||||||
|
export { TbankTokenService } from './tbank-token.service';
|
||||||
|
export {
|
||||||
|
TbankClient,
|
||||||
|
type TbankDividend,
|
||||||
|
type TbankInstrument,
|
||||||
|
type TbankMoney,
|
||||||
|
type TbankOperationItem,
|
||||||
|
type TbankPortfolio,
|
||||||
|
type TbankPositions,
|
||||||
|
type TbankTimestamp,
|
||||||
|
} from './tbank.client';
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
|
||||||
import { status } from '@grpc/grpc-js';
|
import { status } from '@grpc/grpc-js';
|
||||||
|
import { NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||||
import { TbankClient } from './tbank.client';
|
import { TbankClient } from './tbank.client';
|
||||||
|
|
||||||
describe('TbankClient operations', () => {
|
describe('TbankClient operations', () => {
|
||||||
@@ -1,9 +1,4 @@
|
|||||||
import {
|
import { MILLISECONDS_PER_SECOND } from '../../common/time';
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import {
|
import {
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
Client,
|
Client,
|
||||||
@@ -14,20 +9,33 @@ import {
|
|||||||
status,
|
status,
|
||||||
} from '@grpc/grpc-js';
|
} from '@grpc/grpc-js';
|
||||||
import { loadSync } from '@grpc/proto-loader';
|
import { loadSync } from '@grpc/proto-loader';
|
||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
ServiceUnavailableException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { Environment } from '../config/env.validation';
|
import { StructuredLogger } from '../../common/logging/structured-logger.service';
|
||||||
import { StructuredLogger } from '../common/logging/structured-logger.service';
|
import { Environment } from '../../config/env.validation';
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
TbankShare,
|
|
||||||
TbankBond,
|
TbankBond,
|
||||||
TbankCoupon,
|
|
||||||
TbankCandle,
|
TbankCandle,
|
||||||
TbankLastPrice,
|
TbankCoupon,
|
||||||
TbankFundamentals,
|
TbankFundamentals,
|
||||||
|
TbankLastPrice,
|
||||||
|
TbankShare,
|
||||||
} from './tbank-market.types';
|
} from './tbank-market.types';
|
||||||
|
|
||||||
|
const RATE_WINDOW_MS = 1_000;
|
||||||
|
const METADATA_MAX_ATTEMPTS = 3;
|
||||||
|
const RPC_MAX_ATTEMPTS = 2;
|
||||||
|
const MAX_QUEUE_SIZE = 50;
|
||||||
|
const METADATA_RETRY_DELAY_MS = 2_000;
|
||||||
|
const RPC_RETRY_DELAY_MS = 1_000;
|
||||||
|
|
||||||
const requestDeadlineMs = 15_000;
|
const requestDeadlineMs = 15_000;
|
||||||
|
|
||||||
type Unary<Request, Response> = (
|
type Unary<Request, Response> = (
|
||||||
@@ -134,7 +142,7 @@ class RateLimiter {
|
|||||||
|
|
||||||
private drain(): void {
|
private drain(): void {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - this.windowStartedAt >= 1000) {
|
if (now - this.windowStartedAt >= RATE_WINDOW_MS) {
|
||||||
this.windowStartedAt = now;
|
this.windowStartedAt = now;
|
||||||
this.starts = 0;
|
this.starts = 0;
|
||||||
}
|
}
|
||||||
@@ -145,7 +153,7 @@ class RateLimiter {
|
|||||||
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, 1000 - (now - this.windowStartedAt)),
|
Math.max(1, RATE_WINDOW_MS - (now - this.windowStartedAt)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,10 +172,13 @@ export class TbankClient {
|
|||||||
config: ConfigService<Environment, true>,
|
config: ConfigService<Environment, true>,
|
||||||
private readonly logger: StructuredLogger,
|
private readonly logger: StructuredLogger,
|
||||||
) {
|
) {
|
||||||
const sourceProtoRoot = join(process.cwd(), 'src/tbank/proto/contracts');
|
const sourceProtoRoot = join(
|
||||||
|
process.cwd(),
|
||||||
|
'src/integrations/tbank/proto/contracts',
|
||||||
|
);
|
||||||
const protoRoot = existsSync(sourceProtoRoot)
|
const protoRoot = existsSync(sourceProtoRoot)
|
||||||
? sourceProtoRoot
|
? sourceProtoRoot
|
||||||
: join(process.cwd(), 'dist/tbank/proto/contracts');
|
: join(process.cwd(), 'dist/integrations/tbank/proto/contracts');
|
||||||
const definition = loadSync(
|
const definition = loadSync(
|
||||||
[
|
[
|
||||||
'users.proto',
|
'users.proto',
|
||||||
@@ -233,11 +244,12 @@ export class TbankClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getOpenAccounts(token: string): Promise<TbankAccount[]> {
|
getOpenAccounts(token: string): Promise<TbankAccount[]> {
|
||||||
return this.call(token, this.users, 'getAccounts', {
|
return this.call<{ accounts?: TbankAccount[] }>(
|
||||||
status: 'ACCOUNT_STATUS_OPEN',
|
token,
|
||||||
}).then(
|
this.users,
|
||||||
(response: { accounts?: TbankAccount[] }) => response.accounts ?? [],
|
'getAccounts',
|
||||||
);
|
{ status: 'ACCOUNT_STATUS_OPEN' },
|
||||||
|
).then((response) => response.accounts ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
getPortfolio(token: string, accountId: string): Promise<TbankPortfolio> {
|
getPortfolio(token: string, accountId: string): Promise<TbankPortfolio> {
|
||||||
@@ -275,13 +287,16 @@ export class TbankClient {
|
|||||||
from: string,
|
from: string,
|
||||||
to: string,
|
to: string,
|
||||||
): Promise<TbankDividend[]> {
|
): Promise<TbankDividend[]> {
|
||||||
return this.call(token, this.instruments, 'getDividends', {
|
return this.call<{ dividends?: TbankDividend[] }>(
|
||||||
instrumentId,
|
token,
|
||||||
from: { seconds: String(utcSeconds(from)) },
|
this.instruments,
|
||||||
to: { seconds: String(utcSeconds(to)) },
|
'getDividends',
|
||||||
}).then(
|
{
|
||||||
(response: { dividends?: TbankDividend[] }) => response.dividends ?? [],
|
instrumentId,
|
||||||
);
|
from: { seconds: String(utcSeconds(from)) },
|
||||||
|
to: { seconds: String(utcSeconds(to)) },
|
||||||
|
},
|
||||||
|
).then((response) => response.dividends ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
findShares(token: string, query: string): Promise<TbankShare[]> {
|
findShares(token: string, query: string): Promise<TbankShare[]> {
|
||||||
@@ -415,8 +430,12 @@ export class TbankClient {
|
|||||||
'getCandles',
|
'getCandles',
|
||||||
{
|
{
|
||||||
instrumentId: uid,
|
instrumentId: uid,
|
||||||
from: { seconds: String(Math.floor(from.valueOf() / 1000)) },
|
from: {
|
||||||
to: { seconds: String(Math.floor(to.valueOf() / 1000)) },
|
seconds: String(Math.floor(from.valueOf() / MILLISECONDS_PER_SECOND)),
|
||||||
|
},
|
||||||
|
to: {
|
||||||
|
seconds: String(Math.floor(to.valueOf() / MILLISECONDS_PER_SECOND)),
|
||||||
|
},
|
||||||
interval: 'CANDLE_INTERVAL_DAY',
|
interval: 'CANDLE_INTERVAL_DAY',
|
||||||
limit: 2400,
|
limit: 2400,
|
||||||
},
|
},
|
||||||
@@ -449,10 +468,10 @@ export class TbankClient {
|
|||||||
request: object,
|
request: object,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const metadataCall = method === 'getInstrumentBy';
|
const metadataCall = method === 'getInstrumentBy';
|
||||||
const maxAttempts = metadataCall ? 3 : 2;
|
const maxAttempts = metadataCall ? METADATA_MAX_ATTEMPTS : RPC_MAX_ATTEMPTS;
|
||||||
for (let attempts = 1; attempts <= maxAttempts; attempts += 1) {
|
for (let attempts = 1; attempts <= maxAttempts; attempts += 1) {
|
||||||
const startedAt = performance.now();
|
const startedAt = performance.now();
|
||||||
const queueFull = this.queue.size >= 50;
|
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' });
|
||||||
@@ -485,7 +504,12 @@ export class TbankClient {
|
|||||||
durationMs: Math.round(performance.now() - startedAt),
|
durationMs: Math.round(performance.now() - startedAt),
|
||||||
});
|
});
|
||||||
await new Promise((resolve) =>
|
await new Promise((resolve) =>
|
||||||
setTimeout(resolve, metadataCall ? attempts * 2000 : 1000),
|
setTimeout(
|
||||||
|
resolve,
|
||||||
|
metadataCall
|
||||||
|
? attempts * METADATA_RETRY_DELAY_MS
|
||||||
|
: RPC_RETRY_DELAY_MS,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -530,5 +554,5 @@ export class TbankClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function utcSeconds(date: string): number {
|
function utcSeconds(date: string): number {
|
||||||
return Math.floor(Date.parse(`${date}T00:00:00Z`) / 1000);
|
return Math.floor(Date.parse(`${date}T00:00:00Z`) / MILLISECONDS_PER_SECOND);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
||||||
|
|
||||||
|
const KEY_SIZE_BYTES = 32;
|
||||||
|
|
||||||
const VERSION = 1;
|
const VERSION = 1;
|
||||||
const NONCE_SIZE = 12;
|
const NONCE_SIZE = 12;
|
||||||
const TAG_SIZE = 16;
|
const TAG_SIZE = 16;
|
||||||
@@ -9,7 +11,8 @@ 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 !== 32) throw new Error('Invalid token encryption key');
|
if (decoded.length !== KEY_SIZE_BYTES)
|
||||||
|
throw new Error('Invalid token encryption key');
|
||||||
return new TbankCrypto(decoded);
|
return new TbankCrypto(decoded);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { InstrumentMetadataService } from './instrument-metadata.service';
|
||||||
|
import { TbankAccessService } from './tbank-access.service';
|
||||||
|
import { TbankTokenService } from './tbank-token.service';
|
||||||
|
import { TbankClient } from './tbank.client';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [
|
||||||
|
TbankClient,
|
||||||
|
TbankTokenService,
|
||||||
|
TbankAccessService,
|
||||||
|
InstrumentMetadataService,
|
||||||
|
],
|
||||||
|
exports: [
|
||||||
|
TbankClient,
|
||||||
|
TbankTokenService,
|
||||||
|
TbankAccessService,
|
||||||
|
InstrumentMetadataService,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class TbankModule {}
|
||||||
@@ -7,7 +7,7 @@ jest.mock('bcrypt', () => ({
|
|||||||
compare: jest.fn(() => Promise.resolve(true)),
|
compare: jest.fn(() => Promise.resolve(true)),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
jest.mock('../prisma/prisma.service', () => ({
|
jest.mock('../../../prisma/prisma.service', () => ({
|
||||||
PrismaService: class PrismaService {},
|
PrismaService: class PrismaService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -6,10 +6,13 @@ 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 PASSWORD_HASH_ROUNDS = 12;
|
||||||
|
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 =
|
||||||
@@ -39,7 +42,7 @@ export class AuthService {
|
|||||||
data: {
|
data: {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
email: normalizedEmail,
|
email: normalizedEmail,
|
||||||
passwordHash: await bcrypt.hash(password, 12),
|
passwordHash: await bcrypt.hash(password, PASSWORD_HASH_ROUNDS),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -162,7 +165,7 @@ export class AuthService {
|
|||||||
);
|
);
|
||||||
const data = {
|
const data = {
|
||||||
refreshTokenHash: this.hash(refreshToken),
|
refreshTokenHash: this.hash(refreshToken),
|
||||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
expiresAt: new Date(Date.now() + REFRESH_TTL_MS),
|
||||||
};
|
};
|
||||||
if (expectedRefreshTokenHash) {
|
if (expectedRefreshTokenHash) {
|
||||||
const updated = await this.prisma.session.updateMany({
|
const updated = await this.prisma.session.updateMany({
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
// Public cross-module surface. Nest providers are exported by the matching module.
|
||||||
|
export { type AccessPayload } from './application/auth.types';
|
||||||
|
export { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
||||||
@@ -2,11 +2,11 @@ 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 './auth.controller';
|
import { AuthController } from './presentation/auth.controller';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './application/auth.service';
|
||||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
import { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
||||||
import { JwtStrategy } from './jwt.strategy';
|
import { JwtStrategy } from './infrastructure/jwt.strategy';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -19,6 +19,7 @@ import { JwtStrategy } from './jwt.strategy';
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
|
exports: [JwtAuthGuard],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [AuthService, JwtStrategy, JwtAuthGuard],
|
providers: [AuthService, JwtStrategy, JwtAuthGuard],
|
||||||
})
|
})
|
||||||
@@ -2,8 +2,8 @@ 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 './auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
import { HTTP_CODE_METADATA } from '@nestjs/common/constants';
|
import { HTTP_CODE_METADATA } from '@nestjs/common/constants';
|
||||||
|
|
||||||
jest.mock('./auth.service', () => ({
|
jest.mock('../application/auth.service', () => ({
|
||||||
AuthService: class AuthService {},
|
AuthService: class AuthService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -3,11 +3,12 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
HttpCode,
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
Post,
|
Post,
|
||||||
Req,
|
Req,
|
||||||
Res,
|
Res,
|
||||||
UseGuards,
|
|
||||||
UnauthorizedException,
|
UnauthorizedException,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
ApiBearerAuth,
|
ApiBearerAuth,
|
||||||
@@ -17,29 +18,29 @@ import {
|
|||||||
ApiTags,
|
ApiTags,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import type { Request, Response } from 'express';
|
import type { Request, Response } from 'express';
|
||||||
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { CredentialsDto } from './auth.dto';
|
import { CredentialsDto } from './auth.dto';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from '../application/auth.service';
|
||||||
import { AccessPayload } from './auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
import { ApiProblemResponses } from '../common/decorators/api-safe-error-response.decorator';
|
|
||||||
|
|
||||||
const REFRESH_COOKIE = 'refresh_token';
|
const REFRESH_COOKIE = 'refresh_token';
|
||||||
const COOKIE_PATH = '/api/v1/auth';
|
const COOKIE_PATH = '/api/v1/auth';
|
||||||
|
|
||||||
class UserDto {
|
class UserDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id: string;
|
declare id: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
email: string;
|
declare email: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
class AuthenticationDto {
|
class AuthenticationDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
accessToken: string;
|
declare accessToken: string;
|
||||||
|
|
||||||
@ApiProperty({ type: UserDto })
|
@ApiProperty({ type: UserDto })
|
||||||
user: UserDto;
|
declare user: UserDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiTags('auth')
|
@ApiTags('auth')
|
||||||
@@ -49,7 +50,7 @@ export class AuthController {
|
|||||||
constructor(private readonly auth: AuthService) {}
|
constructor(private readonly auth: AuthService) {}
|
||||||
|
|
||||||
@Post('register')
|
@Post('register')
|
||||||
@HttpCode(200)
|
@HttpCode(HttpStatus.OK)
|
||||||
@ApiOkResponse({ type: AuthenticationDto })
|
@ApiOkResponse({ type: AuthenticationDto })
|
||||||
async register(
|
async register(
|
||||||
@Body() credentials: CredentialsDto,
|
@Body() credentials: CredentialsDto,
|
||||||
@@ -62,7 +63,7 @@ export class AuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('login')
|
@Post('login')
|
||||||
@HttpCode(200)
|
@HttpCode(HttpStatus.OK)
|
||||||
@ApiOkResponse({ type: AuthenticationDto })
|
@ApiOkResponse({ type: AuthenticationDto })
|
||||||
async login(
|
async login(
|
||||||
@Body() credentials: CredentialsDto,
|
@Body() credentials: CredentialsDto,
|
||||||
@@ -75,7 +76,7 @@ export class AuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('refresh')
|
@Post('refresh')
|
||||||
@HttpCode(200)
|
@HttpCode(HttpStatus.OK)
|
||||||
@ApiOkResponse({ type: AuthenticationDto })
|
@ApiOkResponse({ type: AuthenticationDto })
|
||||||
async refresh(
|
async refresh(
|
||||||
@Req() request: Request,
|
@Req() request: Request,
|
||||||
@@ -92,7 +93,7 @@ export class AuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('logout')
|
@Post('logout')
|
||||||
@HttpCode(204)
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
@ApiNoContentResponse()
|
@ApiNoContentResponse()
|
||||||
async logout(
|
async logout(
|
||||||
@Req() request: Request,
|
@Req() request: Request,
|
||||||
@@ -1,26 +1,32 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
IsString,
|
IsString,
|
||||||
MinLength,
|
MinLength,
|
||||||
Validate,
|
Validate,
|
||||||
ValidatorConstraint,
|
ValidatorConstraint,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
const MAX_EMAIL_LENGTH = 254;
|
||||||
|
const ASCII_SPACE = 32;
|
||||||
|
const ASCII_DELETE = 127;
|
||||||
|
const MIN_PASSWORD_LENGTH = 12;
|
||||||
|
const MAX_PASSWORD_BYTES = 72;
|
||||||
|
|
||||||
@ValidatorConstraint({ name: 'email' })
|
@ValidatorConstraint({ name: 'email' })
|
||||||
class EmailConstraint {
|
class EmailConstraint {
|
||||||
validate(value: unknown): boolean {
|
validate(value: unknown): boolean {
|
||||||
return (
|
return (
|
||||||
typeof value === 'string' &&
|
typeof value === 'string' &&
|
||||||
value.length <= 254 &&
|
value.length <= MAX_EMAIL_LENGTH &&
|
||||||
value.split('@').length === 2 &&
|
value.split('@').length === 2 &&
|
||||||
!value
|
!value
|
||||||
.split('')
|
.split('')
|
||||||
.some(
|
.some(
|
||||||
(character) =>
|
(character) =>
|
||||||
/\s/.test(character) ||
|
/\s/.test(character) ||
|
||||||
character.charCodeAt(0) < 32 ||
|
character.charCodeAt(0) < ASCII_SPACE ||
|
||||||
character.charCodeAt(0) === 127,
|
character.charCodeAt(0) === ASCII_DELETE,
|
||||||
) &&
|
) &&
|
||||||
value.split('@').every(Boolean)
|
value.split('@').every(Boolean)
|
||||||
);
|
);
|
||||||
@@ -33,7 +39,10 @@ class EmailConstraint {
|
|||||||
@ValidatorConstraint({ name: 'passwordBytes' })
|
@ValidatorConstraint({ name: 'passwordBytes' })
|
||||||
class PasswordBytesConstraint {
|
class PasswordBytesConstraint {
|
||||||
validate(value: unknown): boolean {
|
validate(value: unknown): boolean {
|
||||||
return typeof value === 'string' && Buffer.byteLength(value, 'utf8') <= 72;
|
return (
|
||||||
|
typeof value === 'string' &&
|
||||||
|
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';
|
||||||
@@ -47,11 +56,15 @@ export class CredentialsDto {
|
|||||||
typeof value === 'string' ? value.trim().toLowerCase() : value,
|
typeof value === 'string' ? value.trim().toLowerCase() : value,
|
||||||
)
|
)
|
||||||
@Validate(EmailConstraint)
|
@Validate(EmailConstraint)
|
||||||
email: string;
|
declare email: string;
|
||||||
|
|
||||||
@ApiProperty({ minLength: 12, maxLength: 72, example: 'a secure password' })
|
@ApiProperty({
|
||||||
|
minLength: MIN_PASSWORD_LENGTH,
|
||||||
|
maxLength: MAX_PASSWORD_BYTES,
|
||||||
|
example: 'a secure password',
|
||||||
|
})
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(12)
|
@MinLength(MIN_PASSWORD_LENGTH)
|
||||||
@Validate(PasswordBytesConstraint)
|
@Validate(PasswordBytesConstraint)
|
||||||
password: string;
|
declare password: string;
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
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 './auth.types';
|
import { AccessPayload } from '../application/auth.types';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import {
|
||||||
|
MAX_CARD_NAME_LENGTH,
|
||||||
|
MAX_OPERATION_DESCRIPTION_LENGTH,
|
||||||
|
} from '../domain/bank-card-limits';
|
||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import {
|
||||||
|
bankPaymentSystems,
|
||||||
|
BankPeriodQueryDto,
|
||||||
|
CreateBankCardDto,
|
||||||
|
CreateBankOperationDto,
|
||||||
|
} from '../presentation/bank-card.dto';
|
||||||
|
import { isCalendarDate, moscowToday } from '../domain/bank-card.calculations';
|
||||||
|
import { parseRubMoney } from '../domain/rub-money';
|
||||||
|
|
||||||
|
export const BankErrorCode = {
|
||||||
|
InvalidInput: 'BANK_INVALID_INPUT',
|
||||||
|
VersionConflict: 'BANK_VERSION_CONFLICT',
|
||||||
|
NotFound: 'BANK_NOT_FOUND',
|
||||||
|
InvalidMoney: 'BANK_INVALID_MONEY',
|
||||||
|
InvalidDate: 'BANK_INVALID_DATE',
|
||||||
|
ImmutableOperation: 'BANK_IMMUTABLE_OPERATION',
|
||||||
|
InvalidRefund: 'BANK_INVALID_REFUND',
|
||||||
|
RefundLimit: 'BANK_REFUND_LIMIT',
|
||||||
|
DependentRefunds: 'BANK_DEPENDENT_REFUNDS',
|
||||||
|
IntentConflict: 'BANK_INTENT_CONFLICT',
|
||||||
|
OperationDeleted: 'BANK_OPERATION_DELETED',
|
||||||
|
CardArchived: 'BANK_CARD_ARCHIVED',
|
||||||
|
OpeningDateConflict: 'BANK_OPENING_DATE_CONFLICT',
|
||||||
|
WriteConflict: 'BANK_WRITE_CONFLICT',
|
||||||
|
DuplicateCategory: 'BANK_DUPLICATE_CATEGORY',
|
||||||
|
} as const;
|
||||||
|
export type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||||
|
|
||||||
|
export function fail(code: BankErrorCode = BankErrorCode.InvalidInput): never {
|
||||||
|
throw new BadRequestException({ code });
|
||||||
|
}
|
||||||
|
export function periodBounds(query: BankPeriodQueryDto) {
|
||||||
|
if (query.month && !query.from && !query.to) {
|
||||||
|
const from = `${query.month}-01`;
|
||||||
|
if (!isCalendarDate(from)) return fail();
|
||||||
|
const end = new Date(`${from}T00:00:00Z`);
|
||||||
|
end.setUTCMonth(end.getUTCMonth() + 1, 0);
|
||||||
|
return { from, to: end.toISOString().slice(0, 10) };
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
query.month ||
|
||||||
|
!query.from ||
|
||||||
|
!query.to ||
|
||||||
|
!isCalendarDate(query.from) ||
|
||||||
|
!isCalendarDate(query.to) ||
|
||||||
|
query.from > query.to
|
||||||
|
)
|
||||||
|
return fail();
|
||||||
|
return { from: query.from, to: query.to };
|
||||||
|
}
|
||||||
|
export function conflict(
|
||||||
|
code: BankErrorCode = BankErrorCode.VersionConflict,
|
||||||
|
): never {
|
||||||
|
throw new ConflictException({ code });
|
||||||
|
}
|
||||||
|
export function missing(): never {
|
||||||
|
throw new NotFoundException({ code: BankErrorCode.NotFound });
|
||||||
|
}
|
||||||
|
export const fingerprint = (value: unknown) =>
|
||||||
|
createHash('sha256')
|
||||||
|
.update(
|
||||||
|
JSON.stringify(value, (_key, item: unknown) =>
|
||||||
|
typeof item === 'bigint' ? item.toString() : item,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.digest('hex');
|
||||||
|
export function amount(
|
||||||
|
value: Parameters<typeof parseRubMoney>[0],
|
||||||
|
positive = false,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
return parseRubMoney(value, positive);
|
||||||
|
} catch {
|
||||||
|
return fail(BankErrorCode.InvalidMoney);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function calendar(value: string) {
|
||||||
|
if (!isCalendarDate(value)) fail(BankErrorCode.InvalidDate);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function currentDate(value: string) {
|
||||||
|
calendar(value);
|
||||||
|
if (value > moscowToday()) fail(BankErrorCode.InvalidDate);
|
||||||
|
}
|
||||||
|
export function name(value: string, max: number) {
|
||||||
|
if (typeof value !== 'string' || !value.trim() || value.trim().length > max)
|
||||||
|
fail();
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
export function cardInput(dto: CreateBankCardDto) {
|
||||||
|
const bankName = dto.bankName?.trim() || null;
|
||||||
|
if (bankName && bankName.length > MAX_CARD_NAME_LENGTH) fail();
|
||||||
|
if (dto.lastFour != null && !/^\d{4}$/.test(dto.lastFour)) fail();
|
||||||
|
if (
|
||||||
|
dto.paymentSystem != null &&
|
||||||
|
!bankPaymentSystems.some((system) => system === dto.paymentSystem)
|
||||||
|
)
|
||||||
|
fail();
|
||||||
|
return {
|
||||||
|
...(dto.paymentSystem == null ? {} : { paymentSystem: dto.paymentSystem }),
|
||||||
|
name: name(dto.name, MAX_CARD_NAME_LENGTH),
|
||||||
|
bankName,
|
||||||
|
lastFour: dto.lastFour || null,
|
||||||
|
openingBalanceKopecks: amount(dto.openingBalance),
|
||||||
|
openingDate: calendar(dto.openingDate),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function operationInput(dto: CreateBankOperationDto) {
|
||||||
|
if (
|
||||||
|
dto.description != null &&
|
||||||
|
(typeof dto.description !== 'string' ||
|
||||||
|
dto.description.length > MAX_OPERATION_DESCRIPTION_LENGTH)
|
||||||
|
)
|
||||||
|
fail();
|
||||||
|
return {
|
||||||
|
kind: dto.kind,
|
||||||
|
cardId: dto.cardId,
|
||||||
|
targetCardId: dto.targetCardId ?? null,
|
||||||
|
categoryId: dto.categoryId ?? null,
|
||||||
|
originalExpenseId: dto.originalExpenseId ?? null,
|
||||||
|
amountKopecks: amount(dto.amount, true),
|
||||||
|
date: calendar(dto.date),
|
||||||
|
description: dto.description || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { BankCard, Prisma } from '../../../../../generated/prisma/client';
|
||||||
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
BankCardDto,
|
||||||
|
CreateBankCardDto,
|
||||||
|
UpdateBankCardDto,
|
||||||
|
} from '../presentation/bank-card.dto';
|
||||||
|
import { bankBalance } from '../domain/bank-card.calculations';
|
||||||
|
import { rubMoney } from '../domain/rub-money';
|
||||||
|
|
||||||
|
import {
|
||||||
|
cardInput,
|
||||||
|
BankErrorCode,
|
||||||
|
conflict,
|
||||||
|
currentDate,
|
||||||
|
fail,
|
||||||
|
fingerprint,
|
||||||
|
missing,
|
||||||
|
} from './bank-card-input';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
@Injectable()
|
||||||
|
export class BankCardsService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly repository: BankCardsRepository,
|
||||||
|
) {}
|
||||||
|
private async cardView(tx: Tx, card: BankCard): Promise<BankCardDto> {
|
||||||
|
const rows = await tx.bankCardOperation.findMany({
|
||||||
|
where: {
|
||||||
|
userId: card.userId,
|
||||||
|
deletedAt: null,
|
||||||
|
OR: [{ cardId: card.id }, { targetCardId: card.id }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: card.id,
|
||||||
|
name: card.name,
|
||||||
|
bankName: card.bankName,
|
||||||
|
lastFour: card.lastFour,
|
||||||
|
paymentSystem: card.paymentSystem,
|
||||||
|
openingDate: card.openingDate,
|
||||||
|
openingBalance: rubMoney(card.openingBalanceKopecks),
|
||||||
|
balance: rubMoney(bankBalance(card.id, card.openingBalanceKopecks, rows)),
|
||||||
|
version: card.version,
|
||||||
|
archivedAt: card.archivedAt?.toISOString() ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
list(userId: string, includeArchived = false) {
|
||||||
|
return this.prisma.$transaction(async (tx) =>
|
||||||
|
Promise.all(
|
||||||
|
(
|
||||||
|
await tx.bankCard.findMany({
|
||||||
|
where: { userId, ...(includeArchived ? {} : { archivedAt: null }) },
|
||||||
|
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||||
|
})
|
||||||
|
).map((card) => this.cardView(tx, card)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
get(userId: string, id: string) {
|
||||||
|
return this.prisma.$transaction(async (tx) =>
|
||||||
|
this.cardView(tx, await this.repository.card(tx, userId, id)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
createCard(userId: string, dto: CreateBankCardDto) {
|
||||||
|
const input = cardInput(dto),
|
||||||
|
hash = fingerprint(input);
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const existing = await tx.bankCard.findUnique({ where: { id: dto.id } });
|
||||||
|
if (existing) {
|
||||||
|
if (existing.userId !== userId) missing();
|
||||||
|
if (existing.createFingerprint !== hash)
|
||||||
|
conflict(BankErrorCode.IntentConflict);
|
||||||
|
return this.cardView(tx, existing);
|
||||||
|
}
|
||||||
|
currentDate(input.openingDate);
|
||||||
|
await this.repository.seed(tx, userId);
|
||||||
|
return this.cardView(
|
||||||
|
tx,
|
||||||
|
await tx.bankCard.create({
|
||||||
|
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateCard(userId: string, id: string, dto: UpdateBankCardDto) {
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const previous = await this.repository.card(tx, userId, id);
|
||||||
|
if (previous.version !== dto.version) conflict();
|
||||||
|
const input = cardInput({
|
||||||
|
id,
|
||||||
|
name: dto.name ?? previous.name,
|
||||||
|
bankName:
|
||||||
|
dto.bankName === undefined
|
||||||
|
? (previous.bankName ?? undefined)
|
||||||
|
: (dto.bankName ?? undefined),
|
||||||
|
lastFour:
|
||||||
|
dto.lastFour === undefined
|
||||||
|
? (previous.lastFour ?? undefined)
|
||||||
|
: (dto.lastFour ?? undefined),
|
||||||
|
paymentSystem:
|
||||||
|
dto.paymentSystem === undefined
|
||||||
|
? previous.paymentSystem
|
||||||
|
: dto.paymentSystem,
|
||||||
|
openingBalance:
|
||||||
|
dto.openingBalance ?? rubMoney(previous.openingBalanceKopecks),
|
||||||
|
openingDate: dto.openingDate ?? previous.openingDate,
|
||||||
|
});
|
||||||
|
const financial =
|
||||||
|
input.openingBalanceKopecks !== previous.openingBalanceKopecks ||
|
||||||
|
input.openingDate !== previous.openingDate;
|
||||||
|
if (financial && previous.archivedAt)
|
||||||
|
conflict(BankErrorCode.CardArchived);
|
||||||
|
currentDate(input.openingDate);
|
||||||
|
if (
|
||||||
|
await tx.bankCardOperation.findFirst({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
deletedAt: null,
|
||||||
|
date: { lt: input.openingDate },
|
||||||
|
OR: [{ cardId: id }, { targetCardId: id }],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
fail(BankErrorCode.OpeningDateConflict);
|
||||||
|
const changed = await tx.bankCard.updateMany({
|
||||||
|
where: { id, userId, version: dto.version },
|
||||||
|
data: {
|
||||||
|
...input,
|
||||||
|
paymentSystem: input.paymentSystem ?? null,
|
||||||
|
version: { increment: 1 },
|
||||||
|
...(dto.archived === undefined
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
archivedAt: dto.archived
|
||||||
|
? (previous.archivedAt ?? new Date())
|
||||||
|
: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (changed.count !== 1) conflict();
|
||||||
|
return this.cardView(tx, await this.repository.card(tx, userId, id));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||||
|
import { GoneException, Injectable } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
BankCardOperation,
|
||||||
|
Prisma,
|
||||||
|
} from '../../../../../generated/prisma/client';
|
||||||
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
BankOperationDto,
|
||||||
|
DEFAULT_BANK_PAGE_SIZE,
|
||||||
|
BankOperationsQueryDto,
|
||||||
|
BankPageQueryDto,
|
||||||
|
CreateBankOperationDto,
|
||||||
|
UpdateBankOperationDto,
|
||||||
|
} from '../presentation/bank-card.dto';
|
||||||
|
import { rubMoney } from '../domain/rub-money';
|
||||||
|
|
||||||
|
import {
|
||||||
|
BankErrorCode,
|
||||||
|
conflict,
|
||||||
|
currentDate,
|
||||||
|
fail,
|
||||||
|
fingerprint,
|
||||||
|
missing,
|
||||||
|
operationInput,
|
||||||
|
periodBounds,
|
||||||
|
} from './bank-card-input';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
@Injectable()
|
||||||
|
export class BankOperationsService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly repository: BankCardsRepository,
|
||||||
|
) {}
|
||||||
|
private async operationView(
|
||||||
|
tx: Tx,
|
||||||
|
row: BankCardOperation,
|
||||||
|
): Promise<BankOperationDto> {
|
||||||
|
const card = await this.repository.card(tx, row.userId, row.cardId);
|
||||||
|
const target = row.targetCardId
|
||||||
|
? await this.repository.card(tx, row.userId, row.targetCardId)
|
||||||
|
: null;
|
||||||
|
const source = row.originalExpenseId
|
||||||
|
? await this.repository.operation(tx, row.userId, row.originalExpenseId)
|
||||||
|
: null;
|
||||||
|
const categoryId = source?.categoryId ?? row.categoryId;
|
||||||
|
const category = categoryId
|
||||||
|
? await tx.expenseCategory.findFirst({
|
||||||
|
where: { id: categoryId, userId: row.userId },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
const refunds =
|
||||||
|
row.kind === BankOperationKind.Expense || source
|
||||||
|
? await tx.bankCardOperation.findMany({
|
||||||
|
where: {
|
||||||
|
userId: row.userId,
|
||||||
|
originalExpenseId: source?.id ?? row.id,
|
||||||
|
deletedAt: null,
|
||||||
|
...(source ? { id: { not: row.id } } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
kind: row.kind as BankOperationDto['kind'],
|
||||||
|
cardId: row.cardId,
|
||||||
|
cardName: card.name,
|
||||||
|
targetCardId: row.targetCardId,
|
||||||
|
targetCardName: target?.name ?? null,
|
||||||
|
categoryId,
|
||||||
|
categoryName: category?.name ?? null,
|
||||||
|
originalExpenseId: row.originalExpenseId,
|
||||||
|
amount: rubMoney(row.amountKopecks),
|
||||||
|
availableRefund:
|
||||||
|
row.kind === BankOperationKind.Expense || source
|
||||||
|
? rubMoney(
|
||||||
|
(source?.amountKopecks ?? row.amountKopecks) -
|
||||||
|
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
date: row.date,
|
||||||
|
description: row.description,
|
||||||
|
version: row.version,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private async validateOperation(
|
||||||
|
tx: Tx,
|
||||||
|
userId: string,
|
||||||
|
input: ReturnType<typeof operationInput>,
|
||||||
|
old?: BankCardOperation,
|
||||||
|
) {
|
||||||
|
const cards = new Set(
|
||||||
|
[input.cardId, input.targetCardId, old?.cardId, old?.targetCardId].filter(
|
||||||
|
(id): id is string => Boolean(id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
currentDate(input.date);
|
||||||
|
for (const id of cards) {
|
||||||
|
const card = await this.repository.card(tx, userId, id, true);
|
||||||
|
if (
|
||||||
|
(id === input.cardId || id === input.targetCardId) &&
|
||||||
|
input.date < card.openingDate
|
||||||
|
)
|
||||||
|
fail(BankErrorCode.InvalidDate);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
old &&
|
||||||
|
(old.kind !== input.kind ||
|
||||||
|
old.originalExpenseId !== input.originalExpenseId)
|
||||||
|
)
|
||||||
|
fail(BankErrorCode.ImmutableOperation);
|
||||||
|
if (input.kind === BankOperationKind.Transfer) {
|
||||||
|
if (
|
||||||
|
!input.targetCardId ||
|
||||||
|
input.targetCardId === input.cardId ||
|
||||||
|
input.categoryId ||
|
||||||
|
input.originalExpenseId
|
||||||
|
)
|
||||||
|
fail();
|
||||||
|
} else if (input.targetCardId) fail();
|
||||||
|
if (input.kind === BankOperationKind.Expense) {
|
||||||
|
if (input.originalExpenseId) fail();
|
||||||
|
if (!input.categoryId) {
|
||||||
|
const category = await tx.expenseCategory.findUnique({
|
||||||
|
where: { userId_seedKey: { userId, seedKey: 'other' } },
|
||||||
|
});
|
||||||
|
if (!category) missing();
|
||||||
|
input.categoryId = category.id;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!(await tx.expenseCategory.findFirst({
|
||||||
|
where: { userId, id: input.categoryId },
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
missing();
|
||||||
|
} else if (input.categoryId) fail();
|
||||||
|
if (input.kind !== BankOperationKind.Refund && input.originalExpenseId)
|
||||||
|
fail();
|
||||||
|
if (input.kind === BankOperationKind.Refund) {
|
||||||
|
if (!input.originalExpenseId) fail();
|
||||||
|
const source = await this.repository.operation(
|
||||||
|
tx,
|
||||||
|
userId,
|
||||||
|
input.originalExpenseId,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
source.deletedAt ||
|
||||||
|
source.kind !== BankOperationKind.Expense ||
|
||||||
|
source.cardId !== input.cardId
|
||||||
|
)
|
||||||
|
fail(BankErrorCode.InvalidRefund);
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
await tx.bankCardOperation.updateMany({
|
||||||
|
where: {
|
||||||
|
id: source.id,
|
||||||
|
userId,
|
||||||
|
version: source.version,
|
||||||
|
deletedAt: null,
|
||||||
|
},
|
||||||
|
data: { version: { increment: 1 } },
|
||||||
|
})
|
||||||
|
).count !== 1
|
||||||
|
)
|
||||||
|
conflict();
|
||||||
|
const refunds = await tx.bankCardOperation.findMany({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
originalExpenseId: source.id,
|
||||||
|
deletedAt: null,
|
||||||
|
...(old ? { id: { not: old.id } } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (input.date < source.date) fail(BankErrorCode.InvalidDate);
|
||||||
|
if (
|
||||||
|
refunds.reduce((sum, r) => sum + r.amountKopecks, 0n) +
|
||||||
|
input.amountKopecks >
|
||||||
|
source.amountKopecks
|
||||||
|
)
|
||||||
|
conflict(BankErrorCode.RefundLimit);
|
||||||
|
}
|
||||||
|
if (old?.kind === BankOperationKind.Expense) {
|
||||||
|
const refunds = await tx.bankCardOperation.findMany({
|
||||||
|
where: { userId, originalExpenseId: old.id, deletedAt: null },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
refunds.length &&
|
||||||
|
(input.cardId !== old.cardId ||
|
||||||
|
refunds.some((row) => row.date < input.date) ||
|
||||||
|
refunds.reduce((sum, row) => sum + row.amountKopecks, 0n) >
|
||||||
|
input.amountKopecks)
|
||||||
|
)
|
||||||
|
conflict(BankErrorCode.DependentRefunds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
createOperation(userId: string, dto: CreateBankOperationDto) {
|
||||||
|
const normalized = operationInput(dto),
|
||||||
|
hash = fingerprint(normalized);
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const existing = await tx.bankCardOperation.findUnique({
|
||||||
|
where: { id: dto.id },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
if (existing.userId !== userId) missing();
|
||||||
|
if (existing.createFingerprint !== hash)
|
||||||
|
conflict(BankErrorCode.IntentConflict);
|
||||||
|
if (existing.deletedAt)
|
||||||
|
throw new GoneException({ code: BankErrorCode.OperationDeleted });
|
||||||
|
return this.operationView(tx, existing);
|
||||||
|
}
|
||||||
|
const input = { ...normalized };
|
||||||
|
await this.validateOperation(tx, userId, input);
|
||||||
|
return this.operationView(
|
||||||
|
tx,
|
||||||
|
await tx.bankCardOperation.create({
|
||||||
|
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
getOperation(userId: string, id: string) {
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
const row = await this.repository.operation(tx, userId, id);
|
||||||
|
if (row.deletedAt) missing();
|
||||||
|
return this.operationView(tx, row);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateOperation(userId: string, id: string, dto: UpdateBankOperationDto) {
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const old = await this.repository.operation(tx, userId, id);
|
||||||
|
if (old.deletedAt) missing();
|
||||||
|
if (old.version !== dto.version) conflict();
|
||||||
|
const input = operationInput({
|
||||||
|
id,
|
||||||
|
kind: dto.kind ?? (old.kind as CreateBankOperationDto['kind']),
|
||||||
|
cardId: dto.cardId ?? old.cardId,
|
||||||
|
targetCardId: dto.targetCardId ?? old.targetCardId ?? undefined,
|
||||||
|
categoryId: dto.categoryId ?? old.categoryId ?? undefined,
|
||||||
|
originalExpenseId:
|
||||||
|
dto.originalExpenseId ?? old.originalExpenseId ?? undefined,
|
||||||
|
amount: dto.amount ?? rubMoney(old.amountKopecks),
|
||||||
|
date: dto.date ?? old.date,
|
||||||
|
description: dto.description ?? old.description ?? undefined,
|
||||||
|
});
|
||||||
|
await this.validateOperation(tx, userId, input, old);
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
await tx.bankCardOperation.updateMany({
|
||||||
|
where: { id, userId, version: dto.version, deletedAt: null },
|
||||||
|
data: { ...input, version: { increment: 1 } },
|
||||||
|
})
|
||||||
|
).count !== 1
|
||||||
|
)
|
||||||
|
conflict();
|
||||||
|
return this.operationView(
|
||||||
|
tx,
|
||||||
|
await this.repository.operation(tx, userId, id),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
deleteOperation(userId: string, id: string, version: number) {
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const row = await this.repository.operation(tx, userId, id);
|
||||||
|
if (row.deletedAt) return;
|
||||||
|
if (row.version !== version) conflict();
|
||||||
|
await this.repository.card(tx, userId, row.cardId, true);
|
||||||
|
if (row.targetCardId)
|
||||||
|
await this.repository.card(tx, userId, row.targetCardId, true);
|
||||||
|
if (
|
||||||
|
row.kind === BankOperationKind.Expense &&
|
||||||
|
(await tx.bankCardOperation.findFirst({
|
||||||
|
where: { userId, originalExpenseId: id, deletedAt: null },
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
conflict(BankErrorCode.DependentRefunds);
|
||||||
|
if (row.originalExpenseId) {
|
||||||
|
const source = await this.repository.operation(
|
||||||
|
tx,
|
||||||
|
userId,
|
||||||
|
row.originalExpenseId,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
await tx.bankCardOperation.updateMany({
|
||||||
|
where: { id: source.id, userId, version: source.version },
|
||||||
|
data: { version: { increment: 1 } },
|
||||||
|
})
|
||||||
|
).count !== 1
|
||||||
|
)
|
||||||
|
conflict();
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
await tx.bankCardOperation.updateMany({
|
||||||
|
where: { id, userId, version, deletedAt: null },
|
||||||
|
data: { deletedAt: new Date(), version: { increment: 1 } },
|
||||||
|
})
|
||||||
|
).count !== 1
|
||||||
|
)
|
||||||
|
conflict();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
history(
|
||||||
|
userId: string,
|
||||||
|
id: string,
|
||||||
|
query: BankOperationsQueryDto | BankPageQueryDto,
|
||||||
|
expenses = false,
|
||||||
|
) {
|
||||||
|
const period = expenses
|
||||||
|
? undefined
|
||||||
|
: periodBounds(query as BankOperationsQueryDto);
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
await this.repository.card(tx, userId, id);
|
||||||
|
const page = query.page ?? 1,
|
||||||
|
limit = query.limit ?? DEFAULT_BANK_PAGE_SIZE;
|
||||||
|
const where: Prisma.BankCardOperationWhereInput = {
|
||||||
|
userId,
|
||||||
|
deletedAt: null,
|
||||||
|
OR: [{ cardId: id }, { targetCardId: id }],
|
||||||
|
...(period
|
||||||
|
? { date: { gte: period.from, lte: period.to } }
|
||||||
|
: { kind: BankOperationKind.Expense }),
|
||||||
|
};
|
||||||
|
const total = await tx.bankCardOperation.count({ where });
|
||||||
|
const rows = await tx.bankCardOperation.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
items: await Promise.all(
|
||||||
|
rows.map((row) => this.operationView(tx, row)),
|
||||||
|
),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
hasNext: page * limit < total,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { MAX_CATEGORY_NAME_LENGTH } from '../domain/bank-card-limits';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
|
||||||
|
import { conflict, missing, name } from './bank-card-input';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
@Injectable()
|
||||||
|
export class ExpenseCategoriesService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly repository: BankCardsRepository,
|
||||||
|
) {}
|
||||||
|
async categories(userId: string) {
|
||||||
|
return (
|
||||||
|
await this.prisma.expenseCategory.findMany({
|
||||||
|
where: { userId },
|
||||||
|
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||||
|
})
|
||||||
|
).map(({ id, name, seedKey, version }) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
isDefault: seedKey === 'other',
|
||||||
|
version,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
createCategory(userId: string, value: string) {
|
||||||
|
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
await this.repository.seed(tx, userId);
|
||||||
|
const row = await tx.expenseCategory.create({
|
||||||
|
data: {
|
||||||
|
id: randomUUID(),
|
||||||
|
userId,
|
||||||
|
name: label,
|
||||||
|
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
isDefault: false,
|
||||||
|
version: row.version,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateCategory(userId: string, id: string, value: string, version: number) {
|
||||||
|
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||||
|
return this.repository.write(async (tx) => {
|
||||||
|
const row = await tx.expenseCategory.findFirst({ where: { id, userId } });
|
||||||
|
if (!row) missing();
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
await tx.expenseCategory.updateMany({
|
||||||
|
where: { id, userId, version },
|
||||||
|
data: {
|
||||||
|
name: label,
|
||||||
|
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||||
|
version: { increment: 1 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).count !== 1
|
||||||
|
)
|
||||||
|
conflict();
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: label,
|
||||||
|
isDefault: row.seedKey === 'other',
|
||||||
|
version: version + 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
jest.mock('../../../../prisma/prisma.service', () => ({
|
||||||
|
PrismaService: class {},
|
||||||
|
}));
|
||||||
|
jest.mock('../../../../../generated/prisma/client', () => ({ Prisma: {} }));
|
||||||
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
import { GetBankSummaryUseCase } from './get-bank-summary.use-case';
|
||||||
|
|
||||||
|
describe('bank card summary categories', () => {
|
||||||
|
it('resolves category names and rejects an inconsistent category reference', async () => {
|
||||||
|
const categories = jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue([{ id: 'food', name: 'Продукты' }]);
|
||||||
|
const tx = {
|
||||||
|
bankCardOperation: {
|
||||||
|
findMany: jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
kind: 'expense',
|
||||||
|
categoryId: 'food',
|
||||||
|
amountKopecks: 123n,
|
||||||
|
date: '2026-09-13',
|
||||||
|
originalExpense: null,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
expenseCategory: { findMany: categories },
|
||||||
|
};
|
||||||
|
const service = new GetBankSummaryUseCase(
|
||||||
|
new BankCardsRepository({
|
||||||
|
$transaction: (run: (client: typeof tx) => unknown) => run(tx),
|
||||||
|
} as unknown as PrismaService),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.execute('user', { month: '2026-09' }),
|
||||||
|
).resolves.toMatchObject({
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
categoryId: 'food',
|
||||||
|
categoryName: 'Продукты',
|
||||||
|
net: { value: '1.23' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
categories.mockResolvedValue([]);
|
||||||
|
await expect(service.execute('user', { month: '2026-09' })).rejects.toThrow(
|
||||||
|
'Bank operation category is missing',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { BankSummaryQueryDto } from '../presentation/bank-card.dto';
|
||||||
|
import { bankSummary } from '../domain/bank-card.calculations';
|
||||||
|
import { rubMoney } from '../domain/rub-money';
|
||||||
|
|
||||||
|
import { periodBounds } from './bank-card-input';
|
||||||
|
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||||
|
@Injectable()
|
||||||
|
export class GetBankSummaryUseCase {
|
||||||
|
constructor(private readonly repository: BankCardsRepository) {}
|
||||||
|
|
||||||
|
async execute(userId: string, query: BankSummaryQueryDto) {
|
||||||
|
const period = periodBounds(query);
|
||||||
|
const { operations, categories } = await this.repository.summaryData(
|
||||||
|
userId,
|
||||||
|
period,
|
||||||
|
query.cardId,
|
||||||
|
);
|
||||||
|
const totals = bankSummary(period, operations);
|
||||||
|
return {
|
||||||
|
month: query.month,
|
||||||
|
...period,
|
||||||
|
cardId: query.cardId ?? null,
|
||||||
|
expenses: rubMoney(totals.expenses),
|
||||||
|
refunds: rubMoney(totals.refunds),
|
||||||
|
net: rubMoney(totals.net),
|
||||||
|
categories: totals.categories.map((row) => {
|
||||||
|
const category = categories.find((c) => c.id === row.categoryId);
|
||||||
|
if (!category) throw new Error('Bank operation category is missing');
|
||||||
|
return {
|
||||||
|
categoryId: row.categoryId,
|
||||||
|
categoryName: category.name,
|
||||||
|
expenses: rubMoney(row.expenses),
|
||||||
|
refunds: rubMoney(row.refunds),
|
||||||
|
net: rubMoney(row.net),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
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 { BankOperationsService } from './application/bank-operations.service';
|
||||||
|
import { ExpenseCategoriesService } from './application/expense-categories.service';
|
||||||
|
import { GetBankSummaryUseCase } from './application/get-bank-summary.use-case';
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule],
|
||||||
|
controllers: [BankCardsController],
|
||||||
|
providers: [
|
||||||
|
GetBankSummaryUseCase,
|
||||||
|
ExpenseCategoriesService,
|
||||||
|
BankOperationsService,
|
||||||
|
BankCardsRepository,
|
||||||
|
BankCardsService,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class BankCardsModule {}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export const MAX_CARD_NAME_LENGTH = 100;
|
||||||
|
export const MAX_CATEGORY_NAME_LENGTH = 80;
|
||||||
|
export const MAX_OPERATION_DESCRIPTION_LENGTH = 500;
|
||||||
+29
-7
@@ -1,3 +1,6 @@
|
|||||||
|
import { BankOperationKind } from './bank-operation-kind';
|
||||||
|
|
||||||
|
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',
|
||||||
@@ -30,12 +33,21 @@ export function bankBalance(
|
|||||||
let balance = opening;
|
let balance = opening;
|
||||||
for (const operation of operations) {
|
for (const operation of operations) {
|
||||||
if (operation.cardId === cardId) {
|
if (operation.cardId === cardId) {
|
||||||
if (operation.kind === 'expense' || operation.kind === 'transfer')
|
if (
|
||||||
|
operation.kind === BankOperationKind.Expense ||
|
||||||
|
operation.kind === BankOperationKind.Transfer
|
||||||
|
)
|
||||||
balance -= operation.amountKopecks;
|
balance -= operation.amountKopecks;
|
||||||
else if (operation.kind === 'topup' || operation.kind === 'refund')
|
else if (
|
||||||
|
operation.kind === BankOperationKind.Topup ||
|
||||||
|
operation.kind === BankOperationKind.Refund
|
||||||
|
)
|
||||||
balance += operation.amountKopecks;
|
balance += operation.amountKopecks;
|
||||||
}
|
}
|
||||||
if (operation.kind === 'transfer' && operation.targetCardId === cardId)
|
if (
|
||||||
|
operation.kind === BankOperationKind.Transfer &&
|
||||||
|
operation.targetCardId === cardId
|
||||||
|
)
|
||||||
balance += operation.amountKopecks;
|
balance += operation.amountKopecks;
|
||||||
}
|
}
|
||||||
return balance;
|
return balance;
|
||||||
@@ -60,13 +72,23 @@ export function bankSummary(
|
|||||||
for (const operation of operations) {
|
for (const operation of operations) {
|
||||||
if (
|
if (
|
||||||
typeof period === 'string'
|
typeof period === 'string'
|
||||||
? operation.date.slice(0, 7) !== period
|
? operation.date.slice(0, ISO_MONTH_LENGTH) !== period
|
||||||
: operation.date < period.from || operation.date > period.to
|
: operation.date < period.from || operation.date > period.to
|
||||||
)
|
)
|
||||||
continue;
|
continue;
|
||||||
if (operation.kind !== 'expense' && operation.kind !== 'refund') continue;
|
if (
|
||||||
const expense = operation.kind === 'expense' ? operation.amountKopecks : 0n;
|
operation.kind !== BankOperationKind.Expense &&
|
||||||
const refund = operation.kind === 'refund' ? operation.amountKopecks : 0n;
|
operation.kind !== BankOperationKind.Refund
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
const expense =
|
||||||
|
operation.kind === BankOperationKind.Expense
|
||||||
|
? operation.amountKopecks
|
||||||
|
: 0n;
|
||||||
|
const refund =
|
||||||
|
operation.kind === BankOperationKind.Refund
|
||||||
|
? operation.amountKopecks
|
||||||
|
: 0n;
|
||||||
expenses += expense;
|
expenses += expense;
|
||||||
refunds += refund;
|
refunds += refund;
|
||||||
if (operation.categoryId !== null) {
|
if (operation.categoryId !== null) {
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export const BankOperationKind = {
|
||||||
|
Expense: 'expense',
|
||||||
|
Topup: 'topup',
|
||||||
|
Transfer: 'transfer',
|
||||||
|
Refund: 'refund',
|
||||||
|
} as const;
|
||||||
|
export type BankOperationKind =
|
||||||
|
(typeof BankOperationKind)[keyof typeof BankOperationKind];
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import { decimalFromString, formatDecimal } from './decimal';
|
import { decimalFromString, formatDecimal } from '../../../../common/decimal';
|
||||||
import { MoneyDto } from './money.dto';
|
import type { Money } from '../../../../common/money.types';
|
||||||
|
|
||||||
export function parseRubMoney(money: MoneyDto, positive = false): bigint {
|
const MIN_KOPECKS = -9_223_372_036_854_775_808n;
|
||||||
|
const MAX_KOPECKS = 9_223_372_036_854_775_807n;
|
||||||
|
|
||||||
|
export function parseRubMoney(money: Money, positive = false): bigint {
|
||||||
if (
|
if (
|
||||||
money?.currency !== 'RUB' ||
|
money?.currency !== 'RUB' ||
|
||||||
typeof money.value !== 'string' ||
|
typeof money.value !== 'string' ||
|
||||||
@@ -12,14 +15,14 @@ export function parseRubMoney(money: MoneyDto, positive = false): bigint {
|
|||||||
if (amount.scale > 2)
|
if (amount.scale > 2)
|
||||||
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);
|
const kopecks = amount.value * 10n ** BigInt(2 - amount.scale);
|
||||||
if (kopecks < -(2n ** 63n) || kopecks > 2n ** 63n - 1n)
|
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 <= 0n)
|
||||||
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): MoneyDto {
|
export function rubMoney(kopecks: bigint): Money {
|
||||||
return {
|
return {
|
||||||
currency: 'RUB',
|
currency: 'RUB',
|
||||||
value: formatDecimal({ value: kopecks, scale: 2 }),
|
value: formatDecimal({ value: kopecks, scale: 2 }),
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { Prisma } from '../../../../../generated/prisma/client';
|
||||||
|
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||||
|
|
||||||
|
import {
|
||||||
|
BankErrorCode,
|
||||||
|
conflict,
|
||||||
|
missing,
|
||||||
|
} from '../application/bank-card-input';
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
const TRANSACTION_MAX_WAIT_MS = 10_000;
|
||||||
|
const TRANSACTION_TIMEOUT_MS = 15_000;
|
||||||
|
const MAX_WRITE_RETRY_COUNT = 2;
|
||||||
|
const seeds = [
|
||||||
|
'Продукты',
|
||||||
|
'Кафе',
|
||||||
|
'Такси',
|
||||||
|
'Транспорт',
|
||||||
|
'Жильё',
|
||||||
|
'Здоровье',
|
||||||
|
'Покупки',
|
||||||
|
'Развлечения',
|
||||||
|
'Другое',
|
||||||
|
];
|
||||||
|
@Injectable()
|
||||||
|
export class BankCardsRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
async write<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
try {
|
||||||
|
return await this.prisma.$transaction(run, {
|
||||||
|
maxWait: TRANSACTION_MAX_WAIT_MS,
|
||||||
|
timeout: TRANSACTION_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const code =
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError
|
||||||
|
? error.code
|
||||||
|
: '';
|
||||||
|
const busy =
|
||||||
|
code === 'P2034' ||
|
||||||
|
code === 'P2028' ||
|
||||||
|
(error instanceof Error &&
|
||||||
|
/SQLITE_BUSY|database is locked/.test(error.message));
|
||||||
|
if ((busy || code === 'P2002') && attempt < MAX_WRITE_RETRY_COUNT)
|
||||||
|
continue;
|
||||||
|
if (busy) conflict(BankErrorCode.WriteConflict);
|
||||||
|
if (code === 'P2002') conflict(BankErrorCode.DuplicateCategory);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async card(tx: Tx, userId: string, id: string, active = false) {
|
||||||
|
const card = await tx.bankCard.findFirst({ where: { id, userId } });
|
||||||
|
if (!card) return missing();
|
||||||
|
if (active && card.archivedAt) conflict(BankErrorCode.CardArchived);
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
async operation(tx: Tx, userId: string, id: string) {
|
||||||
|
const row = await tx.bankCardOperation.findFirst({ where: { id, userId } });
|
||||||
|
if (!row) return missing();
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
async seed(tx: Tx, userId: string) {
|
||||||
|
for (const [index, label] of seeds.entries()) {
|
||||||
|
const seedKey = index === seeds.length - 1 ? 'other' : String(index);
|
||||||
|
if (
|
||||||
|
!(await tx.expenseCategory.findUnique({
|
||||||
|
where: { userId_seedKey: { userId, seedKey } },
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
await tx.expenseCategory.create({
|
||||||
|
data: {
|
||||||
|
id: randomUUID(),
|
||||||
|
userId,
|
||||||
|
seedKey,
|
||||||
|
name: label,
|
||||||
|
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
summaryData(
|
||||||
|
userId: string,
|
||||||
|
period: { from: string; to: string },
|
||||||
|
cardId?: string,
|
||||||
|
) {
|
||||||
|
return this.prisma.$transaction(async (tx) => {
|
||||||
|
if (cardId) await this.card(tx, userId, cardId);
|
||||||
|
const rows = await tx.bankCardOperation.findMany({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
deletedAt: null,
|
||||||
|
date: { gte: period.from, lte: period.to },
|
||||||
|
kind: { in: [BankOperationKind.Expense, BankOperationKind.Refund] },
|
||||||
|
...(cardId ? { cardId } : {}),
|
||||||
|
},
|
||||||
|
include: { originalExpense: { select: { categoryId: true } } },
|
||||||
|
});
|
||||||
|
const categories = await tx.expenseCategory.findMany({
|
||||||
|
where: { userId },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
operations: rows.map((row) => ({
|
||||||
|
...row,
|
||||||
|
categoryId: row.originalExpense?.categoryId ?? row.categoryId,
|
||||||
|
})),
|
||||||
|
categories,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+97
-78
@@ -1,8 +1,14 @@
|
|||||||
|
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,
|
||||||
OmitType,
|
|
||||||
IntersectionType,
|
IntersectionType,
|
||||||
|
OmitType,
|
||||||
PartialType,
|
PartialType,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import { Transform, Type } from 'class-transformer';
|
import { Transform, Type } from 'class-transformer';
|
||||||
@@ -22,38 +28,39 @@ import {
|
|||||||
ValidateIf,
|
ValidateIf,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { MoneyDto } from '../common/money.dto';
|
import { MoneyDto } from '../../../../common/money.dto';
|
||||||
|
|
||||||
|
export const DEFAULT_BANK_PAGE_SIZE = 50;
|
||||||
|
const MAX_BANK_PAGE_SIZE = 100;
|
||||||
|
|
||||||
const trim = ({ value }: { value: unknown }) =>
|
const trim = ({ value }: { value: unknown }) =>
|
||||||
typeof value === 'string' ? value.trim() : value;
|
typeof value === 'string' ? value.trim() : value;
|
||||||
export const bankPaymentSystems = ['mir', 'visa', 'mastercard'] as const;
|
export const bankPaymentSystems = ['mir', 'visa', 'mastercard'] as const;
|
||||||
export const bankOperationKinds = [
|
const bankOperationKinds = Object.values(BankOperationKind);
|
||||||
'expense',
|
|
||||||
'topup',
|
|
||||||
'transfer',
|
|
||||||
'refund',
|
|
||||||
] as const;
|
|
||||||
export type BankOperationKind = (typeof bankOperationKinds)[number];
|
|
||||||
export class RubMoneyInputDto {
|
export class RubMoneyInputDto {
|
||||||
@ApiProperty({ enum: ['RUB'] }) @IsIn(['RUB']) 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()
|
||||||
@Matches(/^-?\d+(\.\d{1,2})?$/)
|
@Matches(/^-?\d+(\.\d{1,2})?$/)
|
||||||
value: string;
|
declare value: string;
|
||||||
}
|
}
|
||||||
export class CreateBankCardDto {
|
export class CreateBankCardDto {
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() id: string;
|
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
||||||
@ApiProperty({ minLength: 1, maxLength: 100 })
|
@ApiProperty({ minLength: 1, maxLength: MAX_CARD_NAME_LENGTH })
|
||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(1)
|
@MinLength(1)
|
||||||
@MaxLength(100)
|
@MaxLength(MAX_CARD_NAME_LENGTH)
|
||||||
name: string;
|
declare name: string;
|
||||||
@ApiPropertyOptional({ type: String, nullable: true, maxLength: 100 })
|
@ApiPropertyOptional({
|
||||||
|
type: String,
|
||||||
|
nullable: true,
|
||||||
|
maxLength: MAX_CARD_NAME_LENGTH,
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(100)
|
@MaxLength(MAX_CARD_NAME_LENGTH)
|
||||||
bankName?: string | null;
|
bankName?: string | null;
|
||||||
@ApiPropertyOptional({ type: String, nullable: true, pattern: '^[0-9]{4}$' })
|
@ApiPropertyOptional({ type: String, nullable: true, pattern: '^[0-9]{4}$' })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@@ -67,39 +74,39 @@ export class CreateBankCardDto {
|
|||||||
@IsDefined()
|
@IsDefined()
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@Type(() => RubMoneyInputDto)
|
@Type(() => RubMoneyInputDto)
|
||||||
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}$/)
|
||||||
openingDate: string;
|
declare openingDate: string;
|
||||||
}
|
}
|
||||||
export class UpdateBankCardDto extends PartialType(
|
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) version: number;
|
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) 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: 80 })
|
@ApiProperty({ minLength: 1, maxLength: MAX_CATEGORY_NAME_LENGTH })
|
||||||
@Transform(trim)
|
@Transform(trim)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(1)
|
@MinLength(1)
|
||||||
@MaxLength(80)
|
@MaxLength(MAX_CATEGORY_NAME_LENGTH)
|
||||||
name: string;
|
declare name: string;
|
||||||
}
|
}
|
||||||
export class UpdateExpenseCategoryDto extends CategoryNameDto {
|
export class UpdateExpenseCategoryDto extends CategoryNameDto {
|
||||||
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) version: number;
|
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) declare version: number;
|
||||||
}
|
}
|
||||||
export class CreateBankOperationDto {
|
export class CreateBankOperationDto {
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() id: string;
|
@ApiProperty({ format: 'uuid' }) @IsUUID() declare id: string;
|
||||||
@ApiProperty({ enum: bankOperationKinds })
|
@ApiProperty({ enum: bankOperationKinds })
|
||||||
@IsIn(bankOperationKinds)
|
@IsIn(bankOperationKinds)
|
||||||
kind: BankOperationKind;
|
declare kind: BankOperationKind;
|
||||||
@ApiProperty({ format: 'uuid' }) @IsUUID() 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()
|
||||||
@@ -116,22 +123,22 @@ export class CreateBankOperationDto {
|
|||||||
@IsDefined()
|
@IsDefined()
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@Type(() => RubMoneyInputDto)
|
@Type(() => RubMoneyInputDto)
|
||||||
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}$/)
|
||||||
date: string;
|
declare date: string;
|
||||||
@ApiPropertyOptional({ maxLength: 500 })
|
@ApiPropertyOptional({ maxLength: MAX_OPERATION_DESCRIPTION_LENGTH })
|
||||||
@ValidateIf((_object, value: unknown) => value !== undefined)
|
@ValidateIf((_object, value: unknown) => value !== undefined)
|
||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(500)
|
@MaxLength(MAX_OPERATION_DESCRIPTION_LENGTH)
|
||||||
description?: string;
|
description?: string;
|
||||||
}
|
}
|
||||||
export class UpdateBankOperationDto extends PartialType(
|
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) version: number;
|
@ApiProperty({ minimum: 1 }) @IsInt() @Min(1) declare version: number;
|
||||||
}
|
}
|
||||||
export class BankCardsQueryDto {
|
export class BankCardsQueryDto {
|
||||||
@ApiPropertyOptional({ enum: ['true', 'false'] })
|
@ApiPropertyOptional({ enum: ['true', 'false'] })
|
||||||
@@ -146,12 +153,16 @@ export class BankPageQueryDto {
|
|||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(1)
|
||||||
page?: number;
|
page?: number;
|
||||||
@ApiPropertyOptional({ minimum: 1, maximum: 100, default: 50 })
|
@ApiPropertyOptional({
|
||||||
|
minimum: 1,
|
||||||
|
maximum: MAX_BANK_PAGE_SIZE,
|
||||||
|
default: DEFAULT_BANK_PAGE_SIZE,
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(1)
|
||||||
@Max(100)
|
@Max(MAX_BANK_PAGE_SIZE)
|
||||||
limit?: number;
|
limit?: number;
|
||||||
}
|
}
|
||||||
export class BankPeriodQueryDto {
|
export class BankPeriodQueryDto {
|
||||||
@@ -192,68 +203,76 @@ export class BankVersionQueryDto {
|
|||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(1)
|
||||||
version: number;
|
declare version: number;
|
||||||
}
|
}
|
||||||
export class ExpenseCategoryDto {
|
export class ExpenseCategoryDto {
|
||||||
@ApiProperty({ type: String }) id: string;
|
@ApiProperty({ type: String }) declare id: string;
|
||||||
@ApiProperty({ type: String }) name: string;
|
@ApiProperty({ type: String }) declare name: string;
|
||||||
@ApiProperty({ type: Boolean }) isDefault: boolean;
|
@ApiProperty({ type: Boolean }) declare isDefault: boolean;
|
||||||
@ApiProperty({ type: Number }) version: number;
|
@ApiProperty({ type: Number }) declare version: number;
|
||||||
}
|
}
|
||||||
export class BankCardDto {
|
export class BankCardDto {
|
||||||
@ApiProperty({ type: String }) id: string;
|
@ApiProperty({ type: String }) declare id: string;
|
||||||
@ApiProperty({ type: String }) name: string;
|
@ApiProperty({ type: String }) declare name: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) bankName: string | null;
|
@ApiProperty({ type: String, nullable: true }) declare bankName:
|
||||||
@ApiProperty({ type: String, nullable: true }) lastFour: string | null;
|
|
||||||
@ApiProperty({ enum: bankPaymentSystems, nullable: true }) paymentSystem:
|
|
||||||
string | null;
|
string | null;
|
||||||
@ApiProperty({ type: MoneyDto }) openingBalance: MoneyDto;
|
@ApiProperty({ type: String, nullable: true }) declare lastFour:
|
||||||
@ApiProperty({ type: String }) openingDate: string;
|
string | null;
|
||||||
@ApiProperty({ type: MoneyDto }) balance: MoneyDto;
|
@ApiProperty({ enum: bankPaymentSystems, nullable: true })
|
||||||
@ApiProperty({ type: String, nullable: true }) archivedAt: string | null;
|
declare paymentSystem: string | null;
|
||||||
@ApiProperty({ type: Number }) version: number;
|
@ApiProperty({ type: MoneyDto }) declare openingBalance: MoneyDto;
|
||||||
|
@ApiProperty({ type: String }) declare openingDate: string;
|
||||||
|
@ApiProperty({ type: MoneyDto }) declare balance: MoneyDto;
|
||||||
|
@ApiProperty({ type: String, nullable: true }) declare archivedAt:
|
||||||
|
string | null;
|
||||||
|
@ApiProperty({ type: Number }) declare version: number;
|
||||||
}
|
}
|
||||||
export class BankOperationDto {
|
export class BankOperationDto {
|
||||||
@ApiProperty({ type: String }) id: string;
|
@ApiProperty({ type: String }) declare id: string;
|
||||||
@ApiProperty({ enum: bankOperationKinds }) kind: BankOperationKind;
|
@ApiProperty({ enum: bankOperationKinds }) declare kind: BankOperationKind;
|
||||||
@ApiProperty({ type: String }) cardId: string;
|
@ApiProperty({ type: String }) declare cardId: string;
|
||||||
@ApiProperty({ type: String }) cardName: string;
|
@ApiProperty({ type: String }) declare cardName: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) targetCardId: string | null;
|
@ApiProperty({ type: String, nullable: true }) declare targetCardId:
|
||||||
@ApiProperty({ type: String, nullable: true }) targetCardName: string | null;
|
|
||||||
@ApiProperty({ type: String, nullable: true }) categoryId: string | null;
|
|
||||||
@ApiProperty({ type: String, nullable: true }) categoryName: string | null;
|
|
||||||
@ApiProperty({ type: String, nullable: true }) originalExpenseId:
|
|
||||||
string | null;
|
string | null;
|
||||||
@ApiProperty({ type: MoneyDto }) amount: MoneyDto;
|
@ApiProperty({ type: String, nullable: true }) declare targetCardName:
|
||||||
|
string | null;
|
||||||
|
@ApiProperty({ type: String, nullable: true }) declare categoryId:
|
||||||
|
string | null;
|
||||||
|
@ApiProperty({ type: String, nullable: true }) declare categoryName:
|
||||||
|
string | null;
|
||||||
|
@ApiProperty({ type: String, nullable: true }) declare originalExpenseId:
|
||||||
|
string | null;
|
||||||
|
@ApiProperty({ type: MoneyDto }) declare amount: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto, nullable: true })
|
@ApiProperty({ type: MoneyDto, nullable: true })
|
||||||
availableRefund: MoneyDto | null;
|
declare availableRefund: MoneyDto | null;
|
||||||
@ApiProperty({ type: String }) date: string;
|
@ApiProperty({ type: String }) declare date: string;
|
||||||
@ApiProperty({ type: String, nullable: true }) description: string | null;
|
@ApiProperty({ type: String, nullable: true }) declare description:
|
||||||
@ApiProperty({ type: Number }) version: number;
|
string | null;
|
||||||
@ApiProperty({ type: String }) createdAt: string;
|
@ApiProperty({ type: Number }) declare version: number;
|
||||||
|
@ApiProperty({ type: String }) declare createdAt: string;
|
||||||
}
|
}
|
||||||
export class BankOperationsPageDto {
|
export class BankOperationsPageDto {
|
||||||
@ApiProperty({ type: BankOperationDto, isArray: true })
|
@ApiProperty({ type: BankOperationDto, isArray: true })
|
||||||
items: BankOperationDto[];
|
declare items: BankOperationDto[];
|
||||||
@ApiProperty({ type: Number }) page: number;
|
@ApiProperty({ type: Number }) declare page: number;
|
||||||
@ApiProperty({ type: Number }) total: number;
|
@ApiProperty({ type: Number }) declare total: number;
|
||||||
@ApiProperty({ type: Boolean }) hasNext: boolean;
|
@ApiProperty({ type: Boolean }) declare hasNext: boolean;
|
||||||
}
|
}
|
||||||
export class BankSummaryCategoryDto {
|
export class BankSummaryCategoryDto {
|
||||||
@ApiProperty({ type: String }) categoryId: string;
|
@ApiProperty({ type: String }) declare categoryId: string;
|
||||||
@ApiProperty({ type: String }) categoryName: string;
|
@ApiProperty({ type: String }) declare categoryName: string;
|
||||||
@ApiProperty({ type: MoneyDto }) expenses: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare expenses: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) refunds: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare refunds: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) net: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare net: MoneyDto;
|
||||||
}
|
}
|
||||||
export class BankSummaryDto {
|
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 }) cardId: string | null;
|
@ApiProperty({ type: String, nullable: true }) declare cardId: string | null;
|
||||||
@ApiProperty({ type: MoneyDto }) expenses: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare expenses: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) refunds: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare refunds: MoneyDto;
|
||||||
@ApiProperty({ type: MoneyDto }) net: MoneyDto;
|
@ApiProperty({ type: MoneyDto }) declare net: MoneyDto;
|
||||||
@ApiProperty({ type: BankSummaryCategoryDto, isArray: true })
|
@ApiProperty({ type: BankSummaryCategoryDto, isArray: true })
|
||||||
categories: BankSummaryCategoryDto[];
|
declare categories: BankSummaryCategoryDto[];
|
||||||
}
|
}
|
||||||
+30
-17
@@ -4,6 +4,7 @@ import {
|
|||||||
Delete,
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
HttpCode,
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
@@ -16,17 +17,16 @@ import {
|
|||||||
ApiCreatedResponse,
|
ApiCreatedResponse,
|
||||||
ApiNoContentResponse,
|
ApiNoContentResponse,
|
||||||
ApiOkResponse,
|
ApiOkResponse,
|
||||||
ApiTags,
|
|
||||||
ApiResponse,
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
getSchemaPath,
|
getSchemaPath,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import { AccessPayload } from '../auth/auth.types';
|
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
|
||||||
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 {
|
import {
|
||||||
BankCardDto,
|
BankCardDto,
|
||||||
BankCardsQueryDto,
|
BankCardsQueryDto,
|
||||||
@@ -45,7 +45,10 @@ import {
|
|||||||
UpdateBankOperationDto,
|
UpdateBankOperationDto,
|
||||||
UpdateExpenseCategoryDto,
|
UpdateExpenseCategoryDto,
|
||||||
} from './bank-card.dto';
|
} from './bank-card.dto';
|
||||||
import { BankCardsService } from './bank-cards.service';
|
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,
|
||||||
@@ -73,7 +76,12 @@ type AuthRequest = Request & { user: AccessPayload };
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Controller('bank-cards')
|
@Controller('bank-cards')
|
||||||
export class BankCardsController {
|
export class BankCardsController {
|
||||||
constructor(private readonly cards: BankCardsService) {}
|
constructor(
|
||||||
|
private readonly cards: BankCardsService,
|
||||||
|
private readonly operations: BankOperationsService,
|
||||||
|
private readonly expenseCategories: ExpenseCategoriesService,
|
||||||
|
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) {
|
||||||
@@ -87,12 +95,12 @@ export class BankCardsController {
|
|||||||
@Get('categories')
|
@Get('categories')
|
||||||
@ApiOkResponse({ type: ExpenseCategoryDto, isArray: true })
|
@ApiOkResponse({ type: ExpenseCategoryDto, isArray: true })
|
||||||
categories(@Req() req: AuthRequest) {
|
categories(@Req() req: AuthRequest) {
|
||||||
return this.cards.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.cards.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 })
|
||||||
@@ -101,12 +109,17 @@ export class BankCardsController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() body: UpdateExpenseCategoryDto,
|
@Body() body: UpdateExpenseCategoryDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.updateCategory(req.user.sub, id, body.name, body.version);
|
return this.expenseCategories.updateCategory(
|
||||||
|
req.user.sub,
|
||||||
|
id,
|
||||||
|
body.name,
|
||||||
|
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.cards.summary(req.user.sub, query);
|
return this.bankSummary.execute(req.user.sub, query);
|
||||||
}
|
}
|
||||||
@Post('operations')
|
@Post('operations')
|
||||||
@ApiCreatedResponse({ type: BankOperationDto })
|
@ApiCreatedResponse({ type: BankOperationDto })
|
||||||
@@ -114,12 +127,12 @@ export class BankCardsController {
|
|||||||
@Req() req: AuthRequest,
|
@Req() req: AuthRequest,
|
||||||
@Body() body: CreateBankOperationDto,
|
@Body() body: CreateBankOperationDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.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.cards.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 })
|
||||||
@@ -128,17 +141,17 @@ export class BankCardsController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() body: UpdateBankOperationDto,
|
@Body() body: UpdateBankOperationDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.updateOperation(req.user.sub, id, body);
|
return this.operations.updateOperation(req.user.sub, id, body);
|
||||||
}
|
}
|
||||||
@Delete('operations/:id')
|
@Delete('operations/:id')
|
||||||
@HttpCode(204)
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
@ApiNoContentResponse()
|
@ApiNoContentResponse()
|
||||||
deleteOperation(
|
deleteOperation(
|
||||||
@Req() req: AuthRequest,
|
@Req() req: AuthRequest,
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Query() query: BankVersionQueryDto,
|
@Query() query: BankVersionQueryDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.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 })
|
||||||
@@ -147,7 +160,7 @@ export class BankCardsController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Query() query: BankOperationsQueryDto,
|
@Query() query: BankOperationsQueryDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.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 })
|
||||||
@@ -156,7 +169,7 @@ export class BankCardsController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Query() query: BankPageQueryDto,
|
@Query() query: BankPageQueryDto,
|
||||||
) {
|
) {
|
||||||
return this.cards.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 })
|
||||||
+2
-2
@@ -3,8 +3,8 @@ import { ApiProperty } from '@nestjs/swagger';
|
|||||||
/** Source account of a row in an all-accounts response. */
|
/** Source account of a row in an all-accounts response. */
|
||||||
export class AccountReferenceDto {
|
export class AccountReferenceDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id: string;
|
declare id: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
name: string;
|
declare name: string;
|
||||||
}
|
}
|
||||||
@@ -3,14 +3,17 @@ import {
|
|||||||
ConflictException,
|
ConflictException,
|
||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
jest.mock('./tbank-access.service', () => ({ TbankAccessService: class {} }));
|
jest.mock('../../integrations/tbank/tbank-access.service', () => ({
|
||||||
|
TbankAccessService: class {},
|
||||||
|
}));
|
||||||
|
|
||||||
import { BrokerageOperationsService } from './brokerage-operations.service';
|
import type { TbankConnectionContext } from '../../integrations/tbank/tbank-access.service';
|
||||||
import { IncomeAnalyticsService } from './income-analytics.service';
|
import { IncomeAnalyticsService } from './income/income-analytics.service';
|
||||||
import { PortfolioService } from './portfolio.service';
|
import { BrokerageOperationsService } from './operations/application/brokerage-operations.service';
|
||||||
import { UpcomingEventsService } from './upcoming-events.service';
|
import { PortfolioService } from './portfolio/application/portfolio.service';
|
||||||
import type { TbankConnectionContext } from './tbank-access.service';
|
import { UpcomingEventsService } from './upcoming-events/upcoming-events.service';
|
||||||
|
|
||||||
function setup() {
|
function setup() {
|
||||||
const context = {
|
const context = {
|
||||||
@@ -130,6 +133,7 @@ describe('All accounts', () => {
|
|||||||
instrumentUid: 'common',
|
instrumentUid: 'common',
|
||||||
limit: 1,
|
limit: 1,
|
||||||
});
|
});
|
||||||
|
assert.ok(first.nextCursor);
|
||||||
expect(first.items).toHaveLength(1);
|
expect(first.items).toHaveLength(1);
|
||||||
expect(first.items[0].instrumentUid).toBe('common');
|
expect(first.items[0].instrumentUid).toBe('common');
|
||||||
expect(tbank.getOperationsByCursor).toHaveBeenCalledWith(
|
expect(tbank.getOperationsByCursor).toHaveBeenCalledWith(
|
||||||
@@ -143,13 +147,13 @@ describe('All accounts', () => {
|
|||||||
operations.getAll('user', {
|
operations.getAll('user', {
|
||||||
instrumentUid: 'preferred',
|
instrumentUid: 'preferred',
|
||||||
limit: 1,
|
limit: 1,
|
||||||
cursor: first.nextCursor!,
|
cursor: first.nextCursor,
|
||||||
}),
|
}),
|
||||||
).rejects.toBeInstanceOf(BadRequestException);
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
const second = await operations.getAll('user', {
|
const second = await operations.getAll('user', {
|
||||||
instrumentUid: 'common',
|
instrumentUid: 'common',
|
||||||
limit: 1,
|
limit: 1,
|
||||||
cursor: first.nextCursor!,
|
cursor: first.nextCursor,
|
||||||
});
|
});
|
||||||
expect(second.items[0].instrumentUid).toBe('common');
|
expect(second.items[0].instrumentUid).toBe('common');
|
||||||
expect(second.items[0].id).not.toBe(first.items[0].id);
|
expect(second.items[0].id).not.toBe(first.items[0].id);
|
||||||
@@ -246,17 +250,19 @@ describe('All accounts', () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
const first = await operations.getAll('user', query);
|
const first = await operations.getAll('user', query);
|
||||||
|
assert.ok(first.nextCursor);
|
||||||
const second = await operations.getAll('user', {
|
const second = await operations.getAll('user', {
|
||||||
...query,
|
...query,
|
||||||
cursor: first.nextCursor!,
|
cursor: first.nextCursor,
|
||||||
});
|
});
|
||||||
const repeated = await operations.getAll('user', {
|
const repeated = await operations.getAll('user', {
|
||||||
...query,
|
...query,
|
||||||
cursor: first.nextCursor!,
|
cursor: first.nextCursor,
|
||||||
});
|
});
|
||||||
|
assert.ok(second.nextCursor);
|
||||||
const third = await operations.getAll('user', {
|
const third = await operations.getAll('user', {
|
||||||
...query,
|
...query,
|
||||||
cursor: second.nextCursor!,
|
cursor: second.nextCursor,
|
||||||
});
|
});
|
||||||
expect(first.items.map((item) => [item.id, item.account?.id])).toEqual([
|
expect(first.items.map((item) => [item.id, item.account?.id])).toEqual([
|
||||||
['same', 'a'],
|
['same', 'a'],
|
||||||
@@ -312,7 +318,8 @@ describe('All accounts', () => {
|
|||||||
items: [operation('first', 8), operation('last', 4)],
|
items: [operation('first', 8), operation('last', 4)],
|
||||||
});
|
});
|
||||||
const first = await operations.getAll('user', query);
|
const first = await operations.getAll('user', query);
|
||||||
const next = { ...query, cursor: first.nextCursor! };
|
assert.ok(first.nextCursor);
|
||||||
|
const next = { ...query, cursor: first.nextCursor };
|
||||||
await expect(operations.getAll('other', next)).rejects.toBeInstanceOf(
|
await expect(operations.getAll('other', next)).rejects.toBeInstanceOf(
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
);
|
);
|
||||||
+8
-8
@@ -1,31 +1,31 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { MoneyDto } from '../common/money.dto';
|
import { MoneyDto } from '../../../common/money.dto';
|
||||||
|
|
||||||
export class PortfolioSummaryDto {
|
export class PortfolioSummaryDto {
|
||||||
@ApiProperty({ type: MoneyDto, isArray: true })
|
@ApiProperty({ type: MoneyDto, isArray: true })
|
||||||
totalsByCurrency: MoneyDto[];
|
declare totalsByCurrency: MoneyDto[];
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
type: 'integer',
|
type: 'integer',
|
||||||
minimum: 0,
|
minimum: 0,
|
||||||
description: 'Number of non-zero stock positions, not the number of units.',
|
description: 'Number of non-zero stock positions, not the number of units.',
|
||||||
})
|
})
|
||||||
stockPositionCount: number;
|
declare stockPositionCount: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
type: 'integer',
|
type: 'integer',
|
||||||
minimum: 0,
|
minimum: 0,
|
||||||
description: 'Number of non-zero bond positions, not the number of units.',
|
description: 'Number of non-zero bond positions, not the number of units.',
|
||||||
})
|
})
|
||||||
bondPositionCount: number;
|
declare bondPositionCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BrokerageAccountDto {
|
export class BrokerageAccountDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id: string;
|
declare id: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
name: string;
|
declare name: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
enum: [
|
enum: [
|
||||||
@@ -35,11 +35,11 @@ export class BrokerageAccountDto {
|
|||||||
'MONEY_MARKET_FUND',
|
'MONEY_MARKET_FUND',
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
type:
|
declare type:
|
||||||
'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' })
|
||||||
openedOn: string | null;
|
declare openedOn: string | null;
|
||||||
|
|
||||||
@ApiProperty({ type: PortfolioSummaryDto, nullable: true })
|
@ApiProperty({ type: PortfolioSummaryDto, nullable: true })
|
||||||
portfolioSummary?: PortfolioSummaryDto | null;
|
portfolioSummary?: PortfolioSummaryDto | null;
|
||||||
+2
-3
@@ -1,9 +1,8 @@
|
|||||||
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
|
import { Controller, Get, 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 type { Request } from 'express';
|
||||||
import { AccessPayload } from '../auth/auth.types';
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
||||||
import { ApiProblemResponses } from '../common/decorators/api-safe-error-response.decorator';
|
|
||||||
import { BrokerageAccountDto } from './brokerage-account.dto';
|
import { BrokerageAccountDto } from './brokerage-account.dto';
|
||||||
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TbankModule } from '../../../integrations/tbank/tbank.module';
|
||||||
|
import { AuthModule } from '../../auth/auth.module';
|
||||||
|
import { BrokerageAccountsController } from './brokerage-accounts.controller';
|
||||||
|
import { BrokerageAccountsService } from './brokerage-accounts.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule, TbankModule],
|
||||||
|
controllers: [BrokerageAccountsController],
|
||||||
|
providers: [BrokerageAccountsService],
|
||||||
|
})
|
||||||
|
export class BrokerageAccountsModule {}
|
||||||
+3
-3
@@ -4,13 +4,13 @@ import {
|
|||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
|
||||||
jest.mock('../prisma/prisma.service', () => ({
|
jest.mock('../../../prisma/prisma.service', () => ({
|
||||||
PrismaService: class PrismaService {},
|
PrismaService: class PrismaService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
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';
|
||||||
import { TbankAccessService } from './tbank-access.service';
|
|
||||||
import { TbankTokenService } from './tbank-token.service';
|
|
||||||
|
|
||||||
describe('BrokerageAccountsService', () => {
|
describe('BrokerageAccountsService', () => {
|
||||||
const encryptionKey = 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=';
|
const encryptionKey = 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=';
|
||||||
+8
-7
@@ -1,11 +1,12 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
import { isZero } from '../../../common/decimal';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
TbankClient,
|
||||||
|
} 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';
|
||||||
import { isZero } from '../common/decimal';
|
|
||||||
import { decimal } from './decimal';
|
|
||||||
import { totalsByCurrency } from './portfolio-totals';
|
|
||||||
import { TbankAccessService } from './tbank-access.service';
|
|
||||||
import { TbankClient } from './tbank.client';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BrokerageAccountsService {
|
export class BrokerageAccountsService {
|
||||||
+2
-3
@@ -1,9 +1,8 @@
|
|||||||
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 type { Request } from 'express';
|
||||||
import { AccessPayload } from '../auth/auth.types';
|
import { ApiProblemResponses } from '../../../common/decorators/api-safe-error-response.decorator';
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { AccessPayload, JwtAuthGuard } from '../../auth/auth.api';
|
||||||
import { ApiProblemResponses } from '../common/decorators/api-safe-error-response.decorator';
|
|
||||||
import {
|
import {
|
||||||
IncomeAnalyticsDto,
|
IncomeAnalyticsDto,
|
||||||
IncomeAnalyticsQueryDto,
|
IncomeAnalyticsQueryDto,
|
||||||
+37
-37
@@ -1,7 +1,7 @@
|
|||||||
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 { BrokerageOperationDto } from './brokerage-operation.dto';
|
import { MoneyDto } from '../../../common/money.dto';
|
||||||
import { MoneyDto } from '../common/money.dto';
|
import { BrokerageOperationDto } from '../operations/operations.api';
|
||||||
|
|
||||||
const dateOnly = /^\d{4}-\d{2}-\d{2}$/;
|
const dateOnly = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
@@ -19,123 +19,123 @@ export class IncomeAnalyticsQueryDto {
|
|||||||
|
|
||||||
export class IncomePeriodDto {
|
export class IncomePeriodDto {
|
||||||
@ApiProperty({ format: 'date' })
|
@ApiProperty({ format: 'date' })
|
||||||
from: string;
|
declare from: string;
|
||||||
|
|
||||||
@ApiProperty({ format: 'date' })
|
@ApiProperty({ format: 'date' })
|
||||||
to: string;
|
declare to: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeCurrencySummaryDto {
|
export class IncomeCurrencySummaryDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
currency: string;
|
declare currency: string;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
coupon: MoneyDto;
|
declare coupon: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
dividend: MoneyDto;
|
declare dividend: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
total: MoneyDto;
|
declare total: MoneyDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeSummaryDto {
|
export class IncomeSummaryDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
accountId: string;
|
declare accountId: string;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomePeriodDto })
|
@ApiProperty({ type: IncomePeriodDto })
|
||||||
period: IncomePeriodDto;
|
declare period: IncomePeriodDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeCurrencySummaryDto, isArray: true })
|
@ApiProperty({ type: IncomeCurrencySummaryDto, isArray: true })
|
||||||
totalsByCurrency: IncomeCurrencySummaryDto[];
|
declare totalsByCurrency: IncomeCurrencySummaryDto[];
|
||||||
|
|
||||||
@ApiProperty({ format: 'date-time' })
|
@ApiProperty({ format: 'date-time' })
|
||||||
calculatedAt: string;
|
declare calculatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeComparisonCurrencyDto {
|
export class IncomeComparisonCurrencyDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
currency: string;
|
declare currency: string;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
||||||
selected: IncomeCurrencySummaryDto;
|
declare selected: IncomeCurrencySummaryDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
||||||
compared: IncomeCurrencySummaryDto;
|
declare compared: IncomeCurrencySummaryDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
@ApiProperty({ type: IncomeCurrencySummaryDto })
|
||||||
difference: IncomeCurrencySummaryDto;
|
declare difference: IncomeCurrencySummaryDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeComparisonDto {
|
export class IncomeComparisonDto {
|
||||||
@ApiProperty({ type: IncomePeriodDto })
|
@ApiProperty({ type: IncomePeriodDto })
|
||||||
period: IncomePeriodDto;
|
declare period: IncomePeriodDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeComparisonCurrencyDto, isArray: true })
|
@ApiProperty({ type: IncomeComparisonCurrencyDto, isArray: true })
|
||||||
totalsByCurrency: IncomeComparisonCurrencyDto[];
|
declare totalsByCurrency: IncomeComparisonCurrencyDto[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeBucketDto {
|
export class IncomeBucketDto {
|
||||||
@ApiProperty({ type: IncomePeriodDto })
|
@ApiProperty({ type: IncomePeriodDto })
|
||||||
period: IncomePeriodDto;
|
declare period: IncomePeriodDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeCurrencySummaryDto, isArray: true })
|
@ApiProperty({ type: IncomeCurrencySummaryDto, isArray: true })
|
||||||
totalsByCurrency: IncomeCurrencySummaryDto[];
|
declare totalsByCurrency: IncomeCurrencySummaryDto[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeInstrumentDto {
|
export class IncomeInstrumentDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
key: string;
|
declare key: string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
figi: string | null;
|
declare figi: string | null;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
instrumentUid: string | null;
|
declare instrumentUid: string | null;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
ticker: string | null;
|
declare ticker: string | null;
|
||||||
|
|
||||||
@ApiProperty({ type: String, nullable: true })
|
@ApiProperty({ type: String, nullable: true })
|
||||||
instrumentType: string | null;
|
declare instrumentType: string | null;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
displayName: string;
|
declare displayName: string;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
coupon: MoneyDto;
|
declare coupon: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
dividend: MoneyDto;
|
declare dividend: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty({ type: MoneyDto })
|
@ApiProperty({ type: MoneyDto })
|
||||||
total: MoneyDto;
|
declare total: MoneyDto;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
receiptCount: number;
|
declare receiptCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeAnalyticsEntryDto extends BrokerageOperationDto {
|
export class IncomeAnalyticsEntryDto extends BrokerageOperationDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
instrumentKey: string;
|
declare instrumentKey: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IncomeAnalyticsDto extends IncomeSummaryDto {
|
export class IncomeAnalyticsDto extends IncomeSummaryDto {
|
||||||
@ApiProperty({ type: IncomeComparisonDto })
|
@ApiProperty({ type: IncomeComparisonDto })
|
||||||
previous: IncomeComparisonDto;
|
declare previous: IncomeComparisonDto;
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeComparisonDto, nullable: true })
|
@ApiProperty({ type: IncomeComparisonDto, nullable: true })
|
||||||
yearComparison: IncomeComparisonDto | null;
|
declare yearComparison: IncomeComparisonDto | null;
|
||||||
|
|
||||||
@ApiProperty({ enum: ['day', 'week', 'month'] })
|
@ApiProperty({ enum: ['day', 'week', 'month'] })
|
||||||
bucketGranularity: 'day' | 'week' | 'month';
|
declare bucketGranularity: 'day' | 'week' | 'month';
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeBucketDto, isArray: true })
|
@ApiProperty({ type: IncomeBucketDto, isArray: true })
|
||||||
buckets: IncomeBucketDto[];
|
declare buckets: IncomeBucketDto[];
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeInstrumentDto, isArray: true })
|
@ApiProperty({ type: IncomeInstrumentDto, isArray: true })
|
||||||
instruments: IncomeInstrumentDto[];
|
declare instruments: IncomeInstrumentDto[];
|
||||||
|
|
||||||
@ApiProperty({ type: IncomeAnalyticsEntryDto, isArray: true })
|
@ApiProperty({ type: IncomeAnalyticsEntryDto, isArray: true })
|
||||||
entries: IncomeAnalyticsEntryDto[];
|
declare entries: IncomeAnalyticsEntryDto[];
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
jest.mock('./brokerage-operations.service', () => ({
|
jest.mock('../operations/application/brokerage-operations.service', () => ({
|
||||||
BrokerageOperationsService: class BrokerageOperationsService {},
|
BrokerageOperationsService: class BrokerageOperationsService {},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
import { BrokerageOperationDto } from './brokerage-operation.dto';
|
import { BrokerageOperationDto } from '../operations/presentation/brokerage-operation.dto';
|
||||||
import { IncomeAnalyticsService } from './income-analytics.service';
|
import { IncomeAnalyticsService } from './income-analytics.service';
|
||||||
|
|
||||||
describe('IncomeAnalyticsService', () => {
|
describe('IncomeAnalyticsService', () => {
|
||||||
+11
-10
@@ -1,21 +1,17 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { BrokerageOperationDto } from './brokerage-operation.dto';
|
|
||||||
import { BrokerageOperationsService } from './brokerage-operations.service';
|
|
||||||
import {
|
import {
|
||||||
add,
|
add,
|
||||||
compare,
|
compare,
|
||||||
decimalFromString,
|
decimalFromString,
|
||||||
formatDecimal,
|
formatDecimal,
|
||||||
subtract,
|
subtract,
|
||||||
} from '../common/decimal';
|
} from '../../../common/decimal';
|
||||||
|
import { DateOnlyRange, moscowDate } from '../investment-calendar';
|
||||||
import {
|
import {
|
||||||
DateOnlyRange,
|
BrokerageOperationDto,
|
||||||
IncomeBucketGranularity,
|
BrokerageOperationsService,
|
||||||
moscowDate,
|
} from '../operations/operations.api';
|
||||||
planIncomePeriod,
|
|
||||||
rangeBuckets,
|
|
||||||
} from './income-period';
|
|
||||||
import {
|
import {
|
||||||
IncomeAnalyticsDto,
|
IncomeAnalyticsDto,
|
||||||
IncomeAnalyticsEntryDto,
|
IncomeAnalyticsEntryDto,
|
||||||
@@ -24,6 +20,11 @@ import {
|
|||||||
IncomeInstrumentDto,
|
IncomeInstrumentDto,
|
||||||
IncomeSummaryDto,
|
IncomeSummaryDto,
|
||||||
} from './income-analytics.dto';
|
} from './income-analytics.dto';
|
||||||
|
import {
|
||||||
|
IncomeBucketGranularity,
|
||||||
|
planIncomePeriod,
|
||||||
|
rangeBuckets,
|
||||||
|
} from './income-period';
|
||||||
|
|
||||||
type Total = {
|
type Total = {
|
||||||
coupon: ReturnType<typeof decimalFromString>;
|
coupon: ReturnType<typeof decimalFromString>;
|
||||||
+2
-5
@@ -1,9 +1,6 @@
|
|||||||
import { BadRequestException } from '@nestjs/common';
|
import { BadRequestException } from '@nestjs/common';
|
||||||
import {
|
import { dateOnlyBounds } from '../investment-calendar';
|
||||||
dateOnlyBounds,
|
import { planIncomePeriod, rangeBuckets } from './income-period';
|
||||||
planIncomePeriod,
|
|
||||||
rangeBuckets,
|
|
||||||
} from './income-period';
|
|
||||||
|
|
||||||
describe('income period planning', () => {
|
describe('income period planning', () => {
|
||||||
afterEach(() => jest.useRealTimers());
|
afterEach(() => jest.useRealTimers());
|
||||||
@@ -1,10 +1,20 @@
|
|||||||
|
import { MILLISECONDS_PER_DAY } from '../../../common/time';
|
||||||
import { BadRequestException } from '@nestjs/common';
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
DateOnlyRange,
|
||||||
|
dateParts,
|
||||||
|
moscowDate,
|
||||||
|
utcDate,
|
||||||
|
} from '../investment-calendar';
|
||||||
|
|
||||||
|
const DAILY_BUCKET_MAX_DAYS = 45;
|
||||||
|
const WEEKLY_BUCKET_MAX_DAYS = 180;
|
||||||
|
const DAYS_PER_WEEK = 7;
|
||||||
|
const ISO_MONTH_LENGTH = 7;
|
||||||
|
const ISO_YEAR_LENGTH = 4;
|
||||||
|
|
||||||
export type DateOnlyRange = { from: string; to: string };
|
|
||||||
export type IncomeBucketGranularity = 'day' | 'week' | 'month';
|
export type IncomeBucketGranularity = 'day' | 'week' | 'month';
|
||||||
|
|
||||||
const moscow = 'Europe/Moscow';
|
|
||||||
|
|
||||||
export function planIncomePeriod(
|
export function planIncomePeriod(
|
||||||
from: string | undefined,
|
from: string | undefined,
|
||||||
to: string | undefined,
|
to: string | undefined,
|
||||||
@@ -33,35 +43,14 @@ export function planIncomePeriod(
|
|||||||
previous,
|
previous,
|
||||||
yearAgo: yearAgoRange,
|
yearAgo: yearAgoRange,
|
||||||
granularity:
|
granularity:
|
||||||
rangeDays(selected) <= 45
|
rangeDays(selected) <= DAILY_BUCKET_MAX_DAYS
|
||||||
? 'day'
|
? 'day'
|
||||||
: rangeDays(selected) <= 180
|
: rangeDays(selected) <= WEEKLY_BUCKET_MAX_DAYS
|
||||||
? 'week'
|
? 'week'
|
||||||
: 'month',
|
: 'month',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function moscowDate(value: Date): string {
|
|
||||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
||||||
timeZone: moscow,
|
|
||||||
year: 'numeric',
|
|
||||||
month: '2-digit',
|
|
||||||
day: '2-digit',
|
|
||||||
}).formatToParts(value);
|
|
||||||
const get = (type: string) => parts.find((part) => part.type === type)?.value;
|
|
||||||
return `${get('year')}-${get('month')}-${get('day')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function dateOnlyBounds(range: DateOnlyRange): { from: Date; to: Date } {
|
|
||||||
const from = dateParts(range.from);
|
|
||||||
const end = dateParts(range.to);
|
|
||||||
const to = new Date(Date.UTC(end[0], end[1] - 1, end[2], 20, 59, 59, 999));
|
|
||||||
return {
|
|
||||||
from: new Date(Date.UTC(from[0], from[1] - 1, from[2], -3)),
|
|
||||||
to: to > new Date() ? new Date() : to,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function rangeBuckets(
|
export function rangeBuckets(
|
||||||
range: DateOnlyRange,
|
range: DateOnlyRange,
|
||||||
granularity: IncomeBucketGranularity,
|
granularity: IncomeBucketGranularity,
|
||||||
@@ -71,11 +60,19 @@ export function rangeBuckets(
|
|||||||
const buckets: DateOnlyRange[] = [];
|
const buckets: DateOnlyRange[] = [];
|
||||||
let cursor =
|
let cursor =
|
||||||
granularity === 'week'
|
granularity === 'week'
|
||||||
? addDays(range.from, -((utcDate(range.from).getUTCDay() + 6) % 7))
|
? addDays(
|
||||||
: `${range.from.slice(0, 7)}-01`;
|
range.from,
|
||||||
|
-(
|
||||||
|
(utcDate(range.from).getUTCDay() + DAYS_PER_WEEK - 1) %
|
||||||
|
DAYS_PER_WEEK
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: `${range.from.slice(0, ISO_MONTH_LENGTH)}-01`;
|
||||||
while (cursor <= range.to) {
|
while (cursor <= range.to) {
|
||||||
const end =
|
const end =
|
||||||
granularity === 'week' ? addDays(cursor, 6) : endOfMonth(cursor);
|
granularity === 'week'
|
||||||
|
? addDays(cursor, DAYS_PER_WEEK - 1)
|
||||||
|
: 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,
|
||||||
@@ -89,7 +86,7 @@ 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()) /
|
||||||
86_400_000,
|
MILLISECONDS_PER_DAY,
|
||||||
) + 1
|
) + 1
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -104,27 +101,6 @@ function assertRange(range: DateOnlyRange, today: string): void {
|
|||||||
if (range.from > range.to || range.to > today) throw invalidPeriod();
|
if (range.from > range.to || range.to > today) throw invalidPeriod();
|
||||||
}
|
}
|
||||||
|
|
||||||
function dateParts(value: string): [number, number, number] {
|
|
||||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
||||||
if (!match) throw new Error('Invalid date');
|
|
||||||
const parts = [Number(match[1]), Number(match[2]), Number(match[3])] as [
|
|
||||||
number,
|
|
||||||
number,
|
|
||||||
number,
|
|
||||||
];
|
|
||||||
if (utcDate(value).toISOString().slice(0, 10) !== value)
|
|
||||||
throw new Error('Invalid date');
|
|
||||||
return parts;
|
|
||||||
}
|
|
||||||
|
|
||||||
function utcDate(value: string): Date {
|
|
||||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
||||||
if (!match) return new Date(NaN);
|
|
||||||
return new Date(
|
|
||||||
Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
||||||
@@ -139,7 +115,7 @@ function dates(range: DateOnlyRange): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function firstOfMonth(value: string): string {
|
function firstOfMonth(value: string): string {
|
||||||
return `${value.slice(0, 7)}-01`;
|
return `${value.slice(0, ISO_MONTH_LENGTH)}-01`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function endOfMonth(value: string): string {
|
function endOfMonth(value: string): string {
|
||||||
@@ -165,7 +141,7 @@ 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(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
const result = `${String(year - 1).padStart(ISO_YEAR_LENGTH, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
||||||
return utcDate(result).toISOString().slice(0, 10) === result
|
return utcDate(result).toISOString().slice(0, 10) === result
|
||||||
? result
|
? result
|
||||||
: null;
|
: null;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuthModule } from '../../auth/auth.module';
|
||||||
|
import { OperationsModule } from '../operations/operations.module';
|
||||||
|
import { IncomeAnalyticsController } from './income-analytics.controller';
|
||||||
|
import { IncomeAnalyticsService } from './income-analytics.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule, OperationsModule],
|
||||||
|
controllers: [IncomeAnalyticsController],
|
||||||
|
providers: [IncomeAnalyticsService],
|
||||||
|
})
|
||||||
|
export class IncomeModule {}
|
||||||
+11
-4
@@ -1,14 +1,21 @@
|
|||||||
|
import { MILLISECONDS_PER_SECOND } from '../../../../common/time';
|
||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
import { ServiceUnavailableException } from '@nestjs/common';
|
||||||
import type { TbankTimestamp } from './tbank.client';
|
import type {
|
||||||
import type { TbankCandle } from './tbank-market.types';
|
TbankCandle,
|
||||||
|
TbankTimestamp,
|
||||||
|
} from '../../../../integrations/tbank/tbank.api';
|
||||||
|
|
||||||
|
const MOSCOW_OFFSET_MS = 10_800_000;
|
||||||
export function timestamp(value?: TbankTimestamp): string | null {
|
export function timestamp(value?: TbankTimestamp): string | null {
|
||||||
const seconds = Number(value?.seconds);
|
const seconds = Number(value?.seconds);
|
||||||
return Number.isFinite(seconds) && seconds > 0
|
return Number.isFinite(seconds) && seconds > 0
|
||||||
? new Date(seconds * 1000).toISOString()
|
? new Date(seconds * MILLISECONDS_PER_SECOND).toISOString()
|
||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
export function moscowDay(iso: string): string {
|
export function moscowDay(iso: string): string {
|
||||||
return new Date(Date.parse(iso) + 3 * 3_600_000).toISOString().slice(0, 10);
|
return new Date(Date.parse(iso) + MOSCOW_OFFSET_MS)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 10);
|
||||||
}
|
}
|
||||||
export function previousClose(
|
export function previousClose(
|
||||||
candles: TbankCandle[],
|
candles: TbankCandle[],
|
||||||
+21
-8
@@ -4,11 +4,17 @@ import {
|
|||||||
divide,
|
divide,
|
||||||
formatDecimal,
|
formatDecimal,
|
||||||
multiply,
|
multiply,
|
||||||
} from '../common/decimal';
|
} from '../../../../common/decimal';
|
||||||
|
|
||||||
import { MoneyDto } from '../common/money.dto';
|
import { MoneyDto } from '../../../../common/money.dto';
|
||||||
import { PortfolioDto, PortfolioPositionDto } from './portfolio.dto';
|
import {
|
||||||
import { StockPositionDto } from './stock.dto';
|
PortfolioDto,
|
||||||
|
PortfolioPositionDto,
|
||||||
|
} from '../../portfolio/portfolio.api';
|
||||||
|
import { StockPositionDto } from '../stocks/presentation/stock.dto';
|
||||||
|
|
||||||
|
const PRICE_DECIMAL_PLACES = 9;
|
||||||
|
const RETURN_PERCENT_DECIMAL_PLACES = 6;
|
||||||
|
|
||||||
export function instrumentPosition(
|
export function instrumentPosition(
|
||||||
portfolio: PortfolioDto,
|
portfolio: PortfolioDto,
|
||||||
@@ -38,7 +44,11 @@ export function instrumentPosition(
|
|||||||
? {
|
? {
|
||||||
currency: totalCost.currency,
|
currency: totalCost.currency,
|
||||||
value: formatDecimal(
|
value: formatDecimal(
|
||||||
divide(decimalFromString(totalCost.value), quantity, 9),
|
divide(
|
||||||
|
decimalFromString(totalCost.value),
|
||||||
|
quantity,
|
||||||
|
PRICE_DECIMAL_PLACES,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
@@ -70,13 +80,16 @@ function cost(position: PortfolioPositionDto): MoneyDto | null {
|
|||||||
}
|
}
|
||||||
function sumComplete(values: (MoneyDto | null)[]): MoneyDto | null {
|
function sumComplete(values: (MoneyDto | null)[]): MoneyDto | null {
|
||||||
const currency = values[0]?.currency;
|
const currency = values[0]?.currency;
|
||||||
if (!currency || values.some((v) => !v || v.currency !== currency))
|
if (
|
||||||
|
!currency ||
|
||||||
|
!values.every((v): v is MoneyDto => v !== null && v.currency === currency)
|
||||||
|
)
|
||||||
return null;
|
return null;
|
||||||
return {
|
return {
|
||||||
currency,
|
currency,
|
||||||
value: formatDecimal(
|
value: formatDecimal(
|
||||||
values.reduce(
|
values.reduce(
|
||||||
(sum, value) => add(sum, decimalFromString(value!.value)),
|
(sum, value) => add(sum, decimalFromString(value.value)),
|
||||||
decimalFromString('0'),
|
decimalFromString('0'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -97,7 +110,7 @@ function percent(
|
|||||||
divide(
|
divide(
|
||||||
multiply(decimalFromString(result.value), decimalFromString('100')),
|
multiply(decimalFromString(result.value), decimalFromString('100')),
|
||||||
decimalFromString(base.value),
|
decimalFromString(base.value),
|
||||||
6,
|
RETURN_PERCENT_DECIMAL_PLACES,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
ServiceUnavailableException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { LRUCache } from 'lru-cache';
|
||||||
|
import { formatDecimal } from '../../../../../common/decimal';
|
||||||
|
import type { TbankBond } from '../../../../../integrations/tbank/tbank.api';
|
||||||
|
import {
|
||||||
|
TbankAccessService,
|
||||||
|
TbankClient,
|
||||||
|
type TbankConnectionContext,
|
||||||
|
} from '../../../../../integrations/tbank/tbank.api';
|
||||||
|
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||||
|
import { optional, timestamp } from '../../application/instrument-market';
|
||||||
|
import { BondDto, BondSearchResultDto } from '../presentation/bond.dto';
|
||||||
|
|
||||||
|
type IdentifiedBond = TbankBond & { uid: string };
|
||||||
|
|
||||||
|
import { money } from '../infrastructure/bond-money.mapper';
|
||||||
|
|
||||||
|
const SEARCH_RESULTS_LIMIT = 30;
|
||||||
|
@Injectable()
|
||||||
|
export class BondCatalogService {
|
||||||
|
private readonly cache = new LRUCache<string, Promise<object>>({
|
||||||
|
max: 300,
|
||||||
|
ttl: 30_000,
|
||||||
|
});
|
||||||
|
constructor(
|
||||||
|
private readonly access: TbankAccessService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
) {}
|
||||||
|
search(userId: string, query: string): Promise<BondSearchResultDto[]> {
|
||||||
|
return this.cached(userId, `search:${query}`, async (connection) => {
|
||||||
|
const { token } = connection;
|
||||||
|
const found = await this.tbank.findBonds(token, query);
|
||||||
|
const bonds = selectBonds(found, query).slice(0, SEARCH_RESULTS_LIMIT);
|
||||||
|
if (!bonds.length) return [];
|
||||||
|
// Batch prices and share metadata with detail sections. Resolve readable
|
||||||
|
// aliases only when an issue is opened, not for every search result.
|
||||||
|
const [details, prices] = await Promise.all([
|
||||||
|
Promise.all(
|
||||||
|
bonds.map(
|
||||||
|
async (bond) =>
|
||||||
|
(await optional(
|
||||||
|
() =>
|
||||||
|
this.bond(userId, connection, bond.uid)
|
||||||
|
.then(toBond)
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (error instanceof NotFoundException)
|
||||||
|
return toBond(bond);
|
||||||
|
throw error;
|
||||||
|
}),
|
||||||
|
'details',
|
||||||
|
[],
|
||||||
|
)) ?? toBond(bond),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
optional(
|
||||||
|
() =>
|
||||||
|
this.tbank.getLastPrices(
|
||||||
|
token,
|
||||||
|
bonds.map((bond) => bond.uid),
|
||||||
|
),
|
||||||
|
'prices',
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
return details.map((detail, index) => {
|
||||||
|
const short = toBond(bonds[index]);
|
||||||
|
const last = prices?.find(
|
||||||
|
(price) => price.instrumentUid === detail.instrumentUid,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...detail,
|
||||||
|
classCode: detail.classCode ?? short.classCode,
|
||||||
|
isin: detail.isin ?? short.isin,
|
||||||
|
apiTradeAvailable: short.apiTradeAvailable,
|
||||||
|
pricePercent: last?.price ? formatDecimal(decimal(last.price)) : null,
|
||||||
|
priceAt: timestamp(last?.time),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
get(userId: string, uid: string): Promise<BondDto> {
|
||||||
|
return this.cached(userId, `bond:${uid}`, async (connection) => {
|
||||||
|
const result = toBond(await this.bond(userId, connection, uid));
|
||||||
|
if (
|
||||||
|
!result.ticker ||
|
||||||
|
!/^[A-Za-z0-9][A-Za-z0-9._@+-]{0,79}$/.test(result.ticker)
|
||||||
|
)
|
||||||
|
return result;
|
||||||
|
try {
|
||||||
|
const match = await this.tickerMatch(userId, result.ticker);
|
||||||
|
if (match.uid === uid) result.slug = result.ticker.toUpperCase();
|
||||||
|
} catch (error) {
|
||||||
|
// A readable alias is optional for an exact UID URL, never a reason to substitute another listing.
|
||||||
|
if (
|
||||||
|
!(error instanceof NotFoundException) &&
|
||||||
|
!(error instanceof ConflictException) &&
|
||||||
|
!(error instanceof ServiceUnavailableException)
|
||||||
|
)
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async getByTicker(userId: string, ticker: string): Promise<BondDto> {
|
||||||
|
const match = await this.tickerMatch(userId, ticker);
|
||||||
|
return {
|
||||||
|
...(await this.get(userId, match.uid)),
|
||||||
|
slug: ticker.trim().toUpperCase(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private tickerMatch(userId: string, ticker: string): Promise<IdentifiedBond> {
|
||||||
|
const normalized = ticker.trim().toUpperCase();
|
||||||
|
return this.cached(userId, `ticker:${normalized}`, async (connection) => {
|
||||||
|
const { token } = connection;
|
||||||
|
const found = await this.tbank.findBonds(token, normalized);
|
||||||
|
const matches = selectBonds(
|
||||||
|
found.filter(
|
||||||
|
(item) => item.ticker?.trim().toUpperCase() === normalized,
|
||||||
|
),
|
||||||
|
normalized,
|
||||||
|
);
|
||||||
|
if (!matches.length) throw new NotFoundException();
|
||||||
|
if (matches.length > 1)
|
||||||
|
throw new ConflictException({ code: 'BOND_TICKER_AMBIGUOUS' });
|
||||||
|
return matches[0];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
bond(
|
||||||
|
userId: string,
|
||||||
|
connection: TbankConnectionContext,
|
||||||
|
uid: string,
|
||||||
|
): Promise<IdentifiedBond> {
|
||||||
|
return this.cachedForConnection(
|
||||||
|
userId,
|
||||||
|
connection,
|
||||||
|
`metadata:${uid}`,
|
||||||
|
async () => {
|
||||||
|
const bond = await this.tbank.getBond(connection.token, uid);
|
||||||
|
if (!bond || bond.uid !== uid) throw new NotFoundException();
|
||||||
|
return { ...bond, uid };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cached<T extends object>(
|
||||||
|
userId: string,
|
||||||
|
key: string,
|
||||||
|
operation: (connection: TbankConnectionContext) => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
return this.access.withConnection(userId, (connection) =>
|
||||||
|
this.cachedForConnection(userId, connection, key, () =>
|
||||||
|
operation(connection),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cachedForConnection<T extends object>(
|
||||||
|
userId: string,
|
||||||
|
{ generation }: TbankConnectionContext,
|
||||||
|
key: string,
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const cacheKey = JSON.stringify([userId, generation, key]);
|
||||||
|
const cached = this.cache.get(cacheKey);
|
||||||
|
if (cached) return cached as Promise<T>;
|
||||||
|
const pending = operation();
|
||||||
|
this.cache.set(cacheKey, pending);
|
||||||
|
return pending.catch((error) => {
|
||||||
|
if (this.cache.get(cacheKey) === pending) this.cache.delete(cacheKey);
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectBonds(found: TbankBond[], query: string): IdentifiedBond[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
return found
|
||||||
|
.filter(
|
||||||
|
(bond): bond is IdentifiedBond =>
|
||||||
|
Boolean(bond.uid) && bond.instrumentKind === 'INSTRUMENT_TYPE_BOND',
|
||||||
|
)
|
||||||
|
.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 === 'TQOB') - Number(a.classCode === 'TQOB') ||
|
||||||
|
a.uid.localeCompare(b.uid),
|
||||||
|
)
|
||||||
|
.filter((bond) => {
|
||||||
|
// A missing ISIN must not collapse unrelated catalog instruments.
|
||||||
|
const key = bond.isin?.trim()
|
||||||
|
? `isin:${bond.isin.trim().toUpperCase()}`
|
||||||
|
: `uid:${bond.uid}`;
|
||||||
|
if (seen.has(key)) return false;
|
||||||
|
seen.add(key);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBond(bond: IdentifiedBond): BondDto {
|
||||||
|
return {
|
||||||
|
instrumentUid: bond.uid,
|
||||||
|
slug: bond.uid,
|
||||||
|
name: bond.name?.trim() || bond.ticker || bond.uid,
|
||||||
|
ticker: bond.ticker?.trim() || null,
|
||||||
|
isin: bond.isin?.trim() || null,
|
||||||
|
classCode: bond.classCode?.trim() || null,
|
||||||
|
realExchange: bond.realExchange || null,
|
||||||
|
apiTradeAvailable: bond.apiTradeAvailableFlag ?? null,
|
||||||
|
logoName: bond.brand?.logoName?.trim() || null,
|
||||||
|
currency: bond.currency?.toUpperCase() || null,
|
||||||
|
bondType: bond.bondType || null,
|
||||||
|
sector: bond.sector || null,
|
||||||
|
lot: bond.lot && bond.lot > 0 ? bond.lot : null,
|
||||||
|
historyFrom: timestamp(bond.first_1dayCandleDate),
|
||||||
|
nominal: money(bond.nominal),
|
||||||
|
initialNominal: money(bond.initialNominal),
|
||||||
|
aci: money(bond.aciValue),
|
||||||
|
maturityDate: timestamp(bond.maturityDate)?.slice(0, 10) ?? null,
|
||||||
|
callDate: timestamp(bond.callDate)?.slice(0, 10) ?? null,
|
||||||
|
couponQuantityPerYear: bond.couponQuantityPerYear ?? null,
|
||||||
|
floatingCoupon: bond.floatingCouponFlag ?? null,
|
||||||
|
perpetual: bond.perpetualFlag ?? null,
|
||||||
|
amortization: bond.amortizationFlag ?? null,
|
||||||
|
subordinated: bond.subordinatedFlag ?? null,
|
||||||
|
riskLevel: bond.riskLevel || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
decimalFromString,
|
||||||
|
divide,
|
||||||
|
formatDecimal,
|
||||||
|
multiply,
|
||||||
|
} from '../../../../../common/decimal';
|
||||||
|
import { MoexClient } from '../../../../../integrations/moex/moex.api';
|
||||||
|
import { NcrRatingsClient } from '../../../../../integrations/ncr/ncr.api';
|
||||||
|
import {
|
||||||
|
TbankClient,
|
||||||
|
type TbankConnectionContext,
|
||||||
|
} from '../../../../../integrations/tbank/tbank.api';
|
||||||
|
import { PortfolioService } from '../../../portfolio/portfolio.api';
|
||||||
|
import {
|
||||||
|
moscowDay,
|
||||||
|
optional,
|
||||||
|
timestamp,
|
||||||
|
} from '../../application/instrument-market';
|
||||||
|
import { instrumentPosition } from '../../application/instrument-position';
|
||||||
|
import {
|
||||||
|
BondCouponsDto,
|
||||||
|
BondMetricsDto,
|
||||||
|
BondPositionDto,
|
||||||
|
} from '../presentation/bond.dto';
|
||||||
|
|
||||||
|
import { BondMarketService } from './bond-market.service';
|
||||||
|
import { money } from '../infrastructure/bond-money.mapper';
|
||||||
|
import { BondCatalogService } from './bond-catalog.service';
|
||||||
|
|
||||||
|
const ISO_YEAR_LENGTH = 4;
|
||||||
|
const INCOME_HISTORY_YEARS = 5;
|
||||||
|
const COUPON_YIELD_DECIMAL_PLACES = 4;
|
||||||
|
@Injectable()
|
||||||
|
export class BondIncomeService {
|
||||||
|
constructor(
|
||||||
|
private readonly catalog: BondCatalogService,
|
||||||
|
private readonly tbank: TbankClient,
|
||||||
|
private readonly portfolios: PortfolioService,
|
||||||
|
private readonly market: BondMarketService,
|
||||||
|
private readonly moex: MoexClient,
|
||||||
|
private readonly ratings: NcrRatingsClient,
|
||||||
|
) {}
|
||||||
|
metrics(userId: string, uid: string): Promise<BondMetricsDto> {
|
||||||
|
return this.catalog.cached(userId, `metrics:${uid}`, async (connection) => {
|
||||||
|
const instrument = await this.catalog.bond(userId, connection, uid);
|
||||||
|
const { ticker, isin, classCode } = instrument;
|
||||||
|
const today = moscowDay(new Date().toISOString());
|
||||||
|
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||||
|
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||||
|
const unavailable: string[] = [];
|
||||||
|
const [events, quote, effectiveYield, creditRating] = await Promise.all([
|
||||||
|
optional(
|
||||||
|
() => this.couponEvents(userId, connection, uid, from, to),
|
||||||
|
'coupons',
|
||||||
|
unavailable,
|
||||||
|
),
|
||||||
|
optional(() => this.market.quote(userId, uid), 'quote', unavailable),
|
||||||
|
ticker && isin && classCode
|
||||||
|
? optional(
|
||||||
|
() => this.moex.bondYield(ticker, isin, classCode),
|
||||||
|
'yield',
|
||||||
|
unavailable,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
isin
|
||||||
|
? optional(() => this.ratings.rating(isin), 'rating', unavailable)
|
||||||
|
: null,
|
||||||
|
]);
|
||||||
|
const next = events
|
||||||
|
?.filter((event) => {
|
||||||
|
const date = timestamp(event.couponDate)?.slice(0, 10);
|
||||||
|
return date && date >= today;
|
||||||
|
})
|
||||||
|
.sort(
|
||||||
|
(a, b) =>
|
||||||
|
Number(a.couponDate?.seconds) - Number(b.couponDate?.seconds),
|
||||||
|
)[0];
|
||||||
|
const coupon = money(next?.payOneBond);
|
||||||
|
const period = next?.couponPeriod;
|
||||||
|
const couponPeriodDays =
|
||||||
|
period && Number.isInteger(period) && period > 0 ? period : null;
|
||||||
|
const clean = quote?.cleanPrice;
|
||||||
|
const couponYieldPercent =
|
||||||
|
coupon &&
|
||||||
|
couponPeriodDays &&
|
||||||
|
clean &&
|
||||||
|
coupon.currency === clean.currency &&
|
||||||
|
decimalFromString(coupon.value).value >= 0n &&
|
||||||
|
decimalFromString(clean.value).value > 0n
|
||||||
|
? formatDecimal(
|
||||||
|
divide(
|
||||||
|
multiply(
|
||||||
|
decimalFromString(coupon.value),
|
||||||
|
decimalFromString('36500'),
|
||||||
|
),
|
||||||
|
multiply(
|
||||||
|
decimalFromString(String(couponPeriodDays)),
|
||||||
|
decimalFromString(clean.value),
|
||||||
|
),
|
||||||
|
COUPON_YIELD_DECIMAL_PLACES,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
const couponType =
|
||||||
|
next?.couponType && next.couponType !== 'COUPON_TYPE_UNSPECIFIED'
|
||||||
|
? next.couponType
|
||||||
|
: instrument.floatingCouponFlag === true
|
||||||
|
? 'COUPON_TYPE_FLOATING'
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
creditRating,
|
||||||
|
coupon,
|
||||||
|
couponDate: timestamp(next?.couponDate)?.slice(0, 10) ?? null,
|
||||||
|
couponType,
|
||||||
|
couponPeriodDays,
|
||||||
|
couponYieldPercent,
|
||||||
|
couponYieldPriceAt:
|
||||||
|
couponYieldPercent !== null ? (quote?.priceAt ?? null) : null,
|
||||||
|
effectiveYield,
|
||||||
|
unavailable,
|
||||||
|
observedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private couponEvents(
|
||||||
|
userId: string,
|
||||||
|
connection: TbankConnectionContext,
|
||||||
|
uid: string,
|
||||||
|
from: string,
|
||||||
|
to: string,
|
||||||
|
) {
|
||||||
|
return this.catalog.cachedForConnection(
|
||||||
|
userId,
|
||||||
|
connection,
|
||||||
|
`coupon-events:${uid}:${from}:${to}`,
|
||||||
|
() => this.tbank.getBondCoupons(connection.token, uid, from, to),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
coupons(userId: string, uid: string): Promise<BondCouponsDto> {
|
||||||
|
return this.catalog.cached(userId, `coupons:${uid}`, async (connection) => {
|
||||||
|
await this.catalog.bond(userId, connection, uid);
|
||||||
|
const today = moscowDay(new Date().toISOString());
|
||||||
|
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||||
|
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
|
||||||
|
const unavailable: string[] = [];
|
||||||
|
const [events, position] = await Promise.all([
|
||||||
|
this.couponEvents(userId, connection, uid, from, to),
|
||||||
|
optional(() => this.position(userId, uid), 'position', unavailable),
|
||||||
|
]);
|
||||||
|
const quantity =
|
||||||
|
position?.accounts.length &&
|
||||||
|
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
|
||||||
|
? decimalFromString(position.quantity)
|
||||||
|
: null;
|
||||||
|
const coupons = events
|
||||||
|
.map((event) => {
|
||||||
|
const paymentDate = timestamp(event.couponDate)?.slice(0, 10) ?? null;
|
||||||
|
const recordDate = timestamp(event.fixDate)?.slice(0, 10) ?? null;
|
||||||
|
const perBond = money(event.payOneBond);
|
||||||
|
const timing = !paymentDate
|
||||||
|
? ('undated' as const)
|
||||||
|
: paymentDate >= today
|
||||||
|
? ('upcoming' as const)
|
||||||
|
: ('past' as const);
|
||||||
|
return {
|
||||||
|
number: event.couponNumber ?? null,
|
||||||
|
paymentDate,
|
||||||
|
recordDate,
|
||||||
|
perBond,
|
||||||
|
couponType: event.couponType ?? null,
|
||||||
|
periodDays: event.couponPeriod ?? null,
|
||||||
|
timing,
|
||||||
|
estimatedAmount:
|
||||||
|
quantity &&
|
||||||
|
perBond &&
|
||||||
|
timing === 'upcoming' &&
|
||||||
|
recordDate &&
|
||||||
|
recordDate >= today
|
||||||
|
? {
|
||||||
|
currency: perBond.currency,
|
||||||
|
value: formatDecimal(
|
||||||
|
multiply(quantity, decimalFromString(perBond.value)),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) =>
|
||||||
|
(a.paymentDate ?? '').localeCompare(b.paymentDate ?? ''),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
coupons,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
observedAt: new Date().toISOString(),
|
||||||
|
positionAt: quantity ? (position?.observedAt ?? null) : null,
|
||||||
|
estimateUnavailable: unavailable.length > 0,
|
||||||
|
positionIsStale: position?.isStale ?? false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async position(userId: string, uid: string): Promise<BondPositionDto> {
|
||||||
|
return this.catalog.cached(userId, `position:${uid}`, async () =>
|
||||||
|
instrumentPosition(await this.portfolios.getAll(userId), uid, 'BOND'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user