EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
route.ts
Go to the documentation of this file.
1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
4
5export async function GET(request: NextRequest) {
6 try {
7 const authData = await getStoredAuth();
8 if (!authData || !authData.authenticated) {
9 return NextResponse.json(
10 { error: 'Authentication required' },
11 { status: 401 }
12 );
13 }
14
15 const clientId = request.headers.get('x-forwarded-for') ||
16 request.headers.get('x-real-ip') ||
17 authData.userId ||
18 'unknown';
19 if (!fieldpineServerApi.checkClientRateLimit(clientId)) {
20 return NextResponse.json(
21 { error: 'Rate limit exceeded' },
22 { status: 429 }
23 );
24 }
25
26 const { searchParams } = new URL(request.url);
27 const staffId = searchParams.get('id');
28 const includeRights = searchParams.get('includeRights') === 'true';
29
30 try {
31 let buckParams: Record<string, string> = {
32 "3": "retailmax.elink.staff.list",
33 "10": "121-137,107,143", // Extended fields
34 };
35
36 if (staffId) {
37 buckParams["9"] = `f100,0,${staffId}`;
38 }
39
40 if (includeRights) {
41 buckParams["7"] = "203"; // Include rights
42 }
43
44 const staff = await fieldpineServerApi.buckApiCall(buckParams, authData.apiKey);
45
46 return NextResponse.json({
47 success: true,
48 data: staff,
49 source: 'elink'
50 });
51
52 } catch (error) {
53 console.error('eLink staff error:', error);
54 return NextResponse.json(
55 { error: 'eLink endpoint unavailable', source: 'elink' },
56 { status: 503 }
57 );
58 }
59
60 } catch (error) {
61 console.error('eLink staff error:', error);
62 return NextResponse.json(
63 { error: 'Failed to fetch staff' },
64 { status: 500 }
65 );
66 }
67}
68
69export async function POST(request: NextRequest) {
70 try {
71 const authData = await getStoredAuth();
72 if (!authData || !authData.authenticated) {
73 return NextResponse.json(
74 { error: 'Authentication required' },
75 { status: 401 }
76 );
77 }
78
79 const body = await request.json();
80
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
85 };
86
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();
109
110 // Build XML
111 const xmlLines = ['<DATI>'];
112 for (const [key, value] of Object.entries(datiFields)) {
113 xmlLines.push(` <${key}>${escapeXml(value as string)}</${key}>`);
114 }
115
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>`);
120 });
121 }
122
123 xmlLines.push('</DATI>');
124 const xml = xmlLines.join('\n');
125
126 console.log('Creating/Updating staff with XML:', xml);
127
128 const response = await fieldpineServerApi.datiApiCall(xml, authData.apiKey);
129
130 if (response.success) {
131 return NextResponse.json({
132 success: true,
133 data: response.data,
134 message: body.id ? 'Staff updated successfully' : 'Staff created successfully',
135 });
136 } else {
137 return NextResponse.json(
138 { success: false, error: response.error || 'Operation failed' },
139 { status: 500 }
140 );
141 }
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' },
146 { status: 500 }
147 );
148 }
149}
150
151function escapeXml(str: string): string {
152 if (!str) return '';
153 return str
154 .replace(/&/g, '&amp;')
155 .replace(/</g, '&lt;')
156 .replace(/>/g, '&gt;')
157 .replace(/"/g, '&quot;')
158 .replace(/'/g, '&apos;');
159}