Add lead funnel, stage conversion, and dwell reports to the report builder.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -515,7 +515,10 @@ export class LeadsService {
|
|||||||
include: leadInclude,
|
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) {
|
if (assigneeId) {
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
@@ -675,6 +678,13 @@ export class LeadsService {
|
|||||||
id,
|
id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`وضعیت به «${row.stage.name}» تغییر کرد`,
|
`وضعیت به «${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, {
|
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
||||||
eventKey: `${id}:${row.stageId}`,
|
eventKey: `${id}:${row.stageId}`,
|
||||||
@@ -732,6 +742,13 @@ export class LeadsService {
|
|||||||
id,
|
id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`به مرحله «${stage.name}» منتقل شد`,
|
`به مرحله «${stage.name}» منتقل شد`,
|
||||||
|
null,
|
||||||
|
{
|
||||||
|
fromStageId: before.stageId,
|
||||||
|
fromStageName: before.stage?.name ?? null,
|
||||||
|
toStageId: stageId,
|
||||||
|
toStageName: stage.name,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
||||||
eventKey: `${id}:${stageId}`,
|
eventKey: `${id}:${stageId}`,
|
||||||
@@ -790,6 +807,18 @@ export class LeadsService {
|
|||||||
where: { id: stageId, organizationId: actor.organizationId },
|
where: { id: stageId, organizationId: actor.organizationId },
|
||||||
});
|
});
|
||||||
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
|
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({
|
const result = await this.prisma.lead.updateMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
@@ -798,12 +827,20 @@ export class LeadsService {
|
|||||||
},
|
},
|
||||||
data: { stageId },
|
data: { stageId },
|
||||||
});
|
});
|
||||||
for (const leadId of leadIds) {
|
for (const lead of beforeRows) {
|
||||||
|
if (lead.stageId === stageId) continue;
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
leadId,
|
lead.id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`وضعیت گروهی به «${stage.name}»`,
|
`وضعیت گروهی به «${stage.name}»`,
|
||||||
|
null,
|
||||||
|
{
|
||||||
|
fromStageId: lead.stageId,
|
||||||
|
fromStageName: lead.stage.name,
|
||||||
|
toStageId: stageId,
|
||||||
|
toStageName: stage.name,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return result.count;
|
return result.count;
|
||||||
@@ -1118,6 +1155,22 @@ export class LeadsService {
|
|||||||
include: leadInclude,
|
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(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
id,
|
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')
|
@Get('home')
|
||||||
@RequirePermission('reports', { reads: false })
|
@RequirePermission('reports', { reads: false })
|
||||||
|
|||||||
@@ -10,19 +10,22 @@ import type {
|
|||||||
ReportsDrillKind,
|
ReportsDrillKind,
|
||||||
ReportsDrilldownDto,
|
ReportsDrilldownDto,
|
||||||
ReportsFunnelStageDto,
|
ReportsFunnelStageDto,
|
||||||
|
ReportsLeadsAnalyticsDto,
|
||||||
ReportsPeriodCompareRowDto,
|
ReportsPeriodCompareRowDto,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import {
|
import {
|
||||||
|
isReportsLeadBuilderMetric,
|
||||||
REPORTS_BUILDER_DIMENSION_LABELS,
|
REPORTS_BUILDER_DIMENSION_LABELS,
|
||||||
REPORTS_BUILDER_METRIC_LABELS,
|
REPORTS_BUILDER_METRIC_LABELS,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { customersPersonWhere } from '../common/data-access';
|
import { customersPersonWhere, leadsDeepWhere } from '../common/data-access';
|
||||||
import {
|
import {
|
||||||
type Actor,
|
type Actor,
|
||||||
assigneeWhere,
|
assigneeWhere,
|
||||||
elevated,
|
elevated,
|
||||||
|
forScope,
|
||||||
ownerWhere,
|
ownerWhere,
|
||||||
ticketAccessWhere,
|
ticketAccessWhere,
|
||||||
} from '../common/record-scope';
|
} from '../common/record-scope';
|
||||||
@@ -38,6 +41,10 @@ import {
|
|||||||
jalaliMonthName,
|
jalaliMonthName,
|
||||||
startOfJalaliMonth,
|
startOfJalaliMonth,
|
||||||
} from '../common/jalali';
|
} from '../common/jalali';
|
||||||
|
import {
|
||||||
|
buildLeadStageStays,
|
||||||
|
hoursBetween,
|
||||||
|
} from './leads-analytics.util';
|
||||||
|
|
||||||
const DRILL_LIMIT = 50;
|
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(
|
async builder(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
query: ReportsBuilderQuery,
|
query: ReportsBuilderQuery,
|
||||||
@@ -1226,11 +1457,16 @@ export class ReportsService {
|
|||||||
'invoice_amount',
|
'invoice_amount',
|
||||||
'invoice_count',
|
'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) &&
|
!dealMetrics.has(metric) &&
|
||||||
(dimension === 'source' ||
|
(dimension === 'source' ||
|
||||||
dimension === 'stage' ||
|
dimension === 'stage' ||
|
||||||
|
dimension === 'lead_stage' ||
|
||||||
dimension === 'status')
|
dimension === 'status')
|
||||||
) {
|
) {
|
||||||
dimension = 'none';
|
dimension = 'none';
|
||||||
@@ -1246,6 +1482,7 @@ export class ReportsService {
|
|||||||
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
|
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
|
||||||
userId: query.userId,
|
userId: query.userId,
|
||||||
teamId: query.teamId,
|
teamId: query.teamId,
|
||||||
|
scope: leadMetric ? 'leads' : 'deals',
|
||||||
});
|
});
|
||||||
if (ownerFilterIds && ownerFilterIds.length === 0) {
|
if (ownerFilterIds && ownerFilterIds.length === 0) {
|
||||||
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
|
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
|
||||||
@@ -1310,7 +1547,7 @@ export class ReportsService {
|
|||||||
const label = normalizeSource(opts.source);
|
const label = normalizeSource(opts.source);
|
||||||
return { key: label, label };
|
return { key: label, label };
|
||||||
}
|
}
|
||||||
if (dimension === 'stage') {
|
if (dimension === 'stage' || dimension === 'lead_stage') {
|
||||||
const id = opts.stageId || 'none';
|
const id = opts.stageId || 'none';
|
||||||
return { key: id, label: opts.stageName || 'بدون مرحله' };
|
return { key: id, label: opts.stageName || 'بدون مرحله' };
|
||||||
}
|
}
|
||||||
@@ -1437,13 +1674,174 @@ export class ReportsService {
|
|||||||
add(dim.key, dim.label, amount);
|
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()]
|
const rows: ReportsBuilderRowDto[] = [...buckets.entries()]
|
||||||
.map(([key, row]) => ({
|
.map(([key, row]) => ({
|
||||||
key,
|
key,
|
||||||
label: row.label,
|
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);
|
.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(
|
private async resolveBuilderOwnerIds(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
opts: { userId?: string; teamId?: string },
|
opts: { userId?: string; teamId?: string; scope?: 'deals' | 'leads' },
|
||||||
): Promise<string[] | null> {
|
): Promise<string[] | null> {
|
||||||
const scope = ownerWhere(actor, 'deals');
|
|
||||||
let allowed: string[] | null = null;
|
let allowed: string[] | null = null;
|
||||||
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
|
if (opts.scope === 'leads') {
|
||||||
allowed = [scope.ownerId];
|
const scoped = forScope(actor, 'leads');
|
||||||
} else if (
|
if (elevated(scoped.role) || scoped.dataVisibility === 'org') {
|
||||||
'ownerId' in scope &&
|
allowed = null;
|
||||||
scope.ownerId &&
|
} else if (
|
||||||
typeof scope.ownerId === 'object' &&
|
scoped.dataVisibility === 'team' &&
|
||||||
'in' in scope.ownerId
|
scoped.visibleUserIds?.length
|
||||||
) {
|
) {
|
||||||
allowed = [...scope.ownerId.in];
|
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;
|
let ids: string[] | null = null;
|
||||||
|
|||||||
@@ -37,12 +37,14 @@ import type {
|
|||||||
ReportsFunnelStageDto,
|
ReportsFunnelStageDto,
|
||||||
ReportsPeriodCompareRowDto,
|
ReportsPeriodCompareRowDto,
|
||||||
ReportsViewFilters,
|
ReportsViewFilters,
|
||||||
|
ReportsLeadsAnalyticsDto,
|
||||||
SavedViewDto,
|
SavedViewDto,
|
||||||
TahesabConnectionDto,
|
TahesabConnectionDto,
|
||||||
TeamDto,
|
TeamDto,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import {
|
import {
|
||||||
brand,
|
brand,
|
||||||
|
isReportsLeadBuilderMetric,
|
||||||
REPORTS_BUILDER_DIMENSION_LABELS,
|
REPORTS_BUILDER_DIMENSION_LABELS,
|
||||||
REPORTS_BUILDER_DIMENSIONS,
|
REPORTS_BUILDER_DIMENSIONS,
|
||||||
REPORTS_BUILDER_METRIC_LABELS,
|
REPORTS_BUILDER_METRIC_LABELS,
|
||||||
@@ -50,7 +52,7 @@ import {
|
|||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
|
|
||||||
type PeriodKey = 'today' | 'week' | 'month' | 'quarter' | 'year' | 'custom';
|
type PeriodKey = 'today' | 'week' | 'month' | 'quarter' | 'year' | 'custom';
|
||||||
type PageMode = 'dashboard' | 'builder';
|
type PageMode = 'dashboard' | 'builder' | 'leads';
|
||||||
|
|
||||||
const PERIODS: Array<{ key: PeriodKey; label: string }> = [
|
const PERIODS: Array<{ key: PeriodKey; label: string }> = [
|
||||||
{ key: 'today', label: 'امروز' },
|
{ key: 'today', label: 'امروز' },
|
||||||
@@ -105,12 +107,31 @@ const builderTeamId = ref('');
|
|||||||
const builderLoading = ref(false);
|
const builderLoading = ref(false);
|
||||||
const builderError = ref('');
|
const builderError = ref('');
|
||||||
const builderResult = ref<ReportsBuilderResultDto | null>(null);
|
const builderResult = ref<ReportsBuilderResultDto | null>(null);
|
||||||
|
const leadsData = ref<ReportsLeadsAnalyticsDto | null>(null);
|
||||||
|
const leadsLoading = ref(false);
|
||||||
|
const leadsError = ref('');
|
||||||
const orgUsers = ref<OrgUserDto[]>([]);
|
const orgUsers = ref<OrgUserDto[]>([]);
|
||||||
const orgTeams = ref<TeamDto[]>([]);
|
const orgTeams = ref<TeamDto[]>([]);
|
||||||
const teamsAvailable = ref(true);
|
const teamsAvailable = ref(true);
|
||||||
/** ماژول تهحساب فعال + حداقل یک اتصال تنظیمشده */
|
/** ماژول تهحساب فعال + حداقل یک اتصال تنظیمشده */
|
||||||
const hasTahesabSetup = ref(false);
|
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(
|
const showTahesabSalesReport = computed(
|
||||||
() =>
|
() =>
|
||||||
Boolean(auth.user?.enabledModules?.includes('tahesab')) &&
|
Boolean(auth.user?.enabledModules?.includes('tahesab')) &&
|
||||||
@@ -263,6 +284,7 @@ function applyPeriod(key: PeriodKey, opts?: { keepView?: boolean }) {
|
|||||||
}
|
}
|
||||||
void load().then(() => {
|
void load().then(() => {
|
||||||
if (pageMode.value === 'builder') void runBuilder();
|
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) {
|
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) {
|
if (filters.builder) {
|
||||||
const m = filters.builder.metric;
|
const m = filters.builder.metric;
|
||||||
const d = filters.builder.dimension;
|
const d = filters.builder.dimension;
|
||||||
@@ -373,6 +400,7 @@ function applyFilters(filters: ReportsViewFilters, keepView: boolean) {
|
|||||||
|
|
||||||
const afterRange = () => {
|
const afterRange = () => {
|
||||||
if (pageMode.value === 'builder') void runBuilder();
|
if (pageMode.value === 'builder') void runBuilder();
|
||||||
|
if (pageMode.value === 'leads') void loadLeads();
|
||||||
};
|
};
|
||||||
|
|
||||||
const p = PERIOD_KEYS.has(filters.period as PeriodKey)
|
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<ReportsLeadsAnalyticsDto>('/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) {
|
function setPageMode(mode: PageMode) {
|
||||||
pageMode.value = mode;
|
pageMode.value = mode;
|
||||||
if (mode === 'builder' && !builderResult.value) void runBuilder();
|
if (mode === 'builder' && !builderResult.value) void runBuilder();
|
||||||
if (mode === 'dashboard' && !data.value) void load();
|
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<UiChartOption>(() => {
|
const builderChartOption = computed<UiChartOption>(() => {
|
||||||
const rows = (builderResult.value?.rows ?? []).slice(0, 12);
|
const rows = (builderResult.value?.rows ?? []).slice(0, 12);
|
||||||
const isMoney = builderResult.value?.format === 'money';
|
const isMoney = builderResult.value?.format === 'money';
|
||||||
@@ -705,6 +767,47 @@ function exportReport() {
|
|||||||
return;
|
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;
|
if (!data.value) return;
|
||||||
const d = data.value;
|
const d = data.value;
|
||||||
const lines: string[] = [
|
const lines: string[] = [
|
||||||
@@ -1185,7 +1288,13 @@ const activityMax = computed(() =>
|
|||||||
</UiButton>
|
</UiButton>
|
||||||
<UiButton
|
<UiButton
|
||||||
variant="primary"
|
variant="primary"
|
||||||
:disabled="pageMode === 'dashboard' ? !data : !builderResult"
|
:disabled="
|
||||||
|
pageMode === 'dashboard'
|
||||||
|
? !data
|
||||||
|
: pageMode === 'leads'
|
||||||
|
? !leadsData
|
||||||
|
: !builderResult
|
||||||
|
"
|
||||||
@click="exportReport"
|
@click="exportReport"
|
||||||
>
|
>
|
||||||
<UiIcon name="document" :size="16" />
|
<UiIcon name="document" :size="16" />
|
||||||
@@ -1211,6 +1320,14 @@ const activityMax = computed(() =>
|
|||||||
>
|
>
|
||||||
گزارشساز
|
گزارشساز
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="mode-tab"
|
||||||
|
:class="{ on: pageMode === 'leads' }"
|
||||||
|
@click="setPageMode('leads')"
|
||||||
|
>
|
||||||
|
گزارش لیدها
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Toolbar Filters -->
|
<!-- Toolbar Filters -->
|
||||||
@@ -1270,12 +1387,17 @@ const activityMax = computed(() =>
|
|||||||
syncViewQuery(null);
|
syncViewQuery(null);
|
||||||
load().then(() => {
|
load().then(() => {
|
||||||
if (pageMode === 'builder') runBuilder();
|
if (pageMode === 'builder') runBuilder();
|
||||||
|
if (pageMode === 'leads') loadLeads();
|
||||||
});
|
});
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<JalaliDateInput v-model="from" placeholder="از تاریخ" />
|
<JalaliDateInput v-model="from" placeholder="از تاریخ" />
|
||||||
<JalaliDateInput v-model="to" placeholder="تا تاریخ" />
|
<JalaliDateInput v-model="to" placeholder="تا تاریخ" />
|
||||||
<UiButton variant="primary" type="submit" :disabled="loading || builderLoading">
|
<UiButton
|
||||||
|
variant="primary"
|
||||||
|
type="submit"
|
||||||
|
:disabled="loading || builderLoading || leadsLoading"
|
||||||
|
>
|
||||||
اعمال
|
اعمال
|
||||||
</UiButton>
|
</UiButton>
|
||||||
</form>
|
</form>
|
||||||
@@ -1286,13 +1408,14 @@ const activityMax = computed(() =>
|
|||||||
<template v-if="pageMode === 'builder'">
|
<template v-if="pageMode === 'builder'">
|
||||||
<UiCard class="builder-card" title="گزارشساز ساده">
|
<UiCard class="builder-card" title="گزارشساز ساده">
|
||||||
<p class="deep-hint">
|
<p class="deep-hint">
|
||||||
متریک و بُعد را انتخاب کنید؛ میتوانید بازه بالا و فیلتر کاربر/تیم را هم اعمال کنید.
|
متریک و بُعد را انتخاب کنید (شامل متریکهای لید). میتوانید بازه بالا و فیلتر کاربر/تیم را هم
|
||||||
|
اعمال کنید.
|
||||||
</p>
|
</p>
|
||||||
<div class="builder-form">
|
<div class="builder-form">
|
||||||
<UiField label="متریک">
|
<UiField label="متریک">
|
||||||
<select v-model="builderMetric" class="builder-select">
|
<select v-model="builderMetric" class="builder-select">
|
||||||
<option
|
<option
|
||||||
v-for="m in REPORTS_BUILDER_METRICS"
|
v-for="m in builderMetricOptions"
|
||||||
:key="m"
|
:key="m"
|
||||||
:value="m"
|
:value="m"
|
||||||
>
|
>
|
||||||
@@ -1303,7 +1426,7 @@ const activityMax = computed(() =>
|
|||||||
<UiField label="گروهبندی (بُعد)">
|
<UiField label="گروهبندی (بُعد)">
|
||||||
<select v-model="builderDimension" class="builder-select">
|
<select v-model="builderDimension" class="builder-select">
|
||||||
<option
|
<option
|
||||||
v-for="d in REPORTS_BUILDER_DIMENSIONS"
|
v-for="d in builderDimensionOptions"
|
||||||
:key="d"
|
:key="d"
|
||||||
:value="d"
|
:value="d"
|
||||||
>
|
>
|
||||||
@@ -1403,6 +1526,135 @@ const activityMax = computed(() =>
|
|||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- Leads analytics -->
|
||||||
|
<template v-else-if="pageMode === 'leads'">
|
||||||
|
<p v-if="leadsError" class="error">{{ leadsError }}</p>
|
||||||
|
<div v-if="leadsLoading" class="loading-wrap">
|
||||||
|
<div class="spinner"></div>
|
||||||
|
<span>در حال بارگذاری گزارش لیدها...</span>
|
||||||
|
</div>
|
||||||
|
<template v-else-if="leadsData">
|
||||||
|
<div class="kpis">
|
||||||
|
<article class="kpi-card">
|
||||||
|
<div class="kpi-top"><span class="kpi-label">ایجادشده در بازه</span></div>
|
||||||
|
<strong class="kpi-val">{{ num(leadsData.created) }}</strong>
|
||||||
|
</article>
|
||||||
|
<article class="kpi-card">
|
||||||
|
<div class="kpi-top"><span class="kpi-label">تبدیلشده</span></div>
|
||||||
|
<strong class="kpi-val">{{ num(leadsData.converted) }}</strong>
|
||||||
|
</article>
|
||||||
|
<article class="kpi-card">
|
||||||
|
<div class="kpi-top"><span class="kpi-label">ازدسترفته</span></div>
|
||||||
|
<strong class="kpi-val">{{ num(leadsData.lost) }}</strong>
|
||||||
|
</article>
|
||||||
|
<article class="kpi-card">
|
||||||
|
<div class="kpi-top"><span class="kpi-label">فعال فعلی</span></div>
|
||||||
|
<strong class="kpi-val">{{ num(leadsData.active) }}</strong>
|
||||||
|
</article>
|
||||||
|
<article class="kpi-card">
|
||||||
|
<div class="kpi-top"><span class="kpi-label">نرخ تبدیل بسته</span></div>
|
||||||
|
<strong class="kpi-val">{{ toFaDigits(leadsData.conversionRate) }}٪</strong>
|
||||||
|
<div class="kpi-change flat"><small>تبدیل ÷ (تبدیل + ازدسترفته)</small></div>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="charts-grid">
|
||||||
|
<UiCard class="chart-card span-2" title="قیف ستونهای لید (فعال فعلی)">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="crm-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ستون</th>
|
||||||
|
<th>تعداد</th>
|
||||||
|
<th>سهم</th>
|
||||||
|
<th>نسبت به قبلی</th>
|
||||||
|
<th>میانگین ماندن (ساعت)</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="row in leadsData.funnel" :key="row.stageId">
|
||||||
|
<td>{{ row.stageName }}</td>
|
||||||
|
<td>{{ num(row.count) }}</td>
|
||||||
|
<td>{{ toFaDigits(row.sharePercent) }}٪</td>
|
||||||
|
<td>
|
||||||
|
{{
|
||||||
|
row.conversionFromPrevPercent == null
|
||||||
|
? '—'
|
||||||
|
: `${toFaDigits(row.conversionFromPrevPercent)}٪`
|
||||||
|
}}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{
|
||||||
|
row.avgDwellHours == null
|
||||||
|
? '—'
|
||||||
|
: toFaDigits(row.avgDwellHours)
|
||||||
|
}}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</UiCard>
|
||||||
|
|
||||||
|
<UiCard class="chart-card span-2" title="تبدیل بینمرحلهای در بازه">
|
||||||
|
<p class="deep-hint">
|
||||||
|
بر اساس جابهجاییهای ثبتشده (از → به). برای دادهٔ قدیمی بدون meta ممکن است خالی باشد.
|
||||||
|
</p>
|
||||||
|
<div v-if="!leadsData.transitions.length" class="deep-hint">
|
||||||
|
انتقالی در این بازه ثبت نشده است.
|
||||||
|
</div>
|
||||||
|
<div v-else class="table-wrap">
|
||||||
|
<table class="crm-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>از</th>
|
||||||
|
<th>به</th>
|
||||||
|
<th>تعداد</th>
|
||||||
|
<th>٪ از خروجی مبدأ</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
v-for="(row, idx) in leadsData.transitions"
|
||||||
|
:key="`${row.fromStageId}-${row.toStageId}-${idx}`"
|
||||||
|
>
|
||||||
|
<td>{{ row.fromStageName }}</td>
|
||||||
|
<td>{{ row.toStageName }}</td>
|
||||||
|
<td>{{ num(row.count) }}</td>
|
||||||
|
<td>{{ toFaDigits(row.conversionPercent) }}٪</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</UiCard>
|
||||||
|
|
||||||
|
<UiCard class="chart-card span-2" title="میانگین زمان ماندن در هر ستون">
|
||||||
|
<div v-if="!leadsData.dwellByStage.length" class="deep-hint">
|
||||||
|
نمونهٔ کافی برای محاسبهٔ ماندگاری نیست.
|
||||||
|
</div>
|
||||||
|
<div v-else class="table-wrap">
|
||||||
|
<table class="crm-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ستون</th>
|
||||||
|
<th>میانگین ساعت</th>
|
||||||
|
<th>تعداد نمونه</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="row in leadsData.dwellByStage" :key="row.stageId">
|
||||||
|
<td>{{ row.stageName }}</td>
|
||||||
|
<td>{{ toFaDigits(row.avgHours) }}</td>
|
||||||
|
<td>{{ num(row.sampleCount) }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</UiCard>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Dashboard mode -->
|
<!-- Dashboard mode -->
|
||||||
<div v-else-if="loading" class="loading-wrap">
|
<div v-else-if="loading" class="loading-wrap">
|
||||||
<div class="spinner"></div>
|
<div class="spinner"></div>
|
||||||
|
|||||||
@@ -5387,7 +5387,7 @@ export interface ReportsViewFilters {
|
|||||||
period: string;
|
period: string;
|
||||||
from?: string;
|
from?: string;
|
||||||
to?: string;
|
to?: string;
|
||||||
/** dashboard | builder */
|
/** dashboard | builder | leads */
|
||||||
mode?: string;
|
mode?: string;
|
||||||
builder?: {
|
builder?: {
|
||||||
metric?: string;
|
metric?: string;
|
||||||
@@ -5407,7 +5407,12 @@ export type ReportsBuilderMetric =
|
|||||||
| "activities_done"
|
| "activities_done"
|
||||||
| "people_created"
|
| "people_created"
|
||||||
| "invoice_amount"
|
| "invoice_amount"
|
||||||
| "invoice_count";
|
| "invoice_count"
|
||||||
|
| "leads_created"
|
||||||
|
| "leads_converted"
|
||||||
|
| "leads_lost"
|
||||||
|
| "leads_active"
|
||||||
|
| "leads_avg_dwell_hours";
|
||||||
|
|
||||||
export const REPORTS_BUILDER_METRICS: ReportsBuilderMetric[] = [
|
export const REPORTS_BUILDER_METRICS: ReportsBuilderMetric[] = [
|
||||||
"won_amount",
|
"won_amount",
|
||||||
@@ -5419,6 +5424,11 @@ export const REPORTS_BUILDER_METRICS: ReportsBuilderMetric[] = [
|
|||||||
"people_created",
|
"people_created",
|
||||||
"invoice_amount",
|
"invoice_amount",
|
||||||
"invoice_count",
|
"invoice_count",
|
||||||
|
"leads_created",
|
||||||
|
"leads_converted",
|
||||||
|
"leads_lost",
|
||||||
|
"leads_active",
|
||||||
|
"leads_avg_dwell_hours",
|
||||||
];
|
];
|
||||||
|
|
||||||
export const REPORTS_BUILDER_METRIC_LABELS: Record<
|
export const REPORTS_BUILDER_METRIC_LABELS: Record<
|
||||||
@@ -5434,6 +5444,11 @@ export const REPORTS_BUILDER_METRIC_LABELS: Record<
|
|||||||
people_created: "مشتریان جدید",
|
people_created: "مشتریان جدید",
|
||||||
invoice_amount: "مبلغ فاکتور",
|
invoice_amount: "مبلغ فاکتور",
|
||||||
invoice_count: "تعداد فاکتور",
|
invoice_count: "تعداد فاکتور",
|
||||||
|
leads_created: "لیدهای ایجادشده",
|
||||||
|
leads_converted: "لیدهای تبدیلشده",
|
||||||
|
leads_lost: "لیدهای ازدسترفته",
|
||||||
|
leads_active: "لیدهای فعال (فعلی)",
|
||||||
|
leads_avg_dwell_hours: "میانگین ماندن در مرحله لید (ساعت)",
|
||||||
};
|
};
|
||||||
|
|
||||||
/** ابعاد گروهبندی گزارشساز */
|
/** ابعاد گروهبندی گزارشساز */
|
||||||
@@ -5443,6 +5458,7 @@ export type ReportsBuilderDimension =
|
|||||||
| "team"
|
| "team"
|
||||||
| "source"
|
| "source"
|
||||||
| "stage"
|
| "stage"
|
||||||
|
| "lead_stage"
|
||||||
| "month"
|
| "month"
|
||||||
| "status";
|
| "status";
|
||||||
|
|
||||||
@@ -5452,6 +5468,7 @@ export const REPORTS_BUILDER_DIMENSIONS: ReportsBuilderDimension[] = [
|
|||||||
"team",
|
"team",
|
||||||
"source",
|
"source",
|
||||||
"stage",
|
"stage",
|
||||||
|
"lead_stage",
|
||||||
"month",
|
"month",
|
||||||
"status",
|
"status",
|
||||||
];
|
];
|
||||||
@@ -5465,10 +5482,26 @@ export const REPORTS_BUILDER_DIMENSION_LABELS: Record<
|
|||||||
team: "تیم",
|
team: "تیم",
|
||||||
source: "منبع",
|
source: "منبع",
|
||||||
stage: "مرحله مسیر فروش",
|
stage: "مرحله مسیر فروش",
|
||||||
|
lead_stage: "مرحله / ستون لید",
|
||||||
month: "ماه",
|
month: "ماه",
|
||||||
status: "وضعیت معامله",
|
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 {
|
export interface ReportsBuilderQuery {
|
||||||
metric: ReportsBuilderMetric;
|
metric: ReportsBuilderMetric;
|
||||||
dimension: ReportsBuilderDimension;
|
dimension: ReportsBuilderDimension;
|
||||||
@@ -5484,6 +5517,48 @@ export interface ReportsBuilderRowDto {
|
|||||||
value: number;
|
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 {
|
export interface ReportsBuilderResultDto {
|
||||||
metric: ReportsBuilderMetric;
|
metric: ReportsBuilderMetric;
|
||||||
metricLabel: string;
|
metricLabel: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user