/** 共享:完成订单 API 调用与成功后的 session 同步 */ import type { AuthUser } from "@/app/lib/pocketbase"; const WECHAT_STORAGE_KEY = "salon_join_wechat"; export interface CompleteOrderResult { ok: boolean; token?: string; record?: { wechatId?: string; [k: string]: unknown }; error?: string; } /** 调用 complete-order API */ export async function tryCompleteOrder(orderId: string): Promise { const r = await fetch("/api/salon/complete-order", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ order_id: orderId }), credentials: "include", }); const d = await r.json(); if (!d?.ok) return { ok: false, error: d?.error || d?.detail || `HTTP ${r.status}` }; return { ok: true, token: d.token, record: d.record }; } /** 成功后的通用处理:sync-session、pbSaveAuth、dispatch 事件、localStorage wechatId。token 为空时仅 dispatch 和保存 wechatId(非 pending 用户) */ export function applyCompleteSuccess(data: { token?: string; record?: { wechatId?: string; [k: string]: unknown } }): void { const { token, record } = data; if (token) { fetch("/api/auth/sync-session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token, record }), credentials: "include", }).catch(() => {}); if (record && "id" in record && "email" in record) { import("@/app/lib/pocketbase").then(({ pbSaveAuth }) => pbSaveAuth(token, record as AuthUser)); } } window.dispatchEvent(new CustomEvent("auth:updated")); window.dispatchEvent(new CustomEvent("vip:updated")); window.dispatchEvent(new CustomEvent("registration:refresh")); if (record?.wechatId) { try { localStorage.setItem(WECHAT_STORAGE_KEY, record.wechatId); } catch { /* ignore */ } } }