Skip to content

Prompt as Code | GPT Image 2 / 2.5 提示词与案例库,530+ 个案例、20+ 套工业级模板与可复用 Skills,新增 2.5 同提示词对比专区,附完整提示词与生成记录,持续更新。

Refine Google login and account credits

freestylefly1b89a2ca8102
diff --git a/api/_lib/supabase.js b/api/_lib/supabase.js
index 27961a2..6df4b41 100644
--- a/api/_lib/supabase.js
+++ b/api/_lib/supabase.js
@@ -79,12 +79,14 @@ function profilePayloadFromUser(user, existingProfile) {
const metadata = user.user_metadata || {};
const email = String(user.email || existingProfile?.email || '').trim().toLowerCase();
const desiredRole = isSuperAdminEmail(email) ? 'super_admin' : existingProfile?.role || 'user';
+ const googleName = metadata.full_name || metadata.name || null;
+ const googleAvatar = metadata.avatar_url || metadata.picture || null;
return {
id: user.id,
email,
- full_name: metadata.full_name || metadata.name || existingProfile?.full_name || null,
- avatar_url: metadata.avatar_url || metadata.picture || existingProfile?.avatar_url || null,
+ full_name: existingProfile?.full_name || googleName,
+ avatar_url: googleAvatar || existingProfile?.avatar_url || null,
stripe_customer_id: existingProfile?.stripe_customer_id || null,
role: existingProfile?.role === 'super_admin' || desiredRole === 'super_admin' ? 'super_admin' : 'user'
};
diff --git a/api/generate-image.js b/api/generate-image.js
index f27d0d0..8a01b2a 100644
--- a/api/generate-image.js
+++ b/api/generate-image.js
@@ -42,11 +42,17 @@ function normalizeReservation(data) {
function profileFromReservation(profile, reservation) {
if (!profile || !reservation) return profile;
+ const usage = profile.usage || {};
return {
...profile,
creditBalance: reservation.creditBalance,
freeGenerationsUsed: reservation.freeGenerationsUsed,
- freeUsed: reservation.freeGenerationsUsed >= 1
+ freeUsed: reservation.freeGenerationsUsed >= 1,
+ usage: {
+ ...usage,
+ totalGenerations: Number(usage.totalGenerations || 0) + 1,
+ totalGenerationCredits: Number(usage.totalGenerationCredits || 0) + Number(reservation.creditAmount || 0)
+ }
};
}
@@ -54,7 +60,8 @@ async function reserveGeneration(client, userId, caseId, prompt) {
const { data, error } = await client.rpc('reserve_generation_usage', {
p_user_id: userId,
p_case_id: caseId,
- p_prompt: prompt
+ p_prompt: prompt,
+ p_force_credit: false
});
if (error) {
@@ -72,29 +79,27 @@ async function reserveGeneration(client, userId, caseId, prompt) {
return reservation;
}
-async function createSuperAdminReservation(client, profile, caseId, prompt) {
- const { data, error } = await client
- .from('generation_reservations')
- .insert({
- user_id: profile.id,
- case_id: caseId,
- prompt,
- used_free_generation: false,
- credit_amount: 0,
- usage_source: 'super_admin'
- })
- .select('id')
- .single();
+async function reserveCreditGeneration(client, userId, caseId, prompt) {
+ const { data, error } = await client.rpc('reserve_generation_usage', {
+ p_user_id: userId,
+ p_case_id: caseId,
+ p_prompt: prompt,
+ p_force_credit: true
+ });
- if (error) throw error;
+ if (error) {
+ const normalizedMessage = String(error.message || error.details || '').toUpperCase();
+ if (normalizedMessage.includes('CREDITS_REQUIRED')) {
+ const limitError = new Error('CREDITS_REQUIRED');
+ limitError.code = 'CREDITS_REQUIRED';
+ throw limitError;
+ }
+ throw error;
+ }
- return {
- reservationId: data.id,
- usedFreeGeneration: false,
- creditAmount: 0,
- freeGenerationsUsed: Number(profile.freeGenerationsUsed || 0),
- creditBalance: Number(profile.creditBalance || 0)
- };
+ const reservation = normalizeReservation(data);
+ if (!reservation) throw new Error('RESERVATION_FAILED');
+ return reservation;
}
async function completeReservation(client, reservationId) {
@@ -199,7 +204,7 @@ export default async function handler(req, res) {
let reservation;
try {
reservation = auth.profile.isSuperAdmin
- ? await createSuperAdminReservation(auth.client, auth.profile, caseId, prompt)
+ ? await reserveCreditGeneration(auth.client, auth.user.id, caseId, prompt)
: await reserveGeneration(auth.client, auth.user.id, caseId, prompt);
} catch (error) {
if (error?.code === 'CREDITS_REQUIRED') {
diff --git a/api/me.js b/api/me.js
index 55bce81..a50e8a0 100644
--- a/api/me.js
+++ b/api/me.js
@@ -1,12 +1,65 @@
-import { getAuthContext, isSupabaseServerConfigured } from './_lib/supabase.js';
+import {
+ getAuthContext,
+ getProfileById,
+ isSupabaseServerConfigured
+} from './_lib/supabase.js';
+import { readJsonBody } from './_lib/billing.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 || ''
+ };
+}
+
+function sanitizeDisplayName(value) {
+ return String(value || '').trim().replace(/\s+/g, ' ').slice(0, 80);
+}
+
+async function getAccountExtras(client, userId) {
+ const [usageResult, transactionsResult] = await Promise.all([
+ client.rpc('get_user_account_usage', { p_user_id: userId }),
+ client
+ .from('credit_transactions')
+ .select('id,amount,type,source,metadata,created_at')
+ .eq('user_id', userId)
+ .order('created_at', { ascending: false })
+ .limit(8)
+ ]);
+
+ if (usageResult.error) throw usageResult.error;
+ if (transactionsResult.error) throw transactionsResult.error;
+
+ const usage = Array.isArray(usageResult.data) ? usageResult.data[0] : usageResult.data;
+ return {
+ usage: {
+ totalGenerations: Number(usage?.total_generations || 0),
+ totalGenerationCredits: Number(usage?.total_generation_credits || 0)
+ },
+ recentTransactions: (transactionsResult.data || []).map(formatTransaction)
+ };
+}
+
+async function profileWithExtras(client, profile) {
+ if (!profile?.id) return profile;
+ const extras = await getAccountExtras(client, profile.id);
+ return {
+ ...profile,
+ ...extras
+ };
+}
+
export default async function handler(req, res) {
- if (req.method !== 'GET') {
- res.setHeader('Allow', 'GET');
+ if (!['GET', 'PATCH'].includes(req.method)) {
+ res.setHeader('Allow', 'GET, PATCH');
return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
}
@@ -14,13 +67,50 @@ export default async function handler(req, res) {
return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
}
- const auth = await getAuthContext(req, { allowAnonymous: true });
+ const auth = await getAuthContext(req, { allowAnonymous: req.method === 'GET' });
if (auth.error) {
return json(res, auth.status || 401, { ok: false, error: auth.error });
}
+ if (req.method === 'PATCH') {
+ if (!auth.user || !auth.profile) {
+ return json(res, 401, { ok: false, error: 'AUTH_REQUIRED', loginRequired: true });
+ }
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_PROFILE' });
+ }
+
+ const fullName = sanitizeDisplayName(body.fullName || body.full_name);
+ if (!fullName) {
+ return json(res, 400, { ok: false, error: 'INVALID_PROFILE' });
+ }
+
+ const { error } = await auth.client
+ .from('profiles')
+ .update({ full_name: fullName })
+ .eq('id', auth.user.id);
+
+ if (error) {
+ console.warn('Failed to update profile', {
+ userId: auth.user.id,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 500, { ok: false, error: 'PROFILE_UPDATE_FAILED' });
+ }
+
+ const nextProfile = await getProfileById(auth.user.id);
+ return json(res, 200, {
+ ok: true,
+ user: await profileWithExtras(auth.client, nextProfile)
+ });
+ }
+
return json(res, 200, {
ok: true,
- user: auth.profile
+ user: auth.profile ? await profileWithExtras(auth.client, auth.profile) : null
});
}
diff --git a/src/main.jsx b/src/main.jsx
index cf6941a..b549c33 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -15,11 +15,11 @@ import {
LoaderCircle,
LogIn,
LogOut,
- Mail,
PackageCheck,
RefreshCw,
ReceiptText,
Search,
+ Settings,
ShieldCheck,
Sparkles,
Terminal,
@@ -93,7 +93,7 @@ const copy = {
savedInBrowser: 'Saved in this browser',
resetPrompt: 'Reset Prompt',
oneFreeGeneration: '1 free test image',
- superAdminGeneration: 'Super admin test mode: credits are not consumed.',
+ superAdminGeneration: 'Super admin mode: every generation costs 1 credit.',
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.',
@@ -108,18 +108,26 @@ const copy = {
authRequired: 'Sign in to generate a test image.',
signIn: 'Sign in',
signInTitle: 'Sign in to generate test images',
- signInSubtitle: 'Use email magic link or Google to unlock your free test image and future credits.',
- emailAddress: 'Email address',
- sendMagicLink: 'Send magic link',
- magicLinkSent: 'Magic link sent. Check your inbox, then return here.',
- authRateLimited: 'Too many login emails were sent. Please wait a bit, or use Google sign-in once it is enabled.',
+ signInSubtitle: 'Use your Google account to unlock image generation, credits, and membership features.',
+ authRateLimited: 'Too many login attempts. Please wait a bit, then try Google sign-in again.',
googleNotConfigured: 'Google sign-in is not enabled yet.',
- tryAgainIn: (seconds) => `Try again in ${seconds}s`,
continueWithGoogle: 'Continue with Google',
authNotConfigured: 'Login is not configured yet.',
authError: 'Login failed. Please try again.',
signOut: 'Sign out',
account: 'Account',
+ accountSettings: 'Account settings',
+ accountTitle: 'Account settings',
+ accountSubtitle: 'Manage your public display name, membership status, and GPT-Image2 credit usage.',
+ displayName: 'Display name',
+ saveProfile: 'Save profile',
+ profileSaved: 'Profile saved.',
+ profileUpdateFailed: 'Profile update failed. Please try again.',
+ googleAvatarSource: 'Avatar is synced from your Google account.',
+ accountOverview: 'Account overview',
+ totalGenerations: 'Generated tests',
+ totalGenerationCredits: 'Credits spent',
+ recentUsage: 'Recent credit activity',
adminPanel: 'Admin',
membershipCenter: 'Membership & Credits',
superAdmin: 'Super admin',
@@ -230,7 +238,7 @@ const copy = {
savedInBrowser: '已保存到本浏览器',
resetPrompt: '重置 Prompt',
oneFreeGeneration: '免费生成 1 张测试图',
- superAdminGeneration: '超级管理员测试模式:本次生图不消耗积分。',
+ superAdminGeneration: '超级管理员模式:每次生图消耗 1 积分。',
generationCost: '本次消耗 1 积分',
freeLimitReached: '免费额度已用完,可购买积分包或开通会员继续生成。',
creditsRequired: '积分不足,可购买积分包或开通会员继续生成。',
@@ -245,18 +253,26 @@ const copy = {
authRequired: '登录后即可生成测试图。',
signIn: '登录',
signInTitle: '登录后生成测试图',
- signInSubtitle: '使用邮箱魔法链接或 Google 登录,解锁 1 张免费测试图,并为后续积分体系做准备。',
- emailAddress: '邮箱地址',
- sendMagicLink: '发送魔法链接',
- magicLinkSent: '魔法链接已发送,请查收邮箱后回到这里。',
- authRateLimited: '登录邮件发送太频繁,请稍后再试;Google 登录接通后也可以直接使用 Google 登录。',
+ signInSubtitle: '使用你的 Google 账号登录,解锁生图测试、积分和会员能力。',
+ authRateLimited: '登录尝试过于频繁,请稍后再使用 Google 登录。',
googleNotConfigured: 'Google 登录还没有启用。',
- tryAgainIn: (seconds) => `${seconds} 秒后重试`,
- continueWithGoogle: '使用 Google 继续',
+ continueWithGoogle: '使用 Google 登录',
authNotConfigured: '登录功能还没有完成配置。',
authError: '登录失败,请稍后再试。',
signOut: '退出登录',
account: '账号',
+ accountSettings: '账户设置',
+ accountTitle: '账户设置',
+ accountSubtitle: '管理你的显示名称、会员状态和 GPT-Image2 积分消耗。',
+ displayName: '显示名称',
+ saveProfile: '保存资料',
+ profileSaved: '资料已保存。',
+ profileUpdateFailed: '资料保存失败,请稍后再试。',
+ googleAvatarSource: '头像会同步你的 Google 账号头像。',
+ accountOverview: '账户概览',
+ totalGenerations: '生成测试数',
+ totalGenerationCredits: '已消耗积分',
+ recentUsage: '最近积分动态',
adminPanel: '管理后台',
membershipCenter: '会员与积分',
superAdmin: '超级管理员',
@@ -516,7 +532,9 @@ function getAuthHeaders(session) {
function getGenerationQuotaText(profile, language) {
const t = copy[language];
if (!profile) return t.authRequired;
- if (profile.isSuperAdmin) return t.superAdminGeneration;
+ if (profile.isSuperAdmin) {
+ return profile.creditBalance > 0 ? `${t.superAdminGeneration} ${t.creditsAvailable(profile.creditBalance)}` : t.creditsRequired;
+ }
if (!profile.freeUsed) return t.oneFreeGeneration;
if (profile.creditBalance > 0) return t.creditsAvailable(profile.creditBalance);
return t.creditsRequired;
@@ -755,76 +773,32 @@ function authErrorMessage(error, language) {
return message || t.authError;
}
+function GoogleIcon() {
+ return (
+ <svg className="googleIcon" viewBox="0 0 18 18" aria-hidden="true" focusable="false">
+ <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.71v2.25h2.91c1.7-1.57 2.69-3.89 2.69-6.6z" />
+ <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.91-2.25c-.8.54-1.83.86-3.05.86-2.35 0-4.34-1.58-5.05-3.71H.94v2.33A9 9 0 0 0 9 18z" />
+ <path fill="#FBBC05" d="M3.95 10.72A5.41 5.41 0 0 1 3.67 9c0-.6.1-1.18.28-1.72V4.95H.94A9 9 0 0 0 0 9c0 1.45.34 2.82.94 4.05l3.01-2.33z" />
+ <path fill="#EA4335" d="M9 3.57c1.32 0 2.51.45 3.44 1.35l2.58-2.58C13.46.89 11.43 0 9 0A9 9 0 0 0 .94 4.95l3.01 2.33C4.66 5.15 6.65 3.57 9 3.57z" />
+ </svg>
+ );
+}
+
function AuthModal({ open, language, onClose }) {
const t = copy[language];
- const [email, setEmail] = useState('');
const [status, setStatus] = useState('idle');
const [message, setMessage] = useState('');
- const [cooldownSeconds, setCooldownSeconds] = useState(0);
useEffect(() => {
if (!open) return;
setStatus('idle');
setMessage('');
- setCooldownSeconds(0);
}, [open]);
- useEffect(() => {
- if (!cooldownSeconds) return undefined;
- const timer = window.setInterval(() => {
- setCooldownSeconds((current) => Math.max(current - 1, 0));
- }, 1000);
- return () => window.clearInterval(timer);
- }, [cooldownSeconds]);
-
if (!open) return null;
const redirectTo = `${window.location.origin}${window.location.pathname}`;
- async function handleEmailSubmit(event) {
- event.preventDefault();
- if (!isSupabaseConfigured || !supabase) {
- setStatus('error');
- setMessage(t.authNotConfigured);
- return;
- }
-
- const normalizedEmail = email.trim();
- if (!normalizedEmail) {
- setStatus('error');
- setMessage(t.emailAddress);
- return;
- }
-
- if (cooldownSeconds > 0) {
- setStatus('error');
- setMessage(t.authRateLimited);
- return;
- }
-
- setStatus('loading');
- setMessage('');
- const { error } = await supabase.auth.signInWithOtp({
- email: normalizedEmail,
- options: {
- emailRedirectTo: redirectTo
- }
- });
-
- if (error) {
- setStatus('error');
- if (error.status === 429 || String(error.message || '').toLowerCase().includes('rate limit')) {
- setCooldownSeconds(60);
- }
- setMessage(authErrorMessage(error, language));
- return;
- }
-
- setCooldownSeconds(60);
- setStatus('sent');
- setMessage(t.magicLinkSent);
- }
-
async function handleGoogleSignIn() {
if (!isSupabaseConfigured || !supabase) {
setStatus('error');
@@ -864,24 +838,8 @@ function AuthModal({ open, language, onClose }) {
</div>
<h2 id="auth-title">{t.signInTitle}</h2>
<p>{t.signInSubtitle}</p>
- <form className="authForm" onSubmit={handleEmailSubmit}>
- <label>
- <span>{t.emailAddress}</span>
- <input
- type="email"
- autoComplete="email"
- value={email}
- onChange={(event) => setEmail(event.target.value)}
- placeholder="[email protected]"
- />
- </label>
- <button type="submit" disabled={status === 'loading' || cooldownSeconds > 0}>
- {status === 'loading' ? <LoaderCircle className="spinIcon" size={17} /> : <Mail size={17} />}
- {cooldownSeconds > 0 ? t.tryAgainIn(cooldownSeconds) : t.sendMagicLink}
- </button>
- </form>
<button className="googleButton" type="button" onClick={handleGoogleSignIn} disabled={status === 'loading'}>
- <LogIn size={17} />
+ {status === 'loading' ? <LoaderCircle className="spinIcon" size={18} /> : <GoogleIcon />}
{t.continueWithGoogle}
</button>
{message ? (
@@ -894,7 +852,7 @@ function AuthModal({ open, language, onClose }) {
);
}
-function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, onBilling }) {
+function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, onBilling, onAccount }) {
const t = copy[language];
const [open, setOpen] = useState(false);
const ref = useDropdownDismiss(open, setOpen);
@@ -910,6 +868,8 @@ function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, on
const email = profile?.email || session.user?.email || t.account;
const displayName = profile?.fullName || session.user?.user_metadata?.name || email;
+ const avatarUrl = profile?.avatarUrl || session.user?.user_metadata?.avatar_url || session.user?.user_metadata?.picture || '';
+ const totalSpent = Number(profile?.usage?.totalGenerationCredits || 0);
return (
<div className="dropdownControl userMenu" ref={ref}>
@@ -922,14 +882,14 @@ function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, on
onClick={() => setOpen((current) => !current)}
>
<span className="avatarBadge">
- <UserCircle size={18} />
+ {avatarUrl ? <img src={avatarUrl} alt="" /> : <UserCircle size={18} />}
</span>
<ChevronDown size={15} />
</button>
{open ? (
<div className="dropdownMenu userDropdown" role="menu">
<div className="userSummary">
- <UserCircle size={32} />
+ {avatarUrl ? <img className="userSummaryAvatar" src={avatarUrl} alt="" /> : <UserCircle size={32} />}
<div>
<strong>{displayName}</strong>
<span>{email}</span>
@@ -951,11 +911,23 @@ function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, on
{formatMembershipStatus(profile?.membership, language)}
</span>
<span className="userStat">
- <PackageCheck size={15} />
- {profile?.freeUsed ? t.freeUsedShort : t.freeReady}
+ <ReceiptText size={15} />
+ {t.totalGenerationCredits}: {totalSpent}
</span>
</div>
<div className="dropdownDivider" />
+ <button
+ className="dropdownAction"
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setOpen(false);
+ onAccount();
+ }}
+ >
+ <Settings size={17} />
+ {t.accountSettings}
+ </button>
<button
className="dropdownAction"
type="button"
@@ -1000,6 +972,168 @@ function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, on
);
}
+function AccountPanel({ open, language, session, profile, onClose, onBilling, onProfileChange }) {
+ const t = copy[language];
+ const [fullName, setFullName] = useState('');
+ const [status, setStatus] = useState('idle');
+ const [message, setMessage] = useState('');
+
+ useEffect(() => {
+ if (!open) return;
+ setFullName(profile?.fullName || session?.user?.user_metadata?.name || '');
+ setStatus('idle');
+ setMessage('');
+ }, [open, profile?.fullName, session?.user?.user_metadata?.name]);
+
+ if (!open) return null;
+
+ const email = profile?.email || session?.user?.email || '';
+ const avatarUrl = profile?.avatarUrl || session?.user?.user_metadata?.avatar_url || session?.user?.user_metadata?.picture || '';
+ const usage = profile?.usage || {};
+ const recentTransactions = profile?.recentTransactions || [];
+
+ async function handleSubmit(event) {
+ event.preventDefault();
+ const nextName = fullName.trim();
+ if (!nextName) {
+ setStatus('error');
+ setMessage(t.profileUpdateFailed);
+ return;
+ }
+
+ setStatus('loading');
+ setMessage('');
+ try {
+ const response = await fetch('/api/me', {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...getAuthHeaders(session)
+ },
+ body: JSON.stringify({ fullName: nextName })
+ });
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload.ok) {
+ throw new Error(payload.error || 'PROFILE_UPDATE_FAILED');
+ }
+ if (payload.user) onProfileChange(payload.user);
+ setStatus('success');
+ setMessage(t.profileSaved);
+ } catch {
+ setStatus('error');
+ setMessage(t.profileUpdateFailed);
+ }
+ }
+
+ return (
+ <div
+ className="previewOverlay accountOverlay"
+ role="presentation"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <section className="accountDialog" role="dialog" aria-modal="true" aria-labelledby="account-title">
+ <button className="previewClose" type="button" onClick={onClose} aria-label={t.closePreview}>
+ <X size={20} />
+ </button>
+ <div className="accountHeader">
+ <div className="accountAvatar">
+ {avatarUrl ? <img src={avatarUrl} alt="" /> : <UserCircle size={44} />}
+ </div>
+ <div>
+ <span className="eyebrow">
+ <Settings size={16} />
+ {t.accountSettings}
+ </span>
+ <h2 id="account-title">{t.accountTitle}</h2>
+ <p>{t.accountSubtitle}</p>
+ </div>
+ </div>
+
+ <div className="accountGrid">
+ <form className="accountForm" onSubmit={handleSubmit}>
+ <label>
+ <span>{t.displayName}</span>
+ <input
+ value={fullName}
+ maxLength={80}
+ onChange={(event) => setFullName(event.target.value)}
+ />
+ </label>
+ <div className="accountEmail">
+ <span>{t.account}</span>
+ <strong>{email}</strong>
+ <em>{t.googleAvatarSource}</em>
+ </div>
+ <button type="submit" disabled={status === 'loading'}>
+ {status === 'loading' ? <LoaderCircle className="spinIcon" size={16} /> : <Check size={16} />}
+ {t.saveProfile}
+ </button>
+ {message ? (
+ <p className={cx('authMessage', status === 'error' && 'error', status === 'success' && 'sent')}>
+ {message}
+ </p>
+ ) : null}
+ </form>
+
+ <section className="accountOverview">
+ <h3>{t.accountOverview}</h3>
+ <div className="accountMetrics">
+ <div>
+ <span>{t.creditBalance}</span>
+ <strong>{profile?.creditBalance || 0}</strong>
+ </div>
+ <div>
+ <span>{t.currentPlan}</span>
+ <strong>{formatMembershipStatus(profile?.membership, language)}</strong>
+ </div>
+ <div>
+ <span>{t.totalGenerations}</span>
+ <strong>{Number(usage.totalGenerations || 0)}</strong>
+ </div>
+ <div>
+ <span>{t.totalGenerationCredits}</span>
+ <strong>{Number(usage.totalGenerationCredits || 0)}</strong>
+ </div>
+ </div>
+ <button className="portalButton accountBillingButton" type="button" onClick={onBilling}>
+ <CreditCard size={16} />
+ {t.membershipCenter}
+ </button>
+ </section>
+ </div>
+
+ <section className="transactionSection accountTransactions">
+ <h3>
+ <ReceiptText size={18} />
+ {t.recentUsage}
+ </h3>
+ {recentTransactions.length ? (
+ <div className="transactionList">
+ {recentTransactions.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 AdminPanel({ open, language, session, onClose }) {
const t = copy[language];
const [users, setUsers] = useState([]);
@@ -1749,10 +1883,10 @@ function PreviewDialog({
const isGenerating = generationState.status === 'generating';
const generatedImage = !isTemplate ? generationState.image : '';
const isSignedIn = Boolean(session?.access_token);
+ const creditBalance = Number(profile?.creditBalance || 0);
const isOutOfCredits = isSignedIn
- && !profile?.isSuperAdmin
- && Boolean(profile?.freeUsed)
- && Number(profile?.creditBalance || 0) <= 0;
+ && creditBalance <= 0
+ && (profile?.isSuperAdmin || Boolean(profile?.freeUsed));
const generationLocked = isGenerating;
const quotaText = isSignedIn ? getGenerationQuotaText(profile, language) : t.authRequired;
@@ -1986,6 +2120,7 @@ function App() {
const [session, setSession] = useState(null);
const [profile, setProfile] = useState(null);
const [authOpen, setAuthOpen] = useState(false);
+ const [accountOpen, setAccountOpen] = useState(false);
const [adminOpen, setAdminOpen] = useState(false);
const [billingOpen, setBillingOpen] = useState(false);
const [billingNotice, setBillingNotice] = useState('');
@@ -2138,6 +2273,7 @@ function App() {
if (supabase) await supabase.auth.signOut();
setSession(null);
setProfile(null);
+ setAccountOpen(false);
setAdminOpen(false);
setBillingOpen(false);
}
@@ -2180,6 +2316,7 @@ function App() {
profile={profile}
onSignIn={() => setAuthOpen(true)}
onSignOut={handleSignOut}
+ onAccount={() => setAccountOpen(true)}
onAdmin={() => setAdminOpen(true)}
onBilling={() => {
setBillingNotice('');
@@ -2325,6 +2462,19 @@ function App() {
language={language}
onClose={() => setAuthOpen(false)}
/>
+ <AccountPanel
+ open={accountOpen}
+ language={language}
+ session={session}
+ profile={profile}
+ onClose={() => setAccountOpen(false)}
+ onProfileChange={handleProfileChange}
+ onBilling={() => {
+ setAccountOpen(false);
+ setBillingNotice('');
+ setBillingOpen(true);
+ }}
+ />
<AdminPanel
open={adminOpen}
language={language}
diff --git a/src/styles.css b/src/styles.css
index 3e836cf..6926f85 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -306,6 +306,15 @@ button {
border-radius: 7px;
background: rgba(103, 232, 249, 0.12);
color: #9eeeff;
+ overflow: hidden;
+}
+
+.avatarBadge img,
+.userSummaryAvatar {
+ width: 100%;
+ height: 100%;
+ border-radius: inherit;
+ object-fit: cover;
}
.userDropdown {
@@ -324,6 +333,13 @@ button {
color: #9eeeff;
}
+.userSummaryAvatar {
+ width: 34px;
+ height: 34px;
+ border-radius: 8px;
+ border: 1px solid rgba(103, 232, 249, 0.24);
+}
+
.userSummary strong,
.userSummary span {
display: block;
@@ -1725,7 +1741,8 @@ button {
}
.authDialog h2,
-.adminDialog h2 {
+.adminDialog h2,
+.accountDialog h2 {
margin: 18px 48px 10px 0;
color: #ffffff;
font-size: 30px;
@@ -1734,43 +1751,13 @@ button {
}
.authDialog p,
-.adminDialog p {
+.adminDialog p,
+.accountDialog p {
margin: 0;
color: #aebcd0;
line-height: 1.68;
}
-.authForm {
- display: grid;
- gap: 12px;
- margin-top: 22px;
-}
-
-.authForm label {
- display: grid;
- gap: 8px;
- color: #eaf3ff;
- font-size: 13px;
- font-weight: 900;
-}
-
-.authForm input {
- width: 100%;
- min-height: 46px;
- border: 1px solid rgba(255, 255, 255, 0.12);
- border-radius: 8px;
- outline: 0;
- padding: 0 12px;
- background: rgba(3, 7, 15, 0.72);
- color: #ffffff;
-}
-
-.authForm input:focus {
- border-color: rgba(103, 232, 249, 0.72);
- box-shadow: 0 0 0 3px rgba(103, 232, 249, 0.1);
-}
-
-.authForm button,
.googleButton,
.adminHeader button {
display: inline-flex;
@@ -1788,12 +1775,30 @@ button {
.googleButton {
width: 100%;
- margin-top: 12px;
- border-color: rgba(255, 255, 255, 0.14);
- background: rgba(255, 255, 255, 0.08);
+ margin-top: 24px;
+ min-height: 44px;
+ border-color: #dadce0;
+ background: #ffffff;
+ color: #1f1f1f;
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 14px;
+ font-weight: 700;
+ letter-spacing: 0;
+ box-shadow: 0 1px 2px rgba(3, 7, 15, 0.16);
+}
+
+.googleButton:hover {
+ background: #f8fafd;
+ border-color: #d2e3fc;
+ box-shadow: 0 2px 6px rgba(26, 115, 232, 0.18);
+}
+
+.googleIcon {
+ width: 18px;
+ height: 18px;
+ flex: 0 0 auto;
}
-.authForm button:disabled,
.googleButton:disabled,
.adminHeader button:disabled {
cursor: not-allowed;
@@ -1833,6 +1838,37 @@ button {
padding: 24px;
}
+.accountDialog {
+ width: min(920px, 100%);
+ padding: 24px;
+}
+
+.accountHeader {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: 16px;
+ align-items: start;
+ margin-bottom: 20px;
+}
+
+.accountAvatar {
+ display: grid;
+ width: 72px;
+ height: 72px;
+ overflow: hidden;
+ border: 1px solid rgba(103, 232, 249, 0.24);
+ border-radius: 8px;
+ background: rgba(103, 232, 249, 0.1);
+ color: #9eeeff;
+ place-items: center;
+}
+
+.accountAvatar img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
.adminHeader {
display: flex;
align-items: flex-start;
@@ -1962,6 +1998,7 @@ button {
}
.adminAdjustForm button,
+.accountForm button,
.tableAction,
.billingState button,
.billingCard button,
@@ -2008,6 +2045,8 @@ button {
}
.billingSummary div,
+.accountForm,
+.accountOverview,
.billingCard,
.transactionSection,
.billingState {
@@ -2024,6 +2063,7 @@ button {
}
.billingSummary span,
+.accountMetrics span,
.billingCard span,
.transactionItem span {
color: #8eeeff;
@@ -2032,19 +2072,103 @@ button {
text-transform: uppercase;
}
-.billingSummary strong {
+.billingSummary strong,
+.accountMetrics strong {
color: #ffffff;
font-size: 26px;
line-height: 1.1;
}
.billingSummary em,
+.accountEmail em,
.transactionItem em {
color: #93a4bc;
font-size: 12px;
font-style: normal;
}
+.accountGrid {
+ display: grid;
+ grid-template-columns: minmax(260px, 0.85fr) minmax(0, 1.15fr);
+ gap: 16px;
+}
+
+.accountForm,
+.accountOverview {
+ padding: 14px;
+}
+
+.accountForm {
+ display: grid;
+ gap: 12px;
+}
+
+.accountForm label,
+.accountEmail {
+ display: grid;
+ gap: 7px;
+}
+
+.accountForm label span,
+.accountEmail span {
+ color: #8eeeff;
+ font-size: 12px;
+ font-weight: 900;
+ text-transform: uppercase;
+}
+
+.accountForm input {
+ width: 100%;
+ min-height: 44px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ outline: 0;
+ padding: 0 12px;
+ background: rgba(3, 7, 15, 0.72);
+ color: #ffffff;
+ font-weight: 850;
+}
+
+.accountForm input:focus {
+ border-color: rgba(103, 232, 249, 0.72);
+ box-shadow: 0 0 0 3px rgba(103, 232, 249, 0.1);
+}
+
+.accountEmail strong {
+ color: #eaf3ff;
+ overflow-wrap: anywhere;
+}
+
+.accountOverview h3 {
+ margin: 0 0 12px;
+ color: #eaf3ff;
+ font-size: 16px;
+ letter-spacing: 0;
+}
+
+.accountMetrics {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.accountMetrics div {
+ display: grid;
+ gap: 5px;
+ min-height: 88px;
+ border-radius: 8px;
+ padding: 12px;
+ background: rgba(3, 7, 15, 0.45);
+}
+
+.accountBillingButton {
+ margin-top: 14px;
+}
+
+.accountTransactions {
+ margin-top: 16px;
+}
+
.billingState {
display: flex;
align-items: center;
@@ -2132,6 +2256,7 @@ button {
.billingCard button:disabled,
.portalButton:disabled,
+.accountForm button:disabled,
.adminAdjustForm button:disabled {
cursor: not-allowed;
opacity: 0.6;
@@ -2297,6 +2422,10 @@ button {
grid-template-columns: 1fr;
}
+ .accountGrid {
+ grid-template-columns: 1fr;
+ }
+
.comparisonFigure img {
height: min(48vh, 520px);
}
@@ -2475,12 +2604,14 @@ button {
.authDialog,
.adminDialog,
+ .accountDialog,
.billingDialog {
max-height: calc(100vh - 20px);
}
.authDialog,
.adminDialog,
+ .accountDialog,
.billingDialog {
padding: 20px 16px;
}
@@ -2489,11 +2620,16 @@ button {
flex-direction: column;
}
+ .accountHeader {
+ grid-template-columns: 1fr;
+ }
+
.adminHeader button {
width: 100%;
}
.adminAdjustForm,
+ .accountMetrics,
.billingSummary,
.billingSections,
.transactionItem {
diff --git a/supabase/migrations/20260512090000_google_account_center.sql b/supabase/migrations/20260512090000_google_account_center.sql
new file mode 100644
index 0000000..d9df17f
--- /dev/null
+++ b/supabase/migrations/20260512090000_google_account_center.sql
@@ -0,0 +1,129 @@
+drop function if exists public.reserve_generation_usage(uuid, integer, text);
+
+create or replace function public.reserve_generation_usage(
+ p_user_id uuid,
+ p_case_id integer,
+ p_prompt text,
+ p_force_credit boolean default false
+)
+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 not p_force_credit and 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',
+ 'forceCredit', p_force_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;
+$$;
+
+create or replace function public.get_user_account_usage(
+ p_user_id uuid
+)
+returns table (
+ total_generations integer,
+ total_generation_credits integer
+)
+language plpgsql
+security definer
+set search_path = public
+as $$
+begin
+ return query
+ select
+ count(*)::integer as total_generations,
+ coalesce(sum(r.credit_amount), 0)::integer as total_generation_credits
+ from public.generation_reservations as r
+ where r.user_id = p_user_id
+ and r.status = 'succeeded';
+end;
+$$;
+
+revoke execute on function public.reserve_generation_usage(uuid, integer, text, boolean) from public, anon, authenticated;
+revoke execute on function public.get_user_account_usage(uuid) from public, anon, authenticated;
+
+grant execute on function public.reserve_generation_usage(uuid, integer, text, boolean) to service_role;
+grant execute on function public.get_user_account_usage(uuid) to service_role;