feat: SMS campaigns for people or leads with filters and batching

Add audience tabs, province/city filters, select-all ids, dynamic SMS tokens, and 50-sized create/send chunks.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-17 20:54:32 +03:30
co-authored by Cursor
parent 32c722f42a
commit d62e004e90
10 changed files with 1040 additions and 131 deletions
+17
View File
@@ -63,6 +63,23 @@ export class ListQueryDto {
@IsString()
@MaxLength(40)
importSource?: string;
/** استان شرکت مرتبط */
@IsOptional()
@IsString()
@MaxLength(80)
province?: string;
/** شهر/شهرستان شرکت مرتبط */
@IsOptional()
@IsString()
@MaxLength(80)
city?: string;
/** فقط کسانی که موبایل دارند */
@IsOptional()
@IsIn(['1', 'true', '0', 'false'])
hasMobile?: string;
}
class CompanyExtraFieldsDto {
@@ -43,6 +43,10 @@ export class PeopleController {
@Get()
list(@CurrentUser() user: Actor, @Query() query: ListQueryDto) {
const hasMobile =
query.hasMobile === '1' || query.hasMobile === 'true'
? true
: undefined;
return this.peopleService.list(
user,
query.q,
@@ -52,10 +56,28 @@ export class PeopleController {
mood: query.mood,
sort: query.sort,
importSource: query.importSource,
province: query.province,
city: query.city,
hasMobile,
},
);
}
@Get('ids')
listIds(@CurrentUser() user: Actor, @Query() query: ListQueryDto) {
const hasMobile =
query.hasMobile === '1' || query.hasMobile === 'true'
? true
: undefined;
return this.peopleService.listIds(user, query.q, {
mood: query.mood,
importSource: query.importSource,
province: query.province,
city: query.city,
hasMobile,
});
}
@Get('source-stats')
sourceStats(@CurrentUser() user: Actor) {
return this.peopleService.sourceStats(user);
+86 -9
View File
@@ -10,12 +10,14 @@ import {
} from '@nestjs/common';
import type {
CreatePersonRequest,
FilteredIdsResponse,
PaginatedResponse,
PersonDto,
PersonImportSourceStatDto,
PersonMood,
UpdatePersonRequest,
} from '@mento/shared';
import { FILTERED_IDS_MAX } from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CompaniesService } from './companies.service';
@@ -49,7 +51,7 @@ import {
} from './person-source';
const personInclude = {
company: { select: { id: true, name: true } },
company: { select: { id: true, name: true, province: true, city: true } },
owner: { select: { id: true, fullName: true } },
loyaltyTier: {
select: { id: true, name: true, minPoints: true, color: true },
@@ -82,7 +84,12 @@ type PersonRow = {
loyaltyPoints: number;
createdAt: Date;
updatedAt: Date;
company: { id: string; name: string } | null;
company: {
id: string;
name: string;
province: string | null;
city: string | null;
} | null;
owner: { id: string; fullName: string } | null;
loyaltyTier: {
id: string;
@@ -106,17 +113,17 @@ export class PeopleService implements OnModuleInit {
private readonly sms: SmsService,
) {}
async list(
private personListWhere(
actor: Actor,
q?: string,
page = 1,
limit = 20,
opts?: {
mood?: PersonMood;
sort?: 'name' | 'newest';
importSource?: string;
province?: string;
city?: string;
hasMobile?: boolean;
},
): Promise<PaginatedResponse<PersonDto>> {
): Prisma.PersonWhereInput {
const sourceFilter = opts?.importSource?.trim()
? normalizePersonImportSource(opts.importSource)
: undefined;
@@ -131,14 +138,56 @@ export class PeopleService implements OnModuleInit {
{ sourceRef: ci(t) },
{ previousSourceRef: ci(t) },
{ company: { name: ci(t) } },
{ company: { province: ci(t) } },
{ company: { city: ci(t) } },
]);
const where: Prisma.PersonWhereInput = {
const province = opts?.province?.trim();
const city = opts?.city?.trim();
const and: Prisma.PersonWhereInput[] = [];
if (search) and.push(search);
if (province) {
and.push({
OR: [
{ company: { province: { contains: province, mode: 'insensitive' } } },
{ company: { city: { contains: province, mode: 'insensitive' } } },
],
});
}
if (city) {
and.push({
OR: [
{ company: { city: { contains: city, mode: 'insensitive' } } },
{ company: { province: { contains: city, mode: 'insensitive' } } },
],
});
}
if (opts?.hasMobile) {
and.push({ mobile: { not: null } }, { NOT: { mobile: '' } });
}
return {
organizationId: actor.organizationId,
...ownerWhere(actor),
...(opts?.mood ? { mood: opts.mood } : {}),
...(sourceFilter ? { importSource: sourceFilter } : {}),
...(search ? { AND: [search] } : {}),
...(and.length ? { AND: and } : {}),
};
}
async list(
actor: Actor,
q?: string,
page = 1,
limit = 20,
opts?: {
mood?: PersonMood;
sort?: 'name' | 'newest';
importSource?: string;
province?: string;
city?: string;
hasMobile?: boolean;
},
): Promise<PaginatedResponse<PersonDto>> {
const where = this.personListWhere(actor, q, opts);
const [rows, total] = await this.prisma.$transaction([
this.prisma.person.findMany({
@@ -162,6 +211,34 @@ export class PeopleService implements OnModuleInit {
};
}
async listIds(
actor: Actor,
q?: string,
opts?: {
mood?: PersonMood;
importSource?: string;
province?: string;
city?: string;
hasMobile?: boolean;
},
max = FILTERED_IDS_MAX,
): Promise<FilteredIdsResponse> {
const where = this.personListWhere(actor, q, opts);
const total = await this.prisma.person.count({ where });
if (total > max) {
throw new BadRequestException(
`تعداد نتایج (${total}) از سقف مجاز بیشتر است؛ فیلتر را محدودتر کنید.`,
);
}
const rows = await this.prisma.person.findMany({
where,
select: { id: true },
orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }],
take: max,
});
return { ids: rows.map((r) => r.id), total };
}
async sourceStats(actor: Actor): Promise<PersonImportSourceStatDto[]> {
const rows = await this.prisma.person.groupBy({
by: ['importSource'],
+32
View File
@@ -231,6 +231,34 @@ export class LeadsController {
return new StreamableFile(buffer);
}
@Get('ids')
listIds(
@CurrentUser() user: Actor,
@Query('q') q?: string,
@Query('stageId') stageId?: string,
@Query('assigneeId') assigneeId?: string,
@Query('city') city?: string,
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('hasMobile') hasMobile?: string,
) {
return this.leads.listIds(user, {
q,
stageId,
assigneeId,
city,
region,
trade,
source,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
hasMobile: hasMobile === '1' || hasMobile === 'true',
});
}
@Get()
list(
@CurrentUser() user: Actor,
@@ -240,11 +268,13 @@ export class LeadsController {
@Query('stageId') stageId?: string,
@Query('assigneeId') assigneeId?: string,
@Query('city') city?: string,
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('sort') sort?: string,
@Query('hasMobile') hasMobile?: string,
) {
return this.leads.list(user, {
q,
@@ -253,11 +283,13 @@ export class LeadsController {
stageId,
assigneeId,
city,
region,
trade,
source,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
sort,
hasMobile: hasMobile === '1' || hasMobile === 'true',
});
}
+73 -11
View File
@@ -11,6 +11,7 @@ import * as path from 'node:path';
import { randomUUID } from 'node:crypto';
import type {
ConvertLeadResult,
FilteredIdsResponse,
LeadBoardColumnDto,
LeadDto,
LeadDuplicateCheckResult,
@@ -18,6 +19,7 @@ import type {
LeadStatsDto,
PaginatedResponse,
} from '@mento/shared';
import { FILTERED_IDS_MAX } from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/sms.service';
import { renderSmsText } from '../common/sms-text';
@@ -105,25 +107,21 @@ export class LeadsService {
});
}
async list(
private leadListWhere(
actor: Actor,
opts: {
q?: string;
page?: number;
limit?: number;
stageId?: string;
assigneeId?: string;
city?: string;
region?: string;
trade?: string;
source?: string;
unassigned?: boolean;
archived?: boolean;
sort?: string;
hasMobile?: boolean;
},
): Promise<PaginatedResponse<LeadDto>> {
await this.stages.ensureDefaults(actor.organizationId);
const page = Math.max(1, opts.page ?? 1);
const limit = Math.min(100, Math.max(1, opts.limit ?? 20));
): Prisma.LeadWhereInput {
const search = buildSearchWhere<Prisma.LeadWhereInput>(opts.q, (t) => [
{ title: ci(t) },
{ contactName: ci(t) },
@@ -135,8 +133,12 @@ export class LeadsService {
{ instagram: ci(t) },
{ source: ci(t) },
]);
const where: Prisma.LeadWhereInput = {
const and: Prisma.LeadWhereInput[] = [];
if (search) and.push(search);
if (opts.hasMobile) {
and.push({ mobile: { not: '' } });
}
return {
organizationId: actor.organizationId,
...leadAccessWhere(actor),
archivedAt: opts.archived ? { not: null } : null,
@@ -144,12 +146,39 @@ export class LeadsService {
...(opts.assigneeId ? { assigneeId: opts.assigneeId } : {}),
...(opts.unassigned ? { assigneeId: null } : {}),
...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}),
...(opts.region
? { region: { contains: opts.region, mode: 'insensitive' } }
: {}),
...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}),
...(opts.source
? { source: { contains: opts.source, mode: 'insensitive' } }
: {}),
...(search ? { AND: [search] } : {}),
...(and.length ? { AND: and } : {}),
};
}
async list(
actor: Actor,
opts: {
q?: string;
page?: number;
limit?: number;
stageId?: string;
assigneeId?: string;
city?: string;
region?: string;
trade?: string;
source?: string;
unassigned?: boolean;
archived?: boolean;
sort?: string;
hasMobile?: boolean;
},
): Promise<PaginatedResponse<LeadDto>> {
await this.stages.ensureDefaults(actor.organizationId);
const page = Math.max(1, opts.page ?? 1);
const limit = Math.min(100, Math.max(1, opts.limit ?? 20));
const where = this.leadListWhere(actor, opts);
const orderBy: Prisma.LeadOrderByWithRelationInput =
opts.sort === 'follow_up'
@@ -179,6 +208,39 @@ export class LeadsService {
};
}
async listIds(
actor: Actor,
opts: {
q?: string;
stageId?: string;
assigneeId?: string;
city?: string;
region?: string;
trade?: string;
source?: string;
unassigned?: boolean;
archived?: boolean;
hasMobile?: boolean;
},
max = FILTERED_IDS_MAX,
): Promise<FilteredIdsResponse> {
await this.stages.ensureDefaults(actor.organizationId);
const where = this.leadListWhere(actor, opts);
const total = await this.prisma.lead.count({ where });
if (total > max) {
throw new BadRequestException(
`تعداد نتایج (${total}) از سقف مجاز بیشتر است؛ فیلتر را محدودتر کنید.`,
);
}
const rows = await this.prisma.lead.findMany({
where,
select: { id: true },
orderBy: { updatedAt: 'desc' },
take: max,
});
return { ids: rows.map((r) => r.id), total };
}
async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
const stages = await this.stages.list(actor.organizationId);
const boardStages = stages.filter((s) => s.showOnBoard);
@@ -8,6 +8,7 @@ import {
UseGuards,
} from '@nestjs/common';
import {
ArrayMaxSize,
IsArray,
IsBoolean,
IsDateString,
@@ -21,12 +22,14 @@ import {
ValidateIf,
} from 'class-validator';
import { Type } from 'class-transformer';
import { SMS_CAMPAIGN_CHUNK_SIZE } from '@mento/shared';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { OrgModuleGuard } from '../billing/org-module.guard';
import { RequireOrgModule } from '../billing/org-module.decorator';
import type { Actor } from '../common/record-scope';
import { SmsCampaignsService } from './sms-campaigns.service';
class CreateSmsCampaignDto {
@@ -40,9 +43,17 @@ class CreateSmsCampaignDto {
@MaxLength(900)
body!: string;
@IsOptional()
@IsArray()
@ArrayMaxSize(SMS_CAMPAIGN_CHUNK_SIZE)
@IsString({ each: true })
personIds!: string[];
personIds?: string[];
@IsOptional()
@IsArray()
@ArrayMaxSize(SMS_CAMPAIGN_CHUNK_SIZE)
@IsString({ each: true })
leadIds?: string[];
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@@ -54,6 +65,20 @@ class CreateSmsCampaignDto {
queueNow?: boolean;
}
class AddRecipientsDto {
@IsOptional()
@IsArray()
@ArrayMaxSize(SMS_CAMPAIGN_CHUNK_SIZE)
@IsString({ each: true })
personIds?: string[];
@IsOptional()
@IsArray()
@ArrayMaxSize(SMS_CAMPAIGN_CHUNK_SIZE)
@IsString({ each: true })
leadIds?: string[];
}
class ListQueryDto {
@IsOptional()
@Type(() => Number)
@@ -105,19 +130,17 @@ export class SmsCampaignsController {
}
@Post()
create(
@CurrentUser()
user: { organizationId: string; userId: string; role: string },
@Body() dto: CreateSmsCampaignDto,
create(@CurrentUser() user: Actor, @Body() dto: CreateSmsCampaignDto) {
return this.campaigns.create(user, dto);
}
@Post(':id/recipients')
addRecipients(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Body() dto: AddRecipientsDto,
) {
return this.campaigns.create(
{
organizationId: user.organizationId,
userId: user.userId,
role: user.role as 'owner' | 'admin' | 'sales' | 'support',
},
dto,
);
return this.campaigns.addRecipients(user, id, dto);
}
@Post(':id/queue')
@@ -5,6 +5,7 @@ import {
} from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import type {
AddSmsCampaignRecipientsRequest,
CreateSmsCampaignRequest,
SmsCampaignClickerDto,
SmsCampaignDto,
@@ -12,10 +13,32 @@ import type {
SmsCampaignReportDto,
SmsCampaignStatus,
} from '@mento/shared';
import { SMS_CAMPAIGN_CHUNK_SIZE } from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/sms.service';
import { type Actor, ownerWhere } from '../common/record-scope';
import { renderSmsText } from '../common/sms-text';
import {
type Actor,
elevated,
forScope,
ownerWhere,
} from '../common/record-scope';
import { TrackingService } from '../tracking/tracking.service';
import type { Prisma } from '@prisma/client';
function leadAccessWhere(baseActor: Actor): Prisma.LeadWhereInput {
const actor = forScope(baseActor, 'leads');
if (elevated(actor.role)) return {};
if (actor.dataVisibility === 'org') return {};
if (
actor.dataVisibility === 'team' &&
actor.visibleUserIds &&
actor.visibleUserIds.length
) {
return { assigneeId: { in: actor.visibleUserIds } };
}
return { assigneeId: actor.userId };
}
@Injectable()
export class SmsCampaignsService {
@@ -230,19 +253,24 @@ export class SmsCampaignsService {
throw new BadRequestException('متن پیامک کوتاه است');
}
const personIds = [...new Set((dto.personIds ?? []).filter(Boolean))];
if (!personIds.length) {
const leadIds = [...new Set((dto.leadIds ?? []).filter(Boolean))];
if (personIds.length && leadIds.length) {
throw new BadRequestException('کمپین نمی‌تواند همزمان شخص و لید داشته باشد.');
}
if (!personIds.length && !leadIds.length) {
throw new BadRequestException('حداقل یک مخاطب انتخاب کنید');
}
if (personIds.length > SMS_CAMPAIGN_CHUNK_SIZE || leadIds.length > SMS_CAMPAIGN_CHUNK_SIZE) {
throw new BadRequestException(
`حداکثر ${SMS_CAMPAIGN_CHUNK_SIZE} مخاطب در هر درخواست مجاز است.`,
);
}
const people = await this.prisma.person.findMany({
where: {
id: { in: personIds },
organizationId: actor.organizationId,
...ownerWhere(actor),
},
select: { id: true, mobile: true },
});
if (!people.length) throw new BadRequestException('مخاطب معتبری پیدا نشد');
const recipients =
personIds.length > 0
? await this.resolvePersonRecipients(actor, personIds)
: await this.resolveLeadRecipients(actor, leadIds);
if (!recipients.length) throw new BadRequestException('مخاطب معتبری پیدا نشد');
const queueNow = Boolean(dto.queueNow);
const scheduledAt = dto.scheduledAt ? new Date(dto.scheduledAt) : null;
@@ -252,6 +280,7 @@ export class SmsCampaignsService {
const status: SmsCampaignStatus =
queueNow || scheduledAt ? 'queued' : 'draft';
const skipped = recipients.filter((r) => !r.mobile).length;
const campaign = await this.prisma.smsCampaign.create({
data: {
@@ -260,27 +289,143 @@ export class SmsCampaignsService {
body,
status,
scheduledAt: queueNow ? new Date() : scheduledAt,
totalCount: people.length,
totalCount: recipients.length,
skippedCount: skipped,
createdById: actor.userId,
recipients: {
create: people.map((p) => ({
personId: p.id,
mobile: p.mobile,
status: p.mobile ? 'pending' : 'skipped',
create: recipients.map((r) => ({
personId: r.personId,
leadId: r.leadId,
mobile: r.mobile,
status: r.mobile ? 'pending' : 'skipped',
})),
},
},
});
const skipped = people.filter((p) => !p.mobile).length;
if (skipped) {
await this.prisma.smsCampaign.update({
where: { id: campaign.id },
data: { skippedCount: skipped },
});
return this.get(actor.organizationId, campaign.id);
}
async addRecipients(
actor: Actor,
campaignId: string,
dto: AddSmsCampaignRecipientsRequest,
): Promise<SmsCampaignDto> {
const campaign = await this.prisma.smsCampaign.findFirst({
where: { id: campaignId, organizationId: actor.organizationId },
});
if (!campaign) throw new NotFoundException('کمپین پیدا نشد');
if (campaign.status !== 'draft' && campaign.status !== 'cancelled') {
throw new BadRequestException('فقط به کمپین پیش‌نویس می‌توان مخاطب افزود.');
}
return this.get(actor.organizationId, campaign.id);
const personIds = [...new Set((dto.personIds ?? []).filter(Boolean))];
const leadIds = [...new Set((dto.leadIds ?? []).filter(Boolean))];
if (personIds.length && leadIds.length) {
throw new BadRequestException('در هر درخواست فقط شخص یا فقط لید بفرستید.');
}
if (!personIds.length && !leadIds.length) {
throw new BadRequestException('حداقل یک مخاطب انتخاب کنید');
}
if (personIds.length > SMS_CAMPAIGN_CHUNK_SIZE || leadIds.length > SMS_CAMPAIGN_CHUNK_SIZE) {
throw new BadRequestException(
`حداکثر ${SMS_CAMPAIGN_CHUNK_SIZE} مخاطب در هر درخواست مجاز است.`,
);
}
const existingSample = await this.prisma.smsCampaignRecipient.findFirst({
where: { campaignId },
select: { personId: true, leadId: true },
});
if (existingSample?.personId && leadIds.length) {
throw new BadRequestException('این کمپین فقط برای اشخاص است.');
}
if (existingSample?.leadId && personIds.length) {
throw new BadRequestException('این کمپین فقط برای لیدها است.');
}
const resolved =
personIds.length > 0
? await this.resolvePersonRecipients(actor, personIds)
: await this.resolveLeadRecipients(actor, leadIds);
const existingIds = new Set(
(
await this.prisma.smsCampaignRecipient.findMany({
where: { campaignId },
select: { personId: true, leadId: true },
})
).map((r) => r.personId ?? r.leadId ?? ''),
);
const fresh = resolved.filter(
(r) => !existingIds.has(r.personId ?? r.leadId ?? ''),
);
if (!fresh.length) {
return this.get(actor.organizationId, campaignId);
}
const skipped = fresh.filter((r) => !r.mobile).length;
await this.prisma.smsCampaignRecipient.createMany({
data: fresh.map((r) => ({
campaignId,
personId: r.personId,
leadId: r.leadId,
mobile: r.mobile,
status: r.mobile ? 'pending' : 'skipped',
})),
});
await this.prisma.smsCampaign.update({
where: { id: campaignId },
data: {
totalCount: { increment: fresh.length },
skippedCount: { increment: skipped },
status: 'draft',
},
});
return this.get(actor.organizationId, campaignId);
}
private async resolvePersonRecipients(
actor: Actor,
personIds: string[],
): Promise<
Array<{ personId: string; leadId: null; mobile: string | null }>
> {
const people = await this.prisma.person.findMany({
where: {
id: { in: personIds },
organizationId: actor.organizationId,
...ownerWhere(actor),
},
select: { id: true, mobile: true },
});
return people.map((p) => ({
personId: p.id,
leadId: null,
mobile: p.mobile?.trim() || null,
}));
}
private async resolveLeadRecipients(
actor: Actor,
leadIds: string[],
): Promise<
Array<{ personId: null; leadId: string; mobile: string | null }>
> {
const leads = await this.prisma.lead.findMany({
where: {
id: { in: leadIds },
organizationId: actor.organizationId,
archivedAt: null,
...leadAccessWhere(actor),
},
select: { id: true, mobile: true },
});
return leads.map((l) => ({
personId: null,
leadId: l.id,
mobile: l.mobile?.trim() || null,
}));
}
async queue(organizationId: string, id: string): Promise<SmsCampaignDto> {
@@ -350,10 +495,44 @@ export class SmsCampaignsService {
const batch = await this.prisma.smsCampaignRecipient.findMany({
where: { campaignId, status: 'pending' },
take: 40,
take: SMS_CAMPAIGN_CHUNK_SIZE,
orderBy: { createdAt: 'asc' },
});
const personIds = batch
.map((r) => r.personId)
.filter((id): id is string => Boolean(id));
const leadIds = batch
.map((r) => r.leadId)
.filter((id): id is string => Boolean(id));
const [people, leads] = await Promise.all([
personIds.length
? this.prisma.person.findMany({
where: { id: { in: personIds } },
select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
company: { select: { name: true } },
},
})
: Promise.resolve([]),
leadIds.length
? this.prisma.lead.findMany({
where: { id: { in: leadIds } },
select: {
id: true,
title: true,
contactName: true,
mobile: true,
},
})
: Promise.resolve([]),
]);
const personMap = new Map(people.map((p) => [p.id, p]));
const leadMap = new Map(leads.map((l) => [l.id, l]));
let sent = 0;
let failed = 0;
let skipped = 0;
@@ -368,6 +547,27 @@ export class SmsCampaignsService {
continue;
}
let name = '';
let title = '';
let company = '';
if (recipient.personId) {
const p = personMap.get(recipient.personId);
name = [p?.firstName, p?.lastName].filter(Boolean).join(' ').trim();
title = name;
company = p?.company?.name ?? '';
} else if (recipient.leadId) {
const l = leadMap.get(recipient.leadId);
name = (l?.contactName || l?.title || '').trim();
title = (l?.title || name).trim();
}
const withTokens = renderSmsText(campaign.body, {
name,
phone: recipient.mobile,
title,
company,
});
const personalized = await this.tracking.personalizeSmsBody({
organizationId: campaign.organizationId,
channel: 'sms',
@@ -378,7 +578,7 @@ export class SmsCampaignsService {
smsRecipientId: recipient.id,
personId: recipient.personId,
leadId: recipient.leadId,
body: campaign.body,
body: withTokens,
});
const result = await this.sms.sendSmsDetailed(
+476 -71
View File
@@ -1,14 +1,21 @@
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { api } from '@/lib/api';
import type {
FilteredIdsResponse,
LeadDto,
LeadStageDto,
PaginatedResponse,
PersonDto,
SmsCampaignDto,
SmsCampaignListResponse,
} from '@mento/shared';
import {
MESSAGE_AUTOMATION_FIELDS,
SMS_CAMPAIGN_CHUNK_SIZE,
} from '@mento/shared';
import {
UiButton,
UiCard,
@@ -21,19 +28,34 @@ import {
import UiIcon from '@/components/UiIcon.vue';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
type AudienceTab = 'people' | 'leads';
const router = useRouter();
const loading = ref(false);
const peopleLoading = ref(false);
const listLoading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const campaigns = ref<SmsCampaignDto[]>([]);
const people = ref<PersonDto[]>([]);
const audience = ref<AudienceTab>('people');
const selectedIds = ref<string[]>([]);
const name = ref('');
const body = ref('');
const queueNow = ref(true);
const peopleQ = ref('');
const fieldsOpen = ref(false);
const q = ref('');
const province = ref('');
const city = ref('');
const region = ref('');
const stageId = ref('');
const hasMobile = ref(true);
const page = ref(1);
const pageSize = 40;
const total = ref(0);
const people = ref<PersonDto[]>([]);
const leads = ref<LeadDto[]>([]);
const stages = ref<LeadStageDto[]>([]);
const statusLabel: Record<string, string> = {
draft: 'پیش‌نویس',
@@ -43,19 +65,67 @@ const statusLabel: Record<string, string> = {
cancelled: 'لغو شده',
};
async function loadPeople(q?: string) {
peopleLoading.value = true;
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize)));
const filterParams = computed(() => {
const base: Record<string, string | number | boolean> = {
q: q.value.trim() || undefined,
hasMobile: hasMobile.value ? '1' : undefined,
} as Record<string, string | number | boolean>;
if (audience.value === 'people') {
if (province.value.trim()) base.province = province.value.trim();
if (city.value.trim()) base.city = city.value.trim();
} else {
if (city.value.trim()) base.city = city.value.trim();
if (region.value.trim()) base.region = region.value.trim();
if (stageId.value) base.stageId = stageId.value;
}
return Object.fromEntries(
Object.entries(base).filter(([, v]) => v !== undefined && v !== ''),
);
});
function cleanParams(extra: Record<string, unknown> = {}) {
const merged = { ...filterParams.value, ...extra };
return Object.fromEntries(
Object.entries(merged).filter(([, v]) => v !== undefined && v !== '' && v !== null),
);
}
async function loadList() {
listLoading.value = true;
try {
const { data } = await api.get<PaginatedResponse<PersonDto>>('/people', {
params: {
page: 1,
limit: 100,
...(q?.trim() ? { q: q.trim() } : {}),
},
});
people.value = data.items;
if (audience.value === 'people') {
const { data } = await api.get<PaginatedResponse<PersonDto>>('/people', {
params: cleanParams({ page: page.value, limit: pageSize }),
});
people.value = data.items;
total.value = data.total;
leads.value = [];
} else {
const { data } = await api.get<PaginatedResponse<LeadDto>>('/leads', {
params: cleanParams({ page: page.value, limit: pageSize }),
});
leads.value = data.items;
total.value = data.total;
people.value = [];
}
} finally {
peopleLoading.value = false;
listLoading.value = false;
}
}
async function loadCampaigns() {
const { data } = await api.get<SmsCampaignListResponse>('/sms-campaigns');
campaigns.value = data.items;
}
async function loadStages() {
try {
const { data } = await api.get<LeadStageDto[]>('/leads/stages');
stages.value = data;
} catch {
stages.value = [];
}
}
@@ -63,11 +133,7 @@ async function load() {
loading.value = true;
error.value = '';
try {
const [campRes] = await Promise.all([
api.get<SmsCampaignListResponse>('/sms-campaigns'),
loadPeople(peopleQ.value),
]);
campaigns.value = campRes.data.items;
await Promise.all([loadCampaigns(), loadList(), loadStages()]);
} catch (e) {
if (axios.isAxiosError(e) && e.response?.status === 403) {
error.value = 'ماژول پیامک گروهی برای این محیط فعال نیست.';
@@ -79,17 +145,46 @@ async function load() {
}
}
let peopleSearchTimer: ReturnType<typeof setTimeout> | null = null;
watch(peopleQ, (q) => {
if (peopleSearchTimer) clearTimeout(peopleSearchTimer);
peopleSearchTimer = setTimeout(() => {
void loadPeople(q).catch(() => {
error.value = 'جستجوی مخاطب ناموفق بود.';
let searchTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleReload() {
if (searchTimer) clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
page.value = 1;
void loadList().catch(() => {
error.value = 'بارگذاری مخاطب ناموفق بود.';
});
}, 300);
}
watch([q, province, city, region, stageId, hasMobile], scheduleReload);
watch(page, () => {
void loadList().catch(() => {
error.value = 'بارگذاری مخاطب ناموفق بود.';
});
});
function togglePerson(id: string) {
watch(audience, (next, prev) => {
if (next === prev) return;
if (selectedIds.value.length) {
const okSwitch = window.confirm(
'با تعویض تب، انتخاب‌های فعلی پاک می‌شود. ادامه می‌دهید؟',
);
if (!okSwitch) {
audience.value = prev;
return;
}
}
selectedIds.value = [];
q.value = '';
province.value = '';
city.value = '';
region.value = '';
stageId.value = '';
page.value = 1;
void loadList();
});
function toggleId(id: string) {
if (selectedIds.value.includes(id)) {
selectedIds.value = selectedIds.value.filter((x) => x !== id);
} else {
@@ -98,10 +193,55 @@ function togglePerson(id: string) {
}
function selectVisible() {
const ids = people.value.map((p) => p.id);
const ids =
audience.value === 'people'
? people.value.map((p) => p.id)
: leads.value.map((l) => l.id);
selectedIds.value = [...new Set([...selectedIds.value, ...ids])];
}
async function selectAllFiltered() {
error.value = '';
try {
const path = audience.value === 'people' ? '/people/ids' : '/leads/ids';
const { data } = await api.get<FilteredIdsResponse>(path, {
params: cleanParams(),
});
if (!data.total) {
error.value = 'نتیجه‌ای با این فیلتر پیدا نشد.';
return;
}
const confirmed = window.confirm(
`${toFaDigits(data.total)} مخاطب مطابق فیلتر انتخاب شود؟`,
);
if (!confirmed) return;
selectedIds.value = data.ids;
ok.value = `${toFaDigits(data.ids.length)} مخاطب انتخاب شد.`;
} catch (e) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
error.value = Array.isArray(msg)
? msg.join('، ')
: (msg ?? 'انتخاب همه ناموفق بود.');
} else {
error.value = 'انتخاب همه ناموفق بود.';
}
}
}
function insertField(token: string) {
body.value = `${body.value}${token}`;
fieldsOpen.value = false;
}
function chunkIds(ids: string[]) {
const out: string[][] = [];
for (let i = 0; i < ids.length; i += SMS_CAMPAIGN_CHUNK_SIZE) {
out.push(ids.slice(i, i + SMS_CAMPAIGN_CHUNK_SIZE));
}
return out;
}
async function createCampaign() {
if (!name.value.trim() || body.value.trim().length < 2) {
error.value = 'نام و متن پیامک را کامل کنید.';
@@ -114,20 +254,38 @@ async function createCampaign() {
saving.value = true;
error.value = '';
ok.value = '';
const chunks = chunkIds(selectedIds.value);
const wantQueue = queueNow.value;
try {
await api.post('/sms-campaigns', {
const first = chunks[0]!;
const createBody =
audience.value === 'people'
? { personIds: first }
: { leadIds: first };
const { data: campaign } = await api.post<SmsCampaignDto>('/sms-campaigns', {
name: name.value.trim(),
body: body.value.trim(),
personIds: selectedIds.value,
queueNow: queueNow.value,
queueNow: false,
...createBody,
});
for (let i = 1; i < chunks.length; i += 1) {
const part = chunks[i]!;
await api.post(`/sms-campaigns/${campaign.id}/recipients`, {
...(audience.value === 'people'
? { personIds: part }
: { leadIds: part }),
});
}
if (wantQueue) {
await api.post(`/sms-campaigns/${campaign.id}/queue`);
}
name.value = '';
body.value = '';
selectedIds.value = [];
ok.value = queueNow.value
? 'کمپین در صف ارسال قرار گرفت.'
ok.value = wantQueue
? `کمپین با ${toFaDigits(chunks.reduce((n, c) => n + c.length, 0))} مخاطب در صف ارسال قرار گرفت.`
: 'کمپین به‌صورت پیش‌نویس ذخیره شد.';
await load();
await loadCampaigns();
} catch (e) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
@@ -143,7 +301,7 @@ async function createCampaign() {
async function queue(id: string) {
try {
await api.post(`/sms-campaigns/${id}/queue`);
await load();
await loadCampaigns();
} catch {
error.value = 'صف‌بندی ناموفق بود.';
}
@@ -152,7 +310,7 @@ async function queue(id: string) {
async function cancel(id: string) {
try {
await api.post(`/sms-campaigns/${id}/cancel`);
await load();
await loadCampaigns();
} catch {
error.value = 'لغو ناموفق بود.';
}
@@ -167,7 +325,7 @@ onMounted(() => {
<div class="page">
<UiPageHeader
title="پیامک گروهی"
description="ارسال انبوه پیامک به مخاطبان انتخاب‌شده"
description="ارسال انبوه پیامک به اشخاص یا لیدهای فیلترشده"
>
<template #actions>
<UiButton variant="secondary" :disabled="loading" @click="load">
@@ -190,39 +348,173 @@ onMounted(() => {
ارسال فوری پس از ذخیره
</label>
</div>
<UiField label="متن پیامک">
<div class="body-block">
<div class="body-tools">
<span class="muted">متن پیامک</span>
<div class="pop-wrap">
<button
class="pill"
type="button"
@click="fieldsOpen = !fieldsOpen"
>
<b>{ }</b>
فیلدهای پویا
</button>
<div v-if="fieldsOpen" class="pop">
<button
v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="item.token"
type="button"
@click="insertField(item.token)"
>
<code>{{ item.token }}</code>
<span>{{ item.label }}</span>
</button>
</div>
</div>
</div>
<UiTextarea
v-model="body"
:rows="4"
placeholder="متن پیامک را بنویسید… در صورت وجود لینک http(s)، برای هر مخاطب لینک یکتا ساخته می‌شود."
placeholder="متن پیامک را بنویسید… از فیلدهای پویا استفاده کنید. لینک http(s) برای هر مخاطب یکتا می‌شود."
/>
</UiField>
<div class="people-head">
<UiField label="جستجوی مخاطب">
<UiInput v-model="peopleQ" placeholder="نام یا موبایل…" />
</UiField>
<UiButton variant="secondary" @click="selectVisible">
انتخاب نتایج
</UiButton>
</div>
<p class="muted">
انتخاب‌شده: {{ toFaDigits(selectedIds.length) }} نفر
</p>
<p v-if="peopleLoading" class="muted">در حال بارگذاری مخاطبان…</p>
<div class="people-list">
<label v-for="p in people" :key="p.id" class="person">
<input
type="checkbox"
:checked="selectedIds.includes(p.id)"
@change="togglePerson(p.id)"
/>
<span>
<strong>{{ p.fullName }}</strong>
<small>{{ p.mobile || 'بدون موبایل' }}</small>
</span>
<div class="tabs" role="tablist">
<button
type="button"
role="tab"
:class="{ on: audience === 'people' }"
@click="audience = 'people'"
>
اشخاص
</button>
<button
type="button"
role="tab"
:class="{ on: audience === 'leads' }"
@click="audience = 'leads'"
>
لیدها
</button>
</div>
<div class="filters">
<UiField label="جستجو">
<UiInput v-model="q" placeholder="نام یا موبایل…" />
</UiField>
<UiField v-if="audience === 'people'" label="استان">
<UiInput v-model="province" placeholder="مثلاً اصفهان" />
</UiField>
<UiField :label="audience === 'people' ? 'شهر' : 'شهر'">
<UiInput v-model="city" placeholder="شهر…" />
</UiField>
<UiField v-if="audience === 'leads'" label="منطقه / استان">
<UiInput v-model="region" placeholder="منطقه یا استان…" />
</UiField>
<UiField v-if="audience === 'leads'" label="مرحله">
<select v-model="stageId" class="select">
<option value="">همه</option>
<option v-for="s in stages" :key="s.id" :value="s.id">
{{ s.name }}
</option>
</select>
</UiField>
<label class="check filter-check">
<input v-model="hasMobile" type="checkbox" />
فقط با موبایل
</label>
</div>
<div class="people-head">
<p class="muted">
انتخاب‌شده: {{ toFaDigits(selectedIds.length) }} نفر · نتایج فیلتر:
{{ toFaDigits(total) }}
</p>
<div class="head-actions">
<UiButton variant="secondary" @click="selectVisible">
انتخاب صفحه
</UiButton>
<UiButton variant="secondary" @click="selectAllFiltered">
انتخاب همهٔ نتایج فیلتر
</UiButton>
</div>
</div>
<p v-if="listLoading" class="muted">در حال بارگذاری…</p>
<div class="people-list">
<template v-if="audience === 'people'">
<label v-for="p in people" :key="p.id" class="person">
<input
type="checkbox"
:checked="selectedIds.includes(p.id)"
@change="toggleId(p.id)"
/>
<span>
<strong>{{ p.fullName }}</strong>
<small>
{{ p.mobile || 'بدون موبایل' }}
<template v-if="p.company">
· {{ p.company.name }}
<template v-if="p.company.city || p.company.province">
·
{{
[p.company.city, p.company.province].filter(Boolean).join('، ')
}}
</template>
</template>
</small>
</span>
</label>
</template>
<template v-else>
<label v-for="l in leads" :key="l.id" class="person">
<input
type="checkbox"
:checked="selectedIds.includes(l.id)"
@change="toggleId(l.id)"
/>
<span>
<strong>{{ l.contactName || l.title }}</strong>
<small>
{{ l.mobile || 'بدون موبایل' }}
<template v-if="l.city || l.region">
· {{ [l.city, l.region].filter(Boolean).join('، ') }}
</template>
· {{ l.stageName }}
</small>
</span>
</label>
</template>
<p
v-if="!listLoading && !(audience === 'people' ? people.length : leads.length)"
class="muted empty-list"
>
موردی پیدا نشد.
</p>
</div>
<div class="pager">
<UiButton
variant="secondary"
:disabled="page <= 1"
@click="page -= 1"
>
قبلی
</UiButton>
<span class="muted">
صفحه {{ toFaDigits(page) }} از {{ toFaDigits(pageCount) }}
</span>
<UiButton
variant="secondary"
:disabled="page >= pageCount"
@click="page += 1"
>
بعدی
</UiButton>
</div>
<UiButton :loading="saving" @click="createCampaign">ساخت کمپین</UiButton>
</UiCard>
@@ -294,20 +586,123 @@ onMounted(() => {
color: #334155;
min-height: var(--control-h);
}
.people-head {
.filter-check {
align-self: end;
margin-bottom: 0.35rem;
}
.body-block {
margin-bottom: 0.75rem;
}
.body-tools {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.35rem;
}
.pop-wrap {
position: relative;
}
.pill {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border: 1px solid #e2e8f0;
background: #fff;
border-radius: 999px;
padding: 0.35rem 0.75rem;
font-weight: 700;
cursor: pointer;
color: #0f172a;
}
.pill:hover {
background: #f8fafc;
}
.pop {
position: absolute;
inset-inline-end: 0;
top: calc(100% + 0.35rem);
z-index: 20;
min-width: 220px;
display: grid;
grid-template-columns: 1fr auto;
gap: 0.2rem;
padding: 0.45rem;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: var(--radius);
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
}
.pop button {
display: flex;
justify-content: space-between;
gap: 0.75rem;
align-items: end;
margin-top: 0.75rem;
border: 0;
background: transparent;
padding: 0.45rem 0.55rem;
border-radius: 8px;
cursor: pointer;
text-align: start;
}
.pop button:hover {
background: #f1f5f9;
}
.pop code {
font-weight: 700;
color: #0f766e;
}
.tabs {
display: flex;
gap: 0.35rem;
margin: 0.5rem 0 0.75rem;
border-bottom: 1px solid #e2e8f0;
}
.tabs button {
border: 0;
background: transparent;
padding: 0.55rem 0.9rem;
font-weight: 700;
color: #64748b;
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
}
.tabs button.on {
color: #0f766e;
border-bottom-color: #0f766e;
}
.filters {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 0.65rem;
margin-bottom: 0.5rem;
}
.select {
width: 100%;
min-height: var(--control-h);
border: 1px solid #e2e8f0;
border-radius: var(--radius);
padding: 0 0.65rem;
background: #fff;
}
.people-head {
display: flex;
justify-content: space-between;
gap: 0.75rem;
align-items: center;
flex-wrap: wrap;
margin-top: 0.5rem;
}
.head-actions {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
}
.people-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 0.45rem;
max-height: 280px;
max-height: 360px;
overflow: auto;
margin: 0.75rem 0 1rem;
margin: 0.75rem 0 0.75rem;
padding: 0.35rem;
border: 1px solid #eef2f7;
border-radius: var(--radius);
@@ -329,6 +724,17 @@ onMounted(() => {
.person small {
color: #64748b;
}
.empty-list {
grid-column: 1 / -1;
padding: 0.75rem;
}
.pager {
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.campaigns {
display: grid;
gap: 0.75rem;
@@ -363,7 +769,6 @@ onMounted(() => {
}
@media (max-width: 800px) {
.form-grid,
.people-head,
.campaign {
grid-template-columns: 1fr;
flex-direction: column;
@@ -0,0 +1,51 @@
# SMS Campaign People/Leads Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** SMS campaigns support people-only or leads-only audiences with full filters, select-all-ids, dynamic field tokens, and 50-sized create/send batches.
**Architecture:** Extend people/leads list filters + `/ids` endpoints; expand sms-campaigns create/add-recipients; personalize body via `renderSmsText` then tracking links; rebuild `SmsCampaignsView` with tabs, filters, and chunked create.
**Tech Stack:** NestJS/Prisma, Vue 3, `@mento/shared`, existing MESSAGE_AUTOMATION_FIELDS / renderSmsText.
## Global Constraints
- One campaign = people XOR leads
- Select-all = all filter matches (confirm count)
- Batch size 50 for create chunks and send cron
- People province/city via company (+ addresses search)
- Dynamic tokens: `{نام}` `{شماره}` `{تاریخ}` `{عنوان}` `{شرکت}`
- Spec: `docs/superpowers/specs/2026-10-17-sms-campaign-people-leads-design.md`
---
### Task 1: Shared types
- [ ] Extend `CreateSmsCampaignRequest` with optional `leadIds`; document XOR
- [ ] Add `AddSmsCampaignRecipientsRequest`, `FilteredIdsResponse`
- [ ] Export constants if needed (`SMS_CAMPAIGN_CHUNK = 50`)
### Task 2: People filters + ids
- [ ] `PeopleService.list` / `listIds`: `province`, `city` on company; address contains
- [ ] Controller query + `GET /people/ids` with 50k cap
### Task 3: Leads ids + region filter
- [ ] Ensure list supports `region`; add `GET /leads/ids`
### Task 4: SMS campaigns API
- [ ] Create with personIds XOR leadIds (max 50 first chunk; force draft if more planned via `queueNow` deferred to client)
- [ ] `POST :id/recipients`
- [ ] Batch send 50 + `renderSmsText` before personalizeSmsBody
### Task 5: Frontend SmsCampaignsView
- [ ] Tabs people/leads, filters, pagination, select-all via /ids
- [ ] Dynamic fields pill
- [ ] Chunked create then optional queue
### Task 6: Verify
- [ ] shared build + api tsc/tests relevant; graphify update
+22 -2
View File
@@ -755,6 +755,8 @@ export interface HealthResponse {
export interface CompanySummaryDto {
id: string;
name: string;
province?: string | null;
city?: string | null;
}
export interface CompanyDto {
@@ -4321,15 +4323,33 @@ export interface SmsCampaignDto {
updatedAt: string;
}
/** حداکثر گیرنده در هر درخواست ساخت/افزودن کمپین پیامک */
export const SMS_CAMPAIGN_CHUNK_SIZE = 50;
/** سقف شناسه‌های قابل دریافت از /people/ids و /leads/ids */
export const FILTERED_IDS_MAX = 50_000;
export interface FilteredIdsResponse {
ids: string[];
total: number;
}
export interface CreateSmsCampaignRequest {
name: string;
body: string;
personIds: string[];
/** دقیقاً یکی از personIds یا leadIds */
personIds?: string[];
leadIds?: string[];
scheduledAt?: string | null;
/** اگر true باشد بلافاصله صف می‌شود */
/** اگر true باشد بلافاصله صف می‌شود (فقط وقتی همه گیرنده‌ها در همین درخواست باشند یا بعد از افزودن تکه‌ها جداگانه queue شود) */
queueNow?: boolean;
}
export interface AddSmsCampaignRecipientsRequest {
personIds?: string[];
leadIds?: string[];
}
export interface SmsCampaignListResponse {
items: SmsCampaignDto[];
total: number;