/** بازهٔ ماندن یک لید در یک مرحله */ export type LeadStageStay = { stageId: string; fromMs: number; toMs: number; }; type StageChangeMeta = { fromStageId?: string | null; toStageId?: string | null; }; function asMeta(raw: unknown): StageChangeMeta { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}; const obj = raw as Record; return { fromStageId: typeof obj.fromStageId === 'string' ? obj.fromStageId : null, toStageId: typeof obj.toStageId === 'string' ? obj.toStageId : null, }; } /** * از رویدادهای لید، بازه‌های ماندن در هر مرحله را می‌سازد. * برای دادهٔ قدیمی بدون meta، فقط toStage از meta یا ترتیب رویدادها استفاده می‌شود. */ export function buildLeadStageStays(input: { leadId: string; currentStageId: string; createdAt: Date; convertedAt: Date | null; archivedAt: Date | null; events: Array<{ type: string; createdAt: Date; meta: unknown }>; nowMs?: number; }): LeadStageStay[] { const nowMs = input.nowMs ?? Date.now(); const endCap = Math.min( nowMs, input.convertedAt?.getTime() ?? Number.POSITIVE_INFINITY, input.archivedAt?.getTime() ?? Number.POSITIVE_INFINITY, ); type Point = { at: number; stageId: string | null }; const points: Point[] = [{ at: input.createdAt.getTime(), stageId: null }]; const timeline = [...input.events].sort( (a, b) => a.createdAt.getTime() - b.createdAt.getTime(), ); for (const ev of timeline) { if (ev.type === 'created') { const meta = asMeta(ev.meta); const rawStage = meta.toStageId || (ev.meta && typeof ev.meta === 'object' && !Array.isArray(ev.meta) && typeof (ev.meta as { stageId?: unknown }).stageId === 'string' ? String((ev.meta as { stageId: string }).stageId) : null); if (rawStage) { points[0] = { at: ev.createdAt.getTime(), stageId: rawStage }; } continue; } if (ev.type !== 'stage_changed') continue; const meta = asMeta(ev.meta); const toStageId = meta.toStageId; if (!toStageId) continue; points.push({ at: ev.createdAt.getTime(), stageId: toStageId }); } // اگر نقطهٔ اول stage نداشت، از اولین stage_changed یا مرحلهٔ فعلی استفاده کن if (!points[0]?.stageId) { const firstKnown = points.find((p) => p.stageId); points[0]!.stageId = firstKnown?.stageId ?? input.currentStageId; } // آخرین مرحله تا endCap ادامه دارد const last = points[points.length - 1]!; if (last.stageId !== input.currentStageId && !input.convertedAt && !input.archivedAt) { // مرحلهٔ فعلی ممکن است بدون رویداد باشد (دادهٔ قدیمی) points.push({ at: endCap, stageId: input.currentStageId }); } const stays: LeadStageStay[] = []; for (let i = 0; i < points.length; i++) { const cur = points[i]!; if (!cur.stageId) continue; const nextAt = points[i + 1]?.at ?? endCap; const toMs = Math.min(nextAt, endCap); if (toMs <= cur.at) continue; stays.push({ stageId: cur.stageId, fromMs: cur.at, toMs }); } return stays; } export function hoursBetween(fromMs: number, toMs: number): number { return Math.max(0, (toMs - fromMs) / (1000 * 60 * 60)); }