feat(notifications & advisors): implement unified notification queue, SMTP config, and catalog advisor contact flow
Deploy Canina / deploy (push) Successful in 8m17s

This commit is contained in:
devops committed 2026-11-07 07:41:24 +00:00
1 parent d881dc491e
commit fae4b570f9
20 files changed
+3445 -8

No files matched your search

@@ -0,0 +1,117 @@
-- CreateTable
CREATE TABLE "advisor_contacts" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"name" VARCHAR(150) NOT NULL,
"phone" VARCHAR(20) NOT NULL,
"title" VARCHAR(100),
"is_default" BOOLEAN NOT NULL DEFAULT false,
"is_active" BOOLEAN NOT NULL DEFAULT true,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "advisor_contacts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "product_advisors" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"product_id" UUID NOT NULL,
"advisor_id" UUID NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "product_advisors_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "leads" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"first_name" VARCHAR(100) NOT NULL,
"last_name" VARCHAR(100) NOT NULL,
"phone" VARCHAR(20) NOT NULL,
"product_id" UUID,
"advisor_id" UUID,
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
"notes" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "leads_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "notification_queues" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"channel" VARCHAR(20) NOT NULL,
"recipient" VARCHAR(150) NOT NULL,
"event" VARCHAR(50) NOT NULL,
"subject" VARCHAR(255),
"content" TEXT NOT NULL,
"payload" JSONB,
"status" VARCHAR(30) NOT NULL DEFAULT 'QUEUED',
"attempts" INTEGER NOT NULL DEFAULT 0,
"max_attempts" INTEGER NOT NULL DEFAULT 3,
"last_error" TEXT,
"idempotency_key" VARCHAR(100),
"sent_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "notification_queues_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "notification_templates" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"channel" VARCHAR(20) NOT NULL,
"event" VARCHAR(50) NOT NULL,
"name" VARCHAR(150) NOT NULL,
"subject" VARCHAR(255),
"body" TEXT NOT NULL,
"pattern_code" VARCHAR(50),
"variables" TEXT[] DEFAULT ARRAY[]::TEXT[],
"recipient_type" VARCHAR(30) NOT NULL DEFAULT 'customer',
"custom_recipient" VARCHAR(150),
"is_active" BOOLEAN NOT NULL DEFAULT true,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "notification_templates_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "advisor_contacts_phone_key" ON "advisor_contacts"("phone");
CREATE INDEX "advisor_contacts_phone_idx" ON "advisor_contacts"("phone");
CREATE INDEX "advisor_contacts_is_default_idx" ON "advisor_contacts"("is_default");
CREATE INDEX "advisor_contacts_is_active_idx" ON "advisor_contacts"("is_active");
-- CreateIndex
CREATE UNIQUE INDEX "product_advisors_product_id_advisor_id_key" ON "product_advisors"("product_id", "advisor_id");
CREATE INDEX "product_advisors_product_id_idx" ON "product_advisors"("product_id");
CREATE INDEX "product_advisors_advisor_id_idx" ON "product_advisors"("advisor_id");
-- CreateIndex
CREATE INDEX "leads_phone_idx" ON "leads"("phone");
CREATE INDEX "leads_status_idx" ON "leads"("status");
CREATE INDEX "leads_created_at_idx" ON "leads"("created_at");
CREATE INDEX "leads_advisor_id_idx" ON "leads"("advisor_id");
-- CreateIndex
CREATE UNIQUE INDEX "notification_queues_idempotency_key_key" ON "notification_queues"("idempotency_key");
CREATE INDEX "notification_queues_status_idx" ON "notification_queues"("status");
CREATE INDEX "notification_queues_channel_idx" ON "notification_queues"("channel");
CREATE INDEX "notification_queues_event_idx" ON "notification_queues"("event");
CREATE INDEX "notification_queues_created_at_idx" ON "notification_queues"("created_at");
-- CreateIndex
CREATE UNIQUE INDEX "notification_templates_channel_event_key" ON "notification_templates"("channel", "event");
CREATE INDEX "notification_templates_channel_idx" ON "notification_templates"("channel");
CREATE INDEX "notification_templates_event_idx" ON "notification_templates"("event");
CREATE INDEX "notification_templates_is_active_idx" ON "notification_templates"("is_active");
-- AddForeignKey
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "leads" ADD CONSTRAINT "leads_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "leads" ADD CONSTRAINT "leads_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+119
View File
@@ -286,6 +286,8 @@ model Product {
reviews ProductReview[]
competitorPriceLogs CompetitorPriceLog[]
priceSuggestions PriceSuggestion[]
productAdvisors ProductAdvisor[]
leads Lead[]
@@index([categorySlug])
@@index([suitableFor])
@@ -1088,3 +1090,120 @@ model DepartmentTask {
@@index([createdAt])
@@map("department_tasks")
}
// ------------------------------------------------------------------------------
// 8. AdvisorContact (مشاوران تخصصی و پاسخگویی)
// ------------------------------------------------------------------------------
model AdvisorContact {
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(150)
phone String @unique @db.VarChar(20)
title String? @db.VarChar(100)
isDefault Boolean @default(false) @map("is_default")
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
productAdvisors ProductAdvisor[]
leads Lead[]
@@index([phone])
@@index([isDefault])
@@index([isActive])
@@map("advisor_contacts")
}
// ------------------------------------------------------------------------------
// 9. ProductAdvisor (اتصال مشاور به محصول)
// ------------------------------------------------------------------------------
model ProductAdvisor {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
advisorId String @map("advisor_id") @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
advisor AdvisorContact @relation(fields: [advisorId], references: [id], onDelete: Cascade)
@@unique([productId, advisorId])
@@index([productId])
@@index([advisorId])
@@map("product_advisors")
}
// ------------------------------------------------------------------------------
// 10. Lead (درخواست‌های تماس و مشاوره کاربران)
// ------------------------------------------------------------------------------
model Lead {
id String @id @default(uuid()) @db.Uuid
firstName String @map("first_name") @db.VarChar(100)
lastName String @map("last_name") @db.VarChar(100)
phone String @db.VarChar(20)
productId String? @map("product_id") @db.Uuid
advisorId String? @map("advisor_id") @db.Uuid
status String @default("PENDING") @db.VarChar(30) // PENDING, CONTACTED, CANCELLED
notes String? @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
advisor AdvisorContact? @relation(fields: [advisorId], references: [id], onDelete: SetNull)
@@index([phone])
@@index([status])
@@index([createdAt])
@@index([advisorId])
@@map("leads")
}
// ------------------------------------------------------------------------------
// 11. NotificationQueue (صف ناهمگام نوتیفیکیشن‌ها با قابلیت Retry و Idempotency)
// ------------------------------------------------------------------------------
model NotificationQueue {
id String @id @default(uuid()) @db.Uuid
channel String @db.VarChar(20) // SMS, EMAIL
recipient String @db.VarChar(150)
event String @db.VarChar(50)
subject String? @db.VarChar(255)
content String @db.Text
payload Json? @db.JsonB
status String @default("QUEUED") @db.VarChar(30) // QUEUED, PROCESSING, SENT, FAILED
attempts Int @default(0)
maxAttempts Int @default(3) @map("max_attempts")
lastError String? @map("last_error") @db.Text
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(100)
sentAt DateTime? @map("sent_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@index([status])
@@index([channel])
@@index([event])
@@index([createdAt])
@@map("notification_queues")
}
// ------------------------------------------------------------------------------
// 12. NotificationTemplate (قالب‌های رویدادها برای ایمیل و پیامک)
// ------------------------------------------------------------------------------
model NotificationTemplate {
id String @id @default(uuid()) @db.Uuid
channel String @db.VarChar(20) // SMS, EMAIL
event String @db.VarChar(50) // ORDER_CREATED, PAYMENT_SUCCESS, NEW_LEAD, etc.
name String @db.VarChar(150)
subject String? @db.VarChar(255)
body String @db.Text
patternCode String? @map("pattern_code") @db.VarChar(50)
variables String[] @default([])
recipientType String @default("customer") @map("recipient_type") @db.VarChar(30)
customRecipient String? @map("custom_recipient") @db.VarChar(150)
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@unique([channel, event])
@@index([channel])
@@index([event])
@@index([isActive])
@@map("notification_templates")
}
+125
View File
@@ -0,0 +1,125 @@
import {
Controller,
Get,
Post,
Put,
Patch,
Delete,
Body,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdvisorsService, CreateAdvisorDto } from './advisors.service';
import { PrismaService } from '../prisma/prisma.service';
@Controller('admin')
@UseGuards(JwtAuthGuard)
export class AdvisorsController {
constructor(
private readonly advisorsService: AdvisorsService,
private readonly prisma: PrismaService,
) {}
/**
* Advisors Management
*/
@Get('advisors')
async listAdvisors() {
const data = await this.advisorsService.listAdvisors();
return { success: true, data };
}
@Post('advisors')
async createAdvisor(@Body() dto: CreateAdvisorDto) {
const data = await this.advisorsService.createAdvisor(dto);
return { success: true, message: 'مشاور جدید با موفقیت اضافه شد.', data };
}
@Put('advisors/:id')
async updateAdvisor(@Param('id') id: string, @Body() dto: Partial<CreateAdvisorDto>) {
const data = await this.advisorsService.updateAdvisor(id, dto);
return { success: true, message: 'اطلاعات مشاور به‌روزرسانی شد.', data };
}
@Patch('advisors/:id/set-default')
async setDefaultAdvisor(@Param('id') id: string) {
const data = await this.advisorsService.setDefaultAdvisor(id);
return { success: true, message: 'مشاور با موفقیت به عنوان پیش‌فرض سیستم انتخاب شد.', data };
}
@Delete('advisors/:id')
async deleteAdvisor(@Param('id') id: string) {
return this.advisorsService.deleteAdvisor(id);
}
/**
* Leads (Contact Requests) Management
*/
@Get('leads')
async listLeads(
@Query('page') page?: number,
@Query('limit') limit?: number,
@Query('status') status?: string,
@Query('search') search?: string,
) {
const data = await this.advisorsService.listLeads({ page, limit, status, search });
return { success: true, data };
}
@Patch('leads/:id/status')
async updateLeadStatus(
@Param('id') id: string,
@Body() body: { status: string; notes?: string },
) {
const data = await this.advisorsService.updateLeadStatus(id, body.status, body.notes);
return { success: true, message: 'وضعیت درخواست تماس به‌روزرسانی شد.', data };
}
@Delete('leads/:id')
async deleteLead(@Param('id') id: string) {
return this.advisorsService.deleteLead(id);
}
/**
* Product Advisor Linking
*/
@Get('products/:productId/advisor')
async getProductAdvisor(@Param('productId') productId: string) {
const pa = await this.prisma.productAdvisor.findFirst({
where: { productId },
include: { advisor: true },
});
return { success: true, data: pa?.advisor || null };
}
@Post('products/:productId/advisor')
async assignProductAdvisor(
@Param('productId') productId: string,
@Body() body: { advisorId: string | null },
) {
if (!body.advisorId) {
// Remove product advisor assignment
await this.prisma.productAdvisor.deleteMany({ where: { productId } });
return { success: true, message: 'مشاور اختصاصی محصول حذف و به حالت پیش‌فرض بازگشت.' };
}
// Upsert assignment
await this.prisma.productAdvisor.upsert({
where: {
productId_advisorId: {
productId,
advisorId: body.advisorId,
},
},
create: {
productId,
advisorId: body.advisorId,
},
update: {},
});
return { success: true, message: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' };
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { AdvisorsService } from './advisors.service';
import { AdvisorsController } from './advisors.controller';
import { PublicLeadController } from './public-lead.controller';
@Module({
imports: [PrismaModule, NotificationsModule],
controllers: [AdvisorsController, PublicLeadController],
providers: [AdvisorsService],
exports: [AdvisorsService],
})
export class AdvisorsModule {}
@@ -0,0 +1,111 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdvisorsService } from './advisors.service';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
import { BadRequestException } from '@nestjs/common';
describe('AdvisorsService', () => {
let service: AdvisorsService;
let prisma: any;
let queueService: any;
beforeEach(async () => {
prisma = {
advisorContact: {
findMany: jest.fn(),
findUnique: jest.fn(),
findFirst: jest.fn(),
create: jest.fn(),
update: jest.fn(),
updateMany: jest.fn(),
delete: jest.fn(),
},
lead: {
findMany: jest.fn(),
count: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
product: {
findUnique: jest.fn(),
},
productAdvisor: {
findFirst: jest.fn(),
},
};
queueService = {
enqueue: jest.fn().mockResolvedValue({ id: 'q-1' }),
};
const module: TestingModule = await Test.createTestingModule({
providers: [
AdvisorsService,
{ provide: PrismaService, useValue: prisma },
{ provide: NotificationsQueueService, useValue: queueService },
],
}).compile();
service = module.get<AdvisorsService>(AdvisorsService);
});
it('should list advisors with counts', async () => {
prisma.advisorContact.findMany.mockResolvedValueOnce([
{
id: 'adv-1',
name: 'دکتر علوی',
phone: '09123456789',
isDefault: true,
isActive: true,
_count: { productAdvisors: 2, leads: 5 },
},
]);
const result = await service.listAdvisors();
expect(result).toHaveLength(1);
expect(result[0].name).toBe('دکتر علوی');
expect(result[0].productsCount).toBe(2);
expect(result[0].leadsCount).toBe(5);
});
it('should create lead and enqueue notifications for default advisor and client', async () => {
prisma.lead.count.mockResolvedValueOnce(0); // rate limit
prisma.advisorContact.findFirst.mockResolvedValueOnce({
id: 'adv-def',
name: 'مشاور پیش‌فرض',
phone: '09120000000',
isDefault: true,
isActive: true,
});
prisma.lead.create.mockResolvedValueOnce({
id: 'lead-1',
firstName: 'علی',
lastName: 'رضایی',
phone: '09129876543',
advisorId: 'adv-def',
status: 'PENDING',
});
const res = await service.handlePublicLead({
firstName: 'علی',
lastName: 'رضایی',
phone: '09129876543',
});
expect(res.success).toBe(true);
expect(res.leadId).toBe('lead-1');
expect(queueService.enqueue).toHaveBeenCalledTimes(2); // 1 for advisor, 1 for client
});
it('should reject invalid phone format', async () => {
await expect(
service.handlePublicLead({
firstName: 'تست',
lastName: 'تستی',
phone: '1234',
}),
).rejects.toThrow(BadRequestException);
});
});
+341
View File
@@ -0,0 +1,341 @@
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
export class CreateAdvisorDto {
name!: string;
phone!: string;
title?: string;
isDefault?: boolean;
isActive?: boolean;
}
export class CreateLeadDto {
firstName!: string;
lastName!: string;
phone!: string;
productId?: string;
}
@Injectable()
export class AdvisorsService {
private readonly logger = new Logger(AdvisorsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly queueService: NotificationsQueueService,
) {}
/**
* List all advisors with attached product count and leads count
*/
async listAdvisors() {
const advisors = await this.prisma.advisorContact.findMany({
orderBy: [{ isDefault: 'desc' }, { createdAt: 'desc' }],
include: {
_count: {
select: {
productAdvisors: true,
leads: true,
},
},
},
});
return advisors.map((a) => ({
id: a.id,
name: a.name,
phone: a.phone,
title: a.title,
isDefault: a.isDefault,
isActive: a.isActive,
productsCount: a._count.productAdvisors,
leadsCount: a._count.leads,
createdAt: a.createdAt,
updatedAt: a.updatedAt,
}));
}
/**
* Create a new advisor
*/
async createAdvisor(dto: CreateAdvisorDto) {
if (!dto.name || !dto.phone) {
throw new BadRequestException('نام و شماره موبایل مشاور الزامی است.');
}
const cleanPhone = dto.phone.trim();
const existing = await this.prisma.advisorContact.findUnique({
where: { phone: cleanPhone },
});
if (existing) {
throw new BadRequestException('مشاوری با این شماره تلفن قبلاً ثبت شده است.');
}
// If marked default, unset others first
if (dto.isDefault) {
await this.prisma.advisorContact.updateMany({
where: { isDefault: true },
data: { isDefault: false },
});
}
const advisor = await this.prisma.advisorContact.create({
data: {
name: dto.name.trim(),
phone: cleanPhone,
title: dto.title?.trim() || null,
isDefault: Boolean(dto.isDefault),
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : true,
},
});
return advisor;
}
/**
* Update advisor
*/
async updateAdvisor(id: string, dto: Partial<CreateAdvisorDto>) {
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
if (!existing) throw new NotFoundException('مشاور مورد نظر یافت نشد.');
if (dto.phone && dto.phone !== existing.phone) {
const phoneExists = await this.prisma.advisorContact.findUnique({
where: { phone: dto.phone.trim() },
});
if (phoneExists && phoneExists.id !== id) {
throw new BadRequestException('شماره تلفن وارد شده برای مشاور دیگری ثبت شده است.');
}
}
if (dto.isDefault) {
await this.prisma.advisorContact.updateMany({
where: { isDefault: true, id: { not: id } },
data: { isDefault: false },
});
}
return this.prisma.advisorContact.update({
where: { id },
data: {
name: dto.name ? dto.name.trim() : undefined,
phone: dto.phone ? dto.phone.trim() : undefined,
title: dto.title !== undefined ? dto.title?.trim() || null : undefined,
isDefault: dto.isDefault !== undefined ? Boolean(dto.isDefault) : undefined,
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : undefined,
},
});
}
/**
* Set advisor as default
*/
async setDefaultAdvisor(id: string) {
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
await this.prisma.advisorContact.updateMany({
where: { isDefault: true },
data: { isDefault: false },
});
return this.prisma.advisorContact.update({
where: { id },
data: { isDefault: true, isActive: true },
});
}
/**
* Delete advisor
*/
async deleteAdvisor(id: string) {
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
await this.prisma.advisorContact.delete({ where: { id } });
return { success: true, message: 'مشاور با موفقیت حذف شد.' };
}
/**
* List customer leads (contact requests)
*/
async listLeads(query: { page?: number; limit?: number; status?: string; search?: string }) {
const page = Math.max(1, Number(query.page || 1));
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
const skip = (page - 1) * limit;
const where: any = {};
if (query.status && query.status !== 'ALL') {
where.status = query.status;
}
if (query.search) {
where.OR = [
{ firstName: { contains: query.search, mode: 'insensitive' } },
{ lastName: { contains: query.search, mode: 'insensitive' } },
{ phone: { contains: query.search, mode: 'insensitive' } },
];
}
const [items, total] = await Promise.all([
this.prisma.lead.findMany({
where,
orderBy: { createdAt: 'desc' },
skip,
take: limit,
include: {
advisor: {
select: { id: true, name: true, phone: true, title: true },
},
product: {
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
},
},
}),
this.prisma.lead.count({ where }),
]);
const [pendingCount, contactedCount, cancelledCount] = await Promise.all([
this.prisma.lead.count({ where: { status: 'PENDING' } }),
this.prisma.lead.count({ where: { status: 'CONTACTED' } }),
this.prisma.lead.count({ where: { status: 'CANCELLED' } }),
]);
return {
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit) || 1,
stats: {
total,
pending: pendingCount,
contacted: contactedCount,
cancelled: cancelledCount,
},
};
}
/**
* Update lead status or notes
*/
async updateLeadStatus(id: string, status: string, notes?: string) {
const lead = await this.prisma.lead.findUnique({ where: { id } });
if (!lead) throw new NotFoundException('درخواست تماس یافت نشد.');
return this.prisma.lead.update({
where: { id },
data: {
status,
notes: notes !== undefined ? notes : undefined,
},
});
}
/**
* Delete lead
*/
async deleteLead(id: string) {
await this.prisma.lead.delete({ where: { id } });
return { success: true, message: 'درخواست تماس با موفقیت حذف شد.' };
}
/**
* Public Lead Creation from Website
*/
async handlePublicLead(dto: CreateLeadDto) {
if (!dto.firstName || !dto.lastName || !dto.phone) {
throw new BadRequestException('نام، نام خانوادگی و شماره موبایل الزامی است.');
}
const cleanPhone = dto.phone.replace(/\s+/g, '').replace(/^(\+98|0098)/, '0');
if (!/^09\d{9}$/.test(cleanPhone)) {
throw new BadRequestException('شماره موبایل وارد شده نامعتبر است (مثال: ۰۹۱۲۳۴۵۶۷۸۹).');
}
// Rate limit: max 3 requests per 24 hours per phone
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const countToday = await this.prisma.lead.count({
where: {
phone: cleanPhone,
createdAt: { gte: oneDayAgo },
},
});
if (countToday >= 3) {
throw new BadRequestException('حداکثر تعداد درخواست روزانه برای این شماره تکمیل شده است. همکاران ما به زودی با شما تماس خواهند گرفت.');
}
// Resolve advisor: Product-specific -> Default advisor -> First active advisor
let advisor = null;
let product = null;
if (dto.productId) {
product = await this.prisma.product.findUnique({
where: { id: dto.productId },
select: { id: true, nameFa: true },
});
const pa = await this.prisma.productAdvisor.findFirst({
where: { productId: dto.productId },
include: { advisor: true },
});
if (pa?.advisor?.isActive) {
advisor = pa.advisor;
}
}
if (!advisor) {
advisor = await this.prisma.advisorContact.findFirst({
where: { isDefault: true, isActive: true },
});
}
if (!advisor) {
advisor = await this.prisma.advisorContact.findFirst({
where: { isActive: true },
});
}
// Create lead record in DB
const lead = await this.prisma.lead.create({
data: {
firstName: dto.firstName.trim(),
lastName: dto.lastName.trim(),
phone: cleanPhone,
productId: dto.productId || null,
advisorId: advisor?.id || null,
status: 'PENDING',
},
});
// Enqueue SMS notification to Advisor
if (advisor) {
const productName = product ? product.nameFa : 'مشاوره عمومی';
const advisorMsg = `مشاور گرامی، درخواست تماس جدیدی از ${dto.firstName} ${dto.lastName} (${cleanPhone}) برای «${productName}» ثبت شد. لطفاً در اسرع وقت تماس حاصل فرمایید.`;
await this.queueService.enqueue({
channel: 'SMS',
recipient: advisor.phone,
event: 'NEW_LEAD',
content: advisorMsg,
idempotencyKey: `lead_advisor_${lead.id}`,
});
}
// Enqueue confirmation SMS to Client
const clientMsg = `${dto.firstName} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.`;
await this.queueService.enqueue({
channel: 'SMS',
recipient: cleanPhone,
event: 'LEAD_CONFIRMATION',
content: clientMsg,
idempotencyKey: `lead_client_${lead.id}`,
});
return {
success: true,
message: 'درخواست مشاوره شما با موفقیت ثبت شد. مشاور ما به زودی با شما تماس خواهد گرفت.',
leadId: lead.id,
};
}
}
@@ -0,0 +1,25 @@
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { AdvisorsService, CreateLeadDto } from './advisors.service';
@Controller('public')
export class PublicLeadController {
constructor(private readonly advisorsService: AdvisorsService) {}
@Post('lead')
@HttpCode(HttpStatus.OK)
async createLead(@Body() dto: CreateLeadDto) {
const result = await this.advisorsService.handlePublicLead(dto);
return {
ok: true,
success: true,
message: result.message,
leadId: result.leadId,
};
}
}
+4
View File
@@ -36,6 +36,8 @@ import { DoctorsModule } from "./doctors/doctors.module";
import { FaqModule } from "./faq/faq.module";
import { MenuModule } from "./menu/menu.module";
import { RevalidationModule } from "./common/revalidation/revalidation.module";
import { NotificationsModule } from "./notifications/notifications.module";
import { AdvisorsModule } from "./advisors/advisors.module";
import { Request, Response, NextFunction } from "express";
@@ -79,6 +81,8 @@ import { Request, Response, NextFunction } from "express";
B2BModule,
FaqModule,
MenuModule,
NotificationsModule,
AdvisorsModule,
],
controllers: [MetricsController],
providers: [
+387
View File
@@ -0,0 +1,387 @@
import { Injectable, Logger } from '@nestjs/common';
import * as net from 'net';
import * as tls from 'tls';
import { PrismaService } from '../prisma/prisma.service';
export interface SmtpConfig {
enabled: boolean;
host: string;
port: number;
secure?: boolean; // true for 465 (TLS), false for 587/25 (STARTTLS)
user: string;
password: string;
fromName: string;
fromEmail: string;
}
export interface SendMailOptions {
to: string;
subject: string;
text?: string;
html?: string;
}
@Injectable()
export class EmailService {
private readonly logger = new Logger(EmailService.name);
constructor(private readonly prisma: PrismaService) {}
/**
* Read SMTP configuration from DB Setting table with fallback to env variables
*/
async getConfig(): Promise<SmtpConfig> {
try {
const setting = await this.prisma.setting.findFirst({
where: { category: 'email' },
});
const dbConfig = (setting?.value as Record<string, any>) || {};
return {
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
host: dbConfig.host || process.env.SMTP_HOST || 'mail.canina.ir',
port: Number(dbConfig.port || process.env.SMTP_PORT || 587),
secure: dbConfig.secure !== undefined ? Boolean(dbConfig.secure) : Number(dbConfig.port || 587) === 465,
user: dbConfig.user || process.env.SMTP_USER || '',
password: dbConfig.password || process.env.SMTP_PASSWORD || '',
fromName: dbConfig.fromName || process.env.SMTP_FROM_NAME || 'کنینا ایران',
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'info@canina.ir',
};
} catch (err: any) {
this.logger.error(`Error loading email config: ${err?.message}`);
return {
enabled: true,
host: process.env.SMTP_HOST || 'mail.canina.ir',
port: Number(process.env.SMTP_PORT || 587),
secure: Number(process.env.SMTP_PORT || 587) === 465,
user: process.env.SMTP_USER || '',
password: process.env.SMTP_PASSWORD || '',
fromName: 'کنینا ایران',
fromEmail: 'info@canina.ir',
};
}
}
/**
* Save SMTP configuration to database
*/
async saveConfig(dto: Partial<SmtpConfig>): Promise<SmtpConfig> {
const current = await this.getConfig();
const updated: SmtpConfig = {
...current,
...dto,
port: Number(dto.port ?? current.port),
secure: dto.secure ?? (Number(dto.port ?? current.port) === 465),
};
const existing = await this.prisma.setting.findFirst({ where: { category: 'email' } });
if (existing) {
await this.prisma.setting.update({
where: { id: existing.id },
data: { value: updated as any },
});
} else {
await this.prisma.setting.create({
data: {
category: 'email',
key: 'smtp_config',
value: updated as any,
},
});
}
return updated;
}
/**
* Test SMTP connection with the given or stored configuration
*/
async testConnection(customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; message: string; banner?: string }> {
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
if (!config.host || !config.port) {
return { success: false, message: 'آدرس هاست و پورت SMTP الزامی است.' };
}
return new Promise((resolve) => {
const isExplicitTls = config.secure || config.port === 465;
let buffer = '';
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=quit
let banner = '';
const timer = setTimeout(() => {
try {
socket.destroy();
} catch {}
resolve({ success: false, message: 'تایم‌اوت در اتصال به سرور SMTP (بیش از ۱۰ ثانیه)' });
}, 10000);
const cleanup = (res: { success: boolean; message: string; banner?: string }) => {
clearTimeout(timer);
try {
socket.end();
socket.destroy();
} catch {}
resolve(res);
};
const handleData = (chunk: Buffer) => {
buffer += chunk.toString('utf8');
const lines = buffer.split('\r\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line) continue;
const code = parseInt(line.substring(0, 3), 10);
const isFinal = line.charAt(3) === ' ';
if (!isFinal) continue; // Multi-line response continuation
if (stage === 0) {
banner = line;
if (code >= 200 && code < 300) {
stage = 1;
socket.write(`EHLO canina.ir\r\n`);
} else {
return cleanup({ success: false, message: `پاسخ ناموفق از سرور: ${line}`, banner });
}
} else if (stage === 1) {
if (code >= 200 && code < 300) {
if (config.user && config.password) {
stage = 2;
socket.write('AUTH LOGIN\r\n');
} else {
stage = 5;
socket.write('QUIT\r\n');
return cleanup({ success: true, message: 'اتصال به سرور SMTP بدون احراز هویت با موفقیت برقرار شد.', banner });
}
} else {
return cleanup({ success: false, message: `خطای EHLO: ${line}`, banner });
}
} else if (stage === 2) {
if (code === 334) {
stage = 3;
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
} else {
return cleanup({ success: false, message: `سرور از AUTH LOGIN پشتیبانی نمی‌کند یا خطا داد: ${line}`, banner });
}
} else if (stage === 3) {
if (code === 334) {
stage = 4;
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
} else {
return cleanup({ success: false, message: `نام کاربری پذیرفته نشد: ${line}`, banner });
}
} else if (stage === 4) {
if (code === 235 || (code >= 200 && code < 300)) {
stage = 5;
socket.write('QUIT\r\n');
return cleanup({ success: true, message: 'اتصال و احراز هویت با سرور SMTP با موفقیت تأیید شد.', banner });
} else {
return cleanup({ success: false, message: `احراز هویت ناموفق بود (نام کاربری یا رمز عبور اشتباه است): ${line}`, banner });
}
}
}
};
let socket: net.Socket;
try {
if (isExplicitTls) {
socket = tls.connect({
host: config.host,
port: config.port,
rejectUnauthorized: false,
}, () => {});
} else {
socket = net.connect({
host: config.host,
port: config.port,
}, () => {});
}
socket.on('data', handleData);
socket.on('error', (err) => {
cleanup({ success: false, message: `خطای شبکه در ارتباط با ${config.host}:${config.port} - ${err.message}` });
});
} catch (err: any) {
cleanup({ success: false, message: `خطا در باز کردن سوکت: ${err?.message}` });
}
});
}
/**
* Send a MIME Email message through SMTP
*/
async sendMail(options: SendMailOptions, customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; messageId?: string; error?: string }> {
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
if (!config.enabled) {
return { success: false, error: 'سرویس ارسال ایمیل در تنظیمات غیرفعال است.' };
}
if (!config.host || !options.to) {
return { success: false, error: 'هاست SMTP یا آدرس گیرنده مشخص نشده است.' };
}
return new Promise((resolve) => {
const isExplicitTls = config.secure || config.port === 465;
let buffer = '';
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=mail_from, 6=rcpt_to, 7=data_cmd, 8=data_body, 9=quit
const messageId = `<${Date.now()}.${Math.random().toString(36).substring(2)}@${config.host}>`;
const timer = setTimeout(() => {
try {
socket.destroy();
} catch {}
resolve({ success: false, error: 'تایم‌اوت ارسال ایمیل (۱۵ ثانیه)' });
}, 15000);
const cleanup = (res: { success: boolean; messageId?: string; error?: string }) => {
clearTimeout(timer);
try {
socket.end();
socket.destroy();
} catch {}
resolve(res);
};
const handleData = (chunk: Buffer) => {
buffer += chunk.toString('utf8');
const lines = buffer.split('\r\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line) continue;
const code = parseInt(line.substring(0, 3), 10);
const isFinal = line.charAt(3) === ' ';
if (!isFinal) continue;
if (stage === 0) {
if (code >= 200 && code < 300) {
stage = 1;
socket.write(`EHLO canina.ir\r\n`);
} else {
return cleanup({ success: false, error: `پاسخ سرور: ${line}` });
}
} else if (stage === 1) {
if (code >= 200 && code < 300) {
if (config.user && config.password) {
stage = 2;
socket.write('AUTH LOGIN\r\n');
} else {
stage = 5;
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
}
} else {
return cleanup({ success: false, error: `خطای EHLO: ${line}` });
}
} else if (stage === 2) {
if (code === 334) {
stage = 3;
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
} else {
return cleanup({ success: false, error: `خطای احراز هویت: ${line}` });
}
} else if (stage === 3) {
if (code === 334) {
stage = 4;
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
} else {
return cleanup({ success: false, error: `نام کاربری رد شد: ${line}` });
}
} else if (stage === 4) {
if (code === 235 || (code >= 200 && code < 300)) {
stage = 5;
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
} else {
return cleanup({ success: false, error: `رمز عبور رد شد: ${line}` });
}
} else if (stage === 5) {
if (code >= 200 && code < 300) {
stage = 6;
socket.write(`RCPT TO:<${options.to}>\r\n`);
} else {
return cleanup({ success: false, error: `آدرس فرستنده رد شد: ${line}` });
}
} else if (stage === 6) {
if (code >= 200 && code < 300) {
stage = 7;
socket.write('DATA\r\n');
} else {
return cleanup({ success: false, error: `آدرس گیرنده رد شد: ${line}` });
}
} else if (stage === 7) {
if (code === 354) {
stage = 8;
const encodedSubject = `=?UTF-8?B?${Buffer.from(options.subject).toString('base64')}?=`;
const encodedFromName = `=?UTF-8?B?${Buffer.from(config.fromName).toString('base64')}?=`;
const boundary = `boundary_${Date.now()}`;
let emailBody = '';
emailBody += `From: ${encodedFromName} <${config.fromEmail}>\r\n`;
emailBody += `To: <${options.to}>\r\n`;
emailBody += `Subject: ${encodedSubject}\r\n`;
emailBody += `Message-ID: ${messageId}\r\n`;
emailBody += `Date: ${new Date().toUTCString()}\r\n`;
emailBody += `MIME-Version: 1.0\r\n`;
emailBody += `Content-Type: multipart/alternative; boundary="${boundary}"\r\n\r\n`;
if (options.text) {
emailBody += `--${boundary}\r\n`;
emailBody += `Content-Type: text/plain; charset=UTF-8\r\n`;
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
emailBody += Buffer.from(options.text).toString('base64') + '\r\n\r\n';
}
const htmlContent = options.html || options.text || '';
emailBody += `--${boundary}\r\n`;
emailBody += `Content-Type: text/html; charset=UTF-8\r\n`;
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
emailBody += Buffer.from(htmlContent).toString('base64') + '\r\n\r\n';
emailBody += `--${boundary}--\r\n.\r\n`;
socket.write(emailBody);
} else {
return cleanup({ success: false, error: `دستور DATA رد شد: ${line}` });
}
} else if (stage === 8) {
if (code >= 200 && code < 300) {
stage = 9;
socket.write('QUIT\r\n');
return cleanup({ success: true, messageId });
} else {
return cleanup({ success: false, error: `رد شدن ارسال محتوا: ${line}` });
}
}
}
};
let socket: net.Socket;
try {
if (isExplicitTls) {
socket = tls.connect({
host: config.host,
port: config.port,
rejectUnauthorized: false,
}, () => {});
} else {
socket = net.connect({
host: config.host,
port: config.port,
}, () => {});
}
socket.on('data', handleData);
socket.on('error', (err) => {
cleanup({ success: false, error: `خطای ارسال: ${err.message}` });
});
} catch (err: any) {
cleanup({ success: false, error: `خطا در باز کردن اتصال: ${err?.message}` });
}
});
}
}
@@ -0,0 +1,123 @@
import { Test, TestingModule } from '@nestjs/testing';
import { NotificationsQueueService } from './notifications-queue.service';
import { EmailService } from './email.service';
import { SmsService } from '../common/services/sms.service';
import { PrismaService } from '../prisma/prisma.service';
describe('NotificationsQueueService', () => {
let service: NotificationsQueueService;
let prisma: any;
let emailService: any;
let smsService: any;
beforeEach(async () => {
prisma = {
notificationQueue: {
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
},
};
emailService = {
sendMail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
};
smsService = {
sendPatternSms: jest.fn().mockResolvedValue(true),
sendSms: jest.fn().mockResolvedValue(true),
};
const module: TestingModule = await Test.createTestingModule({
providers: [
NotificationsQueueService,
{ provide: PrismaService, useValue: prisma },
{ provide: EmailService, useValue: emailService },
{ provide: SmsService, useValue: smsService },
],
}).compile();
service = module.get<NotificationsQueueService>(NotificationsQueueService);
});
it('should enqueue notification and preserve idempotency', async () => {
prisma.notificationQueue.findUnique.mockResolvedValueOnce(null);
prisma.notificationQueue.create.mockResolvedValueOnce({
id: 'queue-1',
channel: 'EMAIL',
recipient: 'user@example.com',
event: 'ORDER_CREATED',
content: 'Hello World',
idempotencyKey: 'idemp-1',
status: 'QUEUED',
attempts: 0,
});
const res = await service.enqueue({
channel: 'EMAIL',
recipient: 'user@example.com',
event: 'ORDER_CREATED',
content: 'Hello World',
idempotencyKey: 'idemp-1',
});
expect(prisma.notificationQueue.findUnique).toHaveBeenCalledWith({ where: { idempotencyKey: 'idemp-1' } });
expect(prisma.notificationQueue.create).toHaveBeenCalled();
expect(res.id).toBe('queue-1');
});
it('should return existing notification if idempotency key exists', async () => {
const existing = {
id: 'existing-1',
channel: 'SMS',
recipient: '09121111111',
event: 'OTP',
content: '12345',
idempotencyKey: 'idemp-2',
status: 'SENT',
};
prisma.notificationQueue.findUnique.mockResolvedValueOnce(existing);
const res = await service.enqueue({
channel: 'SMS',
recipient: '09121111111',
event: 'OTP',
content: '12345',
idempotencyKey: 'idemp-2',
});
expect(prisma.notificationQueue.create).not.toHaveBeenCalled();
expect(res.id).toBe('existing-1');
});
it('should process email queue item and mark as SENT', async () => {
const item = {
id: 'item-1',
channel: 'EMAIL',
recipient: 'user@example.com',
subject: 'Test Subject',
content: 'Test Body',
payload: {},
status: 'QUEUED',
attempts: 0,
maxAttempts: 3,
};
prisma.notificationQueue.findUnique.mockResolvedValueOnce(item);
prisma.notificationQueue.update.mockResolvedValue({});
await service.processItem('item-1');
expect(emailService.sendMail).toHaveBeenCalledWith({
to: 'user@example.com',
subject: 'Test Subject',
text: 'Test Body',
html: expect.stringContaining('Test Body'),
});
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
where: { id: 'item-1' },
data: expect.objectContaining({ status: 'SENT' }),
});
});
});
@@ -0,0 +1,273 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { EmailService } from './email.service';
import { SmsService } from '../common/services/sms.service';
export interface EnqueueOptions {
channel: 'SMS' | 'EMAIL';
recipient: string;
event: string;
subject?: string;
content: string;
payload?: any;
idempotencyKey?: string;
maxAttempts?: number;
}
@Injectable()
export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(NotificationsQueueService.name);
private workerInterval: NodeJS.Timeout | null = null;
private isProcessing = false;
constructor(
private readonly prisma: PrismaService,
private readonly emailService: EmailService,
private readonly smsService: SmsService,
) {}
onModuleInit() {
// Run background queue processor every 15 seconds
this.workerInterval = setInterval(() => {
this.processQueue().catch((err) => {
this.logger.error(`Error in queue worker: ${err?.message}`);
});
}, 15000);
}
onModuleDestroy() {
if (this.workerInterval) {
clearInterval(this.workerInterval);
this.workerInterval = null;
}
}
/**
* Enqueue a durable notification with idempotency check
*/
async enqueue(options: EnqueueOptions) {
if (options.idempotencyKey) {
const existing = await this.prisma.notificationQueue.findUnique({
where: { idempotencyKey: options.idempotencyKey },
});
if (existing) {
this.logger.log(`Notification idempotency matched for key: ${options.idempotencyKey}`);
return existing;
}
}
const item = await this.prisma.notificationQueue.create({
data: {
channel: options.channel,
recipient: options.recipient,
event: options.event,
subject: options.subject || null,
content: options.content,
payload: options.payload ?? null,
idempotencyKey: options.idempotencyKey || null,
maxAttempts: options.maxAttempts ?? 3,
status: 'QUEUED',
},
});
// Attempt immediate asynchronous process in the background
setImmediate(() => {
this.processItem(item.id).catch(() => {});
});
return item;
}
/**
* Process a single queued item by ID
*/
async processItem(id: string) {
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
if (!item || item.status === 'SENT') return;
if (item.attempts >= item.maxAttempts) {
await this.prisma.notificationQueue.update({
where: { id },
data: { status: 'FAILED' },
});
return;
}
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'PROCESSING',
attempts: { increment: 1 },
},
});
try {
if (item.channel === 'EMAIL') {
const payloadObj = (item.payload as Record<string, any>) || {};
const res = await this.emailService.sendMail({
to: item.recipient,
subject: item.subject || 'اطلاعیه کنینا ایران',
text: item.content,
html: payloadObj.html || `<div style="font-family:Tahoma,sans-serif;direction:rtl;padding:20px;">${item.content.replace(/\n/g, '<br/>')}</div>`,
});
if (res.success) {
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'SENT',
sentAt: new Date(),
lastError: null,
},
});
return;
} else {
throw new Error(res.error || 'خطای نامشخص در ارسال ایمیل');
}
} else if (item.channel === 'SMS') {
const payloadObj = (item.payload as Record<string, any>) || {};
if (payloadObj.patternId && Array.isArray(payloadObj.args)) {
await this.smsService.sendPatternSms({
to: item.recipient,
bodyId: Number(payloadObj.patternId),
args: payloadObj.args,
type: item.event,
});
} else {
await this.smsService.sendSms(item.recipient, item.content);
}
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'SENT',
sentAt: new Date(),
lastError: null,
},
});
return;
}
} catch (err: any) {
const isFinalAttempt = item.attempts + 1 >= item.maxAttempts;
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: isFinalAttempt ? 'FAILED' : 'QUEUED',
lastError: err?.message || 'خطا در ارسال پیام',
},
});
this.logger.warn(`Failed to deliver notification ${id} (${item.channel} to ${item.recipient}): ${err?.message}`);
}
}
/**
* Process pending batch of queue
*/
async processQueue(batchSize = 10) {
if (this.isProcessing) return;
this.isProcessing = true;
try {
const pendingItems = await this.prisma.notificationQueue.findMany({
where: {
status: 'QUEUED',
attempts: { lt: 3 },
},
orderBy: { createdAt: 'asc' },
take: batchSize,
});
for (const item of pendingItems) {
await this.processItem(item.id);
}
} finally {
this.isProcessing = false;
}
}
/**
* Retry a failed notification manually
*/
async retry(id: string) {
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
if (!item) throw new Error('آیتم صف یافت نشد.');
const updated = await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'QUEUED',
attempts: 0,
lastError: null,
},
});
setImmediate(() => {
this.processItem(id).catch(() => {});
});
return updated;
}
/**
* Get queue items with filtering and pagination
*/
async getQueue(query: { page?: number; limit?: number; status?: string; channel?: string; search?: string }) {
const page = Math.max(1, Number(query.page || 1));
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
const skip = (page - 1) * limit;
const where: any = {};
if (query.status) where.status = query.status;
if (query.channel) where.channel = query.channel;
if (query.search) {
where.OR = [
{ recipient: { contains: query.search, mode: 'insensitive' } },
{ subject: { contains: query.search, mode: 'insensitive' } },
{ event: { contains: query.search, mode: 'insensitive' } },
];
}
const [items, total] = await Promise.all([
this.prisma.notificationQueue.findMany({
where,
orderBy: { createdAt: 'desc' },
skip,
take: limit,
}),
this.prisma.notificationQueue.count({ where }),
]);
const stats = await this.getStats();
return {
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit) || 1,
stats,
};
}
/**
* Get overall stats
*/
async getStats() {
const [total, queued, processing, sent, failed] = await Promise.all([
this.prisma.notificationQueue.count(),
this.prisma.notificationQueue.count({ where: { status: 'QUEUED' } }),
this.prisma.notificationQueue.count({ where: { status: 'PROCESSING' } }),
this.prisma.notificationQueue.count({ where: { status: 'SENT' } }),
this.prisma.notificationQueue.count({ where: { status: 'FAILED' } }),
]);
return {
total,
queued,
processing,
sent,
failed,
successRate: total > 0 ? Math.round((sent / total) * 100) : 100,
};
}
}
@@ -0,0 +1,348 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
BadRequestException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { EmailService, SmtpConfig } from './email.service';
import { NotificationsQueueService } from './notifications-queue.service';
import { SmsService } from '../common/services/sms.service';
import { PrismaService } from '../prisma/prisma.service';
@Controller('admin/notifications')
@UseGuards(JwtAuthGuard)
export class NotificationsController {
constructor(
private readonly emailService: EmailService,
private readonly queueService: NotificationsQueueService,
private readonly smsService: SmsService,
private readonly prisma: PrismaService,
) {}
/**
* Get notification settings (Email & SMS)
*/
@Get('config')
async getConfig() {
const [email, sms] = await Promise.all([
this.emailService.getConfig(),
this.smsService.getSmsConfig(),
]);
// Mask password for security
const maskedEmail = {
...email,
password: email.password ? '••••••••' : '',
};
const maskedSms = {
...sms,
password: sms.password ? '••••••••' : '',
};
return {
success: true,
data: {
email: maskedEmail,
sms: maskedSms,
},
};
}
/**
* Update SMTP Email config
*/
@Put('email-config')
async updateEmailConfig(@Body() dto: Partial<SmtpConfig>) {
// If password is masked, don't overwrite with dots
if (dto.password && dto.password.includes('•')) {
delete dto.password;
}
const saved = await this.emailService.saveConfig(dto);
return {
success: true,
message: 'تنظیمات ایمیل با موفقیت ذخیره شد.',
data: {
...saved,
password: saved.password ? '••••••••' : '',
},
};
}
/**
* Test SMTP connection live
*/
@Post('test-smtp')
async testSmtp(@Body() customConfig?: Partial<SmtpConfig>) {
if (customConfig?.password && customConfig.password.includes('•')) {
delete customConfig.password;
}
const res = await this.emailService.testConnection(customConfig);
return {
success: res.success,
message: res.message,
banner: res.banner,
};
}
/**
* Send test email
*/
@Post('send-test-email')
async sendTestEmail(@Body() body: { to: string; subject?: string; message?: string }) {
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
const res = await this.emailService.sendMail({
to: body.to,
subject: body.subject || 'تست اتصال ایمیل - کنینا ایران',
text: body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.',
html: `
<div style="font-family:Tahoma,sans-serif;direction:rtl;background:#f3f4f6;padding:30px;color:#1f2937;">
<div style="max-width:550px;margin:0 auto;background:#fff;border-radius:12px;padding:24px;border:1px solid #e5e7eb;">
<h2 style="color:#7c3aed;margin-top:0;">کنینا ایران | تست سرور ایمیل</h2>
<p>${body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.'}</p>
<hr style="border:0;border-top:1px solid #f3f4f6;margin:20px 0;" />
<small style="color:#9ca3af;">زمان ارسال: ${new Date().toLocaleString('fa-IR')}</small>
</div>
</div>
`,
});
if (!res.success) {
throw new BadRequestException(res.error || 'ارسال ایمیل تستی ناموفق بود.');
}
return {
success: true,
message: `ایمیل تستی با موفقیت به ${body.to} ارسال شد.`,
messageId: res.messageId,
};
}
/**
* Send test SMS
*/
@Post('send-test-sms')
async sendTestSms(@Body() body: { to: string; message: string }) {
if (!body.to || !body.message) {
throw new BadRequestException('شماره موبایل و متن پیام الزامی است.');
}
const res = await this.smsService.sendSms(body.to, body.message);
if (!res) throw new BadRequestException('ارسال پیامک تستی ناموفق بود.');
return {
success: true,
message: `پیامک تستی با موفقیت به ${body.to} ارسال شد.`,
};
}
/**
* Manual targeted notification send
*/
@Post('manual-send')
async manualSend(
@Body()
body: {
channel: 'SMS' | 'EMAIL';
targetType: 'single' | 'all_users' | 'custom_list';
recipient?: string;
recipients?: string[];
subject?: string;
content: string;
},
) {
if (!body.channel || !body.content) {
throw new BadRequestException('کانال ارسال و متن پیام الزامی است.');
}
let targetList: string[] = [];
if (body.targetType === 'single') {
if (!body.recipient) throw new BadRequestException('گیرنده پیام مشخص نشده است.');
targetList = [body.recipient.trim()];
} else if (body.targetType === 'custom_list') {
if (!Array.isArray(body.recipients) || !body.recipients.length) {
throw new BadRequestException('لیست گیرندگان خالی است.');
}
targetList = body.recipients.map((r) => r.trim()).filter(Boolean);
} else if (body.targetType === 'all_users') {
const users = await this.prisma.user.findMany({
select: { mobile: true, email: true },
take: 1000,
});
if (body.channel === 'SMS') {
targetList = users.map((u) => u.mobile).filter(Boolean) as string[];
} else {
targetList = users.map((u) => u.email).filter(Boolean) as string[];
}
}
if (!targetList.length) {
throw new BadRequestException('هیچ گیرنده معتبری برای ارسال یافت نشد.');
}
// Enqueue all items into durable queue
const queuedItems = await Promise.all(
targetList.map((rec) =>
this.queueService.enqueue({
channel: body.channel,
recipient: rec,
event: 'MANUAL_TARGETED_SEND',
subject: body.subject,
content: body.content,
idempotencyKey: `manual_${body.channel}_${rec}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
}),
),
);
return {
success: true,
message: `${queuedItems.length} پیام با موفقیت در صف ارسال قرار گرفت.`,
count: queuedItems.length,
};
}
/**
* Get queue items and statistics
*/
@Get('queue')
async getQueue(
@Query('page') page?: number,
@Query('limit') limit?: number,
@Query('status') status?: string,
@Query('channel') channel?: string,
@Query('search') search?: string,
) {
const data = await this.queueService.getQueue({ page, limit, status, channel, search });
return {
success: true,
data,
};
}
/**
* Retry failed queue item
*/
@Post('queue/:id/retry')
async retryQueueItem(@Param('id') id: string) {
const retried = await this.queueService.retry(id);
return {
success: true,
message: 'پیام مجدداً در صف ارسال قرار گرفت.',
data: retried,
};
}
/**
* Get notification templates & event definitions
*/
@Get('templates')
async getTemplates() {
const templates = await this.prisma.notificationTemplate.findMany({
orderBy: { createdAt: 'desc' },
});
const defaultEvents = [
{ event: 'ORDER_CREATED', name: 'ثبت سفارش جدید', variables: ['order_id', 'customer_name', 'total_amount'] },
{ event: 'PAYMENT_SUCCESS', name: 'پرداخت موفق سفارش', variables: ['order_id', 'track_id', 'amount'] },
{ event: 'ORDER_SHIPPED', name: 'ارسال سفارش پستی', variables: ['order_id', 'tracking_code', 'carrier'] },
{ event: 'NEW_LEAD', name: 'درخواست تماس یا مشاوره جدید', variables: ['lead_name', 'phone', 'product_name'] },
{ event: 'USER_REGISTERED', name: 'ثبت‌نام کاربر جدید', variables: ['user_name', 'mobile'] },
{ event: 'TICKET_REPLIED', name: 'پاسخ به تیکت پشتیبانی', variables: ['ticket_id', 'user_name'] },
];
return {
success: true,
data: {
templates,
events: defaultEvents,
},
};
}
/**
* Create or update notification template
*/
@Post('templates')
async upsertTemplate(
@Body()
dto: {
id?: string;
channel: 'SMS' | 'EMAIL';
event: string;
name: string;
subject?: string;
body: string;
patternCode?: string;
variables?: string[];
recipientType?: string;
customRecipient?: string;
isActive?: boolean;
},
) {
if (!dto.channel || !dto.event || !dto.name || !dto.body) {
throw new BadRequestException('اطلاعات ضروری قالب ناقص است.');
}
const data = {
channel: dto.channel,
event: dto.event,
name: dto.name,
subject: dto.subject || null,
body: dto.body,
patternCode: dto.patternCode || null,
variables: dto.variables || [],
recipientType: dto.recipientType || 'customer',
customRecipient: dto.customRecipient || null,
isActive: dto.isActive !== undefined ? dto.isActive : true,
};
let template;
if (dto.id) {
template = await this.prisma.notificationTemplate.update({
where: { id: dto.id },
data,
});
} else {
template = await this.prisma.notificationTemplate.upsert({
where: {
channel_event: {
channel: dto.channel,
event: dto.event,
},
},
create: data,
update: data,
});
}
return {
success: true,
message: 'قالب رویداد با موفقیت ذخیره شد.',
data: template,
};
}
/**
* Delete template
*/
@Delete('templates/:id')
async deleteTemplate(@Param('id') id: string) {
await this.prisma.notificationTemplate.delete({ where: { id } });
return {
success: true,
message: 'قالب رویداد حذف شد.',
};
}
}
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { SmsModule } from '../common/sms.module';
import { EmailService } from './email.service';
import { NotificationsQueueService } from './notifications-queue.service';
import { NotificationsController } from './notifications.controller';
@Module({
imports: [PrismaModule, SmsModule],
controllers: [NotificationsController],
providers: [EmailService, NotificationsQueueService],
exports: [EmailService, NotificationsQueueService],
})
export class NotificationsModule {}
@@ -1,5 +1,6 @@
import {
Activity,
Bell,
CheckSquare,
BookOpen,
Building2,
@@ -170,6 +171,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: Users, label: 'مدیریت کاربران', path: '/users' },
{ icon: Heart, label: 'پرونده پت‌ها (همدم‌ها)', path: '/pets' },
{ icon: MessageSquare, label: 'تیکت‌ها و مشاوره تخصصی', path: '/tickets' },
{ icon: PhoneCall, label: 'مشاوران و لیدهای تماس', path: '/advisors' },
{ icon: Building2, label: 'پرتال B2B و همکاران', path: '/b2b' },
{ icon: PhoneCall, label: 'اطلاعات تماس و پیام‌ها', path: '/contact' },
],
@@ -201,6 +203,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: CreditCard, label: 'روش‌های پرداخت و زیبال', path: '/settings/payment-methods' },
{ icon: Truck, label: 'تنظیمات ارسال و کرایه', path: '/settings/shipping' },
{ icon: DollarSign, label: 'تنظیمات مالی و مالیات', path: '/settings/financial' },
{ icon: Bell, label: 'مرکز اطلاع‌رسانی (ایمیل و صف)', path: '/settings/notifications' },
{ icon: MessageSquare, label: 'درگاه پیامک (MeliPayamak)', path: '/settings/sms' },
{ icon: ShieldCheck, label: 'گواهی SSL و امنیت', path: '/settings/ssl' },
{ icon: Key, label: 'کلیدهای دسترسی (API Keys)', path: '/settings/api-keys' },
@@ -0,0 +1,512 @@
import React, { useState, useEffect } from 'react';
import {
Users,
UserPlus,
PhoneCall,
CheckCircle2,
Clock,
Trash2,
Edit2,
Star,
Search,
Package,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import Spinner from '../components/ui/Spinner';
import Modal from '../components/ui/Modal';
import api from '../services/api';
interface Advisor {
id: string;
name: string;
phone: string;
title?: string;
isDefault: boolean;
isActive: boolean;
productsCount: number;
leadsCount: number;
}
interface Lead {
id: string;
firstName: string;
lastName: string;
phone: string;
status: string;
notes?: string;
createdAt: string;
advisor?: { id: string; name: string; phone: string; title?: string };
product?: { id: string; nameFa: string; nameEn: string; slug: string };
}
export default function AdvisorsManagementPage() {
const [activeTab, setActiveTab] = useState<'leads' | 'advisors'>('leads');
const [isLoading, setIsLoading] = useState(true);
// Advisors State
const [advisors, setAdvisors] = useState<Advisor[]>([]);
const [isAdvisorModalOpen, setIsAdvisorModalOpen] = useState(false);
const [editingAdvisor, setEditingAdvisor] = useState<Advisor | null>(null);
const [advisorForm, setAdvisorForm] = useState({
name: '',
phone: '',
title: '',
isDefault: false,
isActive: true,
});
// Leads State
const [leads, setLeads] = useState<Lead[]>([]);
const [leadStats, setLeadStats] = useState({ total: 0, pending: 0, contacted: 0, cancelled: 0 });
const [leadFilterStatus, setLeadFilterStatus] = useState<string>('ALL');
const [searchTerm, setSearchTerm] = useState('');
const loadAdvisors = async () => {
try {
const res = await api.get('/admin/advisors');
if (res.data?.success) {
setAdvisors(res.data.data);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت لیست مشاوران');
}
};
const loadLeads = async () => {
try {
setIsLoading(true);
const res = await api.get(`/admin/leads?status=${leadFilterStatus}&search=${encodeURIComponent(searchTerm)}`);
if (res.data?.success) {
setLeads(res.data.data.items);
if (res.data.data.stats) setLeadStats(res.data.data.stats);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت لیست درخواست‌های تماس');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadAdvisors();
loadLeads();
}, [leadFilterStatus]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
loadLeads();
};
const handleSaveAdvisor = async (e: React.FormEvent) => {
e.preventDefault();
if (!advisorForm.name.trim() || !advisorForm.phone.trim()) {
toast.error('نام و شماره موبایل الزامی است.');
return;
}
try {
if (editingAdvisor) {
await api.put(`/admin/advisors/${editingAdvisor.id}`, advisorForm);
toast.success('مشاور با موفقیت ویرایش شد.');
} else {
await api.post('/admin/advisors', advisorForm);
toast.success('مشاور جدید افزوده شد.');
}
setIsAdvisorModalOpen(false);
setEditingAdvisor(null);
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
loadAdvisors();
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ثبت مشاور');
}
};
const handleSetDefaultAdvisor = async (id: string) => {
try {
await api.patch(`/admin/advisors/${id}/set-default`);
toast.success('مشاور به عنوان پیش‌فرض تعیین شد.');
loadAdvisors();
} catch (err: any) {
toast.error('خطا در تغییر مشاور پیش‌فرض');
}
};
const handleDeleteAdvisor = async (id: string) => {
if (!window.confirm('آیا از حذف این مشاور اطمینان دارید؟')) return;
try {
await api.delete(`/admin/advisors/${id}`);
toast.success('مشاور حذف شد.');
loadAdvisors();
} catch (err: any) {
toast.error('خطا در حذف مشاور');
}
};
const handleUpdateLeadStatus = async (id: string, status: string) => {
try {
await api.patch(`/admin/leads/${id}/status`, { status });
toast.success('وضعیت درخواست تماس به‌روز شد.');
loadLeads();
} catch (err: any) {
toast.error('خطا در به‌روزرسانی وضعیت');
}
};
return (
<div className="space-y-6 pb-12 font-vazir text-gray-800">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
<PhoneCall className="h-7 w-7 text-purple-600" />
درخواست‌های تماس و مشاوران کاتالوگ
</h1>
<p className="mt-1 text-sm text-gray-500">
مدیریت لیدهای تماس وب‌سایت، انتساب مشاوران پیش‌فرض و اختصاصی محصولات
</p>
</div>
<div className="flex items-center gap-3">
<Button onClick={() => {
setEditingAdvisor(null);
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
setIsAdvisorModalOpen(true);
}}>
<UserPlus className="h-4 w-4" />
افزودن مشاور جدید
</Button>
</div>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
<button
onClick={() => setActiveTab('leads')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'leads'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<PhoneCall className="h-4 w-4" />
درخواست‌های تماس کاربران (Leads)
{leadStats.pending > 0 && (
<span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-700 font-bold">
{leadStats.pending} نیازمند تماس
</span>
)}
</button>
<button
onClick={() => setActiveTab('advisors')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'advisors'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Users className="h-4 w-4" />
لیست مشاوران تخصصی
<span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 font-bold">
{advisors.length}
</span>
</button>
</div>
{/* Tab: Leads */}
{activeTab === 'leads' && (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">مجموع درخواست‌ها</span>
<p className="mt-2 text-2xl font-black text-gray-900">{leadStats.total}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-amber-500">در انتظار تماس</span>
<p className="mt-2 text-2xl font-black text-amber-600">{leadStats.pending}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-emerald-500">تماس گرفته شده</span>
<p className="mt-2 text-2xl font-black text-emerald-600">{leadStats.contacted}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">لغو شده / ناموفق</span>
<p className="mt-2 text-2xl font-black text-gray-600">{leadStats.cancelled}</p>
</div>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-4">
<form onSubmit={handleSearch} className="flex gap-2 w-full sm:w-80">
<input
type="text"
placeholder="جستجو با نام یا شماره..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
/>
<Button type="submit" variant="outline" size="sm">
<Search className="h-4 w-4" />
</Button>
</form>
<div className="flex gap-2">
{['ALL', 'PENDING', 'CONTACTED', 'CANCELLED'].map((st) => (
<button
key={st}
onClick={() => setLeadFilterStatus(st)}
className={`rounded-lg px-3 py-1.5 text-xs font-bold transition-all ${
leadFilterStatus === st
? 'bg-purple-600 text-white'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{st === 'ALL' ? 'همه' : st === 'PENDING' ? 'در انتظار' : st === 'CONTACTED' ? 'تماس گرفته شده' : 'لغو'}
</button>
))}
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">کاربر متقاضی</th>
<th className="py-3 px-4">شماره تماس</th>
<th className="py-3 px-4">محصول مرتبط</th>
<th className="py-3 px-4">مشاور منتسب</th>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{leads.length === 0 ? (
<tr>
<td colSpan={7} className="py-8 text-center text-gray-400">
هیچ درخواست تماسی یافت نشد.
</td>
</tr>
) : (
leads.map((l) => (
<tr key={l.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">
{l.firstName} {l.lastName}
</td>
<td className="py-3.5 px-4 font-mono font-medium text-purple-700 dir-ltr text-right">
<a href={`tel:${l.phone}`} className="hover:underline">
{l.phone}
</a>
</td>
<td className="py-3.5 px-4 text-xs text-gray-600">
{l.product ? l.product.nameFa : <span className="text-gray-400">مشاوره عمومی</span>}
</td>
<td className="py-3.5 px-4 text-xs font-medium text-gray-700">
{l.advisor ? `${l.advisor.name} (${l.advisor.phone})` : <span className="text-gray-400">پیش‌فرض</span>}
</td>
<td className="py-3.5 px-4 text-xs text-gray-400">
{new Date(l.createdAt).toLocaleDateString('fa-IR')} - {new Date(l.createdAt).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-bold ${
l.status === 'CONTACTED'
? 'bg-emerald-50 text-emerald-700'
: l.status === 'CANCELLED'
? 'bg-gray-100 text-gray-600'
: 'bg-amber-50 text-amber-700'
}`}>
{l.status === 'CONTACTED' ? 'تماس گرفته شد' : l.status === 'CANCELLED' ? 'لغو شده' : 'در انتظار تماس'}
</span>
</td>
<td className="py-3.5 px-4">
<div className="flex items-center gap-2">
{l.status !== 'CONTACTED' && (
<button
onClick={() => handleUpdateLeadStatus(l.id, 'CONTACTED')}
title="ثبت به عنوان تماس گرفته شده"
className="rounded p-1 text-emerald-600 hover:bg-emerald-50"
>
<CheckCircle2 className="h-4 w-4" />
</button>
)}
{l.status !== 'CANCELLED' && (
<button
onClick={() => handleUpdateLeadStatus(l.id, 'CANCELLED')}
title="لغو درخواست"
className="rounded p-1 text-gray-400 hover:bg-gray-100"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Tab: Advisors */}
{activeTab === 'advisors' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">نام مشاور</th>
<th className="py-3 px-4">شماره همراه</th>
<th className="py-3 px-4">عنوان / تخصص</th>
<th className="py-3 px-4">محصولات منتسب</th>
<th className="py-3 px-4">تعداد لیدها</th>
<th className="py-3 px-4">نقش</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{advisors.map((adv) => (
<tr key={adv.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">{adv.name}</td>
<td className="py-3.5 px-4 font-mono font-medium text-gray-700">{adv.phone}</td>
<td className="py-3.5 px-4 text-xs text-gray-500">{adv.title || '-'}</td>
<td className="py-3.5 px-4 text-xs font-bold text-purple-600">{adv.productsCount} محصول</td>
<td className="py-3.5 px-4 text-xs font-bold text-gray-700">{adv.leadsCount} درخواست</td>
<td className="py-3.5 px-4">
{adv.isDefault ? (
<span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2.5 py-0.5 text-xs font-bold text-amber-700">
<Star className="h-3 w-3 fill-amber-500 text-amber-500" />
پیش‌فرض سیستم
</span>
) : (
<button
onClick={() => handleSetDefaultAdvisor(adv.id)}
className="text-xs text-gray-400 hover:text-purple-600 hover:underline"
>
تنظیم به عنوان پیش‌فرض
</button>
)}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
adv.isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
}`}>
{adv.isActive ? 'فعال' : 'غیرفعال'}
</span>
</td>
<td className="py-3.5 px-4">
<div className="flex items-center gap-2">
<button
onClick={() => {
setEditingAdvisor(adv);
setAdvisorForm({
name: adv.name,
phone: adv.phone,
title: adv.title || '',
isDefault: adv.isDefault,
isActive: adv.isActive,
});
setIsAdvisorModalOpen(true);
}}
className="rounded p-1 text-gray-500 hover:bg-gray-100"
>
<Edit2 className="h-4 w-4" />
</button>
<button
onClick={() => handleDeleteAdvisor(adv.id)}
className="rounded p-1 text-red-500 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Modal: Advisor Create/Edit */}
<Modal
isOpen={isAdvisorModalOpen}
onClose={() => setIsAdvisorModalOpen(false)}
title={editingAdvisor ? 'ویرایش مشاور' : 'افزودن مشاور جدید'}
>
<form onSubmit={handleSaveAdvisor} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام و نام خانوادگی مشاور</label>
<input
type="text"
value={advisorForm.name}
onChange={(e) => setAdvisorForm({ ...advisorForm, name: e.target.value })}
placeholder="مثال: دکتر مهدی صابری"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">شماره تلفن همراه</label>
<input
type="text"
dir="ltr"
value={advisorForm.phone}
onChange={(e) => setAdvisorForm({ ...advisorForm, phone: e.target.value })}
placeholder="09121234567"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">عنوان تخصصی یا سمت</label>
<input
type="text"
value={advisorForm.title}
onChange={(e) => setAdvisorForm({ ...advisorForm, title: e.target.value })}
placeholder="مثال: کارشناس تغذیه سگ و گربه"
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
/>
</div>
<div className="flex items-center gap-6 pt-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={advisorForm.isDefault}
onChange={(e) => setAdvisorForm({ ...advisorForm, isDefault: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs font-bold text-gray-700">مشاور پیش‌فرض سیستم</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={advisorForm.isActive}
onChange={(e) => setAdvisorForm({ ...advisorForm, isActive: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs font-bold text-gray-700">مشاور فعال</span>
</label>
</div>
<div className="flex justify-end gap-2 pt-4 border-t border-gray-100">
<Button variant="outline" type="button" onClick={() => setIsAdvisorModalOpen(false)}>
انصراف
</Button>
<Button type="submit">
ذخیره
</Button>
</div>
</form>
</Modal>
</div>
);
}
@@ -0,0 +1,725 @@
import React, { useState, useEffect } from 'react';
import {
Bell,
Mail,
MessageSquare,
Server,
Send,
ListFilter,
RefreshCw,
CheckCircle2,
AlertCircle,
Clock,
ShieldCheck,
Plus,
Trash2,
ExternalLink,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
interface EmailConfig {
enabled: boolean;
host: string;
port: number;
secure: boolean;
user: string;
password?: string;
fromName: string;
fromEmail: string;
}
interface QueueItem {
id: string;
channel: 'SMS' | 'EMAIL';
recipient: string;
event: string;
subject?: string;
content: string;
status: 'QUEUED' | 'PROCESSING' | 'SENT' | 'FAILED';
attempts: number;
maxAttempts: number;
lastError?: string;
sentAt?: string;
createdAt: string;
}
interface NotificationTemplate {
id: string;
channel: 'SMS' | 'EMAIL';
event: string;
name: string;
subject?: string;
body: string;
recipientType: string;
isActive: boolean;
variables: string[];
}
export default function NotificationsSettingsPage() {
const [activeTab, setActiveTab] = useState<'overview' | 'email' | 'templates' | 'manual' | 'queue'>('overview');
const [isLoading, setIsLoading] = useState(true);
// Email Config State
const [emailConfig, setEmailConfig] = useState<EmailConfig>({
enabled: true,
host: 'mail.canina.ir',
port: 587,
secure: false,
user: '',
password: '',
fromName: 'کنینا ایران',
fromEmail: 'info@canina.ir',
});
const [isSavingEmail, setIsSavingEmail] = useState(false);
const [isTestingSmtp, setIsTestingSmtp] = useState(false);
const [smtpStatus, setSmtpStatus] = useState<{ checked: boolean; success: boolean; message: string } | null>(null);
// Queue state
const [queueItems, setQueueItems] = useState<QueueItem[]>([]);
const [queueStats, setQueueStats] = useState({ total: 0, queued: 0, sent: 0, failed: 0, successRate: 100 });
const [isLoadingQueue, setIsLoadingQueue] = useState(false);
// Templates state
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
const [eventsList, setEventsList] = useState<{ event: string; name: string; variables: string[] }[]>([]);
// Manual Send State
const [manualForm, setManualForm] = useState({
channel: 'SMS' as 'SMS' | 'EMAIL',
targetType: 'single' as 'single' | 'all_users' | 'custom_list',
recipient: '',
subject: '',
content: '',
});
const [isSendingManual, setIsSendingManual] = useState(false);
// Load Initial Config
const loadConfig = async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/notifications/config');
if (res.data?.success) {
setEmailConfig(res.data.data.email);
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت تنظیمات اطلاع‌رسانی');
} finally {
setIsLoading(false);
}
};
const loadQueue = async () => {
try {
setIsLoadingQueue(true);
const res = await api.get('/admin/notifications/queue?limit=50');
if (res.data?.success) {
setQueueItems(res.data.data.items);
if (res.data.data.stats) setQueueStats(res.data.data.stats);
}
} catch (err) {
console.error(err);
} finally {
setIsLoadingQueue(false);
}
};
const loadTemplates = async () => {
try {
const res = await api.get('/admin/notifications/templates');
if (res.data?.success) {
setTemplates(res.data.data.templates);
setEventsList(res.data.data.events || []);
}
} catch (err) {
console.error(err);
}
};
useEffect(() => {
loadConfig();
loadQueue();
loadTemplates();
}, []);
const handleSaveEmail = async (e: React.FormEvent) => {
e.preventDefault();
try {
setIsSavingEmail(true);
const res = await api.put('/admin/notifications/email-config', emailConfig);
if (res.data?.success) {
toast.success(res.data.message || 'تنظیمات سرور ایمیل ذخیره شد.');
}
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ذخیره تنظیمات ایمیل');
} finally {
setIsSavingEmail(false);
}
};
const handleTestSmtp = async () => {
try {
setIsTestingSmtp(true);
setSmtpStatus(null);
const res = await api.post('/admin/notifications/test-smtp', emailConfig);
setSmtpStatus({
checked: true,
success: res.data?.success,
message: res.data?.message,
});
if (res.data?.success) {
toast.success('اتصال به سرور SMTP با موفقیت برقرار شد.');
} else {
toast.error(res.data?.message || 'خطا در اتصال به سرور SMTP');
}
} catch (err: any) {
const msg = err?.response?.data?.message || 'خطا در تست اتصال سرور';
setSmtpStatus({ checked: true, success: false, message: msg });
toast.error(msg);
} finally {
setIsTestingSmtp(false);
}
};
const handleManualSend = async (e: React.FormEvent) => {
e.preventDefault();
if (!manualForm.content.trim()) {
toast.error('متن پیام الزامی است.');
return;
}
try {
setIsSendingManual(true);
const res = await api.post('/admin/notifications/manual-send', manualForm);
if (res.data?.success) {
toast.success(res.data.message || 'پیام با موفقیت در صف ارسال قرار گرفت.');
setManualForm({ ...manualForm, recipient: '', subject: '', content: '' });
loadQueue();
}
} catch (err: any) {
toast.error(err?.response?.data?.message || 'خطا در ثبت پیام در صف');
} finally {
setIsSendingManual(false);
}
};
const handleRetryQueue = async (id: string) => {
try {
const res = await api.post(`/admin/notifications/queue/${id}/retry`);
if (res.data?.success) {
toast.success('پیام مجدداً در صف قرار گرفت.');
loadQueue();
}
} catch (err: any) {
toast.error('خطا در ارسال مجدد');
}
};
if (isLoading) {
return (
<div className="flex h-96 items-center justify-center">
<Spinner size="lg" />
</div>
);
}
return (
<div className="space-y-6 pb-12 font-vazir text-gray-800">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
<Bell className="h-7 w-7 text-purple-600" />
مرکز مدیریت اطلاع‌رسانی و پیام‌ها
</h1>
<p className="mt-1 text-sm text-gray-500">
پیکربندی یکپارچه ایمیل (SMTP)، سامانه پیامک، صف ارسال پایدار و رویدادهای خودکار
</p>
</div>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
<button
onClick={() => setActiveTab('overview')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'overview'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Server className="h-4 w-4" />
داشبورد و وضعیت
</button>
<button
onClick={() => setActiveTab('email')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'email'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Mail className="h-4 w-4" />
تنظیمات ایمیل (SMTP)
</button>
<button
onClick={() => setActiveTab('templates')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'templates'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<ListFilter className="h-4 w-4" />
قالب‌های رویدادها
</button>
<button
onClick={() => setActiveTab('manual')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'manual'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Send className="h-4 w-4" />
ارسال دستی هدفمند
</button>
<button
onClick={() => setActiveTab('queue')}
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
activeTab === 'queue'
? 'border-purple-600 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Clock className="h-4 w-4" />
صف ارسال و لاگ‌ها
{queueStats.failed > 0 && (
<span className="rounded-full bg-red-100 px-2 py-0.5 text-xs text-red-600 font-bold">
{queueStats.failed} خطا
</span>
)}
</button>
</div>
{/* Tab: Overview */}
{activeTab === 'overview' && (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-gray-400">مجموع پیام‌های صف</span>
<p className="mt-2 text-3xl font-black text-gray-900">{queueStats.total}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-emerald-500">ارسال موفق</span>
<p className="mt-2 text-3xl font-black text-emerald-600">{queueStats.sent}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-amber-500">در حال پردازش / صف</span>
<p className="mt-2 text-3xl font-black text-amber-600">{queueStats.queued}</p>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
<span className="text-xs font-bold text-red-500">ناموفق با تلاش مجدد</span>
<p className="mt-2 text-3xl font-black text-red-600">{queueStats.failed}</p>
</div>
</div>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-purple-50 p-3 text-purple-600">
<Mail className="h-6 w-6" />
</div>
<div>
<h3 className="font-bold text-gray-900">سرویس ایمیل سازمانی</h3>
<p className="text-xs text-gray-400">پروتکل SMTP / TLS اختصاصی</p>
</div>
</div>
<span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-bold ${
emailConfig.enabled ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
}`}>
{emailConfig.enabled ? 'فعال' : 'غیرفعال'}
</span>
</div>
<div className="mt-4 space-y-2 text-sm text-gray-600">
<div className="flex justify-between">
<span>سرور میزبان:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.host || '-'}</span>
</div>
<div className="flex justify-between">
<span>پورت اتصال:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.port}</span>
</div>
<div className="flex justify-between">
<span>فرستنده پیش‌فرض:</span>
<span className="font-mono text-gray-900 font-medium">{emailConfig.fromEmail}</span>
</div>
</div>
</div>
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="rounded-xl bg-violet-50 p-3 text-violet-600">
<MessageSquare className="h-6 w-6" />
</div>
<div>
<h3 className="font-bold text-gray-900">درگاه پیامک (MeliPayamak)</h3>
<p className="text-xs text-gray-400">ارسال خدماتی با الگوهای تایید شده</p>
</div>
</div>
<span className="inline-flex rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-bold text-emerald-700">
متصل
</span>
</div>
<div className="mt-4 space-y-2 text-sm text-gray-600">
<div className="flex justify-between">
<span>وضعیت اتصال:</span>
<span className="text-emerald-600 font-bold">برقرار</span>
</div>
<div className="flex justify-between">
<span>قالب‌های پیامک:</span>
<a href="/settings/sms" className="flex items-center gap-1 text-purple-600 hover:underline">
مشاهده تنظیمات پیشرفته ملی‌پیامک
<ExternalLink className="h-3 w-3" />
</a>
</div>
</div>
</div>
</div>
</div>
)}
{/* Tab: Email SMTP */}
{activeTab === 'email' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<form onSubmit={handleSaveEmail} className="space-y-6 max-w-3xl">
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
<div>
<h3 className="text-lg font-bold text-gray-900">پیکربندی سرور ارسال ایمیل (SMTP)</h3>
<p className="text-xs text-gray-500">مشخصات سرور میل اختصاصی خود را وارد نمایید</p>
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={emailConfig.enabled}
onChange={(e) => setEmailConfig({ ...emailConfig, enabled: e.target.checked })}
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-bold text-gray-700">فعال‌سازی ارسال ایمیل</span>
</label>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">هاست سرور SMTP</label>
<input
type="text"
dir="ltr"
value={emailConfig.host}
onChange={(e) => setEmailConfig({ ...emailConfig, host: e.target.value })}
placeholder="mail.canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">پورت اتصال</label>
<input
type="number"
dir="ltr"
value={emailConfig.port}
onChange={(e) => setEmailConfig({ ...emailConfig, port: Number(e.target.value) })}
placeholder="587 یا 465"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام کاربری (ایمیل ورود)</label>
<input
type="text"
dir="ltr"
value={emailConfig.user}
onChange={(e) => setEmailConfig({ ...emailConfig, user: e.target.value })}
placeholder="info@canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">رمز عبور ایمیل</label>
<input
type="password"
dir="ltr"
value={emailConfig.password}
onChange={(e) => setEmailConfig({ ...emailConfig, password: e.target.value })}
placeholder="••••••••"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام فرستنده (Sender Name)</label>
<input
type="text"
value={emailConfig.fromName}
onChange={(e) => setEmailConfig({ ...emailConfig, fromName: e.target.value })}
placeholder="کنینا ایران"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">آدرس ایمیل فرستنده (From Address)</label>
<input
type="email"
dir="ltr"
value={emailConfig.fromEmail}
onChange={(e) => setEmailConfig({ ...emailConfig, fromEmail: e.target.value })}
placeholder="info@canina.ir"
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
</div>
{/* Test result status */}
{smtpStatus && (
<div className={`flex items-center gap-3 rounded-xl p-4 text-sm ${
smtpStatus.success ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'
}`}>
{smtpStatus.success ? <CheckCircle2 className="h-5 w-5 shrink-0" /> : <AlertCircle className="h-5 w-5 shrink-0" />}
<span>{smtpStatus.message}</span>
</div>
)}
<div className="flex items-center gap-3 pt-4 border-t border-gray-100">
<Button type="submit" disabled={isSavingEmail}>
{isSavingEmail ? <Spinner size="sm" /> : 'ذخیره تنظیمات'}
</Button>
<Button
type="button"
variant="outline"
onClick={handleTestSmtp}
disabled={isTestingSmtp}
>
{isTestingSmtp ? <Spinner size="sm" /> : 'تست اتصال به سرور (SMTP Test)'}
</Button>
</div>
</form>
</div>
)}
{/* Tab: Templates */}
{activeTab === 'templates' && (
<div className="space-y-6">
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<h3 className="text-lg font-bold text-gray-900 mb-4">قالب‌های خودکار سیستم بر اساس رویداد</h3>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">نام رویداد</th>
<th className="py-3 px-4">کانال</th>
<th className="py-3 px-4">عنوان / موضوع</th>
<th className="py-3 px-4">گیرنده</th>
<th className="py-3 px-4">متغیرها</th>
<th className="py-3 px-4">وضعیت</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{eventsList.map((ev) => (
<tr key={ev.event} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-bold text-gray-900">{ev.name}</td>
<td className="py-3.5 px-4">
<span className="rounded-md bg-purple-50 px-2 py-1 text-xs font-bold text-purple-700">
SMS & EMAIL
</span>
</td>
<td className="py-3.5 px-4 text-gray-600 font-mono text-xs">{ev.event}</td>
<td className="py-3.5 px-4 text-gray-600">کاربر / مشتری</td>
<td className="py-3.5 px-4 text-xs font-mono text-gray-400">
{ev.variables.join(', ')}
</td>
<td className="py-3.5 px-4">
<span className="inline-flex items-center gap-1 text-xs text-emerald-600 font-bold">
<CheckCircle2 className="h-3.5 w-3.5" />
فعال
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Tab: Manual Send */}
{activeTab === 'manual' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm max-w-2xl">
<h3 className="text-lg font-bold text-gray-900 mb-2">ارسال دستی و هدفمند پیام</h3>
<p className="text-xs text-gray-500 mb-6">پیامک یا ایمیل دلخواه خود را به یک کاربر یا گروه‌های مشخص ارسال کنید</p>
<form onSubmit={handleManualSend} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">کانال ارسال</label>
<div className="flex gap-4">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="channel"
checked={manualForm.channel === 'SMS'}
onChange={() => setManualForm({ ...manualForm, channel: 'SMS' })}
className="text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-medium">پیامک (SMS)</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="channel"
checked={manualForm.channel === 'EMAIL'}
onChange={() => setManualForm({ ...manualForm, channel: 'EMAIL' })}
className="text-purple-600 focus:ring-purple-500"
/>
<span className="text-sm font-medium">ایمیل (Email)</span>
</label>
</div>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">
{manualForm.channel === 'SMS' ? 'شماره موبایل گیرنده' : 'آدرس ایمیل گیرنده'}
</label>
<input
type="text"
dir="ltr"
value={manualForm.recipient}
onChange={(e) => setManualForm({ ...manualForm, recipient: e.target.value })}
placeholder={manualForm.channel === 'SMS' ? '09121234567' : 'user@example.com'}
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
required
/>
</div>
{manualForm.channel === 'EMAIL' && (
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">موضوع ایمیل</label>
<input
type="text"
value={manualForm.subject}
onChange={(e) => setManualForm({ ...manualForm, subject: e.target.value })}
placeholder="موضوع اطلاعیه..."
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
)}
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">متن پیام</label>
<textarea
rows={4}
value={manualForm.content}
onChange={(e) => setManualForm({ ...manualForm, content: e.target.value })}
placeholder="متن پیام خود را اینجا بنویسید..."
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
required
/>
</div>
<Button type="submit" disabled={isSendingManual}>
{isSendingManual ? <Spinner size="sm" /> : 'ثبت در صف ارسال'}
</Button>
</form>
</div>
)}
{/* Tab: Queue & Logs */}
{activeTab === 'queue' && (
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-bold text-gray-900">صف پردازش پایدار نوتیفیکیشن‌ها</h3>
<Button variant="outline" size="sm" onClick={loadQueue} disabled={isLoadingQueue}>
<RefreshCw className={`h-4 w-4 ${isLoadingQueue ? 'animate-spin' : ''}`} />
به‌روزرسانی صف
</Button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
<tr>
<th className="py-3 px-4">گیرنده</th>
<th className="py-3 px-4">کانال</th>
<th className="py-3 px-4">رویداد</th>
<th className="py-3 px-4">تلاش</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{queueItems.length === 0 ? (
<tr>
<td colSpan={7} className="py-8 text-center text-gray-400">
هیچ پیامی در صف وجود ندارد.
</td>
</tr>
) : (
queueItems.map((item) => (
<tr key={item.id} className="hover:bg-gray-50/50">
<td className="py-3.5 px-4 font-mono font-medium text-gray-900">{item.recipient}</td>
<td className="py-3.5 px-4">
<span className={`rounded-md px-2 py-0.5 text-xs font-bold ${
item.channel === 'EMAIL' ? 'bg-blue-50 text-blue-700' : 'bg-violet-50 text-violet-700'
}`}>
{item.channel}
</span>
</td>
<td className="py-3.5 px-4 text-xs font-mono text-gray-600">{item.event}</td>
<td className="py-3.5 px-4 font-mono text-xs">{item.attempts} / {item.maxAttempts}</td>
<td className="py-3.5 px-4">
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
item.status === 'SENT'
? 'bg-emerald-50 text-emerald-700'
: item.status === 'FAILED'
? 'bg-red-50 text-red-700'
: 'bg-amber-50 text-amber-700'
}`}>
{item.status === 'SENT' ? 'ارسال شده' : item.status === 'FAILED' ? 'ناموفق' : 'در صف'}
</span>
</td>
<td className="py-3.5 px-4 text-xs text-gray-400">
{new Date(item.createdAt).toLocaleTimeString('fa-IR')}
</td>
<td className="py-3.5 px-4">
{item.status === 'FAILED' && (
<button
onClick={() => handleRetryQueue(item.id)}
className="text-xs text-purple-600 hover:underline font-bold"
>
تلاش مجدد
</button>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}
+12 -8
View File
@@ -1,12 +1,14 @@
import {
Building2,
ChevronLeft,
CreditCard,
DollarSign,
Globe,
MessageSquare,
Palette,
Save,
Bell,
Building2,
ChevronLeft,
CreditCard,
DollarSign,
Globe,
MessageSquare,
Palette,
PhoneCall,
Save,
Settings as SettingsIcon,
Share2,
ShieldCheck,
@@ -114,6 +116,8 @@ export default function Settings() {
};
const SETTING_MODULES = [
{ title: 'مرکز اطلاع‌رسانی و ایمیل', desc: 'پیکربندی سرور SMTP، صف ارسال پیامک و ایمیل و قالب‌های خودکار', path: '/settings/notifications', icon: Bell, color: 'from-fuchsia-600 to-purple-800', badge: 'جدید' },
{ title: 'مشاوران تخصصی و لیدها', desc: 'مدیریت مشاوران کاتالوگ و پیگیری درخواست‌های تماس کاربران', path: '/advisors', icon: PhoneCall, color: 'from-blue-600 to-indigo-800', badge: 'جدید' },
{ title: 'پشتیبان هوشمند سایت', desc: 'فعال‌سازی، ارائه‌دهنده و مدل، نام دکمه و آیکون دستیار', path: '/settings/smart-chat', icon: MessageSquare, color: 'from-purple-600 to-purple-800', badge: 'هوشمند' },
{
title: 'روش‌های پرداخت و زیبال',
@@ -39,6 +39,8 @@ const ZibalPortalPage = lazyWithRetry(() => import('../pages/ZibalPortalPage'));
const ShippingSettingsPage = lazyWithRetry(() => import('../pages/ShippingSettingsPage'));
const SystemSettingsPage = lazyWithRetry(() => import('../pages/SystemSettingsPage'));
const SmsSettingsPage = lazyWithRetry(() => import('../pages/SmsSettingsPage'));
const NotificationsSettingsPage = lazyWithRetry(() => import('../pages/NotificationsSettingsPage'));
const AdvisorsManagementPage = lazyWithRetry(() => import('../pages/AdvisorsManagementPage'));
const SslSettingsPage = lazyWithRetry(() => import('../pages/SslSettingsPage'));
const ApiKeysPage = lazyWithRetry(() => import('../pages/ApiKeysPage'));
const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
@@ -88,6 +90,9 @@ export const router = createBrowserRouter([
{ path: 'settings/ssl', element: <SslSettingsPage /> },
{ path: 'settings/api-keys', element: <ApiKeysPage /> },
{ path: 'settings/sms', element: <SmsSettingsPage /> },
{ path: 'settings/notifications', element: <NotificationsSettingsPage /> },
{ path: 'advisors/*', element: <AdvisorsManagementPage /> },
{ path: 'leads/*', element: <AdvisorsManagementPage /> },
{ path: 'settings/seo', element: <SeoSettingsPage /> },
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
{ path: 'settings/system', element: <SystemSettingsPage /> },
+2
View File
@@ -4,6 +4,7 @@ import NextTopLoader from 'nextjs-toploader';
import ClientLayout from './ClientLayout';
import AnalyticsDeferred from '../components/AnalyticsDeferred';
import SupportChat from '../components/SupportChat';
import ContactAdvisorButton from '../components/ContactAdvisorButton';
import { getSeoConfig } from '../lib/seo';
import { vazirmatn, lalezar } from '../lib/fonts';
import { generateOrganizationSchema } from '../lib/schema';
@@ -201,6 +202,7 @@ export default async function RootLayout({
{children}
</ClientLayout>
<SupportChat />
<ContactAdvisorButton />
{/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */}
<AnalyticsDeferred
@@ -0,0 +1,185 @@
'use client';
import { useState } from 'react';
import { PhoneCall, X, CheckCircle2, AlertCircle } from 'lucide-react';
interface ContactAdvisorButtonProps {
productId?: string;
productName?: string;
}
export default function ContactAdvisorButton({ productId, productName }: ContactAdvisorButtonProps) {
const [isOpen, setIsOpen] = useState(false);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [phone, setPhone] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [status, setStatus] = useState<{ success: boolean; message: string } | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setStatus(null);
const cleanPhone = phone.trim().replace(/\s+/g, '');
if (!/^09\d{9}$/.test(cleanPhone)) {
setStatus({ success: false, message: 'لطفاً شماره موبایل ۱۱ رقمی معتبر وارد کنید (مثال: ۰۹۱۲۳۴۵۶۷۸۹)' });
return;
}
try {
setIsSubmitting(true);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/public/lead`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: firstName.trim(),
lastName: lastName.trim(),
phone: cleanPhone,
productId: productId || undefined,
}),
});
const data = await res.json();
if (res.ok && (data.ok || data.success)) {
setStatus({
success: true,
message: data.message || 'درخواست شما ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.',
});
setFirstName('');
setLastName('');
setPhone('');
} else {
setStatus({
success: false,
message: data.message || 'خطا در ثبت درخواست. لطفاً دوباره تلاش کنید.',
});
}
} catch {
setStatus({
success: false,
message: 'خطا در برقراری ارتباط با سرور. لطفاً دقایقی دیگر تلاش فرمایید.',
});
} finally {
setIsSubmitting(false);
}
};
return (
<>
{/* Floating Action Button */}
<button
type="button"
onClick={() => setIsOpen(true)}
className="fixed bottom-6 left-6 z-40 flex items-center gap-2.5 rounded-full bg-emerald-600 px-5 py-3.5 text-white font-bold shadow-lg shadow-emerald-600/30 transition-all hover:bg-emerald-700 hover:scale-105 active:scale-95"
>
<PhoneCall className="h-5 w-5 animate-pulse" />
<span>مشاوره و تماس رایگان</span>
</button>
{/* Modal */}
{isOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
<div className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-2xl font-vazir text-right text-gray-800">
<button
onClick={() => {
setIsOpen(false);
setStatus(null);
}}
className="absolute top-4 left-4 rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-700"
>
<X className="h-5 w-5" />
</button>
<div className="flex items-center gap-3 border-b border-gray-100 pb-4">
<div className="rounded-xl bg-emerald-50 p-2.5 text-emerald-600">
<PhoneCall className="h-6 w-6" />
</div>
<div>
<h3 className="font-bold text-gray-900 text-lg">درخواست مشاوره تخصصی کنینا</h3>
<p className="text-xs text-gray-500">
{productName ? `برای محصول: ${productName}` : 'مشاوره اختصاصی مکمل‌ها با دامپزشک'}
</p>
</div>
</div>
{status && (
<div
className={`mt-4 flex items-start gap-3 rounded-xl p-3.5 text-sm ${
status.success ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'
}`}
>
{status.success ? (
<CheckCircle2 className="h-5 w-5 shrink-0 text-emerald-600 mt-0.5" />
) : (
<AlertCircle className="h-5 w-5 shrink-0 text-red-600 mt-0.5" />
)}
<span>{status.message}</span>
</div>
)}
{!status?.success ? (
<form onSubmit={handleSubmit} className="mt-4 space-y-3.5">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام</label>
<input
type="text"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
placeholder="مثال: علی"
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm focus:border-emerald-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام خانوادگی</label>
<input
type="text"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
placeholder="مثال: محمدی"
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm focus:border-emerald-600 focus:outline-none"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">شماره تلفن همراه</label>
<input
type="tel"
dir="ltr"
value={phone}
onChange={(e) => setPhone(e.target.value)}
placeholder="09121234567"
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm font-mono text-right focus:border-emerald-600 focus:outline-none"
required
/>
<p className="mt-1 text-[11px] text-gray-400">مشاوران ما در کمتر از ۵ دقیقه با شما تماس خواهند گرفت.</p>
</div>
<div className="pt-2">
<button
type="submit"
disabled={isSubmitting}
className="w-full rounded-xl bg-emerald-600 py-3 text-sm font-bold text-white shadow-md transition-all hover:bg-emerald-700 disabled:opacity-50"
>
{isSubmitting ? 'در حال ثبت...' : 'ثبت درخواست تماس'}
</button>
</div>
</form>
) : (
<div className="pt-4 text-center">
<button
type="button"
onClick={() => setIsOpen(false)}
className="rounded-xl bg-gray-100 px-6 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-200"
>
بستن پنجره
</button>
</div>
)}
</div>
</div>
)}
</>
);
}