348 lines
12 KiB
TypeScript
348 lines
12 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import type { DealStatus, ImportContactsResult } from '@mento/shared';
|
|
import { Prisma } from '@prisma/client';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import type { Actor } from '../common/record-scope';
|
|
import { dealAccessWhere, resolveOwnerId } from '../common/record-scope';
|
|
import { toJsonCustomFields } from '../common/custom-fields';
|
|
import { normalizePhone } from '../contacts/normalize';
|
|
import {
|
|
excelFieldsFromColumns,
|
|
formatJalaliDate,
|
|
parseAmount,
|
|
parseExcelMapping,
|
|
parseJalaliDateTime,
|
|
previewExcel,
|
|
readMappedRows,
|
|
writeXlsx,
|
|
type ExcelPreviewResult,
|
|
} from '../common/excel';
|
|
import {
|
|
chunkImportMeta,
|
|
resolveExcelImportChunk,
|
|
} from '../common/excel-import-session';
|
|
import { PipelinesService } from './pipelines.service';
|
|
|
|
const DEAL_COLUMNS = [
|
|
{ header: '_type', key: '_type', width: 12 },
|
|
{ header: 'کد دیدار معامله', key: 'didarId', width: 16 },
|
|
{ header: 'عنوان معامله', key: 'title', width: 28 },
|
|
{ header: 'مبلغ معامله', key: 'amount', width: 16 },
|
|
{ header: 'ارز معامله', key: 'currency', width: 12 },
|
|
{ header: 'وضعیت معامله', key: 'status', width: 14 },
|
|
{ header: 'مسئول معامله', key: 'ownerName', width: 18 },
|
|
{ header: 'مجوز مشاهده معامله', key: 'visibility', width: 18 },
|
|
{ header: 'تاریخ ثبت معامله', key: 'createdAt', width: 16 },
|
|
{ header: 'نام خانوادگی شخص معامله', key: 'personName', width: 22 },
|
|
{ header: 'کد دیدار شخص', key: 'personCode', width: 14 },
|
|
{ header: 'موبایل شخص معامله', key: 'personMobile', width: 16 },
|
|
{ header: 'نام شرکت معامله', key: 'companyName', width: 22 },
|
|
{ header: 'کاریز معامله', key: 'pipelineName', width: 20 },
|
|
{ header: 'مرحله کاریز معامله', key: 'stageName', width: 18 },
|
|
{ header: 'تاریخ انجام معامله', key: 'expectedCloseAt', width: 16 },
|
|
{ header: 'منبع معامله', key: 'source', width: 16 },
|
|
{ header: 'توضیحات معامله', key: 'notes', width: 32 },
|
|
{ header: 'برچسب', key: 'tags', width: 16 },
|
|
];
|
|
|
|
const DEAL_ALIASES: Record<string, string> = {
|
|
_type: '_type',
|
|
type: '_type',
|
|
کددیدارمعامله: 'didarId',
|
|
عنوانمعامله: 'title',
|
|
عنوان: 'title',
|
|
مبلغمعامله: 'amount',
|
|
مبلغ: 'amount',
|
|
ارزمعامله: 'currency',
|
|
ارز: 'currency',
|
|
وضعیتمعامله: 'status',
|
|
مسئولمعامله: 'ownerName',
|
|
مجوزمشاهدهمعامله: 'visibility',
|
|
تاریخثبتمعامله: 'createdAt',
|
|
نامخانوادگیشخصمعامله: 'personName',
|
|
کددیدارشخص: 'personCode',
|
|
موبایلشخصمعامله: 'personMobile',
|
|
نامشرکتمعامله: 'companyName',
|
|
شرکت: 'companyName',
|
|
کاریزمعامله: 'pipelineName',
|
|
کاریز: 'pipelineName',
|
|
مرحلهکاریزمعامله: 'stageName',
|
|
مرحله: 'stageName',
|
|
تاریخانجاممعامله: 'expectedCloseAt',
|
|
منبعمعامله: 'source',
|
|
منبع: 'source',
|
|
توضیحاتمعامله: 'notes',
|
|
توضیحات: 'notes',
|
|
برچسب: 'tags',
|
|
};
|
|
|
|
function statusLabel(status: DealStatus) {
|
|
if (status === 'won') return 'برنده';
|
|
if (status === 'lost') return 'از دسترفته';
|
|
return 'باز';
|
|
}
|
|
|
|
function parseStatus(raw?: string): DealStatus {
|
|
const v = (raw ?? '').trim();
|
|
if (/برنده|won|موفق/i.test(v)) return 'won';
|
|
if (/از\s*دست|باخت|lost|ناموفق/i.test(v)) return 'lost';
|
|
return 'open';
|
|
}
|
|
|
|
function parseTags(raw?: string) {
|
|
return (raw ?? '')
|
|
.split(/[،,|#]+/)
|
|
.map((t) => t.trim())
|
|
.filter(Boolean)
|
|
.slice(0, 20);
|
|
}
|
|
|
|
@Injectable()
|
|
export class DealsExcelService {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly pipelines: PipelinesService,
|
|
) {}
|
|
|
|
async export(actor: Actor): Promise<Buffer> {
|
|
const rows = await this.prisma.deal.findMany({
|
|
where: { organizationId: actor.organizationId, ...dealAccessWhere(actor) },
|
|
include: {
|
|
person: {
|
|
select: { id: true, firstName: true, lastName: true, mobile: true },
|
|
},
|
|
company: { select: { name: true } },
|
|
owner: { select: { fullName: true } },
|
|
pipeline: { select: { name: true } },
|
|
stage: { select: { name: true } },
|
|
},
|
|
orderBy: [{ updatedAt: 'desc' }],
|
|
take: 10000,
|
|
});
|
|
|
|
return writeXlsx(
|
|
'Deal',
|
|
DEAL_COLUMNS,
|
|
rows.map((row) => {
|
|
const extra = (row.customFields ?? {}) as Record<string, string>;
|
|
return {
|
|
_type: 'Deal',
|
|
didarId: extra.didarId ?? row.id,
|
|
title: row.title,
|
|
amount: row.amount == null ? '' : Number(row.amount),
|
|
currency: row.currency,
|
|
status: statusLabel(row.status),
|
|
ownerName: row.owner?.fullName ?? '',
|
|
visibility: 'همه افراد شرکت',
|
|
createdAt: formatJalaliDate(row.createdAt),
|
|
personName: row.person
|
|
? `${row.person.firstName} ${row.person.lastName}`.trim()
|
|
: '',
|
|
personCode: row.person?.id ?? '',
|
|
personMobile: row.person?.mobile ?? '',
|
|
companyName: row.company?.name ?? '',
|
|
pipelineName: row.pipeline.name,
|
|
stageName: row.stage.name,
|
|
expectedCloseAt: formatJalaliDate(row.expectedCloseAt),
|
|
source: row.source ?? '',
|
|
notes: row.notes ?? '',
|
|
tags: (row.tags ?? []).join('، '),
|
|
};
|
|
}),
|
|
);
|
|
}
|
|
|
|
preview(file: Express.Multer.File): Promise<ExcelPreviewResult> {
|
|
return previewExcel(file, DEAL_ALIASES, excelFieldsFromColumns(DEAL_COLUMNS, ['title']));
|
|
}
|
|
|
|
async import(
|
|
actor: Actor,
|
|
file: Express.Multer.File | undefined,
|
|
mappingRaw?: string,
|
|
chunk?: { sessionId?: string; offset?: string | number; limit?: string | number },
|
|
): Promise<ImportContactsResult> {
|
|
const ctx = await resolveExcelImportChunk({
|
|
organizationId: actor.organizationId,
|
|
file,
|
|
sessionId: chunk?.sessionId,
|
|
offset: chunk?.offset,
|
|
limit: chunk?.limit,
|
|
loadRows: () =>
|
|
readMappedRows(file!, DEAL_ALIASES, parseExcelMapping(mappingRaw)),
|
|
});
|
|
const result: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
|
const affected = new Map<string, string>();
|
|
|
|
for (let i = 0; i < ctx.slice.length; i++) {
|
|
const row = ctx.slice[i]!;
|
|
const rowNum = ctx.offset + i + 2;
|
|
if ((row._type || '').trim() && row._type.trim().toLowerCase() !== 'deal') {
|
|
continue;
|
|
}
|
|
const title = (row.title || '').trim();
|
|
if (title.length < 2) {
|
|
result.errors.push({ row: rowNum, message: 'عنوان معامله الزامی است' });
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
const status = parseStatus(row.status);
|
|
const { pipelineId, stageId, pipelineName } = await this.resolvePipelineAndStage(
|
|
actor.organizationId,
|
|
row.pipelineName,
|
|
row.stageName,
|
|
status,
|
|
);
|
|
affected.set(pipelineId, pipelineName);
|
|
|
|
const duplicate = await this.prisma.deal.findFirst({
|
|
where: { organizationId: actor.organizationId, pipelineId, title },
|
|
select: { id: true },
|
|
});
|
|
if (duplicate) {
|
|
result.skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
const personId = await this.findPersonId(actor.organizationId, row);
|
|
const companyId = await this.findCompanyId(actor.organizationId, row.companyName);
|
|
const ownerId =
|
|
(await this.findUserId(actor.organizationId, row.ownerName)) ??
|
|
resolveOwnerId(actor, null);
|
|
const amount = parseAmount(row.amount);
|
|
const expectedCloseAt = parseJalaliDateTime(row.expectedCloseAt);
|
|
const customFields: Record<string, string> = {};
|
|
if (row.didarId?.trim()) customFields.didarId = row.didarId.trim();
|
|
|
|
await this.prisma.deal.create({
|
|
data: {
|
|
organizationId: actor.organizationId,
|
|
pipelineId,
|
|
stageId,
|
|
title,
|
|
amount: amount == null ? null : new Prisma.Decimal(amount),
|
|
currency: (row.currency || 'IRR').trim() || 'IRR',
|
|
status,
|
|
source: row.source?.trim() || null,
|
|
notes: row.notes?.trim() || null,
|
|
tags: parseTags(row.tags),
|
|
customFields: toJsonCustomFields(customFields),
|
|
expectedCloseAt,
|
|
personId,
|
|
companyId,
|
|
ownerId,
|
|
},
|
|
});
|
|
result.created += 1;
|
|
} catch (e) {
|
|
result.errors.push({
|
|
row: rowNum,
|
|
message: e instanceof Error ? e.message : 'خطای ناشناخته',
|
|
});
|
|
}
|
|
}
|
|
|
|
const entries = [...affected.entries()];
|
|
if (entries[0]) {
|
|
result.boardId = entries[0][0];
|
|
result.boards = entries.map(([, n]) => n);
|
|
}
|
|
return { ...result, ...chunkImportMeta(ctx) };
|
|
}
|
|
|
|
private async resolvePipelineAndStage(
|
|
organizationId: string,
|
|
pipelineName?: string,
|
|
stageName?: string,
|
|
status: DealStatus = 'open',
|
|
) {
|
|
const name = pipelineName?.trim() || 'کاریز فروش';
|
|
const wanted = stageName?.trim();
|
|
let pipeline = await this.prisma.pipeline.findFirst({
|
|
where: { organizationId, name: { equals: name, mode: 'insensitive' } },
|
|
include: { stages: { orderBy: { position: 'asc' } } },
|
|
});
|
|
if (!pipeline) {
|
|
const created = await this.pipelines.create(organizationId, name);
|
|
pipeline = await this.prisma.pipeline.findFirstOrThrow({
|
|
where: { id: created.id },
|
|
include: { stages: { orderBy: { position: 'asc' } } },
|
|
});
|
|
}
|
|
|
|
if (wanted) {
|
|
const existing = pipeline.stages.find(
|
|
(s) => s.name.trim().toLowerCase() === wanted.toLowerCase(),
|
|
);
|
|
if (existing) {
|
|
return { pipelineId: pipeline.id, stageId: existing.id, pipelineName: pipeline.name };
|
|
}
|
|
const added = await this.pipelines.createStage(organizationId, pipeline.id, wanted);
|
|
const stage = added.stages.find((s) => s.name === wanted) ?? added.stages.at(-1);
|
|
if (!stage) throw new Error('کاریز مرحلهای ندارد');
|
|
return { pipelineId: pipeline.id, stageId: stage.id, pipelineName: pipeline.name };
|
|
}
|
|
|
|
const byStatus =
|
|
status === 'won'
|
|
? pipeline.stages.find((s) => s.isWon)
|
|
: status === 'lost'
|
|
? pipeline.stages.find((s) => s.isLost)
|
|
: pipeline.stages.find((s) => !s.isWon && !s.isLost);
|
|
const stage = byStatus ?? pipeline.stages[0];
|
|
if (!stage) throw new Error('کاریز مرحلهای ندارد');
|
|
return { pipelineId: pipeline.id, stageId: stage.id, pipelineName: pipeline.name };
|
|
}
|
|
|
|
private async findPersonId(organizationId: string, row: Record<string, string>) {
|
|
const mobile = normalizePhone(row.personMobile);
|
|
if (mobile) {
|
|
const needle = mobile.replace(/^\+98|^98|^0/, '');
|
|
const byMobile = await this.prisma.person.findFirst({
|
|
where: { organizationId, mobile: { contains: needle } },
|
|
select: { id: true },
|
|
});
|
|
if (byMobile) return byMobile.id;
|
|
}
|
|
const name = (row.personName ?? '').trim();
|
|
if (name) {
|
|
const byName = await this.prisma.person.findFirst({
|
|
where: {
|
|
organizationId,
|
|
OR: [
|
|
{ lastName: { contains: name, mode: 'insensitive' } },
|
|
{ firstName: { contains: name.split(/\s+/)[0]!, mode: 'insensitive' } },
|
|
],
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (byName) return byName.id;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private async findCompanyId(organizationId: string, name?: string) {
|
|
const n = name?.trim();
|
|
if (!n) return null;
|
|
const row = await this.prisma.company.findFirst({
|
|
where: { organizationId, name: { equals: n, mode: 'insensitive' } },
|
|
select: { id: true },
|
|
});
|
|
return row?.id ?? null;
|
|
}
|
|
|
|
private async findUserId(organizationId: string, name?: string) {
|
|
const n = name?.trim();
|
|
if (!n) return null;
|
|
const row = await this.prisma.user.findFirst({
|
|
where: {
|
|
fullName: { contains: n, mode: 'insensitive' },
|
|
memberships: { some: { organizationId } },
|
|
},
|
|
select: { id: true },
|
|
});
|
|
return row?.id ?? null;
|
|
}
|
|
}
|