Exemplos de prompts
Demonstrações reais e completas do que o Hypper Cloud gera para cada tipo de projeto.
Prompts completos são exclusivos para quem tem créditos. Compre créditos para desbloquear.
PhotoRevive
Micro-SaaS · Restauração de fotos
React + TypeScript · Supabase · Stripe · IA
# PHOTOREVIVE — UNIVERSAL PROMPT
# Works on: Lovable, Base44, Google AI Studio, Replit, Bolt.new, v0, Cursor, Windsurf, etc.
# Just paste this entire prompt and let the platform build it.
---
## ⚡ CRITICAL INSTRUCTION — READ BEFORE ANYTHING ELSE
**Build the ENTIRE application in a SINGLE response, all at once, completely.**
Do NOT ask clarifying questions. Do NOT build one page and wait for feedback. Do NOT say "let me start with the landing page and we can continue later." Do NOT deliver partial versions. Do NOT stop midway.
You must deliver, in one single complete build:
- ✅ Every page listed in this prompt, fully built and functional
- ✅ Complete backend logic (database, auth, storage, server functions)
- ✅ Full authentication system (signup, login, logout, session persistence)
- ✅ Working credit system (deduct on use, refund on failure, add on purchase)
- ✅ Stripe payment integration (checkout, webhook, credit delivery)
- ✅ AI photo restoration logic connected end-to-end
- ✅ All components (including the before/after slider)
- ✅ All loading states, error states, empty states, and success messages
- ✅ Mobile responsive layout on every page
- ✅ Fully usable, ready to test immediately after build
The goal is to receive a **100% complete, working application** that can be opened in the browser, signed up on, used to restore a photo, and paid for — all without any additional prompts or manual configuration.
If this platform cannot build everything at once, build as much as possible in order of priority: auth → app core → payments → remaining pages.
---
Build a complete, production-ready web application called **PhotoRevive** — an AI-powered photo restoration Micro-SaaS where users upload old, damaged, black-and-white, or faded photos and receive an AI-restored, colorized, HD version for download.
Use whatever backend, database, and auth system is native to this platform. Use whatever AI image generation or image-to-image capability is available natively. Do not require any manual API key setup from the user — use built-in integrations only.
---
## WHAT THE APP DOES
1. User signs up / logs in
2. User uploads an old photo (JPG, PNG, WEBP)
3. AI analyzes and restores the photo: colorizes B&W images, removes scratches and damage, sharpens faces and details, increases resolution to HD
4. User sees a before/after comparison slider
5. User downloads the restored photo
6. Each restoration costs 1 credit
7. Free plan includes 1 credit (with watermark on output)
8. Users buy credit packs to restore more photos (no subscriptions)
---
## DESIGN SYSTEM
```
Background: #0C0C0F (near black)
Surface cards: #141418
Surface elevated: #1C1C22
Primary color: #8B5CF6 (violet/purple)
Primary hover: #7C3AED
Accent gold: #F59E0B (for pricing CTAs)
Accent green: #10B981 (for download/success)
Text primary: #F8FAFC
Text secondary: #94A3B8
Text muted: #475569
Border color: #2D2D3A
Font: Inter for all UI text
```
**Visual style:** Dark, cinematic, nostalgic. Like a digital darkroom. Emotional and premium. The before/after slider is the hero UI element on both the landing page and the app.
---
## DATABASE STRUCTURE
Create these data models (use whatever database the platform provides):
**User Profile:**
- id, email, full_name, avatar_url
- plan: "free" | "starter" | "pro" | "unlimited" (default: "free")
- credits: integer (default: 1 — given on signup)
- total_restorations: integer (default: 0)
- stripe_customer_id: string (optional)
- created_at, updated_at
**Restoration:**
- id, user_id
- original_image_url: string
- restored_image_url: string (null until completed)
- enhancement_type: "full" | "colorize" | "upscale" | "face" | "scratch"
- status: "pending" | "processing" | "completed" | "failed"
- credits_used: integer (default: 1)
- error_message: string (optional)
- created_at, updated_at
**Credit Purchase:**
- id, user_id
- package_name: "starter" | "pro" | "unlimited"
- credits_bought: integer
- amount_cents: integer
- payment_id: string (from payment provider)
- status: "pending" | "completed" | "failed"
- created_at
**Security rules:** Users can only read and write their own data. All tables/collections must have user-level access control.
**On user signup:** Automatically create a profile with 1 free credit.
---
## CREDIT PLANS & PRICING
```
FREE (on signup — automatic):
- 1 credit
- Output has watermark ("PhotoRevive" text, subtle, bottom-right)
- Max 2MB file upload
STARTER PACK — $4.99:
- 10 credits
- No watermark
- Max 10MB file upload
- HD output
PRO PACK — $9.99 (MOST POPULAR):
- 25 credits
- No watermark
- Max 20MB file upload
- Full HD output
- Priority processing
UNLIMITED PACK — $24.99:
- 100 credits
- No watermark
- Max 50MB file upload
- Ultra HD output
- Best value ($0.25/photo)
```
**Rules:**
- No subscriptions — one-time purchases only
- Credits never expire
- 1 credit = 1 restoration
- On failed restoration: refund the credit automatically
- Use Stripe for payments (or platform's native payment system if available)
---
## ALL PAGES TO BUILD
### LANDING PAGE (route: /)
**Header:** Logo (PhotoRevive) + Nav links (How It Works, Examples, Pricing) + "Sign In" + "Try Free →" CTA button (purple)
**Hero:**
- H1: "Bring Your Old Photos Back to Life"
- Subheadline: "Upload faded, black & white, or damaged photos and watch AI restore them to stunning HD color — in seconds."
- Large interactive before/after comparison slider (draggable divider, BEFORE label left, AFTER label right) using placeholder/demo images
- CTA button below: "Try it free — no credit card needed" → goes to signup
- Social proof: "✨ 10,000+ photos restored · ⭐ 4.9/5 rating · 🔒 Private & secure"
**How It Works (3 steps):**
1. 📤 Upload Your Photo — drag & drop or click to browse
2. 🤖 AI Restores It — colorizes, sharpens, and enhances every detail
3. ⬇️ Download in HD — get your restored photo instantly
**Examples Gallery:**
6 before/after image pairs in a grid. Use descriptive placeholders styled as old sepia/B&W photos on the left and vivid color photos on the right. Captions: "Family Portrait · 1940s", "Wedding Day · 1958", "Military Portrait · 1943", "Childhood Photo · 1965", "Street Scene · 1930s", "Graduation · 1952"
**What We Fix (6 feature cards):**
- 🎨 Colorization — Transforms B&W to natural color
- ✨ Scratch Removal — Removes tears, scratches, and spots
- 🔍 HD Upscaling — Increases resolution up to 4x
- 👤 Face Enhancement — Sharpens facial details
- 🌫️ Noise Reduction — Removes grain and blur
- 🌟 Contrast & Light — Restores faded exposure
**Pricing Section:** Show all 4 plans (Free, Starter, Pro, Unlimited). Highlight Pro as "Most Popular" with a badge.
**Testimonials (3 cards):**
- "I found a photo of my grandmother I never saw clearly before. PhotoRevive made her face visible for the first time. I cried." — Sarah M.
- "Restored 30 photos from my parents' wedding album. They couldn't believe it." — James K.
- "My grandfather's WWII photos look like they were taken yesterday." — Maria L.
**FAQ (accordion):**
- What types of photos work best?
- Is my data private and secure?
- What file formats are supported?
- Can I restore group photos?
- Do credits expire?
- What if I'm not satisfied with the result?
**Footer:** PhotoRevive © 2026 · Privacy · Terms · Contact · "Built with ❤️ for your memories"
---
### SIGNUP PAGE (route: /signup)
Clean centered card. Dark background.
- Title: "Start Restoring Your Memories"
- Subtitle: "Get 1 free restoration — no credit card required"
- Fields: Full Name, Email, Password
- Primary button: "Create Free Account" (purple, full width)
- Divider: "or"
- Google OAuth button (if available on platform)
- Link: "Already have an account? Sign in →"
- Terms note below button
- After signup: redirect to /app with toast "🎉 Welcome! You have 1 free restoration credit."
---
### LOGIN PAGE (route: /login)
Same clean layout.
- Title: "Welcome Back"
- Fields: Email + Password
- Forgot password link
- Primary button: "Sign In"
- Google OAuth if available
- "Don't have an account? Sign up free →"
---
### MAIN APP / DASHBOARD (route: /app)
**Protected route — requires authentication.**
**Top navigation bar:**
- Logo
- Credits badge: "⚡ 3 credits" (always visible, purple)
- "Buy Credits" button (gold/amber color)
- User avatar with dropdown: Profile, History, Sign Out
**Main content — two panel layout (side by side on desktop, stacked on mobile):**
**LEFT PANEL — Upload & Controls:**
Large drag-and-drop upload zone:
```
[ 📷 camera icon ]
Drop your photo here
or click to browse
JPG, PNG, WEBP supported
```
When a photo is selected: show thumbnail preview of original.
Enhancement type selector (chip/button group, single select):
- ✅ Full Restoration (default)
- 🎨 Colorize Only
- 🔍 Upscale Only
- 👤 Face Enhancement
- ✨ Remove Scratches
Large primary button: "Restore This Photo →" (purple, disabled if no photo uploaded or no credits)
If user has 0 credits: replace button with "Buy Credits to Continue →" (gold) that opens pricing modal.
**Processing state (shown while AI works):**
Animated progress indicator with steps:
1. "Uploading photo..." ✅
2. "Analyzing image..." ⟳
3. "Applying AI restoration..." ⟳
4. "Enhancing resolution..." ⟳
5. "Finalizing..." ⟳
Show: "Usually takes 15–30 seconds"
Fun tip during processing: "Did you know? AI can detect the decade a photo was taken by analyzing film grain patterns."
**RIGHT PANEL — Result Display:**
Before result: placeholder card with text "Your restored photo will appear here"
After completion:
- **Before/after comparison slider** (same draggable component as landing page) showing original vs restored
- Large green button: "⬇️ Download HD Photo"
- Free plan: file has subtle watermark (small "PhotoRevive" text, bottom-right, 30% opacity)
- Paid plans: clean file, no watermark
- Secondary button: "Restore Another Photo" (outline)
- Quick rating: "⭐ Rate this result" → 1-5 stars (optional, for feedback)
**Credit warning banner** (shown when credits = 0):
"You're out of credits. Buy more to keep restoring your memories." + "Buy Credits" button
---
### HISTORY PAGE (route: /history)
Grid of all user's past restorations.
Each card shows:
- Thumbnail of restored photo
- Date created
- Enhancement type used (badge)
- Status badge: Completed ✅ / Processing ⟳ / Failed ❌
- "Download" button (re-download anytime, no extra credits)
- "Delete" button with confirmation dialog
Top controls:
- Filter: All | Completed | Failed
- Sort: Newest first | Oldest first
- Search by date (optional)
Empty state: "No restorations yet. Upload your first photo →" with CTA button
---
### PRICING PAGE (route: /pricing)
**Can also appear as a modal when triggered from /app.**
Title: "Choose Your Credit Pack"
Subtitle: "One-time purchase. No subscriptions. Credits never expire."
4 plan cards in a grid (2x2 on mobile, 4 columns on desktop):
**FREE TRIAL:**
- 1 credit (already included on signup)
- Watermarked output
- Max 2MB upload
- CTA: "Already on your account" (disabled/grey)
**STARTER — $4.99:**
- 10 credits
- No watermark
- HD quality
- Max 10MB upload
- Download forever
- CTA: "Buy Starter" button
**PRO — $9.99 [MOST POPULAR]:**
- 25 credits
- No watermark
- Full HD quality
- Max 20MB upload
- Priority processing
- Download forever
- CTA: "Buy Pro" button (purple, highlighted)
**UNLIMITED — $24.99:**
- 100 credits
- No watermark
- Ultra HD quality
- Max 50MB upload
- Priority processing
- Download forever
- Best value: $0.25/photo
- CTA: "Buy Unlimited" button (gold)
Trust signals below cards:
"🔒 Secure payment via Stripe · No subscription · Credits never expire · Instant delivery"
---
### SETTINGS PAGE (route: /settings)
**Profile section:**
- Full name (editable, save button)
- Email (read-only)
- Change password option
- Profile picture (if platform supports uploads)
**Credits & Billing section:**
- Current balance: X credits
- Purchase history table: Date | Package | Credits | Amount | Status
- "Buy More Credits" button → goes to /pricing
**Danger Zone:**
- "Delete My Account" button (red, with confirmation: type "DELETE" to confirm)
- Deletes all data including photos and restoration history
---
## BEFORE/AFTER SLIDER COMPONENT
This is the most critical UI component. Must be reused on both the landing page and the app result panel.
**Behavior:**
- Two images overlaid in same container
- Vertical divider line with a circular drag handle in the center
- Dragging left reveals more of the BEFORE (original) image
- Dragging right reveals more of the AFTER (restored) image
- Default position: 50% (centered)
- "BEFORE" label in top-left corner
- "AFTER" label in top-right corner
- Works with mouse drag on desktop
- Works with touch/swipe on mobile
- On first render: animate the handle left then right once to show users it's interactive
- Divider handle: circular button with left/right arrows icon, glows with primary purple color
---
## AI RESTORATION LOGIC
Use whatever AI image generation capability is natively available on this platform.
**The prompt to send to the AI for image restoration:**
```
Base prompt (always included):
"Restore and enhance this old photograph professionally. Make it look sharp, clear, and modern while preserving the authentic feel and people in the photo."
Additional by enhancement type:
- Full Restoration: "Colorize if black and white using natural, period-appropriate colors. Remove all scratches, tears, spots, and physical damage. Enhance facial features and details. Increase resolution to HD quality. Improve contrast, brightness, and clarity."
- Colorize Only: "Add natural, realistic, period-appropriate colors to this black and white photograph. Do not change composition or people."
- Upscale Only: "Increase the resolution significantly. Make it sharp, clear and high definition. Preserve all existing details."
- Face Enhancement: "Focus on enhancing and clarifying facial features. Sharpen eyes, skin, and facial details. Restore damaged facial areas."
- Scratch Removal: "Remove all scratches, tears, spots, stains, and physical damage. Restore damaged areas to match the surrounding content seamlessly."
```
**Processing flow:**
1. Validate user is authenticated and has credits ≥ 1
2. Validate file type (JPG/PNG/WEBP only) and size (based on plan)
3. Upload original image to storage
4. Create restoration record with status "processing"
5. Deduct 1 credit from user profile
6. Send image + prompt to AI
7. Upload AI output to storage
8. Update restoration record: status "completed", restored_image_url = new URL
9. Increment user's total_restorations by 1
10. Return restored image URL to frontend
**On any error:**
- Set restoration status to "failed"
- Refund 1 credit (add back to user profile)
- Store error message
- Show user: "Restoration failed. Your credit has been refunded. Please try again."
---
## STRIPE PAYMENT FLOW
Use Stripe for payments (or the platform's native payment system if Stripe integration is not available).
**Three one-time payment products:**
- Starter Pack: $4.99 → adds 10 credits
- Pro Pack: $9.99 → adds 25 credits
- Unlimited Pack: $24.99 → adds 100 credits
**Flow:**
1. User selects a pack and clicks Buy
2. Create a Stripe Checkout Session (one-time payment, not subscription)
3. Redirect user to Stripe hosted checkout
4. On success: redirect to /app?purchase=success
5. Handle Stripe webhook (checkout.session.completed or payment_intent.succeeded)
6. Add credits to user's profile
7. Create record in credit_purchases table
8. Show success toast: "✅ X credits added to your account!"
**On payment page:** Never store card details. Use Stripe's hosted checkout for PCI compliance.
---
## SECURITY REQUIREMENTS
1. All database tables must have row-level security — users access only their own data
2. File storage must be private — users can only access their own uploaded/restored photos
3. Credit validation must happen server-side before processing (not just frontend)
4. File type validation: reject anything that is not JPG, PNG, or WEBP
5. File size limits enforced by plan tier
6. Stripe webhook signature must be verified before processing payment events
7. Rate limiting: max 10 restoration attempts per hour per user
---
## RESPONSIVE DESIGN RULES
**Mobile (< 768px):**
- Single column layout on all pages
- Upload zone and result stacked vertically
- Bottom sticky bar showing: credit count + "Buy Credits" button
- All buttons minimum 48px height for touch
- Before/after slider full width
**Desktop (≥ 768px):**
- Two column layout on /app (upload left, result right)
- 4-column pricing grid
- Side-by-side before/after slider on landing hero
---
## SEO & META TAGS
```html
<title>PhotoRevive — Restore Old Photos with AI | Free Trial</title>
<meta name="description" content="Bring your old, faded, and black & white photos back to life with AI. Colorize, sharpen, and restore damaged photos to stunning HD quality. 1 free restoration on signup.">
<meta property="og:title" content="PhotoRevive — AI Photo Restoration">
<meta property="og:description" content="Upload old photos and watch AI restore them to stunning HD color in seconds. Try free.">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
```
---
## BUILD ORDER
Build ALL of the following simultaneously and deliver everything complete in one single build. Do not stop between steps:
1. **Landing page** (/) — complete with before/after slider, all sections, fully styled
2. **Auth pages** — /signup and /login with email/password + Google OAuth if available
3. **Main app** (/app) — upload zone, processing state, result with before/after slider
4. **History page** (/history) — grid of past restorations
5. **Pricing page** (/pricing) — all 4 plans, buy buttons
6. **Stripe payment integration** — checkout flow + webhook + credit delivery
7. **Settings page** (/settings)
8. **All backend logic** — database schema, auth rules, storage buckets, server functions
9. **All data connections** — credits deducted on restoration, refunded on failure, added on purchase
10. **All UI states** — loading, error, empty, success toasts, credit warnings on every page
---
## IMPORTANT NOTES FOR THE PLATFORM
- Use whatever database, auth, storage, and AI systems are natively available
- Do NOT hardcode any API keys in the frontend code
- All sensitive operations (payment processing, credit deduction, AI calls) must happen server-side
- The before/after slider must be built as a reusable component used in both landing page and /app
- Credits must be deducted BEFORE the AI call and refunded ONLY on confirmed failure
- The app must work on mobile — test the upload and slider on touch screens
- Dark theme only — no light/dark toggle needed
- All pages must be accessible without knowing any platform-specific implementation details
---
## ⚡ FINAL REMINDER — DELIVER EVERYTHING AT ONCE
Do not ask for confirmation. Do not pause and wait for feedback. Do not deliver half the app.
Build the **complete, fully functional PhotoRevive application right now** — every page, every backend function, every database table, the full auth flow, the credit system, the Stripe integration, and the AI restoration logic — all connected, all working, ready to open in the browser and use immediately.
**The app is considered complete when a brand new user can:**
1. Open the landing page and see it fully rendered with the before/after slider
2. Click "Try Free" and create an account
3. Upload an old photo and have it restored by AI
4. Download the restored photo
5. Go to pricing and purchase a credit pack via Stripe
6. See their purchase reflected in their credit balance
7. View their restoration history
8. Update their settings and sign out
Build it now. All of it. At once.DeckScore
Micro-SaaS · Análise de pitch decks
React + TypeScript · Supabase · Stripe · Claude AI
# DECKSCORE — UNIVERSAL LOVABLE PROMPT
# Target market: Silicon Valley founders, angels, VCs, and startup operators
# Stack: Lovable native (Supabase + Stripe + Claude AI API)
# Model: Zero upfront cost — scales on first revenue
---
## ⚡ CRITICAL INSTRUCTION — READ BEFORE ANYTHING ELSE
**Build the ENTIRE application in a SINGLE response, all at once, completely.**
Do NOT ask clarifying questions. Do NOT build one page and wait for feedback. Do NOT deliver partial versions. Do NOT stop midway.
You must deliver, in one single complete build:
- ✅ Every page listed in this prompt, fully built and functional
- ✅ Complete backend logic (Supabase database, auth, storage, edge functions)
- ✅ Full authentication system (signup, login, logout, session persistence)
- ✅ Working credit system (deduct on use, refund on failure, add on purchase)
- ✅ Stripe payment integration (checkout, webhook, credit delivery)
- ✅ Claude AI analysis logic connected end-to-end via Anthropic API
- ✅ All components (score ring, section breakdown cards, benchmark comparison)
- ✅ All loading states, error states, empty states, and success messages
- ✅ Mobile responsive layout on every page
- ✅ Fully usable, ready to test immediately after build
The goal is to receive a **100% complete, working application** that can be opened in the browser, signed up on, used to analyze a pitch deck, and paid for — all without any additional prompts or manual configuration.
If this platform cannot build everything at once, build in order of priority:
auth → upload + AI analysis → score dashboard → payments → remaining pages.
---
## PRODUCT OVERVIEW
**DeckScore** is an AI-powered pitch deck analyzer and validator for Silicon Valley founders.
Upload your pitch deck PDF → Claude AI scores it against VC benchmarks → You receive a detailed scorecard with actionable feedback on every section.
**Core insight driving the product:** Angel investors and VCs receive 20–30+ pitch decks per month. Most look like college homework. A founder with a great idea but a weak deck loses the meeting before it starts. DeckScore gives founders the unfair advantage of knowing exactly what a seasoned VC would think — before the meeting.
**Who uses this:**
- Pre-seed and seed founders preparing for fundraising rounds
- Repeat founders refining their next deck
- Accelerator applicants (YC, a16z, Sequoia scout programs)
- Startup operators prepping a board update
- Anyone pitching in Silicon Valley
---
## WHAT THE APP DOES
1. User signs up / logs in
2. User uploads a pitch deck PDF (max 25MB free, 50MB paid)
3. Claude AI reads and analyzes the full deck
4. AI scores each of 8 core sections (0–100) plus an overall score
5. User receives a detailed scorecard:
- Overall DeckScore (0–100) with letter grade (A–F)
- Section-by-section breakdown with score + 2–3 sentence feedback
- 3 "Killer Weaknesses" — the top things that would make a VC pass
- 3 "Unfair Advantages" — the strongest parts of the deck
- Benchmark comparison: "Your deck scores higher than X% of decks in [sector]"
- Specific, actionable rewrite suggestions for the 2 lowest-scoring sections
6. User can re-analyze an improved deck (costs 1 credit)
7. Each analysis costs 1 credit
8. Free plan: 1 analysis credit on signup (output visible, no download)
9. Paid plans: buy credit packs, download full PDF report
---
## THE 8 SECTIONS SCORED BY AI
For each section, Claude scores 0–100 and provides specific written feedback:
1. **Problem** — Is the pain point clear, real, and urgent? Does it create emotional resonance?
2. **Solution** — Is the product differentiated? Does it directly solve the stated problem?
3. **Market Size** — Is TAM/SAM/SOM credible, sourced, and large enough to justify VC?
4. **Business Model** — Is the revenue model clear? Is unit economics mentioned?
5. **Traction** — Are there real metrics, customers, revenue, or growth signals?
6. **Team** — Does the team have relevant domain expertise and execution track record?
7. **Competition** — Is the competitive landscape accurately represented? Is the moat clear?
8. **Ask & Use of Funds** — Is the raise amount clear? Is the use of funds specific and credible?
**Overall Score** = weighted average (Traction 20%, Team 20%, Problem 15%, Solution 15%, Market 10%, Business Model 10%, Competition 5%, Ask 5%)
---
## DESIGN SYSTEM
```
Background: #09090B (zinc-950, near black)
Surface: #18181B (zinc-900)
Surface elevated: #27272A (zinc-800)
Border: #3F3F46 (zinc-700)
Primary: #22D3EE (cyan-400) — sharp, electric, Silicon Valley energy
Primary dim: #0891B2 (cyan-600)
Accent gold: #FBBF24 (amber-400) — for scores above 80, "excellent" badges
Accent red: #F87171 (red-400) — for scores below 40, weaknesses
Accent green: #4ADE80 (green-400) — for strengths, success states
Text primary: #FAFAFA (zinc-50)
Text secondary: #A1A1AA (zinc-400)
Text muted: #71717A (zinc-500)
Font display: "DM Serif Display" — used only for the main score number and hero H1
Font UI: "DM Sans" — used for all labels, body, navigation, cards
Font mono: "JetBrains Mono" — used for scores, percentages, benchmark numbers
```
**Visual tone:** Surgical precision. A war room for founders. Dark, data-dense, high-contrast. The design should feel like Bloomberg Terminal meets Y Combinator demo day prep tool. Not beautiful for beauty's sake — beautiful because it communicates authority and trust.
**Signature element:** The DeckScore ring — a large animated circular progress ring showing the overall score (0–100) in the center in DM Serif Display, with the letter grade. The ring animates from 0 to the final score on load. This is the hero of the results page.
**No gradients on text. No purple. No rounded pill buttons. No emoji in UI.** Sharp, utilitarian, confidence-inspiring.
---
## DATABASE STRUCTURE (Supabase)
### Table: profiles
```sql
id uuid references auth.users primary key
email text not null
full_name text
company_name text
role text (founder | investor | operator | advisor | other)
plan text default 'free' (free | starter | pro | team)
credits integer default 1
total_analyses integer default 0
stripe_customer_id text
created_at timestamptz default now()
updated_at timestamptz default now()
```
### Table: deck_analyses
```sql
id uuid primary key default gen_random_uuid()
user_id uuid references profiles(id) on delete cascade
deck_name text not null
deck_file_url text
sector text (saas | fintech | marketplace | deeptech | consumer | hardware | other)
stage text (pre-seed | seed | series-a | other)
status text default 'processing' (pending | processing | completed | failed)
-- Overall result
overall_score integer
letter_grade text (A+ | A | B+ | B | C+ | C | D | F)
overall_summary text
percentile integer (0-100 — "scores higher than X% of decks")
-- Section scores (0-100 each)
score_problem integer
score_solution integer
score_market integer
score_business_model integer
score_traction integer
score_team integer
score_competition integer
score_ask integer
-- Section feedback (2-3 sentences each)
feedback_problem text
feedback_solution text
feedback_market text
feedback_business_model text
feedback_traction text
feedback_team text
feedback_competition text
feedback_ask text
-- Top insights
killer_weaknesses jsonb (array of 3 strings)
unfair_advantages jsonb (array of 3 strings)
rewrite_suggestions jsonb (array of 2 objects: {section, current_problem, suggested_rewrite})
-- Meta
credits_used integer default 1
error_message text
created_at timestamptz default now()
updated_at timestamptz default now()
```
### Table: credit_purchases
```sql
id uuid primary key default gen_random_uuid()
user_id uuid references profiles(id)
package_name text (starter | pro | team)
credits_bought integer
amount_cents integer
stripe_payment_id text
status text default 'pending' (pending | completed | failed)
created_at timestamptz default now()
```
**Security:** Enable Row Level Security on all tables. Users can only read and write their own rows.
**On user signup trigger:** Automatically insert a row into profiles with 1 free credit.
---
## CREDIT PLANS & PRICING
```
FREE (automatic on signup):
- 1 analysis credit
- Full scorecard visible in app
- No PDF report download
- 25MB PDF upload limit
STARTER — $19/month:
- 5 credits/month (refreshed monthly)
- Full scorecard + PDF report download
- 50MB upload limit
- Email scorecard delivery
PRO — $49/month (MOST POPULAR):
- 15 credits/month
- Everything in Starter
- Benchmark comparison data
- Competitor deck comparison (upcoming)
- Priority AI processing
TEAM — $149/month:
- 50 credits/month
- Everything in Pro
- 5 team seats
- Shared deck library
- Slack notifications (upcoming)
```
**Rules:**
- Monthly subscriptions (recurring Stripe billing)
- Credits reset on billing date
- Unused credits do not roll over
- On failed AI analysis: refund the credit automatically
- Stripe Checkout for all plans
---
## ALL PAGES TO BUILD
---
### LANDING PAGE (route: /)
**Header (sticky):**
Logo: "DeckScore" in DM Serif Display, size 22px, text-zinc-50 — followed by a tiny cyan dot
Nav: Features | Pricing | How It Works | Sign In
CTA button: "Analyze Your Deck" — dark cyan bg, no border-radius (sharp square corners), DM Sans medium
**Hero:**
- Eyebrow label: "USED BY SILICON VALLEY FOUNDERS" in zinc-500, letter-spacing wide, mono caps
- H1 (DM Serif Display, 64px desktop / 40px mobile):
"Your deck has
10 seconds to
impress a VC."
- Subheadline (DM Sans, zinc-400, 18px):
"DeckScore reads your pitch deck the same way an investor does — and tells you exactly where you're losing them, before it costs you a meeting."
- Primary CTA: "Analyze Your Deck Free" (no credit card)
- Secondary: "See a sample scorecard →" (links to /sample)
- Social proof row: "14,000+ decks analyzed · Average score improvement: +23 points · Trusted by YC and a16z alumni"
**Live Demo / Sample Score Widget:**
A non-interactive preview showing a fictional deck's scorecard:
- The score ring showing "74" with grade "B+"
- 3 section score bars (Problem: 88, Traction: 42, Team: 91)
- One "Killer Weakness" teaser: "Your market size slide cites no credible sources..."
- Blurred out below with "Unlock Full Analysis" overlay — CTA to signup
This gives users an instant feel for the product value before signing up.
**How It Works (3 steps, horizontal on desktop, vertical mobile):**
Step 1: Upload Your Deck — PDF up to 25MB. We never share or store your content longer than needed.
Step 2: AI Reads Like a VC — Claude AI evaluates every slide against investor-grade benchmarks from 10,000+ analyzed decks.
Step 3: Score. Fix. Fundraise. — Get your DeckScore, spot your weaknesses, and walk into your next meeting prepared.
**The 8 Sections Scored:**
Grid of 8 cards, each with:
- Section name
- One-line description of what's evaluated
- A fake score (styled, non-functional) for visual appeal
Design: dark card bg, left border accent in cyan, monospace score on the right.
**Pricing Section:**
4 plan cards. PRO highlighted with "Most Popular" tag.
All prices in USD. Monthly billing. "Cancel anytime."
Sharp card borders, no shadow. Each card lists exact feature set.
**Testimonials (3 cards):**
- "Went from a 61 to an 89 in two iterations. Closed our seed round 3 weeks later." — Jason T., Founder @ Synthara AI, YC S23
- "As an angel, I wish every founder used this before sending me their deck. Would save us both time." — Priya K., Angel Investor, 40+ investments
- "The feedback was more direct and actionable than the advisor I paid $500/hr for." — Marcus R., Co-founder @ Flowpath
**FAQ (accordion, sharp borders):**
- Is my deck data private?
- How accurate is the AI scoring?
- Can I upload a deck that's still in progress?
- What file formats are supported?
- How is DeckScore different from a pitch coach?
- Do credits roll over?
- Can my whole team use one account?
**Footer:**
DeckScore © 2026 · Privacy · Terms · Contact
"Built for founders who want honest feedback, not polite lies."
---
### SIGNUP PAGE (route: /signup)
Clean centered card on dark background. No sidebar.
- Title (DM Serif Display): "Analyze your first deck free."
- Subtitle: "No credit card required. Results in under 60 seconds."
- Fields: Full Name, Company Name (optional), Email, Password
- Role selector (radio chips): Founder | Investor | Operator | Advisor
- Submit button: "Create Account & Get 1 Free Credit"
- Below: "Already have an account? Sign in →"
- Social proof: "Join 14,000+ founders who've improved their decks"
---
### LOGIN PAGE (route: /login)
Minimal centered card.
- Title: "Welcome back."
- Fields: Email, Password
- Forgot password link
- Submit: "Sign In"
- Below: "Don't have an account? Sign up free →"
---
### MAIN APP — UPLOAD (route: /app)
Two-column layout on desktop. Full page on mobile.
**Left panel — Upload zone:**
- Title: "Upload Your Deck"
- Large drag-and-drop zone (dashed border, zinc-700):
Center icon: document upload icon
Primary text: "Drop your PDF here"
Secondary: "or click to browse · PDF only · Max 25MB"
- After file is selected: show filename, file size, green checkmark
- Sector selector (required): SaaS | Fintech | Marketplace | Deep Tech | Consumer | Hardware | Other
- Stage selector (required): Pre-Seed | Seed | Series A | Other
- Deck nickname field (optional): "e.g. Q3 Fundraise Deck v4"
- Submit button: "Analyze Deck — 1 Credit" — disabled until file + sector + stage selected
- Credit balance display below button: "You have X credits remaining"
- "Buy more credits →" link if credits = 0
**Right panel — What happens next:**
Explanation of the analysis process:
- "Reads all slides" — with icon
- "Scores 8 investor criteria" — with icon
- "Compares to 10,000+ decks" — with icon
- "Delivers your scorecard in ~45 seconds" — with icon
And a mini preview of what the results look like (static, styled placeholder)
**Processing state (full-page overlay):**
Animated state while AI is working:
- Pulsing DeckScore logo
- Progress steps updating in real time:
[✓] Uploading deck...
[→] Reading slides...
[ ] Scoring sections...
[ ] Comparing to benchmarks...
[ ] Generating insights...
- Estimated time: "Usually under 60 seconds"
- DO NOT show a spinner — show the step-by-step progress for perceived quality
---
### RESULTS PAGE (route: /app/results/:id)
This is the most important page. Design it as a war room dashboard.
**Top section — Overall Score:**
- Left: The DeckScore Ring (animated circular SVG progress ring, 200px diameter):
- Center: Score number in DM Serif Display, 56px
- Below number: Letter grade in cyan (A+, A, B+, B, C+, C, D, F)
- Ring color: green if >75, amber if 50–75, red if <50
- Animation: ring draws from 0 to final score on page load (1.2s ease-out)
- Right: Summary card:
- Deck name + sector + stage
- "Analyzed on [date]"
- Overall summary paragraph (2–3 sentences from AI)
- Benchmark: "Scores higher than [percentile]% of [sector] decks at [stage]"
- Download PDF Report button (locked for free plan — shows "Upgrade to Download")
**Section Scores — 8 Cards:**
Grid (4 cols desktop, 2 cols tablet, 1 col mobile).
Each card:
- Section name + icon
- Horizontal score bar (animated on load)
- Score number (monospace, right-aligned)
- Color: green bg tint if >75, amber if 50–75, red if <40
- 2–3 sentence feedback below the bar
- Collapsed by default — expand on click to read full feedback
**Killer Weaknesses (3 items):**
Section with red left border accent.
Title: "Where VCs Will Hesitate"
Each item: red dot + weakness statement (1–2 sentences, direct and specific)
**Unfair Advantages (3 items):**
Section with green left border accent.
Title: "Your Strongest Signals"
Each item: green checkmark + strength statement (1–2 sentences)
**Rewrite Suggestions (2 items):**
Section title: "Fix These First"
Each item:
- Section name + current score
- "Current Problem:" — 1 sentence describing what's weak
- "Suggested Rewrite Direction:" — specific, actionable guidance (2–3 sentences)
This should feel like real, honest advisor feedback, not generic tips.
**Bottom CTA bar (sticky on mobile):**
"Re-analyze improved deck — 1 credit" button
"Share results" button (copy link)
"Upgrade plan →" link if on free plan
---
### HISTORY PAGE (route: /history)
Table/list of all past analyses.
Columns: Deck Name | Sector | Stage | Score | Grade | Date | Actions
Actions: View Results | Re-analyze | Delete
Empty state: "No decks analyzed yet. Upload your first deck →"
Filter: by sector, by grade range, by date
---
### SAMPLE PAGE (route: /sample)
A fully rendered, non-interactive version of a fictional deck's results page.
Fictional company: "Prism AI" — seed-stage SaaS for sales teams.
Show the complete results experience so visitors understand the product before signup.
CTA at top and bottom: "Analyze your own deck →"
Label the page clearly: "Sample Analysis — Prism AI (fictional)"
---
### PRICING PAGE (route: /pricing)
Same pricing content as landing page but standalone, full-page experience.
Add comparison table below the cards: feature-by-feature breakdown across all 4 plans.
Trust signals: "Secure payment via Stripe · Cancel anytime · Instant access"
---
### SETTINGS PAGE (route: /settings)
**Profile section:**
- Full Name (editable)
- Company Name (editable)
- Role (editable)
- Email (read-only)
- Change password
**Credits & Billing section:**
- Current credits balance
- Plan name + renewal date
- "Manage Billing" → Stripe Customer Portal
- Purchase history table: Date | Plan | Credits | Amount | Status
**Danger Zone:**
- "Delete My Account" (red, requires typing "DELETE" to confirm)
---
## AI ANALYSIS LOGIC (Claude API via Supabase Edge Function)
### Edge Function: `analyze-deck`
**Trigger:** POST from frontend with `{ analysis_id, user_id }`
**Step-by-step logic:**
1. Validate user is authenticated and has credits >= 1
2. Retrieve deck_analyses row by analysis_id
3. Download PDF from Supabase Storage
4. Deduct 1 credit from user profile (before API call)
5. Call Anthropic Claude API (claude-sonnet-4-6) with the following:
**System prompt:**
```
You are a senior venture capital analyst with 15 years of experience at top-tier Silicon Valley firms. You have reviewed thousands of pitch decks from pre-seed to Series B. You are known for your brutally honest, specific, and actionable feedback. You never give vague advice. You always reference specific evidence from the deck in your feedback. You understand that founders need to hear the hard truth, delivered with respect. Your job is to score this pitch deck and return a structured JSON analysis.
```
**User prompt:**
```
Analyze the following pitch deck for a [sector] company at [stage] stage.
Score each of the 8 sections below on a scale of 0–100. Be calibrated: a 90+ means this section is genuinely exceptional and would impress a top-tier VC. A 50 means it's average — present but not compelling. Below 40 means it's a liability.
For each section, provide 2–3 sentences of specific, direct feedback referencing what you actually found in the deck.
Also provide:
- overall_score (weighted average: Traction 20%, Team 20%, Problem 15%, Solution 15%, Market 10%, Business Model 10%, Competition 5%, Ask 5%)
- letter_grade (A+ = 95–100, A = 88–94, B+ = 80–87, B = 70–79, C+ = 60–69, C = 50–59, D = 40–49, F = below 40)
- overall_summary: 2–3 sentences on the deck as a whole
- percentile: estimate what percentile this deck would rank vs other [sector] decks at [stage] (0–100)
- killer_weaknesses: array of exactly 3 strings — the 3 things most likely to make a VC pass, stated directly
- unfair_advantages: array of exactly 3 strings — the 3 strongest signals in this deck
- rewrite_suggestions: array of exactly 2 objects, each with: { section, current_problem, suggested_rewrite }. Pick the 2 lowest-scoring sections. Be extremely specific in suggested_rewrite.
Return ONLY valid JSON. No markdown, no preamble, no explanation outside the JSON structure.
JSON schema:
{
"overall_score": integer,
"letter_grade": string,
"overall_summary": string,
"percentile": integer,
"scores": {
"problem": integer,
"solution": integer,
"market": integer,
"business_model": integer,
"traction": integer,
"team": integer,
"competition": integer,
"ask": integer
},
"feedback": {
"problem": string,
"solution": string,
"market": string,
"business_model": string,
"traction": string,
"team": string,
"competition": string,
"ask": string
},
"killer_weaknesses": [string, string, string],
"unfair_advantages": [string, string, string],
"rewrite_suggestions": [
{ "section": string, "current_problem": string, "suggested_rewrite": string },
{ "section": string, "current_problem": string, "suggested_rewrite": string }
]
}
```
6. Parse the JSON response from Claude
7. Update deck_analyses row with all scores, feedback, and insights
8. Set status to "completed"
9. Increment user's total_analyses by 1
10. Return the analysis ID to frontend
**On any error:**
- Set deck_analyses status to "failed"
- Store error_message
- Refund 1 credit to user (add back to profile)
- Return error to frontend: "Analysis failed. Your credit has been refunded. Please try again."
---
## STRIPE PAYMENT FLOW
Use Stripe for subscriptions (monthly recurring billing).
**Three subscription products:**
- Starter: $19/month → 5 credits/month
- Pro: $49/month → 15 credits/month
- Team: $149/month → 50 credits/month
**Checkout flow:**
1. User selects a plan and clicks Subscribe
2. Create Stripe Checkout Session (mode: "subscription")
3. Redirect to Stripe hosted checkout
4. On success: redirect to /app?subscribed=true
5. Stripe webhook (customer.subscription.created, invoice.payment_succeeded)
6. Add credits to user profile based on plan
7. Update user's plan field
8. Show success toast: "Plan activated — X credits added"
**Monthly renewal webhook (invoice.payment_succeeded):**
- Reset user's credits to the plan amount each billing cycle
- Do not accumulate — reset to plan amount
**Cancellation webhook (customer.subscription.deleted):**
- Set user plan back to "free"
- Credits remain until depleted
**Stripe Customer Portal:**
- Enable via Stripe dashboard
- "Manage Billing" button in /settings opens portal (update card, cancel, upgrade/downgrade)
---
## SECURITY REQUIREMENTS
1. All Supabase tables: Row Level Security enabled, users access only their own data
2. Storage bucket for deck PDFs: private, accessible only to owner via signed URLs
3. Credit validation happens in Edge Function (server-side), not frontend
4. PDF files only — reject all other file types
5. File size limit enforced server-side
6. Stripe webhook signature verified before processing
7. Rate limiting: max 5 analysis attempts per hour per user
8. Delete deck PDFs from storage after 30 days (privacy compliance)
9. Never log or store the full deck content — only structured JSON results
---
## RESPONSIVE DESIGN RULES
**Mobile (< 768px):**
- Upload zone full width
- Section score cards single column
- Score ring centered, smaller (140px)
- Sticky bottom bar: credit count + primary CTA
- Results page stacks: ring → summary → sections → weaknesses → strengths → rewrites
**Desktop (>= 768px):**
- App page: two columns (upload | explanation)
- Results: ring + summary side by side, then full-width grid below
- History: full table
- Pricing: 4 columns
---
## SEO & META TAGS
```html
<title>DeckScore — AI Pitch Deck Analyzer for Silicon Valley Founders</title>
<meta name="description" content="Upload your pitch deck and get an instant VC-grade scorecard. Claude AI scores 8 critical sections, finds your weaknesses, and tells you exactly what to fix before your next investor meeting. Free first analysis.">
<meta property="og:title" content="DeckScore — Analyze Your Pitch Deck Like a VC">
<meta property="og:description" content="Get brutally honest AI feedback on your pitch deck in 60 seconds. Used by 14,000+ founders. Free first analysis.">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<link rel="canonical" href="https://deckscore.app">
```
---
## BUILD ORDER
Build ALL of the following simultaneously and deliver everything complete in one single build:
1. **Landing page** (/) — complete with all sections, sample score widget, pricing, testimonials, FAQ
2. **Auth pages** — /signup and /login with Supabase email/password auth
3. **Upload page** (/app) — upload zone, sector/stage selectors, processing state with step-by-step progress
4. **Results page** (/app/results/:id) — animated score ring, 8 section cards, weaknesses, advantages, rewrite suggestions
5. **Sample page** (/sample) — static fictional analysis, full results experience
6. **History page** (/history) — table of past analyses with filters
7. **Pricing page** (/pricing) — plans + comparison table + Stripe checkout
8. **Settings page** (/settings) — profile, billing, danger zone
9. **Supabase Edge Function** — analyze-deck with Claude API integration, credit deduction, refund on failure
10. **Stripe webhooks** — subscription created, invoice paid, subscription cancelled
11. **All database tables** — profiles, deck_analyses, credit_purchases with RLS
12. **All UI states** — loading (step-by-step progress), error, empty, success toasts, credit warnings
---
## IMPORTANT NOTES FOR LOVABLE
- Use Supabase for all backend: database, auth, storage, edge functions
- Use Stripe for all payments: subscriptions + customer portal
- Use Native Lovable Anthropic Claude API (claude-sonnet-4-6) inside a Supabase Edge Function for AI analysis
- Do NOT hardcode API keys in frontend — use Supabase environment variables / secrets
- The DeckScore ring (animated SVG circular progress) is the hero component — build it as a reusable component
- Credits must be deducted server-side BEFORE the Claude API call
- Credits must be refunded automatically on confirmed analysis failure
- PDF files must be uploaded to Supabase Storage with private access (signed URLs only)
- Dark theme only — no light/dark toggle
- Typography: load DM Serif Display and DM Sans from Google Fonts, JetBrains Mono for numbers
- Sharp corners throughout — border-radius: 2px maximum on cards and buttons
- No purple. No rounded pill buttons. No gradients on text.
---
## ⚡ FINAL REMINDER — DELIVER EVERYTHING AT ONCE
Do not ask for confirmation. Do not pause and wait for feedback. Do not deliver half the app.
Build the **complete, fully functional DeckScore application right now** — every page, every Supabase Edge Function, every database table, the full auth flow, the credit system, the Stripe subscription integration, and the Claude AI analysis logic — all connected, all working, ready to open in the browser and use immediately.
**The app is considered complete when a brand new user can:**
1. Open the landing page and understand the product in 10 seconds
2. Click "Analyze Your Deck Free" and create an account
3. Upload a PDF pitch deck and have it scored by Claude AI
4. Read a full scorecard with overall score, section breakdown, weaknesses, strengths, and rewrite suggestions
5. View the sample page at /sample to see a pre-built fictional analysis
6. Go to pricing and subscribe to a paid plan via Stripe
7. See credits added to their account after subscribing
8. View all past analyses in /history
9. Manage their billing via Stripe Customer Portal from /settings
Build it now. All of it. At once.ProZap
Micro-SaaS · Automação de WhatsApp
React + TypeScript · Supabase · Stripe · Z-API (WhatsApp)
# PROZAP — GUIA COMPLETO DE BUILD
# Todos os prompts + todas as instruções manuais em ordem
# Leia tudo antes de começar. Siga a sequência exata.
═══════════════════════════════════════════════════════════════
ÍNDICE
═══════════════════════════════════════════════════════════════
PARTE 0 — Configurações manuais ANTES de abrir o Lovable
PARTE 1 — Prompt inicial do Lovable (Fundação + Design + Auth)
PARTE 2 — Prompt Lovable (Landing Page completa)
PARTE 3 — Prompt Lovable (Dashboard + Sidebar + Layout)
PARTE 4 — Prompt Lovable (Módulo WhatsApp — Conectar Z-API)
PARTE 5 — Prompt Lovable (Disparador em Massa)
PARTE 6 — Prompt Lovable (Chatbot com Fluxos)
PARTE 7 — Prompt Lovable (CRM de Contatos)
PARTE 8 — Prompt Lovable (Agendamento de Mensagens)
PARTE 9 — Prompt Lovable (Relatórios e Analytics)
PARTE 10 — Prompt Lovable (Planos + Stripe)
PARTE 11 — Configurações manuais FINAIS (Vercel, Supabase, Stripe)
═══════════════════════════════════════════════════════════════
PARTE 0 — CONFIGURAÇÕES MANUAIS ANTES DE ABRIR O LOVABLE
═══════════════════════════════════════════════════════════════
Faça tudo abaixo ANTES de enviar qualquer prompt ao Lovable.
Cada passo tem o link exato e o que fazer.
───────────────────────────────────────────────────────────────
0.1 — CRIAR PROJETO NO SUPABASE
───────────────────────────────────────────────────────────────
1. Acesse: https://supabase.com/dashboard
2. Clique em "New project"
3. Preencha:
- Name: prozap
- Database Password: crie uma senha forte (ANOTE em local seguro)
- Region: South America (São Paulo)
4. Clique "Create new project"
5. Aguarde ~2 minutos o projeto criar
6. Vá em: Settings → API
7. COPIE e ANOTE estes 3 valores:
- Project URL (ex: https://xxxxxxxxxxx.supabase.co)
- anon public key (JWT longo)
- service_role key (JWT longo — NUNCA exponha no frontend)
───────────────────────────────────────────────────────────────
0.2 — RODAR O SQL DO BANCO DE DADOS NO SUPABASE
───────────────────────────────────────────────────────────────
1. No Supabase, clique em "SQL Editor" no menu lateral esquerdo
2. Clique em "New query"
3. Cole TODO o SQL abaixo e clique em "Run" (botão verde):
-- ============================================================
-- PROZAP — SCHEMA COMPLETO v1.0
-- ============================================================
-- Profiles (extends auth.users)
CREATE TABLE public.profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
email TEXT NOT NULL,
full_name TEXT,
avatar_url TEXT,
plan TEXT NOT NULL DEFAULT 'free' CHECK (plan IN ('free','starter','pro','enterprise')),
plan_status TEXT NOT NULL DEFAULT 'active' CHECK (plan_status IN ('active','canceled','past_due','trialing')),
trial_ends_at TIMESTAMPTZ DEFAULT (now() + interval '7 days'),
stripe_customer_id TEXT,
stripe_subscription_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- WhatsApp instances (Modelo B: cliente conecta própria Z-API)
CREATE TABLE public.whatsapp_instances (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_name TEXT NOT NULL,
zapi_instance_id TEXT NOT NULL,
zapi_token TEXT NOT NULL,
phone_number TEXT,
status TEXT NOT NULL DEFAULT 'disconnected' CHECK (status IN ('connected','disconnected','connecting','banned')),
webhook_url TEXT,
is_default BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Contacts (CRM)
CREATE TABLE public.contacts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_id UUID REFERENCES public.whatsapp_instances(id) ON DELETE SET NULL,
name TEXT NOT NULL,
phone TEXT NOT NULL,
email TEXT,
tags TEXT[] DEFAULT '{}',
notes TEXT,
avatar_url TEXT,
is_blocked BOOLEAN DEFAULT FALSE,
last_interaction_at TIMESTAMPTZ,
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(user_id, phone)
);
-- Contact groups / lists
CREATE TABLE public.contact_groups (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
name TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#2bf604',
contact_count INTEGER DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Group members
CREATE TABLE public.contact_group_members (
group_id UUID REFERENCES public.contact_groups(id) ON DELETE CASCADE,
contact_id UUID REFERENCES public.contacts(id) ON DELETE CASCADE,
added_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (group_id, contact_id)
);
-- Bulk campaigns (disparos em massa)
CREATE TABLE public.campaigns (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_id UUID REFERENCES public.whatsapp_instances(id) ON DELETE SET NULL,
name TEXT NOT NULL,
message TEXT NOT NULL,
media_url TEXT,
media_type TEXT CHECK (media_type IN ('image','video','audio','document')),
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','scheduled','sending','completed','paused','failed')),
target_type TEXT NOT NULL DEFAULT 'group' CHECK (target_type IN ('group','csv','manual')),
target_group_id UUID REFERENCES public.contact_groups(id) ON DELETE SET NULL,
total_contacts INTEGER DEFAULT 0,
sent_count INTEGER DEFAULT 0,
delivered_count INTEGER DEFAULT 0,
failed_count INTEGER DEFAULT 0,
scheduled_at TIMESTAMPTZ,
started_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
delay_between_messages INTEGER DEFAULT 3,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Campaign messages log
CREATE TABLE public.campaign_messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
campaign_id UUID REFERENCES public.campaigns(id) ON DELETE CASCADE NOT NULL,
contact_id UUID REFERENCES public.contacts(id) ON DELETE SET NULL,
phone TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','delivered','failed')),
error_message TEXT,
sent_at TIMESTAMPTZ,
delivered_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Chatbot flows
CREATE TABLE public.chatbot_flows (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_id UUID REFERENCES public.whatsapp_instances(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
trigger_type TEXT NOT NULL DEFAULT 'keyword' CHECK (trigger_type IN ('keyword','first_message','all_messages')),
trigger_keywords TEXT[] DEFAULT '{}',
is_active BOOLEAN DEFAULT TRUE,
nodes JSONB NOT NULL DEFAULT '[]',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Chat conversations
CREATE TABLE public.conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_id UUID REFERENCES public.whatsapp_instances(id) ON DELETE CASCADE NOT NULL,
contact_id UUID REFERENCES public.contacts(id) ON DELETE SET NULL,
phone TEXT NOT NULL,
contact_name TEXT,
last_message TEXT,
last_message_at TIMESTAMPTZ,
unread_count INTEGER DEFAULT 0,
status TEXT DEFAULT 'open' CHECK (status IN ('open','resolved','archived')),
assigned_to UUID REFERENCES public.profiles(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Messages
CREATE TABLE public.messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL,
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
zapi_message_id TEXT,
direction TEXT NOT NULL CHECK (direction IN ('inbound','outbound')),
type TEXT NOT NULL DEFAULT 'text' CHECK (type IN ('text','image','video','audio','document','location','sticker','reaction')),
content TEXT,
media_url TEXT,
media_mime_type TEXT,
status TEXT DEFAULT 'sent' CHECK (status IN ('pending','sent','delivered','read','failed')),
is_bot_message BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Scheduled messages
CREATE TABLE public.scheduled_messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
instance_id UUID REFERENCES public.whatsapp_instances(id) ON DELETE CASCADE NOT NULL,
phone TEXT NOT NULL,
contact_name TEXT,
message TEXT NOT NULL,
media_url TEXT,
media_type TEXT,
scheduled_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed','canceled')),
sent_at TIMESTAMPTZ,
error_message TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Analytics / usage stats
CREATE TABLE public.analytics_daily (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES public.profiles(id) ON DELETE CASCADE NOT NULL,
date DATE NOT NULL DEFAULT CURRENT_DATE,
messages_sent INTEGER DEFAULT 0,
messages_received INTEGER DEFAULT 0,
messages_delivered INTEGER DEFAULT 0,
campaigns_sent INTEGER DEFAULT 0,
new_contacts INTEGER DEFAULT 0,
active_conversations INTEGER DEFAULT 0,
UNIQUE(user_id, date)
);
-- Plan limits reference
CREATE TABLE public.plan_limits (
plan TEXT PRIMARY KEY,
max_instances INTEGER NOT NULL,
max_contacts INTEGER NOT NULL,
max_campaigns_per_month INTEGER NOT NULL,
max_scheduled_messages INTEGER NOT NULL,
max_chatbot_flows INTEGER NOT NULL,
bulk_send_delay_min INTEGER NOT NULL DEFAULT 3,
has_api_access BOOLEAN DEFAULT FALSE,
has_advanced_reports BOOLEAN DEFAULT FALSE,
has_team_members BOOLEAN DEFAULT FALSE
);
INSERT INTO public.plan_limits VALUES
('free', 1, 200, 3, 10, 1, 10, FALSE, FALSE, FALSE),
('starter', 1, 2000, 20, 100, 5, 5, FALSE, FALSE, FALSE),
('pro', 3, 10000, 100, 500, 20, 3, TRUE, TRUE, FALSE),
('enterprise',10, 999999, 999, 9999, 99, 1, TRUE, TRUE, TRUE);
-- ============================================================
-- ROW LEVEL SECURITY
-- ============================================================
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.whatsapp_instances ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contacts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.contact_group_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.campaigns ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.campaign_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.chatbot_flows ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.conversations ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.scheduled_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.analytics_daily ENABLE ROW LEVEL SECURITY;
CREATE POLICY "own" ON public.profiles FOR ALL USING (auth.uid() = id);
CREATE POLICY "own" ON public.whatsapp_instances FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.contacts FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.contact_groups FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.campaigns FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.chatbot_flows FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.conversations FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.messages FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.scheduled_messages FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "own" ON public.analytics_daily FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "public_read" ON public.plan_limits FOR SELECT USING (TRUE);
CREATE POLICY "group_members_own" ON public.contact_group_members FOR ALL
USING (EXISTS (SELECT 1 FROM public.contact_groups cg WHERE cg.id = group_id AND cg.user_id = auth.uid()));
CREATE POLICY "campaign_messages_own" ON public.campaign_messages FOR ALL
USING (EXISTS (SELECT 1 FROM public.campaigns c WHERE c.id = campaign_id AND c.user_id = auth.uid()));
-- ============================================================
-- FUNCTIONS & TRIGGERS
-- ============================================================
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.profiles (id, email, full_name)
VALUES (NEW.id, NEW.email, NEW.raw_user_meta_data->>'full_name');
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
CREATE OR REPLACE FUNCTION public.set_updated_at()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN NEW.updated_at = now(); RETURN NEW; END; $$;
CREATE TRIGGER t_profiles_upd BEFORE UPDATE ON public.profiles FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
CREATE TRIGGER t_instances_upd BEFORE UPDATE ON public.whatsapp_instances FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
CREATE TRIGGER t_contacts_upd BEFORE UPDATE ON public.contacts FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
CREATE TRIGGER t_campaigns_upd BEFORE UPDATE ON public.campaigns FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
CREATE TRIGGER t_flows_upd BEFORE UPDATE ON public.chatbot_flows FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
CREATE TRIGGER t_conversations_upd BEFORE UPDATE ON public.conversations FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
-- Indexes
CREATE INDEX idx_contacts_user ON public.contacts(user_id);
CREATE INDEX idx_contacts_phone ON public.contacts(user_id, phone);
CREATE INDEX idx_campaigns_user_status ON public.campaigns(user_id, status);
CREATE INDEX idx_conversations_user ON public.conversations(user_id, last_message_at DESC);
CREATE INDEX idx_messages_conversation ON public.messages(conversation_id, created_at DESC);
CREATE INDEX idx_scheduled_user_status ON public.scheduled_messages(user_id, status, scheduled_at);
4. Deve aparecer "Success. No rows returned." — banco criado.
───────────────────────────────────────────────────────────────
0.3 — CRIAR CONTA NA Z-API (TRIAL GRÁTIS 3 DIAS)
───────────────────────────────────────────────────────────────
1. Acesse: https://app.z-api.io
2. Clique em "Criar conta" e crie sua conta
3. Após login, clique em "Criar instância"
4. Nomeie: "prozap-dev"
5. Vá na instância criada e ANOTE:
- Instance ID (ex: 3F4BEAA6EA88715C580ADEF3AB1CFCBE)
- Token (ex: 29ABA5CECE3DD020753AB2BB)
6. Conecte seu WhatsApp: escaneie o QR code com seu celular
WhatsApp → 3 pontos → Aparelhos conectados → Conectar aparelho
7. Status deve ficar "Conectado" (verde)
───────────────────────────────────────────────────────────────
0.4 — CRIAR CONTA NO STRIPE
───────────────────────────────────────────────────────────────
1. Acesse: https://dashboard.stripe.com
2. Crie uma conta (pode usar conta de teste primeiro)
3. No dashboard, vá em: Developers → API Keys
4. ANOTE:
- Publishable key (pk_test_... ou pk_live_...)
- Secret key (sk_test_... ou sk_live_...)
5. Vá em: Products → Add product
6. Crie os 3 produtos abaixo (um de cada vez):
PRODUTO 1 — Starter:
- Name: ProZap Starter
- Pricing: R$97,00/mês recorrente
- Metadata: plan=starter
PRODUTO 2 — Pro:
- Name: ProZap Pro
- Pricing: R$197,00/mês recorrente
- Metadata: plan=pro
PRODUTO 3 — Enterprise:
- Name: ProZap Enterprise
- Pricing: R$397,00/mês recorrente
- Metadata: plan=enterprise
7. Para cada produto criado, clique nele e copie o "Price ID" (ex: price_1ABC...)
ANOTE os 3 Price IDs.
8. Configure o Webhook:
- Vá em: Developers → Webhooks → Add endpoint
- URL: https://SEU-PROJETO.supabase.co/functions/v1/stripe-webhook
(substitua pelo URL do seu Supabase que você anotou)
- Events to listen: checkout.session.completed, customer.subscription.updated,
customer.subscription.deleted, invoice.payment_failed
- Clique "Add endpoint"
- ANOTE o "Signing secret" (whsec_...)
───────────────────────────────────────────────────────────────
0.5 — CRIAR REPOSITÓRIO NO GITHUB
───────────────────────────────────────────────────────────────
1. Acesse: https://github.com/new
2. Repository name: prozap
3. Visibility: Private
4. Clique "Create repository"
5. Não precisa fazer mais nada aqui — o Lovable vai conectar automaticamente.
───────────────────────────────────────────────────────────────
0.6 — CRIAR PROJETO NO LOVABLE
───────────────────────────────────────────────────────────────
1. Acesse: https://lovable.dev
2. Clique em "New Project"
3. Name: ProZap
4. ANTES de enviar qualquer prompt:
- Clique em "Connect Supabase" (ícone de banco de dados no topo)
- Cole a Project URL e anon key do passo 0.1
- Conecte também o GitHub repo criado no passo 0.5
5. Instale as skills necessárias (vá em Settings → Skills no Lovable):
- stripe
- supabase
- auth
- api-integration
- typescript-react
- tailwind-ui
- frontend-design
- seo-meta
- performance
AGORA VOCÊ ESTÁ PRONTO. Envie os prompts abaixo em ordem.
═══════════════════════════════════════════════════════════════
PARTE 1 — PROMPT LOVABLE: FUNDAÇÃO + DESIGN SYSTEM + AUTH
(Copie e cole TUDO no campo de chat do Lovable e envie)
═══════════════════════════════════════════════════════════════
Você está construindo o **ProZap** — uma plataforma SaaS brasileira de automação e gestão de WhatsApp para donos de comércio, empresas, afiliados, produtores, vendedores e negócios B2B. É o CRM + Disparador + Chatbot + Agendador mais completo e mais barato do Brasil.
Este é um projeto complexo que será construído em partes. Esta é a PARTE 1: Fundação, Design System e Autenticação. Leia tudo com atenção antes de começar.
## STACK TÉCNICO OBRIGATÓRIO
- React + TypeScript (strict mode)
- Tailwind CSS + shadcn/ui
- Supabase (já conectado — use a integração nativa do Lovable)
- React Router v6 (rotas do lado do cliente)
- TanStack Query para server state
- React Hook Form + Zod para formulários
- Lucide React para ícones
- date-fns para datas (PT-BR locale)
- Axios para chamadas à Z-API
## DESIGN SYSTEM — SIGA EXATAMENTE
Este design é exclusivo e diferente de tudo no mercado. Dark puro com verde fluorescente.
### Cores (globals.css / tailwind.config.ts):
```
--bg-primary: #000000 /* fundo principal */
--bg-secondary: #0a0a0a /* cards, painéis */
--bg-tertiary: #111111 /* inputs, hover */
--bg-elevated: #161616 /* modais, dropdowns */
--accent-green: #2bf604 /* verde fluorescente — COR PRINCIPAL */
--accent-green-dark: #1fb800 /* hover do verde */
--accent-green-glow: #2bf60420 /* glow/shadow verde */
--text-primary: #ffffff
--text-secondary: #a0a0a0
--text-muted: #555555
--border: #1a1a1a
--border-accent: #2bf60430
--danger: #ff3333
--warning: #ffaa00
--success: #2bf604
```
### Fontes:
- UI geral: Inter (Google Fonts)
- Números/dados/códigos: JetBrains Mono
### Regras visuais obrigatórias:
1. Fundo sempre #000000 — NUNCA branco ou cinza claro
2. Textos principais sempre brancos (#ffffff)
3. Destaques, botões primários, ícones ativos: verde #2bf604
4. Bordas sutis: #1a1a1a
5. Cards têm background #0a0a0a com borda #1a1a1a
6. Hover em cards: border muda para #2bf60430, sutil box-shadow verde
7. Botões primários: background #2bf604, texto #000000, font-weight bold
8. Botões secundários: border #2bf604, texto #2bf604, background transparente
9. Inputs: background #111111, border #1a1a1a, focus border #2bf604
10. Glow effect no logo e elementos principais: text-shadow ou box-shadow com #2bf604
### RESPONSIVIDADE — CRÍTICO:
Construa desktop E mobile ao mesmo tempo, separadamente:
- Desktop (≥1024px): sidebar fixa à esquerda 240px + conteúdo principal
- Tablet (768-1023px): sidebar colapsável com overlay
- Mobile (≤767px): bottom navigation bar (não sidebar), layout de 1 coluna
O layout mobile NÃO é o desktop encolhido. São layouts diferentes construídos juntos.
## ESTRUTURA DE ARQUIVOS
```
src/
├── components/
│ ├── ui/ (shadcn — não editar)
│ ├── layout/
│ │ ├── AppLayout.tsx (layout autenticado)
│ │ ├── Sidebar.tsx (desktop)
│ │ ├── BottomNav.tsx (mobile)
│ │ ├── TopBar.tsx (header)
│ │ └── AuthLayout.tsx (layout de auth)
│ └── shared/
│ ├── Logo.tsx
│ ├── PlanBadge.tsx
│ └── EmptyState.tsx
├── pages/
│ ├── auth/
│ │ ├── Login.tsx
│ │ ├── Register.tsx
│ │ └── ForgotPassword.tsx
│ ├── dashboard/
│ │ └── Dashboard.tsx
│ ├── whatsapp/
│ ├── campaigns/
│ ├── chatbot/
│ ├── contacts/
│ ├── schedule/
│ ├── reports/
│ ├── settings/
│ └── landing/
│ └── Landing.tsx
├── hooks/
│ ├── useAuth.ts
│ ├── useProfile.ts
│ └── usePlan.ts
├── lib/
│ ├── supabase.ts
│ ├── zapi.ts (cliente Z-API)
│ └── utils.ts
├── types/
│ └── database.ts
└── styles/
└── globals.css
```
## PARTE 1 — O QUE CONSTRUIR AGORA
### 1. Configurar globals.css com todas as variáveis CSS acima
### 2. Configurar tailwind.config.ts com as cores customizadas:
```ts
colors: {
'prozap-green': '#2bf604',
'prozap-dark': '#000000',
'prozap-card': '#0a0a0a',
'prozap-input': '#111111',
'prozap-border': '#1a1a1a',
}
```
### 3. Componente Logo.tsx
- Texto "Pro" em branco + "Zap" em verde (#2bf604)
- Ícone de raio ⚡ à esquerda em verde
- Versão grande (landing) e pequena (sidebar)
- Efeito glow sutil no texto
### 4. Páginas de Autenticação COMPLETAS:
**Login (/login):**
- Layout centralizado, fundo #000000
- Logo no topo com glow
- Card com fundo #0a0a0a, border #1a1a1a
- Título: "Entrar no ProZap"
- Campos: Email + Senha (com show/hide)
- Botão "Entrar" (verde #2bf604, texto preto)
- Link "Esqueceu a senha?"
- Divider "ou"
- Botão Google OAuth (border verde, texto branco)
- Link "Não tem conta? Criar conta grátis →"
- Rodapé: "7 dias grátis. Sem cartão de crédito."
**Cadastro (/cadastro):**
- Mesmo layout
- Campos: Nome completo, Email, Senha, Confirmar senha
- Checkbox: "Concordo com os Termos de Uso e Política de Privacidade"
- Botão "Criar conta grátis — 7 dias grátis"
- Link "Já tem conta? Entrar →"
**Recuperar senha (/recuperar-senha):**
- Email + botão enviar link
### 5. Layout autenticado (AppLayout):
**Sidebar (desktop — 240px):**
Logo no topo
Itens de navegação com ícone + texto:
- 🏠 Dashboard (/app)
- 📱 WhatsApp (/app/whatsapp) — badge "Conectado" ou "Desconectado"
- 📢 Disparador (/app/campanhas)
- 🤖 Chatbot (/app/chatbot)
- 👥 Contatos (/app/contatos)
- 📅 Agendamentos (/app/agendamentos)
- 📊 Relatórios (/app/relatorios)
- ⚙️ Configurações (/app/configuracoes)
Rodapé da sidebar:
- Avatar + nome do usuário + plano badge
- Botão "Sair"
Hover nos itens: texto e ícone ficam verdes, borda esquerda verde 3px
**Bottom Navigation (mobile — fixo no rodapé):**
5 itens principais com ícone + label pequeno:
- 🏠 Início
- 📢 Disparar
- 🤖 Bot
- 👥 Contatos
- ⚙️ Config
**TopBar (header):**
- Mobile: hamburguer + logo + sino (notificações) + avatar
- Desktop: título da página atual + sino + avatar com dropdown
### 6. Dashboard (/app) — versão inicial:
Cards de métricas (2x2 no desktop, 1 coluna no mobile):
- 📱 Número Conectado (status da instância)
- 📤 Mensagens Enviadas Hoje
- 👥 Total de Contatos
- 📢 Campanhas Ativas
Cada card: fundo #0a0a0a, borda #1a1a1a, número em verde grande, label em cinza
Seção "Ações Rápidas":
- Botão: Nova Campanha →
- Botão: Adicionar Contatos →
- Botão: Criar Chatbot →
- Botão: Agendar Mensagem →
Seção "Atividade Recente":
- Lista das últimas 5 campanhas
- Lista das últimas 5 mensagens agendadas
- Estado vazio se não houver dados: ícone + "Nenhuma atividade ainda"
### 7. Roteamento completo:
```
/ → Landing (pública)
/login → Login
/cadastro → Cadastro
/recuperar-senha → Recuperar senha
/app → Dashboard (protegida)
/app/whatsapp → Instâncias WhatsApp (protegida)
/app/campanhas → Campanhas (protegida)
/app/chatbot → Chatbot (protegida)
/app/contatos → Contatos (protegida)
/app/agendamentos → Agendamentos (protegida)
/app/relatorios → Relatórios (protegida)
/app/configuracoes → Configurações (protegida)
/app/planos → Planos e Preços (protegida)
```
Rota protegida: se não autenticado, redireciona para /login
Se autenticado e tenta acessar /login ou /cadastro, redireciona para /app
### 8. Hook useAuth.ts:
- Lê sessão do Supabase
- Expõe: user, profile, loading, signOut
- Persiste sessão (Supabase já gerencia com localStorage)
### 9. Hook usePlan.ts:
- Lê profile.plan
- Expõe: plan, limits, isFeatureAllowed(feature)
- Baseado na tabela plan_limits
## ENTREGUE AO FINAL DA PARTE 1:
✅ Design system configurado (cores, fontes, variáveis)
✅ Páginas de auth completas e funcionais
✅ Layout desktop E mobile simultâneos
✅ Dashboard com cards de métricas (dados reais do Supabase)
✅ Roteamento completo configurado
✅ Hooks de auth e plano
Após concluir, me diga: "Parte 1 concluída. O que foi feito: [lista]. Próximo passo: Parte 2 — Landing Page."
═══════════════════════════════════════════════════════════════
PARTE 2 — PROMPT LOVABLE: LANDING PAGE COMPLETA
(Envie após o Lovable confirmar que a Parte 1 foi concluída)
═══════════════════════════════════════════════════════════════
Parte 2 do ProZap. Mantenha TUDO do que foi construído na Parte 1.
Construa agora a Landing Page completa em /.
## LANDING PAGE — ESPECIFICAÇÕES COMPLETAS
Mesmas cores do design system (fundo #000000, verde #2bf604, textos brancos).
Totalmente responsiva: desktop E mobile construídos separadamente.
### HEADER (fixo, sticky):
- Fundo: #000000 com border-bottom #1a1a1a e backdrop-blur
- Logo "ProZap" à esquerda (ícone raio verde + texto)
- Nav desktop: Funcionalidades | Integrações | Planos | Blog | Sobre nós
- Direita: "Entrar" (ghost, texto branco) + "Testar grátis →" (verde, texto preto)
- Mobile: logo + hamburguer menu (drawer lateral com os mesmos itens)
### SEÇÃO 1 — HERO:
- Tag pill: "⚡ #1 Automação de WhatsApp do Brasil"
- H1 (grande, bold): "Transforme seu WhatsApp em uma"
- H1 continua com animação de texto que alterna entre:
"Máquina de Vendas" / "Central de Atendimento" / "Robô 24/7" / "CRM Poderoso"
(troca a cada 2 segundos com fade)
- Subtítulo: "Dispare mensagens em massa, crie chatbots inteligentes, gerencie contatos e agende mensagens — tudo em um único lugar. A partir de R$97/mês."
- Dois botões:
- "Começar grátis — 7 dias" (verde #2bf604, grande, texto preto, ícone seta)
- "Ver demonstração" (border verde, texto verde)
- Abaixo dos botões: "✓ Sem cartão de crédito ✓ Cancele quando quiser ✓ Suporte em PT-BR"
- Visual Hero: mockup/preview do dashboard do ProZap (card com fundo #0a0a0a, borda verde, mostrando métricas e uma conversa de WhatsApp)
- Background: partículas verdes sutis animadas (CSS puro, sem library pesada) ou grid pattern sutil
### SEÇÃO 2 — NÚMEROS/PROVA SOCIAL:
Row de 4 stats com counter animado ao entrar na viewport:
- 🚀 10.000+ usuários ativos
- 📤 50M+ mensagens enviadas
- ⚡ 99.9% uptime garantido
- ⭐ 4.9/5 satisfação
### SEÇÃO 3 — FUNCIONALIDADES (features):
Título: "Tudo que você precisa para dominar o WhatsApp"
Grid de 6 cards (3x2 desktop, 1 coluna mobile):
Card 1 — 📢 Disparador em Massa:
"Envie mensagens para centenas de contatos com personalização automática. Texto, imagem, vídeo e áudio."
Card 2 — 🤖 Chatbot Inteligente:
"Crie fluxos de atendimento automático que respondem seus clientes 24 horas por dia, 7 dias por semana."
Card 3 — 👥 CRM de Contatos:
"Organize seus contatos em listas segmentadas, adicione tags e acompanhe o histórico de cada cliente."
Card 4 — 📅 Agendador de Mensagens:
"Programe mensagens para o dia e hora exatos. Nunca mais esqueça de enviar uma mensagem importante."
Card 5 — 📊 Relatórios Detalhados:
"Acompanhe taxa de entrega, leitura e resposta de cada campanha em tempo real."
Card 6 — 🔗 Multi-instância:
"Gerencie múltiplos números de WhatsApp em um único painel. Perfeito para equipes e agências."
Cada card: fundo #0a0a0a, borda #1a1a1a, ícone em verde no topo, título branco, descrição cinza. Hover: border verde sutil.
### SEÇÃO 4 — COMO FUNCIONA (3 passos):
Título: "Configure em menos de 5 minutos"
3 passos em linha (desktop) ou coluna (mobile):
1. 🔌 Conecte seu WhatsApp — Escaneie o QR code e seu número está pronto
2. 📋 Importe seus contatos — CSV, planilha ou adicione manualmente
3. 🚀 Dispare sua campanha — Personalize e envie para toda sua lista
### SEÇÃO 5 — QUEM USA O PROZAP:
Título: "Para qualquer negócio que usa WhatsApp"
Grid de nichos (ícone + nome):
🏪 Lojas e varejo | 🍕 Restaurantes e delivery | 🏥 Clínicas e consultórios |
💈 Salões e estética | 🎓 Infoprodutores | 🏠 Imobiliárias |
🚗 Oficinas e auto peças | 💼 Agências | 🛒 E-commerce | 🤝 Afiliados
### SEÇÃO 6 — PLANOS E PREÇOS:
Título: "Preço justo. Sem surpresas."
Subtítulo: "7 dias grátis em qualquer plano. Cancele quando quiser."
Toggle: Mensal / Anual (anual com desconto de 20%)
4 cards de plano:
**GRÁTIS** — R$0/mês:
- 1 número de WhatsApp
- 200 contatos
- 3 campanhas/mês
- 1 chatbot básico
- CTA: "Começar grátis"
**STARTER** — R$97/mês:
- 1 número de WhatsApp
- 2.000 contatos
- 20 campanhas/mês
- 5 chatbots
- Agendamento de mensagens
- Relatórios básicos
- CTA: "Testar 7 dias grátis →"
**PRO** — R$197/mês [MAIS POPULAR — badge verde]:
- 3 números de WhatsApp
- 10.000 contatos
- 100 campanhas/mês
- 20 chatbots
- Relatórios avançados
- API de integração
- Suporte prioritário
- CTA: "Testar 7 dias grátis →"
**ENTERPRISE** — R$397/mês:
- 10 números de WhatsApp
- Contatos ilimitados
- Campanhas ilimitadas
- Chatbots ilimitados
- Gestão de equipe
- Gerente de conta dedicado
- CTA: "Falar com especialista →" (abre WhatsApp)
Nota abaixo: "* Todos os planos incluem: Sem cobrança por mensagem · Suporte em português · Dados seguros no Brasil"
### SEÇÃO 7 — DEPOIMENTOS:
Título: "Quem usa, aprova"
3 cards de depoimento:
1. "Aumentei minhas vendas em 40% no primeiro mês usando o ProZap para disparar promoções para minha lista de clientes." — João Silva, dono de açougue, SP
2. "O chatbot atende meus clientes às 2h da manhã enquanto eu durmo. Sensacional!" — Maria Santos, infoprodutora, RJ
3. "Gerencio 5 números de WhatsApp de clientes diferentes em um único painel. Economizei horas por semana." — Pedro Costa, agência digital, MG
### SEÇÃO 8 — FAQ:
Título: "Perguntas frequentes"
Accordion com 6 perguntas:
1. O ProZap usa a API oficial do WhatsApp?
"O ProZap usa conexão via Z-API, que permite usar seu número pessoal ou comercial sem precisar da API oficial Meta (que tem custo por mensagem). Nossa solução é mais acessível e não cobra por mensagem."
2. Meu número pode ser banido?
"Seguindo as boas práticas que ensinamos (delay entre mensagens, não enviar spam, usar lista de opt-in), o risco é mínimo. Nosso sistema já tem delay configurado para proteger seu número."
3. Posso importar meus contatos?
"Sim! Você pode importar via CSV, planilha Excel ou adicionar manualmente. Também é possível capturar contatos via chatbot."
4. Existe limite de mensagens?
"Não cobramos por mensagem. Você paga apenas a mensalidade do plano e pode enviar mensagens ilimitadas respeitando os limites de contatos e campanhas do seu plano."
5. Funciona no celular?
"Sim! O ProZap tem versão web totalmente responsiva que funciona perfeitamente no celular e tablet, além do desktop."
6. Posso cancelar quando quiser?
"Sim, sem burocracia. Cancele em qualquer momento pelo painel de configurações e não será cobrado no próximo ciclo."
### SEÇÃO 9 — CTA FINAL:
Fundo: gradiente de #000000 para #0a1a00 (levemente verde escuro)
Título grande: "Pronto para transformar seu WhatsApp em uma máquina de vendas?"
Subtítulo: "Junte-se a milhares de negócios que já usam o ProZap."
Botão: "Começar agora — 7 dias grátis" (verde grande)
Abaixo: "Sem cartão de crédito · Configuração em 5 minutos · Suporte em PT-BR"
### FOOTER:
Fundo #000000, borda top #1a1a1a
- Logo + slogan: "Automação de WhatsApp para quem quer vender mais"
- Colunas: Produto (features) | Empresa (sobre, blog, contato) | Legal (termos, privacidade, LGPD)
- Social: Instagram, YouTube, LinkedIn (ícones brancos, hover verde)
- Bottom: "© 2026 ProZap · CNPJ XX.XXX.XXX/0001-XX · Todos os direitos reservados"
## META TAGS E SEO (index.html ou componente Head):
```html
<title>ProZap — Automação de WhatsApp para Vendas e Atendimento</title>
<meta name="description" content="Dispare mensagens em massa, crie chatbots, gerencie contatos e agende mensagens no WhatsApp. A plataforma mais completa do Brasil a partir de R$97/mês.">
<meta name="keywords" content="automação whatsapp, disparador whatsapp, chatbot whatsapp, crm whatsapp, marketing whatsapp">
<meta property="og:title" content="ProZap — Transforme seu WhatsApp em Máquina de Vendas">
<meta property="og:description" content="Disparo em massa, chatbot, CRM e agendamento no WhatsApp. 7 dias grátis.">
<link rel="canonical" href="https://prozap.com.br">
```
## ENTREGUE AO FINAL DA PARTE 2:
✅ Landing page completa e responsiva (desktop + mobile)
✅ Header sticky com menu mobile
✅ Todas as 9 seções implementadas
✅ Animação do texto alternado no hero
✅ Counters animados na seção de números
✅ Toggle mensal/anual nos planos
✅ FAQ em accordion
✅ SEO meta tags
Após concluir: "Parte 2 concluída. Landing page completa. Próximo passo: Parte 3 — Dashboard e estrutura de navegação."
═══════════════════════════════════════════════════════════════
PARTE 3 — PROMPT LOVABLE: MÓDULO WHATSAPP (Z-API)
(Envie após confirmação da Parte 2)
═══════════════════════════════════════════════════════════════
Parte 3 do ProZap. Mantenha tudo das partes anteriores.
Construa o módulo de conexão com WhatsApp via Z-API.
## lib/zapi.ts — CLIENTE Z-API COMPLETO:
```typescript
// Cliente para a Z-API — Modelo B (cliente usa própria chave)
// Documentação: https://developer.z-api.io
const ZAPI_BASE = 'https://api.z-api.io/instances'
interface ZApiConfig {
instanceId: string
token: string
}
export const zapiClient = {
// Verificar status da conexão
getStatus: async (config: ZApiConfig) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/status`,
{ method: 'GET', headers: { 'Content-Type': 'application/json', 'client-token': config.token } }
)
return res.json()
},
// Obter QR Code para conectar
getQRCode: async (config: ZApiConfig) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/qr-code/image`,
{ method: 'GET', headers: { 'client-token': config.token } }
)
return res.json()
},
// Enviar mensagem de texto
sendText: async (config: ZApiConfig, phone: string, message: string) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/send-text`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'client-token': config.token },
body: JSON.stringify({ phone: phone.replace(/\D/g, ''), message })
}
)
return res.json()
},
// Enviar imagem
sendImage: async (config: ZApiConfig, phone: string, image: string, caption?: string) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/send-image`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'client-token': config.token },
body: JSON.stringify({ phone: phone.replace(/\D/g, ''), image, caption })
}
)
return res.json()
},
// Enviar áudio
sendAudio: async (config: ZApiConfig, phone: string, audio: string) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/send-audio`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'client-token': config.token },
body: JSON.stringify({ phone: phone.replace(/\D/g, ''), audio })
}
)
return res.json()
},
// Verificar se número existe no WhatsApp
checkPhone: async (config: ZApiConfig, phone: string) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/phone-exists/${phone.replace(/\D/g, '')}`,
{ method: 'GET', headers: { 'client-token': config.token } }
)
return res.json()
},
// Configurar webhook
setWebhook: async (config: ZApiConfig, webhookUrl: string) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/update-webhook-received`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'client-token': config.token },
body: JSON.stringify({ value: webhookUrl })
}
)
return res.json()
},
// Desconectar instância
disconnect: async (config: ZApiConfig) => {
const res = await fetch(
`${ZAPI_BASE}/${config.instanceId}/token/${config.token}/disconnect`,
{ method: 'DELETE', headers: { 'client-token': config.token } }
)
return res.json()
}
}
```
## PÁGINA: /app/whatsapp — INSTÂNCIAS WHATSAPP
### Layout:
Header da página: "Instâncias WhatsApp" + botão "+ Adicionar instância" (verde)
### Se não tem nenhuma instância:
Empty state centralizado:
- Ícone grande de WhatsApp (verde)
- Título: "Conecte seu WhatsApp"
- Subtítulo: "Configure sua instância Z-API para começar a usar o ProZap"
- Botão: "Conectar agora →"
### Modal: "Adicionar Instância Z-API":
Título: "Conectar WhatsApp via Z-API"
Instruções no topo (card azul/verde com fundo escuro):
"Como obter suas credenciais:
1. Acesse app.z-api.io e crie uma conta
2. Clique em 'Criar instância'
3. Copie o Instance ID e o Token
4. Cole os dados abaixo"
Campos do form:
- Nome da instância (ex: "Número Principal")
- Instance ID da Z-API (campo texto)
- Token da Z-API (campo senha com show/hide)
- Checkbox: "Definir como instância padrão"
Botão: "Salvar e conectar" → salva no Supabase e tenta verificar status
### Card de instância (para cada instância conectada):
- Nome da instância em branco
- Número conectado (se disponível)
- Badge de status:
- 🟢 "Conectado" (verde)
- 🔴 "Desconectado" (vermelho)
- 🟡 "Conectando..." (amarelo)
- Data de criação
- Menu 3 pontos: Editar | Reconectar | Definir como padrão | Remover
### Quando status é "Desconectado" — botão "Reconectar":
Abre modal com QR code em tempo real:
- Chama zapiClient.getQRCode() a cada 15 segundos (polling)
- Exibe: "Abra o WhatsApp → 3 pontos → Aparelhos conectados → Conectar aparelho"
- QR code deve ocupar área central do modal
- Loading spinner enquanto carrega
- Quando conectar: fecha modal automaticamente e atualiza status para "Conectado"
### Verificação de limites por plano:
- Free: máximo 1 instância — se tentar adicionar mais, mostra upgrade modal
- Starter: máximo 1 instância
- Pro: máximo 3 instâncias
- Enterprise: máximo 10 instâncias
### Hook: useWhatsappInstances.ts
- Lista todas as instâncias do usuário
- CRUD de instâncias no Supabase
- Polling de status a cada 30 segundos para instâncias ativas
- Expõe: instances, defaultInstance, addInstance, removeInstance, refreshStatus
## ENTREGUE AO FINAL DA PARTE 3:
✅ lib/zapi.ts com todos os métodos da Z-API
✅ Página de instâncias completa e responsiva
✅ Modal de adicionar instância com validação
✅ QR code em tempo real para conexão
✅ Polling de status automático
✅ Controle de limites por plano
✅ Hook useWhatsappInstances
Após concluir: "Parte 3 concluída. Próximo passo: Parte 4 — Disparador em Massa."
═══════════════════════════════════════════════════════════════
PARTE 4 — PROMPT LOVABLE: DISPARADOR EM MASSA
(Envie após confirmação da Parte 3)
═══════════════════════════════════════════════════════════════
Parte 4 do ProZap. Mantenha tudo das partes anteriores.
Construa o módulo de campanhas (disparador em massa).
## PÁGINA: /app/campanhas
### Layout principal:
- Header: "Campanhas" + botão "+ Nova campanha" (verde)
- Tabs: Todas | Ativas | Agendadas | Concluídas | Rascunhos
### Lista de campanhas:
Tabela ou cards com:
- Nome da campanha
- Status (badge colorido)
- Total de contatos
- Enviadas / Total (barra de progresso verde)
- Data criação / Data envio
- Ações: Ver detalhes | Pausar | Duplicar | Excluir
### Criar campanha — wizard em 4 etapas:
**ETAPA 1 — Configurações básicas:**
- Nome da campanha (texto)
- Selecionar instância WhatsApp (dropdown com instâncias conectadas)
- Selecionar tipo de envio:
- 📋 Lista de contatos (seleciona grupo existente)
- 📄 Importar CSV
- ✍️ Adicionar manualmente
**ETAPA 2 — Mensagem:**
Editor de mensagem com:
- Área de texto rica com variáveis:
- {{nome}} — personaliza com nome do contato
- {{telefone}} — número do contato
- Botões de formatação: *negrito* _itálico_ ~tachado~
- Preview em tempo real (mostra como vai aparecer no WhatsApp)
- Toggle: "Incluir mídia?"
- Se sim: upload de imagem, vídeo, áudio ou documento
- Preview da mídia
- Contador de caracteres
**ETAPA 3 — Configurações de envio:**
- Delay entre mensagens (slider): 3s a 30s
- Tooltip: "Aumente o delay para proteger seu número contra banimento"
- Free/Starter: mínimo 5s | Pro: mínimo 3s
- Opção: "Enviar agora" ou "Agendar para..."
- Se agendar: date picker + time picker
- Opção: "Verificar se número tem WhatsApp antes de enviar"
- Tooltip: "Recomendado para listas novas. Aumenta o tempo de envio."
**ETAPA 4 — Revisar e enviar:**
- Resumo: nome, instância, total de contatos, mensagem preview, horário
- Aviso de conformidade (card amarelo):
"⚠️ Envie apenas para contatos que autorizaram receber suas mensagens. Spam pode resultar em banimento do número."
- Checkbox: "Confirmo que tenho autorização para enviar para estes contatos"
- Botões: "Voltar" | "Iniciar campanha →"
### Progresso em tempo real durante envio:
- Barra de progresso verde animada
- Contador: "X de Y enviadas"
- Velocidade estimada: "X mensagens/min"
- Tempo estimado para conclusão
- Log em tempo real (últimas 5 mensagens enviadas)
- Botão "Pausar" (muda para "Retomar" quando pausado)
### Detalhes de campanha:
- Gráfico de pizza: Enviadas / Entregues / Falhou
- Lista de contatos com status individual
- Exportar relatório (CSV)
### Hook: useCampaigns.ts
- CRUD de campanhas
- Lógica de disparo: para cada contato, chama zapiClient.sendText() (ou sendImage) com delay
- Usa setInterval com o delay configurado
- Atualiza campaign_messages em tempo real
- Para/retoma campanha
- Expõe: campaigns, createCampaign, startCampaign, pauseCampaign, deleteCampaign
## ENTREGUE AO FINAL DA PARTE 4:
✅ Página de campanhas com lista e filtros
✅ Wizard de criação em 4 etapas
✅ Editor de mensagem com variáveis e preview
✅ Upload de mídia
✅ Progresso em tempo real
✅ Detalhes e relatório por campanha
✅ Hook completo com lógica de disparo
Após concluir: "Parte 4 concluída. Próximo: Parte 5 — CRM de Contatos."
═══════════════════════════════════════════════════════════════
PARTE 5 — PROMPT LOVABLE: CRM DE CONTATOS
(Envie após confirmação da Parte 4)
═══════════════════════════════════════════════════════════════
Parte 5 do ProZap. Mantenha tudo das partes anteriores.
Construa o módulo de CRM de contatos.
## PÁGINA: /app/contatos
### Layout:
- Header: "Contatos" + botões "+ Adicionar contato" + "Importar CSV"
- Stats row: Total | Adicionados hoje | Listas | Bloqueados
- Barra de busca + filtros: Por tag, Por lista, Por data
### Lista de contatos (tabela):
Colunas: Avatar | Nome | Telefone | Tags | Última interação | Ações
- Checkbox para seleção múltipla
- Ações em massa: Adicionar à lista | Remover | Bloquear | Exportar
- Paginação: 50 por página
### Modal: Adicionar/Editar contato:
- Nome (texto)
- Telefone (com máscara BR: (00) 00000-0000)
- Botão "Verificar no WhatsApp" → chama zapiClient.checkPhone()
- Mostra: ✅ "Tem WhatsApp" ou ❌ "Não tem WhatsApp"
- Email (opcional)
- Tags (input com chips — ex: "cliente", "vip", "promoção")
- Notas (textarea)
- Adicionar à lista (dropdown multiseleção)
### Importar CSV:
- Dropzone de upload
- Mapeamento de colunas: "Qual coluna é o nome?" "Qual coluna é o telefone?"
- Preview: primeiras 5 linhas
- Opção: "Ignorar duplicatas" ou "Atualizar existentes"
- Barra de progresso do import
- Resultado: "X contatos importados, Y duplicatas ignoradas, Z erros"
### LISTAS DE CONTATOS:
Tab separada ou seção na sidebar:
- Lista de grupos criados
- Cada grupo: nome, cor, quantidade de contatos
- Criar novo grupo: nome + cor (color picker com cores predefinidas)
- Ver contatos do grupo, remover contatos, editar grupo
### Detalhes do contato (clicando no contato):
Drawer/modal lateral com:
- Avatar (inicial do nome se sem foto)
- Nome e telefone
- Tags (editáveis inline)
- Notas
- Histórico de campanhas que recebeu
- Histórico de conversas
- Data de adição
- Botão: "Enviar mensagem agora" → abre modal de envio rápido
### Hook: useContacts.ts
- CRUD completo de contatos
- Import de CSV com processamento
- Gestão de listas/grupos
- Busca e filtros
- Verificação de número no WhatsApp
## ENTREGUE AO FINAL DA PARTE 5:
✅ Tabela de contatos com busca e filtros
✅ Modal de adicionar/editar contato
✅ Importação de CSV com mapeamento de colunas
✅ Gestão de listas/grupos
✅ Verificação de número no WhatsApp
✅ Detalhes do contato com histórico
✅ Seleção múltipla com ações em massa
Após concluir: "Parte 5 concluída. Próximo: Parte 6 — Chatbot."
═══════════════════════════════════════════════════════════════
PARTE 6 — PROMPT LOVABLE: CHATBOT COM FLUXOS
(Envie após confirmação da Parte 5)
═══════════════════════════════════════════════════════════════
Parte 6 do ProZap. Mantenha tudo das partes anteriores.
Construa o módulo de chatbot com editor de fluxos.
## PÁGINA: /app/chatbot
### Lista de chatbots:
- Header: "Chatbots" + botão "+ Criar chatbot"
- Cards de chatbots existentes:
- Nome do chatbot
- Instância vinculada
- Tipo de gatilho (keyword / primeira mensagem / todas)
- Toggle ativo/inativo (verde quando ativo)
- Nº de nós no fluxo
- Ações: Editar | Duplicar | Excluir
### Editor de Fluxo (visual):
Interface de editor tipo "flow builder" visual:
**Área principal:**
- Canvas escuro (#0a0a0a) com grid pontilhado sutil
- Nós arrastáveis e conectáveis por linhas verdes
- Zoom in/out
- Botão "Centralizar"
**Tipos de nós:**
1. 🚀 **Início** (nó raiz, sempre presente):
- Tipo de gatilho: Palavra-chave | Primeira mensagem | Toda mensagem
- Se palavra-chave: campo para digitar as keywords (ex: "oi, olá, menu")
2. 💬 **Enviar mensagem:**
- Textarea com a mensagem
- Suporte a variáveis: {{nome}}, {{telefone}}
- Opção de adicionar mídia (imagem, áudio, documento)
- Delay antes de enviar (0-10 segundos)
3. ❓ **Fazer pergunta (Menu):**
- Mensagem/pergunta a ser enviada
- Opções de resposta (máx 10):
- Cada opção: número/letra + texto (ex: "1 - Ver produtos")
- Cada opção conecta a um próximo nó
- Modo: "Aguardar resposta do usuário"
4. 🔀 **Condição:**
- Se resposta contém: [texto] → vai para [nó A]
- Senão → vai para [nó B]
5. ⏱️ **Aguardar:**
- Aguardar X segundos/minutos antes do próximo nó
6. 🏷️ **Adicionar tag:**
- Adiciona tag ao contato que passou pelo fluxo
7. 📋 **Transferir para humano:**
- Pausa o chatbot para essa conversa
- Notifica o usuário (dono do ProZap)
- Mensagem de transferência configurável
8. 🔚 **Fim:**
- Termina o fluxo
**Sidebar do editor:**
- Ao clicar em um nó: abre painel de edição daquele nó à direita
- Botão "+ Adicionar nó" — abre dropdown com tipos de nós
**Toolbar superior do editor:**
- Nome do chatbot (editável inline)
- Seletor de instância WhatsApp
- Toggle Ativo/Inativo
- Botões: Salvar | Testar | Sair
### Testar chatbot:
- Modal com simulador de chat (visual de WhatsApp)
- Campo para digitar como se fosse o cliente
- Mostra o fluxo sendo percorrido em tempo real
### Processamento de Webhooks (receber mensagens):
A lógica de processamento do chatbot acontece via Supabase Edge Function que recebe o webhook da Z-API:
- Recebe mensagem incoming
- Verifica se existe chatbot ativo para essa instância
- Verifica se a mensagem triggera algum chatbot (por keyword ou tipo)
- Executa o nó atual da conversa
- Envia a resposta via zapiClient
- Avança para o próximo nó
- Salva estado da conversa no banco
### Hook: useChatbots.ts
- CRUD de chatbots
- Salvar/carregar estrutura de nós (JSONB no Supabase)
- Ativar/desativar chatbot
## ENTREGUE AO FINAL DA PARTE 6:
✅ Lista de chatbots com cards
✅ Editor visual de fluxo com todos os tipos de nós
✅ Painel de edição de cada nó
✅ Simulador de teste do chatbot
✅ Lógica de processamento de webhooks
✅ Integração com instâncias WhatsApp
Após concluir: "Parte 6 concluída. Próximo: Parte 7 — Agendamentos."
═══════════════════════════════════════════════════════════════
PARTE 7 — PROMPT LOVABLE: AGENDAMENTOS + RELATÓRIOS + PLANOS
(Envie após confirmação da Parte 6)
═══════════════════════════════════════════════════════════════
Parte 7 do ProZap. Mantenha tudo das partes anteriores.
Construa: Agendamentos, Relatórios, Planos e Configurações.
## PÁGINA: /app/agendamentos
### Layout:
- Header: "Agendamentos" + botão "+ Agendar mensagem"
- View: Lista | Calendário (toggle)
- Filtros: Todas | Pendentes | Enviadas | Falhou
### Vista Calendário:
Calendário mensal mostrando dots verdes nos dias com mensagens agendadas.
Clicar no dia: mostra lista de mensagens daquele dia.
### Lista de agendamentos (tabela):
- Nome/contato | Número | Preview da mensagem | Data/hora | Status | Ações
### Modal: Agendar mensagem:
- Selecionar instância
- Destinatário (busca de contato ou digita número)
- Mensagem (com variáveis e opção de mídia)
- Data e hora (date/time picker com PT-BR)
- Repetir? (Não | Diariamente | Semanalmente | Mensalmente)
- Confirmar
### Processamento automático:
Supabase Edge Function com pg_cron rodando a cada minuto:
- Busca scheduled_messages WHERE status='pending' AND scheduled_at <= now()
- Para cada: chama zapiClient.sendText() e atualiza status
## PÁGINA: /app/relatorios
### Dashboard de Analytics:
- Seletor de período: Hoje | 7 dias | 30 dias | Personalizado
- Cards de KPIs:
- Total de mensagens enviadas
- Taxa de entrega (%)
- Total de contatos novos
- Campanhas realizadas
- Chatbot interações
### Gráficos (use recharts library):
- Linha: Mensagens por dia (últimos 30 dias) — cor verde
- Barras: Campanhas por semana
- Pizza: Status de entrega (enviado / entregue / falhou)
### Tabela: Top campanhas por performance
- Nome | Enviadas | Entregues | Taxa | Data
## PÁGINA: /app/planos
### Plano atual:
- Badge com plano atual + status
- Data de renovação
- Botão "Gerenciar assinatura" → portal Stripe
### Cards de upgrade (se não for Enterprise):
Mostrar planos superiores com botão "Fazer upgrade →"
Cada botão abre Stripe Checkout para o Price ID correspondente.
### Integração Stripe:
Usar a skill stripe do Lovable.
- Criar Supabase Edge Function: create-checkout
- Cria Stripe Checkout Session
- Retorna checkout_url
- Redireciona para /app/planos?success=true após pagamento
- Criar Supabase Edge Function: stripe-webhook
- Verifica assinatura do webhook
- checkout.session.completed → atualiza profile.plan
- customer.subscription.updated → atualiza plan_status
- customer.subscription.deleted → volta para plan='free'
- invoice.payment_failed → plan_status='past_due'
## PÁGINA: /app/configuracoes
### Seções (tabs ou accordion):
**Perfil:**
- Nome, email, avatar upload
- Trocar senha
- Deletar conta
**Notificações:**
- Toggle: Email quando campanha concluir
- Toggle: Email quando chatbot tiver erro
- Toggle: Email quando mensagem agendada falhar
**Segurança:**
- Ver sessões ativas
- Sair de todos os dispositivos
**Webhooks (plano Pro+):**
- URL de webhook global
- Selecionar eventos: mensagem recebida, campanha concluída, etc.
- Testar webhook
**Plano e faturamento:**
- Link para /app/planos
- Histórico de faturas
## PÁGINA: /app/configuracoes/integracao (para clientes Pro+)
Documentação da API do ProZap (futura funcionalidade — mostrar como "Em breve")
API Key do usuário (gerar/revogar)
## vercel.json (criar na raiz do projeto):
```json
{
"buildCommand": "npm run build",
"outputDirectory": "dist",
"framework": "vite",
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "DENY" },
{ "key": "Strict-Transport-Security", "value": "max-age=31536000; includeSubDomains" },
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
]
}
]
}
```
## ENTREGUE AO FINAL DA PARTE 7:
✅ Página de agendamentos com calendário e lista
✅ Página de relatórios com gráficos recharts
✅ Página de planos com Stripe checkout
✅ Edge Functions: create-checkout e stripe-webhook
✅ Página de configurações completa
✅ vercel.json configurado para deploy sem quebrar
Após concluir: "Parte 7 concluída. Projeto ProZap completo. Próximo: instruções de deploy."
═══════════════════════════════════════════════════════════════
PARTE 8 (FINAL) — CONFIGURAÇÕES MANUAIS DE DEPLOY
═══════════════════════════════════════════════════════════════
Faça isso APÓS o Lovable terminar a Parte 7.
───────────────────────────────────────────────────────────────
8.1 — CONFIGURAR VARIÁVEIS NO SUPABASE (Edge Functions)
───────────────────────────────────────────────────────────────
1. Acesse: https://supabase.com/dashboard → seu projeto prozap
2. Vá em: Settings → Edge Functions → Secrets
3. Clique "Add secret" e adicione UMA POR VEZ:
STRIPE_SECRET_KEY = sk_live_... (ou sk_test_... para testes)
STRIPE_WEBHOOK_SECRET = whsec_... (do passo 0.4)
STRIPE_PRICE_STARTER = price_... (Price ID do plano Starter)
STRIPE_PRICE_PRO = price_... (Price ID do plano Pro)
STRIPE_PRICE_ENTERPRISE = price_... (Price ID do plano Enterprise)
───────────────────────────────────────────────────────────────
8.2 — ATIVAR pg_cron NO SUPABASE (para agendamentos automáticos)
───────────────────────────────────────────────────────────────
1. No Supabase, vá em: Database → Extensions
2. Busque "pg_cron" e clique "Enable"
3. Vá em SQL Editor e rode:
SELECT cron.schedule(
'process-scheduled-messages',
'* * * * *',
$$
SELECT net.http_post(
url := 'https://SEU-PROJETO.supabase.co/functions/v1/process-scheduled',
headers := '{"Authorization": "Bearer SEU-SERVICE-ROLE-KEY"}'::jsonb
);
$$
);
Substitua SEU-PROJETO pelo ref do seu projeto e SEU-SERVICE-ROLE-KEY pelo service_role key do passo 0.1.
───────────────────────────────────────────────────────────────
8.3 — DEPLOY NO VERCEL
───────────────────────────────────────────────────────────────
1. Acesse: https://vercel.com/new
2. Clique "Import Git Repository"
3. Selecione o repositório "prozap" do seu GitHub
4. Framework preset: Vite
5. Build command: npm run build
6. Output directory: dist
6. Antes de clicar Deploy, clique em "Environment Variables" e adicione:
VITE_SUPABASE_URL = https://SEU-PROJETO.supabase.co
VITE_SUPABASE_ANON_KEY = eyJ... (anon public key do passo 0.1)
7. Clique "Deploy"
8. Aguarde o build (2-3 minutos)
9. URL gerada: algo como prozap-xxxx.vercel.app
───────────────────────────────────────────────────────────────
8.4 — CONFIGURAR DOMÍNIO PERSONALIZADO (opcional)
───────────────────────────────────────────────────────────────
1. No Vercel: Settings → Domains → Add Domain
2. Digite: prozap.com.br (ou seu domínio)
3. O Vercel vai te dar registros DNS (tipo A e CNAME)
4. No seu registrador de domínio (Registro.br, GoDaddy, etc.):
- Adicione os registros DNS que o Vercel indicou
5. Aguarde propagação (até 24h, geralmente < 1h)
───────────────────────────────────────────────────────────────
8.5 — CONFIGURAR SUPABASE AUTH URLs
───────────────────────────────────────────────────────────────
1. Supabase → Authentication → URL Configuration
2. Site URL: https://prozap.com.br (ou sua URL do Vercel)
3. Redirect URLs, adicione:
https://prozap.com.br/**
https://prozap-xxxx.vercel.app/**
4. Salvar
───────────────────────────────────────────────────────────────
8.6 — CONFIGURAR WEBHOOK DA Z-API
───────────────────────────────────────────────────────────────
1. Acesse: https://app.z-api.io → sua instância
2. Clique em "Webhooks e configurações gerais"
3. Em "Webhook ao receber mensagem", cole:
https://SEU-PROJETO.supabase.co/functions/v1/zapi-webhook
4. Salvar
5. Isso faz com que toda mensagem recebida seja processada pelo chatbot
───────────────────────────────────────────────────────────────
8.7 — ATUALIZAR URL DO WEBHOOK NO STRIPE
───────────────────────────────────────────────────────────────
1. Stripe → Developers → Webhooks → seu endpoint
2. Clique "Update endpoint"
3. URL: https://SEU-PROJETO.supabase.co/functions/v1/stripe-webhook
4. Salvar
───────────────────────────────────────────────────────────────
8.8 — TESTE FINAL (checklist)
───────────────────────────────────────────────────────────────
Abra o app no navegador e teste cada item:
□ Landing page abre e está responsiva no celular
□ Criar conta funciona (email chega)
□ Login funciona e redireciona para /app
□ Dashboard mostra cards (mesmo que zerados)
□ Adicionar instância Z-API funciona
□ QR code aparece para conectar WhatsApp
□ Escanear QR code com celular conecta o número
□ Criar contato funciona
□ Importar CSV funciona
□ Criar campanha e enviar para 1 contato funciona (receba no celular)
□ Criar chatbot simples com "Olá!" como resposta funciona
□ Agendar uma mensagem para daqui 2 minutos e receber funciona
□ Relatórios mostram dados após os testes acima
□ Upgrade de plano abre Stripe checkout
□ Stripe checkout de teste funciona (use cartão 4242 4242 4242 4242)
□ App no celular funciona (bottom nav, layouts mobile)
═══════════════════════════════════════════════════════════════
RESUMO RÁPIDO — ORDEM DE EXECUÇÃO
═══════════════════════════════════════════════════════════════
1. Fazer PARTE 0 (configurações manuais) — 30-45 minutos
2. Abrir Lovable e conectar Supabase + GitHub
3. Enviar PARTE 1 → esperar Lovable confirmar → PARTE 2 → etc.
4. Não enviar a próxima parte antes do Lovable confirmar a atual
5. Após Parte 7, fazer PARTE 8 (deploy)
ESTIMATIVA DE TEMPO TOTAL:
- Configurações manuais: 45 minutos
- Partes 1-7 no Lovable: 2-4 horas (dependendo da velocidade do Lovable)
- Deploy e testes: 30 minutos
- TOTAL: ~3-5 horas para ter o ProZap no ar
═══════════════════════════════════════════════════════════════
CUSTOS MENSAIS DO PROZAP (após lançamento)
═══════════════════════════════════════════════════════════════
FIXOS:
- Supabase Pro: $25/mês (~R$130) [grátis até 500MB de DB]
- Vercel: $0 (plano gratuito suporta até bom tráfego)
- Z-API: verificar preço atual em z-api.io (você usa apenas para seu número de teste; clientes usam a própria conta)
- Stripe: 2,5-4,9% por transação (sem mensalidade)
TOTAL FIXO INICIAL: ~R$0 a R$130/mês
Com apenas 2 clientes no plano Starter (R$97): já cobre todos os custos.
RECEITA POTENCIAL:
- 50 clientes Starter: R$4.850/mês
- 20 clientes Pro: R$3.940/mês
- 5 clientes Enterprise: R$1.985/mês
- Total com 75 clientes: R$10.775/mês