1import { NextRequest, NextResponse } from 'next/server';
2import { FieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getRequestContext, validateApiAccess, getStoreApiUrl } from '@/lib/server/sessionUtils';
6 * Sales Detail Report (Line-by-Line)
7 * ELINK: retailmax.elink.saleflat.list
8 * Returns detailed line items for all sales transactions
10export async function GET(request: NextRequest) {
12 // Get session context
13 const context = await getRequestContext(request);
14 if (!context || !context.isAuthenticated) {
15 return NextResponse.json(
16 { error: 'Authentication required' },
21 // Validate ELINK access
22 if (!validateApiAccess(context, 'elink')) {
23 return NextResponse.json(
24 { error: 'ELINK access not permitted for this store type' },
29 const { searchParams } = new URL(request.url);
32 const startDate = searchParams.get('startDate'); // YYYY-MM-DD
33 const endDate = searchParams.get('endDate'); // YYYY-MM-DD
34 const limit = searchParams.get('limit') || '200';
37 const locationId = searchParams.get('locationId');
40 const departmentId = searchParams.get('departmentId');
42 // Create store-specific API instance
43 const storeApiUrl = getStoreApiUrl(context, 'elink');
44 const api = new FieldpineServerApi(storeApiUrl, context.session.apiKey);
46 console.log('[Sales Detail] Calling ELINK: retailmax.elink.saleflat.list');
48 // Build BUCK parameters
49 const buckParams: Record<string, string | string[]> = {
50 "3": "retailmax.elink.saleflat.list",
51 "8": limit, // Limit records
52 "103": "1", // Include product details
53 "104": "1" // Include customer details
56 // Add date and other filters
57 const filters: string[] = [];
59 filters.push(`f102,4,${startDate}`); // Start date (f102 = sale date)
62 filters.push(`f102,1,${endDate}`); // End date
65 filters.push(`f131,2,${locationId}`); // f131 = location
68 filters.push(`f133,2,${departmentId}`); // f133 = department
70 if (filters.length > 0) {
71 buckParams["9"] = filters;
74 const result = await api.buckApiCall(buckParams, context.session.apiKey);
76 // Process BUCK response
77 if (result && result.DATS && Array.isArray(result.DATS)) {
78 const sales = result.DATS.map((item: any) => ({
82 productName: item.f201,
87 locationId: item.f131,
88 locationName: item.f132,
89 departmentId: item.f133,
90 departmentName: item.f134,
92 tellerName: item.f141,
93 customerId: item.f300,
94 customerName: item.f301,
95 paymentType: item.f250,
100 return NextResponse.json({
108 return NextResponse.json({
116 console.error('[Sales Detail] Error:', error);
117 return NextResponse.json(
118 { error: 'Failed to fetch sales detail' },