Files
CRM_Montzar/apps/api/src/lead-forms/lead-forms.service.ts
T

696 lines
21 KiB
TypeScript
Raw Normal View History

import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import type {
CreateLeadFormRequest,
LeadFormDto,
LeadFormFieldInput,
PublicLeadFormDto,
SubmitLeadFormResponse,
UpdateLeadFormRequest,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { LocalFileStorage } from '../storage/local-file.storage';
import { AutomationsService } from '../automations/automations.service';
2026-09-13 19:11:47 +03:30
import { MessageAutomationsService } from '../message-automations/message-automations.service';
import {
emptyToNull,
normalizeEmail,
normalizePhone,
} from '../contacts/normalize';
const DEFAULT_FIELDS: LeadFormFieldInput[] = [
{
key: 'fullName',
label: 'نام و نام خانوادگی',
fieldType: 'text',
required: true,
mapTo: 'person.fullName',
placeholder: 'مثلاً علی منتظر',
position: 0,
},
{
key: 'mobile',
label: 'شماره تماس',
fieldType: 'phone',
required: true,
mapTo: 'person.mobile',
placeholder: '۰۹۱۲۱۲۳۴۵۶۷',
position: 1,
},
{
key: 'subject',
label: 'موضوع درخواست',
fieldType: 'select',
required: true,
mapTo: 'deal.title',
options: ['مشاوره فروش', 'پشتیبانی', 'همکاری'],
position: 2,
},
{
key: 'message',
label: 'توضیحات',
fieldType: 'textarea',
required: false,
mapTo: 'deal.notes',
placeholder: 'شرح درخواست خود را بنویسید',
position: 3,
},
];
type FormRow = Prisma.LeadFormGetPayload<{ include: { fields: true } }>;
@Injectable()
export class LeadFormsService {
constructor(
private readonly prisma: PrismaService,
private readonly files: LocalFileStorage,
private readonly automations: AutomationsService,
2026-09-13 19:11:47 +03:30
private readonly messageAutomations: MessageAutomationsService,
) {}
async list(organizationId: string): Promise<LeadFormDto[]> {
const rows = await this.prisma.leadForm.findMany({
where: { organizationId },
include: {
fields: { orderBy: { position: 'asc' } },
_count: { select: { submissions: true } },
},
orderBy: { updatedAt: 'desc' },
});
return rows.map((row) => ({
...this.toDto(row),
submissionCount: row._count.submissions,
}));
}
async get(organizationId: string, id: string): Promise<LeadFormDto> {
const row = await this.findInOrg(organizationId, id);
return this.toDto(row);
}
async create(
organizationId: string,
dto: CreateLeadFormRequest,
): Promise<LeadFormDto> {
await this.assertPipeline(organizationId, dto.pipelineId);
await this.assertAssignees(organizationId, dto.assigneeIds);
const fields = normalizeFields(dto.fields?.length ? dto.fields : DEFAULT_FIELDS);
const row = await this.prisma.leadForm.create({
data: {
organizationId,
name: dto.name.trim(),
description: emptyToNull(dto.description ?? null),
createPerson: dto.createPerson ?? true,
createDeal: dto.createDeal ?? true,
pipelineId: emptyToNull(dto.pipelineId ?? null),
source: emptyToNull(dto.source ?? null) ?? 'فرم وب',
thankYouMessage:
emptyToNull(dto.thankYouMessage ?? null) ??
'پیام شما ثبت شد. به‌زودی با شما تماس می‌گیریم.',
redirectUrl: emptyToNull(dto.redirectUrl ?? null),
assigneeIds: dto.assigneeIds ?? [],
submitLabel: dto.submitLabel?.trim() || 'ارسال درخواست',
submitColor: dto.submitColor?.trim() || '#14b8a6',
fields: {
create: fields.map((f, index) => fieldCreateData(f, index)),
},
},
include: { fields: { orderBy: { position: 'asc' } } },
});
return this.toDto(row);
}
async update(
organizationId: string,
id: string,
dto: UpdateLeadFormRequest,
): Promise<LeadFormDto> {
await this.findInOrg(organizationId, id);
if ('pipelineId' in dto) {
await this.assertPipeline(organizationId, dto.pipelineId);
}
if (dto.assigneeIds) {
await this.assertAssignees(organizationId, dto.assigneeIds);
}
const data: Prisma.LeadFormUpdateInput = {};
if (dto.name !== undefined) data.name = dto.name.trim();
if ('description' in dto) data.description = emptyToNull(dto.description ?? null);
if (dto.submitLabel !== undefined) {
data.submitLabel = dto.submitLabel.trim() || 'ارسال درخواست';
}
if (dto.submitColor !== undefined) {
data.submitColor = dto.submitColor.trim() || '#14b8a6';
}
if (dto.isActive !== undefined) data.isActive = dto.isActive;
if (dto.createPerson !== undefined) data.createPerson = dto.createPerson;
if (dto.createDeal !== undefined) data.createDeal = dto.createDeal;
if ('pipelineId' in dto) data.pipelineId = emptyToNull(dto.pipelineId ?? null);
if ('source' in dto) data.source = emptyToNull(dto.source ?? null);
if ('thankYouMessage' in dto) {
data.thankYouMessage = emptyToNull(dto.thankYouMessage ?? null);
}
if ('redirectUrl' in dto) {
data.redirectUrl = emptyToNull(dto.redirectUrl ?? null);
}
if (dto.assigneeIds !== undefined) data.assigneeIds = dto.assigneeIds;
if (dto.fields) {
const fields = normalizeFields(dto.fields);
await this.prisma.$transaction(async (tx) => {
await tx.leadFormField.deleteMany({ where: { formId: id } });
await tx.leadForm.update({
where: { id },
data: {
...data,
fields: {
create: fields.map((f, index) => fieldCreateData(f, index)),
},
},
});
});
} else if (Object.keys(data).length) {
await this.prisma.leadForm.update({ where: { id }, data });
}
return this.get(organizationId, id);
}
async remove(organizationId: string, id: string): Promise<void> {
await this.findInOrg(organizationId, id);
await this.prisma.leadForm.delete({ where: { id } });
}
async getPublic(token: string): Promise<PublicLeadFormDto> {
const row = await this.prisma.leadForm.findFirst({
where: { publicToken: token, isActive: true },
include: { fields: { orderBy: { position: 'asc' } } },
});
if (!row) throw new NotFoundException('فرم پیدا نشد یا غیرفعال است');
return {
name: row.name,
description: row.description,
thankYouMessage: row.thankYouMessage,
submitLabel: row.submitLabel || 'ارسال درخواست',
submitColor: row.submitColor || '#14b8a6',
hasCover: Boolean(row.coverStorageKey),
coverPath: row.coverStorageKey
? `/api/public/forms/${row.publicToken}/cover`
: null,
fields: row.fields
.filter((f) => f.fieldType !== 'heading' || true)
.map((f) => ({
key: f.key,
label: f.label,
fieldType: f.fieldType,
required: f.required,
placeholder: f.placeholder,
options: asOptions(f.options),
})),
};
}
async submit(
token: string,
values: Record<string, string>,
): Promise<SubmitLeadFormResponse> {
const form = await this.prisma.leadForm.findFirst({
where: { publicToken: token, isActive: true },
include: { fields: { orderBy: { position: 'asc' } } },
});
if (!form) throw new NotFoundException('فرم پیدا نشد یا غیرفعال است');
const mapped = mapValues(form.fields, values);
const extras = collectExtras(form.fields, values);
if (extras) {
mapped.notes = [mapped.notes, extras].filter(Boolean).join('\n');
}
if (form.createPerson) {
if (!mapped.firstName?.trim() && !mapped.lastName?.trim()) {
throw new BadRequestException('نام یا نام خانوادگی لازم است');
}
}
const ownerId = await this.nextAssignee(form);
const actorId =
ownerId ??
(
await this.prisma.user.findFirst({
where: {
memberships: {
some: { organizationId: form.organizationId, role: 'owner' },
},
},
select: { id: true },
})
)?.id;
if (!actorId) {
throw new BadRequestException('سازمان کاربر فعالی برای ثبت سرنخ ندارد');
}
let personId: string | null = null;
if (form.createPerson) {
personId = await this.upsertPerson(
form.organizationId,
mapped,
ownerId ?? actorId,
);
}
await this.prisma.leadFormSubmission.create({
data: {
formId: form.id,
values: values as Prisma.InputJsonValue,
personId,
},
});
if (form.createDeal) {
await this.createDeal(form, mapped, personId, actorId, ownerId);
} else if (personId && mapped.notes) {
await this.prisma.person.update({
where: { id: personId },
data: {
notes: mapped.notes,
},
});
}
const personName = [mapped.firstName, mapped.lastName]
.filter((p) => p?.trim())
.join(' ')
.trim();
2026-09-13 19:11:47 +03:30
const leadCtx = {
organizationId: form.organizationId,
2026-09-13 19:11:47 +03:30
entityType: 'person' as const,
entityId: personId ?? form.id,
title: personName || form.name,
personId,
ownerId: ownerId ?? actorId,
2026-09-13 19:11:47 +03:30
};
await this.automations.runTrigger('lead_submitted', leadCtx);
await this.messageAutomations.onEvent('lead_submitted', leadCtx);
return {
ok: true,
thankYouMessage: form.thankYouMessage,
redirectUrl: form.redirectUrl,
};
}
private async upsertPerson(
organizationId: string,
mapped: MappedValues,
ownerId: string,
): Promise<string> {
const email = normalizeEmail(mapped.email);
const mobile = normalizePhone(mapped.mobile);
const phone = normalizePhone(mapped.phone);
const or: Prisma.PersonWhereInput[] = [];
if (email) or.push({ email });
if (mobile) or.push({ mobile });
const existing = or.length
? await this.prisma.person.findFirst({
where: { organizationId, OR: or },
})
: null;
if (existing) {
await this.prisma.person.update({
where: { id: existing.id },
data: {
firstName: mapped.firstName?.trim() || existing.firstName,
lastName: mapped.lastName?.trim() || existing.lastName,
email: email ?? existing.email,
mobile: mobile ?? existing.mobile,
phone: phone ?? existing.phone,
position: emptyToNull(mapped.position) ?? existing.position,
notes: emptyToNull(mapped.notes) ?? existing.notes,
ownerId: existing.ownerId ?? ownerId,
},
});
return existing.id;
}
const created = await this.prisma.person.create({
data: {
organizationId,
firstName: (mapped.firstName?.trim() || 'سرنخ').slice(0, 80),
lastName: (mapped.lastName?.trim() || 'جدید').slice(0, 80),
email,
mobile,
phone,
position: emptyToNull(mapped.position),
notes: emptyToNull(mapped.notes),
ownerId,
},
});
return created.id;
}
private async createDeal(
form: FormRow,
mapped: MappedValues,
personId: string | null,
actorId: string,
ownerId: string | null,
) {
const pipeline =
(form.pipelineId
? await this.prisma.pipeline.findFirst({
where: { id: form.pipelineId, organizationId: form.organizationId },
include: { stages: { orderBy: { position: 'asc' } } },
})
: null) ??
(await this.prisma.pipeline.findFirst({
where: { organizationId: form.organizationId, isDefault: true },
include: { stages: { orderBy: { position: 'asc' } } },
}));
if (!pipeline?.stages.length) {
throw new BadRequestException('کاریز فعالی برای ثبت معامله وجود ندارد');
}
const stage =
pipeline.stages.find((s) => !s.isWon && !s.isLost) ?? pipeline.stages[0];
const title =
mapped.dealTitle?.trim() ||
[mapped.firstName, mapped.lastName].filter(Boolean).join(' ').trim() ||
`سرنخ از ${form.name}`;
const maxPos = await this.prisma.deal.aggregate({
where: { organizationId: form.organizationId, stageId: stage.id },
_max: { position: true },
});
await this.prisma.deal.create({
data: {
organizationId: form.organizationId,
pipelineId: pipeline.id,
stageId: stage.id,
title: title.slice(0, 200),
source: form.source ?? 'فرم وب',
notes: emptyToNull(mapped.dealNotes ?? mapped.notes),
personId,
ownerId: ownerId ?? actorId,
position: (maxPos._max.position ?? -1) + 1,
status: 'open',
currency: 'IRR',
},
});
}
private async nextAssignee(form: FormRow): Promise<string | null> {
const ids = form.assigneeIds.filter(Boolean);
if (!ids.length) return null;
const index = form.roundRobinIndex % ids.length;
const chosen = ids[index];
await this.prisma.leadForm.update({
where: { id: form.id },
data: { roundRobinIndex: index + 1 },
});
return chosen;
}
private async findInOrg(organizationId: string, id: string): Promise<FormRow> {
const row = await this.prisma.leadForm.findFirst({
where: { id, organizationId },
include: { fields: { orderBy: { position: 'asc' } } },
});
if (!row) throw new NotFoundException('فرم پیدا نشد');
return row;
}
private async assertPipeline(
organizationId: string,
pipelineId?: string | null,
) {
const id = emptyToNull(pipelineId ?? null);
if (!id) return;
const found = await this.prisma.pipeline.findFirst({
where: { id, organizationId },
select: { id: true },
});
if (!found) throw new BadRequestException('کاریز انتخاب‌شده معتبر نیست');
}
private async assertAssignees(
organizationId: string,
assigneeIds?: string[],
) {
if (!assigneeIds?.length) return;
const count = await this.prisma.user.count({
where: {
id: { in: assigneeIds },
memberships: { some: { organizationId } },
},
});
if (count !== assigneeIds.length) {
throw new BadRequestException('یکی از مسئولان انتخاب‌شده معتبر نیست');
}
}
async listSubmissions(organizationId: string, id: string) {
await this.findInOrg(organizationId, id);
const rows = await this.prisma.leadFormSubmission.findMany({
where: { formId: id },
orderBy: { createdAt: 'desc' },
take: 200,
});
return rows.map((r) => ({
id: r.id,
values: asStringRecord(r.values),
personId: r.personId,
createdAt: r.createdAt.toISOString(),
}));
}
async saveCover(
organizationId: string,
id: string,
file: { buffer: Buffer; originalname: string },
) {
if (!file?.buffer) throw new BadRequestException('فایل کاور ارسال نشده');
const row = await this.findInOrg(organizationId, id);
const ext = (file.originalname.split('.').pop() || 'jpg')
.toLowerCase()
.replace(/[^a-z0-9]/g, '')
.slice(0, 6);
const key = `lead-forms/${id}/cover.${ext || 'jpg'}`;
await this.files.save(key, file.buffer);
if (row.coverStorageKey && row.coverStorageKey !== key) {
await this.files.remove(row.coverStorageKey);
}
await this.prisma.leadForm.update({
where: { id },
data: { coverStorageKey: key },
});
return this.get(organizationId, id);
}
async removeCover(organizationId: string, id: string) {
const row = await this.findInOrg(organizationId, id);
if (row.coverStorageKey) await this.files.remove(row.coverStorageKey);
await this.prisma.leadForm.update({
where: { id },
data: { coverStorageKey: null },
});
return this.get(organizationId, id);
}
coverKey(row: FormRow) {
return row.coverStorageKey;
}
async getByToken(token: string, onlyActive = false) {
return this.prisma.leadForm.findFirst({
where: { publicToken: token, ...(onlyActive ? { isActive: true } : {}) },
include: { fields: true },
});
}
private toDto(row: FormRow): LeadFormDto {
return {
id: row.id,
name: row.name,
description: row.description,
publicToken: row.publicToken,
isActive: row.isActive,
createPerson: row.createPerson,
createDeal: row.createDeal,
pipelineId: row.pipelineId,
source: row.source,
thankYouMessage: row.thankYouMessage,
redirectUrl: row.redirectUrl,
assigneeIds: row.assigneeIds,
submitLabel: row.submitLabel || 'ارسال درخواست',
submitColor: row.submitColor || '#14b8a6',
hasCover: Boolean(row.coverStorageKey),
fields: row.fields.map((f) => ({
id: f.id,
key: f.key,
label: f.label,
fieldType: f.fieldType,
required: f.required,
mapTo: f.mapTo,
position: f.position,
placeholder: f.placeholder,
options: asOptions(f.options),
})),
publicPath: `/f/${row.publicToken}`,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
}
type MappedValues = {
firstName?: string;
lastName?: string;
email?: string;
mobile?: string;
phone?: string;
position?: string;
dealTitle?: string;
dealNotes?: string;
notes?: string;
};
function mapValues(
fields: Array<{
key: string;
mapTo: string;
required: boolean;
label: string;
fieldType?: string;
}>,
values: Record<string, string>,
): MappedValues {
const mapped: MappedValues = {};
for (const field of fields) {
if (field.fieldType === 'heading') continue;
const raw = (values?.[field.key] ?? '').toString().trim();
if (field.required && !raw) {
throw new BadRequestException(`فیلد «${field.label}» الزامی است`);
}
if (!raw) continue;
switch (field.mapTo) {
case 'person.fullName': {
const parts = raw.split(/\s+/).filter(Boolean);
mapped.firstName = parts[0] || raw;
mapped.lastName = parts.slice(1).join(' ') || '—';
break;
}
case 'person.firstName':
mapped.firstName = raw;
break;
case 'person.lastName':
mapped.lastName = raw;
break;
case 'person.email':
mapped.email = raw;
break;
case 'person.mobile':
mapped.mobile = raw;
break;
case 'person.phone':
mapped.phone = raw;
break;
case 'person.position':
mapped.position = raw;
break;
case 'deal.title':
mapped.dealTitle = raw;
break;
case 'deal.notes':
mapped.dealNotes = raw;
break;
case 'notes':
mapped.notes = raw;
break;
default:
break;
}
}
return mapped;
}
function normalizeFields(fields: LeadFormFieldInput[]): LeadFormFieldInput[] {
return fields.map((f, index) => {
const key =
f.key?.trim() ||
slugKey(f.label) ||
`field_${index + 1}`;
return {
...f,
key: key.slice(0, 64),
label: f.label.trim(),
fieldType: f.fieldType || 'text',
required: f.required ?? false,
mapTo: f.mapTo,
position: f.position ?? index,
};
});
}
function fieldCreateData(f: LeadFormFieldInput, index: number) {
return {
key: f.key!,
label: f.label,
fieldType: f.fieldType,
required: f.required ?? false,
mapTo: f.mapTo,
position: f.position ?? index,
placeholder: emptyToNull(f.placeholder ?? null),
options: f.options?.length ? f.options : undefined,
};
}
function asOptions(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.map((v) => String(v).trim()).filter(Boolean);
}
function asStringRecord(value: unknown): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (v == null) continue;
out[k] = typeof v === 'string' ? v : JSON.stringify(v);
}
return out;
}
function collectExtras(
fields: Array<{ key: string; mapTo: string; label: string; fieldType: string }>,
values: Record<string, string>,
): string {
const lines: string[] = [];
for (const field of fields) {
if (field.fieldType === 'heading' || field.mapTo !== 'custom') continue;
const raw = (values?.[field.key] ?? '').toString().trim();
if (raw) lines.push(`${field.label}: ${raw}`);
}
return lines.join('\n');
}
function slugKey(label: string): string {
return label
.trim()
.toLowerCase()
.replace(/[^\w\u0600-\u06FF]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 40);
}