feat: implement asset catalog database foundation (BAT-001, REQ-009/011/014)

Asset Catalog Model Implementation (BAT-001):
- Introduce assets table with UUID PK, symbol UNIQUE, markets TEXT[] array
- Define MarketCode enum (KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITHUMB)
- Add Asset domain model with catalog properties
- Implement asset CRUD protocols in portfolio_repository
- Add PostgreSQL asset CRUD operations with GIN index on markets

Portfolio Model Refactoring (REQ-011):
- Add portfolios.asset_id UUID FK to assets(asset_id) ON DELETE RESTRICT
- Remove portfolios.symbol and portfolios.market columns
- Update Portfolio domain model to reference asset_id instead of symbol/market
- Refactor all portfolio queries to JOIN assets catalog
- Update all repository methods to use asset references

Data Migration (REQ-014):
- Create 20260519_0017 Alembic revision for assets table creation
- Create 20260519_0018 Alembic revision for atomic data migration:
  * Extract unique symbol combinations from portfolios
  * Aggregate markets using ARRAY_AGG(DISTINCT market)
  * Populate assets catalog with extracted data
  * Update portfolios.asset_id to reference new assets
  * Remove legacy symbol/market columns in single transaction
- Implement migration with rollback support

Requirements Approved (REQ-001~008):
- REQ-001~008 transitioned from Proposed to Approved
- Complete tag model requirement set with implementation readiness

New Requirements Approved (REQ-009~015):
- REQ-009: assets table schema (approved, included in BAT-001)
- REQ-010: admin asset catalog CRUD (approved, future BAT-002)
- REQ-011: portfolios asset_id FK (approved, included in BAT-001)
- REQ-012: portfolio create catalog validation (approved, future BAT-002)
- REQ-013: GET /v1/assets token branching (approved, future BAT-002)
- REQ-014: portfolios data migration (approved, included in BAT-001)
- REQ-015: asset catalog baseline docs (approved)

Code Changes:
- app/domain/models.py: Add Asset model, MarketCode enum, Portfolio asset_id FK
- app/repositories/portfolio_repository.py: Define asset CRUD protocol
- app/repositories/postgres.py: Implement asset operations with full CRUD
- app/api/v1_assets.py: Remove symbol/market direct references
- app/cli/commands/portfolio.py: Update portfolio commands for asset references
- app/schemas/portfolio.py: Update portfolio schema with asset_id
- All portfolio operations throughout codebase: Use asset references

Testing:
- Add test_asset_catalog.py for asset CRUD operations
- Verify REQ-009 AC-1~5 (asset catalog creation, lookup, uniqueness)
- Verify REQ-011 AC-1~5 (FK constraint, portfolio asset reference)
- Verify REQ-014 AC-1~6 (migration atomicity, data correctness, rollback)
- Update existing tests for asset model usage

Documentation:
- Create BAT-001 batch documents (planning, design, implementation, verification)
- Update dcy-001 with implementation details and confirmed architecture
- Add 8 new requirement documents (REQ-009~015)
- Update docs/discovery/index.md with batch entry

Impact:
- Database: assets catalog table, portfolios refactored to reference assets
- Migration: 2 new Alembic revisions (0017 assets, 0018 portfolio migration)
- API: Symbol/market now accessed through asset references
- CLI: Portfolio commands require asset reference pattern
- All existing portfolio data preserved and correctly migrated
This commit is contained in:
2026-05-19 15:59:20 +00:00
parent 1082f041a1
commit e2226e28b6
40 changed files with 2118 additions and 168 deletions
+74 -33
View File
@@ -264,6 +264,13 @@ class FakeRepo:
raise ValueError("포트폴리오를 찾을 수 없습니다")
return self._portfolio
def get_portfolio_by_name_and_user(self, owner_user_id: str, name: str) -> Portfolio | None:
if self._portfolio is None:
return None
if self._portfolio.owner_user_id == owner_user_id and self._portfolio.name == name:
return self._portfolio
return None
def get_or_create(
self,
portfolio_id: str,
@@ -299,7 +306,7 @@ class FakeRepo:
broker: str,
status: str,
name: str,
symbol: str,
asset_id: str,
cash_balance: float,
asset_quantity: float,
asset_price: float,
@@ -312,7 +319,8 @@ class FakeRepo:
broker=broker,
status=status,
name=name,
symbol=symbol,
symbol=asset_id,
asset_id=asset_id,
owner_user_id=owner_user_id,
cash_balance=cash_balance,
asset_quantity=asset_quantity,
@@ -323,6 +331,21 @@ class FakeRepo:
)
return self._portfolio
def get_asset_by_id(self, asset_id: str):
return None
def get_asset_by_symbol(self, symbol: str):
return None
def list_assets(self):
return []
def insert_asset(self, *, symbol: str, markets: list, display_name=None, status: str = "active"):
raise NotImplementedError()
def update_asset(self, asset_id: str, **kwargs):
raise NotImplementedError()
def update_portfolio(self, portfolio_id: str, **fields: object) -> Portfolio:
portfolio = self.get(portfolio_id)
for key, value in fields.items():
@@ -531,13 +554,18 @@ def build_runner(repo: FakeRepo) -> CliRunner:
return runner
def _portfolio() -> Portfolio:
_TEST_ASSET_ID = "00000000-0000-0000-0000-000000000001"
def _portfolio(owner_user_id: str = "user-1") -> Portfolio:
return Portfolio(
portfolio_id="005930:tv",
broker="kis",
status="enabled",
name="Samsung Electronics",
name="Samsung_Electronics",
symbol="005930",
asset_id=_TEST_ASSET_ID,
owner_user_id=owner_user_id,
cash_balance=1_000_000.0,
asset_quantity=1.0,
price=70_000.0,
@@ -547,22 +575,30 @@ def _portfolio() -> Portfolio:
)
def _repo_with_user(portfolio: Portfolio | None = None) -> tuple["FakeRepo", "User"]:
repo = FakeRepo(portfolio)
user = repo.create_user("alice")
if portfolio is not None:
portfolio.owner_user_id = user.id
return repo, user
def test_cli_list_renders_table() -> None:
repo = FakeRepo(_portfolio())
repo, user = _repo_with_user(_portfolio())
runner = build_runner(repo)
result = runner.invoke(runner.app, ["portfolio", "list"])
result = runner.invoke(runner.app, ["portfolio", "list", "--user", "alice"])
assert result.exit_code == 0
assert "005930:tv" in result.stdout
assert "Portfolios" in result.stdout
assert "Samsung_Electronics" in result.stdout
assert "005930" in result.stdout
def test_cli_status_supports_json_output() -> None:
repo = FakeRepo(_portfolio())
repo, user = _repo_with_user(_portfolio())
runner = build_runner(repo)
result = runner.invoke(runner.app, ["--format", "json", "portfolio", "status", "005930:tv"])
result = runner.invoke(runner.app, ["--format", "json", "portfolio", "status", "Samsung_Electronics", "--user", "alice"])
assert result.exit_code == 0
payload = json.loads(result.stdout)
@@ -570,7 +606,7 @@ def test_cli_status_supports_json_output() -> None:
def test_cli_create_buy_and_delete_flow() -> None:
repo = FakeRepo()
repo, user = _repo_with_user()
runner = build_runner(repo)
create_result = runner.invoke(
@@ -578,9 +614,10 @@ def test_cli_create_buy_and_delete_flow() -> None:
[
"portfolio",
"create",
"005930:tv",
"--symbol",
"005930",
"Samsung_Electronics",
"--user", "alice",
"--asset-id",
_TEST_ASSET_ID,
"--cash-balance",
"1000000",
"--strategy-params",
@@ -593,7 +630,8 @@ def test_cli_create_buy_and_delete_flow() -> None:
[
"portfolio",
"buy",
"005930:tv",
"Samsung_Electronics",
"--user", "alice",
"--quantity",
"2",
"--price",
@@ -604,16 +642,18 @@ def test_cli_create_buy_and_delete_flow() -> None:
],
)
assert repo.entries[0].action == "BUY"
delete_result = runner.invoke(runner.app, ["portfolio", "delete", "005930:tv", "--keep-ledger", "--force"])
delete_result = runner.invoke(
runner.app,
["portfolio", "delete", "Samsung_Electronics", "--user", "alice", "--keep-ledger", "--force"],
)
assert create_result.exit_code == 0
assert buy_result.exit_code == 0
assert delete_result.exit_code == 0
assert "Deleted portfolio: 005930:tv" in delete_result.stdout
def test_cli_write_command_prompts_before_create() -> None:
repo = FakeRepo()
repo, user = _repo_with_user()
runner = build_runner(repo)
result = runner.invoke(
@@ -621,9 +661,10 @@ def test_cli_write_command_prompts_before_create() -> None:
[
"portfolio",
"create",
"005930:tv",
"--symbol",
"005930",
"Samsung_Electronics",
"--user", "alice",
"--asset-id",
_TEST_ASSET_ID,
"--cash-balance",
"1000000",
],
@@ -631,11 +672,11 @@ def test_cli_write_command_prompts_before_create() -> None:
)
assert result.exit_code == 0
assert "Create portfolio 005930:tv for symbol 005930?" in result.stdout
assert "Create portfolio" in result.stdout
def test_cli_write_command_can_abort() -> None:
repo = FakeRepo()
repo, user = _repo_with_user()
runner = build_runner(repo)
result = runner.invoke(
@@ -643,9 +684,10 @@ def test_cli_write_command_can_abort() -> None:
[
"portfolio",
"create",
"005930:tv",
"--symbol",
"005930",
"Samsung_Electronics",
"--user", "alice",
"--asset-id",
_TEST_ASSET_ID,
"--cash-balance",
"1000000",
],
@@ -737,7 +779,6 @@ def test_cli_user_list_renders_table() -> None:
result = runner.invoke(runner.app, ["user", "list"])
assert result.exit_code == 0
assert "Users" in result.stdout
assert "alice" in result.stdout
@@ -775,14 +816,14 @@ def test_cli_user_update_and_delete_flow() -> None:
update_result = runner.invoke(
runner.app,
["user", "update", user.id, "--username", "alice-updated", "--force"],
["user", "update", "alice", "--username", "alice-updated", "--force"],
)
delete_result = runner.invoke(runner.app, ["user", "delete", user.id, "--force"])
delete_result = runner.invoke(runner.app, ["user", "delete", "alice-updated", "--force"])
assert update_result.exit_code == 0
assert "alice-updated" in update_result.stdout
assert delete_result.exit_code == 0
assert f"Deleted user: {user.id}" in delete_result.stdout
assert "Deleted user: alice-updated" in delete_result.stdout
def test_cli_comment_add_and_list() -> None:
repo = FakeRepo(_portfolio())
@@ -910,14 +951,14 @@ def test_cli_tag_add_and_list() -> None:
def test_cli_list_supports_tag_filters() -> None:
repo = FakeRepo(_portfolio())
repo, user = _repo_with_user(_portfolio())
repo.add_tag("005930:tv", tag="grade:A")
runner = build_runner(repo)
result = runner.invoke(runner.app, ["portfolio", "list", "--include-tag", "grade:A", "--match-mode", "AND"])
result = runner.invoke(runner.app, ["portfolio", "list", "--user", "alice", "--include-tag", "grade:A", "--match-mode", "AND"])
assert result.exit_code == 0
assert "005930:tv" in result.stdout
assert "Samsung_Electronics" in result.stdout
def test_cli_tag_remove_flow() -> None: