feat: default manual label form to previous automated parser results

This commit is contained in:
Rafhan Mazaya Fathurrahman committed 2026-07-02 15:57:46 +07:00
1 parent ab21d1ca5d
commit 5ddd4cf37d
1 file changed
+47 -3
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "../../../db";
import fs from "fs";
import path from "path";
@@ -24,8 +25,52 @@ 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
}
// 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: "",
@@ -38,7 +83,6 @@ export async function GET(req: NextRequest) {
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 });