import errorHandlingHelper from "../../utils/errorHandlingHelper" const handleFunc = async (event: any) => { let data: any = {} const config = useRuntimeConfig() const serviceToken = config.api.idempieretoken const body = await readBody(event) if (!serviceToken) { return { status: 500, message: 'Service token not configured' } } if (!body.orderId) { return { status: 400, message: 'Order ID is required' } } // Get all existing fee lines for this order const existingRes: any = await $fetch(`${config.api.url}/models/cust_fulfillmentfeeline?$filter=c_order_id eq ${body.orderId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) if (!existingRes?.records || existingRes.records.length === 0) { return { status: 400, message: 'No fee lines exist for this order. Cannot update fees without existing fee lines.' } } const newFeeAmount = parseFloat(body.feeAmount) || 0 const currentTotal = existingRes.records.reduce((sum: number, record: any) => sum + (record.LineTotalAmt || 0), 0) if (newFeeAmount === currentTotal) { return { status: 200, message: 'Fee amount unchanged' } } // Calculate the difference and apply it proportionally to each fee line // Or simply update the first fee line with the difference const difference = newFeeAmount - currentTotal // Update the first fee line with the new total difference const firstLine = existingRes.records[0] const newLineTotal = (firstLine.LineTotalAmt || 0) + difference const updateRes: any = await $fetch(`${config.api.url}/models/cust_fulfillmentfeeline/${firstLine.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken }, body: { LineTotalAmt: newLineTotal, tableName: 'Cust_FulfillmentFeeLine' } }) if (updateRes) { data = updateRes data['status'] = 200 data['message'] = 'Fee updated successfully' data['newTotal'] = newFeeAmount } return data } export default defineEventHandler(async (event) => { let data: any = {} try { data = await handleFunc(event) } catch(err: any) { data = errorHandlingHelper(err?.data ?? err, err) } return data })