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 { getStoredAuth } from '@/lib/server/auth';
4
5/**
6 * Today's Statistics
7 * BUCK: retailmax.elink.stats.today
8 * Essential dashboard statistics (26 uses)
9 */
10export async function GET(request: NextRequest) {
11 try {
12 const authData = await getStoredAuth();
13 if (!authData || !authData.authenticated) {
14 return NextResponse.json(
15 { error: 'Authentication required' },
16 { status: 401 }
17 );
18 }
19
20 const { searchParams } = new URL(request.url);
21
22 // Optional location filter
23 const locationId = searchParams.get('locationId');
24
25 // Build BUCK parameters
26 const params: string[] = [
27 '3=retailmax.elink.stats.today'
28 ];
29
30 // Add location filter if specified
31 if (locationId) {
32 params.push(`9=f131,0,${locationId}`);
33 }
34
35 const query = params.join('&');
36 const url = `/GNAP/j/buck?${query}`;
37
38 console.log('[Stats Today] BUCK query:', url);
39
40 const result = await fieldpineServerApi.apiCall(url, {
41 cookie: authData.apiKey,
42 useOpenApi: false
43 });
44
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] || {};
49
50 const todayStats = {
51 // Sales metrics
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,
57
58 // Transaction metrics
59 transactionCount: stats.f220 || 0,
60 averageTransaction: stats.f221 || 0,
61 itemsPerTransaction: stats.f222 || 0,
62
63 // Customer metrics
64 customersToday: stats.f300 || 0,
65 newCustomers: stats.f301 || 0,
66 returningCustomers: stats.f302 || 0,
67
68 // Payment metrics
69 cashSales: stats.f250 || 0,
70 cardSales: stats.f251 || 0,
71 creditSales: stats.f252 || 0,
72
73 // Tax and discounts
74 taxCollected: stats.f230 || 0,
75 discountGiven: stats.f231 || 0,
76
77 // Comparison to yesterday
78 yesterdayRevenue: stats.f400 || 0,
79 revenueChange: stats.f401 || 0,
80 revenueChangePercent: stats.f402 || 0,
81
82 // Time tracking
83 firstSaleTime: stats.f500 || null,
84 lastSaleTime: stats.f501 || null,
85 busyHour: stats.f502 || null,
86
87 // Location info
88 locationId: stats.f131 || null,
89 locationName: stats.f132 || null,
90
91 // Timestamp
92 generatedAt: new Date().toISOString()
93 };
94
95 // Calculate some derived metrics
96 if (todayStats.yesterdayRevenue > 0) {
97 todayStats.revenueChangePercent =
98 ((todayStats.totalRevenue - todayStats.yesterdayRevenue) / todayStats.yesterdayRevenue) * 100;
99 }
100
101 return NextResponse.json({
102 success: true,
103 data: todayStats,
104 source: 'buck'
105 });
106 }
107
108 // Return empty stats if no data
109 return NextResponse.json({
110 success: true,
111 data: {
112 totalSales: 0,
113 totalRevenue: 0,
114 transactionCount: 0,
115 customersToday: 0,
116 generatedAt: new Date().toISOString()
117 },
118 source: 'buck'
119 });
120
121 } catch (error) {
122 console.error('[Stats Today] Error:', error);
123 return NextResponse.json(
124 { error: 'Failed to fetch today\'s statistics' },
125 { status: 500 }
126 );
127 }
128}