1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getRequestContext } from '@/lib/server/sessionUtils';
6 * GET /api/v1/elink/sales/flat
7 * Fetch flattened sales list with line items, customer, and product details
9 * - startDate: Start date filter (YYYY-MM-DD)
10 * - endDate: End date filter (YYYY-MM-DD)
11 * - limit: Max number of records (default 200)
12 * - includeCustomer: Include customer details (default true)
13 * - includeProduct: Include product details (default true)
15export async function GET(request: NextRequest) {
17 const context = await getRequestContext(request);
18 if (!context?.session) {
19 return NextResponse.json(
20 { success: false, error: 'Not authenticated' },
25 const { searchParams } = new URL(request.url);
26 const startDate = searchParams.get('startDate');
27 const endDate = searchParams.get('endDate');
28 const limit = searchParams.get('limit') || '200';
29 const includeCustomer = searchParams.get('includeCustomer') !== 'false';
30 const includeProduct = searchParams.get('includeProduct') !== 'false';
32 console.log('[Sales Flat] Fetching flat sales list:', {
40 // Build BUCK parameters for retailmax.elink.saleflat.list
41 const buckParams: Record<string, string> = {
42 '3': 'retailmax.elink.saleflat.list',
44 '103': includeCustomer ? '1' : '0', // Include customer details
45 '104': includeProduct ? '1' : '0', // Include product details
46 // Field list: sale date, location name, sale ID, total, tax, payment method, product, qty, line total
47 '10': '102,106,101,107,104,201,202,203,301'
50 // Add date filters if provided
52 buckParams['9'] = `f102,4,${startDate}`; // >= start date
55 buckParams['9.1'] = `f102,1,${endDate}`; // <= end date
58 console.log('[Sales Flat] BUCK params:', buckParams);
60 const result = await fieldpineServerApi.buckApiCall(buckParams, context.session.apiKey);
62 if (!result || !result.APPT) {
63 return NextResponse.json({
66 message: 'No sales found for the specified period'
70 console.log(`[Sales Flat] Successfully fetched ${result.APPT.length} line items`);
72 return NextResponse.json({
75 count: result.APPT.length
79 console.error('[Sales Flat] Error:', error);
81 // Check if it's a 403 error
82 if (error instanceof Error && error.message.includes('403')) {
83 return NextResponse.json(
86 error: 'Authentication expired. Please log in again.'
92 return NextResponse.json(
95 error: error instanceof Error ? error.message : 'Failed to fetch sales data'