operation-cycle / teamtasker /src /hooks /use-weekly-reports.ts
o134's picture
Upload full TeamTasker system with all fixes
8314cf4 verified
Raw
History Blame Contribute Delete
2.67 kB
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
export interface WeeklyReport {
id: number;
clientId: number;
fileName: string;
fileUrl: string;
fileSize: number;
mimeType: string;
uploadedByUserId: number;
createdAt: string;
}
function getAuthHeaders(): HeadersInit {
const token = localStorage.getItem("teamtasker_token");
return token ? { Authorization: `Bearer ${token}` } : {};
}
async function apiFetch<T>(url: string, options: RequestInit = {}): Promise<T> {
const res = await fetch(url, {
...options,
headers: {
...getAuthHeaders(),
...options.headers,
},
});
if (!res.ok) {
const errorData = await res.json().catch(() => ({}));
throw new Error(errorData.error || `Request failed: ${res.status}`);
}
return res.json() as Promise<T>;
}
export function useGetWeeklyReports(clientId: number) {
return useQuery({
queryKey: ["weeklyReports", clientId],
queryFn: () => apiFetch<WeeklyReport[]>(`/api/clients/${clientId}/weekly-reports`),
enabled: !!clientId,
});
}
export function useCreateWeeklyReport(clientId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (file: File) => {
const formData = new FormData();
formData.append("file", file);
formData.append("report", file);
const token = localStorage.getItem("teamtasker_token");
const res = await fetch(`/api/clients/${clientId}/weekly-reports`, {
method: "POST",
body: formData,
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
if (!res.ok) {
const errorData = await res.json().catch(() => ({}));
throw new Error(errorData.error || "Failed to upload report");
}
return res.json() as Promise<WeeklyReport>;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["weeklyReports", clientId] });
},
});
}
export function useDeleteWeeklyReport(clientId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (reportId: number) =>
apiFetch(`/api/clients/${clientId}/weekly-reports/${reportId}`, { method: "DELETE" }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["weeklyReports", clientId] });
},
});
}
export function useDownloadWeeklyReport(clientId: number) {
return useMutation({
mutationFn: async (reportId: number) => {
const data = await apiFetch<{ signedUrl: string }>(
`/api/clients/${clientId}/weekly-reports/${reportId}/download`
);
return data.signedUrl;
},
});
}