import { useEffect, useMemo, useState } from "react"; import { useAuth } from "../components/auth/AuthProvider"; import { isSystemAdminForCategoryScope } from "../lib/categoryScopeAccess"; import { getTeamMemberById } from "../services/teamMemberService"; /** * 新增/编辑表单的门店范围:系统管理员手选公司;其它角色使用账号绑定的公司 Id。 */ export function useCategoryScopeAuth() { const auth = useAuth(); const requireCompanySelection = useMemo( () => isSystemAdminForCategoryScope({ roleCodes: auth.roleCodes, permissionCodes: auth.permissionCodes, userName: auth.user?.userName, }), [auth.roleCodes, auth.permissionCodes, auth.user?.userName], ); const [fixedPartnerId, setFixedPartnerId] = useState(""); const [loadingPartner, setLoadingPartner] = useState(false); useEffect(() => { if (requireCompanySelection) { setFixedPartnerId(""); setLoadingPartner(false); return; } const uid = (auth.user?.id ?? "").trim(); if (!uid) { setFixedPartnerId(""); return; } let cancelled = false; setLoadingPartner(true); (async () => { try { const detail = await getTeamMemberById(uid); if (cancelled) return; const pid = String(detail.partnerId ?? detail.partnerIds?.[0] ?? "").trim(); setFixedPartnerId(pid); } catch { if (!cancelled) setFixedPartnerId(""); } finally { if (!cancelled) setLoadingPartner(false); } })(); return () => { cancelled = true; }; }, [requireCompanySelection, auth.user?.id]); return { requireCompanySelection, fixedPartnerId, loadingPartner, }; }