import { string } from 'alga-js' import refreshTokenHelper from "../../utils/refreshTokenHelper" import forceLogoutHelper from "../../utils/forceLogoutHelper" import errorHandlingHelper from "../../utils/errorHandlingHelper" const handleFunc = async (event: any, authToken: any = null) => { let data: any = {} const config = useRuntimeConfig() const token = authToken ?? await getTokenHelper(event) const serviceToken = config.api.idempieretoken // Check for fulfillment customer (logship_organization_id) vs regular user (organizationId) const logshipOrgId = getCookie(event, 'logship_organization_id') const regularOrgId = getCookie(event, 'organizationId') // Fulfillment customers use logship_organization_id and need service token for cross-org access const isFulfillmentCustomer = !!logshipOrgId let bpartnerId: number | null = null let isAllowFeeReportDownload = false let res: any = null if (isFulfillmentCustomer && serviceToken) { // Fulfillment customer path: use service token to fetch invoices by business partner try { const orgFilter = `AD_Org_ID eq ${logshipOrgId}` const orgUrl = `${config.api.url}/models/ad_org?$filter=${string.urlEncode(orgFilter)}&$select=C_BPartner_ID` const orgRes: any = await $fetch(orgUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) bpartnerId = orgRes?.records?.[0]?.C_BPartner_ID?.id if (bpartnerId) { const bpartnerRes: any = await $fetch(`${config.api.url}/models/c_bpartner/${bpartnerId}?$select=isAllowFeeReportDownload`, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) isAllowFeeReportDownload = bpartnerRes?.isAllowFeeReportDownload === 'Y' || bpartnerRes?.isAllowFeeReportDownload === true // Fetch invoices for this business partner using service token const bpartnerFilter = `C_BPartner_ID eq ${bpartnerId}` const invoiceUrl = `${config.api.url}/models/C_Invoice?$filter=${string.urlEncode(bpartnerFilter)}&$select=C_Invoice_ID,C_Invoice_UU,IsActive,DocumentNo,Description,IsApproved,IsPaid,IsPrinted,IsTransferred,DateOrdered,DateInvoiced,DateAcct,TotalLines,GrandTotal,ChargeAmt,Processed,IsSOTrx,IsDiscountPrinted,IsTaxIncluded,SendEMail,IsSelfService,ProcessedOn,IsPayScheduleValid,IsInDispute,IsFixedAssetInvoice,IsOverrideCurrencyRate,DocStatus,C_DocType_ID,C_DocTypeTarget_ID,DocBaseType,SalesRep_ID,AD_User_ID,C_PaymentTerm_ID,C_Currency_ID,PaymentRule,M_PriceList_ID,C_BPartner_ID,C_BPartner_Location_ID,AD_Org_ID,AD_Client_ID,C_Order_ID&$expand=C_Order_ID($select=Report_Strapi_Reference)&$orderby=C_Invoice_ID desc` res = await $fetch(invoiceUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) } } catch (err) { console.warn('Could not fetch org business partner:', err) } } // Regular user path: use user token if (!res) { res = await event.context.fetch(`models/c_invoice?$filter=${string.urlEncode('isSOTrx eq true AND isActive eq true OR isActive eq false')}&$select=C_Invoice_ID,C_Invoice_UU,IsActive,DocumentNo,Description,IsApproved,IsPaid,IsPrinted,IsTransferred,DateOrdered,DateInvoiced,DateAcct,TotalLines,GrandTotal,ChargeAmt,Processed,IsSOTrx,IsDiscountPrinted,IsTaxIncluded,SendEMail,IsSelfService,ProcessedOn,IsPayScheduleValid,IsInDispute,IsFixedAssetInvoice,IsOverrideCurrencyRate,DocStatus,C_DocType_ID,C_DocTypeTarget_ID,DocBaseType,SalesRep_ID,AD_User_ID,C_PaymentTerm_ID,C_Currency_ID,PaymentRule,M_PriceList_ID,C_BPartner_ID,C_BPartner_Location_ID,AD_Org_ID,AD_Client_ID,C_Order_ID&$expand=C_Order_ID($select=Report_Strapi_Reference)&$orderby=C_Invoice_ID desc`, 'GET', token, null) } if(res) { data = { ...res, isAllowFeeReportDownload } } return data } 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) { data = errorHandlingHelper(err?.data ?? err, error?.data ?? error) forceLogoutHelper(event, data) } } return data })