1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
5export async function GET(request: NextRequest) {
7 const authData = await getStoredAuth();
8 if (!authData?.authenticated) {
9 return NextResponse.json(
10 { success: false, error: 'Authentication required' },
15 // Fetch products with filter a5
16 const result = await fieldpineServerApi.buckApiCall({
17 "3": "retailmax.elink.products",
19 "9": "f503,0,a5", // Note: Using a5 filter as per user's request
20 "10": "113,349,100,101,105,103,113s,1101,1102",
24 const products = result.DATS || [];
26 // Group products by PLU code (f105)
27 const pluGroups = new Map<string, any[]>();
29 products.forEach((product: any) => {
30 const plu = product.f105;
32 // Only process products with a PLU
33 if (plu && plu.trim() !== '') {
34 if (!pluGroups.has(plu)) {
35 pluGroups.set(plu, []);
37 pluGroups.get(plu)!.push(product);
41 // Find PLUs with duplicates (more than one product)
42 const duplicates: any[] = [];
44 pluGroups.forEach((productList: any, plu: string) => {
45 if (productList.length > 1) {
48 count: productList.length,
49 products: productList.map((p: any) => ({
54 salesInfo: p.f1102 || 'No sales data'
60 // Sort by count (most duplicates first)
61 duplicates.sort((a: any, b: any) => b.count - a.count);
63 return NextResponse.json({
67 totalProducts: products.length,
68 duplicatePLUCount: duplicates.length,
69 totalDuplicateProducts: duplicates.reduce((sum, d) => sum + d.count, 0)
73 } catch (error: any) {
74 console.error('Error fetching duplicate PLU data:', error);
75 return NextResponse.json(
76 { success: false, error: error.message || 'Failed to fetch duplicate PLU data' },