Prompt as Code | GPT Image 2 / 2.5 提示词与案例库,530+ 个案例、20+ 套工业级模板与可复用 Skills,新增 2.5 同提示词对比专区,附完整提示词与生成记录,持续更新。
JavaScript agentsai-image-generationchatgptdsh-plugingpt-image-2image-promptsprompt-as-codeprompt-engineeringskillsworkflow-automation
Add membership and credits foundation
freestyleflyf71c9d68adc2
diff --git a/.env.example b/.env.exampleindex c2091b4..695d4ce 100644--- a/.env.example+++ b/.env.example@@ -5,3 +5,7 @@ VITE_SUPABASE_URL=VITE_SUPABASE_ANON_KEY=SUPABASE_SERVICE_ROLE_KEY=++APP_URL=https://gpt-image2.canghe.ai+STRIPE_SECRET_KEY=+STRIPE_WEBHOOK_SECRET=diff --git a/README.md b/README.mdindex bf74483..cf16743 100644--- a/README.md+++ b/README.md@@ -284,15 +284,22 @@ SUPABASE_SERVICE_ROLE_KEY=CIYUAN_API_KEY=CIYUAN_BASE_URL=https://ciyuan.today+APP_URL=https://gpt-image2.canghe.ai+STRIPE_SECRET_KEY=+STRIPE_WEBHOOK_SECRET=```Setup checklist:- Apply [`supabase/migrations/202605090001_user_credits.sql`](supabase/migrations/202605090001_user_credits.sql) to the Supabase project.+- Apply [`supabase/migrations/20260509090000_membership_billing.sql`](supabase/migrations/20260509090000_membership_billing.sql) to add membership plans, credit packs, Stripe order records, and credit adjustment RPCs.- Add `https://gpt-image2.canghe.ai` and local dev URLs such as `http://127.0.0.1:5173` to Supabase Auth redirect URLs.- Enable Email OTP or magic links in Supabase Auth.- Enable the Google Provider after adding Google OAuth credentials in the Supabase Dashboard.- Keep `SUPABASE_SERVICE_ROLE_KEY` only in server-side environments such as Vercel Environment Variables.+- Configure Stripe Checkout with the webhook URL `https://gpt-image2.canghe.ai/api/billing/webhook`.+- Subscribe the Stripe webhook to `checkout.session.completed`, `invoice.payment_succeeded`, `customer.subscription.updated`, and `customer.subscription.deleted`.+- Keep `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` only in server-side Vercel Environment Variables.<a name="section-gallery"></a>diff --git a/api/_lib/billing.js b/api/_lib/billing.jsnew file mode 100644index 0000000..9cc173d--- /dev/null+++ b/api/_lib/billing.js@@ -0,0 +1,363 @@+import Stripe from 'stripe';++const STRIPE_API_VERSION = '2026-02-25.clover';+const DEFAULT_APP_URL = 'https://gpt-image2.canghe.ai';++let stripeClient;++export function isStripeConfigured() {+ return Boolean(process.env.STRIPE_SECRET_KEY);+}++export function getStripeClient() {+ if (!isStripeConfigured()) return null;+ if (!stripeClient) {+ stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY, {+ apiVersion: STRIPE_API_VERSION+ });+ }+ return stripeClient;+}++export function getAppUrl(req) {+ if (process.env.APP_URL) return process.env.APP_URL.replace(/\/$/, '');+ const host = req?.headers?.['x-forwarded-host'] || req?.headers?.host;+ const protocol = req?.headers?.['x-forwarded-proto'] || 'https';+ return host ? `${protocol}://${host}` : DEFAULT_APP_URL;+}++export async function readJsonBody(req) {+ if (Buffer.isBuffer(req.body)) return JSON.parse(req.body.toString('utf8') || '{}');+ if (req.body && typeof req.body === 'object') return req.body;+ if (typeof req.body === 'string') return JSON.parse(req.body || '{}');++ const chunks = [];+ for await (const chunk of req) {+ chunks.push(chunk);+ }+ const raw = Buffer.concat(chunks).toString('utf8');+ return raw ? JSON.parse(raw) : {};+}++export async function readRawBody(req) {+ if (Buffer.isBuffer(req.body)) return req.body;+ if (typeof req.body === 'string') return Buffer.from(req.body, 'utf8');++ const chunks = [];+ for await (const chunk of req) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ return Buffer.concat(chunks);+}++function normalizeCurrency(value) {+ return String(value || 'usd').toLowerCase();+}++function moneyLabel(amountCents, currency) {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: normalizeCurrency(currency).toUpperCase()+ }).format(Number(amountCents || 0) / 100);+}++export function formatPlan(row) {+ return {+ id: row.id,+ type: 'membership',+ name: {+ en: row.name_en,+ zh: row.name_zh+ },+ description: {+ en: row.description_en,+ zh: row.description_zh+ },+ monthlyCredits: Number(row.monthly_credits || 0),+ amountCents: Number(row.amount_cents || 0),+ currency: normalizeCurrency(row.currency),+ interval: row.interval || 'month',+ priceLabel: moneyLabel(row.amount_cents, row.currency),+ active: Boolean(row.active)+ };+}++export function formatPack(row) {+ return {+ id: row.id,+ type: 'credit_pack',+ name: {+ en: row.name_en,+ zh: row.name_zh+ },+ description: {+ en: row.description_en,+ zh: row.description_zh+ },+ credits: Number(row.credits || 0),+ amountCents: Number(row.amount_cents || 0),+ currency: normalizeCurrency(row.currency),+ priceLabel: moneyLabel(row.amount_cents, row.currency),+ active: Boolean(row.active)+ };+}++export async function getBillingCatalog(client) {+ const [plansResult, packsResult] = await Promise.all([+ client+ .from('membership_plans')+ .select('*')+ .eq('active', true)+ .order('sort_order', { ascending: true }),+ client+ .from('credit_packs')+ .select('*')+ .eq('active', true)+ .order('sort_order', { ascending: true })+ ]);++ if (plansResult.error) throw plansResult.error;+ if (packsResult.error) throw packsResult.error;++ return {+ plans: (plansResult.data || []).map(formatPlan),+ packs: (packsResult.data || []).map(formatPack)+ };+}++export async function getBillingProduct(client, productType, productId) {+ const table = productType === 'membership' ? 'membership_plans' : 'credit_packs';+ const { data, error } = await client+ .from(table)+ .select('*')+ .eq('id', productId)+ .eq('active', true)+ .maybeSingle();++ if (error) throw error;+ if (!data) return null;+ return productType === 'membership' ? formatPlan(data) : formatPack(data);+}++export async function getOrCreateStripeCustomer({ client, stripe, user, profile }) {+ if (profile?.stripeCustomerId) return profile.stripeCustomerId;++ const customer = await stripe.customers.create({+ email: profile?.email || user.email || undefined,+ name: profile?.fullName || undefined,+ metadata: {+ userId: user.id+ }+ });++ const { error } = await client+ .from('profiles')+ .update({ stripe_customer_id: customer.id })+ .eq('id', user.id);++ if (error) throw error;+ return customer.id;+}++export function checkoutLineItem(product) {+ const priceData = {+ currency: product.currency,+ unit_amount: product.amountCents,+ product_data: {+ name: product.name.en,+ description: product.description.en,+ metadata: {+ productType: product.type,+ productId: product.id+ }+ }+ };++ if (product.type === 'membership') {+ priceData.recurring = {+ interval: product.interval || 'month'+ };+ }++ return {+ quantity: 1,+ price_data: priceData+ };+}++export async function createPaymentOrder(client, { userId, product, customerId }) {+ const credits = product.type === 'membership' ? product.monthlyCredits : product.credits;+ const { data, error } = await client+ .from('payment_orders')+ .insert({+ user_id: userId,+ product_type: product.type,+ product_id: product.id,+ status: 'created',+ stripe_customer_id: customerId,+ amount_cents: product.amountCents,+ currency: product.currency,+ credits+ })+ .select('*')+ .single();++ if (error) throw error;+ return data;+}++export async function markOrderCheckoutCreated(client, orderId, session) {+ const { data, error } = await client+ .from('payment_orders')+ .update({+ status: 'checkout_created',+ stripe_session_id: session.id,+ stripe_customer_id: typeof session.customer === 'string' ? session.customer : null,+ stripe_subscription_id: typeof session.subscription === 'string' ? session.subscription : null,+ metadata: {+ checkoutUrl: session.url || ''+ }+ })+ .eq('id', orderId)+ .select('*')+ .single();++ if (error) throw error;+ return data;+}++function stripeTimestampToIso(value) {+ return value ? new Date(value * 1000).toISOString() : null;+}++function normalizeSubscriptionStatus(status) {+ if (['trialing', 'active', 'past_due', 'canceled', 'unpaid'].includes(status)) return status;+ return 'inactive';+}++export async function upsertMembershipFromSubscription(client, subscription, fallback = {}) {+ const userId = subscription.metadata?.userId || fallback.userId;+ const planId = subscription.metadata?.productId || subscription.metadata?.planId || fallback.planId;+ if (!userId || !planId) return null;++ const item = subscription.items?.data?.[0] || {};+ const payload = {+ user_id: userId,+ plan_id: planId,+ status: normalizeSubscriptionStatus(subscription.status),+ stripe_customer_id: typeof subscription.customer === 'string' ? subscription.customer : fallback.customerId || null,+ stripe_subscription_id: subscription.id,+ current_period_start: stripeTimestampToIso(subscription.current_period_start || item.current_period_start),+ current_period_end: stripeTimestampToIso(subscription.current_period_end || item.current_period_end),+ cancel_at_period_end: Boolean(subscription.cancel_at_period_end)+ };++ const { data, error } = await client+ .from('user_memberships')+ .upsert(payload, { onConflict: 'user_id' })+ .select('*')+ .single();++ if (error) throw error;+ return data;+}++async function hasTransactionWithMetadata(client, userId, source, metadata) {+ const { data, error } = await client+ .from('credit_transactions')+ .select('id')+ .eq('user_id', userId)+ .eq('source', source)+ .contains('metadata', metadata)+ .limit(1);++ if (error) throw error;+ return Boolean(data?.length);+}++export async function grantCredits(client, { userId, amount, type, source, referenceId = null, metadata = {} }) {+ const { data, error } = await client.rpc('grant_user_credits', {+ p_user_id: userId,+ p_amount: amount,+ p_type: type,+ p_source: source,+ p_reference_id: referenceId,+ p_metadata: metadata+ });++ if (error) throw error;+ return Array.isArray(data) ? data[0] : data;+}++export async function completeCreditPackOrder(client, session) {+ const { data: order, error } = await client+ .from('payment_orders')+ .select('*')+ .eq('stripe_session_id', session.id)+ .maybeSingle();++ if (error) throw error;+ if (!order || order.status === 'completed') return order || null;+ if (order.product_type !== 'credit_pack') return order;++ await grantCredits(client, {+ userId: order.user_id,+ amount: Number(order.credits || 0),+ type: 'purchase',+ source: 'stripe_checkout',+ referenceId: order.id,+ metadata: {+ stripeSessionId: session.id,+ productId: order.product_id+ }+ });++ const { data, error: updateError } = await client+ .from('payment_orders')+ .update({+ status: 'completed',+ stripe_customer_id: typeof session.customer === 'string' ? session.customer : order.stripe_customer_id,+ completed_at: new Date().toISOString()+ })+ .eq('id', order.id)+ .select('*')+ .single();++ if (updateError) throw updateError;+ return data;+}++export async function grantMembershipCredits(client, { userId, planId, source, metadata, orderId = null }) {+ const { data: plan, error } = await client+ .from('membership_plans')+ .select('*')+ .eq('id', planId)+ .maybeSingle();++ if (error) throw error;+ if (!plan || !plan.active) return null;++ if (await hasTransactionWithMetadata(client, userId, source, metadata)) {+ return null;+ }++ await grantCredits(client, {+ userId,+ amount: Number(plan.monthly_credits || 0),+ type: 'membership_grant',+ source,+ referenceId: orderId,+ metadata: {+ ...metadata,+ planId,+ monthlyCredits: Number(plan.monthly_credits || 0)+ }+ });++ await client+ .from('user_memberships')+ .update({ monthly_credits_granted_at: new Date().toISOString() })+ .eq('user_id', userId);++ return plan;+}diff --git a/api/_lib/supabase.js b/api/_lib/supabase.jsindex 4cea7cb..27961a2 100644--- a/api/_lib/supabase.js+++ b/api/_lib/supabase.js@@ -51,6 +51,30 @@ export function isSuperAdminEmail(email) {return getAdminEmails().includes(String(email).trim().toLowerCase());}+function formatMembership(row) {+ if (!row) return null;+ return {+ id: row.id,+ planId: row.plan_id || '',+ status: row.status || 'inactive',+ isActive: ['trialing', 'active'].includes(row.status),+ currentPeriodEnd: row.current_period_end || '',+ cancelAtPeriodEnd: Boolean(row.cancel_at_period_end),+ monthlyCreditsGrantedAt: row.monthly_credits_granted_at || ''+ };+}++async function getMembershipForUser(client, userId) {+ const { data, error } = await client+ .from('user_memberships')+ .select('id,plan_id,status,current_period_end,cancel_at_period_end,monthly_credits_granted_at')+ .eq('user_id', userId)+ .maybeSingle();++ if (error) throw error;+ return formatMembership(data);+}+function profilePayloadFromUser(user, existingProfile) {const metadata = user.user_metadata || {};const email = String(user.email || existingProfile?.email || '').trim().toLowerCase();@@ -61,22 +85,25 @@ function profilePayloadFromUser(user, existingProfile) {email,full_name: metadata.full_name || metadata.name || existingProfile?.full_name || null,avatar_url: metadata.avatar_url || metadata.picture || existingProfile?.avatar_url || null,+ stripe_customer_id: existingProfile?.stripe_customer_id || null,role: existingProfile?.role === 'super_admin' || desiredRole === 'super_admin' ? 'super_admin' : 'user'};}-export function normalizeProfile(row) {+export function normalizeProfile(row, membership = null) {if (!row) return null;return {id: row.id,email: row.email,fullName: row.full_name || '',avatarUrl: row.avatar_url || '',+ stripeCustomerId: row.stripe_customer_id || '',role: row.role || 'user',isSuperAdmin: row.role === 'super_admin',creditBalance: Number(row.credit_balance || 0),freeGenerationsUsed: Number(row.free_generations_used || 0),freeUsed: Number(row.free_generations_used || 0) >= 1,+ membership,createdAt: row.created_at || '',updatedAt: row.updated_at || ''};@@ -102,7 +129,8 @@ export async function ensureProfileForUser(user) {.single();if (error) throw error;- return normalizeProfile(data);+ const membership = await getMembershipForUser(client, user.id).catch(() => null);+ return normalizeProfile(data, membership);}export async function getProfileById(userId) {@@ -116,7 +144,8 @@ export async function getProfileById(userId) {.maybeSingle();if (error) throw error;- return normalizeProfile(data);+ const membership = await getMembershipForUser(client, userId).catch(() => null);+ return normalizeProfile(data, membership);}export async function getAuthContext(req, options = {}) {diff --git a/api/admin/credits/adjust.js b/api/admin/credits/adjust.jsnew file mode 100644index 0000000..453c201--- /dev/null+++ b/api/admin/credits/adjust.js@@ -0,0 +1,67 @@+import { getAuthContext, getProfileById } from '../../_lib/supabase.js';+import { readJsonBody } from '../../_lib/billing.js';++function json(res, status, payload) {+ res.status(status).json(payload);+}++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ res.setHeader('Allow', 'POST');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ const auth = await getAuthContext(req);+ if (auth.error) {+ return json(res, auth.status || 401, { ok: false, error: auth.error });+ }++ if (!auth.profile?.isSuperAdmin) {+ return json(res, 403, { ok: false, error: 'FORBIDDEN' });+ }++ let body;+ try {+ body = await readJsonBody(req);+ } catch {+ return json(res, 400, { ok: false, error: 'INVALID_CREDIT_ADJUSTMENT' });+ }++ const userId = String(body.userId || '').trim();+ const amount = Number(body.amount);+ const reason = String(body.reason || '').trim().slice(0, 240);+ if (!userId || !Number.isInteger(amount) || amount === 0) {+ return json(res, 400, { ok: false, error: 'INVALID_CREDIT_ADJUSTMENT' });+ }++ try {+ const { error } = await auth.client.rpc('grant_user_credits', {+ p_user_id: userId,+ p_amount: amount,+ p_type: 'adjustment',+ p_source: 'admin_adjustment',+ p_reference_id: null,+ p_metadata: {+ reason,+ adminUserId: auth.user.id+ }+ });++ if (error) throw error;++ const user = await getProfileById(userId);+ return json(res, 200, { ok: true, user });+ } catch (error) {+ const normalizedMessage = String(error?.message || '').toUpperCase();+ if (normalizedMessage.includes('CREDITS_INSUFFICIENT')) {+ return json(res, 400, { ok: false, error: 'CREDITS_INSUFFICIENT' });+ }++ console.warn('Failed to adjust credits', {+ adminUserId: auth.user.id,+ targetUserId: userId,+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'CREDIT_ADJUSTMENT_FAILED' });+ }+}diff --git a/api/admin/users.js b/api/admin/users.jsindex d64bbf5..e478cdb 100644--- a/api/admin/users.js+++ b/api/admin/users.js@@ -14,6 +14,7 @@ function formatAdminUser(row) {creditBalance: Number(row.credit_balance || 0),freeGenerationsUsed: Number(row.free_generations_used || 0),freeUsed: Number(row.free_generations_used || 0) >= 1,+ membership: row.membership || null,createdAt: row.created_at || ''};}@@ -46,8 +47,31 @@ export default async function handler(req, res) {return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });}+ const userIds = (data || []).map((user) => user.id);+ const membershipsByUserId = new Map();+ if (userIds.length) {+ const { data: memberships, error: membershipError } = await auth.client+ .from('user_memberships')+ .select('user_id,plan_id,status,current_period_end,cancel_at_period_end')+ .in('user_id', userIds);++ if (!membershipError) {+ for (const membership of memberships || []) {+ membershipsByUserId.set(membership.user_id, {+ planId: membership.plan_id || '',+ status: membership.status || 'inactive',+ currentPeriodEnd: membership.current_period_end || '',+ cancelAtPeriodEnd: Boolean(membership.cancel_at_period_end)+ });+ }+ }+ }+return json(res, 200, {ok: true,- users: (data || []).map(formatAdminUser)+ users: (data || []).map((user) => formatAdminUser({+ ...user,+ membership: membershipsByUserId.get(user.id) || null+ }))});}diff --git a/api/billing/checkout.js b/api/billing/checkout.jsnew file mode 100644index 0000000..1e67572--- /dev/null+++ b/api/billing/checkout.js@@ -0,0 +1,120 @@+import { getAuthContext, getProfileById, isSupabaseServerConfigured } from '../_lib/supabase.js';+import {+ checkoutLineItem,+ createPaymentOrder,+ getAppUrl,+ getBillingProduct,+ getOrCreateStripeCustomer,+ getStripeClient,+ isStripeConfigured,+ markOrderCheckoutCreated,+ readJsonBody+} from '../_lib/billing.js';++function json(res, status, payload) {+ res.status(status).json(payload);+}++function normalizeProductType(value) {+ if (value === 'membership' || value === 'credit_pack') return value;+ if (value === 'creditPack') return 'credit_pack';+ return '';+}++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ res.setHeader('Allow', 'POST');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ if (!isSupabaseServerConfigured()) {+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });+ }++ if (!isStripeConfigured()) {+ return json(res, 500, { ok: false, error: 'BILLING_NOT_CONFIGURED' });+ }++ const auth = await getAuthContext(req);+ if (auth.error) {+ return json(res, auth.status || 401, {+ ok: false,+ error: auth.error,+ loginRequired: auth.error === 'AUTH_REQUIRED'+ });+ }++ let body;+ try {+ body = await readJsonBody(req);+ } catch {+ return json(res, 400, { ok: false, error: 'INVALID_BILLING_PRODUCT' });+ }++ const productType = normalizeProductType(body.productType || body.type);+ const productId = String(body.productId || body.planId || '').trim();+ if (!productType || !productId) {+ return json(res, 400, { ok: false, error: 'INVALID_BILLING_PRODUCT' });+ }++ try {+ const stripe = getStripeClient();+ const product = await getBillingProduct(auth.client, productType, productId);+ if (!product) {+ return json(res, 404, { ok: false, error: 'BILLING_PRODUCT_NOT_FOUND' });+ }++ const customerId = await getOrCreateStripeCustomer({+ client: auth.client,+ stripe,+ user: auth.user,+ profile: auth.profile+ });+ const refreshedProfile = await getProfileById(auth.user.id);+ const order = await createPaymentOrder(auth.client, {+ userId: auth.user.id,+ product,+ customerId+ });+ const appUrl = getAppUrl(req);+ const metadata = {+ orderId: order.id,+ userId: auth.user.id,+ productType,+ productId+ };++ const sessionPayload = {+ mode: productType === 'membership' ? 'subscription' : 'payment',+ customer: customerId,+ client_reference_id: auth.user.id,+ line_items: [checkoutLineItem(product)],+ success_url: `${appUrl}/?billing=success&session_id={CHECKOUT_SESSION_ID}`,+ cancel_url: `${appUrl}/?billing=cancelled`,+ allow_promotion_codes: true,+ metadata+ };++ if (productType === 'membership') {+ sessionPayload.subscription_data = { metadata };+ } else {+ sessionPayload.payment_intent_data = { metadata };+ }++ const session = await stripe.checkout.sessions.create(sessionPayload);+ const updatedOrder = await markOrderCheckoutCreated(auth.client, order.id, session);++ return json(res, 200, {+ ok: true,+ url: session.url,+ orderId: updatedOrder.id,+ user: refreshedProfile+ });+ } catch (error) {+ console.warn('Failed to create checkout session', {+ userId: auth.user?.id,+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'CHECKOUT_FAILED' });+ }+}diff --git a/api/billing/history.js b/api/billing/history.jsnew file mode 100644index 0000000..5a45bc8--- /dev/null+++ b/api/billing/history.js@@ -0,0 +1,54 @@+import { getAuthContext } from '../_lib/supabase.js';++function json(res, status, payload) {+ res.status(status).json(payload);+}++function formatTransaction(row) {+ return {+ id: row.id,+ amount: Number(row.amount || 0),+ type: row.type || '',+ source: row.source || '',+ metadata: row.metadata || {},+ createdAt: row.created_at || ''+ };+}++export default async function handler(req, res) {+ if (req.method !== 'GET') {+ res.setHeader('Allow', 'GET');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ const auth = await getAuthContext(req);+ if (auth.error) {+ return json(res, auth.status || 401, {+ ok: false,+ error: auth.error,+ loginRequired: auth.error === 'AUTH_REQUIRED'+ });+ }++ try {+ const { data, error } = await auth.client+ .from('credit_transactions')+ .select('id,amount,type,source,metadata,created_at')+ .eq('user_id', auth.user.id)+ .order('created_at', { ascending: false })+ .limit(30);++ if (error) throw error;++ return json(res, 200, {+ ok: true,+ transactions: (data || []).map(formatTransaction)+ });+ } catch (error) {+ console.warn('Failed to load billing history', {+ userId: auth.user?.id,+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'BILLING_HISTORY_FAILED' });+ }+}diff --git a/api/billing/plans.js b/api/billing/plans.jsnew file mode 100644index 0000000..cf8ff18--- /dev/null+++ b/api/billing/plans.js@@ -0,0 +1,38 @@+import { getAuthContext, getProfileById, isSupabaseServerConfigured } from '../_lib/supabase.js';+import { getBillingCatalog, isStripeConfigured } from '../_lib/billing.js';++function json(res, status, payload) {+ res.status(status).json(payload);+}++export default async function handler(req, res) {+ if (req.method !== 'GET') {+ res.setHeader('Allow', 'GET');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ if (!isSupabaseServerConfigured()) {+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });+ }++ const auth = await getAuthContext(req, { allowAnonymous: true });+ if (auth.error) {+ return json(res, auth.status || 401, { ok: false, error: auth.error });+ }++ try {+ const catalog = await getBillingCatalog(auth.client);+ const user = auth.user ? await getProfileById(auth.user.id) : null;+ return json(res, 200, {+ ok: true,+ checkoutAvailable: isStripeConfigured(),+ ...catalog,+ user+ });+ } catch (error) {+ console.warn('Failed to load billing plans', {+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });+ }+}diff --git a/api/billing/portal.js b/api/billing/portal.jsnew file mode 100644index 0000000..d46c05e--- /dev/null+++ b/api/billing/portal.js@@ -0,0 +1,53 @@+import { getAuthContext, isSupabaseServerConfigured } from '../_lib/supabase.js';+import { getAppUrl, getStripeClient, isStripeConfigured } from '../_lib/billing.js';++function json(res, status, payload) {+ res.status(status).json(payload);+}++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ res.setHeader('Allow', 'POST');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ if (!isSupabaseServerConfigured()) {+ return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });+ }++ if (!isStripeConfigured()) {+ return json(res, 500, { ok: false, error: 'BILLING_NOT_CONFIGURED' });+ }++ const auth = await getAuthContext(req);+ if (auth.error) {+ return json(res, auth.status || 401, {+ ok: false,+ error: auth.error,+ loginRequired: auth.error === 'AUTH_REQUIRED'+ });+ }++ if (!auth.profile?.stripeCustomerId) {+ return json(res, 400, { ok: false, error: 'NO_STRIPE_CUSTOMER' });+ }++ try {+ const stripe = getStripeClient();+ const session = await stripe.billingPortal.sessions.create({+ customer: auth.profile.stripeCustomerId,+ return_url: `${getAppUrl(req)}/?billing=portal_return`+ });++ return json(res, 200, {+ ok: true,+ url: session.url+ });+ } catch (error) {+ console.warn('Failed to create billing portal session', {+ userId: auth.user?.id,+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'BILLING_PORTAL_FAILED' });+ }+}diff --git a/api/billing/webhook.js b/api/billing/webhook.jsnew file mode 100644index 0000000..b529749--- /dev/null+++ b/api/billing/webhook.js@@ -0,0 +1,154 @@+import { getSupabaseAdminClient, isSupabaseServerConfigured } from '../_lib/supabase.js';+import {+ completeCreditPackOrder,+ grantMembershipCredits,+ getStripeClient,+ isStripeConfigured,+ readRawBody,+ upsertMembershipFromSubscription+} from '../_lib/billing.js';++export const config = {+ api: {+ bodyParser: false+ }+};++function json(res, status, payload) {+ res.status(status).json(payload);+}++async function handleCheckoutCompleted(client, stripe, session) {+ const productType = session.metadata?.productType;+ if (productType === 'credit_pack') {+ await completeCreditPackOrder(client, session);+ return;+ }++ if (productType !== 'membership') return;++ const subscriptionId = typeof session.subscription === 'string' ? session.subscription : session.subscription?.id;+ if (!subscriptionId) return;++ const subscription = await stripe.subscriptions.retrieve(subscriptionId);+ await upsertMembershipFromSubscription(client, subscription, {+ userId: session.metadata?.userId,+ planId: session.metadata?.productId,+ customerId: typeof session.customer === 'string' ? session.customer : ''+ });++ const { data: order, error } = await client+ .from('payment_orders')+ .select('*')+ .eq('stripe_session_id', session.id)+ .maybeSingle();++ if (error) throw error;++ if (order?.status !== 'completed') {+ await grantMembershipCredits(client, {+ userId: session.metadata?.userId || order?.user_id,+ planId: session.metadata?.productId || order?.product_id,+ source: 'stripe_membership_checkout',+ orderId: order?.id || null,+ metadata: {+ stripeSessionId: session.id,+ stripeSubscriptionId: subscriptionId+ }+ });++ if (order) {+ const { error: updateError } = await client+ .from('payment_orders')+ .update({+ status: 'completed',+ stripe_customer_id: typeof session.customer === 'string' ? session.customer : order.stripe_customer_id,+ stripe_subscription_id: subscriptionId,+ completed_at: new Date().toISOString()+ })+ .eq('id', order.id);++ if (updateError) throw updateError;+ }+ }+}++async function handleInvoicePaid(client, stripe, invoice) {+ if (invoice.billing_reason === 'subscription_create') return;++ const subscriptionId = typeof invoice.subscription === 'string' ? invoice.subscription : invoice.subscription?.id;+ if (!subscriptionId) return;++ const subscription = await stripe.subscriptions.retrieve(subscriptionId);+ const membership = await upsertMembershipFromSubscription(client, subscription);+ const userId = subscription.metadata?.userId || membership?.user_id;+ const planId = subscription.metadata?.productId || subscription.metadata?.planId || membership?.plan_id;+ if (!userId || !planId) return;++ await grantMembershipCredits(client, {+ userId,+ planId,+ source: 'stripe_membership_invoice',+ metadata: {+ stripeInvoiceId: invoice.id,+ stripeSubscriptionId: subscriptionId,+ billingReason: invoice.billing_reason || ''+ }+ });+}++async function handleSubscriptionChanged(client, subscription) {+ await upsertMembershipFromSubscription(client, subscription);+}++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ res.setHeader('Allow', 'POST');+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });+ }++ if (!isSupabaseServerConfigured() || !isStripeConfigured() || !process.env.STRIPE_WEBHOOK_SECRET) {+ return json(res, 500, { ok: false, error: 'BILLING_NOT_CONFIGURED' });+ }++ const stripe = getStripeClient();+ const client = getSupabaseAdminClient();+ const signature = req.headers['stripe-signature'];+ let event;++ try {+ const rawBody = await readRawBody(req);+ event = stripe.webhooks.constructEvent(rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET);+ } catch (error) {+ return json(res, 400, {+ ok: false,+ error: 'INVALID_WEBHOOK_SIGNATURE'+ });+ }++ try {+ switch (event.type) {+ case 'checkout.session.completed':+ await handleCheckoutCompleted(client, stripe, event.data.object);+ break;+ case 'invoice.payment_succeeded':+ await handleInvoicePaid(client, stripe, event.data.object);+ break;+ case 'customer.subscription.updated':+ case 'customer.subscription.deleted':+ await handleSubscriptionChanged(client, event.data.object);+ break;+ default:+ break;+ }++ return json(res, 200, { ok: true, received: true });+ } catch (error) {+ console.warn('Failed to process Stripe webhook', {+ eventType: event.type,+ eventId: event.id,+ message: String(error?.message || 'unknown').slice(0, 240)+ });+ return json(res, 500, { ok: false, error: 'WEBHOOK_PROCESSING_FAILED' });+ }+}diff --git a/api/generate-image.js b/api/generate-image.jsindex c2e4cab..f27d0d0 100644--- a/api/generate-image.js+++ b/api/generate-image.js@@ -80,7 +80,8 @@ async function createSuperAdminReservation(client, profile, caseId, prompt) {case_id: caseId,prompt,used_free_generation: false,- credit_amount: 0+ credit_amount: 0,+ usage_source: 'super_admin'}).select('id').single();diff --git a/package-lock.json b/package-lock.jsonindex 3b5375d..de7cb03 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,9 +13,9 @@"lucide-react": "^0.561.0","react": "^19.2.1","react-dom": "^19.2.1",+ "stripe": "^22.1.1","vite": "^7.2.7"- },- "devDependencies": {}+ }},"node_modules/@babel/code-frame": {"version": "7.29.0",@@ -1677,6 +1677,23 @@"node": ">=0.10.0"}},+ "node_modules/stripe": {+ "version": "22.1.1",+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-22.1.1.tgz",+ "integrity": "sha512-cmodIYP27tBkJ8G7DuGgWw0PFuemlFZbuF3Wwr1TrjFjUa3T7NIgCe6TVwX8BO2ynu+xtTuDGfHafNDCPt9lXA==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@types/node": ">=18"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }+ }+ },"node_modules/tinyglobby": {"version": "0.2.16","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",diff --git a/package.json b/package.jsonindex d2c6b0c..b12e3f7 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"lucide-react": "^0.561.0","react": "^19.2.1","react-dom": "^19.2.1",+ "stripe": "^22.1.1","vite": "^7.2.7"}}diff --git a/src/main.jsx b/src/main.jsxindex 3cfdb25..cf6941a 100644--- a/src/main.jsx+++ b/src/main.jsx@@ -7,6 +7,8 @@ import {Check,Coins,Copy,+ CreditCard,+ Crown,Eye,Github,ImageIcon,@@ -16,6 +18,7 @@ import {Mail,PackageCheck,RefreshCw,+ ReceiptText,Search,ShieldCheck,Sparkles,@@ -91,11 +94,17 @@ const copy = {resetPrompt: 'Reset Prompt',oneFreeGeneration: '1 free test image',superAdminGeneration: 'Super admin test mode: credits are not consumed.',- freeLimitReached: 'Free generation used. Credits are coming soon.',+ generationCost: 'Costs 1 credit',+ freeLimitReached: 'Free generation used. Buy credits or start a membership to keep generating.',+ creditsRequired: 'Credits required. Buy credits or start a membership to keep generating.',generationBusy: 'The image service is busy. Please try again in a moment.',generationFailed: 'Generation failed. Please try again later.',promptRequired: 'Prompt is required and must stay under 6000 characters.',serverUnavailable: 'Generation service is not configured yet.',+ checkoutUnavailable: 'Checkout is not configured yet.',+ checkoutFailed: 'Checkout failed. Please try again later.',+ billingSuccess: 'Payment is processing. Credits will appear after Stripe confirms it.',+ billingCancelled: 'Checkout cancelled. You can choose another pack anytime.',authRequired: 'Sign in to generate a test image.',signIn: 'Sign in',signInTitle: 'Sign in to generate test images',@@ -112,8 +121,32 @@ const copy = {signOut: 'Sign out',account: 'Account',adminPanel: 'Admin',+ membershipCenter: 'Membership & Credits',superAdmin: 'Super admin',credits: 'credits',+ buyCredits: 'Buy credits',+ subscribe: 'Subscribe',+ manageSubscription: 'Manage subscription',+ currentPlan: 'Current plan',+ noPlan: 'Free plan',+ activeUntil: 'Active until',+ membershipPlans: 'Membership',+ creditPacks: 'Credit packs',+ monthlyCredits: (count) => `${count} credits / month`,+ packCredits: (count) => `${count} credits`,+ billingTitle: 'Membership & credits',+ billingSubtitle: 'Members get monthly credits. Credit packs can be added anytime for more GPT-Image2 tests.',+ balanceTitle: 'Current balance',+ transactionHistory: 'Credit history',+ noTransactions: 'No credit history yet.',+ loadBilling: 'Loading billing...',+ openBilling: 'Open membership center',+ paymentReady: 'Secure checkout via Stripe.',+ billingNotReady: 'Stripe checkout is not configured yet.',+ adminAdjust: 'Adjust credits',+ creditAmount: 'Amount',+ reason: 'Reason',+ applyAdjustment: 'Apply adjustment',freeReady: 'Free test ready',freeUsedShort: 'Free test used',signInToGenerate: 'Sign in to generate',@@ -198,11 +231,17 @@ const copy = {resetPrompt: '重置 Prompt',oneFreeGeneration: '免费生成 1 张测试图',superAdminGeneration: '超级管理员测试模式:本次生图不消耗积分。',- freeLimitReached: '免费额度已用完,积分购买即将开放。',+ generationCost: '本次消耗 1 积分',+ freeLimitReached: '免费额度已用完,可购买积分包或开通会员继续生成。',+ creditsRequired: '积分不足,可购买积分包或开通会员继续生成。',generationBusy: '生图服务繁忙,请稍后再试。',generationFailed: '生成失败,请稍后再试。',promptRequired: 'Prompt 不能为空,并且不能超过 6000 字符。',serverUnavailable: '生成服务还没有完成配置。',+ checkoutUnavailable: '支付功能还没有完成配置。',+ checkoutFailed: '创建支付失败,请稍后再试。',+ billingSuccess: '支付正在处理中,Stripe 确认后积分会自动到账。',+ billingCancelled: '已取消支付,你可以随时换一个积分包或会员方案。',authRequired: '登录后即可生成测试图。',signIn: '登录',signInTitle: '登录后生成测试图',@@ -219,8 +258,32 @@ const copy = {signOut: '退出登录',account: '账号',adminPanel: '管理后台',+ membershipCenter: '会员与积分',superAdmin: '超级管理员',credits: '积分',+ buyCredits: '购买积分',+ subscribe: '开通会员',+ manageSubscription: '管理订阅',+ currentPlan: '当前会员',+ noPlan: '免费用户',+ activeUntil: '有效期至',+ membershipPlans: '会员套餐',+ creditPacks: '积分包',+ monthlyCredits: (count) => `每月 ${count} 积分`,+ packCredits: (count) => `${count} 积分`,+ billingTitle: '会员与积分',+ billingSubtitle: '会员每月自动获得积分,也可以随时购买积分包,用来测试更多 GPT-Image2 案例。',+ balanceTitle: '当前余额',+ transactionHistory: '积分流水',+ noTransactions: '暂无积分流水。',+ loadBilling: '正在加载会员与积分...',+ openBilling: '打开会员中心',+ paymentReady: '使用 Stripe 安全支付。',+ billingNotReady: 'Stripe 支付还没有完成配置。',+ adminAdjust: '调整积分',+ creditAmount: '数量',+ reason: '原因',+ applyAdjustment: '确认调整',freeReady: '免费测试可用',freeUsedShort: '免费测试已用',signInToGenerate: '登录后生成',@@ -435,11 +498,13 @@ function useCopy() {function generationErrorMessage(error, language) {const t = copy[language];if (error === 'FREE_LIMIT_REACHED') return t.freeLimitReached;- if (error === 'CREDITS_REQUIRED') return t.freeLimitReached;+ if (error === 'CREDITS_REQUIRED') return t.creditsRequired;if (error === 'AUTH_REQUIRED') return t.authRequired;if (error === 'FORBIDDEN') return t.adminOnly;if (error === 'UPSTREAM_BUSY') return t.generationBusy;if (error === 'SERVER_NOT_CONFIGURED') return t.serverUnavailable;+ if (error === 'BILLING_NOT_CONFIGURED') return t.checkoutUnavailable;+ if (error === 'CHECKOUT_FAILED' || error === 'BILLING_PORTAL_FAILED') return t.checkoutFailed;if (error === 'INVALID_PROMPT') return t.promptRequired;return t.generationFailed;}@@ -454,7 +519,33 @@ function getGenerationQuotaText(profile, language) {if (profile.isSuperAdmin) return t.superAdminGeneration;if (!profile.freeUsed) return t.oneFreeGeneration;if (profile.creditBalance > 0) return t.creditsAvailable(profile.creditBalance);- return t.freeLimitReached;+ return t.creditsRequired;+}++function productText(value, language) {+ if (!value) return '';+ return value[language] || value.en || value.zh || '';+}++function formatMembershipStatus(membership, language) {+ const t = copy[language];+ if (!membership?.isActive) return t.noPlan;+ const status = membership.status === 'trialing' ? 'trialing' : 'active';+ if (!membership.currentPeriodEnd) return status;+ const date = new Date(membership.currentPeriodEnd).toLocaleDateString(language === 'zh' ? 'zh-CN' : 'en-US');+ return `${status} · ${t.activeUntil} ${date}`;+}++function transactionLabel(transaction, language) {+ const typeMap = {+ grant: language === 'zh' ? '赠送' : 'Grant',+ purchase: language === 'zh' ? '购买' : 'Purchase',+ membership_grant: language === 'zh' ? '会员发放' : 'Membership grant',+ generation: language === 'zh' ? '生图消耗' : 'Generation',+ refund: language === 'zh' ? '失败返还' : 'Refund',+ adjustment: language === 'zh' ? '管理员调整' : 'Admin adjustment'+ };+ return typeMap[transaction.type] || transaction.type || '-';}function formatTemplatePrompt(item, language, styleLibrary) {@@ -803,7 +894,7 @@ function AuthModal({ open, language, onClose }) {);}-function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin }) {+function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, onBilling }) {const t = copy[language];const [open, setOpen] = useState(false);const ref = useDropdownDismiss(open, setOpen);@@ -855,12 +946,28 @@ function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin })<Coins size={15} />{profile?.creditBalance || 0} {t.credits}</span>+ <span className="userStat">+ <Crown size={15} />+ {formatMembershipStatus(profile?.membership, language)}+ </span><span className="userStat"><PackageCheck size={15} />{profile?.freeUsed ? t.freeUsedShort : t.freeReady}</span></div><div className="dropdownDivider" />+ <button+ className="dropdownAction"+ type="button"+ role="menuitem"+ onClick={() => {+ setOpen(false);+ onBilling();+ }}+ >+ <CreditCard size={17} />+ {t.membershipCenter}+ </button>{profile?.isSuperAdmin ? (<buttonclassName="dropdownAction"@@ -898,6 +1005,8 @@ function AdminPanel({ open, language, session, onClose }) {const [users, setUsers] = useState([]);const [status, setStatus] = useState('idle');const [message, setMessage] = useState('');+ const [adjustment, setAdjustment] = useState(null);+ const [adjustStatus, setAdjustStatus] = useState('idle');async function loadUsers() {if (!session?.access_token) {@@ -920,6 +1029,40 @@ function AdminPanel({ open, language, session, onClose }) {setStatus('ready');} catch (error) {setStatus('error');+ setMessage(error.message === 'SERVER_NOT_CONFIGURED' ? t.checkoutUnavailable : generationErrorMessage(error.message, language));+ }+ }++ async function handleAdjustCredits(event) {+ event.preventDefault();+ if (!adjustment?.userId) return;+ setAdjustStatus('loading');+ setMessage('');++ try {+ const response = await fetch('/api/admin/credits/adjust', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...getAuthHeaders(session)+ },+ body: JSON.stringify({+ userId: adjustment.userId,+ amount: Number(adjustment.amount),+ reason: adjustment.reason+ })+ });+ const payload = await response.json().catch(() => ({}));+ if (!response.ok || !payload.ok) {+ throw new Error(payload.error || 'CREDIT_ADJUSTMENT_FAILED');+ }+ setUsers((current) => current.map((user) => (+ user.id === payload.user.id ? { ...user, ...payload.user } : user+ )));+ setAdjustment(null);+ setAdjustStatus('idle');+ } catch (error) {+ setAdjustStatus('error');setMessage(generationErrorMessage(error.message, language));}}@@ -963,6 +1106,32 @@ function AdminPanel({ open, language, session, onClose }) {</div>) : null}{status === 'error' ? <p className="authMessage error">{message || t.adminOnly}</p> : null}+ {adjustment ? (+ <form className="adminAdjustForm" onSubmit={handleAdjustCredits}>+ <strong>{adjustment.email}</strong>+ <label>+ {t.creditAmount}+ <input+ type="number"+ step="1"+ value={adjustment.amount}+ onChange={(event) => setAdjustment((current) => ({ ...current, amount: event.target.value }))}+ />+ </label>+ <label>+ {t.reason}+ <input+ value={adjustment.reason}+ onChange={(event) => setAdjustment((current) => ({ ...current, reason: event.target.value }))}+ />+ </label>+ <button type="submit" disabled={adjustStatus === 'loading'}>+ {adjustStatus === 'loading' ? <LoaderCircle className="spinIcon" size={16} /> : <Coins size={16} />}+ {t.applyAdjustment}+ </button>+ </form>+ ) : null}+ {adjustStatus === 'error' ? <p className="authMessage error">{message}</p> : null}{status !== 'loading' && !users.length && status !== 'error' ? (<div className="adminState"><Users size={20} />@@ -977,8 +1146,10 @@ function AdminPanel({ open, language, session, onClose }) {<th>{t.users}</th><th>{t.role}</th><th>{t.creditBalance}</th>+ <th>{t.currentPlan}</th><th>{t.freeGeneration}</th><th>{t.createdAt}</th>+ <th>{t.adminAdjust}</th></tr></thead><tbody>@@ -995,8 +1166,24 @@ function AdminPanel({ open, language, session, onClose }) {</td><td><span className="roleBadge">{user.role}</span></td><td>{user.creditBalance}</td>+ <td>{formatMembershipStatus(user.membership, language)}</td><td>{user.freeUsed ? t.freeUsedShort : t.freeReady}</td><td>{user.createdAt ? new Date(user.createdAt).toLocaleDateString(language === 'zh' ? 'zh-CN' : 'en-US') : '-'}</td>+ <td>+ <button+ className="tableAction"+ type="button"+ onClick={() => setAdjustment({+ userId: user.id,+ email: user.email,+ amount: 10,+ reason: ''+ })}+ >+ <Coins size={15} />+ {t.adminAdjust}+ </button>+ </td></tr>))}</tbody>@@ -1008,6 +1195,281 @@ function AdminPanel({ open, language, session, onClose }) {);}+function BillingPanel({+ open,+ language,+ session,+ profile,+ notice,+ onClose,+ onAuthRequired,+ onProfileChange+}) {+ const t = copy[language];+ const [plans, setPlans] = useState([]);+ const [packs, setPacks] = useState([]);+ const [transactions, setTransactions] = useState([]);+ const [checkoutAvailable, setCheckoutAvailable] = useState(false);+ const [status, setStatus] = useState('idle');+ const [message, setMessage] = useState('');+ const [busyProduct, setBusyProduct] = useState('');++ async function loadBilling() {+ setStatus('loading');+ setMessage(notice || '');++ try {+ const headers = getAuthHeaders(session);+ const [plansResponse, historyResponse] = await Promise.all([+ fetch('/api/billing/plans', { headers }),+ session?.access_token+ ? fetch('/api/billing/history', { headers })+ : Promise.resolve(null)+ ]);+ const plansPayload = await plansResponse.json().catch(() => ({}));+ if (!plansResponse.ok || !plansPayload.ok) {+ throw new Error(plansPayload.error || 'SERVER_NOT_CONFIGURED');+ }++ setPlans(plansPayload.plans || []);+ setPacks(plansPayload.packs || []);+ setCheckoutAvailable(Boolean(plansPayload.checkoutAvailable));+ if (plansPayload.user) onProfileChange(plansPayload.user);++ if (historyResponse) {+ const historyPayload = await historyResponse.json().catch(() => ({}));+ if (historyResponse.ok && historyPayload.ok) {+ setTransactions(historyPayload.transactions || []);+ }+ } else {+ setTransactions([]);+ }++ setStatus('ready');+ } catch (error) {+ setStatus('error');+ setMessage(generationErrorMessage(error.message, language));+ }+ }++ useEffect(() => {+ if (open) loadBilling();+ }, [open, session?.access_token]);++ async function handleCheckout(product) {+ if (!session?.access_token) {+ onAuthRequired();+ return;+ }+ if (!checkoutAvailable) {+ setMessage(t.checkoutUnavailable);+ return;+ }++ setBusyProduct(`${product.type}:${product.id}`);+ setMessage('');++ try {+ const response = await fetch('/api/billing/checkout', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...getAuthHeaders(session)+ },+ body: JSON.stringify({+ productType: product.type,+ productId: product.id+ })+ });+ const payload = await response.json().catch(() => ({}));+ if (!response.ok || !payload.ok || !payload.url) {+ throw new Error(payload.error || 'CHECKOUT_FAILED');+ }+ if (payload.user) onProfileChange(payload.user);+ window.location.href = payload.url;+ } catch (error) {+ setBusyProduct('');+ setMessage(generationErrorMessage(error.message, language));+ }+ }++ async function handlePortal() {+ if (!session?.access_token) {+ onAuthRequired();+ return;+ }+ setBusyProduct('portal');+ setMessage('');++ try {+ const response = await fetch('/api/billing/portal', {+ method: 'POST',+ headers: getAuthHeaders(session)+ });+ const payload = await response.json().catch(() => ({}));+ if (!response.ok || !payload.ok || !payload.url) {+ throw new Error(payload.error || 'BILLING_PORTAL_FAILED');+ }+ window.location.href = payload.url;+ } catch (error) {+ setBusyProduct('');+ setMessage(generationErrorMessage(error.message, language));+ }+ }++ if (!open) return null;++ const activePlanId = profile?.membership?.isActive ? profile.membership.planId : '';+ const activePlan = plans.find((plan) => plan.id === activePlanId);+ const activePlanName = activePlan ? productText(activePlan.name, language) : activePlanId || t.noPlan;++ return (+ <div+ className="previewOverlay billingOverlay"+ role="presentation"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget) onClose();+ }}+ >+ <section className="billingDialog" role="dialog" aria-modal="true" aria-labelledby="billing-title">+ <button className="previewClose" type="button" onClick={onClose} aria-label={t.closePreview}>+ <X size={20} />+ </button>+ <div className="billingHero">+ <span className="eyebrow">+ <CreditCard size={16} />+ {t.membershipCenter}+ </span>+ <h2 id="billing-title">{t.billingTitle}</h2>+ <p>{t.billingSubtitle}</p>+ </div>++ <div className="billingSummary">+ <div>+ <span>{t.balanceTitle}</span>+ <strong>{profile?.creditBalance || 0}</strong>+ <em>{t.credits}</em>+ </div>+ <div>+ <span>{t.currentPlan}</span>+ <strong>{activePlanName}</strong>+ <em>{formatMembershipStatus(profile?.membership, language)}</em>+ </div>+ <div>+ <span>{t.freeGeneration}</span>+ <strong>{profile?.freeUsed ? t.freeUsedShort : t.freeReady}</strong>+ <em>{checkoutAvailable ? t.paymentReady : t.billingNotReady}</em>+ </div>+ </div>++ {!session?.access_token ? (+ <div className="billingState">+ <p>{t.authRequired}</p>+ <button type="button" onClick={onAuthRequired}>+ <LogIn size={17} />+ {t.signIn}+ </button>+ </div>+ ) : null}++ {status === 'loading' ? (+ <div className="billingState">+ <LoaderCircle className="spinIcon" size={20} />+ {t.loadBilling}+ </div>+ ) : null}++ {message ? (+ <p className={cx('authMessage', status === 'error' && 'error')}>{message}</p>+ ) : null}++ <div className="billingSections">+ <section>+ <h3>+ <Crown size={18} />+ {t.membershipPlans}+ </h3>+ <div className="billingCards">+ {plans.map((plan) => {+ const isCurrent = activePlanId === plan.id;+ const busy = busyProduct === `${plan.type}:${plan.id}`;+ return (+ <article className={cx('billingCard', isCurrent && 'current')} key={plan.id}>+ <span>{productText(plan.name, language)}</span>+ <strong>{plan.priceLabel}<small>/{plan.interval}</small></strong>+ <p>{productText(plan.description, language)}</p>+ <div className="billingCredits">{t.monthlyCredits(plan.monthlyCredits)}</div>+ <button type="button" disabled={busy || isCurrent} onClick={() => handleCheckout(plan)}>+ {busy ? <LoaderCircle className="spinIcon" size={16} /> : <Crown size={16} />}+ {isCurrent ? t.currentPlan : t.subscribe}+ </button>+ </article>+ );+ })}+ </div>+ {profile?.membership?.isActive ? (+ <button className="portalButton" type="button" onClick={handlePortal} disabled={busyProduct === 'portal'}>+ {busyProduct === 'portal' ? <LoaderCircle className="spinIcon" size={16} /> : <CreditCard size={16} />}+ {t.manageSubscription}+ </button>+ ) : null}+ </section>++ <section>+ <h3>+ <Coins size={18} />+ {t.creditPacks}+ </h3>+ <div className="billingCards">+ {packs.map((pack) => {+ const busy = busyProduct === `${pack.type}:${pack.id}`;+ return (+ <article className="billingCard" key={pack.id}>+ <span>{productText(pack.name, language)}</span>+ <strong>{pack.priceLabel}</strong>+ <p>{productText(pack.description, language)}</p>+ <div className="billingCredits">{t.packCredits(pack.credits)}</div>+ <button type="button" disabled={busy} onClick={() => handleCheckout(pack)}>+ {busy ? <LoaderCircle className="spinIcon" size={16} /> : <Coins size={16} />}+ {t.buyCredits}+ </button>+ </article>+ );+ })}+ </div>+ </section>+ </div>++ <section className="transactionSection">+ <h3>+ <ReceiptText size={18} />+ {t.transactionHistory}+ </h3>+ {transactions.length ? (+ <div className="transactionList">+ {transactions.map((transaction) => (+ <div className="transactionItem" key={transaction.id}>+ <span>{transactionLabel(transaction, language)}</span>+ <strong className={transaction.amount >= 0 ? 'positive' : 'negative'}>+ {transaction.amount >= 0 ? '+' : ''}{transaction.amount}+ </strong>+ <em>+ {transaction.createdAt+ ? new Date(transaction.createdAt).toLocaleString(language === 'zh' ? 'zh-CN' : 'en-US')+ : '-'}+ </em>+ </div>+ ))}+ </div>+ ) : (+ <p className="emptyTransactions">{t.noTransactions}</p>+ )}+ </section>+ </section>+ </div>+ );+}+function SkillSection({ language, repoUrl }) {const t = copy[language];const [commandCopied, setCommandCopied] = useState(false);@@ -1214,6 +1676,7 @@ function PreviewDialog({onClose,onCopyText,onAuthRequired,+ onBillingRequired,onProfileChange}) {const t = copy[language];@@ -1290,7 +1753,7 @@ function PreviewDialog({&& !profile?.isSuperAdmin&& Boolean(profile?.freeUsed)&& Number(profile?.creditBalance || 0) <= 0;- const generationLocked = isGenerating || isOutOfCredits;+ const generationLocked = isGenerating;const quotaText = isSignedIn ? getGenerationQuotaText(profile, language) : t.authRequired;async function handleGenerate() {@@ -1306,7 +1769,8 @@ function PreviewDialog({return;}if (isOutOfCredits) {- setGenerationState({ status: 'error', image: '', message: t.freeLimitReached });+ onBillingRequired();+ setGenerationState({ status: 'idle', image: generatedImage, message: t.creditsRequired });return;}@@ -1415,7 +1879,7 @@ function PreviewDialog({{!isTemplate ? (<button type="button" onClick={handleGenerate} disabled={generationLocked}>{isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}- {isGenerating ? t.generating : isSignedIn ? t.generateTest : t.signInToGenerate}+ {isGenerating ? t.generating : isOutOfCredits ? t.buyCredits : isSignedIn ? t.generateTest : t.signInToGenerate}</button>) : null}<a href={primaryLink} target="_blank" rel="noreferrer">@@ -1456,7 +1920,7 @@ function PreviewDialog({</div><button type="button" onClick={handleGenerate} disabled={generationLocked}>{isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}- {isGenerating ? t.generating : isSignedIn ? t.generateImage : t.signInToGenerate}+ {isGenerating ? t.generating : isOutOfCredits ? t.buyCredits : isSignedIn ? t.generateImage : t.signInToGenerate}</button>{generationState.status === 'error' ? (<p className="generationMessage">{generationState.message}</p>@@ -1523,6 +1987,8 @@ function App() {const [profile, setProfile] = useState(null);const [authOpen, setAuthOpen] = useState(false);const [adminOpen, setAdminOpen] = useState(false);+ const [billingOpen, setBillingOpen] = useState(false);+ const [billingNotice, setBillingNotice] = useState('');const { copiedId, copyPrompt, copyText } = useCopy();const repoUrl = siteData?.repository || fallbackRepoUrl;const t = copy[language];@@ -1604,6 +2070,20 @@ function App() {});}, [siteData, styleLibrary]);+ useEffect(() => {+ const params = new URLSearchParams(window.location.search);+ const billing = params.get('billing');+ if (!billing) return;+ if (billing === 'success') setBillingNotice(t.billingSuccess);+ if (billing === 'cancelled') setBillingNotice(t.billingCancelled);+ setBillingOpen(true);+ params.delete('billing');+ params.delete('session_id');+ const nextSearch = params.toString();+ const nextUrl = `${window.location.pathname}${nextSearch ? `?${nextSearch}` : ''}${window.location.hash}`;+ window.history.replaceState({}, '', nextUrl);+ }, [t.billingCancelled, t.billingSuccess]);+const latestCases = useMemo(() => {if (!siteData) return [];return [...siteData.cases].sort((a, b) => b.id - a.id);@@ -1659,6 +2139,7 @@ function App() {setSession(null);setProfile(null);setAdminOpen(false);+ setBillingOpen(false);}function handleProfileChange(nextProfile) {@@ -1700,6 +2181,10 @@ function App() {onSignIn={() => setAuthOpen(true)}onSignOut={handleSignOut}onAdmin={() => setAdminOpen(true)}+ onBilling={() => {+ setBillingNotice('');+ setBillingOpen(true);+ }}/></div></header>@@ -1829,6 +2314,10 @@ function App() {onClose={() => setPreview(null)}onCopyText={copyText}onAuthRequired={() => setAuthOpen(true)}+ onBillingRequired={() => {+ setBillingNotice(t.creditsRequired);+ setBillingOpen(true);+ }}onProfileChange={handleProfileChange}/><AuthModal@@ -1842,6 +2331,16 @@ function App() {session={session}onClose={() => setAdminOpen(false)}/>+ <BillingPanel+ open={billingOpen}+ language={language}+ session={session}+ profile={profile}+ notice={billingNotice}+ onClose={() => setBillingOpen(false)}+ onAuthRequired={() => setAuthOpen(true)}+ onProfileChange={handleProfileChange}+ /></main>);}diff --git a/src/styles.css b/src/styles.cssindex 0735986..3e836cf 100644--- a/src/styles.css+++ b/src/styles.css@@ -1695,7 +1695,8 @@ button {}.authDialog,-.adminDialog {+.adminDialog,+.billingDialog {position: relative;width: min(100%, 460px);max-height: min(860px, 92vh);@@ -1827,6 +1828,11 @@ button {padding: 24px;}+.billingDialog {+ width: min(1080px, 100%);+ padding: 24px;+}+.adminHeader {display: flex;align-items: flex-start;@@ -1918,6 +1924,262 @@ button {font-weight: 800;}+.adminAdjustForm {+ display: grid;+ grid-template-columns: minmax(180px, 1fr) 120px minmax(180px, 1.2fr) auto;+ gap: 10px;+ align-items: end;+ margin: 0 0 16px;+ border: 1px solid rgba(103, 232, 249, 0.14);+ border-radius: 8px;+ padding: 12px;+ background: rgba(103, 232, 249, 0.06);+}++.adminAdjustForm strong {+ color: #ffffff;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.adminAdjustForm label {+ display: grid;+ gap: 6px;+ color: #9eeeff;+ font-size: 12px;+ font-weight: 900;+}++.adminAdjustForm input {+ min-height: 38px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 8px;+ outline: 0;+ padding: 0 10px;+ background: rgba(3, 7, 15, 0.72);+ color: #ffffff;+}++.adminAdjustForm button,+.tableAction,+.billingState button,+.billingCard button,+.portalButton {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ min-height: 38px;+ border: 1px solid rgba(120, 255, 185, 0.32);+ border-radius: 8px;+ padding: 0 12px;+ background: rgba(120, 255, 185, 0.1);+ color: #d8ffe4;+ font-weight: 900;+ white-space: nowrap;+}++.tableAction {+ min-height: 34px;+ color: #eaf3ff;+}++.billingHero h2 {+ margin: 18px 48px 10px 0;+ color: #ffffff;+ font-size: clamp(30px, 4vw, 52px);+ line-height: 1.05;+ letter-spacing: 0;+}++.billingHero p {+ max-width: 720px;+ margin: 0;+ color: #aebcd0;+ line-height: 1.7;+}++.billingSummary {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 12px;+ margin: 22px 0;+}++.billingSummary div,+.billingCard,+.transactionSection,+.billingState {+ border: 1px solid rgba(255, 255, 255, 0.11);+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.055);+}++.billingSummary div {+ display: grid;+ gap: 6px;+ min-height: 108px;+ padding: 14px;+}++.billingSummary span,+.billingCard span,+.transactionItem span {+ color: #8eeeff;+ font-size: 12px;+ font-weight: 900;+ text-transform: uppercase;+}++.billingSummary strong {+ color: #ffffff;+ font-size: 26px;+ line-height: 1.1;+}++.billingSummary em,+.transactionItem em {+ color: #93a4bc;+ font-size: 12px;+ font-style: normal;+}++.billingState {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ margin: 14px 0;+ padding: 12px;+ color: #aebcd0;+ font-weight: 800;+}++.billingState p {+ margin: 0;+}++.billingSections {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 18px;+ margin-top: 20px;+}++.billingSections h3,+.transactionSection h3 {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0 0 12px;+ color: #eaf3ff;+ font-size: 16px;+ letter-spacing: 0;+}++.billingCards {+ display: grid;+ gap: 10px;+}++.billingCard {+ display: grid;+ gap: 10px;+ padding: 14px;+}++.billingCard.current {+ border-color: rgba(120, 255, 185, 0.38);+ background: rgba(120, 255, 185, 0.08);+}++.billingCard strong {+ color: #ffffff;+ font-size: 28px;+ line-height: 1;+}++.billingCard strong small {+ margin-left: 3px;+ color: #aebcd0;+ font-size: 13px;+ font-weight: 800;+}++.billingCard p {+ min-height: 44px;+ margin: 0;+ color: #aebcd0;+ line-height: 1.55;+}++.billingCredits {+ width: fit-content;+ border-radius: 999px;+ padding: 7px 10px;+ background: rgba(103, 232, 249, 0.1);+ color: #d8fbff;+ font-size: 12px;+ font-weight: 900;+}++.billingCard button {+ min-height: 42px;+ background: linear-gradient(135deg, rgba(66, 230, 255, 0.22), rgba(120, 255, 185, 0.18));+ color: #ffffff;+}++.billingCard button:disabled,+.portalButton:disabled,+.adminAdjustForm button:disabled {+ cursor: not-allowed;+ opacity: 0.6;+}++.portalButton {+ width: 100%;+ margin-top: 12px;+}++.transactionSection {+ margin-top: 20px;+ padding: 14px;+}++.transactionList {+ display: grid;+ gap: 8px;+}++.transactionItem {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto auto;+ gap: 10px;+ align-items: center;+ min-height: 38px;+ border-radius: 7px;+ padding: 0 10px;+ background: rgba(3, 7, 15, 0.5);+}++.transactionItem strong {+ font-size: 14px;+}++.transactionItem strong.positive {+ color: #c8ffb8;+}++.transactionItem strong.negative {+ color: #ffd0d8;+}++.emptyTransactions {+ margin: 0;+ color: #93a4bc;+}+.limitNote {margin: 24px 0 0;color: #8d9bb0;@@ -2212,12 +2474,14 @@ button {}.authDialog,- .adminDialog {+ .adminDialog,+ .billingDialog {max-height: calc(100vh - 20px);}.authDialog,- .adminDialog {+ .adminDialog,+ .billingDialog {padding: 20px 16px;}@@ -2228,4 +2492,21 @@ button {.adminHeader button {width: 100%;}++ .adminAdjustForm,+ .billingSummary,+ .billingSections,+ .transactionItem {+ grid-template-columns: 1fr;+ }++ .billingState {+ align-items: stretch;+ flex-direction: column;+ }++ .billingState button,+ .transactionItem {+ width: 100%;+ }}diff --git a/supabase/migrations/20260509090000_membership_billing.sql b/supabase/migrations/20260509090000_membership_billing.sqlnew file mode 100644index 0000000..b1c9782--- /dev/null+++ b/supabase/migrations/20260509090000_membership_billing.sql@@ -0,0 +1,379 @@+alter table public.profiles+ add column if not exists stripe_customer_id text;++create unique index if not exists profiles_stripe_customer_id_idx+ on public.profiles (stripe_customer_id)+ where stripe_customer_id is not null;++alter table public.generation_reservations+ add column if not exists usage_source text not null default 'legacy',+ add column if not exists generation_cost integer not null default 1 check (generation_cost >= 0);++alter table public.credit_transactions+ drop constraint if exists credit_transactions_type_check;++alter table public.credit_transactions+ add constraint credit_transactions_type_check+ check (type in ('grant', 'purchase', 'membership_grant', 'generation', 'refund', 'adjustment'));++create table if not exists public.membership_plans (+ id text primary key,+ name_en text not null,+ name_zh text not null,+ description_en text not null,+ description_zh text not null,+ monthly_credits integer not null check (monthly_credits >= 0),+ amount_cents integer not null check (amount_cents >= 0),+ currency text not null default 'usd',+ interval text not null default 'month' check (interval in ('month', 'year')),+ active boolean not null default true,+ sort_order integer not null default 0,+ metadata jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create table if not exists public.credit_packs (+ id text primary key,+ name_en text not null,+ name_zh text not null,+ description_en text not null,+ description_zh text not null,+ credits integer not null check (credits > 0),+ amount_cents integer not null check (amount_cents >= 0),+ currency text not null default 'usd',+ active boolean not null default true,+ sort_order integer not null default 0,+ metadata jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create table if not exists public.user_memberships (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references auth.users(id) on delete cascade,+ plan_id text references public.membership_plans(id),+ status text not null default 'inactive' check (status in ('inactive', 'trialing', 'active', 'past_due', 'canceled', 'unpaid')),+ stripe_customer_id text,+ stripe_subscription_id text,+ current_period_start timestamptz,+ current_period_end timestamptz,+ cancel_at_period_end boolean not null default false,+ monthly_credits_granted_at timestamptz,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ unique (user_id),+ unique (stripe_subscription_id)+);++create table if not exists public.payment_orders (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references auth.users(id) on delete cascade,+ product_type text not null check (product_type in ('credit_pack', 'membership')),+ product_id text not null,+ status text not null default 'created' check (status in ('created', 'checkout_created', 'completed', 'failed', 'canceled')),+ stripe_session_id text,+ stripe_customer_id text,+ stripe_subscription_id text,+ amount_cents integer not null default 0 check (amount_cents >= 0),+ currency text not null default 'usd',+ credits integer not null default 0 check (credits >= 0),+ metadata jsonb not null default '{}'::jsonb,+ completed_at timestamptz,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create unique index if not exists payment_orders_stripe_session_id_idx+ on public.payment_orders (stripe_session_id)+ where stripe_session_id is not null;++create index if not exists user_memberships_user_id_idx+ on public.user_memberships (user_id);++create index if not exists user_memberships_status_idx+ on public.user_memberships (status);++create index if not exists payment_orders_user_id_idx+ on public.payment_orders (user_id, created_at desc);++create index if not exists payment_orders_status_idx+ on public.payment_orders (status);++drop trigger if exists membership_plans_set_updated_at on public.membership_plans;+create trigger membership_plans_set_updated_at+ before update on public.membership_plans+ for each row+ execute function public.set_updated_at();++drop trigger if exists credit_packs_set_updated_at on public.credit_packs;+create trigger credit_packs_set_updated_at+ before update on public.credit_packs+ for each row+ execute function public.set_updated_at();++drop trigger if exists user_memberships_set_updated_at on public.user_memberships;+create trigger user_memberships_set_updated_at+ before update on public.user_memberships+ for each row+ execute function public.set_updated_at();++drop trigger if exists payment_orders_set_updated_at on public.payment_orders;+create trigger payment_orders_set_updated_at+ before update on public.payment_orders+ for each row+ execute function public.set_updated_at();++alter table public.membership_plans enable row level security;+alter table public.credit_packs enable row level security;+alter table public.user_memberships enable row level security;+alter table public.payment_orders enable row level security;++drop policy if exists "Anyone can read active membership plans" on public.membership_plans;+create policy "Anyone can read active membership plans"+ on public.membership_plans for select+ using (active);++drop policy if exists "Anyone can read active credit packs" on public.credit_packs;+create policy "Anyone can read active credit packs"+ on public.credit_packs for select+ using (active);++drop policy if exists "Users can read own membership" on public.user_memberships;+create policy "Users can read own membership"+ on public.user_memberships for select+ using ((select auth.uid()) = user_id);++drop policy if exists "Users can read own payment orders" on public.payment_orders;+create policy "Users can read own payment orders"+ on public.payment_orders for select+ using ((select auth.uid()) = user_id);++grant select on public.membership_plans to anon, authenticated;+grant select on public.credit_packs to anon, authenticated;+grant select on public.user_memberships to authenticated;+grant select on public.payment_orders to authenticated;++insert into public.membership_plans (+ id,+ name_en,+ name_zh,+ description_en,+ description_zh,+ monthly_credits,+ amount_cents,+ sort_order+)+values+ ('starter', 'Starter', '入门会员', 'For light prompt testing and daily inspiration.', '适合轻量测试提示词和日常找灵感。', 80, 900, 10),+ ('creator', 'Creator', '创作者会员', 'For frequent case remixing and content production.', '适合高频复用案例并做内容生产。', 220, 1900, 20),+ ('studio', 'Studio', '工作室会员', 'For teams and high-volume GPT-Image2 experiments.', '适合团队和高频 GPT-Image2 实验。', 700, 4900, 30)+on conflict (id) do update+ set name_en = excluded.name_en,+ name_zh = excluded.name_zh,+ description_en = excluded.description_en,+ description_zh = excluded.description_zh,+ monthly_credits = excluded.monthly_credits,+ amount_cents = excluded.amount_cents,+ sort_order = excluded.sort_order,+ active = true;++insert into public.credit_packs (+ id,+ name_en,+ name_zh,+ description_en,+ description_zh,+ credits,+ amount_cents,+ sort_order+)+values+ ('pack_30', '30 Credits', '30 积分包', 'A small pack for trying more cases.', '适合继续尝试更多案例。', 30, 500, 10),+ ('pack_120', '120 Credits', '120 积分包', 'A balanced pack for regular prompt testing.', '适合稳定进行提示词测试。', 120, 1500, 20),+ ('pack_360', '360 Credits', '360 积分包', 'A larger pack for content batches and teams.', '适合批量内容生产和小团队使用。', 360, 3900, 30)+on conflict (id) do update+ set name_en = excluded.name_en,+ name_zh = excluded.name_zh,+ description_en = excluded.description_en,+ description_zh = excluded.description_zh,+ credits = excluded.credits,+ amount_cents = excluded.amount_cents,+ sort_order = excluded.sort_order,+ active = true;++create or replace function public.grant_user_credits(+ p_user_id uuid,+ p_amount integer,+ p_type text,+ p_source text default null,+ p_reference_id uuid default null,+ p_metadata jsonb default '{}'::jsonb+)+returns table (+ credit_balance integer+)+language plpgsql+security definer+set search_path = public+as $$+declare+ v_profile public.profiles%rowtype;+ v_next_balance integer;+begin+ if p_amount = 0 then+ select p.*+ into v_profile+ from public.profiles as p+ where p.id = p_user_id+ for update;++ if not found then+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';+ end if;++ return query select v_profile.credit_balance;+ return;+ end if;++ select p.*+ into v_profile+ from public.profiles as p+ where p.id = p_user_id+ for update;++ if not found then+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';+ end if;++ v_next_balance := v_profile.credit_balance + p_amount;+ if v_next_balance < 0 then+ raise exception 'CREDITS_INSUFFICIENT' using errcode = 'P0001';+ end if;++ update public.profiles as p+ set credit_balance = v_next_balance+ where p.id = p_user_id+ returning p.* into v_profile;++ insert into public.credit_transactions (+ user_id,+ amount,+ type,+ source,+ reference_id,+ metadata+ )+ values (+ p_user_id,+ p_amount,+ p_type,+ p_source,+ p_reference_id,+ coalesce(p_metadata, '{}'::jsonb)+ );++ return query select v_profile.credit_balance;+end;+$$;++create or replace function public.reserve_generation_usage(+ p_user_id uuid,+ p_case_id integer,+ p_prompt text+)+returns table (+ reservation_id uuid,+ used_free_generation boolean,+ credit_amount integer,+ free_generations_used integer,+ credit_balance integer+)+language plpgsql+security definer+set search_path = public+as $$+declare+ v_profile public.profiles%rowtype;+ v_reservation_id uuid;+begin+ select p.*+ into v_profile+ from public.profiles as p+ where p.id = p_user_id+ for update;++ if not found then+ raise exception 'PROFILE_NOT_FOUND' using errcode = 'P0001';+ end if;++ if v_profile.free_generations_used < 1 then+ update public.profiles as p+ set free_generations_used = p.free_generations_used + 1+ where p.id = p_user_id+ returning p.* into v_profile;++ insert into public.generation_reservations (+ user_id,+ case_id,+ prompt,+ used_free_generation,+ credit_amount,+ usage_source+ )+ values (p_user_id, p_case_id, p_prompt, true, 0, 'free_generation')+ returning id into v_reservation_id;++ return query+ select v_reservation_id, true, 0, v_profile.free_generations_used, v_profile.credit_balance;+ return;+ end if;++ if v_profile.credit_balance >= 1 then+ update public.profiles as p+ set credit_balance = p.credit_balance - 1+ where p.id = p_user_id+ returning p.* into v_profile;++ insert into public.generation_reservations (+ user_id,+ case_id,+ prompt,+ used_free_generation,+ credit_amount,+ usage_source+ )+ values (p_user_id, p_case_id, p_prompt, false, 1, 'credit')+ returning id into v_reservation_id;++ insert into public.credit_transactions (+ user_id,+ amount,+ type,+ source,+ reference_id,+ metadata+ )+ values (+ p_user_id,+ -1,+ 'generation',+ 'case_generation_test',+ v_reservation_id,+ jsonb_build_object('caseId', p_case_id, 'usageSource', 'credit')+ );++ return query+ select v_reservation_id, false, 1, v_profile.free_generations_used, v_profile.credit_balance;+ return;+ end if;++ raise exception 'CREDITS_REQUIRED' using errcode = 'P0001';+end;+$$;++revoke execute on function public.grant_user_credits(uuid, integer, text, text, uuid, jsonb) from public, anon, authenticated;+revoke execute on function public.reserve_generation_usage(uuid, integer, text) from public, anon, authenticated;++grant execute on function public.grant_user_credits(uuid, integer, text, text, uuid, jsonb) to service_role;+grant execute on function public.reserve_generation_usage(uuid, integer, text) to service_role;diff --git a/supabase/migrations/20260509091500_membership_plan_index.sql b/supabase/migrations/20260509091500_membership_plan_index.sqlnew file mode 100644index 0000000..313f8b6--- /dev/null+++ b/supabase/migrations/20260509091500_membership_plan_index.sql@@ -0,0 +1,2 @@+create index if not exists user_memberships_plan_id_idx+ on public.user_memberships (plan_id);