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 * Invoices Endpoint (using BUCK API retailmax.elink.invoice.list)
7 * GET /api/v1/invoices - List received invoices
8 *
9 * Field codes:
10 * - f310: Document number (e.g., "UZDZ-WS-AZI")
11 * - f1300: Supplier name
12 * - f301: Supplier ID (e.g., "A3324949")
13 * - f331: Total cost
14 * - f311: Date (pipe-delimited: "2025|3|25|13|50|35||")
15 * - f313: Store ID
16 * - f1313: Store name
17 * - f300: Status/type
18 * - f312, f1312: Additional fields
19 */
20export async function GET(request: NextRequest) {
21 try {
22 const authData = await getStoredAuth();
23 if (!authData || !authData.authenticated) {
24 return NextResponse.json(
25 { error: 'Authentication required' },
26 { status: 401 }
27 );
28 }
29
30 const { searchParams } = new URL(request.url);
31
32 // Parse query parameters
33 const fromDate = searchParams.get('from') || '2025-01-01';
34 const toDate = searchParams.get('to') || new Date().toISOString().split('T')[0];
35 const status = searchParams.get('status') || 'S'; // S = Submitted/Received
36
37 console.log('[Invoices API] Fetching invoices:', { fromDate, toDate, status });
38
39 // Use BUCK API to get invoice list
40 // Parameters:
41 // - 3: retailmax.elink.invoice.list
42 // - 9: Filters (f311,4,fromDate and f311,1,toDate for date range, f101,0,status for status)
43 const buckParams: Record<string, string> = {
44 '3': 'retailmax.elink.invoice.list',
45 '9': [
46 `f311,4,${fromDate}`, // Date >= fromDate
47 `f311,1,${toDate}`, // Date <= toDate
48 `f101,0,${status}` // Status filter
49 ].join(',')
50 };
51
52 const result = await fieldpineServerApi.buckApiCall(buckParams, authData.apiKey);
53
54 console.log('[Invoices API] BUCK result:', {
55 hasDats: !!result.DATS,
56 datsLength: result.DATS?.length,
57 firstInvoice: result.DATS?.[0]
58 });
59
60 // Parse DATS array into invoice objects
61 let invoices: any[] = [];
62 if (result && result.DATS && Array.isArray(result.DATS)) {
63 invoices = result.DATS.map((invoice: any) => {
64 // Parse date from pipe-delimited string: "2025|3|25|13|50|35||"
65 let invoiceDate = null;
66 if (invoice.f311) {
67 const dateParts = invoice.f311.split('|');
68 if (dateParts.length >= 6) {
69 const [year, month, day, hour, minute, second] = dateParts;
70 invoiceDate = new Date(
71 parseInt(year),
72 parseInt(month) - 1, // JS months are 0-indexed
73 parseInt(day),
74 parseInt(hour),
75 parseInt(minute),
76 parseInt(second)
77 ).toISOString();
78 }
79 }
80
81 return {
82 DocumentNumber: invoice.f310 || null,
83 DocumentId: invoice.f301 || null,
84 SupplierName: invoice.f1300 || null,
85 SupplierCode: invoice.f302 || null,
86 TotalCost: parseFloat(invoice.f331) || 0,
87 InvoiceDate: invoiceDate,
88 StoreId: parseInt(invoice.f313) || null,
89 StoreName: invoice.f1313 || null,
90 Status: parseInt(invoice.f300) || null,
91 StatusText: invoice.f1312 || null,
92
93 // Additional fields
94 RawDate: invoice.f311 || null,
95 RawStatus: invoice.f312 || null
96 };
97 });
98 }
99
100 console.log('[Invoices API] Returning', invoices.length, 'invoices');
101
102 return NextResponse.json({
103 success: true,
104 data: invoices,
105 count: invoices.length,
106 filters: {
107 fromDate,
108 toDate,
109 status
110 },
111 source: 'buck'
112 });
113
114 } catch (error) {
115 console.error('[Invoices API] Error:', error);
116 return NextResponse.json(
117 {
118 success: false,
119 error: 'Failed to fetch invoices',
120 details: error instanceof Error ? error.message : 'Unknown error',
121 data: []
122 },
123 { status: 500 }
124 );
125 }
126}