From 1c4f7e9d1002c289bd0801958966d02c912a6e50 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 7 Nov 2026 09:24:52 +0000 Subject: [PATCH] fix: add missing schema tables migration, expand email config DTO, and connect live MeliPayamak SendSMS endpoint --- .../migration.sql | 72 +++++++++++++++ backend/src/common/services/sms.service.ts | 89 +++++++++++++++++-- .../notifications-queue.service.ts | 10 ++- .../src/notifications/notifications.dto.ts | 35 ++++++-- 4 files changed, 192 insertions(+), 14 deletions(-) create mode 100644 backend/prisma/migrations/20261107120000_add_approvals_audit_and_department_tasks/migration.sql diff --git a/backend/prisma/migrations/20261107120000_add_approvals_audit_and_department_tasks/migration.sql b/backend/prisma/migrations/20261107120000_add_approvals_audit_and_department_tasks/migration.sql new file mode 100644 index 00000000..76a5c273 --- /dev/null +++ b/backend/prisma/migrations/20261107120000_add_approvals_audit_and_department_tasks/migration.sql @@ -0,0 +1,72 @@ +-- CreateTable approval_requests +CREATE TABLE IF NOT EXISTS public.approval_requests ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "department" VARCHAR(50) NOT NULL, + "category" VARCHAR(50) NOT NULL, + "title" VARCHAR(255) NOT NULL, + "payload" JSONB NOT NULL, + "test_context" JSONB, + "status" VARCHAR(30) NOT NULL DEFAULT 'PENDING', + "ceo_notes" TEXT, + "executed_at" TIMESTAMPTZ(6), + "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "approval_requests_pkey" PRIMARY KEY ("id") +); + +-- CreateTable audit_logs +CREATE TABLE IF NOT EXISTS public.audit_logs ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "entity" VARCHAR(50) NOT NULL, + "entity_id" VARCHAR(100), + "action" VARCHAR(50) NOT NULL, + "department" VARCHAR(50), + "actor" VARCHAR(100) NOT NULL DEFAULT 'SYSTEM', + "summary" VARCHAR(255) NOT NULL, + "old_values" JSONB, + "new_values" JSONB, + "metadata" JSONB, + "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable department_tasks +CREATE TABLE IF NOT EXISTS public.department_tasks ( + "id" UUID NOT NULL DEFAULT gen_random_uuid(), + "code" VARCHAR(50) NOT NULL, + "department" VARCHAR(50) NOT NULL, + "title" VARCHAR(255) NOT NULL, + "description" TEXT, + "status" VARCHAR(30) NOT NULL DEFAULT 'BACKLOG', + "priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM', + "assignee" VARCHAR(100), + "acceptance_criteria" JSONB, + "execution_logs" JSONB, + "deliverable_url" VARCHAR(255), + "approval_id" UUID, + "started_at" TIMESTAMPTZ(6), + "completed_at" TIMESTAMPTZ(6), + "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "department_tasks_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "department_tasks_code_key" ON public.department_tasks("code"); +CREATE INDEX IF NOT EXISTS "approval_requests_department_idx" ON public.approval_requests("department"); +CREATE INDEX IF NOT EXISTS "approval_requests_category_idx" ON public.approval_requests("category"); +CREATE INDEX IF NOT EXISTS "approval_requests_status_idx" ON public.approval_requests("status"); +CREATE INDEX IF NOT EXISTS "approval_requests_created_at_idx" ON public.approval_requests("created_at"); + +CREATE INDEX IF NOT EXISTS "audit_logs_entity_idx" ON public.audit_logs("entity"); +CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON public.audit_logs("action"); +CREATE INDEX IF NOT EXISTS "audit_logs_department_idx" ON public.audit_logs("department"); +CREATE INDEX IF NOT EXISTS "audit_logs_created_at_idx" ON public.audit_logs("created_at"); + +CREATE INDEX IF NOT EXISTS "department_tasks_department_idx" ON public.department_tasks("department"); +CREATE INDEX IF NOT EXISTS "department_tasks_status_idx" ON public.department_tasks("status"); +CREATE INDEX IF NOT EXISTS "department_tasks_priority_idx" ON public.department_tasks("priority"); +CREATE INDEX IF NOT EXISTS "department_tasks_created_at_idx" ON public.department_tasks("created_at"); diff --git a/backend/src/common/services/sms.service.ts b/backend/src/common/services/sms.service.ts index cae35718..ff6c8525 100644 --- a/backend/src/common/services/sms.service.ts +++ b/backend/src/common/services/sms.service.ts @@ -1377,13 +1377,88 @@ export class SmsService { }); return false; } - this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`); - await this.recordLog({ - receptor: phone, - type: "GENERIC_TEXT", - messageText: message, - status: "SUCCESS", + // 2. Dispatch generic direct SMS via MeliPayamak SendSMS endpoint if fromNumber configured, else fall back to local log + return new Promise((resolve) => { + const payload = JSON.stringify({ + username: config.username, + password: config.password, + to: phone, + from: config.fromNumber || "50004001100228", + text: message, + isFlash: false, + }); + + const req = https.request( + "https://rest.payamak-panel.com/api/SendSMS/SendSMS", + { + method: "POST", + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(payload), + }, + }, + (res) => { + let data = ""; + res.on("data", (chunk: Buffer | string) => (data += String(chunk))); + res.on("end", () => { + void (async () => { + try { + const json = JSON.parse(data) as { Value?: number | string; RetStatus?: number; StrRetStatus?: string }; + const val = Number(json.Value ?? 0); + if (val > 15 || json.RetStatus === 1) { + this.logger.log(`[SMS Text Sent] To: ${phone}, RecId: ${val}`); + await this.recordLog({ + receptor: phone, + type: "GENERIC_TEXT", + messageText: message, + status: "SUCCESS", + recId: String(val), + }); + resolve(true); + } else { + const errMsg = `خطای ارسال پیامک متنی با کد: ${val} (${json.StrRetStatus || ''})`; + this.logger.error(`[SMS Text Error] To: ${phone}, Code: ${val}`); + await this.recordLog({ + receptor: phone, + type: "GENERIC_TEXT", + messageText: message, + status: "FAILED", + errorMessage: errMsg, + }); + resolve(false); + } + } catch (err: unknown) { + const msg = err instanceof Error ? err.message : String(err); + await this.recordLog({ + receptor: phone, + type: "GENERIC_TEXT", + messageText: message, + status: "FAILED", + errorMessage: `خطای پارس پاسخ ملی پیامک: ${data || msg}`, + }); + resolve(false); + } + })(); + }); + }, + ); + + req.on("error", (err: Error) => { + void (async () => { + this.logger.error(`[SMS Text Network Error] To: ${phone}: ${err.message}`); + await this.recordLog({ + receptor: phone, + type: "GENERIC_TEXT", + messageText: message, + status: "FAILED", + errorMessage: err.message, + }); + resolve(false); + })(); + }); + + req.write(payload); + req.end(); }); - return Promise.resolve(true); } } diff --git a/backend/src/notifications/notifications-queue.service.ts b/backend/src/notifications/notifications-queue.service.ts index f2ac1b26..7afe5404 100644 --- a/backend/src/notifications/notifications-queue.service.ts +++ b/backend/src/notifications/notifications-queue.service.ts @@ -127,14 +127,20 @@ export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy } else if (item.channel === 'SMS') { const payloadObj = (item.payload as Record) || {}; if (payloadObj.patternId && Array.isArray(payloadObj.args)) { - await this.smsService.sendPatternSms({ + const sent = await this.smsService.sendPatternSms({ to: item.recipient, bodyId: Number(payloadObj.patternId), args: payloadObj.args, type: item.event, }); + if (!sent) { + throw new Error(`ارسال پیامک پترن ${payloadObj.patternId} ناموفق بود.`); + } } else { - await this.smsService.sendSms(item.recipient, item.content); + const sent = await this.smsService.sendSms(item.recipient, item.content); + if (!sent) { + throw new Error(`ارسال پیامک متنی به ${item.recipient} ناموفق بود.`); + } } await this.prisma.notificationQueue.update({ diff --git a/backend/src/notifications/notifications.dto.ts b/backend/src/notifications/notifications.dto.ts index d194a7be..02ce48a3 100644 --- a/backend/src/notifications/notifications.dto.ts +++ b/backend/src/notifications/notifications.dto.ts @@ -1,6 +1,10 @@ import { IsString, IsNotEmpty, IsOptional, IsNumber, IsBoolean, IsIn, IsArray } from 'class-validator'; export class UpdateEmailConfigDto { + @IsBoolean() + @IsOptional() + enabled?: boolean; + @IsString() @IsNotEmpty() host!: string; @@ -9,22 +13,35 @@ export class UpdateEmailConfigDto { port!: number; @IsBoolean() - secure!: boolean; + @IsOptional() + secure?: boolean; @IsString() - @IsNotEmpty() - user!: string; + @IsOptional() + user?: string; @IsString() @IsOptional() password?: string; @IsString() - @IsNotEmpty() - from!: string; + @IsOptional() + from?: string; + + @IsString() + @IsOptional() + fromName?: string; + + @IsString() + @IsOptional() + fromEmail?: string; } export class TestSmtpDto { + @IsBoolean() + @IsOptional() + enabled?: boolean; + @IsString() @IsOptional() host?: string; @@ -48,6 +65,14 @@ export class TestSmtpDto { @IsString() @IsOptional() from?: string; + + @IsString() + @IsOptional() + fromName?: string; + + @IsString() + @IsOptional() + fromEmail?: string; } export class SendTestEmailDto {