# Advanced Quota Management, Alerts, Add-ons & Edge Cases

This document serves as the companion specification to [Usage-And-Subscription-Quota-Architecture.md](file:///home/naimul/Sites/social-media-manager/docs/Usage-And-Subscription-Quota-Architecture.md). It outlines advanced quota features including **Subscriber CRM capacity**, **AI Knowledge Base training limits**, **Usage warning alerts (80%/100%)**, **Subscription billing period anchoring**, and **Pay-as-you-go credit top-ups**.

---

## 1. Additional Capacity Limits

### A. Subscriber CRM Capacity (`capturedSubscribers`)
* **Module:** Facebook Tools > Subscriber Manager (`Subscriber` model).
* **Concept:** When Facebook Comment-to-DM Flywheels or Live Chat conversations interact with users, they capture contacts into the CRM.
* **Tier Limits:**
  * **Starter:** 1,000 Subscribers
  * **Professional:** 10,000 Subscribers
  * **Agency:** 50,000 Subscribers
* **Enforcement Point:** `FlywheelService::recordFlywheelSubscriber()` and `SubscriberService::captureSubscriber()`.
* **Behavior on Limit:**
  * Existing subscribers continue receiving automated replies and updates.
  * New incoming commenters still receive public replies and private DMs, but a warning tag (`'unindexed_lead'`) is assigned and full CRM indexing is paused until the workspace upgrades.

---

### B. AI Knowledge Base & Training Quota (`knowledgeBaseItems`)
* **Module:** Facebook Tools > AI Agent Manager > Knowledge Base.
* **Concept:** AI Live Chat and Auto-Reply agents ingest FAQs, PDFs, and custom URLs for contextual responses.
* **Tier Limits:**

| Resource Metric | Starter | Professional | Agency |
| :--- | :--- | :--- | :--- |
| **Max FAQs / Text Chunks** | 15 items | 100 items | 500 items |
| **Max PDF / File Upload Size** | 2 MB | 10 MB | 50 MB |
| **URL Crawl Depth** | Single page | Up to 5 subpages | Full site crawl (25 pages) |

* **Enforcement Point:** `KnowledgeBaseController::store()` / `KnowledgeBaseService::trainDocument()`.
* **Behavior on Limit:**
  * Prevents uploading new documents or training new embeddings with an error prompt: *"Knowledge Base storage limit reached for current plan."*

---

## 2. Proactive Usage Alerts & Warning Thresholds (80% & 100%)

To avoid unexpected bot interruptions, workspaces receive proactive notifications as their monthly consumption approaches plan limits.

### A. Threshold Rules
1. **80% Consumed (Warning State):**
   * **In-App Toast / Banner:** *"You have utilized 80% of your monthly AI Comment Moderation quota (4,000 / 5,000 used)."*
   * **Email Notification:** Sent once per billing cycle to the team owner with a 1-click upgrade button.
2. **100% Consumed (Exhausted State):**
   * **Dashboard Status Badge:** Switches from `Online & Replying` to `AI Quota Reached (Manual Mode)`.
   * **In-App Persistent Alert:** Alert banner displayed at the top of Comment Manager and Live Chat.
   * **Email Alert:** Urgent notification sent to team admins.

### B. Alert Deduping & Tracking
To prevent spamming users on every comment:
* Store alert trigger timestamps in cache or `team_usages`:
  * `ai_comments_80_alert_sent_at`
  * `ai_comments_100_alert_sent_at`
* Reset alerts automatically when the billing cycle rolls over.

---

## 3. Subscription Billing Period Anchoring

### A. Calendar Month vs. Subscription Cycle
* **The Problem:** If a user subscribes on the **18th of the month**, resetting their quota on the **1st of the month** causes confusion (they get a reset after only 12 days).
* **The Solution (Subscription-Anchored Cycles):**
  * Use the team's active `subscription.current_period_starts_at` date as the period identifier.
  * Example Period Identifier: `sub_2026_08_18` instead of plain `2026-08`.

### B. Period Calculation Logic
```php
public function getCurrentBillingPeriod(Team $team): string
{
    $subscription = $team->subscriptions()->latest()->first();

    if ($subscription && $subscription->current_period_starts_at) {
        return 'sub_' . $subscription->current_period_starts_at->format('Y_m_d');
    }

    // Fallback to calendar month for free trial users
    return 'cal_' . now()->format('Y_m');
}
```

---

## 4. Pay-As-You-Go Add-on & Credit Top-Up Packs

When a workspace reaches their quota mid-month but does not wish to jump to a higher subscription tier, they can purchase **Instant Credit Top-Up Packs**.

### A. Top-Up Credit Architecture
Add a `bonus_credits` JSON column to the `teams` table (or integrate with `team_credits` table from wallet migrations):
```json
{
  "aiCaptionGenerations": 100,
  "aiCommentModeration": 2000,
  "aiLiveChatResponses": 1000
}
```

### B. Quota Consumption Priority Flow
```mermaid
flowchart TD
    A[Action: AI Comment Moderation] --> B{Monthly Plan Quota Remaining?}
    B -- Yes --> C[Increment monthly team_usages counter]
    B -- No --> D{Does team have Bonus/Top-up Credits?}
    D -- Yes --> E[Decrement team bonus_credits]
    D -- No --> F[Trigger Quota Exceeded & Fallback to Manual Review]
```

---

## 5. Summary of All Platform Quotas

```
┌────────────────────────────────────────────────────────────────────────┐
│                        PLATFORM QUOTA INVENTORY                        │
├────────────────────────┬─────────────────────────┬─────────────────────┤
│ Resource Key           │ Limit Type              │ Reset Frequency     │
├────────────────────────┼─────────────────────────┼─────────────────────┤
│ aiCaptionGenerations   │ Monthly Consumable      │ Every Billing Cycle │
│ aiCommentModeration    │ Monthly Consumable      │ Every Billing Cycle │
│ aiLiveChatResponses    │ Monthly Consumable      │ Every Billing Cycle │
│ socialPosts            │ Monthly Consumable      │ Every Billing Cycle │
│ connectedAccounts      │ Static Capacity         │ Continuous          │
│ activePages            │ Static Capacity         │ Continuous          │
│ capturedSubscribers    │ Static Capacity         │ Continuous          │
│ knowledgeBaseItems     │ Static Capacity         │ Continuous          │
│ teamMembers            │ Static Capacity         │ Continuous          │
└────────────────────────┴─────────────────────────┴─────────────────────┘
```
