1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
6 * Account Customers Endpoint
7 * Gets customers linked to an account
9export async function GET(request: NextRequest) {
11 // Verify authentication
12 const authData = await getStoredAuth();
13 if (!authData || !authData.authenticated) {
14 return NextResponse.json(
15 { success: false, error: 'Authentication required' },
20 const { searchParams } = new URL(request.url);
21 const accountId = searchParams.get('accountId');
24 return NextResponse.json(
25 { success: false, error: 'Account ID required' },
32 "3": "retailmax.elink.customers",
33 "9": `f132,0,${accountId}`
36 const response = await fieldpineServerApi.buckApiCall(buckParams, authData.apiKey);
38 if (response?.DATS && Array.isArray(response.DATS)) {
39 return NextResponse.json({
45 return NextResponse.json({
53 console.error('Account customers error:', error);
54 return NextResponse.json(
55 { success: false, error: 'Failed to fetch customers', source: 'elink' },
61 console.error('Customers API error:', error);
62 return NextResponse.json(
63 { success: false, error: 'Failed to fetch customers' },
69export async function POST(request: NextRequest) {
71 // Verify authentication
72 const authData = await getStoredAuth();
73 if (!authData || !authData.authenticated) {
74 return NextResponse.json(
75 { success: false, error: 'Authentication required' },
80 const body = await request.json();
81 const { action, customerId, accountId } = body;
84 let xml = '<DATI><f8_s>retailmax.elink.customers.edit</f8_s>';
86 if (action === 'link') {
87 xml += `<f100>${customerId}</f100><f132>${accountId}</f132>`;
88 } else if (action === 'unlink') {
89 xml += `<f100>${customerId}</f100><f132>0</f132>`;
94 // POST DATI XML to BUCK endpoint
95 const url = `${process.env.FIELDPINE_BASE_URL || "https://iig.cwanz.online"}/GNAP/j/buck`;
96 const headers: Record<string, string> = {
97 'Accept': 'application/json',
98 'Content-Type': 'text/xml',
99 'Cookie': `FieldpineApiKey=${authData.apiKey}`
102 const apiResponse = await fetch(url, {
108 if (!apiResponse.ok) {
109 throw new Error(`Customer update failed: ${apiResponse.status} ${apiResponse.statusText}`);
112 const responseData = await apiResponse.json();
114 return NextResponse.json({
121 console.error('Customer link/unlink error:', error);
122 return NextResponse.json(
123 { success: false, error: 'Failed to update customer link', source: 'elink' },
129 console.error('Customers API error:', error);
130 return NextResponse.json(
131 { success: false, error: 'Failed to process request' },