# SMARTFLOW AI
## AI-Powered Marketing & Commerce Automation Platform
### Complete Master Development Blueprint
### Version 4.0
### Deployment: Single Domain | Single Database | Multi-Tenant
### Hosting: WHM / cPanel Compatible
### Framework: Laravel 12
### UI System: Material Design 3 (M3)

See **README.md** for quick start and **DEPLOYMENT.md** for deployment, feature checklist, and troubleshooting.

---

# 1. PRODUCT OVERVIEW

SmartFlow AI is an AI-powered SaaS platform that enables businesses to:

- Generate AI marketing content
- Auto-reply to social messages using AI
- Schedule & publish posts to Facebook, Instagram, WhatsApp, LinkedIn
- Sell digital products
- Build landing pages
- Train AI using uploaded documents
- Manage multiple team members
- Operate in a multi-tenant environment

All within one system.

---

# 2. SYSTEM ARCHITECTURE

Client Browser  
→ Apache/Nginx (cPanel)  
→ Laravel Application  
→ MySQL (Single Database)  
→ Queue (Database or Redis)  
→ External License Server  

---

# 3. MULTI-TENANCY MODEL

Single database.
All business tables must include:

- id (UUID)
- tenant_id (UUID indexed)
- created_at
- updated_at
- deleted_at (soft delete)

Tenant isolation enforced via:
- Global Eloquent Scope
- TenantResolutionMiddleware

No cross-tenant access allowed.

---

# 4. DATABASE TABLES (CORE)

## tenants
id, name, plan, status, created_at, updated_at

## users
id, tenant_id, name, email, password, role, status

Unique: (tenant_id, email)

## products
id, tenant_id, title, price, file_path, status

## orders
id, tenant_id, product_id, user_id, transaction_id, status

## campaigns
id, tenant_id, platform, scheduled_at, status

## ai_requests
id, tenant_id, prompt, response, tokens_used, status

## social_accounts
id, tenant_id, platform, account_id, encrypted_access_token, status

## social_replies
id, tenant_id, platform, sender_id, message, ai_response, status

## knowledge_base
id, tenant_id, title, content, file_path, vector_reference

## subscriptions
id, tenant_id, plan_name, status, expires_at

## license_keys
id, purchase_hash, domain_hash, support_expiry, status

All tenant_id indexed.
Composite index (tenant_id, status).

---

# 5. MODULE STRUCTURE

/app/Modules/

- Identity
- Tenancy
- AI
- AIReply
- AIKnowledge
- Social
- Marketplace
- Funnel
- Billing
- Licensing
- Installer

All business logic must be inside Services.
Controllers only call Services.

---

# 6. AI CONTENT MODULE

AIProviderInterface
generate(prompt)

Flow:
User → AIService → Queue Job → External API → Save result

States:
queued → processing → completed → failed

Retry max 3 times.

---

# 7. SOCIAL MEDIA MODULE

Supported:
- Facebook Pages
- Instagram Business
- WhatsApp Business
- LinkedIn Pages

Features:
- Connect accounts
- Schedule posts
- Publish posts
- Track publish status

Post states:
draft → scheduled → publishing → published → failed

All publishing via queue.

---

# 8. AI AUTO REPLY ENGINE

Purpose:
Auto-reply to incoming messages using AI.

Flow:
Webhook → Store message → Queue AIReplyJob → Generate response → Send reply → Log

Reply states:
received → replied → failed

Include:
- Business tone setting
- Conversation memory
- Knowledge base injection

Prevent infinite reply loops.

---

# 9. AI KNOWLEDGE TRAINING

Allow tenant to:

- Upload PDF/DOC/TXT
- Paste custom content

Process:
Extract text → Chunk → Store → Create embeddings → Save reference

During reply:
Fetch relevant chunks → Append to AI prompt → Generate context-aware answer

All heavy tasks queued.

---

# 10. MARKETPLACE MODULE

- Upload digital products
- Secure file delivery
- Order management
- Transaction validation

File delivery:
Signed temporary URL (expires 10 minutes)

Order states:
pending → paid → completed → refunded

---

# 11. BILLING & PLAN LIMITS

Plan limits include:

- user_limit
- campaign_limit
- ai_token_limit
- social_account_limit
- knowledge_document_limit

PlanLimitMiddleware must enforce limits.

Return structured JSON error when exceeded.

---

# 12. MATERIAL DESIGN 3 UI SYSTEM

UI must follow:

- Material 3 design guidelines
- Left navigation drawer
- Top app bar
- Elevated cards
- Rounded corners
- Soft shadows
- Dark mode toggle
- 8px spacing grid

Dashboard must be:
Tabular-first.

All tables must support:
- Sort
- Filter
- Pagination
- Bulk actions
- Search
- CSV export

Mobile:
Tables collapse into expandable cards.

---

# 13. AUTO INSTALLER

Route:
/install

Steps:

## Step 1 — Environment Check

Validate:
- PHP >= 8.2
- Required extensions
- Writable directories

## Step 2 — Database Setup

Collect:
- DB Host
- DB Port
- DB Name
- DB Username
- DB Password

Test connection.

Optional:
Create database automatically (if permission allows).

## Step 3 — SQL Import

Option A:
Run Laravel migrations (preferred)

Option B:
Import /database/schema/install.sql

Disable FK checks during import.

## Step 4 — License Activation

Collect purchase code.
Validate via License Server.
Store encrypted token.

## Step 5 — Admin Setup

Collect:
- Admin Name
- Email
- Password

Create:
- Tenant record
- Admin user (role=tenant_admin)

Password hashed using Argon2.

## Step 6 — Lock Installer

Create:
/storage/installed.lock

Disable installer route permanently.

---

# 14. LICENSE SYSTEM

License server verifies via Envato API.

JWT signed (RS256).

Validation triggers:
- Installation
- Daily cron
- Plugin activation
- Update check

Grace period:
72 hours if server unreachable.

Never delete data.
Never block login immediately.

---

# 15. QUEUE & CRON

QUEUE_CONNECTION=database

Cron:
* * * * * php artisan schedule:run

All heavy operations must be queued:
- AI generation
- Social publishing
- Auto reply
- Knowledge processing

---

# 16. CPANEL DEPLOYMENT

Upload to public_html.
Set document root to /public.

Run:
php artisan config:cache
php artisan route:cache
php artisan view:cache

Ensure:
APP_DEBUG=false
HTTPS enabled

---

# 17. SECURITY RULES

- No plaintext secrets
- Encrypt API tokens
- Hash purchase codes
- Validate webhook signatures
- CSRF enabled
- Rate limit license attempts
- No raw SQL
- Parameter binding mandatory

---

# 18. DEVELOPMENT ORDER

Phase 1: DB & Tenancy  
Phase 2: Auth & RBAC  
Phase 3: Service Layer  
Phase 4: AI Module  
Phase 5: Social Integration  
Phase 6: AI Auto Reply  
Phase 7: Knowledge System  
Phase 8: Marketplace  
Phase 9: Billing  
Phase 10: License  
Phase 11: Installer  
Phase 12: UI Implementation  
Phase 13: QA & Security  

---

# 19. ACCEPTANCE CHECKLIST

✔ Multi-tenant safe  
✔ AI generation working  
✔ Social publishing working  
✔ Auto-reply functional  
✔ Knowledge training active  
✔ Marketplace secure  
✔ Plan limits enforced  
✔ Installer fully automated  
✔ License validated  
✔ UI Material 3 compliant  
✔ cPanel compatible  
✔ Queue stable  

---

# 20. FINAL SUCCESS CRITERIA

SmartFlow AI must be:

- Single domain
- Single database
- Multi-tenant isolated
- Auto-installable
- License protected
- AI powered
- Social integrated
- Marketplace enabled
- Modern UI
- Production hardened
- CodeCanyon ready

---

# END OF MASTER DEVELOPMENT BLUEPRINT
