profileApi.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // 客服个人资料 API 服务
  2. import { apiUrl } from "@/lib/config";
  3. import { Profile } from "../types";
  4. // 获取个人资料
  5. export async function fetchProfile(userId: number): Promise<Profile | null> {
  6. const res = await fetch(apiUrl(`/agent/profile/${userId}`), {
  7. cache: "no-store",
  8. });
  9. if (!res.ok) {
  10. const error = await res.json().catch(() => ({}));
  11. throw new Error(
  12. error.error || error.message || `获取个人资料失败 (${res.status})`
  13. );
  14. }
  15. const data = await res.json();
  16. return {
  17. id: data.id ?? 0,
  18. username: data.username ?? "",
  19. role: data.role ?? "",
  20. avatar_url: data.avatar_url ?? "",
  21. nickname: data.nickname ?? "",
  22. email: data.email ?? "",
  23. receive_ai_conversations: data.receive_ai_conversations ?? true, // 默认接收
  24. };
  25. }
  26. // 更新个人资料
  27. export interface UpdateProfilePayload {
  28. nickname?: string;
  29. email?: string;
  30. receive_ai_conversations?: boolean; // 是否接收 AI 对话
  31. }
  32. export async function updateProfile(
  33. userId: number,
  34. payload: UpdateProfilePayload
  35. ): Promise<Profile> {
  36. const res = await fetch(apiUrl(`/agent/profile/${userId}`), {
  37. method: "PUT",
  38. headers: { "Content-Type": "application/json" },
  39. body: JSON.stringify(payload),
  40. });
  41. if (!res.ok) {
  42. const error = await res.json().catch(() => ({}));
  43. throw new Error(
  44. error.error || error.message || `更新个人资料失败 (${res.status})`
  45. );
  46. }
  47. const data = await res.json();
  48. return {
  49. id: data.id ?? 0,
  50. username: data.username ?? "",
  51. role: data.role ?? "",
  52. avatar_url: data.avatar_url ?? "",
  53. nickname: data.nickname ?? "",
  54. email: data.email ?? "",
  55. receive_ai_conversations: data.receive_ai_conversations ?? true, // 默认接收
  56. };
  57. }
  58. // 上传头像
  59. export async function uploadAvatar(
  60. userId: number,
  61. file: File
  62. ): Promise<Profile> {
  63. const formData = new FormData();
  64. formData.append("avatar", file);
  65. const res = await fetch(apiUrl(`/agent/avatar/${userId}`), {
  66. method: "POST",
  67. body: formData,
  68. });
  69. if (!res.ok) {
  70. const error = await res.json().catch(() => ({}));
  71. throw new Error(
  72. error.error || error.message || `上传头像失败 (${res.status})`
  73. );
  74. }
  75. const data = await res.json();
  76. return {
  77. id: data.id ?? 0,
  78. username: data.username ?? "",
  79. role: data.role ?? "",
  80. avatar_url: data.avatar_url ?? "",
  81. nickname: data.nickname ?? "",
  82. email: data.email ?? "",
  83. receive_ai_conversations: data.receive_ai_conversations ?? true, // 默认接收
  84. };
  85. }