1import { NextRequest, NextResponse } from "next/server";
2import { fieldpineServerApi } from "@/lib/server/fieldpineApi";
3import { getStoredAuth } from "@/lib/server/auth";
6 * Product Performance Report API
8 * Get product sales performance statistics
10 * - department: Department ID to filter by (optional)
11 * - groupBy: 'product' | 'customer' | 'staff' (default: 'product')
12 * - limit: Number of results (default: 20)
13 * - dateFrom: Start date filter (default: 'today')
15export async function GET(request: NextRequest) {
17 const authData = await getStoredAuth();
19 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
22 const { searchParams } = new URL(request.url);
23 const department = searchParams.get("department");
24 const groupBy = searchParams.get("groupBy") || "product";
25 const limit = searchParams.get("limit") || "20";
26 const dateFrom = searchParams.get("dateFrom") || "today";
28 // Map groupBy to field codes
29 const groupByMap: Record<string, string> = {
35 const groupByField = groupByMap[groupBy] || "pid";
38 const params: Record<string, string | string[]> = {
39 "3": "retailmax.elink.stats.product.performance",
40 "9": [`f102,4,${dateFrom}`], // Date filter
41 "15": `2,${groupByField}`, // Group by
46 // Add department filter if specified
48 (params["9"] as string[]).push(`f105,0,${department}`);
51 console.log(`[Product Performance API] Fetching performance for ${groupBy}`, {
57 const result = await fieldpineServerApi.buckApiCall(params, authData.apiKey!);
59 return NextResponse.json({
69 } catch (error: any) {
70 console.error("[Product Performance API] Error:", error);
71 return NextResponse.json(
72 { success: false, error: error.message || "Failed to fetch product performance" },
73 { status: error.status || 500 }