saas-architect

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SaaS Architect - Next.js + Supabase Edition

SaaS架构师 - Next.js + Supabase 专属版

Purpose

核心用途

This skill transforms SaaS ideas into executable technical architectures optimized for Next.js 15 + Supabase stack. It provides comprehensive planning covering database design, authentication flows, subscription logic, file structure, and realistic development timelines for solo developers building subscription products.
本工具可将SaaS创意转化为针对Next.js 15 + Supabase技术栈优化的可执行技术架构。它为独立开发者搭建订阅制产品提供全面规划,涵盖数据库设计、认证流程、订阅逻辑、文件结构以及贴合实际的开发时间表。

Core Philosophy

核心设计理念

1. Subscription-First Architecture

1. 订阅优先架构

  • Design for recurring revenue from day one
  • Plan for multiple pricing tiers
  • Build upgrade/downgrade flows early
  • Consider trial periods and grace periods
  • 从第一天起就为 recurring revenue( recurring revenue保留,或翻译为“ recurring revenue( recurring revenue是 recurring income,不过保留术语?不对,应该翻译为“ recurring revenue( recurring收入”?不,专业术语“ recurring revenue”通常翻译为“ recurring revenue( recurring营收”?不对,直接翻译为“ recurring revenue( recurring收入”?不,应该是“订阅制营收优先”,原句是“Design for recurring revenue from day one”,翻译为“从项目启动就围绕订阅制营收进行设计”。对,这样更通顺:
  • 从项目启动就围绕订阅制营收进行设计
  • 规划多档位定价体系
  • 提前搭建升级/降级流程
  • 考虑试用周期和宽限期

2. Multi-Tenant by Default

2. 默认支持多租户

  • Row Level Security (RLS) is mandatory
  • Organizations/Teams structure built-in
  • User roles and permissions from start
  • Data isolation is non-negotiable
  • 强制启用Row Level Security (RLS)
  • 内置组织/团队结构
  • 从一开始就规划用户角色与权限
  • 数据隔离是硬性要求

3. Next.js 15 + Supabase Optimized

3. 针对Next.js 15 + Supabase优化

  • Use Server Components for data fetching
  • Leverage Server Actions for mutations
  • Utilize Supabase's built-in features (Auth, Storage, Realtime)
  • Minimize custom backend code
  • 使用Server Components进行数据获取
  • 利用Server Actions处理数据变更
  • 充分利用Supabase的内置功能(Auth、Storage、Realtime)
  • 尽量减少自定义后端代码

4. Production-Ready from Start

4. 从起步就面向生产环境

  • Security considerations upfront
  • Scalability patterns built-in
  • Monitoring and error tracking planned
  • Deployment strategy defined
  • 提前考虑安全因素
  • 内置可扩展性模式
  • 规划监控与错误追踪方案
  • 明确部署策略

How This Skill Works

工具工作流程

Phase 1: SaaS Product Definition

阶段1:SaaS产品定义

1.1 Core Value Proposition

1.1 核心价值主张

markdown
**Product Name:** [Name]
**One-Line Pitch:** [What it does in one sentence]
**Target Market:** [Who pays for this]
**Primary Use Case:** [Main problem solved]
**Success Metric:** [How you measure value]
markdown
**产品名称:** [名称]
**一句话定位:** [产品核心功能]
**目标市场:** [付费用户群体]
**核心使用场景:** [解决的主要问题]
**成功指标:** [价值衡量标准]

1.2 Revenue Model

1.2 营收模式

markdown
**Pricing Strategy:** [Freemium / Trial / Pay-to-start]
**Tiers:** [How many pricing tiers]
**Key Differentiators:** [What makes higher tiers worth it]
**Billing Cycle:** [Monthly / Annual / Both]
Example (Project Management SaaS):
markdown
**Product Name:** TaskFlow
**One-Line Pitch:** Project management for distributed teams with AI-powered task prioritization
**Target Market:** Remote teams, 10-50 employees, tech companies
**Primary Use Case:** Coordinate async work across timezones
**Success Metric:** Teams complete 30% more tasks on time

**Pricing Strategy:** Freemium with 14-day trial on paid plans
**Tiers:** 
  - Free: 1 project, 5 users, basic features
  - Pro ($29/mo): Unlimited projects, 25 users, AI features
  - Enterprise ($99/mo): Unlimited users, advanced integrations, priority support
**Key Differentiators:** 
  - Pro: AI task prioritization, integrations
  - Enterprise: SSO, custom workflows, dedicated support
**Billing Cycle:** Monthly + Annual (2 months free)
markdown
**定价策略:** [免费增值/试用/付费启动]
**档位:** [定价档位数量]
**核心差异点:** [高端档位的价值所在]
**计费周期:** [月度/年度/两者兼具]
示例(项目管理SaaS):
markdown
**产品名称:** TaskFlow
**一句话定位:** 为分布式团队打造的AI驱动任务优先级排序项目管理工具
**目标市场:** 远程团队,10-50人规模,科技公司
**核心使用场景:** 跨时区协调异步工作
**成功指标:** 团队按时完成任务的比例提升30%

**定价策略:** 免费增值模式,付费方案提供14天试用
**档位:** 
  - 免费版:1个项目,5名用户,基础功能
  - 专业版(29美元/月):无限项目,25名用户,AI功能
  - 企业版(99美元/月):无限用户,高级集成,优先支持
**核心差异点:** 
  - 专业版:AI任务优先级排序、第三方集成
  - 企业版:SSO、自定义工作流、专属支持
**计费周期:** 月度 + 年度(年付享2个月免费)

Phase 2: Technical Architecture Planning

阶段2:技术架构规划

2.1 Database Schema Design

2.1 数据库架构设计

The skill generates complete PostgreSQL schemas with RLS policies:
Core Tables for Every SaaS:
sql
-- ============================================
-- USERS & AUTHENTICATION
-- ============================================
-- Note: Supabase Auth handles auth.users table
-- We extend it with profiles

CREATE TABLE profiles (
  id UUID REFERENCES auth.users PRIMARY KEY,
  email TEXT NOT NULL,
  full_name TEXT,
  avatar_url TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- RLS Policies
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own profile"
  ON profiles FOR SELECT
  USING (auth.uid() = id);

CREATE POLICY "Users can update own profile"
  ON profiles FOR UPDATE
  USING (auth.uid() = id);

-- ============================================
-- ORGANIZATIONS (Multi-Tenant Core)
-- ============================================
CREATE TABLE organizations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name TEXT NOT NULL,
  slug TEXT UNIQUE NOT NULL,
  logo_url TEXT,
  subscription_tier TEXT DEFAULT 'free',
  subscription_status TEXT DEFAULT 'active',
  trial_ends_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;

-- ============================================
-- ORGANIZATION MEMBERS (Team Management)
-- ============================================
CREATE TYPE member_role AS ENUM ('owner', 'admin', 'member');

CREATE TABLE organization_members (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  role member_role DEFAULT 'member',
  invited_by UUID REFERENCES auth.users(id),
  joined_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(organization_id, user_id)
);

ALTER TABLE organization_members ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Members can view own org members"
  ON organization_members FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

-- ============================================
-- STRIPE INTEGRATION (Subscriptions)
-- ============================================
CREATE TABLE customers (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  stripe_customer_id TEXT UNIQUE,
  email TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE products (
  id TEXT PRIMARY KEY, -- Stripe product ID
  active BOOLEAN DEFAULT true,
  name TEXT NOT NULL,
  description TEXT,
  image TEXT,
  metadata JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE prices (
  id TEXT PRIMARY KEY, -- Stripe price ID
  product_id TEXT REFERENCES products(id),
  active BOOLEAN DEFAULT true,
  currency TEXT DEFAULT 'usd',
  type TEXT CHECK (type IN ('one_time', 'recurring')),
  unit_amount BIGINT,
  interval TEXT CHECK (interval IN ('day', 'week', 'month', 'year')),
  interval_count INTEGER,
  trial_period_days INTEGER,
  metadata JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE subscriptions (
  id TEXT PRIMARY KEY, -- Stripe subscription ID
  organization_id UUID REFERENCES organizations(id),
  customer_id TEXT REFERENCES customers(stripe_customer_id),
  status TEXT NOT NULL,
  price_id TEXT REFERENCES prices(id),
  quantity INTEGER,
  cancel_at_period_end BOOLEAN DEFAULT false,
  current_period_start TIMESTAMPTZ,
  current_period_end TIMESTAMPTZ,
  trial_start TIMESTAMPTZ,
  trial_end TIMESTAMPTZ,
  canceled_at TIMESTAMPTZ,
  ended_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- RLS for subscription data
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
ALTER TABLE subscriptions ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org owners can view own subscription"
  ON subscriptions FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid() AND role IN ('owner', 'admin')
    )
  );

-- ============================================
-- FEATURE-SPECIFIC TABLES
-- ============================================
-- This section is customized based on your SaaS features
-- Example: Project Management SaaS

CREATE TABLE projects (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  description TEXT,
  status TEXT DEFAULT 'active',
  created_by UUID REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org members can view org projects"
  ON projects FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

CREATE POLICY "Org members can create projects"
  ON projects FOR INSERT
  WITH CHECK (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

CREATE TABLE tasks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  project_id UUID REFERENCES projects(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  description TEXT,
  status TEXT DEFAULT 'todo',
  priority TEXT DEFAULT 'medium',
  assigned_to UUID REFERENCES auth.users(id),
  due_date TIMESTAMPTZ,
  created_by UUID REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org members can view org tasks"
  ON tasks FOR SELECT
  USING (
    project_id IN (
      SELECT id FROM projects 
      WHERE organization_id IN (
        SELECT organization_id FROM organization_members 
        WHERE user_id = auth.uid()
      )
    )
  );
本工具会生成包含RLS策略的完整PostgreSQL架构:
所有SaaS通用的核心表:
sql
-- ============================================
-- 用户与认证
-- ============================================
-- 注意:Supabase Auth 负责 auth.users 表
-- 我们通过profiles表扩展用户信息

CREATE TABLE profiles (
  id UUID REFERENCES auth.users PRIMARY KEY,
  email TEXT NOT NULL,
  full_name TEXT,
  avatar_url TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- RLS 策略
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own profile"
  ON profiles FOR SELECT
  USING (auth.uid() = id);

CREATE POLICY "Users can update own profile"
  ON profiles FOR UPDATE
  USING (auth.uid() = id);

-- ============================================
-- 组织(多租户核心)
-- ============================================
CREATE TABLE organizations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name TEXT NOT NULL,
  slug TEXT UNIQUE NOT NULL,
  logo_url TEXT,
  subscription_tier TEXT DEFAULT 'free',
  subscription_status TEXT DEFAULT 'active',
  trial_ends_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;

-- ============================================
-- 组织成员(团队管理)
-- ============================================
CREATE TYPE member_role AS ENUM ('owner', 'admin', 'member');

CREATE TABLE organization_members (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  role member_role DEFAULT 'member',
  invited_by UUID REFERENCES auth.users(id),
  joined_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(organization_id, user_id)
);

ALTER TABLE organization_members ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Members can view own org members"
  ON organization_members FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

-- ============================================
-- Stripe集成(订阅管理)
-- ============================================
CREATE TABLE customers (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  stripe_customer_id TEXT UNIQUE,
  email TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE products (
  id TEXT PRIMARY KEY, -- Stripe产品ID
  active BOOLEAN DEFAULT true,
  name TEXT NOT NULL,
  description TEXT,
  image TEXT,
  metadata JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE prices (
  id TEXT PRIMARY KEY, -- Stripe价格ID
  product_id TEXT REFERENCES products(id),
  active BOOLEAN DEFAULT true,
  currency TEXT DEFAULT 'usd',
  type TEXT CHECK (type IN ('one_time', 'recurring')),
  unit_amount BIGINT,
  interval TEXT CHECK (interval IN ('day', 'week', 'month', 'year')),
  interval_count INTEGER,
  trial_period_days INTEGER,
  metadata JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE subscriptions (
  id TEXT PRIMARY KEY, -- Stripe订阅ID
  organization_id UUID REFERENCES organizations(id),
  customer_id TEXT REFERENCES customers(stripe_customer_id),
  status TEXT NOT NULL,
  price_id TEXT REFERENCES prices(id),
  quantity INTEGER,
  cancel_at_period_end BOOLEAN DEFAULT false,
  current_period_start TIMESTAMPTZ,
  current_period_end TIMESTAMPTZ,
  trial_start TIMESTAMPTZ,
  trial_end TIMESTAMPTZ,
  canceled_at TIMESTAMPTZ,
  ended_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 订阅数据的RLS策略
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
ALTER TABLE subscriptions ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org owners can view own subscription"
  ON subscriptions FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid() AND role IN ('owner', 'admin')
    )
  );

-- ============================================
-- 功能特定表
-- ============================================
-- 本部分会根据你的SaaS功能进行定制
-- 示例:项目管理SaaS

CREATE TABLE projects (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  description TEXT,
  status TEXT DEFAULT 'active',
  created_by UUID REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org members can view org projects"
  ON projects FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

CREATE POLICY "Org members can create projects"
  ON projects FOR INSERT
  WITH CHECK (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

CREATE TABLE tasks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  project_id UUID REFERENCES projects(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  description TEXT,
  status TEXT DEFAULT 'todo',
  priority TEXT DEFAULT 'medium',
  assigned_to UUID REFERENCES auth.users(id),
  due_date TIMESTAMPTZ,
  created_by UUID REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Org members can view org tasks"
  ON tasks FOR SELECT
  USING (
    project_id IN (
      SELECT id FROM projects 
      WHERE organization_id IN (
        SELECT organization_id FROM organization_members 
        WHERE user_id = auth.uid()
      )
    )
  );

2.2 Next.js File Structure

2.2 Next.js文件结构

The skill generates production-ready file structures:
your-saas-app/
├── app/
│   ├── (auth)/                          # Auth layout group
│   │   ├── login/
│   │   │   └── page.tsx                 # Login page
│   │   ├── signup/
│   │   │   └── page.tsx                 # Signup page
│   │   ├── forgot-password/
│   │   │   └── page.tsx
│   │   └── layout.tsx                   # Auth pages layout
│   │
│   ├── (dashboard)/                     # Protected dashboard routes
│   │   ├── layout.tsx                   # Dashboard shell (sidebar, nav)
│   │   ├── page.tsx                     # Dashboard home
│   │   │
│   │   ├── [orgSlug]/                   # Organization-specific routes
│   │   │   ├── projects/
│   │   │   │   ├── page.tsx             # Projects list
│   │   │   │   ├── [id]/
│   │   │   │   │   └── page.tsx         # Single project view
│   │   │   │   └── new/
│   │   │   │       └── page.tsx         # Create project
│   │   │   │
│   │   │   ├── tasks/
│   │   │   │   ├── page.tsx
│   │   │   │   └── [id]/page.tsx
│   │   │   │
│   │   │   ├── team/
│   │   │   │   ├── page.tsx             # Team members
│   │   │   │   └── invite/page.tsx      # Invite flow
│   │   │   │
│   │   │   └── settings/
│   │   │       ├── page.tsx             # Org settings
│   │   │       ├── billing/
│   │   │       │   └── page.tsx         # Subscription management
│   │   │       └── members/
│   │   │           └── page.tsx         # Member management
│   │   │
│   │   └── onboarding/                  # Post-signup onboarding
│   │       ├── page.tsx
│   │       └── create-org/page.tsx
│   │
│   ├── (marketing)/                     # Public pages
│   │   ├── page.tsx                     # Landing page
│   │   ├── pricing/
│   │   │   └── page.tsx                 # Pricing page
│   │   ├── about/
│   │   │   └── page.tsx
│   │   └── layout.tsx                   # Marketing layout
│   │
│   ├── api/                             # API routes
│   │   ├── stripe/
│   │   │   ├── checkout/
│   │   │   │   └── route.ts             # Create checkout session
│   │   │   ├── portal/
│   │   │   │   └── route.ts             # Customer portal
│   │   │   └── webhook/
│   │   │       └── route.ts             # Stripe webhooks
│   │   │
│   │   └── webhooks/
│   │       └── supabase/
│   │           └── route.ts             # Supabase webhooks
│   │
│   ├── globals.css
│   └── layout.tsx                       # Root layout
├── components/
│   ├── ui/                              # shadcn/ui components
│   │   ├── button.tsx
│   │   ├── card.tsx
│   │   ├── dialog.tsx
│   │   ├── dropdown-menu.tsx
│   │   ├── form.tsx
│   │   ├── input.tsx
│   │   ├── table.tsx
│   │   └── ...
│   │
│   ├── layouts/
│   │   ├── dashboard-shell.tsx          # Dashboard wrapper
│   │   ├── marketing-header.tsx
│   │   └── marketing-footer.tsx
│   │
│   ├── auth/
│   │   ├── login-form.tsx
│   │   ├── signup-form.tsx
│   │   └── auth-guard.tsx               # Protected route wrapper
│   │
│   ├── billing/
│   │   ├── pricing-card.tsx
│   │   ├── subscription-status.tsx
│   │   └── usage-meter.tsx
│   │
│   ├── organizations/
│   │   ├── org-switcher.tsx             # Switch between orgs
│   │   ├── org-selector.tsx
│   │   └── invite-member-dialog.tsx
│   │
│   └── features/                        # Feature-specific components
│       ├── projects/
│       │   ├── project-list.tsx
│       │   ├── project-card.tsx
│       │   └── create-project-dialog.tsx
│       └── tasks/
│           ├── task-list.tsx
│           ├── task-card.tsx
│           └── task-form.tsx
├── lib/
│   ├── supabase/
│   │   ├── client.ts                    # Browser client
│   │   ├── server.ts                    # Server client
│   │   ├── middleware.ts                # Auth middleware
│   │   └── types.ts                     # Generated types
│   │
│   ├── stripe/
│   │   ├── client.ts                    # Stripe initialization
│   │   ├── products.ts                  # Product/price helpers
│   │   └── webhooks.ts                  # Webhook handlers
│   │
│   ├── hooks/
│   │   ├── use-user.ts                  # Get current user
│   │   ├── use-organization.ts          # Get current org
│   │   ├── use-subscription.ts          # Get subscription status
│   │   └── use-permissions.ts           # Check user permissions
│   │
│   ├── actions/                         # Server Actions
│   │   ├── auth.actions.ts
│   │   ├── org.actions.ts
│   │   ├── subscription.actions.ts
│   │   └── features/
│   │       ├── projects.actions.ts
│   │       └── tasks.actions.ts
│   │
│   └── utils/
│       ├── permissions.ts               # Permission checking
│       ├── rate-limit.ts                # Rate limiting
│       └── errors.ts                    # Error handling
├── types/
│   ├── database.types.ts                # Generated from Supabase
│   ├── stripe.types.ts
│   └── app.types.ts
├── middleware.ts                        # Next.js middleware (auth)
├── .env.local
├── .env.example
├── next.config.js
├── package.json
├── tailwind.config.ts
└── tsconfig.json
本工具会生成面向生产环境的文件结构:
your-saas-app/
├── app/
│   ├── (auth)/                          # 认证布局组
│   │   ├── login/
│   │   │   └── page.tsx                 # 登录页面
│   │   ├── signup/
│   │   │   └── page.tsx                 # 注册页面
│   │   ├── forgot-password/
│   │   │   └── page.tsx
│   │   └── layout.tsx                   # 认证页面布局
│   │
│   ├── (dashboard)/                     # 受保护的仪表盘路由
│   │   ├── layout.tsx                   # 仪表盘框架(侧边栏、导航)
│   │   ├── page.tsx                     # 仪表盘首页
│   │   │
│   │   ├── [orgSlug]/                   # 组织专属路由
│   │   │   ├── projects/
│   │   │   │   ├── page.tsx             # 项目列表
│   │   │   │   ├── [id]/
│   │   │   │   │   └── page.tsx         # 单个项目视图
│   │   │   │   └── new/
│   │   │   │       └── page.tsx         # 创建项目
│   │   │   │
│   │   │   ├── tasks/
│   │   │   │   ├── page.tsx
│   │   │   │   └── [id]/page.tsx
│   │   │   │
│   │   │   ├── team/
│   │   │   │   ├── page.tsx             # 团队成员
│   │   │   │   └── invite/page.tsx      # 邀请流程
│   │   │   │
│   │   │   └── settings/
│   │   │       ├── page.tsx             # 组织设置
│   │   │       ├── billing/
│   │   │       │   └── page.tsx         # 订阅管理
│   │   │       └── members/
│   │   │           └── page.tsx         # 成员管理
│   │   │
│   │   └── onboarding/                  # 注册后引导流程
│   │       ├── page.tsx
│   │       └── create-org/page.tsx
│   │
│   ├── (marketing)/                     # 公开页面
│   │   ├── page.tsx                     # 着陆页
│   │   ├── pricing/
│   │   │   └── page.tsx                 # 定价页面
│   │   ├── about/
│   │   │   └── page.tsx
│   │   └── layout.tsx                   # 营销页面布局
│   │
│   ├── api/                             # API路由
│   │   ├── stripe/
│   │   │   ├── checkout/
│   │   │   │   └── route.ts             # 创建结账会话
│   │   │   ├── portal/
│   │   │   │   └── route.ts             # 客户门户
│   │   │   └── webhook/
│   │   │       └── route.ts             # Stripe webhook
│   │   │
│   │   └── webhooks/
│   │       └── supabase/
│   │           └── route.ts             # Supabase webhook
│   │
│   ├── globals.css
│   └── layout.tsx                       # 根布局
├── components/
│   ├── ui/                              # shadcn/ui组件
│   │   ├── button.tsx
│   │   ├── card.tsx
│   │   ├── dialog.tsx
│   │   ├── dropdown-menu.tsx
│   │   ├── form.tsx
│   │   ├── input.tsx
│   │   ├── table.tsx
│   │   └── ...
│   │
│   ├── layouts/
│   │   ├── dashboard-shell.tsx          # 仪表盘包装组件
│   │   ├── marketing-header.tsx
│   │   └── marketing-footer.tsx
│   │
│   ├── auth/
│   │   ├── login-form.tsx
│   │   ├── signup-form.tsx
│   │   └── auth-guard.tsx               # 受保护路由包装组件
│   │
│   ├── billing/
│   │   ├── pricing-card.tsx
│   │   ├── subscription-status.tsx
│   │   └── usage-meter.tsx
│   │
│   ├── organizations/
│   │   ├── org-switcher.tsx             # 组织切换器
│   │   ├── org-selector.tsx
│   │   └── invite-member-dialog.tsx
│   │
│   └── features/                        # 功能特定组件
│       ├── projects/
│       │   ├── project-list.tsx
│       │   ├── project-card.tsx
│       │   └── create-project-dialog.tsx
│       └── tasks/
│           ├── task-list.tsx
│           ├── task-card.tsx
│           └── task-form.tsx
├── lib/
│   ├── supabase/
│   │   ├── client.ts                    # 浏览器端客户端
│   │   ├── server.ts                    # 服务端客户端
│   │   ├── middleware.ts                # 认证中间件
│   │   └── types.ts                     # 生成的类型定义
│   │
│   ├── stripe/
│   │   ├── client.ts                    # Stripe初始化
│   │   ├── products.ts                  # 产品/价格工具函数
│   │   └── webhooks.ts                  # Webhook处理函数
│   │
│   ├── hooks/
│   │   ├── use-user.ts                  # 获取当前用户
│   │   ├── use-organization.ts          # 获取当前组织
│   │   ├── use-subscription.ts          # 获取订阅状态
│   │   └── use-permissions.ts           # 检查用户权限
│   │
│   ├── actions/                         # Server Actions
│   │   ├── auth.actions.ts
│   │   ├── org.actions.ts
│   │   ├── subscription.actions.ts
│   │   └── features/
│   │       ├── projects.actions.ts
│   │       └── tasks.actions.ts
│   │
│   └── utils/
│       ├── permissions.ts               # 权限检查
│       ├── rate-limit.ts                # 限流
│       └── errors.ts                    # 错误处理
├── types/
│   ├── database.types.ts                # 从Supabase生成
│   ├── stripe.types.ts
│   └── app.types.ts
├── middleware.ts                        # Next.js中间件(认证)
├── .env.local
├── .env.example
├── next.config.js
├── package.json
├── tailwind.config.ts
└── tsconfig.json

Phase 3: Feature Planning & Breakdown

阶段3:功能规划与拆解

The skill breaks down SaaS features into implementable chunks:
本工具会将SaaS功能拆解为可实现的模块:

3.1 Core SaaS Features (Must Have)

3.1 核心SaaS功能(必备)

Authentication & User Management
markdown
undefined
认证与用户管理
markdown
undefined

Auth Flow

认证流程

User Stories:
  • As a user, I can sign up with email/password
  • As a user, I can sign in with OAuth (Google, GitHub)
  • As a user, I can reset my password
  • As a user, I can update my profile
Technical Implementation:
  • Supabase Auth handles all authentication
  • Magic link email for password reset
  • OAuth providers configured in Supabase dashboard
  • Profile updates via Server Actions
Acceptance Criteria:
  • Users can create accounts
  • Email verification works
  • Password reset flow functional
  • OAuth providers work
  • Sessions persist across refreshes
  • Logout clears session
Time Estimate: 2-3 days

**Organization Management**
```markdown
用户故事:
  • 作为用户,我可以通过邮箱/密码注册
  • 作为用户,我可以通过OAuth(Google、GitHub)登录
  • 作为用户,我可以重置密码
  • 作为用户,我可以更新个人资料
技术实现:
  • Supabase Auth处理所有认证逻辑
  • 魔法链接邮箱用于密码重置
  • 在Supabase控制台配置OAuth提供商
  • 通过Server Actions更新个人资料
验收标准:
  • 用户可以创建账户
  • 邮箱验证功能正常
  • 密码重置流程可用
  • OAuth提供商正常工作
  • 会话在页面刷新后保持
  • 登出会清除会话
时间预估: 2-3天

**组织管理**
```markdown

Multi-Tenant Organizations

多租户组织

User Stories:
  • As a user, I can create an organization
  • As an owner, I can invite team members
  • As a member, I can accept invitations
  • As an owner, I can manage member roles
  • As a user, I can switch between organizations
Technical Implementation:
  • Organizations table with RLS
  • Invitation system via email
  • Role-based access control (owner, admin, member)
  • Organization switcher component
  • Invites expire after 7 days
Acceptance Criteria:
  • Users can create orgs with unique slugs
  • Owners can invite via email
  • Invites create pending records
  • Members can accept/decline
  • Role changes reflect immediately
  • Users can switch orgs via dropdown
Time Estimate: 3-4 days

**Subscription & Billing**
```markdown
用户故事:
  • 作为用户,我可以创建组织
  • 作为所有者,我可以邀请团队成员
  • 作为成员,我可以接受邀请
  • 作为所有者,我可以管理成员角色
  • 作为用户,我可以在不同组织间切换
技术实现:
  • 带RLS策略的组织表
  • 基于邮箱的邀请系统
  • 基于角色的访问控制(所有者、管理员、成员)
  • 组织切换器组件
  • 邀请7天后过期
验收标准:
  • 用户可以创建带唯一slug的组织
  • 所有者可以通过邮箱发送邀请
  • 邀请会创建待处理记录
  • 成员可以接受/拒绝邀请
  • 角色变更立即生效
  • 用户可以通过下拉菜单切换组织
时间预估: 3-4天

**订阅与计费**
```markdown

Stripe Subscription Flow

Stripe订阅流程

User Stories:
  • As a user, I can view pricing plans
  • As an org owner, I can subscribe to a plan
  • As an org owner, I can upgrade/downgrade
  • As an org owner, I can manage billing
  • As an org owner, I can cancel subscription
Technical Implementation:
  • Stripe Checkout for subscriptions
  • Webhook handler for subscription events
  • Customer Portal for self-service billing
  • Trial period (14 days)
  • Graceful downgrade handling
Acceptance Criteria:
  • Pricing page shows all plans
  • Checkout flow works end-to-end
  • Webhooks update subscription status
  • Features respect subscription tier
  • Portal allows plan changes
  • Cancellation handles end of period
Time Estimate: 4-5 days
undefined
用户故事:
  • 作为用户,我可以查看定价方案
  • 作为组织所有者,我可以订阅方案
  • 作为组织所有者,我可以升级/降级订阅
  • 作为组织所有者,我可以管理计费信息
  • 作为组织所有者,我可以取消订阅
技术实现:
  • 使用Stripe Checkout处理订阅
  • 处理订阅事件的Webhook
  • 用于自助计费的客户门户
  • 14天试用周期
  • 平滑的降级处理
验收标准:
  • 定价页面展示所有方案
  • 结账流程端到端可用
  • Webhook会更新订阅状态
  • 功能会根据订阅档位进行限制
  • 门户支持方案变更
  • 取消订阅会在周期结束时生效
时间预估: 4-5天
undefined

3.2 Feature-Specific Planning

3.2 功能特定规划

The skill generates custom feature breakdowns based on your SaaS:
Example: Project Management Features
markdown
undefined
本工具会根据你的SaaS生成定制化的功能拆解:
示例:项目管理功能
markdown
undefined

Projects Feature

项目功能

User Stories:
  • As a member, I can view all org projects
  • As a member, I can create new projects
  • As a member, I can update project details
  • As an admin, I can archive projects
Database:
  • projects
    table with org relationship
  • RLS policies for org-based access
Components:
  • ProjectList (with search/filter)
  • ProjectCard (preview)
  • CreateProjectDialog (form)
  • ProjectSettings (edit)
API:
  • GET /api/projects?orgId=xxx
  • POST /api/projects
  • PATCH /api/projects/:id
  • DELETE /api/projects/:id
Time Estimate: 3 days
用户故事:
  • 作为成员,我可以查看组织的所有项目
  • 作为成员,我可以创建新项目
  • 作为成员,我可以更新项目详情
  • 作为管理员,我可以归档项目
数据库:
  • 与组织关联的
    projects
  • 基于组织访问的RLS策略
组件:
  • ProjectList(带搜索/过滤)
  • ProjectCard(预览)
  • CreateProjectDialog(表单)
  • ProjectSettings(编辑)
API:
  • GET /api/projects?orgId=xxx
  • POST /api/projects
  • PATCH /api/projects/:id
  • DELETE /api/projects/:id
时间预估: 3天

Tasks Feature

任务功能

User Stories:
  • As a member, I can create tasks in projects
  • As a member, I can assign tasks
  • As an assignee, I can update task status
  • As a member, I can set due dates
Database:
  • tasks
    table with project relationship
  • Status enum (todo, in_progress, done)
  • Priority enum (low, medium, high)
Components:
  • TaskList (kanban or table view)
  • TaskCard (draggable)
  • CreateTaskDialog (form)
  • TaskDetailView (modal)
Time Estimate: 3-4 days
undefined
用户故事:
  • 作为成员,我可以在项目中创建任务
  • 作为成员,我可以分配任务
  • 作为被分配人,我可以更新任务状态
  • 作为成员,我可以设置截止日期
数据库:
  • 与项目关联的
    tasks
  • 状态枚举(todo, in_progress, done)
  • 优先级枚举(low, medium, high)
组件:
  • TaskList(看板或表格视图)
  • TaskCard(可拖拽)
  • CreateTaskDialog(表单)
  • TaskDetailView(模态框)
时间预估: 3-4天
undefined

Phase 4: Development Roadmap

阶段4:开发路线图

The skill generates realistic week-by-week plans:
本工具会生成贴合实际的按周规划:

Week 1: Foundation & Auth

第1周:基础架构与认证

markdown
undefined
markdown
undefined

Days 1-2: Project Setup

第1-2天:项目搭建

Tasks:
  • Create Next.js 15 project with TypeScript
  • Install dependencies (Supabase, Stripe, shadcn/ui, Zod)
  • Set up Supabase project
  • Configure environment variables
  • Set up database schema (run SQL)
  • Configure RLS policies
  • Generate TypeScript types from database
Deliverable: Empty project with database ready
任务:
  • 创建带TypeScript的Next.js 15项目
  • 安装依赖(Supabase、Stripe、shadcn/ui、Zod)
  • 搭建Supabase项目
  • 配置环境变量
  • 搭建数据库架构(执行SQL)
  • 配置RLS策略
  • 从数据库生成TypeScript类型定义
交付物: 数据库就绪的空项目

Days 3-4: Authentication

第3-4天:认证功能

Tasks:
  • Implement Supabase Auth
  • Create login/signup pages
  • Add OAuth providers (Google, GitHub)
  • Build auth middleware
  • Create protected route wrapper
  • Add password reset flow
  • Style auth pages with shadcn/ui
Deliverable: Working authentication system
任务:
  • 实现Supabase Auth
  • 创建登录/注册页面
  • 添加OAuth提供商(Google、GitHub)
  • 搭建认证中间件
  • 创建受保护路由包装组件
  • 添加密码重置流程
  • 使用shadcn/ui美化认证页面
交付物: 可用的认证系统

Day 5: User Profiles

第5天:用户资料

Tasks:
  • Create profile page
  • Implement profile update form
  • Add avatar upload (Supabase Storage)
  • Build user settings page
Deliverable: Users can manage profiles
任务:
  • 创建个人资料页面
  • 实现个人资料更新表单
  • 添加头像上传(Supabase Storage)
  • 搭建用户设置页面
交付物: 用户可以管理个人资料

Weekend: Buffer

周末:缓冲时间

  • Fix any blocking issues
  • Test auth flows
  • Start organization setup
undefined
  • 修复所有阻塞问题
  • 测试认证流程
  • 开始组织功能的搭建
undefined

Week 2: Organizations & Teams

第2周:组织与团队

markdown
undefined
markdown
undefined

Days 1-2: Organization Core

第1-2天:组织核心功能

Tasks:
  • Create org creation flow
  • Build org switcher component
  • Implement org slug validation
  • Add org settings page
  • Create org context/provider
Deliverable: Organizations functional
任务:
  • 创建组织创建流程
  • 搭建组织切换器组件
  • 实现组织slug验证
  • 添加组织设置页面
  • 创建组织上下文/提供者
交付物: 组织功能可用

Days 3-4: Team Management

第3-4天:团队管理

Tasks:
  • Build invitation system
  • Create invite email templates
  • Implement role management
  • Add member list page
  • Build invite acceptance flow
Deliverable: Team collaboration works
任务:
  • 搭建邀请系统
  • 创建邀请邮件模板
  • 实现角色管理
  • 添加成员列表页面
  • 搭建邀请接受流程
交付物: 团队协作功能可用

Day 5: Polish

第5天:优化

Tasks:
  • Add loading states
  • Improve error handling
  • Add toast notifications
  • Test org workflows
Weekend: Integration testing
undefined
任务:
  • 添加加载状态
  • 改进错误处理
  • 添加提示通知
  • 测试组织工作流
周末: 集成测试
undefined

Week 3: Stripe Integration

第3周:Stripe集成

markdown
undefined
markdown
undefined

Days 1-2: Stripe Setup

第1-2天:Stripe搭建

Tasks:
  • Set up Stripe account
  • Create products and prices
  • Implement webhook endpoint
  • Test webhook locally (Stripe CLI)
  • Add webhook handlers for key events
Deliverable: Stripe connected
任务:
  • 搭建Stripe账户
  • 创建产品与价格
  • 实现Webhook端点
  • 本地测试Webhook(Stripe CLI)
  • 为关键事件添加Webhook处理函数
交付物: Stripe已连接

Days 3-4: Subscription Flow

第3-4天:订阅流程

Tasks:
  • Build pricing page
  • Implement checkout flow
  • Create success/cancel pages
  • Add subscription status indicator
  • Implement Customer Portal link
Deliverable: Subscriptions work end-to-end
任务:
  • 搭建定价页面
  • 实现结账流程
  • 创建成功/取消页面
  • 添加订阅状态指示器
  • 实现客户门户链接
交付物: 订阅流程端到端可用

Day 5: Feature Gates

第5天:功能限制

Tasks:
  • Add subscription checking middleware
  • Implement usage limits per tier
  • Build upgrade prompts
  • Add billing page to dashboard
Weekend: Test all subscription scenarios
undefined
任务:
  • 添加订阅检查中间件
  • 实现按档位的使用限制
  • 搭建升级提示
  • 在仪表盘中添加计费页面
周末: 测试所有订阅场景
undefined

Week 4: Core Features

第4周:核心功能

markdown
undefined
markdown
undefined

Days 1-3: Primary Feature (e.g., Projects)

第1-3天:主要功能(如:项目)

Tasks:
  • Build CRUD operations
  • Create list/detail views
  • Add search and filtering
  • Implement Server Actions
  • Add optimistic updates
Deliverable: Primary feature functional
任务:
  • 搭建CRUD操作
  • 创建列表/详情视图
  • 添加搜索与过滤
  • 实现Server Actions
  • 添加乐观更新
交付物: 主要功能可用

Days 4-5: Secondary Feature (e.g., Tasks)

第4-5天:次要功能(如:任务)

Tasks:
  • Build basic CRUD
  • Create list view
  • Add quick actions
  • Implement status updates
Weekend: Feature testing and polish
undefined
任务:
  • 搭建基础CRUD
  • 创建列表视图
  • 添加快速操作
  • 实现状态更新
周末: 功能测试与优化
undefined

Week 5: Polish & Launch Prep

第5周:优化与上线准备

markdown
undefined
markdown
undefined

Days 1-2: UX Polish

第1-2天:用户体验优化

Tasks:
  • Add loading skeletons
  • Improve error messages
  • Add empty states
  • Implement toast notifications
  • Add confirmation dialogs
任务:
  • 添加加载骨架屏
  • 改进错误提示
  • 添加空状态
  • 实现提示通知
  • 添加确认对话框

Days 3-4: Testing & Bugs

第3-4天:测试与修复

Tasks:
  • Test all user flows
  • Fix critical bugs
  • Test mobile responsiveness
  • Check cross-browser compatibility
任务:
  • 测试所有用户流程
  • 修复关键bug
  • 测试移动端响应性
  • 检查跨浏览器兼容性

Day 5: Deploy

第5天:部署

Tasks:
  • Set up Vercel project
  • Configure production environment variables
  • Set up Stripe webhook in production
  • Deploy to production
  • Test production deployment
Weekend: Monitor, fix critical issues
undefined
任务:
  • 搭建Vercel项目
  • 配置生产环境变量
  • 在生产环境中设置Stripe Webhook
  • 部署到生产环境
  • 测试生产部署
周末: 监控并修复关键问题
undefined

Phase 5: Security & Best Practices

阶段5:安全与最佳实践

The skill enforces security patterns:
本工具会强制执行安全模式:

5.1 Row Level Security (RLS) Patterns

5.1 行级安全(RLS)模式

sql
-- Pattern 1: User owns resource
CREATE POLICY "Users can only access own data"
  ON table_name FOR ALL
  USING (user_id = auth.uid());

-- Pattern 2: Org member access
CREATE POLICY "Org members can access org data"
  ON table_name FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

-- Pattern 3: Role-based access
CREATE POLICY "Only admins can delete"
  ON table_name FOR DELETE
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid() 
      AND role IN ('owner', 'admin')
    )
  );

-- Pattern 4: Resource creator can update
CREATE POLICY "Creator can update"
  ON table_name FOR UPDATE
  USING (created_by = auth.uid());
sql
-- 模式1:用户拥有资源
CREATE POLICY "Users can only access own data"
  ON table_name FOR ALL
  USING (user_id = auth.uid());

-- 模式2:组织成员访问
CREATE POLICY "Org members can access org data"
  ON table_name FOR SELECT
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid()
    )
  );

-- 模式3:基于角色的访问
CREATE POLICY "Only admins can delete"
  ON table_name FOR DELETE
  USING (
    organization_id IN (
      SELECT organization_id FROM organization_members 
      WHERE user_id = auth.uid() 
      AND role IN ('owner', 'admin')
    )
  );

-- 模式4:资源创建者可更新
CREATE POLICY "Creator can update"
  ON table_name FOR UPDATE
  USING (created_by = auth.uid());

5.2 Server Action Security

5.2 Server Action安全

typescript
// lib/actions/secure-action.ts
import { createClient } from '@/lib/supabase/server';
import { redirect } from 'next/navigation';

export async function secureAction(
  handler: (userId: string, orgId: string) => Promise<any>
) {
  const supabase = await createClient();
  
  // 1. Verify authentication
  const { data: { user }, error } = await supabase.auth.getUser();
  
  if (error || !user) {
    redirect('/login');
  }
  
  // 2. Get current organization
  const { data: membership } = await supabase
    .from('organization_members')
    .select('organization_id')
    .eq('user_id', user.id)
    .single();
    
  if (!membership) {
    throw new Error('No organization access');
  }
  
  // 3. Execute handler with verified context
  return handler(user.id, membership.organization_id);
}

// Usage in Server Actions
export async function createProject(formData: FormData) {
  'use server';
  
  return secureAction(async (userId, orgId) => {
    const name = formData.get('name') as string;
    
    // Validation
    if (!name || name.length < 3) {
      return { error: 'Name must be at least 3 characters' };
    }
    
    // Database operation (RLS will further verify access)
    const supabase = await createClient();
    const { data, error } = await supabase
      .from('projects')
      .insert({
        name,
        organization_id: orgId,
        created_by: userId
      })
      .select()
      .single();
      
    if (error) {
      return { error: error.message };
    }
    
    return { data };
  });
}
typescript
// lib/actions/secure-action.ts
import { createClient } from '@/lib/supabase/server';
import { redirect } from 'next/navigation';

export async function secureAction(
  handler: (userId: string, orgId: string) => Promise<any>
) {
  const supabase = await createClient();
  
  // 1. 验证认证状态
  const { data: { user }, error } = await supabase.auth.getUser();
  
  if (error || !user) {
    redirect('/login');
  }
  
  // 2. 获取当前组织
  const { data: membership } = await supabase
    .from('organization_members')
    .select('organization_id')
    .eq('user_id', user.id)
    .single();
    
  if (!membership) {
    throw new Error('无组织访问权限');
  }
  
  // 3. 使用已验证的上下文执行处理函数
  return handler(user.id, membership.organization_id);
}

// 在Server Actions中使用
export async function createProject(formData: FormData) {
  'use server';
  
  return secureAction(async (userId, orgId) => {
    const name = formData.get('name') as string;
    
    // 验证
    if (!name || name.length < 3) {
      return { error: '名称至少需要3个字符' };
    }
    
    // 数据库操作(RLS会进一步验证访问权限)
    const supabase = await createClient();
    const { data, error } = await supabase
      .from('projects')
      .insert({
        name,
        organization_id: orgId,
        created_by: userId
      })
      .select()
      .single();
      
    if (error) {
      return { error: error.message };
    }
    
    return { data };
  });
}

5.3 API Route Security

5.3 API路由安全

typescript
// app/api/stripe/webhook/route.ts
import { headers } from 'next/headers';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(req: Request) {
  const body = await req.text();
  const signature = headers().get('stripe-signature');

  if (!signature) {
    return new Response('No signature', { status: 400 });
  }

  try {
    // Verify webhook signature
    const event = stripe.webhooks.constructEvent(
      body,
      signature,
      webhookSecret
    );

    // Handle different events
    switch (event.type) {
      case 'checkout.session.completed':
        await handleCheckoutComplete(event.data.object);
        break;
      case 'customer.subscription.updated':
        await handleSubscriptionUpdate(event.data.object);
        break;
      case 'customer.subscription.deleted':
        await handleSubscriptionCancel(event.data.object);
        break;
    }

    return new Response(JSON.stringify({ received: true }));
  } catch (err) {
    console.error('Webhook error:', err);
    return new Response('Webhook error', { status: 400 });
  }
}
typescript
// app/api/stripe/webhook/route.ts
import { headers } from 'next/headers';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(req: Request) {
  const body = await req.text();
  const signature = headers().get('stripe-signature');

  if (!signature) {
    return new Response('无签名', { status: 400 });
  }

  try {
    // 验证Webhook签名
    const event = stripe.webhooks.constructEvent(
      body,
      signature,
      webhookSecret
    );

    // 处理不同事件
    switch (event.type) {
      case 'checkout.session.completed':
        await handleCheckoutComplete(event.data.object);
        break;
      case 'customer.subscription.updated':
        await handleSubscriptionUpdate(event.data.object);
        break;
      case 'customer.subscription.deleted':
        await handleSubscriptionCancel(event.data.object);
        break;
    }

    return new Response(JSON.stringify({ received: true }));
  } catch (err) {
    console.error('Webhook错误:', err);
    return new Response('Webhook错误', { status: 400 });
  }
}

Phase 6: Deployment & Monitoring

阶段6:部署与监控

6.1 Environment Variables

6.1 环境变量

bash
undefined
bash
undefined

.env.example

.env.example

Supabase

Supabase

NEXT_PUBLIC_SUPABASE_URL=your-project-url NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
NEXT_PUBLIC_SUPABASE_URL=your-project-url NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

Stripe

Stripe

NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx STRIPE_SECRET_KEY=sk_test_xxx STRIPE_WEBHOOK_SECRET=whsec_xxx
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx STRIPE_SECRET_KEY=sk_test_xxx STRIPE_WEBHOOK_SECRET=whsec_xxx

App

应用

NEXT_PUBLIC_APP_URL=http://localhost:3000 NEXT_PUBLIC_APP_NAME=YourSaaS
NEXT_PUBLIC_APP_URL=http://localhost:3000 NEXT_PUBLIC_APP_NAME=YourSaaS

Email (optional)

邮箱(可选)

RESEND_API_KEY=re_xxx
undefined
RESEND_API_KEY=re_xxx
undefined

6.2 Vercel Deployment Checklist

6.2 Vercel部署检查清单

markdown
undefined
markdown
undefined

Pre-Deploy

部署前

  • All environment variables set in Vercel
  • Supabase RLS policies tested
  • Stripe webhook URL configured for production
  • Production Stripe keys configured
  • Error tracking set up (Sentry)
  • Analytics configured (PostHog, Plausible)
  • 在Vercel中设置所有环境变量
  • 测试Supabase RLS策略
  • 为生产环境配置Stripe Webhook URL
  • 配置生产环境Stripe密钥
  • 搭建错误追踪(Sentry)
  • 配置分析工具(PostHog、Plausible)

Deploy

部署

  • Push to main branch
  • Verify build succeeds
  • Check production URL
  • Test critical flows in production
  • 推送到主分支
  • 验证构建成功
  • 检查生产环境URL
  • 在生产环境中测试关键流程

Post-Deploy

部署后

  • Monitor error rates
  • Check webhook delivery
  • Verify subscription flows
  • Test on mobile devices
undefined
  • 监控错误率
  • 检查Webhook交付情况
  • 验证订阅流程
  • 在移动设备上测试
undefined

Output Format

输出格式

When you request SaaS architecture planning, the skill provides:
markdown
undefined
当你请求SaaS架构规划时,本工具会提供:
markdown
undefined

[Your SaaS Name] - Technical Architecture Document

[你的SaaS名称] - 技术架构文档

Executive Summary

执行摘要

[2-3 paragraphs: what you're building, for whom, tech stack]
[2-3段:你要构建什么,面向谁,技术栈]

Product Overview

产品概述

Name: [Product Name] Target: [Target Audience] Value Prop: [One-liner] Revenue Model: [Pricing strategy]
名称: [产品名称] 目标用户: [目标受众] 价值主张: [一句话定位] 营收模式: [定价策略]

Technical Stack

技术栈

  • Frontend: Next.js 15 (App Router) + TypeScript + Tailwind CSS
  • UI Components: shadcn/ui
  • Backend: Next.js Server Actions + API Routes
  • Database: PostgreSQL (Supabase)
  • Auth: Supabase Auth
  • Payments: Stripe
  • Storage: Supabase Storage
  • Hosting: Vercel
  • Email: Resend (optional)
  • 前端: Next.js 15(App Router) + TypeScript + Tailwind CSS
  • UI组件: shadcn/ui
  • 后端: Next.js Server Actions + API路由
  • 数据库: PostgreSQL(Supabase)
  • 认证: Supabase Auth
  • 支付: Stripe
  • 存储: Supabase Storage
  • 托管: Vercel
  • 邮箱: Resend(可选)

Database Architecture

数据库架构

[Complete SQL schema with RLS policies]
[带RLS策略的完整SQL架构]

File Structure

文件结构

[Full Next.js directory structure]
[完整的Next.js目录结构]

Feature Breakdown

功能拆解

Core SaaS Features (Week 1-3)

核心SaaS功能(第1-3周)

[Authentication, Organizations, Subscriptions]
[认证、组织、订阅]

Product Features (Week 4-6)

产品功能(第4-6周)

[Your specific features broken down]
[你的特定功能拆解]

Development Roadmap

开发路线图

[Week-by-week plan with tasks and deliverables]
[按周规划的任务与交付物]

Security Considerations

安全考虑

[RLS patterns, authentication flows, API security]
[RLS模式、认证流程、API安全]

Deployment Strategy

部署策略

[Vercel setup, environment variables, monitoring]
[Vercel设置、环境变量、监控]

Success Metrics

成功指标

  • Activation: [First meaningful action]
  • Engagement: [Regular usage indicator]
  • Retention: [Return behavior]
  • Revenue: [MRR growth targets]
  • 激活: [首次有意义操作]
  • 参与度: [常规使用指标]
  • 留存: [回访行为]
  • 营收: [MRR增长目标]

Risks & Mitigations

风险与缓解措施

RiskImpactMitigation
[Risk 1][High/Med/Low][How to handle]
风险影响缓解方案
[风险1][高/中/低][应对方法]

Next Steps

下一步行动

  1. [First actionable task]
  2. [Second task]
  3. [Third task]
undefined
  1. [第一个可执行任务]
  2. [第二个任务]
  3. [第三个任务]
undefined

How to Use This Skill

工具使用方法

Basic Usage

基础用法

I need architecture for a SaaS product.

Use saas-architect skill.

Idea: [Your SaaS idea]
Target Users: [Who]
Pricing: [How you'll charge]
我需要为SaaS产品规划架构。

使用saas-architect工具。

创意: [你的SaaS创意]
目标用户: [用户群体]
定价: [计费方式]

Detailed Planning

详细规划

Create complete SaaS architecture plan using saas-architect.

Product: [Detailed description]
Features: [List key features]
Timeline: [Launch target]
Constraints: [Any technical/business constraints]
使用saas-architect创建完整的SaaS架构规划。

产品: [详细描述]
功能: [核心功能列表]
时间线: [上线目标]
约束条件: [技术/业务限制]

Feature-Specific Planning

功能特定规划

I have existing SaaS, need to add [feature].

Use saas-architect to plan:
- Database changes needed
- File structure for feature
- Implementation steps
- Timeline estimate

Existing Stack: Next.js 15 + Supabase
我已有一个SaaS,需要添加[功能]。

使用saas-architect规划:
- 需要的数据库变更
- 功能的文件结构
- 实现步骤
- 时间预估

现有技术栈: Next.js 15 + Supabase

Integration with Development

与开发流程集成

With Claude Code

与Claude Code配合

After generating architecture, use with Claude Code:
Generate starter code for this SaaS architecture:

[Paste architecture document]

Start with:
1. Database schema (run SQL in Supabase)
2. Initial project structure
3. Auth implementation
4. Organization setup
生成架构后,可与Claude Code配合使用:
为这个SaaS架构生成启动代码:

[粘贴架构文档]

从以下部分开始:
1. 数据库架构(在Supabase中执行SQL)
2. 初始项目结构
3. 认证实现
4. 组织设置

With Other Skills

与其他工具配合

Recommended workflow:
  1. idea-validator-pro → Validate market fit
  2. saas-architect → Technical planning
  3. modern-ui-designer → Design system
  4. Claude Code → Implementation
  5. code-quality-guardian → Code review
  6. deployment-automation → Launch
推荐工作流:
  1. idea-validator-pro → 验证市场适配性
  2. saas-architect → 技术规划
  3. modern-ui-designer → 设计系统
  4. Claude Code → 实现
  5. code-quality-guardian → 代码审查
  6. deployment-automation → 上线

Best Practices

最佳实践

DO ✅

建议 ✅

  • Start with Core SaaS Features: Auth, Orgs, Subscriptions first
  • Use RLS Everywhere: Never skip Row Level Security
  • Test Subscriptions Early: Stripe webhooks are critical
  • Plan for Multi-Tenancy: Even if starting single-tenant
  • Document Decisions: Future you will thank you
  • 从核心SaaS功能开始: 先做认证、组织、订阅
  • 全面使用RLS: 绝不跳过行级安全
  • 尽早测试订阅: Stripe Webhook至关重要
  • 规划多租户: 即使从单租户开始
  • 记录决策: 未来的你会感谢现在的自己

DON'T ❌

避免 ❌

  • Skip RLS Policies: Data leaks are catastrophic
  • Hardcode Stripe Keys: Use environment variables
  • Ignore Webhook Testing: Test webhooks locally first
  • Over-Engineer: Start simple, scale later
  • Build Without Auth: Start with authentication
  • 跳过RLS策略: 数据泄露是灾难性的
  • 硬编码Stripe密钥: 使用环境变量
  • 忽略Webhook测试: 先在本地测试Webhook
  • 过度设计: 从简单开始,逐步扩展
  • 无认证就开发: 先搭建认证系统

Common Scenarios

常见场景

Scenario 1: Freemium SaaS

场景1:免费增值SaaS

Challenge: Need free tier with upgrade path
Solution: 
- Free tier with feature limits
- Trial period for paid plans
- Usage tracking in database
- Upgrade prompts in UI
挑战: 需要免费档位和升级路径
解决方案: 
- 带功能限制的免费档位
- 付费方案的试用周期
- 数据库中的使用追踪
- UI中的升级提示

Scenario 2: Team Collaboration

场景2:团队协作

Challenge: Multiple users per organization
Solution:
- Organization-based RLS
- Role-based permissions
- Invitation system
- Activity logging
挑战: 每个组织有多个用户
解决方案:
- 基于组织的RLS
- 基于角色的权限
- 邀请系统
- 活动日志

Scenario 3: Usage-Based Pricing

场景3:基于使用量的定价

Challenge: Charge based on usage, not seats
Solution:
- Usage tracking table
- Metered billing with Stripe
- Usage dashboards
- Overage handling
挑战: 按使用量计费,而非按座位
解决方案:
- 使用量追踪表
- Stripe的计量计费
- 使用量仪表盘
- 超额使用处理

Technical Debt Prevention

技术债务预防

Phase 1 (Weeks 1-2): None Expected

阶段1(第1-2周): 预计无技术债务

Focus on getting foundation right.
专注于搭建正确的基础架构。

Phase 2 (Weeks 3-4): Monitor These

阶段2(第3-4周): 监控以下内容

  • Test coverage (aim for >70% on critical paths)
  • Error handling consistency
  • Loading state patterns
  • 测试覆盖率(关键路径目标>70%)
  • 错误处理一致性
  • 加载状态模式

Phase 3 (Weeks 5-6): Refactor Time

阶段3(第5-6周): 重构时间

  • Extract reusable hooks
  • Consolidate similar components
  • Optimize database queries
  • Add missing indexes
  • 提取可复用的hooks
  • 合并相似组件
  • 优化数据库查询
  • 添加缺失的索引

Launch Checklist

上线检查清单

Pre-Launch (1 Week Before)

上线前1周

  • All core features working
  • Mobile responsive tested
  • Cross-browser tested
  • Payment flow tested end-to-end
  • Error tracking configured
  • Analytics set up
  • Terms of Service ready
  • Privacy Policy ready
  • Support email configured
  • 所有核心功能可用
  • 测试移动端响应性
  • 测试跨浏览器兼容性
  • 端到端测试支付流程
  • 配置错误追踪
  • 设置分析工具
  • 准备服务条款
  • 准备隐私政策
  • 配置支持邮箱

Launch Day

上线日

  • Deploy to production
  • Verify all webhooks working
  • Test signup flow
  • Test subscription flow
  • Monitor error rates
  • Check analytics tracking
  • 部署到生产环境
  • 验证所有Webhook正常工作
  • 测试注册流程
  • 测试订阅流程
  • 监控错误率
  • 检查分析追踪

Post-Launch (First Week)

上线后第一周

  • Daily monitoring
  • Fix critical bugs
  • Gather user feedback
  • Iterate on pain points

  • 每日监控
  • 修复关键bug
  • 收集用户反馈
  • 针对痛点进行迭代

Skill Metadata

工具元数据

Version: 1.0.0
Last Updated: November 2025
Optimized For: Next.js 15, Supabase, Stripe
Target: Solo Developers building SaaS products
Output: Complete technical architecture documentation

Key Insight: Great SaaS architecture isn't about having every feature—it's about building the right foundation that scales. Focus on authentication, multi-tenancy, and subscriptions first. Everything else can iterate.
版本: 1.0.0
最后更新: 2025年11月
优化对象: Next.js 15, Supabase, Stripe
目标用户: 搭建SaaS产品的独立开发者
输出: 完整的技术架构文档

核心见解: 优秀的SaaS架构不在于拥有所有功能,而在于搭建可扩展的正确基础。先专注于认证、多租户和订阅,其他功能可以逐步迭代。