diff --git a/.gitea/workflows/publisher-helper.yml b/.gitea/workflows/publisher-helper.yml new file mode 100644 index 00000000..59003bee --- /dev/null +++ b/.gitea/workflows/publisher-helper.yml @@ -0,0 +1,29 @@ +name: Production publisher helper only +on: + push: + branches: + - ops/prod-publisher-helper-20261112 +jobs: + publisher-helper: + runs-on: canina + steps: + - name: Exact reviewed one-file helper release + env: + GITHUB_ACTIONS: 'true' + GITHUB_REF: ${{ github.ref }} + RELEASE_SHA: ${{ github.sha }} + PUBLISHER_HELPER_APPROVED_SHA: ${{ secrets.PUBLISHER_HELPER_APPROVED_SHA }} + run: | + set -eu + [ "$GITHUB_REF" = refs/heads/ops/prod-publisher-helper-20261112 ] + case "$RELEASE_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac + [ "${#RELEASE_SHA}" -eq 40 ] + [ "$RELEASE_SHA" = "$PUBLISHER_HELPER_APPROVED_SHA" ] + export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY= + mkdir -p publisher-src + wget --no-proxy -qO source.tar.gz "https://git.parsaaghayi.ir/parsa/canina/archive/${RELEASE_SHA}.tar.gz" + tar -xzf source.tar.gz --strip-components=1 -C publisher-src + cd publisher-src + export CANINA_EDITORIAL_TEST_SOURCE="$PWD/scripts/publishers/e4c9b52eb040/fixtures" + python3 -m unittest discover -s scripts/publishers/e4c9b52eb040 -p 'test*.py' -v + python3 scripts/publishers/e4c9b52eb040/release_helper.py --sha "$RELEASE_SHA" --approval f5dfb28159010ae043009296006e91bafadd0f62b72681d22063b43d01e81880 diff --git a/scripts/publishers/e4c9b52eb040/fixtures/backend/prisma/schema.prisma b/scripts/publishers/e4c9b52eb040/fixtures/backend/prisma/schema.prisma new file mode 100644 index 00000000..f3a02ce4 --- /dev/null +++ b/scripts/publishers/e4c9b52eb040/fixtures/backend/prisma/schema.prisma @@ -0,0 +1,1022 @@ +generator client { + provider = "prisma-client-js" + binaryTargets = ["native", "linux-musl-openssl-3.0.x"] +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model User { + id String @id @default(uuid()) @db.Uuid + firstName String @map("first_name") @db.VarChar(100) + lastName String @map("last_name") @db.VarChar(100) + email String? @unique @db.VarChar(150) + mobile String @unique @db.VarChar(15) + password String? @db.VarChar(255) + role String @default("User_PetOwner") @db.VarChar(30) + authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz() + stageTestGeneration String? @map("stage_test_generation") @db.Uuid + stageTestSession String? @map("stage_test_session") @db.VarChar(64) + walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2) + charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2) + 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? + paymentTransactions PaymentTransaction[] + tickets Ticket[] + reviews ProductReview[] + blogComments BlogComment[] + supportConversations SupportConversation[] + + @@index([role]) + @@index([createdAt]) + @@map("users") +} + +model SupportConversation { + id String @id @default(uuid()) @db.Uuid + userId String? @map("user_id") @db.Uuid + anonymousBrowserId String? @map("anonymous_browser_id") @db.VarChar(64) + entryPath String? @map("entry_path") @db.VarChar(512) + productSlugs Json? @map("product_slugs") + topics Json? + unanswered Boolean @default(false) + needsFollowup Boolean @default(false) @map("needs_followup") + escalationSignal Boolean @default(false) @map("escalation_signal") + summary String? @db.Text + summaryStatus String @default("pending") @map("summary_status") @db.VarChar(20) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + expiresAt DateTime @map("expires_at") @db.Timestamptz() + + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + messages SupportConversationMessage[] + @@index([userId, updatedAt]) + @@index([anonymousBrowserId, updatedAt]) + @@map("support_conversations") +} + +model SupportConversationMessage { + id String @id @default(uuid()) @db.Uuid + conversationId String @map("conversation_id") @db.Uuid + role String @db.VarChar(20) + content String @db.Text + sequence Int + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade) + @@unique([conversationId, sequence]) + @@index([conversationId, createdAt]) + @@map("support_conversation_messages") +} + +model UserAddress { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + title String @db.VarChar(100) + receptorName String @map("receptor_name") @db.VarChar(150) + phone String @db.VarChar(15) + province String @db.VarChar(100) + city String @db.VarChar(100) + detail String @db.Text + zipCode String @map("zip_code") @db.VarChar(10) + isDefault Boolean @default(false) @map("is_default") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([userId]) + @@map("user_addresses") +} + +model WalletTransaction { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + amount Decimal @db.Decimal(15, 2) + type String @db.VarChar(20) // deposit, withdrawal + status String @db.VarChar(20) // pending, completed, failed + transactionReference String? @unique @map("transaction_reference") @db.VarChar(100) + description String? @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@map("wallet_transactions") +} + +model Media { + id String @id @default(uuid()) @db.Uuid + filename String @db.VarChar(200) + url String @db.Text + mimetype String @db.VarChar(50) + size Int + altText String? @map("alt_text") @db.VarChar(250) + title String? @db.VarChar(250) + description String? @db.Text + caption String? @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@map("media") +} + +model Category { + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(150) + slug String @unique @db.VarChar(150) + description String? @db.Text + parentId String? @map("parent_id") @db.Uuid + metaTitle String? @map("meta_title") @db.VarChar(200) + metaDescription String? @map("meta_description") @db.Text + keywords String? @db.Text + imageUrl String? @map("image_url") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + parent Category? @relation("SubCategories", fields: [parentId], references: [id]) + children Category[] @relation("SubCategories") + products Product[] + + @@map("categories") +} + +model BlogCategory { + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(150) + slug String @unique @db.VarChar(150) + description String? @db.Text + parentId String? @map("parent_id") @db.Uuid + imageUrl String? @map("image_url") @db.Text + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + parent BlogCategory? @relation("BlogSubCategories", fields: [parentId], references: [id], onDelete: Cascade) + children BlogCategory[] @relation("BlogSubCategories") + blogs Blog[] + + @@map("blog_categories") +} + +model BlogTag { + id String @id @default(uuid()) @db.Uuid + name String @unique @db.VarChar(100) + slug String @unique @db.VarChar(100) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + blogs Blog[] + + @@map("blog_tags") +} + +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 + authorTeam String? @map("author_team") @db.VarChar(200) + authorRole String? @map("author_role") @db.VarChar(200) + 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() + contentUpdatedAt DateTime? @map("content_updated_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) + tags BlogTag[] + comments BlogComment[] + + @@index([categoryId]) + @@index([status]) + @@index([publishedAt]) + @@index([featured]) + @@map("blogs") +} + +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() + + 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]) + @@index([productGroup]) + @@index([requiresRx]) + @@index([categorySlug, suitableFor]) + @@map("products") +} + +enum StockStatus { + IN_STOCK + OUT_OF_STOCK + PRE_ORDER + DISCONTINUED +} + +model ProductIngredient { + productId String @map("product_id") @db.Uuid + ingredient String @db.VarChar(150) + ingredientCardId String? @map("ingredient_card_id") @db.Uuid + ingredientCardSlug String? @map("ingredient_card_slug") @db.VarChar(150) + product Product @relation(fields: [productId], references: [id], onDelete: Cascade) + ingredientCard Ingredient? @relation(fields: [ingredientCardId], references: [id], onDelete: SetNull) + + @@id([productId, ingredient]) + @@index([ingredientCardId]) + @@index([ingredientCardSlug]) + @@map("product_ingredients") +} + +model ProductSymptom { + productId String @map("product_id") @db.Uuid + symptom String @db.VarChar(150) + product Product @relation(fields: [productId], references: [id], onDelete: Cascade) + + @@id([productId, symptom]) + @@map("product_symptoms") +} + +model Pet { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + name String @db.VarChar(100) + type String @db.VarChar(10) // سگ, گربه + breed String @db.VarChar(100) + age Int + weight Decimal @db.Decimal(5, 2) + activityLevel String @map("activity_level") @db.VarChar(15) // کم, متوسط, زیاد + imageUrl String? @map("image_url") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + medicalConditions PetMedicalCondition[] + reminders Reminder[] + healthLogs HealthLog[] + prescriptions Prescription[] + tickets Ticket[] + + @@map("pets") +} + +model PetMedicalCondition { + petId String @map("pet_id") @db.Uuid + condition String @db.VarChar(150) + pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade) + + @@id([petId, condition]) + @@map("pet_medical_conditions") +} + +model Reminder { + id String @id @default(uuid()) @db.Uuid + petId String @map("pet_id") @db.Uuid + productId String? @map("product_id") @db.Uuid + title String @db.VarChar(150) + time String @db.VarChar(5) // 08:30 + frequency String @db.VarChar(20) // روزانه, هفتگی + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade) + product Product? @relation(fields: [productId], references: [id], onDelete: SetNull) + completions ReminderCompletion[] + + @@index([petId]) + @@map("reminders") +} + +model ReminderCompletion { + id String @id @default(uuid()) @db.Uuid + reminderId String @map("reminder_id") @db.Uuid + completedDate DateTime @map("completed_date") @db.Date + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + reminder Reminder @relation(fields: [reminderId], references: [id], onDelete: Cascade) + + @@unique([reminderId, completedDate]) + @@index([reminderId, completedDate]) + @@map("reminder_completions") +} + +model HealthLog { + id String @id @default(uuid()) @db.Uuid + petId String @map("pet_id") @db.Uuid + appetite String @db.VarChar(15) + energy String @db.VarChar(15) + digestion String @db.VarChar(15) + note String? @db.Text + loggedDate DateTime @default(now()) @map("logged_date") @db.Date + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade) + + @@map("health_logs") +} + +model Coupon { + id String @id @default(uuid()) @db.Uuid + code String @unique @db.VarChar(50) + type String @default("percent") @db.VarChar(20) // fixed, percent + value Decimal @db.Decimal(15, 2) + minCartValue Decimal? @map("min_cart_value") @db.Decimal(15, 2) + maxCartValue Decimal? @map("max_cart_value") @db.Decimal(15, 2) + maxUses Int? @map("max_uses") + usedCount Int @default(0) @map("used_count") + expiresAt DateTime? @map("expires_at") @db.Timestamptz() + isActive Boolean @default(true) @map("is_active") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + orders Order[] + targets CouponTarget[] + + @@map("coupons") +} + +model CouponTarget { + id String @id @default(uuid()) @db.Uuid + couponId String @map("coupon_id") @db.Uuid + targetType String @map("target_type") @db.VarChar(50) // USER, PET, ROLE, PRODUCT, CATEGORY + targetId String @map("target_id") @db.VarChar(100) // UUID or role name + modifierType String @default("override") @map("modifier_type") @db.VarChar(20) // override, add, subtract + modifierValue Decimal? @map("modifier_value") @db.Decimal(15, 2) + + coupon Coupon @relation(fields: [couponId], references: [id], onDelete: Cascade) + + @@index([targetType, targetId]) + @@map("coupon_targets") +} + +model Order { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + couponId String? @map("coupon_id") @db.Uuid + totalAmount Decimal @map("total_amount") @db.Decimal(15, 2) + charityDonation Decimal @default(0.00) @map("charity_donation") @db.Decimal(15, 2) + isRefill Boolean @default(false) @map("is_refill") + refillIntervalDays Int? @map("refill_interval_days") + status String @default("processing") @db.VarChar(30) // pending_payment, processing, shipped, delivered, cancelled + paymentMethod String? @default("card") @map("payment_method") @db.VarChar(30) + shippingAddress String? @map("shipping_address") @db.Text + trackingNumber String? @unique @map("tracking_number") @db.VarChar(100) + refundStatus String? @default("none") @map("refund_status") @db.VarChar(30) // none, wallet, gateway, partial + refundedAmount Decimal @default(0.00) @map("refunded_amount") @db.Decimal(15, 2) + 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[] + inventoryReservations InventoryReservation[] + + @@index([userId]) + @@index([status]) + @@index([createdAt]) + @@map("orders") +} + +model PaymentTransaction { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + orderId String? @map("order_id") @db.Uuid + amount Decimal @db.Decimal(15, 2) // in Tomans + amountRials BigInt? @map("amount_rials") + gateway String @default("zibal") @db.VarChar(50) + trackId String? @unique @map("track_id") @db.VarChar(100) + refNumber String? @map("ref_number") @db.VarChar(100) + cardNumber String? @map("card_number") @db.VarChar(30) + hashedCardNumber String? @map("hashed_card_number") @db.VarChar(100) + status String @default("PENDING") @db.VarChar(30) // PENDING, PAID, FAILED, VERIFIED + resultCode Int? @map("result_code") + message String? @db.Text + description String? @db.Text + type String @default("ORDER") @db.VarChar(30) // ORDER, WALLET_TOPUP + ipAddress String? @map("ip_address") @db.VarChar(50) + userAgent String? @map("user_agent") @db.Text + rawRequest Json? @map("raw_request") + rawResponse Json? @map("raw_response") + paidAt DateTime? @map("paid_at") @db.Timestamptz() + 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) + + @@index([userId]) + @@index([orderId]) + @@index([trackId]) + @@map("payment_transactions") +} + +model InventoryReservation { + id String @id @default(uuid()) @db.Uuid + orderId String @map("order_id") @db.Uuid + productId String @map("product_id") @db.Uuid + quantity Int @default(1) + expiresAt DateTime @map("expires_at") @db.Timestamptz() + status String @default("ACTIVE") @db.VarChar(20) // ACTIVE, CONSUMED, RELEASED + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + order Order @relation(fields: [orderId], references: [id], onDelete: Cascade) + product Product @relation(fields: [productId], references: [id], onDelete: Cascade) + + @@index([orderId]) + @@index([productId]) + @@index([status]) + @@index([expiresAt]) + @@map("inventory_reservations") +} + +model OrderItem { + id String @id @default(uuid()) @db.Uuid + orderId String @map("order_id") @db.Uuid + productId String? @map("product_id") @db.Uuid + quantity Int + doseQty Decimal? @map("dose_qty") @db.Decimal(10, 2) + doseUnit String? @map("dose_unit") @db.VarChar(50) + + order Order @relation(fields: [orderId], references: [id], onDelete: Cascade) + product Product? @relation(fields: [productId], references: [id], onDelete: SetNull) + + @@map("order_items") +} + +model UiText { + key String @id @db.VarChar(100) + value String @db.Text + + @@map("ui_texts") +} + +model ScientificTerm { + key String @id @db.VarChar(100) + term String @db.VarChar(150) + definition String @db.Text + wikiId String @map("wiki_id") @db.VarChar(50) + metaTitle String? @map("meta_title") @db.VarChar(200) + metaDescription String? @map("meta_description") @db.Text + keywords String? @db.Text + + @@map("scientific_terms") +} + +model HeroBanner { + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(200) + subtitle String? @db.Text + imageUrl String @map("image_url") @db.Text + buttonText String? @map("button_text") @db.VarChar(100) + buttonLink String? @map("button_link") @db.Text + isActive Boolean @default(true) @map("is_active") + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@map("hero_banners") +} + +model VetTestimonial { + id String @id @default(uuid()) @db.Uuid + vetName String @map("vet_name") @db.VarChar(150) + clinicName String? @map("clinic_name") @db.VarChar(150) + imageUrl String? @map("image_url") @db.Text + quote String @db.Text + rating Int @default(5) + isActive Boolean @default(true) @map("is_active") + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@map("vet_testimonials") +} + +model SmartAdvisorRule { + id String @id @default(uuid()) @db.Uuid + condition String @db.VarChar(200) + targetPetType String? @map("target_pet_type") @db.VarChar(50) + recommendedProduct String @map("recommended_product_id") @db.Uuid + reason String @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + product Product @relation(fields: [recommendedProduct], references: [id], onDelete: Cascade) + + @@map("smart_advisor_rules") +} + +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() + + videos Video[] + + @@map("doctors") +} + +model Video { + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(200) + doctor String @db.VarChar(150) + doctorId String? @map("doctor_id") @db.Uuid + duration String @default("02:00") @db.VarChar(20) + thumbnail String? @db.Text + videoUrl String @map("video_url") @db.Text + description String? @db.Text + viewsCount Int @default(0) @map("views_count") + isFeatured Boolean @default(false) @map("is_featured") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + doctorRef Doctor? @relation(fields: [doctorId], references: [id], onDelete: SetNull) + + @@index([doctorId]) + @@map("videos") +} + +model ContactSubmission { + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(100) + phone String @db.VarChar(20) + email String? @db.VarChar(150) + subject String? @db.VarChar(200) + message String @db.Text + status String @default("PENDING") @db.VarChar(20) // PENDING, IN_PROGRESS, RESOLVED + adminNotes String? @map("admin_notes") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@index([status]) + @@index([createdAt]) + @@map("contact_submissions") +} + +model ContactInfo { + id String @id @default(uuid()) @db.Uuid + key String @unique @db.VarChar(100) + title String @db.VarChar(200) + value String @db.Text + icon String? @db.VarChar(100) + order Int @default(0) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + @@map("contact_info") +} + +model Banner { + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(200) + subtitle String? @db.Text + imageUrl String @map("image_url") @db.Text + linkUrl String? @map("link_url") @db.Text + position String @default("home_hero") @db.VarChar(50) + isActive Boolean @default(true) @map("is_active") + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@map("banners") +} + +model Testimonial { + id String @id @default(uuid()) @db.Uuid + authorName String @map("author_name") @db.VarChar(150) + roleTitle String? @map("role_title") @db.VarChar(150) + avatarUrl String? @map("avatar_url") @db.Text + content String @db.Text + rating Int @default(5) + isFeatured Boolean @default(false) @map("is_featured") + isActive Boolean @default(true) @map("is_active") + showOnHome Boolean @default(false) @map("show_on_home") + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@map("testimonials") +} + +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 + benefits String[] @default([]) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + productIngredients ProductIngredient[] + + @@map("ingredients") +} + +model Prescription { + id String @id @default(uuid()) @db.Uuid + userId String? @map("user_id") @db.Uuid + petId String? @map("pet_id") @db.Uuid + fileUrl String @map("file_url") @db.Text + status String @default("PENDING") @db.VarChar(30) + notes String? @db.Text + adminNotes String? @map("admin_notes") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + pet Pet? @relation(fields: [petId], references: [id], onDelete: SetNull) + + @@index([userId]) + @@index([status]) + @@index([createdAt]) + @@map("prescriptions") +} + +model B2BInquiry { + id String @id @default(uuid()) @db.Uuid + companyName String @map("company_name") @db.VarChar(200) + contactName String @map("contact_name") @db.VarChar(150) + email String @db.VarChar(150) + phone String @db.VarChar(20) + businessType String @map("business_type") @db.VarChar(50) + estimatedVolume String? @map("estimated_volume") @db.VarChar(100) + message String @db.Text + status String @default("PENDING") @db.VarChar(30) + adminNotes String? @map("admin_notes") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@index([status]) + @@index([createdAt]) + @@map("b2b_inquiries") +} + +model PartnerAccount { + id String @id @default(uuid()) @db.Uuid + userId String @unique @map("user_id") @db.Uuid + companyName String @map("company_name") @db.VarChar(200) + taxId String? @map("tax_id") @db.VarChar(50) + creditLimit Decimal @default(0.00) @map("credit_limit") @db.Decimal(15, 2) + discountTier String @default("STANDARD") @map("discount_tier") @db.VarChar(30) + status String @default("ACTIVE") @db.VarChar(30) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@map("partner_accounts") +} + +model Setting { + id String @id @default(uuid()) @db.Uuid + category String @db.VarChar(50) + key String @unique @db.VarChar(100) + value Json + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@index([category]) + @@map("settings") +} + +model SmsLog { + id String @id @default(uuid()) @db.Uuid + receptor String @db.VarChar(20) + type String @db.VarChar(50) // OTP, ORDER_CONFIRMATION, SHIPPING_TRACKING, B2B_NOTIFICATION, PET_CARE_REMINDER, TEST, GENERIC + patternId Int? @map("pattern_id") + args String[] @default([]) + messageText String? @map("message_text") @db.Text + status String @db.VarChar(20) // SUCCESS, FAILED, DISABLED + recId String? @map("rec_id") @db.VarChar(50) + errorMessage String? @map("error_message") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@index([receptor]) + @@index([type]) + @@index([status]) + @@index([createdAt]) + @@map("sms_logs") +} + +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() + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + pet Pet? @relation(fields: [petId], references: [id], onDelete: SetNull) + messages TicketMessage[] + + @@index([userId]) + @@index([status]) + @@index([category]) + @@index([createdAt]) + @@map("tickets") +} + +model TicketMessage { + id String @id @default(uuid()) @db.Uuid + ticketId String @map("ticket_id") @db.Uuid + senderId String? @map("sender_id") @db.Uuid + senderRole String @default("USER") @map("sender_role") @db.VarChar(30) // USER, ADMIN, VET_DOCTOR + senderName String @map("sender_name") @db.VarChar(100) + message String @db.Text + attachment String? @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade) + + @@index([ticketId]) + @@index([createdAt]) + @@map("ticket_messages") +} + +model ProductReview { + id String @id @default(uuid()) @db.Uuid + productId String @map("product_id") @db.Uuid + userId String? @map("user_id") @db.Uuid + userName String @map("user_name") @db.VarChar(100) + userPhone String? @map("user_phone") @db.VarChar(20) + rating Int @default(5) + comment String @db.Text + status String @default("PENDING") @db.VarChar(20) // PENDING, APPROVED, REJECTED + adminReply String? @map("admin_reply") @db.Text + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + product Product @relation(fields: [productId], references: [id], onDelete: Cascade) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + + @@index([productId]) + @@index([status]) + @@index([createdAt]) + @@map("product_reviews") +} + +model BlogComment { + id String @id @default(uuid()) @db.Uuid + blogId String @map("blog_id") @db.Uuid + userId String? @map("user_id") @db.Uuid + userName String @map("user_name") @db.VarChar(100) + content String @db.Text + status String @default("PENDING") @db.VarChar(20) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + blog Blog @relation(fields: [blogId], references: [id], onDelete: Cascade) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + + @@index([blogId]) + @@index([status]) + @@map("blog_comments") +} + +model FAQ { + id String @id @default(uuid()) @db.Uuid + question String @db.Text + answer String @db.Text + order Int @default(0) + isActive Boolean @default(true) @map("is_active") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@map("faqs") +} + +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() + + parent MenuItem? @relation("MenuChildren", fields: [parentId], references: [id]) + children MenuItem[] @relation("MenuChildren") + + @@index([menuType]) + @@index([parentId]) + @@map("menu_items") +} + +model ApiKey { + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(150) + keyHash String @unique @map("key_hash") @db.VarChar(255) + keyPrefix String @map("key_prefix") @db.VarChar(30) + scopes String @default("*") @db.Text + status String @default("ACTIVE") @db.VarChar(20) + expiresAt DateTime? @map("expires_at") @db.Timestamptz() + lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz() + description String? @db.VarChar(255) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz() + + @@index([keyHash]) + @@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") +} + diff --git a/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.controller.ts b/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.controller.ts new file mode 100644 index 00000000..2c6b72f6 --- /dev/null +++ b/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.controller.ts @@ -0,0 +1,182 @@ +import { + Controller, + Get, + Post, + Put, + Patch, + Delete, + Body, + Param, + Query, + UseGuards, + Request, +} from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { BlogsService } from "./blogs.service"; +import { JwtAuthGuard } from "../auth/jwt-auth.guard"; +import { + ApiTags, + ApiBearerAuth, + ApiOperation, + ApiQuery, +} from "@nestjs/swagger"; +import { PaginationDto } from "../common/dto/pagination.dto"; + +import { RolesGuard } from "../common/guards/roles.guard"; +import { Roles } from "../common/decorators/roles.decorator"; + +@ApiTags("Admin - مدیریت مقالات (بلاگ)") +@ApiBearerAuth() +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles("Admin", "SUPER_ADMIN") +@Controller("admin/blogs") +export class BlogsController { + constructor(private readonly blogsService: BlogsService) {} + + @Get() + @ApiOperation({ summary: "لیست مقالات" }) + @ApiQuery({ name: "page", required: false }) + @ApiQuery({ name: "limit", required: false }) + @ApiQuery({ name: "search", required: false }) + @ApiQuery({ name: "status", required: false }) + @ApiQuery({ name: "categoryId", required: false }) + async getBlogs( + @Query() + query: PaginationDto & { + status?: string; + categoryId?: string; + tagId?: string; + }, + ) { + return this.blogsService.getBlogs(query); + } + + @Get("authors") + @ApiOperation({ summary: "لیست کاربران برای انتخاب به عنوان نویسنده" }) + async getAuthors() { + const data = await this.blogsService.getAuthors(); + return { success: true, data }; + } + + @Get("categories") + @ApiOperation({ summary: "لیست دسته‌بندی‌های وبلاگ" }) + async getBlogCategories() { + const data = await this.blogsService.getBlogCategories(); + return { success: true, data }; + } + + @Post("categories") + @ApiOperation({ summary: "ایجاد دسته‌بندی جدید برای وبلاگ" }) + async createBlogCategory(@Body() body: Prisma.BlogCategoryCreateInput) { + const data = await this.blogsService.createBlogCategory(body); + return { success: true, data }; + } + + @Put("categories/:id") + @ApiOperation({ summary: "ویرایش دسته‌بندی وبلاگ" }) + async updateBlogCategory( + @Param("id") id: string, + @Body() body: Prisma.BlogCategoryUpdateInput, + ) { + const data = await this.blogsService.updateBlogCategory(id, body); + return { success: true, data }; + } + + @Delete("categories/:id") + @ApiOperation({ summary: "حذف دسته‌بندی وبلاگ" }) + async deleteBlogCategory(@Param("id") id: string) { + await this.blogsService.deleteBlogCategory(id); + return { success: true }; + } + + @Get("tags") + @ApiOperation({ summary: "لیست تگ‌های وبلاگ" }) + async getBlogTags() { + const data = await this.blogsService.getBlogTags(); + return { success: true, data }; + } + + @Post("tags") + @ApiOperation({ summary: "ایجاد تگ جدید برای وبلاگ" }) + async createBlogTag(@Body() body: { name: string; slug?: string }) { + const data = await this.blogsService.createBlogTag(body); + return { success: true, data }; + } + + @Delete("tags/:id") + @ApiOperation({ summary: "حذف تگ وبلاگ" }) + async deleteBlogTag(@Param("id") id: string) { + await this.blogsService.deleteBlogTag(id); + return { success: true }; + } + + @Get(":id") + @ApiOperation({ summary: "دریافت مشخصات یک مقاله" }) + async getBlogById(@Param("id") id: string) { + const data = await this.blogsService.getBlogById(id); + return { success: true, data }; + } + + @Post() + @ApiOperation({ summary: "ایجاد مقاله جدید" }) + async createBlog( + @Body() body: any, + @Request() req: { user: { id: string } }, + ) { + const data = await this.blogsService.createBlog(body, req.user.id); + return { success: true, data }; + } + + @Put(":id") + @ApiOperation({ summary: "ویرایش مقاله" }) + async updateBlog(@Param("id") id: string, @Body() body: any) { + const data = await this.blogsService.updateBlog(id, body); + return { success: true, data }; + } + + @Delete(":id") + @ApiOperation({ summary: "حذف مقاله" }) + async deleteBlog(@Param("id") id: string) { + await this.blogsService.deleteBlog(id); + return { success: true }; + } + + // Blog Comments endpoints + @Get("comments") + @ApiOperation({ summary: "لیست نظرات مقالات" }) + @ApiQuery({ + name: "status", + required: false, + description: "PENDING | APPROVED | REJECTED", + }) + @ApiQuery({ name: "blogId", required: false }) + @ApiQuery({ name: "page", required: false }) + @ApiQuery({ name: "limit", required: false }) + async getComments( + @Query() + query: { + page?: number; + limit?: number; + status?: string; + blogId?: string; + }, + ) { + return this.blogsService.getComments(query); + } + + @Patch("comments/:id/status") + @ApiOperation({ summary: "تغییر وضعیت نظر (تأیید/رد)" }) + async updateCommentStatus( + @Param("id") id: string, + @Body() body: { status: "APPROVED" | "REJECTED" }, + ) { + return this.blogsService.updateCommentStatus(id, body.status); + } + + @Delete("comments/:id") + @ApiOperation({ summary: "حذف نظر" }) + async deleteComment(@Param("id") id: string) { + await this.blogsService.deleteComment(id); + return { success: true }; + } +} diff --git a/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.service.ts b/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.service.ts new file mode 100644 index 00000000..dd584588 --- /dev/null +++ b/scripts/publishers/e4c9b52eb040/fixtures/backend/src/admin/blogs.service.ts @@ -0,0 +1,677 @@ +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, + OnModuleInit, + OnModuleDestroy, + Logger, +} from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { PrismaService } from "../prisma/prisma.service"; +import { PaginationDto } from "../common/dto/pagination.dto"; +import { RevalidationService } from "../common/revalidation/revalidation.service"; + +@Injectable() +export class BlogsService implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(BlogsService.name); + private schedulerTimer: NodeJS.Timeout | null = null; + + constructor( + private prisma: PrismaService, + private revalidationService: RevalidationService, + ) {} + + async onModuleInit() { + await this.seedDefaultCategories(); + // Start background scheduled publishing worker (every 60 seconds) + this.schedulerTimer = setInterval(() => { + this.publishDueScheduledBlogs().catch((err) => { + this.logger.error("Error in publishDueScheduledBlogs worker:", err); + }); + }, 60000); + // Run an initial check on startup + this.publishDueScheduledBlogs().catch(() => {}); + } + + onModuleDestroy() { + if (this.schedulerTimer) { + clearInterval(this.schedulerTimer); + this.schedulerTimer = null; + } + } + + private async seedDefaultCategories() { + try { + const defaultCategories = [ + { name: "تغذیه و رژیم غذایی", slug: "nutrition", order: 1 }, + { name: "سلامت گوارش و متابولیسم", slug: "digestion", order: 2 }, + { name: "مفاصل، استخوان و اسکلت", slug: "joints-bones", order: 3 }, + { name: "پوست، مو و آلرژی", slug: "skin-coat", order: 4 }, + { + name: "ایمنی، پیشگیری و مراقبت بالینی", + slug: "health-prevention", + order: 5, + }, + ]; + + for (const cat of defaultCategories) { + await this.prisma.blogCategory.upsert({ + where: { slug: cat.slug }, + update: { name: cat.name, order: cat.order }, + create: { name: cat.name, slug: cat.slug, order: cat.order }, + }); + } + } catch (err) { + console.warn( + "[BlogsService] Failed to seed default blog categories:", + err, + ); + } + } + + async getBlogs( + query: PaginationDto & { + status?: string; + categoryId?: string; + tagId?: string; + }, + ) { + const page = Number(query.page) || 1; + const limit = Number(query.limit) || 10; + const skip = (page - 1) * limit; + + const where: Prisma.BlogWhereInput = {}; + + if (query.search) { + where.OR = [ + { title: { contains: query.search, mode: "insensitive" } }, + { excerpt: { contains: query.search, mode: "insensitive" } }, + { slug: { contains: query.search, mode: "insensitive" } }, + ]; + } + + if (query.status) { + where.status = query.status; + } + + if (query.categoryId) { + where.categoryId = query.categoryId; + } + + const [data, total] = await Promise.all([ + this.prisma.blog.findMany({ + where, + skip, + take: limit, + orderBy: { createdAt: "desc" }, + include: { + author: { + select: { id: true, firstName: true, lastName: true, email: true }, + }, + category: { select: { id: true, name: true, slug: true } }, + tags: { select: { id: true, name: true, slug: true } }, + _count: { select: { comments: true } }, + }, + }), + this.prisma.blog.count({ where }), + ]); + + return { + data, + meta: { + total, + page, + limit, + lastPage: Math.ceil(total / limit) || 1, + }, + }; + } + + async getBlogById(id: string) { + const blog = await this.prisma.blog.findUnique({ + where: { id }, + include: { + author: { select: { id: true, firstName: true, lastName: true } }, + category: true, + tags: true, + }, + }); + if (!blog) throw new NotFoundException("Blog not found"); + return blog; + } + + async createBlog(data: any, currentUserId: string) { + const { + tagNames, + categoryId, + authorId, + publishedAt, + scheduledAt, + readingTime, + markContentUpdated, + contentUpdatedAt, + } = data; + + const parseOptionalDate = (value: unknown, field: string): Date | null => { + if (value === undefined || value === null || value === "") return null; + const parsed = new Date(value as string | number | Date); + if (!Number.isFinite(parsed.getTime())) { + throw new BadRequestException(`Invalid ${field}`); + } + return parsed; + }; + + const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt"); + const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt"); + const parsedContentUpdatedAt = markContentUpdated + ? new Date() + : parseOptionalDate(contentUpdatedAt, "contentUpdatedAt"); + + // Connect or create tags + const tagConnectOrCreate = []; + if (Array.isArray(tagNames) && tagNames.length > 0) { + for (const tName of tagNames) { + const trimmed = String(tName).trim(); + if (trimmed) { + const slug = trimmed + .toLowerCase() + .replace(/\s+/g, "-") + .replace(/[^\w\u0600-\u06FF-]+/g, ""); + tagConnectOrCreate.push({ + where: { name: trimmed }, + create: { name: trimmed, slug: slug || `tag-${Date.now()}` }, + }); + } + } + } + + const targetAuthorId = authorId || currentUserId; + const now = new Date(); + const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now; + + let finalStatus = data.status || "PUBLISHED"; + let finalIsPublished = + data.isPublished !== undefined ? data.isPublished : true; + let finalPublishedAt = parsedPublishedAt; + + if (isFutureSchedule) { + finalStatus = "SCHEDULED"; + finalIsPublished = false; + finalPublishedAt = null; + } else if (parsedScheduledAt && parsedScheduledAt <= now) { + finalStatus = "PUBLISHED"; + finalIsPublished = true; + finalPublishedAt = parsedScheduledAt; + } else if (!finalPublishedAt && finalStatus === "PUBLISHED") { + finalPublishedAt = now; + } + + const createPayload = { + title: data.title, + slug: data.slug, + content: data.content, + excerpt: data.excerpt, + authorTeam: data.authorTeam, + authorRole: data.authorRole, + imageUrl: data.imageUrl, + imageAlt: data.imageAlt, + imageCaption: data.imageCaption, + metaTitle: data.metaTitle, + metaDescription: data.metaDescription, + keywords: data.keywords, + focusKeywords: data.focusKeywords, + canonicalUrl: data.canonicalUrl, + noIndex: data.noIndex, + noFollow: data.noFollow, + schemaType: data.schemaType, + ogTitle: data.ogTitle, + ogDescription: data.ogDescription, + ogImage: data.ogImage, + status: finalStatus, + isPublished: finalIsPublished, + featured: data.featured, + allowComments: data.allowComments, + showOnHome: data.showOnHome, + homeDisplayMode: data.homeDisplayMode, + relatedProductIds: data.relatedProductIds, + relatedBlogIds: data.relatedBlogIds, + readingTime: readingTime !== undefined ? Number(readingTime) : 3, + publishedAt: finalPublishedAt, + scheduledAt: parsedScheduledAt, + contentUpdatedAt: parsedContentUpdatedAt, + author: { connect: { id: targetAuthorId } }, + ...(categoryId ? { category: { connect: { id: categoryId } } } : {}), + ...(tagConnectOrCreate.length > 0 + ? { tags: { connectOrCreate: tagConnectOrCreate } } + : {}), + } satisfies Prisma.BlogCreateInput; + + const created = await this.prisma.blog.create({ + data: createPayload, + include: { + author: { select: { firstName: true, lastName: true } }, + category: true, + tags: true, + }, + }); + + let cacheRevalidation: "success" | "failed" = "failed"; + try { + const revalidated = await this.revalidationService.revalidateBlog(created.slug); + cacheRevalidation = revalidated ? "success" : "failed"; + } catch (err: any) { + this.logger.warn( + `Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`, + ); + cacheRevalidation = "failed"; + } + + return { + ...created, + cacheRevalidation, + }; + } + + async updateBlog(id: string, data: any) { + const blog = await this.prisma.blog.findUnique({ where: { id } }); + if (!blog) throw new NotFoundException("Blog not found"); + + const { + tagNames, + categoryId, + authorId, + publishedAt, + scheduledAt, + readingTime, + markContentUpdated, + contentUpdatedAt, + expectedUpdatedAt, + } = data; + + const conflict = () => new ConflictException( + "CONCURRENT_MODIFICATION: Blog has been modified by another process", + ); + let expectedTime: number | undefined; + if (expectedUpdatedAt !== undefined) { + // Only accept the millisecond, timezone-qualified ISO token returned by GET + // (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays, + // and its normalization of impossible calendar dates. + const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match( + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/, + ); + if (!match) throw conflict(); + expectedTime = Date.parse(expectedUpdatedAt); + const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`); + if (!Number.isFinite(expectedTime) || + calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` || + Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) { + throw conflict(); + } + } + + const mutableScalarFields = [ + "title", + "slug", + "content", + "excerpt", + "authorTeam", + "authorRole", + "imageUrl", + "imageAlt", + "imageCaption", + "metaTitle", + "metaDescription", + "keywords", + "focusKeywords", + "canonicalUrl", + "noIndex", + "noFollow", + "schemaType", + "ogTitle", + "ogDescription", + "ogImage", + "status", + "isPublished", + "featured", + "allowComments", + "showOnHome", + "homeDisplayMode", + "relatedProductIds", + "relatedBlogIds", + ] as const; + const updatePayload: Prisma.BlogUpdateInput = {}; + for (const field of mutableScalarFields) { + if (data[field] !== undefined) { + (updatePayload as Record)[field] = data[field]; + } + } + + const now = new Date(); + const materialContentFields = [ + "title", + "content", + "excerpt", + "imageUrl", + "imageAlt", + "imageCaption", + ] as const; + const hasMaterialContentChange = materialContentFields.some( + (field) => data[field] !== undefined && data[field] !== blog[field], + ); + if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) { + (updatePayload as Record).contentUpdatedAt = now; + } else if (contentUpdatedAt !== undefined) { + if (contentUpdatedAt === null || contentUpdatedAt === "") { + (updatePayload as Record).contentUpdatedAt = null; + } else { + const parsedContentUpdatedAt = new Date(contentUpdatedAt); + if (!Number.isFinite(parsedContentUpdatedAt.getTime())) { + throw new BadRequestException("Invalid contentUpdatedAt"); + } + (updatePayload as Record).contentUpdatedAt = parsedContentUpdatedAt; + } + } + + Object.assign(updatePayload, { + ...(readingTime !== undefined + ? { readingTime: Number(readingTime) } + : {}), + ...(readingTime !== undefined + ? { readingTime: Number(readingTime) } + : {}), + ...(authorId ? { author: { connect: { id: authorId } } } : {}), + ...(categoryId !== undefined + ? categoryId + ? { category: { connect: { id: categoryId } } } + : { category: { disconnect: true } } + : {}), + }); + + if (scheduledAt !== undefined) { + const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null; + updatePayload.scheduledAt = parsedScheduledAt; + + if (parsedScheduledAt && parsedScheduledAt > now) { + updatePayload.status = "SCHEDULED"; + updatePayload.isPublished = false; + updatePayload.publishedAt = null; + } else if (parsedScheduledAt && parsedScheduledAt <= now) { + updatePayload.status = "PUBLISHED"; + updatePayload.isPublished = true; + updatePayload.publishedAt = parsedScheduledAt; + } + } else if (publishedAt !== undefined) { + updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null; + } + + if (Array.isArray(tagNames)) { + const tagConnectOrCreate = []; + for (const tName of tagNames) { + const trimmed = String(tName).trim(); + if (trimmed) { + const slug = trimmed + .toLowerCase() + .replace(/\s+/g, "-") + .replace(/[^\w\u0600-\u06FF-]+/g, ""); + tagConnectOrCreate.push({ + where: { name: trimmed }, + create: { name: trimmed, slug: slug || `tag-${Date.now()}` }, + }); + } + } + updatePayload.tags = { + set: [], // clear previous relations + connectOrCreate: tagConnectOrCreate, + }; + } + + const include = { + author: { select: { firstName: true, lastName: true } }, + category: true, + tags: true, + }; + // Legacy UI requests without a token intentionally retain last-write-wins. + // Guarded requests claim the row using a DB predicate, not the earlier read. + const updated = expectedTime === undefined + ? await this.prisma.blog.update({ where: { id }, data: updatePayload, include }) + : await this.prisma.$transaction(async (tx) => { + // PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose + // milliseconds. Match the entire represented millisecond, then move + // strictly beyond it (including same-ms writes and clock rollback). + const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1)); + const claim = await tx.blog.updateMany({ + where: { + id, + updatedAt: { + gte: new Date(expectedTime), + lt: new Date(expectedTime + 1), + }, + }, + data: { updatedAt: claimedAt }, + }); + if (claim.count !== 1) throw conflict(); + // The claim holds the row lock until this nested mutation commits. + // Any relation failure rolls back both the claim and all data writes. + return tx.blog.update({ + where: { id }, + data: { ...updatePayload, updatedAt: claimedAt }, + include, + }); + }); + + let cacheRevalidation: "success" | "failed" = "failed"; + try { + const revalidated = await this.revalidationService.revalidateBlog(updated.slug); + cacheRevalidation = revalidated ? "success" : "failed"; + } catch (err: any) { + this.logger.warn( + `Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`, + ); + cacheRevalidation = "failed"; + } + + return { + ...updated, + cacheRevalidation, + }; + } + + async deleteBlog(id: string) { + const blog = await this.prisma.blog.findUnique({ where: { id } }); + if (!blog) throw new NotFoundException("Blog not found"); + const res = await this.prisma.blog.delete({ where: { id } }); + try { + await this.revalidationService.revalidateBlog(blog.slug); + } catch (err: any) { + this.logger.warn( + `Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`, + ); + } + return res; + } + + // Authors (Users who can write) + async getAuthors() { + return this.prisma.user.findMany({ + select: { + id: true, + firstName: true, + lastName: true, + email: true, + role: true, + }, + orderBy: { firstName: "asc" }, + }); + } + + // Blog Categories Management + async getBlogCategories() { + return this.prisma.blogCategory.findMany({ + orderBy: { order: "asc" }, + include: { + parent: true, + children: true, + _count: { select: { blogs: true } }, + }, + }); + } + + async createBlogCategory(data: Prisma.BlogCategoryCreateInput) { + return this.prisma.blogCategory.create({ data }); + } + + async updateBlogCategory(id: string, data: Prisma.BlogCategoryUpdateInput) { + return this.prisma.blogCategory.update({ where: { id }, data }); + } + + async deleteBlogCategory(id: string) { + return this.prisma.blogCategory.delete({ where: { id } }); + } + + // Blog Tags Management + async getBlogTags() { + return this.prisma.blogTag.findMany({ + orderBy: { createdAt: "desc" }, + include: { + _count: { select: { blogs: true } }, + }, + }); + } + + async createBlogTag(data: { name: string; slug?: string }) { + const slug = + data.slug || + data.name + .toLowerCase() + .replace(/\s+/g, "-") + .replace(/[^\w\u0600-\u06FF-]+/g, ""); + return this.prisma.blogTag.create({ + data: { name: data.name, slug: slug || `tag-${Date.now()}` }, + }); + } + + async deleteBlogTag(id: string) { + return this.prisma.blogTag.delete({ where: { id } }); + } + + // Blog Comments Management + async getComments(query: { + page?: number; + limit?: number; + status?: string; + blogId?: string; + }) { + const page = Number(query.page) || 1; + const limit = Number(query.limit) || 20; + const skip = (page - 1) * limit; + + const where: Prisma.BlogCommentWhereInput = {}; + if (query.status) where.status = query.status; + if (query.blogId) where.blogId = query.blogId; + + const [data, total] = await Promise.all([ + this.prisma.blogComment.findMany({ + where, + skip, + take: limit, + orderBy: { createdAt: "desc" }, + include: { + blog: { select: { title: true, slug: true } }, + user: { select: { firstName: true, lastName: true, mobile: true } }, + }, + }), + this.prisma.blogComment.count({ where }), + ]); + + return { + data, + meta: { total, page, limit, lastPage: Math.ceil(total / limit) || 1 }, + }; + } + + async updateCommentStatus(id: string, status: "APPROVED" | "REJECTED") { + const comment = await this.prisma.blogComment.findUnique({ + where: { id }, + include: { blog: { select: { slug: true } } }, + }); + if (!comment) throw new NotFoundException("Comment not found"); + const updated = await this.prisma.blogComment.update({ + where: { id }, + data: { status }, + }); + if (comment.blog?.slug) { + await this.revalidationService.revalidateBlog(comment.blog.slug); + } + return updated; + } + + async deleteComment(id: string) { + const comment = await this.prisma.blogComment.findUnique({ + where: { id }, + include: { blog: { select: { slug: true } } }, + }); + if (!comment) throw new NotFoundException("Comment not found"); + const res = await this.prisma.blogComment.delete({ where: { id } }); + if (comment.blog?.slug) { + await this.revalidationService.revalidateBlog(comment.blog.slug); + } + return res; + } + + /** + * Publishes blogs that have reached their scheduled publication date + */ + async publishDueScheduledBlogs(): Promise { + const now = new Date(); + const dueBlogs = await this.prisma.blog.findMany({ + where: { + status: "SCHEDULED", + scheduledAt: { lte: now }, + }, + select: { + id: true, + slug: true, + title: true, + scheduledAt: true, + }, + }); + + if (!dueBlogs || dueBlogs.length === 0) { + return 0; + } + + this.logger.log( + `Found ${dueBlogs.length} due scheduled blog(s) to publish automatically.`, + ); + + let publishedCount = 0; + for (const blog of dueBlogs) { + try { + const publishDate = blog.scheduledAt || now; + await this.prisma.blog.update({ + where: { id: blog.id }, + data: { + status: "PUBLISHED", + isPublished: true, + publishedAt: publishDate, + }, + }); + + publishedCount++; + this.logger.log( + `Successfully published scheduled blog [${blog.title}] (${blog.slug})`, + ); + + // Immediate cache & sitemap revalidation + await this.revalidationService.revalidateBlog(blog.slug); + } catch (err: any) { + this.logger.error( + `Failed to publish scheduled blog [${blog.id}] (${blog.slug}): ${err?.message}`, + ); + } + } + + return publishedCount; + } +} diff --git a/scripts/publishers/e4c9b52eb040/fixtures/frontend/admin-panel/src/pages/Blogs.tsx b/scripts/publishers/e4c9b52eb040/fixtures/frontend/admin-panel/src/pages/Blogs.tsx new file mode 100644 index 00000000..aa649d26 --- /dev/null +++ b/scripts/publishers/e4c9b52eb040/fixtures/frontend/admin-panel/src/pages/Blogs.tsx @@ -0,0 +1,1824 @@ +import { +Calendar, +CheckCircle2, +Clock, +Edit2, +Eye, +FileText, +FolderTree, +Globe, +Image as ImageIcon, +Layers, +Pin, +Plus, +Search, +Share2, +ShoppingBag, +Sparkles, +Tag, +Trash2, +X, +XCircle +} from 'lucide-react'; +import { useCallback,useEffect,useState } from 'react'; +import { toast } from 'react-hot-toast'; +import { useSearchParams } from 'react-router-dom'; +import Button from '../components/ui/Button'; +import ConfirmModal from '../components/ui/ConfirmModal'; +import MediaSelector from '../components/ui/MediaSelector'; +import Modal from '../components/ui/Modal'; +import Pagination from '../components/ui/Pagination'; +import RichTextEditor from '../components/ui/RichTextEditor'; +import Spinner from '../components/ui/Spinner'; +import api,{ BASE_DOMAIN } from '../services/api'; + +export interface BlogCategory { + id: string; + name: string; + slug: string; + parentId?: string | null; + children?: BlogCategory[]; + parent?: BlogCategory | null; +} + +export interface BlogTag { + id: string; + name: string; + slug: string; +} + +export interface AuthorUser { + id: string; + firstName: string; + lastName: string; + email?: string; + role?: string; +} + +export interface ProductSimple { + id: string; + nameFa: string; + slug: string; + imageUrl?: string; + priceValue?: number; +} + +export interface BlogPost { + id: string; + title: string; + slug: string; + content: string; + excerpt?: string; + authorId?: string; + authorTeam?: string; + authorRole?: string; + contentUpdatedAt?: string | null; + author?: { + id?: string; + firstName?: string; + lastName?: string; + email?: string; + }; + categoryId?: string | null; + category?: BlogCategory | null; + tags?: BlogTag[]; + imageUrl?: string; + imageAlt?: string; + imageCaption?: string; + metaTitle?: string; + metaDescription?: string; + keywords?: string; + canonicalUrl?: string; + ogTitle?: string; + ogDescription?: string; + ogImage?: string; + status: 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED'; + isPublished: boolean; + publishedAt?: string | null; + scheduledAt?: string | null; + readingTime: number; + featured: boolean; + allowComments: boolean; + viewCount: number; + showOnHome: boolean; + relatedProductIds: string[]; + relatedBlogIds: string[]; + createdAt?: string; + updatedAt?: string; + _count?: { + comments: number; + }; +} + +export default function Blogs() { + const [searchParams, setSearchParams] = useSearchParams(); + const [blogs, setBlogs] = useState([]); + const [categories, setCategories] = useState([]); + const [tagsList, setTagsList] = useState([]); + const [authors, setAuthors] = useState([]); + const [allProducts, setAllProducts] = useState([]); + + const [isLoading, setIsLoading] = useState(true); + const [search, setSearch] = useState(() => searchParams.get('search') || ''); + const [statusFilter, setStatusFilter] = useState(() => searchParams.get('status') || 'ALL'); + const [categoryFilter, setCategoryFilter] = useState(() => searchParams.get('categoryId') || 'ALL'); + const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1); + const [totalPages, setTotalPages] = useState(1); + const limit = 10; + + // Active Tab inside Blog Form Modal + const [activeFormTab, setActiveFormTab] = useState<'content' | 'media' | 'seo' | 'relations' | 'publishing'>('content'); + + // Modals state + const [isModalOpen, setIsModalOpen] = useState(false); + const [isLivePreviewOpen, setIsLivePreviewOpen] = useState(false); + const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false); + const [mediaSelectTarget, setMediaSelectTarget] = useState<'featured' | 'ogImage'>('featured'); + const [editingBlog, setEditingBlog] = useState(null); + const [deleteTargetId, setDeleteTargetId] = useState(null); + + // Category & Tag Management Modal + const [isCatTagModalOpen, setIsCatTagModalOpen] = useState(false); + const [newCatName, setNewCatName] = useState(''); + const [newCatSlug, setNewCatSlug] = useState(''); + const [newCatParentId, setNewCatParentId] = useState(''); + const [newTagName, setNewTagName] = useState(''); + + // Tag Input in Edit Form + const [currentTagInput, setCurrentTagInput] = useState(''); + + // Auto-slug manual override flag + const [isSlugManuallyEdited, setIsSlugManuallyEdited] = useState(false); + + // Unsaved Local Draft State + const [hasSavedDraft, setHasSavedDraft] = useState(false); + + const updateUrlParams = (paramsObj: Record) => { + const current = Object.fromEntries(searchParams.entries()); + const merged = { ...current, ...paramsObj }; + const cleaned: Record = {}; + Object.entries(merged).forEach(([k, v]) => { + if (v !== undefined && v !== null && String(v).trim() !== '' && String(v) !== 'ALL') { + cleaned[k] = String(v); + } + }); + setSearchParams(cleaned, { replace: true }); + }; + + const [formData, setFormData] = useState({ + title: '', + slug: '', + content: '', + excerpt: '', + authorId: '', + authorTeam: '', + authorRole: '', + markContentUpdated: false, + categoryId: '', + tagNames: [] as string[], + imageUrl: '', + imageAlt: '', + imageCaption: '', + metaTitle: '', + metaDescription: '', + keywords: '', + focusKeywords: '', + canonicalUrl: '', + noIndex: false, + noFollow: false, + schemaType: 'BlogPosting', + ogTitle: '', + ogDescription: '', + ogImage: '', + status: 'PUBLISHED' as 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED', + isPublished: true, + publishedAt: '', + scheduledAt: '', + readingTime: 3, + featured: false, + allowComments: true, + showOnHome: false, + relatedProductIds: [] as string[], + relatedBlogIds: [] as string[], + }); + + // Calculate reading time automatically based on word count + const calculateReadingTime = (htmlContent: string) => { + const textOnly = htmlContent.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); + const wordCount = textOnly ? textOnly.split(' ').length : 0; + const wordsPerMinute = 200; + const minutes = Math.max(1, Math.ceil(wordCount / wordsPerMinute)); + return minutes; + }; + + // Auto-generate slug from title + const generateSlug = (text: string) => { + return text + .trim() + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^\w\u0600-\u06FF-]+/g, '') + .substring(0, 180); + }; + + const handleTitleChange = (newTitle: string) => { + setFormData((prev) => { + const updated = { ...prev, title: newTitle }; + if (!isSlugManuallyEdited && (!editingBlog || !prev.slug)) { + updated.slug = generateSlug(newTitle); + } + return updated; + }); + }; + + const handleContentChange = (newContent: string) => { + setFormData((prev) => ({ + ...prev, + content: newContent, + readingTime: calculateReadingTime(newContent), + })); + }; + + const openModal = (blog: BlogPost | null = null) => { + setActiveFormTab('content'); + setIsSlugManuallyEdited(false); + if (blog) { + setEditingBlog(blog); + updateUrlParams({ modal: 'edit', blogId: blog.id }); + setFormData({ + title: blog.title, + slug: blog.slug, + content: blog.content || '', + excerpt: blog.excerpt || '', + authorId: blog.authorId || (blog.author?.id || ''), + authorTeam: blog.authorTeam || '', + authorRole: blog.authorRole || '', + markContentUpdated: false, + categoryId: blog.categoryId || '', + tagNames: blog.tags ? blog.tags.map((t) => t.name) : [], + imageUrl: blog.imageUrl || '', + imageAlt: blog.imageAlt || '', + imageCaption: blog.imageCaption || '', + metaTitle: blog.metaTitle || '', + metaDescription: blog.metaDescription || '', + keywords: blog.keywords || '', + focusKeywords: (blog as any).focusKeywords || '', + canonicalUrl: blog.canonicalUrl || '', + noIndex: Boolean((blog as any).noIndex), + noFollow: Boolean((blog as any).noFollow), + schemaType: (blog as any).schemaType || 'BlogPosting', + ogTitle: blog.ogTitle || '', + ogDescription: blog.ogDescription || '', + ogImage: blog.ogImage || '', + status: blog.status || (blog.isPublished ? 'PUBLISHED' : 'DRAFT'), + isPublished: blog.isPublished !== false, + publishedAt: blog.publishedAt ? new Date(blog.publishedAt).toISOString().slice(0, 16) : '', + scheduledAt: blog.scheduledAt ? new Date(blog.scheduledAt).toISOString().slice(0, 16) : '', + readingTime: blog.readingTime || calculateReadingTime(blog.content || ''), + featured: Boolean(blog.featured), + allowComments: blog.allowComments !== false, + showOnHome: Boolean(blog.showOnHome), + relatedProductIds: blog.relatedProductIds || [], + relatedBlogIds: blog.relatedBlogIds || [], + }); + } else { + setEditingBlog(null); + updateUrlParams({ modal: 'create', blogId: undefined }); + setFormData({ + title: '', + slug: '', + content: '', + excerpt: '', + authorId: authors[0]?.id || '', + authorTeam: '', + authorRole: '', + markContentUpdated: false, + categoryId: '', + tagNames: [], + imageUrl: '', + imageAlt: '', + imageCaption: '', + metaTitle: '', + metaDescription: '', + keywords: '', + focusKeywords: '', + canonicalUrl: '', + noIndex: false, + noFollow: false, + schemaType: 'BlogPosting', + ogTitle: '', + ogDescription: '', + ogImage: '', + status: 'PUBLISHED', + isPublished: true, + publishedAt: new Date().toISOString().slice(0, 16), + scheduledAt: '', + readingTime: 3, + featured: false, + allowComments: true, + showOnHome: false, + relatedProductIds: [], + relatedBlogIds: [], + }); + } + setIsModalOpen(true); + }; + const DRAFT_STORAGE_KEY = 'canina_admin_blog_draft_v1'; + + // Check for saved draft on mount + useEffect(() => { + try { + const saved = localStorage.getItem(DRAFT_STORAGE_KEY); + if (saved) { + const parsed = JSON.parse(saved); + if (parsed && (parsed.title || parsed.content)) { + setHasSavedDraft(true); + } + } + } catch { + // ignore + } + }, []); + + // Auto-save unsaved blog form content + useEffect(() => { + if (!isModalOpen) return; + if (editingBlog) return; // Don't auto-save over existing published blogs + if (!formData.title && !formData.content) return; + + const timer = setTimeout(() => { + try { + localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(formData)); + setHasSavedDraft(true); + } catch { + // ignore quota + } + }, 1000); + return () => clearTimeout(timer); + }, [formData, isModalOpen, editingBlog]); + + const restoreDraft = () => { + try { + const saved = localStorage.getItem(DRAFT_STORAGE_KEY); + if (saved) { + const parsed = JSON.parse(saved); + setFormData((prev) => ({ ...prev, ...parsed })); + toast.success('پیش‌نویس ذخیره‌شده با موفقیت بازیابی شد'); + setHasSavedDraft(false); + } + } catch { + toast.error('خطا در بازیابی پیش‌نویس'); + } + }; + + const discardDraft = () => { + try { + localStorage.removeItem(DRAFT_STORAGE_KEY); + setHasSavedDraft(false); + toast.success('پیش‌نویس محلی پاک شد'); + } catch { + // ignore + } + }; + + const closeModal = () => { + setIsModalOpen(false); + updateUrlParams({ modal: undefined, blogId: undefined }); + }; + + const fetchAuxiliaryData = useCallback(async () => { + try { + const [catsRes, tagsRes, authorsRes, prodsRes] = await Promise.allSettled([ + api.get('/admin/blogs/categories'), + api.get('/admin/blogs/tags'), + api.get('/admin/blogs/authors'), + api.get('/admin/products', { params: { limit: 100 } }), + ]); + + if (catsRes.status === 'fulfilled' && catsRes.value.data?.data) { + setCategories(catsRes.value.data.data); + } + if (tagsRes.status === 'fulfilled' && tagsRes.value.data?.data) { + setTagsList(tagsRes.value.data.data); + } + if (authorsRes.status === 'fulfilled' && authorsRes.value.data?.data) { + setAuthors(authorsRes.value.data.data); + } + if (prodsRes.status === 'fulfilled' && prodsRes.value.data?.data) { + setAllProducts(prodsRes.value.data.data); + } + } catch (error) { + console.error('Failed to load auxiliary blog data', error); + } + }, []); + + const fetchBlogs = useCallback(async () => { + try { + setIsLoading(true); + const params: any = { page, limit, search }; + if (statusFilter !== 'ALL') params.status = statusFilter; + if (categoryFilter !== 'ALL') params.categoryId = categoryFilter; + + const res = await api.get('/admin/blogs', { params }); + if (res.data?.data) { + const blogList: BlogPost[] = res.data.data; + setBlogs(blogList); + setTotalPages(res.data.meta?.lastPage || 1); + + const modalParam = searchParams.get('modal'); + const blogId = searchParams.get('blogId'); + if (modalParam === 'create') { + openModal(null); + } else if (modalParam === 'edit' && blogId) { + const found = blogList.find((b) => b.id === blogId); + if (found) openModal(found); + } + } + } catch (err) { + console.error(err); + toast.error('خطا در دریافت لیست مقالات'); + } finally { + setIsLoading(false); + } + }, [page, search, statusFilter, categoryFilter, searchParams]); + + useEffect(() => { + fetchAuxiliaryData(); + }, [fetchAuxiliaryData]); + + useEffect(() => { + const timer = setTimeout(() => { + fetchBlogs(); + }, 400); + return () => clearTimeout(timer); + }, [fetchBlogs]); + + // Tag helper + const addTag = (tagText: string) => { + const trimmed = tagText.trim().replace(/^#/, ''); + if (trimmed && !formData.tagNames.includes(trimmed)) { + setFormData((prev) => ({ ...prev, tagNames: [...prev.tagNames, trimmed] })); + } + setCurrentTagInput(''); + }; + + const removeTag = (tagToRemove: string) => { + setFormData((prev) => ({ + ...prev, + tagNames: prev.tagNames.filter((t) => t !== tagToRemove), + })); + }; + + const handleSave = async (e: React.FormEvent) => { + e.preventDefault(); + if (!formData.title.trim()) { + toast.error('عنوان مقاله نمی‌تواند خالی باشد'); + return; + } + if (!formData.slug.trim()) { + toast.error('اسلاگ (Slug) مقاله الزامی است'); + return; + } + if (formData.imageUrl && !formData.imageAlt?.trim()) { + setActiveFormTab('media'); + toast.error('لطفاً متن جایگزین تصویر (Alt) را در تب تصویر وارد کنید (برای سئو الزامی است)'); + return; + } + + try { + const payload = { + ...formData, + isPublished: formData.status === 'PUBLISHED', + scheduledAt: formData.scheduledAt ? new Date(formData.scheduledAt).toISOString() : null, + }; + + if (editingBlog) { + await api.put(`/admin/blogs/${editingBlog.id}`, payload); + toast.success('مقاله با موفقیت ویرایش و بروزرسانی شد'); + } else { + await api.post('/admin/blogs', payload); + toast.success('مقاله جدید با موفقیت ذخیره شد'); + try { + localStorage.removeItem(DRAFT_STORAGE_KEY); + setHasSavedDraft(false); + } catch { + // ignore + } + } + closeModal(); + fetchBlogs(); + fetchAuxiliaryData(); + } catch (error) { + console.error('Save failed', error); + toast.error('خطا در ذخیره مقاله'); + } + }; + + const confirmDelete = async () => { + if (!deleteTargetId) return; + try { + await api.delete(`/admin/blogs/${deleteTargetId}`); + toast.success('مقاله با موفقیت حذف شد'); + fetchBlogs(); + } catch (error) { + console.error('Delete failed', error); + toast.error('خطا در حذف مقاله'); + } finally { + setDeleteTargetId(null); + } + }; + + // Quick Category creation + const handleCreateCategory = async (e: React.FormEvent) => { + e.preventDefault(); + if (!newCatName.trim()) return; + try { + const slug = newCatSlug.trim() || generateSlug(newCatName); + await api.post('/admin/blogs/categories', { + name: newCatName.trim(), + slug, + ...(newCatParentId ? { parent: { connect: { id: newCatParentId } } } : {}), + }); + toast.success('دسته‌بندی جدید ایجاد شد'); + setNewCatName(''); + setNewCatSlug(''); + setNewCatParentId(''); + fetchAuxiliaryData(); + } catch { + toast.error('خطا در ایجاد دسته‌بندی'); + } + }; + + // Quick Tag creation + const handleCreateTag = async (e: React.FormEvent) => { + e.preventDefault(); + if (!newTagName.trim()) return; + try { + await api.post('/admin/blogs/tags', { name: newTagName.trim() }); + toast.success('برچسب جدید ایجاد شد'); + setNewTagName(''); + fetchAuxiliaryData(); + } catch { + toast.error('خطا در ایجاد تگ'); + } + }; + + // Helper status badge + const renderStatusBadge = (status: string, _isPublished: boolean, scheduledAt?: string | null) => { + switch (status) { + case 'PUBLISHED': + return ( + + + منتشر شده + + ); + case 'SCHEDULED': { + const dateStr = scheduledAt ? new Date(scheduledAt).toLocaleDateString('fa-IR') : ''; + return ( + + + {dateStr ? `در صف: ${dateStr}` : 'زمان‌بندی شده'} + + ); + } + case 'ARCHIVED': + return ( + + + بایگانی + + ); + case 'DRAFT': + default: + return ( + + + پیش‌نویس + + ); + } + }; + + return ( +
+ {/* Header Bar */} +
+
+

+
+ +
+ مدیریت جامع وبلاگ و دانشنامه سلامت +

+

+ سیستم انتشار مقالات علمی، ادیتور پیشرفته چندرسانه‌ای، مدیریت دسته‌بندی و سئو +

+
+
+ + +
+
+ + {/* Filter Bar */} +
+
+ + { + setSearch(e.target.value); + setPage(1); + }} + className="w-full pl-4 pr-11 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 text-xs sm:text-sm outline-none" + /> +
+ +
+ + + +
+
+ + {/* Main Table */} +
+
+ + + + + + + + + + + + + + {isLoading ? ( + + + + ) : blogs.length === 0 ? ( + + + + ) : ( + blogs.map((blog) => ( + + + + + + + + + + )) + )} + +
تصویرعنوان و خلاصه مقالهدسته‌بندی و تگ‌هانویسندهزمان مطالعهوضعیتعملیات
+ +
+ هیچ مقاله‌ای یافت نشد. +
+ {blog.imageUrl ? ( + {blog.imageAlt + ) : ( +
+ +
+ )} +
+
+ {blog.featured && ( + + + ویژه + + )} + {blog.title} +
+

+ {blog.excerpt || 'بدون چکیده'} +

+ + /{blog.slug} + +
+ {blog.category ? ( + + {blog.category.name} + + ) : ( + دسته‌بندی نشده + )} +
+ {blog.tags?.slice(0, 2).map((t) => ( + + #{t.name} + + ))} +
+
+ {blog.author?.firstName ? `${blog.author.firstName} ${blog.author.lastName || ''}` : 'نامشخص'} + +
+ + {blog.readingTime || 3} دقیقه +
+
+ + {(blog.viewCount || 0).toLocaleString('fa-IR')} بازدید +
+
{renderStatusBadge(blog.status, blog.isPublished, blog.scheduledAt)} +
+
+
+
+ + {!isLoading && totalPages > 1 && ( +
+ +
+ )} +
+ + {/* Main Blog Create/Edit Modal */} + {isModalOpen && ( + + + +
+ + +
+
+ } + > +
+ {/* Draft Recovery Banner */} + {hasSavedDraft && !editingBlog && ( +
+
+
+ یک پیش‌نویس ذخیره‌نشده از آخرین ویرایش شما در مرورگر موجود است. +
+
+ + +
+
+ )} + + {/* Form Tabs */} +
+ {[ + { id: 'content', label: '۱. محتوا و متن', icon: FileText }, + { id: 'media', label: '۲. تصویر شاخص و رسانه', icon: ImageIcon }, + { id: 'publishing', label: '۳. زمان‌بندی و انتشار', icon: Calendar }, + { id: 'seo', label: '۴. سئو و سوشال', icon: Globe }, + { id: 'relations', label: '۵. آیتم‌های مرتبط', icon: ShoppingBag }, + ].map((tab) => { + const Icon = tab.icon; + return ( + + ); + })} +
+ +
+ {/* TAB 1: CONTENT */} + {activeFormTab === 'content' && ( +
+
+
+ + handleTitleChange(e.target.value)} + placeholder="مثال: راهنمای جامع مراقبت و تغذیه سگ‌های ژرمن شپرد" + className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-bold" + /> +
+ +
+ + { + setIsSlugManuallyEdited(true); + setFormData({ ...formData, slug: e.target.value }); + }} + placeholder="german-shepherd-care-guide" + className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-mono" + /> +
+
+ + {/* Excerpt */} +
+ +