feat: add Railway-ready Jyotish chat product

This commit is contained in:
Jesse_Chen
2026-07-15 22:23:17 +08:00
parent 4a268c75f2
commit 4aa0105fa4
77 changed files with 15439 additions and 80 deletions
+169
View File
@@ -0,0 +1,169 @@
"use client";
import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
type CodeRecord = {
id: string;
mask: string;
credits: number;
expiresAt: string | null;
redeemedBy: string | null;
redeemedEmail: string | null;
redeemedAt: string | null;
note: string | null;
createdAt: string;
};
type GeneratedCode = { code: string; credits: number; expiresAt: string | null };
function apiMessage(payload: unknown, fallback: string) {
if (!payload || typeof payload !== "object") return fallback;
const data = payload as Record<string, unknown>;
return [data.message, data.error].find((value) => typeof value === "string") as string || fallback;
}
function redirectForAuth(response: Response) {
if (response.status === 401) window.location.assign("/login");
if (response.status === 403) window.location.assign("/");
}
function codeStatus(code: CodeRecord) {
if (code.redeemedAt) return "已兑换";
if (code.expiresAt && new Date(code.expiresAt).getTime() <= Date.now()) return "已过期";
return "可用";
}
function formatDate(value: string | null) {
return value ? new Intl.DateTimeFormat("zh-CN", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—";
}
export default function AdminCodesPage() {
const [codes, setCodes] = useState<CodeRecord[]>([]);
const [generated, setGenerated] = useState<GeneratedCode[]>([]);
const [credits, setCredits] = useState(10);
const [count, setCount] = useState(1);
const [expiresAt, setExpiresAt] = useState("");
const [note, setNote] = useState("");
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [error, setError] = useState("");
const [copyNotice, setCopyNotice] = useState("");
useEffect(() => {
const controller = new AbortController();
void fetch("/api/admin/codes", { signal: controller.signal, cache: "no-store" })
.then(async (response) => {
redirectForAuth(response);
const payload = await response.json().catch(() => null);
if (!response.ok) throw new Error(apiMessage(payload, "暂时无法读取兑换码"));
setCodes((payload as { codes: CodeRecord[] }).codes);
})
.catch((caught) => {
if ((caught as Error).name !== "AbortError") setError(caught instanceof Error ? caught.message : "暂时无法读取兑换码");
})
.finally(() => setLoading(false));
return () => controller.abort();
}, []);
async function reloadCodes() {
const response = await fetch("/api/admin/codes", { cache: "no-store" });
redirectForAuth(response);
const payload = await response.json().catch(() => null);
if (!response.ok) throw new Error(apiMessage(payload, "暂时无法刷新兑换码"));
setCodes((payload as { codes: CodeRecord[] }).codes);
}
async function createCodes(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (creating) return;
setCreating(true);
setError("");
setGenerated([]);
setCopyNotice("");
try {
const response = await fetch("/api/admin/codes", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
credits,
count,
...(expiresAt ? { expiresAt: new Date(expiresAt).toISOString() } : {}),
...(note.trim() ? { note: note.trim() } : {}),
}),
});
redirectForAuth(response);
const payload = await response.json().catch(() => null);
if (!response.ok) throw new Error(apiMessage(payload, "生成兑换码失败"));
setGenerated((payload as { codes: GeneratedCode[] }).codes);
await reloadCodes();
} catch (caught) {
setError(caught instanceof Error ? caught.message : "生成兑换码失败");
} finally {
setCreating(false);
}
}
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
setCopyNotice("已复制到剪贴板");
} catch {
setCopyNotice("无法自动复制,请手动选择兑换码");
}
}
return (
<main className="standalone-page admin-page">
<header className="admin-header">
<div><p className="page-eyebrow">管理员</p><h1>兑换码</h1></div>
<Link className="button-secondary" href="/">返回对话</Link>
</header>
<div className="admin-scroll">
<section className="admin-section" aria-labelledby="create-codes-title">
<div className="section-title"><div><h2 id="create-codes-title">生成兑换码</h2><p>完整兑换码只在本次生成结果中显示,请立即复制保存。</p></div></div>
<form className="code-form" onSubmit={createCodes}>
<label><span>每个点数</span><input type="number" min={1} required value={credits} onChange={(event) => setCredits(Number(event.target.value))} /></label>
<label><span>生成数量</span><input type="number" min={1} max={100} required value={count} onChange={(event) => setCount(Number(event.target.value))} /></label>
<label><span>有效期 <em>可选</em></span><input type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} /></label>
<label className="note-field"><span>备注 <em>可选</em></span><input maxLength={200} value={note} onChange={(event) => setNote(event.target.value)} placeholder="例如:7 月活动" /></label>
<button className="button-primary" type="submit" disabled={creating || credits < 1 || count < 1 || count > 100}>{creating ? "生成中" : "生成"}</button>
</form>
{error && <p className="form-error" role="alert">{error}</p>}
</section>
{generated.length > 0 && (
<section className="admin-section generated-section" aria-labelledby="generated-title">
<div className="section-title">
<div><h2 id="generated-title">本次生成的完整码</h2><p>离开或刷新页面后将不再显示。</p></div>
<button className="button-secondary" type="button" onClick={() => void copy(generated.map((item) => item.code).join("\n"))}>复制全部</button>
</div>
<div className="generated-list">
{generated.map((item) => (
<div key={item.code}><code>{item.code}</code><span>{item.credits} 点</span><button type="button" onClick={() => void copy(item.code)}>复制</button></div>
))}
</div>
{copyNotice && <p className="form-success" role="status">{copyNotice}</p>}
</section>
)}
<section className="admin-section" aria-labelledby="codes-list-title">
<div className="section-title"><div><h2 id="codes-list-title">兑换码状态</h2><p>{loading ? "正在读取…" : `${codes.length} 条记录`}</p></div></div>
<div className="admin-table-wrap">
<table className="admin-table">
<thead><tr><th>兑换码</th><th>点数</th><th>状态</th><th>有效期</th><th>兑换账户</th><th>兑换时间</th><th>备注</th><th>创建时间</th></tr></thead>
<tbody>
{codes.map((code) => (
<tr key={code.id}>
<td><code>{code.mask}</code></td><td>{code.credits}</td><td><span className={`code-status status-${codeStatus(code)}`}>{codeStatus(code)}</span></td><td>{formatDate(code.expiresAt)}</td><td>{code.redeemedEmail || code.redeemedBy || "—"}</td><td>{formatDate(code.redeemedAt)}</td><td>{code.note || "—"}</td><td>{formatDate(code.createdAt)}</td>
</tr>
))}
{!loading && codes.length === 0 && <tr><td colSpan={8} className="empty-cell">尚未生成兑换码</td></tr>}
</tbody>
</table>
</div>
</section>
</div>
</main>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { ReactNode } from "react";
import { redirect } from "next/navigation";
import { isAdminEmail } from "@/lib/supabase/admin";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export default async function AdminLayout({ children }: { children: ReactNode }) {
const supabase = await createServerSupabaseClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) redirect("/login");
if (!isAdminEmail(user.email)) redirect("/");
return children;
}
+40
View File
@@ -0,0 +1,40 @@
import { NextResponse } from "next/server";
import { isAdminEmail } from "@/lib/supabase/admin";
import {
isSupabaseConfigurationError,
} from "@/lib/supabase/config";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
export async function GET() {
try {
const supabase = await createServerSupabaseClient();
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json({ error: "请先登录" }, { status: 401 });
}
const { data: profile, error } = await supabase
.from("profiles")
.select("credits")
.eq("id", user.id)
.single();
if (error) {
return NextResponse.json({ error: "暂时无法读取账户余额" }, { status: 500 });
}
return NextResponse.json({
user: { id: user.id, email: user.email ?? null },
credits: profile.credits,
isAdmin: isAdminEmail(user.email),
});
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json({ error: "Supabase 尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
}
return NextResponse.json({ error: "账户服务暂时不可用" }, { status: 500 });
}
}
+113
View File
@@ -0,0 +1,113 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import {
createAdminSupabaseClient,
isAdminEmail,
} from "@/lib/supabase/admin";
import {
generateRedeemCode,
hashRedeemCode,
maskRedeemCode,
} from "@/lib/supabase/codes";
import {
isSupabaseConfigurationError,
SupabaseConfigurationError,
} from "@/lib/supabase/config";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
const createCodesSchema = z.object({
credits: z.number().int().positive().max(1_000_000),
count: z.number().int().min(1).max(100),
expiresAt: z.string().datetime({ offset: true }).optional(),
note: z.string().trim().max(500).optional(),
});
async function requireAdmin() {
if (!process.env.ADMIN_EMAILS?.trim()) {
throw new SupabaseConfigurationError(["ADMIN_EMAILS"]);
}
const supabase = await createServerSupabaseClient();
const { data: { user }, error } = await supabase.auth.getUser();
if (error || !user) return { response: NextResponse.json({ error: "请先登录" }, { status: 401 }) };
if (!isAdminEmail(user.email)) {
return { response: NextResponse.json({ error: "无管理员权限" }, { status: 403 }) };
}
return { user };
}
export async function GET() {
try {
const auth = await requireAdmin();
if ("response" in auth) return auth.response;
const admin = createAdminSupabaseClient();
const { data, error } = await admin
.from("redemption_codes")
.select("id,code_mask,credits,expires_at,note,created_at,redeemed_by,redeemed_email,redeemed_at")
.order("created_at", { ascending: false })
.limit(100);
if (error) {
return NextResponse.json({ error: "暂时无法读取兑换码列表" }, { status: 500 });
}
return NextResponse.json({
codes: data.map((code) => ({
id: code.id,
mask: code.code_mask,
credits: code.credits,
expiresAt: code.expires_at,
note: code.note,
createdAt: code.created_at,
redeemedBy: code.redeemed_by,
redeemedEmail: code.redeemed_email,
redeemedAt: code.redeemed_at,
})),
});
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json({ error: "Supabase 或管理员白名单尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
}
return NextResponse.json({ error: "兑换码管理服务暂时不可用" }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const auth = await requireAdmin();
if ("response" in auth) return auth.response;
const parsed = createCodesSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: "兑换码参数不正确" }, { status: 400 });
}
const { credits, count, expiresAt, note } = parsed.data;
const codes = Array.from({ length: count }, generateRedeemCode);
const admin = createAdminSupabaseClient();
const { error } = await admin.from("redemption_codes").insert(codes.map((code) => ({
code_hash: hashRedeemCode(code),
code_mask: maskRedeemCode(code),
credits,
expires_at: expiresAt ?? null,
note: note || null,
created_by: auth.user.id,
})));
if (error) {
return NextResponse.json({ error: "生成兑换码失败,请重试" }, { status: 500 });
}
return NextResponse.json({
codes: codes.map((code) => ({ code, credits, expiresAt: expiresAt ?? null, note: note || null })),
}, { status: 201 });
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json({ error: "Supabase 或管理员白名单尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
}
return NextResponse.json({ error: "兑换码管理服务暂时不可用" }, { status: 500 });
}
}
+332
View File
@@ -0,0 +1,332 @@
import { NextResponse } from "next/server";
import {
consultationInputSchema,
jyotishAgent,
runConsultationWorkflow,
} from "@/mastra";
import {
languageModelConfigurationMessage,
languageModelSettings,
} from "@/mastra/model";
import { blocksPromptExtraction } from "@/lib/consult-safety";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { z } from "zod";
export const runtime = "nodejs";
export const maxDuration = 60;
const chatRequestSchema = consultationInputSchema.extend({
name: z.string().trim().max(80).optional().default(""),
history: z.array(z.object({
role: z.enum(["user", "assistant"]),
text: z.string().max(4000),
})).max(20).default([]),
});
type StreamHooks = {
onComplete?: () => Promise<void>;
onError?: (error: unknown) => Promise<void>;
};
type CreditRpcResult = {
success?: boolean;
credits?: number;
error_code?: string;
};
function currentTimeContext(now = new Date()) {
const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000)
.toISOString()
.replace("T", " ")
.slice(0, 19);
return `服务端当前时间(权威):${now.toISOString()};中国标准时间(UTC+8):${chinaTime}。涉及“现在、今天、今年、未来几个月”等相对时间时,以此为准。`;
}
function streamTextResponse(
stream: AsyncIterable<string>,
mode: "engine" | "mastra",
hooks: StreamHooks = {},
) {
const iterator = stream[Symbol.asyncIterator]();
const encoder = new TextEncoder();
let settled = false;
let emitted = false;
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
settled = true;
if (!emitted) {
const error = new Error("empty_stream");
await hooks.onError?.(error);
controller.error(error);
return;
}
await hooks.onComplete?.();
controller.close();
return;
}
if (/\S/.test(value)) emitted = true;
controller.enqueue(encoder.encode(value));
} catch (error) {
if (!settled) {
settled = true;
await hooks.onError?.(error);
}
controller.error(error);
}
},
async cancel() {
const refundBeforeOutput = !settled && !emitted;
settled = true;
try {
await iterator.return?.();
} finally {
if (refundBeforeOutput) {
await hooks.onError?.(new Error("stream_cancelled_before_output"));
}
}
},
});
return new Response(body, {
headers: {
"cache-control": "no-cache, no-transform",
"content-type": "text/plain; charset=utf-8",
"x-accel-buffering": "no",
"x-ayanam-mode": mode,
},
});
}
async function* staticTextStream(text: string) {
yield text;
}
function engineSummary(data: Record<string, unknown>) {
const topics = Array.isArray(data.guided_topics) ? data.guided_topics : [];
const routing = data.routing && typeof data.routing === "object" ? data.routing : {};
const route = "primary_route" in routing ? String(routing.primary_route) : "统一咨询工作流";
const topicText = topics
.slice(0, 3)
.map((item) => {
if (!item || typeof item !== "object") return null;
const record = item as Record<string, unknown>;
return String(record.title || record.label || record.theme || "值得继续探索的主题");
})
.filter(Boolean);
return [
"星盘计算已完成,但当前没有配置 AI 模型,因此先返回引擎摘要。",
`本次路由:${route}。`,
topicText.length ? `建议继续查看:${topicText.join("、")}。` : "可继续查看事业、关系与年度时间窗口。",
"启动 AI 解读需配置模型;原始计算结果已保留。",
].join("\n");
}
function configuredModelId() {
if (languageModelSettings.mode === "compatible") {
return process.env.LLM_MODEL?.trim() || "third-party";
}
return process.env.MASTRA_MODEL?.trim() || "openai/gpt-5-mini";
}
async function recordModelUsage(
accounting: ReturnType<typeof createAdminSupabaseClient>,
userId: string,
requestId: string,
usage: Promise<{ inputTokens?: number; outputTokens?: number }>,
) {
try {
const resolved = await usage;
const { error } = await accounting
.from("credit_transactions")
.update({
model: configuredModelId(),
input_tokens: Math.max(0, Math.trunc(resolved.inputTokens ?? 0)),
output_tokens: Math.max(0, Math.trunc(resolved.outputTokens ?? 0)),
})
.eq("user_id", userId)
.eq("transaction_type", "reserve")
.eq("request_id", requestId);
if (error) console.warn("[billing] unable to record model usage", error.message);
} catch (error) {
console.warn("[billing] unable to read model usage", error);
}
}
export async function POST(request: Request) {
let supabase: Awaited<ReturnType<typeof createServerSupabaseClient>>;
let accounting: ReturnType<typeof createAdminSupabaseClient>;
try {
supabase = await createServerSupabaseClient();
accounting = createAdminSupabaseClient();
} catch {
return NextResponse.json(
{ error: "服务尚未配置", message: "请先配置 Supabase 环境变量。" },
{ status: 503 },
);
}
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: "请先登录", message: "登录后才能开始咨询。" },
{ status: 401 },
);
}
const parsed = chatRequestSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json(
{ error: "出生资料或问题格式不正确", details: parsed.error.flatten() },
{ status: 400 },
);
}
const userControlledPrompt = [
parsed.data.question,
...parsed.data.history
.filter((message) => message.role === "user")
.map((message) => message.text),
].join("\n");
if (blocksPromptExtraction(userControlledPrompt)) {
return NextResponse.json(
{ error: "无法处理该请求", message: "我不能提供系统提示词、技能原文或任何密钥。你可以继续询问占星相关问题。" },
{ status: 400 },
);
}
const userId = user.id;
const requestId = crypto.randomUUID();
let refunded = false;
let refundInFlight: Promise<void> | null = null;
async function performRefund() {
if (refunded) return;
if (refundInFlight) return refundInFlight;
refundInFlight = (async () => {
let lastError = "unknown_refund_error";
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
const { data, error } = await accounting.rpc("refund_credit", {
p_user_id: userId,
p_request_id: requestId,
});
const result = Array.isArray(data) ? data[0] : data;
if (!error && result?.success) {
refunded = true;
return;
}
lastError = error?.message || result?.error_code || "refund_rejected";
} catch (error) {
lastError = error instanceof Error ? error.message : "refund_request_failed";
}
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, attempt * 150));
}
}
console.error(`[billing] refund failed for ${requestId}: ${lastError}`);
})();
try {
await refundInFlight;
} finally {
refundInFlight = null;
}
}
async function refund() {
await performRefund();
}
let reserveResult: CreditRpcResult | null = null;
let reserveErrorMessage = "";
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
const { data, error } = await accounting.rpc("reserve_credit", {
p_user_id: userId,
p_request_id: requestId,
});
const result = (Array.isArray(data) ? data[0] : data) as CreditRpcResult | null;
if (!error && result) {
reserveResult = result;
break;
}
reserveErrorMessage = error?.message || "empty_reservation_response";
} catch (error) {
reserveErrorMessage = error instanceof Error ? error.message : "reservation_request_failed";
}
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, attempt * 150));
}
}
if (!reserveResult) {
await performRefund();
return NextResponse.json(
{ error: "暂时无法确认咨询点数", message: reserveErrorMessage || "请稍后重试。" },
{ status: 503 },
);
}
if (!reserveResult.success) {
const insufficient = reserveResult.error_code === "insufficient_credits";
return NextResponse.json(
{
error: insufficient ? "咨询点数不足" : "暂时无法扣除咨询点数",
message: insufficient ? "请先兑换咨询点数后再继续。" : reserveResult.error_code || "请稍后重试。",
},
{ status: insufficient ? 402 : 503 },
);
}
try {
const { history, name, ...toolInput } = parsed.data;
if (!languageModelSettings.configured) {
const evidence = await runConsultationWorkflow(toolInput);
return streamTextResponse(staticTextStream(engineSummary(evidence)), "engine", {
onError: refund,
});
}
const result = await jyotishAgent.stream([
...history.map((message) => message.role === "user"
? { role: "user" as const, content: message.text }
: { role: "assistant" as const, content: message.text }),
{
role: "user",
content: [
currentTimeContext(),
name ? `用户称呼:${name}` : "",
parsed.data.question,
"\n需要查询星盘时,使用以下经过服务端校验的工具参数:",
JSON.stringify(toolInput),
].filter(Boolean).join("\n"),
},
]);
return streamTextResponse(result.textStream, "mastra", {
onComplete: () => recordModelUsage(accounting, userId, requestId, result.totalUsage),
onError: refund,
});
} catch (error) {
await refund();
const message = error instanceof Error ? error.message : "咨询服务暂时不可用";
return NextResponse.json(
{
error: "暂时无法生成解读",
message,
recovery: `请确认 Python API 已运行,并检查 JYOTISH_API_BASE 与模型配置。${languageModelConfigurationMessage() ? ` ${languageModelConfigurationMessage()}` : ""}`,
},
{ status: 503 },
);
}
}
+173
View File
@@ -0,0 +1,173 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { onboardingAgent } from "@/mastra";
import { languageModelSettings } from "@/mastra/model";
export const runtime = "nodejs";
export const maxDuration = 30;
const ONBOARDING_VERSION = "ayanam-onboarding-v2";
const ONBOARDING_PENDING_VERSION = `${ONBOARDING_VERSION}:pending`;
const ONBOARDING_CLAIM_TTL_MS = 2 * 60 * 1000;
const onboardingSchema = z.object({
greeting: z.string().trim().min(8).max(180),
suggestions: z.tuple([
z.object({ theme: z.literal("career"), text: z.string().trim().min(4).max(80) }),
z.object({ theme: z.literal("marriage"), text: z.string().trim().min(4).max(80) }),
z.object({ theme: z.literal("timing"), text: z.string().trim().min(4).max(80) }),
]),
});
type OnboardingPayload = z.infer<typeof onboardingSchema>;
const fallbackPayload: OnboardingPayload = {
greeting: "出生资料已经准备好了。你可以从下面三个方向开始,也可以直接告诉我现在最想问的事。",
suggestions: [
{ theme: "career", text: "我的事业优势更适合怎样发挥?" },
{ theme: "marriage", text: "我在关系里容易重复什么模式?" },
{ theme: "timing", text: "未来一年有哪些阶段值得提前准备?" },
],
};
function parseJsonObject(text: string) {
const normalized = text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
const start = normalized.indexOf("{");
const end = normalized.lastIndexOf("}");
if (start < 0 || end <= start) throw new Error("onboarding_json_missing");
return JSON.parse(normalized.slice(start, end + 1));
}
function hasCompleteBirthProfile(profile: Record<string, unknown>) {
return Boolean(
profile.name
&& profile.birth_date
&& profile.birth_time
&& profile.country_code
&& profile.province_code
&& profile.city_code,
);
}
export async function POST() {
let supabase: Awaited<ReturnType<typeof createServerSupabaseClient>>;
let admin: ReturnType<typeof createAdminSupabaseClient>;
try {
supabase = await createServerSupabaseClient();
admin = createAdminSupabaseClient();
} catch {
return NextResponse.json(
{ error: "服务尚未配置", message: "请先配置 Supabase 环境变量。" },
{ status: 503 },
);
}
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: "请先登录", message: "登录后才能准备初始问题。" },
{ status: 401 },
);
}
const { data: profile, error: profileError } = await admin
.from("profiles")
.select("name,birth_date,birth_time,country_code,province_code,city_code,onboarding_payload,onboarding_version,onboarding_generated_at")
.eq("id", user.id)
.maybeSingle();
if (profileError || !profile) {
return NextResponse.json(
{ error: "无法读取用户档案", message: profileError?.message || "请重新登录后再试。" },
{ status: 503 },
);
}
if (!hasCompleteBirthProfile(profile)) {
return NextResponse.json(
{ error: "出生资料尚未完成", message: "请先填写称呼、出生日期、时间和地点。" },
{ status: 409 },
);
}
if (profile.onboarding_version === ONBOARDING_VERSION) {
const cached = onboardingSchema.safeParse(profile.onboarding_payload);
if (cached.success) {
return NextResponse.json({ ...cached.data, source: "cache" });
}
}
const generatedAt = typeof profile.onboarding_generated_at === "string"
? Date.parse(profile.onboarding_generated_at)
: 0;
const activeClaim = profile.onboarding_version === ONBOARDING_PENDING_VERSION
&& Number.isFinite(generatedAt)
&& Date.now() - generatedAt < ONBOARDING_CLAIM_TTL_MS;
if (activeClaim) {
return NextResponse.json({ ...fallbackPayload, source: "pending" });
}
const claimTime = new Date().toISOString();
let claim = admin
.from("profiles")
.update({
onboarding_version: ONBOARDING_PENDING_VERSION,
onboarding_generated_at: claimTime,
})
.eq("id", user.id);
claim = profile.onboarding_version === null
? claim.is("onboarding_version", null)
: claim.eq("onboarding_version", profile.onboarding_version);
const { data: claimedProfile, error: claimError } = await claim.select("id").maybeSingle();
if (claimError) {
return NextResponse.json(
{ error: "暂时无法准备初始问题", message: claimError.message },
{ status: 503 },
);
}
if (!claimedProfile) {
return NextResponse.json({ ...fallbackPayload, source: "pending" });
}
let payload = fallbackPayload;
let source: "agent" | "fallback" = "fallback";
if (languageModelSettings.configured) {
try {
const result = await onboardingAgent.generate([
{
role: "user",
content: [
profile.name ? `用户称呼:${String(profile.name).slice(0, 80)}` : "用户未填写称呼。",
"用户已经完成出生资料。请生成首次欢迎语和三个入门问题。",
].join("\n"),
},
]);
const parsed = onboardingSchema.safeParse(parseJsonObject(result.text));
if (parsed.success) {
payload = parsed.data;
source = "agent";
}
} catch (error) {
console.warn("[onboarding] agent generation failed; using safe fallback", error);
}
}
const { error: cacheError } = await admin
.from("profiles")
.update({
onboarding_payload: payload,
onboarding_version: ONBOARDING_VERSION,
onboarding_generated_at: new Date().toISOString(),
})
.eq("id", user.id)
.eq("onboarding_version", ONBOARDING_PENDING_VERSION);
if (cacheError) {
console.warn("[onboarding] unable to cache generated content", cacheError.message);
}
return NextResponse.json({ ...payload, source });
}
+61
View File
@@ -0,0 +1,61 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { hashRedeemCode, normalizeRedeemCode } from "@/lib/supabase/codes";
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
const requestSchema = z.object({ code: z.string().max(100) });
const redeemErrors: Record<string, { status: number; message: string }> = {
unauthorized: { status: 401, message: "请先登录" },
invalid_code: { status: 404, message: "兑换码不存在" },
expired_code: { status: 410, message: "兑换码已过期" },
already_redeemed: { status: 409, message: "兑换码已被使用" },
profile_missing: { status: 500, message: "账户资料不存在,请稍后重试" },
};
export async function POST(request: Request) {
try {
const parsed = requestSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: "请输入有效兑换码" }, { status: 400 });
}
const code = normalizeRedeemCode(parsed.data.code);
if (!/^JYOTISH-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(code)) {
return NextResponse.json({ error: "兑换码格式不正确" }, { status: 400 });
}
const supabase = await createServerSupabaseClient();
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json({ error: "请先登录" }, { status: 401 });
}
const { data, error } = await supabase.rpc("redeem_code", {
p_code_hash: hashRedeemCode(code),
});
if (error) {
return NextResponse.json({ error: "兑换失败,请稍后重试" }, { status: 500 });
}
const result = Array.isArray(data) ? data[0] : data;
if (!result?.success) {
const mapped = redeemErrors[result?.error_code] ?? {
status: 500,
message: "兑换失败,请稍后重试",
};
return NextResponse.json({ error: mapped.message }, { status: mapped.status });
}
return NextResponse.json({ credits: result.credits });
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json({ error: "Supabase 尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
}
return NextResponse.json({ error: "兑换服务暂时不可用" }, { status: 500 });
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+272
View File
@@ -0,0 +1,272 @@
:root {
--canvas: #f3f2ee;
--surface: #fbfaf7;
--ink: #1d1d1f;
--muted: #676762;
--faint: #8a8983;
--line: #d8d6cf;
--line-strong: #b8b5ad;
--accent: #85432f;
--accent-soft: #f4e8e2;
--danger: #9a2f2f;
--success: #28633e;
--ease-out: cubic-bezier(.22, 1, .36, 1);
}
* { box-sizing: border-box; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
html, body { width: 100%; height: 100%; overflow: hidden; }
body { margin: 0; background: var(--canvas); color: var(--ink); font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "SF Pro Display", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; text-rendering: optimizeLegibility; }
button, input, textarea, select { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
button { color: inherit; }
button:focus-visible, a:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 70%, white); outline-offset: 2px; }
button:disabled { cursor: default; opacity: .46; }
.chat-app { width: 100%; height: 100dvh; min-height: 0; overflow: hidden; display: grid; grid-template-columns: 272px minmax(0, 1fr); background: var(--surface); }
.sidebar { height: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column; padding: 16px 12px 12px; border-right: 1px solid rgba(120, 118, 111, .26); background: rgba(235, 233, 227, .86); backdrop-filter: saturate(130%) blur(20px); }
.brand-row { height: 44px; display: flex; align-items: center; gap: 10px; padding: 0 8px; font-size: 17px; letter-spacing: -.02em; }
.brand-mark, .welcome-mark, .auth-brand span { width: 28px; height: 28px; display: grid; place-items: center; border: 1px solid #c6a99f; color: var(--accent); font-size: 15px; font-weight: 600; line-height: 1; }
.new-chat { width: 100%; min-height: 44px; display: flex; align-items: center; justify-content: center; gap: 7px; margin: 14px 0 20px; padding: 0 14px; border: 1px solid var(--ink); border-radius: 10px; background: var(--ink); color: white; cursor: pointer; font-size: 13px; font-weight: 650; transition: background-color 140ms ease-out, transform 100ms ease-out; }
.new-chat span { font-size: 18px; font-weight: 400; line-height: 1; }
.new-chat:not(:disabled):active, .button-primary:not(:disabled):active, .button-secondary:not(:disabled):active, .credit-button:not(:disabled):active, .generated-list button:active { transform: scale(.97); }
.session-nav { min-height: 0; flex: 1; display: flex; flex-direction: column; }
.sidebar-label { display: block; padding: 0 10px 8px; color: var(--muted); font-size: 11px; font-weight: 650; letter-spacing: .06em; }
.session-list { min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; }
.session-list button { position: relative; width: 100%; min-height: 48px; display: grid; gap: 2px; padding: 8px 10px 8px 12px; border: 0; border-radius: 9px; background: transparent; color: #484844; cursor: pointer; text-align: left; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.session-list button:active, .profile-trigger:active, .starter-list button:not(:disabled):active, .section-toggle:active, .inline-actions button:active { transform: scale(.98); }
.session-list button.is-active { background: rgba(255, 255, 255, .62); color: var(--ink); }
.session-list button.is-active::before { position: absolute; top: 12px; bottom: 12px; left: 3px; width: 3px; border-radius: 3px; background: var(--accent); content: ""; }
.session-list button > span { overflow: hidden; font-size: 13px; font-weight: 620; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
.session-list button small { color: var(--muted); font-size: 10px; line-height: 1.3; }
.sidebar-footer { margin-top: 12px; padding-top: 10px; border-top: 1px solid rgba(120, 118, 111, .22); }
.profile-trigger { width: 100%; min-height: 52px; display: grid; grid-template-columns: 34px minmax(0, 1fr) 18px; align-items: center; gap: 9px; padding: 5px 7px; border: 0; border-radius: 9px; background: transparent; cursor: pointer; text-align: left; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.profile-initial { width: 32px; height: 32px; display: grid; place-items: center; border: 1px solid #c7c4bc; border-radius: 50%; background: #e5e3dd; color: #50504c; font-size: 12px; font-weight: 650; text-transform: uppercase; }
.profile-trigger b, .profile-trigger small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.profile-trigger b { font-size: 12px; line-height: 1.4; }
.profile-trigger small { margin-top: 2px; color: var(--muted); font-size: 10px; }
.chevron { color: var(--muted); font-size: 20px; font-weight: 300; }
.sidebar-footer > p { margin: 9px 8px 0; color: var(--muted); font-size: 9px; line-height: 1.5; }
.chat-panel { height: 100%; min-width: 0; min-height: 0; overflow: hidden; display: grid; grid-template-rows: 64px minmax(0, 1fr) auto; background: var(--surface); }
.chat-header { z-index: 2; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 0 28px; border-bottom: 1px solid rgba(120, 118, 111, .18); background: rgba(251, 250, 247, .84); backdrop-filter: saturate(140%) blur(18px); }
.chat-header strong, .chat-header span { display: block; }
.chat-header strong { max-width: min(560px, 62vw); overflow: hidden; font-size: 13px; font-weight: 680; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
.chat-header span { margin-top: 3px; color: var(--muted); font-size: 10px; }
.status { width: 6px; height: 6px; display: inline-block; margin: 0 6px 1px 0; border-radius: 50%; background: #85847d; }
.status-loading { background: var(--accent); }
.credit-button { min-width: 92px; min-height: 44px; padding: 0 12px; border: 0; border-radius: 9px; background: transparent; color: var(--muted); cursor: pointer; font-size: 12px; font-weight: 650; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.conversation { min-width: 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
.conversation.is-empty { display: grid; place-items: center; padding: 28px; }
.welcome { width: min(760px, 100%); padding: 26px 0 56px; }
.welcome-mark { margin-bottom: 20px; }
.welcome-overline, .page-eyebrow { margin: 0 0 10px; color: var(--accent); font-size: 11px; font-weight: 700; letter-spacing: .06em; }
.welcome h1, .auth-panel h1, .admin-header h1 { margin: 0; font-size: clamp(30px, 4vw, 42px); font-weight: 650; letter-spacing: -.035em; line-height: 1.1; }
.welcome-copy { max-width: 460px; margin: 13px 0 28px; color: var(--muted); font-size: 13px; line-height: 1.7; }
.starter-list { border-top: 1px solid var(--line); }
.starter-list button { width: 100%; min-height: 68px; display: grid; grid-template-columns: 38px minmax(0, 1fr) 24px; align-items: center; gap: 8px; padding: 10px 6px 10px 0; border: 0; border-bottom: 1px solid var(--line); background: transparent; cursor: pointer; text-align: left; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.starter-loading { margin-left: 46px; padding: 12px 0; color: var(--muted); font-size: 12px; }
.starter-note { margin: 10px 0 0; color: var(--muted); font-size: 10px; line-height: 1.5; }
.starter-index { align-self: start; padding-top: 3px; color: var(--faint); font-size: 11px; font-variant-numeric: tabular-nums; }
.starter-content { min-width: 0; display: grid; gap: 4px; }
.starter-content b { color: var(--accent); font-size: 11px; font-weight: 700; letter-spacing: .03em; }
.starter-content span { overflow: hidden; color: #454541; font-size: 13px; line-height: 1.45; text-overflow: ellipsis; white-space: nowrap; }
.starter-arrow { color: var(--faint); font-size: 17px; }
.profile-link { min-height: 44px; margin-top: 12px; padding: 0; border: 0; background: transparent; color: var(--accent); cursor: pointer; font-size: 12px; text-decoration: underline; text-underline-offset: 3px; }
.onboarding-message { padding: 0 0 10px; }
.onboarding-stream .message-markdown p:last-child::after { width: 2px; height: 1em; display: inline-block; margin-left: 3px; background: var(--accent); vertical-align: -.12em; animation: onboarding-caret 700ms steps(1, end) infinite; content: ""; }
.onboarding-stream.is-complete .message-markdown p:last-child::after { content: none; }
.onboarding-card { margin: 6px 0 12px; padding: 20px; border: 1px solid var(--line); border-radius: 14px; background: #fff; box-shadow: 0 10px 28px rgba(30, 29, 26, .06); }
.onboarding-card-reveal { display: grid; grid-template-rows: 0fr; animation: onboarding-card-reveal 240ms var(--ease-out) forwards; }
.onboarding-card-reveal-inner { min-height: 0; overflow: hidden; }
.onboarding-step-card { max-width: 620px; transform-origin: top center; animation: onboarding-card-enter 220ms 30ms var(--ease-out) both; }
.onboarding-card-heading { display: grid; gap: 4px; padding-bottom: 2px; }
.onboarding-card-heading b { font-size: 14px; }.onboarding-card-heading small { color: var(--muted); font-size: 11px; line-height: 1.5; }
.onboarding-card-actions { display: flex; justify-content: flex-end; padding-top: 2px; }
.onboarding-card-actions .button-primary { min-width: 84px; }
.onboarding-inline-error { margin-left: 0; }
.welcome > .starter-list { margin-left: 0; }
.message-list { width: 100%; padding: 22px 28px 46px; }
.message { display: flex; padding: 6px 0; animation: message-enter 160ms var(--ease-out) both; }
.message-assistant { justify-content: flex-start; }
.message-user { justify-content: flex-end; }
.message-content { min-width: 0; max-width: min(78%, 680px); }
.message-user .message-content { display: flex; flex-direction: column; align-items: flex-end; }
.message-assistant .message-content { width: 100%; max-width: none; }
.message-bubble { padding: 10px 14px; overflow: hidden; border: 1px solid #e1ded7; border-radius: 18px 18px 18px 6px; background: #eeece7; }
.message-assistant .message-bubble { padding: 10px 0; border: 0; border-radius: 0; background: transparent; }
.message-user .message-bubble { border-color: var(--ink); border-radius: 18px 18px 6px 18px; background: var(--ink); }
.message p { max-width: none; margin: 0; color: #383834; font-size: 14px; line-height: 1.7; white-space: pre-wrap; }
.message-user p { color: #fff; }
.thinking { height: 24px; display: flex; align-items: center; gap: 5px; }
.thinking i { width: 5px; height: 5px; border-radius: 50%; background: var(--accent); animation: pulse 850ms ease-in-out infinite alternate; }
.thinking i:nth-child(2) { animation-delay: 100ms; }
.thinking i:nth-child(3) { animation-delay: 200ms; }
.suggestion-list { width: 100%; display: grid; margin-top: 12px; border-top: 1px solid var(--line); }
.suggestion-list button { min-height: 44px; display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 8px 0; border: 0; border-bottom: 1px solid var(--line); background: transparent; color: #494945; cursor: pointer; font-size: 12px; text-align: left; transition: color 120ms ease-out, transform 100ms ease-out; }
.suggestion-list button span { margin: 0; color: var(--faint); font-size: 15px; font-weight: 400; }
.suggestion-list button:not(:disabled):active { transform: scale(.99); }
.error-message { margin: 12px 0 0; padding: 12px 14px; border-left: 3px solid var(--accent); background: var(--accent-soft); color: #713725; font-size: 12px; line-height: 1.6; }
.composer-wrap { z-index: 2; min-width: 0; padding: 12px 24px 14px; border-top: 1px solid rgba(120, 118, 111, .14); background: rgba(251, 250, 247, .86); backdrop-filter: saturate(140%) blur(18px); }
.composer { width: min(760px, 100%); min-height: 58px; display: flex; align-items: flex-end; gap: 10px; margin: 0 auto; padding: 8px 8px 8px 15px; border: 1px solid var(--line-strong); border-radius: 16px; background: rgba(255, 255, 255, .76); transition: border-color 140ms ease-out, box-shadow 140ms ease-out; }
.composer:focus-within { border-color: #8c675a; box-shadow: 0 0 0 3px rgba(133, 67, 47, .1); }
.composer textarea { min-height: 40px; max-height: 128px; flex: 1; resize: none; padding: 10px 0 7px; border: 0; outline: 0; background: transparent; color: var(--ink); font-size: 14px; line-height: 1.45; }
.composer textarea::placeholder { color: var(--faint); }
.composer button { width: 44px; height: 44px; flex: 0 0 auto; border: 0; border-radius: 12px; background: var(--ink); color: white; cursor: pointer; font-size: 20px; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.composer button:not(:disabled):active { transform: scale(.92); }
.composer-wrap > p { width: min(760px, 100%); margin: 6px auto 0; color: var(--faint); font-size: 9px; text-align: center; }
.profile-overlay { position: fixed; z-index: 20; inset: 0; display: flex; justify-content: flex-end; background: rgba(20, 20, 18, .32); opacity: 0; visibility: hidden; transition: opacity 180ms ease-out, visibility 0s linear 180ms; }
.profile-overlay.is-open { opacity: 1; visibility: visible; transition-delay: 0s; }
.profile-dialog { width: min(520px, 100%); height: 100dvh; overflow-y: auto; padding: 24px; border-left: 1px solid var(--line); background: var(--surface); box-shadow: -14px 0 40px rgba(30, 29, 26, .12); transform: translateX(20px); transition: transform 180ms var(--ease-out); }
.profile-overlay.is-open .profile-dialog { transform: translateX(0); }
.profile-dialog > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 20px; }
.dialog-eyebrow { display: block; margin-bottom: 5px; color: var(--accent); font-size: 10px; font-weight: 700; letter-spacing: .06em; }
.profile-dialog h2 { margin: 0; font-size: 24px; font-weight: 680; letter-spacing: -.025em; }
.dialog-close { width: 44px; height: 44px; flex: 0 0 auto; border: 0; border-radius: 50%; background: #eceae4; cursor: pointer; font-size: 22px; line-height: 1; transition: background-color 120ms ease-out, transform 100ms ease-out; }
.dialog-close:active { transform: scale(.92); }
.account-summary { display: grid; grid-template-columns: minmax(0, 1fr) 120px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.account-summary div { min-width: 0; padding: 16px 0; }
.account-summary div + div { padding-left: 18px; border-left: 1px solid var(--line); }
.account-summary span, .account-summary strong { display: block; }
.account-summary span { margin-bottom: 6px; color: var(--muted); font-size: 11px; }
.account-summary strong { overflow: hidden; font-size: 14px; text-overflow: ellipsis; white-space: nowrap; }
.sheet-section { padding: 18px 0; border-bottom: 1px solid var(--line); }
.section-toggle { width: 100%; min-height: 52px; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 0; border: 0; background: transparent; cursor: pointer; text-align: left; transition: transform 100ms ease-out; }
.section-toggle b, .section-heading b { display: block; font-size: 14px; }
.section-toggle small, .section-heading small { display: block; margin-top: 4px; color: var(--muted); font-size: 11px; font-weight: 400; }
.section-toggle > span:last-child { font-size: 20px; font-weight: 300; }
.redeem-form { display: grid; gap: 8px; padding-top: 12px; }
.redeem-form > div { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; }
.redeem-form label, .profile-form label > span, .code-form label > span, .stack-form label { color: #555550; font-size: 11px; font-weight: 650; }
.profile-form { display: grid; gap: 14px; margin-top: 16px; }
.profile-form label { display: grid; gap: 7px; }
.profile-form em, .code-form em { color: var(--faint); font-size: 10px; font-style: normal; font-weight: 400; }
.profile-grid, .location-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.location-fieldset { margin: 0; padding: 0; border: 0; }
.location-fieldset legend { margin-bottom: 10px; color: #555550; font-size: 11px; font-weight: 650; }
input, select { width: 100%; min-height: 44px; padding: 0 12px; border: 1px solid var(--line-strong); border-radius: 9px; background: #fff; color: var(--ink); font-size: 13px; }
input:disabled, select:disabled { background: #eeece7; color: var(--faint); }
.button-primary, .button-secondary { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; padding: 0 15px; border: 1px solid var(--ink); border-radius: 9px; cursor: pointer; font-size: 12px; font-weight: 680; text-decoration: none; transition: background-color 120ms ease-out, color 120ms ease-out, transform 100ms ease-out; }
.button-primary { background: var(--ink); color: white; }
.button-secondary { background: transparent; color: var(--ink); }
.save-profile { justify-self: end; }
.form-error, .form-success { margin: 10px 0 0; padding: 10px 12px; border-left: 3px solid currentColor; font-size: 12px; line-height: 1.5; }
.form-error { background: #f8e8e6; color: var(--danger); }
.form-success { background: #e8f2eb; color: var(--success); }
.account-actions { display: flex; justify-content: space-between; gap: 8px; padding-top: 20px; }
.account-actions .danger-button { margin-left: auto; color: var(--danger); border-color: #c99d9d; }
.message-markdown { max-width: none; color: #383834; font-size: 14px; line-height: 1.85; overflow-wrap: anywhere; }
.message-markdown > :first-child { margin-top: 0; }
.message-markdown > :last-child { margin-bottom: 0; }
.message-markdown p, .message-markdown ul, .message-markdown ol { margin: 0 0 11px; }
.message-markdown h1, .message-markdown h2, .message-markdown h3, .message-markdown h4 { margin: 18px 0 8px; color: var(--ink); font-weight: 700; line-height: 1.35; }
.message-markdown h1 { font-size: 18px; }.message-markdown h2 { font-size: 16px; }.message-markdown h3, .message-markdown h4 { font-size: 14px; }
.message-markdown ul, .message-markdown ol { padding-left: 20px; }.message-markdown li + li { margin-top: 3px; }
.message-markdown blockquote { margin: 12px 0; padding: 2px 0 2px 12px; border-left: 2px solid #b7a38d; color: #62605a; }
.message-markdown code, .generated-list code, .admin-table code { font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace; }
.message-markdown code { padding: 1px 4px; background: #efede7; color: #553428; font-size: .88em; }
.message-markdown pre { margin: 12px 0; padding: 12px; overflow-x: auto; border: 1px solid var(--line); background: #f5f3ee; }
.message-markdown pre code { padding: 0; background: transparent; color: inherit; font-size: 12px; line-height: 1.6; }
.message-markdown a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
.markdown-table { width: 100%; margin: 12px 0; overflow-x: auto; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.markdown-table table { width: 100%; min-width: 360px; border-collapse: collapse; color: #41413d; font-size: 12px; line-height: 1.55; text-align: left; }
.markdown-table th, .markdown-table td { padding: 8px 10px; border-bottom: 1px solid #dfdcd5; vertical-align: top; }
.markdown-table th { color: #62605a; font-size: 11px; font-weight: 700; }.markdown-table tbody tr:last-child td { border-bottom: 0; }
.standalone-page { width: 100%; height: 100dvh; min-height: 0; overflow: auto; background: var(--surface); }
.auth-page { display: grid; place-items: center; padding: 28px; }
.auth-panel { width: min(420px, 100%); padding: 34px 0; border-top: 1px solid var(--line-strong); border-bottom: 1px solid var(--line); }
.auth-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 42px; font-size: 17px; }
.auth-panel h1 { font-size: 34px; }
.page-intro { margin: 12px 0 28px; color: var(--muted); font-size: 13px; line-height: 1.65; }
.stack-form { display: grid; gap: 10px; }
.stack-form .button-primary { margin-top: 4px; }
.otp-input { text-align: center; font-size: 22px; font-weight: 650; letter-spacing: .3em; font-variant-numeric: tabular-nums; }
.inline-actions { display: flex; justify-content: space-between; gap: 16px; }
.inline-actions button { min-height: 44px; padding: 0; border: 0; background: transparent; color: var(--accent); cursor: pointer; font-size: 12px; text-decoration: underline; text-underline-offset: 3px; transition: transform 100ms ease-out; }
.admin-page { display: grid; grid-template-rows: 72px minmax(0, 1fr); }
.admin-header { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 0 max(24px, calc((100vw - 1180px) / 2)); border-bottom: 1px solid rgba(120, 118, 111, .18); background: rgba(251, 250, 247, .86); backdrop-filter: saturate(140%) blur(18px); }
.admin-header .page-eyebrow { margin-bottom: 2px; }.admin-header h1 { font-size: 24px; }
.admin-scroll { min-height: 0; overflow-y: auto; padding: 30px max(24px, calc((100vw - 1180px) / 2)) 60px; }
.admin-section { padding: 0 0 30px; margin-bottom: 30px; border-bottom: 1px solid var(--line); }
.section-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 18px; }
.section-title h2 { margin: 0; font-size: 18px; letter-spacing: -.01em; }.section-title p { margin: 5px 0 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
.code-form { display: grid; grid-template-columns: 130px 130px minmax(210px, 1fr) minmax(220px, 1.2fr) auto; align-items: end; gap: 12px; }
.code-form label { display: grid; gap: 7px; }.code-form .button-primary { min-width: 88px; }
.generated-list { border-top: 1px solid var(--line); }
.generated-list > div { min-height: 52px; display: grid; grid-template-columns: minmax(0, 1fr) 72px 56px; align-items: center; gap: 12px; border-bottom: 1px solid var(--line); }
.generated-list code { overflow-wrap: anywhere; color: var(--ink); font-size: 13px; }.generated-list span { color: var(--muted); font-size: 12px; }
.generated-list button { min-height: 44px; padding: 0; border: 0; background: transparent; color: var(--accent); cursor: pointer; font-size: 12px; text-decoration: underline; text-underline-offset: 3px; transition: transform 100ms ease-out; }
.admin-table-wrap { width: 100%; overflow-x: auto; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.admin-table { width: 100%; min-width: 1050px; border-collapse: collapse; font-size: 12px; text-align: left; }
.admin-table th, .admin-table td { padding: 12px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
.admin-table th { color: var(--muted); font-size: 10px; font-weight: 700; letter-spacing: .03em; white-space: nowrap; }
.admin-table tbody tr:last-child td { border-bottom: 0; }.admin-table code { font-size: 11px; }.empty-cell { color: var(--muted); text-align: center; }
.code-status { display: inline-block; padding: 3px 7px; border-radius: 999px; background: #eceae5; color: #555550; font-size: 10px; font-weight: 700; white-space: nowrap; }
.status-可用 { background: #e4f0e7; color: var(--success); }.status-已兑换 { background: #e8e8ed; color: #55556a; }.status-已过期, .status-已停用 { background: #f4e4e3; color: var(--danger); }
@keyframes message-enter { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
@keyframes onboarding-card-reveal { from { grid-template-rows: 0fr; } to { grid-template-rows: 1fr; } }
@keyframes onboarding-card-enter { from { opacity: 0; transform: translateY(8px) scale(.985); } to { opacity: 1; transform: translateY(0) scale(1); } }
@keyframes onboarding-caret { 50% { opacity: 0; } }
@keyframes pulse { from { opacity: .25; transform: translateY(0); } to { opacity: 1; transform: translateY(-2px); } }
@media (hover: hover) and (pointer: fine) {
.new-chat:not(:disabled):hover, .composer button:not(:disabled):hover, .button-primary:not(:disabled):hover { background: #383836; }
.session-list button:hover, .profile-trigger:hover, .credit-button:hover { background: rgba(255, 255, 255, .48); }
.starter-list button:not(:disabled):hover { background: #f1efea; }
.suggestion-list button:not(:disabled):hover { color: var(--accent); }
.button-secondary:hover, .dialog-close:hover { background: #eceae5; }
.section-toggle:hover { color: var(--accent); }
}
@media (max-width: 900px) {
.code-form { grid-template-columns: 1fr 1fr; }.code-form .note-field { grid-column: 1 / -1; }.code-form .button-primary { justify-self: start; }
}
@media (max-width: 760px) {
.chat-app { grid-template-columns: 1fr; grid-template-rows: 146px minmax(0, 1fr); }
.sidebar { position: relative; height: 146px; padding: 8px 10px; border-right: 0; border-bottom: 1px solid rgba(120, 118, 111, .22); }
.brand-row { height: 40px; padding: 0 4px; }.brand-mark { width: 26px; height: 26px; }
.new-chat { position: absolute; top: 7px; right: 10px; width: auto; min-height: 40px; margin: 0; padding: 0 12px; }.new-chat span { display: none; }
.session-nav { margin-top: 5px; overflow: visible; }.sidebar-label { display: none; }
.session-list { overflow-x: auto; overflow-y: hidden; flex-direction: row; gap: 6px; padding-bottom: 2px; }
.session-list button { width: 146px; min-width: 146px; min-height: 46px; }
.sidebar-footer { position: absolute; top: 7px; right: 104px; margin: 0; padding: 0; border: 0; }
.profile-trigger { width: 44px; min-height: 40px; grid-template-columns: 32px; padding: 4px 6px; }.profile-trigger > span:nth-child(2), .profile-trigger .chevron, .sidebar-footer > p { display: none; }
.chat-panel { grid-template-rows: 58px minmax(0, 1fr) auto; }.chat-header { padding: 0 14px; }.chat-header strong { max-width: 54vw; }.credit-button { min-width: 80px; padding: 0 6px; }
.conversation.is-empty { padding: 20px; }.welcome { padding: 20px 0 30px; }.welcome h1 { font-size: 30px; }.welcome-copy { margin-bottom: 20px; }.onboarding-card, .welcome > .starter-list, .starter-loading { margin-left: 0; }.onboarding-card { padding: 16px; }
.starter-list button { min-height: 62px; }.starter-content span { font-size: 12px; }
.message-list { width: 100%; padding: 12px 10px 46px; }.message { padding: 5px 0; }.message-content { max-width: 86%; }.error-message { margin-left: 0; }
.composer-wrap { padding: 9px 10px 10px; }.composer-wrap > p { display: none; }
.profile-overlay { align-items: flex-end; }.profile-dialog { width: 100%; height: min(88dvh, 760px); padding: 20px; border-top: 1px solid var(--line); border-left: 0; border-radius: 16px 16px 0 0; transform: translateY(20px); }.profile-overlay.is-open .profile-dialog { transform: translateY(0); }
.account-actions { padding-bottom: max(0px, env(safe-area-inset-bottom)); }
.admin-header { padding: 0 16px; }.admin-scroll { padding: 24px 16px 50px; }.section-title { align-items: stretch; }.generated-section .section-title { flex-direction: column; }.generated-section .button-secondary { align-self: flex-start; }
}
@media (max-width: 480px) {
.profile-grid, .location-grid, .code-form { grid-template-columns: 1fr; }.code-form .note-field { grid-column: auto; }.code-form .button-primary { width: 100%; }
.account-summary { grid-template-columns: minmax(0, 1fr) 96px; }.profile-dialog h2 { font-size: 22px; }
.auth-page { padding: 20px; }.auth-panel { padding: 26px 0; }.auth-brand { margin-bottom: 34px; }.auth-panel h1 { font-size: 30px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; scroll-behavior: auto !important; transition-duration: .01ms !important; transition-delay: 0s !important; }
}
@media (prefers-reduced-transparency: reduce) {
.sidebar, .chat-header, .composer-wrap, .admin-header { background: var(--surface); backdrop-filter: none; }
.sidebar { background: #ebe9e3; }.composer { background: #fff; }
}
@media (prefers-contrast: more) {
:root { --muted: #454541; --faint: #5c5b56; --line: #aaa79e; --line-strong: #77746c; }
.sidebar, .chat-header, .composer-wrap, .admin-header { backdrop-filter: none; }
.button-primary, .button-secondary, input, select, .composer { border-width: 2px; }
.session-list button.is-active::before { width: 4px; }
}
+15
View File
@@ -0,0 +1,15 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Ayanam · 印度占星对话",
description: "与 Mastra Agent 对话,基于星盘证据讨论事业、关系与时间窗口。",
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="zh-CN" suppressHydrationWarning>
<body>{children}</body>
</html>
);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { FormEvent, useState } from "react";
import { createBrowserSupabaseClient } from "@/lib/supabase/client";
function authMessage(caught: unknown) {
const message = caught instanceof Error ? caught.message : "暂时无法登录";
const lower = message.toLowerCase();
if (message.includes("Supabase") || message.includes("environment") || message.includes("URL")) return "Supabase 尚未配置";
if (lower.includes("expired") || lower.includes("invalid")) return "验证码错误或已过期,请重新获取";
if (lower.includes("rate limit")) return "发送过于频繁,请稍后再试";
return message;
}
export default function LoginPage() {
const [email, setEmail] = useState("");
const [token, setToken] = useState("");
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
async function sendOtp(event?: FormEvent<HTMLFormElement>) {
event?.preventDefault();
const normalizedEmail = email.trim();
if (!normalizedEmail || busy) return;
setBusy(true);
setError("");
setNotice("");
try {
const { error: otpError } = await createBrowserSupabaseClient().auth.signInWithOtp({
email: normalizedEmail,
options: { shouldCreateUser: true },
});
if (otpError) throw otpError;
setSent(true);
setNotice(`验证码已发送至 ${normalizedEmail}`);
} catch (caught) {
setError(authMessage(caught));
} finally {
setBusy(false);
}
}
async function verifyOtp(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!token || busy) return;
setBusy(true);
setError("");
try {
const { error: otpError } = await createBrowserSupabaseClient().auth.verifyOtp({
email: email.trim(),
token,
type: "email",
});
if (otpError) throw otpError;
window.location.assign("/");
} catch (caught) {
setError(authMessage(caught));
setBusy(false);
}
}
function changeEmail() {
setSent(false);
setToken("");
setError("");
setNotice("");
}
return (
<main className="standalone-page auth-page">
<section className="auth-panel" aria-labelledby="login-title">
<div className="auth-brand"><span aria-hidden="true">अ</span><strong>Ayanam</strong></div>
<p className="page-eyebrow">邮箱登录</p>
<h1 id="login-title">继续你的占星对话</h1>
<p className="page-intro">我们会发送一次性登录验证码,新邮箱会自动创建账户。</p>
{!sent ? (
<form className="stack-form" onSubmit={sendOtp}>
<label htmlFor="login-email">邮箱</label>
<input id="login-email" type="email" autoComplete="email" inputMode="email" required autoFocus value={email} onChange={(event) => { setEmail(event.target.value); setError(""); setNotice(""); }} placeholder="you@example.com" />
<button className="button-primary" type="submit" disabled={!email.trim() || busy}>{busy ? "发送中" : "发送验证码"}</button>
</form>
) : (
<form className="stack-form" onSubmit={verifyOtp}>
<label htmlFor="login-token">邮箱验证码</label>
<input id="login-token" className="otp-input" type="text" autoComplete="one-time-code" inputMode="numeric" pattern="[0-9]*" minLength={6} maxLength={6} required autoFocus value={token} onChange={(event) => { setToken(event.target.value.replace(/\D/g, "").slice(0, 6)); setError(""); }} />
<button className="button-primary" type="submit" disabled={!token || busy}>{busy ? "验证中" : "验证并登录"}</button>
<div className="inline-actions">
<button type="button" disabled={busy} onClick={() => void sendOtp()}>{busy ? "发送中" : "重新发送验证码"}</button>
<button type="button" disabled={busy} onClick={changeEmail}>更换邮箱</button>
</div>
</form>
)}
{error && <p className="form-error" role="alert">{error}</p>}
{notice && <p className="form-success" role="status">{notice}</p>}
</section>
</main>
);
}
File diff suppressed because it is too large Load Diff