1import { NextRequest, NextResponse } from 'next/server';
2import { fieldpineServerApi } from '@/lib/server/fieldpineApi';
3import { getStoredAuth } from '@/lib/server/auth';
5interface ProductLowPrice {
6 f100: number; // Product ID
7 f101: string; // Product name
8 f103: number; // Price (sell price)
10 f105: string; // PLU/SKU
12 f108?: number; // Cost price
16 f1102?: string; // Sales info
19export async function GET(request: NextRequest) {
21 // Verify authentication
22 const authData = await getStoredAuth();
23 if (!authData || !authData.authenticated) {
24 return NextResponse.json(
25 { error: 'Authentication required' },
30 console.log('[Products Priced Low] Fetching low-priced products...');
32 // Fetch products priced below cost using BUCK API
33 // Based on: https://iig.cwanz.online/GNAP/j/buck?3=retailmax.elink.products&10=113,349,100,101,105,103,113s,1101,1102&18=1101,1102&9=f503,0,a1&8=150000
34 const result = await fieldpineServerApi.buckApiCall({
35 "3": "retailmax.elink.products",
36 "8": "150000", // Limit to 150000 products
37 "9": "f503,0,a1", // Filter: f503 equals "a1" (likely active products)
38 "10": "113,349,100,101,105,103,113s,1101,1102", // Fields to return
39 "18": "1101,1102" // Sort by these fields
42 console.log('[Products Priced Low] BUCK result:', {
43 hasRootType: !!result?.RootType,
44 hasDats: !!result?.DATS,
45 datsLength: result?.DATS?.length || 0
48 // Extract product data
49 const products: ProductLowPrice[] = result?.DATS || [];
51 if (!products || products.length === 0) {
52 console.log('[Products Priced Low] No products found');
53 return NextResponse.json({
56 message: 'No low-priced products found'
60 console.log('[Products Priced Low] Found', products.length, 'products');
62 // Filter and transform products
63 const lowPricedProducts = products
65 const sellPrice = p.f103 || 0;
66 const costPrice = p.f108 || 0;
67 // Only include products where sell price is less than cost price
68 return costPrice > 0 && sellPrice < costPrice;
71 const sellPrice = p.f103 || 0;
72 const costPrice = p.f108 || 0;
73 const margin = costPrice > 0 ? ((sellPrice - costPrice) / costPrice) * 100 : 0;
78 name: p.f101 || 'Unknown Product',
82 salesInfo: p.f1102 || '',
86 .sort((a, b) => a.margin - b.margin); // Sort by margin (worst first)
88 console.log('[Products Priced Low] Filtered to', lowPricedProducts.length, 'products below cost');
90 return NextResponse.json({
92 products: lowPricedProducts,
93 totalProducts: products.length,
94 lowPricedCount: lowPricedProducts.length,
97 } catch (error: any) {
98 console.error('Products Priced Low API error:', error);
99 return NextResponse.json(
100 { success: false, error: error.message || 'Failed to fetch low-priced products' },