1import { NextRequest, NextResponse } from "next/server";
2import { fieldpineServerApi } from "@/lib/server/fieldpineApi";
3import { getStoredAuth } from "@/lib/server/auth";
8 * Provides various sales statistics endpoints:
9 * - ?type=today - Today's overall stats
10 * - ?type=department - Today's stats by department
11 * - ?type=hourly - Sales broken down by hour
12 * - ?type=store - Sales by store/location
13 * - ?type=payment - Sales by payment method
14 * - ?type=staff - Sales by staff member
16export async function GET(request: NextRequest) {
18 const authData = await getStoredAuth();
20 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
23 const { searchParams } = new URL(request.url);
24 const type = searchParams.get("type") || "today";
27 let params: Record<string, string> = {};
31 // Overall today's statistics
33 "3": "retailmax.elink.stats.today"
38 // Today's stats by department
40 "3": "retailmax.elink.stats.today.department"
45 // Sales grouped by hour - use sale.totals.group with hour dimension
47 "3": "retailmax.elink.sale.totals.group",
48 "15": "hour", // Group by hour
49 "9": "f110,5,today" // Filter: sales >= today
54 // Sales grouped by day for the last 7 days
56 "3": "retailmax.elink.sale.totals.group",
57 "15": "day", // Group by day
58 "9": "f110,5,today-7" // Filter: sales >= 7 days ago
63 // Sales grouped by store/location
65 "3": "retailmax.elink.sale.totals.group",
66 "15": "location", // Group by location
72 // Get flat sale list with payment details
74 "3": "retailmax.elink.saleflat.list",
76 "10": "110,120,130,140" // Include sale fields + payment info
81 // Sales grouped by staff/teller
83 "3": "retailmax.elink.sale.totals.group",
84 "15": "teller", // Group by staff
90 return NextResponse.json(
91 { success: false, error: "Invalid type parameter" },
96 console.log(`[Sales Stats API] Fetching ${type} stats`);
98 const result = await fieldpineServerApi.buckApiCall(params, authData.apiKey!);
100 console.log(`[Sales Stats API] Result for ${type}:`, {
101 hasDats: !!result.DATS,
102 datsLength: result.DATS?.length,
103 resultKeys: Object.keys(result)
106 return NextResponse.json({
112 } catch (error: any) {
113 console.error("[Sales Stats API] Error:", error);
114 return NextResponse.json(
115 { success: false, error: error.message || "Failed to fetch sales statistics" },
116 { status: error.status || 500 }