conversationApi.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { API_BASE_URL } from "@/lib/config";
  2. import {
  3. ConversationDetail,
  4. ConversationSummary,
  5. } from "../types";
  6. export async function fetchConversations(): Promise<ConversationSummary[]> {
  7. const res = await fetch(`${API_BASE_URL}/conversations`, {
  8. cache: "no-store",
  9. });
  10. if (!res.ok) {
  11. throw new Error("获取对话列表失败");
  12. }
  13. const data = await res.json();
  14. if (!Array.isArray(data)) {
  15. return [];
  16. }
  17. return data.map((item) => ({
  18. ...item,
  19. unread_count: item.unread_count ?? 0,
  20. }));
  21. }
  22. export async function searchConversations(
  23. query: string
  24. ): Promise<ConversationSummary[]> {
  25. const res = await fetch(
  26. `${API_BASE_URL}/conversations/search?q=${encodeURIComponent(query)}`,
  27. {
  28. cache: "no-store",
  29. }
  30. );
  31. if (!res.ok) {
  32. throw new Error("搜索对话失败");
  33. }
  34. const data = await res.json();
  35. if (!Array.isArray(data)) {
  36. return [];
  37. }
  38. return data.map((item) => ({
  39. ...item,
  40. unread_count: item.unread_count ?? 0,
  41. }));
  42. }
  43. export async function fetchConversationDetail(
  44. conversationId: number
  45. ): Promise<ConversationDetail | null> {
  46. const res = await fetch(`${API_BASE_URL}/conversations/${conversationId}`, {
  47. cache: "no-store",
  48. });
  49. if (!res.ok) {
  50. return null;
  51. }
  52. const data = await res.json();
  53. return {
  54. ...data,
  55. unread_count: data.unread_count ?? 0,
  56. };
  57. }
  58. export interface UpdateConversationContactPayload {
  59. email?: string;
  60. phone?: string;
  61. notes?: string;
  62. }
  63. export interface UpdateConversationContactResult {
  64. email: string;
  65. phone: string;
  66. notes: string;
  67. }
  68. export async function updateConversationContact(
  69. conversationId: number,
  70. payload: UpdateConversationContactPayload
  71. ): Promise<UpdateConversationContactResult> {
  72. const res = await fetch(
  73. `${API_BASE_URL}/conversations/${conversationId}/contact`,
  74. {
  75. method: "PUT",
  76. headers: { "Content-Type": "application/json" },
  77. body: JSON.stringify(payload),
  78. }
  79. );
  80. if (!res.ok) {
  81. throw new Error("更新访客联系信息失败");
  82. }
  83. const data = await res.json();
  84. return {
  85. email: data.email ?? "",
  86. phone: data.phone ?? "",
  87. notes: data.notes ?? "",
  88. };
  89. }