1import { NextRequest, NextResponse } from "next/server";
2import { fieldpineServerApi } from "@/lib/server/fieldpineApi";
3import { getStoredAuth } from "@/lib/server/auth";
5// GET: Look up product by barcode
6export async function GET(request: NextRequest) {
8 const authData = await getStoredAuth();
10 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
13 const { searchParams } = new URL(request.url);
14 const barcode = searchParams.get("barcode");
17 return NextResponse.json(
18 { success: false, error: "Barcode parameter is required" },
23 // Look up product by barcode
24 const result = await fieldpineServerApi.buckApiCall({
25 "3": "retailmax.elink.products",
27 "9": `f501,0,${barcode}`
30 return NextResponse.json({
35 } catch (error: any) {
36 console.error("Error looking up product:", error);
37 return NextResponse.json(
38 { success: false, error: error.message || "Failed to look up product" },
39 { status: error.status || 500 }
44// POST: Record stocktake count
45export async function POST(request: NextRequest) {
47 const authData = await getStoredAuth();
49 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
52 const body = await request.json();
53 const { productId, quantity, barcode, storeId, reference } = body;
55 if (!productId || !quantity || !barcode) {
56 return NextResponse.json(
57 { success: false, error: "Missing required fields: productId, quantity, barcode" },
62 // Build DATI XML for stocktake count
63 const escapeXml = (v: string) =>
64 v.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
68 "<f8>retailmax.elink.stocktake.count</f8>",
71 "<f110_E>2</f110_E>", // scanner type
72 `<f118_E>${productId}</f118_E>`,
73 `<f111_E>${quantity}</f111_E>`,
74 `<f120_s>${escapeXml(barcode)}</f120_s>`,
75 storeId && storeId !== "0" ? `<f121_E>${storeId}</f121_E>` : "",
76 reference ? `<f124_s>${escapeXml(reference)}</f124_s>` : "",
80 // POST DATI XML to BUCK endpoint
81 const url = `${process.env.FIELDPINE_BASE_URL || "https://iig.cwanz.online"}/GNAP/j/buck`;
82 const headers: Record<string, string> = {
83 'Accept': 'application/json',
84 'Content-Type': 'text/xml',
85 'Cookie': `FieldpineApiKey=${authData.apiKey}`
88 const response = await fetch(url, {
95 throw new Error(`Stocktake count failed: ${response.status} ${response.statusText}`);
98 const result = await response.json();
100 return NextResponse.json({
105 } catch (error: any) {
106 console.error("Error recording stocktake:", error);
107 return NextResponse.json(
108 { success: false, error: error.message || "Failed to record stocktake" },
109 { status: error.status || 500 }