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 const organizationId = getCookie(event, 'logship_organization_id') console.log('=== INVOICES SO.GET DEBUG ===') console.log('organizationId from cookie:', organizationId) console.log('serviceToken available:', !!serviceToken) console.log('API URL:', config.api.url) // First, get the org's business partner ID using the service token // Query: /models/ad_org?$filter=AD_Org_ID eq {organizationId}&$select=C_BPartner_ID let bpartnerId: number | null = null let isAllowFeeReportDownload = false if (organizationId && serviceToken) { try { const orgFilter = `AD_Org_ID eq ${organizationId}` const orgUrl = `${config.api.url}/models/ad_org?$filter=${string.urlEncode(orgFilter)}&$select=C_BPartner_ID` console.log('Step 1 - Fetching org with URL:', orgUrl) const orgRes: any = await $fetch(orgUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) console.log('Step 1 - Org response:', JSON.stringify(orgRes, null, 2)) // Response has records array, get C_BPartner_ID from first record bpartnerId = orgRes?.records?.[0]?.C_BPartner_ID?.id console.log('Step 1 - Extracted bpartnerId:', bpartnerId) 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' } } catch (err) { console.error('Could not fetch org business partner:', err) } } else { console.log('Skipping service token path - organizationId:', organizationId, 'serviceToken:', !!serviceToken) } // Fetch invoices using service account token, filtered by the org's business partner // This allows fulfillment customers to see invoices where they are the recipient, // even if the invoice was created by a different org let res: any = null if (bpartnerId && serviceToken) { // Use service token to fetch invoices for this specific business partner // Query: /models/C_Invoice?$filter=C_BPartner_ID eq {bpartnerId} 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` console.log('Step 2 - Fetching invoices with URL:', invoiceUrl) res = await $fetch(invoiceUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: 'Bearer ' + serviceToken } }) console.log('Step 2 - Invoice response records count:', res?.records?.length || 0) } else { console.log('Using fallback with user token') // Fallback to user token if no business partner or service token 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_${string.urlEncode('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 })