Files
mdb/app/hooks/useGrillePrix.ts
Bastien COIGNOUX 2b8741de08 recherche
2026-05-04 21:52:51 +02:00

80 lines
2.4 KiB
TypeScript

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { marginPctFromPrices } from '@/constants/rechercheMarche';
import { getCurrentUserId, pb } from '@/services/pocketbase';
import type { GrillePrixEtat, GrillePrixRecord, GrillePrixTypeBien } from '@/types/collections';
export type GrillePrixInput = {
type_bien: GrillePrixTypeBien;
etat: GrillePrixEtat;
prix_achat_m2: number;
prix_revente_m2: number;
ville?: string;
};
function withMargin(input: GrillePrixInput): Record<string, unknown> {
const marge = marginPctFromPrices(input.prix_achat_m2, input.prix_revente_m2);
return {
type_bien: input.type_bien,
etat: input.etat,
prix_achat_m2: input.prix_achat_m2,
prix_revente_m2: input.prix_revente_m2,
ville: input.ville?.trim() || undefined,
marge_estimee_pct: marge != null ? Math.round(marge * 100) / 100 : undefined,
};
}
export function useGrillePrix() {
const uid = getCurrentUserId();
const queryClient = useQueryClient();
const query = useQuery({
queryKey: ['grille_prix', uid],
queryFn: async () => {
if (!uid) return [] as GrillePrixRecord[];
return pb.collection('grille_prix').getFullList<GrillePrixRecord>({
filter: `user="${uid}"`,
sort: '-updated',
});
},
enabled: Boolean(uid),
});
const invalidate = () => {
void queryClient.invalidateQueries({ queryKey: ['grille_prix', uid] });
};
const createRow = useMutation({
mutationFn: async (input: GrillePrixInput) => {
if (!uid) throw new Error('Non connecté');
return pb.collection('grille_prix').create<GrillePrixRecord>({
user: uid,
...withMargin(input),
});
},
onSuccess: invalidate,
});
const updateRow = useMutation({
mutationFn: async ({ id, input }: { id: string; input: GrillePrixInput }) => {
return pb.collection('grille_prix').update<GrillePrixRecord>(id, withMargin(input));
},
onSuccess: invalidate,
});
const deleteRow = useMutation({
mutationFn: async (id: string) => pb.collection('grille_prix').delete(id),
onSuccess: invalidate,
});
return {
rows: query.data ?? [],
isLoading: query.isPending,
error: query.error,
createRow: createRow.mutateAsync,
updateRow: updateRow.mutateAsync,
deleteRow: deleteRow.mutateAsync,
isMutating: createRow.isPending || updateRow.isPending || deleteRow.isPending,
};
}