|
1 | 1 | import { useAuthStore } from "@features/auth/stores/authStore"; |
2 | 2 | import { useQuery } from "@tanstack/react-query"; |
| 3 | +import { useMemo } from "react"; |
3 | 4 |
|
4 | 5 | export interface ProjectInfo { |
5 | 6 | id: number; |
@@ -36,27 +37,52 @@ export function useProjects() { |
36 | 37 | const client = useAuthStore((s) => s.client); |
37 | 38 | const currentProjectId = useAuthStore((s) => s.projectId); |
38 | 39 |
|
39 | | - const query = useQuery({ |
40 | | - queryKey: ["projects", availableProjectIds], |
41 | | - queryFn: async () => { |
42 | | - if (!client || availableProjectIds.length === 0) { |
43 | | - return []; |
44 | | - } |
45 | | - return client.getProjectDetails(availableProjectIds); |
46 | | - }, |
47 | | - enabled: !!client && availableProjectIds.length > 0, |
48 | | - staleTime: 5 * 60 * 1000, // Cache for 5 minutes |
| 40 | + const { |
| 41 | + data: currentUser, |
| 42 | + isLoading, |
| 43 | + error, |
| 44 | + } = useQuery({ |
| 45 | + queryKey: ["currentUser"], |
| 46 | + queryFn: () => client?.getCurrentUser(), |
| 47 | + enabled: !!client, |
| 48 | + staleTime: 5 * 60 * 1000, |
49 | 49 | }); |
50 | 50 |
|
51 | | - const currentProject = query.data?.find((p) => p.id === currentProjectId); |
52 | | - const groupedProjects = query.data ? groupProjectsByOrg(query.data) : []; |
| 51 | + const projects = useMemo(() => { |
| 52 | + if (!currentUser?.organization) return []; |
| 53 | + |
| 54 | + const teams = (currentUser.organization.teams ?? []) as Array<{ |
| 55 | + id: number; |
| 56 | + name?: string; |
| 57 | + }>; |
| 58 | + const orgName = currentUser.organization.name ?? "Unknown Organization"; |
| 59 | + const orgId = currentUser.organization.id ?? ""; |
| 60 | + |
| 61 | + const teamMap = new Map(teams.map((t) => [t.id, t])); |
| 62 | + |
| 63 | + return availableProjectIds |
| 64 | + .map((id) => { |
| 65 | + const team = teamMap.get(id); |
| 66 | + if (!team) return null; |
| 67 | + return { |
| 68 | + id, |
| 69 | + name: team.name ?? `Project ${id}`, |
| 70 | + organization: { id: orgId, name: orgName }, |
| 71 | + }; |
| 72 | + }) |
| 73 | + .filter((p): p is ProjectInfo => p !== null); |
| 74 | + }, [currentUser, availableProjectIds]); |
| 75 | + |
| 76 | + const currentProject = projects.find((p) => p.id === currentProjectId); |
| 77 | + const groupedProjects = groupProjectsByOrg(projects); |
53 | 78 |
|
54 | 79 | return { |
55 | | - projects: query.data ?? [], |
| 80 | + projects, |
56 | 81 | groupedProjects, |
57 | 82 | currentProject, |
58 | 83 | currentProjectId, |
59 | | - isLoading: query.isLoading, |
60 | | - error: query.error, |
| 84 | + currentUser: currentUser ?? null, |
| 85 | + isLoading, |
| 86 | + error, |
61 | 87 | }; |
62 | 88 | } |
0 commit comments