diff --git a/backend/prisma/migrations/20261106180000_add_advisors_leads_and_notification_queue/migration.sql b/backend/prisma/migrations/20261106180000_add_advisors_leads_and_notification_queue/migration.sql new file mode 100644 index 00000000..c5ab8818 --- /dev/null +++ b/backend/prisma/migrations/20261106180000_add_advisors_leads_and_notification_queue/migration.sql @@ -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; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 3b3d2804..a1529d03 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") +} diff --git a/backend/src/advisors/advisors.controller.ts b/backend/src/advisors/advisors.controller.ts new file mode 100644 index 00000000..8bd4d1de --- /dev/null +++ b/backend/src/advisors/advisors.controller.ts @@ -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) { + 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: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' }; + } +} diff --git a/backend/src/advisors/advisors.module.ts b/backend/src/advisors/advisors.module.ts new file mode 100644 index 00000000..85bcdfb0 --- /dev/null +++ b/backend/src/advisors/advisors.module.ts @@ -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 {} diff --git a/backend/src/advisors/advisors.service.spec.ts b/backend/src/advisors/advisors.service.spec.ts new file mode 100644 index 00000000..eab4283a --- /dev/null +++ b/backend/src/advisors/advisors.service.spec.ts @@ -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); + }); + + 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); + }); +}); diff --git a/backend/src/advisors/advisors.service.ts b/backend/src/advisors/advisors.service.ts new file mode 100644 index 00000000..769ff86a --- /dev/null +++ b/backend/src/advisors/advisors.service.ts @@ -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) { + 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, + }; + } +} diff --git a/backend/src/advisors/public-lead.controller.ts b/backend/src/advisors/public-lead.controller.ts new file mode 100644 index 00000000..f942c399 --- /dev/null +++ b/backend/src/advisors/public-lead.controller.ts @@ -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, + }; + } +} diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 53b5f778..8df4456d 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -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: [ diff --git a/backend/src/notifications/email.service.ts b/backend/src/notifications/email.service.ts new file mode 100644 index 00000000..130ea677 --- /dev/null +++ b/backend/src/notifications/email.service.ts @@ -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 { + try { + const setting = await this.prisma.setting.findFirst({ + where: { category: 'email' }, + }); + const dbConfig = (setting?.value as Record) || {}; + + 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): Promise { + 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): 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): 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}` }); + } + }); + } +} diff --git a/backend/src/notifications/notifications-queue.service.spec.ts b/backend/src/notifications/notifications-queue.service.spec.ts new file mode 100644 index 00000000..bf911c05 --- /dev/null +++ b/backend/src/notifications/notifications-queue.service.spec.ts @@ -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); + }); + + 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' }), + }); + }); +}); diff --git a/backend/src/notifications/notifications-queue.service.ts b/backend/src/notifications/notifications-queue.service.ts new file mode 100644 index 00000000..f2ac1b26 --- /dev/null +++ b/backend/src/notifications/notifications-queue.service.ts @@ -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) || {}; + const res = await this.emailService.sendMail({ + to: item.recipient, + subject: item.subject || 'اطلاعیه کنینا ایران', + text: item.content, + html: payloadObj.html || `
${item.content.replace(/\n/g, '
')}
`, + }); + + 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) || {}; + 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, + }; + } +} diff --git a/backend/src/notifications/notifications.controller.ts b/backend/src/notifications/notifications.controller.ts new file mode 100644 index 00000000..773f21fb --- /dev/null +++ b/backend/src/notifications/notifications.controller.ts @@ -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) { + // 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) { + 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: ` +
+
+

کنینا ایران | تست سرور ایمیل

+

${body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.'}

+
+ زمان ارسال: ${new Date().toLocaleString('fa-IR')} +
+
+ `, + }); + + 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: 'قالب رویداد حذف شد.', + }; + } +} diff --git a/backend/src/notifications/notifications.module.ts b/backend/src/notifications/notifications.module.ts new file mode 100644 index 00000000..5ca2d99c --- /dev/null +++ b/backend/src/notifications/notifications.module.ts @@ -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 {} diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index c6c20151..5f3cce26 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -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' }, diff --git a/frontend/admin-panel/src/pages/AdvisorsManagementPage.tsx b/frontend/admin-panel/src/pages/AdvisorsManagementPage.tsx new file mode 100644 index 00000000..26e6e27c --- /dev/null +++ b/frontend/admin-panel/src/pages/AdvisorsManagementPage.tsx @@ -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([]); + const [isAdvisorModalOpen, setIsAdvisorModalOpen] = useState(false); + const [editingAdvisor, setEditingAdvisor] = useState(null); + const [advisorForm, setAdvisorForm] = useState({ + name: '', + phone: '', + title: '', + isDefault: false, + isActive: true, + }); + + // Leads State + const [leads, setLeads] = useState([]); + const [leadStats, setLeadStats] = useState({ total: 0, pending: 0, contacted: 0, cancelled: 0 }); + const [leadFilterStatus, setLeadFilterStatus] = useState('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 ( +
+ {/* Header */} +
+
+

+ + درخواست‌های تماس و مشاوران کاتالوگ +

+

+ مدیریت لیدهای تماس وب‌سایت، انتساب مشاوران پیش‌فرض و اختصاصی محصولات +

+
+
+ +
+
+ + {/* Tabs */} +
+ + +
+ + {/* Tab: Leads */} + {activeTab === 'leads' && ( +
+
+
+ مجموع درخواست‌ها +

{leadStats.total}

+
+
+ در انتظار تماس +

{leadStats.pending}

+
+
+ تماس گرفته شده +

{leadStats.contacted}

+
+
+ لغو شده / ناموفق +

{leadStats.cancelled}

+
+
+ +
+
+
+ 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" + /> + +
+ +
+ {['ALL', 'PENDING', 'CONTACTED', 'CANCELLED'].map((st) => ( + + ))} +
+
+ +
+ + + + + + + + + + + + + + {leads.length === 0 ? ( + + + + ) : ( + leads.map((l) => ( + + + + + + + + + + )) + )} + +
کاربر متقاضیشماره تماسمحصول مرتبطمشاور منتسبزمان ثبتوضعیتعملیات
+ هیچ درخواست تماسی یافت نشد. +
+ {l.firstName} {l.lastName} + + + {l.phone} + + + {l.product ? l.product.nameFa : مشاوره عمومی} + + {l.advisor ? `${l.advisor.name} (${l.advisor.phone})` : پیش‌فرض} + + {new Date(l.createdAt).toLocaleDateString('fa-IR')} - {new Date(l.createdAt).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })} + + + {l.status === 'CONTACTED' ? 'تماس گرفته شد' : l.status === 'CANCELLED' ? 'لغو شده' : 'در انتظار تماس'} + + +
+ {l.status !== 'CONTACTED' && ( + + )} + {l.status !== 'CANCELLED' && ( + + )} +
+
+
+
+
+ )} + + {/* Tab: Advisors */} + {activeTab === 'advisors' && ( +
+
+ + + + + + + + + + + + + + + {advisors.map((adv) => ( + + + + + + + + + + + ))} + +
نام مشاورشماره همراهعنوان / تخصصمحصولات منتسبتعداد لیدهانقشوضعیتعملیات
{adv.name}{adv.phone}{adv.title || '-'}{adv.productsCount} محصول{adv.leadsCount} درخواست + {adv.isDefault ? ( + + + پیش‌فرض سیستم + + ) : ( + + )} + + + {adv.isActive ? 'فعال' : 'غیرفعال'} + + +
+ + +
+
+
+
+ )} + + {/* Modal: Advisor Create/Edit */} + setIsAdvisorModalOpen(false)} + title={editingAdvisor ? 'ویرایش مشاور' : 'افزودن مشاور جدید'} + > +
+
+ + 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 + /> +
+ +
+ + 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 + /> +
+ +
+ + 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" + /> +
+ +
+ + + +
+ +
+ + +
+
+
+
+ ); +} diff --git a/frontend/admin-panel/src/pages/NotificationsSettingsPage.tsx b/frontend/admin-panel/src/pages/NotificationsSettingsPage.tsx new file mode 100644 index 00000000..f70a625a --- /dev/null +++ b/frontend/admin-panel/src/pages/NotificationsSettingsPage.tsx @@ -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({ + 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([]); + 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([]); + 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 ( +
+ +
+ ); + } + + return ( +
+ {/* Header */} +
+
+

+ + مرکز مدیریت اطلاع‌رسانی و پیام‌ها +

+

+ پیکربندی یکپارچه ایمیل (SMTP)، سامانه پیامک، صف ارسال پایدار و رویدادهای خودکار +

+
+
+ + {/* Tabs */} +
+ + + + + +
+ + {/* Tab: Overview */} + {activeTab === 'overview' && ( +
+
+
+ مجموع پیام‌های صف +

{queueStats.total}

+
+
+ ارسال موفق +

{queueStats.sent}

+
+
+ در حال پردازش / صف +

{queueStats.queued}

+
+
+ ناموفق با تلاش مجدد +

{queueStats.failed}

+
+
+ +
+
+
+
+
+ +
+
+

سرویس ایمیل سازمانی

+

پروتکل SMTP / TLS اختصاصی

+
+
+ + {emailConfig.enabled ? 'فعال' : 'غیرفعال'} + +
+
+
+ سرور میزبان: + {emailConfig.host || '-'} +
+
+ پورت اتصال: + {emailConfig.port} +
+
+ فرستنده پیش‌فرض: + {emailConfig.fromEmail} +
+
+
+ +
+
+
+
+ +
+
+

درگاه پیامک (MeliPayamak)

+

ارسال خدماتی با الگوهای تایید شده

+
+
+ + متصل + +
+
+
+ وضعیت اتصال: + برقرار +
+ +
+
+
+
+ )} + + {/* Tab: Email SMTP */} + {activeTab === 'email' && ( +
+
+
+
+

پیکربندی سرور ارسال ایمیل (SMTP)

+

مشخصات سرور میل اختصاصی خود را وارد نمایید

+
+ +
+ +
+
+ + 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 + /> +
+ +
+ + 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 + /> +
+ +
+ + 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" + /> +
+ +
+ + 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" + /> +
+ +
+ + 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 + /> +
+ +
+ + 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 + /> +
+
+ + {/* Test result status */} + {smtpStatus && ( +
+ {smtpStatus.success ? : } + {smtpStatus.message} +
+ )} + +
+ + +
+
+
+ )} + + {/* Tab: Templates */} + {activeTab === 'templates' && ( +
+
+

قالب‌های خودکار سیستم بر اساس رویداد

+
+ + + + + + + + + + + + + {eventsList.map((ev) => ( + + + + + + + + + ))} + +
نام رویدادکانالعنوان / موضوعگیرندهمتغیرهاوضعیت
{ev.name} + + SMS & EMAIL + + {ev.event}کاربر / مشتری + {ev.variables.join(', ')} + + + + فعال + +
+
+
+
+ )} + + {/* Tab: Manual Send */} + {activeTab === 'manual' && ( +
+

ارسال دستی و هدفمند پیام

+

پیامک یا ایمیل دلخواه خود را به یک کاربر یا گروه‌های مشخص ارسال کنید

+ +
+
+ +
+ + +
+
+ +
+ + 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 + /> +
+ + {manualForm.channel === 'EMAIL' && ( +
+ + 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 + /> +
+ )} + +
+ +