1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
5export async function GET(request: NextRequest) {
7 const authData = await getStoredAuth();
8 if (!authData || !authData.authenticated) {
9 return NextResponse.json(
10 { error: 'Authentication required' },
15 const clientId = request.headers.get('x-forwarded-for') ||
16 request.headers.get('x-real-ip') ||
19 if (!fieldpineServerApi.checkClientRateLimit(clientId)) {
20 return NextResponse.json(
21 { error: 'Rate limit exceeded' },
26 const { searchParams } = new URL(request.url);
27 const staffId = searchParams.get('id');
28 const includeRights = searchParams.get('includeRights') === 'true';
31 let buckParams: Record<string, string> = {
32 "3": "retailmax.elink.staff.list",
33 "10": "121-137,107,143", // Extended fields
37 buckParams["9"] = `f100,0,${staffId}`;
41 buckParams["7"] = "203"; // Include rights
44 const staff = await fieldpineServerApi.buckApiCall(buckParams, authData.apiKey);
46 return NextResponse.json({
53 console.error('eLink staff error:', error);
54 return NextResponse.json(
55 { error: 'eLink endpoint unavailable', source: 'elink' },
61 console.error('eLink staff error:', error);
62 return NextResponse.json(
63 { error: 'Failed to fetch staff' },
69export async function POST(request: NextRequest) {
71 const authData = await getStoredAuth();
72 if (!authData || !authData.authenticated) {
73 return NextResponse.json(
74 { error: 'Authentication required' },
79 const body = await request.json();
81 // Build DATI XML for staff creation/update
82 const datiFields: any = {
83 f8_s: 'retailmax.elink.staff.edit',
84 f11_B: body.id ? 'E' : 'I', // Edit or Insert
87 if (body.id) datiFields.f100_s = body.id.toString();
88 if (body.name !== undefined) datiFields.f101_s = body.name;
89 if (body.active !== undefined) datiFields.f102_s = body.active ? '1' : '0';
90 if (body.password !== undefined) datiFields.f103_s = body.password;
91 if (body.barcode !== undefined) datiFields.f107_s = body.barcode;
92 if (body.formalName !== undefined) datiFields.f121_s = body.formalName;
93 if (body.mainLocation !== undefined) datiFields.f122_s = body.mainLocation;
94 if (body.printedName !== undefined) datiFields.f123_s = body.printedName;
95 if (body.firstName !== undefined) datiFields.f124_s = body.firstName;
96 if (body.lastName !== undefined) datiFields.f125_s = body.lastName;
97 if (body.nickName !== undefined) datiFields.f126_s = body.nickName;
98 if (body.startDate !== undefined) datiFields.f127_s = body.startDate;
99 if (body.leaveDate !== undefined) datiFields.f128_s = body.leaveDate;
100 if (body.privateEmail !== undefined) datiFields.f130_s = body.privateEmail;
101 if (body.workEmail !== undefined) datiFields.f131_s = body.workEmail;
102 if (body.onlineLogin !== undefined) datiFields.f133_s = body.onlineLogin;
103 if (body.isCustomerRep !== undefined) datiFields.f134_E = body.isCustomerRep ? '1' : '0';
104 if (body.isAccountRep !== undefined) datiFields.f135_E = body.isAccountRep ? '1' : '0';
105 if (body.remoteProfile !== undefined) datiFields.f136_s = body.remoteProfile.toString();
106 if (body.autoLoginFrom !== undefined) datiFields.f137_s = body.autoLoginFrom;
107 if (body.onlinePassword !== undefined) datiFields.f141_s = body.onlinePassword;
108 if (body.loginWhere !== undefined) datiFields.f143_E = body.loginWhere.toString();
111 const xmlLines = ['<DATI>'];
112 for (const [key, value] of Object.entries(datiFields)) {
113 xmlLines.push(` <${key}>${escapeXml(value as string)}</${key}>`);
116 // Add roles if provided
117 if (body.roles && Array.isArray(body.roles)) {
118 body.roles.forEach((roleId: number) => {
119 xmlLines.push(` <f500_E>${roleId}</f500_E>`);
123 xmlLines.push('</DATI>');
124 const xml = xmlLines.join('\n');
126 console.log('Creating/Updating staff with XML:', xml);
128 const response = await fieldpineServerApi.datiApiCall(xml, authData.apiKey);
130 if (response.success) {
131 return NextResponse.json({
134 message: body.id ? 'Staff updated successfully' : 'Staff created successfully',
137 return NextResponse.json(
138 { success: false, error: response.error || 'Operation failed' },
142 } catch (error: any) {
143 console.error('Error saving staff:', error);
144 return NextResponse.json(
145 { success: false, error: error.message || 'Failed to save staff' },
151function escapeXml(str: string): string {
154 .replace(/&/g, '&')
155 .replace(/</g, '<')
156 .replace(/>/g, '>')
157 .replace(/"/g, '"')
158 .replace(/'/g, ''');