Sfoglia il codice sorgente

新增合伙人账号入口并重做指定客户选择器

sy 19 ore fa
parent
commit
65ab618a21

+ 7 - 38
web-scaffold/src/components/OrganizationAccountDialog.tsx

@@ -8,7 +8,7 @@ import { ACCT_STATUS, ACTIVATION_STATUS, label } from "../lib/api/labels";
 export type AccountTarget =
   | { kind: "operator" | "partner" | "operations-member" | "maintenance-lead" | "maintenance-member"; id: string };
 
-type FeedbackArea = "access" | "phone" | "password" | "status";
+type FeedbackArea = "access" | "password" | "status";
 
 function subject(data: OrganizationData, target: AccountTarget) {
   if (target.kind === "operator") {
@@ -52,7 +52,10 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
   const data = useOrganizationSnapshot();
   const current = subject(data, target);
   const [login, setLogin] = useState(current?.account.login ?? "");
-  const [phone, setPhone] = useState(current?.account.phone ?? "");
+  const [phone, setPhone] = useState(() => {
+    const saved = current?.account.phone ?? "";
+    return target.kind === "partner" && saved.includes("*") ? "" : saved;
+  });
   const [busy, setBusy] = useState(false);
   const [feedback, setFeedback] = useState<{ area: FeedbackArea; message: string; error?: boolean } | null>(null);
   const [activation, setActivation] = useState<{ code: string | null; expire: string | null } | null>(null);
@@ -82,12 +85,9 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
     }
   };
   if (!current) return null;
-  const account = current;
   const opened = Boolean(current.account.login);
   const provisionPlan = provisionPlanOf(target);
   const userId = current.account.userId;
-  /** 手机号改绑只有合伙人有可用写接口;其余主体 ⛔ 对应入参。 */
-  const canEditPhone = target.kind === "partner";
   const title = `账号设置 · ${current.label}`;
   /** 已激活账号**不支持重置激活码**(U-03/`KLT-A003`)⇒ 不展示重置卡片,⛔ 让用户点了才被后端拦。 */
   const activated = current.account.activationStatus === "activated";
@@ -121,24 +121,6 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
     }
   }
 
-  /** 改绑手机号:仅合伙人有写接口;成功后整包刷新。 */
-  async function savePhone(event: FormEvent<HTMLFormElement>) {
-    event.preventDefault();
-    if (busy || !canEditPhone || target.kind !== "partner") return;
-    const nextPhone = phone.trim();
-    const problem = checkPhone(nextPhone);
-    if (problem) { report("phone", problem, true); return; }
-    setBusy(true);
-    try {
-      await bos.partnerUpdate({ partner_id: target.id, name: account.label, mobile: nextPhone });
-      await reloadOrganizationData();
-      report("phone", nextPhone ? "手机号已提交改绑。" : "手机号已提交解绑,后续使用登录名登录。");
-    } catch (e) {
-      report("phone", (e as Error)?.message || "手机号改绑失败", true);
-    } finally {
-      setBusy(false);
-    }
-  }
 
   /** 重置:后端只有 `account/reset_code`(仅未激活账号可重置),⛔ 管理员设定密码。 */
   async function resetCode(event: FormEvent<HTMLFormElement>) {
@@ -175,7 +157,7 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
     setBusy(true);
     try {
       // 启停态写 `bos_user_binding.status`,契约只认 `active`/`disabled`(⛔ UI 展示态「正常」≠ 入参 `normal`)。
-      const res = await bos.accountUpdateStatus({ user_id: userId, status: account.account.account === "停用" ? "active" : "disabled" });
+      const res = await bos.accountUpdateStatus({ user_id: userId, status: stopped ? "active" : "disabled" });
       await reloadOrganizationData();
       setConfirmation(null);
       report("status", `后端回状态:${res?.status ? label(ACCT_STATUS, res.status) : FIELD_UNAVAILABLE}。`);
@@ -284,19 +266,6 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
                 )}
                 <section className="org-account-access" aria-labelledby="org-access-status-title">
                   <h3 id="org-access-status-title">访问管理</h3>
-                  {canEditPhone && (
-                    <div className="org-account-setting-row">
-                      <div><strong>登录手机号</strong></div>
-                      <form className="org-account-phone-form" onSubmit={savePhone}>
-                        <label className="org-field">
-                          <span className="sr-only">绑定手机号</span>
-                          <input inputMode="tel" maxLength={11} disabled={busy} onChange={(event) => setPhone(event.target.value)} placeholder="未绑定则只能用登录名" value={phone} />
-                        </label>
-                        <button className="org-button org-button-quiet" disabled={busy} type="submit">保存手机号</button>
-                      </form>
-                      {message("phone")}
-                    </div>
-                  )}
                   <div className="org-account-setting-row">
                     <div>
                       <strong>登录权限</strong>
@@ -314,7 +283,7 @@ export function OrganizationAccountDialog({ target, onClose }: { target: Account
                   <div className="org-account-setting-row">
                     <div>
                       <strong>账号绑定</strong>
-                      <p>撤销当前登录账号的绑定,保留运营商档案。</p>
+                      <p>撤销当前登录账号的绑定,保留主体档案。</p>
                     </div>
                     <button
                       className="org-button org-button-quiet org-account-danger-action"

+ 88 - 0
web-scaffold/src/components/PartnerCustomerPicker.tsx

@@ -0,0 +1,88 @@
+import { useEffect, useState } from "react";
+import { Plus, Search, X } from "lucide-react";
+import { customerGetList, rowsOf } from "../lib/api/bos";
+import { useLoad } from "../lib/useLoad";
+import { SearchInput } from "./ui/search-input";
+
+export function PartnerCustomerPicker({ selectedIds, blockedIds, onChange, disabled }: {
+  selectedIds: string[];
+  blockedIds: ReadonlySet<string>;
+  onChange: (ids: string[]) => void;
+  disabled: boolean;
+}) {
+  const [search, setSearch] = useState("");
+  const [knownNames, setKnownNames] = useState(new Map<string, string>());
+  const keyword = search.trim();
+  const results = useLoad(async () => {
+    const list = await customerGetList({ page: 0, page_size: 20, keyword: keyword || undefined });
+    return {
+      keyword,
+      customers: rowsOf(list).map((row) => ({ id: row.customer_id, name: row.customer_name || row.customer_id })),
+    };
+  }, [keyword]);
+
+  useEffect(() => {
+    const matches = results.data?.customers;
+    if (!matches?.length) return;
+    setKnownNames((current) => {
+      const next = new Map(current);
+      for (const { id, name } of matches) next.set(id, name);
+      return next;
+    });
+  }, [results.data]);
+
+  const matches = results.data?.keyword === keyword ? results.data.customers : [];
+  const loading = results.loading || (!results.error && results.data?.keyword !== keyword);
+
+  return (
+    <section className="partner-customer-picker" aria-label="指定客户">
+      <h3>指定客户</h3>
+      <div className="partner-customer-picker-grid">
+        <div className="partner-customer-pane">
+          <h4>可选客户</h4>
+          <label className="partner-customer-search">
+            <Search size={15} aria-hidden="true" />
+            <SearchInput aria-label="搜索客户" placeholder="输入客户名称或主体号" value={search} onCommit={setSearch} />
+          </label>
+          {loading ? <p className="partner-customer-feedback" role="status">正在查找客户…</p> : results.error ? (
+            <div className="partner-customer-feedback" role="alert">
+              <p>{results.error.message || "客户搜索失败。"}</p>
+              <button className="org-inline-link" type="button" onClick={results.reload}>重试</button>
+            </div>
+          ) : matches.length ? (
+            <ul className="partner-customer-list">
+              {matches.map(({ id, name }) => {
+                const selected = selectedIds.includes(id);
+                const blocked = blockedIds.has(id);
+                return (
+                  <li key={id}>
+                    <div className="partner-customer-label"><span title={name}>{name}</span>{name !== id && <small title={id}>{id}</small>}</div>
+                    {selected || blocked ? <span className="partner-customer-status">{selected ? "已选" : "其他合伙人已选"}</span> : (
+                      <button className="partner-customer-icon" aria-label={`添加 ${name}`} title="添加" disabled={disabled} onClick={() => onChange([...selectedIds, id])} type="button"><Plus size={16} /></button>
+                    )}
+                  </li>
+                );
+              })}
+            </ul>
+          ) : <p className="partner-customer-feedback" role="status">{keyword ? "未找到匹配的客户。" : "暂无可选客户。"}</p>}
+        </div>
+        <div className="partner-customer-pane">
+          <h4>已选客户 <span aria-live="polite">{selectedIds.length}</span></h4>
+          {selectedIds.length ? (
+            <ul className="partner-customer-list">
+              {selectedIds.map((id) => {
+                const name = knownNames.get(id) ?? id;
+                return (
+                  <li key={id}>
+                    <div className="partner-customer-label"><span title={name}>{name}</span>{name !== id && <small title={id}>{id}</small>}</div>
+                    <button className="partner-customer-icon is-remove" aria-label={`移除 ${name}`} title="移除" disabled={disabled} onClick={() => onChange(selectedIds.filter((selected) => selected !== id))} type="button"><X size={15} /></button>
+                  </li>
+                );
+              })}
+            </ul>
+          ) : <p className="partner-customer-feedback">还没有指定客户。</p>}
+        </div>
+      </div>
+    </section>
+  );
+}

+ 11 - 55
web-scaffold/src/pages/OrganizationPages.tsx

@@ -16,7 +16,7 @@ import { TreeSelect } from "../components/ui/tree-select";
 import { regionLevelText, regionParentInTree, regionTreeNodes } from "../lib/region-tree";
 import { markPeerOccupiedTreeNodes, peerOccupiedRegionIds, regionAncestorChain } from "../lib/region-ownership";
 import { OrganizationAccountDialog, type AccountTarget } from "../components/OrganizationAccountDialog";
-import { OrganizationAccountInline } from "../components/OrganizationAccountInline";
+import { PartnerCustomerPicker } from "../components/PartnerCustomerPicker";
 import { OrganizationAccountStatus } from "../components/OrganizationAccountStatus";
 import { MaintenanceAccounts, OperationsAccounts } from "../components/OrganizationTeamAccounts";
 import {
@@ -177,13 +177,9 @@ function OrgEditor({ editor, onClose, onSaved }: { editor: Editor; onClose: () =
     return editor.parent ?? data.regions[0]?.id ?? "";
   });
   const [username, setUsername] = useState("");
-  // 编辑回填:列表手机号已脱敏(`139****0002`)⇒ 留空表示「不改」;⛔ 把脱敏串当写入值上行。
   const [mobile, setMobile] = useState(() => {
-    if (!(existing && "phone" in existing) || editor.id === undefined) {
-      return existing && "phone" in existing ? ((existing as { phone?: string }).phone ?? "") : "";
-    }
-    const raw = ((existing as { phone?: string }).phone ?? "").trim();
-    return raw.includes("*") ? "" : raw;
+    const phone = editor.kind === "partner" ? (existing as Partner | undefined)?.phone ?? "" : "";
+    return /^\d{11}$/.test(phone) ? phone : "";
   });
   const [busy, setBusy] = useState(false);
   const [confirmDispatch, setConfirmDispatch] = useState(false);
@@ -214,27 +210,6 @@ function OrgEditor({ editor, onClose, onSaved }: { editor: Editor; onClose: () =
   const [scope, setScope] = useState<Scope>("scope" in (existing ?? {}) ? structuredClone((existing as { scope: Scope }).scope) : editor.parent && editor.kind !== "region" ? { regions: [editor.parent], enterprises: [] } : freshScope());
   /** 合伙人「指定客户」:存客户主体号(⛔ 全量 enterprises 下标)。 */
   const [pickedCustomerIds, setPickedCustomerIds] = useState<string[]>(() => (existing as Partner | undefined)?.scopeCustomerIds ?? []);
-  const [customerSearch, setCustomerSearch] = useState("");
-  const [customerHits, setCustomerHits] = useState<{ id: string; name: string }[]>([]);
-  const [customerSearchBusy, setCustomerSearchBusy] = useState(false);
-  useEffect(() => {
-    if (editor.kind !== "partner") return;
-    let alive = true;
-    const handle = window.setTimeout(() => {
-      setCustomerSearchBusy(true);
-      void bos.customerGetList({ page: 0, page_size: 20, keyword: customerSearch.trim() || undefined })
-        .then((res) => {
-          if (!alive) return;
-          setCustomerHits((res.items ?? []).map((row) => ({
-            id: row.customer_id,
-            name: row.customer_name || row.customer_id,
-          })));
-        })
-        .catch(() => { if (alive) setCustomerHits([]); })
-        .finally(() => { if (alive) setCustomerSearchBusy(false); });
-    }, 280);
-    return () => { alive = false; window.clearTimeout(handle); };
-  }, [editor.kind, customerSearch]);
   /** 负责范围旁嵌套「新建区域」:挂靠上级(空=平台树根=建省)。 */
   const [regionCreateParent, setRegionCreateParent] = useState("");
   const [regionModal, setRegionModal] = useState<RegionModal | null>(null);
@@ -307,12 +282,9 @@ function OrgEditor({ editor, onClose, onSaved }: { editor: Editor; onClose: () =
         else await bos.operatorCreate({ name: trimmed, brand, region_node_id: region, is_province_node: true, settle_mode: settleMode, settle_value: settleValue, recon_day: reconDay ? Number(reconDay) : null, pay_cycle: payCycle || null });
       } else if (editor.kind === "partner") {
         if (editor.id) {
-          // 脱敏串/非法手机号一律不携带 mobile(留空=不改);合法 11 位才上行。
           const nextMobile = mobile.trim();
-          const mobilePayload = !nextMobile ? undefined
-            : /^1[3-9]\d{9}$/.test(nextMobile) ? nextMobile
-              : (() => { throw new Error("请输入 11 位中国大陆手机号,或留空表示不改"); })();
-          await bos.partnerUpdate({ partner_id: editor.id, name: trimmed, duty_desc: title.trim(), region_node_id: region, ...(mobilePayload !== undefined ? { mobile: mobilePayload } : {}), settle_mode: settleMode, settle_value: settleValue });
+          if (nextMobile && !/^1[3-9]\d{9}$/.test(nextMobile)) throw new Error("请输入 11 位中国大陆手机号,或留空表示不改");
+          await bos.partnerUpdate({ partner_id: editor.id, name: trimmed, duty_desc: title.trim(), region_node_id: region, ...(nextMobile ? { mobile: nextMobile } : {}), settle_mode: settleMode, settle_value: settleValue });
           // 负责范围并入本弹窗:区域用 scope;指定客户用主体号清单(⛔ 全量 enterprises 下标)。
           const prevCustomerIds = (existing as Partner | undefined)?.scopeCustomerIds ?? [];
           const customersChanged = prevCustomerIds.length !== customerIds.length
@@ -472,31 +444,13 @@ function OrgEditor({ editor, onClose, onSaved }: { editor: Editor; onClose: () =
       {editor.kind === "operator" && <label className="org-field"><span>付款周期</span><select className="org-select" onChange={(e) => setPayCycle(e.target.value)} value={payCycle}><option value="">未配置</option>{payCycleOptions.map((value) => <option key={value} value={value}>{value}</option>)}</select></label>}
       {editor.kind === "partner" && <label className={editor.id ? "org-field" : "org-field org-editor-wide"}><span>渠道说明</span><input onChange={(e) => setTitle(e.target.value)} value={title} /></label>}
       {editor.kind === "partner" && !editor.id && <><label className="org-field"><span>登录名 <em>*</em></span><input autoComplete="off" maxLength={64} onChange={(e) => setUsername(e.target.value)} value={username} /></label><label className="org-field"><span>手机号</span><input autoComplete="off" maxLength={20} onChange={(e) => setMobile(e.target.value)} value={mobile} /></label><p className="org-helper">后端创建合伙人时会同步创建其登录账号,登录名为必填;账号密码由后端以激活码下发。</p></>}
-      {editor.kind === "partner" && editor.id && <label className="org-field"><span>手机号 <small>留空则不改(不上传该字段)</small></span><input autoComplete="off" inputMode="tel" maxLength={11} onChange={(e) => setMobile(e.target.value)} placeholder="列表为脱敏值,请重新输入完整手机号;清空号码请联系总运营" value={mobile} /></label>}
-      {/* 合伙人账号并入「编辑合伙人」(2026-11-16 业主指示),沿用档案字段风格;手机号仍由上方档案字段维护。 */}
-      {editor.kind === "partner" && editor.id && existing && <OrganizationAccountInline account={existing as Partner} mobile={mobile} provision={{ role_code: "partner", subject_type: "partner", subject_id: editor.id }} />}
+      {editor.kind === "partner" && editor.id && <label className="org-field"><span>手机号 <small>留空则不改</small></span><input autoComplete="off" inputMode="tel" maxLength={11} onChange={(e) => setMobile(e.target.value)} placeholder="输入完整手机号" value={mobile} /></label>}
       {editor.kind === "partner" && <p className="org-helper">通知地址:后端合伙人档案未下发该字段,本页不提供录入。</p>}
       {editor.kind === "maintenance" && <><label className="org-field org-maintenance-mode-field"><span>分派方式</span><select className="org-select" onChange={(e) => setMode(e.target.value as MaintenanceTeam["mode"])} value={mode}><option>手工</option><option>自动平均</option></select></label><div className="org-field org-ticket-types-field"><span>可分配工单类型 <em>*</em></span><MultiTreeSelect nodes={maintenanceTicketOptions} values={ticketTypes} onChange={setTicketTypes} label="可分配工单类型" placeholder="选择工单类型,可多选" searchPlaceholder="搜索工单类型" /></div></>}
       {/* 「指定客户」2026-11-16 起运维团队侧**暂时隐去**(业主指示):保存时透传档案原值,⛔ 表单未展示却改写。 */}
       {hasScope && <fieldset className="org-scope-editor org-scope-dropdowns"><legend>负责范围</legend>
         <div className="org-field"><span>负责区域</span><MultiTreeSelect nodes={scopeRegionNodes} values={scope.regions} onChange={(regions) => setScope(current => ({ ...current, regions }))} label="负责区域" placeholder="选择负责区域,可多选" searchPlaceholder="搜索区域名称或路径" /></div>
-        {editor.kind === "partner" && <div className="org-field"><span>指定客户</span>
-          <div className="org-customer-picker">
-            {pickedCustomerIds.length ? <div className="org-check-grid">{pickedCustomerIds.map((id) => {
-              const hit = customerHits.find((item) => item.id === id);
-              const label = hit?.name ?? id;
-              return <label key={id}><input type="checkbox" checked onChange={() => setPickedCustomerIds((current) => current.filter((item) => item !== id))} />{label}<small>{id}</small></label>;
-            })}</div> : <p className="org-helper">未指定客户;可按名称/主体号搜索后勾选(⛔ 全量客户清单)。</p>}
-            <input aria-label="搜索客户" placeholder="搜索客户名称或主体号" value={customerSearch} onChange={(event) => setCustomerSearch(event.target.value)} />
-            <div className="org-check-grid">{customerSearchBusy && !customerHits.length ? <p className="org-helper">搜索中…</p> : null}
-              {customerHits.filter((item) => !pickedCustomerIds.includes(item.id)).slice(0, 20).map((item) => {
-                const blocked = peerPickedCustomerIds.has(item.id);
-                return <label key={item.id}><input type="checkbox" disabled={blocked} checked={false} onChange={() => { if (!blocked) setPickedCustomerIds((current) => [...current, item.id]); }} />{item.name}<small>{blocked ? "已被其他合伙人占用" : item.id}</small></label>;
-              })}
-              {!customerSearchBusy && customerSearch.trim() && !customerHits.length ? <p className="org-helper">无匹配客户</p> : null}
-            </div>
-          </div>
-        </div>}
+        {editor.kind === "partner" && <PartnerCustomerPicker selectedIds={pickedCustomerIds} blockedIds={peerPickedCustomerIds} onChange={setPickedCustomerIds} disabled={busy} />}
         {editor.kind === "operations" && (() => {
           const walk = (nodes: typeof scopeRegionNodes): boolean => nodes.every((n) => Boolean(n.disabled) && (!n.children?.length || walk(n.children)));
           const allOccupied = scopeRegionNodes.length > 0 && walk(scopeRegionNodes);
@@ -1208,8 +1162,7 @@ export function PartnerManagementPage() {
   const data = useOrganizationData(["regions", "partners"]);
   useOrganizationDemand(["enterprises"]);
   const tableOverflow = useHorizontalOverflow();
-  // 2026-11-16 业主指示:合伙人操作列只有「编辑」「删除」两项,直接平铺,⛔ 收进「更多」菜单。
-  const minimumWidths = [122, 108, 110, 84, 96, 150, 88, 132];
+  const minimumWidths = [122, 108, 110, 84, 96, 150, 88, 186];
   const minimumTableWidth = minimumWidths.reduce((sum, width) => sum + width, 0);
   const extraWidth = Math.max(0, tableOverflow.width - minimumTableWidth);
   const extraShares = [.22, .18, .17, .07, .10, .26, 0, 0];
@@ -1222,6 +1175,7 @@ export function PartnerManagementPage() {
   const saveNotice = useSaveNotice();
   const [selected, setSelected] = useState<string | null>(data.partners[0]?.id ?? null);
   const [deleteId, setDeleteId] = useState<string | null>(null);
+  const [accountTarget, setAccountTarget] = useState<AccountTarget | null>(null);
   const status = useOrganizationStatus();
   const filtered = data.partners.filter((p) => (!region || descendants(data, region).includes(p.region)) && `${p.name} ${p.title} ${p.notify}`.toLowerCase().includes(query.trim().toLowerCase()));
   type PtSort = "name" | "region" | "coverage";
@@ -1305,6 +1259,7 @@ export function PartnerManagementPage() {
                   <td className="org-directory-customer-count"><Count v={p.coverageCustomers} /></td>
                   <td className="org-table-actions-cell">
                     <div className="org-table-actions is-icons">
+                      <button className="is-account" aria-haspopup="dialog" onClick={(event) => { event.stopPropagation(); setSelected(p.id); setAccountTarget({ kind: "partner", id: p.id }); }} type="button"><UserRound size={15} />账号</button>
                       <OpsResponsiveActions expanded items={[
                         { label: "编辑合伙人", shortLabel: "编辑", icon: <PencilLine size={15} />, onSelect: () => { setSelected(p.id); setEditor({ kind: "partner", id: p.id }); } },
                         { label: "删除合伙人", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, onSelect: () => { setSelected(p.id); setDeleteId(p.id); } },
@@ -1321,6 +1276,7 @@ export function PartnerManagementPage() {
       <ListPager total={rows.length} page={paging.safePage} pageSize={paging.pageSize} onPageChange={paging.setPage} onPageSizeChange={paging.setPageSize} unit="位" className="org-list-pager" />
     </section></div>
     {saveNotice.node}{editor && <OrgEditor key={editor.id ?? "new"} editor={editor} onClose={() => setEditor(null)} onSaved={saveNotice.show} />}
+    {accountTarget && <OrganizationAccountDialog target={accountTarget} onClose={() => setAccountTarget(null)} />}
     {deleteId && <DeleteDialog data={data} id={deleteId} kind="partner" name={data.partners.find((p) => p.id === deleteId)?.name ?? ""} onClose={() => setDeleteId(null)} onDeleted={() => setSelected(null)} />}
   </div>;
 }

+ 74 - 0
web-scaffold/src/pages/__tests__/partner-management.test.tsx

@@ -0,0 +1,74 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { afterEach, expect, it, vi } from "vitest";
+import type { OrganizationData, Partner } from "../../lib/organization-demo";
+import { PartnerManagementPage } from "../OrganizationPages";
+
+const { saveScope } = vi.hoisted(() => ({ saveScope: vi.fn(async () => ({})) }));
+vi.mock("../../auth/session", () => ({ useSession: () => ({ ctx: { role_code: "admin" } }) }));
+vi.mock("../../lib/use-horizontal-overflow", () => ({ useHorizontalOverflow: () => ({ ref: null, width: 1160 }) }));
+vi.mock("../../lib/api/bos", async (load) => ({
+  ...await load<typeof import("../../lib/api/bos")>(),
+  partnerUpdate: async () => ({}),
+  partnerScopeSave: saveScope,
+  customerGetList: async ({ keyword }: { keyword?: string }) => ({
+    items: keyword ? [{ customer_id: "CUSTOMER-B", customer_name: "客户乙" }] : [
+      { customer_id: "CUSTOMER-A", customer_name: "客户甲" },
+      { customer_id: "BLOCKED", customer_name: "已被分配的客户" },
+    ],
+  }),
+}));
+vi.mock("../../lib/organization-demo", async (load) => {
+  const partner: Partner = {
+    id: "PARTNER", name: "浙江渠道合伙人", region: "PROVINCE", title: "", notify: "",
+    account: "在用", login: "zhejiang-channel", userId: "USER-1", shareMode: "按比例", shareValue: 0.08,
+    scope: { regions: ["PROVINCE"], enterprises: [] }, scopeCustomerIds: ["LEGACY"],
+  };
+  const data: OrganizationData = {
+    regions: [{ id: "PROVINCE", name: "浙江省", level: 0, parent: null }],
+    operators: [], operationsTeams: [], maintenanceTeams: [], enterprises: [],
+    partners: [partner, { ...partner, id: "OTHER", name: "其他渠道", scopeCustomerIds: ["BLOCKED"] }],
+  };
+  return {
+    ...await load<typeof import("../../lib/organization-demo")>(),
+    useOrganizationData: () => data,
+    useOrganizationSnapshot: () => data,
+    useOrganizationStatus: () => ({ loading: false, partial: {} }),
+    useOrganizationDemand: () => {},
+    reloadOrganizationData: async () => {},
+  };
+});
+
+afterEach(cleanup);
+
+it("账号从列表独立打开,指定客户跨搜索保留并按主体号保存", async () => {
+  render(<MemoryRouter><PartnerManagementPage /></MemoryRouter>);
+  const row = screen.getByRole("row", { name: /浙江渠道合伙人档案/ });
+
+  fireEvent.click(within(row).getByRole("button", { name: "账号" }));
+  const account = screen.getByRole("dialog", { name: "账号设置 · 浙江渠道合伙人" });
+  expect(within(account).getByText("zhejiang-channel")).toBeTruthy();
+  fireEvent.keyDown(account, { key: "Escape" });
+
+  fireEvent.click(within(row).getByRole("button", { name: "编辑" }));
+  const edit = screen.getByRole("dialog", { name: "编辑合伙人" });
+  expect(within(edit).queryByRole("button", { name: "重置激活码" })).toBeNull();
+  expect(within(edit).getByRole("button", { name: "移除 LEGACY" })).toBeTruthy();
+  fireEvent.click(await within(edit).findByRole("button", { name: "添加 客户甲" }));
+  expect(within(edit).getByText("其他合伙人已选")).toBeTruthy();
+  expect(within(edit).queryByRole("button", { name: "添加 已被分配的客户" })).toBeNull();
+
+  const search = within(edit).getByRole("textbox", { name: "搜索客户" });
+  fireEvent.change(search, { target: { value: "客户乙" } });
+  fireEvent.keyDown(search, { key: "Enter" });
+  await within(edit).findByRole("button", { name: "添加 客户乙" });
+  expect(within(edit).getByRole("button", { name: "移除 客户甲" })).toBeTruthy();
+  fireEvent.click(within(edit).getByRole("button", { name: "移除 LEGACY" }));
+  fireEvent.click(within(edit).getByRole("button", { name: "保存档案" }));
+
+  await waitFor(() => expect(saveScope).toHaveBeenCalledWith({
+    partner_id: "PARTNER",
+    region_node_ids: ["PROVINCE"],
+    customer_ids: ["CUSTOMER-A"],
+  }));
+});

+ 25 - 4
web-scaffold/src/styles/organization.css

@@ -498,7 +498,6 @@
 .org-account-access > h3 { padding-block: 11px; }
 .org-account-setting-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px 13px; padding: 11px 0; border-top: 1px solid var(--border-subtle); }
 .org-account-setting-row strong { color: var(--foreground); font-size: var(--type-body); font-weight: 600; }
-.org-account-setting-row > .org-account-phone-form { display: flex; flex-direction: row; align-items: center; gap: 8px; }
 .org-account-settings .org-button { min-height: 34px; padding: 5px 11px; font-size: var(--type-support); font-weight: 600; }
 .org-account-settings .org-account-danger-action { color: var(--destructive); }
 .org-account-settings .org-account-danger-action:hover:not(:disabled) { background: var(--destructive-soft); border-color: var(--destructive-border); }
@@ -522,8 +521,6 @@
   .org-account-settings .org-account-fields { grid-template-columns: minmax(0, 1fr); }
   .org-account-activation { grid-template-columns: auto minmax(0, 1fr); }
   .org-account-activation > form { grid-column: 2; justify-self: start; }
-  .org-account-setting-row > .org-account-phone-form { grid-column: 1 / -1; }
-  .org-account-phone-form > .org-field { flex: 1; }
 }
 .org-inline-link{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;color:var(--primary);font-size:var(--type-support);font-weight:700;cursor:pointer}
 .org-inline-link:hover{text-decoration:underline}
@@ -703,10 +700,34 @@ a.org-overview-card{text-decoration:none;color:inherit}
 .org-editor-modal .org-dialog-content.org-editor-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:10px 16px}
 .org-editor-form-grid>.org-scope-editor,
 .org-editor-form-grid>.org-form-error{grid-column:1/-1}
-.org-centered-backdrop .org-editor-form-grid > :is(.org-helper, .org-account-inline, .org-editor-wide) { grid-column: 1 / -1; }
+.org-centered-backdrop .org-editor-form-grid > :is(.org-helper, .org-editor-wide) { grid-column: 1 / -1; }
 .org-editor-form-grid .org-scope-dropdowns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 18px}
 .org-editor-form-grid .org-scope-dropdowns>legend{grid-column:1/-1}
 .org-editor-form-grid .org-scope-dropdowns>.org-field+.org-field{margin-top:0}
+.org-editor-form-grid .org-scope-dropdowns:has(> .partner-customer-picker) { grid-template-columns: minmax(0, 1fr); gap: 14px; }
+.partner-customer-picker h3 { margin: 0 0 8px; color: var(--field-label); font-size: var(--type-body); font-weight: 500; }
+.partner-customer-picker-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
+.partner-customer-pane { min-width: 0; border: 1px solid var(--border); border-radius: 8px; background: var(--card); }
+.partner-customer-pane h4 { display: flex; align-items: center; justify-content: space-between; margin: 0; padding: 8px 11px; border-bottom: 1px solid var(--border-subtle); background: var(--surface-subtle); border-radius: 8px 8px 0 0; color: var(--foreground); font-size: var(--type-support); font-weight: 600; }
+.partner-customer-pane h4 span { color: var(--primary); font-variant-numeric: tabular-nums; }
+.partner-customer-search { display: flex; align-items: center; gap: 6px; margin: 8px 10px 4px; color: var(--muted-foreground); }
+.partner-customer-search svg { flex: none; }
+.partner-customer-search input { min-width: 0; }
+.partner-customer-list { max-height: 184px; overflow: auto; margin: 0; padding: 0 10px; list-style: none; scrollbar-gutter: stable; }
+.partner-customer-list li { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 42px; padding: 5px 0; }
+.partner-customer-list li + li { border-top: 1px solid var(--border-subtle); }
+.partner-customer-label { min-width: 0; font-size: var(--type-support); color: var(--foreground); }
+.partner-customer-label :is(span, small) { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.partner-customer-label small, .partner-customer-status { color: var(--muted-foreground); font-size: var(--type-meta); }
+.partner-customer-status { flex: none; }
+.partner-customer-icon { display: grid; place-items: center; flex: none; width: 28px; height: 28px; border: 0; border-radius: 6px; background: var(--primary-soft); color: var(--primary); cursor: pointer; }
+.partner-customer-icon.is-remove { background: var(--surface-subtle); color: var(--text-secondary); }
+.partner-customer-icon:hover:not(:disabled) { background: var(--primary-border); }
+.partner-customer-icon.is-remove:hover:not(:disabled) { background: var(--destructive-soft); color: var(--destructive); }
+.partner-customer-icon:disabled { opacity: .5; cursor: not-allowed; }
+.partner-customer-feedback { padding: 8px 11px; color: var(--muted-foreground); font-size: var(--type-support); overflow-wrap: anywhere; }
+.partner-customer-feedback[role="alert"] p { margin: 0 0 4px; color: var(--destructive); }
+@media (max-width: 560px) { .partner-customer-picker-grid { grid-template-columns: minmax(0, 1fr); } }
 @media(max-width:600px){.org-editor-modal .org-dialog-content.org-editor-form-grid,.org-editor-form-grid .org-scope-dropdowns{grid-template-columns:minmax(0,1fr)}.org-editor-form-grid .org-scope-dropdowns{row-gap:14px}}
 
 .org-dialog.org-region-editor-modal{width:min(100%,720px)}