Files
gitlab-instance-0a899031_salon/app/lib/complete-order.ts
2026-03-16 20:39:19 -05:00

52 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 共享:完成订单 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<CompleteOrderResult> {
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 */
}
}
}