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 organizationId = getCookie(event, 'organizationId') const query = getQuery(event) const res: any = await event.context.fetch(`models/ad_user?$filter=${string.urlEncode('(isActive eq true OR isActive eq false) AND (isSalesLead eq true OR isVendorLead eq true)')}&$orderby=${string.urlEncode('ad_user_id desc')}`, 'GET', token, null) if(res) { data = res // Last activity per lead (C_ContactActivity.StartDate) for the list's "last activity" // column. One bounded query, newest first, reduced in Node — fail-soft: the list still // loads without the dates when the activity fetch fails. try { const act: any = await event.context.fetch(`models/c_contactactivity?$select=AD_User_ID,StartDate&$orderby=${string.urlEncode('StartDate desc')}&$top=5000`, 'GET', token, null) const lastByUser = new Map() for (const a of (act?.records || [])) { const userId = Number(a?.AD_User_ID?.id) if (userId && a?.StartDate && !lastByUser.has(userId)) lastByUser.set(userId, a.StartDate) } for (const lead of (data?.records || [])) { lead.lastActivityDate = lastByUser.get(Number(lead.id)) || null } } catch (e: any) { console.error('[Leads] last-activity lookup skipped:', e?.data ?? e?.message ?? e) } } 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: any) { data = errorHandlingHelper(err?.data ?? err, error?.data ?? error) forceLogoutHelper(event, data) } } return data })