feat(project): base smatec's frontend

This commit is contained in:
Tran Anh Tuan
2026-01-21 11:48:57 +07:00
commit 5c2a909bed
138 changed files with 43666 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
import { InitialStateResponse } from '@/app';
import { LIMIT_TREE_LEVEL } from '@/constants';
import { apiQueryGroups } from '@/services/master/GroupController';
import { useModel } from '@umijs/max';
import { useCallback, useEffect, useRef, useState } from 'react';
type UseGetGroupsResult = {
groups: MasterModel.GroupNode[] | null;
groupMap: GroupMap;
loading: boolean;
getGroups: () => Promise<void>;
};
type GroupMap = Record<string, { name: string; code?: string }>;
function buildGroupMap(
groups: MasterModel.GroupNode[],
map: GroupMap = {},
): GroupMap {
groups.forEach((g) => {
map[g.id] = {
name: g.name,
code: g.metadata?.code,
};
if (g.children?.length) {
buildGroupMap(g.children, map);
}
});
return map;
}
export default function useGetGroups(): UseGetGroupsResult {
const [groups, setGroups] = useState<MasterModel.GroupNode[] | null>(null);
const [groupMap, setGroupMap] = useState<GroupMap>({});
const [loading, setLoading] = useState(false);
const { initialState } = useModel('@@initialState') as {
initialState?: InitialStateResponse;
};
const currentUserProfile = initialState?.currentUserProfile;
/**
* ✅ FIX CACHE
* Khi user đổi (logout / login user khác)
* → clear groups cũ
*/
const prevUserIdRef = useRef<string | null>(null);
useEffect(() => {
const currentUserId = currentUserProfile?.id ?? null;
if (prevUserIdRef.current && prevUserIdRef.current !== currentUserId) {
// user đổi → clear cache
setGroups(null);
}
prevUserIdRef.current = currentUserId;
}, [currentUserProfile?.id]);
/**
* ✅ GIỮ NGUYÊN LOGIC CŨ
* chỉ thêm guard + dependency đúng
**/
const getGroups = useCallback(async (): Promise<void> => {
if (!currentUserProfile?.id) return;
setLoading(true);
try {
const tree = await apiQueryGroups({
level: LIMIT_TREE_LEVEL,
tree: true,
});
setGroups(tree?.groups || []);
setGroupMap(buildGroupMap(tree?.groups || []));
} catch (err) {
console.error('Fetch data failed', err);
setGroups([]);
} finally {
setLoading(false);
}
}, [currentUserProfile]);
return {
groups,
groupMap,
loading,
getGroups,
};
}