187 lines
5.7 KiB
TypeScript
187 lines
5.7 KiB
TypeScript
import {
|
|
Controller,
|
|
Get,
|
|
Post,
|
|
Put,
|
|
Delete,
|
|
Body,
|
|
Param,
|
|
Query,
|
|
Res,
|
|
UseGuards,
|
|
NotFoundException,
|
|
} from "@nestjs/common";
|
|
import type { Response } from "express";
|
|
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
|
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
|
import { RolesGuard } from "../common/guards/roles.guard";
|
|
import { Roles } from "../common/decorators/roles.decorator";
|
|
import { PrismaService } from "../prisma/prisma.service";
|
|
import {
|
|
CreateSmsCampaignDto,
|
|
UpdateSmsCampaignDto,
|
|
QuerySmsCampaignDto,
|
|
} from "./dto/sms-campaign.dto";
|
|
import { generateCsv } from "../common/utils/csv-helper";
|
|
|
|
@ApiTags("Admin - CRM SMS Campaigns")
|
|
@ApiBearerAuth()
|
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
@Roles("Admin", "SUPER_ADMIN")
|
|
@Controller("admin/crm/sms-campaigns")
|
|
export class SmsCampaignsController {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
@Get()
|
|
@ApiOperation({ summary: "لیست کمپینهای پیامکی CRM" })
|
|
async findAll(@Query() query: QuerySmsCampaignDto) {
|
|
const page = Number(query.page) || 1;
|
|
const limit = Number(query.limit) || 10;
|
|
const skip = (page - 1) * limit;
|
|
|
|
const where: any = {};
|
|
if (query.targetSegment) {
|
|
where.targetSegment = query.targetSegment;
|
|
}
|
|
if (query.status) {
|
|
where.status = query.status;
|
|
}
|
|
if (query.search) {
|
|
where.OR = [
|
|
{ title: { contains: query.search, mode: "insensitive" } },
|
|
{ body: { contains: query.search, mode: "insensitive" } },
|
|
];
|
|
}
|
|
|
|
const [total, items] = await Promise.all([
|
|
this.prisma.smsCampaign.count({ where }),
|
|
this.prisma.smsCampaign.findMany({
|
|
where,
|
|
skip,
|
|
take: limit,
|
|
orderBy: { [query.sortBy || "createdAt"]: query.sortOrder || "desc" },
|
|
}),
|
|
]);
|
|
|
|
return {
|
|
success: true,
|
|
data: items,
|
|
meta: {
|
|
total,
|
|
page,
|
|
limit,
|
|
totalPages: Math.ceil(total / limit),
|
|
},
|
|
};
|
|
}
|
|
|
|
@Get("export/csv")
|
|
@ApiOperation({ summary: "خروجی CSV کمپینهای پیامکی" })
|
|
async exportCsv(@Query() query: QuerySmsCampaignDto, @Res() res: Response) {
|
|
const where: any = {};
|
|
if (query.targetSegment) {
|
|
where.targetSegment = query.targetSegment;
|
|
}
|
|
if (query.status) {
|
|
where.status = query.status;
|
|
}
|
|
|
|
const items: any[] = await this.prisma.smsCampaign.findMany({
|
|
where,
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
|
|
const rows = items.map((item: any) => ({
|
|
id: item.id,
|
|
title: item.title,
|
|
body: item.body,
|
|
targetSegment: item.targetSegment,
|
|
estimatedCost: item.estimatedCost ? item.estimatedCost.toString() : "",
|
|
status: item.status,
|
|
metrics: item.metrics ? JSON.stringify(item.metrics) : "{}",
|
|
createdAt: item.createdAt.toISOString(),
|
|
updatedAt: item.updatedAt.toISOString(),
|
|
}));
|
|
|
|
const csvData = generateCsv(rows, [
|
|
{ key: "id", header: "ID" },
|
|
{ key: "title", header: "Title" },
|
|
{ key: "body", header: "Message Body" },
|
|
{ key: "targetSegment", header: "Target Segment" },
|
|
{ key: "estimatedCost", header: "Estimated Cost" },
|
|
{ key: "status", header: "Status" },
|
|
{ key: "metrics", header: "Metrics" },
|
|
{ key: "createdAt", header: "Created At" },
|
|
{ key: "updatedAt", header: "Updated At" },
|
|
]);
|
|
|
|
res.setHeader("Content-Type", "text/csv; charset=utf-8");
|
|
res.setHeader(
|
|
"Content-Disposition",
|
|
`attachment; filename="sms-campaigns-${Date.now()}.csv"`,
|
|
);
|
|
return res.status(200).send(csvData);
|
|
}
|
|
|
|
@Get(":id")
|
|
@ApiOperation({ summary: "دریافت جزییات یک کمپین پیامکی" })
|
|
async findOne(@Param("id") id: string) {
|
|
const item = await this.prisma.smsCampaign.findUnique({
|
|
where: { id },
|
|
});
|
|
if (!item) {
|
|
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
|
|
}
|
|
return { success: true, data: item };
|
|
}
|
|
|
|
@Post()
|
|
@ApiOperation({ summary: "ایجاد کمپین پیامکی جدید" })
|
|
async create(@Body() dto: CreateSmsCampaignDto) {
|
|
const item = await this.prisma.smsCampaign.create({
|
|
data: {
|
|
title: dto.title,
|
|
body: dto.body,
|
|
targetSegment: dto.targetSegment,
|
|
estimatedCost: dto.estimatedCost,
|
|
status: dto.status || "draft",
|
|
metrics: dto.metrics || {},
|
|
},
|
|
});
|
|
return { success: true, data: item };
|
|
}
|
|
|
|
@Put(":id")
|
|
@ApiOperation({ summary: "ویرایش کمپین پیامکی" })
|
|
async update(@Param("id") id: string, @Body() dto: UpdateSmsCampaignDto) {
|
|
const exists = await this.prisma.smsCampaign.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
|
|
}
|
|
|
|
const updated = await this.prisma.smsCampaign.update({
|
|
where: { id },
|
|
data: {
|
|
...(dto.title && { title: dto.title }),
|
|
...(dto.body && { body: dto.body }),
|
|
...(dto.targetSegment && { targetSegment: dto.targetSegment }),
|
|
...(dto.estimatedCost !== undefined && { estimatedCost: dto.estimatedCost }),
|
|
...(dto.status && { status: dto.status }),
|
|
...(dto.metrics !== undefined && { metrics: dto.metrics }),
|
|
},
|
|
});
|
|
return { success: true, data: updated };
|
|
}
|
|
|
|
@Delete(":id")
|
|
@ApiOperation({ summary: "حذف کمپین پیامکی" })
|
|
async remove(@Param("id") id: string) {
|
|
const exists = await this.prisma.smsCampaign.findUnique({ where: { id } });
|
|
if (!exists) {
|
|
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
|
|
}
|
|
await this.prisma.smsCampaign.delete({ where: { id } });
|
|
return { success: true, message: "Deleted successfully" };
|
|
}
|
|
}
|