feat: merge develop into main with approval gate, hermes bridge and admin modules
Deploy Canina / deploy (push) Successful in 2m12s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s

This commit is contained in:
devops committed 2026-10-14 03:44:52 +00:00
commit a66733cc32
19 files changed
+2237 -162

No files matched your search

@@ -0,0 +1,106 @@
-- CreateTable
CREATE TABLE "competitor_price_logs" (
"id" UUID NOT NULL,
"product_id" UUID NOT NULL,
"competitor_name" VARCHAR(100) NOT NULL,
"competitor_price" DECIMAL(15,2) NOT NULL,
"shop_url" TEXT NOT NULL,
"in_stock" BOOLEAN NOT NULL DEFAULT true,
"checked_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "competitor_price_logs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "b2b_leads" (
"id" UUID NOT NULL,
"clinic_name" VARCHAR(200) NOT NULL,
"contact_person" VARCHAR(150) NOT NULL,
"phone" VARCHAR(20) NOT NULL,
"city" VARCHAR(100) NOT NULL,
"district" VARCHAR(100),
"tier" VARCHAR(50) NOT NULL DEFAULT 'STANDARD',
"specialties" TEXT[] DEFAULT ARRAY[]::TEXT[],
"status" VARCHAR(30) NOT NULL DEFAULT 'NEW',
"notes" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "b2b_leads_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "price_suggestions" (
"id" UUID NOT NULL,
"product_id" UUID NOT NULL,
"suggested_price" DECIMAL(15,2) NOT NULL,
"current_price" DECIMAL(15,2) NOT NULL,
"competitor_benchmark" DECIMAL(15,2),
"rationale" TEXT,
"status" VARCHAR(20) NOT NULL DEFAULT 'pending',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "price_suggestions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sms_campaigns" (
"id" UUID NOT NULL,
"title" VARCHAR(200) NOT NULL,
"body" TEXT NOT NULL,
"target_segment" VARCHAR(100) NOT NULL,
"estimated_cost" DECIMAL(15,2),
"status" VARCHAR(20) NOT NULL DEFAULT 'draft',
"metrics" JSONB DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "sms_campaigns_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "competitor_price_logs_product_id_idx" ON "competitor_price_logs"("product_id");
-- CreateIndex
CREATE INDEX "competitor_price_logs_competitor_name_idx" ON "competitor_price_logs"("competitor_name");
-- CreateIndex
CREATE INDEX "competitor_price_logs_checked_at_idx" ON "competitor_price_logs"("checked_at");
-- CreateIndex
CREATE INDEX "b2b_leads_status_idx" ON "b2b_leads"("status");
-- CreateIndex
CREATE INDEX "b2b_leads_city_idx" ON "b2b_leads"("city");
-- CreateIndex
CREATE INDEX "b2b_leads_tier_idx" ON "b2b_leads"("tier");
-- CreateIndex
CREATE INDEX "b2b_leads_phone_idx" ON "b2b_leads"("phone");
-- CreateIndex
CREATE INDEX "price_suggestions_product_id_idx" ON "price_suggestions"("product_id");
-- CreateIndex
CREATE INDEX "price_suggestions_status_idx" ON "price_suggestions"("status");
-- CreateIndex
CREATE INDEX "price_suggestions_created_at_idx" ON "price_suggestions"("created_at");
-- CreateIndex
CREATE INDEX "sms_campaigns_status_idx" ON "sms_campaigns"("status");
-- CreateIndex
CREATE INDEX "sms_campaigns_target_segment_idx" ON "sms_campaigns"("target_segment");
-- CreateIndex
CREATE INDEX "sms_campaigns_created_at_idx" ON "sms_campaigns"("created_at");
-- AddForeignKey
ALTER TABLE "competitor_price_logs" ADD CONSTRAINT "competitor_price_logs_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "price_suggestions" ADD CONSTRAINT "price_suggestions_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+265 -157
View File
@@ -21,17 +21,17 @@ model User {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamptz()
addresses UserAddress[]
walletTransactions WalletTransaction[]
pets Pet[]
orders Order[]
blogs Blog[]
prescriptions Prescription[]
partnerAccount PartnerAccount?
addresses UserAddress[]
walletTransactions WalletTransaction[]
pets Pet[]
orders Order[]
blogs Blog[]
prescriptions Prescription[]
partnerAccount PartnerAccount?
paymentTransactions PaymentTransaction[]
tickets Ticket[]
reviews ProductReview[]
blogComments BlogComment[]
tickets Ticket[]
reviews ProductReview[]
blogComments BlogComment[]
@@index([role])
@@index([createdAt])
@@ -136,41 +136,41 @@ model BlogTag {
}
model Blog {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(200)
slug String @unique @db.VarChar(200)
content String @db.Text
excerpt String? @db.Text
authorId String @map("author_id") @db.Uuid
categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255)
imageCaption String? @map("image_caption") @db.Text
metaTitle String? @map("meta_title") @db.VarChar(200)
metaDescription String? @map("meta_description") @db.Text
keywords String? @db.Text
focusKeywords String? @map("focus_keywords") @db.Text
canonicalUrl String? @map("canonical_url") @db.Text
noIndex Boolean @default(false) @map("no_index")
noFollow Boolean @default(false) @map("no_follow")
schemaType String @default("BlogPosting") @map("schema_type") @db.VarChar(50)
ogTitle String? @map("og_title") @db.VarChar(200)
ogDescription String? @map("og_description") @db.Text
ogImage String? @map("og_image") @db.Text
status String @default("PUBLISHED") @db.VarChar(20) // DRAFT, PUBLISHED, SCHEDULED, ARCHIVED
isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments")
viewCount Int @default(0) @map("view_count")
showOnHome Boolean @default(false) @map("show_on_home")
homeDisplayMode String @default("selected") @map("home_display_mode") @db.VarChar(30)
relatedProductIds String[] @default([]) @map("related_product_ids")
relatedBlogIds String[] @default([]) @map("related_blog_ids")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(200)
slug String @unique @db.VarChar(200)
content String @db.Text
excerpt String? @db.Text
authorId String @map("author_id") @db.Uuid
categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255)
imageCaption String? @map("image_caption") @db.Text
metaTitle String? @map("meta_title") @db.VarChar(200)
metaDescription String? @map("meta_description") @db.Text
keywords String? @db.Text
focusKeywords String? @map("focus_keywords") @db.Text
canonicalUrl String? @map("canonical_url") @db.Text
noIndex Boolean @default(false) @map("no_index")
noFollow Boolean @default(false) @map("no_follow")
schemaType String @default("BlogPosting") @map("schema_type") @db.VarChar(50)
ogTitle String? @map("og_title") @db.VarChar(200)
ogDescription String? @map("og_description") @db.Text
ogImage String? @map("og_image") @db.Text
status String @default("PUBLISHED") @db.VarChar(20) // DRAFT, PUBLISHED, SCHEDULED, ARCHIVED
isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments")
viewCount Int @default(0) @map("view_count")
showOnHome Boolean @default(false) @map("show_on_home")
homeDisplayMode String @default("selected") @map("home_display_mode") @db.VarChar(30)
relatedProductIds String[] @default([]) @map("related_product_ids")
relatedBlogIds String[] @default([]) @map("related_blog_ids")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
author User @relation(fields: [authorId], references: [id])
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
@@ -185,68 +185,70 @@ model Blog {
}
model Product {
id String @id @default(uuid()) @db.Uuid
artNo String @unique @map("art_no") @db.VarChar(20)
barcode String? @unique @db.VarChar(30)
slug String @unique @db.VarChar(150)
productGroup String? @map("product_group") @db.VarChar(100)
nameFa String @map("name_fa") @db.VarChar(200)
nameEn String @map("name_en") @db.VarChar(200)
scientificTagline String? @map("scientific_tagline") @db.VarChar(250)
description String @db.Text
shortDescription String? @map("short_description") @db.Text
ingredients String? @db.Text
categoryId String @map("category_id") @db.Uuid
categorySlug String @map("category_slug") @db.VarChar(100)
priceValue Decimal @map("price_value") @db.Decimal(15, 2)
wholesalePrice Decimal? @map("wholesale_price") @db.Decimal(15, 2)
requiresRx Boolean @default(false) @map("requires_rx")
buyPrice Decimal @default(0) @map("buy_price") @db.Decimal(15, 2)
marginRetailPercent Decimal? @map("margin_retail_percent") @db.Decimal(6, 2)
marginWholesalePercent Decimal? @map("margin_wholesale_percent") @db.Decimal(6, 2)
roundingStep Int? @map("rounding_step")
roundingMode String? @map("rounding_mode") @db.VarChar(10)
priceDisplay String @map("price_display") @db.VarChar(50)
unit String @db.VarChar(50)
packageSize Decimal @map("package_size") @db.Decimal(10, 2)
dosageLogic String? @map("dosage_logic") @db.Text
dosageConfig Json? @map("dosage_config")
suitableFor String @map("suitable_for") @db.VarChar(15) // سگ, گربه, هر دو
imageUrl String @map("image_url") @db.Text
images String[] @default([])
podcastUrl String? @map("podcast_url") @db.Text
podcastTitle String? @map("podcast_title") @db.VarChar(250)
podcastDescription String? @map("podcast_description") @db.Text
podcastCover String? @map("podcast_cover") @db.Text
videoUrl String? @map("video_url") @db.Text
videoTitle String? @map("video_title") @db.VarChar(250)
videoDescription String? @map("video_description") @db.Text
videoCover String? @map("video_cover") @db.Text
pdfUrl String? @map("pdf_url") @db.Text
pdfTitle String? @map("pdf_title") @db.VarChar(250)
pdfDescription String? @map("pdf_description") @db.Text
pdfCover String? @map("pdf_cover") @db.Text
metaTitle String? @map("meta_title") @db.VarChar(200)
metaDescription String? @map("meta_description") @db.Text
canonicalUrl String? @map("canonical_url") @db.Text
keywords String? @db.Text
stock Int @default(100) @map("stock")
stockStatus StockStatus @default(IN_STOCK) @map("stock_status")
noIndex Boolean @default(false) @map("no_index")
noFollow Boolean @default(false) @map("no_follow")
ogImage String? @map("og_image") @db.Text
featuredImageAlt String? @map("featured_image_alt") @db.VarChar(255)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
artNo String @unique @map("art_no") @db.VarChar(20)
barcode String? @unique @db.VarChar(30)
slug String @unique @db.VarChar(150)
productGroup String? @map("product_group") @db.VarChar(100)
nameFa String @map("name_fa") @db.VarChar(200)
nameEn String @map("name_en") @db.VarChar(200)
scientificTagline String? @map("scientific_tagline") @db.VarChar(250)
description String @db.Text
shortDescription String? @map("short_description") @db.Text
ingredients String? @db.Text
categoryId String @map("category_id") @db.Uuid
categorySlug String @map("category_slug") @db.VarChar(100)
priceValue Decimal @map("price_value") @db.Decimal(15, 2)
wholesalePrice Decimal? @map("wholesale_price") @db.Decimal(15, 2)
requiresRx Boolean @default(false) @map("requires_rx")
buyPrice Decimal @default(0) @map("buy_price") @db.Decimal(15, 2)
marginRetailPercent Decimal? @map("margin_retail_percent") @db.Decimal(6, 2)
marginWholesalePercent Decimal? @map("margin_wholesale_percent") @db.Decimal(6, 2)
roundingStep Int? @map("rounding_step")
roundingMode String? @map("rounding_mode") @db.VarChar(10)
priceDisplay String @map("price_display") @db.VarChar(50)
unit String @db.VarChar(50)
packageSize Decimal @map("package_size") @db.Decimal(10, 2)
dosageLogic String? @map("dosage_logic") @db.Text
dosageConfig Json? @map("dosage_config")
suitableFor String @map("suitable_for") @db.VarChar(15) // سگ, گربه, هر دو
imageUrl String @map("image_url") @db.Text
images String[] @default([])
podcastUrl String? @map("podcast_url") @db.Text
podcastTitle String? @map("podcast_title") @db.VarChar(250)
podcastDescription String? @map("podcast_description") @db.Text
podcastCover String? @map("podcast_cover") @db.Text
videoUrl String? @map("video_url") @db.Text
videoTitle String? @map("video_title") @db.VarChar(250)
videoDescription String? @map("video_description") @db.Text
videoCover String? @map("video_cover") @db.Text
pdfUrl String? @map("pdf_url") @db.Text
pdfTitle String? @map("pdf_title") @db.VarChar(250)
pdfDescription String? @map("pdf_description") @db.Text
pdfCover String? @map("pdf_cover") @db.Text
metaTitle String? @map("meta_title") @db.VarChar(200)
metaDescription String? @map("meta_description") @db.Text
canonicalUrl String? @map("canonical_url") @db.Text
keywords String? @db.Text
stock Int @default(100) @map("stock")
stockStatus StockStatus @default(IN_STOCK) @map("stock_status")
noIndex Boolean @default(false) @map("no_index")
noFollow Boolean @default(false) @map("no_follow")
ogImage String? @map("og_image") @db.Text
featuredImageAlt String? @map("featured_image_alt") @db.VarChar(255)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
category Category @relation(fields: [categoryId], references: [id])
ingredientList ProductIngredient[]
symptoms ProductSymptom[]
category Category @relation(fields: [categoryId], references: [id])
ingredientList ProductIngredient[]
symptoms ProductSymptom[]
reminders Reminder[]
orderItems OrderItem[]
advisorRules SmartAdvisorRule[]
inventoryReservations InventoryReservation[]
reviews ProductReview[]
competitorPriceLogs CompetitorPriceLog[]
priceSuggestions PriceSuggestion[]
@@index([categorySlug])
@@index([suitableFor])
@@ -263,8 +265,6 @@ enum StockStatus {
DISCONTINUED
}
model ProductIngredient {
productId String @map("product_id") @db.Uuid
ingredient String @db.VarChar(150)
@@ -414,10 +414,10 @@ model Order {
refundMethod String? @map("refund_method") @db.VarChar(30) // wallet, zibal
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
coupon Coupon? @relation(fields: [couponId], references: [id])
orderItems OrderItem[]
paymentTransactions PaymentTransaction[]
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
coupon Coupon? @relation(fields: [couponId], references: [id])
orderItems OrderItem[]
paymentTransactions PaymentTransaction[]
inventoryReservations InventoryReservation[]
@@index([userId])
@@ -450,8 +450,8 @@ model PaymentTransaction {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
@@index([userId])
@@index([orderId])
@@ -554,23 +554,23 @@ model SmartAdvisorRule {
}
model Doctor {
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(150)
title String? @db.VarChar(150)
clinicName String? @map("clinic_name") @db.VarChar(200)
avatarUrl String? @map("avatar_url") @db.Text
bio String? @db.Text
cv String? @db.Text
phone String? @db.VarChar(50)
email String? @db.VarChar(150)
instagram String? @db.VarChar(100)
quote String? @db.Text
quoteProductRef String? @map("quote_product_ref") @db.VarChar(200)
showQuoteOnHome Boolean @default(false) @map("show_quote_on_home")
isActive Boolean @default(true) @map("is_active")
order Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(150)
title String? @db.VarChar(150)
clinicName String? @map("clinic_name") @db.VarChar(200)
avatarUrl String? @map("avatar_url") @db.Text
bio String? @db.Text
cv String? @db.Text
phone String? @db.VarChar(50)
email String? @db.VarChar(150)
instagram String? @db.VarChar(100)
quote String? @db.Text
quoteProductRef String? @map("quote_product_ref") @db.VarChar(200)
showQuoteOnHome Boolean @default(false) @map("show_quote_on_home")
isActive Boolean @default(true) @map("is_active")
order Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
videos Video[]
@@ -658,13 +658,13 @@ model Testimonial {
}
model Ingredient {
id String @id @default(uuid()) @db.Uuid
nameFa String @map("name_fa") @db.VarChar(150)
nameEn String @map("name_en") @db.VarChar(150)
slug String @unique @db.VarChar(150)
description String? @db.Text
scientificName String? @map("scientific_name") @db.VarChar(200)
imageUrl String? @map("image_url") @db.Text
id String @id @default(uuid()) @db.Uuid
nameFa String @map("name_fa") @db.VarChar(150)
nameEn String @map("name_en") @db.VarChar(150)
slug String @unique @db.VarChar(150)
description String? @db.Text
scientificName String? @map("scientific_name") @db.VarChar(200)
imageUrl String? @map("image_url") @db.Text
benefits String[] @default([])
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@ -760,16 +760,16 @@ model SmsLog {
}
model Ticket {
id String @id @default(uuid()) @db.Uuid
ticketNumber String @unique @map("ticket_number") @db.VarChar(50)
userId String @map("user_id") @db.Uuid
petId String? @map("pet_id") @db.Uuid
subject String @db.VarChar(255)
category String @default("VET_CONSULTATION") @db.VarChar(50) // VET_CONSULTATION, ORDER_SUPPORT, PRODUCT_INQUIRY, GENERAL
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, URGENT
status String @default("OPEN") @db.VarChar(30) // OPEN, ANSWERED, IN_PROGRESS, CLOSED
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
ticketNumber String @unique @map("ticket_number") @db.VarChar(50)
userId String @map("user_id") @db.Uuid
petId String? @map("pet_id") @db.Uuid
subject String @db.VarChar(255)
category String @default("VET_CONSULTATION") @db.VarChar(50) // VET_CONSULTATION, ORDER_SUPPORT, PRODUCT_INQUIRY, GENERAL
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, URGENT
status String @default("OPEN") @db.VarChar(30) // OPEN, ANSWERED, IN_PROGRESS, CLOSED
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
pet Pet? @relation(fields: [petId], references: [id], onDelete: SetNull)
@@ -821,8 +821,6 @@ model ProductReview {
@@map("product_reviews")
}
model BlogComment {
id String @id @default(uuid()) @db.Uuid
blogId String @map("blog_id") @db.Uuid
@@ -853,18 +851,18 @@ model FAQ {
}
model MenuItem {
id String @id @default(uuid()) @db.Uuid
menuType String @map("menu_type") @db.VarChar(30)
label String @db.VarChar(150)
href String @db.VarChar(500)
parentId String? @map("parent_id") @db.Uuid
order Int @default(0)
isActive Boolean @default(true) @map("is_active")
isExternal Boolean @default(false) @map("is_external")
icon String? @db.VarChar(100)
badge String? @db.VarChar(50)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
menuType String @map("menu_type") @db.VarChar(30)
label String @db.VarChar(150)
href String @db.VarChar(500)
parentId String? @map("parent_id") @db.Uuid
order Int @default(0)
isActive Boolean @default(true) @map("is_active")
isExternal Boolean @default(false) @map("is_external")
icon String? @db.VarChar(100)
badge String? @db.VarChar(50)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
parent MenuItem? @relation("MenuChildren", fields: [parentId], references: [id])
children MenuItem[] @relation("MenuChildren")
@@ -891,3 +889,113 @@ model ApiKey {
@@index([status])
@@map("api_keys")
}
// ------------------------------------------------------------------------------
// Admin CRM & Competitor Modules Extension
// ------------------------------------------------------------------------------
model CompetitorPriceLog {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
competitorName String @map("competitor_name") @db.VarChar(100)
competitorPrice Decimal @map("competitor_price") @db.Decimal(15, 2)
shopUrl String @map("shop_url") @db.Text
inStock Boolean @default(true) @map("in_stock")
checkedAt DateTime @default(now()) @map("checked_at") @db.Timestamptz()
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@index([productId])
@@index([competitorName])
@@index([checkedAt])
@@map("competitor_price_logs")
}
// ------------------------------------------------------------------------------
// 2. B2BLead
// ------------------------------------------------------------------------------
model B2BLead {
id String @id @default(uuid()) @db.Uuid
clinicName String @map("clinic_name") @db.VarChar(200)
contactPerson String @map("contact_person") @db.VarChar(150)
phone String @db.VarChar(20)
city String @db.VarChar(100)
district String? @db.VarChar(100)
tier String @default("STANDARD") @db.VarChar(50)
specialties String[] @default([])
status String @default("NEW") @db.VarChar(30)
notes String? @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@index([status])
@@index([city])
@@index([tier])
@@index([phone])
@@map("b2b_leads")
}
// ------------------------------------------------------------------------------
// 3. PriceSuggestion
// ------------------------------------------------------------------------------
model PriceSuggestion {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
suggestedPrice Decimal @map("suggested_price") @db.Decimal(15, 2)
currentPrice Decimal @map("current_price") @db.Decimal(15, 2)
competitorBenchmark Decimal? @map("competitor_benchmark") @db.Decimal(15, 2)
rationale String? @db.Text
status String @default("pending") @db.VarChar(20) // pending, approved, rejected
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@index([productId])
@@index([status])
@@index([createdAt])
@@map("price_suggestions")
}
// ------------------------------------------------------------------------------
// 4. SmsCampaign
// ------------------------------------------------------------------------------
model SmsCampaign {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(200)
body String @db.Text
targetSegment String @map("target_segment") @db.VarChar(100)
estimatedCost Decimal? @map("estimated_cost") @db.Decimal(15, 2)
status String @default("draft") @db.VarChar(20) // draft, approved, rejected, sent
metrics Json? @default("{}")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@index([status])
@@index([targetSegment])
@@index([createdAt])
@@map("sms_campaigns")
}
// ------------------------------------------------------------------------------
// 5. ApprovalRequest (CEO Governance & Decision Gate)
// ------------------------------------------------------------------------------
model ApprovalRequest {
id String @id @default(uuid()) @db.Uuid
department String @db.VarChar(50)
category String @db.VarChar(50)
title String @db.VarChar(255)
payload Json @db.JsonB
testContext Json? @map("test_context") @db.JsonB
status String @default("PENDING") @db.VarChar(30)
ceoNotes String? @map("ceo_notes") @db.Text
executedAt DateTime? @map("executed_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@index([department])
@@index([category])
@@index([status])
@@index([createdAt])
@@map("approval_requests")
}
+10
View File
@@ -17,6 +17,11 @@ import { SslController } from "./ssl.controller";
import { SslService } from "./ssl.service";
import { ApiKeysController } from "./api-keys.controller";
import { ApiKeysService } from "./api-keys.service";
import { CompetitorPricingController } from "./competitor-pricing.controller";
import { B2BLeadsController } from "./b2b-leads.controller";
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
import { SmsCampaignsController } from "./sms-campaigns.controller";
import { ApprovalsController } from "./approvals.controller";
import { PrismaModule } from "../prisma/prisma.module";
import { RedisModule } from "../redis/redis.module";
import { SettingsModule } from "../settings/settings.module";
@@ -33,6 +38,11 @@ import { SettingsModule } from "../settings/settings.module";
PetsController,
SslController,
ApiKeysController,
CompetitorPricingController,
B2BLeadsController,
PricingSuggestionsController,
SmsCampaignsController,
ApprovalsController,
],
providers: [
AdminService,
+176
View File
@@ -0,0 +1,176 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
NotFoundException,
BadRequestException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateApprovalRequestDto,
DecideApprovalDto,
QueryApprovalDto,
} from "./dto/approval-request.dto";
@ApiTags("Admin - CEO Approvals & Governance")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/approvals")
export class ApprovalsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
async findAll(@Query() query: QueryApprovalDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 20;
const skip = (page - 1) * limit;
const where: any = {};
if (query.department) where.department = query.department;
if (query.category) where.category = query.category;
if (query.status) where.status = query.status;
const [total, items, pendingCount] = await Promise.all([
(this.prisma as any).approvalRequest.count({ where }),
(this.prisma as any).approvalRequest.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
}),
(this.prisma as any).approvalRequest.count({
where: { status: "PENDING" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
pendingCount,
},
};
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
async findOne(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" })
async create(@Body() dto: CreateApprovalRequestDto) {
const item = await (this.prisma as any).approvalRequest.create({
data: {
department: dto.department,
category: dto.category,
title: dto.title,
payload: dto.payload,
testContext: dto.testContext || {},
status: "PENDING",
},
});
return { success: true, data: item };
}
@Post(":id/test")
@ApiOperation({ summary: "اجرای شبیه‌سازی تست زنده برای آیتم کارتابل" })
async runTestSimulation(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
// شبیه‌سازی بسته به دسته‌بندی
let testResult: any = { status: "SIMULATION_SUCCESS" };
if (item.category === "PRICING") {
const payload = item.payload as any;
testResult = {
impact: "Price change simulation",
currentPrice: payload.currentPrice,
newPrice: payload.newPrice,
marginDiff: payload.newPrice && payload.buyPrice
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
: "N/A",
torobFeedReflectEstimate: "< 5 seconds",
};
} else if (item.category === "PURCHASE_ORDER") {
const payload = item.payload as any;
testResult = {
document: "PO Pre-check",
itemsCount: payload.items ? payload.items.length : 1,
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
fulfillmentCapacity: "انبار آماده پذیرش",
};
} else {
testResult = {
executionSafe: true,
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
};
}
return { success: true, testResult };
}
@Put(":id/decide")
@ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
}
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: dto.decision,
ceoNotes: dto.ceoNotes || null,
executedAt: dto.decision === "APPROVED" ? new Date() : null,
},
});
return {
success: true,
message: dto.decision === "APPROVED" ? "درخواست با موفقیت تایید شد." : "درخواست رد شد.",
data: updated,
};
}
@Delete(":id")
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
async remove(@Param("id") id: string) {
await (this.prisma as any).approvalRequest.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
+205
View File
@@ -0,0 +1,205 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
Res,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import type { Response } from "express";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateB2BLeadDto,
UpdateB2BLeadDto,
QueryB2BLeadDto,
} from "./dto/b2b-lead.dto";
import { generateCsv } from "../common/utils/csv-helper";
@ApiTags("Admin - B2B Leads")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/b2b/leads")
export class B2BLeadsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست لیدهای سازمانی و کلینیک‌ها" })
async findAll(@Query() query: QueryB2BLeadDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.city) {
where.city = { contains: query.city, mode: "insensitive" };
}
if (query.tier) {
where.tier = query.tier;
}
if (query.status) {
where.status = query.status;
}
if (query.search) {
where.OR = [
{ clinicName: { contains: query.search, mode: "insensitive" } },
{ contactPerson: { contains: query.search, mode: "insensitive" } },
{ phone: { contains: query.search } },
];
}
const [total, items] = await Promise.all([
this.prisma.b2BLead.count({ where }),
this.prisma.b2BLead.findMany({
where,
skip,
take: limit,
orderBy: { [query.sortBy || "createdAt"]: query.sortOrder || "desc" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("export/csv")
@ApiOperation({ summary: "خروجی CSV لیدهای B2B" })
async exportCsv(@Query() query: QueryB2BLeadDto, @Res() res: Response) {
const where: any = {};
if (query.city) {
where.city = { contains: query.city, mode: "insensitive" };
}
if (query.tier) {
where.tier = query.tier;
}
if (query.status) {
where.status = query.status;
}
const items: any[] = await this.prisma.b2BLead.findMany({
where,
orderBy: { createdAt: "desc" },
});
const rows = items.map((item: any) => ({
id: item.id,
clinicName: item.clinicName,
contactPerson: item.contactPerson,
phone: item.phone,
city: item.city,
district: item.district || "",
tier: item.tier,
specialties: (item.specialties || []).join(" | "),
status: item.status,
notes: item.notes || "",
createdAt: item.createdAt.toISOString(),
updatedAt: item.updatedAt.toISOString(),
}));
const csvData = generateCsv(rows, [
{ key: "id", header: "ID" },
{ key: "clinicName", header: "Clinic Name" },
{ key: "contactPerson", header: "Contact Person" },
{ key: "phone", header: "Phone" },
{ key: "city", header: "City" },
{ key: "district", header: "District" },
{ key: "tier", header: "Tier" },
{ key: "specialties", header: "Specialties" },
{ key: "status", header: "Status" },
{ key: "notes", header: "Notes" },
{ key: "createdAt", header: "Created At" },
{ key: "updatedAt", header: "Updated At" },
]);
res.setHeader("Content-Type", "text/csv; charset=utf-8");
res.setHeader(
"Content-Disposition",
`attachment; filename="b2b-leads-${Date.now()}.csv"`,
);
return res.status(200).send(csvData);
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک لید B2B" })
async findOne(@Param("id") id: string) {
const item = await this.prisma.b2BLead.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`B2B Lead with ID ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ثبت لید سازمانی جدید" })
async create(@Body() dto: CreateB2BLeadDto) {
const item = await this.prisma.b2BLead.create({
data: {
clinicName: dto.clinicName,
contactPerson: dto.contactPerson,
phone: dto.phone,
city: dto.city,
district: dto.district,
tier: dto.tier || "STANDARD",
specialties: dto.specialties || [],
status: dto.status || "NEW",
notes: dto.notes,
},
});
return { success: true, data: item };
}
@Put(":id")
@ApiOperation({ summary: "ویرایش لید سازمانی" })
async update(@Param("id") id: string, @Body() dto: UpdateB2BLeadDto) {
const exists = await this.prisma.b2BLead.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`B2B Lead with ID ${id} not found`);
}
const updated = await this.prisma.b2BLead.update({
where: { id },
data: {
...(dto.clinicName && { clinicName: dto.clinicName }),
...(dto.contactPerson && { contactPerson: dto.contactPerson }),
...(dto.phone && { phone: dto.phone }),
...(dto.city && { city: dto.city }),
...(dto.district !== undefined && { district: dto.district }),
...(dto.tier && { tier: dto.tier }),
...(dto.specialties !== undefined && { specialties: dto.specialties }),
...(dto.status && { status: dto.status }),
...(dto.notes !== undefined && { notes: dto.notes }),
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف لید سازمانی" })
async remove(@Param("id") id: string) {
const exists = await this.prisma.b2BLead.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`B2B Lead with ID ${id} not found`);
}
await this.prisma.b2BLead.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -0,0 +1,217 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
Res,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import type { Response } from "express";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateCompetitorPriceDto,
UpdateCompetitorPriceDto,
QueryCompetitorPriceDto,
} from "./dto/competitor-price.dto";
import { generateCsv } from "../common/utils/csv-helper";
@ApiTags("Admin - Competitor Pricing")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/competitors/pricing")
export class CompetitorPricingController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست لاگ‌های قیمت رقبا" })
async findAll(@Query() query: QueryCompetitorPriceDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.productId) {
where.productId = query.productId;
}
if (query.competitorName) {
where.competitorName = { contains: query.competitorName, mode: "insensitive" };
}
if (query.inStock !== undefined) {
where.inStock = String(query.inStock) === "true";
}
if (query.search) {
where.OR = [
{ competitorName: { contains: query.search, mode: "insensitive" } },
{ shopUrl: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
this.prisma.competitorPriceLog.count({ where }),
this.prisma.competitorPriceLog.findMany({
where,
skip,
take: limit,
orderBy: { [query.sortBy || "checkedAt"]: query.sortOrder || "desc" },
include: {
product: {
select: { id: true, nameFa: true, artNo: true, priceValue: true },
},
},
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("export/csv")
@ApiOperation({ summary: "خروجی CSV لاگ‌های قیمت رقبا" })
async exportCsv(@Query() query: QueryCompetitorPriceDto, @Res() res: Response) {
const where: any = {};
if (query.productId) {
where.productId = query.productId;
}
if (query.competitorName) {
where.competitorName = { contains: query.competitorName, mode: "insensitive" };
}
if (query.inStock !== undefined) {
where.inStock = String(query.inStock) === "true";
}
const items: any[] = await this.prisma.competitorPriceLog.findMany({
where,
orderBy: { checkedAt: "desc" },
include: {
product: {
select: { nameFa: true, artNo: true, priceValue: true },
},
},
});
const rows = items.map((item: any) => ({
id: item.id,
productId: item.productId,
productName: item.product?.nameFa || "",
productArtNo: item.product?.artNo || "",
ourPrice: item.product?.priceValue ? item.product.priceValue.toString() : "",
competitorName: item.competitorName,
competitorPrice: item.competitorPrice.toString(),
shopUrl: item.shopUrl,
inStock: item.inStock ? "Yes" : "No",
checkedAt: item.checkedAt.toISOString(),
}));
const csvData = generateCsv(rows, [
{ key: "id", header: "ID" },
{ key: "productId", header: "Product ID" },
{ key: "productName", header: "Product Name" },
{ key: "productArtNo", header: "Art No" },
{ key: "ourPrice", header: "Our Price" },
{ key: "competitorName", header: "Competitor" },
{ key: "competitorPrice", header: "Competitor Price" },
{ key: "shopUrl", header: "Shop URL" },
{ key: "inStock", header: "In Stock" },
{ key: "checkedAt", header: "Checked At" },
]);
res.setHeader("Content-Type", "text/csv; charset=utf-8");
res.setHeader(
"Content-Disposition",
`attachment; filename="competitor-pricing-${Date.now()}.csv"`,
);
return res.status(200).send(csvData);
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک لاگ قیمت رقیب" })
async findOne(@Param("id") id: string) {
const item = await this.prisma.competitorPriceLog.findUnique({
where: { id },
include: {
product: {
select: { id: true, nameFa: true, artNo: true, priceValue: true },
},
},
});
if (!item) {
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ثبت لاگ قیمت جدید برای رقیب" })
async create(@Body() dto: CreateCompetitorPriceDto) {
const item = await this.prisma.competitorPriceLog.create({
data: {
productId: dto.productId,
competitorName: dto.competitorName,
competitorPrice: dto.competitorPrice,
shopUrl: dto.shopUrl,
inStock: dto.inStock ?? true,
},
include: {
product: {
select: { id: true, nameFa: true, artNo: true },
},
},
});
return { success: true, data: item };
}
@Put(":id")
@ApiOperation({ summary: "ویرایش لاگ قیمت رقیب" })
async update(@Param("id") id: string, @Body() dto: UpdateCompetitorPriceDto) {
const exists = await this.prisma.competitorPriceLog.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
}
const updated = await this.prisma.competitorPriceLog.update({
where: { id },
data: {
...(dto.productId && { productId: dto.productId }),
...(dto.competitorName && { competitorName: dto.competitorName }),
...(dto.competitorPrice !== undefined && { competitorPrice: dto.competitorPrice }),
...(dto.shopUrl && { shopUrl: dto.shopUrl }),
...(dto.inStock !== undefined && { inStock: dto.inStock }),
},
include: {
product: {
select: { id: true, nameFa: true, artNo: true },
},
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف لاگ قیمت رقیب" })
async remove(@Param("id") id: string) {
const exists = await this.prisma.competitorPriceLog.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`Competitor price log with ID ${id} not found`);
}
await this.prisma.competitorPriceLog.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -0,0 +1,58 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsString, IsOptional, IsObject } from "class-validator";
export class CreateApprovalRequestDto {
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
@IsString()
department: string;
@ApiProperty({ description: "دسته‌بندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
@IsString()
category: string;
@ApiProperty({ description: "عنوان مورد تایید" })
@IsString()
title: string;
@ApiProperty({ description: "داده‌های تغییرات پیشنهادی" })
@IsObject()
payload: Record<string, any>;
@ApiPropertyOptional({ description: "داده‌های سناریوی تست و ارزیابی" })
@IsOptional()
@IsObject()
testContext?: Record<string, any>;
}
export class DecideApprovalDto {
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
@IsString()
decision: "APPROVED" | "REJECTED";
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
@IsOptional()
@IsString()
ceoNotes?: string;
}
export class QueryApprovalDto {
@ApiPropertyOptional()
@IsOptional()
department?: string;
@ApiPropertyOptional()
@IsOptional()
category?: string;
@ApiPropertyOptional()
@IsOptional()
status?: string;
@ApiPropertyOptional()
@IsOptional()
page?: number;
@ApiPropertyOptional()
@IsOptional()
limit?: number;
}
+116
View File
@@ -0,0 +1,116 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsString,
IsOptional,
IsArray,
} from "class-validator";
import { PaginationDto } from "../../common/dto/pagination.dto";
export class CreateB2BLeadDto {
@ApiProperty({ description: "نام کلینیک یا سازمان", example: "کلینیک دامپزشکی مهر" })
@IsString()
clinicName!: string;
@ApiProperty({ description: "نام شخص رابط", example: "دکتر حسینی" })
@IsString()
contactPerson!: string;
@ApiProperty({ description: "شماره تلفن تماس", example: "09123456789" })
@IsString()
phone!: string;
@ApiProperty({ description: "شهر", example: "تهران" })
@IsString()
city!: string;
@ApiPropertyOptional({ description: "منطقه شهرداری یا محله", example: "منطقه ۲" })
@IsOptional()
@IsString()
district?: string;
@ApiPropertyOptional({ description: "سطح یا تی‌یر همکاری", example: "STANDARD", default: "STANDARD" })
@IsOptional()
@IsString()
tier?: string = "STANDARD";
@ApiPropertyOptional({ description: "تخصص‌ها", example: ["surgery", "internal"] })
@IsOptional()
@IsArray()
@IsString({ each: true })
specialties?: string[] = [];
@ApiPropertyOptional({ description: "وضعیت لید", example: "NEW", default: "NEW" })
@IsOptional()
@IsString()
status?: string = "NEW";
@ApiPropertyOptional({ description: "یادداشت‌ها و توضیحات" })
@IsOptional()
@IsString()
notes?: string;
}
export class UpdateB2BLeadDto {
@ApiPropertyOptional({ description: "نام کلینیک" })
@IsOptional()
@IsString()
clinicName?: string;
@ApiPropertyOptional({ description: "نام شخص رابط" })
@IsOptional()
@IsString()
contactPerson?: string;
@ApiPropertyOptional({ description: "شماره تماس" })
@IsOptional()
@IsString()
phone?: string;
@ApiPropertyOptional({ description: "شهر" })
@IsOptional()
@IsString()
city?: string;
@ApiPropertyOptional({ description: "منطقه" })
@IsOptional()
@IsString()
district?: string;
@ApiPropertyOptional({ description: "سطح همکاری" })
@IsOptional()
@IsString()
tier?: string;
@ApiPropertyOptional({ description: "تخصص‌ها" })
@IsOptional()
@IsArray()
@IsString({ each: true })
specialties?: string[];
@ApiPropertyOptional({ description: "وضعیت لید" })
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({ description: "یادداشت‌ها" })
@IsOptional()
@IsString()
notes?: string;
}
export class QueryB2BLeadDto extends PaginationDto {
@ApiPropertyOptional({ description: "فیلتر بر اساس شهر" })
@IsOptional()
@IsString()
city?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس سطح همکاری (tier)" })
@IsOptional()
@IsString()
tier?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس وضعیت" })
@IsOptional()
@IsString()
status?: string;
}
@@ -0,0 +1,83 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsString,
IsNumber,
IsBoolean,
IsOptional,
IsUUID,
Min,
} from "class-validator";
import { Type } from "class-transformer";
import { PaginationDto } from "../../common/dto/pagination.dto";
export class CreateCompetitorPriceDto {
@ApiProperty({ description: "شناسه محصول", example: "123e4567-e89b-12d3-a456-426614174000" })
@IsUUID()
productId!: string;
@ApiProperty({ description: "نام رقیب / فروشگاه", example: "دیجی‌کالا" })
@IsString()
competitorName!: string;
@ApiProperty({ description: "قیمت رقیب به تومان", example: 450000 })
@Type(() => Number)
@IsNumber()
@Min(0)
competitorPrice!: number;
@ApiProperty({ description: "آدرس لینک صفحه محصول در سایت رقیب", example: "https://competitor.com/p/123" })
@IsString()
shopUrl!: string;
@ApiPropertyOptional({ description: "آیا در سایت رقیب موجود است؟", default: true })
@IsOptional()
@IsBoolean()
inStock?: boolean = true;
}
export class UpdateCompetitorPriceDto {
@ApiPropertyOptional({ description: "شناسه محصول" })
@IsOptional()
@IsUUID()
productId?: string;
@ApiPropertyOptional({ description: "نام رقیب" })
@IsOptional()
@IsString()
competitorName?: string;
@ApiPropertyOptional({ description: "قیمت رقیب" })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
competitorPrice?: number;
@ApiPropertyOptional({ description: "آدرس لینک رقیب" })
@IsOptional()
@IsString()
shopUrl?: string;
@ApiPropertyOptional({ description: "وضعیت موجودی در سایت رقیب" })
@IsOptional()
@IsBoolean()
inStock?: boolean;
}
export class QueryCompetitorPriceDto extends PaginationDto {
@ApiPropertyOptional({ description: "فیلتر بر اساس شناسه محصول" })
@IsOptional()
@IsUUID()
productId?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس نام رقیب" })
@IsOptional()
@IsString()
competitorName?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس وضعیت موجودی" })
@IsOptional()
@Type(() => Boolean)
@IsBoolean()
inStock?: boolean;
}
@@ -0,0 +1,94 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsString,
IsNumber,
IsOptional,
IsUUID,
IsIn,
Min,
} from "class-validator";
import { Type } from "class-transformer";
import { PaginationDto } from "../../common/dto/pagination.dto";
export class CreatePriceSuggestionDto {
@ApiProperty({ description: "شناسه محصول", example: "123e4567-e89b-12d3-a456-426614174000" })
@IsUUID()
productId!: string;
@ApiProperty({ description: "قیمت پیشنهادی", example: 420000 })
@Type(() => Number)
@IsNumber()
@Min(0)
suggestedPrice!: number;
@ApiProperty({ description: "قیمت فعلی", example: 450000 })
@Type(() => Number)
@IsNumber()
@Min(0)
currentPrice!: number;
@ApiPropertyOptional({ description: "قیمت مبنای رقیب", example: 410000 })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
competitorBenchmark?: number;
@ApiPropertyOptional({ description: "دلیل و تحلیل پیشنهاد قیمت" })
@IsOptional()
@IsString()
rationale?: string;
@ApiPropertyOptional({ description: "وضعیت پیشنهاد", enum: ["pending", "approved", "rejected"], default: "pending" })
@IsOptional()
@IsString()
@IsIn(["pending", "approved", "rejected"])
status?: string = "pending";
}
export class UpdatePriceSuggestionDto {
@ApiPropertyOptional({ description: "قیمت پیشنهادی" })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
suggestedPrice?: number;
@ApiPropertyOptional({ description: "قیمت فعلی" })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
currentPrice?: number;
@ApiPropertyOptional({ description: "قیمت مبنای رقیب" })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
competitorBenchmark?: number;
@ApiPropertyOptional({ description: "دلیل پیشنهاد" })
@IsOptional()
@IsString()
rationale?: string;
@ApiPropertyOptional({ description: "وضعیت پیشنهاد", enum: ["pending", "approved", "rejected"] })
@IsOptional()
@IsString()
@IsIn(["pending", "approved", "rejected"])
status?: string;
}
export class QueryPriceSuggestionDto extends PaginationDto {
@ApiPropertyOptional({ description: "فیلتر بر اساس شناسه کالا" })
@IsOptional()
@IsUUID()
productId?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس وضعیت", enum: ["pending", "approved", "rejected"] })
@IsOptional()
@IsString()
@IsIn(["pending", "approved", "rejected"])
status?: string;
}
+88
View File
@@ -0,0 +1,88 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsString,
IsNumber,
IsOptional,
IsIn,
Min,
} from "class-validator";
import { Type } from "class-transformer";
import { PaginationDto } from "../../common/dto/pagination.dto";
export class CreateSmsCampaignDto {
@ApiProperty({ description: "عنوان کمپین", example: "تخفیف پایان فصل مکمل‌ها" })
@IsString()
title!: string;
@ApiProperty({ description: "متن پیامک", example: "تخفیف ویژه ۲۰ درصدی مکمل‌های کانینا به مدت ۳ روز! کد: OFF20" })
@IsString()
body!: string;
@ApiProperty({ description: "سگمنت مخاطبان", example: "b2b_clinics" })
@IsString()
targetSegment!: string;
@ApiPropertyOptional({ description: "هزینه تخمینی کمپین به تومان", example: 2500000 })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
estimatedCost?: number;
@ApiPropertyOptional({ description: "وضعیت کمپین", enum: ["draft", "approved", "rejected", "sent"], default: "draft" })
@IsOptional()
@IsString()
@IsIn(["draft", "approved", "rejected", "sent"])
status?: string = "draft";
@ApiPropertyOptional({ description: "متریک‌ها و نتایج ارسال کمپین" })
@IsOptional()
metrics?: Record<string, any>;
}
export class UpdateSmsCampaignDto {
@ApiPropertyOptional({ description: "عنوان کمپین" })
@IsOptional()
@IsString()
title?: string;
@ApiPropertyOptional({ description: "متن پیامک" })
@IsOptional()
@IsString()
body?: string;
@ApiPropertyOptional({ description: "سگمنت مخاطبان" })
@IsOptional()
@IsString()
targetSegment?: string;
@ApiPropertyOptional({ description: "هزینه تخمینی کمپین" })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
estimatedCost?: number;
@ApiPropertyOptional({ description: "وضعیت کمپین", enum: ["draft", "approved", "rejected", "sent"] })
@IsOptional()
@IsString()
@IsIn(["draft", "approved", "rejected", "sent"])
status?: string;
@ApiPropertyOptional({ description: "متریک‌ها" })
@IsOptional()
metrics?: Record<string, any>;
}
export class QuerySmsCampaignDto extends PaginationDto {
@ApiPropertyOptional({ description: "فیلتر بر اساس سگمنت مخاطبان" })
@IsOptional()
@IsString()
targetSegment?: string;
@ApiPropertyOptional({ description: "فیلتر بر اساس وضعیت کمپین", enum: ["draft", "approved", "rejected", "sent"] })
@IsOptional()
@IsString()
@IsIn(["draft", "approved", "rejected", "sent"])
status?: string;
}
@@ -0,0 +1,212 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
Res,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import type { Response } from "express";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreatePriceSuggestionDto,
UpdatePriceSuggestionDto,
QueryPriceSuggestionDto,
} from "./dto/price-suggestion.dto";
import { generateCsv } from "../common/utils/csv-helper";
@ApiTags("Admin - Pricing Suggestions")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/pricing/suggestions")
export class PricingSuggestionsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست پیشنهادات هوشمند قیمت‌گذاری" })
async findAll(@Query() query: QueryPriceSuggestionDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.productId) {
where.productId = query.productId;
}
if (query.status) {
where.status = query.status;
}
if (query.search) {
where.OR = [
{ rationale: { contains: query.search, mode: "insensitive" } },
{ product: { nameFa: { contains: query.search, mode: "insensitive" } } },
];
}
const [total, items] = await Promise.all([
this.prisma.priceSuggestion.count({ where }),
this.prisma.priceSuggestion.findMany({
where,
skip,
take: limit,
orderBy: { [query.sortBy || "createdAt"]: query.sortOrder || "desc" },
include: {
product: {
select: { id: true, nameFa: true, artNo: true, priceValue: true },
},
},
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("export/csv")
@ApiOperation({ summary: "خروجی CSV پیشنهادات قیمت‌گذاری" })
async exportCsv(@Query() query: QueryPriceSuggestionDto, @Res() res: Response) {
const where: any = {};
if (query.productId) {
where.productId = query.productId;
}
if (query.status) {
where.status = query.status;
}
const items: any[] = await this.prisma.priceSuggestion.findMany({
where,
orderBy: { createdAt: "desc" },
include: {
product: {
select: { nameFa: true, artNo: true },
},
},
});
const rows = items.map((item: any) => ({
id: item.id,
productId: item.productId,
productName: item.product?.nameFa || "",
productArtNo: item.product?.artNo || "",
currentPrice: item.currentPrice.toString(),
suggestedPrice: item.suggestedPrice.toString(),
competitorBenchmark: item.competitorBenchmark ? item.competitorBenchmark.toString() : "",
rationale: item.rationale || "",
status: item.status,
createdAt: item.createdAt.toISOString(),
}));
const csvData = generateCsv(rows, [
{ key: "id", header: "ID" },
{ key: "productId", header: "Product ID" },
{ key: "productName", header: "Product Name" },
{ key: "productArtNo", header: "Art No" },
{ key: "currentPrice", header: "Current Price" },
{ key: "suggestedPrice", header: "Suggested Price" },
{ key: "competitorBenchmark", header: "Competitor Benchmark" },
{ key: "rationale", header: "Rationale" },
{ key: "status", header: "Status" },
{ key: "createdAt", header: "Created At" },
]);
res.setHeader("Content-Type", "text/csv; charset=utf-8");
res.setHeader(
"Content-Disposition",
`attachment; filename="price-suggestions-${Date.now()}.csv"`,
);
return res.status(200).send(csvData);
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات پیشنهاد قیمت" })
async findOne(@Param("id") id: string) {
const item = await this.prisma.priceSuggestion.findUnique({
where: { id },
include: {
product: {
select: { id: true, nameFa: true, artNo: true, priceValue: true },
},
},
});
if (!item) {
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ایجاد پیشنهاد قیمت جدید" })
async create(@Body() dto: CreatePriceSuggestionDto) {
const item = await this.prisma.priceSuggestion.create({
data: {
productId: dto.productId,
suggestedPrice: dto.suggestedPrice,
currentPrice: dto.currentPrice,
competitorBenchmark: dto.competitorBenchmark,
rationale: dto.rationale,
status: dto.status || "pending",
},
include: {
product: {
select: { id: true, nameFa: true, artNo: true },
},
},
});
return { success: true, data: item };
}
@Put(":id")
@ApiOperation({ summary: "ویرایش پیشنهاد قیمت یا تایید/رد آن" })
async update(@Param("id") id: string, @Body() dto: UpdatePriceSuggestionDto) {
const exists = await this.prisma.priceSuggestion.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
}
const updated = await this.prisma.priceSuggestion.update({
where: { id },
data: {
...(dto.suggestedPrice !== undefined && { suggestedPrice: dto.suggestedPrice }),
...(dto.currentPrice !== undefined && { currentPrice: dto.currentPrice }),
...(dto.competitorBenchmark !== undefined && { competitorBenchmark: dto.competitorBenchmark }),
...(dto.rationale !== undefined && { rationale: dto.rationale }),
...(dto.status && { status: dto.status }),
},
include: {
product: {
select: { id: true, nameFa: true, artNo: true },
},
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف پیشنهاد قیمت" })
async remove(@Param("id") id: string) {
const exists = await this.prisma.priceSuggestion.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`Price suggestion with ID ${id} not found`);
}
await this.prisma.priceSuggestion.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -0,0 +1,186 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
Res,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import type { Response } from "express";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateSmsCampaignDto,
UpdateSmsCampaignDto,
QuerySmsCampaignDto,
} from "./dto/sms-campaign.dto";
import { generateCsv } from "../common/utils/csv-helper";
@ApiTags("Admin - CRM SMS Campaigns")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/crm/sms-campaigns")
export class SmsCampaignsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست کمپین‌های پیامکی CRM" })
async findAll(@Query() query: QuerySmsCampaignDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.targetSegment) {
where.targetSegment = query.targetSegment;
}
if (query.status) {
where.status = query.status;
}
if (query.search) {
where.OR = [
{ title: { contains: query.search, mode: "insensitive" } },
{ body: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
this.prisma.smsCampaign.count({ where }),
this.prisma.smsCampaign.findMany({
where,
skip,
take: limit,
orderBy: { [query.sortBy || "createdAt"]: query.sortOrder || "desc" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("export/csv")
@ApiOperation({ summary: "خروجی CSV کمپین‌های پیامکی" })
async exportCsv(@Query() query: QuerySmsCampaignDto, @Res() res: Response) {
const where: any = {};
if (query.targetSegment) {
where.targetSegment = query.targetSegment;
}
if (query.status) {
where.status = query.status;
}
const items: any[] = await this.prisma.smsCampaign.findMany({
where,
orderBy: { createdAt: "desc" },
});
const rows = items.map((item: any) => ({
id: item.id,
title: item.title,
body: item.body,
targetSegment: item.targetSegment,
estimatedCost: item.estimatedCost ? item.estimatedCost.toString() : "",
status: item.status,
metrics: item.metrics ? JSON.stringify(item.metrics) : "{}",
createdAt: item.createdAt.toISOString(),
updatedAt: item.updatedAt.toISOString(),
}));
const csvData = generateCsv(rows, [
{ key: "id", header: "ID" },
{ key: "title", header: "Title" },
{ key: "body", header: "Message Body" },
{ key: "targetSegment", header: "Target Segment" },
{ key: "estimatedCost", header: "Estimated Cost" },
{ key: "status", header: "Status" },
{ key: "metrics", header: "Metrics" },
{ key: "createdAt", header: "Created At" },
{ key: "updatedAt", header: "Updated At" },
]);
res.setHeader("Content-Type", "text/csv; charset=utf-8");
res.setHeader(
"Content-Disposition",
`attachment; filename="sms-campaigns-${Date.now()}.csv"`,
);
return res.status(200).send(csvData);
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک کمپین پیامکی" })
async findOne(@Param("id") id: string) {
const item = await this.prisma.smsCampaign.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ایجاد کمپین پیامکی جدید" })
async create(@Body() dto: CreateSmsCampaignDto) {
const item = await this.prisma.smsCampaign.create({
data: {
title: dto.title,
body: dto.body,
targetSegment: dto.targetSegment,
estimatedCost: dto.estimatedCost,
status: dto.status || "draft",
metrics: dto.metrics || {},
},
});
return { success: true, data: item };
}
@Put(":id")
@ApiOperation({ summary: "ویرایش کمپین پیامکی" })
async update(@Param("id") id: string, @Body() dto: UpdateSmsCampaignDto) {
const exists = await this.prisma.smsCampaign.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
}
const updated = await this.prisma.smsCampaign.update({
where: { id },
data: {
...(dto.title && { title: dto.title }),
...(dto.body && { body: dto.body }),
...(dto.targetSegment && { targetSegment: dto.targetSegment }),
...(dto.estimatedCost !== undefined && { estimatedCost: dto.estimatedCost }),
...(dto.status && { status: dto.status }),
...(dto.metrics !== undefined && { metrics: dto.metrics }),
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف کمپین پیامکی" })
async remove(@Param("id") id: string) {
const exists = await this.prisma.smsCampaign.findUnique({ where: { id } });
if (!exists) {
throw new NotFoundException(`SMS Campaign with ID ${id} not found`);
}
await this.prisma.smsCampaign.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -0,0 +1,54 @@
import { Injectable, Logger } from "@nestjs/common";
@Injectable()
export class HermesClientService {
private readonly logger = new Logger(HermesClientService.name);
private readonly baseUrl: string;
private readonly apiKey: string;
constructor() {
this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642";
this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || "";
}
async checkHealth(): Promise<boolean> {
try {
const res = await fetch(`${this.baseUrl}/v1/health`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
});
return res.status === 200;
} catch (error: any) {
this.logger.error(`Hermes health check failed: ${error.message}`);
return false;
}
}
async triggerEvent(eventName: string, payload: Record<string, any>) {
try {
this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`);
const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "hermes-agent",
messages: [
{
role: "user",
content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`,
},
],
}),
});
const data = await res.json();
return { success: true, data };
} catch (error: any) {
this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`);
return { success: false, error: error.message };
}
}
}
+27
View File
@@ -0,0 +1,27 @@
export function generateCsv(
rows: Record<string, any>[],
columns: { key: string; header: string }[],
): string {
const headerLine = columns
.map((c) => `"${c.header.replace(/"/g, '""')}"`)
.join(",");
const lines = rows.map((row) => {
return columns
.map((c) => {
let val = row[c.key];
if (val === null || val === undefined) {
return '""';
}
if (typeof val === "object") {
if (val instanceof Date) {
val = val.toISOString();
} else {
val = JSON.stringify(val);
}
}
return `"${String(val).replace(/"/g, '""')}"`;
})
.join(",");
});
return "\uFEFF" + [headerLine, ...lines].join("\r\n");
}
@@ -1,5 +1,6 @@
import {
Activity,
CheckSquare,
BookOpen,
Building2,
ChevronDown,
@@ -109,12 +110,22 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' },
],
},
{
id: 'governance',
title: 'حاکمیت و تاییدات مدیریت',
icon: CheckSquare,
items: [
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
],
},
{
id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت',
icon: Activity,
CheckSquare,
items: [
{ icon: Activity, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' },
{ icon: Activity,
CheckSquare, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' },
{ icon: RotateCcw, label: 'پرتال مالی و استرداد زیبال', path: '/zibal-portal' },
],
},
@@ -0,0 +1,322 @@
import { useState, useEffect } from 'react';
import {
CheckCircle2,
XCircle,
Play,
AlertTriangle,
RefreshCw,
DollarSign,
ShoppingCart,
Send,
Sliders,
Check,
X,
MessageSquare,
FileText
} from 'lucide-react';
import api from '../services/api';
import Button from '../components/ui/Button';
import Badge from '../components/ui/Badge';
import Spinner from '../components/ui/Spinner';
interface ApprovalItem {
id: string;
department: string;
category: string;
title: string;
payload: any;
testContext?: any;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
ceoNotes?: string;
createdAt: string;
executedAt?: string;
}
export default function ApprovalsPage() {
const [items, setItems] = useState<ApprovalItem[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<string>('ALL');
const [testingId, setTestingId] = useState<string | null>(null);
const [testResults, setTestResults] = useState<Record<string, any>>({});
const [notes, setNotes] = useState<Record<string, string>>({});
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [pendingCount, setPendingCount] = useState(0);
const fetchApprovals = async () => {
setLoading(true);
try {
const res = await api.get('/admin/approvals');
if (res.data?.success) {
setItems(res.data.data);
setPendingCount(res.data.meta?.pendingCount || 0);
// Pre-fill notes
const initialNotes: Record<string, string> = {};
res.data.data.forEach((item: ApprovalItem) => {
if (item.ceoNotes) initialNotes[item.id] = item.ceoNotes;
});
setNotes(initialNotes);
}
} catch (err) {
console.error('Error fetching approvals', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchApprovals();
}, []);
const handleRunTest = async (id: string) => {
setTestingId(id);
try {
const res = await api.post(`/admin/approvals/${id}/test`);
if (res.data?.success) {
setTestResults((prev) => ({ ...prev, [id]: res.data.testResult }));
}
} catch (err) {
console.error('Test simulation failed', err);
} finally {
setTestingId(null);
}
};
const handleDecision = async (id: string, decision: 'APPROVED' | 'REJECTED') => {
setActionLoading(id);
try {
const res = await api.put(`/admin/approvals/${id}/decide`, {
decision,
ceoNotes: notes[id] || '',
});
if (res.data?.success) {
await fetchApprovals();
}
} catch (err) {
console.error('Decision update failed', err);
} finally {
setActionLoading(null);
}
};
const filteredItems = items.filter((item) => {
if (activeTab === 'ALL') return true;
if (activeTab === 'PENDING') return item.status === 'PENDING';
if (activeTab === 'PRICING') return item.category === 'PRICING';
if (activeTab === 'PURCHASE_ORDER') return item.category === 'PURCHASE_ORDER';
return item.department === activeTab;
});
const getCategoryIcon = (category: string) => {
switch (category) {
case 'PRICING':
return <DollarSign className="w-5 h-5 text-amber-500" />;
case 'PURCHASE_ORDER':
return <ShoppingCart className="w-5 h-5 text-blue-500" />;
case 'CAMPAIGN':
return <Send className="w-5 h-5 text-purple-500" />;
default:
return <Sliders className="w-5 h-5 text-emerald-500" />;
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'PENDING':
return <Badge variant="warning">در انتظار تایید شما</Badge>;
case 'APPROVED':
return <Badge variant="success">تایید و اعمال شد</Badge>;
case 'REJECTED':
return <Badge variant="danger">رد شده</Badge>;
default:
return <Badge variant="neutral">{status}</Badge>;
}
};
return (
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6" dir="rtl">
{/* Header */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white dark:bg-slate-900 p-6 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm">
<div>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">
میز کار تاییدات و حاکمیت سازمانی (CEO Approvals Gate)
</h1>
{pendingCount > 0 && (
<span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300">
{pendingCount} مورد نیازمند بررسی
</span>
)}
</div>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
هیچ تغییر حساسی اعم از قیمت‌گذاری، صدور سفارش تامین یا ارسال پیامک بدون امضای دیجیتال شما در سیستم پروداکشن اجرایی نخواهد شد.
</p>
</div>
<Button
variant="secondary"
onClick={fetchApprovals}
disabled={loading}
icon={<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />}
>
به‌روزرسانی کارتابل
</Button>
</div>
{/* Tabs */}
<div className="flex flex-wrap gap-2 border-b border-slate-200 dark:border-slate-800 pb-3">
{[
{ id: 'ALL', label: 'همه موارد' },
{ id: 'PENDING', label: `در انتظار تایید (${pendingCount})` },
{ id: 'PRICING', label: 'تغییرات قیمت و سود' },
{ id: 'PURCHASE_ORDER', label: 'اسناد سفارش تامین' },
{ id: 'SUPPLY', label: 'دپارتمان تامین و انبار' },
{ id: 'FINANCE', label: 'دپارتمان مالی' },
].map((tab) => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${
activeTab === tab.id
? 'bg-blue-600 text-white shadow-sm'
: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700'
}`}
>
{tab.label}
</button>
))}
</div>
{/* Content */}
{loading ? (
<div className="py-20 flex justify-center items-center">
<Spinner className="w-8 h-8 text-blue-600" />
</div>
) : filteredItems.length === 0 ? (
<div className="bg-white dark:bg-slate-900 p-12 text-center rounded-2xl border border-slate-200 dark:border-slate-800">
<CheckCircle2 className="w-12 h-12 text-emerald-500 mx-auto mb-3" />
<h3 className="text-lg font-bold text-slate-900 dark:text-white">هیچ موردی در این بخش وجود ندارد</h3>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-1">تمامی موارد قبلی رسیدگی شده‌اند یا هنوز دستور جدیدی صادر نشده است.</p>
</div>
) : (
<div className="grid gap-6">
{filteredItems.map((item) => (
<div
key={item.id}
className={`bg-white dark:bg-slate-900 rounded-2xl border transition-all overflow-hidden ${
item.status === 'PENDING'
? 'border-amber-300 dark:border-amber-800/60 shadow-md ring-1 ring-amber-400/20'
: 'border-slate-200 dark:border-slate-800 opacity-90'
}`}
>
{/* Card Header */}
<div className="p-5 border-b border-slate-100 dark:border-slate-800/80 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-slate-50/50 dark:bg-slate-800/30">
<div className="flex items-center gap-3">
<div className="p-2.5 rounded-xl bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700">
{getCategoryIcon(item.category)}
</div>
<div>
<h3 className="font-bold text-slate-900 dark:text-white text-base">
{item.title}
</h3>
<div className="flex items-center gap-2 mt-1 text-xs text-slate-500 dark:text-slate-400">
<span>دپارتمان: <strong>{item.department}</strong></span>
<span>•</span>
<span>دسته‌بندی: <strong>{item.category}</strong></span>
<span>•</span>
<span>تاریخ: {new Date(item.createdAt).toLocaleDateString('fa-IR')}</span>
</div>
</div>
</div>
<div>{getStatusBadge(item.status)}</div>
</div>
{/* Card Body */}
<div className="p-5 space-y-4">
{/* Proposed Data Payload Diff */}
<div className="bg-slate-50 dark:bg-slate-950 p-4 rounded-xl border border-slate-200/80 dark:border-slate-800 text-xs font-mono text-slate-800 dark:text-slate-200 overflow-x-auto">
<div className="font-sans font-bold text-xs text-slate-500 dark:text-slate-400 mb-2">
جزئیات داده‌های ارسالی (Payload Details):
</div>
<pre className="whitespace-pre-wrap">{JSON.stringify(item.payload, null, 2)}</pre>
</div>
{/* Simulation / Sandbox Test */}
<div className="bg-blue-50/40 dark:bg-blue-950/20 p-4 rounded-xl border border-blue-100 dark:border-blue-900/40 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div className="space-y-1">
<div className="flex items-center gap-2 font-bold text-sm text-blue-900 dark:text-blue-300">
<Play className="w-4 h-4 text-blue-600" />
<span>محیط شبیه‌سازی و تست میدانی (Sandbox Preview)</span>
</div>
<p className="text-xs text-blue-700/80 dark:text-blue-400">
پیش از تایید می‌توانید نتایج محاسباتی و اثر این اقدام روی سایت و سرویس‌ها را شبیه‌سازی کنید.
</p>
{testResults[item.id] && (
<div className="mt-3 p-3 bg-white dark:bg-slate-900 rounded-lg border border-blue-200 dark:border-blue-800 text-xs text-slate-700 dark:text-slate-300">
<span className="font-bold text-emerald-600 dark:text-emerald-400 block mb-1">
✓ نتیجه شبیه‌سازی موفق:
</span>
<pre className="text-xs">{JSON.stringify(testResults[item.id], null, 2)}</pre>
</div>
)}
</div>
<Button
variant="secondary"
size="sm"
onClick={() => handleRunTest(item.id)}
disabled={testingId === item.id}
icon={<Play className={`w-3.5 h-3.5 ${testingId === item.id ? 'animate-spin' : ''}`} />}
>
{testingId === item.id ? 'در حال شبیه‌سازی...' : 'اجرای تست آزمایشی'}
</Button>
</div>
{/* CEO Feedback & Instructions Field */}
<div className="space-y-2">
<label className="flex items-center gap-1.5 text-xs font-bold text-slate-700 dark:text-slate-300">
<MessageSquare className="w-3.5 h-3.5 text-blue-600" />
<span>توضیحات و بازخورد مدیرعامل (دستورات تایید یا دلایل رد):</span>
</label>
<textarea
rows={2}
value={notes[item.id] || ''}
onChange={(e) => setNotes({ ...notes, [item.id]: e.target.value })}
placeholder="توضیحات، اصلاحات یا شروط لازم را بنویسید (مثلاً: قیمت تایید است ولی از فردا صبح اعمال شود)..."
disabled={item.status !== 'PENDING' || actionLoading === item.id}
className="w-full text-sm p-3 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none transition disabled:opacity-60"
/>
</div>
{/* Action Buttons */}
{item.status === 'PENDING' && (
<div className="flex flex-wrap items-center justify-end gap-3 pt-2">
<Button
variant="danger"
onClick={() => handleDecision(item.id, 'REJECTED')}
disabled={actionLoading === item.id}
icon={<X className="w-4 h-4" />}
>
رد این مورد
</Button>
<Button
variant="primary"
onClick={() => handleDecision(item.id, 'APPROVED')}
disabled={actionLoading === item.id}
icon={<Check className="w-4 h-4" />}
>
تایید و اعمال نهایی در پروداکشن
</Button>
</div>
)}
{item.status !== 'PENDING' && item.ceoNotes && (
<div className="p-3 bg-slate-100 dark:bg-slate-800/60 rounded-xl text-xs text-slate-600 dark:text-slate-300">
<strong>یادداشت ثبت شده مدیرعامل:</strong> {item.ceoNotes}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
);
}
@@ -46,6 +46,8 @@ const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
export interface AdminRouteConfig {
@@ -108,6 +110,8 @@ export const router = createBrowserRouter([
{ path: 'faq/*', element: <FAQManager /> },
{ path: 'menu/*', element: <MenuManager /> },
{ path: 'monitoring/*', element: <MonitoringPage /> },
{ path: 'approvals/*', element: <ApprovalsPage /> },
],
},
+2 -4
View File
@@ -39,10 +39,8 @@ export function getMediaUrl(url?: string | null): string {
}
if (uploadPath) {
const isStage = typeof window !== 'undefined' && window.location.hostname.includes('stage');
const isDev = process.env.NODE_ENV === 'development';
const backendBase = process.env.NEXT_PUBLIC_API_URL?.replace(/\/api\/?$/, '') ||
(isDev ? 'http://localhost:4400' : isStage ? 'https://stageapi.canina.ir' : 'https://api.canina.ir');
// All environments consume production media uploads directly (no duplication)
const backendBase = 'https://api.canina.ir';
return `${backendBase}/uploads/${uploadPath}`;
}