Skip to content

LED 93 account application boundary cleanup - #274

Merged
gorushkin merged 21 commits into
mainfrom
LED-93-account-application-boundary-cleanup
Aug 17, 2026
Merged

gorushkin merged 21 commits into
mainfrom
LED-93-account-application-boundary-cleanup

Conversation

@gorushkin

Copy link
Copy Markdown
Owner

No description provided.

- Removed `isSystem` flag from Account and Operation entities, snapshots, and persistence layers.
- Updated related tests and documentation to reflect the removal of system flags.
- Adjusted database schema to eliminate `is_system` columns from accounts and operations tables.
- Updated API contracts and validation schemas to remove references to initial balances and system flags.
- Enhanced documentation regarding future multi-currency reconciliation plans without reliance on deprecated flags.
…rom-account-entity

LED-92 feat: remove system flags from account and operation models
…rchestration

LED-96 test: reset transaction manager mock and verify call count in CreateAccountUseCase tests
…e-repositories

LED-98 refactor: decouple account use case repositories by using interfaces
LED-112 refactor: unify database schema exports and clean up imports across modules
…s-filter

LED-120 refactor: rename variables for clarity in account filtering tests
…text reuse

feat: throw RecordAlreadyExistsError for duplicate email in user creation
…daries

LED-127 test: add TransactionManager tests for nested transaction context reuse
…p-guard

LED-131 refactor: unify account ownership checks by integrating ensureOwnedSnapshot across use cases
…istsError and update related error handling across services and tests
refactor: update import paths for error handling in user service and tests
LED-135 refactor: replace UserAlreadyExistsError with EntityAlreadyExistsError and update related error handling across services and tests

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

PR приводит границы account/operation домена, API-контрактов и persistence к текущему фактическому поведению (без “system flags” и без balance-derived полей в аккаунте), а также унифицирует обработку конфликтов уникальности через новый публичный код ошибки ENTITY_ALREADY_EXISTS.

Changes:

  • Удалены isSystem (operation/account) и account balance-derived поля (initialBalance, currentClearedBalanceLocal) из shared-contracts, домена, мапперов, read-models, тестов и документации.
  • Введён EntityAlreadyExistsError + маппер mapRepositoryAlreadyExists() для перевода RecordAlreadyExistsError в публичный ENTITY_ALREADY_EXISTS (в т.ч. для регистрации).
  • Рефакторинг account use cases: переход с локальной базовой логики ensureAccountExistsAndOwned на общий ensureOwnedSnapshot, плюс чистка импортов/публичных DB schema API.

Reviewed changes

Copilot reviewed 109 out of 109 changed files in this pull request and generated no comments.

Show a summary per file
File Description
restAPI/accounts/create.bru Обновление примера запроса создания аккаунта под новый контракт
packages/shared/src/validation/accounts.ts Удаление initialBalance из схемы валидации создания аккаунта
packages/shared/src/validation/accounts.test.ts Адаптация тестовых данных под обновлённую схему
packages/shared/src/types/transaction.ts Удаление isSystem из OperationResponseDTO
packages/shared/src/types/error-contract.ts Добавление ENTITY_ALREADY_EXISTS, удаление REGISTRATION_CONFLICT, обновление контекстов
packages/shared/src/types/account.ts Удаление initialBalance/balance-derived полей и isSystem из account DTO
docs/MULTICURRENCY_DESIGN.md Синхронизация документации с удалением isSystem и “trading ops” как будущего поведения
docs/ERROR_ARCHITECTURE.md Документация EntityAlreadyExistsError и allowlisted контекстов
docs/DOMAIN.md Обновление доменной документации: убраны system flags и initial/current balance поля
docs/DATABASE_SCHEMA.md Обновление схемы: удалены колонки и добавлено пояснение про schema public API
docs/architecture/adr/README.md Обновление правил ADR + добавление ссылок на ADR 0022/0023
docs/architecture/adr/0023-entity-already-exists-error-contract.md Новый ADR для контракта ENTITY_ALREADY_EXISTS
docs/architecture/adr/0022-remove-system-flags-from-account-and-operation-contracts.md Новый ADR по удалению system flags
docs/architecture/adr/0021-split-commodity-reference-business-policy-from-persistence-integrity.md Удаление PR-метаданных из ADR
docs/architecture/adr/0020-terminal-tombstone-and-reversible-entity-states.md Удаление PR-метаданных из ADR
docs/architecture/adr/0019-repository-enforced-commodity-reference-validation.md Удаление PR-метаданных из ADR
docs/architecture/adr/0017-backend-http-adapter-boundary.md Удаление PR-метаданных из ADR
docs/architecture/adr/0016-backend-request-flow.md Удаление PR-метаданных из ADR
docs/architecture/adr/0015-domain-restoration-factory-naming.md Удаление PR-метаданных из ADR
docs/architecture/adr/0014-keep-amount-value-object-name.md Удаление PR-метаданных из ADR
docs/architecture/adr/0013-no-domain-entity-base-class.md Удаление PR-метаданных из ADR
docs/architecture/adr/0012-user-repository-application-boundary.md Удаление PR-метаданных из ADR
docs/architecture/adr/0011-domain-entity-api-conventions.md Удаление PR-метаданных из ADR
docs/architecture/adr/0010-entity-not-found-api-code.md Удаление PR-метаданных из ADR
docs/architecture/adr/0009-repository-error-code-migration.md Удаление PR-метаданных из ADR
docs/architecture/adr/0008-structured-api-error-contract.md Обновление ADR под новый ENTITY_ALREADY_EXISTS
docs/architecture/adr/0007-no-operation-amount-sign-invariant.md Удаление PR-метаданных из ADR
docs/architecture/adr/0006-commodity-registry-before-currency-validation.md Удаление PR-метаданных из ADR
docs/architecture/adr/0005-no-non-zero-operation-invariant.md Удаление PR-метаданных из ADR
docs/architecture/adr/0004-no-minimum-distinct-accounts-invariant.md Удаление PR-метаданных из ADR
docs/architecture/adr/0003-no-zero-net-account-effect-invariant.md Удаление PR-метаданных из ADR
docs/architecture/adr/0002-operation-application-boundary.md Удаление PR-метаданных из ADR
docs/architecture/adr/0001-transaction-repository-boundaries.md Удаление PR-метаданных из ADR
apps/backend/src/services/user.service.ts Переход с UserAlreadyExistsError на EntityAlreadyExistsError
apps/backend/src/presentation/http/error-handler.ts Добавление HTTP-маппинга для ENTITY_ALREADY_EXISTS, удаление REGISTRATION_CONFLICT
apps/backend/src/presentation/http/error-handler.test.ts Обновление unit-тестов error handler под новый код/контекст
apps/backend/src/presentation/http/commodities/commodity.integration.test.ts Обновление интеграционных тестов на 409 shape для duplicates
apps/backend/src/presentation/http/auth/auth.integration.test.ts Регистрация: переход на ENTITY_ALREADY_EXISTS + allowlisted context
apps/backend/src/presentation/http/accounts/account.integration.test.ts Обновление account API контрактов + новые проверки по user isolation
apps/backend/src/presentation/http/accounts/account.controller.test.ts Удаление initialBalance из тела запроса в тестах
apps/backend/src/infrastructure/db/user/user.repository.ts Передача контекста unique constraint для нормализации в RecordAlreadyExistsError
apps/backend/src/infrastructure/db/user/user.repository.test.ts Тест на RecordAlreadyExistsError при duplicate email
apps/backend/src/infrastructure/db/TransactionManager.ts Фикс/улучшение: reuse transaction context в nested run()
apps/backend/src/infrastructure/db/TransactionManager.test.ts Юнит-тест на переиспользование transaction context
apps/backend/src/infrastructure/db/transaction/transaction.repository.test.ts Удаление isSystem из ожиданий persistence
apps/backend/src/infrastructure/db/transaction/transaction-read-model.mapper.ts Удаление isSystem из read-model mapping
apps/backend/src/infrastructure/db/transaction/transaction-query.repository.test.ts Удаление isSystem из ожиданий query/read model
apps/backend/src/infrastructure/db/operations/operation-persistence.mapper.ts Переименование insert-типа + удаление isSystem из persistence row
apps/backend/src/infrastructure/db/operations/operation-persistence.mapper.test.ts Обновление тестов под новый persistence mapping
apps/backend/src/infrastructure/db/commodities/commodity.repository.ts Импорт commoditiesTable через schema public API
apps/backend/src/infrastructure/db/commodities/commodity.repository.test.ts Переход на типы из src/db/schemas public API
apps/backend/src/infrastructure/db/accounts/account.repository.ts Импорт accountsTable через schema public API + удаление obsolete полей из update/create
apps/backend/src/infrastructure/db/accounts/account.repository.test.ts Обновление тестовых вставок/ожиданий под новый account schema
apps/backend/src/infrastructure/db/accounts/account-persistence.mapper.ts Обновление snapshot<->db mapping под новый schema и типы
apps/backend/src/infrastructure/db/accounts/account-persistence.mapper.test.ts Обновление тестов account persistence mapper
apps/backend/src/domain/operations/types.ts Удаление isSystem из OperationSnapshot
apps/backend/src/domain/operations/operation.entity.ts Удаление isSystem из сущности и snapshot-логики
apps/backend/src/domain/accounts/types.ts Удаление balance-derived полей и system flag из AccountSnapshot/props
apps/backend/src/domain/accounts/account.entity.ts Удаление initialBalance/currentClearedBalanceLocal/isSystem из доменной сущности
apps/backend/src/domain/accounts/account.entity.test.ts Обновление тестов доменной сущности + удаление TODO про isSystem
apps/backend/src/domain/accounts/account-type.enum.ts Удаление system-type логики (isSystemType)
apps/backend/src/di/types.ts DI-типизация на уровне интерфейсов репозиториев
apps/backend/src/di/container.ts Прокидывание ensureOwnedSnapshot в account use cases
apps/backend/src/db/test-utils/testEntityBuilder.ts Создание тестовых аккаунтов без initialBalance
apps/backend/src/db/test-db.ts Удаление isSystem/initialBalance/currentClearedBalanceLocal из тестовой DB фабрики
apps/backend/src/db/schemas/transactions.ts Переход на импорт schema через ./... и чистка устаревших alias-типов
apps/backend/src/db/schemas/operations.ts Удаление is_system колонки/alias-типа из schema
apps/backend/src/db/schemas/index.ts Расширение public API: экспорт таблиц + типов insert/row
apps/backend/src/db/schemas/common.ts Удаление isSystem column builder
apps/backend/src/db/schemas/accounts.ts Удаление balance-derived колонок и is_system из schema
apps/backend/src/db/schema.ts Реэкспорт всего через ./schemas
apps/backend/src/db/createTestUser.ts Создание тестового аккаунта без initialBalance
apps/backend/src/application/usecases/transaction/tests/getTransactionById.test.ts Удаление isSystem из test fixtures/expectations
apps/backend/src/application/usecases/transaction/tests/getAllTransactions.test.ts Удаление isSystem из test fixtures
apps/backend/src/application/usecases/commodities/updateCommodity.ts Маппинг duplicate conflicts через mapRepositoryAlreadyExists
apps/backend/src/application/usecases/commodities/createCommodity.ts Маппинг duplicate conflicts через mapRepositoryAlreadyExists
apps/backend/src/application/usecases/commodities/tests/updateCommodity.test.ts Тест на маппинг duplicates в ENTITY_ALREADY_EXISTS
apps/backend/src/application/usecases/commodities/tests/createCommodity.test.ts Тест на маппинг duplicates в ENTITY_ALREADY_EXISTS
apps/backend/src/application/usecases/auth/registerUser.ts Удаление pre-check + маппинг repository duplicate в ENTITY_ALREADY_EXISTS
apps/backend/src/application/usecases/auth/tests/registerUser.test.ts Тест на новый duplicate mapping для регистрации
apps/backend/src/application/usecases/accounts/updateAccount.ts Рефакторинг: ensureOwnedSnapshot + маппинг duplicates + отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/openAccount.ts Рефакторинг: ensureOwnedSnapshot + отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/getAllAccounts.ts Рефакторинг: отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/getAccountById.ts Рефакторинг: ensureOwnedSnapshot + отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/deleteAccount.ts Рефакторинг: отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/createAccount.ts Маппинг duplicates в ENTITY_ALREADY_EXISTS при создании аккаунта
apps/backend/src/application/usecases/accounts/closeAccount.ts Рефакторинг: ensureOwnedSnapshot + отказ от AccountUseCaseBase
apps/backend/src/application/usecases/accounts/accountBase.ts Удаление базового класса use case (перенос ответственности в shared helper)
apps/backend/src/application/usecases/accounts/tests/updateAccount.test.ts Тест на ENTITY_ALREADY_EXISTS при duplicate name + адаптация snapshot
apps/backend/src/application/usecases/accounts/tests/openAccount.test.ts Адаптация тестов под новый snapshot
apps/backend/src/application/usecases/accounts/tests/getAllAccounts.test.ts Адаптация тестов под новый snapshot
apps/backend/src/application/usecases/accounts/tests/getAccountById.test.ts Подключение ensureOwnedSnapshot в тесте use case
apps/backend/src/application/usecases/accounts/tests/deleteAccount.test.ts Адаптация тестов под новый snapshot
apps/backend/src/application/usecases/accounts/tests/createAccount.test.ts Тест на ENTITY_ALREADY_EXISTS при duplicate name + фиксация ожиданий create payload
apps/backend/src/application/usecases/accounts/tests/closeAccount.test.ts Адаптация тестов под новый snapshot
apps/backend/src/application/shared/repositoryConflictMapper.ts Новый маппер repository unique conflicts → EntityAlreadyExistsError
apps/backend/src/application/read-models/transaction.read-model.ts Удаление isSystem из read-model типа
apps/backend/src/application/mappers/transaction.mapper.test.ts Удаление isSystem из ожиданий маппера
apps/backend/src/application/mappers/transaction-read-model-response.mapper.ts Удаление isSystem из response mapping
apps/backend/src/application/mappers/operation.mapper.ts Удаление isSystem из mapping snapshot→DTO
apps/backend/src/application/mappers/account.mapper.ts Удаление balance-derived полей из response + обновление create-props mapping
apps/backend/src/application/mappers/account.mapper.test.ts Обновление тестов account mapper
apps/backend/src/application/interfaces/AccountRepository.interface.ts Удаление initialBalance из update input контракта репозитория
apps/backend/src/application/application.errors.ts Добавление EntityAlreadyExistsError, удаление UserAlreadyExistsError
apps/backend/src/application/application.errors.test.ts Тест для нового EntityAlreadyExistsError
apps/backend/src/tests/user/user.service.test.ts Переход теста на EntityAlreadyExistsError
apps/backend/drizzle/meta/0000_snapshot.json Обновление drizzle snapshot под новый schema
apps/backend/drizzle/0000_nostalgic_ben_parker.sql Обновление базовой SQL-миграции под новый schema
.agents/skills/ledgerly-architecture-docs/SKILL.md Обновление правил по ADR (убраны PR-метаданные)
Suppressed comments (1)

apps/backend/drizzle/0000_nostalgic_ben_parker.sql:14

  • В PR изменена уже существующая базовая миграция 0000_*.sql. Это опасно для окружений, где миграция 0000 уже применялась: фактическая схема БД останется со старыми NOT NULL-колонками (например, initial_balance/current_cleared_balance_local/is_system), а код перестал их писать, из‑за чего новые INSERT’ы могут начать падать. Кроме того, в репозитории явно закреплено правило «Never edit migrations manually» (см. .github/copilot-instructions.md:93). Решение: откатить правки существующей миграции 0000 и добавить новую миграцию (например, 0001_...) с корректным ALTER/пересозданием таблиц и переносом данных; после этого обновить drizzle meta через pnpm db:generate.
CREATE TABLE `accounts` (
	`commodity_id` text NOT NULL,
	`created_at` text NOT NULL,
	`description` text NOT NULL,
	`id` text PRIMARY KEY NOT NULL,
	`is_closed` integer NOT NULL,
	`is_tombstone` integer NOT NULL,
	`name` text NOT NULL,
	`type` text NOT NULL,
	`updated_at` text NOT NULL,
	`user_id` text NOT NULL,
	FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
	FOREIGN KEY (`user_id`,`commodity_id`) REFERENCES `commodities`(`user_id`,`id`) ON UPDATE no action ON DELETE no action
);

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@gorushkin
gorushkin requested a balanced review from Copilot August 17, 2026 13:16
@gorushkin
gorushkin merged commit 352b3ae into main Aug 17, 2026
4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 109 out of 109 changed files in this pull request and generated no new comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants