feat(arch): implement soft delete for business-critical models

Adds SoftDeleteMixin (deleted_at + deleted_by_id) with automatic query
filtering via do_orm_execute event. Soft-deleted records are invisible
by default; bypass with execution_options={"include_deleted": True}.

Models: User, Merchant, Store, StoreUser, Customer, Order, Product,
LoyaltyProgram, LoyaltyCard.

Infrastructure:
- SoftDeleteMixin in models/database/base.py
- Auto query filter registered on SessionLocal and test sessions
- soft_delete(), restore(), soft_delete_cascade() in app/core/soft_delete.py
- Alembic migration adding columns to 9 tables
- Partial unique indexes on users.email/username, stores.store_code/subdomain

Service changes:
- admin_service: delete_user, delete_store → soft_delete/soft_delete_cascade
- merchant_service: delete_merchant → soft_delete_cascade (stores→children)
- store_team_service: remove_team_member → soft_delete (fixes is_active bug)
- product_service: delete_product → soft_delete
- program_service: delete_program → soft_delete_cascade

Admin API:
- include_deleted/only_deleted query params on admin list endpoints
- PUT restore endpoints for users, merchants, stores

Tests: 9 unit tests for soft-delete infrastructure.
Docs: docs/backend/soft-delete.md + follow-up proposals.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-28 21:08:07 +01:00
parent 332960de30
commit 9bceeaac9c
26 changed files with 1069 additions and 51 deletions

View File

@@ -1,6 +1,6 @@
from datetime import UTC, datetime
from sqlalchemy import Column, DateTime
from sqlalchemy import Column, DateTime, ForeignKey, Integer
from app.core.database import Base
@@ -15,3 +15,20 @@ class TimestampMixin:
onupdate=datetime.now(UTC),
nullable=False,
)
class SoftDeleteMixin:
"""Mixin for soft-deletable models.
Adds deleted_at and deleted_by_id columns. Records with deleted_at set
are automatically excluded from queries via the do_orm_execute event
in app.core.database. Use execution_options={"include_deleted": True}
to bypass the filter.
"""
deleted_at = Column(DateTime, nullable=True, index=True)
deleted_by_id = Column(
Integer,
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
)