auth.ts 21.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
/**
 * 登录态与受保护接口的请求封装。
 *
 * 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;
  isSuperadmin: boolean;
  mustChangePwd: boolean;
  deptId: string | null;
  deptName: string | null;
  positionName: string | null;
  storeName: string | null;
  roles: string[];
}

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> {
  // 登录接口不走 apiFetch:apiFetch 会把任何 401 统一抛成 UnauthorizedError(用于受保护
  // 接口触发跳登录),而登录接口的 401 = 凭据错误,应原样显示后端 detail(如「账号或密码错误」)。
  let res: Response;
  try {
    res = await fetch(`${API_BASE}/auth/login`, {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ account, password }),
    });
  } catch {
    // 网络层失败(后端不可达等),给用户可读文案而非底层异常字符串
    throw new Error("无法连接服务器,请检查网络后重试");
  }
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    throw new Error((data as { detail?: string }).detail || "登录失败,请稍后重试");
  }
  return (data as { user: CurrentUser }).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;
  durationMs?: number;
  createdAt: string | null;
}

/** 落库的思考步骤:含每步耗时 time、工具返回正文摘要 content、引用来源 data。 */
export interface ReasoningStep {
  id: string;
  type: "status" | "thought" | "call" | "response" | "sources";
  name?: string | null;
  content?: string;
  time?: string;
  data?: { original: string[]; wiki: 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;
  longMemCoreMd: string;
  // 未剥离元信息的原文,供编辑器加载
  profileMdRaw: string;
  longMemCoreMdRaw: 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; longMemCoreMd?: 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;
  longMemCoreMd: 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; longMemCoreMd?: 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" });
}

// ============================== OA 权限装配 ==============================

export interface MenuNode {
  id: string;
  parentId: string | null;
  name: string;
  type: string;
  perm: string | null;
  path: string | null;
  icon: string | null;
  orderNum: number;
  children: MenuNode[];
}

export interface MyPerms {
  isSuperadmin: boolean;
  perms: string[];
  menus: MenuNode[];
}

export async function fetchMyPerms() {
  return apiJson<MyPerms & { success: boolean }>("/oa/me/perms");
}

/** 前端按钮/页面级权限判定。超管(perms 含 "*")恒通过。 */
export function hasPerm(perms: string[] | undefined, code: string): boolean {
  if (!perms) return false;
  return perms.includes("*") || perms.includes(code);
}

// ============================== OA CRUD ==============================

export interface OaUser {
  id: string;
  username: string;
  displayName: string;
  phone: string | null;
  email: string | null;
  deptId: string | null;
  deptName: string | null;
  archName: string | null;
  centerId: string | null;
  centerName: string | null;
  storeName: string | null;
  isSuperadmin: boolean;
  status: string;
  roles: string[];
  roleIds: string[];
  posts: string[];
  postIds: string[];
  lastLoginAt: string | null;
}

export interface OaRole {
  id: string;
  roleCode: string;
  roleName: string;
  dataScope: number;
  orderNum: number;
  isBuiltin: boolean;
  status: string;
  remark: string | null;
}

export interface OaDept {
  id: string;
  parentId: string | null;
  deptName: string;
  deptCategory: string;
  duty: string | null;
  orderNum: number;
  status: string;
  children: OaDept[];
}

export interface OaPost {
  id: string;
  deptId: string | null;
  deptName: string | null;
  centerId: string | null;
  centerName: string | null;
  postName: string;
  duty: string | null;
  orderNum: number;
  status: string;
  defaultRoleIds: string[];
}

export interface OaOperLog {
  id: string;
  operatorName: string | null;
  module: string;
  action: string;
  targetType: string | null;
  targetName: string | null;
  detail: unknown;
  clientIp: string | null;
  result: string;
  createdAt: string | null;
}

export interface OaSource {
  id: string;
  parentId: string | null;
  name: string;
  type: string;
  perm: string | null;
  path: string | null;
  component: string | null;
  icon: string | null;
  orderNum: number;
  visible: boolean;
  status: string;
  children: OaSource[];
}

// 用户
export const listOaUsers = (q: {
  keyword?: string;
  deptId?: string;
  roleId?: string;
  postName?: string;
  status?: string;
  sortBy?: string;
  sortOrder?: "asc" | "desc";
  limit?: number;
  offset?: number;
}) => {
  const p = new URLSearchParams();
  if (q.keyword) p.set("keyword", q.keyword);
  if (q.deptId) p.set("deptId", q.deptId);
  if (q.roleId) p.set("roleId", q.roleId);
  if (q.postName) p.set("postName", q.postName);
  if (q.status) p.set("status", q.status);
  if (q.sortBy) p.set("sortBy", q.sortBy);
  if (q.sortOrder) p.set("sortOrder", q.sortOrder);
  p.set("limit", String(q.limit ?? 20));
  p.set("offset", String(q.offset ?? 0));
  return apiJson<{ total: number; items: OaUser[] }>(`/oa/users?${p.toString()}`);
};
export const batchDeleteOaUsers = (ids: string[]) =>
  apiJson<{ deleted: number; skipped: number }>("/oa/users/batch-delete", {
    method: "POST",
    body: JSON.stringify({ ids }),
  });
export const setOaUserPosts = (id: string, postIds: string[]) =>
  apiJson(`/oa/users/${id}/posts`, { method: "PUT", body: JSON.stringify({ postIds }) });
export const createOaUser = (body: Record<string, unknown>) =>
  apiJson<{ id: string; initialPassword: string }>("/oa/users", {
    method: "POST",
    body: JSON.stringify(body),
  });
export const updateOaUser = (id: string, body: Record<string, unknown>) =>
  apiJson(`/oa/users/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const deleteOaUser = (id: string) => apiJson(`/oa/users/${id}`, { method: "DELETE" });
export const resetOaUserPwd = (id: string) =>
  apiJson<{ initialPassword: string }>(`/oa/users/${id}/reset-password`, { method: "POST" });
export const setOaUserRoles = (id: string, roleIds: string[]) =>
  apiJson(`/oa/users/${id}/roles`, { method: "PUT", body: JSON.stringify({ roleIds }) });

// 角色
export const listOaRoles = () => apiJson<{ items: OaRole[] }>("/oa/roles");
export const createOaRole = (body: Record<string, unknown>) =>
  apiJson<{ id: string }>("/oa/roles", { method: "POST", body: JSON.stringify(body) });
export const updateOaRole = (id: string, body: Record<string, unknown>) =>
  apiJson(`/oa/roles/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const deleteOaRole = (id: string) => apiJson(`/oa/roles/${id}`, { method: "DELETE" });
export const getOaRoleSources = (id: string) =>
  apiJson<{ sourceIds: string[]; deptIds: string[] }>(`/oa/roles/${id}/sources`);
export const setOaRoleSources = (id: string, sourceIds: string[]) =>
  apiJson(`/oa/roles/${id}/sources`, { method: "PUT", body: JSON.stringify({ sourceIds }) });
export const setOaRoleDataScope = (id: string, dataScope: number, deptIds: string[] = []) =>
  apiJson(`/oa/roles/${id}/data-scope`, {
    method: "PUT",
    body: JSON.stringify({ dataScope, deptIds }),
  });

// 部门
export interface BatchDeleteResult {
  deleted: number;
  skipped: number;
  skippedItems: { id: string; name: string | null; reason: string }[];
}
/** 把批量删除结果拼成一句可读提示:已删除 N 个,跳过 M 个(附前几条原因)。 */
export function summarizeBatchDelete(r: BatchDeleteResult, unit: string): string {
  const parts = [`已删除 ${r.deleted} 个${unit}`];
  if (r.skipped) {
    const shown = r.skippedItems.slice(0, 5).map((i) => `${i.name ?? i.id}(${i.reason})`).join("、");
    const more = r.skippedItems.length > 5 ? ` 等 ${r.skippedItems.length} 项` : "";
    parts.push(`跳过 ${r.skipped} 个未删除:${shown}${more}`);
  }
  return parts.join(";");
}
export const listOaDepts = () => apiJson<{ items: OaDept[] }>("/oa/depts");
export const createOaDept = (body: Record<string, unknown>) =>
  apiJson<{ id: string }>("/oa/depts", { method: "POST", body: JSON.stringify(body) });
export const updateOaDept = (id: string, body: Record<string, unknown>) =>
  apiJson(`/oa/depts/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const deleteOaDept = (id: string) => apiJson(`/oa/depts/${id}`, { method: "DELETE" });

// 岗位
export const listOaPosts = (q: { deptId?: string; keyword?: string } = {}) => {
  const p = new URLSearchParams();
  if (q.deptId) p.set("deptId", q.deptId);
  if (q.keyword) p.set("keyword", q.keyword);
  return apiJson<{ total: number; items: OaPost[] }>(`/oa/posts?${p.toString()}`);
};
export const createOaPost = (body: Record<string, unknown>) =>
  apiJson<{ id: string }>("/oa/posts", { method: "POST", body: JSON.stringify(body) });
export const updateOaPost = (id: string, body: Record<string, unknown>) =>
  apiJson(`/oa/posts/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const deleteOaPost = (id: string) => apiJson(`/oa/posts/${id}`, { method: "DELETE" });
export const batchDeleteOaPosts = (ids: string[]) =>
  apiJson<BatchDeleteResult>("/oa/posts/batch-delete", {
    method: "POST",
    body: JSON.stringify({ ids }),
  });
export const setOaPostRoles = (id: string, roleIds: string[]) =>
  apiJson(`/oa/posts/${id}/roles`, { method: "PUT", body: JSON.stringify({ roleIds }) });

// 资源
export const listOaSources = () => apiJson<{ items: OaSource[] }>("/oa/sources");
export const listOaSourcesFlat = (types: string[]) =>
  apiJson<{ items: OaSource[] }>(`/oa/sources/flat?types=${encodeURIComponent(types.join(","))}`);
export const syncOaSources = () =>
  apiJson<{ count: number; interfaces: number }>("/oa/sources/sync", { method: "POST" });
export const createOaSource = (body: Record<string, unknown>) =>
  apiJson<{ id: string }>("/oa/sources", { method: "POST", body: JSON.stringify(body) });
export const updateOaSource = (id: string, body: Record<string, unknown>) =>
  apiJson(`/oa/sources/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const deleteOaSource = (id: string) => apiJson(`/oa/sources/${id}`, { method: "DELETE" });

// 操作日志
export const listOaOperLogs = (q: { module?: string; keyword?: string; limit?: number; offset?: number } = {}) => {
  const p = new URLSearchParams();
  if (q.module) p.set("module", q.module);
  if (q.keyword) p.set("keyword", q.keyword);
  p.set("limit", String(q.limit ?? 20));
  p.set("offset", String(q.offset ?? 0));
  return apiJson<{ total: number; items: OaOperLog[] }>(`/oa/oper-logs?${p.toString()}`);
};

// ============ 知识库(多库) ============
export interface KbInfo {
  id: string;
  kbType: string; // base=公共库 / dept=部门库
  kbName: string;
  deptId: string | null;
  deptPath: string | null;
  deptIdPath?: string[];   // 组织链 id(根在前含自身),前端建组织树用
  sortKey?: string;         // 可排序键(架构<中心<部门、父在子前)
  ownerUserId: string | null;
  rootDir: string;
  status: string;
  isBuiltin?: boolean;      // 系统内置公共库:类型/停用/删除均锁死
  createdAt: string | null;
  grantedLabels?: string[];
  access?: "owner" | "editor" | "reader" | null;  // 当前用户对本库的有效级别(/kb/readable 才返回)
}
export interface KbGrant {
  id: string;
  granteeType: string;
  granteeId: string;
  granteeLabel?: string | null;  // 组织节点完整路径
  access: "editor" | "reader";   // editor=写权限(读写) / reader=访问权限(只读);owner 由 kb.deptId 承载
}
export const listKbs = (q: {
  keyword?: string;
  kbType?: string;
  status?: string;
  sortBy?: string;
  sortOrder?: "asc" | "desc";
  limit?: number;
  offset?: number;
} = {}) => {
  const p = new URLSearchParams();
  if (q.keyword) p.set("keyword", q.keyword);
  if (q.kbType) p.set("kbType", q.kbType);
  if (q.status) p.set("status", q.status);
  if (q.sortBy) p.set("sortBy", q.sortBy);
  if (q.sortOrder) p.set("sortOrder", q.sortOrder);
  p.set("limit", String(q.limit ?? 20));
  p.set("offset", String(q.offset ?? 0));
  return apiJson<{ total: number; items: KbInfo[] }>(`/kb?${p.toString()}`);
};
/** 当前用户可读知识库(供库下拉 / Copilot 库选择)。 */
export const listReadableKbs = () => apiJson<{ items: KbInfo[] }>("/kb/readable");
/** 完整部门组织树(kb:list 授权,供知识库配置页授权组织树多选,无需 oa:dept:list)。 */
export const listKbOrgTree = () => apiJson<{ items: OaDept[] }>("/kb/org-tree");
/** 新建知识库:库名 + 类型;部门库须绑定唯一 Owner 部门(deptId,叶子)。base 库不绑定。 */
export const createKb = (kbName: string, kbType: string = "dept", deptId?: string) =>
  apiJson<{ id: string }>("/kb", { method: "POST", body: JSON.stringify({ kbName, kbType, deptId }) });
export const updateKb = (
  id: string,
  body: { kbName?: string; kbType?: string; deptId?: string; status?: string }
) => apiJson(`/kb/${id}`, { method: "PATCH", body: JSON.stringify(body) });
export const listKbGrants = (id: string) => apiJson<{ items: KbGrant[] }>(`/kb/${id}/grants`);
/** 以 editor/reader 级别授权一批组织节点(部门/中心);授任一节点=授其整棵子树,一次多 id。 */
export const grantKb = (
  id: string,
  body: { granteeIds: string[]; access: "editor" | "reader" }
) => apiJson<{ granted: string[] }>(`/kb/${id}/grant`, { method: "POST", body: JSON.stringify(body) });
export const revokeKb = (id: string, grantId: string) =>
  apiJson(`/kb/${id}/grant/${grantId}`, { method: "DELETE" });
/** 删除知识库(逻辑删除,库内有文件会被后端安全拦截)。 */
export const removeKb = (id: string) => apiJson(`/kb/${id}`, { method: "DELETE" });

// ============ 技能管理 ============
export interface SkillItem {
  id: string;
  name: string;
  displayName: string | null;
  description: string | null;
  sourceType: string;
  enabled: boolean;
  isBuiltin: boolean;
  scope: string;
  fileSize: number;
  uploadedBy: string | null;
  createdAt: string | null;
  grantedLabels?: string[];
}
export interface SkillGrant {
  id: string;
  granteeType: string;
  granteeId: string;
  granteeLabel?: string | null;  // 组织节点完整路径
}
export const listSkills = (q: {
  keyword?: string;
  enabled?: string;
  granteeDeptId?: string;
  sortBy?: string;
  sortOrder?: "asc" | "desc";
  limit?: number;
  offset?: number;
} = {}) => {
  const p = new URLSearchParams();
  if (q.keyword) p.set("keyword", q.keyword);
  if (q.enabled) p.set("enabled", q.enabled);
  if (q.granteeDeptId) p.set("granteeDeptId", q.granteeDeptId);
  if (q.sortBy) p.set("sortBy", q.sortBy);
  if (q.sortOrder) p.set("sortOrder", q.sortOrder);
  p.set("limit", String(q.limit ?? 20));
  p.set("offset", String(q.offset ?? 0));
  return apiJson<{ total: number; items: SkillItem[] }>(`/skills?${p.toString()}`);
};
/** 上传技能(.md 或 .zip),走 multipart。用原生 fetch,避免 apiFetch 强加 JSON Content-Type
 *  破坏 multipart 边界(浏览器需自行设置 boundary)。 */
export const uploadSkill = async (file: File) => {
  const fd = new FormData();
  fd.append("file", file);
  const res = await fetch(`${API_BASE}/skills/upload`, {
    method: "POST",
    body: fd,
    credentials: "include",
  });
  if (res.status === 401) throw new UnauthorizedError();
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error((data as { detail?: string }).detail || "上传失败");
  return data as { id: string; name: string };
};
export const toggleSkill = (id: string) =>
  apiJson<{ enabled: boolean }>(`/skills/${id}/toggle`, { method: "POST" });
export const previewSkill = async (id: string) => {
  const res = await apiFetch(`/skills/${id}/preview`);
  if (!res.ok) throw new Error("预览失败");
  return res.text();
};
export interface SkillTreeNode {
  name: string;
  type: "dir" | "file";
  path: string;
  children?: SkillTreeNode[];
}
export const fetchSkillTree = (id: string) =>
  apiJson<{ tree: SkillTreeNode[] }>(`/skills/${id}/tree`);
export const fetchSkillFile = async (id: string, path: string) => {
  const res = await apiFetch(`/skills/${id}/file?path=${encodeURIComponent(path)}`);
  if (!res.ok) throw new Error("读取失败");
  return res.text();
};
export const downloadSkillUrl = (id: string) => `${API_BASE}/skills/${id}/download`;
export const deleteSkill = (id: string) => apiJson(`/skills/${id}`, { method: "DELETE" });

// 技能部门授权
/** 完整部门组织树(oa:skill:grant 授权,供技能授权弹窗多选)。 */
export const listSkillOrgTree = () => apiJson<{ items: OaDept[] }>("/skills/org-tree");
export const listSkillGrants = (id: string) => apiJson<{ items: SkillGrant[] }>(`/skills/${id}/grants`);
/** 授权一批组织节点(部门/中心)使用该技能;授任一节点=授其整棵子树,一次多 id。 */
export const grantSkill = (id: string, granteeIds: string[]) =>
  apiJson<{ granted: string[] }>(`/skills/${id}/grant`, {
    method: "POST",
    body: JSON.stringify({ granteeIds }),
  });
export const revokeSkill = (id: string, grantId: string) =>
  apiJson(`/skills/${id}/grant/${grantId}`, { method: "DELETE" });