# Product Requirements Document (PRD)
## AI-Powered Social Media Manager Panel

**Version:** 1.0 (Draft)
**Date:** August 6, 2026
**Owner:** [Product Owner Name]
**Status:** Draft for Review

---

## 1. Executive Summary

The Social Media Manager Panel is a web-based SaaS platform that lets businesses, agencies, and creators manage multiple social media pages (Facebook, Instagram, and optionally LinkedIn/X/TikTok) from a single dashboard. It combines **content publishing and scheduling**, **AI-assisted comment moderation and auto-reply**, **an AI live-chat agent trained per page on business-specific knowledge**, and **AI-generated content creation** — reducing manual workload for social media teams while improving response time and customer experience.

This document defines the product scope, features, suggested enhancements, and a recommended technical approach to build it.

---

## 2. Goals & Success Metrics

| Goal | Metric |
|---|---|
| Reduce manual comment moderation effort | % of toxic/spam comments auto-handled without human review |
| Speed up customer response time | Average first-response time on comments/DMs (target: <2 min) |
| Increase publishing efficiency | Time to publish one post across N pages (target: <30 sec) |
| Improve engagement | Reply rate, resolution rate of chat queries by AI |
| Platform stickiness | Weekly active pages per account, retention at 90 days |

---

## 3. Target Users

- **Social media agencies** managing 5–100+ client pages
- **SMBs / e-commerce brands** with 1–5 pages needing automation
- **Enterprise marketing teams** needing role-based multi-brand management
- **Solo creators/influencers** wanting AI-assisted engagement

---

## 4. Scope

### In Scope (V1)
- Facebook Pages + Instagram Business accounts (via Meta Graph API) — these are the most API-accessible platforms for comment/DM automation
- Post publishing, scheduling, multi-page posting
- Comment moderation (auto-hide/delete "bad" comments)
- Auto-reply to comments (rule-based + AI-generated)
- Unified live chat inbox (Messenger + Instagram DM) with AI auto-response
- Page-wise AI knowledge base / agent training
- AI post/caption generator
- Multi-page, multi-user (team) support with roles/permissions

### Out of Scope (V1, candidates for later phases)
- TikTok, X/Twitter, LinkedIn, YouTube, Pinterest (add in V2+ as each has separate API approval processes)
- Paid ads management
- Deep analytics/BI (basic analytics only in V1)

---

## 5. Core Features (Detailed)

### 5.1 Bad Comment Removal (Comment Moderation)
**What it does:** Automatically scans incoming comments in near real-time and flags/hides/deletes ones that are toxic, spam, abusive, or against a custom "banned words/patterns" list.

**Requirements:**
- Toxicity/spam/hate-speech classification per comment (AI model + custom keyword/regex rules per page)
- Configurable moderation levels per page: *Off / Flag only / Auto-hide / Auto-delete*
- Custom blocklist (words, phrases, competitor names, links)
- Whitelist/VIP commenters who bypass moderation
- Audit log of every moderation action (reversible/undo)
- Language detection (support multi-language comments, especially important for Bangladesh/South Asia market — Bangla + English + Banglish)

### 5.2 Auto-Reply Comment / Predefined Response ("Comment AI")
**What it does:** Automatically replies to comments using either fixed templates or AI-generated context-aware replies. Special case: when a comment matches an intent (e.g., "send me the PDF" / "price list" / "brochure"), the bot replies with a **public comment + a private DM containing the resource link** (this mirrors how Meta's "Automated Responses" + ManyChat-style comment-to-DM flywheels work, and avoids policy issues with posting direct download links publicly on some categories of pages).

**Requirements:**
- Keyword/intent triggers ("price", "pdf", "link", "details", "kivabe pabo", etc.)
- Predefined response library with variables (e.g., `{{first_name}}`, `{{page_name}}`)
- AI fallback: if no rule matches, generate a contextual reply from page's trained knowledge base
- Resource delivery: attach PDF/catalog/link — delivered via comment reply and/or auto-DM
- Rate limiting to stay within Meta API comment-reply limits and avoid spam flags
- Human-in-the-loop mode: AI drafts reply, human approves before sending (optional per page)

### 5.3 Social Media Posting (Multi-Page, Scheduling)
**What it does:** Compose once, publish to one or many selected pages, immediately or on a schedule.

**Requirements:**
- Rich composer: text, images, carousel, video, first comment, hashtags
- Page/account picker (multi-select — post to Page A + Page B + IG account simultaneously)
- Per-platform content adaptation (aspect ratio checks, caption length limits)
- Scheduling calendar (drag-and-drop), queue view, best-time-to-post suggestions
- Draft, review/approval workflow (client approves before agency publishes)
- Recurring/evergreen post support
- Bulk upload via CSV/spreadsheet for large content batches
- Retry/failure handling if a platform API call fails

### 5.4 AI Post Generator
**What it does:** Generates captions, hashtags, and image ideas from a short prompt, product info, or URL.

**Requirements:**
- Input: topic/prompt, tone (formal/funny/promotional), target platform, language
- Output: 2–3 caption variants + hashtag suggestions + optional AI image generation
- "Repurpose" mode: turn one blog/article/product URL into multiple platform-specific posts
- Brand voice profile per page (so AI writes consistently with a trained tone)

### 5.5 Live Chat with AI Response (Trained Per Page)
**What it does:** Unified inbox for Messenger/Instagram DMs where an AI agent answers using knowledge specific to that page (products, FAQs, policies), with human handoff.

**Requirements:**
- Unified inbox across pages/platforms with conversation assignment to team members
- Page-wise AI agent: each page has its own knowledge base (uploaded docs, FAQs, product catalog, website scrape)
- Retrieval-Augmented Generation (RAG) so answers are grounded in that page's data, not generic
- Confidence threshold: AI answers if confident, escalates to human if not
- Conversation tagging, canned replies, internal notes
- Business hours / auto-away messages
- Order status / e-commerce integration hooks (e.g., "where is my order")

### 5.6 Multipage / Multi-Account Support
**What it does:** One account can manage multiple Facebook Pages / Instagram accounts, and multiple team members can collaborate with different permission levels.

**Requirements:**
- Add/remove pages via Meta OAuth (Business Login)
- Workspace/organization model (agency → clients → pages)
- Role-based access control (Owner, Admin, Editor, Moderator, Viewer — per page or per workspace)
- Client-facing view (limited permissions for approval-only clients)
- Activity/audit log per page

---

## 6. Suggested Additional Features

**Engagement & Growth**
- **Sentiment analytics dashboard** — track sentiment trend of comments/DMs over time
- **Influencer/UGC discovery** — auto-flag posts where your page is tagged/mentioned
- **Contest/giveaway comment picker** — auto-pick winners from comments with rule filters
- **Story/Reel scheduling** with AI-suggested trending audio (where API allows)

**AI/Automation**
- **AI content calendar planner** — suggests a month of post ideas based on niche/industry trends
- **Auto-translate** replies/posts for multi-language pages
- **Competitor benchmarking** — track competitor page posting frequency/engagement (public data)
- **AI-generated video captions/subtitles**
- **Smart hashtag performance tracker**

**Operations**
- **Approval workflows with client sign-off links** (no login required for client)
- **White-label option** for agencies to rebrand the panel for their clients
- **Team performance reports** (response time, resolution rate per agent)
- **Webhook/Zapier/Make integration** for connecting to CRM, e-commerce, helpdesk tools
- **Mobile app / PWA** for on-the-go moderation and replies

**Compliance & Safety**
- **Crisis mode** — one-click pause all auto-replies/auto-posting during a PR crisis
- **PII redaction** — auto-mask phone numbers/emails/addresses shared in public comments
- **Data export & deletion tools** (GDPR-style compliance, important if serving EU clients)

**Monetization-ready**
- Usage-based billing hooks (per page, per AI response, per seat)
- Free trial with page/message quotas

---

## 7. How to Build It — Technical Approach (Laravel Stack)

This project maps very well onto a **Laravel monolith** — Laravel's queues, scheduler, broadcasting, and the new official AI SDK cover almost every backend need here (webhooks, scheduled posting, real-time inbox, AI/RAG) without needing a separate microservices layer for V1.

**Confirmed stack:**
- **Backend:** Laravel (12.x)
- **Frontend:** Inertia.js + Vue 3 (single monolith, no separate SPA/API layer needed)
- **Real-time:** Laravel Reverb (first-party WebSocket server) for the live chat inbox and instant notifications
- **Multi-tenancy / Teams:** Laravel Jetstream's **Teams** feature (Workspace → Team → Pages model), extended with a permissions package for page-level RBAC
- **AI:** Laravel AI SDK (`laravel/ai`) — Laravel's official first-party package (released Feb 2026) for LLM text generation, agents with tools, structured output, embeddings, images, and audio, with a provider-agnostic interface across OpenAI, Anthropic, Gemini, Groq, xAI, and more

### 7.1 High-Level Architecture

```
┌───────────────────────────────────────────────────────────────────┐
│                    Laravel App (Monolith)                          │
│                                                                      │
│  ┌───────────────────┐   Inertia.js (Vue 3) — SPA-like dashboard,  │
│  │  Web / Dashboard   │   server-driven routing, no separate API   │
│  └─────────┬──────────┘   layer needed for the UI                  │
│            │                                                        │
│  ┌─────────▼──────────┐   ┌────────────────────┐                   │
│  │  Laravel Reverb     │   │  Broadcasting        │  → pushes new  │
│  │  (WebSocket server) │◄──┤  Events (new comment,│    messages/   │
│  │                     │   │  new message, etc.)  │    comments to │
│  └─────────────────────┘   └────────────────────┘    the live UI  │
│                                                                      │
│  ┌───────────────────────────────────────────────────────────┐    │
│  │  Controllers / Actions                                      │    │
│  │  - PostingController (compose/schedule/multi-page publish)   │    │
│  │  - WebhookController (Meta webhook receiver)                 │    │
│  │  - ChatController (inbox, assignment, AI handoff)            │    │
│  │  - AutomationController (moderation & auto-reply rules)      │    │
│  └───────────────────────────────────────────────────────────┘    │
│                                                                      │
│  ┌───────────────────────────────────────────────────────────┐    │
│  │  Queued Jobs (database/Redis queue + Laravel Horizon)        │    │
│  │  - PublishScheduledPost   - ProcessIncomingComment            │    │
│  │  - ModerateComment (AI)  - GenerateAiReply (AI SDK Agent)     │    │
│  │  - IngestKnowledgeDocument (embeddings)                       │    │
│  └───────────────────────────────────────────────────────────┘    │
│                                                                      │
│  ┌───────────────────────────────────────────────────────────┐    │
│  │  Laravel AI SDK (laravel/ai)                                  │    │
│  │  - Agents (per-page persona + tools + structured output)      │    │
│  │  - Embeddings (per-page knowledge base → vector store)        │    │
│  │  - Provider-agnostic: OpenAI / Anthropic / Gemini / etc.       │    │
│  └───────────────────────────────────────────────────────────┘    │
│                                                                      │
│  Laravel Scheduler (cron) → dispatches due scheduled posts hourly/  │
│  per-minute into the queue                                          │
└──────────────────────────────┬───────────────────────────────────┘
                                │
                ┌───────────────▼────────────────┐
                │  Meta Graph API / Webhooks       │
                │  (Pages, Instagram, Messenger,   │
                │   comment & message webhooks)    │
                └──────────────────────────────────┘

Supporting: MySQL/PostgreSQL (core data + pgvector if Postgres) · Redis (queues, cache, Reverb scaling)
· S3-compatible storage (media/PDFs, via Laravel Filesystem) · Laravel Horizon (queue monitoring)
```

### 7.2 Why This Stack Fits Well
- **Inertia.js + Vue** gives you a modern, reactive dashboard (drag-and-drop scheduler, live inbox, composer) while keeping everything in one Laravel codebase — no separate REST/GraphQL API to maintain for the frontend, which speeds up development significantly for a single-team build.
- **Laravel Reverb** replaces the need for a third-party service like Pusher/Socket.io — it's self-hosted, integrates directly with Laravel's `Broadcasting` events, and is the natural fit for the live chat inbox (new message pushed instantly to agents) and real-time moderation alerts (new flagged comment appears live).
- **Laravel Jetstream Teams** gives you the Workspace/Agency → Team → Members model out of the box (invite members, switch teams). Layer a package like **Spatie's `laravel-permission`** on top for fine-grained, per-page roles (Owner/Admin/Editor/Moderator/Viewer) beyond Jetstream's default team roles.
- **Laravel AI SDK (`laravel/ai`)** directly covers the AI-heavy parts of this product:
  - **Agents with tools** → build a `PageSupportAgent` per page that can call tools (e.g., "look up order status", "fetch product info") and return structured output.
  - **Structured output** → use `HasStructuredOutput` to force the AI's comment-moderation or reply decisions into a predictable JSON shape (`{action: "hide"|"reply"|"escalate", reply_text, confidence}`) that your app logic can safely act on.
  - **Embeddings** → generate embeddings for each page's uploaded FAQs/PDFs/catalog for retrieval (RAG).
  - **Streaming** → stream AI replies into the live chat UI via Reverb for a "typing" effect.
  - **Provider-agnostic config** → start with one LLM provider and switch/add others later via config, without rewriting business logic.
  - **Built-in testing fakes** → makes the AI agents unit-testable, which matters a lot once you have automation acting on real customer comments.

### 7.3 Platform Integrations
- **Facebook Pages & Instagram:** Meta Graph API (Pages API, Instagram Graph API) for posting and reading comments, plus the Messenger/Instagram Messaging API for DMs. Use **Laravel Socialite** (with a Facebook/Meta driver) for the OAuth "Connect Page" flow. Requires Meta **App Review** for permissions like `pages_manage_posts`, `pages_messaging`, `instagram_manage_comments`, `pages_read_engagement` — budget 2–6 weeks.
- **Webhooks:** A dedicated `WebhookController` route (excluded from CSRF, signature-verified using Meta's `X-Hub-Signature-256`) receives new comments/messages and immediately dispatches a queued job — keeps the webhook response fast (Meta expects a quick 200 OK) while the actual moderation/AI-reply work happens asynchronously in the queue.
- **Future platforms (V2+):** X/Twitter API, LinkedIn Marketing API, TikTok Business API — each needs separate developer approval; wrap each platform behind a common `SocialPlatform` interface/contract in Laravel so adding a new platform means writing one new adapter class, not touching core logic.

### 7.4 AI/ML Layer (via Laravel AI SDK)
- **Comment moderation:** A queued job (`ModerateComment`) calls an AI SDK agent configured with structured output to classify each comment (toxicity/spam/hate-speech/language) and return a decision object; combine with a fast pre-filter of custom regex/keyword blocklists per page before hitting the LLM, to save cost on obvious cases.
- **Comment/DM auto-reply & post generation:** Prompt-templated calls through the AI SDK's unified interface — one `Agent` class per use case (`CommentReplyAgent`, `DmReplyAgent`, `CaptionGeneratorAgent`), each with its own instructions/persona, swappable LLM provider via config.
- **Page-wise trained AI agent (RAG):**
  1. On document upload (FAQ, PDF, catalog, scraped website text), a queued `IngestKnowledgeDocument` job chunks the text and generates embeddings via the AI SDK's embeddings API.
  2. Store embeddings in **pgvector** (if using Postgres) or a dedicated vector store, scoped strictly by `page_id` — critical for tenant isolation so one client's data never leaks into another's answers.
  3. On an incoming DM/comment, retrieve top-matching chunks for that specific page, pass them + conversation history into the page's `Agent` instance, and generate a grounded reply.
  4. Structured output includes a confidence score; below threshold → auto-escalate to a human in the live inbox instead of guessing.
- **Multi-language support:** detect the incoming language and instruct the agent to reply in kind (important for Bangla/English/Banglish audiences).

### 7.5 Data Model (Core Entities)
- `Team` (Jetstream Team = Workspace/Agency) → `Page` (social account) → `Post`, `Comment`, `Conversation`/`Message`
- `KnowledgeDocument` (per Page) → `Chunk` with `embedding` column (pgvector)
- `AutomationRule` (per Page) → trigger type, condition, action
- `User` ↔ `Team` (Jetstream) with per-page roles via `laravel-permission`
- `AuditLog`, `ScheduledPost` (with `scheduled_at`, dispatched by the Laravel scheduler), `MediaAsset`

### 7.6 Suggested Package List
| Need | Laravel Package |
|---|---|
| Frontend scaffolding | Inertia.js + Vue 3, Tailwind CSS |
| Auth + Teams | Laravel Jetstream (Livewire or Inertia stack — choose Inertia stack to match frontend) |
| Fine-grained roles/permissions | `spatie/laravel-permission` |
| Real-time / live inbox | Laravel Reverb + Laravel Echo (client-side) |
| AI (generation, agents, embeddings) | `laravel/ai` (official Laravel AI SDK) |
| OAuth with Meta | Laravel Socialite |
| Queues + monitoring | Laravel Queues (Redis driver) + Laravel Horizon |
| Scheduled posting | Laravel Task Scheduling (`schedule:run` cron) + queued jobs |
| Vector storage | `pgvector` Postgres extension (simplest — same DB as the app) |
| Media/PDF storage | Laravel Filesystem with S3-compatible driver |
| Activity/audit logging | `spatie/laravel-activitylog` |
| Testing | Pest (pairs with `laravel/ai`'s built-in AI fakes for testing automation logic) |

### 7.7 Build Order (Phased Roadmap)
**Phase 1 — MVP (8–12 weeks)**
- Meta OAuth + connect Pages/IG accounts
- Basic composer: post now / schedule, multi-page select
- Webhook ingestion of comments + basic keyword-based auto-reply
- Manual comment moderation UI + simple blocklist auto-hide
- Single-page AI knowledge base (upload FAQ/PDF) + basic RAG chat reply for DMs

**Phase 2 — Core AI Automation (6–10 weeks)**
- AI post/caption generator
- AI-based toxicity moderation (replacing pure keyword rules)
- Full live chat inbox with team assignment, canned replies
- Comment-to-DM resource delivery flow (PDF link automation)
- Role-based access control, multi-user workspaces

**Phase 3 — Scale & Expand (ongoing)**
- Add more platforms (X, LinkedIn, TikTok)
- Analytics dashboard, sentiment trends
- White-label, billing/usage metering
- Approval workflows, client portal
- Mobile app/PWA

### 7.8 Compliance & Platform Policy Notes
- Meta requires **App Review** before you can use permissions like posting, reading comments, or messaging at scale on behalf of other Pages — plan 2–6 weeks for this process.
- Automated replies to Messenger/Instagram must follow **Meta's Platform Policy** (e.g., the 24-hour messaging window rules, message tags for outside-window messages).
- Publicly posting external download links in comments can trigger spam flags on some page categories — routing PDFs/links via **DM after a comment trigger** is safer and is the standard pattern used by comment-automation tools.
- Store only the minimum required user data; provide a Laravel route for Meta's required Data Deletion Callback URL, and encrypt stored page access tokens at rest (Laravel's built-in encrypted casts on the `Page` model work well here).

---

## 8. Non-Functional Requirements
- **Reliability:** scheduled posts must have retry logic; webhook processing must be idempotent (avoid duplicate replies)
- **Latency:** comment/DM auto-reply should trigger within seconds of webhook receipt
- **Security:** encrypt stored access tokens; per-page data isolation in the vector DB; RBAC enforced at API layer
- **Scalability:** design for horizontal scaling of webhook processors and the AI orchestrator independently from the web app
- **Observability:** logging/alerting on failed API calls, Meta rate-limit warnings, AI response failures

---

## 9. Risks & Mitigations
| Risk | Mitigation |
|---|---|
| Meta App Review rejection/delay | Start review process early with a minimal working demo; keep permissions scope minimal at first |
| API rate limits during bulk actions | Queue and throttle requests; use batch endpoints where available |
| AI giving wrong/off-brand answers | Confidence threshold + human escalation; strict per-page RAG isolation; regular prompt/response audits |
| Over-aggressive comment moderation (false positives) | Flag-first mode by default; easy undo; human review queue before hard delete |
| Platform policy changes breaking automation | Abstract platform integrations behind an internal adapter layer so changes are isolated |

---

## 10. Open Questions (to resolve with stakeholders)
1. Which platforms are must-have for launch — Facebook + Instagram only, or is X/LinkedIn needed at V1?
2. Is this being built for internal use, or as a sellable SaaS product for other agencies (affects billing/white-label priority)?
3. What's the expected scale at launch (number of pages, messages/day) — affects infra choices (pgvector vs dedicated vector DB, monolith vs microservices)?
4. Which LLM provider is preferred for cost/quality tradeoffs?

---

*End of document.*
