Speed up lead board load and polish lead detail/list UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-19 12:08:45 +03:30
co-authored by Cursor
parent dbb61ff870
commit e90f9f9538
8 changed files with 225 additions and 90 deletions
@@ -595,7 +595,9 @@ export class LeadFormsService {
}; };
} }
const stages = await this.leadStages.list(form.organizationId); const stages = await this.leadStages.list(form.organizationId, {
withLeadCounts: false,
});
const stageId = const stageId =
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) || (form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id || stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
+16 -8
View File
@@ -43,18 +43,26 @@ export class LeadStagesService {
}); });
} }
async list(organizationId: string): Promise<LeadStageDto[]> { async list(
organizationId: string,
opts: { withLeadCounts?: boolean } = {},
): Promise<LeadStageDto[]> {
const withLeadCounts = opts.withLeadCounts !== false;
await this.ensureDefaults(organizationId); await this.ensureDefaults(organizationId);
const rows = await this.prisma.leadStage.findMany({ const rows = await this.prisma.leadStage.findMany({
where: { organizationId }, where: { organizationId },
orderBy: { position: 'asc' }, orderBy: { position: 'asc' },
include: { ...(withLeadCounts
_count: { ? {
select: { include: {
leads: { where: { archivedAt: null } }, _count: {
}, select: {
}, leads: { where: { archivedAt: null } },
}, },
},
},
}
: {}),
}); });
return rows.map((r) => this.toDto(r)); return rows.map((r) => this.toDto(r));
} }
+3 -1
View File
@@ -181,7 +181,9 @@ export class LeadsImportService {
const job = await this.prisma.leadImportJob.findUnique({ where: { id } }); const job = await this.prisma.leadImportJob.findUnique({ where: { id } });
if (!job) return; if (!job) return;
const stages = await this.stages.list(job.organizationId); const stages = await this.stages.list(job.organizationId, {
withLeadCounts: false,
});
const defaultStageId = stages[0]?.id; const defaultStageId = stages[0]?.id;
if (!defaultStageId) { if (!defaultStageId) {
await this.prisma.leadImportJob.update({ await this.prisma.leadImportJob.update({
+7 -2
View File
@@ -70,8 +70,13 @@ export class LeadsController {
} }
@Get('stages') @Get('stages')
listStages(@CurrentUser() user: Actor) { listStages(
return this.stages.list(user.organizationId); @CurrentUser() user: Actor,
@Query('counts') counts?: string,
) {
return this.stages.list(user.organizationId, {
withLeadCounts: counts !== '0' && counts !== 'false',
});
} }
@Post('stages') @Post('stages')
+125 -23
View File
@@ -104,7 +104,38 @@ const leadInclude = {
assignee: { select: { id: true, fullName: true } }, assignee: { select: { id: true, fullName: true } },
} as const; } as const;
/** فیلدهای لازم برای کارت مسیر لیدها — بدون notes/addresses حجیم و بدون join مرحله */
const boardLeadSelect = {
id: true,
title: true,
contactName: true,
gender: true,
showGenderInName: true,
mobile: true,
phone: true,
city: true,
region: true,
instagram: true,
birthDate: true,
trade: true,
source: true,
logoStorageKey: true,
estimatedValue: true,
stageId: true,
position: true,
assigneeId: true,
lastContactAt: true,
nextFollowUpAt: true,
convertedPersonId: true,
convertedAt: true,
archivedAt: true,
createdAt: true,
updatedAt: true,
assignee: { select: { id: true, fullName: true } },
} as const;
type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>; type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>;
type BoardLeadRow = Prisma.LeadGetPayload<{ select: typeof boardLeadSelect }>;
@Injectable() @Injectable()
export class LeadsService { export class LeadsService {
@@ -338,33 +369,56 @@ export class LeadsService {
} }
async board(actor: Actor): Promise<LeadBoardColumnDto[]> { async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
const stages = await this.stages.list(actor.organizationId); // بدون شمارش لید روی هر مرحله — شمارش را یک‌بار با groupBy می‌گیریم
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const boardStages = stages.filter((s) => s.showOnBoard); const boardStages = stages.filter((s) => s.showOnBoard);
const whereBase = { if (!boardStages.length) return [];
const access = leadAccessWhere(actor);
const stageIds = boardStages.map((s) => s.id);
const whereBase: Prisma.LeadWhereInput = {
organizationId: actor.organizationId, organizationId: actor.organizationId,
...leadAccessWhere(actor), ...access,
archivedAt: null, archivedAt: null,
stageId: { in: stageIds },
}; };
const perColumn = 120; const perColumn = 120;
return Promise.all(
boardStages.map(async (stage) => { const [counts, ...columnRows] = await Promise.all([
const where = { ...whereBase, stageId: stage.id }; this.prisma.lead.groupBy({
const [total, rows] = await Promise.all([ by: ['stageId'],
this.prisma.lead.count({ where }), where: whereBase,
this.prisma.lead.findMany({ _count: { _all: true },
where,
include: leadInclude,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
]);
return {
stage,
total,
leads: rows.map((row) => this.toDto(row)),
};
}), }),
...boardStages.map((stage) =>
this.prisma.lead.findMany({
where: {
organizationId: actor.organizationId,
...access,
archivedAt: null,
stageId: stage.id,
},
// کارت بورد به join مرحله نیاز ندارد؛ اسم مرحله را از ستون می‌گذاریم
select: boardLeadSelect,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
),
]);
const totalByStage = new Map(
counts.map((row) => [row.stageId, row._count._all]),
); );
return boardStages.map((stage, index) => ({
stage,
total: totalByStage.get(stage.id) ?? 0,
leads: (columnRows[index] ?? []).map((row) =>
this.toBoardDto(row, stage.name),
),
}));
} }
async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> { async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> {
@@ -459,7 +513,9 @@ export class LeadsService {
); );
} }
const stages = await this.stages.list(actor.organizationId); const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const stageId = dto.stageId || stages[0]?.id; const stageId = dto.stageId || stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده'); if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -1232,7 +1288,9 @@ export class LeadsService {
...leadAccessWhere(actor), ...leadAccessWhere(actor),
archivedAt: null, archivedAt: null,
}; };
const stages = await this.stages.list(actor.organizationId); const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id); const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
const lostIds = stages.filter((s) => s.isLost).map((s) => s.id); const lostIds = stages.filter((s) => s.isLost).map((s) => s.id);
// همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید» // همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید»
@@ -1374,7 +1432,9 @@ export class LeadsService {
} }
await this.stages.ensureDefaults(input.organizationId); await this.stages.ensureDefaults(input.organizationId);
const stages = await this.stages.list(input.organizationId); const stages = await this.stages.list(input.organizationId, {
withLeadCounts: false,
});
const stageId = stages[0]?.id; const stageId = stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده'); if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -1586,6 +1646,48 @@ export class LeadsService {
}; };
} }
private toBoardDto(row: BoardLeadRow, stageName: string): LeadDto {
const daysInStage = Math.max(
0,
Math.floor(
(Date.now() - row.updatedAt.getTime()) / (24 * 60 * 60 * 1000),
),
);
return {
id: row.id,
title: row.title,
contactName: row.contactName,
gender: row.gender === 'male' || row.gender === 'female' ? row.gender : 'none',
showGenderInName: row.showGenderInName,
mobile: row.mobile,
phone: row.phone,
city: row.city,
region: row.region,
instagram: row.instagram,
birthDate: row.birthDate?.toISOString() ?? null,
addresses: [],
trade: row.trade,
source: row.source,
notes: null,
estimatedValue:
row.estimatedValue != null ? Number(row.estimatedValue) : null,
stageId: row.stageId,
stageName,
position: row.position,
assigneeId: row.assigneeId,
assigneeName: row.assignee?.fullName ?? null,
lastContactAt: row.lastContactAt?.toISOString() ?? null,
nextFollowUpAt: row.nextFollowUpAt?.toISOString() ?? null,
convertedPersonId: row.convertedPersonId,
convertedAt: row.convertedAt?.toISOString() ?? null,
archivedAt: row.archivedAt?.toISOString() ?? null,
daysInStage,
hasLogo: Boolean(row.logoStorageKey),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
async saveLogo( async saveLogo(
actor: Actor, actor: Actor,
id: string, id: string,
+5 -4
View File
@@ -212,7 +212,8 @@ async function load() {
try { try {
const [board, stageRows] = await Promise.all([ const [board, stageRows] = await Promise.all([
api.get<LeadBoardColumnDto[]>('/leads/board'), api.get<LeadBoardColumnDto[]>('/leads/board'),
api.get<LeadStageDto[]>('/leads/stages'), // بدون شمارش لید روی هر مرحله — total ستون‌ها از خود board می‌آید
api.get<LeadStageDto[]>('/leads/stages', { params: { counts: '0' } }),
]); ]);
columns.value = board.data; columns.value = board.data;
stages.value = stageRows.data; stages.value = stageRows.data;
@@ -614,7 +615,7 @@ async function confirmPendingLeadMove() {
if (!pending || moving.value) return Promise.reject(); if (!pending || moving.value) return Promise.reject();
const reason = stageMoveReason.value.trim(); const reason = stageMoveReason.value.trim();
if (!reason) { if (!reason) {
stageMoveError.value = 'دلیل تغییر ستون را بنویسید.'; stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.';
return Promise.reject(); return Promise.reject();
} }
columns.value = pending.nextColumns; columns.value = pending.nextColumns;
@@ -1037,7 +1038,7 @@ onMounted(load);
<a-modal <a-modal
:open="!!pendingLeadMove" :open="!!pendingLeadMove"
title="دلیل تغییر ستون" title="دلیل تغییر وضعیت"
ok-text="ثبت و انتقال" ok-text="ثبت و انتقال"
cancel-text="انصراف" cancel-text="انصراف"
:confirm-loading="moving" :confirm-loading="moving"
@@ -1054,7 +1055,7 @@ onMounted(load);
:rows="4" :rows="4"
:maxlength="1000" :maxlength="1000"
show-count show-count
placeholder="دلیل تغییر ستون را بنویسید…" placeholder="دلیل تغییر وضعیت را بنویسید…"
/> />
<a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" /> <a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" />
</a-flex> </a-flex>
+59 -47
View File
@@ -22,7 +22,7 @@ import {
List as AList, List as AList,
ListItem as AListItem, ListItem as AListItem,
ListItemMeta as AListItemMeta, ListItemMeta as AListItemMeta,
Modal, Modal as AModal,
Row as ARow, Row as ARow,
Select as ASelect, Select as ASelect,
Space as ASpace, Space as ASpace,
@@ -87,6 +87,18 @@ const canBehavior = computed(() => canUseBehavior(auth.user));
const copilotOpen = ref(false); const copilotOpen = ref(false);
const id = computed(() => String(route.params.id)); const id = computed(() => String(route.params.id));
/** برگشت به همان جایی که از آن آمده‌ایم (فهرست یا مسیر/بورد لیدها). */
function goBack() {
const back = String((window.history.state as { back?: string | null } | null)?.back ?? '');
const path = back.split('?')[0];
if (path === '/leads' || path === '/leads/board') {
router.back();
return;
}
void router.push({ name: 'leads' });
}
const loading = ref(false); const loading = ref(false);
const busy = ref(false); const busy = ref(false);
const error = ref(''); const error = ref('');
@@ -293,7 +305,7 @@ async function changeStage() {
} }
const reason = stageMoveReason.value.trim(); const reason = stageMoveReason.value.trim();
if (!reason) { if (!reason) {
stageMoveError.value = 'دلیل تغییر ستون را بنویسید.'; stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.';
return Promise.reject(); return Promise.reject();
} }
busy.value = true; busy.value = true;
@@ -411,7 +423,7 @@ async function setFollowUp() {
} }
function convertLead() { function convertLead() {
Modal.confirm({ AModal.confirm({
title: 'این لید به مشتری تبدیل شود؟', title: 'این لید به مشتری تبدیل شود؟',
okText: 'تبدیل', okText: 'تبدیل',
cancelText: 'انصراف', cancelText: 'انصراف',
@@ -440,7 +452,7 @@ function convertLead() {
} }
function archiveLead() { function archiveLead() {
Modal.confirm({ AModal.confirm({
title: 'این لید بایگانی شود؟', title: 'این لید بایگانی شود؟',
okText: 'بایگانی', okText: 'بایگانی',
cancelText: 'انصراف', cancelText: 'انصراف',
@@ -534,11 +546,9 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
<a-col :span="24"> <a-col :span="24">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="token.marginSM"> <a-flex justify="space-between" align="center" wrap="wrap" :gap="token.marginSM">
<a-space :size="12" align="start"> <a-space :size="12" align="start">
<RouterLink :to="{ name: 'leads-board' }" custom v-slot="{ navigate }"> <a-button aria-label="بازگشت" @click="goBack">
<a-button @click="navigate"> <template #icon><ArrowLeftOutlined /></template>
<template #icon><ArrowLeftOutlined /></template> </a-button>
</a-button>
</RouterLink>
<div> <div>
<a-typography-title :level="3" :style="{ margin: 0 }"> <a-typography-title :level="3" :style="{ margin: 0 }">
{{ lead?.title || 'جزئیات لید' }} {{ lead?.title || 'جزئیات لید' }}
@@ -1219,45 +1229,47 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
</a-button> </a-button>
</a-form> </a-form>
</a-drawer> </a-drawer>
</template>
<a-modal
v-model:open="stageMoveOpen"
title="دلیل تغییر ستون"
ok-text="ثبت و انتقال"
cancel-text="انصراف"
:confirm-loading="busy"
:ok-button-props="{ disabled: !stageMoveReason.trim() }"
@ok="changeStage"
@cancel="cancelStageMove"
>
<a-flex vertical :gap="12">
<a-typography-text type="secondary">
انتقال به «{{ stages.find((s) => s.id === stageId)?.name || '—' }}»
</a-typography-text>
<a-textarea
v-model:value="stageMoveReason"
:rows="4"
:maxlength="1000"
show-count
placeholder="دلیل تغییر ستون را بنویسید…"
/>
<a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" />
</a-flex>
</a-modal>
<SmsComposeModal
:open="smsOpen"
title="ارسال پیامک"
:endpoint="`/leads/${lead.id}/sms`"
:history-endpoint="`/leads/${lead.id}/sms-history`"
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template>
</a-spin> </a-spin>
</a-col> </a-col>
</a-row> </a-row>
<a-modal
v-model:open="stageMoveOpen"
title="دلیل تغییر وضعیت"
ok-text="ثبت و انتقال"
cancel-text="انصراف"
destroy-on-close
:confirm-loading="busy"
:ok-button-props="{ disabled: !stageMoveReason.trim() }"
@ok="changeStage"
@cancel="cancelStageMove"
>
<a-flex vertical :gap="12">
<a-typography-text type="secondary">
انتقال از «{{ lead?.stageName || '—' }}» به «{{ stages.find((s) => s.id === stageId)?.name || '—' }}»
</a-typography-text>
<a-textarea
v-model:value="stageMoveReason"
:rows="4"
:maxlength="1000"
show-count
placeholder="دلیل تغییر وضعیت را بنویسید…"
/>
<a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" />
</a-flex>
</a-modal>
<SmsComposeModal
v-if="lead"
:open="smsOpen"
title="ارسال پیامک"
:endpoint="`/leads/${lead.id}/sms`"
:history-endpoint="`/leads/${lead.id}/sms-history`"
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template> </template>
+7 -4
View File
@@ -1293,7 +1293,7 @@ async function bulkStageSelected() {
if (!bulkStageId.value || !selectedIds.value.length) return Promise.reject(); if (!bulkStageId.value || !selectedIds.value.length) return Promise.reject();
const reason = bulkStageReason.value.trim(); const reason = bulkStageReason.value.trim();
if (!reason) { if (!reason) {
bulkStageReasonError.value = 'دلیل تغییر ستون را بنویسید.'; bulkStageReasonError.value = 'دلیل تغییر وضعیت را بنویسید.';
return Promise.reject(); return Promise.reject();
} }
busy.value = true; busy.value = true;
@@ -2194,7 +2194,10 @@ onBeforeUnmount(() => {
:pagination="false" :pagination="false"
:row-key="(r: LeadDto) => r.id" :row-key="(r: LeadDto) => r.id"
:scroll="{ x: 1100 }" :scroll="{ x: 1100 }"
:custom-row="(record: LeadDto) => ({ onClick: () => goDetail(record.id) })" :custom-row="(record: LeadDto) => ({
onClick: () => goDetail(record.id),
style: { cursor: 'pointer' },
})"
> >
<template #bodyCell="{ column, record }"> <template #bodyCell="{ column, record }">
<template v-if="column.key === 'select'"> <template v-if="column.key === 'select'">
@@ -2535,7 +2538,7 @@ onBeforeUnmount(() => {
<a-modal <a-modal
v-model:open="bulkStageReasonOpen" v-model:open="bulkStageReasonOpen"
title="دلیل تغییر ستون" title="دلیل تغییر وضعیت"
ok-text="ثبت و انتقال" ok-text="ثبت و انتقال"
cancel-text="انصراف" cancel-text="انصراف"
:confirm-loading="busy" :confirm-loading="busy"
@@ -2553,7 +2556,7 @@ onBeforeUnmount(() => {
:rows="4" :rows="4"
:maxlength="1000" :maxlength="1000"
show-count show-count
placeholder="دلیل تغییر ستون را بنویسید…" placeholder="دلیل تغییر وضعیت را بنویسید…"
/> />
<a-alert <a-alert
v-if="bulkStageReasonError" v-if="bulkStageReasonError"