customer-list-store.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * `POST /customer/get_list@v1` 的**模块级共享快照**(缺口清单 C-8)。
  3. *
  4. * 此前同一份客户列表有三个各自独立的读源——第 2 册台账 `useCustomerDirectory()`、
  5. * 第 1 册组织 store `fetchAll()` 里为合伙人/团队反查而做的 `pagedAll(customerGetList)`、
  6. * 概览页 `useOverview()` 的客户状态分桶——同一页面进入即打 2 次同一接口
  7. * (`useLoad` 的飞行中去重按 `run` 身份合并,跨调用点合不了)。
  8. * 本模块把该列表收成**一份缓存 + 一次请求**:并发调用复用同一次在飞请求,
  9. * 热态直接回缓存,写操作后由 `invalidateCustomerList()` 显式作废。
  10. *
  11. * 失效口径(⛔ TTL、⛔ "看起来够新"):只有两种情况会重新打接口——
  12. * ① 本模块内任何客户写操作后 `invalidateCustomerList()`/`reload()`;② 换登录身份
  13. * (可见范围由后端按角色下发,⛔ 把上一个身份的快照留给下一个)。
  14. *
  15. * 取数失败⛔ 进缓存(下次调用真重取),并把 `ApiError` 如实回给每个读源——
  16. * 「本次取数失败」与「后端确实没有客户」必须能区分(总则§16.5)。
  17. */
  18. import { useEffect, useSyncExternalStore } from "react";
  19. import { customerGetList } from "./api/bos.ts";
  20. import type { ApiError } from "./api/http.ts";
  21. import type { CustomerListResult, CustomerListRow } from "./api/types.ts";
  22. import type { Load } from "./useLoad.ts";
  23. /** ⚠️ `page` 为 **0 基**(缺口清单 B-8),`page:1` 实测回空集。 */
  24. const PAGE_SIZE = 200;
  25. type State = { data: CustomerListResult | null; loading: boolean; error: ApiError | null };
  26. /** 首帧即「取数中」:冷快照下页面⛔ 闪一下空列表(看起来像「0 条客户」)。 */
  27. let state: State = { data: null, loading: true, error: null };
  28. let fresh = false;
  29. /** 在飞请求的发起代数:其间作废过 ⇒ 结果⛔ 回写快照(否则写前的数据会顶掉写后的)。 */
  30. let epoch = 0;
  31. let inflight: Promise<CustomerListResult> | null = null;
  32. const listeners = new Set<() => void>();
  33. function publish(next: State) {
  34. state = next;
  35. listeners.forEach((listener) => listener());
  36. }
  37. /** 分页取全量(`total` 可能是字符串,见缺口清单 B-7)。 */
  38. async function fetchAllPages(): Promise<CustomerListResult> {
  39. const acc: CustomerListRow[] = [];
  40. let total = 0;
  41. let page = 0;
  42. for (;;) {
  43. const res = await customerGetList({ page, page_size: PAGE_SIZE });
  44. const rows = res?.items ?? [];
  45. acc.push(...rows);
  46. total = Number(res?.total ?? acc.length);
  47. if (!rows.length || acc.length >= total || page >= 40) return { items: acc, total };
  48. page += 1;
  49. }
  50. }
  51. /**
  52. * 读客户列表:热缓存直接返回、在飞请求直接复用,冷态才发一次。
  53. * `force`=绕开缓存(页面「重试/刷新」用)。失败不进缓存。
  54. */
  55. export function loadCustomerList(force = false): Promise<CustomerListResult> {
  56. if (inflight) return inflight;
  57. if (!force && fresh && state.data) return Promise.resolve(state.data);
  58. const myEpoch = epoch;
  59. const run = fetchAllPages().then(
  60. (data) => {
  61. if (inflight === run) inflight = null;
  62. if (myEpoch !== epoch) {
  63. // 其间有写操作作废过:把结果交回调用方(它要的是一个可用应答),但⛔ 进快照。
  64. if (!inflight) publish({ ...state, loading: false });
  65. return data;
  66. }
  67. fresh = true;
  68. publish({ data, loading: false, error: null });
  69. return data;
  70. },
  71. (e) => {
  72. if (inflight === run) inflight = null;
  73. if (myEpoch === epoch) publish({ ...state, loading: false, error: e as ApiError });
  74. else if (!inflight) publish({ ...state, loading: false });
  75. throw e;
  76. },
  77. );
  78. inflight = run;
  79. publish({ ...state, loading: true, error: null });
  80. return run;
  81. }
  82. /**
  83. * 作废缓存(客户建档/编辑/归属变更/移动区域/删除/批量导入建档/分账号数变化后调用)。
  84. * 在飞的旧请求一并作废:完成后⛔ 回写快照。已挂载的读源由调用方随后 `reload()` 触发重取。
  85. */
  86. export function invalidateCustomerList() {
  87. epoch += 1;
  88. fresh = false;
  89. inflight = null;
  90. }
  91. /** 换登录身份:整块快照连同失败态一起清,⛔ 把上一个身份的可见范围留给下一个。 */
  92. export function resetCustomerListCache() {
  93. invalidateCustomerList();
  94. publish({ data: null, loading: true, error: null });
  95. }
  96. export function peekCustomerList(): CustomerListResult | null {
  97. return state.data;
  98. }
  99. const subscribe = (listener: () => void) => {
  100. listeners.add(listener);
  101. return () => {
  102. listeners.delete(listener);
  103. };
  104. };
  105. /**
  106. * 与 `useLoad<CustomerListResult>` 同形状的读源(页面⛔ 感知缓存的存在):
  107. * 多处同时读 ⇒ 仍只发一次请求;`reload()`=作废 + 强制重取。
  108. */
  109. export function useCustomerList(): Load<CustomerListResult> {
  110. const snapshot = useSyncExternalStore(subscribe, () => state);
  111. useEffect(() => {
  112. loadCustomerList().catch(() => {});
  113. }, []);
  114. return {
  115. data: snapshot.data,
  116. loading: snapshot.loading,
  117. error: snapshot.error,
  118. reload: () => {
  119. invalidateCustomerList();
  120. loadCustomerList(true).catch(() => {});
  121. },
  122. };
  123. }