1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getRequestContext } from '@/lib/server/sessionUtils';
6 * Top Products by Sales
7 * ELINK: retailmax.elink.sale.totals.group (grouped by product)
8 * Returns top selling products by revenue
10export async function GET(request: NextRequest) {
12 const context = await getRequestContext(request);
13 if (!context?.session) {
14 return NextResponse.json(
15 { error: 'Authentication required' },
20 const { searchParams } = new URL(request.url);
21 const startDate = searchParams.get('startDate');
22 const endDate = searchParams.get('endDate');
23 const location = searchParams.get('location');
25 // Build BUCK request parameters for grouped product sales
26 const buckParams: Record<string, string> = {
27 "3": "retailmax.elink.sale.totals.group",
28 "10": "11000", // Quartile stats
29 "15": "2,1,pid", // Group by product ID
30 "13": "120", // Sort by sales amount
31 "8": "1000" // Limit to 1000 results
34 // Add date filters if provided
36 buckParams["9"] = `f110,4,${startDate}`;
39 // Add as second date filter
40 const key = startDate ? "9.1" : "9";
41 buckParams[key] = `f110,1,${endDate}`;
44 // Add location filter if provided
45 if (location && location !== '0') {
46 buckParams["7"] = location;
49 const data = await fieldpineServerApi.buckApiCall(buckParams, context.session.apiKey);
51 return NextResponse.json(data);
52 } catch (error: any) {
53 console.error('Error fetching top products:', error);
54 return NextResponse.json(
55 { error: error.message || 'Failed to fetch top products' },