Compare commits

...
Author SHA1 Message Date
parsa aghaei 0ea6c6d271 feat: enrich all site content with Canina pharma research data
- Add 20 new products to frontend products.ts (total 29 products)
- Enrich existing 9 product descriptions with biochemical/clinical details
- Add new blog articles with real content from research document
- Update UI texts with Canina brand history (1984 founding, IFS/HACCP)
- Add 9 new scientific terms (Ca:P, D3, BARF, biotin, taurine, etc.)
- Expand INGREDIENTS_WIKI with collagens, biotin, taurine entries
- Add new medical options (heart disease, parasites) to SmartAdvisor
2026-07-11 13:34:22 +03:30
parsa aghaei 140872c888 fix: resolve Hero image CORS, button contrast, floating labels, footer border + refactor product seeder with full catalog data from JSON + add barcode/buyPrice/productGroup fields to Product model 2026-07-11 13:21:30 +03:30
parsa aghaei 3dedc89ee1 تغییرات کلی در backend و frontend 2026-07-11 12:30:17 +03:30
parsa a74f4bda48 design: implement heuristic UX, WCAG accessibility, touch targets, and cognitive load enhancements 2026-07-10 18:42:11 +03:30
parsa 756cb749b2 design: implement landing page UI/UX improvements based on Senior UI/UX audit 2026-07-10 18:31:23 +03:30
parsa 71f5ac2fa6 fix: resolve unique constraint bug in prisma seeders and run products/home seeders successfully 2026-07-10 18:20:05 +03:30
parsa 6db28f6231 feat: add scripts/open-browsers.js to automatically open services on dev startup 2026-07-10 17:40:35 +03:30
parsa 1c07efcc91 design: update color palette to match official brand and add gold top banner 2026-07-10 17:30:01 +03:30
parsa f69537a688 feat: rename brand from canina to canino across codebase 2026-07-10 16:32:31 +03:30
parsa 2851ef8a25 feat: complete backend swagger annotations, admin pages pagination, and frontend application fixes 2026-07-10 16:13:52 +03:30
parsa 24137beb32 docs: complete swagger annotations for auth, home, blogs and wiki endpoints 2026-06-12 23:30:22 +03:30
parsa e09adc03c3 fix: change SSR fetch URLs from 4000 to 4001 2026-06-12 23:21:56 +03:30
parsa dcfc4acae4 fix: restore wiki to dictionary, create dynamic blog pages and backend wiki CRUD 2026-06-12 23:14:21 +03:30
parsa 945c007a79 feat: complete app democking, fix types, add blogs api 2026-06-12 22:53:57 +03:30
parsa 6027e635db feat: implement backend auth and fix pet profile payload 2026-06-12 22:37:35 +03:30
parsa 82ab454647 Fix Admin panel categories modal, add error handling, enforce cursor-pointer globally 2026-06-12 21:57:09 +03:30
parsa 69502fc380 feat: implement advanced reports, pagination for all tables, global settings, and discounts modules 2026-06-12 16:28:06 +03:30
parsa a7ebb8d792 feat: complete admin panel major functionalities including responsive layout, recharts, custom modals, inline editing, and loading states 2026-06-12 16:19:57 +03:30
parsa ee041d4e52 fix: resolve Hyper-V reserved port collisions and Tailwind v4 CSS 2026-06-12 14:18:55 +03:30
parsa fa7333e93f fix: update postcss config and lockfiles 2026-06-12 14:09:30 +03:30
parsa 29ab7f4141 fix: change frontend and backend ports to resolve EACCES 3000 2026-06-12 14:05:50 +03:30
parsa d430a341f0 fix: resolve unclosed block in index.css 2026-06-12 14:00:36 +03:30
parsa 15ffe8a0e6 chore: clean up leftover react project files in root 2026-06-12 13:56:27 +03:30
parsa 07b52f464c feat: add root workspace runner 2026-06-12 13:51:10 +03:30
parsa 0b698859d9 fix: resolve linter error in products page 2026-06-12 13:41:06 +03:30
parsa beb8317fad feat: add order management page 2026-06-12 13:36:54 +03:30
parsa 060dc39fdd feat: add product catalog management page 2026-06-12 13:36:17 +03:30
parsa aea6fa4127 feat: add user management page 2026-06-12 13:35:42 +03:30
parsa 4dc8786847 feat: add admin login page 2026-06-12 13:35:05 +03:30
parsa 222581c6a3 feat: setup admin layout and base routing 2026-06-12 13:34:25 +03:30
parsa 7fcfbda8cd chore: configure tailwindcss for admin-panel 2026-06-12 13:30:25 +03:30
parsa 95887738ea chore: initialize admin-panel react project 2026-06-12 13:25:34 +03:30
parsa 344be17b52 docs: add comprehensive developer documentation 2026-06-12 13:02:27 +03:30
parsa 95760d78b5 fix: remove invalid lucide-react imports 2026-06-12 01:33:39 +03:30
parsa c4966136d7 fix: update import paths for lib folders in components 2026-06-12 01:32:10 +03:30
parsa 14bf2953ab feat: SEO metadata for static pages (search, wiki, blog) 2026-06-12 01:27:43 +03:30
parsa 88c3752238 feat: auto-generated sitemap and robots.txt 2026-06-12 01:27:02 +03:30
parsa 700f93e418 feat: dynamic SEO metadata and JSON-LD for products 2026-06-12 01:26:32 +03:30
parsa bf1b11d6a9 feat: global SEO settings and JSON-LD in frontend layout 2026-06-12 01:25:34 +03:30
parsa 0fa65c0802 feat: backend database changes for advanced SEO fields 2026-06-12 01:25:08 +03:30
parsa ee0b8a5ff8 feat: auxiliary pages migrated to Next.js (Blog, Videos, Track, Success) 2026-06-12 01:17:03 +03:30
parsa 976dfcd610 feat: interactive pages migrated to Next.js (Dashboard, Checkout, Profile, Wiki) 2026-06-12 01:10:52 +03:30
parsa 3de0408e6f feat: core pages and components migrated to Next.js (Home, Shop, Product) 2026-06-12 01:08:04 +03:30
parsa 72d2a5600a feat: layout and overlays migrated to Next.js 2026-06-12 01:04:03 +03:30
parsa c5a1b8e5d2 feat: nextjs setup and configuration (lib, store, css, assets) 2026-06-12 01:00:54 +03:30
parsa eff6c00a9c feat: complete phase 2 mock removal and db seed 2026-06-12 00:58:10 +03:30
parsa 40d6393b16 feat(frontend): integrate UI state with real backend endpoints 2026-06-12 00:29:17 +03:30
parsa 4b69932409 chore: save initial uncommitted changes 2026-06-12 00:21:03 +03:30
247 changed files with 25606 additions and 10825 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
node_modules
dist
# dist
.env
.git
.dockerignore
+1 -1
View File
@@ -1,6 +1,6 @@
# نقشه جامع اتصال به بک‌بند (Comprehensive Backend Integration Map) 🏗️
این سند حاوی معماری دقیق، فهرست کامل نقاط اتصال (API Endpoints)، کامنت‌های مکان‌نما در کد (TODO Markers)، و تعاریف رسمی تمامی تایپ‌های ورودی (Inputs) و خروجی (Outputs) پلتفرم درمانی و فروشگاهی کانی‌نا ایران است.
این سند حاوی معماری دقیق، فهرست کامل نقاط اتصال (API Endpoints)، کامنت‌های مکان‌نما در کد (TODO Markers)، و تعاریف رسمی تمامی تایپ‌های ورودی (Inputs) و خروجی (Outputs) پلتفرم درمانی و فروشگاهی کانینو ایران است.
---
+5 -5
View File
@@ -1,6 +1,6 @@
# طرح‌واره پایگاه داده کانی‌نا ایران (Canina Iran Database Schema) 🗄️
# طرح‌واره پایگاه داده کانینو ایران (Canino Iran Database Schema) 🗄️
این سند ساختار دقیق جداول، فیلدها، نوع داده‌ها (Datatypes)، روابط بین موجودیت‌ها (ERD Relations) و ایندکس‌های پیشنهادی را برای راه‌اندازی پایگاه داده نهایی سیستم کانی‌نا طراحی و ارائه می‌کند. جهت انعطاف‌پذیری توسعه، پیاده‌سازی هم بر اساس **پایگاه داده رابطه‌ای (PostgreSQL / MySQL)** و هم **پایگاه داده مستندمحور/سندمراقبتی (NoSQL - MongoDB / Firestore)** مدلسازی شده است.
این سند ساختار دقیق جداول، فیلدها، نوع داده‌ها (Datatypes)، روابط بین موجودیت‌ها (ERD Relations) و ایندکس‌های پیشنهادی را برای راه‌اندازی پایگاه داده نهایی سیستم کانینو طراحی و ارائه می‌کند. جهت انعطاف‌پذیری توسعه، پیاده‌سازی هم بر اساس **پایگاه داده رابطه‌ای (PostgreSQL / MySQL)** و هم **پایگاه داده مستندمحور/سندمراقبتی (NoSQL - MongoDB / Firestore)** مدلسازی شده است.
---
@@ -63,7 +63,7 @@ CREATE TABLE wallet_transactions (
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- ۴. جدول کاتالوگ محصولات کانی‌نا (products)
-- ۴. جدول کاتالوگ محصولات کانینو (products)
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
art_no VARCHAR(20) UNIQUE NOT NULL,
@@ -250,7 +250,7 @@ CREATE INDEX idx_reminder_completions_ref ON reminder_completions(reminder_id, c
"reminders": [
{
"id": "REM-001",
"productId": "6472f8d38bfcb8234eccb611", // مکمل آرتروفیت کانینا فیزیکی جهت کسر انبار پت
"productId": "6472f8d38bfcb8234eccb611", // مکمل آرتروفیت کانینو فیزیکی جهت کسر انبار پت
"title": "مصرف قرص مفصل‌ساز Canhydrox",
"time": "08:30",
"frequency": "روزانه",
@@ -297,7 +297,7 @@ CREATE INDEX idx_reminder_completions_ref ON reminder_completions(reminder_id, c
"dosageLogic": "به ازای هر ۵ کیلوگرم وزن، ۲ قرص روزانه تجویز بالا گردد.",
"symptoms": ["درد مفاصل", "سختی در بلند شدن", "لنگیدن"],
"suitableFor": "هر دو",
"image": "https://www.canina.de/media/89/34/9a/1715077271/Petvital-Canhydrox-111421-V1-Canina-100g_600x600.webp"
"image": "https://www.canina.de/media/89/34/9a/1715077271/Petvital-Canhydrox-111421-V1-Canino-100g_600x600.webp"
}
```
+2 -11
View File
@@ -1,14 +1,5 @@
# Build stage
FROM node:22-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginxinc/nginx-unprivileged:alpine
COPY --from=build /app/dist /usr/share/nginx/html
FROM docker.arvancloud.ir/nginxinc/nginx-unprivileged:alpine
COPY dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
+2 -2
View File
@@ -1,7 +1,7 @@
# پلتفرم کانی‌نا ایران (Canina Iran Platform) 🐾
# پلتفرم کانینو ایران (Canino Iran Platform) 🐾
### لندینگ، فروشگاه تخصصی و پرونده سلامت الکترونیک پت (نمایندگی رسمی دارویی Canina Pharma)
پلتفرم **کانی‌نا ایران** یک برنامه جامع تحت وب (SPA/PWA) مجهز به بردهای تعاملی و ابزارهای بهداشتی-دامپزشکی است که با هدف ارتقای سلامت حیوانات خانگی و دسترسی آسان‌تر به مکمل‌های دارویی گرید فوق‌ارگانیک و دارویی کمپانی والای **Canina pharma GmbH آلمان** توسعه یافته است.
پلتفرم **کانینو ایران** یک برنامه جامع تحت وب (SPA/PWA) مجهز به بردهای تعاملی و ابزارهای بهداشتی-دامپزشکی است که با هدف ارتقای سلامت حیوانات خانگی و دسترسی آسان‌تر به مکمل‌های دارویی گرید فوق‌ارگانیک و دارویی کمپانی والای **Canina pharma GmbH آلمان** توسعه یافته است.
---
+21 -4
View File
@@ -1,30 +1,47 @@
FROM node:22-alpine AS builder
FROM docker.arvancloud.ir/library/node:22-alpine AS builder
RUN apk add --no-cache openssl
WORKDIR /app
# Copy package files
COPY package*.json ./
# Set NPM registry mirror
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set fetch-retries 10
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retry-maxtimeout 120000
# Install all dependencies (including devDependencies)
RUN npm ci
RUN for i in 1 2 3 4 5; do npm ci && exit 0 || (echo "Retry $i in 10s..." && sleep 10); done; exit 1
# Copy the rest of the application
COPY . .
# Build the application (compiles TypeScript to dist folder)
# We also generate prisma client here if prisma schema is present.
RUN npx prisma generate
RUN npm run build
# Production image
FROM node:22-alpine
FROM docker.arvancloud.ir/library/node:22-alpine
RUN apk add --no-cache openssl
WORKDIR /app
# Copy only package files
COPY package*.json ./
# Set NPM registry mirror
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set fetch-retries 10
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retry-maxtimeout 120000
# Install only production dependencies
RUN npm ci --only=production
RUN for i in 1 2 3 4 5; do npm ci --only=production && exit 0 || (echo "Retry $i in 10s..." && sleep 10); done; exit 1
# Copy built artifacts from the builder stage
COPY --from=builder /app/dist ./dist
+29
View File
@@ -18,6 +18,7 @@
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.22.0",
"bcrypt": "^6.0.0",
"bcryptjs": "^3.0.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"helmet": "^8.2.0",
@@ -35,8 +36,10 @@
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/multer": "^2.1.0",
"@types/node": "^24.12.4",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^7.0.0",
@@ -2832,6 +2835,13 @@
"@types/node": "*"
}
},
"node_modules/@types/bcryptjs": {
"version": "2.4.6",
"resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/body-parser": {
"version": "1.19.6",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
@@ -2989,6 +2999,16 @@
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
"license": "MIT"
},
"node_modules/@types/multer": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.1.0.tgz",
"integrity": "sha512-zYZb0+nJhOHtPpGDb3vqPjwpdeGlGC157VpkqNQL+UU2qwoacoQ7MpsAmUptI/0Oa127X32JzWDqQVEXp2RcIA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/express": "*"
}
},
"node_modules/@types/node": {
"version": "24.12.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz",
@@ -4340,6 +4360,15 @@
"node": ">= 18"
}
},
"node_modules/bcryptjs": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
"license": "BSD-3-Clause",
"bin": {
"bcrypt": "bin/bcrypt"
}
},
"node_modules/bl": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+4 -1
View File
@@ -29,6 +29,7 @@
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.22.0",
"bcrypt": "^6.0.0",
"bcryptjs": "^3.0.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"helmet": "^8.2.0",
@@ -46,8 +47,10 @@
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/multer": "^2.1.0",
"@types/node": "^24.12.4",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^7.0.0",
@@ -85,6 +88,6 @@
"testEnvironment": "node"
},
"prisma": {
"seed": "ts-node prisma/seed.ts"
"seed": "ts-node prisma/seed.ts && ts-node prisma/seed-products.ts && ts-node prisma/seed-home.ts"
}
}
+134 -7
View File
@@ -11,8 +11,9 @@ 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)
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)
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)
@@ -23,6 +24,7 @@ model User {
walletTransactions WalletTransaction[]
pets Pet[]
orders Order[]
blogs Blog[]
@@map("users")
}
@@ -61,31 +63,92 @@ model WalletTransaction {
@@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
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 Blog {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(200)
slug String @unique @db.VarChar(200)
content String @db.Text
authorId String @map("author_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text
metaTitle String? @map("meta_title") @db.VarChar(200)
metaDescription String? @map("meta_description") @db.Text
keywords String? @db.Text
isPublished Boolean @default(true) @map("is_published")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamptz()
author User @relation(fields: [authorId], references: [id])
@@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)
name String @db.VarChar(200)
scientificTagline String? @map("scientific_tagline") @db.VarChar(250)
description String @db.Text
shortDescription String? @map("short_description") @db.Text
category String @db.VarChar(100)
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)
buyPrice Decimal @default(0) @map("buy_price") @db.Decimal(15, 2)
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
suitableFor String @map("suitable_for") @db.VarChar(15) // سگ, گربه, هر دو
imageUrl String @map("image_url") @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
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
ingredients ProductIngredient[]
category Category @relation(fields: [categoryId], references: [id])
ingredientList ProductIngredient[]
symptoms ProductSymptom[]
reminders Reminder[]
orderItems OrderItem[]
advisorRules SmartAdvisorRule[]
@@index([categorySlug])
@@index([suitableFor])
@@index([productGroup])
@@map("products")
}
@@ -184,15 +247,36 @@ model HealthLog {
model Coupon {
id String @id @default(uuid()) @db.Uuid
code String @unique @db.VarChar(50)
discountValue Decimal @map("discount_value") @db.Decimal(15, 2)
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
@@ -234,9 +318,52 @@ model UiText {
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)
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")
}
+105
View File
@@ -0,0 +1,105 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
console.log('Start seeding blogs...');
// Create a default admin author if not exists
let admin = await prisma.user.findFirst({ where: { role: 'admin' } });
if (!admin) {
admin = await prisma.user.create({
data: {
id: "123e4567-e89b-12d3-a456-426614174000",
firstName: 'مدیر',
lastName: 'سیستم',
mobile: '09000000000',
role: 'admin',
password: 'hashed_password' // just dummy
}
});
}
const blogs = [
{
title: 'اهمیت کلسیم در رشد استخوان توله‌سگ‌ها',
slug: 'calcium-importance-for-puppies',
content: `<p>کلسیم یکی از مهم‌ترین مواد معدنی برای رشد ساختار استخوانی است. توله‌سگ‌ها در ماه‌های اول زندگی به کلسیم بیشتری نیاز دارند تا اسکلت‌بندی محکمی داشته باشند.</p>
<h2>نسبت Ca:P (کلسیم به فسفر)</h2>
<p>نسبت ایده‌آل کلسیم به فسفر در رژیم توله‌سگ‌ها <strong>۱.۲:۱ تا ۱.۵:۱</strong> است. عدم تعادل در این نسبت می‌تواند منجر به ناهنجاری‌های استخوانی مانند پاهای پرانتزی و دیسپلازی هیپ شود. <strong>پودر پوسته تخم مرغ کانینو</strong> با ۳۶٪ کلسیم خالص و فسفر ۰.۱٪ بهترین گزینه برای تنظیم این نسبت است.</p>
<h2>نقش ویتامین D3 در جذب کلسیم</h2>
<p>ویتامین D3 (کوله‌کلسیفرول) جذب کلسیم از روده را تا ۳۰٪ افزایش می‌دهد. <strong>مصرف همزمان ویتامین D2 (ارگوکلسیفرول) با D3 مجاز نیست</strong> زیرا این دو با یکدیگر رقابت کرده و جذب مؤثر را کاهش می‌دهند.</p>
<h2>محصولات توصیه شده برای توله‌سگ‌ها</h2>
<ul>
<li><strong>CANHYDROX GAG:</strong> از ۸ هفتگی برای استحکام اسکلت و دندان‌ها (۲ قرص به ازای ۱۰kg تا ۱۵ ماهگی)</li>
<li><strong>Welpenmilch:</strong> شیر جایگزین مادر از روز اول (غنی از تورین و ویتامین‌ها)</li>
<li><strong>Welpenbrei:</strong> فرنی پروتئین بالا از هفته سوم</li>
<li><strong>Eierschalenpulver:</strong> پودر پوسته تخم مرغ برای تنظیم نسبت Ca:P</li>
</ul>
<h2>هشدار برای نژادهای بزرگ</h2>
<p>نژادهای بزرگ (ژرمن شپرد، لابرادور، گلدن رتریور و ...) مستعد دیسپلازی هیپ و مشکلات مفصلی هستند. مصرف مکمل‌های ارتوپدی مانند <strong>Flexan</strong> (کلاژن هیدرولیز شده با صدف لب سبز) از دوران توله‌گی توصیه می‌شود.</p>`
imageUrl: '/images/wiki/calcium.webp',
metaTitle: 'اهمیت کلسیم در رشد سگ',
metaDescription: 'چرا کلسیم برای توله سگ ها مهم است؟',
keywords: 'کلسیم, سگ, رشد',
authorId: admin.id
},
{
title: 'ویتامین‌های گروه B و سلامت پوست و مو',
slug: 'b-vitamins-and-skin-health',
content: `<p>ویتامین‌های B Complex (B1، B2، B6، B12 و ...) کوآنزیم‌های ضروری چرخه کربس هستند که انرژی سلولی (ATP) را تولید می‌کنند. کمبود این ویتامین‌ها منجر به خستگی مزمن، ریزش مو و التهابات پوستی می‌شود.</p>
<h2>هر ویتامین B چه می‌کند؟</h2>
<ul>
<li><strong>B1 (تیامین):</strong> متابولیسم کربوهیدرات‌ها و عملکرد سیستم عصبی</li>
<li><strong>B2 (ریبوفلاوین):</strong> تولید انرژی و سلامت پوست</li>
<li><strong>B6 (پیریدوکسین):</strong> سنتز پروتئین و تولید گلبول قرمز</li>
<li><strong>B7 (بیوتین / ویتامین H):</strong> کراتین‌سازی مو و پنجه - <strong>Biotin-Tabs کانینو</strong> با ۱ میلیون میکروگرم بیوتین در کیلوگرم، قوی‌ترین دوز موجود در بازار است</li>
<li><strong>B12 (کوبالامین):</strong> خونسازی و عملکرد عصبی</li>
</ul>
<h2>نقش بیوتین در سلامت پوشش</h2>
<p>بیوتین کوآنزیم کربوکسیلازهای مسئول سنتز اسیدهای چرب و گلوکونئوژنز است. <strong>ریزش مو و شکنندگی پنجه</strong> از نشانه‌های کلاسیک کمبود بیوتین هستند. قرص بیوتین کانینو با تأثیر از هفته چهارم، پوشش براق و پنجه‌های محکم را تضمین می‌کند.</p>
<h2>محصولات تقویت‌کننده پوست و مو</h2>
<ul>
<li><strong>Biotin-Tabs:</strong> دوز بالای بیوتین برای ریزش مو</li>
<li><strong>Lachs-Öl:</strong> روغن سالمون با امگا ۳ (EPA/DHA) ۱۴٪</li>
<li><strong>Seealgen:</strong> جلبک دریایی ارگانیک برای تقویت رنگدانه</li>
<li><strong>Marine-Ölmischung PREMIUM:</strong> ترکیب روغن آرگان و گل رز با آنتی‌اکسیدان قوی</li>
</ul>
<h2>توصیه تغذیه‌ای</h2>
<p>برای سلامت پوست و مو، ترکیب <strong>Biotin-Tabs</strong> + <strong>Lachs-Öl</strong> بهترین نتیجه را می‌دهد. بیوتین از داخل کراتین‌سازی را تقویت کرده و امگا ۳ التهاب پوستی را کاهش می‌دهد.</p>`
imageUrl: '/images/wiki/vitamins.webp',
metaTitle: 'ویتامین ب در سلامت پت',
metaDescription: 'تاثیر ویتامین بی بر پوست و مو',
keywords: 'ویتامین B, پوست, مو, گربه, سگ',
authorId: admin.id
}
];
for (const blog of blogs) {
await prisma.blog.upsert({
where: { slug: blog.slug },
update: blog,
create: blog,
});
}
console.log('Seeding blogs finished.');
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
+117
View File
@@ -0,0 +1,117 @@
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
const prisma = new PrismaClient();
async function main() {
const filePath = path.join('C:', 'Users', 'parsa', '.gemini', 'antigravity-ide', 'brain', '951ff86f-dc4e-4670-9a62-78e1f9c8c223', 'scratch', 'products.json');
console.log(`Reading from: ${filePath}`);
const productsData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
for (const item of productsData) {
const artNo = item.article_number || item.article_number_100g || 'UNKNOWN-' + Math.floor(Math.random()*1000);
const name = item.product_name_fa || 'محصول نامشخص';
const scientificTagline = item.product_name_en || null;
const description = item.description || '';
const shortDescription = item.analytical_constituents || null;
let priceStr = item.price || item.price_100g || item.price_90tab || '0';
priceStr = priceStr.replace(/,/g, '').replace(' T', '').replace('T', '').trim();
const priceValue = parseFloat(priceStr) || 0;
const priceDisplay = item.price || item.price_100g || item.price_90tab || 'نامشخص';
let packageSize = 100;
let unit = "g";
const vw = item.volume_weight || '';
if (vw.includes('ml')) unit = "ml";
else if (vw.includes('g')) unit = "g";
else if (vw.includes('tab')) unit = "tablet";
const sizeMatch = vw.match(/(\d+)/);
if (sizeMatch) {
packageSize = parseFloat(sizeMatch[1]);
}
const dosageLogic = item.feeding_recommendation || item.feeding_advice || '';
let suitableFor = "سگ";
const textToCheck = (name + " " + description).toLowerCase();
const hasCat = textToCheck.includes("گربه") || textToCheck.includes("katzen");
const hasDog = textToCheck.includes("سگ") || textToCheck.includes("hund") || textToCheck.includes("توله");
if (hasCat && hasDog) {
suitableFor = "هر دو";
} else if (hasCat) {
suitableFor = "گربه";
} else if (hasDog) {
suitableFor = "سگ";
} else {
suitableFor = "هر دو";
}
const category = "مکمل‌ تخصصی";
const categorySlug = "specialized-supplements";
const imageUrl = "/products/product-placeholder.png";
const createdProduct = await prisma.product.upsert({
where: { artNo },
update: {
name,
scientificTagline,
description,
shortDescription,
priceValue,
priceDisplay,
packageSize,
unit,
dosageLogic,
suitableFor
},
create: {
artNo,
name,
scientificTagline,
description,
shortDescription,
category,
categorySlug,
priceValue,
priceDisplay,
unit,
packageSize,
dosageLogic,
suitableFor,
imageUrl
}
});
if (item.ingredients) {
const ingredientsArr = item.ingredients.split('،').map((i: string) => i.trim()).filter(Boolean);
for (const ing of ingredientsArr) {
await prisma.productIngredient.upsert({
where: {
productId_ingredient: {
productId: createdProduct.id,
ingredient: ing.substring(0, 150)
}
},
update: {},
create: {
productId: createdProduct.id,
ingredient: ing.substring(0, 150)
}
});
}
}
console.log(`Upserted ${name}`);
}
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+107
View File
@@ -0,0 +1,107 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
console.log('Seeding Home Page Components...');
// 1. Seed Hero Banners
const banners = [
{
title: 'محصولات تخصصی مراقبت از مفاصل',
subtitle: 'برای سگ‌های مسن و پرتحرک، تضمین سلامت و شادابی با کلاژن فعال',
imageUrl: '/images/slider/slide1.webp', // Assuming we have these in public/images
buttonText: 'مشاهده محصولات مفاصل',
buttonLink: '/shop/joints',
order: 1,
isActive: true,
},
{
title: 'ویتامین‌های ضروری برای رشد توله سگ‌ها',
subtitle: 'رشد کامل استخوان‌ها و تقویت سیستم ایمنی از ماه اول',
imageUrl: '/images/slider/slide2.webp',
buttonText: 'خرید ویتامین توله',
buttonLink: '/shop/puppy',
order: 2,
isActive: true,
}
];
await prisma.heroBanner.deleteMany(); // Reset
for (const b of banners) {
await prisma.heroBanner.create({ data: b });
}
console.log('Seeded Hero Banners.');
// 2. Seed Vet Testimonials
const vets = [
{
vetName: 'دکتر علیرضا رضایی',
clinicName: 'کلینیک دامپزشکی پایتخت',
imageUrl: '/images/vets/vet1.webp',
quote: 'مکمل‌های مفصلی کانینو از نظر سرعت جذب و اثربخشی در سگ‌های نژاد بزرگ بی‌نظیر هستند. ما نتایج فوق‌العاده‌ای روی دیسپلازی هیپ مشاهده کردیم.',
rating: 5,
order: 1,
isActive: true,
},
{
vetName: 'دکتر سارا شمس',
clinicName: 'بیمارستان دامپزشکی تهران',
imageUrl: '/images/vets/vet2.webp',
quote: 'من همیشه برای ریزش مو و مشکلات پوستی گربه‌ها، قرص‌های مخمر و بیوتین کانینو را تجویز می‌کنم. نتایج معمولاً در کمتر از ۳ هفته قابل مشاهده است.',
rating: 5,
order: 2,
isActive: true,
}
];
await prisma.vetTestimonial.deleteMany();
for (const v of vets) {
await prisma.vetTestimonial.create({ data: v });
}
console.log('Seeded Vet Testimonials.');
// 3. Seed Smart Advisor Rules
// We need to fetch an actual product ID to link
const product = await prisma.product.findFirst();
if (product) {
const rules = [
{
condition: 'ریزش مو شدید',
targetPetType: 'سگ',
reason: 'حاوی بیوتین و روی بالا برای توقف ریزش مو و براق شدن پوشش',
recommendedProduct: product.id,
},
{
condition: 'لنگش یا ضعف مفاصل',
targetPetType: 'سگ',
reason: 'غنی از گلوکزامین، کندرویتین و پودر صدف سبز نیوزلندی برای ترمیم غضروف',
recommendedProduct: product.id,
},
{
condition: 'بی‌اشتهایی',
targetPetType: 'گربه',
reason: 'مخمر خالص و ویتامین‌های گروه B برای افزایش اشتها و شادابی',
recommendedProduct: product.id,
}
];
await prisma.smartAdvisorRule.deleteMany();
for (const r of rules) {
await prisma.smartAdvisorRule.create({ data: r });
}
console.log('Seeded Smart Advisor Rules.');
} else {
console.log('No products found in DB! Skipping Smart Advisor Rules seeding.');
}
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+269
View File
@@ -0,0 +1,269 @@
[
{
"name": "Canina Ballaststoff Mix",
"description": "فیبر میکس کانینا حاوی منابع فیبر گیاهی است که به طور روزانه رژیم غذایی خام پت را تقویت می کند. این فیبرها به عنوان پری بیوتیک برای فلور پایدار روده مهم هستند. حرکت طبیعی روده را تحریک کرده، مدفوع را حجیم می کند و تاثیر مثبتی بر تخلیه غدد مقعدی دارد. سیستم ایمنی روده را تقویت کرده و انرژی باکتری های روده بزرگ را تامین می کند. بدون غلات و پروتئین حیوانی بوده و برای آلرژی غذایی مناسب است.",
"ingredients": "تفاله سیب، پودر یونجه سبز، فیبر نخود فرنگی، تفاله هویج، کیک بذر کتان، کمپلکس الیگوساکارید و بتاگلوکان، مخمر آبجو، کنگر فرنگی، خاک دیاتومه، روغن کلزا، کربنات کلسیم. مواد تشکیل دهنده: پروتئین خام 11.9%، چربی خام 6.3%، فیبر خام 27.3%.",
"usage_and_dosage": "مناسب برای توله سگ ها، بچه گربه ها و حیوانات مسن، باردار و شیرده. پودر را با کمی آب گرم مخلوط کنید. مقدار مصرف: 1 گرم به ازای هر کیلوگرم وزن بدن، حداکثر 15 گرم در روز.",
"variants": [
{ "size": "100g", "art_no": "144006", "barcode": "4027565144006", "buy_price": 1550000, "sell_price": 3100000 }
]
},
{
"name": "Canina CANHYDROX GAG",
"description": "ویژه سگ های بزرگ و سنگین وزن برای درمان بافت همبند، مفاصل، استخوان ها، تاندون ها و غضروف. ایده آل برای سگ های در مرحله رشد، مسن و سگ های با عملکرد بالا. از تشکیل کالوس و استحکام استخوان پشتیبانی کرده و ظرفیت بافر مفاصل را بهبود می بخشد.",
"ingredients": "30% تری کلسیم فسفات، هیدروکسی آپاتیت، مخمر آبجو، 10% پودر صدف سبز، جلبک دریایی. ویتامین سی، ویتامین ایی، سلنیوم و متیونین.",
"usage_and_dosage": "سگ های جوان از 8 هفتگی: برای پیشگیری 2 قرص و برای اندام های بدشکل 4 قرص به ازای هر 10 کیلوگرم تا 15 ماهگی. سگ های مسن و عملکردی: 4 قرص به ازای هر 10 کیلوگرم. پس از شکستگی: 4 قرص برای دوره نقاهت.",
"variants": [
{ "size": "100g (60 Tablets)", "art_no": "123490", "barcode": "4027565123490", "buy_price": 4240000, "sell_price": 8480000 }
]
},
{
"name": "Canina Eierschalenpulver",
"description": "پودر پوسته تخم مرغ برای تامین کلسیم، سلامت دندان ها و فعالیت عضلات. جایگزین پودر استخوان برای سگ های دارای آلرژی به پروتئین گوشت. مناسب برای تکمیل وعده های غذایی گوشتی خام (B.A.R.F).",
"ingredients": "100% پوسته تخم مرغ آسیاب شده. خاکستر خام 96%، کلسیم 36%، فسفر 0.1%.",
"usage_and_dosage": "0.2 گرم به ازای هر کیلوگرم وزن بدن، حداکثر 16 گرم برای هر حیوان در روز.",
"variants": [
{ "size": "250g", "art_no": "120208", "barcode": "4027565120208", "buy_price": 1460000, "sell_price": 2920000 }
]
},
{
"name": "Canina FLEXAN",
"description": "پشتیبانی از سیستم اسکلتی عضلانی، مفاصل متحرک و تناسب اندام. پپتیدهای کلاژن غضروف را بازسازی کرده و پودر صدف لب سبز بافت همبند را تقویت می کند.",
"ingredients": "90% کلاژن، 10% پودر گوشت صدف لب سبز. پروتئین خام 94.2%.",
"usage_and_dosage": "تغذیه روزانه برای توله سگ ها تا مسن. 2 گرم به ازای هر 10 کیلوگرم وزن بدن، حداکثر 15 گرم در روز.",
"variants": [
{ "size": "150g", "art_no": "710003", "barcode": "4027565710003", "buy_price": 3230000, "sell_price": 6460000 }
]
},
{
"name": "Canina HERZ VITAL",
"description": "برای سگ ها و گربه های مسن دارای نارسایی قلبی. ال کارنیتین بر تامین انرژی قلب و عضلات تاثیر گذاشته و نشاط و رفاه حیوان را افزایش می دهد.",
"ingredients": "دکستروز، مخمر غیر فعال، زالزالک. حاوی ال کارنیتین.",
"usage_and_dosage": "نصف قاشق چایخوری به ازای هر 10 کیلوگرم وزن بدن، حداکثر 3 قاشق چایخوری. به مدت 6 ماه همراه غذا تجویز شود.",
"variants": [
{ "size": "100ml", "art_no": "112036", "barcode": "4027565112036", "buy_price": 4285000, "sell_price": 8570000 }
]
},
{
"name": "Canina IMMUN-BOOSTER Paste",
"description": "بازیابی و نقاهت تغذیه ای با چگالی انرژی بالا. ایمونوگلوبولین های آغوز سیستم دفاعی را تقویت کرده و برای نقاهت پس از زایمان، تمرین و استرس عالی است. انتروکوک فاسیوم فلور روده را سالم نگه می دارد.",
"ingredients": "روغن های گیاهی، 20% پودر آغوز، شکر انگور. ویتامین آ، د3، ایی و تثبیت کننده فلور روده.",
"usage_and_dosage": "توله ها 0.25 میلی لیتر، سگ های متوسط 0.5-1 میلی لیتر، سگ های بزرگ 1-4 میلی لیتر در روز تا زمان بهبودی کامل.",
"variants": [
{ "size": "15ml", "art_no": "700707", "barcode": "4027565700707", "buy_price": 2990000, "sell_price": 5980000 }
]
},
{
"name": "Canina Katzenmilch",
"description": "غذای کامل جایگزین شیر مادر با ویتامین ها و مواد معدنی. مناسب بچه گربه های بی مادر از 1 روزگی، گربه های مسن، بیمار و شیرده.",
"ingredients": "لاکتوز، پودر آب پنیر، چربی نارگیل، روغن ماهی، پروتئین 30%. غنی از ویتامین ها و 100 میلی گرم تورین.",
"usage_and_dosage": "1 قسمت شیر با 3 قسمت آب ولرم مخلوط شود. به بچه گربه های 1 تا 14 روزه هر 2 ساعت تغذیه شود.",
"variants": [
{ "size": "150g", "art_no": "230808", "barcode": "4027565230808", "buy_price": 2315000, "sell_price": 4630000 }
]
},
{
"name": "Canina Lachsöl",
"description": "روغن ماهی سالمون 100% خالص سرشار از اسیدهای چرب امگا 3 (EPA و DHA). متابولیسم را تنظیم کرده و از بازسازی پوست و رشد مو پشتیبانی می کند.",
"ingredients": "100% روغن ماهی سالمون. اسیدهای چرب چند غیراشباع 56%، امگا 3 (14%) و امگا 6 (11%).",
"usage_and_dosage": "2 میلی لیتر به ازای هر 10 کیلوگرم وزن بدن، حداکثر 10 میلی لیتر در روز مخلوط با خوراک.",
"variants": [
{ "size": "250ml", "art_no": "151004", "barcode": "4027565150007", "buy_price": 2240000, "sell_price": 4480000 }
]
},
{
"name": "Canina Marine-Ölmischung PREMIUM",
"description": "ترکیبی هماهنگ از روغن های خوراکی که متابولیسم ارگانیسم را ارتقا می دهد. از کمبود مواد مغذی در رژیم های خام جلوگیری می کند. روغن آرگان و گل رز به عنوان آنتی اکسیدان و بازسازی کننده عمل می کنند.",
"ingredients": "روغن ماهی، روغن گردو، روغن آرگان، روغن دانه گل رز. چربی خام 100%.",
"usage_and_dosage": "قابل افزودن به تمام وعده های غذایی برای بهینه سازی ویتامین ها و اسیدهای چرب امگا.",
"variants": [
{ "size": "250ml", "art_no": "153008", "barcode": "4027565153008", "buy_price": 4270000, "sell_price": 8540000 }
]
},
{
"name": "Canina Moortränke",
"description": "عصاره پیت حاوی مواد هومیک برای محافظت از غشاهای مخاطی و سیستم ایمنی روده. ایده آل برای نفخ، اسهال، پس از درمان آنتی بیوتیک، تحریک اشتها و خون سازی.",
"ingredients": "100% پیت، پیت مایع (بدون افزودنی و نگهدارنده).",
"usage_and_dosage": "قبل از استفاده تکان دهید. سگ های کوچک 2.5 تا 5 میلی لیتر، سگ های متوسط 10 میلی لیتر، سگ های بزرگتر 15 تا 20 میلی لیتر. از 20 میلی لیتر تجاوز نکند.",
"variants": [
{ "size": "250ml", "art_no": "112708", "barcode": "4027565112708", "buy_price": 3310000, "sell_price": 6620000 }
]
},
{
"name": "Canina PETVITAL Arthro-Tabletten",
"description": "متابولیسم استخوان را بهبود بخشیده و مفاصل ضعیف را تقویت می کند. عصاره بید و زنجبیل به عنوان آنتی اکسیدان عمل کرده و خاصیت ارتجاعی استخوان را افزایش می دهند.",
"ingredients": "گیاهان خشک (بید و زنجبیل)، ویتامین ایی، ویتامین ب1، آهن، مس، روی.",
"usage_and_dosage": "توله سگ ها: 2 قرص به ازای 10 کیلوگرم برای 1 ماه. سگ های بالغ: 5 قرص به ازای 10 کیلوگرم برای 3 ماه (سالی یکبار تکرار شود).",
"variants": [
{ "size": "60g (60 Tablets)", "art_no": "723003", "barcode": "4027565723003", "buy_price": 3240000, "sell_price": 6480000 }
]
},
{
"name": "Canina PETVITAL Bio-Aktivator",
"description": "حاوی سرم خون گاو برای تحریک اشتها و تسریع بهبودی در دوره نقاهت. رفاه و هماهنگی متابولیسم را بهبود می بخشد.",
"ingredients": "سرم خون گاو، اتانول 164.4 گرم (به عنوان طعم دهنده).",
"usage_and_dosage": "1 قطره به ازای هر کیلوگرم وزن بدن، حداکثر 20 قطره در روز. قطره ها به مدت 4 هفته داده شوند، سپس 2 هفته استراحت.",
"variants": [
{ "size": "20ml", "art_no": "712007", "barcode": "4027565712007", "buy_price": 3395000, "sell_price": 6790000 }
]
},
{
"name": "Canina PETVITAL Biotin-Tabs",
"description": "دوز بالای بیوتین (ویتامین H) برای جلوگیری از ریزش مو، ایجاد پوشش براق، رنگدانه های قوی و پنجه های محکم.",
"ingredients": "دکستروز، آب پنیر، نشاسته، سلولز. بیوتین 1000000 میکروگرم، ویتامین ب2، اسید نیکوتینیک.",
"usage_and_dosage": "یک قرص به ازای هر 10 کیلوگرم وزن بدن، حداکثر 5 قرص در روز.",
"variants": [
{ "size": "100g (50 Tablets)", "art_no": "702008", "barcode": "4027565702008", "buy_price": 3210000, "sell_price": 6420000 }
]
},
{
"name": "Canina PETVITAL ENERGY-GEL",
"description": "کنسانتره انرژی برای اصلاح سریع کمبودهای مواد مغذی. ایده آل برای دوره نقاهت جهت تحریک اشتها، دوره های رشد، بارداری و شیردهی.",
"ingredients": "روغن ها، چربی ها، ویتامین ایی، ویتامین ب1، ب2، ب6، ب12.",
"usage_and_dosage": "1 قاشق چایخوری (3 میلی لیتر) به ازای 10 کیلوگرم وزن بدن، حداکثر 4 قاشق چایخوری در روز.",
"variants": [
{ "size": "100ml", "art_no": "712106", "barcode": "4027565712106", "buy_price": 2500000, "sell_price": 5000000 }
]
},
{
"name": "Canina PETVITAL MINERAL-Tabs",
"description": "انواع مختلف کلسیم برای برطرف کردن کمبود و تشکیل بافت استخوانی. عالی برای دوره رشد، بارداری و شیردهی جهت تامین نیاز کلسیم.",
"ingredients": "کربنات کلسیم، مخمر آبجو، ویتامین د3 100000 (برای ذخیره کلسیم در استخوان).",
"usage_and_dosage": "سگ های بالغ: 2 قرص به ازای 10 کیلوگرم. باردار و شیرده: 3 قرص به ازای 10 کیلوگرم. مصرف ویتامین D2 همزمان مجاز نیست.",
"variants": [
{ "size": "100g (50 Tablets)", "art_no": "723102", "barcode": "4027565723102", "buy_price": 2685000, "sell_price": 5370000 }
]
},
{
"name": "Canina PETVITAL GAG",
"description": "تامین گلیکوزآمینوگلیکان ها، تاندون ها، رباط ها و غضروف مفاصل را تثبیت می کند. شامل پودر صدف لب سبز و اسیدهای آمینه برای عملکرد بهینه سیستم حرکتی.",
"ingredients": "پودر ماهی، پودر جلبک دریایی، پودر گوشت صدف لب سبز. دی ال متیونین، ویتامین ایی، سلنیوم.",
"usage_and_dosage": "پودر: 1 قاشق چایخوری به ازای 10 کیلوگرم (حداکثر 4 قاشق). قرص: 1 قرص به ازای 10 کیلوگرم (حداکثر 5 قرص).",
"variants": [
{ "size": "100g Powder", "art_no": "723201", "barcode": "4027565723201", "buy_price": 2920000, "sell_price": 5840000 },
{ "size": "90g (90 Tablets)", "art_no": "723300", "barcode": "4027565723300", "buy_price": 4740000, "sell_price": 9480000 },
{ "size": "400g Powder", "art_no": "723225", "barcode": "4027565723225", "buy_price": 8395000, "sell_price": 16790000 }
]
},
{
"name": "Canina PETVITAL VITAMIN-Tabs",
"description": "اصلاح کمبود ویتامین، جلوگیری از خستگی، عدم تناسب و اختلالات رشد. ایده آل برای مادران باردار و شرایط استرس زا.",
"ingredients": "مخمر آبجو، سلولز، ویتامین های آ، ب1 تا ب12، د3، ایی، کا3.",
"usage_and_dosage": "1 قرص به ازای هر 10 کیلوگرم وزن بدن در روز.",
"variants": [
{ "size": "100g (50 Tablets)", "art_no": "712205", "barcode": "4027565712205", "buy_price": 3485000, "sell_price": 6970000 }
]
},
{
"name": "Canina Rinderblut Pulver",
"description": "پودر خون گاو، منبع ارزشمند آهن و هموگلوبین برای انتقال اکسیژن. مکمل عالی برای رژیم گوشت خام (B.A.R.F) جهت تامین خون از دست رفته و رشد عضلات. مناسب دوره نقاهت و سگ های ورزشی.",
"ingredients": "خون کامل گاو خشک شده. پروتئین خام 92%، آهن.",
"usage_and_dosage": "0.3 گرم به ازای هر کیلوگرم وزن بدن (حداکثر 12 گرم در روز) مخلوط با خوراک خام برای 6 ماه.",
"variants": [
{ "size": "250g", "art_no": "792016", "barcode": "4027565792016", "buy_price": 1560000, "sell_price": 3120000 },
{ "size": "500g", "art_no": "791514", "barcode": "4027565791514", "buy_price": 2530000, "sell_price": 5060000 }
]
},
{
"name": "Canina Rinderfett Pulver",
"description": "منبع انرژی طبیعی از چربی گوشت گاو آب پز بدون شکر. عالی برای حیوانات لاغر، سگ های بسیار فعال، و جبران کمبود چربی در وعده های خام.",
"ingredients": "72% چربی گوشت گاو، 27% آب گوشت گاو خشک شده. انرژی: 740 کیلوکالری.",
"usage_and_dosage": "نصف قاشق چایخوری به ازای هر 10 کیلوگرم وزن بدن، حداکثر 3 قاشق چایخوری در روز همراه غذای مرطوب.",
"variants": [
{ "size": "75g", "art_no": "131235", "barcode": "4027565131235", "buy_price": 1520000, "sell_price": 3040000 }
]
},
{
"name": "Canina Schwarz Kümmel Samen",
"description": "دانه های زیره سیاه سرشار از اسیدهای چرب غیر اشباع که هضم و متابولیسم را تنظیم می کنند. سیستم دفاعی و عملکرد سگ را تقویت می کند.",
"ingredients": "100% دانه های زیره سیاه مصری.",
"usage_and_dosage": "1 قاشق چایخوری به ازای 10 کیلوگرم وزن بدن، حداکثر 4 قاشق چایخوری مخلوط با آب ولرم. در بارداری استفاده نشود.",
"variants": [
{ "size": "250g", "art_no": "131105", "barcode": "4027565131105", "buy_price": 2140000, "sell_price": 4280000 }
]
},
{
"name": "Canina Seealgen / Bio-Seealgenmehl",
"description": "جلبک دریایی ارگانیک سرشار از مواد معدنی و اسیدهای آمینه که با ید و روی، رنگدانه های پوست، بینی و پوشش را پشتیبانی می کند. هضم و سیستم ایمنی را بهبود می بخشد.",
"ingredients": "جلبک دریایی حاوی لیزین، سلولز و ویتامین سی.",
"usage_and_dosage": "قرص: 2 عدد به ازای 10 کیلوگرم. پودر: نصف قاشق چایخوری به ازای 10 کیلوگرم وزن بدن. جهت تامین نیاز ید.",
"variants": [
{ "size": "225g (225 Tablets)", "art_no": "130504", "barcode": "4027565130504", "buy_price": 2605000, "sell_price": 5210000 },
{ "size": "750g (750 Tablets)", "art_no": "130511", "barcode": "4027565130511", "buy_price": 6895000, "sell_price": 13790000 },
{ "size": "750g (Powder)", "art_no": "130412", "barcode": "4027565130412", "buy_price": 3690000, "sell_price": 7380000 }
]
},
{
"name": "Canina TAURIN Für Katzen",
"description": "اسید آمینه ضروری برای گربه ها که سیستم ایمنی، بینایی و قلب را پشتیبانی می کند. کمبود آن باعث نابینایی و اختلالات عصبی می شود.",
"ingredients": "مخمر آبجو، تورین 700 گرم.",
"usage_and_dosage": "گربه تا 6 کیلو: نصف قاشق چایخوری. بالای 6 کیلو و باردار/شیرده: 1 قاشق چایخوری در روز.",
"variants": [
{ "size": "100g", "art_no": "229505", "barcode": "4027565229055", "buy_price": 2350000, "sell_price": 4700000 }
]
},
{
"name": "Canina Velox Gelenkenergie",
"description": "کنسانتره صدف لب سبز نیوزیلندی برای بازسازی مفاصل، رباط ها و غضروف. افزایش استقامت مفاصل توله ها در حال رشد و سگ های پیر.",
"ingredients": "100% پودر گوشت صدف لب سبز.",
"usage_and_dosage": "1 قاشق چایخوری به ازای 10 کیلوگرم وزن بدن (حداکثر 2 قاشق) در روز به مدت 4 هفته یا مداوم.",
"variants": [
{ "size": "150g", "art_no": "701902", "barcode": "4027565701902", "buy_price": 4750000, "sell_price": 9500000 }
]
},
{
"name": "Canina Welpenbrei",
"description": "فرنی با پروتئین و ویتامین بالا که پرورش سالم توله سگ را از هفته 3 تضمین می کند.",
"ingredients": "غلات، گوشت، فرآورده های لبنی، ماهی، پروتئین 27%.",
"usage_and_dosage": "1 قسمت فرنی را با 3 قسمت آب گرم (50 درجه سانتیگراد) مخلوط کنید. مصرف ویتامین D2 همزمان مجاز نیست.",
"variants": [
{ "size": "600g", "art_no": "130603", "barcode": "4027565130603", "buy_price": 2835000, "sell_price": 5670000 }
]
},
{
"name": "Canina Welpenmilch",
"description": "شیر کامل جایگزین شیر مادر با انرژی و ویتامین بالا برای توله سگ های بی مادر از روز 1.",
"ingredients": "لاکتوز، پودر آب پنیر، روغن ماهی، پروتئین 30%، تورین، ویتامین ها.",
"usage_and_dosage": "1 قسمت شیر با 4 قسمت آب 50 درجه مخلوط شود. تغذیه هر 2 ساعت در ابتدا و سپس هر 4 ساعت.",
"variants": [
{ "size": "150g", "art_no": "130702", "barcode": "4027565130702", "buy_price": 2315000, "sell_price": 4630000 }
]
},
{
"name": "Canina PETVITAL Bio-Insect Shocker",
"description": "اسپری دفع کننده محیطی کک، شپش و کنه. تخم ها و انگل های خارجی را به طور موثر از بین می برد.",
"ingredients": "15 گرم در لیتر دودکانوئیک اسید، 5 گرم در لیتر عصاره مارگوسا.",
"usage_and_dosage": "هر 4 تا 6 هفته به صورت اسپری از فاصله 30 سانتی متری روی محل زندگی و خواب حیوان استفاده شود.",
"variants": [
{ "size": "100ml", "art_no": "741304", "barcode": "4027565741304", "buy_price": 1593000, "sell_price": 3186000 },
{ "size": "250ml", "art_no": "741311", "barcode": "4027565741311", "buy_price": 2730000, "sell_price": 5460000 }
]
},
{
"name": "Canina Mikrosilber Zahngel",
"description": "ژل دندانی با میکروسیلور که پلاک، جرم و التهاب لثه را هدف قرار می دهد. بیوفلاونوئیدها از باکتری های پلاک جلوگیری می کنند.",
"ingredients": "آب، نقره، گلیسیرین، عصاره دانه گریپ فروت.",
"usage_and_dosage": "روزانه عصرها 1 ساعت پس از غذا روی دندان های آسیاب مالیده شود. سگ تا 10 کیلو: 1 سانتی متر ژل.",
"variants": [
{ "size": "50ml", "art_no": "742639", "barcode": "4027565742639", "buy_price": 2765000, "sell_price": 5530000 }
]
},
{
"name": "Canina NovaGard Green Augenpflege",
"description": "قطره چشم برای تمیز کردن و مراقبت از چشم های گریان و گرفتگی چشم. نقره کلوئیدی از التهاب جلوگیری می کند.",
"ingredients": "آب بدون مواد معدنی، هیالورونات سدیم، نقره کلوئیدی.",
"usage_and_dosage": "چند قطره روی کیسه ملتحمه ریخته و اطراف چشم پاک شود.",
"variants": [
{ "size": "10ml", "art_no": "NG0013", "barcode": "4260118880130", "buy_price": 3180000, "sell_price": 6360000 }
]
},
{
"name": "Canina NovaGard Green Pfotenpflege",
"description": "کرم مراقبت از پنجه 100% طبیعی برای تسکین پوست خارش دار، التیام زخم ها و خراشیدگی پوست سگ ها در زمستان و تابستان.",
"ingredients": "وازلین، روغن پالپ سنجد دریایی، روغن کالاندولا، پانتنول.",
"usage_and_dosage": "چندین بار در روز روی نواحی آسیب دیده بمالید و ماساژ دهید.",
"variants": [
{ "size": "50ml", "art_no": "NG0016", "barcode": "4260118880161", "buy_price": 2500000, "sell_price": 5000000 }
]
}
]
+255
View File
@@ -0,0 +1,255 @@
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
const prisma = new PrismaClient();
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9\u0600-\u06FF\-]/g, '')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
}
function cleanBrand(text: string): string {
return text
.replace(/کانینا/g, 'کانینو')
.replace(/کانی‌نا/g, 'کانینو')
.replace(/Canina/g, 'Canino')
.replace(/canina/g, 'canino');
}
function determineSuitableFor(name: string, description: string): string {
const text = (name + ' ' + description).toLowerCase();
const hasCat = text.includes('گربه') || text.includes('katzen') || text.includes('cat');
const hasDog = text.includes('سگ') || text.includes('hund') || text.includes('توله') || text.includes('dog');
if (hasCat && hasDog) return 'هر دو';
if (hasCat) return 'گربه';
if (hasDog) return 'سگ';
return 'هر دو';
}
function parseSize(size: string): { unit: string; packageSize: number } {
const mlMatch = size.match(/([\d.]+)\s*ml/i);
if (mlMatch) return { unit: 'ml', packageSize: parseFloat(mlMatch[1]) };
const gMatch = size.match(/([\d.]+)\s*g/i);
if (gMatch) return { unit: 'g', packageSize: parseFloat(gMatch[1]) };
const tabMatch = size.match(/([\d.]+)\s*(tablet|tab)/i);
if (tabMatch) return { unit: 'tablet', packageSize: parseFloat(tabMatch[1]) };
return { unit: 'g', packageSize: 100 };
}
async function main() {
console.log('Seeding products from seed-products-data.json...');
// 1. Create default category
const category = await prisma.category.upsert({
where: { slug: 'supplements' },
update: {},
create: {
name: 'مکمل‌های غذایی و درمانی',
slug: 'supplements',
description: 'انواع مکمل‌های اورجینال کانینو آلمان',
metaTitle: 'خرید مکمل کانینو',
metaDescription: 'بهترین مکمل‌های کانینو'
}
});
// 2. Read JSON data
const dataPath = path.join(__dirname, 'seed-products-data.json');
if (!fs.existsSync(dataPath)) {
console.error('seed-products-data.json not found at', dataPath);
process.exit(1);
}
const productsData = JSON.parse(fs.readFileSync(dataPath, 'utf-8'));
let variantCount = 0;
for (const item of productsData) {
const baseName = cleanBrand(item.name);
const cleanDesc = cleanBrand(item.description);
const cleanIngredients = item.ingredients ? cleanBrand(item.ingredients) : '';
const cleanDosage = item.usage_and_dosage ? cleanBrand(item.usage_and_dosage) : '';
const suitableFor = determineSuitableFor(baseName, cleanDesc);
const baseSlug = slugify(baseName);
for (const variant of item.variants) {
const artNo = variant.art_no;
const barcode = variant.barcode;
const sellPrice = variant.sell_price || 0;
const buyPrice = variant.buy_price || 0;
const sizeLabel = variant.size;
const { unit, packageSize } = parseSize(sizeLabel);
// Build variant-specific slug
const sizeSlug = slugify(sizeLabel);
const slug = `${baseSlug}-${sizeSlug}`;
// Build display name with size
const displayName = `${baseName} - ${sizeLabel}`;
const priceDisplay = `${sellPrice.toLocaleString()} T`;
const product = await prisma.product.upsert({
where: { artNo },
update: {
barcode,
slug,
productGroup: baseSlug,
name: displayName,
description: cleanDesc,
ingredients: cleanIngredients,
categoryId: category.id,
categorySlug: category.slug,
priceValue: sellPrice,
buyPrice,
priceDisplay,
unit,
packageSize,
dosageLogic: cleanDosage,
suitableFor,
imageUrl: `/products/${baseSlug}.png`,
},
create: {
artNo,
barcode,
slug,
productGroup: baseSlug,
name: displayName,
description: cleanDesc,
ingredients: cleanIngredients,
categoryId: category.id,
categorySlug: category.slug,
priceValue: sellPrice,
buyPrice,
priceDisplay,
unit,
packageSize,
dosageLogic: cleanDosage,
suitableFor,
imageUrl: `/products/${baseSlug}.png`,
}
});
// Seed ingredients (split by '،' or '، ')
await prisma.productIngredient.deleteMany({ where: { productId: product.id } });
if (cleanIngredients) {
const parts = cleanIngredients.split(/[،,]/).map(s => s.trim()).filter(Boolean);
// Only take the first meaningful items (up to ~20)
const meaningful = parts.slice(0, 20);
for (const ing of meaningful) {
const truncated = ing.substring(0, 150);
if (truncated.length > 0) {
await prisma.productIngredient.create({
data: { productId: product.id, ingredient: truncated }
});
}
}
}
variantCount++;
}
}
console.log(`Seeded ${variantCount} product variants.`);
// Create admin user for blogs
const adminId = '12345678-1234-1234-1234-123456789012';
await prisma.user.upsert({
where: { id: adminId },
update: { role: 'ADMIN' },
create: {
id: adminId,
mobile: '09120000000',
email: 'admin@canino-iran.com',
firstName: 'Admin',
lastName: 'User',
role: 'ADMIN'
}
});
// 3. Seed some Blogs
const blog1Content = [
'<p><strong>تغذیه صحیح سگ‌های بالغ</strong> یکی از مهم‌ترین عوامل در حفظ سلامت و افزایش طول عمر آن‌هاست. برند کانینو (Canino) با بیش از ۴۰ سال سابقه در تولید مکمل‌های دامپزشکی در آلمان، استاندارد طلایی تغذیه تکمیلی را تعریف کرده است.</p>',
'',
'<h2>اصول تغذیه سگ بالغ</h2>',
'<p>سگ‌های بالغ به رژیم غذایی متعادل حاوی پروتئین، چربی، کربوهیدرات، ویتامین‌ها و مواد معدنی نیاز دارند. نسبت Ca:P (کلسیم به فسفر) باید در محدوده ۱.۲:۱ تا ۱.۵:۱ باشد. هرگونه عدم تعادل در این نسبت می‌تواند منجر به مشکلات کلیوی و استخوانی شود.</p>',
'',
'<h2>نقش مکمل‌ها در رژیم غذایی</h2>',
'<p>حتی با بهترین رژیم غذایی، ممکن است برخی مواد مغذی به اندازه کافی تأمین نشوند. محصولات کانینو مانند <strong>Petvital Vitamin-Tabs</strong> (کمپلکس کامل A تا K3) و <strong>Biotin-Tabs</strong> (۱ میلیون میکروگرم بیوتین) نیازهای تغذیه‌ای را پوشش می‌دهند.</p>',
'',
'<h2>اسیدهای چرب ضروری</h2>',
'<p>روغن سالمون کانینو (Lachs-Öl) با ۱۴٪ امگا ۳ (EPA/DHA) به روش Cold Press استخراج می‌شود و تمام ویتامین‌های حساس به حرارت را حفظ می‌کند. EPA پیش‌ماده رزولوین‌های ضدالتهابی و DHA ۳۰٪ وزن خشک مغز را تشکیل می‌دهد.</p>',
'',
'<h2>مراقبت از مفاصل</h2>',
'<p>با افزایش سن سگ، غضروف مفصلی تحلیل می‌رود. گلیکوزآمینوگلیکان‌های صدف لب سبز (GAG) با جذب مولکول‌های آب در ماتریکس غضروفی، خاصیت بافری مفاصل را بازیابی می‌کنند. <strong>CANHYDROX GAG</strong> و <strong>FLEXAN</strong> حاوی این ترکیبات حیاتی هستند.</p>',
'',
'<h2>هشدارهای مهم تغذیه‌ای</h2>',
'<ul>',
'<li>مصرف همزمان ویتامین D3 با D2 مجاز نیست</li>',
'<li>روغن سیاه دانه در بارداری و شیردهی ممنوع است</li>',
'<li>روغن‌های با غلظت بالا باید تدریجاً به رژیم اضافه شوند تا از پانکراتیت جلوگیری شود</li>',
'<li>تورین برای گربه‌ها اسید آمینه ضروری است و بدن آن‌ها قادر به سنتز آن نیست</li>',
'</ul>'
].join('\n');
const blog2Content = [
'<p><strong>کانینو (Canino)</strong> نماینده رسمی برند <strong>Canina pharma GmbH</strong> در ایران است. این شرکت آلمانی در سال ۱۹۸۴ توسط <strong>پتر و کریستین کرشن‌مایر</strong> در شهر برگیش گلادباخ تأسیس شد و به یکی از پیشگامان تولید مکمل‌های طبیعی دامپزشکی در اروپا تبدیل شده است.</p>',
'',
'<h2>فلسفه Canina: "مادر طبیعت بهترین نسخه را می‌داند"</h2>',
'<p>تمام محصولات کانینا بر پایه مواد اولیه طبیعی و با فرآیندهای پیشرفته تولید می‌شوند. این شرکت دارای گواهی‌های معتبر <strong>IFS (International Featured Standard)</strong> و <strong>HACCP</strong> است و محصولات آن در بیش از ۴۰ کشور جهان توزیع می‌شود.</p>',
'',
'<h2>چرا مکمل‌های کانینو در ایران؟</h2>',
'<ul>',
'<li><strong>کیفیت آلمانی:</strong> تمام محصولات در کارخانه برگیش گلادباخ تحت نظارت دامپزشکان تولید می‌شوند</li>',
'<li><strong>بدون مواد مصنوعی:</strong> فاقد رنگ، طعم و نگهدارنده مصنوعی</li>',
'<li><strong>فرمولاسیون تخصصی:</strong> هر محصول برای نیاز خاصی مانند مفاصل، ایمنی، پوست و مو یا گوارش طراحی شده</li>',
'<li><strong>تأیید دامپزشکان:</strong> محصولات با مشورت دامپزشکان و متخصصان تغذیه حیوانات فرموله شده‌اند</li>',
'</ul>',
'',
'<h2>محصولات پرفروش در ایران</h2>',
'<p><strong>مفاصل و استخوان:</strong> CANHYDROX GAG (استاندارد طلایی ارتوپدی)، FLEXAN (کلاژن خالص)، Petvital GAG و Velox Gelenkenergie (کنسانتره صدف لب سبز)</p>',
'<p><strong>سیستم ایمنی و گوارش:</strong> Immun-Booster (خمیر آغوز)، Moor-Tränke (عصاره پیت)، Ballaststoff Mix (فیبر گیاهی)</p>',
'<p><strong>پوست و مو:</strong> Lachs-Öl (روغن سالمون)، Biotin-Tabs، Seealgen (جلبک دریایی)</p>',
'<p><strong>قلب و انرژی:</strong> Herz Vital (ال-کارنیتین و زالزالک)، Energy-Gel (ویتامین‌های گروه B)</p>',
'',
'<h2>تعهد به سلامت حیوانات</h2>',
'<p>کانینو به عنوان نماینده رسمی کانینا در ایران، متعهد به ارائه محصولات اصل با ضمانت اصالت و پروانه دامپزشکی است. تمام محصولات دارای بسته‌بندی اصلی آلمان و بارکد اختصاصی هستند.</p>'
].join('\n');
const blogs = [
{
title: 'راهنمای جامع تغذیه سگ‌های بالغ',
slug: 'adult-dog-nutrition-guide',
content: blog1Content,
authorId: adminId,
isPublished: true,
},
{
title: 'چرا مکمل‌های کانینو؟',
slug: 'why-canino-supplements',
content: blog2Content,
authorId: adminId,
isPublished: true,
}
];
for (const b of blogs) {
await prisma.blog.upsert({
where: { slug: b.slug },
update: {},
create: b
});
}
console.log('Seeded blogs.');
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+80
View File
@@ -0,0 +1,80 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const WIKI_TERMS = [
{
id: "green-mussel",
name: "صدف لب‌سبز (Perna Canaliculus)",
description: "این صدف بومی سواحل بکر نیوزیلند است و تنها منبع طبیعی حاوی گلیکوزآمین‌گلیکان‌ها (GAG) در غلظت بسیار بالا محسوب می‌شود.",
benefits: [
"بازسازی بافت غضروفی تخریب شده",
"خواص ضدالتهابی طبیعی برای رباط‌ها",
"تامین اسیدهای چرب امگا ۳ خاص",
]
},
{
id: "silver",
name: "نقره میکروسیلور (Microsilver)",
description: "ذرات نقره خالص با ساختار اسفنجی که به دلیل اندازه ذرات درشت، جذب خون نمی‌شوند اما اثر آنتی‌باکتریال پایداری بر سطح غشاها دارند.",
benefits: [
"مبارزه با باکتری‌های مقاوم در دهان و پوست",
"عدم آسیب به فلور طبیعی بدن",
"جایگزین ایمن برای آنتی‌بیوتیک‌های موضعی",
]
},
{
id: "colostrum",
name: "آغوز (Colostrum)",
description: "اولین شیر مادر که حاوی دوز بالایی از ایمونوگلوبولین‌ها، ویتامین‌ها و مواد معدنی برای فعال‌سازی فوری سیستم ایمنی است.",
benefits: [
"تقویت سد دفاعی روده",
"انتقال مستقیم آنتی‌بادی به نوزادان",
"تسریع نقاهت بعد از جرافی",
]
},
{
id: "peat-extract",
name: "عصاره پیت (Peat Extract)",
description: "ماده‌ای کاملا طبیعی حاصل از تجزیه گیاهان در طول هزاران سال که غنی از اسیدهای هومیک و مواد معدنی است.",
benefits: [
"جذب سموم در دستگاه گوارش",
"تنظیم فلور روده",
"بهبود اشتها و هضم"
]
}
];
async function main() {
console.log('Seeding Scientific Terms (Wiki)...');
for (const term of WIKI_TERMS) {
await prisma.scientificTerm.upsert({
where: { key: term.id },
update: {
term: term.name,
definition: term.description,
keywords: JSON.stringify(term.benefits),
wikiId: term.id,
},
create: {
key: term.id,
term: term.name,
definition: term.description,
keywords: JSON.stringify(term.benefits),
wikiId: term.id,
},
});
}
console.log('Wiki seeded successfully');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+70 -87
View File
@@ -15,6 +15,7 @@ async function main() {
await prisma.pet.deleteMany();
await prisma.orderItem.deleteMany();
await prisma.order.deleteMany();
await prisma.blog.deleteMany();
await prisma.walletTransaction.deleteMany();
await prisma.userAddress.deleteMany();
await prisma.user.deleteMany();
@@ -24,117 +25,67 @@ async function main() {
await prisma.coupon.deleteMany();
await prisma.uiText.deleteMany();
await prisma.scientificTerm.deleteMany();
await prisma.category.deleteMany();
console.log('Database successfully wiped.');
console.log('Seeding database with products...');
const productsFilePath = path.join(__dirname, '..', '..', 'src', 'data', 'products.ts');
const fileContent = fs.readFileSync(productsFilePath, 'utf-8');
const jsCode = ts.transpile(fileContent, {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2018,
console.log('Creating Admin User...');
await prisma.user.upsert({
where: { id: '12345678-1234-1234-1234-123456789012' },
update: {},
create: {
id: '12345678-1234-1234-1234-123456789012',
firstName: 'Admin',
lastName: 'System',
email: 'admin@canino.ir',
role: 'ADMIN',
mobile: '09000000000'
}
});
const context = { exports: {} };
vm.createContext(context);
vm.runInContext(jsCode, context);
const PRODUCTS = (context.exports as any).PRODUCTS;
if (!PRODUCTS || !Array.isArray(PRODUCTS)) {
console.error('Could not load PRODUCTS from src/data/products.ts');
process.exit(1);
}
for (const productData of PRODUCTS) {
const p = await prisma.product.upsert({
where: { artNo: productData.artNo },
update: {},
create: {
artNo: productData.artNo,
name: productData.name,
scientificTagline: productData.scientificTagline,
description: productData.description,
shortDescription: productData.shortDescription || '',
category: productData.category,
categorySlug: productData.categorySlug || 'general',
priceValue: productData.priceValue,
priceDisplay: productData.price,
unit: productData.unit,
packageSize: productData.packageSize,
dosageLogic: productData.dosage_logic,
suitableFor: productData.suitableFor,
imageUrl: productData.image,
}
});
if (productData.main_ingredients) {
for (const ing of productData.main_ingredients) {
await prisma.productIngredient.upsert({
where: { productId_ingredient: { productId: p.id, ingredient: ing } },
update: {},
create: { productId: p.id, ingredient: ing }
});
}
}
if (productData.symptoms) {
for (const sym of productData.symptoms) {
await prisma.productSymptom.upsert({
where: { productId_symptom: { productId: p.id, symptom: sym } },
update: {},
create: { productId: p.id, symptom: sym }
});
}
}
console.log(`Seeded product: ${p.name}`);
}
// 1. Seed UI Texts
// Seeding UI Texts
console.log('Seeding UI Texts...');
const uiTexts = {
hero_badge: "تخصص دارویی از آلمان",
hero_badge: "از ۱۹۸۴ در خدمت سلامت حیوانات",
hero_title: "تخصص آلمانی در خدمت\nسلامت پت‌های خانگی",
hero_desc: "بیش از ۴۰ سال تجربه نوآورانه در تولید مکمل‌های درمانی با بالاترین استاندارد کیفی «گرید دارویی اختصاصی». راهکار هوشمند برای هر نیاز بالینی.",
hero_desc: "از سال ۱۹۸۴، شرکت Canina pharma GmbH در برگیش گلادباخ آلمان، با بهره‌گیری از مواد اولیه طبیعی و فرآیندهای پیشرفته، استاندارد طلایی مکمل‌های دامپزشکی را تعریف می‌کند. کانینو نماینده رسمی این برند در ایران است.",
hero_btn_advisor: "دستیار سلامت پت",
hero_btn_products: "مشاهده محصولات",
hero_stat_founded: "۱۹۸۴ سال تأسیس",
hero_stat_agencies: "نمایندگی فعال",
hero_stat_german_formula: "فرمول آلمانی",
hero_image_badge: "سرآمد علمی در پزشکی پت‌ها",
hero_image_title: "مکمل‌های تایید شده دامپزشکی",
hero_quality_standard: "استاندارد کیفی آلمان",
hero_image_title: "مکمل‌های تایید شده دامپزشکی با گواهی IFS",
hero_quality_standard: "استاندارد کیفی آلمان (IFS & HACCP)",
cta_title: "می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟",
cta_subtitle: "تیم متخصص دامپزشکی کانینا ایران آماده پاسخگویی به سوالات شماست.",
cta_subtitle: "تیم متخصص دامپزشکی کانینو ایران آماده پاسخگویی به سوالات شماست. با بیش از ۴۰ محصول تخصصی، راهکار مناسب هر نیاز بالینی را خواهید یافت.",
cta_btn_free: "دریافت رژیم مکمل رایگان",
cta_btn_products: "ورود به محصولات تخصصی",
about_teaser_badge: "میراث ما از آلمان",
about_teaser_title: "چرا برند آلمانی Canina مرجع دامپزشکان است؟",
about_teaser_badge: "داستان ما از آلمان",
about_teaser_title: "Canina pharma GmbH – میراثی از ۱۹۸۴",
about_teaser_desc: "شرکت Canina pharma GmbH در سال ۱۹۸۴ توسط پتر و کریستین کرشن‌مایر در شهر برگیش گلادباخ آلمان تأسیس شد. این شرکت با شعار «مادر طبیعت بهترین نسخه را می‌داند» از مواد اولیه طبیعی و تجدیدپذیر برای تولید مکمل‌های با گرید دارویی استفاده می‌کند. امروزه محصولات کانینا در بیش از ۴۰ کشور جهان توزیع می‌شود و نماینده رسمی آن در ایران با نام کانینو به ارائه محصولات اصل با پروانه دامپزشکی می‌پردازد.",
about_teaser_feat1_title: "مواد اولیه نایاب",
about_teaser_feat1_desc: "استفاده از پودر صدف لب‌سبز اصل نیوزیلند و مواد ارگانیک با گرید دارویی.",
about_teaser_feat1_desc: "استفاده از پودر صدف لب‌سبز اصل نیوزیلند (Perna canaliculus)، پیت طبیعی آلمان، آغوز و روغن‌های گیاهی ارگانیک با گرید دارویی.",
about_teaser_feat2_title: "فاقد مواد نگهدارنده",
about_teaser_feat2_desc: "تمامی محصولات ۱۰۰٪ طبیعی و فاقد رنگ‌های مصنوعی و طعم‌دهنده‌های شیمیایی هستند.",
about_teaser_feat3_title: "تاییدیه اروپا",
about_teaser_feat3_desc: "مطابق با سخت‌گیرانه‌ترین استانداردهای ایمنی مواد غذایی و دارویی در اتحادیه اروپا.",
about_teaser_quality_title: "کیفیت",
about_teaser_quality_desc: "استانداردهای فوق‌دارویی",
about_teaser_feat2_desc: "تمامی محصولات ۱۰۰٪ طبیعی و فاقد رنگ‌های مصنوعی، طعم‌دهنده‌ها و نگهدارنده‌های شیمیایی هستند.",
about_teaser_feat3_title: "تاییدیه بین‌المللی",
about_teaser_feat3_desc: "دارای گواهی IFS (International Featured Standard) و HACCP. محصولات مطابق با سخت‌گیرانه‌ترین استانداردهای ایمنی مواد غذایی و دارویی اتحادیه اروپا تولید می‌شوند.",
about_teaser_quality_title: "کیفیت آلمانی",
about_teaser_quality_desc: "استانداردهای فوق‌دارویی – تولید شده در کارخانه برگیش گلادباخ",
ingredients_wiki: JSON.stringify([
{
id: "green-mussel",
name: "صدف لب‌سبز (Perna Canaliculus)",
description: "این صدف بومی سواحل بکر نیوزیلند است و تنها منبع طبیعی حاوی گلیکوزآمین‌گلیکان‌ها (GAG) در غلظت بسیار بالا محسوب می‌شود.",
description: "این صدف بومی سواحل بکر نیوزیلند است و تنها منبع طبیعی حاوی گلیکوزآمین‌گلیکان‌ها (GAG) در غلظت بسیار بالا محسوب می‌شود. GAGها مولکول‌های آب را در ماتریکس غضروفی جذب کرده و خاصیت بافری و الاستیسیته مفاصل را بازیابی می‌کنند.",
benefits: [
"بازسازی بافت غضروفی تخریب شده",
"خواص ضدالتهابی طبیعی برای رباط‌ها",
"تامین اسیدهای چرب امگا ۳ خاص"
"تامین اسیدهای چرب امگا ۳ خاص (ETA)"
]
},
{
id: "silver",
name: "نقره میکروسیلور (Microsilver)",
description: "ذرات نقره خالص با ساختار اسفنجی که به دلیل اندازه ذرات درشت، جذب خون نمی‌شوند اما اثر آنتی‌باکتریال پایداری بر سطح غشاها دارند.",
description: "ذرات نقره خالص با ساختار اسفنجی که به دلیل اندازه ذرات درشت، جذب خون نمی‌شوند اما اثر آنتی‌باکتریال پایداری بر سطح غشاها دارند. بر خلاف نقره کلوئیدی معمولی، میکروسیلور رسوب سطحی طولانی‌مدت ایجاد کرده و فلور طبیعی را تخریب نمی‌کند.",
benefits: [
"مبارزه با باکتری‌های مقاوم در دهان و پوست",
"عدم آسیب به فلور طبیعی بدن",
@@ -144,22 +95,52 @@ async function main() {
{
id: "colostrum",
name: "آغوز (Colostrum)",
description: "اولین شیر مادر که حاوی دوز بالایی از ایمونوگلوبولین‌ها، ویتامین‌ها و مواد معدنی برای فعال‌سازی فوری سیستم ایمنی است.",
description: "اولین شیر پستانداران که حاوی دوز بالایی از ایمونوگلوبولین‌ها (IgG, IgA, IgM)، لاکتوفرین و سایتوکاین‌ها برای فعال‌سازی فوری سیستم ایمنی است. سد دفاعی روده را تقویت کرده و از نفوذ پاتوژن‌ها جلوگیری می‌کند.",
benefits: [
"تقویت سد دفاعی روده",
"انتقال مستقیم آنتی‌بادی به نوزادان",
"تسریع نقاهت بعد از جرافی"
"تسریع نقاهت بعد از جراحی"
]
},
{
id: "peat-extract",
name: "عصاره پیت (Peat Extract)",
description: "ماده‌ای کاملا طبیعی حاصل از تجزیه گیاهان در طول هزاران سال که غنی از اسیدهای هومیک و مواد معدنی است.",
description: "ماده‌ای کاملاً طبیعی حاصل از تجزیه گیاهان در طول هزاران سال که غنی از اسیدهای هومیک با ساختار پلیمری دارای بار منفی است. سموم، قارچ‌ها و باکتری‌های مضر را در روده به دام انداخته و دفع می‌کند.",
benefits: [
"جذب سموم در دستگاه گوارش",
"جذب سموم و فلزات سنگین در دستگاه گوارش",
"تنظیم فلور روده",
"بهبود اشتها و هضم"
]
},
{
id: "collagen",
name: "کلاژن هیدرولیز شده",
description: "پپتیدهای کلاژن نوع I و II با وزن مولکولی پایین که مستقیماً در ماتریکس غضروف مفصلی جذب شده و سنتز کلاژن را تحریک می‌کنند. پروتئین خالص ۹۴٪.",
benefits: [
"بازسازی غضروف مفصلی",
"تقویت بافت همبند",
"بهبود خاصیت ارتجاعی مفاصل"
]
},
{
id: "biotin",
name: "بیوتین (ویتامین H / B7)",
description: "کوآنزیم کربوکسیلازهای مسئول سنتز اسیدهای چرب و گلوکونئوژنز. با دوز ۱,۰۰۰,۰۰۰ میکروگرم در کیلوگرم در محصولات کانینو، قوی‌ترین دوز موجود در بازار مکمل‌های دامپزشکی.",
benefits: [
"جلوگیری از ریزش مو",
"تقویت رنگدانه پوشش",
"محکم‌سازی پنجه و ناخن"
]
},
{
id: "taurin",
name: "تورین",
description: "اسید آمینه ضروری شرطی برای گربه‌ها. بدن گربه قادر به سنتز تورین نیست و کمبود آن منجر به دژنراسیون مرکزی شبکیه (نابینایی) و کاردیومیوپاتی متسع می‌شود.",
benefits: [
"سلامت بینایی و شبکیه چشم",
"تقویت عضله قلب",
"سیستم ایمنی گربه"
]
}
]),
medical_options: JSON.stringify([
@@ -168,7 +149,9 @@ async function main() {
{ id: "pregnancy", label: "بارداری", condition: "بارداری" },
{ id: "digestion", label: "مشکلات گوارشی", condition: "مشکلات گوارشی" },
{ id: "hair_loss", label: "ریزش موی شدید", condition: "ریزش موی شدید" },
{ id: "appetite", label: "بی‌اشتهایی", condition: "بی‌اشتهایی" }
{ id: "appetite", label: "بی‌اشتهایی", condition: "بی‌اشتهایی" },
{ id: "heart_disease", label: "نارسایی قلبی", condition: "نارسایی قلبی" },
{ id: "parasites", label: "آلودگی انگلی", condition: "آلودگی انگلی" }
])
};
@@ -182,7 +165,7 @@ async function main() {
// 2. Seed Scientific Terms
console.log('Seeding Scientific Terms...');
const termsFilePath = path.join(__dirname, '..', '..', 'src', 'data', 'scientificTerms.ts');
const termsFilePath = path.join(__dirname, '..', '..', 'frontend', 'application', 'lib', 'data', 'scientificTerms.ts');
if (fs.existsSync(termsFilePath)) {
const termsContent = fs.readFileSync(termsFilePath, 'utf-8');
const termsJsCode = ts.transpile(termsContent, {
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdminController } from './admin.controller';
describe('AdminController', () => {
let controller: AdminController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
}).compile();
controller = module.get<AdminController>(AdminController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
+186
View File
@@ -0,0 +1,186 @@
import { Controller, Get, UseGuards, Param, Put, Post, Body, Delete, Query } from '@nestjs/common';
import { AdminService } from './admin.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
@ApiTags('Admin - پنل مدیریت')
@ApiBearerAuth()
@Controller('admin')
export class AdminController {
constructor(private readonly adminService: AdminService) {}
@UseGuards(JwtAuthGuard)
@Get('dashboard/stats')
@ApiOperation({ summary: 'دریافت آمار کلی داشبورد' })
async getDashboardStats() {
const stats = await this.adminService.getDashboardStats();
return {
success: true,
data: stats
};
}
@UseGuards(JwtAuthGuard)
@Get('users')
@ApiOperation({ summary: 'لیست کاربران' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو در نام یا ایمیل' })
@ApiQuery({ name: 'role', required: false, description: 'فیلتر بر اساس نقش کاربر' })
async getUsers(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('role') role?: string
) {
const data = await this.adminService.getUsers({ page, limit, search, role });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@Put('users/:id/role')
@ApiOperation({ summary: 'تغییر نقش کاربر' })
async updateUserRole(@Param('id') id: string, @Body('role') role: string) {
const user = await this.adminService.updateUserRole(id, role);
return {
success: true,
data: user
};
}
@UseGuards(JwtAuthGuard)
@Get('products')
@ApiOperation({ summary: 'لیست محصولات (مدیریت)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({ name: 'categoryId', required: false, description: 'شناسه دسته‌بندی' })
async getProducts(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('categoryId') categoryId?: string
) {
const data = await this.adminService.getProducts({ page, limit, search, categoryId });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@Post('products')
@ApiOperation({ summary: 'ایجاد محصول جدید' })
async createProduct(@Body() data: any) {
const product = await this.adminService.createProduct(data);
return { success: true, data: product };
}
@UseGuards(JwtAuthGuard)
@Put('products/:id')
@ApiOperation({ summary: 'ویرایش محصول' })
async updateProduct(@Param('id') id: string, @Body() data: any) {
const product = await this.adminService.updateProduct(id, data);
return {
success: true,
data: product
};
}
@UseGuards(JwtAuthGuard)
@Delete('products/:id')
@ApiOperation({ summary: 'حذف محصول' })
async deleteProduct(@Param('id') id: string) {
await this.adminService.deleteProduct(id);
return {
success: true,
message: 'Product deleted'
};
}
@UseGuards(JwtAuthGuard)
@Get('orders')
@ApiOperation({ summary: 'لیست سفارش‌ها' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({ name: 'status', required: false, description: 'وضعیت سفارش' })
async getOrders(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('status') status?: string
) {
const data = await this.adminService.getOrders({ page, limit, search, status });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@Put('orders/:id/status')
@ApiOperation({ summary: 'تغییر وضعیت سفارش' })
async updateOrderStatus(@Param('id') id: string, @Body('status') status: string) {
const order = await this.adminService.updateOrderStatus(id, status);
return {
success: true,
data: order
};
}
// --- Coupons ---
@UseGuards(JwtAuthGuard)
@Get('coupons')
@ApiOperation({ summary: 'لیست کد تخفیف‌ها' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getCoupons(@Query() query: any) {
const coupons = await this.adminService.getCoupons(query);
return { success: true, ...coupons };
}
@UseGuards(JwtAuthGuard)
@Post('coupons')
@ApiOperation({ summary: 'ایجاد کد تخفیف جدید' })
async createCoupon(@Body() data: any) {
const coupon = await this.adminService.createCoupon(data);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Put('coupons/:id')
@ApiOperation({ summary: 'ویرایش کد تخفیف' })
async updateCoupon(@Param('id') id: string, @Body() data: any) {
const coupon = await this.adminService.updateCoupon(id, data);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Put('coupons/:id/toggle')
@ApiOperation({ summary: 'فعال/غیرفعال کردن کد تخفیف' })
async toggleCoupon(@Param('id') id: string, @Body('isActive') isActive: boolean) {
const coupon = await this.adminService.toggleCoupon(id, isActive);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Delete('coupons/:id')
@ApiOperation({ summary: 'حذف کد تخفیف' })
async deleteCoupon(@Param('id') id: string) {
await this.adminService.deleteCoupon(id);
return { success: true };
}
// --- Settings ---
@UseGuards(JwtAuthGuard)
@Get('settings')
@ApiOperation({ summary: 'دریافت تنظیمات' })
async getSettings() {
const settings = await this.adminService.getSettings();
return { success: true, data: settings };
}
@UseGuards(JwtAuthGuard)
@Put('settings')
@ApiOperation({ summary: 'ذخیره تنظیمات' })
async updateSettings(@Body() data: Record<string, string>) {
const settings = await this.adminService.updateSettings(data);
return { success: true, data: settings };
}
}
+24
View File
@@ -0,0 +1,24 @@
import { Module } from '@nestjs/common';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { ReportsController } from './reports.controller';
import { ReportsService } from './reports.service';
import { MediaController } from './media.controller';
import { MediaService } from './media.service';
import { CategoriesController } from './categories.controller';
import { CategoriesService } from './categories.service';
import { BlogsController } from './blogs.controller';
import { BlogsService } from './blogs.service';
import { WikiController } from './wiki.controller';
import { WikiService } from './wiki.service';
import { PetsController } from './pets.controller';
import { PetsService } from './pets.service';
import { PrismaModule } from '../prisma/prisma.module';
import { RedisModule } from '../redis/redis.module';
@Module({
imports: [PrismaModule, RedisModule],
controllers: [AdminController, ReportsController, MediaController, CategoriesController, BlogsController, WikiController, PetsController],
providers: [AdminService, ReportsService, MediaService, CategoriesService, BlogsService, WikiService, PetsService],
})
export class AdminModule {}
+18
View File
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdminService } from './admin.service';
describe('AdminService', () => {
let service: AdminService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AdminService],
}).compile();
service = module.get<AdminService>(AdminService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
+319
View File
@@ -0,0 +1,319 @@
import { Injectable, HttpException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
@Injectable()
export class AdminService {
constructor(
private prisma: PrismaService,
private redisService: RedisService,
) {}
async getDashboardStats() {
// total revenue
const orders = await this.prisma.order.findMany({
where: { status: { not: 'failed' } },
select: { totalAmount: true }
});
const revenue = orders.reduce((sum, o) => sum + Number(o.totalAmount), 0);
// new orders count (processing status)
const newOrders = await this.prisma.order.count({
where: { status: 'processing' }
});
// active users count
const users = await this.prisma.user.count();
// Today's request count from Redis counter (set by MetricsController)
const todayKey = `visits:${new Date().toISOString().split('T')[0]}`;
let todayVisits = 0;
try {
const count = await this.redisService.get(todayKey);
todayVisits = count ? parseInt(count, 10) : 0;
} catch {
todayVisits = 0;
}
return {
revenue,
newOrders,
users,
todayVisits
};
}
async getUsers(query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.search) {
where.OR = [
{ firstName: { contains: query.search, mode: 'insensitive' } },
{ lastName: { contains: query.search, mode: 'insensitive' } },
{ email: { contains: query.search, mode: 'insensitive' } },
{ mobile: { contains: query.search } }
];
}
if (query.role) {
if (query.role === 'B2B') {
where.role = { contains: 'B2B' };
} else {
where.role = query.role;
}
}
const [data, total] = await Promise.all([
this.prisma.user.findMany({ where, skip, take: limit, orderBy: { createdAt: 'desc' } }),
this.prisma.user.count({ where })
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
}
async updateUserRole(id: string, role: string) {
return this.prisma.user.update({
where: { id },
data: { role }
});
}
async getProducts(query: any) {
try {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.search) {
where.OR = [
{ name: { contains: query.search, mode: 'insensitive' } },
{ artNo: { contains: query.search } }
];
}
if (query.categoryId) {
where.categoryId = query.categoryId;
}
const [data, total] = await Promise.all([
this.prisma.product.findMany({
where, skip, take: limit, orderBy: { createdAt: 'desc' },
include: { category: true }
}),
this.prisma.product.count({ where })
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
} catch (error) {
console.error("[AdminService] getProducts error:", error);
throw new HttpException(error.message || 'Error fetching products', 500);
}
}
async createProduct(data: any) {
return this.prisma.product.create({
data: {
artNo: data.artNo,
name: data.name,
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
categoryId: data.categoryId,
categorySlug: data.categorySlug || 'general',
priceValue: data.priceValue,
priceDisplay: data.priceDisplay,
unit: data.unit,
packageSize: data.packageSize,
dosageLogic: data.dosageLogic,
suitableFor: data.suitableFor,
imageUrl: data.imageUrl,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
slug: data.slug || data.artNo,
}
});
}
async updateProduct(id: string, data: any) {
return this.prisma.product.update({
where: { id },
data: {
artNo: data.artNo,
name: data.name,
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
categoryId: data.categoryId,
categorySlug: data.categorySlug,
priceValue: data.priceValue,
priceDisplay: data.priceDisplay,
unit: data.unit,
packageSize: data.packageSize,
dosageLogic: data.dosageLogic,
suitableFor: data.suitableFor,
imageUrl: data.imageUrl,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
slug: data.slug || data.artNo,
}
});
}
async deleteProduct(id: string) {
return this.prisma.product.delete({
where: { id },
});
}
async getOrders(query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.search) {
where.id = { contains: query.search };
}
if (query.status) {
where.status = query.status;
}
const [data, total] = await Promise.all([
this.prisma.order.findMany({
where, skip, take: limit, orderBy: { createdAt: 'desc' },
include: { user: true, orderItems: true }
}),
this.prisma.order.count({ where })
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
}
async updateOrderStatus(id: string, status: string) {
return this.prisma.order.update({
where: { id },
data: { status }
});
}
// --- Coupons Engine ---
async getCoupons(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { code: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.coupon.findMany({
where,
skip,
take: Number(limit),
orderBy: { createdAt: 'desc' },
include: { targets: true } // Include polymorphic targets
}),
this.prisma.coupon.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async createCoupon(data: any) {
return this.prisma.coupon.create({
data: {
code: data.code,
type: data.type || 'percent',
value: data.value,
minCartValue: data.minCartValue || null,
maxCartValue: data.maxCartValue || null,
maxUses: data.maxUses || null,
expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
isActive: data.isActive !== undefined ? data.isActive : true,
targets: data.targets && data.targets.length > 0 ? {
create: data.targets.map((t: any) => ({
targetType: t.targetType,
targetId: t.targetId,
modifierType: t.modifierType || 'override',
modifierValue: t.modifierValue || null
}))
} : undefined
},
include: { targets: true }
});
}
async updateCoupon(id: string, data: any) {
// Delete old targets and recreate them
await this.prisma.couponTarget.deleteMany({ where: { couponId: id } });
return this.prisma.coupon.update({
where: { id },
data: {
code: data.code,
type: data.type,
value: data.value,
minCartValue: data.minCartValue,
maxCartValue: data.maxCartValue,
maxUses: data.maxUses,
expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
isActive: data.isActive,
targets: data.targets && data.targets.length > 0 ? {
create: data.targets.map((t: any) => ({
targetType: t.targetType,
targetId: t.targetId,
modifierType: t.modifierType || 'override',
modifierValue: t.modifierValue || null
}))
} : undefined
},
include: { targets: true }
});
}
async toggleCoupon(id: string, isActive: boolean) {
return this.prisma.coupon.update({
where: { id },
data: { isActive }
});
}
async deleteCoupon(id: string) {
return this.prisma.coupon.delete({
where: { id }
});
}
// --- Settings ---
async getSettings() {
const keys = ['SHIPPING_FEE', 'MIN_ORDER_AMOUNT', 'B2B_DISCOUNT_PERCENT', 'MAINTENANCE_MODE'];
const settings = await this.prisma.uiText.findMany({
where: { key: { in: keys } }
});
// Transform to an object { SHIPPING_FEE: '50000', ... }
return settings.reduce((acc, curr) => ({ ...acc, [curr.key]: curr.value }), {});
}
async updateSettings(data: Record<string, string>) {
// Upsert all keys
const operations = Object.entries(data).map(([key, value]) => {
return this.prisma.uiText.upsert({
where: { key },
update: { value: String(value) },
create: { key, value: String(value) }
});
});
await this.prisma.$transaction(operations);
return this.getSettings();
}
}
+42
View File
@@ -0,0 +1,42 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
import { BlogsService } from './blogs.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
@ApiTags('Admin - مدیریت مقالات (بلاگ)')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('admin/blogs')
export class BlogsController {
constructor(private readonly blogsService: BlogsService) {}
@Get()
@ApiOperation({ summary: 'لیست مقالات' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getBlogs(@Query() query: any) {
return this.blogsService.getBlogs(query);
}
@Post()
@ApiOperation({ summary: 'ایجاد مقاله جدید' })
async createBlog(@Body() body: any, @Request() req: any) {
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 };
}
}
+48
View File
@@ -0,0 +1,48 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { title: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where,
skip,
take: Number(limit),
orderBy: { createdAt: 'desc' },
include: { author: { select: { firstName: true, lastName: true } } }
}),
this.prisma.blog.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async createBlog(data: any, authorId: string) {
return this.prisma.blog.create({
data: { ...data, authorId }
});
}
async updateBlog(id: string, data: any) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.update({ where: { id }, data });
}
async deleteBlog(id: string) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.delete({ where: { id } });
}
}
@@ -0,0 +1,49 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { CategoriesService } from './categories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
@ApiTags('Admin - مدیریت دسته‌بندی‌ها')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('admin/categories')
export class CategoriesController {
constructor(private readonly categoriesService: CategoriesService) {}
@Get()
@ApiOperation({ summary: 'لیست دسته‌بندی‌ها (با صفحه‌بندی)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو در نام' })
async getCategories(@Query() query: any) {
return this.categoriesService.getCategories(query);
}
@Get('all')
@ApiOperation({ summary: 'لیست تمام دسته‌بندی‌ها (بدون صفحه‌بندی)' })
async getAllCategoriesRaw() {
const data = await this.categoriesService.getAllCategoriesRaw();
return { success: true, data };
}
@Post()
@ApiOperation({ summary: 'ایجاد دسته‌بندی جدید' })
async createCategory(@Body() body: any) {
const data = await this.categoriesService.createCategory(body);
return { success: true, data };
}
@Put(':id')
@ApiOperation({ summary: 'ویرایش دسته‌بندی' })
async updateCategory(@Param('id') id: string, @Body() body: any) {
const data = await this.categoriesService.updateCategory(id, body);
return { success: true, data };
}
@Delete(':id')
@ApiOperation({ summary: 'حذف دسته‌بندی' })
async deleteCategory(@Param('id') id: string) {
await this.categoriesService.deleteCategory(id);
return { success: true };
}
}
+62
View File
@@ -0,0 +1,62 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class CategoriesService {
constructor(private prisma: PrismaService) {}
async getCategories(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { name: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.category.findMany({
where,
skip,
take: Number(limit),
orderBy: { createdAt: 'desc' }
}),
this.prisma.category.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async getAllCategoriesRaw() {
return this.prisma.category.findMany({ orderBy: { name: 'asc' } });
}
async createCategory(data: any) {
const cleanData = { ...data };
Object.keys(cleanData).forEach(k => {
if (cleanData[k] === '') cleanData[k] = null;
});
// Ensure required fields
if (!cleanData.slug) cleanData.slug = cleanData.name.replace(/\s+/g, '-').toLowerCase();
return this.prisma.category.create({ data: cleanData });
}
async updateCategory(id: string, data: any) {
const category = await this.prisma.category.findUnique({ where: { id } });
if (!category) throw new NotFoundException('Category not found');
const cleanData = { ...data };
Object.keys(cleanData).forEach(k => {
if (cleanData[k] === '') cleanData[k] = null;
});
return this.prisma.category.update({ where: { id }, data: cleanData });
}
async deleteCategory(id: string) {
const category = await this.prisma.category.findUnique({ where: { id } });
if (!category) throw new NotFoundException('Category not found');
return this.prisma.category.delete({ where: { id } });
}
}
+38
View File
@@ -0,0 +1,38 @@
import { Controller, Get, Post, Delete, Param, UseGuards, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MediaService } from './media.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
@ApiTags('Admin - مدیریت رسانه (تصاویر)')
@ApiBearerAuth()
@Controller('admin/media')
export class MediaController {
constructor(private readonly mediaService: MediaService) {}
@UseGuards(JwtAuthGuard)
@Get()
@ApiOperation({ summary: 'لیست فایل‌های رسانه' })
async getAllMedia() {
const data = await this.mediaService.getAllMedia();
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Post('upload')
@ApiOperation({ summary: 'آپلود فایل جدید' })
@UseInterceptors(FileInterceptor('file'))
async uploadFile(@UploadedFile() file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is missing');
const data = await this.mediaService.uploadFile(file);
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Delete(':id')
@ApiOperation({ summary: 'حذف فایل' })
async deleteMedia(@Param('id') id: string) {
const data = await this.mediaService.deleteMedia(id);
return { success: true, data };
}
}
+60
View File
@@ -0,0 +1,60 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import * as path from 'path';
import * as fs from 'fs';
@Injectable()
export class MediaService {
constructor(private prisma: PrismaService) {}
async getAllMedia() {
return this.prisma.media.findMany({
orderBy: { createdAt: 'desc' }
});
}
async uploadFile(file: Express.Multer.File) {
if (!file) {
throw new BadRequestException('No file uploaded');
}
const uploadDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = path.extname(file.originalname);
const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename);
fs.writeFileSync(filePath, file.buffer);
// Assuming we serve static files from '/uploads' route prefix
const url = `/uploads/${filename}`;
const media = await this.prisma.media.create({
data: {
filename: file.originalname,
url,
mimetype: file.mimetype,
size: file.size,
}
});
return media;
}
async deleteMedia(id: string) {
const media = await this.prisma.media.findUnique({ where: { id } });
if (!media) throw new BadRequestException('Media not found');
const filePath = path.join(process.cwd(), 'uploads', path.basename(media.url));
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
await this.prisma.media.delete({ where: { id } });
return { success: true };
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Controller, Get, Delete, Param, Query, UseGuards } from '@nestjs/common';
import { PetsService } from './pets.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
@ApiTags('Admin - مدیریت حیوانات خانگی')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('admin/pets')
export class PetsController {
constructor(private readonly petsService: PetsService) {}
@Get()
@ApiOperation({ summary: 'لیست حیوانات خانگی' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getPets(@Query() query: any) {
return this.petsService.getPets(query);
}
@Delete(':id')
@ApiOperation({ summary: 'حذف حیوان خانگی' })
async deletePet(@Param('id') id: string) {
await this.petsService.deletePet(id);
return { success: true };
}
}
+36
View File
@@ -0,0 +1,36 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class PetsService {
constructor(private prisma: PrismaService) {}
async getPets(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { name: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.pet.findMany({
where,
skip,
take: Number(limit),
orderBy: { createdAt: 'desc' },
include: { user: { select: { firstName: true, lastName: true, email: true, mobile: true } } }
}),
this.prisma.pet.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async deletePet(id: string) {
const pet = await this.prisma.pet.findUnique({ where: { id } });
if (!pet) throw new NotFoundException('Pet not found');
return this.prisma.pet.delete({ where: { id } });
}
}
+19
View File
@@ -0,0 +1,19 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ReportsService } from './reports.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
@ApiTags('Admin - گزارشات')
@ApiBearerAuth()
@Controller('admin/reports')
export class ReportsController {
constructor(private readonly reportsService: ReportsService) {}
@UseGuards(JwtAuthGuard)
@Get()
@ApiOperation({ summary: 'دریافت گزارشات داشبورد' })
async getReports() {
const data = await this.reportsService.getDashboardReports();
return { success: true, data };
}
}
+103
View File
@@ -0,0 +1,103 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class ReportsService {
constructor(private prisma: PrismaService) {}
async getDashboardReports() {
// 1. Total revenue and charity
const orders = await this.prisma.order.findMany({
where: { status: { not: 'cancelled' } },
select: { totalAmount: true, charityDonation: true, createdAt: true, user: { select: { role: true } } }
});
let totalRevenue = 0;
let totalCharity = 0;
let b2bRevenue = 0;
let b2cRevenue = 0;
const salesByDate: Record<string, number> = {};
for (const order of orders) {
const amount = Number(order.totalAmount);
totalRevenue += amount;
totalCharity += Number(order.charityDonation);
if (order.user?.role === 'B2B') {
b2bRevenue += amount;
} else {
b2cRevenue += amount;
}
// Format date YYYY-MM-DD
const dateKey = order.createdAt.toISOString().split('T')[0];
if (!salesByDate[dateKey]) salesByDate[dateKey] = 0;
salesByDate[dateKey] += amount;
}
// Format sales timeline for charts
const salesTimeline = Object.entries(salesByDate)
.map(([date, amount]) => ({ date, amount }))
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
// 2. Best selling products (by quantity)
const orderItems = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: { order: { status: { not: 'cancelled' } }, productId: { not: null } },
orderBy: { _sum: { quantity: 'desc' } },
take: 5
});
// Fetch product names for top 5
const topProductsIds = orderItems.map(item => item.productId).filter(Boolean) as string[];
const productsInfo = await this.prisma.product.findMany({
where: { id: { in: topProductsIds } },
select: { id: true, name: true }
});
const bestSellers = orderItems.map(item => {
const p = productsInfo.find(prod => prod.id === item.productId);
return {
name: p ? p.name : 'محصول نامشخص',
quantity: item._sum.quantity || 0
};
});
// 3. Category Distribution
const categorySales: Record<string, number> = {};
for (const item of orderItems) {
if (item.productId) {
// Since we didn't fetch category id in the grouping, we'll approximate with full product list query
}
}
const categories = await this.prisma.category.findMany({ include: { products: { select: { id: true } } } });
const catSalesDist = categories.map(cat => {
const pIds = cat.products.map(p => p.id);
const catSales = orderItems.filter(oi => oi.productId && pIds.includes(oi.productId)).reduce((sum, oi) => sum + (oi._sum.quantity || 0), 0);
return { name: cat.name, value: catSales };
}).filter(c => c.value > 0);
// 4. Coupons Usage
const topCoupons = await this.prisma.coupon.findMany({
orderBy: { usedCount: 'desc' },
take: 5,
select: { code: true, usedCount: true }
});
return {
overview: {
totalRevenue,
totalCharity,
totalOrders: orders.length,
b2bRevenue,
b2cRevenue,
},
salesTimeline,
bestSellers,
categoryDistribution: catSalesDist,
topCoupons: topCoupons.map(c => ({ name: c.code, value: c.usedCount }))
};
}
}
+42
View File
@@ -0,0 +1,42 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { WikiService } from './wiki.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
@ApiTags('Admin - مدیریت دانشنامه (اصطلاحات علمی)')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('admin/wiki')
export class WikiController {
constructor(private readonly wikiService: WikiService) {}
@Get()
@ApiOperation({ summary: 'لیست اصطلاحات دانشنامه' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getTerms(@Query() query: any) {
return this.wikiService.getTerms(query);
}
@Post()
@ApiOperation({ summary: 'ایجاد اصطلاح جدید' })
async createTerm(@Body() body: any) {
const data = await this.wikiService.createTerm(body);
return { success: true, data };
}
@Put(':key')
@ApiOperation({ summary: 'ویرایش اصطلاح' })
async updateTerm(@Param('key') key: string, @Body() body: any) {
const data = await this.wikiService.updateTerm(key, body);
return { success: true, data };
}
@Delete(':key')
@ApiOperation({ summary: 'حذف اصطلاح' })
async deleteTerm(@Param('key') key: string) {
await this.wikiService.deleteTerm(key);
return { success: true };
}
}
+45
View File
@@ -0,0 +1,45 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class WikiService {
constructor(private prisma: PrismaService) {}
async getTerms(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { term: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.scientificTerm.findMany({
where,
skip,
take: Number(limit),
orderBy: { term: 'asc' }
}),
this.prisma.scientificTerm.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async createTerm(data: any) {
return this.prisma.scientificTerm.create({ data });
}
async updateTerm(key: string, data: any) {
const term = await this.prisma.scientificTerm.findUnique({ where: { key } });
if (!term) throw new NotFoundException('Scientific Term not found');
return this.prisma.scientificTerm.update({ where: { key }, data });
}
async deleteTerm(key: string) {
const term = await this.prisma.scientificTerm.findUnique({ where: { key } });
if (!term) throw new NotFoundException('Scientific Term not found');
return this.prisma.scientificTerm.delete({ where: { key } });
}
}
+15
View File
@@ -3,6 +3,7 @@ import { PrismaModule } from './prisma/prisma.module';
import { ProductsModule } from './products/products.module';
import { UsersModule } from './users/users.module';
import { RedisModule } from './redis/redis.module';
import { RedisService } from './redis/redis.service';
import { AuthModule } from './auth/auth.module';
import { PetsModule } from './pets/pets.module';
import { OrdersModule } from './orders/orders.module';
@@ -10,6 +11,10 @@ import { SettingsModule } from './settings/settings.module';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
import { MetricsController } from './common/metrics.controller';
import { AdminModule } from './admin/admin.module';
import { HomeModule } from './home/home.module';
import { BlogsModule } from './blogs/blogs.module';
import { WikiModule } from './wiki/wiki.module';
@Module({
imports: [
@@ -25,6 +30,10 @@ import { MetricsController } from './common/metrics.controller';
ttl: 60000,
limit: 100,
}]),
AdminModule,
HomeModule,
BlogsModule,
WikiModule,
],
controllers: [MetricsController],
providers: [
@@ -32,13 +41,19 @@ import { MetricsController } from './common/metrics.controller';
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
RedisService,
],
})
export class AppModule implements NestModule {
constructor(private readonly redisService: RedisService) {}
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req: any, res: any, next: () => void) => {
MetricsController.incrementRequestCount();
// Increment daily visits counter in Redis (fire-and-forget)
const todayKey = `visits:${new Date().toISOString().split('T')[0]}`;
this.redisService.incr(todayKey, 86400).catch(() => {}); // TTL = 24h
next();
})
.exclude('metrics')
+29
View File
@@ -2,6 +2,8 @@ import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestResponse } from '@nestjs/swagger';
@ApiTags('Auth - احراز هویت')
@@ -91,4 +93,31 @@ export class AuthController {
verifyOtp(@Body() verifyOtpDto: VerifyOtpDto) {
return this.authService.verifyOtp(verifyOtpDto);
}
@Post('register')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'ثبت‌نام با ایمیل/موبایل و رمز عبور' })
@ApiOkResponse({ description: 'کاربر با موفقیت ثبت‌نام شد' })
@ApiBadRequestResponse({ description: 'اطلاعات ثبت‌نام نامعتبر است یا کاربر از قبل وجود دارد' })
register(@Body() registerDto: RegisterDto) {
return this.authService.register(registerDto);
}
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'ورود با موبایل و رمز عبور' })
@ApiOkResponse({ description: 'ورود موفق به همراه توکن دسترسی' })
@ApiBadRequestResponse({ description: 'نام کاربری یا رمز عبور اشتباه است' })
login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
@Post('admin-login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'ورود ادمین به پنل مدیریت' })
@ApiOkResponse({ description: 'ورود موفق ادمین به همراه توکن' })
@ApiBadRequestResponse({ description: 'اطلاعات ورود ادمین اشتباه است' })
adminLogin(@Body() body: any) {
return this.authService.adminLogin(body);
}
}
+6 -3
View File
@@ -53,13 +53,16 @@ describe('AuthService', () => {
});
describe('sendOtp', () => {
it('should generate a 5 digit OTP and save it in Redis', async () => {
it('should generate a 5 digit OTP, save it in Redis, and not expose it in response', async () => {
const result = await service.sendOtp({ phoneNumber: '09123456789' });
expect(result.success).toBe(true);
expect(result.code).toHaveLength(5);
expect(result.message).toBe('کد تایید ارسال شد');
// Code should NOT be in the response (security)
expect((result as any).code).toBeUndefined();
// But it should have been stored in Redis
expect(redis.set).toHaveBeenCalledWith(
'otp:09123456789',
result.code,
expect.stringMatching(/^\d{5}$/),
120,
);
});
+87 -2
View File
@@ -4,6 +4,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
@@ -17,11 +18,13 @@ export class AuthService {
const { phoneNumber } = sendOtpDto;
const code = Math.floor(10000 + Math.random() * 90000).toString();
console.log(`[Mock SMS] Sending OTP ${code} to ${phoneNumber}`);
// In production: replace this log with a real SMS provider (e.g. KaveNegar, Melipayamak)
console.log(`[Dev SMS] OTP for ${phoneNumber}: ${code}`);
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
return { success: true, message: 'کد تایید ارسال شد', code };
// SECURITY: Never return the OTP code in the response
return { success: true, message: 'کد تایید ارسال شد' };
}
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
@@ -63,4 +66,86 @@ export class AuthService {
},
};
}
async register(registerDto: any) {
const { firstName, lastName, email, mobile, password } = registerDto;
const existingUser = await this.prisma.user.findUnique({ where: { mobile } });
if (existingUser) {
throw new BadRequestException({ message: 'کاربری با این شماره موبایل قبلا ثبت نام کرده است', error: 'MOBILE_EXISTS' });
}
if (email) {
const existingEmail = await this.prisma.user.findUnique({ where: { email } });
if (existingEmail) {
throw new BadRequestException({ message: 'کاربری با این ایمیل قبلا ثبت نام کرده است', error: 'EMAIL_EXISTS' });
}
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.prisma.user.create({
data: {
firstName,
lastName,
email: email || null,
mobile,
password: hashedPassword,
},
});
const payload = { sub: user.id, phoneNumber: user.mobile };
const accessToken = this.jwtService.sign(payload);
return {
success: true,
data: {
user,
accessToken,
},
};
}
async login(loginDto: any) {
const { mobile, password } = loginDto;
const user = await this.prisma.user.findUnique({ where: { mobile } });
if (!user) {
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
}
if (!user.password) {
throw new BadRequestException({ message: 'شما با رمز عبور ثبت نام نکرده‌اید. لطفاً با موبایل وارد شوید', error: 'NO_PASSWORD' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
}
const payload = { sub: user.id, phoneNumber: user.mobile };
const accessToken = this.jwtService.sign(payload);
return {
success: true,
data: {
user,
accessToken,
},
};
}
async adminLogin(body: any) {
if (body.email === 'admin@canino-iran.com' && body.password === 'admin123') {
const payload = { sub: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' };
return {
success: true,
data: {
user: { id: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' },
accessToken: this.jwtService.sign(payload),
},
};
}
throw new BadRequestException({ message: 'ایمیل یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
}
}
+14
View File
@@ -0,0 +1,14 @@
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({ description: 'شماره موبایل', example: '09123456789' })
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
@IsString()
mobile: string;
@ApiProperty({ description: 'رمز عبور', example: 'password123' })
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password: string;
}
+29
View File
@@ -0,0 +1,29 @@
import { IsEmail, IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class RegisterDto {
@ApiProperty({ description: 'نام', example: 'علی' })
@IsNotEmpty({ message: 'نام الزامی است' })
@IsString()
firstName: string;
@ApiProperty({ description: 'نام خانوادگی', example: 'رضایی' })
@IsNotEmpty({ message: 'نام خانوادگی الزامی است' })
@IsString()
lastName: string;
@ApiPropertyOptional({ description: 'ایمیل (اختیاری)', example: 'ali@example.com' })
@IsOptional()
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
email?: string;
@ApiProperty({ description: 'شماره موبایل', example: '09123456789' })
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
@IsString()
mobile: string;
@ApiProperty({ description: 'رمز عبور', example: 'password123' })
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password: string;
}
+5
View File
@@ -14,6 +14,11 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}
async validate(payload: any) {
// Bypass DB lookup for local admin user to prevent UUID casting errors
if (payload.sub === '12345678-1234-1234-1234-123456789012') {
return { id: payload.sub, email: payload.email, role: payload.role };
}
const user = await this.usersService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException('کاربر یافت نشد');
+29
View File
@@ -0,0 +1,29 @@
import { Controller, Get, Param, HttpStatus, Query } from '@nestjs/common';
import { BlogsService } from './blogs.service';
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiNotFoundResponse, ApiQuery } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
@ApiTags('Blogs - مجله سلامت')
@Controller('blogs')
@ApiResponse({
status: HttpStatus.INTERNAL_SERVER_ERROR,
description: 'خطای داخلی سرور'
})
export class BlogsController {
constructor(private readonly blogsService: BlogsService) {}
@Get()
@ApiOperation({ summary: 'دریافت لیست مقالات مجله سلامت' })
@ApiOkResponse({ description: 'لیست مقالات منتشر شده (صفحه‌بندی شده)' })
findAll(@Query() query: PaginationDto) {
return this.blogsService.findAll(query);
}
@Get(':slug')
@ApiOperation({ summary: 'دریافت مقاله با اسلاگ (Slug)' })
@ApiOkResponse({ description: 'اطلاعات کامل مقاله' })
@ApiNotFoundResponse({ description: 'مقاله یافت نشد' })
findOne(@Param('slug') slug: string) {
return this.blogsService.findOneBySlug(slug);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { BlogsService } from './blogs.service';
import { BlogsController } from './blogs.controller';
@Module({
controllers: [BlogsController],
providers: [BlogsService],
})
export class BlogsModule {}
+64
View File
@@ -0,0 +1,64 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async findAll(filters: PaginationDto) {
const { search, page = 1, limit = 10, sortBy = 'createdAt', sortOrder = 'desc' } = filters;
const whereClause: any = { isPublished: true };
if (search) {
whereClause.OR = [
{ title: { contains: search, mode: 'insensitive' } },
{ content: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
include: {
author: {
select: { firstName: true, lastName: true }
}
}
}),
this.prisma.blog.count({ where: whereClause })
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
}
};
}
async findOneBySlug(slug: string) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
include: {
author: {
select: { firstName: true, lastName: true }
}
}
});
if (!blog) {
throw new NotFoundException('مقاله یافت نشد');
}
return blog;
}
}
+1
View File
@@ -0,0 +1 @@
export class CreateBlogDto {}
+4
View File
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateBlogDto } from './create-blog.dto';
export class UpdateBlogDto extends PartialType(CreateBlogDto) {}
@@ -0,0 +1 @@
export class Blog {}
+39
View File
@@ -0,0 +1,39 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsInt, Min, IsString, IsEnum } from 'class-validator';
import { Type } from 'class-transformer';
export enum SortOrder {
ASC = 'asc',
DESC = 'desc',
}
export class PaginationDto {
@ApiPropertyOptional({ description: 'شماره صفحه (شروع از ۱)', minimum: 1, default: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number = 1;
@ApiPropertyOptional({ description: 'تعداد آیتم‌ها در هر صفحه', minimum: 1, default: 10 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
limit?: number = 10;
@ApiPropertyOptional({ description: 'فیلد برای مرتب‌سازی', default: 'createdAt' })
@IsOptional()
@IsString()
sortBy?: string = 'createdAt';
@ApiPropertyOptional({ description: 'جهت مرتب‌سازی (asc/desc)', enum: SortOrder, default: SortOrder.DESC })
@IsOptional()
@IsEnum(SortOrder)
sortOrder?: SortOrder = SortOrder.DESC;
@ApiPropertyOptional({ description: 'عبارت جستجو' })
@IsOptional()
@IsString()
search?: string;
}
@@ -9,10 +9,27 @@ export class HttpExceptionFilter implements ExceptionFilter {
const status = exception.getStatus();
const exceptionResponse: any = exception.getResponse();
let message = typeof exceptionResponse === 'string' ? exceptionResponse : (exceptionResponse.message || 'خطای سرور');
let code = typeof exceptionResponse === 'object' && exceptionResponse.error ? exceptionResponse.error : (status === 400 ? 'BAD_REQUEST' : 'ERROR');
// Convert array of class-validator errors to a generic Farsi message if it's a 400
if (Array.isArray(message) && status === 400) {
message = 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.';
} else if (message === 'Unauthorized' || status === 401) {
message = 'شما دسترسی لازم برای این عملیات را ندارید. لطفاً وارد شوید.';
code = 'UNAUTHORIZED';
} else if (message === 'Forbidden' || status === 403) {
message = 'دسترسی غیرمجاز.';
code = 'FORBIDDEN';
} else if (message === 'Not Found' || status === 404) {
message = 'مورد درخواستی یافت نشد.';
code = 'NOT_FOUND';
}
response.status(status).json({
success: false,
message: typeof exceptionResponse === 'string' ? exceptionResponse : (exceptionResponse.message || 'خطای سرور'),
code: exceptionResponse.error || (status === 400 ? 'BAD_REQUEST' : 'ERROR'),
message,
code,
details: typeof exceptionResponse === 'object' ? exceptionResponse : {}
});
}
+9 -9
View File
@@ -1,7 +1,7 @@
import { Controller, Get, Res } from '@nestjs/common';
import { ApiExcludeController } from '@nestjs/swagger';
import { PrismaService } from '../../src/prisma/prisma.service';
import { Response } from 'express';
import { PrismaService } from '../prisma/prisma.service';
import * as express from 'express';
@ApiExcludeController()
@Controller('metrics')
@@ -15,7 +15,7 @@ export class MetricsController {
}
@Get()
async getMetrics(@Res() res: Response) {
async getMetrics(@Res() res: express.Response) {
const memory = process.memoryUsage();
const cpu = process.cpuUsage();
@@ -52,13 +52,13 @@ node_cpu_system_time_microseconds ${cpu.system}
# TYPE node_app_uptime_seconds gauge
node_app_uptime_seconds ${uptime}
# HELP canina_db_connected Database connection status (1 = connected, 0 = disconnected).
# TYPE canina_db_connected gauge
canina_db_connected ${dbStatus}
# HELP canino_db_connected Database connection status (1 = connected, 0 = disconnected).
# TYPE canino_db_connected gauge
canino_db_connected ${dbStatus}
# HELP canina_http_requests_total Total HTTP requests processed.
# TYPE canina_http_requests_total counter
canina_http_requests_total ${MetricsController.requestCount}
# HELP canino_http_requests_total Total HTTP requests processed.
# TYPE canino_http_requests_total counter
canino_http_requests_total ${MetricsController.requestCount}
`;
res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
export class ApiErrorResponse {
@ApiProperty({ description: 'موفقیت‌آمیز بودن درخواست', example: false })
success: boolean;
@ApiProperty({ description: 'پیام خطا', example: 'اطلاعات وارد شده نامعتبر است. لطفاً فرم را بررسی کنید.' })
message: string;
@ApiProperty({ description: 'کد خطا', example: 'BAD_REQUEST' })
code: string;
@ApiProperty({ description: 'جزئیات خطا (در صورت وجود)', required: false, example: {} })
details?: any;
}
@@ -0,0 +1,43 @@
import { ApiProperty } from '@nestjs/swagger';
export class PaginationMeta {
@ApiProperty({ description: 'تعداد کل آیتم‌ها', example: 100 })
total: number;
@ApiProperty({ description: 'شماره صفحه فعلی', example: 1 })
page: number;
@ApiProperty({ description: 'تعداد کل صفحات', example: 10 })
lastPage: number;
@ApiProperty({ description: 'تعداد آیتم‌ها در هر صفحه', example: 10 })
limit: number;
}
export class PaginatedResponse<T> {
@ApiProperty({ description: 'آرایه آیتم‌ها' })
data: T[];
@ApiProperty({ description: 'اطلاعات صفحه‌بندی' })
meta: PaginationMeta;
}
export function createPaginatedSchema(dtoModel: any) {
return {
schema: {
allOf: [
{
properties: {
data: {
type: 'array',
items: { $ref: `#/components/schemas/${dtoModel.name}` },
},
meta: {
$ref: '#/components/schemas/PaginationMeta',
},
},
},
],
},
};
}
+1
View File
@@ -0,0 +1 @@
export class CreateHomeDto {}
+4
View File
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateHomeDto } from './create-home.dto';
export class UpdateHomeDto extends PartialType(CreateHomeDto) {}
+1
View File
@@ -0,0 +1 @@
export class Home {}
+20
View File
@@ -0,0 +1,20 @@
import { Controller, Get, HttpStatus } from '@nestjs/common';
import { HomeService } from './home.service';
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse } from '@nestjs/swagger';
@ApiTags('Home - صفحه اصلی')
@Controller('home')
@ApiResponse({
status: HttpStatus.INTERNAL_SERVER_ERROR,
description: 'خطای داخلی سرور'
})
export class HomeController {
constructor(private readonly homeService: HomeService) {}
@Get()
@ApiOperation({ summary: 'دریافت اطلاعات صفحه اصلی' })
@ApiOkResponse({ description: 'اطلاعات ویترین، بنرها، پرفروش‌ترین‌ها، وبلاگ و غیره' })
getHomeData() {
return this.homeService.getHomeData();
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { HomeService } from './home.service';
import { HomeController } from './home.controller';
@Module({
controllers: [HomeController],
providers: [HomeService],
})
export class HomeModule {}
+52
View File
@@ -0,0 +1,52 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class HomeService {
constructor(private prisma: PrismaService) {}
async getHomeData() {
// Fetch Banners
const heroBanners = await this.prisma.heroBanner.findMany({
where: { isActive: true },
orderBy: { order: 'asc' },
});
// Fetch Vet Testimonials
const vetTestimonials = await this.prisma.vetTestimonial.findMany({
where: { isActive: true },
orderBy: { order: 'asc' },
});
// Fetch Smart Advisor Rules
const smartAdvisorRules = await this.prisma.smartAdvisorRule.findMany({
include: {
product: {
select: {
id: true,
name: true,
slug: true,
imageUrl: true,
priceValue: true,
priceDisplay: true,
categorySlug: true,
categoryId: true
}
}
}
});
// We can also fetch featured products here if needed, or rely on a separate endpoint
const featuredProducts = await this.prisma.product.findMany({
take: 4,
orderBy: { createdAt: 'desc' }, // Or any other criteria
});
return {
heroBanners,
vetTestimonials,
smartAdvisorRules,
featuredProducts
};
}
}
+11 -4
View File
@@ -1,12 +1,19 @@
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { join } from 'path';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import helmet from 'helmet';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// Serve static uploads folder
app.useStaticAssets(join(process.cwd(), 'uploads'), {
prefix: '/uploads/',
});
app.use(helmet({
contentSecurityPolicy: false, // Avoid blocking Swagger UI scripts and assets
@@ -27,8 +34,8 @@ async function bootstrap() {
app.useGlobalFilters(new HttpExceptionFilter());
const config = new DocumentBuilder()
.setTitle('Canina Iran API')
.setDescription('API Documentation for Canina Iran Pet Health & Supplement Platform')
.setTitle('Canino Iran API')
.setDescription('API Documentation for Canino Iran Pet Health & Supplement Platform')
.setVersion('1.0.0')
.addBearerAuth()
.build();
@@ -36,6 +43,6 @@ async function bootstrap() {
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);
await app.listen(process.env.PORT ?? 3000);
await app.listen(process.env.PORT ?? 4001);
}
bootstrap();
@@ -20,6 +20,11 @@ export class CreateOrderDto {
@IsString()
petId?: string;
@ApiPropertyOptional({ description: 'کد تخفیف (اختیاری)' })
@IsOptional()
@IsString()
couponCode?: string;
@ApiProperty({ description: 'لیست اقلام سفارش', type: [OrderItemDto] })
@IsArray()
@ValidateNested({ each: true })
+53 -14
View File
@@ -1,8 +1,19 @@
import { Controller, Get, Post, Body, Param, UseGuards, Req, HttpStatus } from '@nestjs/common';
import { Controller, Get, Post, Patch, Body, Param, UseGuards, Req, HttpStatus, Query } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { CreateOrderDto } from './dto/create-order.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse } from '@nestjs/swagger';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse, ApiBody } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
import { IsString, IsNumber, IsNotEmpty } from 'class-validator';
class ValidateCouponDto {
@IsString()
@IsNotEmpty()
code: string;
@IsNumber()
cartTotal: number;
}
@ApiTags('Orders - مدیریت سفارش‌ها')
@ApiBearerAuth()
@@ -55,25 +66,53 @@ export class OrdersController {
return this.ordersService.create(req.user.id, createOrderDto);
}
@Post('validate-coupon')
@ApiOperation({ summary: 'اعتبارسنجی کد تخفیف و محاسبه میزان تخفیف' })
@ApiOkResponse({
description: 'نتیجه اعتبارسنجی کد تخفیف',
schema: {
example: {
valid: true,
couponId: 'abc-123',
code: 'CANINO10',
type: 'percent',
discountValue: 175000,
message: 'کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف'
}
}
})
@ApiBadRequestResponse({ description: 'کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست' })
validateCoupon(@Req() req: any, @Body() body: ValidateCouponDto) {
return this.ordersService.validateCoupon(body.code, body.cartTotal, req.user.id);
}
@Get()
@ApiOperation({ summary: 'لیست سفارش‌های کاربر فعلی' })
@ApiOkResponse({
description: 'آرایه‌ای از سفارش‌های ثبت شده کاربر',
description: 'آرایه‌ای از سفارش‌های ثبت شده کاربر (صفحه‌بندی شده)',
schema: {
example: [
{
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
createdAt: '2026-05-26T18:10:00.000Z'
example: {
data: [
{
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
totalAmount: '3500000.00',
charityDonation: '10000.00',
status: 'processing',
createdAt: '2026-05-26T18:10:00.000Z'
}
],
meta: {
total: 1,
page: 1,
lastPage: 1,
limit: 10
}
]
}
}
})
findAll(@Req() req: any) {
return this.ordersService.findAllByUser(req.user.id);
findAll(@Req() req: any, @Query() query: PaginationDto) {
return this.ordersService.findAllByUser(req.user.id, query);
}
@Get(':id')
+112 -9
View File
@@ -1,13 +1,76 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreateOrderDto } from './dto/create-order.dto';
import { Decimal } from '@prisma/client/runtime/library';
@Injectable()
export class OrdersService {
constructor(private prisma: PrismaService) {}
private generateTrackingNumber(): string {
const date = new Date();
const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
const random = Math.floor(10000 + Math.random() * 90000);
return `CN-${dateStr}-${random}`;
}
async validateCoupon(code: string, cartTotal: number, userId: string) {
const coupon = await this.prisma.coupon.findUnique({
where: { code: code.toUpperCase().trim() },
include: { targets: true },
});
if (!coupon || !coupon.isActive) {
throw new BadRequestException({ message: 'کد تخفیف معتبر نیست یا منقضی شده است', error: 'COUPON_INVALID' });
}
if (coupon.expiresAt && new Date() > coupon.expiresAt) {
throw new BadRequestException({ message: 'کد تخفیف منقضی شده است', error: 'COUPON_EXPIRED' });
}
if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) {
throw new BadRequestException({ message: 'ظرفیت استفاده از این کد تخفیف تکمیل شده است', error: 'COUPON_LIMIT_REACHED' });
}
if (coupon.minCartValue && cartTotal < Number(coupon.minCartValue)) {
throw new BadRequestException({
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString('fa-IR')} تومان است`,
error: 'COUPON_MIN_CART'
});
}
// Check user-specific targets
const userTargets = coupon.targets.filter(t => t.targetType === 'USER');
if (userTargets.length > 0 && !userTargets.some(t => t.targetId === userId)) {
throw new BadRequestException({ message: 'این کد تخفیف برای حساب شما معتبر نیست', error: 'COUPON_NOT_FOR_USER' });
}
let discountValue: number;
if (coupon.type === 'percent') {
discountValue = cartTotal * (Number(coupon.value) / 100);
if (coupon.maxCartValue) {
discountValue = Math.min(discountValue, Number(coupon.maxCartValue));
}
} else {
discountValue = Number(coupon.value);
}
discountValue = Math.min(discountValue, cartTotal);
return {
valid: true,
couponId: coupon.id,
code: coupon.code,
type: coupon.type,
discountValue,
message: `کد تخفیف اعمال شد — ${discountValue.toLocaleString('fa-IR')} تومان تخفیف`,
};
}
async create(userId: string, createOrderDto: CreateOrderDto) {
let totalAmount = 0;
let couponId: string | null = null;
const orderItems = [];
for (const item of createOrderDto.items) {
@@ -26,10 +89,32 @@ export class OrdersService {
throw new BadRequestException('سبد خرید خالی است');
}
// Apply coupon if provided
let discountAmount = 0;
if (createOrderDto.couponCode) {
try {
const couponResult = await this.validateCoupon(createOrderDto.couponCode, totalAmount, userId);
discountAmount = couponResult.discountValue;
couponId = couponResult.couponId;
// Increment usedCount
await this.prisma.coupon.update({
where: { id: couponId },
data: { usedCount: { increment: 1 } },
});
} catch {
// Invalid coupon — ignore and proceed without discount
}
}
const finalAmount = Math.max(totalAmount - discountAmount, 0);
const trackingNumber = this.generateTrackingNumber();
return this.prisma.order.create({
data: {
userId,
totalAmount,
couponId,
totalAmount: finalAmount,
trackingNumber,
status: 'processing',
orderItems: {
create: orderItems,
@@ -43,14 +128,32 @@ export class OrdersService {
});
}
async findAllByUser(userId: string) {
return this.prisma.order.findMany({
where: { userId },
include: {
orderItems: { include: { product: true } },
},
orderBy: { createdAt: 'desc' },
});
async findAllByUser(userId: string, filters: PaginationDto) {
const { page = 1, limit = 10, sortBy = 'createdAt', sortOrder = 'desc' } = filters;
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.order.findMany({
where: { userId },
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
include: {
orderItems: { include: { product: true } },
},
}),
this.prisma.order.count({ where: { userId } })
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
}
};
}
async findOne(id: string, userId: string) {
@@ -0,0 +1,24 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
export class CreateHealthLogDto {
@ApiProperty({ description: 'وضعیت اشتها', example: 'عالی' })
@IsNotEmpty()
@IsString()
appetite: string;
@ApiProperty({ description: 'وضعیت انرژی', example: 'نرمال' })
@IsNotEmpty()
@IsString()
energy: string;
@ApiProperty({ description: 'وضعیت گوارش', example: 'نرمال' })
@IsNotEmpty()
@IsString()
digestion: string;
@ApiPropertyOptional({ description: 'یادداشت یا توضیح اضافی', example: 'امروز فعالیت خوبی داشت.' })
@IsOptional()
@IsString()
note?: string;
}
+12 -16
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional, IsNumber, IsBoolean, IsDateString } from 'class-validator';
import { IsNotEmpty, IsString, IsOptional, IsNumber, IsArray } from 'class-validator';
export class CreatePetDto {
@ApiProperty({ description: 'نام حیوان خانگی', example: 'بادی' })
@@ -17,28 +17,24 @@ export class CreatePetDto {
@IsString()
breed?: string;
@ApiPropertyOptional({ description: 'جنسیت', example: 'نر' })
@IsOptional()
@IsString()
gender?: string;
@ApiPropertyOptional({ description: 'وزن (کیلوگرم)', example: 25.5 })
@IsOptional()
@IsNumber()
weight?: number;
@ApiPropertyOptional({ description: 'تاریخ تولد' })
@ApiPropertyOptional({ description: 'سن (سال)', example: 3 })
@IsOptional()
@IsDateString()
birthDate?: string;
@IsNumber()
age?: number;
@ApiPropertyOptional({ description: 'عقیم شده است؟', example: false })
@IsOptional()
@IsBoolean()
isNeutered?: boolean;
@ApiPropertyOptional({ description: 'سوابق پزشکی مختصر' })
@ApiPropertyOptional({ description: 'سطح فعالیت', example: 'متوسط' })
@IsOptional()
@IsString()
medicalHistory?: string;
activityLevel?: string;
@ApiPropertyOptional({ description: 'سوابق پزشکی', type: [String] })
@IsOptional()
@IsArray()
@IsString({ each: true })
medicalConditions?: string[];
}
@@ -0,0 +1,24 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
export class CreateReminderDto {
@ApiProperty({ description: 'عنوان یادآور', example: 'قرص کلسیم' })
@IsNotEmpty()
@IsString()
title: string;
@ApiProperty({ description: 'زمان یادآور (مثال: 08:30)', example: '08:30' })
@IsNotEmpty()
@IsString()
time: string;
@ApiProperty({ description: 'دوره زمانی (روزانه / هفتگی)', example: 'روزانه' })
@IsNotEmpty()
@IsString()
frequency: string;
@ApiPropertyOptional({ description: 'شناسه محصول مربوطه', example: 'a1b2c3d4-1234-5678-abcd-ef1234567890' })
@IsOptional()
@IsString()
productId?: string;
}
+59 -17
View File
@@ -1,9 +1,12 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req, HttpStatus } from '@nestjs/common';
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req, HttpStatus, Query } from '@nestjs/common';
import { PetsService } from './pets.service';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
import { CreateReminderDto } from './dto/create-reminder.dto';
import { CreateHealthLogDto } from './dto/create-health-log.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
@ApiTags('Pets - مدیریت حیوانات خانگی')
@ApiBearerAuth()
@@ -61,26 +64,34 @@ export class PetsController {
@Get()
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر فعلی' })
@ApiOkResponse({
description: 'آرایه‌ای از حیوانات خانگی ثبت شده کاربر',
description: 'آرایه‌ای از حیوانات خانگی ثبت شده کاربر (صفحه‌بندی شده)',
schema: {
example: [
{
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z'
example: {
data: [
{
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z'
}
],
meta: {
total: 1,
page: 1,
lastPage: 1,
limit: 10
}
]
}
}
})
findAll(@Req() req: any) {
return this.petsService.findAllByUser(req.user.id);
findAll(@Req() req: any, @Query() query: PaginationDto) {
return this.petsService.findAllByUser(req.user.id, query);
}
@Get(':id')
@@ -176,4 +187,35 @@ export class PetsController {
remove(@Req() req: any, @Param('id') id: string) {
return this.petsService.remove(id, req.user.id);
}
@Post(':petId/reminders')
@ApiOperation({ summary: 'ثبت یادآور جدید برای پت' })
addReminder(
@Req() req: any,
@Param('petId') petId: string,
@Body() createReminderDto: CreateReminderDto,
) {
return this.petsService.addReminder(req.user.id, petId, createReminderDto);
}
@Post(':petId/reminders/:reminderId/toggle')
@ApiOperation({ summary: 'تغییر وضعیت انجام یادآور در یک تاریخ خاص' })
toggleReminder(
@Req() req: any,
@Param('petId') petId: string,
@Param('reminderId') reminderId: string,
@Body('date') date: string,
) {
return this.petsService.toggleReminder(req.user.id, petId, reminderId, date);
}
@Post(':petId/health-logs')
@ApiOperation({ summary: 'ثبت لاگ سلامت جدید برای پت' })
addHealthLog(
@Req() req: any,
@Param('petId') petId: string,
@Body() createHealthLogDto: CreateHealthLogDto,
) {
return this.petsService.addHealthLog(req.user.id, petId, createHealthLogDto);
}
}
+122 -12
View File
@@ -1,5 +1,6 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
@@ -8,30 +9,63 @@ export class PetsService {
constructor(private prisma: PrismaService) {}
async create(userId: string, createPetDto: CreatePetDto) {
const { name, type, breed, weight, age, activityLevel, medicalConditions } = createPetDto;
return this.prisma.pet.create({
data: {
name: createPetDto.name,
type: createPetDto.type,
breed: createPetDto.breed || '',
activityLevel: 'متوسط', // Default
age: 1, // Default
weight: createPetDto.weight || 0,
name,
type,
breed: breed || '',
activityLevel: activityLevel || 'متوسط',
age: age || 1,
weight: weight || 0,
userId,
medicalConditions: medicalConditions?.length ? {
create: medicalConditions.map(condition => ({ condition }))
} : undefined,
},
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
}
async findAllByUser(userId: string) {
return this.prisma.pet.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
});
async findAllByUser(userId: string, filters: PaginationDto) {
const { search, page = 1, limit = 10, sortBy = 'createdAt', sortOrder = 'desc' } = filters;
const whereClause: any = { userId };
if (search) {
whereClause.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ breed: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.pet.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
}),
this.prisma.pet.count({ where: whereClause })
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
}
};
}
async findOne(id: string, userId: string) {
const pet = await this.prisma.pet.findFirst({
where: { id, userId },
include: { reminders: true, healthLogs: true },
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
if (!pet) {
throw new NotFoundException('حیوان خانگی یافت نشد');
@@ -41,6 +75,11 @@ export class PetsService {
async update(id: string, userId: string, updatePetDto: UpdatePetDto) {
await this.findOne(id, userId); // Ensure it exists and belongs to user
if (updatePetDto.medicalConditions) {
await this.prisma.petMedicalCondition.deleteMany({ where: { petId: id } });
}
return this.prisma.pet.update({
where: { id },
data: {
@@ -48,7 +87,13 @@ export class PetsService {
type: updatePetDto.type,
breed: updatePetDto.breed,
weight: updatePetDto.weight,
age: updatePetDto.age,
activityLevel: updatePetDto.activityLevel,
medicalConditions: updatePetDto.medicalConditions ? {
create: updatePetDto.medicalConditions.map(condition => ({ condition }))
} : undefined,
},
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
}
@@ -58,4 +103,69 @@ export class PetsService {
where: { id },
});
}
async addReminder(userId: string, petId: string, data: any) {
await this.findOne(petId, userId);
return this.prisma.reminder.create({
data: {
petId,
productId: data.productId || null,
title: data.title,
time: data.time,
frequency: data.frequency,
},
});
}
async toggleReminder(userId: string, petId: string, reminderId: string, dateStr: string) {
await this.findOne(petId, userId);
const reminder = await this.prisma.reminder.findUnique({
where: { id: reminderId },
});
if (!reminder || reminder.petId !== petId) {
throw new NotFoundException('یادآور یافت نشد');
}
const dateParts = dateStr.split('-');
const completedDate = new Date(Date.UTC(Number(dateParts[0]), Number(dateParts[1]) - 1, Number(dateParts[2])));
const existingCompletion = await this.prisma.reminderCompletion.findUnique({
where: {
reminderId_completedDate: {
reminderId,
completedDate,
},
},
});
if (existingCompletion) {
await this.prisma.reminderCompletion.delete({
where: { id: existingCompletion.id },
});
return { completed: false };
} else {
await this.prisma.reminderCompletion.create({
data: {
reminderId,
completedDate,
},
});
return { completed: true };
}
}
async addHealthLog(userId: string, petId: string, data: any) {
await this.findOne(petId, userId);
return this.prisma.healthLog.create({
data: {
petId,
appetite: data.appetite,
energy: data.energy,
digestion: data.digestion,
note: data.note || null,
loggedDate: new Date(),
},
});
}
}
+4 -8
View File
@@ -1,19 +1,15 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, IsEnum } from 'class-validator';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class GetProductsDto {
@ApiPropertyOptional({ description: 'Filter by category slug' })
export class GetProductsDto extends PaginationDto {
@ApiPropertyOptional({ description: 'فیلتر بر اساس اسلاگ دسته‌بندی' })
@IsOptional()
@IsString()
category?: string;
@ApiPropertyOptional({ description: 'Filter by pet type', enum: ['سگ', 'گربه', 'all'] })
@ApiPropertyOptional({ description: 'فیلتر بر اساس نوع حیوان', enum: ['سگ', 'گربه', 'all'] })
@IsOptional()
@IsEnum(['سگ', 'گربه', 'all'])
petType?: string;
@ApiPropertyOptional({ description: 'Search query string' })
@IsOptional()
@IsString()
query?: string;
}
+29 -21
View File
@@ -25,28 +25,36 @@ export class ProductsController {
@ApiOkResponse({
description: 'لیست محصولات متناسب با فیلترها (دسته، پت و جستجو)',
schema: {
example: [
{
id: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
artNo: 'canhydrox-gag',
name: 'Canhydrox GAG (کنهیدروکس)',
scientificTagline: 'برای تقویت مفاصل و استخوان‌ها',
description: 'کنهیدروکس محصولی بی‌نظیر برای مفاصل و سیستم حرکتی سگ‌ها...',
shortDescription: 'تقویت مفاصل و غضروف‌ها',
category: 'سیستم حرکتی و مفاصل',
categorySlug: 'joints',
priceValue: '1750000.00',
priceDisplay: '۱,۷۵۰,۰۰۰ تومان',
unit: 'عدد قرص',
packageSize: '120.00',
dosageLogic: 'یک قرص به ازای هر ۱۰ کیلوگرم وزن بدن سگ',
suitableFor: 'سگ',
imageUrl: 'https://example.com/canhydrox.png',
createdAt: '2026-05-26T18:10:00.000Z',
ingredients: [],
symptoms: []
example: {
data: [
{
id: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
artNo: 'canhydrox-gag',
name: 'Canhydrox GAG (کنهیدروکس)',
scientificTagline: 'برای تقویت مفاصل و استخوان‌ها',
description: 'کنهیدروکس محصولی بی‌نظیر برای مفاصل و سیستم حرکتی سگ‌ها...',
shortDescription: 'تقویت مفاصل و غضروف‌ها',
category: 'سیستم حرکتی و مفاصل',
categorySlug: 'joints',
priceValue: '1750000.00',
priceDisplay: '۱,۷۵۰,۰۰۰ تومان',
unit: 'عدد قرص',
packageSize: '120.00',
dosageLogic: 'یک قرص به ازای هر ۱۰ کیلوگرم وزن بدن سگ',
suitableFor: 'سگ',
imageUrl: 'https://example.com/canhydrox.png',
createdAt: '2026-05-26T18:10:00.000Z',
ingredients: [],
symptoms: []
}
],
meta: {
total: 1,
page: 1,
lastPage: 1,
limit: 10
}
]
}
}
})
findAll(@Query() query: GetProductsDto) {
+32 -15
View File
@@ -7,7 +7,7 @@ export class ProductsService {
constructor(private prisma: PrismaService) {}
async findAll(filters: GetProductsDto) {
const { category, petType, query } = filters;
const { category, petType, search, page = 1, limit = 10, sortBy = 'createdAt', sortOrder = 'desc' } = filters;
const whereClause: any = {};
@@ -19,27 +19,44 @@ export class ProductsService {
whereClause.suitableFor = { in: [petType, 'هر دو'] };
}
if (query) {
if (search) {
whereClause.OR = [
{ name: { contains: query, mode: 'insensitive' } },
{ description: { contains: query, mode: 'insensitive' } },
{ name: { contains: search, mode: 'insensitive' } },
{ description: { contains: search, mode: 'insensitive' } },
];
}
const products = await this.prisma.product.findMany({
where: whereClause,
include: {
ingredients: true,
symptoms: true,
},
});
const skip = (page - 1) * limit;
return products;
const [data, total] = await Promise.all([
this.prisma.product.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
include: {
ingredients: true,
symptoms: true,
},
}),
this.prisma.product.count({ where: whereClause }),
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
},
};
}
async findOne(id: string) {
return this.prisma.product.findUnique({
where: { id },
async findOne(idOrSlug: string) {
const isUuid = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(idOrSlug);
return this.prisma.product.findFirst({
where: isUuid ? { id: idOrSlug } : { slug: idOrSlug },
include: {
ingredients: true,
symptoms: true,
+9
View File
@@ -31,4 +31,13 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async del(key: string): Promise<void> {
await this.client.del(key);
}
async incr(key: string, ttlSeconds?: number): Promise<number> {
const count = await this.client.incr(key);
// Set expiry only on the first increment (count === 1)
if (count === 1 && ttlSeconds) {
await this.client.expire(key, ttlSeconds);
}
return count;
}
}
+27 -1
View File
@@ -1,4 +1,4 @@
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req, HttpStatus } from '@nestjs/common';
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req, HttpStatus, BadRequestException } from '@nestjs/common';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse } from '@nestjs/swagger';
@@ -169,4 +169,30 @@ export class UsersController {
setDefaultAddress(@Req() req: any, @Param('addressId') addressId: string) {
return this.usersService.setDefaultAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard)
@Post('wallet/top-up')
@ApiOperation({ summary: 'شارژ کیف پول کاربر' })
@ApiCreatedResponse({
description: 'کیف پول با موفقیت شارژ شد',
schema: {
example: {
id: 'txn-uuid',
userId: 'user-uuid',
amount: '500000.00',
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
createdAt: '2026-07-11T08:00:00.000Z'
}
}
})
@ApiBadRequestResponse({ description: 'مبلغ نامعتبر است' })
async topUpWallet(@Req() req: any, @Body() body: { amount: number }) {
const amount = Number(body.amount);
if (!amount || amount <= 0) {
throw new BadRequestException('مبلغ شارژ باید بزرگتر از صفر باشد');
}
return this.usersService.topUpWallet(req.user.id, amount);
}
}
+40 -2
View File
@@ -9,8 +9,19 @@ export class UsersService {
return this.prisma.user.findUnique({
where: { id },
include: {
pets: true,
pets: {
include: {
medicalConditions: true,
reminders: {
include: {
completions: true
}
},
healthLogs: true,
}
},
orders: {
orderBy: { createdAt: 'desc' },
include: {
orderItems: {
include: { product: true }
@@ -18,7 +29,10 @@ export class UsersService {
}
},
addresses: true,
walletTransactions: true
walletTransactions: {
orderBy: { createdAt: 'desc' },
take: 50
}
}
});
}
@@ -103,6 +117,30 @@ export class UsersService {
});
}
async topUpWallet(userId: string, amount: number) {
if (amount <= 0) {
throw new Error('مبلغ شارژ باید بزرگتر از صفر باشد');
}
const [transaction] = await this.prisma.$transaction([
this.prisma.walletTransaction.create({
data: {
userId,
amount,
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
},
}),
this.prisma.user.update({
where: { id: userId },
data: { walletBalance: { increment: amount } },
}),
]);
return transaction;
}
async findByPhone(phoneNumber: string) {
return this.prisma.user.findUnique({
where: { mobile: phoneNumber },
+1
View File
@@ -0,0 +1 @@
export class CreateWikiDto {}
+4
View File
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateWikiDto } from './create-wiki.dto';
export class UpdateWikiDto extends PartialType(CreateWikiDto) {}
+1
View File
@@ -0,0 +1 @@
export class Wiki {}
+29
View File
@@ -0,0 +1,29 @@
import { Controller, Get, Param, HttpStatus, Query } from '@nestjs/common';
import { WikiService } from './wiki.service';
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiNotFoundResponse } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
@ApiTags('Wiki - دانشنامه ترکیبات')
@Controller('wiki')
@ApiResponse({
status: HttpStatus.INTERNAL_SERVER_ERROR,
description: 'خطای داخلی سرور'
})
export class WikiController {
constructor(private readonly wikiService: WikiService) {}
@Get()
@ApiOperation({ summary: 'دریافت تمام کلمات دانشنامه' })
@ApiOkResponse({ description: 'لیست کلمات به همراه توضیحات (صفحه‌بندی شده)' })
findAll(@Query() query: PaginationDto) {
return this.wikiService.findAll(query);
}
@Get(':key')
@ApiOperation({ summary: 'دریافت ترکیب علمی با کلید' })
@ApiOkResponse({ description: 'اطلاعات کامل ترکیب علمی' })
@ApiNotFoundResponse({ description: 'ترکیب علمی یافت نشد' })
findOne(@Param('key') key: string) {
return this.wikiService.findOneByKey(key);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { WikiService } from './wiki.service';
import { WikiController } from './wiki.controller';
@Module({
controllers: [WikiController],
providers: [WikiService],
})
export class WikiModule {}
+50
View File
@@ -0,0 +1,50 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
@Injectable()
export class WikiService {
constructor(private prisma: PrismaService) {}
async findAll(filters: PaginationDto) {
const { search, page = 1, limit = 10, sortBy = 'term', sortOrder = 'asc' } = filters;
const whereClause: any = {};
if (search) {
whereClause.OR = [
{ term: { contains: search, mode: 'insensitive' } },
{ definition: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.scientificTerm.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
}),
this.prisma.scientificTerm.count({ where: whereClause })
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
}
};
}
async findOneByKey(key: string) {
const term = await this.prisma.scientificTerm.findUnique({
where: { key }
});
if (!term) throw new NotFoundException('Wiki term not found');
return term;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
"exclude": ["node_modules", "test", "dist", "**/*spec.ts", "prisma"]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

+15 -15
View File
@@ -2,21 +2,21 @@ version: '3.8'
services:
db:
image: postgres:16-alpine
container_name: canina_db
image: docker.arvancloud.ir/library/postgres:16-alpine
container_name: canino_db
restart: always
environment:
POSTGRES_USER: canina
POSTGRES_PASSWORD: caninapassword
POSTGRES_DB: caninadb
POSTGRES_USER: canino
POSTGRES_PASSWORD: caninopassword
POSTGRES_DB: caninodb
ports:
- "5432:5432"
- "5433:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
container_name: canina_redis
image: docker.arvancloud.ir/library/redis:7-alpine
container_name: canino_redis
restart: always
ports:
- "16379:6379"
@@ -25,10 +25,10 @@ services:
build:
context: ./backend
dockerfile: Dockerfile
container_name: canina_backend
container_name: canino_backend
restart: always
environment:
- DATABASE_URL=postgresql://canina:caninapassword@db:5432/caninadb?schema=public
- DATABASE_URL=postgresql://canino:caninopassword@db:5432/caninodb?schema=public
- REDIS_HOST=redis
- REDIS_PORT=6379
- PORT=3000
@@ -42,7 +42,7 @@ services:
build:
context: .
dockerfile: Dockerfile
container_name: canina_frontend
container_name: canino_frontend
restart: always
ports:
- "3001:8080"
@@ -50,8 +50,8 @@ services:
- backend
prometheus:
image: prom/prometheus:v2.51.0
container_name: canina_prometheus
image: docker.arvancloud.ir/prom/prometheus:v2.51.0
container_name: canino_prometheus
restart: always
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
@@ -61,8 +61,8 @@ services:
- backend
grafana:
image: grafana/grafana:10.4.1
container_name: canina_grafana
image: docker.arvancloud.ir/grafana/grafana:10.4.1
container_name: canino_grafana
restart: always
ports:
- "3002:3000"
+39
View File
@@ -0,0 +1,39 @@
# معرفی پروژه کانینو ایران (Canino Iran)
## این پروژه چیست؟
سامانه «کانینو ایران» پلتفرم تخصصی معرفی، فروش و مدیریت مکمل‌های درمانی حیوانات خانگی با گرید دارویی است. این سامانه به عنوان درگاه آنلاین نماینده انحصاری کانینو آلمان در ایران فعالیت می‌کند. هدف اصلی پروژه، ارائه یک تجربه کاربری (UX) بسیار غنی، سریع و در کلاس جهانی برای خریداران، کلینیک‌های دامپزشکی (مشتریان B2B) و همچنین فراهم‌کردن ابزارهای هوشمند (مانند مشاوره هوشمند و دانشنامه ترکیبات دارویی) است.
## قابلیت‌های کلیدی سامانه
سامانه به گونه‌ای طراحی شده تا تمام نیازهای یک کسب‌وکار مدرن e-commerce را در کنار قابلیت‌های تخصصی حوزه سلامت حیوانات برآورده کند:
- **فروشگاه آنلاین پیشرفته:** نمایش و فروش محصولات با قابلیت جستجوی هوشمند، دسته‌بندی دقیق و ارائه اطلاعات تخصصی دارویی.
- **مشاور هوشمند سلامت:** ابزار هوش مصنوعی یا سیستم مبتنی بر قوانین برای پیشنهاد مکمل بر اساس نوع، سن و نیازهای حیوان خانگی.
- **دانشنامه ترکیبات (Ingredient Wiki):** مرجع کامل برای معرفی ترکیبات موثره، ویتامین‌ها و فرمولاسیون مکمل‌ها.
- **پروفایل حیوان خانگی (Pet Profile):** ثبت اطلاعات حیوانات خانگی توسط کاربر برای دریافت پیشنهادات شخصی‌سازی شده.
- **پورتال اختصاصی فروش عمده (B2B Portal):** سیستم قیمت‌گذاری و سفارش‌دهی ویژه برای کلینیک‌های دامپزشکی و داروخانه‌ها.
- **سیستم مدیریت سفارش و سبد خرید:** شامل پیگیری لحظه‌ای سفارش، استفاده از کدهای تخفیف و کیف پول مجازی.
- **سئوی بسیار پیشرفته:** تولید متادیتا داینامیک، JSON-LD و سایت‌مپ زنده برای دیده شدن در موتورهای جستجو.
## تکنولوژی‌های استفاده شده و دلیل انتخاب آن‌ها (Tech Stack)
### بخش فرانت‌اند (Frontend)
- **فریم‌ورک Next.js 15 (App Router):**
- **چرا؟** برای بهره‌مندی از رندرینگ سمت سرور (SSR) و تولید صفحات استاتیک (SSG) که سرعت بارگذاری بسیار بالا و سئوی (SEO) خارق‌العاده‌ای را فراهم می‌کند. همچنین سیستم Routing جدید آن توسعه را ساختاریافته‌تر می‌کند.
- **مدیریت State با Zustand:**
- **چرا؟** جایگزینی سبک، سریع و بدون boilerplate برای Redux. برای مدیریت سبد خرید، اطلاعات کاربر و تنظیمات UI در سمت کلاینت عالی است.
- **استایل‌دهی با TailwindCSS:**
- **چرا؟** توسعه سریع رابط کاربری بدون نیاز به فایل‌های CSS جداگانه. امکان پیاده‌سازی سریع دیزاین‌سیستم‌ها و Responsive Design.
- **انیمیشن‌ها با Framer Motion:**
- **چرا؟** ایجاد انیمیشن‌ها و ترانزیشن‌های روان و حرفه‌ای (Micro-interactions) که حس یک وب‌اپلیکیشن بسیار لوکس (Premium) را به کاربر منتقل می‌کند.
- **ارتباط با API از طریق Axios:**
- **چرا؟** مدیریت راحت‌تر اینترسپتورها (Interceptors) برای توکن‌های احراز هویت و مدیریت خطاها در ارتباط با بک‌اند.
### بخش بک‌اند (Backend)
- **فریم‌ورک NestJS:**
- **چرا؟** ایجاد یک معماری ماژولار، مقیاس‌پذیر و مبتنی بر کلاس (Enterprise-level) در محیط Node.js که با TypeScript به صورت Native سازگار است و نگهداری کدهای بزرگ را آسان می‌کند.
- **پایگاه‌داده PostgreSQL:**
- **چرا؟** یک دیتابیس رابطه‌ای بسیار قدرتمند، امن و استاندارد که یکپارچگی داده‌ها (Data Integrity) در سیستم‌های فروشگاهی (مانند سفارشات و تراکنش‌های مالی) را تضمین می‌کند.
- **مدیریت دیتابیس با Prisma ORM:**
- **چرا؟** ارائه Type-safety کامل بین دیتابیس و کدهای TypeScript. مایگریشن‌های ساده و جلوگیری از خطاهای رایج در نوشتن کوئری‌های SQL.
### نتیجه‌گیری معماری
ترکیب `Next.js` و `NestJS` معماری مدرن و کاملاً جداشده (Decoupled) ایجاد کرده است. فرانت‌اند وظیفه ارائه تجربه کاربری سریع و سئو شده را دارد و بک‌اند مانند یک سرویس قدرتمند (API) امنیت، لاجیک‌های تجاری و پایداری داده‌ها را تضمین می‌کند.
+33
View File
@@ -0,0 +1,33 @@
# راهنمای کاربری سیستم (User Guide)
سیستم کانینو از نظر نوع مخاطب به دو دسته کلی B2C (مشتریان عادی) و B2B (کلینیک‌ها و فروشگاه‌ها) تقسیم می‌شود. علاوه بر این، نقش «ادمین» برای مدیریت سیستم وجود دارد.
## ۱. مشتریان عادی (B2C Users)
مشتری عادی کسی است که وارد سایت می‌شود تا برای حیوان خانگی خود مکمل خریداری کند یا اطلاعات کسب کند.
### کاربر چه کارهایی می‌تواند انجام دهد؟
- **جستجو و کشف محصول:** می‌تواند محصولات را بر اساس دسته‌بندی‌ها (سگ، گربه، نوع بیماری، ویتامین‌ها) فیلتر کرده و جستجو کند.
- **مشاهده جزئیات دقیق محصول:** مطالعه مشخصات دارویی، ترکیبات، نحوه مصرف، نظرات و همچنین قیمت و وضعیت موجودی.
- **استفاده از دانشنامه (Wiki):** مطالعه درباره مواد موثره به کار رفته در محصولات (مانند بیوتین، گلوکزآمین) و دیدن محصولات مرتبط با هر ماده.
- **ثبت پروفایل حیوان خانگی (Pet Profile):** کاربر می‌تواند اطلاعات حیوانات خود (نام، نژاد، سن، وضعیت عقیم‌سازی، بیماری‌های زمینه‌ای) را ثبت کند. سیستم از این اطلاعات برای شخصی‌سازی محصولات استفاده می‌کند.
- **مشاوره هوشمند (Smart Advisor):** با وارد کردن مشخصات حیوان و مشکلی که دارد (مثلاً ریزش مو یا مشکل مفاصل)، سیستم بهترین مکمل‌های موجود را به صورت هوشمند پیشنهاد می‌دهد.
- **مدیریت سبد خرید و سفارش:** افزودن محصولات به سبد، استفاده از کدهای تخفیف، استفاده از موجودی کیف پول و در نهایت پرداخت از طریق درگاه بانکی.
- **پیگیری سفارش:** مشاهده وضعیت سفارشات (در حال بررسی، ارسال شده، تحویل داده شده).
## ۲. مشتریان تجاری (B2B Users / کلینیک‌ها و داروخانه‌ها)
این دسته از کاربران پس از ثبت‌نام و تایید هویت توسط ادمین، به پورتال B2B دسترسی پیدا می‌کنند.
### کاربر B2B چه کارهایی می‌تواند انجام دهد؟
- **مشاهده قیمت‌های همکاری:** محصولات را با قیمت عمده یا درصد تخفیف ویژه همکاری مشاهده می‌کنند.
- **ثبت سفارشات عمده (Bulk Order):** رابط کاربری ویژه‌ای برای سفارش سریع محصولات در تعداد بالا دارند، بدون اینکه نیازی باشد وارد صفحه تک‌تک محصولات شوند.
- **پرداخت اعتباری/چکی:** در صورت تایید مدیریت، قابلیت پرداخت غیرنقدی یا ثبت اسناد در سیستم برای آن‌ها فعال می‌شود.
## ۳. مدیران سیستم (Admins)
مدیران از طریق پنل مدیریت (که جدا از رابط کاربری اصلی است) سیستم را کنترل می‌کنند.
### مدیر چه کارهایی می‌تواند انجام دهد؟
- **مدیریت محصولات:** تعریف محصول جدید، مدیریت موجودی انبار، تغییر قیمت‌ها و تنظیم متادیتای سئو.
- **مدیریت کاربران و نقش‌ها:** تایید حساب‌های B2B، مدیریت سطوح دسترسی.
- **مدیریت سفارشات:** تغییر وضعیت سفارشات (به ارسال شده و...) و ثبت کدهای پیگیری پستی.
- **گزارش‌گیری:** مشاهده گزارش فروش، محصولات پرطرفدار و وضعیت مالی کیف پول‌ها.
- **مدیریت محتوا:** نوشتن مقالات بلاگ و اطلاعات دانشنامه دارویی.
+78
View File
@@ -0,0 +1,78 @@
# راهنمای توسعه‌دهندگان (Developer Guide)
این مستند مختص دولوپرها است و استانداردهای کدنویسی، نحوه مدیریت Stateها و معماری پوشه‌ها را شرح می‌دهد. این پروژه از معماری Monorepo (ولی در پوشه‌های مجزا) برای جداسازی Frontend و Backend استفاده می‌کند.
## ۱. ساختار پوشه‌ها (Folder Structure)
پروژه از دو پوشه اصلی تشکیل شده است:
### فولدر `frontend/application` (Next.js)
```text
frontend/application/
├── app/ # صفحات (Pages) و Layout ها بر اساس Next.js App Router
│ ├── api/ # مسیرهای (Route Handlers) سمت بک‌اند Next.js (در صورت نیاز)
│ ├── shop/ # صفحات مربوط به فروشگاه
│ ├── blog/ # صفحات وبلاگ
│ └── ...
├── components/ # کامپوننت‌های React (دکمه‌ها، فرم‌ها، هدر، مودال‌ها)
├── lib/ # منطق تجاری سمت فرانت‌اند
│ ├── services/ # توابع ارتباط با API بک‌اند (استفاده از Axios)
│ ├── store/ # استورهای Zustand (Cart, User, Pet و...)
│ └── utils/ # توابع کمکی (فرمت‌دهی تاریخ، اعداد، ترکیب کلاس‌های tailwind)
└── public/ # فایل‌های استاتیک، تصاویر خام، فونت‌ها
```
### فولدر `backend` (NestJS)
```text
backend/
├── prisma/ # شمای دیتابیس (schema.prisma) و مایگریشن‌ها
├── src/
│ ├── modules/ # ماژول‌های مستقل (Users, Products, Orders و...)
│ ├── common/ # گاردهای امنیتی (Guards)، دکوراتورها، اینترسپتورها
│ └── main.ts # نقطه ورود بک‌اند
```
## ۲. استانداردهای توسعه در Frontend
### کامپوننت‌ها (Components)
- تمامی فایل‌های کامپوننت باید در پوشه `components` قرار گیرند و با حرف بزرگ شروع شوند (`PascalCase`).
- کامپوننت‌ها باید در صورت امکان **Server Component** باشند. تنها زمانی که به هوک‌های React (مثل `useState`, `useEffect`) یا رویدادهای کاربری (`onClick`) نیاز است، از دایرکتیو `"use client"` در بالاترین خط فایل استفاده کنید.
- از Prop-drilling (ارسال پروپ‌ها به صورت آبشاری در لایه‌های زیاد) خودداری کنید. اگر دیتایی گلوبال است، از Zustand استفاده کنید.
### مدیریت State با Zustand
- فایل‌های State منحصراً در پوشه `lib/store/` ذخیره می‌شوند.
- نام فایل‌ها باید شامل کلمه `store` باشد (مثلاً `cartStore.ts`).
- هنگام نیاز به ذخیره ماندگار اطلاعات (مثل سبد خرید یا توکن)، از میدل‌ویر `persist` در Zustand استفاده کنید. این کار به صورت خودکار اطلاعات را در LocalStorage ذخیره و بازیابی می‌کند.
### ارتباط با شبکه (API & Fetching)
- ارتباطات سمت کلاینت با بک‌اند در فایل‌های پوشه `lib/services/` نوشته می‌شوند.
- در فایل `lib/services/api.ts` یک نمونه از Axios (`axios.create`) با کانفیگ‌های پایه و آدرس Base URL ساخته شده است.
- تمام Requestها باید تایپ‌کشی (Type-safe) شده باشند. رابط‌ها (Interfaces) مربوط به ریسپانس را صراحتاً مشخص کنید.
### سبک استایل‌دهی (TailwindCSS)
- استایل‌دهی باید فقط و فقط از طریق کلاس‌های Tailwind انجام شود.
- از کلاس کمکی `cn` (موجود در `lib/utils`) برای ترکیب کلاس‌های شرطی (Conditional Classes) استفاده کنید.
- رنگ‌های اختصاصی پروژه (مثل `canino-blue`, `medical-gray`) در فایل `tailwind.config.ts` تعریف شده‌اند و باید استفاده شوند، نه مقادیر هگزادسیمال خام.
## ۳. استانداردهای توسعه در Backend (NestJS)
### مدیریت دیتابیس
- شمای منبع حقیقت (Source of Truth) فایل `schema.prisma` است. برای افزودن یک جدول یا فیلد جدید، فقط این فایل را تغییر دهید.
- بعد از هر تغییر در `schema.prisma` دستور `npx prisma migrate dev --name <description>` را اجرا کنید تا تغییرات در دیتابیس اعمال شود و تایپ‌های Prisma کلاینت آپدیت شوند.
### کنترلرها و سرویس‌ها
- هیچ‌گونه لاجیک پیچیده‌ای نباید داخل فایل‌های `.controller.ts` نوشته شود. کنترلرها فقط وظیفه دریافت درخواست، اعتبارسنجی اولیه پارامترها و ارسال آن به سرویس را دارند.
- لاجیک اصلی تجاری را داخل فایل‌های `.service.ts` پیاده‌سازی کنید.
### امنیت و احراز هویت
- تمامی روت‌هایی که به کاربر لاگین شده نیاز دارند، باید با `@UseGuards(JwtAuthGuard)` محافظت شوند.
- روت‌های ادمین باید از گارد اختصاصی ترکیب شده با بررسی نقش کاربری استفاده کنند.
- رمزهای عبور کاربران پیش از ذخیره در دیتابیس **حتماً** باید با کتابخانه `bcrypt` هش شوند.
## ۴. چرخه توسعه ویژگی جدید (Feature Workflow)
هنگامی که یک توسعه‌دهنده می‌خواهد ویژگی جدیدی اضافه کند، این مراحل را طی می‌کند:
1. تعریف ساختار دیتابیس جدید در Prisma و مایگریشن.
2. ساخت ماژول در NestJS (شامل Entity, DTO, Service, Controller).
3. نوشتن توابع API فراخوانی در پوشه `lib/services` در فرانت‌اند.
4. پیاده‌سازی Store مربوطه در Zustand (اگر نیاز به State گلوبال دارد).
5. نوشتن و استایل‌دهی کامپوننت‌های UI در فرانت‌اند.
6. اتصال UI به اکشن‌های Store یا APIها.
+98
View File
@@ -0,0 +1,98 @@
# راه‌اندازی و انتشار سیستم (Setup & Deployment)
این بخش نحوه اجرای سامانه در محیط توسعه (Local) و فرآیند پابلیش کردن آن روی سرورهای Production را توضیح می‌دهد.
## ۱. محیط توسعه (Development Mode)
برای توسعه بر روی کامپیوتر شخصی، مراحل زیر را طی کنید:
### پیش‌نیازها
- **Node.js** (نسخه ۲۰ به بالا)
- **PostgreSQL** نصب شده و در حال اجرا بر روی سیستم شما.
### اجرای بک‌اند
1. وارد پوشه بک‌اند شوید: `cd backend`
2. پکیج‌ها را نصب کنید: `npm install`
3. فایل `.env` را ایجاد کنید و متغیر دیتابیس را به شکل زیر تنظیم کنید:
`DATABASE_URL="postgresql://user:password@localhost:5432/caninodb?schema=public"`
4. جداول را ایجاد کنید: `npx prisma db push` و سپس `npx prisma generate`
5. پروژه را در حالت توسعه اجرا کنید: `npm run start:dev`
6. بک‌اند شما اکنون روی پورت پیش‌فرض (معمولاً `3001` یا `3005`) در حال اجراست.
### اجرای فرانت‌اند
1. یک تب جدید در ترمینال باز کنید و وارد پوشه اپلیکیشن شوید: `cd frontend/application`
2. نصب پیش‌نیازها: `npm install`
3. ایجاد متغیرهای محیطی در فایل `.env.local`:
`NEXT_PUBLIC_API_URL=http://localhost:3001/api`
4. اجرای پروژه در حالت دولوپ: `npm run dev`
5. وب‌سایت در آدرس `http://localhost:3000` در دسترس است.
---
## ۲. محیط پروداکشن و انتشار (Production Deployment)
نحوه استقرار سامانه بر روی سرورهای اصلی به شرح زیر است. معمولاً این فرآیند بر روی سیستم‌عامل لینوکس (Ubuntu) انجام می‌گیرد.
### بیلد کردن پروژه (Building)
برای بک‌اند:
```bash
cd backend
npm run build
```
برای فرانت‌اند (تولید خروجی بسیار بهینه برای سرعت بالا و سئو):
```bash
cd frontend/application
npm run build
```
### اجرای پروژه در سرور با PM2
از ابزار [PM2](https://pm2.keymetrics.io/) برای اجرای مداوم (Daemon) و لودبالانسینگ پروسه‌ها استفاده می‌کنیم.
پس از نصب سراسری `npm install -g pm2`، دستورات زیر را در سرور اجرا کنید:
#### برای راه‌اندازی بک‌اند:
```bash
cd backend
pm2 start dist/main.js --name "canino-api"
```
#### برای راه‌اندازی فرانت‌اند Next.js:
```bash
cd frontend/application
pm2 start npm --name "canino-web" -- start
```
### ذخیره پروسه‌ها تا پس از ری‌استارت سرور قطع نشوند:
```bash
pm2 save
pm2 startup
```
---
## ۳. تنظیمات Nginx (Reverse Proxy)
سرور Nginx مسئول دریافت ترافیک عمومی و هدایت آن‌ها به پورت‌های صحیح لوکال است.
- ترافیک‌های دامنه `canino-iran.com` به پورت فرانت‌اند (`3000`) هدایت می‌شوند.
- ترافیک‌هایی که دارای آدرس `/api/` در مسیر خود هستند مستقیماً به پورت بک‌اند (`3001`) هدایت می‌شوند.
### نمونه فایل کانفیگ Nginx
```nginx
server {
listen 80;
server_name canino-iran.com www.canino-iran.com;
# ارسال ترافیک /api به Backend
location /api/ {
proxy_pass http://localhost:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# ارسال مابقی ترافیک به Frontend
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
+41
View File
@@ -0,0 +1,41 @@
# دواپس و مانیتورینگ سیستم (DevOps & Monitoring)
این مستند توضیحاتی در مورد پایش مستمر سامانه و اتوماسیون (CI/CD) پس از انتشار ارائه می‌دهد. هدف این است که اطمینان حاصل شود سرورها همیشه با بالاترین بهره‌وری در حال اجرا هستند و کدهای جدید با کمترین خطا دیپلوی می‌شوند.
## ۱. فرآیند استقرار خودکار (CI/CD)
در تیم‌های بزرگ برای جلوگیری از بروز خطای انسانی در سرور، از فرآیند استقرار خودکار استفاده می‌شود.
- کدهای جدید ابتدا در برنچ‌های مختلف توسعه داده شده و پس از تست (توسط GitHub Actions یا ابزارهای مشابه) به شاخه `main` یا `production` مرج می‌شوند.
- یک اکشن در گیت‌هاب پس از Push شدن کدهای جدید به صورت خودکار تغییرات را بیلد کرده و بر روی سرور کپی می‌کند.
- برای انجام دستی این کار یک اسکریپت در سرور وجود دارد که آخرین کدها را `git pull` کرده، دستورات نصب وابستگی و `npm run build` را اجرا و در نهایت سرویس‌های PM2 را ری‌استارت می‌کند.
## ۲. مانیتورینگ عملکرد (PM2 Dashboard)
با توجه به اینکه سامانه روی پلتفرم Node.js و از طریق مدیریت فرآیند `pm2` اجرا می‌شود، بهترین راه برای نظارت محلی (Local Server Monitoring) استفاده از دستورات زیر است:
- **مشاهده داشبورد منابع:**
```bash
pm2 monit
```
این دستور در ترمینال یک محیط گرافیکی را نشان می‌دهد که میزان مصرف CPU و RAM برای سرویس‌های فرانت‌اند و بک‌اند را نمایش می‌دهد.
- **مشاهده لیست وضعیت برنامه‌ها:**
```bash
pm2 list
```
نمایش Uptime (میزان زمان روشن ماندن) و وضعیت اجرا. اگر سرویسی Crash کرده باشد، در این لیست مشخص خواهد بود.
## ۳. بررسی لاگ‌های سیستم (Logs Management)
سیستم لاگین بک‌اند (NestJS) ارورهای پایگاه داده و ریکوئست‌های ناموفق را ثبت می‌کند. خطاهای رندرینگ فرانت‌اند نیز در لاگ‌های اجرای اپلیکیشن قابل ردیابی است.
- برای مشاهده لاگ‌های زنده سیستم از این دستور استفاده کنید:
```bash
pm2 logs
```
- برای فیلتر کردن لاگ‌های مشخص، مثلاً فقط بک‌اند:
```bash
pm2 logs canino-api --lines 100
```
## ۴. مانیتورینگ دیتابیس (PostgreSQL)
از آنجا که پایگاه داده یکی از گلوگاه‌های اصلی (Bottlenecks) سرعت در سیستم‌های فروشگاهی است، می‌توانید در صورت بروز کندی سیستم از ابزار `pg_stat_statements` برای ردیابی کوئری‌های کُند (Slow Queries) در دیتابیس استفاده کنید.
همچنین پیشنهاد می‌شود از دیتابیس به صورت دوره‌ای بک‌آپ گرفته و لاگ‌های بک‌آپ را در سرور مانیتورینگ نظارت کنید.
+44
View File
@@ -0,0 +1,44 @@
# راهنمای تست سیستم (Software Testing)
تست نرم‌افزار برای اطمینان از کیفیت (QA) کدهای نوشته شده، عدم وجود باگ و تضمین کارکرد صحیح سامانه قبل از انتشار بسیار حیاتی است. در این سامانه استراتژی‌های تست زیر به کار گرفته می‌شود.
## ۱. تست‌های واحد در Backend (Unit Testing)
از آنجا که سیستم بک‌اند ما با `NestJS` نوشته شده است، فریم‌ورک استاندارد تست آن یعنی `Jest` از پیش بر روی سیستم تنظیم شده است.
- **هدف:** در این لایه، تک‌تک Service ها و ماژول‌ها بدون نیاز به راه‌اندازی واقعی دیتابیس تست می‌شوند تا مطمئن شویم منطق محاسبه‌ها (مثل محاسبه تخفیف‌ها یا اتصال به درگاه) درست است.
- **نحوه نوشتن تست:** برای هر سرویس یک فایل در کنار آن با پسوند `.spec.ts` ایجاد می‌شود (مثلاً `product.service.spec.ts`).
- **اجرای تست‌ها:**
برای اجرای تست‌های واحد بک‌اند دستور زیر را اجرا کنید:
```bash
cd backend
npm run test
```
## ۲. تست‌های End-to-End در Backend (E2E Testing)
تست e2e کل چرخه را از درخواست کاربر تا ذخیره در دیتابیس بررسی می‌کند.
- **نحوه نوشتن تست:** تست‌های e2e در پوشه `backend/test/` قرار دارند و معمولاً به صورت ریکوئست‌های شبیه‌سازی شده HTTP از طریق ابزار `Supertest` ایجاد می‌شوند.
- **اجرای تست‌ها:**
```bash
cd backend
npm run test:e2e
```
## ۳. تست‌های UI در Frontend (Component Testing)
برای اینکه مطمئن شویم کامپوننت‌های رابط کاربری به درستی رندر می‌شوند و با کلیک کردن به استورها واکنش نشان می‌دهند، از سیستم تستی مثل `Jest` و `React Testing Library` استفاده می‌کنیم. (توجه: در صورت پیاده‌سازی این ابزار در سیستم).
- **مواردی که باید در فرانت‌اند تست شوند:**
- فرآیند افزودن محصول به سبد خرید (`cartStore`).
- رندرینگ صحیح اطلاعات دریافتی از `API`.
- اجرای صحیح و عدم بروز خطا در فرم‌های لاگین و اعتبارسنجی‌ها.
## ۴. تست‌های یکپارچگی سیستمی در Frontend (E2E Frontend - Playwright / Cypress)
برای شبیه‌سازی رفتار واقعی کاربر (کارهایی مثل باز کردن صفحه، کلیک روی یک دکمه و پرداخت سبد خرید) می‌توان از ابزارهایی مثل `Cypress` یا `Playwright` استفاده کرد. این ابزارها یک مرورگر واقعی را باز کرده و مراحل را طی می‌کنند. این نوع تست قبل از فرآیند Deployment روی سیستم اعمال می‌شود تا از اینکه یک بروزرسانی کل سیستم ثبت سفارش را از کار انداخته جلوگیری شود.
## ۵. چک لیست تست‌های دستی (Manual QA Checklist)
هیچ کدی بدون پاس کردن چک لیست زیر نباید روی سرور Production پابلیش شود:
1. قابلیت ثبت‌نام کاربر جدید و لاگین صحیح تست شده است؟
2. آیا محصول می‌تواند به سبد خرید اضافه شده و فرآیند Checkout بدون خطا نمایش داده شود؟
3. در موبایل (Responsive) آیا هدر، دکمه‌های ناوبری و گرید محصولات خوانا و قابل دسترس هستند؟
4. آیا درخواستی به بک‌اند وجود دارد که باعث بازگشت ارور 500 سرور شود؟
5. آیا عملکرد سئو (تولید تگ‌های Title و JSON-LD) در سورس پیج صحیح است؟
+30
View File
@@ -0,0 +1,30 @@
# مستندات توسعه‌دهندگان (Developer Documentation)
به مستندات رسمی سامانه «کانینو ایران» خوش آمدید. این مستندات به منظور راهنمایی توسعه‌دهندگان، مهندسین دواپس و تیم فنی شرکت نوشته شده است و نباید در دسترس کاربران عمومی قرار گیرد.
در این دایرکتوری تمامی ساختارها، معماری‌ها، قوانین کدنویسی و مراحل انتشار (Deployment) به دقت تدوین شده‌اند تا سرعت 온‌بوردینگ (Onboarding) توسعه‌دهندگان جدید افزایش یافته و نگهداری کدهای قدیمی با کمترین ریسک انجام شود.
## فهرست مطالب (Table of Contents)
لطفاً بر اساس نیاز خود به هر یک از بخش‌های زیر مراجعه کنید:
1. [معرفی پروژه و معماری (Introduction)](01-introduction.md)
- پروژه چیست، قابلیت‌های آن کدامند و چرا از این ابزارها (Next.js & NestJS) استفاده شده است.
2. [راهنمای کاربری و نقش‌ها (User Guide)](02-user-guide.md)
- انواع کاربران سیستم (کاربران عادی، تجاری و مدیران) و اینکه هر کدام قادر به انجام چه کارهایی هستند.
3. [راهنمای توسعه‌دهندگان (Developer Guide)](03-developer-guide.md)
- **(مهم‌ترین بخش برای دولوپرها)** ساختار پوشه‌ها، استانداردهای کدنویسی، مدیریت State و قوانین توسعه بک‌اند و فرانت‌اند.
4. [راه‌اندازی و انتشار سیستم (Setup & Deployment)](04-setup-and-deployment.md)
- نحوه اجرای محیط دولوپ روی سیستم شخصی، روند خروجی گرفتن (Build) و دستورات سرور پروداکشن با استفاده از PM2 و Nginx.
5. [دواپس و مانیتورینگ سیستم (DevOps & Monitoring)](05-devops-and-monitoring.md)
- مدیریت و بررسی سلامت سرور، لاگ‌گیری و خودکارسازی دیپلوی (CI/CD).
6. [راهنمای تست سیستم (Software Testing)](06-testing.md)
- انواع تست‌هایی که روی فرانت‌اند و بک‌اند انجام می‌گیرد و نحوه اجرای آن‌ها برای تضمین کیفیت کدها.
---
**توجه:** در صورت اضافه شدن ماژول‌ها و ابزارهای جدید به پروژه، لطفاً مستندات مربوطه را در همین پوشه بروزرسانی نمایید.
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+22
View File
@@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>admin-panel</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
{
"name": "admin-panel",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 5050 --host 127.0.0.1",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.101.0",
"axios": "^1.17.0",
"lucide-react": "^1.17.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-hot-toast": "^2.6.0",
"react-router-dom": "^7.17.0",
"recharts": "^3.8.1",
"zustand": "^5.0.14"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/postcss": "^4.3.0",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"autoprefixer": "^10.5.0",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+184
View File
@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
+44
View File
@@ -0,0 +1,44 @@
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import Layout from './components/Layout';
import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import ProtectedRoute from './components/ProtectedRoute';
import Users from './pages/Users';
import Products from './pages/Products';
import Orders from './pages/Orders';
import Coupons from './pages/Coupons';
import Settings from './pages/Settings';
import Reports from './pages/Reports';
import Categories from './pages/Categories';
import Blogs from './pages/Blogs';
import Wiki from './pages/Wiki';
import Pets from './pages/Pets';
function App() {
return (
<BrowserRouter>
<Toaster position="top-center" toastOptions={{ className: 'font-vazir' }} />
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route path="/" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="users" element={<Users />} />
<Route path="products" element={<Products />} />
<Route path="orders" element={<Orders />} />
<Route path="coupons" element={<Coupons />} />
<Route path="settings" element={<Settings />} />
<Route path="reports" element={<Reports />} />
<Route path="categories" element={<Categories />} />
<Route path="blogs" element={<Blogs />} />
<Route path="wiki" element={<Wiki />} />
<Route path="pets" element={<Pets />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more