Blame view

美国版/Food Labeling Management Platform/src/hooks/useCategoryScopeAuth.ts 1.7 KB
91821909   杨鑫   最新
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  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,
    };
  }