fix: prevent duplicate document rows on OCR retry

registerLocalDocument always did a plain insert, so retrying a
document whose first OCR attempt failed created a new duplicate
row each time instead of updating the existing one. Now looks up
an existing (case_id, filename) match and updates it in place.
This commit is contained in:
mstfyldz
2026-08-11 11:09:05 +03:00
parent 8065df4ff0
commit 6bd6da3776
+44 -14
View File
@@ -111,21 +111,51 @@ export const registerLocalDocument = async (req: AuthenticatedRequest, res: Resp
const caseId = await findOrCreateCaseByTitle(userId as string, case_title);
const { data: documentRecord, error: docError } = await supabase
// "Yeniden İşle" aynı case_title+filename ile bu uca tekrar tekrar istek
// atabiliyor (OCR ilk seferde boş sonuç döndüğünde) — daha önce burada koşulsuz
// insert vardı, bu yüzden her yeniden deneme aynı belgeyi Belgeler ekranında
// yinelenen bir satır olarak çoğaltıyordu. Var olan kaydı bulup güncelliyoruz,
// sadece hiç kayıt yoksa yeni satır açıyoruz.
const { data: existingDoc, error: existingErr } = await supabase
.from('documents')
.insert([{
case_id: caseId,
user_id: userId,
storage_path: 'local', // ham dosya sadece kullanıcının cihazında; Storage'da bir karşılığı yok
filename,
mime_type: null,
file_size: extracted_text.length,
ocr_status: extracted_text ? 'done' : 'failed',
extracted_text,
}])
.select()
.single();
if (docError) throw docError;
.select('id')
.eq('case_id', caseId)
.eq('filename', filename)
.maybeSingle();
if (existingErr) throw existingErr;
let documentRecord;
if (existingDoc) {
const { data, error: updateErr } = await supabase
.from('documents')
.update({
file_size: extracted_text.length,
ocr_status: extracted_text ? 'done' : 'failed',
extracted_text,
})
.eq('id', existingDoc.id)
.select()
.single();
if (updateErr) throw updateErr;
documentRecord = data;
} else {
const { data, error: docError } = await supabase
.from('documents')
.insert([{
case_id: caseId,
user_id: userId,
storage_path: 'local', // ham dosya sadece kullanıcının cihazında; Storage'da bir karşılığı yok
filename,
mime_type: null,
file_size: extracted_text.length,
ocr_status: extracted_text ? 'done' : 'failed',
extracted_text,
}])
.select()
.single();
if (docError) throw docError;
documentRecord = data;
}
let analysisRecord = null;
if (extracted_text.trim()) {