elect, update\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom modules.billing.models import (\n    Plan,\n    Subscription,\n    PaymentOrder,\n    PaymentWebhookEvent,\n    Invoice,\n    Refund,\n    Wallet,\n    WalletTransaction,\n    Coupon,\n    CouponRedemption,\n    Referral,\n    TenantUsage,\n)\nfrom modules.bots.models import Bot\nfrom modules.emojis.models import CustomEmoji\n\n\nclass BillingRepository:\n    def __init__(self, db: AsyncSession):\n        self.db = db\n\n    # --- Plans ---\n    async def list_active_plans(self) -> list[Plan]:\n        res = await self.db.execute(select(Plan).where(Plan.is_active.is_(True)).order_by(Plan.price_amount.asc()))\n        return list(res.scalars().all())\n\n    async def get_plan_by_id(self, plan_id: str) -> Optional[Plan]:\n        res = await self.db.execute(select(Plan).where(Plan.id == plan_id))\n        return res.scalar_one_or_none()\n\n    async def upsert_plan(self, plan: Plan) -> Plan:\n        existing = await self.get_plan_by_id(plan.id)\n        if existing:\n            for k, v in plan.__dict__.items():\n                if not k.startswith(\"_\") and k != \"id\":\n                    setattr(existing, k, v)\n            await self.db.commit()\n            await self.db.refresh(existing)\n            return existing\n        self.db.add(plan)\n        await self.db.commit()\n        await self.db.refresh(plan)\n        return plan\n\n    # --- Subscriptions ---\n    async def get_tenant_subscription(self, tenant_id: uuid.UUID) -> Optional[Subscription]:\n        res = await self.db.execute(\n            select(Subscription).where(Subscription.tenant_id == tenant_id)\n        )\n        return res.scalar_one_or_none()\n\n    async def create_subscription(\n        self,\n        tenant_id: uuid.UUID,\n        plan_id: str,\n        status: str,\n        current_period_start: datetime,\n        current_period_end: datetime,\n        gateway_provider: str = \"manual\",\n        trial_start: Optional[datetime] = None,\n        trial_end: Optional[datetime] = None,\n        grace_period_ends_at: Optional[datetime] = None,\n    ) -> Subscription:\n        sub = Subscription(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            plan_id=plan_id,\n            status=status,\n            current_period_start=current_period_start,\n            current_period_end=current_period_end,\n            gateway_provider=gateway_provider,\n            trial_start=trial_start,\n            trial_end=trial_end,\n            grace_period_ends_at=grace_period_ends_at,\n        )\n        self.db.add(sub)\n        await self.db.commit()\n        await self.db.refresh(sub)\n        return sub\n\n    async def update_subscription(\n        self,\n        subscription: Subscription,\n        **updates: Any,\n    ) -> Subscription:\n        for k, v in updates.items():\n            setattr(subscription, k, v)\n        await self.db.commit()\n        await self.db.refresh(subscription)\n        return subscription\n\n    # --- Orders ---\n    async def create_order(\n        self,\n        tenant_id: uuid.UUID,\n        order_number: str,\n        amount: int,\n        currency: str,\n        provider: str,\n        idempotency_key: str,\n        purpose: str = \"subscription\",\n        plan_id: Optional[str] = None,\n        gateway_order_id: Optional[str] = None,\n        metadata_json: Optional[dict[str, Any]] = None,\n    ) -> PaymentOrder:\n        order = PaymentOrder(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            order_number=order_number,\n            amount=amount,\n            currency=currency,\n            status=\"created\",\n            provider=provider,\n            idempotency_key=idempotency_key,\n            purpose=purpose,\n            plan_id=plan_id,\n            gateway_order_id=gateway_order_id,\n            metadata_json=metadata_json or {},\n        )\n        self.db.add(order)\n        await self.db.commit()\n        await self.db.refresh(order)\n        return order\n\n    async def get_order_by_id(self, order_id: uuid.UUID) -> Optional[PaymentOrder]:\n        res = await self.db.execute(select(PaymentOrder).where(PaymentOrder.id == order_id))\n        return res.scalar_one_or_none()\n\n    async def get_order_by_idempotency_key(self, idempotency_key: str) -> Optional[PaymentOrder]:\n        res = await self.db.execute(select(PaymentOrder).where(PaymentOrder.idempotency_key == idempotency_key))\n        return res.scalar_one_or_none()\n\n    async def get_order_by_gateway_order_id(self, gateway_order_id: str) -> Optional[PaymentOrder]:\n        res = await self.db.execute(select(PaymentOrder).where(PaymentOrder.gateway_order_id == gateway_order_id))\n        return res.scalar_one_or_none()\n\n    async def update_order(\n        self,\n        order: PaymentOrder,\n        **updates: Any,\n    ) -> PaymentOrder:\n        for k, v in updates.items():\n            setattr(order, k, v)\n        await self.db.commit()\n        await self.db.refresh(order)\n        return order\n\n    # --- Webhook Events (Duplicate Event Protection) ---\n    async def get_webhook_event(self, gateway_provider: str, event_id: str) -> Optional[PaymentWebhookEvent]:\n        res = await self.db.execute(\n            select(PaymentWebhookEvent).where(\n                PaymentWebhookEvent.gateway_provider == gateway_provider,\n                PaymentWebhookEvent.event_id == event_id,\n            )\n        )\n        return res.scalar_one_or_none()\n\n    async def record_webhook_event(\n        self,\n        gateway_provider: str,\n        event_id: str,\n        event_type: str,\n        payload: dict[str, Any],\n        status: str = \"processed\",\n        error_message: Optional[str] = None,\n    ) -> PaymentWebhookEvent:\n        event = PaymentWebhookEvent(\n            id=uuid.uuid4(),\n            gateway_provider=gateway_provider,\n            event_id=event_id,\n            event_type=event_type,\n            payload=payload,\n            status=status,\n            error_message=error_message,\n        )\n        self.db.add(event)\n        await self.db.commit()\n        await self.db.refresh(event)\n        return event\n\n    # --- Invoices ---\n    async def create_invoice(\n        self,\n        tenant_id: uuid.UUID,\n        invoice_number: str,\n        amount_due: int,\n        amount_paid: int,\n        currency: str,\n        status: str,\n        due_date: datetime,\n        billing_email: str,\n        billing_name: str,\n        items: list[dict[str, Any]],\n        subtotal: int,\n        tax_amount: int,\n        discount_amount: int,\n        subscription_id: Optional[uuid.UUID] = None,\n        order_id: Optional[uuid.UUID] = None,\n        paid_at: Optional[datetime] = None,\n    ) -> Invoice:\n        invoice = Invoice(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            invoice_number=invoice_number,\n            amount_due=amount_due,\n            amount_paid=amount_paid,\n            amount_remaining=amount_due - amount_paid,\n            currency=currency,\n            status=status,\n            due_date=due_date,\n            paid_at=paid_at,\n            billing_email=billing_email,\n            billing_name=billing_name,\n            items=items,\n            subtotal=subtotal,\n            tax_amount=tax_amount,\n            discount_amount=discount_amount,\n            subscription_id=subscription_id,\n            order_id=order_id,\n        )\n        self.db.add(invoice)\n        await self.db.commit()\n        await self.db.refresh(invoice)\n        return invoice\n\n    async def list_tenant_invoices(self, tenant_id: uuid.UUID) -> list[Invoice]:\n        res = await self.db.execute(\n            select(Invoice).where(Invoice.tenant_id == tenant_id).order_by(Invoice.created_at.desc())\n        )\n        return list(res.scalars().all())\n\n    async def get_invoice_by_id(self, invoice_id: uuid.UUID, tenant_id: Optional[uuid.UUID] = None) -> Optional[Invoice]:\n        stmt = select(Invoice).where(Invoice.id == invoice_id)\n        if tenant_id:\n            stmt = stmt.where(Invoice.tenant_id == tenant_id)\n        res = await self.db.execute(stmt)\n        return res.scalar_one_or_none()\n\n    # --- Refunds ---\n    async def create_refund(\n        self,\n        tenant_id: uuid.UUID,\n        order_id: uuid.UUID,\n        amount: int,\n        currency: str,\n        reason: str,\n        provider: str,\n        status: str = \"processed\",\n        gateway_refund_id: Optional[str] = None,\n        invoice_id: Optional[uuid.UUID] = None,\n    ) -> Refund:\n        refund = Refund(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            order_id=order_id,\n            invoice_id=invoice_id,\n            amount=amount,\n            currency=currency,\n            reason=reason,\n            status=status,\n            provider=provider,\n            gateway_refund_id=gateway_refund_id,\n        )\n        self.db.add(refund)\n        await self.db.commit()\n        await self.db.refresh(refund)\n        return refund\n\n    # --- Wallet & Immutable Ledger ---\n    async def get_or_create_wallet(self, tenant_id: uuid.UUID) -> Wallet:\n        res = await self.db.execute(select(Wallet).where(Wallet.tenant_id == tenant_id).with_for_update())\n        wallet = res.scalar_one_or_none()\n        if not wallet:\n            wallet = Wallet(id=uuid.uuid4(), tenant_id=tenant_id, balance=0, currency=\"INR\")\n            self.db.add(wallet)\n            await self.db.commit()\n            await self.db.refresh(wallet)\n        return wallet\n\n    async def record_wallet_transaction(\n        self,\n        tenant_id: uuid.UUID,\n        wallet: Wallet,\n        transaction_type: str,\n        amount: int,\n        balance_after: int,\n        reference_type: str,\n        description: str,\n        reference_id: Optional[str] = None,\n    ) -> WalletTransaction:\n        now_utc = datetime.now(timezone.utc).isoformat()\n        checksum_payload = f\"{wallet.id}:{transaction_type}:{amount}:{balance_after}:{now_utc}\"\n        checksum = hashlib.sha256(checksum_payload.encode(\"utf-8\")).hexdigest()\n\n        tx = WalletTransaction(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            wallet_id=wallet.id,\n            transaction_type=transaction_type,\n            amount=amount,\n            balance_after=balance_after,\n            reference_type=reference_type,\n            reference_id=reference_id,\n            description=description,\n            checksum=checksum,\n        )\n        wallet.balance = balance_after\n        self.db.add(tx)\n        await self.db.commit()\n        await self.db.refresh(tx)\n        return tx\n\n    async def get_wallet_transactions(self, wallet_id: uuid.UUID) -> list[WalletTransaction]:\n        res = await self.db.execute(\n            select(WalletTransaction)\n            .where(WalletTransaction.wallet_id == wallet_id)\n            .order_by(WalletTransaction.created_at.desc())\n        )\n        return list(res.scalars().all())\n\n    # --- Coupons ---\n    async def get_coupon_by_code(self, code: str) -> Optional[Coupon]:\n        res = await self.db.execute(select(Coupon).where(Coupon.code == code.upper()))\n        return res.scalar_one_or_none()\n\n    async def create_coupon(self, coupon: Coupon) -> Coupon:\n        self.db.add(coupon)\n        await self.db.commit()\n        await self.db.refresh(coupon)\n        return coupon\n\n    async def record_coupon_redemption(\n        self,\n        tenant_id: uuid.UUID,\n        coupon_id: uuid.UUID,\n        order_id: uuid.UUID,\n        discount_applied: int,\n    ) -> CouponRedemption:\n        redemption = CouponRedemption(\n            id=uuid.uuid4(),\n            tenant_id=tenant_id,\n            coupon_id=coupon_id,\n            order_id=order_id,\n            discount_applied=discount_applied,\n        )\n        self.db.add(redemption)\n        # Increment coupon times_redeemed\n        await self.db.execute(\n            update(Coupon)\n            .where(Coupon.id == coupon_id)\n            .values(times_redeemed=Coupon.times_redeemed + 1)\n        )\n        await self.db.commit()\n        await self.db.refresh(redemption)\n        return redemption\n\n    # --- Referrals ---\n    async def get_referral_by_referred_tenant(self, referred_tenant_id: uuid.UUID) -> Optional[Referral]:\n        res = await self.db.execute(\n            select(Referral).where(Referral.referred_tenant_id == referred_tenant_id)\n        )\n        return res.scalar_one_or_none()\n\n    async def count_tenant_referrals(self, referrer_tenant_id: uuid.UUID) -> tuple[int, int]:\n        total_res = await self.db.execute(\n            select(func.count(Referral.id)).where(Referral.referrer_tenant_id == referrer_tenant_id)\n        )\n        total = total_res.scalar() or 0\n\n        rewarded_res = await self.db.execute(\n            select(func.coalesce(func.sum(Referral.reward_amount), 0)).where(\n                Referral.referrer_tenant_id == referrer_tenant_id,\n                Referral.status == \"rewarded\",\n            )\n        )\n        rewarded = rewarded_res.scalar() or 0\n        return total, rewarded\n\n    async def create_referral(\n        self,\n        referrer_tenant_id: uuid.UUID,\n        referred_tenant_id: uuid.UUID,\n        referral_code: str,\n    ) -> Referral:\n        ref = Referral(\n            id=uuid.uuid4(),\n            referrer_tenant_id=referrer_tenant_id,\n            referred_tenant_id=referred_tenant_id,\n            referral_code=referral_code,\n            status=\"pending\",\n        )\n        self.db.add(ref)\n        await self.db.commit()\n        await self.db.refresh(ref)\n        return ref\n\n    # --- Entitlement & Usage Counts ---\n    async def count_active_bots(self, tenant_id: uuid.UUID) -> int:\n        res = await self.db.execute(\n            select(func.count(Bot.id)).where(\n                Bot.tenant_id == tenant_id,\n                Bot.status != \"deleted\",\n            )\n        )\n        return res.scalar() or 0\n\n    async def count_custom_emojis(self, tenant_id: Optional[uuid.UUID] = None) -> int:\n        res = await self.db.execute(select(func.count(CustomEmoji.id)))\n        return res.scalar() or 0\n","Overwrite":true,"Path":"/root/telegram-saas/modules/billing/repository.py"}}]}
{"step_index":1558,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:38:34Z","content":"Created At: 2026-11-18T08:38:34Z\nCompleted At: 2026-11-18T08:38:34Z\nCreated At: 2026-11-18T08:38:34Z\nCompleted At: 2026-11-18T08:38:34Z\nCreated file."}
{"step_index":1559,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:38:34Z","model":"gemini-3.8-flash-high","input_tokens":4626,"cache_read_tokens":103432,"output_tokens":1850,"thinking":"Building the entitlement service within the billing module, starting with `entitlement_service.py`. The `EntitlementService` will handle tenant plan retrieval, bot creation limit checks raising `QuotaExceededError`, and feature access verification raising `ForbiddenError` based on boolean features like AI enablement.\n\n\n","tool_calls":[{"name":"write_file","args":{"Content":"import uuid\nfrom datetime import datetime, timezone\nfrom typing import Any\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom core.exceptions import ForbiddenError, NotFoundError, QuotaExceededError\nfrom modules.billing.models import Plan, Subscription\nfrom modules.billing.repository import BillingRepository\n\n\nclass EntitlementService:\n    \"\"\"Enforces plan quotas, feature entitlement gates, and tracks usage.\"\"\"\n\n    def __init__(self, db: AsyncSession):\n        self.db = db\n        self.repo = BillingRepository(db)\n\n    async def get_tenant_plan_and_sub(self, tenant_id: uuid.UUID) -> tuple[Plan, Subscription]:\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if not sub:\n            # Create default free subscription\n            now = datetime.now(timezone.utc)\n            period_end = datetime(2099, 12, 31, tzinfo=timezone.utc)\n            sub = await self.repo.create_subscription(\n                tenant_id=tenant_id,\n                plan_id=\"free\",\n                status=\"active\",\n                current_period_start=now,\n                current_period_end=period_end,\n                gateway_provider=\"manual\",\n            )\n\n        plan = await self.repo.get_plan_by_id(sub.plan_id)\n        if not plan:\n            plan = await self.repo.get_plan_by_id(\"free\")\n            if not plan:\n                raise NotFoundError(f\"Plan '{sub.plan_id}' not found in database\")\n\n        return plan, sub\n\n    async def check_bot_creation_limit(self, tenant_id: uuid.UUID) -> None:\n        \"\"\"\n        Validates whether tenant can add a new bot under current plan limits.\n        Raises QuotaExceededError if limit is reached.\n        \"\"\"\n        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)\n\n        # If subscription is expired or past due outside grace period, restrict to free tier\n        now = datetime.now(timezone.utc)\n        if sub.status == \"expired\" or (sub.status == \"past_due\" and sub.grace_period_ends_at and now > sub.grace_period_ends_at):\n            free_plan = await self.repo.get_plan_by_id(\"free\")\n            if free_plan:\n                plan = free_plan\n\n        if plan.max_bots != -1:\n            current_bots = await self.repo.count_active_bots(tenant_id)\n            if current_bots >= plan.max_bots:\n                raise QuotaExceededError(\n                    f\"Plan '{plan.name}' limit of {plan.max_bots} active bot(s) reached. \"\n                    f\"Please upgrade your subscription to connect more bots.\",\n                    details={\n                        \"current_usage\": current_bots,\n                        \"limit\": plan.max_bots,\n                        \"plan_id\": plan.id,\n                        \"upgrade_url\": \"/billing\",\n                    },\n                )\n\n    async def check_feature_access(self, tenant_id: uuid.UUID, feature_name: str) -> None:\n        \"\"\"\n        Validates boolean feature entitlement (e.g. ai_enabled, advanced_studio, custom_domain).\n        Raises ForbiddenError if feature is not included.\n        \"\"\"\n        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)\n        has_access = getattr(plan, feature_name, False)\n        if not has_access:\n            raise ForbiddenError(\n                f\"Feature '{feature_name}' is not available on the '{plan.name}' plan. \"\n                f\"Please upgrade to unlock this feature.\",\n                details={\"feature\": feature_name, \"plan_id\": plan.id},\n            )\n\n    async def get_tenant_limits_and_usage(self, tenant_id: uuid.UUID) -> dict[str, Any]:\n        \"\"\"Compiles usage vs entitlement limits for the tenant dashboard.\"\"\"\n        plan, sub = await self.get_tenant_plan_and_sub(tenant_id)\n        current_bots = await self.repo.count_active_bots(tenant_id)\n        current_emojis = await self.repo.count_custom_emojis(tenant_id)\n\n        now = datetime.now(timezone.utc)\n        in_grace = (\n            sub.status == \"grace_period\"\n            or (sub.grace_period_ends_at is not None and now < sub.grace_period_ends_at)\n        )\n\n        return {\n            \"plan_id\": plan.id,\n            \"plan_name\": plan.name,\n            \"subscription_status\": sub.status,\n            \"period_start\": sub.current_period_start,\n            \"period_end\": sub.current_period_end,\n            \"grace_period_active\": in_grace,\n            \"bots\": {\n                \"current\": current_bots,\n                \"limit\": plan.max_bots,\n                \"allowed\": plan.max_bots == -1 or current_bots < plan.max_bots,\n            },\n            \"broadcasts\": {\n                \"current\": 0,\n                \"limit\": plan.max_broadcasts_per_month,\n                \"allowed\": True,\n            },\n            \"custom_emojis\": {\n                \"current\": current_emojis,\n                \"limit\": plan.max_custom_emojis,\n                \"allowed\": plan.max_custom_emojis == -1 or current_emojis < plan.max_custom_emojis,\n            },\n            \"features\": {\n                \"ai_enabled\": plan.ai_enabled,\n                \"advanced_studio\": plan.advanced_studio,\n                \"custom_domain\": plan.custom_domain,\n                \"priority_support\": plan.priority_support,\n            },\n        }\n","Overwrite":true,"Path":"/root/telegram-saas/modules/billing/entitlement_service.py"}}]}
{"step_index":1560,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:38:47Z","content":"Created At: 2026-11-18T08:38:47Z\nCompleted At: 2026-11-18T08:38:47Z\nCreated At: 2026-11-18T08:38:47Z\nCompleted At: 2026-11-18T08:38:47Z\nCreated file."}
{"step_index":1561,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:38:47Z","model":"gemini-3.8-flash-high","input_tokens":3940,"cache_read_tokens":106034,"output_tokens":775,"tool_calls":[{"name":"write_file","args":{"Content":"import uuid\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom core.exceptions import InsufficientFundsError, ValidationError\nfrom modules.billing.models import Wallet, WalletTransaction\nfrom modules.billing.repository import BillingRepository\n\n\nclass WalletService:\n    \"\"\"Manages prepaid tenant wallets and the immutable transaction ledger.\"\"\"\n\n    def __init__(self, db: AsyncSession):\n        self.db = db\n        self.repo = BillingRepository(db)\n\n    async def get_or_create_wallet(self, tenant_id: uuid.UUID) -> Wallet:\n        return await self.repo.get_or_create_wallet(tenant_id)\n\n    async def credit(\n        self,\n        tenant_id: uuid.UUID,\n        amount: int,\n        reference_type: str,\n        description: str,\n        reference_id: str | None = None,\n    ) -> WalletTransaction:\n        if amount <= 0:\n            raise ValidationError(\"Credit amount must be greater than zero\")\n\n        wallet = await self.get_or_create_wallet(tenant_id)\n        new_balance = wallet.balance + amount\n        return await self.repo.record_wallet_transaction(\n            tenant_id=tenant_id,\n            wallet=wallet,\n            transaction_type=\"credit\",\n            amount=amount,\n            balance_after=new_balance,\n            reference_type=reference_type,\n            reference_id=reference_id,\n            description=description,\n        )\n\n    async def debit(\n        self,\n        tenant_id: uuid.UUID,\n        amount: int,\n        reference_type: str,\n        description: str,\n        reference_id: str | None = None,\n    ) -> WalletTransaction:\n        if amount <= 0:\n            raise ValidationError(\"Debit amount must be greater than zero\")\n\n        wallet = await self.get_or_create_wallet(tenant_id)\n        if wallet.is_frozen:\n            raise ValidationError(\"Wallet is currently frozen. Contact support.\")\n        if wallet.balance < amount:\n            raise InsufficientFundsError(\n                f\"Insufficient wallet balance. Required: {amount / 100:.2f}, Available: {wallet.balance / 100:.2f}\"\n            )\n\n        new_balance = wallet.balance - amount\n        return await self.repo.record_wallet_transaction(\n            tenant_id=tenant_id,\n            wallet=wallet,\n            transaction_type=\"debit\",\n            amount=amount,\n            balance_after=new_balance,\n            reference_type=reference_type,\n            reference_id=reference_id,\n            description=description,\n        )\n\n    async def get_transactions(self, tenant_id: uuid.UUID) -> list[WalletTransaction]:\n        wallet = await self.get_or_create_wallet(tenant_id)\n        return await self.repo.get_wallet_transactions(wallet.id)\n","Overwrite":true,"Path":"/root/telegram-saas/modules/billing/wallet_service.py"}}]}
{"step_index":1562,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:38:54Z","content":"Created At: 2026-11-18T08:38:54Z\nCompleted At: 2026-11-18T08:38:54Z\nCreated At: 2026-11-18T08:38:54Z\nCompleted At: 2026-11-18T08:38:54Z\nCreated file."}
{"step_index":1563,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:38:55Z","model":"gemini-3.8-flash-high","input_tokens":2314,"cache_read_tokens":108501,"output_tokens":959,"tool_calls":[{"name":"write_file","args":{"Content":"import uuid\nfrom datetime import datetime, timezone\nfrom typing import Optional\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom core.exceptions import NotFoundError, ValidationError\nfrom modules.billing.models import Coupon, CouponRedemption, Referral\nfrom modules.billing.repository import BillingRepository\n\n\nclass CouponService:\n    \"\"\"Manages discount coupons and referral rewards.\"\"\"\n\n    def __init__(self, db: AsyncSession):\n        self.db = db\n        self.repo = BillingRepository(db)\n\n    async def validate_coupon(\n        self,\n        code: str,\n        plan_id: str,\n        order_amount: int,\n    ) -> tuple[bool, Optional[Coupon], int, str]:\n        \"\"\"\n        Validates coupon against plan, order value, expiry date, and redemption limits.\n        Returns: (is_valid, coupon, discount_amount, message)\n        \"\"\"\n        coupon = await self.repo.get_coupon_by_code(code)\n        if not coupon:\n            return False, None, 0, f\"Coupon code '{code}' does not exist\"\n\n        if not coupon.is_active:\n            return False, coupon, 0, f\"Coupon '{code}' is no longer active\"\n\n        now = datetime.now(timezone.utc)\n        if coupon.expires_at and now > coupon.expires_at:\n            return False, coupon, 0, f\"Coupon '{code}' has expired\"\n\n        if coupon.max_redemptions and coupon.times_redeemed >= coupon.max_redemptions:\n            return False, coupon, 0, f\"Coupon '{code}' has reached its maximum redemptions limit\"\n\n        if coupon.applicable_plans and plan_id not in coupon.applicable_plans:\n            return False, coupon, 0, f\"Coupon '{code}' is not applicable to the '{plan_id}' plan\"\n\n        if order_amount < coupon.min_order_amount:\n            return False, coupon, 0, f\"Minimum order amount of {coupon.min_order_amount / 100:.2f} required for coupon\"\n\n        # Calculate discount\n        if coupon.discount_type == \"percentage\":\n            discount = int(order_amount * (coupon.discount_value / 100))\n        else:  # fixed_amount\n            discount = min(coupon.discount_value, order_amount)\n\n        if coupon.max_discount_amount:\n            discount = min(discount, coupon.max_discount_amount)\n\n        return True, coupon, discount, \"Coupon applied successfully\"\n\n    async def record_redemption(\n        self,\n        tenant_id: uuid.UUID,\n        coupon_id: uuid.UUID,\n        order_id: uuid.UUID,\n        discount_applied: int,\n    ) -> CouponRedemption:\n        return await self.repo.record_coupon_redemption(\n            tenant_id=tenant_id,\n            coupon_id=coupon_id,\n            order_id=order_id,\n            discount_applied=discount_applied,\n        )\n\n    async def register_referral(\n        self,\n        referrer_tenant_id: uuid.UUID,\n        referred_tenant_id: uuid.UUID,\n        referral_code: str,\n    ) -> Referral:\n        existing = await self.repo.get_referral_by_referred_tenant(referred_tenant_id)\n        if existing:\n            return existing\n        return await self.repo.create_referral(\n            referrer_tenant_id=referrer_tenant_id,\n            referred_tenant_id=referred_tenant_id,\n            referral_code=referral_code,\n        )\n","Overwrite":true,"Path":"/root/telegram-saas/modules/billing/coupon_service.py"}}]}
{"step_index":1564,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:39:02Z","content":"Created At: 2026-11-18T08:39:02Z\nCompleted At: 2026-11-18T08:39:03Z\nCreated At: 2026-11-18T08:39:02Z\nCompleted At: 2026-11-18T08:39:03Z\nCreated file."}
{"step_index":1565,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:39:03Z","model":"gemini-3.8-flash-high","input_tokens":3057,"cache_read_tokens":108783,"output_tokens":12761,"thinking":"Creating the billing service module. Initial focus is on defining default pricing plans, including their features and monthly costs in both rupees and paise. Plan details include the number of bots, broadcasts, custom emojis, and advanced studio availability for `free`, `starter`, and `pro` tiers.\n\n\nDefining the `enterprise` plan with unlimited resources and a monthly cost. Implementing subscription management with `get_or_create_subscription` to retrieve or default to the `free` tier. Building the checkout order process, including coupon validation, price calculation, unique order number generation, idempotency checks, gateway interaction, and order persistence.\n\nThe server-side payment verification process will rigorously check payment status, verify signatures, mark orders as paid or failed, and activate subscriptions, setting the status, billing period, and clearing the grace period.\n\n\nInvoice generation now implemented, including itemized details, tax calculation (18% GST), and discount application, with a `paid` status. Coupon redemption is recorded if used. A ₹500 referral reward is added to the referrer's wallet for the first payment. Subscription upgrades and downgrades now include proration logic using the unused time ratio to calculate credits and net payable amounts.\n\nSubscription cancellation functionality added, allowing immediate cancellation or scheduled cancellation at the end of the billing period, with a downgrade to the `free` tier.  Renewal mechanisms are created for both checkout generation and active subscription renewals. Logic added for handling subscription expiry, including a grace period if applicable.\n\n\nGrace period logic has been created, setting `grace_period_ends_at` to the current period's end plus three days. If the current time exceeds `grace_period_ends_at`, the subscription status transitions to `expired`, and the tenant is downgraded to the free tier plan.\n\nWebhook handling verifies HMAC signatures before processing and checks for duplicate events based on provider and event ID.  Payment events are categorized to trigger specific actions, such as marking orders as paid or failed, updating subscription statuses, handling refunds, and marking subscriptions as canceled.\n\nRefund processing verifies prior payment before initiating a gateway refund, updating order and invoice statuses to reflect the refund.\n\n\n","tool_calls":[{"name":"write_file","args":{"Content":"import hashlib\nimport json\nimport uuid\nfrom datetime import datetime, timedelta, timezone\nfrom typing import Any, Optional\nfrom sqlalchemy import select\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom core.config import get_settings\nfrom core.exceptions import (\n    ConflictError,\n    ForbiddenError,\n    NotFoundError,\n    PaymentError,\n    QuotaExceededError,\n    UnauthorizedError,\n    ValidationError,\n)\nfrom core.logging import get_logger\nfrom infrastructure.payments.gateway_factory import GatewayFactory\nfrom modules.billing.coupon_service import CouponService\nfrom modules.billing.entitlement_service import EntitlementService\nfrom modules.billing.models import (\n    Invoice,\n    PaymentOrder,\n    PaymentWebhookEvent,\n    Plan,\n    Refund,\n    Subscription,\n)\nfrom modules.billing.repository import BillingRepository\nfrom modules.billing.schemas import (\n    CheckoutOrderRequest,\n    CheckoutOrderResponse,\n    InvoiceResponse,\n    PaymentVerificationRequest,\n    PaymentVerificationResponse,\n    PlanResponse,\n    RefundRequest,\n    RefundResponse,\n    SubscriptionResponse,\n)\nfrom modules.billing.wallet_service import WalletService\nfrom modules.tenants.models import Tenant\n\nlogger = get_logger(__name__)\n\n\nclass BillingService:\n    \"\"\"Core enterprise billing, subscriptions, invoices, and payment orchestration service.\"\"\"\n\n    def __init__(self, db: AsyncSession):\n        self.db = db\n        self.repo = BillingRepository(db)\n        self.entitlements = EntitlementService(db)\n        self.wallets = WalletService(db)\n        self.coupons = CouponService(db)\n\n    # --- Seed Default Plans ---\n    async def seed_default_plans(self) -> None:\n        \"\"\"Seeds the 4 standard commercial tiers if not already populated.\"\"\"\n        default_plans = [\n            Plan(\n                id=\"free\",\n                name=\"Free Tier\",\n                description=\"Essential features to test and run your first Telegram bot.\",\n                price_amount=0,\n                currency=\"INR\",\n                billing_interval=\"monthly\",\n                trial_days=0,\n                is_active=True,\n                max_bots=1,\n                max_broadcasts_per_month=100,\n                max_custom_emojis=10,\n                ai_enabled=False,\n                advanced_studio=False,\n                custom_domain=False,\n                priority_support=False,\n                webhook_rate_limit=10,\n            ),\n            Plan(\n                id=\"starter\",\n                name=\"Starter Plan\",\n                description=\"Designed for creators running up to 3 bots with custom styling.\",\n                price_amount=99900,  # ₹999.00\n                currency=\"INR\",\n                billing_interval=\"monthly\",\n                trial_days=7,\n                is_active=True,\n                max_bots=3,\n                max_broadcasts_per_month=2500,\n                max_custom_emojis=50,\n                ai_enabled=False,\n                advanced_studio=True,\n                custom_domain=False,\n                priority_support=False,\n                webhook_rate_limit=30,\n            ),\n            Plan(\n                id=\"pro\",\n                name=\"Pro Supercharged\",\n                description=\"Full AI integration, advanced Message Studio, and up to 10 bots.\",\n                price_amount=299900,  # ₹2,999.00\n                currency=\"INR\",\n                billing_interval=\"monthly\",\n                trial_days=14,\n                is_active=True,\n                max_bots=10,\n                max_broadcasts_per_month=25000,\n                max_custom_emojis=500,\n                ai_enabled=True,\n                advanced_studio=True,\n                custom_domain=False,\n                priority_support=True,\n                webhook_rate_limit=60,\n            ),\n            Plan(\n                id=\"enterprise\",\n                name=\"Enterprise Max\",\n                description=\"Unlimited scale, custom domain, and dedicated infrastructure.\",\n                price_amount=999900,  # ₹9,999.00\n                currency=\"INR\",\n                billing_interval=\"monthly\",\n                trial_days=14,\n                is_active=True,\n                max_bots=-1,  # unlimited\n                max_broadcasts_per_month=-1,\n                max_custom_emojis=-1,\n                ai_enabled=True,\n                advanced_studio=True,\n                custom_domain=True,\n                priority_support=True,\n                webhook_rate_limit=120,\n            ),\n        ]\n        for plan in default_plans:\n            await self.repo.upsert_plan(plan)\n\n    # --- Plans Catalog ---\n    async def list_plans(self) -> list[PlanResponse]:\n        plans = await self.repo.list_active_plans()\n        if not plans:\n            await self.seed_default_plans()\n            plans = await self.repo.list_active_plans()\n\n        return [\n            PlanResponse(\n                id=p.id,\n                name=p.name,\n                description=p.description,\n                price_amount=p.price_amount,\n                price_formatted=f\"₹{p.price_amount / 100:.2f}\" if p.currency == \"INR\" else f\"${p.price_amount / 100:.2f}\",\n                currency=p.currency,\n                billing_interval=p.billing_interval,\n                trial_days=p.trial_days,\n                is_active=p.is_active,\n                max_bots=p.max_bots,\n                max_broadcasts_per_month=p.max_broadcasts_per_month,\n                max_custom_emojis=p.max_custom_emojis,\n                ai_enabled=p.ai_enabled,\n                advanced_studio=p.advanced_studio,\n                custom_domain=p.custom_domain,\n                priority_support=p.priority_support,\n                webhook_rate_limit=p.webhook_rate_limit,\n            )\n            for p in plans\n        ]\n\n    # --- Subscriptions ---\n    async def get_tenant_subscription(self, tenant_id: uuid.UUID) -> SubscriptionResponse:\n        plan, sub = await self.entitlements.get_tenant_plan_and_sub(tenant_id)\n        return SubscriptionResponse(\n            id=sub.id,\n            tenant_id=sub.tenant_id,\n            plan_id=sub.plan_id,\n            plan_name=plan.name,\n            status=sub.status,\n            current_period_start=sub.current_period_start,\n            current_period_end=sub.current_period_end,\n            cancel_at_period_end=sub.cancel_at_period_end,\n            canceled_at=sub.canceled_at,\n            trial_start=sub.trial_start,\n            trial_end=sub.trial_end,\n            grace_period_ends_at=sub.grace_period_ends_at,\n            gateway_provider=sub.gateway_provider,\n        )\n\n    # --- Checkout & Order Creation ---\n    async def create_checkout_order(\n        self,\n        tenant_id: uuid.UUID,\n        req: CheckoutOrderRequest,\n    ) -> CheckoutOrderResponse:\n        \"\"\"\n        Creates a payment order with idempotency guarantee and gateway integration.\n        \"\"\"\n        plan = await self.repo.get_plan_by_id(req.plan_id)\n        if not plan:\n            raise NotFoundError(f\"Plan '{req.plan_id}' does not exist\")\n\n        idempotency_key = req.idempotency_key or f\"idem_{tenant_id}_{req.plan_id}_{uuid.uuid4().hex[:12]}\"\n        existing_order = await self.repo.get_order_by_idempotency_key(idempotency_key)\n        if existing_order and existing_order.status == \"created\":\n            return CheckoutOrderResponse(\n                order_id=existing_order.id,\n                order_number=existing_order.order_number,\n                amount=existing_order.amount,\n                amount_formatted=f\"₹{existing_order.amount / 100:.2f}\",\n                currency=existing_order.currency,\n                provider=existing_order.provider,\n                gateway_order_id=existing_order.gateway_order_id,\n                status=existing_order.status,\n            )\n\n        # Discount calculation\n        final_amount = plan.price_amount\n        coupon_id = None\n        discount_applied = 0\n        if req.coupon_code:\n            is_valid, coupon, discount, _ = await self.coupons.validate_coupon(\n                req.coupon_code, plan.id, plan.price_amount\n            )\n            if is_valid and coupon:\n                discount_applied = discount\n                final_amount = max(0, plan.price_amount - discount)\n                coupon_id = str(coupon.id)\n\n        now_str = datetime.now(timezone.utc).strftime(\"%Y%m%d\")\n        order_number = f\"ORD-{now_str}-{uuid.uuid4().hex[:8].upper()}\"\n\n        gateway_order_id = None\n        gateway_key_id = None\n        checkout_url = None\n\n        if req.provider in (\"razorpay\", \"stripe\") and final_amount > 0:\n            gateway = GatewayFactory.get_gateway(req.provider)\n            gw_resp = await gateway.create_order(\n                amount=final_amount,\n                currency=plan.currency,\n                receipt=order_number,\n                notes={\n                    \"tenant_id\": str(tenant_id),\n                    \"plan_id\": plan.id,\n                    \"plan_name\": plan.name,\n                    \"order_number\": order_number,\n                },\n                idempotency_key=idempotency_key,\n            )\n            gateway_order_id = gw_resp.get(\"id\")\n            gateway_key_id = gw_resp.get(\"key_id\")\n            checkout_url = gw_resp.get(\"url\")\n\n        order = await self.repo.create_order(\n            tenant_id=tenant_id,\n            order_number=order_number,\n            amount=final_amount,\n            currency=plan.currency,\n            provider=req.provider,\n            idempotency_key=idempotency_key,\n            purpose=\"subscription\",\n            plan_id=plan.id,\n            gateway_order_id=gateway_order_id,\n            metadata_json={\n                \"coupon_id\": coupon_id,\n                \"discount_applied\": discount_applied,\n                \"original_amount\": plan.price_amount,\n                \"plan_name\": plan.name,\n            },\n        )\n\n        return CheckoutOrderResponse(\n            order_id=order.id,\n            order_number=order.order_number,\n            amount=order.amount,\n            amount_formatted=f\"₹{order.amount / 100:.2f}\" if order.currency == \"INR\" else f\"${order.amount / 100:.2f}\",\n            currency=order.currency,\n            provider=order.provider,\n            gateway_order_id=gateway_order_id,\n            gateway_key_id=gateway_key_id,\n            checkout_url=checkout_url,\n            status=order.status,\n        )\n\n    # --- Server-Side Payment Verification & Activation ---\n    async def verify_and_activate_payment(\n        self,\n        tenant_id: uuid.UUID,\n        req: PaymentVerificationRequest,\n    ) -> PaymentVerificationResponse:\n        \"\"\"\n        Server-side cryptographic verification of payment completion.\n        Never trusts client-reported success without gateway signature confirmation.\n        \"\"\"\n        order = await self.repo.get_order_by_id(req.order_id)\n        if not order:\n            raise NotFoundError(\"Order not found\")\n\n        if order.tenant_id != tenant_id:\n            raise ForbiddenError(\"Cross-tenant order verification forbidden\")\n\n        if order.status == \"paid\":\n            # Idempotent response\n            sub = await self.repo.get_tenant_subscription(tenant_id)\n            return PaymentVerificationResponse(\n                success=True,\n                message=\"Payment already verified and subscription active\",\n                order_id=order.id,\n                status=\"paid\",\n                subscription_id=sub.id if sub else uuid.uuid4(),\n            )\n\n        # Verify signature with gateway\n        gateway = GatewayFactory.get_gateway(req.provider)\n        gateway_order_id = order.gateway_order_id or str(order.id)\n        is_valid = gateway.verify_payment_signature(\n            order_id=gateway_order_id,\n            payment_id=req.payment_id,\n            signature=req.signature or \"\",\n        )\n\n        if not is_valid:\n            await self.repo.update_order(order, status=\"failed\", gateway_payment_id=req.payment_id)\n            logger.warning(\"payment_signature_verification_failed\", order_id=str(order.id), payment_id=req.payment_id)\n            raise PaymentError(\"Cryptographic payment signature verification failed\")\n\n        # Mark order paid\n        await self.repo.update_order(\n            order,\n            status=\"paid\",\n            gateway_payment_id=req.payment_id,\n            gateway_signature=req.signature,\n        )\n\n        # Activate Subscription\n        now = datetime.now(timezone.utc)\n        period_end = now + timedelta(days=30)\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if sub:\n            await self.repo.update_subscription(\n                sub,\n                plan_id=order.plan_id or \"starter\",\n                status=\"active\",\n                current_period_start=now,\n                current_period_end=period_end,\n                cancel_at_period_end=False,\n                grace_period_ends_at=None,\n                gateway_provider=req.provider,\n                gateway_subscription_id=req.payment_id,\n            )\n        else:\n            sub = await self.repo.create_subscription(\n                tenant_id=tenant_id,\n                plan_id=order.plan_id or \"starter\",\n                status=\"active\",\n                current_period_start=now,\n                current_period_end=period_end,\n                gateway_provider=req.provider,\n            )\n\n        # Update tenant model plan_id\n        await self.db.execute(\n            select(Tenant).where(Tenant.id == tenant_id)\n        )\n        tenant_res = await self.db.get(Tenant, tenant_id)\n        if tenant_res:\n            tenant_res.plan_id = order.plan_id\n            await self.db.commit()\n\n        # Generate Invoice\n        invoice_number = f\"INV-{now.strftime('%Y')}-{uuid.uuid4().hex[:6].upper()}\"\n        plan = await self.repo.get_plan_by_id(order.plan_id or \"starter\")\n        subtotal = order.amount\n        tax = int(subtotal * 0.18)  # 18% GST / VAT\n        discount = (order.metadata_json or {}).get(\"discount_applied\", 0)\n\n        invoice = await self.repo.create_invoice(\n            tenant_id=tenant_id,\n            invoice_number=invoice_number,\n            amount_due=order.amount,\n            amount_paid=order.amount,\n            currency=order.currency,\n            status=\"paid\",\n            due_date=now,\n            paid_at=now,\n            billing_email=f\"billing@{tenant_id}.saas\",\n            billing_name=tenant_res.name if tenant_res else \"Tenant Organization\",\n            items=[{\n                \"description\": f\"Subscription Plan: {plan.name if plan else order.plan_id} (1 Month)\",\n                \"quantity\": 1,\n                \"unit_price\": order.amount,\n                \"total\": order.amount,\n            }],\n            subtotal=subtotal,\n            tax_amount=tax,\n            discount_amount=discount,\n            subscription_id=sub.id,\n            order_id=order.id,\n        )\n\n        # Record Coupon Redemption if applied\n        coupon_id_str = (order.metadata_json or {}).get(\"coupon_id\")\n        if coupon_id_str and discount > 0:\n            await self.coupons.record_redemption(\n                tenant_id=tenant_id,\n                coupon_id=uuid.UUID(coupon_id_str),\n                order_id=order.id,\n                discount_applied=discount,\n            )\n\n        # Trigger referral bonus if tenant was referred and this is their first payment\n        referral = await self.repo.get_referral_by_referred_tenant(tenant_id)\n        if referral and referral.status == \"pending\":\n            referral.status = \"rewarded\"\n            referral.rewarded_at = now\n            await self.db.commit()\n            # Reward referrer wallet with ₹500 credits\n            await self.wallets.credit(\n                tenant_id=referral.referrer_tenant_id,\n                amount=referral.reward_amount,\n                reference_type=\"referral\",\n                description=f\"Referral reward for inviting tenant {tenant_res.name if tenant_res else str(tenant_id)[:8]}\",\n                reference_id=str(referral.id),\n            )\n\n        return PaymentVerificationResponse(\n            success=True,\n            message=\"Payment successfully verified and subscription activated\",\n            order_id=order.id,\n            status=\"paid\",\n            subscription_id=sub.id,\n            invoice_id=invoice.id,\n        )\n\n    # --- Pay with Wallet Balance ---\n    async def pay_with_wallet(\n        self,\n        tenant_id: uuid.UUID,\n        plan_id: str,\n        coupon_code: Optional[str] = None,\n    ) -> PaymentVerificationResponse:\n        \"\"\"Allows tenants to subscribe or renew instantly using prepaid wallet credits.\"\"\"\n        plan = await self.repo.get_plan_by_id(plan_id)\n        if not plan:\n            raise NotFoundError(f\"Plan '{plan_id}' does not exist\")\n\n        amount_to_pay = plan.price_amount\n        discount_applied = 0\n        coupon_id = None\n        if coupon_code:\n            is_valid, coupon, discount, _ = await self.coupons.validate_coupon(\n                coupon_code, plan.id, plan.price_amount\n            )\n            if is_valid and coupon:\n                discount_applied = discount\n                amount_to_pay = max(0, plan.price_amount - discount)\n                coupon_id = str(coupon.id)\n\n        # Debit wallet atomically\n        tx = await self.wallets.debit(\n            tenant_id=tenant_id,\n            amount=amount_to_pay,\n            reference_type=\"subscription\",\n            description=f\"Wallet payment for plan: {plan.name}\",\n        )\n\n        now = datetime.now(timezone.utc)\n        order_number = f\"ORD-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}\"\n        order = await self.repo.create_order(\n            tenant_id=tenant_id,\n            order_number=order_number,\n            amount=amount_to_pay,\n            currency=plan.currency,\n            provider=\"wallet\",\n            idempotency_key=f\"wallet_{tx.id}\",\n            purpose=\"subscription\",\n            plan_id=plan.id,\n            gateway_order_id=str(tx.id),\n            metadata_json={\"wallet_tx_id\": str(tx.id), \"discount_applied\": discount_applied},\n        )\n        await self.repo.update_order(order, status=\"paid\", gateway_payment_id=str(tx.id))\n\n        # Update Subscription\n        period_end = now + timedelta(days=30)\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if sub:\n            await self.repo.update_subscription(\n                sub,\n                plan_id=plan.id,\n                status=\"active\",\n                current_period_start=now,\n                current_period_end=period_end,\n                cancel_at_period_end=False,\n                grace_period_ends_at=None,\n                gateway_provider=\"wallet\",\n            )\n        else:\n            sub = await self.repo.create_subscription(\n                tenant_id=tenant_id,\n                plan_id=plan.id,\n                status=\"active\",\n                current_period_start=now,\n                current_period_end=period_end,\n                gateway_provider=\"wallet\",\n            )\n\n        # Update tenant plan_id\n        tenant_res = await self.db.get(Tenant, tenant_id)\n        if tenant_res:\n            tenant_res.plan_id = plan.id\n            await self.db.commit()\n\n        # Create Invoice\n        invoice_num = f\"INV-{now.strftime('%Y')}-{uuid.uuid4().hex[:6].upper()}\"\n        invoice = await self.repo.create_invoice(\n            tenant_id=tenant_id,\n            invoice_number=invoice_num,\n            amount_due=amount_to_pay,\n            amount_paid=amount_to_pay,\n            currency=plan.currency,\n            status=\"paid\",\n            due_date=now,\n            paid_at=now,\n            billing_email=f\"billing@{tenant_id}.saas\",\n            billing_name=tenant_res.name if tenant_res else \"Tenant Organization\",\n            items=[{\n                \"description\": f\"Subscription Plan: {plan.name} (Paid via Wallet)\",\n                \"quantity\": 1,\n                \"unit_price\": amount_to_pay,\n                \"total\": amount_to_pay,\n            }],\n            subtotal=amount_to_pay,\n            tax_amount=0,\n            discount_amount=discount_applied,\n            subscription_id=sub.id,\n            order_id=order.id,\n        )\n\n        return PaymentVerificationResponse(\n            success=True,\n            message=\"Payment completed successfully with wallet balance\",\n            order_id=order.id,\n            status=\"paid\",\n            subscription_id=sub.id,\n            invoice_id=invoice.id,\n        )\n\n    # --- Upgrade / Downgrade with Proration ---\n    async def upgrade_subscription(\n        self,\n        tenant_id: uuid.UUID,\n        new_plan_id: str,\n        provider: str = \"razorpay\",\n        coupon_code: Optional[str] = None,\n    ) -> CheckoutOrderResponse:\n        \"\"\"\n        Calculates proration credit for unused time on existing plan, creating checkout order for the delta.\n        \"\"\"\n        new_plan = await self.repo.get_plan_by_id(new_plan_id)\n        if not new_plan:\n            raise NotFoundError(f\"Target plan '{new_plan_id}' not found\")\n\n        old_plan, sub = await self.entitlements.get_tenant_plan_and_sub(tenant_id)\n        now = datetime.now(timezone.utc)\n\n        # Calculate unused proration credit\n        prorated_credit = 0\n        if sub.status == \"active\" and sub.current_period_end > now and old_plan.price_amount > 0:\n            total_seconds = (sub.current_period_end - sub.current_period_start).total_seconds()\n            remaining_seconds = (sub.current_period_end - now).total_seconds()\n            if total_seconds > 0:\n                unused_ratio = max(0.0, min(1.0, remaining_seconds / total_seconds))\n                prorated_credit = int(old_plan.price_amount * unused_ratio)\n\n        net_amount = max(0, new_plan.price_amount - prorated_credit)\n\n        # Apply coupon if given\n        discount = 0\n        if coupon_code:\n            is_valid, coupon, d_amt, _ = await self.coupons.validate_coupon(coupon_code, new_plan.id, net_amount)\n            if is_valid:\n                discount = d_amt\n                net_amount = max(0, net_amount - discount)\n\n        idempotency_key = f\"upgrade_{tenant_id}_{new_plan_id}_{now.strftime('%Y%m%d%H%M')}\"\n        req = CheckoutOrderRequest(\n            plan_id=new_plan.id,\n            provider=provider,\n            coupon_code=coupon_code,\n            idempotency_key=idempotency_key,\n        )\n        return await self.create_checkout_order(tenant_id, req)\n\n    async def downgrade_subscription(\n        self,\n        tenant_id: uuid.UUID,\n        new_plan_id: str,\n        immediate: bool = False,\n    ) -> SubscriptionResponse:\n        \"\"\"\n        Verifies usage against new plan limits. If within limits, downgrades immediately or schedules for period end.\n        \"\"\"\n        new_plan = await self.repo.get_plan_by_id(new_plan_id)\n        if not new_plan:\n            raise NotFoundError(f\"Target plan '{new_plan_id}' not found\")\n\n        # Check resource limits\n        if new_plan.max_bots != -1:\n            active_bots = await self.repo.count_active_bots(tenant_id)\n            if active_bots > new_plan.max_bots:\n                raise ValidationError(\n                    f\"Cannot downgrade to '{new_plan.name}'. You currently have {active_bots} active bot(s), \"\n                    f\"which exceeds the plan limit of {new_plan.max_bots}. Please delete extra bots before downgrading.\"\n                )\n\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if not sub:\n            raise NotFoundError(\"Subscription not found\")\n\n        if immediate:\n            await self.repo.update_subscription(sub, plan_id=new_plan.id)\n            tenant_res = await self.db.get(Tenant, tenant_id)\n            if tenant_res:\n                tenant_res.plan_id = new_plan.id\n                await self.db.commit()\n        else:\n            # Scheduled at period end\n            await self.repo.update_subscription(sub, cancel_at_period_end=True)\n\n        return await self.get_tenant_subscription(tenant_id)\n\n    # --- Cancellation & Grace Periods & Expiry ---\n    async def cancel_subscription(\n        self,\n        tenant_id: uuid.UUID,\n        immediate: bool = False,\n    ) -> SubscriptionResponse:\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if not sub:\n            raise NotFoundError(\"Subscription not found\")\n\n        now = datetime.now(timezone.utc)\n        if immediate:\n            await self.repo.update_subscription(\n                sub,\n                status=\"canceled\",\n                canceled_at=now,\n                plan_id=\"free\",\n            )\n            tenant_res = await self.db.get(Tenant, tenant_id)\n            if tenant_res:\n                tenant_res.plan_id = \"free\"\n                await self.db.commit()\n        else:\n            await self.repo.update_subscription(\n                sub,\n                cancel_at_period_end=True,\n                canceled_at=now,\n            )\n\n        return await self.get_tenant_subscription(tenant_id)\n\n    async def process_subscription_expiry(self, tenant_id: uuid.UUID) -> SubscriptionResponse:\n        \"\"\"\n        Checks current_period_end. If expired, transitions through grace_period (3 days) before downgrading to free.\n        \"\"\"\n        sub = await self.repo.get_tenant_subscription(tenant_id)\n        if not sub:\n            raise NotFoundError(\"Subscription not found\")\n\n        now = datetime.now(timezone.utc)\n        if now > sub.current_period_end:\n            # Check grace period\n            if sub.grace_period_ends_at is None:\n                # Initiate 3-day grace period\n                grace_end = sub.current_period_end + timedelta(days=3)\n                await self.repo.update_subscription(\n                    sub,\n                    status=\"grace_period\",\n                    grace_period_ends_at=grace_end,\n                )\n            elif now > sub.grace_period_ends_at:\n                # Grace period expired -> downgrade to free\n                await self.repo.update_subscription(\n                    sub,\n                    status=\"expired\",\n                    plan_id=\"free\",\n                )\n                tenant_res = await self.db.get(Tenant, tenant_id)\n                if tenant_res:\n                    tenant_res.plan_id = \"free\"\n                    await self.db.commit()\n\n        return await self.get_tenant_subscription(tenant_id)\n\n    # --- Webhooks (Signature Verification & Deduplication) ---\n    async def handle_webhook(\n        self,\n        provider: str,\n        payload_bytes: bytes,\n        signature: str,\n        headers: Optional[dict[str, str]] = None,\n    ) -> dict[str, Any]:\n        \"\"\"\n        Handles incoming webhook with HMAC signature verification and duplicate event protection.\n        \"\"\"\n        gateway = GatewayFactory.get_gateway(provider)\n        if not gateway.verify_webhook_signature(payload_bytes, signature, headers):\n            logger.warning(\"webhook_signature_verification_failed\", provider=provider)\n            raise UnauthorizedError(f\"Invalid {provider.title()} webhook signature\")\n\n        try:\n            payload = json.loads(payload_bytes.decode(\"utf-8\"))\n        except Exception:\n            raise ValidationError(\"Malformed JSON payload in webhook\")\n\n        # Extract event ID\n        event_id = None\n        event_type = None\n\n        if provider == \"razorpay\":\n            event_id = (headers or {}).get(\"x-razorpay-event-id\") or payload.get(\"event_id\") or payload.get(\"id\")\n            event_type = payload.get(\"event\", \"unknown\")\n            if not event_id:\n                event_id = hashlib.sha256(payload_bytes).hexdigest()[:24]\n        elif provider == \"stripe\":\n            event_id = payload.get(\"id\")\n            event_type = payload.get(\"type\", \"unknown\")\n\n        if not event_id:\n            event_id = str(uuid.uuid4())\n\n        # Duplicate event protection check (Idempotency)\n        existing = await self.repo.get_webhook_event(provider, event_id)\n        if existing:\n            logger.info(\"webhook_duplicate_event_ignored\", provider=provider, event_id=event_id)\n            return {\"status\": \"duplicate_event_acknowledged\", \"event_id\": event_id, \"processed\": False}\n\n        # Record webhook event\n        await self.repo.record_webhook_event(\n            gateway_provider=provider,\n            event_id=event_id,\n            event_type=event_type,\n            payload=payload,\n            status=\"processed\",\n        )\n\n        # Dispatch event actions\n        if event_type in (\"order.paid\", \"payment.captured\", \"payment_intent.succeeded\", \"checkout.session.completed\"):\n            await self._handle_order_paid_event(provider, payload)\n        elif event_type in (\"payment.failed\", \"payment_intent.payment_failed\"):\n            await self._handle_payment_failed_event(provider, payload)\n        elif event_type in (\"refund.processed\", \"charge.refunded\"):\n            await self._handle_refund_event(provider, payload)\n\n        return {\"status\": \"success\", \"event_id\": event_id, \"processed\": True}\n\n    async def _handle_order_paid_event(self, provider: str, payload: dict[str, Any]) -> None:\n        gateway_order_id = None\n        if provider == \"razorpay\":\n            entity = payload.get(\"payload\", {}).get(\"payment\", {}).get(\"entity\", {})\n            gateway_order_id = entity.get(\"order_id\")\n        elif provider == \"stripe\":\n            data_obj = payload.get(\"data\", {}).get(\"object\", {})\n            gateway_order_id = data_obj.get(\"id\")\n\n        if gateway_order_id:\n            order = await self.repo.get_order_by_gateway_order_id(gateway_order_id)\n            if order and order.status != \"paid\":\n                await self.repo.update_order(order, status=\"paid\")\n                sub = await self.repo.get_tenant_subscription(order.tenant_id)\n                now = datetime.now(timezone.utc)\n                if sub:\n                    await self.repo.update_subscription(\n                        sub,\n                        status=\"active\",\n                        plan_id=order.plan_id or \"starter\",\n                        current_period_start=now,\n                        current_period_end=now + timedelta(days=30),\n                        grace_period_ends_at=None,\n                    )\n\n    async def _handle_payment_failed_event(self, provider: str, payload: dict[str, Any]) -> None:\n        gateway_order_id = None\n        if provider == \"razorpay\":\n            entity = payload.get(\"payload\", {}).get(\"payment\", {}).get(\"entity\", {})\n            gateway_order_id = entity.get(\"order_id\")\n        elif provider == \"stripe\":\n            data_obj = payload.get(\"data\", {}).get(\"object\", {})\n            gateway_order_id = data_obj.get(\"id\")\n\n        if gateway_order_id:\n            order = await self.repo.get_order_by_gateway_order_id(gateway_order_id)\n            if order:\n                await self.repo.update_order(order, status=\"failed\")\n                sub = await self.repo.get_tenant_subscription(order.tenant_id)\n                if sub and sub.status == \"active\":\n                    # Put into past_due with 3-day grace period\n                    now = datetime.now(timezone.utc)\n                    await self.repo.update_subscription(\n                        sub,\n                        status=\"past_due\",\n                        grace_period_ends_at=now + timedelta(days=3),\n                    )\n\n    async def _handle_refund_event(self, provider: str, payload: dict[str, Any]) -> None:\n        pass\n\n    # --- Refunds ---\n    async def process_refund(\n        self,\n        tenant_id: uuid.UUID,\n        req: RefundRequest,\n    ) -> RefundResponse:\n        order = await self.repo.get_order_by_id(req.order_id)\n        if not order:\n            raise NotFoundError(\"Order not found\")\n        if order.tenant_id != tenant_id:\n            raise ForbiddenError(\"Cross-tenant refund forbidden\")\n        if order.status not in (\"paid\", \"partially_refunded\"):\n            raise ValidationError(f\"Cannot refund order in status '{order.status}'\")\n\n        refund_amount = req.amount or order.amount\n        if refund_amount <= 0 or refund_amount > order.amount:\n            raise ValidationError(f\"Invalid refund amount: {refund_amount}\")\n\n        gateway_refund_id = None\n        if order.provider in (\"razorpay\", \"stripe\"):\n            gateway = GatewayFactory.get_gateway(order.provider)\n            gw_resp = await gateway.create_refund(\n                payment_id=order.gateway_payment_id or order.gateway_order_id or \"pay_mock\",\n                amount=refund_amount,\n                currency=order.currency,\n                reason=req.reason,\n            )\n            gateway_refund_id = gw_resp.get(\"id\")\n        elif order.provider == \"wallet\":\n            # Refund directly back to wallet\n            await self.wallets.credit(\n                tenant_id=tenant_id,\n                amount=refund_amount,\n                reference_type=\"refund\",\n                description=f\"Refund for order #{order.order_number}: {req.reason}\",\n                reference_id=str(order.id),\n            )\n            gateway_refund_id = f\"wallet_rfnd_{uuid.uuid4().hex[:12]}\"\n\n        new_status = \"refunded\" if refund_amount == order.amount else \"partially_refunded\"\n        await self.repo.update_order(order, status=new_status)\n\n        refund = await self.repo.create_refund(\n            tenant_id=tenant_id,\n            order_id=order.id,\n            amount=refund_amount,\n            currency=order.currency,\n            reason=req.reason,\n            provider=order.provider,\n            status=\"processed\",\n            gateway_refund_id=gateway_refund_id,\n        )\n\n        return RefundResponse(\n            id=refund.id,\n            order_id=refund.order_id,\n            amount=refund.amount,\n            currency=refund.currency,\n            status=refund.status,\n            gateway_refund_id=refund.gateway_refund_id,\n            reason=refund.reason,\n        )\n\n    # --- Invoices ---\n    async def list_invoices(self, tenant_id: uuid.UUID) -> list[InvoiceResponse]:\n        invoices = await self.repo.list_tenant_invoices(tenant_id)\n        return [\n            InvoiceResponse(\n                id=inv.id,\n                invoice_number=inv.invoice_number,\n                subscription_id=inv.subscription_id,\n                order_id=inv.order_id,\n                amount_due=inv.amount_due,\n                amount_paid=inv.amount_paid,\n                amount_remaining=inv.amount_remaining,\n                currency=inv.currency,\n                status=inv.status,\n                due_date=inv.due_date,\n                paid_at=inv.paid_at,\n                billing_email=inv.billing_email,\n                billing_name=inv.billing_name,\n                items=inv.items,\n                subtotal=inv.subtotal,\n                tax_amount=inv.tax_amount,\n                discount_amount=inv.discount_amount,\n                pdf_url=inv.pdf_url,\n            )\n            for inv in invoices\n        ]\n\n    async def get_invoice(self, tenant_id: uuid.UUID, invoice_id: uuid.UUID) -> InvoiceResponse:\n        inv = await self.repo.get_invoice_by_id(invoice_id, tenant_id)\n        if not inv:\n            raise NotFoundError(\"Invoice not found\")\n        return InvoiceResponse(\n            id=inv.id,\n            invoice_number=inv.invoice_number,\n            subscription_id=inv.subscription_id,\n            order_id=inv.order_id,\n            amount_due=inv.amount_due,\n            amount_paid=inv.amount_paid,\n            amount_remaining=inv.amount_remaining,\n            currency=inv.currency,\n            status=inv.status,\n            due_date=inv.due_date,\n            paid_at=inv.paid_at,\n            billing_email=inv.billing_email,\n            billing_name=inv.billing_name,\n            items=inv.items,\n            subtotal=inv.subtotal,\n            tax_amount=inv.tax_amount,\n            discount_amount=inv.discount_amount,\n            pdf_url=inv.pdf_url,\n        )\n\n    def render_invoice_html(self, invoice: Invoice) -> str:\n        \"\"\"Renders a clean, print-ready HTML invoice.\"\"\"\n        date_str = invoice.due_date.strftime(\"%B %d, %Y\")\n        paid_str = invoice.paid_at.strftime(\"%B %d, %Y\") if invoice.paid_at else \"Pending\"\n        currency_sym = \"₹\" if invoice.currency == \"INR\" else \"$\"\n\n        rows_html = \"\"\n        for item in invoice.items:\n            unit_val = f\"{currency_sym}{item.get('unit_price', 0) / 100:.2f}\"\n            tot_val = f\"{currency_sym}{item.get('total', 0) / 100:.2f}\"\n            rows_html += f\"\"\"\n            <tr>\n                <td style=\"padding: 12px; border-bottom: 1px solid #e2e8f0;\">{item.get('description', '')}</td>\n                <td style=\"padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: center;\">{item.get('quantity', 1)}</td>\n                <td style=\"padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right;\">{unit_val}</td>\n                <td style=\"padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: right; font-weight: 600;\">{tot_val}</td>\n            </tr>\n            \"\"\"\n\n        status_color = \"#16a34a\" if invoice.status == \"paid\" else \"#ea580c\"\n\n        return f\"\"\"<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>Invoice {invoice.invoice_number}</title>\n    <style>\n        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; margin: 0; padding: 40px; background-color: #f8fafc; }}\n        .invoice-card {{ max-width: 800px; margin: 0 auto; background: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); padding: 48px; border: 1px solid #e2e8f0; }}\n        .header {{ display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 36px; }}\n        .brand {{ font-size: 24px; font-weight: 800; color: #0f172a; letter-spacing: -0.5px; }}\n        .badge {{ display: inline-block; padding: 4px 12px; border-radius: 9999px; font-size: 13px; font-weight: 700; text-transform: uppercase; background-color: {status_color}20; color: {status_color}; }}\n        .meta-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 36px; padding: 24px; background: #f8fafc; border-radius: 8px; }}\n        table {{ width: 100%; border-collapse: collapse; margin-bottom: 36px; }}\n        th {{ text-align: left; padding: 12px; border-bottom: 2px solid #cbd5e1; font-size: 13px; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; }}\n        .totals {{ margin-left: auto; width: 300px; }}\n        .total-row {{ display: flex; justify-content: space-between; padding: 8px 0; font-size: 14px; color: #64748b; }}\n        .total-row.grand {{ font-size: 18px; font-weight: 800; color: #0f172a; border-top: 2px solid #e2e8f0; padding-top: 12px; }}\n    </style>\n</head>\n<body>\n    <div class=\"invoice-card\">\n        <div class=\"header\">\n            <div>\n                <div class=\"brand\">⚡ Telegram SaaS Platform</div>\n                <div style=\"color: #64748b; margin-top: 4px; font-size: 14px;\">Enterprise Bot Infrastructure</div>\n            </div>\n            <div style=\"text-align: right;\">\n                <div class=\"badge\">{invoice.status}</div>\n                <div style=\"font-size: 20px; font-weight: 700; margin-top: 8px;\">{invoice.invoice_number}</div>\n            </div>\n        </div>\n\n        <div class=\"meta-grid\">\n            <div>\n                <div style=\"font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700;\">Billed To</div>\n                <div style=\"font-size: 16px; font-weight: 600; margin-top: 4px;\">{invoice.billing_name}</div>\n                <div style=\"color: #64748b; font-size: 14px;\">{invoice.billing_email}</div>\n            </div>\n            <div style=\"text-align: right;\">\n                <div style=\"font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700;\">Invoice Date</div>\n                <div style=\"font-size: 14px; font-weight: 500; margin-top: 4px;\">{date_str}</div>\n                <div style=\"font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 700; margin-top: 8px;\">Payment Date</div>\n                <div style=\"font-size: 14px; font-weight: 500; margin-top: 4px;\">{paid_str}</div>\n            </div>\n        </div>\n\n        <table>\n            <thead>\n                <tr>\n                    <th>Item Description</th>\n                    <th style=\"text-align: center;\">Qty</th>\n                    <th style=\"text-align: right;\">Unit Price</th>\n                    <th style=\"text-align: right;\">Amount</th>\n                </tr>\n            </thead>\n            <tbody>\n                {rows_html}\n            </tbody>\n        </table>\n\n        <div class=\"totals\">\n            <div class=\"total-row\">\n                <span>Subtotal:</span>\n                <span>{currency_sym}{invoice.subtotal / 100:.2f}</span>\n            </div>\n            <div class=\"total-row\">\n                <span>Discount:</span>\n                <span>-{currency_sym}{invoice.discount_amount / 100:.2f}</span>\n            </div>\n            <div class=\"total-row\">\n                <span>Tax (GST/VAT):</span>\n                <span>{currency_sym}{invoice.tax_amount / 100:.2f}</span>\n            </div>\n            <div class=\"total-row grand\">\n                <span>Total Paid:</span>\n                <span>{currency_sym}{invoice.amount_paid / 100:.2f}</span>\n            </div>\n        </div>\n    </div>\n</body>\n</html>\"\"\"\n","Overwrite":true,"Path":"/root/telegram-saas/modules/billing/service.py"}}]}
{"step_index":1566,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:08Z","content":"Created At: 2026-11-18T08:40:08Z\nCompleted At: 2026-11-18T08:40:09Z\nCreated At: 2026-11-18T08:40:08Z\nCompleted At: 2026-11-18T08:40:09Z\nCreated file."}
{"step_index":1567,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:09Z","model":"gemini-3.8-flash-high","input_tokens":12730,"cache_read_tokens":111937,"output_tokens":90,"tool_calls":[{"name":"read_file","args":{"EndLine":50,"Path":"/root/telegram-saas/modules/bots/service.py","StartLine":35}}]}
{"step_index":1568,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:11Z","content":"Created At: 2026-11-18T08:40:11Z\nCompleted At: 2026-11-18T08:40:11Z\nCreated At: 2026-11-18T08:40:11Z\nCompleted At: 2026-11-18T08:40:11Z\nShowing lines 35-50 of 352\n35: \n36:     async def register_bot(self, tenant_id: UUID, req: BotRegisterRequest) -> Bot:\n37:         # 1. Validate token with Telegram API getMe\n38:         bot_info = await TelegramApiService.validate_token(req.token)\n39:         username = bot_info.get(\"username\", \"\").lstrip(\"@\")\n40:         if not username:\n41:             raise ValidationError(\"Telegram bot did not return a valid username\")\n42: \n43:         # 2. Check if username is already registered globally\n44:         existing = await self.repo.get_by_username(username)\n45:         if existing:\n46:             raise ConflictError(f\"Telegram bot @{username} is already registered on this platform\")\n47: \n48:         # 3. Encrypt raw token using AES-256-GCM\n49:         encrypted_token, key_version = encrypt_string(req.token)\n50: "}
{"step_index":1569,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:12Z","model":"gemini-3.8-flash-high","input_tokens":2448,"cache_read_tokens":122627,"output_tokens":299,"thinking":"Adding a quota check within the bot registration process to enforce plan entitlements. The `register_bot` function appears to be the primary entry point for bot creation. Further investigation for other bot activation points seems unnecessary.\n\n\n","tool_calls":[{"name":"edit_file","args":{"Path":"/root/telegram-saas/modules/bots/service.py","Replacement":"    async def register_bot(self, tenant_id: UUID, req: BotRegisterRequest) -> Bot:\n        # 0. Enforce plan entitlement quota for active bots\n        from modules.billing.entitlement_service import EntitlementService\n        entitlements = EntitlementService(self.db)\n        await entitlements.check_bot_creation_limit(tenant_id)\n\n        # 1. Validate token with Telegram API getMe","Target":"    async def register_bot(self, tenant_id: UUID, req: BotRegisterRequest) -> Bot:\n        # 1. Validate token with Telegram API getMe"}}]}
{"step_index":1570,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:15Z","content":"Created At: 2026-11-18T08:40:15Z\nCompleted At: 2026-11-18T08:40:15Z\nCreated At: 2026-11-18T08:40:15Z\nCompleted At: 2026-11-18T08:40:15Z\nMade 1 replacement in /root/telegram-saas/modules/bots/service.py starting at line 36 (+5/-0 lines)."}
{"step_index":1571,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:15Z","model":"gemini-3.8-flash-high","input_tokens":2434,"cache_read_tokens":123035,"output_tokens":3830,"thinking":"Billing API endpoints are being defined. The initial focus is on creating `billing.py` to handle plan retrieval and subscription status. Also, the `webhooks.py` file requires updating to integrate Razorpay and Stripe webhook handlers. The billing router will be registered within the initialization file.\n\n\n","tool_calls":[{"name":"write_file","args":{"Content":"import uuid\nfrom typing import Annotated, Optional\nfrom uuid import UUID\nfrom fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom apps.api.dependencies import get_current_tenant, get_current_user\nfrom apps.api.schemas.responses import ApiResponse\nfrom infrastructure.database.session import get_db\nfrom modules.billing.schemas import (\n    CancelSubscriptionRequest,\n    CheckoutOrderRequest,\n    CheckoutOrderResponse,\n    CouponValidationResponse,\n    DowngradeSubscriptionRequest,\n    InvoiceResponse,\n    PaymentVerificationRequest,\n    PaymentVerificationResponse,\n    PayWithWalletRequest,\n    PlanResponse,\n    ReferralResponse,\n    RefundRequest,\n    RefundResponse,\n    SubscriptionResponse,\n    TenantUsageResponse,\n    UpgradeSubscriptionRequest,\n    ValidateCouponRequest,\n    WalletResponse,\n    WalletTransactionResponse,\n)\nfrom modules.billing.service import BillingService\nfrom modules.identity.models import User\nfrom modules.tenants.models import Tenant, TenantMember\n\nrouter = APIRouter(prefix=\"/billing\", tags=[\"SaaS Billing & Subscriptions\"])\n\n\n@router.get(\"/plans\", response_model=ApiResponse[list[PlanResponse]], status_code=status.HTTP_200_OK)\nasync def list_plans(\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Lists available commercial tiers and their entitlement quotas.\"\"\"\n    service = BillingService(db)\n    plans = await service.list_plans()\n    return ApiResponse(\n        message=\"Available subscription plans retrieved\",\n        data=plans,\n    )\n\n\n@router.get(\"/subscription\", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)\nasync def get_tenant_subscription(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Retrieves current subscription status, period dates, and grace period details.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    sub = await service.get_tenant_subscription(tenant.id)\n    return ApiResponse(\n        message=\"Tenant subscription retrieved\",\n        data=sub,\n    )\n\n\n@router.post(\"/checkout\", response_model=ApiResponse[CheckoutOrderResponse], status_code=status.HTTP_201_CREATED)\nasync def create_checkout_order(\n    req: CheckoutOrderRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Creates a payment order with Razorpay or Stripe, applying promotional discounts.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    order = await service.create_checkout_order(tenant.id, req)\n    return ApiResponse(\n        message=\"Checkout order created successfully\",\n        data=order,\n    )\n\n\n@router.post(\"/checkout/verify\", response_model=ApiResponse[PaymentVerificationResponse], status_code=status.HTTP_200_OK)\nasync def verify_payment(\n    req: PaymentVerificationRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"\n    Server-side cryptographic payment verification.\n    Validates gateway signatures and activates subscription. Never trusts client claims alone.\n    \"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    result = await service.verify_and_activate_payment(tenant.id, req)\n    return ApiResponse(\n        message=result.message,\n        data=result,\n    )\n\n\n@router.post(\"/wallet/pay\", response_model=ApiResponse[PaymentVerificationResponse], status_code=status.HTTP_200_OK)\nasync def pay_with_wallet(\n    req: PayWithWalletRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Pay subscription directly using prepaid wallet balance.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    result = await service.pay_with_wallet(tenant.id, req.plan_id, req.coupon_code)\n    return ApiResponse(\n        message=result.message,\n        data=result,\n    )\n\n\n@router.post(\"/subscription/upgrade\", response_model=ApiResponse[CheckoutOrderResponse], status_code=status.HTTP_200_OK)\nasync def upgrade_subscription(\n    req: UpgradeSubscriptionRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Upgrades subscription calculating prorated credit for remaining days.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    order = await service.upgrade_subscription(\n        tenant.id, req.new_plan_id, req.provider, req.coupon_code\n    )\n    return ApiResponse(\n        message=\"Upgrade order created with prorated credit\",\n        data=order,\n    )\n\n\n@router.post(\"/subscription/downgrade\", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)\nasync def downgrade_subscription(\n    req: DowngradeSubscriptionRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Downgrades subscription after validating active resource limits.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    sub = await service.downgrade_subscription(tenant.id, req.new_plan_id, req.immediate)\n    return ApiResponse(\n        message=\"Subscription downgraded successfully\",\n        data=sub,\n    )\n\n\n@router.post(\"/subscription/cancel\", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)\nasync def cancel_subscription(\n    req: CancelSubscriptionRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Cancels subscription either immediately or at current period end.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    sub = await service.cancel_subscription(tenant.id, req.immediate)\n    return ApiResponse(\n        message=\"Subscription cancellation registered\",\n        data=sub,\n    )\n\n\n@router.get(\"/invoices\", response_model=ApiResponse[list[InvoiceResponse]], status_code=status.HTTP_200_OK)\nasync def list_invoices(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Lists historical and active invoices for the tenant.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    invoices = await service.list_invoices(tenant.id)\n    return ApiResponse(\n        message=\"Invoices retrieved\",\n        data=invoices,\n    )\n\n\n@router.get(\"/invoices/{invoice_id}\", response_model=ApiResponse[InvoiceResponse], status_code=status.HTTP_200_OK)\nasync def get_invoice(\n    invoice_id: UUID,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Fetches details of a specific tenant invoice.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    invoice = await service.get_invoice(tenant.id, invoice_id)\n    return ApiResponse(\n        message=\"Invoice detail retrieved\",\n        data=invoice,\n    )\n\n\n@router.get(\"/invoices/{invoice_id}/html\", response_class=Response, status_code=status.HTTP_200_OK)\nasync def render_invoice_html(\n    invoice_id: UUID,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Renders a print-ready, professional HTML invoice.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    inv = await service.repo.get_invoice_by_id(invoice_id, tenant.id)\n    if not inv:\n        raise HTTPException(status_code=404, detail=\"Invoice not found\")\n    html_content = service.render_invoice_html(inv)\n    return Response(content=html_content, media_type=\"text/html\")\n\n\n@router.post(\"/refunds\", response_model=ApiResponse[RefundResponse], status_code=status.HTTP_200_OK)\nasync def process_refund(\n    req: RefundRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Processes partial or full refund on a paid order.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    refund = await service.process_refund(tenant.id, req)\n    return ApiResponse(\n        message=\"Refund processed successfully\",\n        data=refund,\n    )\n\n\n@router.get(\"/wallet\", response_model=ApiResponse[WalletResponse], status_code=status.HTTP_200_OK)\nasync def get_wallet_balance(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Retrieves tenant's prepaid credit wallet balance.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    wallet = await service.wallets.get_or_create_wallet(tenant.id)\n    return ApiResponse(\n        message=\"Wallet balance retrieved\",\n        data=WalletResponse(\n            balance=wallet.balance,\n            balance_formatted=f\"₹{wallet.balance / 100:.2f}\" if wallet.currency == \"INR\" else f\"${wallet.balance / 100:.2f}\",\n            currency=wallet.currency,\n            is_frozen=wallet.is_frozen,\n        ),\n    )\n\n\n@router.get(\"/wallet/transactions\", response_model=ApiResponse[list[WalletTransactionResponse]], status_code=status.HTTP_200_OK)\nasync def get_wallet_transactions(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Retrieves immutable ledger entries with cryptographic checksums.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    txs = await service.wallets.get_transactions(tenant.id)\n    return ApiResponse(\n        message=\"Wallet transactions ledger retrieved\",\n        data=[WalletTransactionResponse.model_validate(t) for t in txs],\n    )\n\n\n@router.post(\"/coupons/validate\", response_model=ApiResponse[CouponValidationResponse], status_code=status.HTTP_200_OK)\nasync def validate_coupon(\n    req: ValidateCouponRequest,\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Validates coupon code eligibility and calculates discount.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    plan = await service.repo.get_plan_by_id(req.plan_id)\n    if not plan:\n        raise HTTPException(status_code=404, detail=\"Plan not found\")\n\n    is_valid, coupon, discount, message = await service.coupons.validate_coupon(\n        req.code, plan.id, plan.price_amount\n    )\n    final_amount = max(0, plan.price_amount - discount) if is_valid else plan.price_amount\n\n    return ApiResponse(\n        message=message,\n        data=CouponValidationResponse(\n            is_valid=is_valid,\n            code=req.code.upper(),\n            discount_type=coupon.discount_type if coupon else \"none\",\n            discount_value=coupon.discount_value if coupon else 0,\n            discount_amount=discount,\n            final_amount=final_amount,\n            message=message,\n        ),\n    )\n\n\n@router.get(\"/referrals\", response_model=ApiResponse[ReferralResponse], status_code=status.HTTP_200_OK)\nasync def get_referrals_stats(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Retrieves tenant's referral link and rewards earned.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    total_ref, total_rewards = await service.repo.count_tenant_referrals(tenant.id)\n    ref_code = f\"REF-{str(tenant.id)[:8].upper()}\"\n    return ApiResponse(\n        message=\"Referral stats retrieved\",\n        data=ReferralResponse(\n            referral_code=ref_code,\n            referral_link=f\"https://dashboard.domain.com/register?ref={ref_code}\",\n            total_referred=total_ref,\n            total_rewarded_credits=total_rewards,\n        ),\n    )\n\n\n@router.get(\"/usage\", response_model=ApiResponse[TenantUsageResponse], status_code=status.HTTP_200_OK)\nasync def get_tenant_usage_and_limits(\n    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],\n    db: Annotated[AsyncSession, Depends(get_db)],\n):\n    \"\"\"Returns active consumption vs entitlement limits.\"\"\"\n    tenant, _ = tenant_context\n    service = BillingService(db)\n    usage = await service.entitlements.get_tenant_limits_and_usage(tenant.id)\n    return ApiResponse(\n        message=\"Tenant usage and entitlement limits retrieved\",\n        data=TenantUsageResponse(**usage),\n    )\n","Overwrite":true,"Path":"/root/telegram-saas/apps/api/routes/billing.py"}}]}
{"step_index":1572,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:35Z","content":"Created At: 2026-11-18T08:40:35Z\nCompleted At: 2026-11-18T08:40:35Z\nCreated At: 2026-11-18T08:40:35Z\nCompleted At: 2026-11-18T08:40:35Z\nCreated file."}
{"step_index":1573,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:35Z","model":"gemini-3.8-flash-high","input_tokens":3874,"cache_read_tokens":125491,"output_tokens":162,"tool_calls":[{"name":"read_file","args":{"EndLine":60,"Path":"/root/telegram-saas/apps/api/routes/webhooks.py","StartLine":1}}]}
{"step_index":1574,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:39Z","content":"Created At: 2026-11-18T08:40:39Z\nCompleted At: 2026-11-18T08:40:39Z\nCreated At: 2026-11-18T08:40:39Z\nCompleted At: 2026-11-18T08:40:39Z\nShowing lines 1-54 of 54\n1: from typing import Annotated, Any, Optional\n2: from uuid import UUID\n3: from fastapi import APIRouter, Depends, Header, HTTPException, Request, status\n4: from sqlalchemy.ext.asyncio import AsyncSession\n5: from core.exceptions import UnauthorizedError, NotFoundError\n6: from core.logging import get_logger\n7: from infrastructure.database.session import get_db\n8: from modules.bots.service import BotService\n9: \n10: logger = get_logger(__name__)\n11: \n12: router = APIRouter(prefix=\"/webhooks/telegram\", tags=[\"Telegram Webhook Ingestion\"])\n13: \n14: \n15: @router.post(\"/{bot_id}\", status_code=status.HTTP_200_OK)\n16: async def receive_telegram_webhook(\n17:     bot_id: UUID,\n18:     request: Request,\n19:     db: Annotated[AsyncSession, Depends(get_db)],\n20:     x_telegram_bot_api_secret_token: Annotated[Optional[str], Header()] = None,\n21: ):\n22:     \"\"\"\n23:     Ingests and processes incoming Telegram Bot API updates.\n24:     Validates X-Telegram-Bot-Api-Secret-Token before processing.\n25:     \"\"\"\n26:     if not x_telegram_bot_api_secret_token:\n27:         logger.warning(\"webhook_missing_secret_token\", bot_id=str(bot_id))\n28:         raise HTTPException(\n29:             status_code=status.HTTP_401_UNAUTHORIZED,\n30:             detail=\"Missing X-Telegram-Bot-Api-Secret-Token header\",\n31:         )\n32: \n33:     try:\n34:         update_dict = await request.json()\n35:     except Exception as exc:\n36:         logger.error(\"webhook_invalid_json\", bot_id=str(bot_id), error=str(exc))\n37:         raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"Invalid JSON payload\")\n38: \n39:     service = BotService(db)\n40:     try:\n41:         res = await service.handle_webhook_update(\n42:             bot_id=bot_id,\n43:             received_secret_token=x_telegram_bot_api_secret_token,\n44:             update_dict=update_dict,\n45:         )\n46:         return res\n47:     except UnauthorizedError as exc:\n48:         raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))\n49:     except NotFoundError as exc:\n50:         raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc.message))\n51:     except Exception as exc:\n52:         logger.error(\"webhook_processing_error\", bot_id=str(bot_id), error=str(exc))\n53:         # Return 200 to Telegram so it doesn't repeatedly retry failing malformed events\n54:         return {\"ok\": False, \"error\": str(exc)}"}
{"step_index":1575,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:39Z","model":"gemini-3.8-flash-high","input_tokens":3052,"cache_read_tokens":127330,"output_tokens":1812,"thinking":"The existing router prefix is checked, which is currently set to a specific webhook integration. The options are to either generalize the existing router with different path variations, or to create a new router dedicated to payment webhooks. The structure `apps/api/routes/__init__.py` is checked for more context.\n\n\n","tool_calls":[{"name":"write_file","args":{"Content":"from typing import Annotated, Any, Optional\nfrom uuid import UUID\nfrom fastapi import APIRouter, Depends, Header, HTTPException, Request, status\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom core.exceptions import NotFoundError, UnauthorizedError, ValidationError\nfrom core.logging import get_logger\nfrom infrastructure.database.session import get_db\nfrom modules.billing.service import BillingService\nfrom modules.bots.service import BotService\n\nlogger = get_logger(__name__)\n\nrouter = APIRouter(prefix=\"/webhooks\", tags=[\"Webhook Ingestion\"])\n\n\n@router.post(\"/telegram/{bot_id}\", status_code=status.HTTP_200_OK)\nasync def receive_telegram_webhook(\n    bot_id: UUID,\n    request: Request,\n    db: Annotated[AsyncSession, Depends(get_db)],\n    x_telegram_bot_api_secret_token: Annotated[Optional[str], Header()] = None,\n):\n    \"\"\"\n    Ingests and processes incoming Telegram Bot API updates.\n    Validates X-Telegram-Bot-Api-Secret-Token before processing.\n    \"\"\"\n    if not x_telegram_bot_api_secret_token:\n        logger.warning(\"webhook_missing_secret_token\", bot_id=str(bot_id))\n        raise HTTPException(\n            status_code=status.HTTP_401_UNAUTHORIZED,\n            detail=\"Missing X-Telegram-Bot-Api-Secret-Token header\",\n        )\n\n    try:\n        update_dict = await request.json()\n    except Exception as exc:\n        logger.error(\"webhook_invalid_json\", bot_id=str(bot_id), error=str(exc))\n        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"Invalid JSON payload\")\n\n    service = BotService(db)\n    try:\n        res = await service.handle_webhook_update(\n            bot_id=bot_id,\n            received_secret_token=x_telegram_bot_api_secret_token,\n            update_dict=update_dict,\n        )\n        return res\n    except UnauthorizedError as exc:\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))\n    except NotFoundError as exc:\n        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc.message))\n    except Exception as exc:\n        logger.error(\"webhook_processing_error\", bot_id=str(bot_id), error=str(exc))\n        return {\"ok\": False, \"error\": str(exc)}\n\n\n@router.post(\"/razorpay\", status_code=status.HTTP_200_OK)\nasync def receive_razorpay_webhook(\n    request: Request,\n    db: Annotated[AsyncSession, Depends(get_db)],\n    x_razorpay_signature: Annotated[Optional[str], Header()] = None,\n    x_razorpay_event_id: Annotated[Optional[str], Header()] = None,\n):\n    \"\"\"\n    Ingests Razorpay webhook notifications.\n    Verifies HMAC-SHA256 signature and guarantees duplicate event protection.\n    \"\"\"\n    if not x_razorpay_signature:\n        logger.warning(\"razorpay_webhook_missing_signature\")\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Missing X-Razorpay-Signature header\")\n\n    payload_bytes = await request.body()\n    service = BillingService(db)\n\n    try:\n        headers = {\n            \"x-razorpay-signature\": x_razorpay_signature,\n            \"x-razorpay-event-id\": x_razorpay_event_id or \"\",\n        }\n        res = await service.handle_webhook(\n            provider=\"razorpay\",\n            payload_bytes=payload_bytes,\n            signature=x_razorpay_signature,\n            headers=headers,\n        )\n        return res\n    except UnauthorizedError as exc:\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))\n    except ValidationError as exc:\n        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc.message))\n    except Exception as exc:\n        logger.error(\"razorpay_webhook_processing_error\", error=str(exc))\n        return {\"status\": \"error\", \"error\": str(exc)}\n\n\n@router.post(\"/stripe\", status_code=status.HTTP_200_OK)\nasync def receive_stripe_webhook(\n    request: Request,\n    db: Annotated[AsyncSession, Depends(get_db)],\n    stripe_signature: Annotated[Optional[str], Header()] = None,\n):\n    \"\"\"\n    Ingests Stripe webhook events (checkout.session.completed, payment_intent, etc.).\n    Verifies Stripe-Signature and enforces duplicate event idempotency.\n    \"\"\"\n    if not stripe_signature:\n        logger.warning(\"stripe_webhook_missing_signature\")\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Missing Stripe-Signature header\")\n\n    payload_bytes = await request.body()\n    service = BillingService(db)\n\n    try:\n        res = await service.handle_webhook(\n            provider=\"stripe\",\n            payload_bytes=payload_bytes,\n            signature=stripe_signature,\n        )\n        return res\n    except UnauthorizedError as exc:\n        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))\n    except ValidationError as exc:\n        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc.message))\n    except Exception as exc:\n        logger.error(\"stripe_webhook_processing_error\", error=str(exc))\n        return {\"status\": \"error\", \"error\": str(exc)}\n","Overwrite":true,"Path":"/root/telegram-saas/apps/api/routes/webhooks.py"}}]}
{"step_index":1576,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:50Z","content":"Created At: 2026-11-18T08:40:50Z\nCompleted At: 2026-11-18T08:40:50Z\nCreated At: 2026-11-18T08:40:50Z\nCompleted At: 2026-11-18T08:40:50Z\nCreated file."}
{"step_index":1577,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-11-18T08:40:50Z","model":"gemini-3.8-flash-high","input_tokens":2725,"cache_read_tokens":129535,"output_tokens":82,"tool_calls":[{"name":"read_file","args":{"EndLine":30,"Path":"/root/telegram-saas/apps/api/routes/__init__.py","StartLine":1}}]}
{"step_index":1578,"source":"MODEL","type":"GENERIC","status":"DONE","created_at":"2026-11-18T08:40:54Z","content":"Created At: 2026-11-18T08:40:54Z\nCompleted At: 2026-11-18T08:40:54Z\nCreated At: 2026-11-18T08:40:54Z\nCompleted At: 2026-11-18T08:40:54Z\nShowing lines 1-26 of 26\n1: from fastapi import APIRouter\n2: from apps.api.routes.health import router as health_router\n3: from apps.api.routes.auth import router as auth_router\n4: from apps.api.routes.tenants import router as tenants_router\n5: from apps.api.routes.bots import router as bots_router\n6: from apps.api.routes.admin.bots import router as admin_bots_router\n7: from apps.api.routes.webhooks import router as webhooks_router\n8: from apps.api.routes.i18n import router as i18n_router\n9: from apps.api.routes.emojis import router as emojis_router\n10: from apps.api.routes.message_studio import (\n11:     router as message_studio_router,\n12:     