// services/callReport/collapseDisplayCalls.js // Collapse repetitive AA-only bursts for readable /callreport output. import { formatLocalTime } from './formatCallLine.js'; function callerKey(call) { return [ call.callingLineId || call.leftParty?.lineId || '', call.callingNumber || call.leftParty?.number || '', call.aaKeyPress || '', ].join('|'); } /** * Collapse 3+ AA-only calls from the same caller into a single summary row. * @param {object[]} calls * @param {{ timeZone?: string, minBurst?: number }} opts * @returns {Array} */ export function collapseAaBursts(calls, opts = {}) { const minBurst = opts.minBurst ?? 3; const timeZone = opts.timeZone; const out = []; let i = 0; while (i < (calls || []).length) { const call = calls[i]; const key = callerKey(call); let j = i + 1; while (j < calls.length && callerKey(calls[j]) === key) j += 1; const group = calls.slice(i, j); if (group.length >= minBurst) { const first = group[0]; const last = group[group.length - 1]; const left = first.callingLineId && String(first.callingLineId).toUpperCase() !== 'NA' ? `${first.callingLineId} (${first.callingNumber || ''})` : (first.callingNumber || '?'); const main = first.storeMainNumber || first.calledNumber || '?'; const start = formatLocalTime(first.start, timeZone); const end = formatLocalTime(last.start, timeZone); const keyLabel = first.aaKeyPress ? ` (AA key ${first.aaKeyPress})` : ''; out.push({ kind: 'burst', calls: group, summary: `⚠️ ${start}–${end}: ${left} → ${main}${keyLabel} — ` + `${group.length} calls stopped at auto-attendant`, }); } else { out.push(...group); } i = j; } return out; }