From 5ddd4cf37d63507e6de93d09a3874ac5d072e414 Mon Sep 17 00:00:00 2001 From: Rafhan Mazaya Fathurrahman Date: Thu, 2 Jul 2026 15:57:46 +0700 Subject: [PATCH] feat: default manual label form to previous automated parser results --- .../src/app/api/manual-label/route.ts | 72 +++++++++++++++---- 1 file changed, 58 insertions(+), 14 deletions(-) diff --git a/backend/pfm-web-app/src/app/api/manual-label/route.ts b/backend/pfm-web-app/src/app/api/manual-label/route.ts index 1594a59..4fec4e2 100644 --- a/backend/pfm-web-app/src/app/api/manual-label/route.ts +++ b/backend/pfm-web-app/src/app/api/manual-label/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; +import { query } from "../../../db"; import fs from "fs"; import path from "path"; @@ -24,21 +25,64 @@ export async function GET(req: NextRequest) { if (fs.existsSync(filePath)) { const fileData = fs.readFileSync(filePath, "utf8"); return NextResponse.json(JSON.parse(fileData)); - } else { - // Return empty default state if not found - return NextResponse.json({ - filename, - noPO: "", - noSO: "", - noDO: "", - tanggal: "", - customer: "", - store: "", - alamat: "", - plat: "", - items: [] - }); } + + // Try fallback to automated parser results in database + try { + const safeFilename = path.basename(filename); + const docRes = await query( + "SELECT id, metadata FROM documents WHERE filename = $1", + [safeFilename] + ); + + if (docRes.rowCount && docRes.rowCount > 0) { + const doc = docRes.rows[0]; + const docId = doc.id; + const meta = doc.metadata || {}; + + // Fetch ocr items + const itemsRes = await query( + "SELECT kode_barang, nama_barang, banyak, jumlah FROM ocr_items WHERE document_id = $1 ORDER BY row_index", + [docId] + ); + + const items = itemsRes.rows.map(row => ({ + kodeBarang: row.kode_barang || "", + namaBarang: row.nama_barang || "", + banyak: row.banyak || "", + jumlah: row.jumlah || "" + })); + + return NextResponse.json({ + filename, + noPO: meta.noPO || "", + noSO: meta.noSO || "", + noDO: meta.noDO || "", + tanggal: meta.tanggal || "", + customer: meta.customerInfo || "", + store: meta.orderUntuk || "", + alamat: meta.alamat || "", + plat: meta.platTruk || "", + items + }); + } + } catch (dbErr) { + console.error("DB fallback failed inside manual-label GET:", dbErr); + } + + // Return empty default state if not found anywhere + return NextResponse.json({ + filename, + noPO: "", + noSO: "", + noDO: "", + tanggal: "", + customer: "", + store: "", + alamat: "", + plat: "", + items: [] + }); } catch (err: any) { console.error("Error in GET manual-label:", err); return NextResponse.json({ error: err.message || "Failed to load manual label" }, { status: 500 });