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 { getRequestContext } from '@/lib/server/sessionUtils';
4
5/**
6 * Top Products by Sales
7 * ELINK: retailmax.elink.sale.totals.group (grouped by product)
8 * Returns top selling products by revenue
9 */
10export async function GET(request: NextRequest) {
11 try {
12 const context = await getRequestContext(request);
13 if (!context?.session) {
14 return NextResponse.json(
15 { error: 'Authentication required' },
16 { status: 401 }
17 );
18 }
19
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');
24
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
32 };
33
34 // Add date filters if provided
35 if (startDate) {
36 buckParams["9"] = `f110,4,${startDate}`;
37 }
38 if (endDate) {
39 // Add as second date filter
40 const key = startDate ? "9.1" : "9";
41 buckParams[key] = `f110,1,${endDate}`;
42 }
43
44 // Add location filter if provided
45 if (location && location !== '0') {
46 buckParams["7"] = location;
47 }
48
49 const data = await fieldpineServerApi.buckApiCall(buckParams, context.session.apiKey);
50
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' },
56 { status: 500 }
57 );
58 }
59}