267 lines
7.7 KiB
TypeScript
267 lines
7.7 KiB
TypeScript
import {
|
|||
|
|
BadRequestException,
|
||
|
|
Injectable,
|
||
|
|
NotFoundException,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
import { Cron } from '@nestjs/schedule';
|
||
|
|
import type {
|
||
|
|
CreateSmsCampaignRequest,
|
||
|
|
SmsCampaignDto,
|
||
|
|
SmsCampaignListResponse,
|
||
|
|
SmsCampaignStatus,
|
||
|
|
} from '@mento/shared';
|
||
|
|
import { PrismaService } from '../prisma/prisma.service';
|
||
|
|
import { SmsService } from '../common/sms.service';
|
||
|
|
import { type Actor, ownerWhere } from '../common/record-scope';
|
||
|
|
|
||
|
|
@Injectable()
|
||
|
|
export class SmsCampaignsService {
|
||
|
|
constructor(
|
||
|
|
private readonly prisma: PrismaService,
|
||
|
|
private readonly sms: SmsService,
|
||
|
|
) {}
|
||
|
|
|
||
|
|
async list(
|
||
|
|
organizationId: string,
|
||
|
|
page = 1,
|
||
|
|
limit = 20,
|
||
|
|
): Promise<SmsCampaignListResponse> {
|
||
|
|
const where = { organizationId };
|
||
|
|
const [total, rows] = await Promise.all([
|
||
|
|
this.prisma.smsCampaign.count({ where }),
|
||
|
|
this.prisma.smsCampaign.findMany({
|
||
|
|
where,
|
||
|
|
orderBy: { createdAt: 'desc' },
|
||
|
|
skip: (page - 1) * limit,
|
||
|
|
take: limit,
|
||
|
|
}),
|
||
|
|
]);
|
||
|
|
return {
|
||
|
|
total,
|
||
|
|
items: rows.map((row) => this.toDto(row)),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
async get(organizationId: string, id: string): Promise<SmsCampaignDto> {
|
||
|
|
const row = await this.prisma.smsCampaign.findFirst({
|
||
|
|
where: { id, organizationId },
|
||
|
|
});
|
||
|
|
if (!row) throw new NotFoundException('کمپین پیدا نشد');
|
||
|
|
return this.toDto(row);
|
||
|
|
}
|
||
|
|
|
||
|
|
async create(
|
||
|
|
actor: Actor,
|
||
|
|
dto: CreateSmsCampaignRequest,
|
||
|
|
): Promise<SmsCampaignDto> {
|
||
|
|
const name = dto.name?.trim();
|
||
|
|
const body = dto.body?.trim();
|
||
|
|
if (!name) throw new BadRequestException('نام کمپین الزامی است');
|
||
|
|
if (!body || body.length < 2) {
|
||
|
|
throw new BadRequestException('متن پیامک کوتاه است');
|
||
|
|
}
|
||
|
|
const personIds = [...new Set((dto.personIds ?? []).filter(Boolean))];
|
||
|
|
if (!personIds.length) {
|
||
|
|
throw new BadRequestException('حداقل یک مخاطب انتخاب کنید');
|
||
|
|
}
|
||
|
|
|
||
|
|
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 queueNow = Boolean(dto.queueNow);
|
||
|
|
const scheduledAt = dto.scheduledAt ? new Date(dto.scheduledAt) : null;
|
||
|
|
if (scheduledAt && Number.isNaN(scheduledAt.getTime())) {
|
||
|
|
throw new BadRequestException('زمانبندی نامعتبر است');
|
||
|
|
}
|
||
|
|
|
||
|
|
const status: SmsCampaignStatus =
|
||
|
|
queueNow || scheduledAt ? 'queued' : 'draft';
|
||
|
|
|
||
|
|
const campaign = await this.prisma.smsCampaign.create({
|
||
|
|
data: {
|
||
|
|
organizationId: actor.organizationId,
|
||
|
|
name,
|
||
|
|
body,
|
||
|
|
status,
|
||
|
|
scheduledAt: queueNow ? new Date() : scheduledAt,
|
||
|
|
totalCount: people.length,
|
||
|
|
createdById: actor.userId,
|
||
|
|
recipients: {
|
||
|
|
create: people.map((p) => ({
|
||
|
|
personId: p.id,
|
||
|
|
mobile: p.mobile,
|
||
|
|
status: p.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 queue(organizationId: string, id: string): Promise<SmsCampaignDto> {
|
||
|
|
const row = await this.prisma.smsCampaign.findFirst({
|
||
|
|
where: { id, organizationId },
|
||
|
|
});
|
||
|
|
if (!row) throw new NotFoundException('کمپین پیدا نشد');
|
||
|
|
if (row.status !== 'draft' && row.status !== 'cancelled') {
|
||
|
|
throw new BadRequestException('این کمپین قابل صفبندی نیست');
|
||
|
|
}
|
||
|
|
await this.prisma.smsCampaign.update({
|
||
|
|
where: { id },
|
||
|
|
data: {
|
||
|
|
status: 'queued',
|
||
|
|
scheduledAt: row.scheduledAt ?? new Date(),
|
||
|
|
},
|
||
|
|
});
|
||
|
|
return this.get(organizationId, id);
|
||
|
|
}
|
||
|
|
|
||
|
|
async cancel(organizationId: string, id: string): Promise<SmsCampaignDto> {
|
||
|
|
const row = await this.prisma.smsCampaign.findFirst({
|
||
|
|
where: { id, organizationId },
|
||
|
|
});
|
||
|
|
if (!row) throw new NotFoundException('کمپین پیدا نشد');
|
||
|
|
if (row.status === 'done') {
|
||
|
|
throw new BadRequestException('کمپین تمامشده قابل لغو نیست');
|
||
|
|
}
|
||
|
|
await this.prisma.smsCampaign.update({
|
||
|
|
where: { id },
|
||
|
|
data: { status: 'cancelled' },
|
||
|
|
});
|
||
|
|
return this.get(organizationId, id);
|
||
|
|
}
|
||
|
|
|
||
|
|
@Cron('*/1 * * * *')
|
||
|
|
async processDue(): Promise<number> {
|
||
|
|
if (!this.sms.isConfigured()) return 0;
|
||
|
|
const now = new Date();
|
||
|
|
const campaigns = await this.prisma.smsCampaign.findMany({
|
||
|
|
where: {
|
||
|
|
status: 'queued',
|
||
|
|
OR: [{ scheduledAt: null }, { scheduledAt: { lte: now } }],
|
||
|
|
},
|
||
|
|
orderBy: { createdAt: 'asc' },
|
||
|
|
take: 3,
|
||
|
|
});
|
||
|
|
|
||
|
|
let processed = 0;
|
||
|
|
for (const campaign of campaigns) {
|
||
|
|
await this.processCampaign(campaign.id);
|
||
|
|
processed += 1;
|
||
|
|
}
|
||
|
|
return processed;
|
||
|
|
}
|
||
|
|
|
||
|
|
private async processCampaign(campaignId: string): Promise<void> {
|
||
|
|
await this.prisma.smsCampaign.update({
|
||
|
|
where: { id: campaignId },
|
||
|
|
data: { status: 'sending' },
|
||
|
|
});
|
||
|
|
|
||
|
|
const campaign = await this.prisma.smsCampaign.findUnique({
|
||
|
|
where: { id: campaignId },
|
||
|
|
});
|
||
|
|
if (!campaign) return;
|
||
|
|
|
||
|
|
const batch = await this.prisma.smsCampaignRecipient.findMany({
|
||
|
|
where: { campaignId, status: 'pending' },
|
||
|
|
take: 40,
|
||
|
|
orderBy: { createdAt: 'asc' },
|
||
|
|
});
|
||
|
|
|
||
|
|
let sent = 0;
|
||
|
|
let failed = 0;
|
||
|
|
let skipped = 0;
|
||
|
|
|
||
|
|
for (const recipient of batch) {
|
||
|
|
if (!recipient.mobile) {
|
||
|
|
await this.prisma.smsCampaignRecipient.update({
|
||
|
|
where: { id: recipient.id },
|
||
|
|
data: { status: 'skipped', error: 'موبایل ندارد' },
|
||
|
|
});
|
||
|
|
skipped += 1;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
const result = await this.sms.sendSmsDetailed(
|
||
|
|
recipient.mobile,
|
||
|
|
campaign.body,
|
||
|
|
);
|
||
|
|
if (result.ok) {
|
||
|
|
await this.prisma.smsCampaignRecipient.update({
|
||
|
|
where: { id: recipient.id },
|
||
|
|
data: { status: 'sent', sentAt: new Date(), error: null },
|
||
|
|
});
|
||
|
|
sent += 1;
|
||
|
|
} else {
|
||
|
|
await this.prisma.smsCampaignRecipient.update({
|
||
|
|
where: { id: recipient.id },
|
||
|
|
data: {
|
||
|
|
status: 'failed',
|
||
|
|
error: result.reason?.slice(0, 200) ?? 'ارسال ناموفق',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
failed += 1;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const remaining = await this.prisma.smsCampaignRecipient.count({
|
||
|
|
where: { campaignId, status: 'pending' },
|
||
|
|
});
|
||
|
|
|
||
|
|
await this.prisma.smsCampaign.update({
|
||
|
|
where: { id: campaignId },
|
||
|
|
data: {
|
||
|
|
sentCount: { increment: sent },
|
||
|
|
failedCount: { increment: failed },
|
||
|
|
skippedCount: { increment: skipped },
|
||
|
|
status: remaining > 0 ? 'queued' : 'done',
|
||
|
|
scheduledAt: remaining > 0 ? new Date() : campaign.scheduledAt,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
private toDto(row: {
|
||
|
|
id: string;
|
||
|
|
name: string;
|
||
|
|
body: string;
|
||
|
|
status: string;
|
||
|
|
scheduledAt: Date | null;
|
||
|
|
totalCount: number;
|
||
|
|
sentCount: number;
|
||
|
|
failedCount: number;
|
||
|
|
skippedCount: number;
|
||
|
|
createdAt: Date;
|
||
|
|
updatedAt: Date;
|
||
|
|
}): SmsCampaignDto {
|
||
|
|
return {
|
||
|
|
id: row.id,
|
||
|
|
name: row.name,
|
||
|
|
body: row.body,
|
||
|
|
status: row.status as SmsCampaignStatus,
|
||
|
|
scheduledAt: row.scheduledAt?.toISOString() ?? null,
|
||
|
|
totalCount: row.totalCount,
|
||
|
|
sentCount: row.sentCount,
|
||
|
|
failedCount: row.failedCount,
|
||
|
|
skippedCount: row.skippedCount,
|
||
|
|
createdAt: row.createdAt.toISOString(),
|
||
|
|
updatedAt: row.updatedAt.toISOString(),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|