auth.ts 5.88 KB
/**
 * 登录态与受保护接口的请求封装。
 *
 * token 由后端种在 httpOnly cookie 中,前端读不到也不需要读,
 * 所有请求带上 `credentials: "include"` 即可自动携带。
 */

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";

export interface CurrentUser {
  id: string;
  username: string;
  displayName: string;
  phone: string | null;
  role: string;
  positionId: string | null;
  positionName: string | null;
  storeName: string | null;
}

export class UnauthorizedError extends Error {
  constructor() {
    super("未登录或登录已失效");
    this.name = "UnauthorizedError";
  }
}

/** 带凭据的 fetch。遇到 401 统一抛 UnauthorizedError,由调用方决定是否跳登录页。 */
export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
  const response = await fetch(`${API_BASE}${path}`, {
    ...init,
    credentials: "include",
    headers: {
      ...(init.body ? { "Content-Type": "application/json" } : {}),
      ...(init.headers || {}),
    },
  });

  if (response.status === 401) {
    throw new UnauthorizedError();
  }
  return response;
}

/** 请求 JSON 接口,非 2xx 时抛出后端返回的 detail 文案。 */
export async function apiJson<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
  const response = await apiFetch(path, init);
  const data = await response.json().catch(() => ({}));

  if (!response.ok) {
    const detail = (data as { detail?: string }).detail || `请求失败(${response.status})`;
    throw new Error(detail);
  }
  return data as T;
}

export async function login(account: string, password: string): Promise<CurrentUser> {
  const data = await apiJson<{ user: CurrentUser }>("/auth/login", {
    method: "POST",
    body: JSON.stringify({ account, password }),
  });
  return data.user;
}

export async function logout(): Promise<void> {
  await apiFetch("/auth/logout", { method: "POST" }).catch(() => undefined);
}

/** 获取当前用户;未登录返回 null(不抛异常,便于页面做重定向判断)。 */
export async function fetchMe(): Promise<CurrentUser | null> {
  try {
    const data = await apiJson<{ user: CurrentUser }>("/auth/me");
    return data.user;
  } catch (error) {
    if (error instanceof UnauthorizedError) return null;
    throw error;
  }
}

export async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
  await apiJson("/auth/change-password", {
    method: "POST",
    body: JSON.stringify({ oldPassword, newPassword }),
  });
}

// ============================== 会话 ==============================

export interface SessionItem {
  id: string;
  title: string;
  totalTurns: number;
  status: string;
  updatedAt: string | null;
  createdAt: string | null;
}

export interface SessionMessage {
  seq: number;
  role: "user" | "assistant";
  content: string;
  reasoning: ReasoningStep[] | null;
  createdAt: string | null;
}

/** 落库的思考步骤。工具返回正文不入库,只有 meta 里的成功标志与字节数。 */
export interface ReasoningStep {
  id: string;
  type: "thought" | "call" | "response";
  name?: string | null;
  content?: string;
  meta?: { ok: boolean; bytes: number };
}

export async function listSessions(limit = 20, offset = 0) {
  return apiJson<{ total: number; items: SessionItem[] }>(
    `/sessions?limit=${limit}&offset=${offset}`
  );
}

/** 新建会话。传 previousSessionId 可让后端对上一个会话触发收尾沉淀。 */
export async function createSession(previousSessionId?: string | null) {
  return apiJson<{ id: string }>("/sessions", {
    method: "POST",
    body: JSON.stringify({ previousSessionId: previousSessionId || null }),
  });
}

export async function fetchSessionMessages(sessionId: string) {
  return apiJson<{ id: string; title: string; messages: SessionMessage[] }>(
    `/sessions/${sessionId}/messages`
  );
}

export async function deleteSession(sessionId: string) {
  return apiJson(`/sessions/${sessionId}`, { method: "DELETE" });
}

export async function renameSession(sessionId: string, title: string) {
  return apiJson(`/sessions/${sessionId}`, {
    method: "PATCH",
    body: JSON.stringify({ title }),
  });
}

// ============================== 画像 ==============================

export interface ProfilePayload {
  profileMd: string;
  agentMd: string;
  // 未剥离元信息的原文,供编辑器加载
  profileMdRaw: string;
  agentMdRaw: string;
  profileGenerated: boolean;
  profileVersion: number;
  memoryStats: { chars: number; entries: number; maxChars: number };
}

export async function fetchProfile() {
  return apiJson<ProfilePayload>("/profile");
}

export async function regenerateProfile() {
  return apiJson("/profile/regenerate", { method: "POST" });
}

/** 用户本人编辑自己的用户画像 / 长期记忆。 */
export async function updateMyProfile(payload: { profileMd?: string; agentMd?: string }) {
  return apiJson("/profile", { method: "PATCH", body: JSON.stringify(payload) });
}

export async function clearMemory() {
  return apiJson("/profile/memory", { method: "DELETE" });
}

// ============================== 管理员:用户画像编辑 ==============================

export interface AdminUserProfile {
  userId: string;
  displayName: string;
  profileMd: string;
  agentMd: string;
  profileGenerated: boolean;
  profileVersion: number;
  memoryStats: { chars: number; entries: number; maxChars: number };
}

export async function fetchUserProfile(userId: string) {
  return apiJson<AdminUserProfile>(`/admin/users/${userId}/profile`);
}

export async function updateUserProfile(
  userId: string,
  payload: { profileMd?: string; agentMd?: string }
) {
  return apiJson(`/admin/users/${userId}/profile`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function regenerateUserProfile(userId: string) {
  return apiJson(`/admin/users/${userId}/profile/regenerate`, { method: "POST" });
}