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 * Product Performance Report API
7 *
8 * Get product sales performance statistics
9 * Query params:
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')
14 */
15export async function GET(request: NextRequest) {
16 try {
17 const authData = await getStoredAuth();
18 if (!authData) {
19 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
20 }
21
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";
27
28 // Map groupBy to field codes
29 const groupByMap: Record<string, string> = {
30 product: "pid",
31 customer: "cid",
32 staff: "tid",
33 };
34
35 const groupByField = groupByMap[groupBy] || "pid";
36
37 // Build parameters
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
42 "8": limit,
43 "100": "1",
44 };
45
46 // Add department filter if specified
47 if (department) {
48 (params["9"] as string[]).push(`f105,0,${department}`);
49 }
50
51 console.log(`[Product Performance API] Fetching performance for ${groupBy}`, {
52 department,
53 dateFrom,
54 limit
55 });
56
57 const result = await fieldpineServerApi.buckApiCall(params, authData.apiKey!);
58
59 return NextResponse.json({
60 success: true,
61 data: result,
62 params: {
63 department,
64 groupBy,
65 limit,
66 dateFrom
67 }
68 });
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 }
74 );
75 }
76}