1import { NextRequest, NextResponse } from "next/server";
2import { fieldpineServerApi } from "@/lib/server/fieldpineApi";
3import { getRequestContext } from "@/lib/server/sessionUtils";
5export async function POST(request: NextRequest) {
7 const context = await getRequestContext(request);
8 if (!context || !context.isAuthenticated || !context.session.apiKey) {
9 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
12 const body = await request.json();
13 console.log('[Locations API POST] Saving location:', body);
15 // Build DATI XML for location
16 const fields: Record<string, any> = {};
18 if (body.id) fields['100'] = body.id;
19 if (body.name) fields['101'] = body.name;
20 if (body.latitude !== undefined) fields['102'] = body.latitude;
21 if (body.longitude !== undefined) fields['103'] = body.longitude;
22 if (body.phone) fields['150'] = body.phone;
23 if (body.email) fields['151'] = body.email;
24 if (body.storeType) fields['164'] = body.storeType;
27 let datiXml = '<DATI>';
28 for (const [fieldNum, value] of Object.entries(fields)) {
29 datiXml += `<f${fieldNum}>${value}</f${fieldNum}>`;
33 console.log('[Locations API POST] DATI XML:', datiXml);
35 const result = await fieldpineServerApi.buckApiCall(
37 "3": "retailmax.elink.locations.save",
40 context.session.apiKey!,
44 return NextResponse.json({
48 } catch (error: any) {
49 console.error("[Locations API POST] Error:", error);
50 return NextResponse.json(
51 { success: false, error: error.message || "Failed to save location" },
52 { status: error.status || 500 }
57export async function GET(request: NextRequest) {
59 const context = await getRequestContext(request);
60 if (!context || !context.isAuthenticated || !context.session.apiKey) {
61 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
64 console.log('[Locations API] Making BUCK call for locations');
65 console.log('[Locations API] Auth:', { hasApiKey: !!context.session.apiKey });
67 // Use BUCK API with correct field set
68 const result = await fieldpineServerApi.buckApiCall({
69 "3": "retailmax.elink.locations",
70 "10": "100-160,164,185,186"
71 }, context.session.apiKey!, context.store.url);
73 console.log('[Locations API] BUCK result:', {
74 hasDats: !!result.DATS,
75 datsLength: result.DATS?.length,
76 resultKeys: Object.keys(result)
79 // Return DATS array directly for franchise report compatibility
80 const locations = result.DATS || [];
82 return NextResponse.json(locations);
83 } catch (error: any) {
84 console.error("[Locations API] Error:", error);
85 console.error("[Locations API] Error stack:", error.stack);
86 return NextResponse.json(
87 { success: false, error: error.message || "Failed to fetch locations" },
88 { status: error.status || 500 }