79 lines
2.2 KiB
TypeScript
79 lines
2.2 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
|
|
import { getCurrentUserId, pb } from '@/services/pocketbase';
|
|
import type { TacheExpanded, TacheRecord } from '@/types/collections';
|
|
|
|
export type TacheCreateInput = {
|
|
titre: string;
|
|
description?: string;
|
|
date_echeance?: string;
|
|
bien?: string;
|
|
type_tache?: string;
|
|
priorite?: number;
|
|
is_urgent?: boolean;
|
|
statut?: string;
|
|
};
|
|
|
|
export function useTachesList() {
|
|
const uid = getCurrentUserId();
|
|
const queryClient = useQueryClient();
|
|
|
|
const query = useQuery({
|
|
queryKey: ['taches_list', uid],
|
|
queryFn: async () => {
|
|
if (!uid) return [] as TacheExpanded[];
|
|
return pb.collection('taches').getFullList<TacheExpanded>({
|
|
filter: `user="${uid}"`,
|
|
sort: '-id',
|
|
expand: 'bien',
|
|
});
|
|
},
|
|
enabled: Boolean(uid),
|
|
});
|
|
|
|
const invalidate = () => {
|
|
void queryClient.invalidateQueries({ queryKey: ['taches_list', uid] });
|
|
};
|
|
|
|
const createTache = useMutation({
|
|
mutationFn: async (input: TacheCreateInput) => {
|
|
if (!uid) throw new Error('Utilisateur non connecté');
|
|
return pb.collection('taches').create<TacheRecord>({
|
|
user: uid,
|
|
titre: input.titre,
|
|
description: input.description,
|
|
date_echeance: input.date_echeance,
|
|
bien: input.bien || undefined,
|
|
type_tache: input.type_tache ?? 'autre',
|
|
priorite: input.priorite ?? 2,
|
|
is_urgent: input.is_urgent ?? false,
|
|
statut: input.statut ?? 'a_faire',
|
|
});
|
|
},
|
|
onSuccess: invalidate,
|
|
});
|
|
|
|
const updateTache = useMutation({
|
|
mutationFn: async ({ id, patch }: { id: string; patch: Partial<TacheRecord> }) => {
|
|
return pb.collection('taches').update<TacheRecord>(id, patch);
|
|
},
|
|
onSuccess: invalidate,
|
|
});
|
|
|
|
const deleteTache = useMutation({
|
|
mutationFn: async (id: string) => pb.collection('taches').delete(id),
|
|
onSuccess: invalidate,
|
|
});
|
|
|
|
return {
|
|
taches: query.data ?? [],
|
|
isLoading: query.isPending,
|
|
error: query.error,
|
|
refetch: query.refetch,
|
|
createTache: createTache.mutateAsync,
|
|
updateTache: updateTache.mutateAsync,
|
|
deleteTache: deleteTache.mutateAsync,
|
|
isCreatePending: createTache.isPending,
|
|
};
|
|
}
|