From a6502ddd5592f5982373c121dba6560698406b95 Mon Sep 17 00:00:00 2001 From: Urvish Date: Tue, 1 Dec 2026 14:19:20 +0530 Subject: [PATCH] feat(cli): add acupedia-access delete-plan command with active subscriber guard --- app/cli/README.md | 16 ++++ app/cli/access.py | 152 +++++++++++++++++++++++++++++++++- tests/test_cli_delete_plan.py | 121 +++++++++++++++++++++++++++ 3 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 tests/test_cli_delete_plan.py diff --git a/app/cli/README.md b/app/cli/README.md index e5a5bfb..39c1d4b 100644 --- a/app/cli/README.md +++ b/app/cli/README.md @@ -76,3 +76,19 @@ acupedia-ops access revoke-plan \ `--user-id ` can be used instead of `--email`. The grant operation is idempotent for an already-active subscription and active module entitlements. It never invents plan/module mappings; the selected plan must already have rows in `commerce.access_plan_modules`. + +Delete an unwanted access plan (dry-run by default; blocks if active subscribers exist): + +```bash +# Dry-run +acupedia-access delete-plan --plan-code TEST_PLAN + +# Execute deletion +acupedia-access delete-plan --plan-code TEST_PLAN --execute + +# Deactivate instead if active subscribers exist +acupedia-access delete-plan --plan-code TEST_PLAN --execute --deactivate + +# Detach expired/cancelled historical subscriptions before deleting +acupedia-access delete-plan --plan-code TEST_PLAN --execute --detach-history +``` diff --git a/app/cli/access.py b/app/cli/access.py index e7332da..99ff5d7 100644 --- a/app/cli/access.py +++ b/app/cli/access.py @@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone import os from uuid import UUID -from sqlalchemy import or_, select +from sqlalchemy import func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app.db.enums import EntitlementStatus, SubscriptionStatus @@ -41,6 +41,16 @@ class RevokeSummary: entitlements_revoked: int +@dataclass(frozen=True) +class DeletePlanSummary: + plan_id: UUID + plan_code: str + action: str + active_subscribers: int + historical_subscriptions: int + modules_mapped: int + + def utcnow() -> datetime: return datetime.now(timezone.utc) @@ -87,6 +97,27 @@ def build_parser() -> argparse.ArgumentParser: help="Reason stored on revoked entitlements/subscriptions.", ) + delete = subparsers.add_parser( + "delete-plan", + help="Safely delete an unwanted access plan (dry-run by default; blocks if active subscribers exist).", + ) + delete.add_argument("--plan-code", required=True, help="Canonical plan code to delete.") + delete.add_argument( + "--execute", + action="store_true", + help="Perform deletion/deactivation. Without this flag, runs in dry-run mode.", + ) + delete.add_argument( + "--detach-history", + action="store_true", + help="Detach inactive/expired historical UserSubscription rows (plan_id=NULL) before deleting.", + ) + delete.add_argument( + "--deactivate", + action="store_true", + help="Deactivate (is_active=False) the plan instead of failing when active subscribers exist.", + ) + return parser @@ -329,6 +360,108 @@ async def revoke_plan( ) +async def delete_plan( + session: AsyncSession, + *, + plan_code: str, + execute: bool = False, + detach_history: bool = False, + deactivate: bool = False, +) -> DeletePlanSummary: + """Safely delete or deactivate an access plan via developer CLI.""" + now = utcnow() + plan = ( + await session.execute(select(AccessPlan).where(AccessPlan.code == plan_code.strip())) + ).scalar_one_or_none() + if plan is None: + raise ValueError(f"Plan not found: {plan_code}") + + active_subscribers = int( + ( + await session.execute( + select(func.count(UserSubscription.id)).where( + UserSubscription.plan_id == plan.id, + UserSubscription.status == SubscriptionStatus.ACTIVE, + or_( + UserSubscription.expires_at.is_(None), + UserSubscription.expires_at > now, + ), + ) + ) + ).scalar_one() + ) + total_subscriptions = int( + ( + await session.execute( + select(func.count(UserSubscription.id)).where( + UserSubscription.plan_id == plan.id + ) + ) + ).scalar_one() + ) + historical_subscriptions = max(0, total_subscriptions - active_subscribers) + modules_mapped = int( + ( + await session.execute( + select(func.count(AccessPlanModule.module_id)).where( + AccessPlanModule.plan_id == plan.id + ) + ) + ).scalar_one() + ) + + if not execute: + return DeletePlanSummary( + plan_id=plan.id, + plan_code=plan.code, + action="dry-run", + active_subscribers=active_subscribers, + historical_subscriptions=historical_subscriptions, + modules_mapped=modules_mapped, + ) + + if active_subscribers > 0: + if deactivate: + plan.is_active = False + plan.updated_at = now + await session.commit() + return DeletePlanSummary( + plan_id=plan.id, + plan_code=plan.code, + action="deactivated", + active_subscribers=active_subscribers, + historical_subscriptions=historical_subscriptions, + modules_mapped=modules_mapped, + ) + raise ValueError( + "Cannot delete plan with active subscribers. Please deactivate instead." + ) + + if historical_subscriptions > 0: + if not detach_history: + raise ValueError( + f"Plan '{plan.code}' has {historical_subscriptions} historical (inactive/expired) " + "subscription(s). Pass --detach-history to set their plan_id=NULL before deleting." + ) + await session.execute( + update(UserSubscription) + .where(UserSubscription.plan_id == plan.id) + .values(plan_id=None, updated_at=now) + ) + + await session.delete(plan) + await session.commit() + + return DeletePlanSummary( + plan_id=plan.id, + plan_code=plan.code, + action="deleted", + active_subscribers=active_subscribers, + historical_subscriptions=historical_subscriptions, + modules_mapped=modules_mapped, + ) + + async def run(args: argparse.Namespace) -> int: if not args.database_url: raise ValueError("DATABASE_URL is required") @@ -366,6 +499,23 @@ async def run(args: argparse.Namespace) -> int: ) return 0 + if args.command == "delete-plan": + summary = await delete_plan( + session, + plan_code=args.plan_code, + execute=args.execute, + detach_history=args.detach_history, + deactivate=args.deactivate, + ) + print( + f"{summary.action.upper()} " + f"plan={summary.plan_code} plan_id={summary.plan_id} " + f"active_subscribers={summary.active_subscribers} " + f"historical_subscriptions={summary.historical_subscriptions} " + f"modules_mapped={summary.modules_mapped}" + ) + return 0 + summary = await revoke_plan( session, email=args.email, diff --git a/tests/test_cli_delete_plan.py b/tests/test_cli_delete_plan.py new file mode 100644 index 0000000..3f68343 --- /dev/null +++ b/tests/test_cli_delete_plan.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from app.cli.access import build_parser, delete_plan + + +def _scalar_result(val): + res = MagicMock() + res.scalar_one_or_none.return_value = val + res.scalar_one.return_value = val + return res + + +@pytest.mark.asyncio +async def test_cli_delete_plan_not_found(): + session = AsyncMock() + session.execute.return_value = _scalar_result(None) + + with pytest.raises(ValueError, match="Plan not found: MISSING"): + await delete_plan(session, plan_code="MISSING", execute=True) + + +@pytest.mark.asyncio +async def test_cli_delete_plan_dry_run_and_execute(): + plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_TEST_DELETE_1", is_active=True, updated_at=None) + session = AsyncMock() + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(0), # active_subscribers + _scalar_result(0), # total_subscriptions + _scalar_result(2), # modules_mapped + ] + + dry = await delete_plan(session, plan_code="CLI_TEST_DELETE_1", execute=False) + assert dry.action == "dry-run" + assert dry.modules_mapped == 2 + session.delete.assert_not_awaited() + + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(0), + _scalar_result(0), + _scalar_result(2), + ] + deleted = await delete_plan(session, plan_code="CLI_TEST_DELETE_1", execute=True) + assert deleted.action == "deleted" + session.delete.assert_awaited_once_with(plan) + session.commit.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_cli_delete_plan_blocks_active_subscribers_and_supports_deactivate(): + plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_ACTIVE", is_active=True, updated_at=None) + session = AsyncMock() + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(3), # active_subscribers + _scalar_result(4), # total_subscriptions + _scalar_result(1), # modules_mapped + ] + + with pytest.raises(ValueError, match="Cannot delete plan with active subscribers. Please deactivate instead."): + await delete_plan(session, plan_code="CLI_ACTIVE", execute=True) + + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(3), + _scalar_result(4), + _scalar_result(1), + ] + deact = await delete_plan(session, plan_code="CLI_ACTIVE", execute=True, deactivate=True) + assert deact.action == "deactivated" + assert plan.is_active is False + session.commit.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_cli_delete_plan_detaches_historical_subscriptions(): + plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_HIST", is_active=True, updated_at=None) + session = AsyncMock() + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(0), # active_subscribers + _scalar_result(2), # total_subscriptions (historical=2) + _scalar_result(1), # modules_mapped + ] + + with pytest.raises(ValueError, match="--detach-history"): + await delete_plan(session, plan_code="CLI_HIST", execute=True) + + session.execute.side_effect = [ + _scalar_result(plan), + _scalar_result(0), + _scalar_result(2), + _scalar_result(1), + MagicMock(), # update(UserSubscription) + ] + deleted = await delete_plan( + session, + plan_code="CLI_HIST", + execute=True, + detach_history=True, + ) + assert deleted.action == "deleted" + assert deleted.historical_subscriptions == 2 + session.delete.assert_awaited_once_with(plan) + session.commit.assert_awaited_once() + + +def test_cli_delete_plan_parser(): + args = build_parser().parse_args(["delete-plan", "--plan-code", "TEST_PLAN", "--execute", "--detach-history"]) + assert args.command == "delete-plan" + assert args.plan_code == "TEST_PLAN" + assert args.execute is True + assert args.detach_history is True + assert args.deactivate is False