1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
7 * BUCK: retailmax.elink.stats.today
8 * Essential dashboard statistics (26 uses)
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);
22 // Optional location filter
23 const locationId = searchParams.get('locationId');
25 // Build BUCK parameters
26 const params: string[] = [
27 '3=retailmax.elink.stats.today'
30 // Add location filter if specified
32 params.push(`9=f131,0,${locationId}`);
35 const query = params.join('&');
36 const url = `/GNAP/j/buck?${query}`;
38 console.log('[Stats Today] BUCK query:', url);
40 const result = await fieldpineServerApi.apiCall(url, {
41 cookie: authData.apiKey,
45 // Process BUCK response
46 if (result && result.DATS && Array.isArray(result.DATS)) {
47 // Usually returns a single record with today's stats
48 const stats = result.DATS[0] || {};
52 totalSales: stats.f210 || 0,
53 totalRevenue: stats.f211 || 0,
54 totalCost: stats.f212 || 0,
55 grossProfit: stats.f213 || 0,
56 grossMargin: stats.f214 || 0,
58 // Transaction metrics
59 transactionCount: stats.f220 || 0,
60 averageTransaction: stats.f221 || 0,
61 itemsPerTransaction: stats.f222 || 0,
64 customersToday: stats.f300 || 0,
65 newCustomers: stats.f301 || 0,
66 returningCustomers: stats.f302 || 0,
69 cashSales: stats.f250 || 0,
70 cardSales: stats.f251 || 0,
71 creditSales: stats.f252 || 0,
74 taxCollected: stats.f230 || 0,
75 discountGiven: stats.f231 || 0,
77 // Comparison to yesterday
78 yesterdayRevenue: stats.f400 || 0,
79 revenueChange: stats.f401 || 0,
80 revenueChangePercent: stats.f402 || 0,
83 firstSaleTime: stats.f500 || null,
84 lastSaleTime: stats.f501 || null,
85 busyHour: stats.f502 || null,
88 locationId: stats.f131 || null,
89 locationName: stats.f132 || null,
92 generatedAt: new Date().toISOString()
95 // Calculate some derived metrics
96 if (todayStats.yesterdayRevenue > 0) {
97 todayStats.revenueChangePercent =
98 ((todayStats.totalRevenue - todayStats.yesterdayRevenue) / todayStats.yesterdayRevenue) * 100;
101 return NextResponse.json({
108 // Return empty stats if no data
109 return NextResponse.json({
116 generatedAt: new Date().toISOString()
122 console.error('[Stats Today] Error:', error);
123 return NextResponse.json(
124 { error: 'Failed to fetch today\'s statistics' },