Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ea6c6d271 | ||
|
|
140872c888 | ||
|
|
3dedc89ee1 | ||
|
|
a74f4bda48 | ||
|
|
756cb749b2 | ||
|
|
71f5ac2fa6 | ||
|
|
6db28f6231 | ||
|
|
1c07efcc91 | ||
|
|
f69537a688 | ||
|
|
2851ef8a25 | ||
|
|
24137beb32 | ||
|
|
e09adc03c3 | ||
|
|
dcfc4acae4 | ||
|
|
945c007a79 | ||
|
|
6027e635db | ||
|
|
82ab454647 | ||
|
|
69502fc380 | ||
|
|
a7ebb8d792 | ||
|
|
ee041d4e52 | ||
|
|
fa7333e93f | ||
|
|
29ab7f4141 | ||
|
|
d430a341f0 | ||
|
|
15ffe8a0e6 | ||
|
|
07b52f464c | ||
|
|
0b698859d9 | ||
|
|
beb8317fad | ||
|
|
060dc39fdd | ||
|
|
aea6fa4127 | ||
|
|
4dc8786847 | ||
|
|
222581c6a3 | ||
|
|
7fcfbda8cd | ||
|
|
95887738ea | ||
|
|
344be17b52 | ||
|
|
95760d78b5 | ||
|
|
c4966136d7 | ||
|
|
14bf2953ab | ||
|
|
88c3752238 | ||
|
|
700f93e418 | ||
|
|
bf1b11d6a9 | ||
|
|
0fa65c0802 | ||
|
|
ee0b8a5ff8 | ||
|
|
976dfcd610 | ||
|
|
3de0408e6f | ||
|
|
72d2a5600a | ||
|
|
c5a1b8e5d2 | ||
|
|
eff6c00a9c | ||
|
|
40d6393b16 | ||
|
|
4b69932409 | ||
|
|
40ff169dc2 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
# dist
|
||||
.env
|
||||
.git
|
||||
.dockerignore
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# نقشه جامع اتصال به بکبند (Comprehensive Backend Integration Map) 🏗️
|
||||
|
||||
این سند حاوی معماری دقیق، فهرست کامل نقاط اتصال (API Endpoints)، کامنتهای مکاننما در کد (TODO Markers)، و تعاریف رسمی تمامی تایپهای ورودی (Inputs) و خروجی (Outputs) پلتفرم درمانی و فروشگاهی کانینا ایران است.
|
||||
این سند حاوی معماری دقیق، فهرست کامل نقاط اتصال (API Endpoints)، کامنتهای مکاننما در کد (TODO Markers)، و تعاریف رسمی تمامی تایپهای ورودی (Inputs) و خروجی (Outputs) پلتفرم درمانی و فروشگاهی کانینو ایران است.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+5
-5
@@ -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"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+3
-12
@@ -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 nginx: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 80
|
||||
EXPOSE 8080
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -1,7 +1,7 @@
|
||||
# پلتفرم کانینا ایران (Canina Iran Platform) 🐾
|
||||
# پلتفرم کانینو ایران (Canino Iran Platform) 🐾
|
||||
### لندینگ، فروشگاه تخصصی و پرونده سلامت الکترونیک پت (نمایندگی رسمی دارویی Canina Pharma)
|
||||
|
||||
پلتفرم **کانینا ایران** یک برنامه جامع تحت وب (SPA/PWA) مجهز به بردهای تعاملی و ابزارهای بهداشتی-دامپزشکی است که با هدف ارتقای سلامت حیوانات خانگی و دسترسی آسانتر به مکملهای دارویی گرید فوقارگانیک و دارویی کمپانی والای **Canina pharma GmbH آلمان** توسعه یافته است.
|
||||
پلتفرم **کانینو ایران** یک برنامه جامع تحت وب (SPA/PWA) مجهز به بردهای تعاملی و ابزارهای بهداشتی-دامپزشکی است که با هدف ارتقای سلامت حیوانات خانگی و دسترسی آسانتر به مکملهای دارویی گرید فوقارگانیک و دارویی کمپانی والای **Canina pharma GmbH آلمان** توسعه یافته است.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+26
-7
@@ -1,38 +1,57 @@
|
||||
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
|
||||
# If we have prisma later, we need to copy generated client:
|
||||
# COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||
# COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
|
||||
# Copy generated prisma client:
|
||||
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
USER node
|
||||
|
||||
# Start the application
|
||||
CMD ["node", "dist/main"]
|
||||
Generated
+54
@@ -15,10 +15,13 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.4",
|
||||
"@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",
|
||||
"ioredis": "^5.11.0",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
@@ -33,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",
|
||||
@@ -2537,6 +2542,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/throttler": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/throttler/-/throttler-6.5.0.tgz",
|
||||
"integrity": "sha512-9j0ZRfH0QE1qyrj9JjIRDz5gQLPqq9yVC2nHsrosDVAfI5HHw08/aUAWx9DZLSdQf4HDkmhTTEGLrRFHENvchQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
||||
"@nestjs/core": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
|
||||
"reflect-metadata": "^0.1.13 || ^0.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
@@ -2819,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",
|
||||
@@ -2976,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",
|
||||
@@ -4327,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",
|
||||
@@ -6272,6 +6314,18 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/helmet": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.2.0.tgz",
|
||||
"integrity": "sha512-DRgTIUgnWcJ62KyarxxziuqYxKGnR6Rgg19BlbucN/dpmJbl1XOit6qvoOX0ZT+HhWe5OUVhU/a1zpGyc1xA0Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/EvanHahn"
|
||||
}
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
|
||||
|
||||
@@ -26,10 +26,13 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.4",
|
||||
"@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",
|
||||
"ioredis": "^5.11.0",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
@@ -44,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",
|
||||
@@ -83,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"
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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 }
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
+88
-86
@@ -7,115 +7,85 @@ import * as vm from 'vm';
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('Seeding database with products...');
|
||||
console.log('Wiping existing database records...');
|
||||
await prisma.reminderCompletion.deleteMany();
|
||||
await prisma.reminder.deleteMany();
|
||||
await prisma.healthLog.deleteMany();
|
||||
await prisma.petMedicalCondition.deleteMany();
|
||||
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();
|
||||
await prisma.productIngredient.deleteMany();
|
||||
await prisma.productSymptom.deleteMany();
|
||||
await prisma.product.deleteMany();
|
||||
await prisma.coupon.deleteMany();
|
||||
await prisma.uiText.deleteMany();
|
||||
await prisma.scientificTerm.deleteMany();
|
||||
await prisma.category.deleteMany();
|
||||
console.log('Database successfully wiped.');
|
||||
|
||||
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: [
|
||||
"مبارزه با باکتریهای مقاوم در دهان و پوست",
|
||||
"عدم آسیب به فلور طبیعی بدن",
|
||||
@@ -125,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([
|
||||
@@ -149,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: "آلودگی انگلی" }
|
||||
])
|
||||
};
|
||||
|
||||
@@ -163,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();
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 } });
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 } });
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 }))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 } });
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,62 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
|
||||
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';
|
||||
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: [PrismaModule, RedisModule, ProductsModule, UsersModule, AuthModule, PetsModule, OrdersModule, SettingsModule],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
imports: [
|
||||
PrismaModule,
|
||||
RedisModule,
|
||||
ProductsModule,
|
||||
UsersModule,
|
||||
AuthModule,
|
||||
PetsModule,
|
||||
OrdersModule,
|
||||
SettingsModule,
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60000,
|
||||
limit: 100,
|
||||
}]),
|
||||
AdminModule,
|
||||
HomeModule,
|
||||
BlogsModule,
|
||||
WikiModule,
|
||||
],
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
RedisService,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
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')
|
||||
.forRoutes('*');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
let service: AuthService;
|
||||
|
||||
const mockAuthService = {
|
||||
sendOtp: jest.fn().mockResolvedValue({ success: true, message: 'کد تایید ارسال شد' }),
|
||||
verifyOtp: jest.fn().mockResolvedValue({ success: true, data: { accessToken: 'token' } }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: mockAuthService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call sendOtp on service', async () => {
|
||||
const dto = { phoneNumber: '09123456789' };
|
||||
const result = await controller.sendOtp(dto);
|
||||
expect(service.sendOtp).toHaveBeenCalledWith(dto);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should call verifyOtp on service', async () => {
|
||||
const dto = { phoneNumber: '09123456789', code: '12345' };
|
||||
const result = await controller.verifyOtp(dto);
|
||||
expect(service.verifyOtp).toHaveBeenCalledWith(dto);
|
||||
expect(result.data.accessToken).toBe('token');
|
||||
});
|
||||
});
|
||||
@@ -2,26 +2,122 @@ 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 { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestResponse } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@ApiTags('Auth - احراز هویت')
|
||||
@Controller('auth')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'خطای ناشناخته در سرور رخ داده است',
|
||||
code: 'SERVER_ERROR',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('send-otp')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ارسال کد تایید پیامکی' })
|
||||
@ApiResponse({ status: 200, description: 'کد با موفقیت ارسال شد' })
|
||||
@ApiOperation({ summary: 'ارسال کد تایید پیامکی (OTP)' })
|
||||
@ApiOkResponse({
|
||||
description: 'کد با موفقیت ارسال شد (کد تایید در پاسخ بازگردانده میشود)',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'کد تایید ارسال شد',
|
||||
code: '12345'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'فرمت شماره تلفن همراه نامعتبر است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'شماره موبایل نامعتبر است',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {
|
||||
message: ['شماره موبایل نامعتبر است']
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
sendOtp(@Body() sendOtpDto: SendOtpDto) {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
}
|
||||
|
||||
@Post('verify-otp')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'تایید کد پیامکی و ورود/ثبتنام' })
|
||||
@ApiResponse({ status: 200, description: 'ورود موفق به همراه توکن' })
|
||||
@ApiOperation({ summary: 'تایید کد پیامکی و ورود/ثبتنام کاربر' })
|
||||
@ApiOkResponse({
|
||||
description: 'ورود موفق به همراه توکن دسترسی JWT و اطلاعات کاربر',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
firstName: 'کاربر',
|
||||
lastName: 'جدید',
|
||||
email: '09123456789@temp.local',
|
||||
mobile: '09123456789',
|
||||
role: 'User_PetOwner',
|
||||
walletBalance: '0.00',
|
||||
charityDonationTotal: '0.00',
|
||||
createdAt: '2026-05-26T15:20:00.000Z',
|
||||
updatedAt: '2026-05-26T15:20:00.000Z'
|
||||
},
|
||||
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'کد تایید اشتباه یا منقضی شده است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'کد تایید اشتباه است',
|
||||
code: 'OTP_INVALID',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
let prisma: PrismaService;
|
||||
let jwt: JwtService;
|
||||
let redis: RedisService;
|
||||
|
||||
const mockPrisma = {
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const mockJwt = {
|
||||
sign: jest.fn().mockReturnValue('mock-jwt-token'),
|
||||
};
|
||||
|
||||
const mockRedis = {
|
||||
set: jest.fn(),
|
||||
get: jest.fn(),
|
||||
del: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
{ provide: JwtService, useValue: mockJwt },
|
||||
{ provide: RedisService, useValue: mockRedis },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
jwt = module.get<JwtService>(JwtService);
|
||||
redis = module.get<RedisService>(RedisService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('sendOtp', () => {
|
||||
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.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',
|
||||
expect.stringMatching(/^\d{5}$/),
|
||||
120,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyOtp', () => {
|
||||
it('should throw BadRequestException if OTP is expired/not found', async () => {
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.verifyOtp({ phoneNumber: '09123456789', code: '12345' }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException if OTP is incorrect', async () => {
|
||||
mockRedis.get.mockResolvedValue('54321');
|
||||
await expect(
|
||||
service.verifyOtp({ phoneNumber: '09123456789', code: '12345' }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should delete OTP, find or create user and sign JWT', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
const mockUser = { id: 'user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await service.verifyOtp({ phoneNumber: '09123456789', code: '12345' });
|
||||
|
||||
expect(redis.del).toHaveBeenCalledWith('otp:09123456789');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { mobile: '09123456789' } });
|
||||
expect(jwt.sign).toHaveBeenCalledWith({ sub: 'user-id', phoneNumber: '09123456789' });
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data.accessToken).toBe('mock-jwt-token');
|
||||
expect(result.data.user).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('should create new user if user does not exist', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
mockPrisma.user.findUnique.mockResolvedValue(null);
|
||||
const newUser = { id: 'new-user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.create.mockResolvedValue(newUser);
|
||||
|
||||
const result = await service.verifyOtp({ phoneNumber: '09123456789', code: '12345' });
|
||||
expect(prisma.user.create).toHaveBeenCalled();
|
||||
expect(result.data.user).toEqual(newUser);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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' });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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('کاربر یافت نشد');
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export class CreateBlogDto {}
|
||||
@@ -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 {}
|
||||
@@ -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 : {}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Controller, Get, Res } from '@nestjs/common';
|
||||
import { ApiExcludeController } from '@nestjs/swagger';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import * as express from 'express';
|
||||
|
||||
@ApiExcludeController()
|
||||
@Controller('metrics')
|
||||
export class MetricsController {
|
||||
private static requestCount = 0;
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
public static incrementRequestCount() {
|
||||
this.requestCount++;
|
||||
}
|
||||
|
||||
@Get()
|
||||
async getMetrics(@Res() res: express.Response) {
|
||||
const memory = process.memoryUsage();
|
||||
const cpu = process.cpuUsage();
|
||||
|
||||
let dbStatus = 1;
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
} catch (e) {
|
||||
dbStatus = 0;
|
||||
}
|
||||
|
||||
const uptime = process.uptime();
|
||||
|
||||
const responseText = `# HELP node_memory_rss_bytes Resident set size in bytes.
|
||||
# TYPE node_memory_rss_bytes gauge
|
||||
node_memory_rss_bytes ${memory.rss}
|
||||
|
||||
# HELP node_memory_heap_used_bytes Heap used in bytes.
|
||||
# TYPE node_memory_heap_used_bytes gauge
|
||||
node_memory_heap_used_bytes ${memory.heapUsed}
|
||||
|
||||
# HELP node_memory_heap_total_bytes Heap total in bytes.
|
||||
# TYPE node_memory_heap_total_bytes gauge
|
||||
node_memory_heap_total_bytes ${memory.heapTotal}
|
||||
|
||||
# HELP node_cpu_user_time_microseconds CPU user time in microseconds.
|
||||
# TYPE node_cpu_user_time_microseconds counter
|
||||
node_cpu_user_time_microseconds ${cpu.user}
|
||||
|
||||
# HELP node_cpu_system_time_microseconds CPU system time in microseconds.
|
||||
# TYPE node_cpu_system_time_microseconds counter
|
||||
node_cpu_system_time_microseconds ${cpu.system}
|
||||
|
||||
# HELP node_app_uptime_seconds Application uptime in seconds.
|
||||
# TYPE node_app_uptime_seconds gauge
|
||||
node_app_uptime_seconds ${uptime}
|
||||
|
||||
# HELP canino_db_connected Database connection status (1 = connected, 0 = disconnected).
|
||||
# TYPE canino_db_connected gauge
|
||||
canino_db_connected ${dbStatus}
|
||||
|
||||
# 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');
|
||||
res.end(responseText);
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export class CreateHomeDto {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateHomeDto } from './create-home.dto';
|
||||
|
||||
export class UpdateHomeDto extends PartialType(CreateHomeDto) {}
|
||||
@@ -0,0 +1 @@
|
||||
export class Home {}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
}
|
||||
+26
-6
@@ -1,21 +1,41 @@
|
||||
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
|
||||
}));
|
||||
|
||||
app.setGlobalPrefix('api');
|
||||
app.enableCors();
|
||||
|
||||
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
|
||||
app.enableCors({
|
||||
origin: true,
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
app.useGlobalPipes(new ValidationPipe({
|
||||
transform: true,
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
}));
|
||||
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();
|
||||
@@ -23,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 })
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { OrdersController } from './orders.controller';
|
||||
import { OrdersService } from './orders.service';
|
||||
|
||||
describe('OrdersController', () => {
|
||||
let controller: OrdersController;
|
||||
let service: OrdersService;
|
||||
|
||||
const mockOrdersService = {
|
||||
create: jest.fn().mockResolvedValue({ id: 'order-id', totalAmount: 1000 }),
|
||||
findAllByUser: jest.fn().mockResolvedValue([{ id: 'order-id', totalAmount: 1000 }]),
|
||||
findOne: jest.fn().mockResolvedValue({ id: 'order-id', totalAmount: 1000 }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [OrdersController],
|
||||
providers: [
|
||||
{ provide: OrdersService, useValue: mockOrdersService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<OrdersController>(OrdersController);
|
||||
service = module.get<OrdersService>(OrdersService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should create order', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = { items: [{ productId: 'prod-1', quantity: 2 }] };
|
||||
const result = await controller.create(req, dto);
|
||||
expect(service.create).toHaveBeenCalledWith('user-id', dto);
|
||||
expect(result.id).toBe('order-id');
|
||||
});
|
||||
|
||||
it('should list orders of user', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.findAll(req);
|
||||
expect(service.findAllByUser).toHaveBeenCalledWith('user-id');
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should find one order', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.findOne(req, 'order-id');
|
||||
expect(service.findOne).toHaveBeenCalledWith('order-id', 'user-id');
|
||||
expect(result.id).toBe('order-id');
|
||||
});
|
||||
});
|
||||
@@ -1,30 +1,159 @@
|
||||
import { Controller, Get, Post, Body, Param, UseGuards, Req } 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 } 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';
|
||||
|
||||
@ApiTags('Orders')
|
||||
class ValidateCouponDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code: string;
|
||||
|
||||
@IsNumber()
|
||||
cartTotal: number;
|
||||
}
|
||||
|
||||
@ApiTags('Orders - مدیریت سفارشها')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('orders')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
code: 'UNAUTHORIZED',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class OrdersController {
|
||||
constructor(private readonly ordersService: OrdersService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'ثبت سفارش جدید' })
|
||||
@ApiCreatedResponse({
|
||||
description: 'سفارش با موفقیت ثبت شد',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
|
||||
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
couponId: null,
|
||||
totalAmount: '3500000.00',
|
||||
charityDonation: '10000.00',
|
||||
status: 'processing',
|
||||
trackingNumber: null,
|
||||
createdAt: '2026-05-26T18:10:00.000Z'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'اعتبارسنجی اقلام سبد خرید با خطا مواجه شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'سبد خرید نمیتواند خالی باشد',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
create(@Req() req: any, @Body() createOrderDto: CreateOrderDto) {
|
||||
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: 'لیست سفارشهای کاربر' })
|
||||
findAll(@Req() req: any) {
|
||||
return this.ordersService.findAllByUser(req.user.id);
|
||||
@ApiOperation({ summary: 'لیست سفارشهای کاربر فعلی' })
|
||||
@ApiOkResponse({
|
||||
description: 'آرایهای از سفارشهای ثبت شده کاربر (صفحهبندی شده)',
|
||||
schema: {
|
||||
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, @Query() query: PaginationDto) {
|
||||
return this.ordersService.findAllByUser(req.user.id, query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'جزئیات یک سفارش' })
|
||||
@ApiOperation({ summary: 'دریافت جزئیات یک سفارش خاص' })
|
||||
@ApiOkResponse({
|
||||
description: 'اطلاعات کامل سفارش مشخص شده به همراه اقلام سفارش',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
|
||||
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
totalAmount: '3500000.00',
|
||||
charityDonation: '10000.00',
|
||||
status: 'processing',
|
||||
trackingNumber: 'TRK-987654321',
|
||||
createdAt: '2026-05-26T18:10:00.000Z',
|
||||
orderItems: [
|
||||
{
|
||||
id: 'item-1',
|
||||
quantity: 2,
|
||||
product: {
|
||||
id: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
|
||||
name: 'Canhydrox GAG (کنهیدروکس)',
|
||||
priceDisplay: '۱,۷۵۰,۰۰۰ تومان',
|
||||
imageUrl: 'https://example.com/canhydrox.png'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiNotFoundResponse({
|
||||
description: 'سفارش یافت نشد یا متعلق به کاربر فعلی نیست',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Order not found',
|
||||
code: 'NOT_FOUND',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
findOne(@Req() req: any, @Param('id') id: string) {
|
||||
return this.ordersService.findOne(id, req.user.id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { OrdersService } from './orders.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotFoundException, BadRequestException } from '@nestjs/common';
|
||||
|
||||
describe('OrdersService', () => {
|
||||
let service: OrdersService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
product: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
order: {
|
||||
create: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
OrdersService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<OrdersService>(OrdersService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('should throw NotFoundException if product does not exist', async () => {
|
||||
mockPrisma.product.findUnique.mockResolvedValue(null);
|
||||
const dto = { items: [{ productId: 'invalid-prod', quantity: 2 }] };
|
||||
await expect(service.create('user-id', dto)).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException if items are empty', async () => {
|
||||
const dto = { items: [] };
|
||||
await expect(service.create('user-id', dto)).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should successfully create order and sum amounts', async () => {
|
||||
const prod = { id: 'prod-1', priceValue: 1000 };
|
||||
mockPrisma.product.findUnique.mockResolvedValue(prod);
|
||||
mockPrisma.order.create.mockResolvedValue({ id: 'order-1', totalAmount: 2000 });
|
||||
|
||||
const dto = { items: [{ productId: 'prod-1', quantity: 2 }] };
|
||||
const result = await service.create('user-id', dto);
|
||||
|
||||
expect(prisma.product.findUnique).toHaveBeenCalledWith({ where: { id: 'prod-1' } });
|
||||
expect(prisma.order.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
userId: 'user-id',
|
||||
totalAmount: 2000,
|
||||
status: 'processing',
|
||||
orderItems: {
|
||||
create: [{ productId: 'prod-1', quantity: 2 }],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result.id).toBe('order-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAllByUser', () => {
|
||||
it('should find all orders of a user', async () => {
|
||||
mockPrisma.order.findMany.mockResolvedValue([{ id: 'order-1' }]);
|
||||
const result = await service.findAllByUser('user-id');
|
||||
expect(prisma.order.findMany).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should throw NotFoundException if order does not exist', async () => {
|
||||
mockPrisma.order.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOne('order-id', 'user-id')).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it('should return order if found', async () => {
|
||||
const order = { id: 'order-1', userId: 'user-id' };
|
||||
mockPrisma.order.findFirst.mockResolvedValue(order);
|
||||
const result = await service.findOne('order-1', 'user-id');
|
||||
expect(result).toEqual(order);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PetsController } from './pets.controller';
|
||||
import { PetsService } from './pets.service';
|
||||
|
||||
describe('PetsController', () => {
|
||||
let controller: PetsController;
|
||||
let service: PetsService;
|
||||
|
||||
const mockPetsService = {
|
||||
create: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy' }),
|
||||
findAllByUser: jest.fn().mockResolvedValue([{ id: 'pet-id', name: 'Buddy' }]),
|
||||
findOne: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy' }),
|
||||
update: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy New' }),
|
||||
remove: jest.fn().mockResolvedValue({ success: true }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [PetsController],
|
||||
providers: [
|
||||
{ provide: PetsService, useValue: mockPetsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<PetsController>(PetsController);
|
||||
service = module.get<PetsService>(PetsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should create pet', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = { name: 'Buddy', type: 'Dog' };
|
||||
const result = await controller.create(req, dto);
|
||||
expect(service.create).toHaveBeenCalledWith('user-id', dto);
|
||||
expect(result.id).toBe('pet-id');
|
||||
});
|
||||
|
||||
it('should findAll pets', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.findAll(req);
|
||||
expect(service.findAllByUser).toHaveBeenCalledWith('user-id');
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should findOne pet', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.findOne(req, 'pet-id');
|
||||
expect(service.findOne).toHaveBeenCalledWith('pet-id', 'user-id');
|
||||
expect(result.id).toBe('pet-id');
|
||||
});
|
||||
|
||||
it('should update pet', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = { name: 'Buddy New' };
|
||||
const result = await controller.update(req, 'pet-id', dto);
|
||||
expect(service.update).toHaveBeenCalledWith('pet-id', 'user-id', dto);
|
||||
expect(result.name).toBe('Buddy New');
|
||||
});
|
||||
|
||||
it('should remove pet', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.remove(req, 'pet-id');
|
||||
expect(service.remove).toHaveBeenCalledWith('pet-id', 'user-id');
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,44 +1,221 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req } 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 } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse } from '@nestjs/swagger';
|
||||
import { PaginationDto } from '../common/dto/pagination.dto';
|
||||
|
||||
@ApiTags('Pets')
|
||||
@ApiTags('Pets - مدیریت حیوانات خانگی')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('pets')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
code: 'UNAUTHORIZED',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class PetsController {
|
||||
constructor(private readonly petsService: PetsService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'ثبت حیوان خانگی جدید' })
|
||||
@ApiCreatedResponse({
|
||||
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'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'خطا در صحتسنجی فیلدهای ورودی',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'نوع حیوان خانگی اجباری است',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
create(@Req() req: any, @Body() createPetDto: CreatePetDto) {
|
||||
return this.petsService.create(req.user.id, createPetDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر' })
|
||||
findAll(@Req() req: any) {
|
||||
return this.petsService.findAllByUser(req.user.id);
|
||||
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر فعلی' })
|
||||
@ApiOkResponse({
|
||||
description: 'آرایهای از حیوانات خانگی ثبت شده کاربر (صفحهبندی شده)',
|
||||
schema: {
|
||||
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, @Query() query: PaginationDto) {
|
||||
return this.petsService.findAllByUser(req.user.id, query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'دریافت جزئیات یک حیوان خانگی' })
|
||||
@ApiOperation({ summary: 'دریافت جزئیات کامل یک حیوان خانگی' })
|
||||
@ApiOkResponse({
|
||||
description: 'اطلاعات کامل حیوان خانگی مشخص شده با ID',
|
||||
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,
|
||||
medicalConditions: [],
|
||||
reminders: [],
|
||||
healthLogs: [],
|
||||
createdAt: '2026-05-26T18:10:00.000Z'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiNotFoundResponse({
|
||||
description: 'حیوان خانگی پیدا نشد یا متعلق به کاربر جاری نیست',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Pet not found or unauthorized',
|
||||
code: 'NOT_FOUND',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
findOne(@Req() req: any, @Param('id') id: string) {
|
||||
return this.petsService.findOne(id, req.user.id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOperation({ summary: 'بروزرسانی اطلاعات حیوان خانگی' })
|
||||
@ApiOkResponse({
|
||||
description: 'اطلاعات حیوان خانگی با موفقیت بهروزرسانی شد',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
|
||||
name: 'بادی قهرمان',
|
||||
type: 'سگ',
|
||||
breed: 'ژرمن شپرد',
|
||||
age: 4,
|
||||
weight: '26.00',
|
||||
activityLevel: 'زیاد'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiNotFoundResponse({
|
||||
description: 'حیوان خانگی یافت نشد',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Pet not found',
|
||||
code: 'NOT_FOUND',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
update(@Req() req: any, @Param('id') id: string, @Body() updatePetDto: UpdatePetDto) {
|
||||
return this.petsService.update(id, req.user.id, updatePetDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'حذف حیوان خانگی' })
|
||||
@ApiOkResponse({
|
||||
description: 'حیوان خانگی با موفقیت حذف شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'حیوان خانگی با موفقیت حذف شد'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiNotFoundResponse({
|
||||
description: 'حیوان خانگی یافت نشد',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Pet not found',
|
||||
code: 'NOT_FOUND',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PetsService } from './pets.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
|
||||
describe('PetsService', () => {
|
||||
let service: PetsService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
pet: {
|
||||
create: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
PetsService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<PetsService>(PetsService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('should create pet', async () => {
|
||||
const dto = { name: 'Buddy', type: 'Dog', weight: 12.5 };
|
||||
mockPrisma.pet.create.mockResolvedValue({ id: 'pet-id', ...dto });
|
||||
|
||||
const result = await service.create('user-id', dto);
|
||||
expect(prisma.pet.create).toHaveBeenCalled();
|
||||
expect(result.name).toBe('Buddy');
|
||||
});
|
||||
|
||||
it('should find all pets by user', async () => {
|
||||
mockPrisma.pet.findMany.mockResolvedValue([{ id: 'pet-1' }]);
|
||||
const result = await service.findAllByUser('user-id');
|
||||
expect(prisma.pet.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-id' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should throw NotFoundException if pet not found', async () => {
|
||||
mockPrisma.pet.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOne('pet-id', 'user-id')).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it('should return pet if found', async () => {
|
||||
const pet = { id: 'pet-id', userId: 'user-id' };
|
||||
mockPrisma.pet.findFirst.mockResolvedValue(pet);
|
||||
const result = await service.findOne('pet-id', 'user-id');
|
||||
expect(result).toEqual(pet);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update pet', async () => {
|
||||
const pet = { id: 'pet-id', userId: 'user-id' };
|
||||
mockPrisma.pet.findFirst.mockResolvedValue(pet);
|
||||
const dto = { name: 'Buddy New', type: 'Dog' };
|
||||
mockPrisma.pet.update.mockResolvedValue({ ...pet, ...dto });
|
||||
|
||||
const result = await service.update('pet-id', 'user-id', dto);
|
||||
expect(prisma.pet.update).toHaveBeenCalled();
|
||||
expect(result.name).toBe('Buddy New');
|
||||
});
|
||||
|
||||
it('should remove pet', async () => {
|
||||
const pet = { id: 'pet-id', userId: 'user-id' };
|
||||
mockPrisma.pet.findFirst.mockResolvedValue(pet);
|
||||
mockPrisma.pet.delete.mockResolvedValue(pet);
|
||||
|
||||
const result = await service.remove('pet-id', 'user-id');
|
||||
expect(prisma.pet.delete).toHaveBeenCalled();
|
||||
expect(result.id).toBe('pet-id');
|
||||
});
|
||||
});
|
||||
@@ -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(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProductsController } from './products.controller';
|
||||
import { ProductsService } from './products.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
|
||||
describe('ProductsController', () => {
|
||||
let controller: ProductsController;
|
||||
let service: ProductsService;
|
||||
|
||||
const mockProductsService = {
|
||||
findAll: jest.fn().mockResolvedValue([{ id: 'prod-id', name: 'Product 1' }]),
|
||||
findOne: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [ProductsController],
|
||||
providers: [
|
||||
{ provide: ProductsService, useValue: mockProductsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<ProductsController>(ProductsController);
|
||||
service = module.get<ProductsService>(ProductsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should list products', async () => {
|
||||
const query = { category: 'joints' };
|
||||
const result = await controller.findAll(query);
|
||||
expect(service.findAll).toHaveBeenCalledWith(query);
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should throw NotFoundException if product not found', async () => {
|
||||
mockProductsService.findOne.mockResolvedValue(null);
|
||||
await expect(controller.findOne('invalid-id')).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it('should return product details if found', async () => {
|
||||
const prod = { id: 'prod-id', name: 'Product 1' };
|
||||
mockProductsService.findOne.mockResolvedValue(prod);
|
||||
const result = await controller.findOne('prod-id');
|
||||
expect(service.findOne).toHaveBeenCalledWith('prod-id');
|
||||
expect(result).toEqual(prod);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,108 @@
|
||||
import { Controller, Get, Query, Param, NotFoundException } from '@nestjs/common';
|
||||
import { Controller, Get, Query, Param, NotFoundException, HttpStatus } from '@nestjs/common';
|
||||
import { ProductsService } from './products.service';
|
||||
import { GetProductsDto } from './dto/get-products.dto';
|
||||
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiNotFoundResponse } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Products')
|
||||
@ApiTags('Products - مدیریت محصولات دارویی')
|
||||
@Controller('products')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'خطای داخلی سرور',
|
||||
code: 'SERVER_ERROR',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class ProductsController {
|
||||
constructor(private readonly productsService: ProductsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List Products' })
|
||||
@ApiResponse({ status: 200, description: 'List of products' })
|
||||
@ApiOperation({ summary: 'لیست و فیلتر محصولات' })
|
||||
@ApiOkResponse({
|
||||
description: 'لیست محصولات متناسب با فیلترها (دسته، پت و جستجو)',
|
||||
schema: {
|
||||
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) {
|
||||
return this.productsService.findAll(query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get Product by ID' })
|
||||
@ApiResponse({ status: 200, description: 'Product details' })
|
||||
@ApiOperation({ summary: 'دریافت اطلاعات محصول با شناسه یکتا (ID)' })
|
||||
@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: [
|
||||
{ productId: 'a1b2c3d4-1234-5678-abcd-ef1234567890', ingredient: 'صدف لبسبز' }
|
||||
],
|
||||
symptoms: [
|
||||
{ productId: 'a1b2c3d4-1234-5678-abcd-ef1234567890', symptom: 'لنگیدن' }
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiNotFoundResponse({
|
||||
description: 'محصول با شناسه ارسال شده پیدا نشد',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Product with ID a1b2c3d4-1234-5678-abcd-ef1234567890 not found',
|
||||
code: 'NOT_FOUND',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
async findOne(@Param('id') id: string) {
|
||||
const product = await this.productsService.findOne(id);
|
||||
if (!product) {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProductsService } from './products.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('ProductsService', () => {
|
||||
let service: ProductsService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
product: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ProductsService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ProductsService>(ProductsService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('findAll', () => {
|
||||
it('should query products with correct filters', async () => {
|
||||
mockPrisma.product.findMany.mockResolvedValue([{ id: 'prod-1' }]);
|
||||
const filters = { category: 'joints', petType: 'سگ', query: 'can' };
|
||||
const result = await service.findAll(filters);
|
||||
|
||||
expect(prisma.product.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
categorySlug: 'joints',
|
||||
suitableFor: { in: ['سگ', 'هر دو'] },
|
||||
OR: [
|
||||
{ name: { contains: 'can', mode: 'insensitive' } },
|
||||
{ description: { contains: 'can', mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
ingredients: true,
|
||||
symptoms: true,
|
||||
},
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should find product by id', async () => {
|
||||
const prod = { id: 'prod-1' };
|
||||
mockPrisma.product.findUnique.mockResolvedValue(prod);
|
||||
const result = await service.findOne('prod-1');
|
||||
expect(prisma.product.findUnique).toHaveBeenCalledWith({
|
||||
where: { id: 'prod-1' },
|
||||
include: {
|
||||
ingredients: true,
|
||||
symptoms: true,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual(prod);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RedisService } from './redis.service';
|
||||
|
||||
jest.mock('ioredis', () => {
|
||||
return jest.fn().mockImplementation(() => {
|
||||
return {
|
||||
set: jest.fn(),
|
||||
get: jest.fn().mockResolvedValue('mock-value'),
|
||||
del: jest.fn(),
|
||||
disconnect: jest.fn(),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe('RedisService', () => {
|
||||
let service: RedisService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [RedisService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<RedisService>(RedisService);
|
||||
service.onModuleInit();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
service.onModuleDestroy();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call set with or without ttl', async () => {
|
||||
const setSpy = jest.spyOn((service as any).client, 'set');
|
||||
await service.set('key', 'val');
|
||||
expect(setSpy).toHaveBeenCalledWith('key', 'val');
|
||||
|
||||
await service.set('key', 'val', 60);
|
||||
expect(setSpy).toHaveBeenCalledWith('key', 'val', 'EX', 60);
|
||||
});
|
||||
|
||||
it('should call get', async () => {
|
||||
const getSpy = jest.spyOn((service as any).client, 'get');
|
||||
const result = await service.get('key');
|
||||
expect(getSpy).toHaveBeenCalledWith('key');
|
||||
expect(result).toBe('mock-value');
|
||||
});
|
||||
|
||||
it('should call del', async () => {
|
||||
const delSpy = jest.spyOn((service as any).client, 'del');
|
||||
await service.del('key');
|
||||
expect(delSpy).toHaveBeenCalledWith('key');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { SettingsController } from './settings.controller';
|
||||
import { SettingsService } from './settings.service';
|
||||
|
||||
describe('SettingsController', () => {
|
||||
let controller: SettingsController;
|
||||
let service: SettingsService;
|
||||
|
||||
const mockSettingsService = {
|
||||
getUiTexts: jest.fn().mockResolvedValue([{ key: 'k', value: 'v' }]),
|
||||
updateUiText: jest.fn().mockResolvedValue({ key: 'k', value: 'v' }),
|
||||
getScientificTerms: jest.fn().mockResolvedValue([{ key: 'k' }]),
|
||||
upsertScientificTerm: jest.fn().mockResolvedValue({ key: 'k' }),
|
||||
deleteScientificTerm: jest.fn().mockResolvedValue({ success: true }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [SettingsController],
|
||||
providers: [
|
||||
{ provide: SettingsService, useValue: mockSettingsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<SettingsController>(SettingsController);
|
||||
service = module.get<SettingsService>(SettingsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should getUiTexts', async () => {
|
||||
const result = await controller.getUiTexts();
|
||||
expect(service.getUiTexts).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should updateUiText', async () => {
|
||||
const result = await controller.updateUiText('k', 'v');
|
||||
expect(service.updateUiText).toHaveBeenCalledWith('k', 'v');
|
||||
expect(result.key).toBe('k');
|
||||
});
|
||||
|
||||
it('should getScientificTerms', async () => {
|
||||
const result = await controller.getScientificTerms();
|
||||
expect(service.getScientificTerms).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should upsertScientificTerm', async () => {
|
||||
const data = { term: 't', definition: 'd' };
|
||||
const result = await controller.upsertScientificTerm('k', data);
|
||||
expect(service.upsertScientificTerm).toHaveBeenCalledWith('k', data);
|
||||
expect(result.key).toBe('k');
|
||||
});
|
||||
|
||||
it('should deleteScientificTerm', async () => {
|
||||
const result = await controller.deleteScientificTerm('k');
|
||||
expect(service.deleteScientificTerm).toHaveBeenCalledWith('k');
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,25 @@
|
||||
import { Controller, Get, Patch, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Get, Patch, Put, Delete, Body, Param, UseGuards, HttpStatus } from '@nestjs/common';
|
||||
import { SettingsService } from './settings.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse, ApiOkResponse, ApiUnauthorizedResponse } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Settings')
|
||||
@ApiTags('Settings - تنظیمات متون پویا و واژهنامه علمی')
|
||||
@Controller('settings')
|
||||
export class SettingsController {
|
||||
constructor(private readonly settingsService: SettingsService) {}
|
||||
|
||||
@Get('ui-texts')
|
||||
@ApiOperation({ summary: 'دریافت تمامی متون رابط کاربری' })
|
||||
@ApiResponse({ status: 200, description: 'تمامی متون بازگردانده شدند' })
|
||||
@ApiOperation({ summary: 'دریافت تمامی متون و پیکربندیهای رابط کاربری' })
|
||||
@ApiOkResponse({
|
||||
description: 'یک آبجکت کلید-مقدار حاوی تمامی متون، شعارها و برچسبهای دکمهها',
|
||||
schema: {
|
||||
example: {
|
||||
hero_badge: "تخصص دارویی از آلمان",
|
||||
hero_title: "تخصص آلمانی در خدمت سلامت پتهای خانگی",
|
||||
hero_desc: "بیش از ۴۰ سال تجربه نوآورانه..."
|
||||
}
|
||||
}
|
||||
})
|
||||
getUiTexts() {
|
||||
return this.settingsService.getUiTexts();
|
||||
}
|
||||
@@ -18,15 +27,39 @@ export class SettingsController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Patch('ui-texts/:key')
|
||||
@ApiOperation({ summary: 'ویرایش متن یک کلید در رابط کاربری' })
|
||||
@ApiResponse({ status: 200, description: 'متن با موفقیت بهروزرسانی شد' })
|
||||
@ApiOperation({ summary: 'ویرایش متن یک کلید در رابط کاربری (نیازمند توکن)' })
|
||||
@ApiOkResponse({
|
||||
description: 'متن با موفقیت بهروزرسانی شد',
|
||||
schema: {
|
||||
example: {
|
||||
key: 'hero_badge',
|
||||
value: 'تخصص دارویی ممتاز از آلمان'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiUnauthorizedResponse({
|
||||
description: 'عدم دسترسی به دلیل عدم احراز هویت',
|
||||
schema: { example: { success: false, message: 'Unauthorized', code: 'UNAUTHORIZED' } }
|
||||
})
|
||||
updateUiText(@Param('key') key: string, @Body('value') value: string) {
|
||||
return this.settingsService.updateUiText(key, value);
|
||||
}
|
||||
|
||||
@Get('scientific-terms')
|
||||
@ApiOperation({ summary: 'دریافت تمامی اصطلاحات علمی' })
|
||||
@ApiResponse({ status: 200, description: 'تمامی اصطلاحات علمی بازگردانده شدند' })
|
||||
@ApiOperation({ summary: 'دریافت تمامی اصطلاحات واژهنامه علمی' })
|
||||
@ApiOkResponse({
|
||||
description: 'لیست کامل اصطلاحات علمی به همراه تعاریف و شناسهها',
|
||||
schema: {
|
||||
example: [
|
||||
{
|
||||
key: 'green-mussel',
|
||||
term: 'صدف لبسبز (Perna Canaliculus)',
|
||||
definition: 'این صدف بومی سواحل بکر نیوزیلند است...',
|
||||
wikiId: 'general'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
getScientificTerms() {
|
||||
return this.settingsService.getScientificTerms();
|
||||
}
|
||||
@@ -34,8 +67,22 @@ export class SettingsController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Put('scientific-terms/:key')
|
||||
@ApiOperation({ summary: 'ثبت یا ویرایش یک اصطلاح علمی' })
|
||||
@ApiResponse({ status: 200, description: 'اصطلاح علمی ثبت یا ویرایش شد' })
|
||||
@ApiOperation({ summary: 'ثبت یا ویرایش یک اصطلاح علمی (نیازمند توکن)' })
|
||||
@ApiOkResponse({
|
||||
description: 'اصطلاح علمی ثبت یا ویرایش شد',
|
||||
schema: {
|
||||
example: {
|
||||
key: 'green-mussel',
|
||||
term: 'صدف لبسبز اصل نیوزیلند',
|
||||
definition: 'این صدف بومی سواحل بکر نیوزیلند است...',
|
||||
wikiId: 'general'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiUnauthorizedResponse({
|
||||
description: 'عدم دسترسی',
|
||||
schema: { example: { success: false, message: 'Unauthorized', code: 'UNAUTHORIZED' } }
|
||||
})
|
||||
upsertScientificTerm(@Param('key') key: string, @Body() data: any) {
|
||||
return this.settingsService.upsertScientificTerm(key, data);
|
||||
}
|
||||
@@ -43,8 +90,20 @@ export class SettingsController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Delete('scientific-terms/:key')
|
||||
@ApiOperation({ summary: 'حذف یک اصطلاح علمی' })
|
||||
@ApiResponse({ status: 200, description: 'اصطلاح علمی حذف شد' })
|
||||
@ApiOperation({ summary: 'حذف یک اصطلاح علمی (نیازمند توکن)' })
|
||||
@ApiOkResponse({
|
||||
description: 'اصطلاح علمی حذف شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'Scientific term successfully deleted'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiUnauthorizedResponse({
|
||||
description: 'عدم دسترسی',
|
||||
schema: { example: { success: false, message: 'Unauthorized', code: 'UNAUTHORIZED' } }
|
||||
})
|
||||
deleteScientificTerm(@Param('key') key: string) {
|
||||
return this.settingsService.deleteScientificTerm(key);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { SettingsService } from './settings.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('SettingsService', () => {
|
||||
let service: SettingsService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
uiText: {
|
||||
findMany: jest.fn(),
|
||||
upsert: jest.fn(),
|
||||
},
|
||||
scientificTerm: {
|
||||
findMany: jest.fn(),
|
||||
upsert: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
SettingsService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<SettingsService>(SettingsService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('should getUiTexts', async () => {
|
||||
mockPrisma.uiText.findMany.mockResolvedValue([{ key: 'k', value: 'v' }]);
|
||||
const result = await service.getUiTexts();
|
||||
expect(prisma.uiText.findMany).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should updateUiText', async () => {
|
||||
mockPrisma.uiText.upsert.mockResolvedValue({ key: 'k', value: 'v2' });
|
||||
const result = await service.updateUiText('k', 'v2');
|
||||
expect(prisma.uiText.upsert).toHaveBeenCalledWith({
|
||||
where: { key: 'k' },
|
||||
update: { value: 'v2' },
|
||||
create: { key: 'k', value: 'v2' },
|
||||
});
|
||||
expect(result.value).toBe('v2');
|
||||
});
|
||||
|
||||
it('should getScientificTerms', async () => {
|
||||
mockPrisma.scientificTerm.findMany.mockResolvedValue([{ key: 'k' }]);
|
||||
const result = await service.getScientificTerms();
|
||||
expect(prisma.scientificTerm.findMany).toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should upsertScientificTerm', async () => {
|
||||
mockPrisma.scientificTerm.upsert.mockResolvedValue({ key: 'k', term: 't' });
|
||||
const data = { term: 't', definition: 'd', wikiId: 'w' };
|
||||
const result = await service.upsertScientificTerm('k', data);
|
||||
expect(prisma.scientificTerm.upsert).toHaveBeenCalledWith({
|
||||
where: { key: 'k' },
|
||||
update: { term: 't', definition: 'd', wikiId: 'w' },
|
||||
create: { key: 'k', term: 't', definition: 'd', wikiId: 'w' },
|
||||
});
|
||||
expect(result.term).toBe('t');
|
||||
});
|
||||
|
||||
it('should deleteScientificTerm', async () => {
|
||||
mockPrisma.scientificTerm.delete.mockResolvedValue({ key: 'k' });
|
||||
const result = await service.deleteScientificTerm('k');
|
||||
expect(prisma.scientificTerm.delete).toHaveBeenCalledWith({
|
||||
where: { key: 'k' },
|
||||
});
|
||||
expect(result.key).toBe('k');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
describe('UsersController', () => {
|
||||
let controller: UsersController;
|
||||
let service: UsersService;
|
||||
|
||||
const mockUsersService = {
|
||||
findById: jest.fn().mockResolvedValue({ id: 'user-id', firstName: 'Test' }),
|
||||
update: jest.fn().mockResolvedValue({ id: 'user-id', firstName: 'Updated' }),
|
||||
addAddress: jest.fn().mockResolvedValue({ id: 'addr-id', title: 'Home' }),
|
||||
updateAddress: jest.fn().mockResolvedValue({ id: 'addr-id', title: 'Work' }),
|
||||
deleteAddress: jest.fn().mockResolvedValue({ success: true }),
|
||||
setDefaultAddress: jest.fn().mockResolvedValue({ success: true }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UsersController],
|
||||
providers: [
|
||||
{ provide: UsersService, useValue: mockUsersService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UsersController>(UsersController);
|
||||
service = module.get<UsersService>(UsersService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should getProfile', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.getProfile(req);
|
||||
expect(service.findById).toHaveBeenCalledWith('user-id');
|
||||
expect(result.id).toBe('user-id');
|
||||
});
|
||||
|
||||
it('should updateProfile', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = { firstName: 'Updated' };
|
||||
const result = await controller.updateProfile(req, dto);
|
||||
expect(service.update).toHaveBeenCalledWith('user-id', dto);
|
||||
expect(result.firstName).toBe('Updated');
|
||||
});
|
||||
|
||||
it('should addAddress', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = {
|
||||
title: 'Home',
|
||||
receptorName: 'Ali',
|
||||
phone: '0912',
|
||||
province: 'Teh',
|
||||
city: 'Teh',
|
||||
detail: 'Det',
|
||||
zipCode: '123',
|
||||
};
|
||||
const result = await controller.addAddress(req, dto);
|
||||
expect(service.addAddress).toHaveBeenCalledWith('user-id', dto);
|
||||
expect(result.id).toBe('addr-id');
|
||||
});
|
||||
|
||||
it('should updateAddress', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const dto = {
|
||||
title: 'Work',
|
||||
receptorName: 'Ali',
|
||||
phone: '0912',
|
||||
province: 'Teh',
|
||||
city: 'Teh',
|
||||
detail: 'Det',
|
||||
zipCode: '123',
|
||||
};
|
||||
const result = await controller.updateAddress(req, 'addr-id', dto);
|
||||
expect(service.updateAddress).toHaveBeenCalledWith('user-id', 'addr-id', dto);
|
||||
expect(result.title).toBe('Work');
|
||||
});
|
||||
|
||||
it('should deleteAddress', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.deleteAddress(req, 'addr-id');
|
||||
expect(service.deleteAddress).toHaveBeenCalledWith('user-id', 'addr-id');
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should setDefaultAddress', async () => {
|
||||
const req = { user: { id: 'user-id' } };
|
||||
const result = await controller.setDefaultAddress(req, 'addr-id');
|
||||
expect(service.setDefaultAddress).toHaveBeenCalledWith('user-id', 'addr-id');
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,50 @@
|
||||
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req } 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 } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse } from '@nestjs/swagger';
|
||||
import { UpdateProfileDto } from './dto/update-profile.dto';
|
||||
import { AddressDto } from './dto/address.dto';
|
||||
|
||||
@ApiTags('Users')
|
||||
@ApiTags('Users - مدیریت کاربران و آدرسها')
|
||||
@ApiBearerAuth()
|
||||
@Controller('users')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
code: 'UNAUTHORIZED',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class UsersController {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('profile')
|
||||
@ApiOperation({ summary: 'دریافت پروفایل کاربر فعلی' })
|
||||
@ApiOkResponse({
|
||||
description: 'مشخصات کامل کاربر به همراه آدرسها و اطلاعات حیوانات خانگی',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
firstName: 'کاربر',
|
||||
lastName: 'جدید',
|
||||
email: '09123456789@temp.local',
|
||||
mobile: '09123456789',
|
||||
role: 'User_PetOwner',
|
||||
walletBalance: '1500000.00',
|
||||
charityDonationTotal: '25000.00',
|
||||
addresses: [],
|
||||
pets: [],
|
||||
createdAt: '2026-05-26T15:20:00.000Z',
|
||||
updatedAt: '2026-05-26T15:20:00.000Z'
|
||||
}
|
||||
}
|
||||
})
|
||||
getProfile(@Req() req: any) {
|
||||
return this.usersService.findById(req.user.id);
|
||||
}
|
||||
@@ -21,7 +52,34 @@ export class UsersController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Patch('profile')
|
||||
@ApiOperation({ summary: 'ویرایش پروفایل کاربر فعلی' })
|
||||
@ApiResponse({ status: 200, description: 'پروفایل با موفقیت ویرایش شد' })
|
||||
@ApiOkResponse({
|
||||
description: 'پروفایل با موفقیت ویرایش شد',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
firstName: 'علی',
|
||||
lastName: 'احمدی',
|
||||
email: 'ali@example.com',
|
||||
mobile: '09123456789',
|
||||
role: 'User_PetOwner',
|
||||
walletBalance: '1500000.00',
|
||||
charityDonationTotal: '25000.00'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'خطا در صحتسنجی فیلدهای ورودی',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'ایمیل نامعتبر است',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {
|
||||
message: ['ایمیل نامعتبر است']
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
updateProfile(@Req() req: any, @Body() updateProfileDto: UpdateProfileDto) {
|
||||
return this.usersService.update(req.user.id, updateProfileDto);
|
||||
}
|
||||
@@ -29,7 +87,24 @@ export class UsersController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('addresses')
|
||||
@ApiOperation({ summary: 'ایجاد آدرس جدید برای کاربر' })
|
||||
@ApiResponse({ status: 201, description: 'آدرس جدید با موفقیت ایجاد شد' })
|
||||
@ApiCreatedResponse({
|
||||
description: 'آدرس جدید با موفقیت ایجاد شد',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'b5a6c7d8-1234-5678-abcd-ef1234567890',
|
||||
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
title: 'خانه',
|
||||
receptorName: 'علی احمدی',
|
||||
phone: '09123456789',
|
||||
province: 'تهران',
|
||||
city: 'تهران',
|
||||
detail: 'خیابان آزادی، کوچه مریم، پلاک ۱۰',
|
||||
zipCode: '1456789012',
|
||||
isDefault: false,
|
||||
createdAt: '2026-05-26T18:00:00.000Z'
|
||||
}
|
||||
}
|
||||
})
|
||||
addAddress(@Req() req: any, @Body() addressDto: AddressDto) {
|
||||
return this.usersService.addAddress(req.user.id, addressDto);
|
||||
}
|
||||
@@ -37,7 +112,24 @@ export class UsersController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Patch('addresses/:addressId')
|
||||
@ApiOperation({ summary: 'ویرایش آدرس کاربر' })
|
||||
@ApiResponse({ status: 200, description: 'آدرس با موفقیت ویرایش شد' })
|
||||
@ApiOkResponse({
|
||||
description: 'آدرس با موفقیت ویرایش شد',
|
||||
schema: {
|
||||
example: {
|
||||
id: 'b5a6c7d8-1234-5678-abcd-ef1234567890',
|
||||
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
title: 'دفتر کار',
|
||||
receptorName: 'علی احمدی',
|
||||
phone: '09123456789',
|
||||
province: 'تهران',
|
||||
city: 'تهران',
|
||||
detail: 'خیابان ولیعصر، برج سپهر، طبقه ۴',
|
||||
zipCode: '1456789012',
|
||||
isDefault: false,
|
||||
createdAt: '2026-05-26T18:00:00.000Z'
|
||||
}
|
||||
}
|
||||
})
|
||||
updateAddress(
|
||||
@Req() req: any,
|
||||
@Param('addressId') addressId: string,
|
||||
@@ -49,7 +141,15 @@ export class UsersController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete('addresses/:addressId')
|
||||
@ApiOperation({ summary: 'حذف آدرس کاربر' })
|
||||
@ApiResponse({ status: 200, description: 'آدرس با موفقیت حذف شد' })
|
||||
@ApiOkResponse({
|
||||
description: 'آدرس با موفقیت حذف شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'آدرس با موفقیت حذف شد'
|
||||
}
|
||||
}
|
||||
})
|
||||
deleteAddress(@Req() req: any, @Param('addressId') addressId: string) {
|
||||
return this.usersService.deleteAddress(req.user.id, addressId);
|
||||
}
|
||||
@@ -57,8 +157,42 @@ export class UsersController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Patch('addresses/:addressId/default')
|
||||
@ApiOperation({ summary: 'انتخاب آدرس به عنوان پیشفرض' })
|
||||
@ApiResponse({ status: 200, description: 'آدرس به عنوان پیشفرض ثبت شد' })
|
||||
@ApiOkResponse({
|
||||
description: 'آدرس به عنوان پیشفرض ثبت شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'آدرس پیشفرض با موفقیت تغییر کرد'
|
||||
}
|
||||
}
|
||||
})
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsersService } from './users.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('UsersService', () => {
|
||||
let service: UsersService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
userAddress: {
|
||||
updateMany: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
UsersService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UsersService>(UsersService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call prisma findUnique in findById', async () => {
|
||||
const mockUser = { id: 'user-id' };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
const result = await service.findById('user-id');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalled();
|
||||
expect(result).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('should call prisma update in update', async () => {
|
||||
const data = { firstName: 'Ali' };
|
||||
mockPrisma.user.update.mockResolvedValue({ id: 'user-id', ...data });
|
||||
const result = await service.update('user-id', data);
|
||||
expect(prisma.user.update).toHaveBeenCalled();
|
||||
expect(result.firstName).toBe('Ali');
|
||||
});
|
||||
|
||||
it('should addAddress', async () => {
|
||||
const addressData = { title: 'Home', isDefault: true };
|
||||
mockPrisma.userAddress.create.mockResolvedValue({ id: 'addr-id', ...addressData });
|
||||
|
||||
const result = await service.addAddress('user-id', addressData);
|
||||
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-id' },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
expect(prisma.userAddress.create).toHaveBeenCalled();
|
||||
expect(result.id).toBe('addr-id');
|
||||
});
|
||||
|
||||
it('should updateAddress', async () => {
|
||||
const addressData = { title: 'Work', isDefault: true };
|
||||
mockPrisma.userAddress.update.mockResolvedValue({ id: 'addr-id', ...addressData });
|
||||
|
||||
const result = await service.updateAddress('user-id', 'addr-id', addressData);
|
||||
expect(prisma.userAddress.updateMany).toHaveBeenCalled();
|
||||
expect(prisma.userAddress.update).toHaveBeenCalled();
|
||||
expect(result.title).toBe('Work');
|
||||
});
|
||||
|
||||
it('should deleteAddress', async () => {
|
||||
mockPrisma.userAddress.delete.mockResolvedValue({ id: 'addr-id' });
|
||||
const result = await service.deleteAddress('user-id', 'addr-id');
|
||||
expect(prisma.userAddress.delete).toHaveBeenCalled();
|
||||
expect(result.id).toBe('addr-id');
|
||||
});
|
||||
|
||||
it('should setDefaultAddress', async () => {
|
||||
mockPrisma.userAddress.update.mockResolvedValue({ id: 'addr-id', isDefault: true });
|
||||
const result = await service.setDefaultAddress('user-id', 'addr-id');
|
||||
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-id' },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
expect(prisma.userAddress.update).toHaveBeenCalledWith({
|
||||
where: { id: 'addr-id', userId: 'user-id' },
|
||||
data: { isDefault: true },
|
||||
});
|
||||
expect(result.isDefault).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -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 },
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export class CreateWikiDto {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateWikiDto } from './create-wiki.dto';
|
||||
|
||||
export class UpdateWikiDto extends PartialType(CreateWikiDto) {}
|
||||
@@ -0,0 +1 @@
|
||||
export class Wiki {}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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,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 |
+34
-12
@@ -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,12 +42,34 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: canina_frontend
|
||||
container_name: canino_frontend
|
||||
restart: always
|
||||
ports:
|
||||
- "3001:80"
|
||||
- "3001:8080"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
prometheus:
|
||||
image: docker.arvancloud.ir/prom/prometheus:v2.51.0
|
||||
container_name: canino_prometheus
|
||||
restart: always
|
||||
volumes:
|
||||
- ./prometheus.yml:/etc/prometheus/prometheus.yml
|
||||
ports:
|
||||
- "9090:9090"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
grafana:
|
||||
image: docker.arvancloud.ir/grafana/grafana:10.4.1
|
||||
container_name: canino_grafana
|
||||
restart: always
|
||||
ports:
|
||||
- "3002:3000"
|
||||
environment:
|
||||
- GF_SECURITY_ADMIN_PASSWORD=admin
|
||||
depends_on:
|
||||
- prometheus
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -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) امنیت، لاجیکهای تجاری و پایداری دادهها را تضمین میکند.
|
||||
@@ -0,0 +1,33 @@
|
||||
# راهنمای کاربری سیستم (User Guide)
|
||||
|
||||
سیستم کانینو از نظر نوع مخاطب به دو دسته کلی B2C (مشتریان عادی) و B2B (کلینیکها و فروشگاهها) تقسیم میشود. علاوه بر این، نقش «ادمین» برای مدیریت سیستم وجود دارد.
|
||||
|
||||
## ۱. مشتریان عادی (B2C Users)
|
||||
مشتری عادی کسی است که وارد سایت میشود تا برای حیوان خانگی خود مکمل خریداری کند یا اطلاعات کسب کند.
|
||||
|
||||
### کاربر چه کارهایی میتواند انجام دهد؟
|
||||
- **جستجو و کشف محصول:** میتواند محصولات را بر اساس دستهبندیها (سگ، گربه، نوع بیماری، ویتامینها) فیلتر کرده و جستجو کند.
|
||||
- **مشاهده جزئیات دقیق محصول:** مطالعه مشخصات دارویی، ترکیبات، نحوه مصرف، نظرات و همچنین قیمت و وضعیت موجودی.
|
||||
- **استفاده از دانشنامه (Wiki):** مطالعه درباره مواد موثره به کار رفته در محصولات (مانند بیوتین، گلوکزآمین) و دیدن محصولات مرتبط با هر ماده.
|
||||
- **ثبت پروفایل حیوان خانگی (Pet Profile):** کاربر میتواند اطلاعات حیوانات خود (نام، نژاد، سن، وضعیت عقیمسازی، بیماریهای زمینهای) را ثبت کند. سیستم از این اطلاعات برای شخصیسازی محصولات استفاده میکند.
|
||||
- **مشاوره هوشمند (Smart Advisor):** با وارد کردن مشخصات حیوان و مشکلی که دارد (مثلاً ریزش مو یا مشکل مفاصل)، سیستم بهترین مکملهای موجود را به صورت هوشمند پیشنهاد میدهد.
|
||||
- **مدیریت سبد خرید و سفارش:** افزودن محصولات به سبد، استفاده از کدهای تخفیف، استفاده از موجودی کیف پول و در نهایت پرداخت از طریق درگاه بانکی.
|
||||
- **پیگیری سفارش:** مشاهده وضعیت سفارشات (در حال بررسی، ارسال شده، تحویل داده شده).
|
||||
|
||||
## ۲. مشتریان تجاری (B2B Users / کلینیکها و داروخانهها)
|
||||
این دسته از کاربران پس از ثبتنام و تایید هویت توسط ادمین، به پورتال B2B دسترسی پیدا میکنند.
|
||||
|
||||
### کاربر B2B چه کارهایی میتواند انجام دهد؟
|
||||
- **مشاهده قیمتهای همکاری:** محصولات را با قیمت عمده یا درصد تخفیف ویژه همکاری مشاهده میکنند.
|
||||
- **ثبت سفارشات عمده (Bulk Order):** رابط کاربری ویژهای برای سفارش سریع محصولات در تعداد بالا دارند، بدون اینکه نیازی باشد وارد صفحه تکتک محصولات شوند.
|
||||
- **پرداخت اعتباری/چکی:** در صورت تایید مدیریت، قابلیت پرداخت غیرنقدی یا ثبت اسناد در سیستم برای آنها فعال میشود.
|
||||
|
||||
## ۳. مدیران سیستم (Admins)
|
||||
مدیران از طریق پنل مدیریت (که جدا از رابط کاربری اصلی است) سیستم را کنترل میکنند.
|
||||
|
||||
### مدیر چه کارهایی میتواند انجام دهد؟
|
||||
- **مدیریت محصولات:** تعریف محصول جدید، مدیریت موجودی انبار، تغییر قیمتها و تنظیم متادیتای سئو.
|
||||
- **مدیریت کاربران و نقشها:** تایید حسابهای B2B، مدیریت سطوح دسترسی.
|
||||
- **مدیریت سفارشات:** تغییر وضعیت سفارشات (به ارسال شده و...) و ثبت کدهای پیگیری پستی.
|
||||
- **گزارشگیری:** مشاهده گزارش فروش، محصولات پرطرفدار و وضعیت مالی کیف پولها.
|
||||
- **مدیریت محتوا:** نوشتن مقالات بلاگ و اطلاعات دانشنامه دارویی.
|
||||
@@ -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ها.
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -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) در دیتابیس استفاده کنید.
|
||||
همچنین پیشنهاد میشود از دیتابیس به صورت دورهای بکآپ گرفته و لاگهای بکآپ را در سرور مانیتورینگ نظارت کنید.
|
||||
@@ -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) در سورس پیج صحیح است؟
|
||||
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user