recherche

This commit is contained in:
Bastien COIGNOUX
2026-05-04 21:52:51 +02:00
parent 432f8ce176
commit 2b8741de08
30 changed files with 2317 additions and 246 deletions

View File

@ -16,6 +16,8 @@ export type AnalyseFormInput = {
taxe_fonciere_annuelle?: number;
charges_copropriete_mensuelle?: number;
prix_revente_cible?: number;
/** Prix de revente estimé au m² (marché). */
prix_revente_m2?: number;
frais_agence_vente_pct?: number;
taux_impot?: number;
};
@ -98,6 +100,9 @@ function formToRecord(form: AnalyseFormInput, calc: AnalyseCalculated): Record<s
taxe_fonciere_annuelle: form.taxe_fonciere_annuelle,
charges_copropriete_mensuelle: form.charges_copropriete_mensuelle,
prix_revente_cible: form.prix_revente_cible,
...(form.prix_revente_m2 !== undefined && form.prix_revente_m2 !== null
? { prix_revente_m2: form.prix_revente_m2 }
: {}),
frais_agence_vente_pct: form.frais_agence_vente_pct,
taux_impot: form.taux_impot,
marge_brute: calc.marge_brute,
@ -153,6 +158,30 @@ export function useAnalyse(bienId: string | undefined) {
},
});
const patchMutation = useMutation({
mutationFn: async (patch: { prix_revente_m2?: number | null }) => {
if (!bienId || !uid) throw new Error('Données manquantes');
const res = await pb.collection('analyses_financieres').getList<AnalyseFinanciereRecord>(1, 1, {
filter: `bien="${bienId}" && user="${uid}"`,
sort: '-id',
});
const existing = res.items[0];
if (existing) {
return pb.collection('analyses_financieres').update<AnalyseFinanciereRecord>(existing.id, patch);
}
return pb.collection('analyses_financieres').create<AnalyseFinanciereRecord>({
user: uid,
bien: bienId,
type_bien_fiscal: 'ancien',
...patch,
});
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ['analyse_financiere', bienId, uid] });
void queryClient.invalidateQueries({ queryKey: ['bien_detail', bienId] });
},
});
return {
analyse: query.data ?? null,
isLoading: query.isPending,
@ -161,6 +190,8 @@ export function useAnalyse(bienId: string | undefined) {
fetchAnalyse: query.refetch,
saveAnalyse: saveMutation.mutateAsync,
isSaving: saveMutation.isPending,
patchAnalyse: patchMutation.mutateAsync,
isPatching: patchMutation.isPending,
calculateResults,
};
}

View File

@ -0,0 +1,60 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getCurrentUserId, pb } from '@/services/pocketbase';
import type { AnalyseSecteurRecord } from '@/types/collections';
function escapeFilterValue(s: string): string {
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
export function useAnalyseSecteurForVille(ville: string) {
const uid = getCurrentUserId();
const key = ville.trim().toLowerCase();
return useQuery({
queryKey: ['analyse_secteur', uid, key],
queryFn: async (): Promise<AnalyseSecteurRecord | null> => {
if (!uid || !key) return null;
const esc = escapeFilterValue(ville.trim());
const list = await pb.collection('analyses_secteur').getFullList<AnalyseSecteurRecord>({
filter: `user="${uid}" && ville="${esc}"`,
sort: '-updated',
});
return list[0] ?? null;
},
enabled: Boolean(uid && key),
});
}
export function useSaveAnalyseSecteur() {
const uid = getCurrentUserId();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (payload: { ville: string; notes: string }) => {
if (!uid) throw new Error('Non connecté');
const ville = payload.ville.trim();
if (!ville) throw new Error('Ville requise');
const esc = escapeFilterValue(ville);
const existing = await pb.collection('analyses_secteur').getFullList<AnalyseSecteurRecord>({
filter: `user="${uid}" && ville="${esc}"`,
sort: '-updated',
});
const row = existing[0];
if (row) {
return pb.collection('analyses_secteur').update<AnalyseSecteurRecord>(row.id, {
notes: payload.notes,
});
}
return pb.collection('analyses_secteur').create<AnalyseSecteurRecord>({
user: uid,
ville,
notes: payload.notes,
});
},
onSuccess: (_, v) => {
const key = v.ville.trim().toLowerCase();
void queryClient.invalidateQueries({ queryKey: ['analyse_secteur', uid, key] });
},
});
}

View File

@ -0,0 +1,79 @@
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,
};
}

View File

@ -0,0 +1,90 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { CATEGORIE_NOTES_PROSPECTION } from '@/constants/rechercheMarche';
import { getCurrentUserId, pb } from '@/services/pocketbase';
import type { NoteProspectionRecord } from '@/types/collections';
function escapePb(s: string): string {
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
export type ChecklistPersist = { done: boolean; note: string };
function encodeReponse(data: ChecklistPersist): string {
return JSON.stringify(data);
}
function decodeReponse(raw?: string | null): ChecklistPersist {
if (!raw?.trim()) return { done: false, note: '' };
try {
const v = JSON.parse(raw) as unknown;
if (v && typeof v === 'object' && 'done' in v) {
const o = v as { done?: boolean; note?: string };
return { done: Boolean(o.done), note: typeof o.note === 'string' ? o.note : '' };
}
} catch {
return { done: false, note: raw };
}
return { done: false, note: '' };
}
export function useNotesProspectionRecherche() {
const uid = getCurrentUserId();
const queryClient = useQueryClient();
const query = useQuery({
queryKey: ['notes_prospection', uid, CATEGORIE_NOTES_PROSPECTION],
queryFn: async () => {
if (!uid) return [] as NoteProspectionRecord[];
return pb.collection('notes_prospection').getFullList<NoteProspectionRecord>({
filter: `user="${uid}" && categorie="${CATEGORIE_NOTES_PROSPECTION}"`,
sort: '-id',
});
},
enabled: Boolean(uid),
});
const byQuestionId = (questionId: string): NoteProspectionRecord | undefined =>
query.data?.find((r) => r.question === questionId);
const upsert = useMutation({
mutationFn: async (payload: { questionId: string; data: ChecklistPersist }) => {
if (!uid) throw new Error('Non connecté');
const reponse = encodeReponse(payload.data);
const qe = escapePb(payload.questionId);
const existing = await pb.collection('notes_prospection').getFullList<NoteProspectionRecord>({
filter: `user="${uid}" && categorie="${escapePb(CATEGORIE_NOTES_PROSPECTION)}" && question="${qe}"`,
});
const row = existing[0];
if (row) {
return pb.collection('notes_prospection').update<NoteProspectionRecord>(row.id, {
reponse,
categorie: CATEGORIE_NOTES_PROSPECTION,
});
}
return pb.collection('notes_prospection').create<NoteProspectionRecord>({
user: uid,
question: payload.questionId,
reponse,
categorie: CATEGORIE_NOTES_PROSPECTION,
});
},
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: ['notes_prospection', uid, CATEGORIE_NOTES_PROSPECTION],
});
},
});
return {
rows: query.data ?? [],
isLoading: query.isPending,
error: query.error,
getState(questionId: string): ChecklistPersist {
const row = byQuestionId(questionId);
return decodeReponse(row?.reponse);
},
saveChecklistItem: upsert.mutateAsync,
isSaving: upsert.isPending,
};
}