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

@ -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,
};
}