Loading...
Loading...
Loading...
# LovedBy — Product Requirements Document (PRD)
> **Version:** 1.0
> **Date:** February 15, 2026
> **Status:** Living Document — reflects current production codebase
> **Domain:** lovedby.in
---
## Table of Contents
1. [Executive Summary](#1-executive-summary)
2. [Product Vision & Positioning](#2-product-vision--positioning)
3. [Target Users & Personas](#3-target-users--personas)
4. [User Roles & Access Control](#4-user-roles--access-control)
5. [Platform Architecture](#5-platform-architecture)
6. [Feature Specification — Public Experience](#6-feature-specification--public-experience)
7. [Feature Specification — Creator Studio](#7-feature-specification--creator-studio)
8. [Feature Specification — Brand Dashboard](#8-feature-specification--brand-dashboard)
9. [Feature Specification — Admin Panel](#9-feature-specification--admin-panel)
10. [Commerce Engine](#10-commerce-engine)
11. [Database Schema & Data Model](#11-database-schema--data-model)
12. [Authentication & Security](#12-authentication--security)
13. [Design System & UX Language](#13-design-system--ux-language)
14. [Tech Stack & Infrastructure](#14-tech-stack--infrastructure)
15. [Deployment & DevOps](#15-deployment--devops)
16. [Current Limitations & Known Gaps](#16-current-limitations--known-gaps)
17. [Roadmap & Future Considerations](#17-roadmap--future-considerations)
---
## 1. Executive Summary
**LovedBy** is a **creator-led social commerce platform** that enables content creators (influencers, YouTubers, bloggers) to curate and sell products from partner brands through personalized storefronts. Rather than creators building their own e-commerce from scratch, LovedBy provides the infrastructure — creators pick products from a shared catalog, set their own markups, and earn margins on every sale through their unique `@handle` storefronts.
### Core Value Proposition
| Stakeholder | Value |
|---|---|
| **Creators** | Zero-inventory storefront, earn margins on curated products, own your `@handle` URL |
| **Brands** | Access to creator distribution networks, no upfront creator fees, pay-on-sale commission model |
| **Customers** | Discover products through trusted creators, transparent "supporting @creator" checkout flow |
| **Platform** | 5% platform fee on all transactions, aggregated commerce infrastructure |
### Business Model
```
Brand sets base price → Creator adds margin → Customer pays creator price
→ Brand gets base price
→ Creator gets margin
→ Platform gets 5% fee
```
---
## 2. Product Vision & Positioning
### Vision Statement
> *"Every creator deserves a store. Every purchase should feel personal."*
### Market Position
LovedBy sits at the intersection of **social commerce** and **creator economy**, differentiated from:
- **Shopify/Dukaan**: LovedBy is *not* a generic store builder — it's a curated marketplace where creators don't hold inventory.
- **Amazon Influencer Storefronts**: LovedBy offers full branding control, custom pricing, and a premium aesthetic (vs. Amazon's utilitarian affiliate pages).
- **LTK (LikeToKnowIt)**: LovedBy handles the full transaction, not just affiliate links — creators own the customer relationship.
### Design Philosophy
The platform follows a **"Warm Luxury"** aesthetic — not flashy, not sterile, but a curated boutique feel:
- Soft warm tones (`#FAFAF9` base, `#1C1917` charcoal text)
- Gold accents (`#CA8A04`) for premium highlights
- Glassmorphism for layered UI depth
- Cinematic GSAP scroll animations
- Lenis smooth scrolling for fluid navigation
---
## 3. Target Users & Personas
### Persona 1: The Creator
- **Who**: Influencers with 10K-1M+ followers on Instagram/YouTube
- **Pain Point**: Wants to monetize recommendations without managing inventory, shipping, or customer service
- **Use Case**: Applies to LovedBy → Gets approved → Claims `@handle` → Curates 5+ products from catalog → Shares store link with audience → Earns margin on every sale
- **Categories**: Beauty, Tech, Fashion, Fitness, Home, Travel, Food, Books
### Persona 2: The Brand
- **Who**: D2C and emerging brands wanting creator-led distribution
- **Pain Point**: Paying upfront for influencer campaigns with uncertain ROI
- **Use Case**: Applies as brand → Gets approved → Uploads product catalog → Creators pick and sell products → Brand fulfills orders, pays commission only on sales
- **Categories**: Beauty & Skincare, Fashion & Accessories, Tech & Gadgets, Home & Living, Fitness & Wellness, Food & Kitchen, Travel & Outdoor, Books & Learning
### Persona 3: The Customer
- **Who**: Followers of the creator, aged 18-35, digitally native
- **Pain Point**: Wants product recommendations they can trust, not generic ads
- **Use Case**: Visits creator's `@handle` store → Browses curated products → Adds to cart → Checks out → Sees "You're supporting @creator" messaging
### Persona 4: The Platform Admin
- **Who**: LovedBy operations team
- **Use Case**: Reviews application queue → Approves/rejects creators and brands → Monitors platform KPIs → Manages payouts and flagged content
---
## 4. User Roles & Access Control
### Role Definitions (Database Enum: `user_role`)
| Role | Enum Value | Access Scope | Login Entry Point |
|---|---|---|---|
| Platform Admin | `admin` | Full platform management | `/admin/login` |
| Creator | `creator` | Creator Studio, own storefront | `/login` → `/studio` |
| Brand | `brand` | Brand Dashboard, product catalog | `/login` → `/brand` |
| Public User | *(no auth)* | Public pages, storefronts, cart, checkout | N/A |
### Role-Based Route Protection
Routes are protected via the `<ProtectedRoute>` component which:
1. Checks authentication status via `useAuth()` context
2. Validates user role against `allowedRoles` prop
3. Redirects unauthorized users to the appropriate login page
4. On role mismatch, redirects to the user's correct dashboard (admin → `/admin`, creator → `/studio`, brand → `/brand`)
### Permission Matrix
| Action | Public | Creator | Brand | Admin |
|---|---|---|---|---|
| Browse stores | ✅ | ✅ | ✅ | ✅ |
| Add to cart / Checkout | ✅ | ✅ | ✅ | ✅ |
| Submit application | ✅ | — | — | — |
| Manage own storefront | — | ✅ | — | — |
| Set product margins | — | ✅ | — | — |
| Create collections | — | ✅ | — | — |
| Add products to catalog | — | — | ✅ | — |
| View own brand orders | — | — | ✅ | — |
| Approve / reject applications | — | — | — | ✅ |
| View platform analytics | — | — | — | ✅ |
| Manage payouts | — | — | — | ✅ |
| Configure platform settings | — | — | — | ✅ |
---
## 5. Platform Architecture
### High-Level Architecture
```mermaid
graph TB
subgraph Client["Frontend (React SPA)"]
A[Vite + React 19 + TypeScript]
B[React Router v7 — Client-side routing]
C[Tailwind CSS via CDN]
D[GSAP + ScrollTrigger — Animations]
E[Lenis — Smooth Scroll]
end
subgraph Backend["Backend (Supabase BaaS)"]
F[Supabase Auth — Email/Password]
G[Supabase Postgres — Database]
H[Row Level Security — Authorization]
I[Supabase Realtime — Live subscriptions]
J[Supabase RPC — Server-side functions]
end
subgraph Infra["Infrastructure"]
K[Vercel — Static hosting + SPA rewrites]
L[Google Fonts — Typography CDN]
M[Google User Content — Image CDN]
end
A --> F
A --> G
A --> I
G --> H
A --> K
```
### Frontend Module Map
```
LovedBy/
├── App.tsx # Root router, providers, layout
├── index.tsx # React DOM entry point
├── index.html # Tailwind config, fonts, meta
│
├── pages/ # 46 page components
│ ├── Home.tsx # Landing page with hero carousel
│ ├── Explore.tsx # Creator discovery + filtering
│ ├── CreatorStore.tsx # Individual creator storefront (@handle)
│ ├── Cart.tsx # Shopping cart
│ ├── Checkout.tsx # Order placement
│ ├── Login.tsx # User authentication
│ ├── Signup.tsx # User registration
│ ├── ForgotPassword.tsx # Password recovery
│ ├── SetPassword.tsx # Password setup (post-approval)
│ ├── BecomeCreator.tsx # Creator application form
│ ├── BecomeBrand.tsx # Brand application form
│ ├── About.tsx # Company about page
│ ├── Contact.tsx # Contact form
│ ├── Careers.tsx # Careers page
│ ├── Blog.tsx # Blog/articles page
│ ├── AdminSetup.tsx # Initial admin setup
│ │
│ ├── admin/ # Admin panel (13 pages)
│ │ ├── Overview.tsx # Dashboard with KPI cards + alerts
│ │ ├── Applications.tsx # Application review queue
│ │ ├── Creators.tsx # Creator management
│ │ ├── Brands.tsx # Brand management
│ │ ├── Products.tsx # Product catalog management
│ │ ├── Orders.tsx # Order management
│ │ ├── Stores.tsx # Store monitoring
│ │ ├── Payouts.tsx # Payout processing
│ │ ├── Flags.tsx # Flagged content
│ │ ├── Logs.tsx # Activity logs
│ │ ├── Settings.tsx # Platform configuration
│ │ ├── AdminLogin.tsx # Admin-specific login
│ │ └── AdminDashboard.tsx # Legacy dashboard
│ │
│ ├── studio/ # Creator Studio (9 pages)
│ │ ├── Dashboard.tsx # Creator analytics dashboard
│ │ ├── Onboarding.tsx # 3-phase store setup wizard
│ │ ├── ProductBrowser.tsx # Browse & add products to store
│ │ ├── StorefrontManager.tsx # Manage store products
│ │ ├── CollectionManager.tsx # Create & manage collections
│ │ ├── CollectionDetail.tsx # Individual collection editor
│ │ ├── ProfileEditor.tsx # Edit creator profile
│ │ ├── Orders.tsx # View creator's orders
│ │ └── Settings.tsx # Creator settings (UPI, etc.)
│ │
│ ├── brand/ # Brand Dashboard (5 pages)
│ │ ├── Dashboard.tsx # Brand analytics dashboard
│ │ ├── Products.tsx # Manage product catalog
│ │ ├── AddProduct.tsx # Add new product form
│ │ ├── Orders.tsx # Brand order tracking
│ │ └── Settings.tsx # Brand settings
│ │
│ └── legal/ # Legal pages (3 pages)
│ ├── Terms.tsx # Terms of Service
│ ├── Privacy.tsx # Privacy Policy
│ └── Refund.tsx # Refund Policy
│
├── components/ # Shared UI components
│ ├── Navbar.tsx # Global navigation with typing animation
│ ├── Footer.tsx # Global footer
│ ├── Animations.tsx # AnimatedSection, StaggerContainer, TextReveal, TiltCard
│ ├── PageTransition.tsx # Route transition wrapper
│ ├── ProtectedRoute.tsx # Role-based auth guard
│ ├── SplashScreen.tsx # Initial loading animation
│ ├── SafePage.tsx # Error boundary wrapper
│ ├── RootRedirect.tsx # Root `/` redirect logic
│ ├── StoreNavbar.tsx # Creator store-specific navbar
│ ├── PremiumComponents.tsx # Reusable premium UI components
│ ├── admin/AdminLayout.tsx # Admin sidebar layout
│ ├── brand/BrandLayout.tsx # Brand sidebar layout
│ └── studio/ # Studio components
│ ├── StudioLayout.tsx # Studio sidebar layout
│ ├── StatsCard.tsx # Reusable stats card
│ └── ProductCard.tsx # Product card with "Add to Store" UX
│
├── contexts/ # React Context providers
│ ├── AuthContext.tsx # Authentication state + Supabase auth
│ └── CartContext.tsx # Shopping cart (localStorage-persisted)
│
├── hooks/ # Custom React hooks
│ └── useAdminStats.ts # Real-time admin dashboard stats
│
├── lib/ # Utility libraries
│ ├── supabase.ts # Supabase client initialization
│ ├── adminActions.ts # Admin API functions
│ ├── gsap.ts # GSAP + ScrollTrigger setup
│ ├── lenis.ts # Lenis smooth scroll setup
│ ├── safetyInit.ts # Animation fallback safety
│ └── index.ts # Barrel exports
│
├── types/ # TypeScript type definitions
│ ├── index.ts # Domain types (Creator, Brand, Product, Order, etc.)
│ └── database.ts # Supabase database types + Database interface
│
├── constants/ # Static data
│ ├── index.ts # Featured creators + sample products
│ └── featuredData.ts # Hero cards + featured creators for Home
│
├── styles/ # CSS
│ ├── animations.css # GSAP & CSS animation keyframes (35KB)
│ └── glass.css # Glassmorphism utility classes (19KB)
│
├── design-system/ # Design system documentation
│ ├── lovedby/ # Core design tokens
│ └── lovedby-explore/ # Explore page design reference
│
├── sql/ # Database schema files
│ ├── supabase-schema.sql # Master schema (DDL + RLS + triggers)
│ ├── seed_admin_data.sql # Admin seed data
│ ├── seed_scaling_data.sql # Large-scale test data (67KB)
│ ├── seed_test_flow.sql # Test flow data
│ └── reset-admins.sql # Admin reset utility
│
├── migrations/ # Incremental schema migrations
│ ├── 001_sprint_1_schema.sql # Creator commerce + dashboards
│ ├── 002_sprint_2_schema.sql # Brand dashboard + product images
│ ├── 002_store_collections.sql # Collections feature
│ └── 003_auto_confirm_emails.sql # Email auto-confirm
│
└── scripts/ # Development utilities
├── deploy_schema.cjs # Schema deployment script
├── seed_scaling_data.py # Python seeder for test data
├── download_mock_images.py # Mock image downloader
└── ... # Diagnostic & patching scripts
```
---
## 6. Feature Specification — Public Experience
### 6.1 Home Page (`/home`)
**Purpose:** Landing page that communicates the LovedBy value proposition and drives user acquisition.
| Section | Description |
|---|---|
| **Hero Carousel** | 3-card interactive carousel showcasing featured creator stores with image, title, product count, and tag (Featured/Trending/Verified). Navigation arrows for carousel control. |
| **Featured Creators** | Grid of 4 verified creator cards with avatar, name, handle, and role. Links to creator profiles. |
| **How It Works** | Step-by-step explanation of the creator commerce model. |
| **Stats Strip** | Key platform metrics (creators, products, orders). |
| **Testimonials** | Social proof from existing creators and customers. |
| **CTA Sections** | "Become a Creator" and "Become a Brand" conversion sections. |
**Animations:** GSAP ScrollTrigger-powered fade-ins, stagger effects, text reveals, parallax. Splash screen on initial load.
### 6.2 Explore Page (`/explore`)
**Purpose:** Creator discovery and browsing hub.
| Feature | Details |
|---|---|
| **Creator Grid** | Responsive card grid showing all active creators from Supabase + fallback to static constants |
| **Category Filtering** | Real-time filtering by product categories fetched from `product_categories` table |
| **Niche Filtering** | Multi-select niche filters (Beauty, Tech, Fashion, Fitness, Home, Travel, etc.) |
| **Dark Mode Toggle** | Page-level dark theme toggle for immersive browsing |
| **Search** | Text search across creator names, handles, and bios |
| **Clickable Cards** | Entire creator card is clickable, navigates to `/@{handle}` |
**Data Source:** Hybrid — fetches from `creator_profiles` via Supabase with join on `profiles` for verified status. Falls back to `EXPLORE_CREATORS` constant data when Supabase is unconfigured.
### 6.3 Creator Store (`/@{handle}`)
**Purpose:** Individual creator's curated storefront — the core product experience.
| Feature | Details |
|---|---|
| **URL Pattern** | `/@{handle}` or `/{handle}` (fallback route) |
| **Creator Banner** | Full-width banner image with gradient overlay |
| **Creator Profile** | Avatar, display name, handle, bio, tagline, follower count |
| **Product Grid** | All active `store_products` for this creator with product images, titles, prices, and brand attribution |
| **Collections** | Grouped product sections based on creator's curated collections |
| **Add to Cart** | Each product card has an "Add to Cart" button with quantity selector |
| **Store Navbar** | Custom store-specific navigation with creator branding |
| **Price Display** | Shows `creator_price` (the price the creator set, including their margin) |
| **Verified Badge** | Shows verification checkmark for verified creator profiles |
**Data Flow:**
1. Extract `handle` from URL params
2. Query `creator_profiles` WHERE `handle = :handle`
3. Fetch `store_products` with joined `products` and `brand_profiles` WHERE `creator_id = profile.id` AND `is_active = true`
4. Fetch `collections` + `collection_items` for grouped display
5. Render storefront with creator's branding
### 6.4 Cart (`/cart`)
**Purpose:** Shopping cart with full CRUD operations.
| Feature | Details |
|---|---|
| **Persistence** | `localStorage` under key `lovedby_cart` |
| **Cart Items** | Displays product image, title, price, quantity controls, brand_id, creator_id |
| **Quantity Control** | Increment/decrement per item, remove at `quantity ≤ 0` |
| **Price Summary** | Subtotal, free shipping label, total |
| **Creator Attribution** | Tracks which creator's store each item came from |
| **Empty State** | "Your cart is empty" with link to Explore |
### 6.5 Checkout (`/checkout`)
**Purpose:** Order placement with financial split calculation.
| Feature | Details |
|---|---|
| **Form Fields** | Email, first name, last name, address, city, postal code |
| **Validation** | Required fields check, email regex validation |
| **Creator Attribution** | "You're supporting @{handle}" messaging via URL query param |
| **Payment** | Simulated payment gateway (1.5s delay), references Razorpay in UI |
| **Currency** | INR (₹) — Indian Rupee |
| **Free Shipping** | All orders have free shipping |
**Financial Split on Order Placement:**
```
margin_total = Σ(item.margin × item.quantity)
creator_payout = margin_total (creator gets full margin)
platform_fee = total_amount × 5%
```
**Order Flow:**
1. Validate form fields
2. Simulate payment processing
3. Insert into `orders` table with financial split
4. Insert into `order_items` with per-item breakdown
5. Call `increment_creator_stats` RPC to update creator profile stats
6. Clear cart + show success page with order ID
### 6.6 Application Forms
#### Become a Creator (`/creators`)
| Field | Type | Required |
|---|---|---|
| Full Name | text | ✅ |
| Email | email | ✅ |
| Phone | tel | ❌ |
| Social Link (Instagram/YouTube) | URL | ❌ |
| Niche | select | ✅ |
| Bio | textarea | ✅ |
**On Submit:** Inserts into `applications` table with `type = 'creator'` and `form_data` JSONB containing all fields.
#### Become a Brand (`/brands`)
| Field | Type | Required |
|---|---|---|
| Brand Name | text | ✅ |
| Contact Name | text | ✅ |
| Email | email | ✅ |
| Phone | tel | ❌ |
| Website | URL | ❌ |
| Instagram | text | ❌ |
| Category | select | ✅ |
| Description | textarea | ❌ |
**On Submit:** Inserts into `applications` table with `type = 'brand'` and `form_data` JSONB.
### 6.7 Auth Pages
| Page | Route | Functionality |
|---|---|---|
| Login | `/login` | Email + password sign-in via Supabase Auth |
| Signup | `/signup` | Email + password sign-up, email confirmation redirect |
| Forgot Password | `/forgot-password` | Password reset email via `supabase.auth.resetPasswordForEmail()` |
| Set Password | `/set-password` | Set initial password (used post-approval for creators/brands) |
### 6.8 Static / Content Pages
| Page | Route | Content Type |
|---|---|---|
| About | `/about` | Company story, mission, team |
| Contact | `/contact` | Contact form + office details |
| Careers | `/careers` | Job listings |
| Blog | `/blog` | Article listings |
| Terms | `/terms` | Legal Terms of Service |
| Privacy | `/privacy` | Privacy Policy |
| Refund | `/refund` | Refund & Cancellation Policy |
---
## 7. Feature Specification — Creator Studio
**Entry Point:** `/studio` (requires `role = 'creator'`)
### 7.1 Creator Onboarding (`/studio/onboarding`)
A **3-phase guided wizard** that activates a creator's store:
**Phase 1 — Claim Handle:**
- Input field with `lovedby.in/@` prefix
- Validation: min 3 characters, alphanumeric + underscores only, uniqueness check against `creator_profiles.handle`
- Stores handle in `creator_profiles` table
**Phase 2 — Curate Products:**
- Browse full product catalog from `products` table (status = 'active')
- Filter by: search text, category (from `product_categories`), brand, price range
- Sort by: featured, price low/high
- Minimum **5 products** required to proceed (enforced with progress bar)
- Each product added creates a `store_products` record with `creator_price`
- Product card shows brand attribution, base price, and "Add to Store" button
**Phase 3 — Launch:**
- Updates `creator_profiles.store_status` from `'setup'` to `'active'`
- Animated success screen ("You're Live!")
- Auto-redirect to Studio Dashboard after 3 seconds
### 7.2 Creator Dashboard (`/studio`)
| Widget | Data Source |
|---|---|
| Total Sales | `creator_profiles.total_sales` |
| Total Earnings | `creator_profiles.total_earnings` |
| Products in Store | Count of `store_products` WHERE `creator_id = self` |
| Recent Orders | `orders` WHERE `creator_id = self` ordered by `created_at DESC` |
| Quick Actions | Links to Product Browser, Storefront, Profile, Collections |
### 7.3 Product Browser (`/studio/products`)
- Full catalog view of all active products
- Advanced filtering: search, category, brand, price range, sort
- "Add to Store" with custom creator price input
- Shows which products are already in the creator's store
- Brand attribution on every product card
### 7.4 Storefront Manager (`/studio/storefront`)
- View all products currently in the creator's store
- Toggle product active/inactive status (`store_products.is_active`)
- Reorder products (`store_products.display_order`)
- Delete products from store (removes `store_products` row)
- Edit creator price and margins
### 7.5 Collection Manager (`/studio/collections`)
- Create themed collections (e.g., "Summer Essentials", "Work From Home Kit")
- Each collection has: title, slug (auto-generated), cover image, public/private toggle
- Collections table: `collections` with `creator_id` FK
### 7.6 Collection Detail (`/studio/collections/:id`)
- Add/remove products from a collection via `collection_items` junction table
- Drag-and-drop sort order (`collection_items.sort_order`)
- Preview collection as it would appear on the storefront
### 7.7 Profile Editor (`/studio/profile`)
- Edit: display name, bio, tagline, avatar URL, banner URL, social links (Instagram, YouTube)
- Changes update `creator_profiles` table
- Live preview of profile card
### 7.8 Creator Orders (`/studio/orders`)
- View all orders attributed to this creator
- Order details: customer name, items, amounts, status, date
- Status tracking: pending → confirmed → shipped → delivered → cancelled
### 7.9 Creator Settings (`/studio/settings`)
- UPI ID configuration for payouts
- Notification preferences
- Account management
---
## 8. Feature Specification — Brand Dashboard
**Entry Point:** `/brand` (requires `role = 'brand'`)
### 8.1 Brand Dashboard (`/brand`)
| Widget | Data Source |
|---|---|
| Total Products | `brand_profiles.total_products` |
| Total Sales | `brand_profiles.total_sales` |
| Active Creators Selling | Count of distinct `store_products.creator_id` WHERE product belongs to this brand |
| Recent Orders | `order_items` joined with `orders` WHERE `brand_id = self` |
### 8.2 Product Management (`/brand/products`)
- View all products uploaded by this brand
- Product statuses: `draft`, `active`, `archived`
- Per-product details: title, price, compare_at_price, images, category, stock, commission_percent
### 8.3 Add Product (`/brand/products/new`)
| Field | Type | Required |
|---|---|---|
| Product Title | text | ✅ |
| Description | textarea | ❌ |
| Base Price | number (₹) | ✅ |
| Compare At Price | number (₹) | ❌ |
| Images | URL array | ✅ (at least 1) |
| Category | select (from `product_categories`) | ❌ |
| Stock | number | ✅ |
| Commission Percent | number (%) | Default: 10% |
| Status | select | Default: `draft` |
### 8.4 Brand Orders (`/brand/orders`)
- All order items containing this brand's products
- Fulfillment tracking per item
- Revenue metrics
### 8.5 Brand Settings (`/brand/settings`)
- Update brand name, about, website, category, contact info
- Logo management
---
## 9. Feature Specification — Admin Panel
**Entry Point:** `/admin` (requires `role = 'admin'`)
### 9.1 Admin Overview (`/admin` or `/admin/dashboard`)
**KPI Stats Cards** (real-time via Supabase Realtime subscriptions):
| Metric | Source | Details |
|---|---|---|
| Active Creators | `profiles` WHERE `role = 'creator'` | Shows pending application count |
| Active Brands | `brand_profiles` count | Shows pending brand app count |
| Live Stores | `creator_profiles` WHERE `store_status = 'active'` | — |
| Orders Today | `orders` WHERE `created_at >= today` | — |
| Orders This Week | `orders` WHERE `created_at >= start_of_week` | — |
| Escrow Balance | Sum of `total_amount` for orders in `paid`/`shipped` status | — |
| Pending Payouts | Sum of `total_amount` for `delivered` orders | — |
**Alert System:** Surfaces critical items (pending applications, low stock, etc.)
**Activity Feed:** Recent platform activity with timestamps and icons.
**Realtime Updates:** The `useAdminStats` hook subscribes to Postgres changes on `applications`, `orders`, and `creator_profiles` tables via Supabase Realtime channels for instant dashboard updates.
### 9.2 Applications (`/admin/applications`)
**Purpose:** Review and approve/reject creator and brand applications.
| Feature | Details |
|---|---|
| Tab System | Separate tabs for "Creators" and "Brands" with pending count badges |
| Status Filters | All, Pending, Approved, Rejected |
| Search | By name or email |
| Bulk Selection | Checkbox per row + "Select All" |
| Bulk Actions | Floating action bar: Approve selected, Reject selected |
| Expandable Details | Click to expand and view full application data |
| Individual Actions | Approve/Reject buttons per application |
**Approval Flow (Creator):**
1. Fetch application data
2. Find matching user in `profiles` by email
3. Generate auto-handle: `lowercaseName + random3digits`
4. Insert into `creator_profiles` with `store_status = 'setup'`
5. If user exists, update `profiles.role` to `'creator'`
6. Update application `status = 'approved'`
**Approval Flow (Brand):**
1. Fetch application data
2. Find matching user in `profiles` by email
3. Insert into `brand_profiles`
4. If user exists, update `profiles.role` to `'brand'`
5. Update application `status = 'approved'`
### 9.3 Other Admin Pages
| Page | Route | Purpose |
|---|---|---|
| Creators | `/admin/creators` | Manage creator profiles, toggle statuses, view details |
| Brands | `/admin/brands` | Manage brand profiles |
| Products | `/admin/products` | Global product catalog management |
| Orders | `/admin/orders` | Platform-wide order management |
| Stores | `/admin/stores` | Monitor active creator stores |
| Payouts | `/admin/payouts` | Process creator payout requests |
| Flags | `/admin/flags` | Flagged content review |
| Logs | `/admin/logs` | Activity and audit logs |
| Settings | `/admin/settings` | Platform configuration |
---
## 10. Commerce Engine
### 10.1 Pricing Model
```
Brand Base Price (set by brand in `products.price`)
+ Creator Margin (set by creator as `store_products.creator_price - products.price`)
= Customer Price (stored in `store_products.creator_price`)
Commission % (set by brand in `products.commission_percent`, default 10%)
Platform Fee (5% of total_amount, calculated at checkout)
```
### 10.2 Order Lifecycle
```mermaid
stateDiagram-v2
[*] --> pending: Customer places order
pending --> confirmed: Admin/Brand confirms
pending --> cancelled: Customer/Admin cancels
confirmed --> shipped: Brand ships
shipped --> delivered: Delivery confirmed
delivered --> [*]: Payout eligible
cancelled --> [*]
```
### 10.3 Order Data Flow
```
1. Customer clicks "Place Order"
2. → INSERT orders (total, margin_total, creator_payout, platform_fee)
3. → INSERT order_items[] (per-item price breakdown)
4. → RPC increment_creator_stats (updates creator_profiles.total_sales + total_earnings)
5. → Clear cart (localStorage)
6. → Show confirmation with order ID
```
### 10.4 Cart Architecture
- **Storage:** `localStorage` (key: `lovedby_cart`)
- **Structure:** Array of `CartItem` objects
- **Dedup Key:** `product_id` — adding duplicate increments quantity
- **Item Fields:** `id`, `product_id`, `title`, `price`, `image`, `quantity`, `brand_id`, `creator_id`
- **Computed:** `totalItems` (sum of quantities), `totalPrice` (sum of price × quantity)
### 10.5 Payment
**Current State:** Mock payment simulation.
- UI references **Razorpay** as payment processor
- Simulates a 1.5-second processing delay
- No actual payment integration — orders are created directly in Supabase
- Currency: INR (₹)
---
## 11. Database Schema & Data Model
### 11.1 Tables Overview
| Table | Purpose | Row Count Estimate |
|---|---|---|
| `profiles` | User accounts (extends `auth.users`) | All registered users |
| `applications` | Creator/Brand application queue | All applications ever submitted |
| `creator_profiles` | Extended creator data | Approved creators |
| `brand_profiles` | Extended brand data | Approved brands |
| `products` | Product catalog (owned by brands) | All products |
| `product_categories` | Category taxonomy | 8 default categories |
| `store_products` | Creator ↔ Product junction (curation) | Many-to-many |
| `collections` | Creator-curated product groups | Per-creator |
| `collection_items` | Collection ↔ Product junction | Many-to-many |
| `orders` | Customer orders | All orders |
| `order_items` | Per-product order line items | Per-order items |
| `payouts` | Creator payout records | Payout requests |
### 11.2 Entity Relationship Diagram
```mermaid
erDiagram
auth_users ||--|| profiles : "1:1"
profiles ||--o| creator_profiles : "1:0..1"
profiles ||--o| brand_profiles : "1:0..1"
brand_profiles ||--o{ products : "owns"
products }o--o{ product_categories : "categorized"
creator_profiles ||--o{ store_products : "curates"
products ||--o{ store_products : "listed in"
creator_profiles ||--o{ collections : "creates"
collections ||--o{ collection_items : "contains"
products ||--o{ collection_items : "featured in"
creator_profiles ||--o{ orders : "attributed to"
orders ||--o{ order_items : "contains"
products ||--o{ order_items : "sold in"
brand_profiles ||--o{ order_items : "fulfilled by"
creator_profiles ||--o{ payouts : "requests"
```
### 11.3 Key Table Definitions
#### `profiles`
| Column | Type | Notes |
|---|---|---|
| id | UUID (PK) | References `auth.users(id)` |
| email | TEXT | NOT NULL |
| role | `user_role` enum | `'admin' \| 'creator' \| 'brand'` |
| is_verified | BOOLEAN | Default false |
| created_at | TIMESTAMPTZ | Auto |
#### `creator_profiles`
| Column | Type | Notes |
|---|---|---|
| id | UUID (PK) | Auto-generated |
| user_id | UUID (FK → profiles) | UNIQUE |
| handle | TEXT | UNIQUE, NOT NULL (e.g., `rahul`) |
| display_name | TEXT | — |
| bio | TEXT | — |
| tagline | TEXT | — |
| avatar_url | TEXT | — |
| banner_url | TEXT | — |
| socials | JSONB | `{ instagram, youtube }` |
| store_status | `store_status` enum | `'setup' \| 'active' \| 'disabled'` |
| total_sales | INTEGER | Denormalized counter |
| total_earnings | NUMERIC(12,2) | Denormalized sum |
| upi_id | TEXT | Payment receiver |
#### `products`
| Column | Type | Notes |
|---|---|---|
| id | UUID (PK) | Auto-generated |
| brand_id | UUID (FK → brand_profiles) | NOT NULL |
| title | TEXT | NOT NULL |
| description | TEXT | — |
| price | NUMERIC(10,2) | Base price, NOT NULL |
| compare_at_price | NUMERIC(10,2) | For showing discounts |
| image | TEXT | Primary thumbnail |
| images | TEXT[] | Array of image URLs |
| category | TEXT | Legacy category field |
| category_id | UUID (FK → product_categories) | Normalized category |
| stock | INTEGER | Default 0 |
| status | TEXT CHECK | `'draft' \| 'active' \| 'archived'` |
| commission_percent | NUMERIC(5,2) | Default 10.00% |
#### `store_products`
| Column | Type | Notes |
|---|---|---|
| id | UUID (PK) | Auto-generated |
| creator_id | UUID (FK → creator_profiles) | NOT NULL |
| product_id | UUID (FK → products) | NOT NULL |
| creator_price | NUMERIC(10,2) | Price set by creator (base + margin) |
| is_active | BOOLEAN | Default true |
| display_order | INTEGER | Sort position |
| is_featured | BOOLEAN | Default false |
| UNIQUE | (creator_id, product_id) | Prevents duplicate curation |
#### `orders`
| Column | Type | Notes |
|---|---|---|
| id | UUID (PK) | Auto-generated |
| customer_name | TEXT | NOT NULL |
| customer_email | TEXT | NOT NULL |
| customer_phone | TEXT | — |
| shipping_address | JSONB | `{ address, city, postalCode }` |
| total_amount | NUMERIC(12,2) | NOT NULL |
| margin_total | NUMERIC(10,2) | Creator margin sum |
| creator_payout | NUMERIC(10,2) | Amount due to creator |
| platform_fee | NUMERIC(10,2) | 5% platform cut |
| status | `order_status` enum | `pending → paid → shipped → delivered → cancelled` |
| payment_method | TEXT | Default `'cod'` |
| payment_status | TEXT | Default `'pending'` |
| creator_id | UUID (FK → creator_profiles) | Sales attribution |
### 11.4 Row Level Security (RLS)
All tables have RLS enabled. Key policies:
| Table | Policy | Rule |
|---|---|---|
| `profiles` | Public read | `SELECT` for all |
| `profiles` | Self-edit | `UPDATE` where `auth.uid() = id` |
| `applications` | Anyone can submit | `INSERT` with check `true` |
| `applications` | Admin full access | All ops where user is admin |
| `creator_profiles` | Public read | `SELECT` for all |
| `creator_profiles` | Self-manage | All ops where `auth.uid() = user_id` |
| `products` | Public read active | `SELECT` where `status = 'active'` |
| `products` | Brand self-manage | All ops where brand's `user_id = auth.uid()` |
| `store_products` | Public read | `SELECT` for all |
| `store_products` | Creator self-manage | All ops where creator's `user_id = auth.uid()` |
| `product_categories` | Public read | `SELECT` for all |
| `product_categories` | Admin manage | All ops where user is admin |
| `payouts` | Creator view own | `SELECT` where creator's `user_id = auth.uid()` |
| `payouts` | Admin manage | All ops where user is admin |
### 11.5 Database Triggers
| Trigger | Event | Action |
|---|---|---|
| `on_auth_user_created` | `AFTER INSERT ON auth.users` | Creates `profiles` row with default role `'creator'` |
---
## 12. Authentication & Security
### 12.1 Auth Flow
```mermaid
sequenceDiagram
actor U as User
participant A as App (AuthContext)
participant S as Supabase Auth
U->>A: Navigate to /login
U->>A: Enter email + password
A->>S: signInWithPassword()
S-->>A: Session + JWT
A->>S: getSession() on mount
A->>S: Fetch profile from profiles table
A->>A: Set user, session, profile state
A->>A: Derive isAdmin, isCreator, isBrand
A->>U: Redirect to role-appropriate dashboard
```
### 12.2 Session Management
- **Provider:** Supabase Auth (email/password)
- **Token Storage:** Managed by Supabase JS SDK (localStorage)
- **Session Persistence:** Supabase handles token refresh automatically
- **Auth State Listener:** `supabase.auth.onAuthStateChange()` — reacts to login/logout/token refresh
- **Profile Fetch:** On each auth state change, fetches `profiles` row for the user
- **Auto-Link:** Calls `supabase.rpc('link_approved_application')` on login to auto-link approved applications to user accounts
### 12.3 Security Model
| Layer | Mechanism |
|---|---|
| Transport | HTTPS (Vercel + Supabase default) |
| Authentication | Supabase Auth via JWT |
| Authorization | RLS policies on all tables |
| Frontend Guards | `<ProtectedRoute>` component with role checking |
| API Security | Supabase anon key is publishable; RLS provides actual security |
| Secrets | Environment variables via `.env` (VITE_SUPABASE_URL, VITE_SUPABASE_ANON_KEY) |
---
## 13. Design System & UX Language
### 13.1 Color Palette
| Token | Value | Usage |
|---|---|---|
| `warm-50` | `#FAFAF9` | Page background |
| `warm-100` | `#F5F5F4` | Card backgrounds, secondary surfaces |
| `warm-200` | `#E7E5E4` | Borders, dividers |
| `charcoal` | `#1C1917` | Primary text, buttons, headings |
| `accent-gold` | `#CA8A04` | Accent highlights, CTAs, premium elements |
| `accent-gold-light` | `#EAB308` | Light gold variants |
| `text-dark` | `#0C0A09` | Maximum contrast text |
| `primary` | `#1C1917` | Alias for charcoal |
| `secondary` | `#44403C` | Secondary text |
| `muted` | `#78716C` | Muted text, labels |
### 13.2 Typography
| Font | Family | Usage |
|---|---|---|
| **Plus Jakarta Sans** | `font-sans` | Body text, UI labels, forms (primary) |
| **Playfair Display** | `font-serif` | Headlines, feature sections, luxury feel |
| **Syne** | `font-display` | Display headings, hero sections, brand identity |
### 13.3 Glassmorphism System
Defined in `styles/glass.css` (19KB) — a comprehensive system of glassy, semi-transparent surfaces:
- `.glass-card`: `background: rgba(255, 255, 255, 0.75)`, `backdrop-filter: blur(12px)`, `border: 1px solid rgba(255, 255, 255, 0.4)`
- `.premium-shadow`: Multi-layer soft shadow for depth
### 13.4 Animation System
Defined in `styles/animations.css` (35KB) + `components/Animations.tsx`:
| Component | Purpose |
|---|---|
| `AnimatedSection` | GSAP-powered section fade-in on scroll |
| `StaggerContainer` | Children animate in sequence with configurable stagger |
| `TextReveal` | Character-by-character text reveal animation |
| `TiltCard` | 3D tilt effect on hover (mouse tracking) |
| `SplashScreen` | Full-screen brand splash on initial load |
| `PageTransition` | Route-level crossfade transitions |
**CSS Animations:** `float`, `float-slow`, `float-fast`, `pulse-slow`, `shimmer`
### 13.5 Smooth Scrolling
**Library:** Lenis
**Setup:** `lib/lenis.ts` — initialized in `LenisProvider` wrapper, runs RAF loop for smooth scroll.
### 13.6 Component Patterns
| Pattern | Implementation |
|---|---|
| Border Radius | `rounded-3xl` to `rounded-6xl` (1.5rem–3rem) |
| Button Style | Charcoal bg, white text, bold font, rounded-xl, shadow-lg, hover scale |
| Card Style | White bg, `border-charcoal/5`, `rounded-2xl` or `rounded-3xl`, shadow-sm |
| Input Style | `bg-warm-50` or `bg-gray-50`, `border-charcoal/10`, `rounded-xl`, bold font |
| Labels | `text-[10px]`, `font-bold`, `uppercase`, `tracking-widest`, `text-charcoal/40` |
| Icons | Material Symbols Outlined (Google Fonts CDN) |
---
## 14. Tech Stack & Infrastructure
### 14.1 Frontend
| Technology | Version | Purpose |
|---|---|---|
| React | 19.2.4 | UI framework |
| TypeScript | ~5.8.2 | Type safety |
| Vite | ^6.2.0 | Build tool + dev server |
| React Router | ^7.13.0 | Client-side routing |
| Tailwind CSS | v3 (CDN) | Utility-first styling |
| GSAP | ^3.14.2 | Animation engine |
| Lenis | ^1.3.17 | Smooth scrolling |
| Barba.js | ^2.10.3 | Page transitions (installed, minimal usage) |
### 14.2 Backend
| Technology | Purpose |
|---|---|
| Supabase | BaaS — Auth, Database, Realtime, RPC |
| PostgreSQL | Database (via Supabase) |
| Row Level Security | Authorization layer |
| Supabase Realtime | Live data subscriptions (admin stats) |
### 14.3 Infrastructure
| Service | Purpose |
|---|---|
| Vercel | Hosting + SPA rewrite rules |
| Google Fonts CDN | Typography (Plus Jakarta Sans, Playfair Display, Syne, Material Symbols) |
| Google User Content CDN | Image hosting (profile images, product images) |
### 14.4 Development Tools
| Tool | Purpose |
|---|---|
| Web3Forms | Application form email notifications |
| MCP Supabase | AI-assisted database management |
| Node.js scripts | Schema deployment, data seeding, diagnostics |
| Python scripts | Test data generation, image downloads |
---
## 15. Deployment & DevOps
### 15.1 Deployment Configuration
**Platform:** Vercel
**Config:** `vercel.json` with SPA rewrite rule:
```json
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
```
### 15.2 Environment Variables
| Variable | Description | Required |
|---|---|---|
| `VITE_SUPABASE_URL` | Supabase project URL | ✅ |
| `VITE_SUPABASE_ANON_KEY` | Supabase anonymous/public key | ✅ |
| `VITE_WEB3FORMS_KEY` | Web3Forms API key (for application forms) | ❌ |
### 15.3 Build Pipeline
```bash
npm install # Install dependencies
npm run dev # Start Vite dev server
npm run build # Build for production (Vite)
npm run preview # Preview production build locally
```
---
## 16. Current Limitations & Known Gaps
### 16.1 Payment Integration
> **Status: Not integrated.** Checkout simulates payment with a 1.5-second delay. UI references Razorpay but no actual SDK integration exists. All orders are created directly in Supabase without real payment verification.
### 16.2 Image Uploads
> **Status: No upload pipeline.** All images are referenced by external URL (Google User Content CDN, Unsplash). No Supabase Storage integration for creator/brand self-service upload.
### 16.3 Email Notifications
> **Status: Minimal.** Password reset emails via Supabase Auth. No transactional email for order confirmations, application status updates, or shipping notifications.
### 16.4 Search
> **Status: Client-side only.** Search is implemented as local JavaScript filtering on pre-fetched data. No server-side full-text search, Algolia, or similar.
### 16.5 Analytics
> **Status: Admin-only, basic.** `useAdminStats` provides aggregate counts. No per-creator analytics dashboards, funnel tracking, conversion metrics, or external analytics integration (GA4, Mixpanel, etc.).
### 16.6 Mobile Responsiveness
> **Status: Partially responsive.** Tailwind responsive classes used throughout but not comprehensively audited for all screen sizes. No native mobile app.
### 16.7 Inventory Management
> **Status: Basic.** `products.stock` field exists but is not decremented on order placement. No stock validation at checkout, no out-of-stock enforcement.
### 16.8 Payout Processing
> **Status: UI scaffolded, not functional.** Admin payouts page exists but no actual bank/UPI transfer execution. Creator UPI IDs are stored but not used in automated processing.
### 16.9 SEO
> **Status: Minimal.** Basic meta tags on `index.html`. No dynamic meta tags per page, no sitemap, no structured data, no SSR/SSG for SEO-critical pages.
### 16.10 Testing
> **Status: No automated tests.** No unit tests, integration tests, or E2E tests in the codebase.
---
## 17. Roadmap & Future Considerations
### Phase 1: Commerce Foundation (MVP Complete ✅)
- [x] Creator/Brand application flow
- [x] Admin application review
- [x] Creator onboarding wizard
- [x] Product catalog with brand management
- [x] Creator storefront (@handle URLs)
- [x] Cart & Checkout flow
- [x] Order management across all dashboards
- [x] Collections system
- [x] Design system (Warm Luxury + GSAP animations)
### Phase 2: Commerce Hardening (Recommended Next)
- [ ] **Payment integration** (Razorpay/Stripe) — most critical gap
- [ ] **Image upload** via Supabase Storage
- [ ] **Stock validation** at checkout
- [ ] **Email notifications** (order confirmations, status updates, application results)
- [ ] **Payout automation** (UPI disbursement via partner API)
- [ ] **Inventory decrement** on order placement
### Phase 3: Growth & Engagement
- [ ] Creator analytics dashboard (views, conversions, top products)
- [ ] Brand analytics (which creators drive most sales)
- [ ] Customer accounts & order history
- [ ] Wishlist functionality
- [ ] Product reviews & ratings
- [ ] Social sharing UX
- [ ] Referral / affiliate tracking
### Phase 4: Scale & Platform
- [ ] SSR/SSG for SEO (Next.js migration or Vite SSR)
- [ ] Server-side search (Algolia / Supabase full-text)
- [ ] Mobile app (React Native)
- [ ] Multi-language / i18n support
- [ ] Advanced admin reporting & exports
- [ ] Webhook integrations for brands
- [ ] API for external brand catalog sync
---
> *This PRD is auto-generated from the LovedBy codebase and reflects the application as built. It should be maintained as a living document alongside feature development.*
**GitHub**:<https://github.com/HammerLynch/MSDS6306_Case_Study_2>
*Company Name : SK C&C*
Reference for building PL/SQL or Scala ETL pipelines. Types use PostgreSQL names as emitted by Diesel.
This document describes how to use the analytics system in the application.