Connect public lead forms to CRM Leads on submit.

This commit is contained in:
2026-09-28 13:39:44 +03:30
parent 32e27d45f7
commit f20206b045
10 changed files with 971 additions and 91 deletions
@@ -0,0 +1,21 @@
-- AlterTable LeadForm: publish → Lead connection
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "createLead" BOOLEAN NOT NULL DEFAULT true;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "leadStageId" TEXT;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "duplicateMode" TEXT NOT NULL DEFAULT 'update';
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "viewCount" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "startCount" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "submitCount" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "leadCreateCount" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "duplicateCount" INTEGER NOT NULL DEFAULT 0;
-- Existing forms: keep person/deal behavior unless already lead-oriented
ALTER TABLE "LeadForm" ALTER COLUMN "createPerson" SET DEFAULT false;
ALTER TABLE "LeadForm" ALTER COLUMN "createDeal" SET DEFAULT false;
-- AlterTable LeadFormSubmission
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "leadId" TEXT;
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "status" TEXT NOT NULL DEFAULT 'created';
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "utm" JSONB;
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "meta" JSONB;
CREATE INDEX IF NOT EXISTS "LeadFormSubmission_leadId_idx" ON "LeadFormSubmission"("leadId");
+19 -2
View File
@@ -793,9 +793,15 @@ model LeadForm {
description String?
publicToken String @unique @default(cuid())
isActive Boolean @default(true)
createPerson Boolean @default(true)
createDeal Boolean @default(true)
/// ثبت به‌عنوان Lead در CRM (مسیر اصلی انتشار فرم)
createLead Boolean @default(true)
createPerson Boolean @default(false)
createDeal Boolean @default(false)
pipelineId String?
/// مرحله اولیه لید (اختیاری؛ وگرنه اولین مرحله)
leadStageId String?
/// skip | update | activity
duplicateMode String @default("update")
source String?
thankYouMessage String?
redirectUrl String?
@@ -804,6 +810,11 @@ model LeadForm {
submitLabel String @default("ارسال درخواست")
submitColor String @default("#14b8a6")
coverStorageKey String?
viewCount Int @default(0)
startCount Int @default(0)
submitCount Int @default(0)
leadCreateCount Int @default(0)
duplicateCount Int @default(0)
fields LeadFormField[]
submissions LeadFormSubmission[]
createdAt DateTime @default(now())
@@ -835,9 +846,15 @@ model LeadFormSubmission {
form LeadForm @relation(fields: [formId], references: [id], onDelete: Cascade)
values Json
personId String?
leadId String?
/// created | updated | duplicate_skipped | error
status String @default("created")
utm Json?
meta Json?
createdAt DateTime @default(now())
@@index([formId, createdAt])
@@index([leadId])
}
model Quote {
+98
View File
@@ -23,10 +23,21 @@ const MAP_TO = [
'person.position',
'deal.title',
'deal.notes',
'lead.title',
'lead.contactName',
'lead.mobile',
'lead.phone',
'lead.city',
'lead.region',
'lead.trade',
'lead.notes',
'lead.source',
'notes',
'custom',
] as const;
const DUPLICATE_MODES = ['skip', 'update', 'activity'] as const;
export class LeadFormFieldInputDto {
@IsOptional()
@IsString()
@@ -74,6 +85,10 @@ export class CreateLeadFormDto {
@MaxLength(400)
description?: string | null;
@IsOptional()
@IsBoolean()
createLead?: boolean;
@IsOptional()
@IsBoolean()
createPerson?: boolean;
@@ -86,6 +101,14 @@ export class CreateLeadFormDto {
@IsString()
pipelineId?: string | null;
@IsOptional()
@IsString()
leadStageId?: string | null;
@IsOptional()
@IsIn(DUPLICATE_MODES)
duplicateMode?: (typeof DUPLICATE_MODES)[number];
@IsOptional()
@IsString()
@MaxLength(80)
@@ -141,6 +164,10 @@ export class UpdateLeadFormDto {
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsBoolean()
createLead?: boolean;
@IsOptional()
@IsBoolean()
createPerson?: boolean;
@@ -153,6 +180,14 @@ export class UpdateLeadFormDto {
@IsString()
pipelineId?: string | null;
@IsOptional()
@IsString()
leadStageId?: string | null;
@IsOptional()
@IsIn(DUPLICATE_MODES)
duplicateMode?: (typeof DUPLICATE_MODES)[number];
@IsOptional()
@IsString()
@MaxLength(80)
@@ -192,7 +227,70 @@ export class UpdateLeadFormDto {
fields?: LeadFormFieldInputDto[];
}
export class LeadFormUtmDto {
@IsOptional()
@IsString()
@MaxLength(120)
source?: string;
@IsOptional()
@IsString()
@MaxLength(120)
medium?: string;
@IsOptional()
@IsString()
@MaxLength(160)
campaign?: string;
@IsOptional()
@IsString()
@MaxLength(160)
term?: string;
@IsOptional()
@IsString()
@MaxLength(160)
content?: string;
@IsOptional()
@IsString()
@MaxLength(500)
landingPage?: string;
@IsOptional()
@IsString()
@MaxLength(500)
referrer?: string;
}
export class SubmitLeadFormDto {
@IsObject()
values!: Record<string, string>;
@IsOptional()
@ValidateNested()
@Type(() => LeadFormUtmDto)
utm?: LeadFormUtmDto;
@IsOptional()
@IsString()
@MaxLength(1000)
pageUrl?: string;
@IsOptional()
@IsString()
@MaxLength(1000)
referrer?: string;
/** honeypot */
@IsOptional()
@IsString()
@MaxLength(200)
website?: string;
}
export class LeadFormPublicEventDto {
@IsIn(['view', 'start'])
type!: 'view' | 'start';
}
+7 -1
View File
@@ -2,12 +2,18 @@ import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { AutomationsModule } from '../automations/automations.module';
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
import { LeadsModule } from '../leads/leads.module';
import { LeadFormsController } from './lead-forms.controller';
import { LeadFormsService } from './lead-forms.service';
import { PublicLeadFormsController } from './public-lead-forms.controller';
@Module({
imports: [AuthModule, AutomationsModule, MessageAutomationsModule],
imports: [
AuthModule,
AutomationsModule,
MessageAutomationsModule,
LeadsModule,
],
controllers: [LeadFormsController, PublicLeadFormsController],
providers: [LeadFormsService],
exports: [LeadFormsService],
+448 -41
View File
@@ -7,7 +7,9 @@ import type {
CreateLeadFormRequest,
LeadFormDto,
LeadFormFieldInput,
LeadFormUtmDto,
PublicLeadFormDto,
SubmitLeadFormRequest,
SubmitLeadFormResponse,
UpdateLeadFormRequest,
} from '@mento/shared';
@@ -21,6 +23,7 @@ import {
normalizeEmail,
normalizePhone,
} from '../contacts/normalize';
import { LeadStagesService } from '../leads/lead-stages.service';
const DEFAULT_FIELDS: LeadFormFieldInput[] = [
{
@@ -28,7 +31,7 @@ const DEFAULT_FIELDS: LeadFormFieldInput[] = [
label: 'نام و نام خانوادگی',
fieldType: 'text',
required: true,
mapTo: 'person.fullName',
mapTo: 'lead.contactName',
placeholder: 'مثلاً علی منتظر',
position: 0,
},
@@ -37,17 +40,17 @@ const DEFAULT_FIELDS: LeadFormFieldInput[] = [
label: 'شماره تماس',
fieldType: 'phone',
required: true,
mapTo: 'person.mobile',
mapTo: 'lead.mobile',
placeholder: '۰۹۱۲۱۲۳۴۵۶۷',
position: 1,
},
{
key: 'subject',
label: 'موضوع درخواست',
fieldType: 'select',
key: 'title',
label: 'نام فروشگاه / موضوع',
fieldType: 'text',
required: true,
mapTo: 'deal.title',
options: ['مشاوره فروش', 'پشتیبانی', 'همکاری'],
mapTo: 'lead.title',
placeholder: 'مثلاً فروشگاه نمونه',
position: 2,
},
{
@@ -55,12 +58,17 @@ const DEFAULT_FIELDS: LeadFormFieldInput[] = [
label: 'توضیحات',
fieldType: 'textarea',
required: false,
mapTo: 'deal.notes',
mapTo: 'lead.notes',
placeholder: 'شرح درخواست خود را بنویسید',
position: 3,
},
];
/** Simple in-memory rate limit: token+ip → timestamps */
const submitHits = new Map<string, number[]>();
const RATE_WINDOW_MS = 60_000;
const RATE_MAX = 12;
type FormRow = Prisma.LeadFormGetPayload<{ include: { fields: true } }>;
@Injectable()
@@ -70,6 +78,7 @@ export class LeadFormsService {
private readonly files: LocalFileStorage,
private readonly automations: AutomationsService,
private readonly messageAutomations: MessageAutomationsService,
private readonly leadStages: LeadStagesService,
) {}
async list(organizationId: string): Promise<LeadFormDto[]> {
@@ -97,6 +106,7 @@ export class LeadFormsService {
dto: CreateLeadFormRequest,
): Promise<LeadFormDto> {
await this.assertPipeline(organizationId, dto.pipelineId);
await this.assertLeadStage(organizationId, dto.leadStageId);
await this.assertAssignees(organizationId, dto.assigneeIds);
const fields = normalizeFields(dto.fields?.length ? dto.fields : DEFAULT_FIELDS);
@@ -105,9 +115,12 @@ export class LeadFormsService {
organizationId,
name: dto.name.trim(),
description: emptyToNull(dto.description ?? null),
createPerson: dto.createPerson ?? true,
createDeal: dto.createDeal ?? true,
createLead: dto.createLead ?? true,
createPerson: dto.createPerson ?? false,
createDeal: dto.createDeal ?? false,
pipelineId: emptyToNull(dto.pipelineId ?? null),
leadStageId: emptyToNull(dto.leadStageId ?? null),
duplicateMode: normalizeDuplicateMode(dto.duplicateMode),
source: emptyToNull(dto.source ?? null) ?? 'فرم وب',
thankYouMessage:
emptyToNull(dto.thankYouMessage ?? null) ??
@@ -134,6 +147,9 @@ export class LeadFormsService {
if ('pipelineId' in dto) {
await this.assertPipeline(organizationId, dto.pipelineId);
}
if ('leadStageId' in dto) {
await this.assertLeadStage(organizationId, dto.leadStageId);
}
if (dto.assigneeIds) {
await this.assertAssignees(organizationId, dto.assigneeIds);
}
@@ -148,9 +164,14 @@ export class LeadFormsService {
data.submitColor = dto.submitColor.trim() || '#14b8a6';
}
if (dto.isActive !== undefined) data.isActive = dto.isActive;
if (dto.createLead !== undefined) data.createLead = dto.createLead;
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 ('leadStageId' in dto) data.leadStageId = emptyToNull(dto.leadStageId ?? null);
if (dto.duplicateMode !== undefined) {
data.duplicateMode = normalizeDuplicateMode(dto.duplicateMode);
}
if ('source' in dto) data.source = emptyToNull(dto.source ?? null);
if ('thankYouMessage' in dto) {
data.thankYouMessage = emptyToNull(dto.thankYouMessage ?? null);
@@ -196,29 +217,51 @@ export class LeadFormsService {
name: row.name,
description: row.description,
thankYouMessage: row.thankYouMessage,
redirectUrl: row.redirectUrl,
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),
})),
fields: row.fields.map((f) => ({
key: f.key,
label: f.label,
fieldType: f.fieldType,
required: f.required,
placeholder: f.placeholder,
options: asOptions(f.options),
})),
};
}
async recordPublicEvent(token: string, type: 'view' | 'start'): Promise<{ ok: true }> {
const form = await this.prisma.leadForm.findFirst({
where: { publicToken: token, isActive: true },
select: { id: true },
});
if (!form) throw new NotFoundException('فرم پیدا نشد یا غیرفعال است');
const data =
type === 'view'
? { viewCount: { increment: 1 } }
: { startCount: { increment: 1 } };
await this.prisma.leadForm.update({ where: { id: form.id }, data });
return { ok: true };
}
async submit(
token: string,
values: Record<string, string>,
body: SubmitLeadFormRequest,
clientIp?: string | null,
): Promise<SubmitLeadFormResponse> {
const values = body.values ?? {};
if ((body.website ?? '').trim()) {
// honeypot tripped — pretend success
return { ok: true, thankYouMessage: null, redirectUrl: null, outcome: 'created' };
}
this.assertRateLimit(token, clientIp);
const form = await this.prisma.leadForm.findFirst({
where: { publicToken: token, isActive: true },
include: { fields: { orderBy: { position: 'asc' } } },
@@ -231,10 +274,10 @@ export class LeadFormsService {
mapped.notes = [mapped.notes, extras].filter(Boolean).join('\n');
}
if (form.createPerson) {
if (!mapped.firstName?.trim() && !mapped.lastName?.trim()) {
throw new BadRequestException('نام یا نام خانوادگی لازم است');
}
const utm = buildUtm(body);
const utmNote = formatUtmNote(utm);
if (utmNote) {
mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n');
}
const ownerId = await this.nextAssignee(form);
@@ -256,7 +299,30 @@ export class LeadFormsService {
}
let personId: string | null = null;
let leadId: string | null = null;
let status: 'created' | 'updated' | 'duplicate_skipped' = 'created';
let leadCreated = false;
let wasDuplicate = false;
let message: string | null = null;
if (form.createLead) {
const result = await this.upsertLead(form, mapped, ownerId ?? actorId, actorId);
leadId = result.leadId;
status = result.status;
leadCreated = result.created;
wasDuplicate = result.duplicate;
message = result.message;
}
if (form.createPerson) {
if (!mapped.firstName?.trim() && !mapped.lastName?.trim() && mapped.contactName) {
const parts = mapped.contactName.split(/\s+/).filter(Boolean);
mapped.firstName = parts[0] || mapped.contactName;
mapped.lastName = parts.slice(1).join(' ') || '—';
}
if (!mapped.firstName?.trim() && !mapped.lastName?.trim()) {
throw new BadRequestException('نام یا نام خانوادگی لازم است');
}
personId = await this.upsertPerson(
form.organizationId,
mapped,
@@ -264,34 +330,51 @@ export class LeadFormsService {
);
}
if (form.createDeal) {
await this.createDeal(form, mapped, personId, actorId, ownerId);
} else if (personId && mapped.notes && !form.createLead) {
await this.prisma.person.update({
where: { id: personId },
data: { notes: mapped.notes },
});
}
await this.prisma.leadFormSubmission.create({
data: {
formId: form.id,
values: values as Prisma.InputJsonValue,
personId,
leadId,
status,
utm: utm ? (utm as Prisma.InputJsonValue) : undefined,
meta: {
pageUrl: body.pageUrl ?? null,
referrer: body.referrer ?? null,
ip: clientIp ?? null,
} as Prisma.InputJsonValue,
},
});
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,
},
});
}
await this.prisma.leadForm.update({
where: { id: form.id },
data: {
submitCount: { increment: 1 },
...(leadCreated ? { leadCreateCount: { increment: 1 } } : {}),
...(wasDuplicate ? { duplicateCount: { increment: 1 } } : {}),
},
});
const title =
mapped.leadTitle?.trim() ||
mapped.contactName?.trim() ||
[mapped.firstName, mapped.lastName].filter(Boolean).join(' ').trim() ||
form.name;
const personName = [mapped.firstName, mapped.lastName]
.filter((p) => p?.trim())
.join(' ')
.trim();
const leadCtx = {
organizationId: form.organizationId,
entityType: 'person' as const,
entityId: personId ?? form.id,
title: personName || form.name,
entityId: personId ?? leadId ?? form.id,
title,
personId,
ownerId: ownerId ?? actorId,
};
@@ -302,6 +385,223 @@ export class LeadFormsService {
ok: true,
thankYouMessage: form.thankYouMessage,
redirectUrl: form.redirectUrl,
outcome: status,
leadId,
duplicate: wasDuplicate,
message,
};
}
private assertRateLimit(token: string, ip?: string | null) {
const key = `${token}:${ip || 'unknown'}`;
const now = Date.now();
const prev = (submitHits.get(key) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
if (prev.length >= RATE_MAX) {
throw new BadRequestException('تعداد ارسال بیش از حد مجاز است. کمی بعد دوباره تلاش کنید.');
}
prev.push(now);
submitHits.set(key, prev);
}
private async upsertLead(
form: FormRow,
mapped: MappedValues,
assigneeId: string,
actorId: string,
): Promise<{
leadId: string | null;
status: 'created' | 'updated' | 'duplicate_skipped';
created: boolean;
duplicate: boolean;
message: string | null;
}> {
await this.leadStages.ensureDefaults(form.organizationId);
const mobile = mobileKey(mapped.mobile);
if (!mobile) {
throw new BadRequestException('شماره موبایل معتبر نیست');
}
const mode = normalizeDuplicateMode(form.duplicateMode);
const existingLead = await this.prisma.lead.findFirst({
where: { organizationId: form.organizationId, mobile },
});
const personDup = !existingLead
? await this.prisma.person.findFirst({
where: {
organizationId: form.organizationId,
OR: [{ mobile }, { phone: mobile }],
},
select: { id: true, firstName: true, lastName: true },
})
: null;
if (personDup && !existingLead) {
// Person exists with this mobile — treat as duplicate for lead creation
if (mode === 'skip') {
return {
leadId: null,
status: 'duplicate_skipped',
created: false,
duplicate: true,
message: `این شماره قبلاً به‌عنوان مشتری ثبت شده است`,
};
}
// update/activity without a lead: still create a new lead (person is separate)
}
const title =
(mapped.leadTitle?.trim() ||
mapped.contactName?.trim() ||
[mapped.firstName, mapped.lastName].filter(Boolean).join(' ').trim() ||
`سرنخ از ${form.name}`).slice(0, 200);
const contactName =
emptyToNull(mapped.contactName) ??
emptyToNull([mapped.firstName, mapped.lastName].filter(Boolean).join(' ').trim()) ??
null;
const source =
emptyToNull(mapped.leadSource) ?? form.source ?? 'فرم وب';
if (existingLead) {
if (mode === 'skip') {
await this.prisma.leadEvent.create({
data: {
organizationId: form.organizationId,
leadId: existingLead.id,
type: 'form_submit',
title: 'ارسال فرم (تکراری — رد شد)',
body: `فرم «${form.name}» دوباره ارسال شد و طبق تنظیمات رد شد.`,
actorId,
meta: { formId: form.id, mode: 'skip' },
},
});
return {
leadId: existingLead.id,
status: 'duplicate_skipped',
created: false,
duplicate: true,
message: 'این شماره قبلاً ثبت شده است',
};
}
if (mode === 'activity') {
await this.prisma.leadEvent.create({
data: {
organizationId: form.organizationId,
leadId: existingLead.id,
type: 'form_submit',
title: 'ارسال مجدد فرم',
body: [
`فرم «${form.name}»`,
mapped.notes ? mapped.notes : null,
]
.filter(Boolean)
.join('\n'),
actorId,
meta: { formId: form.id, mode: 'activity' },
},
});
await this.prisma.lead.update({
where: { id: existingLead.id },
data: { lastContactAt: new Date() },
});
return {
leadId: existingLead.id,
status: 'updated',
created: false,
duplicate: true,
message: null,
};
}
// update mode
await this.prisma.lead.update({
where: { id: existingLead.id },
data: {
title: title || existingLead.title,
contactName: contactName ?? existingLead.contactName,
phone: emptyToNull(mapped.phone) ?? existingLead.phone,
city: emptyToNull(mapped.city) ?? existingLead.city,
region: emptyToNull(mapped.region) ?? existingLead.region,
trade: emptyToNull(mapped.trade) ?? existingLead.trade,
source: source ?? existingLead.source,
notes: emptyToNull(mapped.notes) ?? existingLead.notes,
assigneeId: existingLead.assigneeId ?? assigneeId,
lastContactAt: new Date(),
},
});
await this.prisma.leadEvent.create({
data: {
organizationId: form.organizationId,
leadId: existingLead.id,
type: 'form_submit',
title: 'به‌روزرسانی از فرم',
body: `فرم «${form.name}» دوباره ارسال شد و لید به‌روز شد.`,
actorId,
meta: { formId: form.id, mode: 'update' },
},
});
return {
leadId: existingLead.id,
status: 'updated',
created: false,
duplicate: true,
message: null,
};
}
const stages = await this.leadStages.list(form.organizationId);
const stageId =
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای برای لید تعریف نشده');
const maxPos = await this.prisma.lead.aggregate({
where: { organizationId: form.organizationId, stageId },
_max: { position: true },
});
const created = await this.prisma.lead.create({
data: {
organizationId: form.organizationId,
title,
contactName,
mobile,
phone: emptyToNull(mapped.phone),
city: emptyToNull(mapped.city),
region: emptyToNull(mapped.region),
trade: emptyToNull(mapped.trade),
source,
notes: emptyToNull(mapped.notes),
stageId,
position: (maxPos._max.position ?? -1) + 1,
assigneeId,
createdById: actorId,
lastContactAt: new Date(),
},
});
await this.prisma.leadEvent.create({
data: {
organizationId: form.organizationId,
leadId: created.id,
type: 'created',
title: 'لید از فرم وب ساخته شد',
body: `فرم «${form.name}»`,
actorId,
meta: { formId: form.id },
},
});
return {
leadId: created.id,
status: 'created',
created: true,
duplicate: false,
message: null,
};
}
@@ -385,7 +685,9 @@ export class LeadFormsService {
const title =
mapped.dealTitle?.trim() ||
mapped.leadTitle?.trim() ||
[mapped.firstName, mapped.lastName].filter(Boolean).join(' ').trim() ||
mapped.contactName?.trim() ||
`سرنخ از ${form.name}`;
const maxPos = await this.prisma.deal.aggregate({
@@ -445,6 +747,20 @@ export class LeadFormsService {
if (!found) throw new BadRequestException('کاریز انتخاب‌شده معتبر نیست');
}
private async assertLeadStage(
organizationId: string,
leadStageId?: string | null,
) {
const id = emptyToNull(leadStageId ?? null);
if (!id) return;
await this.leadStages.ensureDefaults(organizationId);
const found = await this.prisma.leadStage.findFirst({
where: { id, organizationId },
select: { id: true },
});
if (!found) throw new BadRequestException('مرحله لید انتخاب‌شده معتبر نیست');
}
private async assertAssignees(
organizationId: string,
assigneeIds?: string[],
@@ -472,6 +788,9 @@ export class LeadFormsService {
id: r.id,
values: asStringRecord(r.values),
personId: r.personId,
leadId: r.leadId,
status: r.status,
utm: r.utm ? asStringRecord(r.utm) : null,
createdAt: r.createdAt.toISOString(),
}));
}
@@ -527,9 +846,12 @@ export class LeadFormsService {
description: row.description,
publicToken: row.publicToken,
isActive: row.isActive,
createLead: row.createLead,
createPerson: row.createPerson,
createDeal: row.createDeal,
pipelineId: row.pipelineId,
leadStageId: row.leadStageId,
duplicateMode: row.duplicateMode,
source: row.source,
thankYouMessage: row.thankYouMessage,
redirectUrl: row.redirectUrl,
@@ -548,6 +870,11 @@ export class LeadFormsService {
placeholder: f.placeholder,
options: asOptions(f.options),
})),
viewCount: row.viewCount,
startCount: row.startCount,
submitCount: row.submitCount,
leadCreateCount: row.leadCreateCount,
duplicateCount: row.duplicateCount,
publicPath: `/f/${row.publicToken}`,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
@@ -565,6 +892,12 @@ type MappedValues = {
dealTitle?: string;
dealNotes?: string;
notes?: string;
leadTitle?: string;
contactName?: string;
city?: string;
region?: string;
trade?: string;
leadSource?: string;
};
function mapValues(
@@ -590,6 +923,7 @@ function mapValues(
const parts = raw.split(/\s+/).filter(Boolean);
mapped.firstName = parts[0] || raw;
mapped.lastName = parts.slice(1).join(' ') || '—';
mapped.contactName = raw;
break;
}
case 'person.firstName':
@@ -616,6 +950,33 @@ function mapValues(
case 'deal.notes':
mapped.dealNotes = raw;
break;
case 'lead.title':
mapped.leadTitle = raw;
break;
case 'lead.contactName':
mapped.contactName = raw;
break;
case 'lead.mobile':
mapped.mobile = raw;
break;
case 'lead.phone':
mapped.phone = raw;
break;
case 'lead.city':
mapped.city = raw;
break;
case 'lead.region':
mapped.region = raw;
break;
case 'lead.trade':
mapped.trade = raw;
break;
case 'lead.notes':
mapped.notes = raw;
break;
case 'lead.source':
mapped.leadSource = raw;
break;
case 'notes':
mapped.notes = raw;
break;
@@ -693,3 +1054,49 @@ function slugKey(label: string): string {
.replace(/^_+|_+$/g, '')
.slice(0, 40);
}
function mobileKey(raw: string | null | undefined): string | null {
const n = normalizePhone(raw);
if (!n) return null;
const d = n.replace(/\D/g, '');
if (!d) return null;
if (d.startsWith('98') && d.length >= 12) return `0${d.slice(2)}`;
if (d.length === 10 && d.startsWith('9')) return `0${d}`;
return d.startsWith('0') ? d : d;
}
function normalizeDuplicateMode(raw?: string | null): string {
if (raw === 'skip' || raw === 'activity' || raw === 'update') return raw;
return 'update';
}
function buildUtm(body: SubmitLeadFormRequest): Record<string, string> | null {
const u = body.utm ?? ({} as LeadFormUtmDto);
const out: Record<string, string> = {};
const put = (k: string, v?: string) => {
const t = (v ?? '').trim();
if (t) out[k] = t.slice(0, 500);
};
put('source', u.source);
put('medium', u.medium);
put('campaign', u.campaign);
put('term', u.term);
put('content', u.content);
put('landingPage', u.landingPage || body.pageUrl);
put('referrer', u.referrer || body.referrer);
return Object.keys(out).length ? out : null;
}
function formatUtmNote(utm: Record<string, string> | null): string | null {
if (!utm) return null;
const parts = [
utm.source && `utm_source=${utm.source}`,
utm.medium && `utm_medium=${utm.medium}`,
utm.campaign && `utm_campaign=${utm.campaign}`,
utm.term && `utm_term=${utm.term}`,
utm.content && `utm_content=${utm.content}`,
utm.landingPage && `صفحه=${utm.landingPage}`,
utm.referrer && `ارجاع=${utm.referrer}`,
].filter(Boolean);
return parts.length ? `UTM: ${parts.join(' | ')}` : null;
}
@@ -5,11 +5,12 @@ import {
NotFoundException,
Param,
Post,
Req,
Res,
StreamableFile,
} from '@nestjs/common';
import type { Response } from 'express';
import { SubmitLeadFormDto } from './dto';
import type { Request, Response } from 'express';
import { LeadFormPublicEventDto, SubmitLeadFormDto } from './dto';
import { LeadFormsService } from './lead-forms.service';
import { LocalFileStorage } from '../storage/local-file.storage';
@@ -36,8 +37,32 @@ export class PublicLeadFormsController {
return new StreamableFile(this.files.openReadStream(row.coverStorageKey));
}
@Post(':token/event')
event(@Param('token') token: string, @Body() dto: LeadFormPublicEventDto) {
return this.leadFormsService.recordPublicEvent(token, dto.type);
}
@Post(':token/submit')
submit(@Param('token') token: string, @Body() dto: SubmitLeadFormDto) {
return this.leadFormsService.submit(token, dto.values ?? {});
submit(
@Param('token') token: string,
@Body() dto: SubmitLeadFormDto,
@Req() req: Request,
) {
const forwarded = req.headers['x-forwarded-for'];
const ip =
(typeof forwarded === 'string' ? forwarded.split(',')[0]?.trim() : null) ||
req.ip ||
null;
return this.leadFormsService.submit(
token,
{
values: dto.values ?? {},
utm: dto.utm,
pageUrl: dto.pageUrl,
referrer: dto.referrer,
website: dto.website,
},
ip,
);
}
}
+215 -36
View File
@@ -6,14 +6,17 @@ import { api } from '@/lib/api';
import UiIcon from '@/components/UiIcon.vue';
import type {
LeadFormDto,
LeadFormDuplicateMode,
LeadFormFieldDto,
LeadFormFieldInput,
LeadFormFieldType,
LeadFormMapTo,
LeadFormSubmissionDto,
LeadStageDto,
OrgUserDto,
PipelineDto,
} from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
type Tab = 'edit' | 'settings' | 'share' | 'responses';
type IconName =
@@ -30,8 +33,9 @@ const error = ref('');
const ok = ref('');
const tab = ref<Tab>('edit');
const desktopPreviewOpen = ref(false);
const publishOpen = ref(false);
const advancedOpen = ref(false);
const readyOpen = ref<string | null>('personal');
const readyOpen = ref<string | null>('lead');
const editFieldKey = ref<string | null>(null);
const dragKey = ref<string | null>(null);
@@ -42,15 +46,19 @@ const fields = ref<LeadFormFieldDto[]>([]);
const submitLabel = ref('ارسال درخواست');
const submitColor = ref('#14b8a6');
const isActive = ref(true);
const createPerson = ref(true);
const createDeal = ref(true);
const createLead = ref(true);
const createPerson = ref(false);
const createDeal = ref(false);
const pipelineId = ref('');
const leadStageId = ref('');
const duplicateMode = ref<LeadFormDuplicateMode>('update');
const source = ref('وب‌سایت');
const thankYouMessage = ref('');
const redirectUrl = ref('');
const assigneeIds = ref<string[]>([]);
const users = ref<OrgUserDto[]>([]);
const pipelines = ref<PipelineDto[]>([]);
const leadStages = ref<LeadStageDto[]>([]);
const submissions = ref<LeadFormSubmissionDto[]>([]);
const coverInput = ref<HTMLInputElement | null>(null);
@@ -75,7 +83,20 @@ const typeLabel: Record<string, string> = Object.fromEntries(
const readyGroups = [
{
key: 'personal', title: 'اطلاعات فردی',
key: 'lead', title: 'فیلدهای لید',
items: [
{ label: 'نام فروشگاه / عنوان', fieldType: 'text' as const, mapTo: 'lead.title' as const },
{ label: 'نام مخاطب', fieldType: 'text' as const, mapTo: 'lead.contactName' as const },
{ label: 'موبایل', fieldType: 'phone' as const, mapTo: 'lead.mobile' as const },
{ label: 'تلفن', fieldType: 'phone' as const, mapTo: 'lead.phone' as const },
{ label: 'شهر', fieldType: 'text' as const, mapTo: 'lead.city' as const },
{ label: 'منطقه', fieldType: 'text' as const, mapTo: 'lead.region' as const },
{ label: 'صنف', fieldType: 'text' as const, mapTo: 'lead.trade' as const },
{ label: 'توضیحات', fieldType: 'textarea' as const, mapTo: 'lead.notes' as const },
],
},
{
key: 'personal', title: 'اطلاعات فردی (شخص)',
items: [
{ label: 'نام و نام خانوادگی', fieldType: 'text' as const, mapTo: 'person.fullName' as const },
{ label: 'ایمیل', fieldType: 'email' as const, mapTo: 'person.email' as const },
@@ -85,27 +106,27 @@ const readyGroups = [
{
key: 'org', title: 'اطلاعات سازمانی',
items: [
{ label: 'نام شرکت', fieldType: 'text' as const, mapTo: 'custom' as const },
{ label: 'نام شرکت', fieldType: 'text' as const, mapTo: 'lead.title' as const },
{ label: 'سمت', fieldType: 'text' as const, mapTo: 'person.position' as const },
],
},
{
key: 'job', title: 'اطلاعات شغلی',
items: [{ label: 'عنوان شغلی', fieldType: 'text' as const, mapTo: 'person.position' as const }],
},
{
key: 'market', title: 'سؤالات بازاریابی',
items: [{
label: 'از کجا آشنا شدید؟', fieldType: 'select' as const, mapTo: 'custom' as const,
label: 'از کجا آشنا شدید؟', fieldType: 'select' as const, mapTo: 'lead.source' as const,
options: ['سایت', 'اینستاگرام', 'معرفی'],
}],
},
];
const origin = computed(() => window.location.origin);
const publicUrl = computed(() => (form.value ? `${origin.value}${form.value.publicPath}` : ''));
const publicBase = computed(() => {
const env = String(import.meta.env.VITE_LEAD_FORM_PUBLIC_BASE || '').replace(/\/$/, '');
return env || window.location.origin;
});
const publicUrl = computed(() => (form.value ? `${publicBase.value}${form.value.publicPath}` : ''));
const iframeSnippet = computed(
() => `<iframe src="${publicUrl.value}" width="100%" height="720" style="border:0;border-radius:16px" title="${name.value}"></iframe>`,
() =>
`<iframe src="${publicUrl.value}" style="width:100%;min-height:600px;border:0" title="${name.value || 'فرم'}" loading="lazy"></iframe>`,
);
const qrUrl = computed(() =>
`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(publicUrl.value)}`,
@@ -114,6 +135,22 @@ const coverSrc = computed(() =>
form.value?.hasCover ? `/api/public/forms/${form.value.publicToken}/cover` : '',
);
const editingField = computed(() => fields.value.find((f) => f.key === editFieldKey.value) ?? null);
const conversionRate = computed(() => {
const submits = form.value?.submitCount ?? 0;
const leads = form.value?.leadCreateCount ?? 0;
if (!submits) return '۰٪';
return `${toFaDigits(Math.round((leads / submits) * 100))}٪`;
});
const crmSummary = computed(() => {
const parts: string[] = [];
if (createLead.value) parts.push('ثبت لید');
if (createPerson.value) parts.push('شخص');
if (createDeal.value) parts.push('معامله');
const stage = leadStages.value.find((s) => s.id === leadStageId.value);
if (stage) parts.push(`مرحله: ${stage.name}`);
if (source.value) parts.push(`منبع: ${source.value}`);
return parts.join(' · ') || 'اتصال CRM تنظیم نشده';
});
function newKey(label: string) {
const base = label.replace(/\s+/g, '_').slice(0, 24) || 'field';
@@ -123,10 +160,10 @@ function newKey(label: string) {
}
function defaultMap(type: LeadFormFieldType): LeadFormMapTo {
if (type === 'email') return 'person.email';
if (type === 'phone') return 'person.mobile';
if (type === 'text') return 'person.fullName';
if (type === 'textarea') return 'deal.notes';
if (type === 'email') return 'custom';
if (type === 'phone') return 'lead.mobile';
if (type === 'text') return 'lead.contactName';
if (type === 'textarea') return 'lead.notes';
return 'custom';
}
@@ -182,9 +219,12 @@ function applyForm(row: LeadFormDto) {
submitLabel.value = row.submitLabel;
submitColor.value = row.submitColor;
isActive.value = row.isActive;
createLead.value = row.createLead;
createPerson.value = row.createPerson;
createDeal.value = row.createDeal;
pipelineId.value = row.pipelineId ?? '';
leadStageId.value = row.leadStageId ?? '';
duplicateMode.value = (row.duplicateMode as LeadFormDuplicateMode) || 'update';
source.value = row.source ?? 'وب‌سایت';
thankYouMessage.value = row.thankYouMessage ?? '';
redirectUrl.value = row.redirectUrl ?? '';
@@ -195,14 +235,16 @@ async function load() {
loading.value = true;
error.value = '';
try {
const [fRes, uRes, pRes] = await Promise.all([
const [fRes, uRes, pRes, sRes] = await Promise.all([
api.get<LeadFormDto>(`/lead-forms/${id.value}`),
api.get<OrgUserDto[]>('/users'),
api.get<PipelineDto[]>('/pipelines'),
api.get<LeadStageDto[]>('/leads/stages'),
]);
applyForm(fRes.data);
users.value = uRes.data;
pipelines.value = pRes.data;
leadStages.value = sRes.data;
} catch {
error.value = 'بارگذاری فرم ناموفق بود.';
} finally {
@@ -219,9 +261,12 @@ async function save() {
name: name.value.trim(),
description: description.value.trim() || null,
isActive: isActive.value,
createLead: createLead.value,
createPerson: createPerson.value,
createDeal: createDeal.value,
pipelineId: pipelineId.value || null,
leadStageId: leadStageId.value || null,
duplicateMode: duplicateMode.value,
source: source.value.trim() || null,
thankYouMessage: thankYouMessage.value.trim() || null,
redirectUrl: redirectUrl.value.trim() || null,
@@ -295,6 +340,9 @@ onMounted(load);
<a class="btn ghost" :href="form?.publicPath" target="_blank" rel="noopener">
<UiIcon name="eye" :size="15" /> پیش‌نمایش
</a>
<button class="btn ghost" type="button" @click="publishOpen = true">
<UiIcon name="megaphone" :size="15" /> انتشار فرم
</button>
<button class="btn primary" type="button" :disabled="saving" @click="save">
<UiIcon name="check" :size="15" /> ذخیره تغییرات
</button>
@@ -397,8 +445,9 @@ onMounted(load);
<button class="adv" type="button" @click="advancedOpen = !advancedOpen">تنظیمات پیشرفته</button>
<div v-if="advancedOpen" class="adv-box">
<label class="chk"><input v-model="createPerson" type="checkbox" /> ساخت شخص</label>
<label class="chk"><input v-model="createDeal" type="checkbox" /> ساخت معامله</label>
<label class="chk"><input v-model="createLead" type="checkbox" /> ثبت به‌عنوان لید</label>
<label class="chk"><input v-model="createPerson" type="checkbox" /> ساخت شخص (اختیاری)</label>
<label class="chk"><input v-model="createDeal" type="checkbox" /> ساخت معامله (اختیاری)</label>
</div>
</section>
@@ -428,12 +477,21 @@ onMounted(load);
</div>
<section v-else-if="tab === 'settings'" class="panel">
<h3 class="panel-title">اتصال به CRM</h3>
<label class="chk"><input v-model="isActive" type="checkbox" /> فرم فعال باشد</label>
<label class="chk"><input v-model="createLead" type="checkbox" /> ثبت پاسخ به‌عنوان لید</label>
<label>مرحله اولیه لید
<select v-model="leadStageId">
<option value="">اولین مرحله فعال</option>
<option v-for="s in leadStages" :key="s.id" :value="s.id">{{ s.name }}</option>
</select>
</label>
<label>منبع بازاریابی <input v-model="source" /></label>
<label>کاریز مقصد
<select v-model="pipelineId">
<option value="">پیش‌فرض سازمان</option>
<option v-for="p in pipelines" :key="p.id" :value="p.id">{{ p.name }}</option>
<label>سیاست شماره تکراری
<select v-model="duplicateMode">
<option value="update">به‌روزرسانی لید موجود</option>
<option value="skip">رد کردن (ثبت نشود)</option>
<option value="activity">فقط ثبت رویداد روی لید موجود</option>
</select>
</label>
<label>پیام تشکر <input v-model="thankYouMessage" /></label>
@@ -451,10 +509,25 @@ onMounted(load);
{{ u.fullName }}
</button>
</div>
<h3 class="panel-title">مسیر اختیاری شخص / معامله</h3>
<label class="chk"><input v-model="createPerson" type="checkbox" /> ساخت شخص</label>
<label class="chk"><input v-model="createDeal" type="checkbox" /> ساخت معامله</label>
<label>کاریز مقصد (برای معامله)
<select v-model="pipelineId">
<option value="">پیش‌فرض سازمان</option>
<option v-for="p in pipelines" :key="p.id" :value="p.id">{{ p.name }}</option>
</select>
</label>
<button class="btn primary" type="button" @click="save">ذخیره تنظیمات</button>
</section>
<section v-else-if="tab === 'share'" class="panel">
<div class="share-actions">
<button class="btn primary" type="button" @click="publishOpen = true">
<UiIcon name="megaphone" :size="15" /> باز کردن مودال انتشار
</button>
</div>
<label>لینک عمومی
<div class="row">
<input :value="publicUrl" readonly />
@@ -463,17 +536,31 @@ onMounted(load);
</label>
<label>کد iframe
<div class="row">
<input :value="iframeSnippet" readonly />
<textarea class="iframe-code" :value="iframeSnippet" readonly rows="3" />
<button class="btn ghost" type="button" @click="copyText(iframeSnippet)">کپی</button>
</div>
</label>
<img v-if="publicUrl" :src="qrUrl" alt="QR" width="140" height="140" />
<p class="crm-hint">{{ crmSummary }}</p>
<button class="link" type="button" @click="tab = 'settings'">ویرایش اتصال CRM</button>
</section>
<section v-else class="panel">
<div v-if="form" class="stats-grid">
<div class="stat"><b>{{ toFaDigits(form.viewCount) }}</b><span>بازدید</span></div>
<div class="stat"><b>{{ toFaDigits(form.startCount) }}</b><span>شروع پر کردن</span></div>
<div class="stat"><b>{{ toFaDigits(form.submitCount) }}</b><span>ارسال</span></div>
<div class="stat"><b>{{ toFaDigits(form.leadCreateCount) }}</b><span>لید جدید</span></div>
<div class="stat"><b>{{ toFaDigits(form.duplicateCount) }}</b><span>تکراری</span></div>
<div class="stat"><b>{{ conversionRate }}</b><span>نرخ submit→lead</span></div>
</div>
<p v-if="!submissions.length">هنوز پاسخی ثبت نشده.</p>
<article v-for="s in submissions" :key="s.id" class="sub">
<small>{{ new Date(s.createdAt).toLocaleString('fa-IR') }}</small>
<small>
{{ new Date(s.createdAt).toLocaleString('fa-IR') }}
<span v-if="s.status"> · {{ s.status }}</span>
<span v-if="s.leadId"> · لید</span>
</small>
<p v-for="(val, key) in s.values" :key="key"><b>{{ key }}:</b> {{ val }}</p>
</article>
</section>
@@ -527,16 +614,31 @@ onMounted(load);
<label class="chk"><input v-model="editingField.required" type="checkbox" /> الزامی</label>
<label>اتصال به
<select v-model="editingField.mapTo">
<option value="person.fullName">نام کامل</option>
<option value="person.firstName">نام</option>
<option value="person.lastName">نام خانوادگی</option>
<option value="person.mobile">موبایل</option>
<option value="person.email">ایمیل</option>
<option value="person.phone">تلفن</option>
<option value="person.position">سمت</option>
<option value="deal.title">عنوان معامله</option>
<option value="deal.notes">یادداشت معامله</option>
<option value="notes">یادداشت شخص</option>
<optgroup label="لید">
<option value="lead.title">عنوان / نام فروشگاه</option>
<option value="lead.contactName">نام مخاطب</option>
<option value="lead.mobile">موبایل لید</option>
<option value="lead.phone">تلفن لید</option>
<option value="lead.city">شهر</option>
<option value="lead.region">منطقه</option>
<option value="lead.trade">صنف</option>
<option value="lead.notes">یادداشت لید</option>
<option value="lead.source">منبع لید</option>
</optgroup>
<optgroup label="شخص">
<option value="person.fullName">نام کامل</option>
<option value="person.firstName">نام</option>
<option value="person.lastName">نام خانوادگی</option>
<option value="person.mobile">موبایل</option>
<option value="person.email">ایمیل</option>
<option value="person.phone">تلفن</option>
<option value="person.position">سمت</option>
</optgroup>
<optgroup label="معامله">
<option value="deal.title">عنوان معامله</option>
<option value="deal.notes">یادداشت معامله</option>
</optgroup>
<option value="notes">یادداشت</option>
<option value="custom">فقط در پاسخ فرم</option>
</select>
</label>
@@ -551,6 +653,41 @@ onMounted(load);
<button class="btn primary" type="button" @click="editFieldKey = null">تمام</button>
</div>
</div>
<div v-if="publishOpen" class="overlay" @click.self="publishOpen = false">
<div class="sheet publish-sheet" role="dialog" aria-label="انتشار فرم">
<header class="publish-head">
<strong>انتشار فرم</strong>
<button class="btn ghost" type="button" @click="publishOpen = false">بستن</button>
</header>
<div class="publish-preview">
<div class="mini-cover" :style="{ background: submitColor }">
<img v-if="coverSrc" :src="coverSrc" alt="" />
</div>
<div>
<h4>{{ name || 'فرم' }}</h4>
<p>{{ crmSummary }}</p>
<a :href="form?.publicPath" target="_blank" rel="noopener">باز کردن پیش‌نمایش</a>
</div>
</div>
<label>لینک مستقیم
<div class="row">
<input :value="publicUrl" readonly />
<button class="btn ghost" type="button" @click="copyText(publicUrl)">کپی</button>
</div>
</label>
<label>کد iframe ریسپانسیو
<div class="row col">
<textarea class="iframe-code" :value="iframeSnippet" readonly rows="3" />
<button class="btn ghost" type="button" @click="copyText(iframeSnippet)">کپی iframe</button>
</div>
</label>
<img v-if="publicUrl" class="publish-qr" :src="qrUrl" alt="QR" width="120" height="120" />
<button class="link" type="button" @click="publishOpen = false; tab = 'settings'">
تنظیم اتصال CRM
</button>
</div>
</div>
</section>
</template>
@@ -637,6 +774,48 @@ h1 :deep(.ico) { color: var(--teal); }
.overlay { position: fixed; inset: 0; background: rgba(15,23,42,.35); display: grid; place-items: center; z-index: 40; padding: 1rem; }
.sheet { width: min(420px,100%); background: #fff; border-radius: var(--radius); padding: 1rem; display: grid; gap: 0.65rem; }
.link { background: none; border: 0; color: #0f766e; font: inherit; font-weight: 700; cursor: pointer; }
.panel-title { margin: 0.4rem 0 0; font-size: 0.95rem; color: #0f766e; }
.share-actions { display: flex; gap: 0.4rem; }
.iframe-code { flex: 1; border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; font: inherit; width: 100%; resize: vertical; }
.row.col { flex-direction: column; align-items: stretch; }
.crm-hint { margin: 0; color: #64748b; font-size: 0.85rem; }
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
gap: 0.55rem;
margin-bottom: 0.85rem;
}
.stat {
background: #f0fdfa;
border: 1px solid #ccfbf1;
border-radius: var(--radius);
padding: 0.65rem 0.7rem;
display: grid;
gap: 0.15rem;
}
.stat b { font-size: 1.15rem; color: #0f766e; }
.stat span { font-size: 0.75rem; color: #64748b; }
.publish-sheet { width: min(520px, 100%); gap: 0.75rem; }
.publish-head { display: flex; justify-content: space-between; align-items: center; }
.publish-preview {
display: grid;
grid-template-columns: 72px 1fr;
gap: 0.75rem;
align-items: center;
padding: 0.65rem;
background: #f8fafc;
border-radius: var(--radius);
}
.publish-preview h4 { margin: 0 0 0.25rem; }
.publish-preview p { margin: 0 0 0.35rem; color: #64748b; font-size: 0.82rem; }
.mini-cover {
width: 72px;
height: 72px;
border-radius: var(--radius);
overflow: hidden;
}
.mini-cover img { width: 100%; height: 100%; object-fit: cover; }
.publish-qr { justify-self: start; border-radius: 8px; }
@media (max-width: 1100px) {
.workspace { grid-template-columns: 1fr; }
.preview-col { order: 3; }
+59 -3
View File
@@ -10,14 +10,47 @@ const saving = ref(false);
const error = ref('');
const done = ref(false);
const thankYou = ref('');
const started = ref(false);
const form = ref<PublicLeadFormDto | null>(null);
const values = reactive<Record<string, string>>({});
const honeypot = ref('');
const token = String(route.params.token || '');
const coverUrl = computed(() =>
form.value?.coverPath || (form.value?.hasCover ? `/api/public/forms/${token}/cover` : ''),
);
function readUtm() {
const q = route.query;
const pick = (key: string) => {
const v = q[key];
return typeof v === 'string' ? v : Array.isArray(v) ? String(v[0] || '') : '';
};
return {
source: pick('utm_source'),
medium: pick('utm_medium'),
campaign: pick('utm_campaign'),
term: pick('utm_term'),
content: pick('utm_content'),
landingPage: typeof window !== 'undefined' ? window.location.href : '',
referrer: typeof document !== 'undefined' ? document.referrer : '',
};
}
async function postEvent(type: 'view' | 'start') {
try {
await axios.post(`/api/public/forms/${token}/event`, { type });
} catch {
/* ignore analytics errors */
}
}
function onFieldFocus() {
if (started.value) return;
started.value = true;
void postEvent('start');
}
async function load() {
loading.value = true;
error.value = '';
@@ -28,6 +61,7 @@ async function load() {
if (field.fieldType === 'heading') continue;
values[field.key] = values[field.key] ?? '';
}
void postEvent('view');
} catch {
error.value = 'این فرم پیدا نشد یا غیرفعال است.';
form.value = null;
@@ -52,11 +86,21 @@ async function submit() {
saving.value = true;
error.value = '';
try {
const utm = readUtm();
const { data } = await axios.post<SubmitLeadFormResponse>(
`/api/public/forms/${token}/submit`,
{ values: { ...values } },
{
values: { ...values },
utm,
pageUrl: window.location.href,
referrer: document.referrer || undefined,
website: honeypot.value,
},
);
thankYou.value = data.thankYouMessage || 'ثبت شد. متشکریم.';
thankYou.value =
data.message ||
data.thankYouMessage ||
'ثبت شد. متشکریم.';
done.value = true;
if (data.redirectUrl) window.location.assign(data.redirectUrl);
} catch (e) {
@@ -95,9 +139,14 @@ onMounted(load);
</div>
<form v-else-if="form" class="fields" @submit.prevent="submit">
<!-- honeypot -->
<label class="hp" aria-hidden="true">
وب‌سایت
<input v-model="honeypot" type="text" tabindex="-1" autocomplete="off" />
</label>
<template v-for="field in form.fields" :key="field.key">
<p v-if="field.fieldType === 'heading'" class="heading">{{ field.label }}</p>
<label v-else>
<label v-else @focusin="onFieldFocus">
{{ field.label }}
<span v-if="field.required" class="req">*</span>
<textarea
@@ -200,4 +249,11 @@ input, textarea, select {
.stars button { border: 0; background: none; font-size: 1.3rem; color: #cbd5e1; cursor: pointer; }
.stars button.on { color: #eab308; }
.heading { margin: 0; font-weight: 700; color: #0f172a; }
.hp {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
</style>
+25 -4
View File
@@ -43,8 +43,10 @@ async function createForm() {
name: 'درخواست مشاوره',
description: 'فرم دریافت درخواست مشاوره مشتریان',
source: 'وب‌سایت',
createPerson: true,
createDeal: true,
createLead: true,
createPerson: false,
createDeal: false,
duplicateMode: 'update',
});
await router.push({ name: 'lead-form-builder', params: { id: data.id } });
} catch {
@@ -60,6 +62,16 @@ async function removeForm(form: LeadFormDto) {
await load();
}
function publicUrl(form: LeadFormDto) {
const base = String(import.meta.env.VITE_LEAD_FORM_PUBLIC_BASE || '').replace(/\/$/, '')
|| window.location.origin;
return `${base}${form.publicPath}`;
}
async function copyPublishLink(form: LeadFormDto) {
await navigator.clipboard.writeText(publicUrl(form));
}
const countLabel = computed(() => toFaDigits(forms.value.length));
onMounted(load);
@@ -69,7 +81,7 @@ onMounted(load);
<section class="crm-page lead-forms-page" dir="rtl">
<UiPageHeader
title="فرم‌ساز وب"
description="فرم‌های آنلاین بسازید، فیلدها را بچینید و لیدها را به صورت خودکار در کاریز و باشگاه مشتریان دریافت کنید."
description="فرم‌های آنلاین بسازید، در وب‌سایت منتشر کنید و لیدها را مستقیم در CRM دریافت کنید."
>
<template #actions>
<UiButton :loading="saving" @click="createForm">
@@ -115,7 +127,9 @@ onMounted(load);
<p class="form-meta">
<span>{{ toFaDigits(form.fields.length) }} فیلد سفارشی</span>
<span class="meta-dot">·</span>
<span>{{ toFaDigits(form.submissionCount ?? 0) }} ارسال شده</span>
<span>{{ toFaDigits(form.submitCount ?? form.submissionCount ?? 0) }} ارسال</span>
<span class="meta-dot">·</span>
<span>{{ toFaDigits(form.leadCreateCount ?? 0) }} لید</span>
<span v-if="form.source" class="meta-dot">·</span>
<span v-if="form.source">منبع: {{ form.source }}</span>
</p>
@@ -131,6 +145,13 @@ onMounted(load);
</UiButton>
</RouterLink>
<UiButton variant="secondary" size="sm" @click="copyPublishLink(form)">
<template #icon>
<UiIcon name="megaphone" />
</template>
کپی لینک انتشار
</UiButton>
<a :href="form.publicPath" target="_blank" rel="noopener" class="preview-link">
<UiButton variant="ghost" size="sm">
<template #icon>
+50
View File
@@ -1425,9 +1425,20 @@ export type LeadFormMapTo =
| "person.position"
| "deal.title"
| "deal.notes"
| "lead.title"
| "lead.contactName"
| "lead.mobile"
| "lead.phone"
| "lead.city"
| "lead.region"
| "lead.trade"
| "lead.notes"
| "lead.source"
| "notes"
| "custom";
export type LeadFormDuplicateMode = "skip" | "update" | "activity";
export interface LeadFormFieldDto {
id: string;
key: string;
@@ -1446,9 +1457,12 @@ export interface LeadFormDto {
description: string | null;
publicToken: string;
isActive: boolean;
createLead: boolean;
createPerson: boolean;
createDeal: boolean;
pipelineId: string | null;
leadStageId: string | null;
duplicateMode: LeadFormDuplicateMode | string;
source: string | null;
thankYouMessage: string | null;
redirectUrl: string | null;
@@ -1458,6 +1472,11 @@ export interface LeadFormDto {
hasCover: boolean;
fields: LeadFormFieldDto[];
submissionCount?: number;
viewCount: number;
startCount: number;
submitCount: number;
leadCreateCount: number;
duplicateCount: number;
publicPath: string;
createdAt: string;
updatedAt: string;
@@ -1477,9 +1496,12 @@ export interface LeadFormFieldInput {
export interface CreateLeadFormRequest {
name: string;
description?: string | null;
createLead?: boolean;
createPerson?: boolean;
createDeal?: boolean;
pipelineId?: string | null;
leadStageId?: string | null;
duplicateMode?: LeadFormDuplicateMode | string;
source?: string | null;
thankYouMessage?: string | null;
redirectUrl?: string | null;
@@ -1493,9 +1515,12 @@ export interface UpdateLeadFormRequest {
name?: string;
description?: string | null;
isActive?: boolean;
createLead?: boolean;
createPerson?: boolean;
createDeal?: boolean;
pipelineId?: string | null;
leadStageId?: string | null;
duplicateMode?: LeadFormDuplicateMode | string;
source?: string | null;
thankYouMessage?: string | null;
redirectUrl?: string | null;
@@ -1509,6 +1534,7 @@ export interface PublicLeadFormDto {
name: string;
description: string | null;
thankYouMessage: string | null;
redirectUrl: string | null;
submitLabel: string;
submitColor: string;
hasCover: boolean;
@@ -1527,19 +1553,43 @@ export interface LeadFormSubmissionDto {
id: string;
values: Record<string, string>;
personId: string | null;
leadId: string | null;
status: string;
utm: Record<string, string> | null;
createdAt: string;
}
export interface LeadFormUtmDto {
source?: string;
medium?: string;
campaign?: string;
term?: string;
content?: string;
landingPage?: string;
referrer?: string;
}
export interface SubmitLeadFormRequest {
values: Record<string, string>;
utm?: LeadFormUtmDto;
pageUrl?: string;
referrer?: string;
/** honeypot — must be empty */
website?: string;
}
export interface SubmitLeadFormResponse {
ok: true;
thankYouMessage: string | null;
redirectUrl: string | null;
outcome?: "created" | "updated" | "duplicate_skipped";
leadId?: string | null;
duplicate?: boolean;
message?: string | null;
}
export type LeadFormPublicEvent = "view" | "start";
export type QuoteStatus =
| "draft"
| "sent"