[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BN28MNECYPYW6B9DN4K723":3,"skill-same:01M7BN28MNECYPYW6B9DN4K723":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BN28MNECYPYW6B9DN4K723","billing-automation",null,"Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and dunning management. Use when implementing subscription billing, automating invoicing, or managing recurring payment systems.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fpayment-processing\u002Fskills\u002Fbilling-automation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: billing-automation\ndescription: Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and dunning management. Use when implementing subscription billing, automating invoicing, or managing recurring payment systems.\n---\n\n# Billing Automation\n\nMaster automated billing systems including recurring billing, invoice generation, dunning management, proration, and tax calculation.\n\n## When to Use This Skill\n\n- Implementing SaaS subscription billing\n- Automating invoice generation and delivery\n- Managing failed payment recovery (dunning)\n- Calculating prorated charges for plan changes\n- Handling sales tax, VAT, and GST\n- Processing usage-based billing\n- Managing billing cycles and renewals\n\n## Core Concepts\n\n### 1. Billing Cycles\n\n**Common Intervals:**\n\n- Monthly (most common for SaaS)\n- Annual (discounted long-term)\n- Quarterly\n- Weekly\n- Custom (usage-based, per-seat)\n\n### 2. Subscription States\n\n```\ntrial → active → past_due → canceled\n              → paused → resumed\n```\n\n### 3. Dunning Management\n\nAutomated process to recover failed payments through:\n\n- Retry schedules\n- Customer notifications\n- Grace periods\n- Account restrictions\n\n### 4. Proration\n\nAdjusting charges when:\n\n- Upgrading\u002Fdowngrading mid-cycle\n- Adding\u002Fremoving seats\n- Changing billing frequency\n\n## Quick Start\n\n```python\nfrom billing import BillingEngine, Subscription\n\n# Initialize billing engine\nbilling = BillingEngine()\n\n# Create subscription\nsubscription = billing.create_subscription(\n    customer_id=\"cus_123\",\n    plan_id=\"plan_pro_monthly\",\n    billing_cycle_anchor=datetime.now(),\n    trial_days=14\n)\n\n# Process billing cycle\nbilling.process_billing_cycle(subscription.id)\n```\n\n## Subscription Lifecycle Management\n\n```python\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nclass SubscriptionStatus(Enum):\n    TRIAL = \"trial\"\n    ACTIVE = \"active\"\n    PAST_DUE = \"past_due\"\n    CANCELED = \"canceled\"\n    PAUSED = \"paused\"\n\nclass Subscription:\n    def __init__(self, customer_id, plan, billing_cycle_day=None):\n        self.id = generate_id()\n        self.customer_id = customer_id\n        self.plan = plan\n        self.status = SubscriptionStatus.TRIAL\n        self.current_period_start = datetime.now()\n        self.current_period_end = self.current_period_start + timedelta(days=plan.trial_days or 30)\n        self.billing_cycle_day = billing_cycle_day or self.current_period_start.day\n        self.trial_end = datetime.now() + timedelta(days=plan.trial_days) if plan.trial_days else None\n\n    def start_trial(self, trial_days):\n        \"\"\"Start trial period.\"\"\"\n        self.status = SubscriptionStatus.TRIAL\n        self.trial_end = datetime.now() + timedelta(days=trial_days)\n        self.current_period_end = self.trial_end\n\n    def activate(self):\n        \"\"\"Activate subscription after trial or immediately.\"\"\"\n        self.status = SubscriptionStatus.ACTIVE\n        self.current_period_start = datetime.now()\n        self.current_period_end = self.calculate_next_billing_date()\n\n    def mark_past_due(self):\n        \"\"\"Mark subscription as past due after failed payment.\"\"\"\n        self.status = SubscriptionStatus.PAST_DUE\n        # Trigger dunning workflow\n\n    def cancel(self, at_period_end=True):\n        \"\"\"Cancel subscription.\"\"\"\n        if at_period_end:\n            self.cancel_at_period_end = True\n            # Will cancel when current period ends\n        else:\n            self.status = SubscriptionStatus.CANCELED\n            self.canceled_at = datetime.now()\n\n    def calculate_next_billing_date(self):\n        \"\"\"Calculate next billing date based on interval.\"\"\"\n        if self.plan.interval == 'month':\n            return self.current_period_start + timedelta(days=30)\n        elif self.plan.interval == 'year':\n            return self.current_period_start + timedelta(days=365)\n        elif self.plan.interval == 'week':\n            return self.current_period_start + timedelta(days=7)\n```\n\n## Billing Cycle Processing\n\n```python\nclass BillingEngine:\n    def process_billing_cycle(self, subscription_id):\n        \"\"\"Process billing for a subscription.\"\"\"\n        subscription = self.get_subscription(subscription_id)\n\n        # Check if billing is due\n        if datetime.now() \u003C subscription.current_period_end:\n            return\n\n        # Generate invoice\n        invoice = self.generate_invoice(subscription)\n\n        # Attempt payment\n        payment_result = self.charge_customer(\n            subscription.customer_id,\n            invoice.total\n        )\n\n        if payment_result.success:\n            # Payment successful\n            invoice.mark_paid()\n            subscription.advance_billing_period()\n            self.send_invoice(invoice)\n        else:\n            # Payment failed\n            subscription.mark_past_due()\n            self.start_dunning_process(subscription, invoice)\n\n    def generate_invoice(self, subscription):\n        \"\"\"Generate invoice for billing period.\"\"\"\n        invoice = Invoice(\n            customer_id=subscription.customer_id,\n            subscription_id=subscription.id,\n            period_start=subscription.current_period_start,\n            period_end=subscription.current_period_end\n        )\n\n        # Add subscription line item\n        invoice.add_line_item(\n            description=subscription.plan.name,\n            amount=subscription.plan.amount,\n            quantity=subscription.quantity or 1\n        )\n\n        # Add usage-based charges if applicable\n        if subscription.has_usage_billing:\n            usage_charges = self.calculate_usage_charges(subscription)\n            invoice.add_line_item(\n                description=\"Usage charges\",\n                amount=usage_charges\n            )\n\n        # Calculate tax\n        tax = self.calculate_tax(invoice.subtotal, subscription.customer)\n        invoice.tax = tax\n\n        invoice.finalize()\n        return invoice\n\n    def charge_customer(self, customer_id, amount):\n        \"\"\"Charge customer using saved payment method.\"\"\"\n        customer = self.get_customer(customer_id)\n\n        try:\n            # Charge using payment processor\n            charge = stripe.Charge.create(\n                customer=customer.stripe_id,\n                amount=int(amount * 100),  # Convert to cents\n                currency='usd'\n            )\n\n            return PaymentResult(success=True, transaction_id=charge.id)\n        except stripe.error.CardError as e:\n            return PaymentResult(success=False, error=str(e))\n```\n\n## Dunning Management\n\n```python\nclass DunningManager:\n    \"\"\"Manage failed payment recovery.\"\"\"\n\n    def __init__(self):\n        self.retry_schedule = [\n            {'days': 3, 'email_template': 'payment_failed_first'},\n            {'days': 7, 'email_template': 'payment_failed_reminder'},\n            {'days': 14, 'email_template': 'payment_failed_final'}\n        ]\n\n    def start_dunning_process(self, subscription, invoice):\n        \"\"\"Start dunning process for failed payment.\"\"\"\n        dunning_attempt = DunningAttempt(\n            subscription_id=subscription.id,\n            invoice_id=invoice.id,\n            attempt_number=1,\n            next_retry=datetime.now() + timedelta(days=3)\n        )\n\n        # Send initial failure notification\n        self.send_dunning_email(subscription, 'payment_failed_first')\n\n        # Schedule retries\n        self.schedule_retries(dunning_attempt)\n\n    def retry_payment(self, dunning_attempt):\n        \"\"\"Retry failed payment.\"\"\"\n        subscription = self.get_subscription(dunning_attempt.subscription_id)\n        invoice = self.get_invoice(dunning_attempt.invoice_id)\n\n        # Attempt payment again\n        result = self.charge_customer(subscription.customer_id, invoice.total)\n\n        if result.success:\n            # Payment succeeded\n            invoice.mark_paid()\n            subscription.status = SubscriptionStatus.ACTIVE\n            self.send_dunning_email(subscription, 'payment_recovered')\n            dunning_attempt.mark_resolved()\n        else:\n            # Still failing\n            dunning_attempt.attempt_number += 1\n\n            if dunning_attempt.attempt_number \u003C len(self.retry_schedule):\n                # Schedule next retry\n                next_retry_config = self.retry_schedule[dunning_attempt.attempt_number]\n                dunning_attempt.next_retry = datetime.now() + timedelta(days=next_retry_config['days'])\n                self.send_dunning_email(subscription, next_retry_config['email_template'])\n            else:\n                # Exhausted retries, cancel subscription\n                subscription.cancel(at_period_end=False)\n                self.send_dunning_email(subscription, 'subscription_canceled')\n\n    def send_dunning_email(self, subscription, template):\n        \"\"\"Send dunning notification to customer.\"\"\"\n        customer = self.get_customer(subscription.customer_id)\n\n        email_content = self.render_template(template, {\n            'customer_name': customer.name,\n            'amount_due': subscription.plan.amount,\n            'update_payment_url': f\"https:\u002F\u002Fapp.example.com\u002Fbilling\"\n        })\n\n        send_email(\n            to=customer.email,\n            subject=email_content['subject'],\n            body=email_content['body']\n        )\n```\n\n## Proration\n\n```python\nclass ProrationCalculator:\n    \"\"\"Calculate prorated charges for plan changes.\"\"\"\n\n    @staticmethod\n    def calculate_proration(old_plan, new_plan, period_start, period_end, change_date):\n        \"\"\"Calculate proration for plan change.\"\"\"\n        # Days in current period\n        total_days = (period_end - period_start).days\n\n        # Days used on old plan\n        days_used = (change_date - period_start).days\n\n        # Days remaining on new plan\n        days_remaining = (period_end - change_date).days\n\n        # Calculate prorated amounts\n        unused_amount = (old_plan.amount \u002F total_days) * days_remaining\n        new_plan_amount = (new_plan.amount \u002F total_days) * days_remaining\n\n        # Net charge\u002Fcredit\n        proration = new_plan_amount - unused_amount\n\n        return {\n            'old_plan_credit': -unused_amount,\n            'new_plan_charge': new_plan_amount,\n            'net_proration': proration,\n            'days_used': days_used,\n            'days_remaining': days_remaining\n        }\n\n    @staticmethod\n    def calculate_seat_proration(current_seats, new_seats, price_per_seat, period_start, period_end, change_date):\n        \"\"\"Calculate proration for seat changes.\"\"\"\n        total_days = (period_end - period_start).days\n        days_remaining = (period_end - change_date).days\n\n        # Additional seats charge\n        additional_seats = new_seats - current_seats\n        prorated_amount = (additional_seats * price_per_seat \u002F total_days) * days_remaining\n\n        return {\n            'additional_seats': additional_seats,\n            'prorated_charge': max(0, prorated_amount),  # No refund for removing seats mid-cycle\n            'effective_date': change_date\n        }\n```\n\n## Tax Calculation\n\n```python\nclass TaxCalculator:\n    \"\"\"Calculate sales tax, VAT, GST.\"\"\"\n\n    def __init__(self):\n        # Tax rates by region\n        self.tax_rates = {\n            'US_CA': 0.0725,  # California sales tax\n            'US_NY': 0.04,    # New York sales tax\n            'GB': 0.20,       # UK VAT\n            'DE': 0.19,       # Germany VAT\n            'FR': 0.20,       # France VAT\n            'AU': 0.10,       # Australia GST\n        }\n\n    def calculate_tax(self, amount, customer):\n        \"\"\"Calculate applicable tax.\"\"\"\n        # Determine tax jurisdiction\n        jurisdiction = self.get_tax_jurisdiction(customer)\n\n        if not jurisdiction:\n            return 0\n\n        # Get tax rate\n        tax_rate = self.tax_rates.get(jurisdiction, 0)\n\n        # Calculate tax\n        tax = amount * tax_rate\n\n        return {\n            'tax_amount': tax,\n            'tax_rate': tax_rate,\n            'jurisdiction': jurisdiction,\n            'tax_type': self.get_tax_type(jurisdiction)\n        }\n\n    def get_tax_jurisdiction(self, customer):\n        \"\"\"Determine tax jurisdiction based on customer location.\"\"\"\n        if customer.country == 'US':\n            # US: Tax based on customer state\n            return f\"US_{customer.state}\"\n        elif customer.country in ['GB', 'DE', 'FR']:\n            # EU: VAT\n            return customer.country\n        elif customer.country == 'AU':\n            # Australia: GST\n            return 'AU'\n        else:\n            return None\n\n    def get_tax_type(self, jurisdiction):\n        \"\"\"Get type of tax for jurisdiction.\"\"\"\n        if jurisdiction.startswith('US_'):\n            return 'Sales Tax'\n        elif jurisdiction in ['GB', 'DE', 'FR']:\n            return 'VAT'\n        elif jurisdiction == 'AU':\n            return 'GST'\n        return 'Tax'\n\n    def validate_vat_number(self, vat_number, country):\n        \"\"\"Validate EU VAT number.\"\"\"\n        # Use VIES API for validation\n        # Returns True if valid, False otherwise\n        pass\n```\n\n## Invoice Generation\n\n```python\nclass Invoice:\n    def __init__(self, customer_id, subscription_id=None):\n        self.id = generate_invoice_number()\n        self.customer_id = customer_id\n        self.subscription_id = subscription_id\n        self.status = 'draft'\n        self.line_items = []\n        self.subtotal = 0\n        self.tax = 0\n        self.total = 0\n        self.created_at = datetime.now()\n\n    def add_line_item(self, description, amount, quantity=1):\n        \"\"\"Add line item to invoice.\"\"\"\n        line_item = {\n            'description': description,\n            'unit_amount': amount,\n            'quantity': quantity,\n            'total': amount * quantity\n        }\n        self.line_items.append(line_item)\n        self.subtotal += line_item['total']\n\n    def finalize(self):\n        \"\"\"Finalize invoice and calculate total.\"\"\"\n        self.total = self.subtotal + self.tax\n        self.status = 'open'\n        self.finalized_at = datetime.now()\n\n    def mark_paid(self):\n        \"\"\"Mark invoice as paid.\"\"\"\n        self.status = 'paid'\n        self.paid_at = datetime.now()\n\n    def to_pdf(self):\n        \"\"\"Generate PDF invoice.\"\"\"\n        from reportlab.pdfgen import canvas\n\n        # Generate PDF\n        # Include: company info, customer info, line items, tax, total\n        pass\n\n    def to_html(self):\n        \"\"\"Generate HTML invoice.\"\"\"\n        template = \"\"\"\n        \u003C!DOCTYPE html>\n        \u003Chtml>\n        \u003Chead>\u003Ctitle>Invoice #{invoice_number}\u003C\u002Ftitle>\u003C\u002Fhead>\n        \u003Cbody>\n            \u003Ch1>Invoice #{invoice_number}\u003C\u002Fh1>\n            \u003Cp>Date: {date}\u003C\u002Fp>\n            \u003Ch2>Bill To:\u003C\u002Fh2>\n            \u003Cp>{customer_name}\u003Cbr>{customer_address}\u003C\u002Fp>\n            \u003Ctable>\n                \u003Ctr>\u003Cth>Description\u003C\u002Fth>\u003Cth>Quantity\u003C\u002Fth>\u003Cth>Amount\u003C\u002Fth>\u003C\u002Ftr>\n                {line_items}\n            \u003C\u002Ftable>\n            \u003Cp>Subtotal: ${subtotal}\u003C\u002Fp>\n            \u003Cp>Tax: ${tax}\u003C\u002Fp>\n            \u003Ch3>Total: ${total}\u003C\u002Fh3>\n        \u003C\u002Fbody>\n        \u003C\u002Fhtml>\n        \"\"\"\n\n        return template.format(\n            invoice_number=self.id,\n            date=self.created_at.strftime('%Y-%m-%d'),\n            customer_name=self.customer.name,\n            customer_address=self.customer.address,\n            line_items=self.render_line_items(),\n            subtotal=self.subtotal,\n            tax=self.tax,\n            total=self.total\n        )\n```\n\n## Usage-Based Billing\n\n```python\nclass UsageBillingEngine:\n    \"\"\"Track and bill for usage.\"\"\"\n\n    def track_usage(self, customer_id, metric, quantity):\n        \"\"\"Track usage event.\"\"\"\n        UsageRecord.create(\n            customer_id=customer_id,\n            metric=metric,\n            quantity=quantity,\n            timestamp=datetime.now()\n        )\n\n    def calculate_usage_charges(self, subscription, period_start, period_end):\n        \"\"\"Calculate charges for usage in billing period.\"\"\"\n        usage_records = UsageRecord.get_for_period(\n            subscription.customer_id,\n            period_start,\n            period_end\n        )\n\n        total_usage = sum(record.quantity for record in usage_records)\n\n        # Tiered pricing\n        if subscription.plan.pricing_model == 'tiered':\n            charge = self.calculate_tiered_pricing(total_usage, subscription.plan.tiers)\n        # Per-unit pricing\n        elif subscription.plan.pricing_model == 'per_unit':\n            charge = total_usage * subscription.plan.unit_price\n        # Volume pricing\n        elif subscription.plan.pricing_model == 'volume':\n            charge = self.calculate_volume_pricing(total_usage, subscription.plan.tiers)\n\n        return charge\n\n    def calculate_tiered_pricing(self, total_usage, tiers):\n        \"\"\"Calculate cost using tiered pricing.\"\"\"\n        charge = 0\n        remaining = total_usage\n\n        for tier in sorted(tiers, key=lambda x: x['up_to']):\n            tier_usage = min(remaining, tier['up_to'] - tier['from'])\n            charge += tier_usage * tier['unit_price']\n            remaining -= tier_usage\n\n            if remaining \u003C= 0:\n                break\n\n        return charge\n```\n","# Billing Automation\n\nMaster automated billing systems including recurring billing, invoice generation, dunning management, proration, and tax calculation.\n\n## When to Use This Skill\n\n- Implementing SaaS subscription billing\n- Automating invoice generation and delivery\n- Managing failed payment recovery (dunning)\n- Calculating prorated charges for plan changes\n- Handling sales tax, VAT, and GST\n- Processing usage-based billing\n- Managing billing cycles and renewals\n\n## Core Concepts\n\n### 1. Billing Cycles\n\n**Common Intervals:**\n\n- Monthly (most common for SaaS)\n- Annual (discounted long-term)\n- Quarterly\n- Weekly\n- Custom (usage-based, per-seat)\n\n### 2. Subscription States\n\n```\ntrial → active → past_due → canceled\n              → paused → resumed\n```\n\n### 3. Dunning Management\n\nAutomated process to recover failed payments through:\n\n- Retry schedules\n- Customer notifications\n- Grace periods\n- Account restrictions\n\n### 4. Proration\n\nAdjusting charges when:\n\n- Upgrading\u002Fdowngrading mid-cycle\n- Adding\u002Fremoving seats\n- Changing billing frequency\n\n## Quick Start\n\n```python\nfrom billing import BillingEngine, Subscription\n\n# Initialize billing engine\nbilling = BillingEngine()\n\n# Create subscription\nsubscription = billing.create_subscription(\n    customer_id=\"cus_123\",\n    plan_id=\"plan_pro_monthly\",\n    billing_cycle_anchor=datetime.now(),\n    trial_days=14\n)\n\n# Process billing cycle\nbilling.process_billing_cycle(subscription.id)\n```\n\n## Subscription Lifecycle Management\n\n```python\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nclass SubscriptionStatus(Enum):\n    TRIAL = \"trial\"\n    ACTIVE = \"active\"\n    PAST_DUE = \"past_due\"\n    CANCELED = \"canceled\"\n    PAUSED = \"paused\"\n\nclass Subscription:\n    def __init__(self, customer_id, plan, billing_cycle_day=None):\n        self.id = generate_id()\n        self.customer_id = customer_id\n        self.plan = plan\n        self.status = SubscriptionStatus.TRIAL\n        self.current_period_start = datetime.now()\n        self.current_period_end = self.current_period_start + timedelta(days=plan.trial_days or 30)\n        self.billing_cycle_day = billing_cycle_day or self.current_period_start.day\n        self.trial_end = datetime.now() + timedelta(days=plan.trial_days) if plan.trial_days else None\n\n    def start_trial(self, trial_days):\n        \"\"\"Start trial period.\"\"\"\n        self.status = SubscriptionStatus.TRIAL\n        self.trial_end = datetime.now() + timedelta(days=trial_days)\n        self.current_period_end = self.trial_end\n\n    def activate(self):\n        \"\"\"Activate subscription after trial or immediately.\"\"\"\n        self.status = SubscriptionStatus.ACTIVE\n        self.current_period_start = datetime.now()\n        self.current_period_end = self.calculate_next_billing_date()\n\n    def mark_past_due(self):\n        \"\"\"Mark subscription as past due after failed payment.\"\"\"\n        self.status = SubscriptionStatus.PAST_DUE\n        # Trigger dunning workflow\n\n    def cancel(self, at_period_end=True):\n        \"\"\"Cancel subscription.\"\"\"\n        if at_period_end:\n            self.cancel_at_period_end = True\n            # Will cancel when current period ends\n        else:\n            self.status = SubscriptionStatus.CANCELED\n            self.canceled_at = datetime.now()\n\n    def calculate_next_billing_date(self):\n        \"\"\"Calculate next billing date based on interval.\"\"\"\n        if self.plan.interval == 'month':\n            return self.current_period_start + timedelta(days=30)\n        elif self.plan.interval == 'year':\n            return self.current_period_start + timedelta(days=365)\n        elif self.plan.interval == 'week':\n            return self.current_period_start + timedelta(days=7)\n```\n\n## Billing Cycle Processing\n\n```python\nclass BillingEngine:\n    def process_billing_cycle(self, subscription_id):\n        \"\"\"Process billing for a subscription.\"\"\"\n        subscription = self.get_subscription(subscription_id)\n\n        # Check if billing is due\n        if datetime.now() \u003C subscription.current_period_end:\n            return\n\n        # Generate invoice\n        invoice = self.generate_invoice(subscription)\n\n        # Attempt payment\n        payment_result = self.charge_customer(\n            subscription.customer_id,\n            invoice.total\n        )\n\n        if payment_result.success:\n            # Payment successful\n            invoice.mark_paid()\n            subscription.advance_billing_period()\n            self.send_invoice(invoice)\n        else:\n            # Payment failed\n            subscription.mark_past_due()\n            self.start_dunning_process(subscription, invoice)\n\n    def generate_invoice(self, subscription):\n        \"\"\"Generate invoice for billing period.\"\"\"\n        invoice = Invoice(\n            customer_id=subscription.customer_id,\n            subscription_id=subscription.id,\n            period_start=subscription.current_period_start,\n            period_end=subscription.current_period_end\n        )\n\n        # Add subscription line item\n        invoice.add_line_item(\n            description=subscription.plan.name,\n            amount=subscription.plan.amount,\n            quantity=subscription.quantity or 1\n        )\n\n        # Add usage-based charges if applicable\n        if subscription.has_usage_billing:\n            usage_charges = self.calculate_usage_charges(subscription)\n            invoice.add_line_item(\n                description=\"Usage charges\",\n                amount=usage_charges\n            )\n\n        # Calculate tax\n        tax = self.calculate_tax(invoice.subtotal, subscription.customer)\n        invoice.tax = tax\n\n        invoice.finalize()\n        return invoice\n\n    def charge_customer(self, customer_id, amount):\n        \"\"\"Charge customer using saved payment method.\"\"\"\n        customer = self.get_customer(customer_id)\n\n        try:\n            # Charge using payment processor\n            charge = stripe.Charge.create(\n                customer=customer.stripe_id,\n                amount=int(amount * 100),  # Convert to cents\n                currency='usd'\n            )\n\n            return PaymentResult(success=True, transaction_id=charge.id)\n        except stripe.error.CardError as e:\n            return PaymentResult(success=False, error=str(e))\n```\n\n## Dunning Management\n\n```python\nclass DunningManager:\n    \"\"\"Manage failed payment recovery.\"\"\"\n\n    def __init__(self):\n        self.retry_schedule = [\n            {'days': 3, 'email_template': 'payment_failed_first'},\n            {'days': 7, 'email_template': 'payment_failed_reminder'},\n            {'days': 14, 'email_template': 'payment_failed_final'}\n        ]\n\n    def start_dunning_process(self, subscription, invoice):\n        \"\"\"Start dunning process for failed payment.\"\"\"\n        dunning_attempt = DunningAttempt(\n            subscription_id=subscription.id,\n            invoice_id=invoice.id,\n            attempt_number=1,\n            next_retry=datetime.now() + timedelta(days=3)\n        )\n\n        # Send initial failure notification\n        self.send_dunning_email(subscription, 'payment_failed_first')\n\n        # Schedule retries\n        self.schedule_retries(dunning_attempt)\n\n    def retry_payment(self, dunning_attempt):\n        \"\"\"Retry failed payment.\"\"\"\n        subscription = self.get_subscription(dunning_attempt.subscription_id)\n        invoice = self.get_invoice(dunning_attempt.invoice_id)\n\n        # Attempt payment again\n        result = self.charge_customer(subscription.customer_id, invoice.total)\n\n        if result.success:\n            # Payment succeeded\n            invoice.mark_paid()\n            subscription.status = SubscriptionStatus.ACTIVE\n            self.send_dunning_email(subscription, 'payment_recovered')\n            dunning_attempt.mark_resolved()\n        else:\n            # Still failing\n            dunning_attempt.attempt_number += 1\n\n            if dunning_attempt.attempt_number \u003C len(self.retry_schedule):\n                # Schedule next retry\n                next_retry_config = self.retry_schedule[dunning_attempt.attempt_number]\n                dunning_attempt.next_retry = datetime.now() + timedelta(days=next_retry_config['days'])\n                self.send_dunning_email(subscription, next_retry_config['email_template'])\n            else:\n                # Exhausted retries, cancel subscription\n                subscription.cancel(at_period_end=False)\n                self.send_dunning_email(subscription, 'subscription_canceled')\n\n    def send_dunning_email(self, subscription, template):\n        \"\"\"Send dunning notification to customer.\"\"\"\n        customer = self.get_customer(subscription.customer_id)\n\n        email_content = self.render_template(template, {\n            'customer_name': customer.name,\n            'amount_due': subscription.plan.amount,\n            'update_payment_url': f\"https:\u002F\u002Fapp.example.com\u002Fbilling\"\n        })\n\n        send_email(\n            to=customer.email,\n            subject=email_content['subject'],\n            body=email_content['body']\n        )\n```\n\n## Proration\n\n```python\nclass ProrationCalculator:\n    \"\"\"Calculate prorated charges for plan changes.\"\"\"\n\n    @staticmethod\n    def calculate_proration(old_plan, new_plan, period_start, period_end, change_date):\n        \"\"\"Calculate proration for plan change.\"\"\"\n        # Days in current period\n        total_days = (period_end - period_start).days\n\n        # Days used on old plan\n        days_used = (change_date - period_start).days\n\n        # Days remaining on new plan\n        days_remaining = (period_end - change_date).days\n\n        # Calculate prorated amounts\n        unused_amount = (old_plan.amount \u002F total_days) * days_remaining\n        new_plan_amount = (new_plan.amount \u002F total_days) * days_remaining\n\n        # Net charge\u002Fcredit\n        proration = new_plan_amount - unused_amount\n\n        return {\n            'old_plan_credit': -unused_amount,\n            'new_plan_charge': new_plan_amount,\n            'net_proration': proration,\n            'days_used': days_used,\n            'days_remaining': days_remaining\n        }\n\n    @staticmethod\n    def calculate_seat_proration(current_seats, new_seats, price_per_seat, period_start, period_end, change_date):\n        \"\"\"Calculate proration for seat changes.\"\"\"\n        total_days = (period_end - period_start).days\n        days_remaining = (period_end - change_date).days\n\n        # Additional seats charge\n        additional_seats = new_seats - current_seats\n        prorated_amount = (additional_seats * price_per_seat \u002F total_days) * days_remaining\n\n        return {\n            'additional_seats': additional_seats,\n            'prorated_charge': max(0, prorated_amount),  # No refund for removing seats mid-cycle\n            'effective_date': change_date\n        }\n```\n\n## Tax Calculation\n\n```python\nclass TaxCalculator:\n    \"\"\"Calculate sales tax, VAT, GST.\"\"\"\n\n    def __init__(self):\n        # Tax rates by region\n        self.tax_rates = {\n            'US_CA': 0.0725,  # California sales tax\n            'US_NY': 0.04,    # New York sales tax\n            'GB': 0.20,       # UK VAT\n            'DE': 0.19,       # Germany VAT\n            'FR': 0.20,       # France VAT\n            'AU': 0.10,       # Australia GST\n        }\n\n    def calculate_tax(self, amount, customer):\n        \"\"\"Calculate applicable tax.\"\"\"\n        # Determine tax jurisdiction\n        jurisdiction = self.get_tax_jurisdiction(customer)\n\n        if not jurisdiction:\n            return 0\n\n        # Get tax rate\n        tax_rate = self.tax_rates.get(jurisdiction, 0)\n\n        # Calculate tax\n        tax = amount * tax_rate\n\n        return {\n            'tax_amount': tax,\n            'tax_rate': tax_rate,\n            'jurisdiction': jurisdiction,\n            'tax_type': self.get_tax_type(jurisdiction)\n        }\n\n    def get_tax_jurisdiction(self, customer):\n        \"\"\"Determine tax jurisdiction based on customer location.\"\"\"\n        if customer.country == 'US':\n            # US: Tax based on customer state\n            return f\"US_{customer.state}\"\n        elif customer.country in ['GB', 'DE', 'FR']:\n            # EU: VAT\n            return customer.country\n        elif customer.country == 'AU':\n            # Australia: GST\n            return 'AU'\n        else:\n            return None\n\n    def get_tax_type(self, jurisdiction):\n        \"\"\"Get type of tax for jurisdiction.\"\"\"\n        if jurisdiction.startswith('US_'):\n            return 'Sales Tax'\n        elif jurisdiction in ['GB', 'DE', 'FR']:\n            return 'VAT'\n        elif jurisdiction == 'AU':\n            return 'GST'\n        return 'Tax'\n\n    def validate_vat_number(self, vat_number, country):\n        \"\"\"Validate EU VAT number.\"\"\"\n        # Use VIES API for validation\n        # Returns True if valid, False otherwise\n        pass\n```\n\n## Invoice Generation\n\n```python\nclass Invoice:\n    def __init__(self, customer_id, subscription_id=None):\n        self.id = generate_invoice_number()\n        self.customer_id = customer_id\n        self.subscription_id = subscription_id\n        self.status = 'draft'\n        self.line_items = []\n        self.subtotal = 0\n        self.tax = 0\n        self.total = 0\n        self.created_at = datetime.now()\n\n    def add_line_item(self, description, amount, quantity=1):\n        \"\"\"Add line item to invoice.\"\"\"\n        line_item = {\n            'description': description,\n            'unit_amount': amount,\n            'quantity': quantity,\n            'total': amount * quantity\n        }\n        self.line_items.append(line_item)\n        self.subtotal += line_item['total']\n\n    def finalize(self):\n        \"\"\"Finalize invoice and calculate total.\"\"\"\n        self.total = self.subtotal + self.tax\n        self.status = 'open'\n        self.finalized_at = datetime.now()\n\n    def mark_paid(self):\n        \"\"\"Mark invoice as paid.\"\"\"\n        self.status = 'paid'\n        self.paid_at = datetime.now()\n\n    def to_pdf(self):\n        \"\"\"Generate PDF invoice.\"\"\"\n        from reportlab.pdfgen import canvas\n\n        # Generate PDF\n        # Include: company info, customer info, line items, tax, total\n        pass\n\n    def to_html(self):\n        \"\"\"Generate HTML invoice.\"\"\"\n        template = \"\"\"\n        \u003C!DOCTYPE html>\n        \u003Chtml>\n        \u003Chead>\u003Ctitle>Invoice #{invoice_number}\u003C\u002Ftitle>\u003C\u002Fhead>\n        \u003Cbody>\n            \u003Ch1>Invoice #{invoice_number}\u003C\u002Fh1>\n            \u003Cp>Date: {date}\u003C\u002Fp>\n            \u003Ch2>Bill To:\u003C\u002Fh2>\n            \u003Cp>{customer_name}\u003Cbr>{customer_address}\u003C\u002Fp>\n            \u003Ctable>\n                \u003Ctr>\u003Cth>Description\u003C\u002Fth>\u003Cth>Quantity\u003C\u002Fth>\u003Cth>Amount\u003C\u002Fth>\u003C\u002Ftr>\n                {line_items}\n            \u003C\u002Ftable>\n            \u003Cp>Subtotal: ${subtotal}\u003C\u002Fp>\n            \u003Cp>Tax: ${tax}\u003C\u002Fp>\n            \u003Ch3>Total: ${total}\u003C\u002Fh3>\n        \u003C\u002Fbody>\n        \u003C\u002Fhtml>\n        \"\"\"\n\n        return template.format(\n            invoice_number=self.id,\n            date=self.created_at.strftime('%Y-%m-%d'),\n            customer_name=self.customer.name,\n            customer_address=self.customer.address,\n            line_items=self.render_line_items(),\n            subtotal=self.subtotal,\n            tax=self.tax,\n            total=self.total\n        )\n```\n\n## Usage-Based Billing\n\n```python\nclass UsageBillingEngine:\n    \"\"\"Track and bill for usage.\"\"\"\n\n    def track_usage(self, customer_id, metric, quantity):\n        \"\"\"Track usage event.\"\"\"\n        UsageRecord.create(\n            customer_id=customer_id,\n            metric=metric,\n            quantity=quantity,\n            timestamp=datetime.now()\n        )\n\n    def calculate_usage_charges(self, subscription, period_start, period_end):\n        \"\"\"Calculate charges for usage in billing period.\"\"\"\n        usage_records = UsageRecord.get_for_period(\n            subscription.customer_id,\n            period_start,\n            period_end\n        )\n\n        total_usage = sum(record.quantity for record in usage_records)\n\n        # Tiered pricing\n        if subscription.plan.pricing_model == 'tiered':\n            charge = self.calculate_tiered_pricing(total_usage, subscription.plan.tiers)\n        # Per-unit pricing\n        elif subscription.plan.pricing_model == 'per_unit':\n            charge = total_usage * subscription.plan.unit_price\n        # Volume pricing\n        elif subscription.plan.pricing_model == 'volume':\n            charge = self.calculate_volume_pricing(total_usage, subscription.plan.tiers)\n\n        return charge\n\n    def calculate_tiered_pricing(self, total_usage, tiers):\n        \"\"\"Calculate cost using tiered pricing.\"\"\"\n        charge = 0\n        remaining = total_usage\n\n        for tier in sorted(tiers, key=lambda x: x['up_to']):\n            tier_usage = min(remaining, tier['up_to'] - tier['from'])\n            charge += tier_usage * tier['unit_price']\n            remaining -= tier_usage\n\n            if remaining \u003C= 0:\n                break\n\n        return charge\n```\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fpayment-processing\u002Fskills\u002Fbilling-automation",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill billing-automation",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill billing-automation",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill billing-automation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fpayment-processing\u002Fskills\u002Fbilling-automation\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]