Add lead funnel, stage conversion, and dwell reports to the report builder.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-18 17:29:58 +03:30
co-authored by Cursor
parent 2788103488
commit 968252ec2f
6 changed files with 944 additions and 27 deletions
+56 -3
View File
@@ -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,
@@ -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<string, unknown>;
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));
}
@@ -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 })
+444 -15
View File
@@ -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<ReportsLeadsAnalyticsDto> {
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<string, number>();
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<string, { hours: number; n: number }>();
const transitionCount = new Map<string, number>();
const leftFromCount = new Map<string, number>();
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<string, unknown>)
: {};
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<typeof row> => 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<string, { hours: number; n: number; label: string }>();
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<string[] | null> {
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;