feat(admin): implement 4 admin modules schema, migrations, DTOs and controllers with CSV export
This commit is contained in:
1 parent
5e0541c739
commit
ff3f819fb6
12 files changed
+1584
-157
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;
|
||||
|
||||
+242
-157
@@ -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,90 @@ 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")
|
||||
}
|
||||
@@ -17,6 +17,10 @@ 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 { PrismaModule } from "../prisma/prisma.module";
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { SettingsModule } from "../settings/settings.module";
|
||||
@@ -33,6 +37,10 @@ import { SettingsModule } from "../settings/settings.module";
|
||||
PetsController,
|
||||
SslController,
|
||||
ApiKeysController,
|
||||
CompetitorPricingController,
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
],
|
||||
providers: [
|
||||
AdminService,
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
@@ -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,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");
|
||||
}
|
||||
Reference in new issue
Block a user