AccountPages.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import { useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
  2. import { BellRing, KeyRound, Mail, Pencil, Smartphone, UserRound, X } from "lucide-react";
  3. import { Button } from "../components/ui/button";
  4. import { Input } from "../components/ui/input";
  5. import { Tri } from "../components/triState";
  6. import { useDemoAccount, useDemoIdentity } from "../lib/demo-session";
  7. import { useSession } from "../auth/session";
  8. import {
  9. accountChangePassword,
  10. accountNotifyEmail,
  11. accountNotifyPref,
  12. accountNotifyPrefSave,
  13. accountProfileUpdate,
  14. } from "../lib/api/bos";
  15. import type { AccountNotifyPrefResult } from "../lib/api/types";
  16. import { ACCT_STATUS, label } from "../lib/api/labels";
  17. import { ApiError } from "../lib/api/http";
  18. import { WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  19. /** 三态:未登录=未配置,登录后后端没下发该键=取数失败,⛔ 用「—」冒充。 */
  20. function field(value: string | null | undefined, missing = WORD_UNCONFIGURED) {
  21. if (value === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
  22. if (value === null || value === "") return <Tri tone="missing" text={missing} />;
  23. return value;
  24. }
  25. function apiMessage(e: unknown, fallback: string) {
  26. return e instanceof ApiError ? e.message : fallback;
  27. }
  28. /**
  29. * 「个人资料」页(AC-05)——本人账号信息 + 自助改密 + 通知投递通道。
  30. *
  31. * 呈现形态:业主 2026-11-14 定案为**叠在当前页面上的浮层**(见 `components/layout/ProfileOverlay.tsx`),
  32. * 由顶栏用户菜单就地打开,关闭按钮/Esc/点遮罩即可退出;⛔ 再作为独立页面把用户带走。
  33. *
  34. * 账号信息取自 `GET /auth/context@v1`(后端已下发姓名/主体/手机号摘要/账号状态);
  35. * 姓名可点输入框右侧悬停出现的编辑图标就地改(`POST /account/profile/update@v1`,只写账号级
  36. * 自填姓名,⛔ 动主体档案);改密走 `POST /account/change_password@v1`(平台自助口,只改本人这一行);
  37. * 通知投递通道与投递邮箱(AC-06)同页承载(需求 §3.4、总则 §16.2 的 `/bos/me`);
  38. * 换绑手机号仍由运营侧代办,本页⛔ 提供自助换绑表单。
  39. * 校验口径:原密码必填、新密码 8–32 位、两次一致、新旧不同(`KLT-T223` 前置拦截)。
  40. */
  41. export function ProfilePage({ titleId }: { titleId?: string } = {}) {
  42. const account = useDemoAccount();
  43. const identity = useDemoIdentity();
  44. const { ctx, refresh } = useSession();
  45. // 改密界面由第一张卡片右侧的图标按钮唤起(业主 2026-11-14:⛔ 再占一张卡片)。
  46. const [pwdOpen, setPwdOpen] = useState(false);
  47. const [pwdNotice, setPwdNotice] = useState("");
  48. // 姓名就地编辑(姓名是账号持有人本人的姓名,⛔ 主体档案名称)
  49. const [editingName, setEditingName] = useState(false);
  50. const [nameDraft, setNameDraft] = useState("");
  51. const [namePending, setNamePending] = useState(false);
  52. const [nameError, setNameError] = useState("");
  53. const [nameNotice, setNameNotice] = useState("");
  54. function startEditName() {
  55. setNameDraft(ctx?.display_name ?? "");
  56. setNameError("");
  57. setNameNotice("");
  58. setEditingName(true);
  59. }
  60. function cancelEditName() {
  61. if (namePending) return;
  62. setEditingName(false);
  63. setNameError("");
  64. }
  65. async function saveName() {
  66. if (namePending) return;
  67. const value = nameDraft.trim();
  68. if (!value) {
  69. setNameError("请输入姓名");
  70. return;
  71. }
  72. setNamePending(true);
  73. setNameError("");
  74. try {
  75. await accountProfileUpdate({ display_name: value });
  76. // 顶栏称呼与资料页同源 `auth/context@v1`,保存后回读一次,⛔ 让两处显示打架。
  77. await refresh();
  78. setEditingName(false);
  79. setNameNotice("姓名已保存。");
  80. } catch (e) {
  81. setNameError(apiMessage(e, "保存姓名失败,请稍后重试"));
  82. } finally {
  83. setNamePending(false);
  84. }
  85. }
  86. const displayName = ctx?.display_name ?? ctx?.username ?? identity?.login ?? account;
  87. const acctStatus = ctx?.acct_status ? label(ACCT_STATUS, ctx.acct_status) : undefined;
  88. return (
  89. // ⚠️ 宽度跟随容器:资料页现在只作为浮层内容渲染,⛔ 再套 `max-w-3xl`
  90. // (那会让卡片比面板窄、右侧空出一条,实测面板 920 时左 25/右 127)。
  91. <section className="w-full">
  92. {/* 浮层内右上角有固定关闭按钮:标题区留出右侧安全区,⛔ 让副标题压到按钮下面。 */}
  93. <header className={titleId ? "pr-12" : undefined}>
  94. <h1 className="text-2xl font-semibold tracking-tight" id={titleId}>个人资料</h1>
  95. <p className="mt-2 text-sm text-muted-foreground">本人账号信息、密码维护与通知投递通道配置;换绑手机号请联系运营代办。</p>
  96. </header>
  97. <div className="mt-6 flex items-center gap-4 rounded-lg border border-border bg-card p-6 shadow-[var(--shadow-panel)]">
  98. <span className="grid size-12 shrink-0 place-items-center rounded-full bg-primary-soft text-primary"><UserRound aria-hidden="true" size={22} /></span>
  99. <div className="min-w-0 flex-1">
  100. <p className="font-semibold">{field(displayName)}</p>
  101. <p className="mt-1 text-sm text-muted-foreground">{identity?.title ?? "尚未接入认证"}</p>
  102. {identity && <p className="mt-1 text-sm text-muted-foreground">登录账号:{identity.login}</p>}
  103. </div>
  104. {/* 改密入口挂在名片右侧:点它唤起改密浮层,⛔ 再占一张卡片(业主 2026-11-14)。
  105. 用描边图标按钮而非纯 ghost:这是唯一的功能入口,需要一眼可见(⛔ 悬停才出现)。 */}
  106. <Button
  107. aria-haspopup="dialog"
  108. aria-label="修改密码"
  109. className="shrink-0 text-muted-foreground hover:text-foreground"
  110. onClick={() => { setPwdNotice(""); setPwdOpen(true); }}
  111. size="icon"
  112. title="修改密码"
  113. type="button"
  114. variant="outline"
  115. >
  116. <KeyRound aria-hidden="true" size={18} />
  117. </Button>
  118. </div>
  119. {pwdNotice && <p className="mt-2 text-sm text-primary" role="status">{pwdNotice}</p>}
  120. <dl className="mt-4 grid grid-cols-2 gap-px overflow-hidden rounded-lg border border-border bg-border text-sm sm:grid-cols-3">
  121. <div className="bg-card px-4 py-3">
  122. <dt className="text-xs text-muted-foreground">姓名</dt>
  123. <dd className="mt-1">
  124. {editingName ? (
  125. <div className="flex flex-col gap-1.5">
  126. <div className="flex flex-wrap items-center gap-1.5">
  127. <Input
  128. aria-label="姓名"
  129. autoFocus
  130. className="h-8 min-w-0 flex-1 basis-full sm:basis-0"
  131. disabled={namePending}
  132. maxLength={64}
  133. onChange={(e) => { setNameDraft(e.target.value); setNameError(""); }}
  134. onKeyDown={(e) => {
  135. if (e.key === "Enter") { e.preventDefault(); void saveName(); }
  136. // ⚠️ 必须拦住冒泡:资料浮层在 document 上监听 Esc 关闭,⛔ 让「取消改名」把整层关掉。
  137. if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); cancelEditName(); }
  138. }}
  139. value={nameDraft}
  140. />
  141. <Button disabled={namePending} onClick={() => void saveName()} size="sm" type="button">
  142. {namePending ? "保存中…" : "保存"}
  143. </Button>
  144. <Button disabled={namePending} onClick={cancelEditName} size="sm" type="button" variant="ghost">
  145. 取消
  146. </Button>
  147. </div>
  148. {nameError && <p className="text-xs text-destructive" role="alert">{nameError}</p>}
  149. </div>
  150. ) : (
  151. <span className="group/name flex items-start gap-1">
  152. <span className="break-words font-medium">{field(ctx?.display_name)}</span>
  153. <button
  154. aria-label="修改姓名"
  155. className="cursor-pointer rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/name:opacity-100"
  156. onClick={startEditName}
  157. title="修改姓名"
  158. type="button"
  159. >
  160. <Pencil aria-hidden="true" size={13} />
  161. </button>
  162. </span>
  163. )}
  164. </dd>
  165. </div>
  166. <div className="bg-card px-4 py-3"><dt className="text-xs text-muted-foreground">账号用途</dt><dd className="mt-1 font-medium">{field(identity?.title ?? ctx?.role_code)}</dd></div>
  167. <div className="bg-card px-4 py-3"><dt className="text-xs text-muted-foreground">所属主体</dt><dd className="mt-1 font-medium">{field(ctx?.subject_name)}</dd></div>
  168. <div className="bg-card px-4 py-3"><dt className="text-xs text-muted-foreground">登录名</dt><dd className="mt-1 font-medium">{field(ctx?.username ?? identity?.login)}</dd></div>
  169. <div className="bg-card px-4 py-3"><dt className="text-xs text-muted-foreground">账号状态</dt><dd className="mt-1 font-medium">{field(acctStatus)}</dd></div>
  170. <div className="bg-card px-4 py-3"><dt className="text-xs text-muted-foreground">绑定手机号</dt><dd className="mt-1 font-medium">{field(ctx?.mobile_hint, "未绑定手机号")}</dd></div>
  171. </dl>
  172. {nameNotice && <p className="mt-2 text-sm text-primary" role="status">{nameNotice}</p>}
  173. <NotifyPrefPanel />
  174. {pwdOpen && (
  175. <PasswordDialog
  176. onClose={() => setPwdOpen(false)}
  177. onSaved={() => {
  178. setPwdOpen(false);
  179. setPwdNotice("密码已修改,下次登录请使用新密码。");
  180. }}
  181. />
  182. )}
  183. </section>
  184. );
  185. }
  186. /**
  187. * 改密浮层(AC-05)——由名片右侧的钥匙图标唤起,⛔ 再占一张「修改密码」卡片。
  188. *
  189. * 层级(`z-[70]`)高于个人资料浮层(`z-[60]`):看起来是资料浮层上的第二层。
  190. * ⚠️ Esc 必须**拦在本层**(`stopPropagation`),否则会继续冒泡到资料浮层的
  191. * document 监听器、把整个资料浮层一起关掉。
  192. *
  193. * 校验口径:原密码必填、新密码 8–32 位、两次一致、新旧不同(`KLT-T223` 前置拦截);
  194. * 真正的口令校验与落库在平台侧(`POST /account/change_password@v1`),本层只做入口拦截。
  195. */
  196. function PasswordDialog({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) {
  197. const [oldPassword, setOldPassword] = useState("");
  198. const [newPassword, setNewPassword] = useState("");
  199. const [confirmPassword, setConfirmPassword] = useState("");
  200. const [error, setError] = useState("");
  201. const [pending, setPending] = useState(false);
  202. const oldRef = useRef<HTMLInputElement>(null);
  203. useEffect(() => {
  204. oldRef.current?.focus();
  205. }, []);
  206. async function submit(event: FormEvent<HTMLFormElement>) {
  207. event.preventDefault();
  208. if (pending) return;
  209. setError("");
  210. if (!oldPassword) return setError("请输入原密码");
  211. if (newPassword.length < 8 || newPassword.length > 32) return setError("新密码需 8 至 32 位");
  212. if (newPassword !== confirmPassword) return setError("两次输入的新密码不一致");
  213. if (newPassword === oldPassword) return setError("新密码不能与原密码相同");
  214. setPending(true);
  215. try {
  216. await accountChangePassword({ old_password: oldPassword, new_password: newPassword });
  217. onSaved();
  218. } catch (e) {
  219. setError(apiMessage(e, "修改密码失败,请稍后重试"));
  220. } finally {
  221. setPending(false);
  222. }
  223. }
  224. return (
  225. <div
  226. className="fixed inset-0 z-[70] grid place-items-center bg-black/50 p-4"
  227. // 点遮罩空白处关闭本层(⛔ 穿透到资料浮层的遮罩)。
  228. onMouseDown={(event) => {
  229. if (event.target === event.currentTarget && !pending) onClose();
  230. }}
  231. // 两层浮层叠着:Esc 只关最上面这层(⛔ 冒泡到资料浮层的监听器)。
  232. onKeyDown={(event) => {
  233. if (event.key !== "Escape") return;
  234. event.preventDefault();
  235. event.stopPropagation();
  236. if (!pending) onClose();
  237. }}
  238. >
  239. <form
  240. aria-labelledby="password-dialog-title"
  241. aria-modal="true"
  242. className="w-[min(440px,100%)] rounded-xl border border-border bg-card p-6 shadow-[var(--shadow-panel)]"
  243. noValidate
  244. onSubmit={submit}
  245. role="dialog"
  246. >
  247. <div className="flex items-start justify-between gap-4">
  248. <div>
  249. <h2 className="flex items-center gap-2 text-base font-semibold" id="password-dialog-title">
  250. <KeyRound aria-hidden="true" size={17} />修改密码
  251. </h2>
  252. <p className="mt-1 text-sm text-muted-foreground">只改本人这一行的登录密码;改完请用新密码登录。</p>
  253. </div>
  254. <Button
  255. aria-label="关闭修改密码"
  256. className="shrink-0 text-muted-foreground"
  257. disabled={pending}
  258. onClick={onClose}
  259. size="icon"
  260. title="关闭(Esc)"
  261. type="button"
  262. variant="ghost"
  263. >
  264. <X aria-hidden="true" size={18} />
  265. </Button>
  266. </div>
  267. <div className="mt-4 grid gap-4">
  268. <label className="block text-sm">
  269. <span className="field-label mb-1.5 block">原密码</span>
  270. <Input
  271. autoComplete="current-password"
  272. disabled={pending}
  273. onChange={(e) => { setOldPassword(e.target.value); setError(""); }}
  274. ref={oldRef}
  275. type="password"
  276. value={oldPassword}
  277. />
  278. </label>
  279. <label className="block text-sm">
  280. <span className="field-label mb-1.5 block">新密码</span>
  281. <Input
  282. autoComplete="new-password"
  283. disabled={pending}
  284. onChange={(e) => { setNewPassword(e.target.value); setError(""); }}
  285. placeholder="8 至 32 位"
  286. type="password"
  287. value={newPassword}
  288. />
  289. </label>
  290. <label className="block text-sm">
  291. <span className="field-label mb-1.5 block">确认新密码</span>
  292. <Input
  293. autoComplete="new-password"
  294. disabled={pending}
  295. onChange={(e) => { setConfirmPassword(e.target.value); setError(""); }}
  296. type="password"
  297. value={confirmPassword}
  298. />
  299. </label>
  300. </div>
  301. {error && <p className="mt-3 text-sm text-destructive" role="alert">{error}</p>}
  302. <div className="mt-5 flex justify-end gap-2">
  303. <Button disabled={pending} onClick={onClose} type="button" variant="outline">取消</Button>
  304. <Button disabled={pending} type="submit">{pending ? "提交中…" : "保存新密码"}</Button>
  305. </div>
  306. </form>
  307. </div>
  308. );
  309. }
  310. /** 投递地址的就地编辑状态(目前只有邮箱通道用;⛔ 与通道开关混在一个 pending 里)。 */type AddressEdit = {
  311. editing: boolean;
  312. draft: string;
  313. pending: boolean;
  314. error: string;
  315. /** 已登记本人地址时给「清空登记」;为 `undefined` 表示当前是档案回落地址、无本人登记可清。 */
  316. onClear?: () => void;
  317. onDraftChange: (next: string) => void;
  318. onStart: () => void;
  319. onCancel: () => void;
  320. onSave: () => void;
  321. };
  322. /** 通道卡片:站内固定开启由 `fixed` 表达,其余两路由服务端 `available` 决定能否切换。 */
  323. function ChannelRow({
  324. icon,
  325. title,
  326. description,
  327. enabled,
  328. available,
  329. addressHint,
  330. fixed,
  331. pending,
  332. onToggle,
  333. addressEdit,
  334. emptyAddressText,
  335. }: {
  336. icon: ReactNode;
  337. title: string;
  338. description: string;
  339. enabled: boolean;
  340. available: boolean;
  341. addressHint: string | null;
  342. fixed?: boolean;
  343. pending: boolean;
  344. onToggle?: (next: boolean) => void;
  345. /** 给出即把「投递地址」做成可悬停编辑(业主 2026-11-14:邮箱地址就地录入,⛔ 另开一张卡片)。 */
  346. addressEdit?: AddressEdit;
  347. /** 地址为空时的占位文案(只在 `addressEdit` 存在时用得上:空地址也要留出入口)。 */
  348. emptyAddressText?: string;
  349. }) {
  350. const editing = addressEdit?.editing ?? false;
  351. const showAddressLine = editing || Boolean(addressHint) || Boolean(addressEdit);
  352. return (
  353. // `group/addr` 挂整行:悬停这张卡任意位置就露出地址编辑图标(⛔ 必须精准悬停到文字上)。
  354. <div className="group/addr flex items-start gap-4 border-t border-border px-6 py-4 first:border-t-0">
  355. <span className="mt-0.5 grid size-9 shrink-0 place-items-center rounded-md bg-primary-soft text-primary">{icon}</span>
  356. <div className="min-w-0 flex-1">
  357. <div className="flex items-center gap-2">
  358. <p className="font-medium">{title}</p>
  359. {fixed && <span className="rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">固定开启 · 不可关闭</span>}
  360. {!fixed && !available && <span className="rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">当前不可切换</span>}
  361. </div>
  362. <p className="mt-1 text-sm leading-6 text-muted-foreground">{description}</p>
  363. {addressEdit && editing ? (
  364. <div className="mt-1.5 flex flex-col gap-1.5">
  365. <div className="flex flex-wrap items-center gap-1.5">
  366. <Input
  367. aria-label={`${title}投递地址`}
  368. autoFocus
  369. className="h-8 min-w-0 flex-1 basis-full sm:basis-64"
  370. disabled={addressEdit.pending}
  371. maxLength={254}
  372. onChange={(e) => addressEdit.onDraftChange(e.target.value)}
  373. onKeyDown={(e) => {
  374. if (e.key === "Enter") { e.preventDefault(); addressEdit.onSave(); }
  375. // 同上:Esc 只取消本行编辑(⛔ 冒泡到资料浮层把整层关掉)。
  376. if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); addressEdit.onCancel(); }
  377. }}
  378. placeholder="例如 notify@example.com"
  379. type="email"
  380. value={addressEdit.draft}
  381. />
  382. <Button disabled={addressEdit.pending} onClick={addressEdit.onSave} size="sm" type="button">
  383. {addressEdit.pending ? "保存中…" : "保存"}
  384. </Button>
  385. <Button disabled={addressEdit.pending} onClick={addressEdit.onCancel} size="sm" type="button" variant="ghost">
  386. 取消
  387. </Button>
  388. {addressEdit.onClear && (
  389. <Button disabled={addressEdit.pending} onClick={addressEdit.onClear} size="sm" type="button" variant="outline">
  390. 清空登记
  391. </Button>
  392. )}
  393. </div>
  394. <p className="text-xs text-muted-foreground">
  395. 保存后立即生效;清除本人登记请点「清空登记」(运营商/合伙人会回落到主体档案邮箱)。
  396. </p>
  397. {addressEdit.error && <p className="text-xs text-destructive" role="alert">{addressEdit.error}</p>}
  398. </div>
  399. ) : showAddressLine ? (
  400. <p className="mt-1 flex items-start gap-1 text-sm text-muted-foreground">
  401. <span>
  402. 投递地址:
  403. <span className={addressHint ? "font-medium text-foreground" : undefined}>
  404. {addressHint ?? emptyAddressText ?? "未登记"}
  405. </span>
  406. </span>
  407. {addressEdit && !editing && (
  408. <button
  409. aria-label={`修改${title}投递地址`}
  410. className="cursor-pointer rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/addr:opacity-100"
  411. onClick={addressEdit.onStart}
  412. title={`修改${title}投递地址`}
  413. type="button"
  414. >
  415. <Pencil aria-hidden="true" size={13} />
  416. </button>
  417. )}
  418. </p>
  419. ) : null}
  420. </div>
  421. {fixed ? (
  422. <span className="mt-1 text-sm font-medium text-primary">已开启</span>
  423. ) : (
  424. <label className="ops-form-check mt-1 shrink-0">
  425. <input
  426. checked={enabled && available}
  427. disabled={!available || pending}
  428. onChange={(e) => onToggle?.(e.target.checked)}
  429. type="checkbox"
  430. />
  431. {enabled && available ? "已开启" : "已关闭"}
  432. </label>
  433. )}
  434. </div>
  435. );
  436. }
  437. /**
  438. * 「通知投递通道」面板(AC-06)——并入「个人资料」页(需求 §3.4、总则 §16.2 的 `/bos/me`)。
  439. *
  440. * 三个开关是**本人账号**的投递偏好(⛔ 不动主体档案、⛔ 不影响通知是否产生):
  441. * 站内恒开不可关;邮箱默认开、需有生效收件地址;短信默认关、需已绑定手机号。
  442. * 邮箱地址在「邮箱」这一行内就地登记/清空(悬停行内地址出铅笔图标),为空时
  443. * 运营商/合伙人回落档案邮箱(页面如实标出来源)。⛔ 再单开一张「通知投递邮箱」卡片。
  444. */
  445. function NotifyPrefPanel() {
  446. const { ctx } = useSession();
  447. const [pref, setPref] = useState<AccountNotifyPrefResult | null>(null);
  448. const [loading, setLoading] = useState(true);
  449. const [loadError, setLoadError] = useState("");
  450. const [actionError, setActionError] = useState("");
  451. const [notice, setNotice] = useState("");
  452. const [pending, setPending] = useState(false);
  453. // 邮箱投递地址就地编辑(业主 2026-11-14:并入本卡片、⛔ 再单开一张「通知投递邮箱」卡)
  454. const [editingEmail, setEditingEmail] = useState(false);
  455. const [emailDraft, setEmailDraft] = useState("");
  456. const [emailPending, setEmailPending] = useState(false);
  457. const [emailError, setEmailError] = useState("");
  458. const load = useCallback(async (options?: { quiet?: boolean }) => {
  459. if (!options?.quiet) setLoading(true);
  460. setLoadError("");
  461. try {
  462. setPref(await accountNotifyPref());
  463. } catch (e) {
  464. setLoadError(apiMessage(e, "读取通知投递偏好失败,请稍后重试"));
  465. } finally {
  466. if (!options?.quiet) setLoading(false);
  467. }
  468. }, []);
  469. useEffect(() => {
  470. if (ctx) void load();
  471. }, [ctx, load]);
  472. async function saveToggles(next: { mail: boolean; sms: boolean }) {
  473. if (!pref || pending) return;
  474. setPending(true);
  475. setActionError("");
  476. setNotice("");
  477. try {
  478. await accountNotifyPrefSave({ mail_enabled: next.mail, sms_enabled: next.sms });
  479. setPref({
  480. ...pref,
  481. mail: { ...pref.mail, enabled: next.mail },
  482. sms: { ...pref.sms, enabled: next.sms },
  483. items: pref.items.map((item) =>
  484. item.channel === "mail" ? { ...item, enabled: next.mail }
  485. : item.channel === "sms" ? { ...item, enabled: next.sms }
  486. : item,
  487. ),
  488. });
  489. setNotice("通知投递偏好已保存。");
  490. } catch (e) {
  491. setActionError(apiMessage(e, "保存通知投递偏好失败,请稍后重试"));
  492. // 失败回读,避免界面停留在未落库的乐观值上。
  493. await load({ quiet: true });
  494. } finally {
  495. setPending(false);
  496. }
  497. }
  498. async function saveEmail(value: string) {
  499. if (!pref || emailPending) return;
  500. setEmailPending(true);
  501. setEmailError("");
  502. setActionError("");
  503. setNotice("");
  504. try {
  505. const result = await accountNotifyEmail({ email: value });
  506. setPref({
  507. ...pref,
  508. mail: {
  509. ...pref.mail,
  510. available: result.address_hint !== null,
  511. address_hint: result.address_hint,
  512. address_source: result.address_source,
  513. },
  514. items: pref.items.map((item) =>
  515. item.channel === "mail"
  516. ? { ...item, available: result.address_hint !== null, address_hint: result.address_hint }
  517. : item,
  518. ),
  519. });
  520. setEditingEmail(false);
  521. setEmailDraft("");
  522. setNotice(value.trim() ? "通知投递邮箱已保存。" : "通知投递邮箱已清空。");
  523. } catch (e) {
  524. setEmailError(apiMessage(e, "保存通知投递邮箱失败,请稍后重试"));
  525. } finally {
  526. setEmailPending(false);
  527. }
  528. }
  529. const mail = pref?.mail;
  530. const sms = pref?.sms;
  531. const inapp = pref?.inapp;
  532. const usingFallback = mail?.address_source === "operator_profile" || mail?.address_source === "partner_profile";
  533. const hasOwnEmail = mail?.address_source === "account";
  534. return (
  535. <>
  536. <section className="mt-6 overflow-hidden rounded-lg border border-border bg-card shadow-[var(--shadow-panel)]">
  537. <header className="flex items-center justify-between px-6 py-4">
  538. <div>
  539. <h2 className="flex items-center gap-2 text-base font-semibold"><BellRing aria-hidden="true" size={17} />通知投递通道</h2>
  540. <p className="mt-1 text-sm text-muted-foreground">开关只作用于本人账号;站内标记与待处理提示不受影响。</p>
  541. </div>
  542. {loading && <span className="text-sm text-muted-foreground">读取中…</span>}
  543. </header>
  544. {loadError && (
  545. <div className="border-t border-border px-6 py-4 text-sm text-destructive" role="alert">
  546. {loadError}
  547. <Button className="ml-3" onClick={() => void load()} size="sm" type="button" variant="outline">重试</Button>
  548. </div>
  549. )}
  550. {!loadError && !loading && !pref && (
  551. <p className="border-t border-border px-6 py-4 text-sm text-muted-foreground">后端未返回通知投递偏好。</p>
  552. )}
  553. {pref && (
  554. <>
  555. <ChannelRow
  556. addressHint={inapp?.address_hint ?? null}
  557. available
  558. description="站内消息与待处理提示始终送达,是业务留痕的兜底通道。"
  559. enabled
  560. fixed
  561. icon={<BellRing aria-hidden="true" size={17} />}
  562. pending={pending}
  563. title="站内"
  564. />
  565. <ChannelRow
  566. addressEdit={{
  567. editing: editingEmail,
  568. draft: emailDraft,
  569. pending: emailPending,
  570. error: emailError,
  571. // 只有本人登记过才给「清空登记」;当前是档案回落地址时没有本人登记可清。
  572. onClear: hasOwnEmail ? () => void saveEmail("") : undefined,
  573. onDraftChange: (next) => { setEmailDraft(next); setEmailError(""); },
  574. onStart: () => { setEmailDraft(""); setEmailError(""); setNotice(""); setActionError(""); setEditingEmail(true); },
  575. onCancel: () => { if (emailPending) return; setEditingEmail(false); setEmailError(""); },
  576. onSave: () => {
  577. const value = emailDraft.trim();
  578. if (!value) return setEmailError("请输入邮箱地址;如需清除本人登记,请点「清空登记」");
  579. void saveEmail(value);
  580. },
  581. }}
  582. addressHint={mail?.address_hint ?? null}
  583. available={mail?.available ?? false}
  584. description={
  585. mail?.available
  586. ? usingFallback
  587. ? "通知发往主体档案邮箱;点地址右侧图标可登记本人投递邮箱覆盖它。"
  588. : "通知发往本人登记的投递邮箱;可随时关闭或点地址右侧图标更换地址。"
  589. : "尚未登记通知投递邮箱;点地址右侧图标登记后才能开启邮箱投递。"
  590. }
  591. emptyAddressText="未登记(点右侧图标登记)"
  592. enabled={mail?.enabled ?? false}
  593. icon={<Mail aria-hidden="true" size={17} />}
  594. onToggle={(next) => void saveToggles({ mail: next, sms: sms?.enabled ?? false })}
  595. pending={pending}
  596. title="邮箱"
  597. />
  598. <ChannelRow
  599. addressHint={sms?.address_hint ?? null}
  600. available={sms?.available ?? false}
  601. description={
  602. sms?.available
  603. ? "通知以短信发往绑定手机号;换绑手机号请联系运营代办。"
  604. : "当前账号未绑定手机号,不能开启短信投递。"
  605. }
  606. enabled={sms?.enabled ?? false}
  607. icon={<Smartphone aria-hidden="true" size={17} />}
  608. onToggle={(next) => void saveToggles({ mail: mail?.enabled ?? true, sms: next })}
  609. pending={pending}
  610. title="手机短信"
  611. />
  612. </>
  613. )}
  614. {/* 卡内反馈区:⛔ 再单开「通知投递邮箱」卡(业主 2026-11-14 定案,地址已并入上面的行内编辑)。 */}
  615. {(actionError || notice) && (
  616. <div className="border-t border-border px-6 py-3">
  617. {actionError && <p className="text-sm text-destructive" role="alert">{actionError}</p>}
  618. {notice && !actionError && <p className="text-sm text-primary" role="status">{notice}</p>}
  619. </div>
  620. )}
  621. </section>
  622. </>
  623. );
  624. }