import { string } from 'alga-js' import refreshTokenHelper from "../../utils/refreshTokenHelper" import forceLogoutHelper from "../../utils/forceLogoutHelper" import errorHandlingHelper from "../../utils/errorHandlingHelper" import fetchHelper from "../../utils/fetchHelper" const handleFunc = async (event: any, authToken: any = null) => { const token = authToken ?? await getTokenHelper(event) const query = getQuery(event) const days = parseInt(query.days as string) || 0 // Accept either orderSourceIds (comma-separated, preferred) or single orderSourceId (legacy) const idsParam = (query.orderSourceIds as string) ?? '' const singleId = (query.orderSourceId as string) ?? '' const orderSourceIds = (idsParam ? idsParam.split(',') : (singleId ? [singleId] : [])) .map(v => v.trim()) .filter(Boolean) if (orderSourceIds.length === 0) { return { status: 400, message: 'orderSourceIds is required', records: [] } } const now = new Date() const startDate = new Date(now) startDate.setDate(startDate.getDate() - days) const startDateStr = startDate.toISOString().split('T')[0] const sourceFilter = orderSourceIds.length === 1 ? `C_OrderSource_ID eq ${orderSourceIds[0]}` : '(' + orderSourceIds.map(id => `C_OrderSource_ID eq ${id}`).join(' OR ') + ')' console.log(`[shipping-confirmations] orderSourceIds=${orderSourceIds.join(',')}, days=${days}, startDate=${startDateStr}`) const filter = string.urlEncode( `${sourceFilter} AND DocStatus eq 'CO' AND isSOTrx eq true AND DateOrdered ge '${startDateStr}'` ) const expand = string.urlEncode( 'C_Orderline($expand=M_Product_ID),M_InOut($expand=M_Shipper_ID),C_OrderSource_ID($expand=Marketplace)' ) const res: any = await fetchHelper( event, `models/c_order?$filter=${filter}&$expand=${expand}&$orderby=${string.urlEncode('c_order_id desc')}&$top=500`, 'GET', token, null ) if (!res?.records) { return { records: [] } } const shippedOrders = [] for (const order of res.records) { const inouts = order.M_InOut || order.m_inout || [] const shippedInouts = inouts.filter((inout: any) => !!(inout.TrackingNo)) if (shippedInouts.length === 0) continue const externalOrderId = order.ExternalOrderId || order.POReference || order.Description || '' const orderLines = order.C_Orderline || order.c_orderline || [] const orderSource = order.C_OrderSource_ID || {} const marketplaceIdentifier = (orderSource?.Marketplace?.identifier || '').toLowerCase() shippedOrders.push({ orderId: order.id, orderSourceId: orderSource?.id ?? null, orderSourceName: orderSource?.identifier || orderSource?.Name || '', marketplace: marketplaceIdentifier, documentNo: order.DocumentNo, externalOrderId: externalOrderId, dateOrdered: order.DateOrdered, partnerName: order.C_BPartner_ID?.identifier || '', orderLines: orderLines.map((line: any) => ({ id: line.id, lineNo: line.Line, productName: line.M_Product_ID?.Name || line.M_Product_ID?.identifier || '', productValue: line.M_Product_ID?.Value || '', qty: line.QtyOrdered || line.QtyEntered || 0, qtyDelivered: line.QtyDelivered || 0, })), shipments: shippedInouts.map((inout: any) => ({ id: inout.id, documentNo: inout.DocumentNo, trackingNo: inout.TrackingNo || '', shippingDate: inout.shipping_date || inout.MovementDate || '', shipperName: inout.M_Shipper_ID?.Name || inout.M_Shipper_ID?.identifier || '', shippingServiceName: inout.shipping_service_name || '', })), }) } console.log(`[shipping-confirmations] Found ${shippedOrders.length} shipped orders out of ${res.records.length} total`) return { records: shippedOrders } } export default defineEventHandler(async (event) => { let data: any = {} try { data = await handleFunc(event) } catch (err: any) { try { let authToken: any = await refreshTokenHelper(event) data = await handleFunc(event, authToken) } catch (error: any) { data = errorHandlingHelper(err?.data ?? err, error?.data ?? error) forceLogoutHelper(event, data) } } return data })