1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
7 * BUCK: retailmax.elink.sale.totals.group
8 * Returns sales aggregated by product, supplier, or department
10export async function GET(request: NextRequest) {
12 const authData = await getStoredAuth();
13 if (!authData || !authData.authenticated) {
14 return NextResponse.json(
15 { error: 'Authentication required' },
20 const { searchParams } = new URL(request.url);
23 const startDate = searchParams.get('startDate');
24 const endDate = searchParams.get('endDate');
25 const limit = searchParams.get('limit') || '100';
27 // Grouping: product, supplier, department, location, teller
28 const groupBy = searchParams.get('groupBy') || 'product';
30 // Build BUCK parameters
31 const params: string[] = [
32 '3=retailmax.elink.sale.totals.group',
38 params.push(`9=f102,4,${startDate}`);
41 params.push(`9=f102,1,${endDate}`);
47 params.push('15=200'); // Group by product (f200)
50 params.push('15=220'); // Group by supplier (f220)
53 params.push('15=133'); // Group by department (f133)
56 params.push('15=131'); // Group by location (f131)
59 params.push('15=140'); // Group by teller (f140)
63 const query = params.join('&');
64 const url = `/GNAP/j/buck?${query}`;
66 console.log('[Sales Grouped] BUCK query:', url);
68 const result = await fieldpineServerApi.apiCall(url, {
69 cookie: authData.apiKey,
73 // Process BUCK response
74 if (result && result.DATS && Array.isArray(result.DATS)) {
75 const grouped = result.DATS.map((item: any) => ({
78 totalSales: item.f210,
79 totalUnits: item.f211,
80 totalRevenue: item.f212,
82 grossProfit: item.f214,
83 grossMargin: item.f215,
84 transactionCount: item.f220
87 return NextResponse.json({
90 count: grouped.length,
96 return NextResponse.json({
105 console.error('[Sales Grouped] Error:', error);
106 return NextResponse.json(
107 { error: 'Failed to fetch grouped sales' },