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 * Grouped Sales Report
7 * BUCK: retailmax.elink.sale.totals.group
8 * Returns sales aggregated by product, supplier, or department
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 // Date filters
23 const startDate = searchParams.get('startDate');
24 const endDate = searchParams.get('endDate');
25 const limit = searchParams.get('limit') || '100';
26
27 // Grouping: product, supplier, department, location, teller
28 const groupBy = searchParams.get('groupBy') || 'product';
29
30 // Build BUCK parameters
31 const params: string[] = [
32 '3=retailmax.elink.sale.totals.group',
33 `8=${limit}`
34 ];
35
36 // Add date filters
37 if (startDate) {
38 params.push(`9=f102,4,${startDate}`);
39 }
40 if (endDate) {
41 params.push(`9=f102,1,${endDate}`);
42 }
43
44 // Set grouping field
45 switch (groupBy) {
46 case 'product':
47 params.push('15=200'); // Group by product (f200)
48 break;
49 case 'supplier':
50 params.push('15=220'); // Group by supplier (f220)
51 break;
52 case 'department':
53 params.push('15=133'); // Group by department (f133)
54 break;
55 case 'location':
56 params.push('15=131'); // Group by location (f131)
57 break;
58 case 'teller':
59 params.push('15=140'); // Group by teller (f140)
60 break;
61 }
62
63 const query = params.join('&');
64 const url = `/GNAP/j/buck?${query}`;
65
66 console.log('[Sales Grouped] BUCK query:', url);
67
68 const result = await fieldpineServerApi.apiCall(url, {
69 cookie: authData.apiKey,
70 useOpenApi: false
71 });
72
73 // Process BUCK response
74 if (result && result.DATS && Array.isArray(result.DATS)) {
75 const grouped = result.DATS.map((item: any) => ({
76 groupId: item.f100,
77 groupName: item.f101,
78 totalSales: item.f210,
79 totalUnits: item.f211,
80 totalRevenue: item.f212,
81 totalCost: item.f213,
82 grossProfit: item.f214,
83 grossMargin: item.f215,
84 transactionCount: item.f220
85 }));
86
87 return NextResponse.json({
88 success: true,
89 data: grouped,
90 count: grouped.length,
91 groupBy,
92 source: 'buck'
93 });
94 }
95
96 return NextResponse.json({
97 success: true,
98 data: [],
99 count: 0,
100 groupBy,
101 source: 'buck'
102 });
103
104 } catch (error) {
105 console.error('[Sales Grouped] Error:', error);
106 return NextResponse.json(
107 { error: 'Failed to fetch grouped sales' },
108 { status: 500 }
109 );
110 }
111}