From 968252ec2fd09f96ff65f99e50b0745796bfe5fd Mon Sep 17 00:00:00 2001 From: Mahdi Date: Wed, 18 Nov 2026 17:29:58 +0330 Subject: [PATCH] Add lead funnel, stage conversion, and dwell reports to the report builder. Co-authored-by: Cursor --- apps/api/src/leads/leads.service.ts | 59 ++- apps/api/src/reports/leads-analytics.util.ts | 99 ++++ apps/api/src/reports/reports.controller.ts | 9 + apps/api/src/reports/reports.service.ts | 459 ++++++++++++++++++- apps/web/src/views/ReportsView.vue | 266 ++++++++++- packages/shared/src/index.ts | 79 +++- 6 files changed, 944 insertions(+), 27 deletions(-) create mode 100644 apps/api/src/reports/leads-analytics.util.ts diff --git a/apps/api/src/leads/leads.service.ts b/apps/api/src/leads/leads.service.ts index c49cc81..d40104d 100644 --- a/apps/api/src/leads/leads.service.ts +++ b/apps/api/src/leads/leads.service.ts @@ -515,7 +515,10 @@ export class LeadsService { include: leadInclude, }); - await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null); + await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null, { + stageId: row.stageId, + stageName: row.stage.name, + }); if (assigneeId) { await this.addEvent( actor, @@ -675,6 +678,13 @@ export class LeadsService { id, 'stage_changed', `وضعیت به «${row.stage.name}» تغییر کرد`, + null, + { + fromStageId: existing.stageId, + fromStageName: existing.stage?.name ?? null, + toStageId: row.stageId, + toStageName: row.stage.name, + }, ); this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, { eventKey: `${id}:${row.stageId}`, @@ -732,6 +742,13 @@ export class LeadsService { id, 'stage_changed', `به مرحله «${stage.name}» منتقل شد`, + null, + { + fromStageId: before.stageId, + fromStageName: before.stage?.name ?? null, + toStageId: stageId, + toStageName: stage.name, + }, ); this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, { eventKey: `${id}:${stageId}`, @@ -790,6 +807,18 @@ export class LeadsService { where: { id: stageId, organizationId: actor.organizationId }, }); if (!stage) throw new NotFoundException('مرحله پیدا نشد'); + const beforeRows = await this.prisma.lead.findMany({ + where: { + organizationId: actor.organizationId, + id: { in: leadIds }, + archivedAt: null, + }, + select: { + id: true, + stageId: true, + stage: { select: { name: true } }, + }, + }); const result = await this.prisma.lead.updateMany({ where: { organizationId: actor.organizationId, @@ -798,12 +827,20 @@ export class LeadsService { }, data: { stageId }, }); - for (const leadId of leadIds) { + for (const lead of beforeRows) { + if (lead.stageId === stageId) continue; await this.addEvent( actor, - leadId, + lead.id, 'stage_changed', `وضعیت گروهی به «${stage.name}»`, + null, + { + fromStageId: lead.stageId, + fromStageName: lead.stage.name, + toStageId: stageId, + toStageName: stage.name, + }, ); } return result.count; @@ -1118,6 +1155,22 @@ export class LeadsService { include: leadInclude, }); + if (convertedStage && convertedStage.id !== lead.stageId) { + await this.addEvent( + actor, + id, + 'stage_changed', + `وضعیت به «${convertedStage.name}» تغییر کرد`, + null, + { + fromStageId: lead.stageId, + fromStageName: lead.stage?.name ?? null, + toStageId: convertedStage.id, + toStageName: convertedStage.name, + }, + ); + } + await this.addEvent( actor, id, diff --git a/apps/api/src/reports/leads-analytics.util.ts b/apps/api/src/reports/leads-analytics.util.ts new file mode 100644 index 0000000..eb0e8b6 --- /dev/null +++ b/apps/api/src/reports/leads-analytics.util.ts @@ -0,0 +1,99 @@ +/** بازهٔ ماندن یک لید در یک مرحله */ +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)); +} diff --git a/apps/api/src/reports/reports.controller.ts b/apps/api/src/reports/reports.controller.ts index 597db8a..12e9fff 100644 --- a/apps/api/src/reports/reports.controller.ts +++ b/apps/api/src/reports/reports.controller.ts @@ -97,6 +97,15 @@ export class ReportsController { }); } + /** قیف لید، تبدیل بین‌مرحله‌ای و میانگین ماندن در ستون‌ها */ + @Get('leads') + leads(@CurrentUser() user: Actor, @Query() query: ReportsQueryDto) { + return this.reportsService.leadsAnalytics(user, { + from: query.from, + to: query.to, + }); + } + /** داشبورد صفحهٔ خانه برای همه باز است */ @Get('home') @RequirePermission('reports', { reads: false }) diff --git a/apps/api/src/reports/reports.service.ts b/apps/api/src/reports/reports.service.ts index 62e0214..fb407eb 100644 --- a/apps/api/src/reports/reports.service.ts +++ b/apps/api/src/reports/reports.service.ts @@ -10,19 +10,22 @@ import type { ReportsDrillKind, ReportsDrilldownDto, ReportsFunnelStageDto, + ReportsLeadsAnalyticsDto, ReportsPeriodCompareRowDto, } from '@mento/shared'; import { + isReportsLeadBuilderMetric, REPORTS_BUILDER_DIMENSION_LABELS, REPORTS_BUILDER_METRIC_LABELS, } from '@mento/shared'; import { Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; -import { customersPersonWhere } from '../common/data-access'; +import { customersPersonWhere, leadsDeepWhere } from '../common/data-access'; import { type Actor, assigneeWhere, elevated, + forScope, ownerWhere, ticketAccessWhere, } from '../common/record-scope'; @@ -38,6 +41,10 @@ import { jalaliMonthName, startOfJalaliMonth, } from '../common/jalali'; +import { + buildLeadStageStays, + hoursBetween, +} from './leads-analytics.util'; const DRILL_LIMIT = 50; @@ -1205,6 +1212,230 @@ export class ReportsService { }; } + async leadsAnalytics( + actor: Actor, + opts: { from?: string; to?: string }, + ): Promise { + const { start, end } = resolveRange(opts.from, opts.to); + const orgId = actor.organizationId; + const access = this.leadAccessWhere(actor); + + const stages = await this.prisma.leadStage.findMany({ + where: { organizationId: orgId }, + orderBy: { position: 'asc' }, + select: { + id: true, + name: true, + position: true, + isConverted: true, + isLost: true, + isUnqualified: true, + }, + }); + const stageName = new Map(stages.map((s) => [s.id, s.name])); + const lostIds = new Set( + stages.filter((s) => s.isLost || s.isUnqualified).map((s) => s.id), + ); + const convertedIds = new Set( + stages.filter((s) => s.isConverted).map((s) => s.id), + ); + + const [created, converted, lost, activeLeads, stageEvents] = + await Promise.all([ + this.prisma.lead.count({ + where: { + organizationId: orgId, + ...access, + createdAt: { gte: start, lte: end }, + }, + }), + this.prisma.lead.count({ + where: { + organizationId: orgId, + ...access, + convertedAt: { gte: start, lte: end }, + }, + }), + this.prisma.lead.count({ + where: { + organizationId: orgId, + ...access, + archivedAt: null, + stageId: { in: [...lostIds] }, + updatedAt: { gte: start, lte: end }, + }, + }), + this.prisma.lead.findMany({ + where: { + organizationId: orgId, + ...access, + archivedAt: null, + convertedAt: null, + stageId: { notIn: [...lostIds, ...convertedIds] }, + }, + select: { id: true, stageId: true }, + }), + this.prisma.leadEvent.findMany({ + where: { + organizationId: orgId, + type: { in: ['created', 'stage_changed'] }, + createdAt: { gte: start, lte: end }, + lead: { ...access }, + }, + select: { + leadId: true, + type: true, + createdAt: true, + meta: true, + }, + orderBy: { createdAt: 'asc' }, + }), + ]); + + const active = activeLeads.length; + const byStageCount = new Map(); + for (const lead of activeLeads) { + byStageCount.set(lead.stageId, (byStageCount.get(lead.stageId) ?? 0) + 1); + } + const funnelTotal = active || 1; + let prevCount: number | null = null; + + // ماندگاری و انتقال‌ها از رویدادها + وضعیت فعلی لیدهای درگیر + const leadIds = [ + ...new Set([ + ...stageEvents.map((e) => e.leadId), + ...activeLeads.map((l) => l.id), + ]), + ]; + const leadsForDwell = leadIds.length + ? await this.prisma.lead.findMany({ + where: { id: { in: leadIds }, organizationId: orgId, ...access }, + select: { + id: true, + stageId: true, + createdAt: true, + convertedAt: true, + archivedAt: true, + events: { + where: { type: { in: ['created', 'stage_changed'] } }, + select: { type: true, createdAt: true, meta: true }, + orderBy: { createdAt: 'asc' }, + }, + }, + }) + : []; + + const dwellSum = new Map(); + const transitionCount = new Map(); + const leftFromCount = new Map(); + + for (const lead of leadsForDwell) { + const stays = buildLeadStageStays({ + leadId: lead.id, + currentStageId: lead.stageId, + createdAt: lead.createdAt, + convertedAt: lead.convertedAt, + archivedAt: lead.archivedAt, + events: lead.events, + }); + for (const stay of stays) { + // فقط بازه‌هایی که با بازهٔ گزارش همپوشانی دارند + const fromMs = Math.max(stay.fromMs, start.getTime()); + const toMs = Math.min(stay.toMs, end.getTime()); + if (toMs <= fromMs) continue; + const hours = hoursBetween(fromMs, toMs); + const cur = dwellSum.get(stay.stageId) ?? { hours: 0, n: 0 }; + cur.hours += hours; + cur.n += 1; + dwellSum.set(stay.stageId, cur); + } + + for (const ev of lead.events) { + if (ev.type !== 'stage_changed') continue; + if (ev.createdAt < start || ev.createdAt > end) continue; + const meta = + ev.meta && typeof ev.meta === 'object' && !Array.isArray(ev.meta) + ? (ev.meta as Record) + : {}; + const fromId = + typeof meta.fromStageId === 'string' ? meta.fromStageId : null; + const toId = typeof meta.toStageId === 'string' ? meta.toStageId : null; + if (!fromId || !toId || fromId === toId) continue; + const key = `${fromId}→${toId}`; + transitionCount.set(key, (transitionCount.get(key) ?? 0) + 1); + leftFromCount.set(fromId, (leftFromCount.get(fromId) ?? 0) + 1); + } + } + + const funnel = stages.map((s) => { + const count = byStageCount.get(s.id) ?? 0; + const conversionFromPrevPercent = + prevCount == null + ? null + : prevCount === 0 + ? count > 0 + ? 100 + : 0 + : Math.round((count / prevCount) * 1000) / 10; + prevCount = count; + const dwell = dwellSum.get(s.id); + return { + stageId: s.id, + stageName: s.name, + count, + sharePercent: Math.round((count / funnelTotal) * 1000) / 10, + conversionFromPrevPercent, + avgDwellHours: dwell + ? Math.round((dwell.hours / dwell.n) * 10) / 10 + : null, + }; + }); + + const transitions = [...transitionCount.entries()] + .map(([key, count]) => { + const [fromStageId, toStageId] = key.split('→'); + const left = leftFromCount.get(fromStageId!) ?? 0; + return { + fromStageId: fromStageId!, + fromStageName: stageName.get(fromStageId!) ?? fromStageId!, + toStageId: toStageId!, + toStageName: stageName.get(toStageId!) ?? toStageId!, + count, + conversionPercent: + left > 0 ? Math.round((count / left) * 1000) / 10 : 0, + }; + }) + .sort((a, b) => b.count - a.count); + + const dwellByStage = stages + .map((s) => { + const d = dwellSum.get(s.id); + if (!d || d.n === 0) return null; + return { + stageId: s.id, + stageName: s.name, + avgHours: Math.round((d.hours / d.n) * 10) / 10, + sampleCount: d.n, + }; + }) + .filter((row): row is NonNullable => row != null); + + const closed = converted + lost; + return { + from: start.toISOString(), + to: end.toISOString(), + created, + converted, + lost, + active, + conversionRate: + closed > 0 ? Math.round((converted / closed) * 1000) / 10 : 0, + funnel, + transitions, + dwellByStage, + }; + } + async builder( actor: Actor, query: ReportsBuilderQuery, @@ -1226,11 +1457,16 @@ export class ReportsService { 'invoice_amount', 'invoice_count', ]); + const leadMetric = isReportsLeadBuilderMetric(metric); - if ( + if (leadMetric) { + if (dimension === 'stage') dimension = 'lead_stage'; + if (dimension === 'status') dimension = 'none'; + } else if ( !dealMetrics.has(metric) && (dimension === 'source' || dimension === 'stage' || + dimension === 'lead_stage' || dimension === 'status') ) { dimension = 'none'; @@ -1246,6 +1482,7 @@ export class ReportsService { const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, { userId: query.userId, teamId: query.teamId, + scope: leadMetric ? 'leads' : 'deals', }); if (ownerFilterIds && ownerFilterIds.length === 0) { return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format); @@ -1310,7 +1547,7 @@ export class ReportsService { const label = normalizeSource(opts.source); return { key: label, label }; } - if (dimension === 'stage') { + if (dimension === 'stage' || dimension === 'lead_stage') { const id = opts.stageId || 'none'; return { key: id, label: opts.stageName || 'بدون مرحله' }; } @@ -1437,13 +1674,174 @@ export class ReportsService { add(dim.key, dim.label, amount); } } + } else if (leadMetric) { + const leadAccess = this.leadAccessWhere(actor); + const assigneeFilter = + ownerFilterIds == null + ? {} + : { assigneeId: { in: ownerFilterIds } }; + + const stages = await this.prisma.leadStage.findMany({ + where: { organizationId: orgId }, + select: { + id: true, + name: true, + isConverted: true, + isLost: true, + isUnqualified: true, + }, + }); + const lostIds = stages + .filter((s) => s.isLost || s.isUnqualified) + .map((s) => s.id); + const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id); + + if (metric === 'leads_avg_dwell_hours') { + const leads = await this.prisma.lead.findMany({ + where: { + organizationId: orgId, + ...leadAccess, + ...assigneeFilter, + OR: [ + { createdAt: { gte: start, lte: end } }, + { updatedAt: { gte: start, lte: end } }, + { convertedAt: { gte: start, lte: end } }, + ], + }, + select: { + id: true, + stageId: true, + assigneeId: true, + source: true, + createdAt: true, + convertedAt: true, + archivedAt: true, + events: { + where: { type: { in: ['created', 'stage_changed'] } }, + select: { type: true, createdAt: true, meta: true }, + orderBy: { createdAt: 'asc' }, + }, + }, + }); + const sum = new Map(); + for (const lead of leads) { + const stays = buildLeadStageStays({ + leadId: lead.id, + currentStageId: lead.stageId, + createdAt: lead.createdAt, + convertedAt: lead.convertedAt, + archivedAt: lead.archivedAt, + events: lead.events, + }); + for (const stay of stays) { + const fromMs = Math.max(stay.fromMs, start.getTime()); + const toMs = Math.min(stay.toMs, end.getTime()); + if (toMs <= fromMs) continue; + const hours = hoursBetween(fromMs, toMs); + if (dimension === 'lead_stage' || dimension === 'stage') { + const name = + stages.find((s) => s.id === stay.stageId)?.name ?? stay.stageId; + const cur = sum.get(stay.stageId) ?? { + hours: 0, + n: 0, + label: name, + }; + cur.hours += hours; + cur.n += 1; + sum.set(stay.stageId, cur); + } else { + const dim = await dimKey({ + ownerId: lead.assigneeId, + source: lead.source, + stageId: stay.stageId, + stageName: + stages.find((s) => s.id === stay.stageId)?.name ?? null, + at: new Date(stay.fromMs), + }); + const cur = sum.get(dim.key) ?? { + hours: 0, + n: 0, + label: dim.label, + }; + cur.hours += hours; + cur.n += 1; + sum.set(dim.key, cur); + } + } + } + for (const [key, row] of sum.entries()) { + if (row.n <= 0) continue; + add(key, row.label, Math.round((row.hours / row.n) * 10) / 10); + } + } else { + let where: Prisma.LeadWhereInput = { + organizationId: orgId, + ...leadAccess, + ...assigneeFilter, + }; + if (metric === 'leads_created') { + where = { ...where, createdAt: { gte: start, lte: end } }; + } else if (metric === 'leads_converted') { + where = { ...where, convertedAt: { gte: start, lte: end } }; + } else if (metric === 'leads_lost') { + where = { + ...where, + archivedAt: null, + stageId: { in: lostIds.length ? lostIds : ['__none__'] }, + updatedAt: { gte: start, lte: end }, + }; + } else { + // leads_active + where = { + ...where, + archivedAt: null, + convertedAt: null, + stageId: { + notIn: [...lostIds, ...convertedIds], + }, + }; + } + + const leads = await this.prisma.lead.findMany({ + where, + select: { + assigneeId: true, + source: true, + stageId: true, + stage: { select: { name: true } }, + createdAt: true, + updatedAt: true, + convertedAt: true, + }, + }); + + for (const lead of leads) { + const at = + metric === 'leads_converted' + ? lead.convertedAt ?? lead.updatedAt + : metric === 'leads_created' + ? lead.createdAt + : lead.updatedAt; + const dim = await dimKey({ + ownerId: lead.assigneeId, + source: lead.source, + stageId: lead.stageId, + stageName: lead.stage?.name, + at, + }); + add(dim.key, dim.label, 1); + } + } } const rows: ReportsBuilderRowDto[] = [...buckets.entries()] .map(([key, row]) => ({ key, label: row.label, - value: Math.round(row.value * (format === 'money' ? 1 : 1)), + value: + metric === 'leads_avg_dwell_hours' + ? Math.round(row.value * 10) / 10 + : Math.round(row.value * (format === 'money' ? 1 : 1)), })) .sort((a, b) => b.value - a.value); @@ -1471,21 +1869,52 @@ export class ReportsService { }; } + private leadAccessWhere(actor: Actor): Prisma.LeadWhereInput { + if (actor.leadsAccess !== undefined) { + return leadsDeepWhere(actor); + } + const scoped = forScope(actor, 'leads'); + if (elevated(scoped.role)) return {}; + if (scoped.dataVisibility === 'org') return {}; + if ( + scoped.dataVisibility === 'team' && + scoped.visibleUserIds && + scoped.visibleUserIds.length + ) { + return { assigneeId: { in: scoped.visibleUserIds } }; + } + return { assigneeId: scoped.userId }; + } + private async resolveBuilderOwnerIds( actor: Actor, - opts: { userId?: string; teamId?: string }, + opts: { userId?: string; teamId?: string; scope?: 'deals' | 'leads' }, ): Promise { - const scope = ownerWhere(actor, 'deals'); let allowed: string[] | null = null; - if ('ownerId' in scope && typeof scope.ownerId === 'string') { - allowed = [scope.ownerId]; - } else if ( - 'ownerId' in scope && - scope.ownerId && - typeof scope.ownerId === 'object' && - 'in' in scope.ownerId - ) { - allowed = [...scope.ownerId.in]; + if (opts.scope === 'leads') { + const scoped = forScope(actor, 'leads'); + if (elevated(scoped.role) || scoped.dataVisibility === 'org') { + allowed = null; + } else if ( + scoped.dataVisibility === 'team' && + scoped.visibleUserIds?.length + ) { + allowed = [...scoped.visibleUserIds]; + } else { + allowed = [scoped.userId]; + } + } else { + const scope = ownerWhere(actor, 'deals'); + if ('ownerId' in scope && typeof scope.ownerId === 'string') { + allowed = [scope.ownerId]; + } else if ( + 'ownerId' in scope && + scope.ownerId && + typeof scope.ownerId === 'object' && + 'in' in scope.ownerId + ) { + allowed = [...scope.ownerId.in]; + } } let ids: string[] | null = null; diff --git a/apps/web/src/views/ReportsView.vue b/apps/web/src/views/ReportsView.vue index 9e2bc96..aad4b57 100644 --- a/apps/web/src/views/ReportsView.vue +++ b/apps/web/src/views/ReportsView.vue @@ -37,12 +37,14 @@ import type { ReportsFunnelStageDto, ReportsPeriodCompareRowDto, ReportsViewFilters, + ReportsLeadsAnalyticsDto, SavedViewDto, TahesabConnectionDto, TeamDto, } from '@mento/shared'; import { brand, + isReportsLeadBuilderMetric, REPORTS_BUILDER_DIMENSION_LABELS, REPORTS_BUILDER_DIMENSIONS, REPORTS_BUILDER_METRIC_LABELS, @@ -50,7 +52,7 @@ import { } from '@mento/shared'; type PeriodKey = 'today' | 'week' | 'month' | 'quarter' | 'year' | 'custom'; -type PageMode = 'dashboard' | 'builder'; +type PageMode = 'dashboard' | 'builder' | 'leads'; const PERIODS: Array<{ key: PeriodKey; label: string }> = [ { key: 'today', label: 'امروز' }, @@ -105,12 +107,31 @@ const builderTeamId = ref(''); const builderLoading = ref(false); const builderError = ref(''); const builderResult = ref(null); +const leadsData = ref(null); +const leadsLoading = ref(false); +const leadsError = ref(''); const orgUsers = ref([]); const orgTeams = ref([]); const teamsAvailable = ref(true); /** ماژول ته‌حساب فعال + حداقل یک اتصال تنظیم‌شده */ const hasTahesabSetup = ref(false); +const builderMetricOptions = computed(() => REPORTS_BUILDER_METRICS); +const builderDimensionOptions = computed(() => { + if (isReportsLeadBuilderMetric(builderMetric.value)) { + return REPORTS_BUILDER_DIMENSIONS.filter( + (d) => + d === 'none' || + d === 'owner' || + d === 'team' || + d === 'source' || + d === 'lead_stage' || + d === 'month', + ); + } + return REPORTS_BUILDER_DIMENSIONS.filter((d) => d !== 'lead_stage'); +}); + const showTahesabSalesReport = computed( () => Boolean(auth.user?.enabledModules?.includes('tahesab')) && @@ -263,6 +284,7 @@ function applyPeriod(key: PeriodKey, opts?: { keepView?: boolean }) { } void load().then(() => { if (pageMode.value === 'builder') void runBuilder(); + if (pageMode.value === 'leads') void loadLeads(); }); } @@ -351,7 +373,12 @@ async function loadSavedViews() { } function applyFilters(filters: ReportsViewFilters, keepView: boolean) { - pageMode.value = filters.mode === 'builder' ? 'builder' : 'dashboard'; + pageMode.value = + filters.mode === 'builder' + ? 'builder' + : filters.mode === 'leads' + ? 'leads' + : 'dashboard'; if (filters.builder) { const m = filters.builder.metric; const d = filters.builder.dimension; @@ -373,6 +400,7 @@ function applyFilters(filters: ReportsViewFilters, keepView: boolean) { const afterRange = () => { if (pageMode.value === 'builder') void runBuilder(); + if (pageMode.value === 'leads') void loadLeads(); }; const p = PERIOD_KEYS.has(filters.period as PeriodKey) @@ -440,12 +468,46 @@ async function runBuilder() { } } +async function loadLeads() { + leadsLoading.value = true; + leadsError.value = ''; + try { + const { data: res } = await api.get('/reports/leads', { + params: { + from: from.value || undefined, + to: to.value || undefined, + }, + }); + leadsData.value = res; + } catch (e) { + leadsData.value = null; + leadsError.value = axios.isAxiosError(e) + ? String( + (e.response?.data as { message?: string })?.message ?? + 'بارگذاری گزارش لیدها ناموفق بود.', + ) + : 'بارگذاری گزارش لیدها ناموفق بود.'; + } finally { + leadsLoading.value = false; + } +} + function setPageMode(mode: PageMode) { pageMode.value = mode; if (mode === 'builder' && !builderResult.value) void runBuilder(); if (mode === 'dashboard' && !data.value) void load(); + if (mode === 'leads') void loadLeads(); } +watch(builderMetric, (metric) => { + const allowed = builderDimensionOptions.value; + if (!allowed.includes(builderDimension.value)) { + builderDimension.value = isReportsLeadBuilderMetric(metric) + ? 'lead_stage' + : 'owner'; + } +}); + const builderChartOption = computed(() => { const rows = (builderResult.value?.rows ?? []).slice(0, 12); const isMoney = builderResult.value?.format === 'money'; @@ -705,6 +767,47 @@ function exportReport() { return; } + if (pageMode.value === 'leads') { + if (!leadsData.value) return; + const l = leadsData.value; + const lines: string[] = [ + `گزارش لیدها ${brand.nameFa}`, + `بازه,${rangeLabel()}`, + `ایجادشده,${l.created}`, + `تبدیل‌شده,${l.converted}`, + `ازدست‌رفته,${l.lost}`, + `فعال,${l.active}`, + `نرخ تبدیل,${l.conversionRate}`, + '', + 'قیف,تعداد,سهم٪,نسبت به قبلی٪,میانگین ماندن ساعت', + ...l.funnel.map( + (r) => + `${r.stageName},${r.count},${r.sharePercent},${r.conversionFromPrevPercent ?? ''},${r.avgDwellHours ?? ''}`, + ), + '', + 'از,به,تعداد,٪ خروجی مبدأ', + ...l.transitions.map( + (r) => + `${r.fromStageName},${r.toStageName},${r.count},${r.conversionPercent}`, + ), + '', + 'ستون,میانگین ساعت,نمونه', + ...l.dwellByStage.map( + (r) => `${r.stageName},${r.avgHours},${r.sampleCount}`, + ), + ]; + const blob = new Blob(['\ufeff' + lines.join('\n')], { + type: 'text/csv;charset=utf-8', + }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${brand.filePrefix}-leads-${from.value || 'from'}-${to.value || 'to'}.csv`; + a.click(); + URL.revokeObjectURL(url); + return; + } + if (!data.value) return; const d = data.value; const lines: string[] = [ @@ -1185,7 +1288,13 @@ const activityMax = computed(() => @@ -1211,6 +1320,14 @@ const activityMax = computed(() => > گزارش‌ساز + @@ -1270,12 +1387,17 @@ const activityMax = computed(() => syncViewQuery(null); load().then(() => { if (pageMode === 'builder') runBuilder(); + if (pageMode === 'leads') loadLeads(); }); " > - + اعمال @@ -1286,13 +1408,14 @@ const activityMax = computed(() => + + +
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 14b760f..8577989 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -5387,7 +5387,7 @@ export interface ReportsViewFilters { period: string; from?: string; to?: string; - /** dashboard | builder */ + /** dashboard | builder | leads */ mode?: string; builder?: { metric?: string; @@ -5407,7 +5407,12 @@ export type ReportsBuilderMetric = | "activities_done" | "people_created" | "invoice_amount" - | "invoice_count"; + | "invoice_count" + | "leads_created" + | "leads_converted" + | "leads_lost" + | "leads_active" + | "leads_avg_dwell_hours"; export const REPORTS_BUILDER_METRICS: ReportsBuilderMetric[] = [ "won_amount", @@ -5419,6 +5424,11 @@ export const REPORTS_BUILDER_METRICS: ReportsBuilderMetric[] = [ "people_created", "invoice_amount", "invoice_count", + "leads_created", + "leads_converted", + "leads_lost", + "leads_active", + "leads_avg_dwell_hours", ]; export const REPORTS_BUILDER_METRIC_LABELS: Record< @@ -5434,6 +5444,11 @@ export const REPORTS_BUILDER_METRIC_LABELS: Record< people_created: "مشتریان جدید", invoice_amount: "مبلغ فاکتور", invoice_count: "تعداد فاکتور", + leads_created: "لیدهای ایجادشده", + leads_converted: "لیدهای تبدیل‌شده", + leads_lost: "لیدهای ازدست‌رفته", + leads_active: "لیدهای فعال (فعلی)", + leads_avg_dwell_hours: "میانگین ماندن در مرحله لید (ساعت)", }; /** ابعاد گروه‌بندی گزارش‌ساز */ @@ -5443,6 +5458,7 @@ export type ReportsBuilderDimension = | "team" | "source" | "stage" + | "lead_stage" | "month" | "status"; @@ -5452,6 +5468,7 @@ export const REPORTS_BUILDER_DIMENSIONS: ReportsBuilderDimension[] = [ "team", "source", "stage", + "lead_stage", "month", "status", ]; @@ -5465,10 +5482,26 @@ export const REPORTS_BUILDER_DIMENSION_LABELS: Record< team: "تیم", source: "منبع", stage: "مرحله مسیر فروش", + lead_stage: "مرحله / ستون لید", month: "ماه", status: "وضعیت معامله", }; +/** متریک‌های مربوط به لید در گزارش‌ساز */ +export const REPORTS_LEAD_BUILDER_METRICS: ReportsBuilderMetric[] = [ + "leads_created", + "leads_converted", + "leads_lost", + "leads_active", + "leads_avg_dwell_hours", +]; + +export function isReportsLeadBuilderMetric( + metric: ReportsBuilderMetric, +): boolean { + return (REPORTS_LEAD_BUILDER_METRICS as string[]).includes(metric); +} + export interface ReportsBuilderQuery { metric: ReportsBuilderMetric; dimension: ReportsBuilderDimension; @@ -5484,6 +5517,48 @@ export interface ReportsBuilderRowDto { value: number; } +/** تحلیل اختصاصی کانبان لیدها (قیف، تبدیل بین‌مرحله‌ای، ماندگاری) */ +export interface ReportsLeadsFunnelStageDto { + stageId: string; + stageName: string; + count: number; + sharePercent: number; + /** نسبت به ستون قبلی در ترتیب کانبان؛ null برای اولی */ + conversionFromPrevPercent: number | null; + avgDwellHours: number | null; +} + +export interface ReportsLeadsTransitionDto { + fromStageId: string; + fromStageName: string; + toStageId: string; + toStageName: string; + count: number; + /** درصد از کل خروجی‌های fromStage در بازه */ + conversionPercent: number; +} + +export interface ReportsLeadsDwellDto { + stageId: string; + stageName: string; + avgHours: number; + sampleCount: number; +} + +export interface ReportsLeadsAnalyticsDto { + from: string; + to: string; + created: number; + converted: number; + lost: number; + active: number; + /** تبدیل‌شده ÷ (تبدیل‌شده + ازدست‌رفته) در بازه؛ اگر مخرج صفر باشد ۰ */ + conversionRate: number; + funnel: ReportsLeadsFunnelStageDto[]; + transitions: ReportsLeadsTransitionDto[]; + dwellByStage: ReportsLeadsDwellDto[]; +} + export interface ReportsBuilderResultDto { metric: ReportsBuilderMetric; metricLabel: string;