Compare commits
164
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e9a0e30c1 | ||
|
|
ad0acaccc2 | ||
|
|
30019a02d8 | ||
|
|
87999be3d2 | ||
|
|
4ce9f6000c | ||
|
|
0529962391 | ||
|
|
14c45e4f6c | ||
|
|
1c38b95fb0 | ||
|
|
dab66a2dce | ||
|
|
86eb0cfcae | ||
|
|
d3aa10c769 | ||
|
|
15524609fe | ||
|
|
aacb91ac70 | ||
|
|
f91502026b | ||
|
|
7f2f638f38 | ||
|
|
7879ead486 | ||
|
|
dda1caf3e0 | ||
|
|
bb483d3e68 | ||
|
|
73bc79b4bb | ||
|
|
9520426a66 | ||
|
|
b077423ab2 | ||
|
|
94867fbd5a | ||
|
|
6a37f2f4c7 | ||
|
|
b54338f91f | ||
|
|
c7b95b4d2b | ||
|
|
8e4388c325 | ||
|
|
305995cbe2 | ||
|
|
468170349d | ||
|
|
52446592e7 | ||
|
|
7bca0ef335 | ||
|
|
80717680a1 | ||
|
|
bb81f2c944 | ||
|
|
69094a8646 | ||
|
|
bed0b480d7 | ||
|
|
f8f9329c50 | ||
|
|
189e1f1202 | ||
|
|
5cf2863987 | ||
|
|
83cf70ac74 | ||
|
|
87bf867513 | ||
|
|
961bb383db | ||
|
|
5d5cc14f9e | ||
|
|
bfe228adee | ||
|
|
b5b4e64453 | ||
|
|
f23efbf90d | ||
|
|
81d1fa816b | ||
|
|
f5c970f82e | ||
|
|
6d0dea07f8 | ||
|
|
c4d95762f8 | ||
|
|
23724df4e4 | ||
|
|
21f7768cce | ||
|
|
92065cc7f2 | ||
|
|
956ef3b4d3 | ||
|
|
0d8125bd37 | ||
|
|
ea4d33b6bb | ||
|
|
b4fdd7abb8 | ||
|
|
f9d70bc196 | ||
|
|
5b20bab381 | ||
|
|
2c3e4bb752 | ||
|
|
570f0acc66 | ||
|
|
297aaadbe6 | ||
|
|
5573bb3568 | ||
|
|
80d9dc2f45 | ||
|
|
092933860a | ||
|
|
3d45b618ab | ||
|
|
2ab2318732 | ||
|
|
f3806cd6de | ||
|
|
8326e10ce8 | ||
|
|
d77ddd4bb2 | ||
|
|
9149e2b5ab | ||
|
|
5534d050af | ||
|
|
994086e580 | ||
|
|
dbd7d8b37d | ||
|
|
f440c60891 | ||
|
|
8672d4bcac | ||
|
|
87ad359e60 | ||
|
|
5afa2a37be | ||
|
|
d73b2e51c6 | ||
|
|
26f5f68708 | ||
|
|
86cfa4b3c8 | ||
|
|
e2b6d2acae | ||
|
|
8ef98cb415 | ||
|
|
6dbee69601 | ||
|
|
1aad481930 | ||
|
|
4393de5d8f | ||
|
|
5380bb66bb | ||
|
|
9a9ab149ed | ||
|
|
bec76393bb | ||
|
|
427b0d8591 | ||
|
|
1de8fd9a60 | ||
|
|
5c90d1629d | ||
|
|
c1a5223798 | ||
|
|
139aaff86c | ||
|
|
d9ff4aef58 | ||
|
|
a68e9b2c1e | ||
|
|
66cbf4c68d | ||
|
|
30ca17712c | ||
|
|
781b437c11 | ||
|
|
cf8f920aa6 | ||
|
|
c16e34df02 | ||
|
|
e67a4bd51c | ||
|
|
18e59efdcc | ||
|
|
c596c3a8b2 | ||
|
|
1f68210d08 | ||
|
|
fb4669e5a5 | ||
|
|
7b376f1126 | ||
|
|
e3426449e8 | ||
|
|
8795617d7f | ||
|
|
0dbf9cabb5 | ||
|
|
b6ac30d0e3 | ||
|
|
d79612b7e8 | ||
|
|
33c605132b | ||
|
|
686de48a95 | ||
|
|
043488fe55 | ||
|
|
f292195edf | ||
|
|
b61ba761bc | ||
|
|
4d64ad96b2 | ||
|
|
def903734f | ||
|
|
59ab154d0f | ||
|
|
31c55525c3 | ||
|
|
332d400a37 | ||
|
|
b5dcdec18c | ||
|
|
c6cf2e31aa | ||
|
|
b7268d0c47 | ||
|
|
a7b7164fc0 | ||
|
|
73f5d6d278 | ||
|
|
c04f1675f6 | ||
|
|
50cbd5b8ae | ||
|
|
19a029291b | ||
|
|
bd7345078a | ||
|
|
4969ec3fcd | ||
|
|
ec420e6053 | ||
|
|
4749ec91e4 | ||
|
|
679a551243 | ||
|
|
240a176151 | ||
|
|
d2c227c733 | ||
|
|
a532e2c73f | ||
|
|
3ff77d585d | ||
|
|
2a58e0c731 | ||
|
|
200ddda352 | ||
|
|
1cbd210be1 | ||
|
|
419e478489 | ||
|
|
8f8f0c36d5 | ||
|
|
2271291c87 | ||
|
|
ed20f6d089 | ||
|
|
12861288f2 | ||
|
|
73bfe0d893 | ||
|
|
a289c40503 | ||
|
|
b6735b5a9c | ||
|
|
f6736cd43f | ||
|
|
fa4f1124e6 | ||
|
|
30cebb92fa | ||
|
|
d87885826c | ||
|
|
f4e715f2d1 | ||
|
|
33afd7f45a | ||
|
|
e0581f22aa | ||
|
|
612360640c | ||
|
|
1fd2961cf4 | ||
|
|
ccbc495900 | ||
|
|
98f9223798 | ||
|
|
32cda55557 | ||
|
|
ea6d743e7d | ||
|
|
f5ebc6c508 | ||
|
|
969020105a | ||
|
|
dd90ab0f4c |
No files matched your search
@@ -13,6 +13,7 @@ jobs:
|
|||||||
- name: Run deploy.sh from within the scripts folder
|
- name: Run deploy.sh from within the scripts folder
|
||||||
env:
|
env:
|
||||||
BRANCH: ${{ github.ref_name }}
|
BRANCH: ${{ github.ref_name }}
|
||||||
|
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||||
run: |
|
run: |
|
||||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
name: E2E Playwright Tests
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
- develop
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
- develop
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test-e2e:
|
|
||||||
name: Run Full E2E & Security Suites
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout Code
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 20
|
|
||||||
cache: 'npm'
|
|
||||||
|
|
||||||
- name: Install Monorepo Dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Install Playwright Browsers
|
|
||||||
run: npx playwright install --with-deps chromium
|
|
||||||
|
|
||||||
- name: Run E2E Test Suite
|
|
||||||
run: npx playwright test --project=chromium-desktop --project=admin-chromium
|
|
||||||
env:
|
|
||||||
CI: true
|
|
||||||
NODE_ENV: test
|
|
||||||
|
|
||||||
- name: Upload Test Report
|
|
||||||
if: always()
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: playwright-report
|
|
||||||
path: playwright-report/
|
|
||||||
retention-days: 14
|
|
||||||
+1
-1
@@ -45,4 +45,4 @@ COPY --chown=node:node --from=builder /app/src ./src
|
|||||||
COPY --chown=node:node --from=builder /app/test ./test
|
COPY --chown=node:node --from=builder /app/test ./test
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
USER node
|
USER node
|
||||||
CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"]
|
CMD ["node", "dist/main.js"]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id));
|
||||||
|
CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id));
|
||||||
|
CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence);
|
||||||
|
CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at);
|
||||||
|
CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at);
|
||||||
|
CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at);
|
||||||
|
ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -32,12 +32,49 @@ model User {
|
|||||||
tickets Ticket[]
|
tickets Ticket[]
|
||||||
reviews ProductReview[]
|
reviews ProductReview[]
|
||||||
blogComments BlogComment[]
|
blogComments BlogComment[]
|
||||||
|
supportConversations SupportConversation[]
|
||||||
|
|
||||||
@@index([role])
|
@@index([role])
|
||||||
@@index([createdAt])
|
@@index([createdAt])
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model SupportConversation {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
userId String? @map("user_id") @db.Uuid
|
||||||
|
anonymousBrowserId String? @map("anonymous_browser_id") @db.VarChar(64)
|
||||||
|
entryPath String? @map("entry_path") @db.VarChar(512)
|
||||||
|
productSlugs Json? @map("product_slugs")
|
||||||
|
topics Json?
|
||||||
|
unanswered Boolean @default(false)
|
||||||
|
needsFollowup Boolean @default(false) @map("needs_followup")
|
||||||
|
escalationSignal Boolean @default(false) @map("escalation_signal")
|
||||||
|
summary String? @db.Text
|
||||||
|
summaryStatus String @default("pending") @map("summary_status") @db.VarChar(20)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
messages SupportConversationMessage[]
|
||||||
|
@@index([userId, updatedAt])
|
||||||
|
@@index([anonymousBrowserId, updatedAt])
|
||||||
|
@@map("support_conversations")
|
||||||
|
}
|
||||||
|
|
||||||
|
model SupportConversationMessage {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
conversationId String @map("conversation_id") @db.Uuid
|
||||||
|
role String @db.VarChar(20)
|
||||||
|
content String @db.Text
|
||||||
|
sequence Int
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
||||||
|
@@unique([conversationId, sequence])
|
||||||
|
@@index([conversationId, createdAt])
|
||||||
|
@@map("support_conversation_messages")
|
||||||
|
}
|
||||||
|
|
||||||
model UserAddress {
|
model UserAddress {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
userId String @map("user_id") @db.Uuid
|
userId String @map("user_id") @db.Uuid
|
||||||
@@ -141,7 +178,7 @@ model Blog {
|
|||||||
slug String @unique @db.VarChar(200)
|
slug String @unique @db.VarChar(200)
|
||||||
content String @db.Text
|
content String @db.Text
|
||||||
excerpt String? @db.Text
|
excerpt String? @db.Text
|
||||||
authorId String @map("author_id") @db.Uuid
|
authorId String? @map("author_id") @db.Uuid
|
||||||
categoryId String? @map("category_id") @db.Uuid
|
categoryId String? @map("category_id") @db.Uuid
|
||||||
imageUrl String? @map("image_url") @db.Text
|
imageUrl String? @map("image_url") @db.Text
|
||||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||||
@@ -172,7 +209,7 @@ model Blog {
|
|||||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
author User @relation(fields: [authorId], references: [id])
|
author User? @relation(fields: [authorId], references: [id])
|
||||||
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||||
tags BlogTag[]
|
tags BlogTag[]
|
||||||
comments BlogComment[]
|
comments BlogComment[]
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||||
async getUsers(@Query() query: AdminQueryDto) {
|
async getUsers(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getUsers(query);
|
const result = await this.adminService.getUsers(query);
|
||||||
return { success: true, ...result };
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("users")
|
@Post("users")
|
||||||
@@ -145,7 +145,7 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||||
async getProducts(@Query() query: AdminQueryDto) {
|
async getProducts(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getProducts(query);
|
const result = await this.adminService.getProducts(query);
|
||||||
return { success: true, ...result };
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("products")
|
@Post("products")
|
||||||
@@ -206,7 +206,7 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
||||||
async getOrders(@Query() query: AdminQueryDto) {
|
async getOrders(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getOrders(query);
|
const result = await this.adminService.getOrders(query);
|
||||||
return { success: true, ...result };
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("orders/:id")
|
@Get("orders/:id")
|
||||||
@@ -354,4 +354,34 @@ export class AdminController {
|
|||||||
await this.settingsService.updateBulkUiTexts(body);
|
await this.settingsService.updateBulkUiTexts(body);
|
||||||
return { success: true, data: body };
|
return { success: true, data: body };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Get("symptoms")
|
||||||
|
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحهبندی، جستجو و متادیتا" })
|
||||||
|
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
|
||||||
|
const res = await this.adminService.getSymptoms(query);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("symptoms")
|
||||||
|
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
|
||||||
|
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||||
|
const res = await this.adminService.createSymptom(body);
|
||||||
|
return { success: true, data: res };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put("symptoms/:id")
|
||||||
|
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
|
||||||
|
async updateSymptom(@Param("id") id: string, @Body() body: any) {
|
||||||
|
const res = await this.adminService.updateSymptom(id, body);
|
||||||
|
return { success: true, data: res };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("symptoms/:id")
|
||||||
|
@ApiOperation({ summary: "حذف علامت درمانی" })
|
||||||
|
async deleteSymptom(@Param("id") id: string) {
|
||||||
|
const res = await this.adminService.deleteSymptom(id);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -27,6 +27,8 @@ import { DepartmentTasksController } from "./department-tasks.controller";
|
|||||||
import { PrismaModule } from "../prisma/prisma.module";
|
import { PrismaModule } from "../prisma/prisma.module";
|
||||||
import { RedisModule } from "../redis/redis.module";
|
import { RedisModule } from "../redis/redis.module";
|
||||||
import { SettingsModule } from "../settings/settings.module";
|
import { SettingsModule } from "../settings/settings.module";
|
||||||
|
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
|
||||||
|
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||||
@@ -47,6 +49,7 @@ import { SettingsModule } from "../settings/settings.module";
|
|||||||
ApprovalsController,
|
ApprovalsController,
|
||||||
AuditLogsController,
|
AuditLogsController,
|
||||||
DepartmentTasksController,
|
DepartmentTasksController,
|
||||||
|
SupportChatAnalyticsController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
AdminService,
|
AdminService,
|
||||||
@@ -58,6 +61,7 @@ import { SettingsModule } from "../settings/settings.module";
|
|||||||
PetsService,
|
PetsService,
|
||||||
SslService,
|
SslService,
|
||||||
ApiKeysService,
|
ApiKeysService,
|
||||||
|
SupportChatAnalyticsService,
|
||||||
],
|
],
|
||||||
exports: [ApiKeysService, MediaService],
|
exports: [ApiKeysService, MediaService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1869,4 +1869,164 @@ export class AdminService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
|
||||||
|
const page = Math.max(1, Number(params?.page) || 1);
|
||||||
|
const limit = Math.max(1, Number(params?.limit) || 20);
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
|
const search = params?.search?.trim() || '';
|
||||||
|
|
||||||
|
let items: any[] = [];
|
||||||
|
let total = 0;
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
const searchPattern = `%${search}%`;
|
||||||
|
const [listResult, countResult] = await Promise.all([
|
||||||
|
this.prisma.$queryRaw<any[]>`
|
||||||
|
SELECT
|
||||||
|
s.id,
|
||||||
|
s.name,
|
||||||
|
s.slug,
|
||||||
|
s.description,
|
||||||
|
s.meta_title as "metaTitle",
|
||||||
|
s.meta_description as "metaDescription",
|
||||||
|
s.keywords,
|
||||||
|
s.icon,
|
||||||
|
s.created_at as "createdAt",
|
||||||
|
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||||
|
FROM symptoms s
|
||||||
|
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||||
|
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
|
||||||
|
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||||
|
ORDER BY s.name ASC
|
||||||
|
LIMIT ${limit} OFFSET ${offset};
|
||||||
|
`,
|
||||||
|
this.prisma.$queryRaw<any[]>`
|
||||||
|
SELECT COUNT(*)::int as total
|
||||||
|
FROM symptoms s
|
||||||
|
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
items = listResult;
|
||||||
|
total = countResult[0]?.total || 0;
|
||||||
|
} else {
|
||||||
|
const [listResult, countResult] = await Promise.all([
|
||||||
|
this.prisma.$queryRaw<any[]>`
|
||||||
|
SELECT
|
||||||
|
s.id,
|
||||||
|
s.name,
|
||||||
|
s.slug,
|
||||||
|
s.description,
|
||||||
|
s.meta_title as "metaTitle",
|
||||||
|
s.meta_description as "metaDescription",
|
||||||
|
s.keywords,
|
||||||
|
s.icon,
|
||||||
|
s.created_at as "createdAt",
|
||||||
|
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||||
|
FROM symptoms s
|
||||||
|
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||||
|
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||||
|
ORDER BY s.name ASC
|
||||||
|
LIMIT ${limit} OFFSET ${offset};
|
||||||
|
`,
|
||||||
|
this.prisma.$queryRaw<any[]>`
|
||||||
|
SELECT COUNT(*)::int as total
|
||||||
|
FROM symptoms s;
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
items = listResult;
|
||||||
|
total = countResult[0]?.total || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastPage = Math.ceil(total / limit) || 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: items,
|
||||||
|
meta: {
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
total,
|
||||||
|
lastPage,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||||
|
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
|
||||||
|
const name = dto.name.trim();
|
||||||
|
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
|
||||||
|
|
||||||
|
return await this.prisma.$queryRawUnsafe(`
|
||||||
|
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||||
|
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||||
|
// 1. Get existing symptom
|
||||||
|
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||||
|
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||||
|
const oldName = existing[0].name;
|
||||||
|
const newName = dto.name?.trim() || oldName;
|
||||||
|
const newSlug = dto.slug?.trim() || existing[0].slug;
|
||||||
|
|
||||||
|
return await this.prisma.$transaction(async (tx) => {
|
||||||
|
// Update symptoms table
|
||||||
|
const updated = await tx.$queryRawUnsafe(`
|
||||||
|
UPDATE symptoms
|
||||||
|
SET
|
||||||
|
name = $2,
|
||||||
|
slug = $3,
|
||||||
|
description = $4,
|
||||||
|
meta_title = $5,
|
||||||
|
meta_description = $6,
|
||||||
|
keywords = $7,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||||
|
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
|
||||||
|
|
||||||
|
// If name changed, cascade update across product_symptoms & products JSON
|
||||||
|
if (oldName !== newName) {
|
||||||
|
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
|
||||||
|
await tx.$executeRaw`
|
||||||
|
UPDATE products
|
||||||
|
SET dosage_config = jsonb_set(
|
||||||
|
dosage_config,
|
||||||
|
'{symptoms}',
|
||||||
|
(
|
||||||
|
SELECT jsonb_agg(
|
||||||
|
CASE
|
||||||
|
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
|
||||||
|
ELSE elem
|
||||||
|
END
|
||||||
|
)
|
||||||
|
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
|
||||||
|
)
|
||||||
|
)
|
||||||
|
WHERE dosage_config ? 'symptoms'
|
||||||
|
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteSymptom(id: string) {
|
||||||
|
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||||
|
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||||
|
const name = existing[0].name;
|
||||||
|
|
||||||
|
return await this.prisma.$transaction(async (tx) => {
|
||||||
|
// Delete join links
|
||||||
|
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
|
||||||
|
// Delete symptom row
|
||||||
|
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
|
||||||
|
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -151,18 +151,61 @@ export class ApprovalsController {
|
|||||||
throw new NotFoundException(`Approval request ${id} not found`);
|
throw new NotFoundException(`Approval request ${id} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (dto.decision === "REJECTED") {
|
||||||
|
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل میشوند
|
||||||
|
await (this.prisma as any).departmentTask.deleteMany({
|
||||||
|
where: { approvalId: id },
|
||||||
|
});
|
||||||
|
await (this.prisma as any).approvalRequest.delete({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر مییابد
|
||||||
const updated = await (this.prisma as any).approvalRequest.update({
|
const updated = await (this.prisma as any).approvalRequest.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
status: dto.decision,
|
status: "APPROVED",
|
||||||
ceoNotes: dto.ceoNotes || null,
|
ceoNotes: dto.ceoNotes || null,
|
||||||
executedAt: dto.decision === "APPROVED" ? new Date() : null,
|
executedAt: new Date(),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
||||||
|
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
||||||
|
where: { approvalId: id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingTask) {
|
||||||
|
await (this.prisma as any).departmentTask.update({
|
||||||
|
where: { id: existingTask.id },
|
||||||
|
data: {
|
||||||
|
status: "TODO",
|
||||||
|
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await (this.prisma as any).departmentTask.create({
|
||||||
|
data: {
|
||||||
|
code: "TSK-" + Date.now().toString().slice(-6),
|
||||||
|
department: item.department,
|
||||||
|
title: item.title,
|
||||||
|
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
|
||||||
|
status: "TODO",
|
||||||
|
priority: "HIGH",
|
||||||
|
assignee: "AI_AGENT",
|
||||||
|
approvalId: item.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: dto.decision === "APPROVED" ? "درخواست با موفقیت تایید شد." : "درخواست رد شد.",
|
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
|
||||||
data: updated,
|
data: updated,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,12 +73,14 @@ export class DepartmentTasksController {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const statusCounts: Record<string, number> = {
|
const statusCounts: Record<string, number> = {
|
||||||
BACKLOG: 0,
|
TODO: 0,
|
||||||
IN_PROGRESS: 0,
|
IN_PROGRESS: 0,
|
||||||
|
TEST: 0,
|
||||||
|
DONE: 0,
|
||||||
|
BACKLOG: 0,
|
||||||
IN_REVIEW: 0,
|
IN_REVIEW: 0,
|
||||||
APPROVED: 0,
|
APPROVED: 0,
|
||||||
DEPLOYING: 0,
|
DEPLOYING: 0,
|
||||||
DONE: 0,
|
|
||||||
};
|
};
|
||||||
const departmentCounts: Record<string, number> = {};
|
const departmentCounts: Record<string, number> = {};
|
||||||
|
|
||||||
@@ -117,7 +119,7 @@ export class DepartmentTasksController {
|
|||||||
department: body.department,
|
department: body.department,
|
||||||
title: body.title,
|
title: body.title,
|
||||||
description: body.description || null,
|
description: body.description || null,
|
||||||
status: body.status || "BACKLOG",
|
status: body.status || "TODO",
|
||||||
priority: body.priority || "MEDIUM",
|
priority: body.priority || "MEDIUM",
|
||||||
assignee: body.assignee || "AI_AGENT",
|
assignee: body.assignee || "AI_AGENT",
|
||||||
acceptanceCriteria: body.acceptanceCriteria || null,
|
acceptanceCriteria: body.acceptanceCriteria || null,
|
||||||
@@ -170,6 +172,10 @@ export class DepartmentTasksController {
|
|||||||
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
||||||
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
||||||
if (body.status === "DONE") updateData.completedAt = new Date();
|
if (body.status === "DONE") updateData.completedAt = new Date();
|
||||||
|
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه میشود
|
||||||
|
if (body.status === "TODO" && body.logNote) {
|
||||||
|
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||||
|
}
|
||||||
|
|
||||||
const updated = await (this.prisma as any).departmentTask.update({
|
const updated = await (this.prisma as any).departmentTask.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ describe("MediaService", () => {
|
|||||||
|
|
||||||
const validFile = {
|
const validFile = {
|
||||||
originalname: "product-cover.webp",
|
originalname: "product-cover.webp",
|
||||||
buffer: Buffer.from("dummy-image-bytes"),
|
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
|
||||||
mimetype: "image/webp",
|
mimetype: "image/webp",
|
||||||
size: 5000,
|
size: 5000,
|
||||||
} as any;
|
} as any;
|
||||||
|
|||||||
@@ -79,6 +79,28 @@ export class MediaService {
|
|||||||
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SEC-01: Magic number verification for uploaded binary content
|
||||||
|
const buf = file.buffer;
|
||||||
|
if (!buf || buf.length < 4) {
|
||||||
|
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||||
|
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
||||||
|
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
||||||
|
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
||||||
|
const isWebp =
|
||||||
|
buf.length >= 12 &&
|
||||||
|
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
||||||
|
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
||||||
|
|
||||||
|
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const filename = `${uniqueSuffix}${ext}`;
|
const filename = `${uniqueSuffix}${ext}`;
|
||||||
const filePath = path.join(uploadDir, filename);
|
const filePath = path.join(uploadDir, filename);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Controller, Get, Query, UseGuards } from "@nestjs/common";
|
||||||
|
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||||
|
import { RolesGuard } from "../common/guards/roles.guard";
|
||||||
|
import { Roles } from "../common/decorators/roles.decorator";
|
||||||
|
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles("Admin", "SUPER_ADMIN")
|
||||||
|
@Controller("admin/support-chat")
|
||||||
|
export class SupportChatAnalyticsController {
|
||||||
|
constructor(private readonly analytics: SupportChatAnalyticsService) {}
|
||||||
|
@Get("stats") stats(@Query("startDate") startDate?: string, @Query("endDate") endDate?: string) { return this.analytics.stats(startDate, endDate).then(data => ({ success: true, data })); }
|
||||||
|
@Get("conversations") conversations(@Query("page") page?: string, @Query("limit") limit?: string, @Query("startDate") startDate?: string, @Query("endDate") endDate?: string, @Query("onlyUnanswered") onlyUnanswered?: string) { return this.analytics.conversations(Number(page), Number(limit), startDate, endDate, onlyUnanswered === "true").then(data => ({ success: true, ...data })); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SupportChatAnalyticsService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async stats(startDate?: string, endDate?: string) {
|
||||||
|
const where = this.range(startDate, endDate);
|
||||||
|
const [conversations, messages, authenticated, unanswered, followup, escalated, topics] = await Promise.all([
|
||||||
|
this.prisma.supportConversation.count({ where }),
|
||||||
|
this.prisma.supportConversationMessage.count({ where: { conversation: where } }),
|
||||||
|
this.prisma.supportConversation.count({ where: { ...where, userId: { not: null } } }),
|
||||||
|
this.prisma.supportConversation.count({ where: { ...where, unanswered: true } }),
|
||||||
|
this.prisma.supportConversation.count({ where: { ...where, needsFollowup: true } }),
|
||||||
|
this.prisma.supportConversation.count({ where: { ...where, escalationSignal: true } }),
|
||||||
|
this.prisma.supportConversation.findMany({ where, select: { topics: true }, take: 5000 }),
|
||||||
|
]);
|
||||||
|
const topicCounts: Record<string, number> = {};
|
||||||
|
for (const row of topics) for (const topic of Array.isArray(row.topics) ? row.topics : []) if (typeof topic === "string") topicCounts[topic] = (topicCounts[topic] || 0) + 1;
|
||||||
|
return { conversations, messages, authenticated, anonymous: conversations - authenticated, unanswered, followup, escalated, topics: topicCounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
async conversations(page = 1, limit = 25, startDate?: string, endDate?: string, onlyUnanswered = false) {
|
||||||
|
const safePage = Math.max(1, Math.min(10000, Number(page) || 1));
|
||||||
|
const safeLimit = Math.max(1, Math.min(100, Number(limit) || 25));
|
||||||
|
const where = { ...this.range(startDate, endDate), ...(onlyUnanswered ? { unanswered: true } : {}) };
|
||||||
|
const [data, total] = await Promise.all([
|
||||||
|
this.prisma.supportConversation.findMany({ where, orderBy: { updatedAt: "desc" }, skip: (safePage - 1) * safeLimit, take: safeLimit, include: { user: { select: { id: true, firstName: true, lastName: true, mobile: true, email: true } }, messages: { orderBy: { sequence: "asc" }, take: 40 } } }),
|
||||||
|
this.prisma.supportConversation.count({ where }),
|
||||||
|
]);
|
||||||
|
return { data, meta: { total, page: safePage, limit: safeLimit, lastPage: Math.ceil(total / safeLimit) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
private range(startDate?: string, endDate?: string) {
|
||||||
|
const createdAt: any = {};
|
||||||
|
if (startDate && /^\d{4}-\d{2}-\d{2}$/.test(startDate)) createdAt.gte = new Date(`${startDate}T00:00:00.000Z`);
|
||||||
|
if (endDate && /^\d{4}-\d{2}-\d{2}$/.test(endDate)) { const end = new Date(`${endDate}T00:00:00.000Z`); end.setUTCDate(end.getUTCDate() + 1); createdAt.lt = end; }
|
||||||
|
return Object.keys(createdAt).length ? { createdAt } : {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { TasksModule } from './common/services/tasks.module';
|
||||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||||
import { PrismaModule } from "./prisma/prisma.module";
|
import { PrismaModule } from "./prisma/prisma.module";
|
||||||
import { SupportChatModule } from './support-chat/support-chat.module';
|
import { SupportChatModule } from './support-chat/support-chat.module';
|
||||||
@@ -79,6 +80,7 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
B2BModule,
|
B2BModule,
|
||||||
FaqModule,
|
FaqModule,
|
||||||
MenuModule,
|
MenuModule,
|
||||||
|
TasksModule,
|
||||||
],
|
],
|
||||||
controllers: [MetricsController],
|
controllers: [MetricsController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
|
|||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should query published blogs with pagination", async () => {
|
it("should query published blogs with pagination", async () => {
|
||||||
const blogs = [
|
const blogs = [
|
||||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null },
|
||||||
];
|
];
|
||||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||||
mockPrisma.blog.count.mockResolvedValue(1);
|
mockPrisma.blog.count.mockResolvedValue(1);
|
||||||
@@ -49,6 +49,8 @@ describe("BlogsService", () => {
|
|||||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||||
expect(result.data).toEqual(blogs);
|
expect(result.data).toEqual(blogs);
|
||||||
expect(result.meta.total).toBe(1);
|
expect(result.meta.total).toBe(1);
|
||||||
|
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
||||||
|
expect(query.include.author).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should filter by categorySlug and search term", async () => {
|
it("should filter by categorySlug and search term", async () => {
|
||||||
|
|||||||
@@ -68,9 +68,6 @@ export class BlogsService {
|
|||||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
author: {
|
|
||||||
select: { firstName: true, lastName: true },
|
|
||||||
},
|
|
||||||
category: {
|
category: {
|
||||||
select: { id: true, name: true, slug: true },
|
select: { id: true, name: true, slug: true },
|
||||||
},
|
},
|
||||||
@@ -110,7 +107,6 @@ export class BlogsService {
|
|||||||
take: 4,
|
take: 4,
|
||||||
orderBy: { publishedAt: "desc" },
|
orderBy: { publishedAt: "desc" },
|
||||||
include: {
|
include: {
|
||||||
author: { select: { firstName: true, lastName: true } },
|
|
||||||
category: { select: { id: true, name: true, slug: true } },
|
category: { select: { id: true, name: true, slug: true } },
|
||||||
tags: { select: { id: true, name: true, slug: true } },
|
tags: { select: { id: true, name: true, slug: true } },
|
||||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||||
@@ -127,7 +123,6 @@ export class BlogsService {
|
|||||||
take: 4,
|
take: 4,
|
||||||
orderBy: { publishedAt: "desc" },
|
orderBy: { publishedAt: "desc" },
|
||||||
include: {
|
include: {
|
||||||
author: { select: { firstName: true, lastName: true } },
|
|
||||||
category: { select: { id: true, name: true, slug: true } },
|
category: { select: { id: true, name: true, slug: true } },
|
||||||
tags: { select: { id: true, name: true, slug: true } },
|
tags: { select: { id: true, name: true, slug: true } },
|
||||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||||
@@ -163,9 +158,6 @@ export class BlogsService {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
author: {
|
|
||||||
select: { firstName: true, lastName: true },
|
|
||||||
},
|
|
||||||
category: {
|
category: {
|
||||||
select: { id: true, name: true, slug: true },
|
select: { id: true, name: true, slug: true },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TasksService } from './tasks.service';
|
||||||
|
import { OrdersModule } from '../../orders/orders.module';
|
||||||
|
import { PaymentModule } from '../../payment/payment.module';
|
||||||
|
import { RedisModule } from '../../redis/redis.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [OrdersModule, PaymentModule, RedisModule],
|
||||||
|
providers: [TasksService],
|
||||||
|
exports: [TasksService],
|
||||||
|
})
|
||||||
|
export class TasksModule {}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
||||||
|
import { OrdersService } from '../../orders/orders.service';
|
||||||
|
import { RedisService } from '../../redis/redis.service';
|
||||||
|
import { PaymentService } from '../../payment/payment.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
|
||||||
|
private readonly logger = new Logger(TasksService.name);
|
||||||
|
private reservationTimer: NodeJS.Timeout | null = null;
|
||||||
|
private reconciliationTimer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly ordersService: OrdersService,
|
||||||
|
private readonly paymentService: PaymentService,
|
||||||
|
private readonly redisService: RedisService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
onApplicationBootstrap() {
|
||||||
|
this.logger.log('Starting background maintenance tasks...');
|
||||||
|
|
||||||
|
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
|
||||||
|
this.reservationTimer = setInterval(async () => {
|
||||||
|
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
|
||||||
|
if (!lockAcquired) {
|
||||||
|
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await this.ordersService.releaseExpiredInventoryReservations();
|
||||||
|
if (result.releasedCount > 0) {
|
||||||
|
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
|
||||||
|
} finally {
|
||||||
|
await this.redisService.releaseLock('task:inventory_release');
|
||||||
|
}
|
||||||
|
}, 5 * 60 * 1000);
|
||||||
|
|
||||||
|
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
|
||||||
|
this.reconciliationTimer = setInterval(async () => {
|
||||||
|
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
|
||||||
|
if (!lockAcquired) {
|
||||||
|
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await this.paymentService.reconcilePendingTransactions();
|
||||||
|
if (result.total > 0) {
|
||||||
|
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
|
||||||
|
} finally {
|
||||||
|
await this.redisService.releaseLock('task:payment_reconciliation');
|
||||||
|
}
|
||||||
|
}, 10 * 60 * 1000);
|
||||||
|
|
||||||
|
// Initial check on startup after 30 seconds
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await this.ordersService.releaseExpiredInventoryReservations();
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
|
||||||
|
}
|
||||||
|
}, 30 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
onApplicationShutdown() {
|
||||||
|
this.logger.log('Stopping background maintenance tasks...');
|
||||||
|
if (this.reservationTimer) {
|
||||||
|
clearInterval(this.reservationTimer);
|
||||||
|
this.reservationTimer = null;
|
||||||
|
}
|
||||||
|
if (this.reconciliationTimer) {
|
||||||
|
clearInterval(this.reconciliationTimer);
|
||||||
|
this.reconciliationTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,9 +13,8 @@ describe("ContactService", () => {
|
|||||||
count: jest.fn(),
|
count: jest.fn(),
|
||||||
update: jest.fn(),
|
update: jest.fn(),
|
||||||
},
|
},
|
||||||
contactInfo: {
|
setting: {
|
||||||
findMany: jest.fn(),
|
findMany: jest.fn(),
|
||||||
upsert: jest.fn(),
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,26 +81,27 @@ describe("ContactService", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("getContactInfo", () => {
|
describe("getContactInfo", () => {
|
||||||
it("should return contact items if they already exist", async () => {
|
it("should return contact items from canonical settings", async () => {
|
||||||
const items = [
|
mockPrisma.setting.findMany.mockResolvedValue([
|
||||||
{ id: "1", key: "branch_info", title: "تلفن", value: "021" },
|
{ key: "CONTACT_PHONE", value: "021-12345678" },
|
||||||
];
|
{ key: "CONTACT_EMAIL", value: "support@example.test" },
|
||||||
mockPrisma.contactInfo.findMany.mockResolvedValue(items);
|
{ key: "CONTACT_ADDRESS", value: "آدرس تنظیمشده" },
|
||||||
|
]);
|
||||||
|
|
||||||
const result = await service.getContactInfo();
|
const result = await service.getContactInfo();
|
||||||
expect(result).toEqual(items);
|
expect(result).toEqual([
|
||||||
expect(mockPrisma.contactInfo.upsert).not.toHaveBeenCalled();
|
{ key: "phone", title: "تلفنهای تماس", value: "021-12345678", icon: "phone", order: 1 },
|
||||||
|
{ key: "email", title: "پست الکترونیک", value: "support@example.test", icon: "mail", order: 2 },
|
||||||
|
{ key: "address", title: "نشانی دفتر مرکزی", value: "آدرس تنظیمشده", icon: "map-pin", order: 3 },
|
||||||
|
]);
|
||||||
|
expect(mockPrisma.setting.findMany).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should seed default items if empty", async () => {
|
it("does not return hardcoded contact values when settings are empty", async () => {
|
||||||
mockPrisma.contactInfo.findMany
|
mockPrisma.setting.findMany.mockResolvedValue([]);
|
||||||
.mockResolvedValueOnce([])
|
expect(await service.getContactInfo()).toEqual([]);
|
||||||
.mockResolvedValueOnce([{ key: "branch_info" }]);
|
|
||||||
|
|
||||||
const result = await service.getContactInfo();
|
|
||||||
expect(mockPrisma.contactInfo.upsert).toHaveBeenCalledTimes(3);
|
|
||||||
expect(result).toHaveLength(1);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getAllSubmissions", () => {
|
describe("getAllSubmissions", () => {
|
||||||
|
|||||||
@@ -65,51 +65,20 @@ export class ContactService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getContactInfo() {
|
async getContactInfo() {
|
||||||
let items = await this.prisma.contactInfo.findMany({
|
const settings = await this.prisma.setting.findMany({
|
||||||
orderBy: { order: "asc" },
|
where: { key: { in: ["CONTACT_PHONE", "contact_phone", "CONTACT_EMAIL", "contact_email", "CONTACT_ADDRESS", "contact_address"] } },
|
||||||
|
select: { key: true, value: true },
|
||||||
});
|
});
|
||||||
|
const values = new Map(settings.map((item) => [item.key, String(item.value ?? "")]));
|
||||||
if (items.length === 0) {
|
const read = (...keys: string[]) => keys.map((key) => values.get(key)).find((value) => value?.trim()) || "";
|
||||||
// Seed default items if empty
|
const phone = read("CONTACT_PHONE", "contact_phone");
|
||||||
const defaultItems = [
|
const email = read("CONTACT_EMAIL", "contact_email");
|
||||||
{
|
const address = read("CONTACT_ADDRESS", "contact_address");
|
||||||
key: "branch_info",
|
return [
|
||||||
title: "اطلاعات نمایندگی",
|
{ key: "phone", title: "تلفنهای تماس", value: phone, icon: "phone", order: 1 },
|
||||||
value:
|
{ key: "email", title: "پست الکترونیک", value: email, icon: "mail", order: 2 },
|
||||||
"تلفنهای تماس\n۰۲۱-۸۸۸۸ ۴۴۴۴\n\nشنبه تا چهارشنبه ۹:۰۰ الی ۱۸:۰۰",
|
{ key: "address", title: "نشانی دفتر مرکزی", value: address, icon: "map-pin", order: 3 },
|
||||||
icon: "phone",
|
].filter((item) => item.value.trim());
|
||||||
order: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "email_info",
|
|
||||||
title: "پست الکترونیک",
|
|
||||||
value: "info@canina.ir\n\nپاسخگویی در کمتر از ۲۴ ساعت کاری",
|
|
||||||
icon: "mail",
|
|
||||||
order: 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "address_info",
|
|
||||||
title: "نشانی دفتر مرکزی",
|
|
||||||
value: "تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹",
|
|
||||||
icon: "map-pin",
|
|
||||||
order: 3,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const item of defaultItems) {
|
|
||||||
await this.prisma.contactInfo.upsert({
|
|
||||||
where: { key: item.key },
|
|
||||||
update: {},
|
|
||||||
create: item,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
items = await this.prisma.contactInfo.findMany({
|
|
||||||
orderBy: { order: "asc" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return items;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAllSubmissions(page = 1, limit = 20, status?: string) {
|
async getAllSubmissions(page = 1, limit = 20, status?: string) {
|
||||||
|
|||||||
@@ -5,5 +5,6 @@ import { OrdersController } from "./orders.controller";
|
|||||||
@Module({
|
@Module({
|
||||||
controllers: [OrdersController],
|
controllers: [OrdersController],
|
||||||
providers: [OrdersService],
|
providers: [OrdersService],
|
||||||
|
exports: [OrdersService],
|
||||||
})
|
})
|
||||||
export class OrdersModule {}
|
export class OrdersModule {}
|
||||||
@@ -39,7 +39,7 @@ describe("OrdersService", () => {
|
|||||||
uiText: {
|
uiText: {
|
||||||
findFirst: jest.fn().mockResolvedValue(null),
|
findFirst: jest.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
$executeRaw: jest.fn(),
|
$executeRaw: jest.fn().mockResolvedValue(1),
|
||||||
$transaction: jest.fn(),
|
$transaction: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -346,13 +346,14 @@ export class OrdersService {
|
|||||||
// Deduct inventory immediately for non-online orders (card to card)
|
// Deduct inventory immediately for non-online orders (card to card)
|
||||||
if (!isOnline) {
|
if (!isOnline) {
|
||||||
for (const item of createOrderDto.items) {
|
for (const item of createOrderDto.items) {
|
||||||
|
// BE-05: Atomic decrement with inventory constraint guard
|
||||||
const updated = await tx.product.update({
|
const updated = await tx.product.update({
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: {
|
data: {
|
||||||
stock: { decrement: item.quantity },
|
stock: { decrement: item.quantity },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (updated.stock <= 0) {
|
if (updated && updated.stock <= 0) {
|
||||||
await tx.product.update({
|
await tx.product.update({
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: { stockStatus: "OUT_OF_STOCK" },
|
data: { stockStatus: "OUT_OF_STOCK" },
|
||||||
|
|||||||
@@ -447,17 +447,32 @@ export class PaymentService {
|
|||||||
if (orderWithItems?.orderItems) {
|
if (orderWithItems?.orderItems) {
|
||||||
for (const item of orderWithItems.orderItems) {
|
for (const item of orderWithItems.orderItems) {
|
||||||
if (item.productId) {
|
if (item.productId) {
|
||||||
const updated = await tx.product.update({
|
// BE-05: Atomic decrement with inventory constraint guard
|
||||||
where: { id: item.productId },
|
let updateCount = 1;
|
||||||
data: {
|
if (typeof (tx as any).$executeRaw === 'function') {
|
||||||
stock: { decrement: item.quantity },
|
updateCount = await tx.$executeRaw`
|
||||||
},
|
UPDATE products
|
||||||
});
|
SET stock = stock - ${item.quantity},
|
||||||
if (updated.stock <= 0) {
|
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
|
||||||
await tx.product.update({
|
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
|
||||||
|
`;
|
||||||
|
} else {
|
||||||
|
const updated = await tx.product.update({
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: { stockStatus: "OUT_OF_STOCK" },
|
data: { stock: { decrement: item.quantity } },
|
||||||
});
|
});
|
||||||
|
if (updated.stock <= 0) {
|
||||||
|
await tx.product.update({
|
||||||
|
where: { id: item.productId },
|
||||||
|
data: { stockStatus: "OUT_OF_STOCK" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateCount === 0) {
|
||||||
|
this.logger.error(
|
||||||
|
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,39 @@
|
|||||||
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
|
||||||
|
import { Logger } from "@nestjs/common";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PrismaService
|
export class PrismaService
|
||||||
extends PrismaClient
|
extends PrismaClient
|
||||||
implements OnModuleInit, OnModuleDestroy
|
implements OnModuleInit, OnModuleDestroy
|
||||||
{
|
{
|
||||||
|
private readonly logger = new Logger(PrismaService.name);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super({
|
||||||
|
log: [
|
||||||
|
{ emit: "event", level: "query" },
|
||||||
|
{ emit: "stdout", level: "error" },
|
||||||
|
{ emit: "stdout", level: "warn" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async onModuleInit() {
|
async onModuleInit() {
|
||||||
await this.$connect();
|
await this.$connect();
|
||||||
|
|
||||||
|
// BE-07: Slow query logging interceptor (> 300ms)
|
||||||
|
if (typeof (this as any).$on === "function") {
|
||||||
|
(this as any).$on("query", (e: any) => {
|
||||||
|
if (e.duration >= 300) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await this.ensureTablesExist();
|
await this.ensureTablesExist();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ describe("ProductsService", () => {
|
|||||||
findFirst: jest.fn(),
|
findFirst: jest.fn(),
|
||||||
count: jest.fn(),
|
count: jest.fn(),
|
||||||
},
|
},
|
||||||
|
orderItem: {
|
||||||
|
groupBy: jest.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockRevalidationService = {
|
const mockRevalidationService = {
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ export class ProductsService {
|
|||||||
|
|
||||||
const skip = (page - 1) * limit;
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
// 1. Fetch products with lean relations (no heavy N+1 orderItems join)
|
||||||
const [rawProducts, total] = await Promise.all([
|
const [rawProducts, total] = await Promise.all([
|
||||||
this.prisma.product.findMany({
|
this.prisma.product.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
@@ -96,15 +97,33 @@ export class ProductsService {
|
|||||||
include: {
|
include: {
|
||||||
ingredientList: true,
|
ingredientList: true,
|
||||||
symptoms: true,
|
symptoms: true,
|
||||||
orderItems: {
|
|
||||||
where: { order: { status: { not: "CANCELLED" } } },
|
|
||||||
select: { quantity: true },
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
this.prisma.product.count({ where: whereClause }),
|
this.prisma.product.count({ where: whereClause }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// 2. Efficient single aggregate query for total sold counts for the current page slice
|
||||||
|
const productIds = rawProducts.map((p) => p.id);
|
||||||
|
let salesMap: Record<string, number> = {};
|
||||||
|
|
||||||
|
if (productIds.length > 0) {
|
||||||
|
const salesAgg = await this.prisma.orderItem.groupBy({
|
||||||
|
by: ['productId'],
|
||||||
|
_sum: { quantity: true },
|
||||||
|
where: {
|
||||||
|
productId: { in: productIds },
|
||||||
|
order: { status: { not: 'CANCELLED' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
salesMap = salesAgg.reduce((acc, row) => {
|
||||||
|
if (row.productId) {
|
||||||
|
acc[row.productId] = Number(row._sum.quantity) || 0;
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, number>);
|
||||||
|
}
|
||||||
|
|
||||||
const isWholesaleOrAdmin =
|
const isWholesaleOrAdmin =
|
||||||
userRole === "User_Wholesale" ||
|
userRole === "User_Wholesale" ||
|
||||||
userRole === "User_Partner" ||
|
userRole === "User_Partner" ||
|
||||||
@@ -113,12 +132,8 @@ export class ProductsService {
|
|||||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||||
|
|
||||||
const data = rawProducts.map((p) => {
|
const data = rawProducts.map((p) => {
|
||||||
const totalSold =
|
const totalSold = salesMap[p.id] || 0;
|
||||||
p.orderItems?.reduce(
|
const { buyPrice, wholesalePrice, ...publicProduct } = p;
|
||||||
(acc, item) => acc + (Number(item.quantity) || 0),
|
|
||||||
0,
|
|
||||||
) || 0;
|
|
||||||
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
|
|
||||||
void buyPrice;
|
void buyPrice;
|
||||||
void wholesalePrice;
|
void wholesalePrice;
|
||||||
if (!isWholesaleOrAdmin) {
|
if (!isWholesaleOrAdmin) {
|
||||||
|
|||||||
@@ -140,6 +140,18 @@ describe("TorobController", () => {
|
|||||||
expect(result.max_pages).toBe(1);
|
expect(result.max_pages).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([['garbage', 'garbage', 100], ['2', 'garbage', 100], ['garbage', '20', 20]])(
|
||||||
|
"defaults nonnumeric pagination safely (%s, %s)", async (page, size, take) => {
|
||||||
|
mockPrismaService.product.count.mockResolvedValue(0);
|
||||||
|
mockPrismaService.product.findMany.mockResolvedValue([]);
|
||||||
|
const result = await controller.getTorobProducts(page, size);
|
||||||
|
expect(mockPrismaService.product.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ skip: page === '2' ? 100 : 0, take }),
|
||||||
|
);
|
||||||
|
expect(result.max_pages).toBe(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it("should correctly mark out-of-stock products", async () => {
|
it("should correctly mark out-of-stock products", async () => {
|
||||||
const mockOutOfStock = [
|
const mockOutOfStock = [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -141,10 +141,12 @@ export class TorobController {
|
|||||||
@Query("page") pageQuery?: string,
|
@Query("page") pageQuery?: string,
|
||||||
@Query("page_size") pageSizeQuery?: string,
|
@Query("page_size") pageSizeQuery?: string,
|
||||||
) {
|
) {
|
||||||
const page = Math.max(1, parseInt(pageQuery || "1", 10));
|
const parsedPage = parseInt(pageQuery || "1", 10);
|
||||||
|
const parsedSize = parseInt(pageSizeQuery || "100", 10);
|
||||||
|
const page = Math.max(1, Number.isFinite(parsedPage) ? parsedPage : 1);
|
||||||
const pageSize = Math.min(
|
const pageSize = Math.min(
|
||||||
100,
|
100,
|
||||||
Math.max(10, parseInt(pageSizeQuery || "100", 10)),
|
Math.max(10, Number.isFinite(parsedSize) ? parsedSize : 100),
|
||||||
);
|
);
|
||||||
const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace(
|
const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace(
|
||||||
/\/$/,
|
/\/$/,
|
||||||
|
|||||||
@@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
|
|||||||
async ttl(key: string): Promise<number> {
|
async ttl(key: string): Promise<number> {
|
||||||
return this.client.ttl(key);
|
return this.client.ttl(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acquire a distributed lock using Redis SET NX EX
|
||||||
|
* Returns true if lock acquired, false otherwise
|
||||||
|
*/
|
||||||
|
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
|
||||||
|
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
|
||||||
|
return res === "OK";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Release a distributed lock
|
||||||
|
*/
|
||||||
|
async releaseLock(key: string): Promise<void> {
|
||||||
|
await this.client.del(`lock:${key}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -94,4 +94,26 @@ describe("SettingsService", () => {
|
|||||||
});
|
});
|
||||||
expect(result.key).toBe("k");
|
expect(result.key).toBe("k");
|
||||||
});
|
});
|
||||||
|
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
|
||||||
|
mockPrisma.uiText.findMany.mockResolvedValue([
|
||||||
|
{ key: "SITE_NAME", value: "Canina Iran" },
|
||||||
|
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
|
||||||
|
{ key: "zibal_api_key", value: "secret_api_key" },
|
||||||
|
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
|
||||||
|
]);
|
||||||
|
mockPrisma.setting.findMany.mockResolvedValue([
|
||||||
|
{ key: "PUBLIC_BANNER", value: "Welcome" },
|
||||||
|
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = await service.getUiTexts();
|
||||||
|
const returnedKeys = result.map((r) => r.key);
|
||||||
|
|
||||||
|
expect(returnedKeys).toContain("SITE_NAME");
|
||||||
|
expect(returnedKeys).toContain("PUBLIC_BANNER");
|
||||||
|
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
|
||||||
|
expect(returnedKeys).not.toContain("zibal_api_key");
|
||||||
|
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
|
||||||
|
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -247,7 +247,7 @@ export class SettingsService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 2. Add from settings and unpack object keys
|
// 2. Add from settings and unpack object keys
|
||||||
settings.forEach((s) => {
|
settings.filter((s) => s.key !== "support_chat").forEach((s) => {
|
||||||
const valStr =
|
const valStr =
|
||||||
typeof s.value === "string" ? s.value : JSON.stringify(s.value);
|
typeof s.value === "string" ? s.value : JSON.stringify(s.value);
|
||||||
mergedMap.set(s.key, valStr);
|
mergedMap.set(s.key, valStr);
|
||||||
@@ -269,13 +269,31 @@ export class SettingsService implements OnModuleInit {
|
|||||||
mergedMap.set("b2b_enabled", val);
|
mergedMap.set("b2b_enabled", val);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Array.from(mergedMap.entries()).map(([key, value]) => ({
|
const SENSITIVE_KEY_PATTERNS = [
|
||||||
key,
|
/token/i,
|
||||||
value,
|
/secret/i,
|
||||||
}));
|
/password/i,
|
||||||
|
/api_key/i,
|
||||||
|
/apikey/i,
|
||||||
|
/private/i,
|
||||||
|
/zibal/i,
|
||||||
|
/kavenegar/i,
|
||||||
|
/ghasedak/i,
|
||||||
|
/credential/i,
|
||||||
|
/account_id/i,
|
||||||
|
/access_key/i,
|
||||||
|
];
|
||||||
|
|
||||||
|
return Array.from(mergedMap.entries())
|
||||||
|
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
|
||||||
|
.map(([key, value]) => ({
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUiText(key: string, value: string) {
|
async updateUiText(key: string, value: string) {
|
||||||
|
if (key === "support_chat") throw new Error("Use support-chat settings API");
|
||||||
const strVal = String(value ?? "");
|
const strVal = String(value ?? "");
|
||||||
const allKeysToUpdate = new Set<string>([key]);
|
const allKeysToUpdate = new Set<string>([key]);
|
||||||
const aliases = CANONICAL_ALIASES[key] || [];
|
const aliases = CANONICAL_ALIASES[key] || [];
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Body, Controller, Get, Put, UseGuards, Header } from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { RolesGuard } from '../common/guards/roles.guard';
|
||||||
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
|
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||||
|
@Controller('support-chat')
|
||||||
|
export class SupportChatSettingsController {
|
||||||
|
constructor(private readonly settings: SupportChatSettingsService) {}
|
||||||
|
@Get('config') @Header('Cache-Control', 'no-store')
|
||||||
|
config() { return this.settings.publicConfig(); }
|
||||||
|
@Get('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
|
||||||
|
read() { return this.settings.read(); }
|
||||||
|
@Get('catalog') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
|
||||||
|
catalog() { return this.settings.catalog(); }
|
||||||
|
@Put('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin')
|
||||||
|
save(@Body() body: unknown) { return this.settings.save(body); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
export const CHAT_SETTINGS_KEY = 'support_chat';
|
||||||
|
export type ChatSettings = { enabled: boolean; provider: string; model: string; label: string; icon: string };
|
||||||
|
const fail = () => new ServiceUnavailableException('تنظیمات پشتیبان هوشمند در دسترس نیست.');
|
||||||
|
export const ICONS = ['chat', 'paw', 'bot'] as const;
|
||||||
|
export function validateSettings(value: any): ChatSettings {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'enabled,icon,label,model,provider' || typeof value.enabled !== 'boolean' || typeof value.provider !== 'string' || typeof value.model !== 'string' || value.provider.length > 100 || value.model.length > 160 || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 60 || /[<>\x00-\x1f]/.test(value.label) || !ICONS.includes(value.icon)) throw new BadRequestException('تنظیمات پشتیبان نامعتبر است.');
|
||||||
|
return { enabled: value.enabled, provider: value.provider, model: value.model, label: value.label.trim(), icon: value.icon };
|
||||||
|
}
|
||||||
|
@Injectable()
|
||||||
|
export class SupportChatSettingsService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
async read(): Promise<ChatSettings> {
|
||||||
|
try {
|
||||||
|
const row = await this.prisma.setting.findUnique({ where: { key: CHAT_SETTINGS_KEY } });
|
||||||
|
if (!row) throw fail();
|
||||||
|
return validateSettings(row.value);
|
||||||
|
} catch { throw fail(); }
|
||||||
|
}
|
||||||
|
async publicConfig() {
|
||||||
|
const { enabled, label, icon } = await this.read();
|
||||||
|
return { enabled, label, icon };
|
||||||
|
}
|
||||||
|
async catalog(): Promise<{ providers: { id: string; label: string; models: string[] }[] }> {
|
||||||
|
try {
|
||||||
|
const url = process.env.SUPPORT_CHAT_URL;
|
||||||
|
const key = process.env.SUPPORT_CHAT_KEY;
|
||||||
|
if (!url?.endsWith('/ask') || !key) throw fail();
|
||||||
|
const response = await fetch(url.replace(/\/ask$/, '/catalog'), { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(100000), redirect: 'error' });
|
||||||
|
if (!response.ok) throw fail();
|
||||||
|
const data = await response.json();
|
||||||
|
if (!Array.isArray(data.providers) || !data.providers.length || data.providers.length > 50) throw fail();
|
||||||
|
const safe = (s: any) => typeof s === 'string' && s.length > 0 && s.length <= 160 && /^[\w .:/@+\[\]()-]+$/.test(s) && !s.includes('://');
|
||||||
|
return { providers: data.providers.map((p: any) => {
|
||||||
|
if (!/^configured-[a-f0-9]{16}$/.test(p.id) || !safe(p.label) || !Array.isArray(p.models) || !p.models.length || p.models.length > 2000 || !p.models.every(safe)) throw fail();
|
||||||
|
return { id: p.id, label: p.label, models: p.models };
|
||||||
|
}) };
|
||||||
|
} catch { throw fail(); }
|
||||||
|
}
|
||||||
|
async save(input: unknown) {
|
||||||
|
const value = validateSettings(input);
|
||||||
|
if (value.provider || value.model || value.enabled) {
|
||||||
|
const catalog = await this.catalog();
|
||||||
|
if (!catalog.providers.some(p => p.id === value.provider && p.models.includes(value.model))) throw new BadRequestException('مدل متعلق به ارائهدهنده انتخابشده نیست.');
|
||||||
|
}
|
||||||
|
await this.prisma.setting.upsert({ where: { key: CHAT_SETTINGS_KEY }, create: { key: CHAT_SETTINGS_KEY, category: 'support-chat', value }, update: { value } });
|
||||||
|
return this.read();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { SupportChatSettingsService, validateSettings } from './support-chat-settings.service';
|
||||||
|
import { SupportChatService } from './support-chat.service';
|
||||||
|
import { SupportChatSettingsController } from './support-chat-settings.controller';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import { PassportModule, PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import request from 'supertest';
|
||||||
|
class TestJwt extends PassportStrategy(Strategy) {
|
||||||
|
constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey:'test' }); }
|
||||||
|
validate(p: any) { return { id:p.sub, role:p.role }; }
|
||||||
|
}
|
||||||
|
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
|
||||||
|
describe('smart chat settings', () => {
|
||||||
|
let stored:any = null;
|
||||||
|
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} };
|
||||||
|
let service:SupportChatSettingsService;
|
||||||
|
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
|
||||||
|
afterEach(()=>jest.restoreAllMocks());
|
||||||
|
const catalog=()=>jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'Configured',models:[selected.model]}]})} as any);
|
||||||
|
it('persists and reads exact fields and projects safe public config',async()=>{catalog();expect(await service.save(selected)).toEqual(selected);expect(await service.read()).toEqual(selected);expect(await service.publicConfig()).toEqual({enabled:true,label:selected.label,icon:'paw'});});
|
||||||
|
it.each([{...selected,model:'unknown'},{...selected,provider:'http://127.0.0.1'},{...selected,provider:'configured-ffffffffffffffff'}])('rejects invalid combination %j',async s=>{catalog();await expect(service.save(s)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
|
||||||
|
it.each(['https://evil/a.svg','<svg onload=alert(1)>','data:image/svg+xml,abc','/uploads/x.svg'])('rejects unsafe icon %s',icon=>{expect(()=>validateSettings({...selected,icon})).toThrow();});
|
||||||
|
it('rejects unknown fields and invalid label',()=>{expect(()=>validateSettings({...selected,baseUrl:'https://evil'})).toThrow();expect(()=>validateSettings({...selected,label:'<script>'})).toThrow();});
|
||||||
|
it('fails closed without configuration',async()=>{await expect(service.read()).rejects.toThrow();});
|
||||||
|
it('fails closed on catalog outage',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.save(selected)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
|
||||||
|
it('rejects sanitized catalog violations',async()=>{jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'https://internal',models:['m'],api_key:'secret'}]})} as any);await expect(service.catalog()).rejects.toThrow();});
|
||||||
|
it('disabling rejects ask before model and private DB calls',async()=>{stored={value:{...selected,enabled:false}};const f=jest.spyOn(global,'fetch');await expect(new SupportChatService(prisma,service).ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow();expect(f).not.toHaveBeenCalled();expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
||||||
|
it('uses identical stored selection for classify and answer with no identity leakage',async()=>{stored={value:selected};const f=jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?{intent:'public'}:{answer:'سلام'}} as any));await new SupportChatService(prisma,service).ask({message:'سلام'},{id:'alice'});const bodies=f.mock.calls.map(c=>JSON.parse(c[1]!.body as string));expect(bodies.map(b=>b.selection)).toEqual([{provider:selected.provider,model:selected.model},{provider:selected.provider,model:selected.model}]);expect(JSON.stringify(bodies)).not.toContain('alice');});
|
||||||
|
});
|
||||||
|
describe('settings HTTP admin boundary',()=>{
|
||||||
|
let app:any;
|
||||||
|
const jwt=new JwtService({secret:'test'});
|
||||||
|
const service={read:jest.fn(async()=>selected),publicConfig:jest.fn(async()=>({enabled:true,label:'test',icon:'bot'})),save:jest.fn(async()=>selected),catalog:jest.fn(async()=>({providers:[]}))};
|
||||||
|
beforeAll(async()=>{const mod=await Test.createTestingModule({imports:[PassportModule],controllers:[SupportChatSettingsController],providers:[TestJwt,{provide:SupportChatSettingsService,useValue:service}]}).compile();app=mod.createNestApplication();await app.init();});
|
||||||
|
afterAll(()=>app.close());
|
||||||
|
it.each(['settings','catalog'])('rejects anonymous %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).expect(401);});
|
||||||
|
it.each(['settings','catalog'])('rejects customer %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).expect(403);});
|
||||||
|
it('rejects anonymous and customer writes',async()=>{await request(app.getHttpServer()).put('/support-chat/settings').send(selected).expect(401);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).send(selected).expect(403);});
|
||||||
|
it('allows Admin reads and writes',async()=>{const auth='Bearer '+jwt.sign({sub:'admin',role:'Admin'});await request(app.getHttpServer()).get('/support-chat/settings').set('Authorization',auth).expect(200);await request(app.getHttpServer()).get('/support-chat/catalog').set('Authorization',auth).expect(200);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization',auth).send(selected).expect(200);});
|
||||||
|
it('public configuration only returns safe fields',async()=>{const r=await request(app.getHttpServer()).get('/support-chat/config').expect(200);expect(Object.keys(r.body).sort()).toEqual(['enabled','icon','label']);});
|
||||||
|
});
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Body, Controller, Post, Req, UseGuards, Header } from '@nestjs/common';
|
import { Body, Controller, Get, Header, Param, ParseUUIDPipe, Post, Req, UseGuards } from '@nestjs/common';
|
||||||
import { Throttle } from '@nestjs/throttler';
|
import { Throttle } from '@nestjs/throttler';
|
||||||
import { SupportChatService } from './support-chat.service';
|
import { SupportChatService } from './support-chat.service';
|
||||||
import { SupportChatDto } from './support-chat.dto';
|
import { SupportChatDto } from './support-chat.dto';
|
||||||
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
||||||
@Controller('support-chat')
|
@Controller('support-chat')
|
||||||
export class SupportChatController {
|
export class SupportChatController {
|
||||||
constructor(private readonly service: SupportChatService) {}
|
constructor(private readonly service: SupportChatService) {}
|
||||||
@Post('ask') @UseGuards(OptionalCustomerJwtGuard)
|
@Get(':id') @UseGuards(OptionalCustomerJwtGuard) @Header('Cache-Control', 'no-store')
|
||||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
history(@Param('id', ParseUUIDPipe) id: string, @Req() req: { user?: { id: string } }) { return this.service.history(id, req.user); }
|
||||||
@Header('Cache-Control', 'no-store')
|
@Post('ask') @UseGuards(OptionalCustomerJwtGuard) @Throttle({ default: { limit: 10, ttl: 60000 } }) @Header('Cache-Control', 'no-store')
|
||||||
ask(@Body() dto: SupportChatDto, @Req() req: { user?: { id: string } }) { return this.service.ask(dto, req.user); }
|
ask(@Body() dto: SupportChatDto, @Req() req: { user?: { id: string } }) { return this.service.ask(dto, req.user); }
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { IsIn, IsString, Length } from 'class-validator';
|
import { IsOptional, IsString, Length, Matches } from 'class-validator';
|
||||||
export class SupportChatDto {
|
export class SupportChatDto {
|
||||||
@IsString() @Length(1, 1500) message!: string;
|
@IsString() @Length(1, 1500) message!: string;
|
||||||
@IsIn(['public', 'orders', 'wallet']) scope: 'public' | 'orders' | 'wallet' = 'public';
|
@IsOptional() @IsString() @Length(36, 36) @Matches(/^[0-9a-f-]{36}$/i) conversationId?: string;
|
||||||
|
@IsOptional() @IsString() @Length(1, 512) entryPath?: string;
|
||||||
|
@IsOptional() @IsString() @Length(1, 64) @Matches(/^[A-Za-z0-9_-]+$/) anonymousBrowserId?: string;
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||||
import { Test } from '@nestjs/testing';
|
import { Test } from '@nestjs/testing';
|
||||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
import { PassportModule, PassportStrategy } from '@nestjs/passport';
|
import { PassportModule, PassportStrategy } from '@nestjs/passport';
|
||||||
@@ -14,28 +15,41 @@ class TestJwt extends PassportStrategy(Strategy) {
|
|||||||
}
|
}
|
||||||
describe('support HTTP boundary', () => {
|
describe('support HTTP boundary', () => {
|
||||||
let app: INestApplication;
|
let app: INestApplication;
|
||||||
const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22' })) } };
|
const prisma: any = { supportConversation: { create: jest.fn().mockResolvedValue({ id: '11111111-1111-4111-8111-111111111111', userId: null, messages: [] }), findUnique: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}) }, supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22', mobile: where.id+'-mobile', email: where.id+'@example.test', firstName: 'Test', lastName: 'User' })) } };
|
||||||
const jwt = new JwtService({ secret: 'test-secret' });
|
const jwt = new JwtService({ secret: 'test-secret' });
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
||||||
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
|
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
|
||||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
||||||
});
|
});
|
||||||
afterAll(() => app.close());
|
afterAll(() => app.close());
|
||||||
beforeEach(() => { jest.clearAllMocks(); });
|
beforeEach(() => {
|
||||||
it.each(['userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); });
|
jest.restoreAllMocks(); jest.clearAllMocks();
|
||||||
|
process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test';
|
||||||
|
jest.spyOn(global,'fetch').mockImplementation(async (url, opts) => {
|
||||||
|
const message=JSON.parse(opts!.body as string).message;
|
||||||
|
const intent=message==='کیف پول'?'wallet':message==='سفارش من'||message==='سفارش'?'orders':message.includes('شماره تماس')?'profile':'public';
|
||||||
|
return {ok:true,status:200,json:async()=>String(url).endsWith('/classify')?{intent}:{answer:'راهنمای محصولات کنینا'}} as any;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it.each(['scope','userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); });
|
||||||
it.each(['Bearer broken','Basic abc','', 'Bearer '])('rejects supplied invalid auth %j', async auth => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization',auth).send({message:'سلام'}).expect(401); });
|
it.each(['Bearer broken','Basic abc','', 'Bearer '])('rejects supplied invalid auth %j', async auth => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization',auth).send({message:'سلام'}).expect(401); });
|
||||||
it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول',scope:'wallet'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; });
|
it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; });
|
||||||
it('rejects expired JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'}, {expiresIn:-1})).send({message:'سلام'}).expect(401); });
|
it('rejects expired JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'}, {expiresIn:-1})).send({message:'سلام'}).expect(401); });
|
||||||
it('rejects cookie JWT rather than downgrading to guest', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Cookie','accessToken=broken').send({message:'سلام'}).expect(401); });
|
it('rejects cookie JWT rather than downgrading to guest', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Cookie','accessToken=broken').send({message:'سلام'}).expect(401); });
|
||||||
it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من',scope:'orders'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||||
|
it('returns only the authenticated user profile contact data', async () => {
|
||||||
|
const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'شماره تماس و ایمیل ثبتشده من چیست؟'}).expect(201);
|
||||||
|
expect(r.body.answer).toContain('alice-mobile'); expect(r.body.answer).toContain('alice@example.test');
|
||||||
|
expect(prisma.user.findUnique).toHaveBeenCalledWith(expect.objectContaining({where:{id:'alice'}}));
|
||||||
|
});
|
||||||
it('scopes wallet to validated identity across concurrent callers', async () => {
|
it('scopes wallet to validated identity across concurrent callers', async () => {
|
||||||
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول',scope:'wallet'}).expect(201)));
|
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201)));
|
||||||
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled();
|
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش',scope:'orders'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
||||||
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
||||||
it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام',scope:'public'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||||
it.each([{error:'upstream-secret'}, {answer:'Provider authentication failed Hermes'}, {answer:''}])('filters malformed and default upstream failures', async body => { process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; const f=jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); expect(JSON.stringify(r.body)).not.toContain('upstream-secret'); f.mockRestore(); });
|
it.each([{error:'upstream-secret'}, {answer:'Provider authentication failed Hermes'}, {answer:''}])('filters malformed and default upstream failures', async body => { process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; const f=jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); expect(JSON.stringify(r.body)).not.toContain('upstream-secret'); f.mockRestore(); });
|
||||||
it('returns safe unavailable on network errors', async () => { const f=jest.spyOn(global,'fetch').mockRejectedValue(new Error('private-secret')); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); f.mockRestore(); });
|
it('returns safe unavailable on network errors', async () => { const f=jest.spyOn(global,'fetch').mockRejectedValue(new Error('private-secret')); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); f.mockRestore(); });
|
||||||
});
|
});
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||||
|
import { SupportChatSettingsController } from './support-chat-settings.controller';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
import { PrismaModule } from '../prisma/prisma.module';
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
import { SupportChatController } from './support-chat.controller';
|
import { SupportChatController } from './support-chat.controller';
|
||||||
import { SupportChatService } from './support-chat.service';
|
import { SupportChatService } from './support-chat.service';
|
||||||
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
||||||
@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard] })
|
@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatSettingsController, SupportChatController], providers: [SupportChatService, SupportChatSettingsService, OptionalCustomerJwtGuard] })
|
||||||
export class SupportChatModule {}
|
export class SupportChatModule {}
|
||||||
@@ -1,13 +1,36 @@
|
|||||||
import { SupportChatService, UNAVAILABLE } from './support-chat.service';
|
import { SupportChatService, UNAVAILABLE } from './support-chat.service';
|
||||||
|
|
||||||
describe('SupportChatService', () => {
|
describe('model intent routing', () => {
|
||||||
const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockResolvedValue([]) }, user: { findUnique: jest.fn().mockResolvedValue({ walletBalance: '17' }) } };
|
const prisma: any = { supportConversation: { create: jest.fn().mockResolvedValue({id:'11111111-1111-4111-8111-111111111111',userId:null,messages:[]}), findUnique: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}) }, supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, pet:{findMany:jest.fn().mockResolvedValue([])}, product:{findMany:jest.fn().mockResolvedValue([])}, order:{findMany:jest.fn().mockResolvedValue([])}, user:{findUnique:jest.fn().mockResolvedValue({walletBalance:'17', mobile:'0912', email:'a@example.test', firstName:'A', lastName:'B'})} };
|
||||||
let service: SupportChatService;
|
let service: SupportChatService;
|
||||||
beforeEach(() => { jest.clearAllMocks(); service = new SupportChatService(prisma); });
|
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
|
||||||
it('does not load private rows for a guest asking about wallet', async () => {
|
afterEach(()=>jest.restoreAllMocks());
|
||||||
const result = await service.ask({ message: 'موجودی کیف پول من', scope: 'wallet' });
|
function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); }
|
||||||
expect(result.answer).toContain('وارد');
|
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
|
||||||
expect(prisma.user.findUnique).not.toHaveBeenCalled();
|
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};});
|
||||||
expect(prisma.order.findMany).not.toHaveBeenCalled();
|
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
|
||||||
|
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
||||||
|
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
describe('persistent conversations', () => {
|
||||||
|
it('creates a conversation and stores both messages without blocking the answer', async () => {
|
||||||
|
const conversation = { id: '11111111-1111-4111-8111-111111111111', userId: null };
|
||||||
|
const prisma: any = {
|
||||||
|
product: { findMany: jest.fn().mockResolvedValue([]) },
|
||||||
|
supportConversation: { create: jest.fn().mockResolvedValue(conversation), update: jest.fn().mockResolvedValue(conversation), findUnique: jest.fn().mockResolvedValue(conversation) },
|
||||||
|
supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) },
|
||||||
|
};
|
||||||
|
process.env.SUPPORT_CHAT_URL = 'http://internal/ask';
|
||||||
|
process.env.SUPPORT_CHAT_KEY = 'test';
|
||||||
|
jest.spyOn(global, 'fetch').mockImplementation(async (url, opts: any) => ({
|
||||||
|
ok: true, status: 200, json: async () => String(url).endsWith('/classify') ? { intent: 'public' } : { answer: 'پاسخ' },
|
||||||
|
}) as any);
|
||||||
|
const service = new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);
|
||||||
|
const result = await service.ask({ message: 'سلام', entryPath: '/products' } as any);
|
||||||
|
expect(result).toMatchObject({ conversationId: conversation.id, answer: 'پاسخ' });
|
||||||
|
expect(prisma.supportConversation.create).toHaveBeenCalled();
|
||||||
|
expect(prisma.supportConversationMessage.createMany).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,34 +1,95 @@
|
|||||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
import { Injectable, NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { SupportChatDto } from './support-chat.dto';
|
import { SupportChatDto } from './support-chat.dto';
|
||||||
|
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||||
|
|
||||||
export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
||||||
|
const MAX_HISTORY = 20;
|
||||||
|
const safePath = (v?: string) => v?.split('?')[0].slice(0, 512);
|
||||||
|
const safeBrowserId = (v?: string) => v && /^[A-Za-z0-9_-]{1,64}$/.test(v) ? v : undefined;
|
||||||
|
const resolvePageContext = async (db: any, entryPath?: string) => {
|
||||||
|
const path = safePath(entryPath);
|
||||||
|
if (!path || !path.startsWith('/') || path.includes('..') || /[?#]/.test(path)) return { type: 'unknown', path: path || '/' };
|
||||||
|
const match = path.match(/^\/(shop|blog|wiki)\/([A-Za-z0-9_-]+)$/);
|
||||||
|
if (!match) return { type: path === '/contact' ? 'contact' : 'other', path };
|
||||||
|
const [type, slug] = match.slice(1);
|
||||||
|
if (type === 'shop') {
|
||||||
|
const row = await db.product.findFirst({ where: { slug }, select: { slug: true, nameFa: true, shortDescription: true, description: true } });
|
||||||
|
return row ? { type: 'product', slug: row.slug, title: row.nameFa, contentExcerpt: String(row.shortDescription || row.description || '').slice(0, 1200), path } : { type: 'product', slug, path };
|
||||||
|
}
|
||||||
|
if (type === 'blog') {
|
||||||
|
const row = await db.blog.findFirst({ where: { slug, status: 'PUBLISHED' }, select: { slug: true, title: true, excerpt: true, content: true } });
|
||||||
|
return row ? { type: 'blog', slug: row.slug, title: row.title, contentExcerpt: String(row.excerpt || row.content || '').replace(/<[^>]*>/g, '').slice(0, 1200), path } : { type: 'blog', slug, path };
|
||||||
|
}
|
||||||
|
const row = await db.wiki.findFirst({ where: { key: slug }, select: { key: true, term: true, description: true } });
|
||||||
|
return row ? { type: 'wiki', slug: row.key, title: row.term, contentExcerpt: String(row.description || '').slice(0, 1200), path } : { type: 'wiki', slug, path };
|
||||||
|
};
|
||||||
|
|
||||||
|
const extract = (question: string, answer: string, products: any[]) => {
|
||||||
|
const q = question.toLowerCase();
|
||||||
|
const topics = ['nutrition','supplement','health','order','wallet','product','shipping'].filter(x => q.includes(x));
|
||||||
|
if (/تغذ|غذا|مکمل|ویتامین/.test(q)) topics.push('nutrition');
|
||||||
|
if (/سلامت|بیمار|دامپزشک/.test(q)) topics.push('health');
|
||||||
|
if (/سفارش|ارسال/.test(q)) topics.push('order');
|
||||||
|
const productSlugs = (products || []).filter(p => p.slug && (q.includes(String(p.slug).toLowerCase()) || q.includes(String(p.nameFa || '').toLowerCase()))).map(p => p.slug).slice(0, 20);
|
||||||
|
const uniqueTopics = [...new Set(topics)].slice(0, 20);
|
||||||
|
const unanswered = /نمی.?دانم|اطلاعاتی ندارم|پاسخ ندارم|متوجه نشدم/i.test(answer);
|
||||||
|
const needsFollowup = unanswered || /دامپزشک|پشتیبانی|تیکت|پیگیری/i.test(answer);
|
||||||
|
const escalationSignal = /فوری|شکایت|مشکل جدی|خطر|اورژانس/i.test(question + ' ' + answer);
|
||||||
|
const summary = `موضوع: ${uniqueTopics.join(', ') || 'عمومی'}؛ محصولات: ${productSlugs.join(', ') || 'ندارد'}؛ نیاز به پیگیری: ${needsFollowup ? 'بله' : 'خیر'}`;
|
||||||
|
return { productSlugs, topics: uniqueTopics, unanswered, needsFollowup, escalationSignal, summary };
|
||||||
|
};
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SupportChatService {
|
export class SupportChatService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {}
|
||||||
|
private db() { return this.prisma as any; }
|
||||||
|
async history(id: string, user?: { id: string }) {
|
||||||
|
const row = await this.db().supportConversation.findUnique({ where: { id }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } });
|
||||||
|
if (!row || (user?.id ? row.userId !== user.id : row.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.');
|
||||||
|
return { conversationId: id, messages: row.messages.map((m: any) => ({ role: m.role, content: m.content, createdAt: m.createdAt })) };
|
||||||
|
}
|
||||||
async ask(input: SupportChatDto, user?: { id: string }) {
|
async ask(input: SupportChatDto, user?: { id: string }) {
|
||||||
if (input.scope !== 'public' && !user) return { answer: 'برای مشاهده سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' };
|
const config = await this.settings.read(); if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE);
|
||||||
if (input.scope === 'wallet') {
|
const db = this.db(); let conversation: any;
|
||||||
const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } });
|
if (input.conversationId) {
|
||||||
if (!row) throw new ServiceUnavailableException(UNAVAILABLE);
|
conversation = await db.supportConversation.findUnique({ where: { id: input.conversationId }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } });
|
||||||
return { answer: `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.` };
|
if (!conversation || (user?.id ? conversation.userId !== user.id : conversation.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.');
|
||||||
|
} else {
|
||||||
|
conversation = await db.supportConversation.create({ data: { id: randomUUID(), userId: user?.id ?? null, anonymousBrowserId: safeBrowserId(input.anonymousBrowserId), entryPath: safePath(input.entryPath), expiresAt: new Date(Date.now() + 90 * 86400000) }, include: { messages: true } });
|
||||||
}
|
}
|
||||||
if (input.scope === 'orders') {
|
const conversationHistory = (conversation.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content }));
|
||||||
const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true, createdAt: true }, take: 5, orderBy: { createdAt: 'desc' } });
|
const selection = { provider: config.provider, model: config.model };
|
||||||
return { answer: rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.' };
|
const pageContext = await resolvePageContext(db, input.entryPath); const url = process.env.SUPPORT_CHAT_URL; const key = process.env.SUPPORT_CHAT_KEY;
|
||||||
}
|
const pets = user && db.pet?.findMany ? await db.pet.findMany({ where: { userId: user.id }, select: { id: true, name: true, type: true, breed: true, age: true, weight: true, activityLevel: true, medicalConditions: { select: { condition: true } } }, take: 20, orderBy: { createdAt: 'asc' } }) : [];
|
||||||
// Private account rows never leave the backend, even when the model is compromised.
|
const petContext = pets.map((pet: any) => ({ ...pet, medicalConditions: pet.medicalConditions.map((item: any) => item.condition) }));
|
||||||
|
let intent: 'public' | 'orders' | 'wallet' | 'profile';
|
||||||
try {
|
try {
|
||||||
const products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } });
|
if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled');
|
||||||
const url = process.env.SUPPORT_CHAT_URL;
|
const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, conversation_history: conversationHistory, pet_context: petContext, selection }) });
|
||||||
const key = process.env.SUPPORT_CHAT_KEY;
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.' };
|
||||||
if (!url || !key) throw new Error('disabled');
|
if (!response.ok) throw new Error('upstream'); const data = await response.json();
|
||||||
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products }) });
|
if (!data || Object.keys(data).length !== 1 || !['public','orders','wallet','profile'].includes(data.intent)) throw new Error('intent'); intent = data.intent;
|
||||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمیشود.' };
|
|
||||||
if (!response.ok) throw new Error('upstream');
|
|
||||||
const data = await response.json();
|
|
||||||
if (typeof data.answer !== 'string' || !data.answer.trim() || data.answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(data.answer)) throw new Error('unsafe');
|
|
||||||
return { answer: data.answer };
|
|
||||||
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
||||||
|
if (intent !== 'public' && !user) return { answer: 'برای مشاهده اطلاعات حساب، سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.', conversationId: conversation.id, contextLimited: conversationHistory.length >= MAX_HISTORY };
|
||||||
|
let answer: string; let products: any[] = [];
|
||||||
|
try {
|
||||||
|
if (intent === 'wallet') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); if (!row) throw new Error('missing'); answer = `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.`; } else if (intent === 'profile') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { firstName: true, lastName: true, mobile: true, email: true } }); if (!row) throw new Error('missing'); answer = `اطلاعات تماس ثبتشده برای حساب شما:
|
||||||
|
شماره موبایل: ${row.mobile || 'ثبت نشده'}
|
||||||
|
ایمیل: ${row.email || 'ثبت نشده'}.`; }
|
||||||
|
else if (intent === 'orders') { const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true }, take: 5, orderBy: { createdAt: 'desc' } }); answer = rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.'; }
|
||||||
|
else {
|
||||||
|
products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } });
|
||||||
|
const response = await fetch(url!, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products, conversation_history: conversationHistory, page_context: pageContext, pet_context: petContext, selection }) });
|
||||||
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.', conversationId: conversation.id };
|
||||||
|
if (!response.ok) throw new Error('upstream'); const data = await response.json(); answer = data.answer;
|
||||||
|
if (typeof answer !== 'string' || !answer.trim() || answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(answer)) throw new Error('unsafe');
|
||||||
|
}
|
||||||
|
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
||||||
|
const analytics = extract(input.message + ' ' + JSON.stringify(pageContext), answer!, products);
|
||||||
|
analytics.summary = `${analytics.summary}; صفحه: ${pageContext.type} ${pageContext.slug || pageContext.path || ''}`.slice(0, 1000);
|
||||||
|
await db.supportConversationMessage.createMany({ data: [{ conversationId: conversation.id, role: 'user', content: input.message, sequence: conversationHistory.length }, { conversationId: conversation.id, role: 'assistant', content: answer!, sequence: conversationHistory.length + 1 }] });
|
||||||
|
await db.supportConversation.update({ where: { id: conversation.id }, data: { productSlugs: analytics.productSlugs, topics: analytics.topics, unanswered: analytics.unanswered, needsFollowup: analytics.needsFollowup, escalationSignal: analytics.escalationSignal, summary: analytics.summary, summaryStatus: 'completed' } });
|
||||||
|
return { answer: answer!, conversationId: conversation.id, contextLimited: conversationHistory.length + 2 >= MAX_HISTORY };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "..",
|
||||||
|
"testRegex": "test/torob.integration.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { TorobController } from '../src/products/torob.controller';
|
||||||
|
import { PrismaService } from '../src/prisma/prisma.service';
|
||||||
|
|
||||||
|
// Dedicated disposable DB only. Never initializes PrismaService's DDL hooks.
|
||||||
|
describe('Torob real PostgreSQL regression', () => {
|
||||||
|
let db: PrismaClient;
|
||||||
|
let controller: TorobController;
|
||||||
|
const originalUrl = process.env.FRONTEND_URL;
|
||||||
|
beforeAll(async () => {
|
||||||
|
const url = new URL(process.env.DATABASE_URL || '');
|
||||||
|
if (url.hostname !== 'torob-test-db' || url.pathname !== '/torob_test') {
|
||||||
|
throw new Error('Refusing any DB other than disposable torob-test-db/torob_test');
|
||||||
|
}
|
||||||
|
process.env.FRONTEND_URL = 'https://stage.canina.ir';
|
||||||
|
db = new PrismaClient();
|
||||||
|
await db.$connect();
|
||||||
|
const category = await db.category.create({data: {name: 'Fixture', slug: 'fixture'}});
|
||||||
|
const common = {categoryId: category.id, categorySlug: category.slug, nameFa: 'آزمون', nameEn: 'Fixture', description: 'test fixture', priceValue: '123456.78', priceDisplay: 'fixture', unit: 'g', packageSize: 10, suitableFor: 'DOG', imageUrl: '/uploads/fixture.png'};
|
||||||
|
await db.product.createMany({data: [
|
||||||
|
{...common, artNo: 'T1', slug: 'fixture-in', stock: 3, stockStatus: 'IN_STOCK'},
|
||||||
|
{...common, artNo: 'T2', slug: 'fixture-zero', stock: 0, stockStatus: 'IN_STOCK'},
|
||||||
|
{...common, artNo: 'T3', slug: 'fixture-out', stock: 3, stockStatus: 'OUT_OF_STOCK'},
|
||||||
|
{...common, artNo: 'T4', slug: 'fixture-hidden', noIndex: true},
|
||||||
|
{...common, artNo: 'T5', slug: 'fixture-discontinued', stockStatus: 'DISCONTINUED'},
|
||||||
|
]});
|
||||||
|
controller = new TorobController(db as PrismaService);
|
||||||
|
});
|
||||||
|
afterAll(async () => {
|
||||||
|
if (db) await db.$disconnect();
|
||||||
|
if (originalUrl === undefined) delete process.env.FRONTEND_URL;
|
||||||
|
else process.env.FRONTEND_URL = originalUrl;
|
||||||
|
});
|
||||||
|
it('filters hidden/discontinued rows and preserves DB decimal price, stock and URLs', async () => {
|
||||||
|
const result = await controller.getTorobProducts();
|
||||||
|
expect(result.count).toBe(3);
|
||||||
|
expect(result.results.map(p => p.product_id).sort()).toEqual(['T1', 'T2', 'T3']);
|
||||||
|
for (const item of result.results) {
|
||||||
|
const row = await db.product.findUniqueOrThrow({where: {artNo: item.product_id}});
|
||||||
|
expect(item.price).toBe(Number(row.priceValue));
|
||||||
|
expect(item.old_price).toBe(Number(row.priceValue));
|
||||||
|
expect(item.availability).toBe(row.artNo === 'T1' ? 'instock' : 'outofstock');
|
||||||
|
expect(item.page_url).toBe(`https://stage.canina.ir/shop/${row.slug}`);
|
||||||
|
expect(item.image_link).toBe('https://stage.canina.ir/api/uploads/fixture.png');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Canina UX Modernization — Task Register
|
||||||
|
|
||||||
|
Source: live Chromium audits, source audit at `bec76393b`, and QA/SEO/content reviews.
|
||||||
|
Status model: TODO -> IN_PROGRESS -> TEST -> DONE. Estimates are engineering hours, not elapsed calendar time.
|
||||||
|
|
||||||
|
| ID | Owner departments | Pri | Estimate | Dependencies | Acceptance summary | Status |
|
||||||
|
|---|---|---:|---:|---|---|---|
|
||||||
|
| UX-PMO-001 | PMO | P0 | 4h | audits | Register, owners, dependencies, release gates and evidence contract are versioned | DONE |
|
||||||
|
| UX-DEV-001 | Dev + QA | P0 | 12h | none | `/login` and `/cart` are real routes, no 404, mobile/desktop smoke tests pass | IN_PROGRESS |
|
||||||
|
| UX-CAT-001 | Dev + UX + QA | P0 | 24h | UX-DEV-001 | Shop has deterministic SSR/client data states: success/loading/empty/error/retry | TODO |
|
||||||
|
| UX-CAT-002 | Dev + Product + QA | P0 | 24h | UX-CAT-001 | Catalog uses typed pagination/query URL state; no limit-999 hydration | TODO |
|
||||||
|
| UX-DATA-001 | Dev + DevOps | P0 | 20h | UX-CAT-001 | API errors are typed/actionable; cache tags and invalidation are verified | TODO |
|
||||||
|
| UX-A11Y-001 | UX + Dev + QA | P0 | 16h | UX-DEV-001 | Forms/buttons/overlays have names, labels, focus return and keyboard operation | TODO |
|
||||||
|
| UX-RESP-001 | UX + Dev + QA | P1 | 20h | UX-CAT-001 | 360/390/768/1024/1440 layouts have no unintended overflow and 44px targets | TODO |
|
||||||
|
| UX-PDP-001 | Product + UX + Dev + QA | P1 | 20h | UX-CAT-001 | PDP has one H1 and above-fold image/name/price/stock/CTA at all viewports | TODO |
|
||||||
|
| UX-CHECKOUT-001 | Payments + Dev + QA | P1 | 20h | UX-A11Y-001 | Checkout fields have labels/autocomplete/inputmode and announced errors | TODO |
|
||||||
|
| UX-NAV-001 | UX + Product + Dev | P1 | 16h | UX-RESP-001 | Mobile/desktop navigation is canonical, active state and cart state are consistent | TODO |
|
||||||
|
| UX-SEARCH-001 | Product + UX + SEO + Dev | P1 | 16h | UX-CAT-002 | Search landmark, Persian normalization, result count and actionable no-results state | TODO |
|
||||||
|
| UX-CONTENT-001 | Content + UX | P1 | 12h | UX-NAV-001 | Persian CTA/glossary unified across shop, wiki, auth, cart and footer | TODO |
|
||||||
|
| UX-CONTACT-001 | Support + Dev + Product | P1 | 4h | settings readback | No empty `tel:`/`mailto:` targets; official values verified live | TODO |
|
||||||
|
| UX-SEO-001 | SEO + Dev + QA | P1 | 16h | UX-CAT-002 | Category URLs, canonical/H1/meta and sitemap parity are tested | TODO |
|
||||||
|
| UX-SEO-002 | SEO + Dev + Content | P1 | 12h | UX-SEO-001 | Product 404 is real 404; Product/Offer/Breadcrumb JSON-LD matches facts | TODO |
|
||||||
|
| UX-MEDIA-001 | Content + SEO + Dev | P2 | 12h | UX-PDP-001 | Product/blog/feed images are valid, same-item, HTTPS and have useful alt text | TODO |
|
||||||
|
| UX-PERF-001 | Dev + DevOps + QA | P0 | 24h | UX-CAT-002, UX-RESP-001 | Mobile LCP/CLS/INP budgets, reduced-motion and image dimensions are verified | TODO |
|
||||||
|
| UX-ARCH-001 | Dev + UX | P1 | 24h | UX-CAT-001 | ArchivePage/global shell split into typed, independently testable feature modules | TODO |
|
||||||
|
| UX-STATE-001 | Dev + Commerce + QA | P0 | 24h | UX-DATA-001 | Cart price/stock/order state is backend-authoritative and persisted safely | TODO |
|
||||||
|
| UX-TEST-001 | Dev + QA | P0 | 16h | UX-DEV-001 | npm test/typecheck/lint scripts and coverage gates execute in clean checkout | TODO |
|
||||||
|
| UX-E2E-001 | QA + DevOps | P1 | 20h | UX-TEST-001, UX-RESP-001 | Chromium desktop/mobile smoke covers shop/PDP/cart/login/checkout/errors | TODO |
|
||||||
|
| UX-CI-001 | DevOps + Dev + QA | P0 | 20h | UX-TEST-001, UX-E2E-001 | CI gates lint/type/unit/build/E2E/perf and publishes evidence | TODO |
|
||||||
|
| UX-DEPLOY-001 | DevOps + QA | P1 | 24h | UX-CI-001 | Immutable SHA deployment, health checks, smoke gate and rollback are documented/tested | TODO |
|
||||||
|
| UX-CLAIMS-001 | R&D + Content + Compliance + human vet review | P1 | 32h | legal/vet access | 35 product/media medical claims have evidence/status and no unsupported claims publish | BLOCKED_EXTERNAL_REVIEW |
|
||||||
|
| UX-VERIFY-001 | PMO + QA + Analytics | P2 | 16h | all release tasks | Live release checklist, CWV/error/catalog/checkout telemetry and go/no-go evidence | TODO |
|
||||||
|
|
||||||
|
**Current program estimate:** 396 engineering/review hours; critical path is lower with parallel teams. External legal/human-veterinarian review, recruited user panel, GSC/GA4 access and payment sandbox are explicit blockers where applicable.
|
||||||
|
|
||||||
|
## Immediate execution order
|
||||||
|
|
||||||
|
1. UX-DEV-001 — restore login/cart routes (current)
|
||||||
|
2. UX-TEST-001 — make frontend test/typecheck gates executable
|
||||||
|
3. UX-A11Y-001 + UX-RESP-001 — fix shared interaction and responsive foundations
|
||||||
|
4. UX-CAT-001/002 + UX-DATA-001 — reliable catalog flow
|
||||||
|
5. UX-PDP-001 + UX-CHECKOUT-001 + UX-STATE-001 — conversion journey
|
||||||
|
6. SEO/content/media/performance/CI/deployment gates
|
||||||
|
7. Live verification and release decision
|
||||||
@@ -7,7 +7,10 @@
|
|||||||
"dev": "vite --port 3400 --host 127.0.0.1",
|
"dev": "vite --port 3400 --host 127.0.0.1",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "^5.101.0",
|
"@tanstack/react-query": "^5.101.0",
|
||||||
|
|||||||
@@ -109,6 +109,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
|||||||
items: [
|
items: [
|
||||||
{ icon: LayoutDashboard, label: 'نمای کلی داشبورد', path: '/' },
|
{ icon: LayoutDashboard, label: 'نمای کلی داشبورد', path: '/' },
|
||||||
{ icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' },
|
{ icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' },
|
||||||
|
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -156,6 +157,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
|||||||
{ icon: Package, label: 'لیست محصولات', path: '/products' },
|
{ icon: Package, label: 'لیست محصولات', path: '/products' },
|
||||||
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
|
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
|
||||||
{ icon: FolderTree, label: 'دستهبندیهای تخصصی', path: '/categories' },
|
{ icon: FolderTree, label: 'دستهبندیهای تخصصی', path: '/categories' },
|
||||||
|
{ icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' },
|
||||||
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
||||||
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
|
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
|
||||||
{ icon: FileText, label: 'نسخههای دریافتی', path: '/prescriptions' },
|
{ icon: FileText, label: 'نسخههای دریافتی', path: '/prescriptions' },
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
|
||||||
|
import Button from '../ui/Button';
|
||||||
|
|
||||||
|
interface ProductFaqTabProps {
|
||||||
|
activeTab: string;
|
||||||
|
formData: any;
|
||||||
|
setFormData: React.Dispatch<React.SetStateAction<any>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
|
||||||
|
activeTab,
|
||||||
|
formData,
|
||||||
|
setFormData,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
|
||||||
|
{/* Top FAQ Controls */}
|
||||||
|
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
|
||||||
|
<HelpCircle className="w-4 h-4 text-purple-600" />
|
||||||
|
<span>بخش پرسش و پاسخهای متداول محصول (Product FAQs)</span>
|
||||||
|
</h4>
|
||||||
|
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسشهای متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<label className="relative inline-flex items-center cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="sr-only peer"
|
||||||
|
checked={formData.showFaqs}
|
||||||
|
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
|
||||||
|
/>
|
||||||
|
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
|
||||||
|
</label>
|
||||||
|
<span className="text-xs font-bold text-gray-700">
|
||||||
|
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
startIcon={Plus}
|
||||||
|
onClick={() => {
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
|
||||||
|
>
|
||||||
|
افزودن سوال جدید
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
const defaultFaqs = [
|
||||||
|
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای تولهها یا بچهگربهها مجاز است؟`, answer: 'بله، مطابق دوز اعلامشده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
|
||||||
|
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دورههای درمانی بین ۴ الی ۶ هفته توصیه میشود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
|
||||||
|
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیمهای غذایی خشک و مرطوب استاندارد هستند.' }
|
||||||
|
];
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
faqs: [...(formData.faqs || []), ...defaultFaqs]
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
|
||||||
|
>
|
||||||
|
+ درج سوالات پیشنهادی هوشمند
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* FAQs List */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
{(!formData.faqs || formData.faqs.length === 0) ? (
|
||||||
|
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
|
||||||
|
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
|
||||||
|
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
|
||||||
|
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداولترین پرسشهای خریداران را ثبت کنید.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
formData.faqs.map((faq: any, index: number) => (
|
||||||
|
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
|
||||||
|
<div className="flex items-center justify-between gap-3 border-b pb-2">
|
||||||
|
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
|
||||||
|
پرسش شماره {index + 1}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
const newFaqs = [...formData.faqs];
|
||||||
|
newFaqs.splice(index, 1);
|
||||||
|
setFormData({ ...formData, faqs: newFaqs });
|
||||||
|
}}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||||
|
title="حذف این پرسش"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={faq.question}
|
||||||
|
onChange={(e) => {
|
||||||
|
const newFaqs = [...formData.faqs];
|
||||||
|
newFaqs[index].question = e.target.value;
|
||||||
|
setFormData({ ...formData, faqs: newFaqs });
|
||||||
|
}}
|
||||||
|
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
|
||||||
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
|
||||||
|
dir="rtl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
value={faq.answer}
|
||||||
|
onChange={(e) => {
|
||||||
|
const newFaqs = [...formData.faqs];
|
||||||
|
newFaqs[index].answer = e.target.value;
|
||||||
|
setFormData({ ...formData, faqs: newFaqs });
|
||||||
|
}}
|
||||||
|
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
|
||||||
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
|
||||||
|
dir="rtl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -202,6 +202,23 @@ export default function MediaSelector({ isOpen, onClose, onSelect, multiple = fa
|
|||||||
const files = Array.from(e.dataTransfer.files);
|
const files = Array.from(e.dataTransfer.files);
|
||||||
if (files.length === 0) return;
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
|
||||||
|
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
|
||||||
|
|
||||||
|
const validFiles = files.filter(f => {
|
||||||
|
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
|
||||||
|
toast.error(`فرمت فایل ${f.name} مجاز نمیباشد.`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (f.size > MAX_FILE_SIZE) {
|
||||||
|
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (validFiles.length === 0) return;
|
||||||
|
|
||||||
setIsUploading(true);
|
setIsUploading(true);
|
||||||
let successCount = 0;
|
let successCount = 0;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -43,11 +43,14 @@ describe('Dashboard Page Component', () => {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
vi.mocked(api.get).mockResolvedValue({
|
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||||
data: {
|
if (url.includes('/admin/audit-logs')) {
|
||||||
success: true,
|
return Promise.resolve({ data: { success: true, data: [] } } as any);
|
||||||
data: mockStats,
|
}
|
||||||
},
|
if (url.includes('/admin/approvals')) {
|
||||||
|
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
|
||||||
|
}
|
||||||
|
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -62,8 +65,8 @@ describe('Dashboard Page Component', () => {
|
|||||||
it('renders dashboard headers and initial zero or placeholder stats', async () => {
|
it('renders dashboard headers and initial zero or placeholder stats', async () => {
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
|
|
||||||
expect(screen.getByText('داشبورد')).toBeInTheDocument();
|
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument();
|
||||||
expect(screen.getByText('خلاصهای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
|
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument();
|
||||||
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
|
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
|
||||||
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
|
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
|
||||||
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
|
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
|
||||||
@@ -123,7 +126,12 @@ describe('Dashboard Page Component', () => {
|
|||||||
|
|
||||||
it('falls back gracefully when API returns error', async () => {
|
it('falls back gracefully when API returns error', async () => {
|
||||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
|
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||||
|
if (url.includes('/admin/dashboard/stats')) {
|
||||||
|
return Promise.reject(new Error('Network error'));
|
||||||
|
}
|
||||||
|
return Promise.resolve({ data: { success: true, data: [] } } as any);
|
||||||
|
});
|
||||||
|
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
|
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export default function Dashboard() {
|
|||||||
try {
|
try {
|
||||||
const res = await api.get('/admin/audit-logs?limit=5');
|
const res = await api.get('/admin/audit-logs?limit=5');
|
||||||
if (res.data?.success) {
|
if (res.data?.success) {
|
||||||
setRecentLogs(res.data.data);
|
setRecentLogs(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : []));
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to fetch audit logs widget', e);
|
console.error('Failed to fetch audit logs widget', e);
|
||||||
@@ -217,7 +217,7 @@ export default function Dashboard() {
|
|||||||
رکوردی در تاریخچه ثبت نشده است.
|
رکوردی در تاریخچه ثبت نشده است.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
recentLogs.map((log) => (
|
(Array.isArray(recentLogs) ? recentLogs : []).map((log) => (
|
||||||
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
|
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
|
||||||
<div className="flex items-center gap-2.5 overflow-hidden">
|
<div className="flex items-center gap-2.5 overflow-hidden">
|
||||||
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
|
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export default function MonitoringPage() {
|
|||||||
timestamp: new Date().toLocaleTimeString('fa-IR'),
|
timestamp: new Date().toLocaleTimeString('fa-IR'),
|
||||||
zibal: {
|
zibal: {
|
||||||
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
|
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
|
||||||
latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120,
|
latencyMs: health?.latencyMs ?? 0,
|
||||||
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
|
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
|
||||||
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
|
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
|
||||||
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
|
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
|
||||||
@@ -89,14 +89,14 @@ export default function MonitoringPage() {
|
|||||||
melipayamak: {
|
melipayamak: {
|
||||||
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
|
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
|
||||||
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
|
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
|
||||||
latencyMs: Math.floor(Math.random() * 60) + 95,
|
latencyMs: 0,
|
||||||
todaySmsSent: 48,
|
todaySmsSent: 48,
|
||||||
patternActive: true,
|
patternActive: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
post: {
|
post: {
|
||||||
status: 'ONLINE',
|
status: 'ONLINE',
|
||||||
latencyMs: Math.floor(Math.random() * 110) + 140,
|
latencyMs: 0,
|
||||||
trackingActive: true,
|
trackingActive: true,
|
||||||
},
|
},
|
||||||
system: {
|
system: {
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import api from '../services/api';
|
|||||||
|
|
||||||
|
|
||||||
export interface OrderItem {
|
export interface OrderItem {
|
||||||
|
requiresRx?: boolean;
|
||||||
id?: string;
|
id?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
priceValue?: number;
|
priceValue?: number;
|
||||||
@@ -758,6 +759,12 @@ export default function Orders() {
|
|||||||
سفارش جدید
|
سفارش جدید
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{(order.orderItems || order.items || []).some(it => it.product?.requiresRx) && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-600 text-white shadow-xs animate-pulse" title="نیازمند تماس تلفنی و تایید نسخه دامپزشک">
|
||||||
|
<span>Rx</span>
|
||||||
|
<span>هماهنگی نسخه</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl">
|
<div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl">
|
||||||
<span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}>
|
<span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}>
|
||||||
@@ -911,6 +918,24 @@ export default function Orders() {
|
|||||||
>
|
>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
{/* Rx Warning Notice for Admin */}
|
||||||
|
{(selectedOrder.orderItems || selectedOrder.items || []).some(it => it.requiresRx || it.product?.requiresRx) && (
|
||||||
|
<div className="bg-rose-50 border border-rose-200 rounded-2xl p-4 flex items-center justify-between gap-3 text-rose-900 font-vazir shadow-xs" dir="rtl">
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<span className="w-8 h-8 rounded-xl bg-rose-600 text-white flex items-center justify-center font-black text-xs shrink-0 shadow-sm">Rx</span>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-xs font-black">این سفارش شامل داروی نیازمند نسخه و نظارت دامپزشکی است</h4>
|
||||||
|
<p className="text-[11px] text-rose-700 font-medium mt-0.5">ارسال سفارش تنها پس از تماس تلفنی کارشناس پشتیبانی و تایید نسخه معتبر انجام شود.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href={`tel:${selectedOrder.user?.mobile || selectedOrder.user?.phone || ''}`}
|
||||||
|
className="bg-rose-600 hover:bg-rose-700 text-white px-3.5 py-2 rounded-xl text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 shrink-0"
|
||||||
|
>
|
||||||
|
<span>تماس با مشتری</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{/* Status & Timing Banner */}
|
{/* Status & Timing Banner */}
|
||||||
<div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100">
|
<div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { ProductFaqTab } from "../components/products/ProductFaqTab";
|
||||||
import {
|
import {
|
||||||
Activity,
|
Activity,
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
@@ -2317,152 +2318,12 @@ export default function Products() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* FAQ Tab */}
|
{/* FAQ Tab */}
|
||||||
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
|
{/* FAQ Tab */}
|
||||||
{/* Top FAQ Controls */}
|
<ProductFaqTab
|
||||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
|
activeTab={activeTab}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
|
formData={formData}
|
||||||
<div>
|
setFormData={setFormData}
|
||||||
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
|
/>
|
||||||
<HelpCircle className="w-4 h-4 text-purple-600" />
|
|
||||||
<span>بخش پرسش و پاسخهای متداول محصول (Product FAQs)</span>
|
|
||||||
</h4>
|
|
||||||
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسشهای متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
|
||||||
<label className="relative inline-flex items-center cursor-pointer">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
className="sr-only peer"
|
|
||||||
checked={formData.showFaqs}
|
|
||||||
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
|
|
||||||
/>
|
|
||||||
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
|
|
||||||
</label>
|
|
||||||
<span className="text-xs font-bold text-gray-700">
|
|
||||||
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
startIcon={Plus}
|
|
||||||
onClick={() => {
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
|
|
||||||
>
|
|
||||||
افزودن سوال جدید
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
const name = formData.nameFa || 'این محصول';
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
faqs: [
|
|
||||||
{
|
|
||||||
question: `آیا لیسیدن ${name} توسط حیوان خطرناک است؟`,
|
|
||||||
answer: `خیر، ترکیبات این محصول با استانداردهای دارویی آلمان فرموله شده و فاقد مواد نگهدارنده شیمیایی مضر است. لیسیدن محدود آن باعث مسمومیت نمیشود؛ اما جهت اثربخشی و جذب حداکثری، پیشنهاد میشود ۱۰ تا ۱۵ دقیقه حواس حیوان پرت شود.`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
question: `مدت زمان ماندگاری و شرایط نگهداری ${name} چگونه است؟`,
|
|
||||||
answer: `این محصول در جای خشک، خنک (دمای زیر ۲۵ درجه سانتیگراد) و دور از تابش مستقیم نور خورشید نگهداری شود. مدت زمان مجاز مصرف پس از باز شدن درب (PAO) ${formData.paoMonths ? `${formData.paoMonths} ماه` : '۱۲ ماه'} میباشد.`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
question: `آیا برای تولهها و حیوانات باردار یا شیرده قابل استفاده است؟`,
|
|
||||||
answer: `بله، با توجه به فرمولاسیون ۱۰۰٪ طبیعی و عدم وجود هورمون یا مواد شیمیایی سنتتیک، استفاده از این محصول برای تمامی ردههای سنی و دوران حساس بارداری و شیردهی طبق دستورالعمل ایمن است.`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
question: `در صورت استفاده همزمان با سایر داروها یا پمادها چه نکاتی باید رعایت شود؟`,
|
|
||||||
answer: `جهت جلوگیری از تداخل در جذب، توصیه میشود بین استفاده از این محصول و سایر داروها، اسپریها یا مکملهای درمانی حداقل ۲۰ الی ۳۰ دقیقه فاصله زمانی رعایت شود.`
|
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
|
||||||
toast.success('سوالات متداول استاندارد کاتالوگ بارگذاری شدند');
|
|
||||||
}}
|
|
||||||
className="text-xs text-purple-600 hover:text-purple-800 font-bold flex items-center gap-1 hover:underline"
|
|
||||||
>
|
|
||||||
درج سوالات متداول پیشنهادی کاتالوگ Canina ⚡
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* FAQ Items List */}
|
|
||||||
{formData.faqs && formData.faqs.length > 0 ? (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{formData.faqs.map((faq, idx) => (
|
|
||||||
<div key={idx} className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
|
|
||||||
<div className="flex items-center justify-between gap-2 border-b border-gray-100 pb-2">
|
|
||||||
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-full">
|
|
||||||
سوال {idx + 1}
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
const newFaqs = formData.faqs.filter((_, i) => i !== idx);
|
|
||||||
setFormData({ ...formData, faqs: newFaqs });
|
|
||||||
}}
|
|
||||||
className="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors"
|
|
||||||
title="حذف این سوال"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-xs font-bold text-gray-700">متن پرسش:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={faq.question}
|
|
||||||
onChange={(e) => {
|
|
||||||
const updated = [...formData.faqs];
|
|
||||||
updated[idx].question = e.target.value;
|
|
||||||
setFormData({ ...formData, faqs: updated });
|
|
||||||
}}
|
|
||||||
placeholder="مثال: آیا لیسیدن این محصول خطرناک است؟"
|
|
||||||
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold font-vazir"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<label className="text-xs font-bold text-gray-700">متن پاسخ علمی و کامل:</label>
|
|
||||||
<textarea
|
|
||||||
rows={3}
|
|
||||||
value={faq.answer}
|
|
||||||
onChange={(e) => {
|
|
||||||
const updated = [...formData.faqs];
|
|
||||||
updated[idx].answer = e.target.value;
|
|
||||||
setFormData({ ...formData, faqs: updated });
|
|
||||||
}}
|
|
||||||
placeholder="پاسخ کامل و علمی را وارد نمایید..."
|
|
||||||
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed font-vazir"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-300 text-center space-y-3">
|
|
||||||
<div className="w-12 h-12 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center mx-auto">
|
|
||||||
<HelpCircle className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<h5 className="text-sm font-black text-gray-800">هیچ پرسش و پاسخی ثبت نشده است</h5>
|
|
||||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
|
||||||
میتوانید با کلیک بر روی «درج سوالات متداول پیشنهادی»، پرسشهای متداول کاتالوگ دارویی را به صورت خودکار بارگذاری و سپس شخصیسازی نمایید.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Pricing Tab */}
|
{/* Pricing Tab */}
|
||||||
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
|
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
|
||||||
|
|||||||
@@ -114,6 +114,7 @@ export default function Settings() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const SETTING_MODULES = [
|
const SETTING_MODULES = [
|
||||||
|
{ title: 'پشتیبان هوشمند سایت', desc: 'فعالسازی، ارائهدهنده و مدل، نام دکمه و آیکون دستیار', path: '/settings/smart-chat', icon: MessageSquare, color: 'from-purple-600 to-purple-800', badge: 'هوشمند' },
|
||||||
{
|
{
|
||||||
title: 'روشهای پرداخت و زیبال',
|
title: 'روشهای پرداخت و زیبال',
|
||||||
desc: 'درگاه آنلاین شتاب، کیف پول کنینا، کارت به کارت و پرداخت در محل',
|
desc: 'درگاه آنلاین شتاب، کیف پول کنینا، کارت به کارت و پرداخت در محل',
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
import api from '../services/api';
|
||||||
|
import Button from '../components/ui/Button';
|
||||||
|
|
||||||
|
type Settings = { enabled: boolean; provider: string; model: string; label: string; icon: string };
|
||||||
|
type Provider = { id: string; label: string; models: string[] };
|
||||||
|
const unwrap = (r: any) => r.data?.data ?? r.data;
|
||||||
|
export default function SmartChatSettingsPage() {
|
||||||
|
const [settings, setSettings] = useState<Settings | null>(null);
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([]);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const load = async () => {
|
||||||
|
setError('');
|
||||||
|
const [s, c] = await Promise.allSettled([api.get('/support-chat/settings'), api.get('/support-chat/catalog')]);
|
||||||
|
if (s.status === 'fulfilled') setSettings(unwrap(s.value));
|
||||||
|
else setError('تنظیمات ذخیرهشده دریافت نشد. پشتیبان تا ثبت تنظیمات معتبر نمایش داده نمیشود.');
|
||||||
|
if (c.status === 'fulfilled') setProviders(unwrap(c.value).providers);
|
||||||
|
else { setProviders([]); setError('فهرست واقعی ارائهدهندگان در دسترس نیست. لطفاً دوباره تلاش کنید.'); }
|
||||||
|
};
|
||||||
|
useEffect(() => { void load(); }, []);
|
||||||
|
const save = async (event: React.FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!settings) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await api.put('/support-chat/settings', settings);
|
||||||
|
const saved = unwrap(await api.get('/support-chat/settings'));
|
||||||
|
setSettings(saved);
|
||||||
|
setError('');
|
||||||
|
toast.success('تنظیمات پشتیبان هوشمند ذخیره شد.');
|
||||||
|
} catch { toast.error('ذخیره تنظیمات انجام نشد؛ ارائهدهنده و مدل را بررسی کنید.'); }
|
||||||
|
finally { setSaving(false); }
|
||||||
|
};
|
||||||
|
const icons: Record<string, string> = { chat: '💬', paw: '🐾', bot: '🤖' };
|
||||||
|
return <div dir="rtl" className="space-y-6 font-vazir">
|
||||||
|
<Link to="/settings">← تنظیمات فروشگاه</Link>
|
||||||
|
<h2 className="text-2xl font-black">پشتیبان هوشمند سایت</h2>
|
||||||
|
<p>انتخاب مدل برای تشخیص درخواست و پاسخگویی یکسان است. اطلاعات حساب مشتری به مدل ارسال نمیشود.</p>
|
||||||
|
{error && <div role="alert" className="rounded-xl bg-amber-50 p-4">{error} <button type="button" onClick={load}>تلاش دوباره</button></div>}
|
||||||
|
{!settings ? <Button onClick={() => setSettings({ enabled: false, provider: '', model: '', label: '', icon: 'chat' })}>ایجاد تنظیمات جدید</Button> :
|
||||||
|
<form onSubmit={save} className="space-y-5 rounded-2xl bg-white p-6 border border-gray-200">
|
||||||
|
<label className="flex gap-2"><input type="checkbox" checked={settings.enabled} onChange={e => setSettings({ ...settings, enabled: e.target.checked })} />فعالسازی پشتیبان هوشمند</label>
|
||||||
|
<label className="block">ارائهدهنده<select aria-label="ارائهدهنده" className="block border rounded-xl p-3 w-full" value={settings.provider} onChange={e => setSettings({ ...settings, provider: e.target.value, model: '' })}>
|
||||||
|
<option value="">انتخاب ارائهدهنده</option>{providers.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
|
||||||
|
</select></label>
|
||||||
|
<label className="block">مدل<select aria-label="مدل" disabled={!settings.provider} className="block border rounded-xl p-3 w-full" value={settings.model} onChange={e => setSettings({ ...settings, model: e.target.value })}>
|
||||||
|
<option value="">انتخاب مدل</option>{providers.find(p => p.id === settings.provider)?.models.map(m => <option key={m} value={m}>{m}</option>)}
|
||||||
|
</select></label>
|
||||||
|
<label className="block">نام دکمه و دستیار<input aria-label="نام دکمه و دستیار" required maxLength={60} className="block border rounded-xl p-3 w-full" value={settings.label} onChange={e => setSettings({ ...settings, label: e.target.value })} /></label>
|
||||||
|
<label className="block">آیکون دستیار<select aria-label="آیکون دستیار" className="block border rounded-xl p-3 w-full" value={settings.icon} onChange={e => setSettings({ ...settings, icon: e.target.value })}><option value="chat">💬 گفتگو</option><option value="paw">🐾 پنجه</option><option value="bot">🤖 ربات</option></select></label>
|
||||||
|
<p className="text-sm text-gray-500">برای امنیت سایت فقط آیکونهای داخلی قابل انتخاب هستند؛ نشانی یا SVG دلخواه پذیرفته نمیشود.</p>
|
||||||
|
<div aria-label="پیشنمایش دکمه" className="inline-flex gap-2 rounded-full bg-[#1E4053] text-white px-4 py-3"><span>{icons[settings.icon]}</span><span>{settings.label}</span></div>
|
||||||
|
<div><Button type="submit" disabled={saving || (settings.enabled && (!settings.provider || !settings.model))}>{saving ? 'در حال ذخیره…' : 'ذخیره تنظیمات'}</Button></div>
|
||||||
|
</form>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import api from "../services/api";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
|
||||||
|
type Stats = { conversations: number; messages: number; authenticated: number; anonymous: number; unanswered: number; followup: number; escalated: number; topics: Record<string, number> };
|
||||||
|
type Conversation = { id: string; createdAt: string; updatedAt: string; entryPath?: string; unanswered: boolean; needsFollowup: boolean; escalationSignal: boolean; summary?: string; user?: { firstName?: string; lastName?: string; mobile?: string; email?: string } | null; messages: { role: string; content: string; createdAt: string }[] };
|
||||||
|
const unwrap = (r: any) => r.data?.data ?? r.data;
|
||||||
|
export default function SupportChatAnalyticsPage() {
|
||||||
|
const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" });
|
||||||
|
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); const statsData = unwrap(s);
|
||||||
|
const convData = unwrap(c);
|
||||||
|
setStats(statsData);
|
||||||
|
setRows(Array.isArray(convData) ? convData : (Array.isArray(convData?.data) ? convData.data : [])); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
|
||||||
|
useEffect(() => { void load(); }, []);
|
||||||
|
return <div dir="rtl" className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤالها، پاسخها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>بهروزرسانی</button></div>
|
||||||
|
<div className="flex gap-3"><label>از تاریخ<input type="date" className="block rounded border p-2" value={dates.startDate} onChange={e => setDates({ ...dates, startDate: e.target.value })} /></label><label>تا تاریخ<input type="date" className="block rounded border p-2" value={dates.endDate} onChange={e => setDates({ ...dates, endDate: e.target.value })} /></label><button className="self-end rounded border px-4 py-2" onClick={() => void load()}>اعمال</button></div>
|
||||||
|
{error && <div role="alert" className="rounded bg-red-50 p-3 text-red-700">{error}</div>}
|
||||||
|
{stats && <div className="grid grid-cols-2 gap-4 md:grid-cols-4">{[["گفتگو", stats.conversations],["پیام", stats.messages],["کاربر واردشده", stats.authenticated],["مهمان", stats.anonymous],["بیپاسخ", stats.unanswered],["نیازمند پیگیری", stats.followup],["هشدار", stats.escalated]].map(([label, value]) => <div key={String(label)} className="rounded-xl border bg-white p-4"><div className="text-sm text-gray-500">{label}</div><div className="mt-2 text-2xl font-black">{value}</div></div>)}</div>}
|
||||||
|
<div className="space-y-4">{rows.map(row => <article key={row.id} className="rounded-xl border bg-white p-4"><div className="flex justify-between gap-3"><div className="font-bold">{row.user ? `${row.user.firstName || ""} ${row.user.lastName || ""}`.trim() || "کاربر واردشده" : "مهمان"}</div><div className="text-xs text-gray-500">{new Date(row.updatedAt).toLocaleString("fa-IR")}</div></div><div className="mt-2 flex gap-2 text-xs">{row.unanswered && <span className="rounded bg-red-100 px-2 py-1">بیپاسخ</span>}{row.needsFollowup && <span className="rounded bg-amber-100 px-2 py-1">پیگیری</span>}{row.escalationSignal && <span className="rounded bg-red-100 px-2 py-1">هشدار</span>}</div><div className="mt-3 space-y-2">{row.messages.map((m, i) => <div key={`${row.id}-${i}`} className={m.role === "user" ? "rounded bg-blue-50 p-2" : "rounded bg-gray-50 p-2"}><b>{m.role === "user" ? "کاربر" : "پشتیبان"}:</b> {m.content}</div>)}</div></article>)}</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
import { Edit2, Plus, Search, Trash2, Activity, Tag, Sparkles } from 'lucide-react';
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
import Button from '../components/ui/Button';
|
||||||
|
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||||
|
import Modal from '../components/ui/Modal';
|
||||||
|
import Pagination from '../components/ui/Pagination';
|
||||||
|
import Spinner from '../components/ui/Spinner';
|
||||||
|
import api from '../services/api';
|
||||||
|
import { useSearchParams } from 'react-router-dom';
|
||||||
|
|
||||||
|
export interface Symptom {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
description?: string;
|
||||||
|
metaTitle?: string;
|
||||||
|
metaDescription?: string;
|
||||||
|
keywords?: string;
|
||||||
|
productsCount?: number;
|
||||||
|
createdAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SymptomsPage() {
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [search, setSearch] = useState(() => searchParams.get('search') || '');
|
||||||
|
const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1);
|
||||||
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
|
const limit = 15;
|
||||||
|
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
const [editingSymptom, setEditingSymptom] = useState<Symptom | null>(null);
|
||||||
|
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
name: '',
|
||||||
|
slug: '',
|
||||||
|
description: '',
|
||||||
|
metaTitle: '',
|
||||||
|
metaDescription: '',
|
||||||
|
keywords: ''
|
||||||
|
});
|
||||||
|
|
||||||
|
const openModal = (symptom: Symptom | null = null) => {
|
||||||
|
if (symptom) {
|
||||||
|
setEditingSymptom(symptom);
|
||||||
|
setFormData({
|
||||||
|
name: symptom.name,
|
||||||
|
slug: symptom.slug,
|
||||||
|
description: symptom.description || '',
|
||||||
|
metaTitle: symptom.metaTitle || '',
|
||||||
|
metaDescription: symptom.metaDescription || '',
|
||||||
|
keywords: symptom.keywords || ''
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setEditingSymptom(null);
|
||||||
|
setFormData({
|
||||||
|
name: '',
|
||||||
|
slug: '',
|
||||||
|
description: '',
|
||||||
|
metaTitle: '',
|
||||||
|
metaDescription: '',
|
||||||
|
keywords: ''
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeModal = () => {
|
||||||
|
setIsModalOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchSymptoms = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const res = await api.get('/admin/symptoms', { params: { page, limit, search } });
|
||||||
|
if (res.data?.data) {
|
||||||
|
setSymptoms(res.data.data);
|
||||||
|
setTotalPages(res.data.meta?.lastPage || 1);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error('خطا در دریافت لیست علائم');
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [page, search]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchSymptoms();
|
||||||
|
}, [fetchSymptoms]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
toast.error('نام علامت الزامی است');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true);
|
||||||
|
if (editingSymptom) {
|
||||||
|
await api.put(`/admin/symptoms/${editingSymptom.id}`, formData);
|
||||||
|
toast.success('علامت با موفقیت ویرایش و در تمامی محصولات همگام شد');
|
||||||
|
} else {
|
||||||
|
await api.post('/admin/symptoms', formData);
|
||||||
|
toast.success('علامت درمانی جدید با موفقیت ایجاد شد');
|
||||||
|
}
|
||||||
|
closeModal();
|
||||||
|
fetchSymptoms();
|
||||||
|
} catch {
|
||||||
|
toast.error('خطا در ذخیره اطلاعات علامت');
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!deleteTargetId) return;
|
||||||
|
try {
|
||||||
|
await api.delete(`/admin/symptoms/${deleteTargetId}`);
|
||||||
|
toast.success('علامت با موفقیت حذف شد');
|
||||||
|
setDeleteTargetId(null);
|
||||||
|
fetchSymptoms();
|
||||||
|
} catch {
|
||||||
|
toast.error('خطا در حذف علامت');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 font-vazir" dir="rtl">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-100 shadow-sm">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<span className="w-10 h-10 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center">
|
||||||
|
<Activity className="w-5 h-5 text-purple-600" />
|
||||||
|
</span>
|
||||||
|
<h1 className="text-xl font-black text-gray-900">مدیریت علائم بالینی و درمانی</h1>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 font-bold mt-1">
|
||||||
|
تعریف و ویرایش علائم، بهینهسازی متادیتاهای سئو و همگامسازی یکپارچه با محصولات کاتالوگ
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => openModal()} className="bg-purple-600 hover:bg-purple-700 text-white rounded-2xl px-5 py-3 flex items-center gap-2 font-bold text-xs shadow-md shadow-purple-600/20">
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
<span>افزودن علامت جدید</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filter & Search */}
|
||||||
|
<div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-3">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Search className="w-4 h-4 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="جستجوی علامت بالینی بر اساس نام یا اسلاگ..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="py-20 flex justify-center">
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
) : symptoms.length === 0 ? (
|
||||||
|
<div className="py-20 text-center text-gray-400 font-bold text-sm">
|
||||||
|
هیچ علامت بالینی یافت نشد.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-right text-xs">
|
||||||
|
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black uppercase">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-4">نام علامت بالینی</th>
|
||||||
|
<th className="px-6 py-4">اسلاگ URL</th>
|
||||||
|
<th className="px-6 py-4">محصولات متصل</th>
|
||||||
|
<th className="px-6 py-4">سئو متاتایتل</th>
|
||||||
|
<th className="px-6 py-4 text-left">عملیات</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{symptoms.map((symptom) => (
|
||||||
|
<tr key={symptom.id} className="hover:bg-purple-50/20 transition-colors">
|
||||||
|
<td className="px-6 py-4 font-black text-gray-900 flex items-center gap-2">
|
||||||
|
<Tag className="w-3.5 h-3.5 text-purple-600" />
|
||||||
|
<span>{symptom.name}</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 font-mono text-gray-500 dir-ltr text-right">
|
||||||
|
{symptom.slug}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className="px-2.5 py-1 bg-purple-50 text-purple-700 font-black rounded-lg border border-purple-100">
|
||||||
|
{symptom.productsCount || 0} محصول
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-gray-600 max-w-xs truncate" title={symptom.metaTitle}>
|
||||||
|
{symptom.metaTitle || '—'}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-left space-x-2 space-x-reverse">
|
||||||
|
<button
|
||||||
|
onClick={() => openModal(symptom)}
|
||||||
|
className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
|
||||||
|
title="ویرایش و سئو"
|
||||||
|
>
|
||||||
|
<Edit2 className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setDeleteTargetId(symptom.id)}
|
||||||
|
className="p-2 text-red-600 hover:bg-red-50 rounded-xl transition-colors"
|
||||||
|
title="حذف"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="p-4 border-t border-gray-100 flex justify-center">
|
||||||
|
<Pagination currentPage={page} totalPages={totalPages} onPageChange={(p) => setPage(p)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal CRUD */}
|
||||||
|
<Modal isOpen={isModalOpen} onClose={closeModal} title={editingSymptom ? 'ویرایش علامت و سئو' : 'تعریف علامت جدید'}>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">نام علامت درمانی (فارسی) *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
|
||||||
|
placeholder="مثلاً: پوکی استخوان یا کمخونی"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">اسلاگ URL و انگلیسی</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.slug}
|
||||||
|
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs dir-ltr focus:outline-none focus:ring-2 focus:ring-purple-500/20"
|
||||||
|
placeholder="anemia یا osteoporosis"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">توضیحات تشخیصی و بالینی</label>
|
||||||
|
<textarea
|
||||||
|
rows={3}
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
|
||||||
|
placeholder="توضیحات بالینی و پروتکلهای مکملهای درمانی..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-2 border-t border-gray-100 space-y-3">
|
||||||
|
<div className="flex items-center gap-1.5 text-xs font-black text-purple-700">
|
||||||
|
<Sparkles className="w-3.5 h-3.5" />
|
||||||
|
<span>تنظیمات پیشرفته سئو (SEO Meta)</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Title</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.metaTitle}
|
||||||
|
onChange={(e) => setFormData({ ...formData, metaTitle: e.target.value })}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
|
||||||
|
placeholder="عنوان سئو در نتایج گوگل..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Description</label>
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
value={formData.metaDescription}
|
||||||
|
onChange={(e) => setFormData({ ...formData, metaDescription: e.target.value })}
|
||||||
|
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
|
||||||
|
placeholder="توضیحات متای صفحه سئو..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-4">
|
||||||
|
<Button type="button" variant="outline" onClick={closeModal}>انصراف</Button>
|
||||||
|
<Button type="submit" disabled={isSubmitting} className="bg-purple-600 hover:bg-purple-700 text-white">
|
||||||
|
{isSubmitting ? 'در حال ثبت...' : (editingSymptom ? 'بروزرسانی یکپارچه' : 'ثبت علامت')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Delete Confirmation */}
|
||||||
|
<ConfirmModal
|
||||||
|
isOpen={!!deleteTargetId}
|
||||||
|
onClose={() => setDeleteTargetId(null)}
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
title="حذف علامت بالینی"
|
||||||
|
description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,16 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
CheckSquare,
|
|
||||||
Search,
|
Search,
|
||||||
Filter,
|
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
Clock,
|
|
||||||
User,
|
|
||||||
Plus,
|
|
||||||
PlayCircle,
|
|
||||||
CheckCircle2,
|
|
||||||
AlertTriangle,
|
|
||||||
ChevronDown,
|
|
||||||
ArrowRight,
|
|
||||||
ExternalLink,
|
|
||||||
Bot,
|
Bot,
|
||||||
Briefcase
|
Briefcase,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Play,
|
||||||
|
CheckCircle,
|
||||||
|
Clock,
|
||||||
|
Filter
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import api from '../services/api';
|
import api from '../services/api';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
@@ -25,11 +21,11 @@ interface DepartmentTask {
|
|||||||
department: string;
|
department: string;
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
status: 'BACKLOG' | 'IN_PROGRESS' | 'IN_REVIEW' | 'APPROVED' | 'DEPLOYING' | 'DONE';
|
status: string;
|
||||||
priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
|
priority: string;
|
||||||
assignee: string;
|
assignee: string;
|
||||||
acceptanceCriteria?: string;
|
acceptanceCriteria?: any;
|
||||||
executionLogs?: Array<{ timestamp: string; status: string; note: string }>;
|
executionLogs?: any;
|
||||||
deliverableUrl?: string;
|
deliverableUrl?: string;
|
||||||
startedAt?: string;
|
startedAt?: string;
|
||||||
completedAt?: string;
|
completedAt?: string;
|
||||||
@@ -47,10 +43,14 @@ export default function TasksManagementPage() {
|
|||||||
const [logNote, setLogNote] = useState('');
|
const [logNote, setLogNote] = useState('');
|
||||||
const [updating, setUpdating] = useState(false);
|
const [updating, setUpdating] = useState(false);
|
||||||
|
|
||||||
|
// Pagination states
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const itemsPerPage = 10;
|
||||||
|
|
||||||
const fetchTasks = async () => {
|
const fetchTasks = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await api.get('/admin/department-tasks?limit=100');
|
const res = await api.get('/admin/department-tasks?limit=200');
|
||||||
if (res.data?.success) {
|
if (res.data?.success) {
|
||||||
setTasks(res.data.data);
|
setTasks(res.data.data);
|
||||||
}
|
}
|
||||||
@@ -99,20 +99,41 @@ export default function TasksManagementPage() {
|
|||||||
return matchesSearch && matchesDept && matchesStatus && matchesPriority;
|
return matchesSearch && matchesDept && matchesStatus && matchesPriority;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Calculate pagination
|
||||||
|
const totalPages = Math.ceil(filteredTasks.length / itemsPerPage) || 1;
|
||||||
|
const paginatedTasks = filteredTasks.slice(
|
||||||
|
(currentPage - 1) * itemsPerPage,
|
||||||
|
currentPage * itemsPerPage
|
||||||
|
);
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
const getStatusBadge = (status: string) => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
|
case 'TODO':
|
||||||
case 'BACKLOG':
|
case 'BACKLOG':
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-700 border border-gray-200">بکلاگ (Backlog)</span>;
|
return (
|
||||||
|
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-700 border border-gray-200">
|
||||||
|
۱. صف اقدام (TODO)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
case 'IN_PROGRESS':
|
case 'IN_PROGRESS':
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200 animate-pulse">در حال انجام (In Progress)</span>;
|
return (
|
||||||
|
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200 animate-pulse">
|
||||||
|
۲. در حال توسعه (IN_PROGRESS)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
case 'TEST':
|
||||||
case 'IN_REVIEW':
|
case 'IN_REVIEW':
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">در انتظار بررسی (Review)</span>;
|
return (
|
||||||
case 'APPROVED':
|
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-indigo-100 text-indigo-800 border border-indigo-200">تایید شده (Approved)</span>;
|
۳. تست استیج و QA (TEST)
|
||||||
case 'DEPLOYING':
|
</span>
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-purple-100 text-purple-800 border border-purple-200">درحال استقرار (Deploying)</span>;
|
);
|
||||||
case 'DONE':
|
case 'DONE':
|
||||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">تکمیل شده (Done)</span>;
|
return (
|
||||||
|
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||||
|
۴. مستقر پروداکشن (DONE)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
default:
|
default:
|
||||||
return <span>{status}</span>;
|
return <span>{status}</span>;
|
||||||
}
|
}
|
||||||
@@ -144,6 +165,35 @@ export default function TasksManagementPage() {
|
|||||||
return map[dept] || dept;
|
return map[dept] || dept;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const renderAcceptanceCriteria = (criteria: any) => {
|
||||||
|
if (!criteria) return null;
|
||||||
|
if (typeof criteria === 'string') return criteria;
|
||||||
|
if (typeof criteria === 'object') {
|
||||||
|
if (criteria.rule) return criteria.rule;
|
||||||
|
try {
|
||||||
|
return JSON.stringify(criteria, null, 2);
|
||||||
|
} catch (e) {
|
||||||
|
return String(criteria);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String(criteria);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderExecutionLogs = (logs: any) => {
|
||||||
|
if (!logs) return [];
|
||||||
|
if (Array.isArray(logs)) return logs;
|
||||||
|
if (typeof logs === 'object') {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
note: logs.notes || logs.message || JSON.stringify(logs),
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
status: logs.status || 'LOG',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return [{ note: String(logs), timestamp: new Date().toISOString(), status: 'LOG' }];
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 font-vazir pb-12" dir="rtl">
|
<div className="space-y-6 font-vazir pb-12" dir="rtl">
|
||||||
{/* Top Header */}
|
{/* Top Header */}
|
||||||
@@ -179,7 +229,10 @@ export default function TasksManagementPage() {
|
|||||||
type="text"
|
type="text"
|
||||||
placeholder="جستجو بر اساس عنوان تسک، کد..."
|
placeholder="جستجو بر اساس عنوان تسک، کد..."
|
||||||
value={searchTerm}
|
value={searchTerm}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setSearchTerm(e.target.value);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -187,7 +240,10 @@ export default function TasksManagementPage() {
|
|||||||
<div>
|
<div>
|
||||||
<select
|
<select
|
||||||
value={selectedDept}
|
value={selectedDept}
|
||||||
onChange={(e) => setSelectedDept(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setSelectedDept(e.target.value);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||||
>
|
>
|
||||||
<option value="ALL">همه دپارتمانها</option>
|
<option value="ALL">همه دپارتمانها</option>
|
||||||
@@ -203,23 +259,27 @@ export default function TasksManagementPage() {
|
|||||||
<div>
|
<div>
|
||||||
<select
|
<select
|
||||||
value={selectedStatus}
|
value={selectedStatus}
|
||||||
onChange={(e) => setSelectedStatus(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setSelectedStatus(e.target.value);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||||
>
|
>
|
||||||
<option value="ALL">همه وضعیتها</option>
|
<option value="ALL">همه وضعیتها</option>
|
||||||
<option value="BACKLOG">بکلاگ (Backlog)</option>
|
<option value="TODO">۱. صف اقدام (TODO)</option>
|
||||||
<option value="IN_PROGRESS">در حال انجام (In Progress)</option>
|
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
|
||||||
<option value="IN_REVIEW">در انتظار بررسی (Review)</option>
|
<option value="TEST">۳. تست و QA (TEST)</option>
|
||||||
<option value="APPROVED">تایید شده (Approved)</option>
|
<option value="DONE">۴. تکمیل شده (DONE)</option>
|
||||||
<option value="DEPLOYING">در حال دپلوی (Deploying)</option>
|
|
||||||
<option value="DONE">تکمیل شده (Done)</option>
|
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<select
|
<select
|
||||||
value={selectedPriority}
|
value={selectedPriority}
|
||||||
onChange={(e) => setSelectedPriority(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setSelectedPriority(e.target.value);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}}
|
||||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||||
>
|
>
|
||||||
<option value="ALL">همه اولویتها</option>
|
<option value="ALL">همه اولویتها</option>
|
||||||
@@ -244,63 +304,106 @@ export default function TasksManagementPage() {
|
|||||||
هیچ تسکی با این مشخصات یافت نشد.
|
هیچ تسکی با این مشخصات یافت نشد.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div>
|
||||||
<table className="w-full text-right text-xs">
|
<div className="overflow-x-auto">
|
||||||
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
<table className="w-full text-right text-xs">
|
||||||
<tr>
|
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
||||||
<th className="py-3 px-4">کد تسک</th>
|
<tr>
|
||||||
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
|
<th className="py-3 px-4">کد تسک</th>
|
||||||
<th className="py-3 px-4">دپارتمان</th>
|
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
|
||||||
<th className="py-3 px-4">اولویت</th>
|
<th className="py-3 px-4">دپارتمان</th>
|
||||||
<th className="py-3 px-4">مسئول اجرا (Agent)</th>
|
<th className="py-3 px-4">اولویت</th>
|
||||||
<th className="py-3 px-4">وضعیت</th>
|
<th className="py-3 px-4">مسئول اجرا (Agent)</th>
|
||||||
<th className="py-3 px-4 text-center">اقدام و تغییر استیت</th>
|
<th className="py-3 px-4">وضعیت</th>
|
||||||
</tr>
|
<th className="py-3 px-4 text-center">اقدام و تغییر استیت</th>
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
|
|
||||||
{filteredTasks.map((task) => (
|
|
||||||
<tr key={task.id} className="hover:bg-purple-50/20 transition-colors">
|
|
||||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
|
||||||
<span className="font-mono font-bold text-gray-500 bg-gray-100 px-2 py-1 rounded">
|
|
||||||
{task.code}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4">
|
|
||||||
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
|
|
||||||
{task.description && (
|
|
||||||
<div className="text-[11px] text-gray-500 line-clamp-1 max-w-sm">{task.description}</div>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
|
||||||
<span className="text-[11px] font-bold text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-md border border-purple-100">
|
|
||||||
{getDeptName(task.department)}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
|
||||||
{getPriorityBadge(task.priority)}
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
|
||||||
<div className="flex items-center gap-1.5 font-bold text-gray-800">
|
|
||||||
<Bot className="w-4 h-4 text-indigo-600" />
|
|
||||||
<span>{task.assignee}</span>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
|
||||||
{getStatusBadge(task.status)}
|
|
||||||
</td>
|
|
||||||
<td className="py-3.5 px-4 text-center whitespace-nowrap">
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveTaskModal(task)}
|
|
||||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl bg-purple-600 text-white font-bold text-[11px] hover:bg-purple-700 transition-colors shadow-sm cursor-pointer"
|
|
||||||
>
|
|
||||||
<span>مدیریت و استیت</span>
|
|
||||||
<ChevronDown className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
</thead>
|
||||||
</tbody>
|
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
|
||||||
</table>
|
{paginatedTasks.map((task) => (
|
||||||
|
<tr key={task.id} className="hover:bg-purple-50/20 transition-colors">
|
||||||
|
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||||
|
<span className="font-mono font-bold text-gray-500 bg-gray-100 px-2 py-1 rounded">
|
||||||
|
{task.code}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
|
||||||
|
{task.description && (
|
||||||
|
<div className="text-[11px] text-gray-500 line-clamp-1 max-w-sm">{task.description}</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||||
|
<span className="text-[11px] font-bold text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-md border border-purple-100">
|
||||||
|
{getDeptName(task.department)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||||
|
{getPriorityBadge(task.priority)}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||||
|
<div className="flex items-center gap-1.5 font-bold text-gray-800">
|
||||||
|
<Bot className="w-4 h-4 text-indigo-600" />
|
||||||
|
<span>{task.assignee}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||||
|
{getStatusBadge(task.status)}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-center whitespace-nowrap">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTaskModal(task)}
|
||||||
|
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl bg-purple-600 text-white font-bold text-[11px] hover:bg-purple-700 transition-colors shadow-sm cursor-pointer"
|
||||||
|
>
|
||||||
|
<span>مدیریت و استیت</span>
|
||||||
|
<ChevronDown className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Pagination Controls */}
|
||||||
|
<div className="p-4 border-t border-gray-100 flex items-center justify-between text-xs">
|
||||||
|
<span className="text-gray-500 font-medium">
|
||||||
|
نمایش {(currentPage - 1) * itemsPerPage + 1} تا {Math.min(currentPage * itemsPerPage, filteredTasks.length)} از کل {filteredTasks.length} تسک
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
|
||||||
|
>
|
||||||
|
<ChevronRight className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{Array.from({ length: totalPages }).map((_, i) => (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
onClick={() => setCurrentPage(i + 1)}
|
||||||
|
className={`w-7 h-7 rounded-lg text-xs font-bold transition-colors cursor-pointer ${
|
||||||
|
currentPage === i + 1
|
||||||
|
? 'bg-purple-600 text-white shadow-sm'
|
||||||
|
: 'text-gray-600 hover:bg-gray-100'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{i + 1}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -331,21 +434,23 @@ export default function TasksManagementPage() {
|
|||||||
{activeTaskModal.acceptanceCriteria && (
|
{activeTaskModal.acceptanceCriteria && (
|
||||||
<div className="p-3 bg-indigo-50/50 rounded-xl space-y-1 border border-indigo-100">
|
<div className="p-3 bg-indigo-50/50 rounded-xl space-y-1 border border-indigo-100">
|
||||||
<div className="font-bold text-indigo-900">معیارهای پذیرش (Acceptance Criteria):</div>
|
<div className="font-bold text-indigo-900">معیارهای پذیرش (Acceptance Criteria):</div>
|
||||||
<div className="text-indigo-800 font-medium">{activeTaskModal.acceptanceCriteria}</div>
|
<div className="text-indigo-800 font-medium whitespace-pre-wrap">
|
||||||
|
{renderAcceptanceCriteria(activeTaskModal.acceptanceCriteria)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Status Update Options */}
|
{/* Status Update Options */}
|
||||||
<div className="pt-2">
|
<div className="pt-2">
|
||||||
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
|
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
|
||||||
<div className="grid grid-cols-3 gap-2">
|
<div className="grid grid-cols-4 gap-2">
|
||||||
{['BACKLOG', 'IN_PROGRESS', 'IN_REVIEW', 'APPROVED', 'DEPLOYING', 'DONE'].map((st) => (
|
{['TODO', 'IN_PROGRESS', 'TEST', 'DONE'].map((st) => (
|
||||||
<button
|
<button
|
||||||
key={st}
|
key={st}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => handleStatusChange(activeTaskModal.id, st)}
|
onClick={() => handleStatusChange(activeTaskModal.id, st)}
|
||||||
disabled={updating || activeTaskModal.status === st}
|
disabled={updating || activeTaskModal.status === st}
|
||||||
className={`py-2 px-2 text-[11px] font-bold rounded-xl border text-center transition-all ${
|
className={`py-2 px-2 text-[11px] font-bold rounded-xl border text-center transition-all cursor-pointer ${
|
||||||
activeTaskModal.status === st
|
activeTaskModal.status === st
|
||||||
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
|
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
|
||||||
: 'bg-white hover:bg-gray-50 text-gray-700 border-gray-200'
|
: 'bg-white hover:bg-gray-50 text-gray-700 border-gray-200'
|
||||||
@@ -364,19 +469,21 @@ export default function TasksManagementPage() {
|
|||||||
placeholder="مثال: تستها پاس شد و کاتالوگ بهروز گردید..."
|
placeholder="مثال: تستها پاس شد و کاتالوگ بهروز گردید..."
|
||||||
value={logNote}
|
value={logNote}
|
||||||
onChange={(e) => setLogNote(e.target.value)}
|
onChange={(e) => setLogNote(e.target.value)}
|
||||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500"
|
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Execution Logs */}
|
{/* Execution Logs */}
|
||||||
{activeTaskModal.executionLogs && activeTaskModal.executionLogs.length > 0 && (
|
{activeTaskModal.executionLogs && (
|
||||||
<div className="pt-2 space-y-1">
|
<div className="pt-2 space-y-1">
|
||||||
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجامشده روی این تسک:</div>
|
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجامشده روی این تسک:</div>
|
||||||
<div className="space-y-1 max-h-36 overflow-y-auto">
|
<div className="space-y-1 max-h-36 overflow-y-auto">
|
||||||
{activeTaskModal.executionLogs.map((lg, i) => (
|
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
|
||||||
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
|
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
|
||||||
<span className="font-bold text-gray-800">{lg.note}</span>
|
<span className="font-bold text-gray-800">{lg.note || JSON.stringify(lg)}</span>
|
||||||
<span className="text-gray-400 font-mono">{new Date(lg.timestamp).toLocaleTimeString('fa-IR')}</span>
|
<span className="text-gray-400 font-mono">
|
||||||
|
{lg.timestamp ? new Date(lg.timestamp).toLocaleTimeString('fa-IR') : '-'}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -388,7 +495,7 @@ export default function TasksManagementPage() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setActiveTaskModal(null)}
|
onClick={() => setActiveTaskModal(null)}
|
||||||
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold transition-colors"
|
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
انصراف
|
انصراف
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -12,9 +12,13 @@ const Users = lazyWithRetry(() => import('../pages/Users'));
|
|||||||
const Products = lazyWithRetry(() => import('../pages/Products'));
|
const Products = lazyWithRetry(() => import('../pages/Products'));
|
||||||
const Orders = lazyWithRetry(() => import('../pages/Orders'));
|
const Orders = lazyWithRetry(() => import('../pages/Orders'));
|
||||||
const Coupons = lazyWithRetry(() => import('../pages/Coupons'));
|
const Coupons = lazyWithRetry(() => import('../pages/Coupons'));
|
||||||
|
const SmartChatSettingsPage = lazyWithRetry(() => import('../pages/SmartChatSettingsPage'));
|
||||||
|
const SupportChatAnalyticsPage = lazyWithRetry(() => import('../pages/SupportChatAnalyticsPage'));
|
||||||
const Settings = lazyWithRetry(() => import('../pages/Settings'));
|
const Settings = lazyWithRetry(() => import('../pages/Settings'));
|
||||||
const Reports = lazyWithRetry(() => import('../pages/Reports'));
|
const Reports = lazyWithRetry(() => import('../pages/Reports'));
|
||||||
const Categories = lazyWithRetry(() => import('../pages/Categories'));
|
const Categories = lazyWithRetry(() => import('../pages/Categories'));
|
||||||
|
const SymptomsPage = lazyWithRetry(() => import('../pages/SymptomsPage'));
|
||||||
|
|
||||||
const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
|
const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
|
||||||
const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
|
const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
|
||||||
const Pets = lazyWithRetry(() => import('../pages/Pets'));
|
const Pets = lazyWithRetry(() => import('../pages/Pets'));
|
||||||
@@ -79,6 +83,8 @@ export const router = createBrowserRouter([
|
|||||||
{ path: 'zibal-portal/*', element: <ZibalPortalPage /> },
|
{ path: 'zibal-portal/*', element: <ZibalPortalPage /> },
|
||||||
{ path: 'coupons/*', element: <Coupons /> },
|
{ path: 'coupons/*', element: <Coupons /> },
|
||||||
{ path: 'settings', element: <Settings /> },
|
{ path: 'settings', element: <Settings /> },
|
||||||
|
{ path: 'settings/smart-chat', element: <SupportChatAnalyticsPage /> },
|
||||||
|
{ path: 'settings/smart-chat/config', element: <SmartChatSettingsPage /> },
|
||||||
{ path: 'settings/payment-methods', element: <PaymentGatewaysPage /> },
|
{ path: 'settings/payment-methods', element: <PaymentGatewaysPage /> },
|
||||||
{ path: 'settings/shipping', element: <ShippingSettingsPage /> },
|
{ path: 'settings/shipping', element: <ShippingSettingsPage /> },
|
||||||
{ path: 'settings/ssl', element: <SslSettingsPage /> },
|
{ path: 'settings/ssl', element: <SslSettingsPage /> },
|
||||||
@@ -89,6 +95,8 @@ export const router = createBrowserRouter([
|
|||||||
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
||||||
{ path: 'reports/*', element: <Reports /> },
|
{ path: 'reports/*', element: <Reports /> },
|
||||||
{ path: 'categories/*', element: <Categories /> },
|
{ path: 'categories/*', element: <Categories /> },
|
||||||
|
{ path: 'symptoms/*', element: <SymptomsPage /> },
|
||||||
|
|
||||||
{ path: 'blogs/*', element: <Blogs /> },
|
{ path: 'blogs/*', element: <Blogs /> },
|
||||||
{ path: 'wiki/*', element: <Wiki /> },
|
{ path: 'wiki/*', element: <Wiki /> },
|
||||||
{ path: 'videos/*', element: <Videos /> },
|
{ path: 'videos/*', element: <Videos /> },
|
||||||
|
|||||||
@@ -87,11 +87,24 @@ api.interceptors.response.use(
|
|||||||
isRefreshing = true;
|
isRefreshing = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
|
let refreshResponse;
|
||||||
`${baseURL}/auth/refresh`,
|
try {
|
||||||
{},
|
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
|
||||||
{ withCredentials: true }
|
`${baseURL}/auth/refresh`,
|
||||||
);
|
{},
|
||||||
|
{
|
||||||
|
withCredentials: true,
|
||||||
|
headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// If bearer-based refresh fails (e.g. access token fully expired), try cookie-based /auth/refresh-token
|
||||||
|
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
|
||||||
|
`${baseURL}/auth/refresh-token`,
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
|
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
|
||||||
const newToken = refreshResponse.data.data.accessToken;
|
const newToken = refreshResponse.data.data.accessToken;
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { render, screen, cleanup } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Mock next/navigation
|
||||||
|
let currentPathname = "/";
|
||||||
|
const mockRouter = {
|
||||||
|
push: vi.fn(),
|
||||||
|
replace: vi.fn(),
|
||||||
|
back: vi.fn(),
|
||||||
|
prefetch: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
usePathname: () => currentPathname,
|
||||||
|
useRouter: () => mockRouter,
|
||||||
|
useSearchParams: () => new URLSearchParams(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock dynamic components to render test identifiers
|
||||||
|
vi.mock("next/dynamic", () => ({
|
||||||
|
default: (loader: any) => {
|
||||||
|
const str = loader.toString();
|
||||||
|
const isCart = str.includes("CartDrawer");
|
||||||
|
const isAuth = str.includes("AuthModal");
|
||||||
|
const isLogin = str.includes("LoginModal");
|
||||||
|
return function MockDynamic(props: any) {
|
||||||
|
if (props.isOpen === false) return null;
|
||||||
|
if (isCart) return <div data-testid="shell-cart-drawer" data-open={String(props.isOpen)} />;
|
||||||
|
if (isAuth) return <div data-testid="shell-auth-modal" data-open={String(props.isOpen)} />;
|
||||||
|
if (isLogin) return <div data-testid="shell-login-modal" data-open={String(props.isOpen)} />;
|
||||||
|
return <div data-testid="shell-dynamic-other" />;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/Header", () => ({
|
||||||
|
default: () => <header data-testid="shell-header">Header</header>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/Footer", () => ({
|
||||||
|
default: () => <footer data-testid="shell-footer">Footer</footer>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/NetworkBanner", () => ({
|
||||||
|
NetworkBanner: () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/NavigationProgressBar", () => ({
|
||||||
|
default: () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/MobileBottomNav", () => ({
|
||||||
|
default: () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/PrescriptionUploadModal", () => ({
|
||||||
|
default: () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("sonner", () => ({
|
||||||
|
Toaster: () => null,
|
||||||
|
toast: { success: vi.fn(), error: vi.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock real components used inside page routes
|
||||||
|
vi.mock("../components/AuthModal", () => ({
|
||||||
|
default: (props: any) => (
|
||||||
|
<div data-testid="page-auth-modal" data-isopen={String(props.isOpen)} />
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/CartDrawer", () => ({
|
||||||
|
default: (props: any) => (
|
||||||
|
<div data-testid="page-cart-drawer" data-isopen={String(props.isOpen)} />
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock stores
|
||||||
|
const mockUserStoreState: any = {
|
||||||
|
isAuthModalOpen: false,
|
||||||
|
setAuthModalOpen: vi.fn(),
|
||||||
|
fetchProfile: vi.fn().mockResolvedValue({}),
|
||||||
|
user: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock("../lib/store/userStore", () => {
|
||||||
|
const store = (selector?: any) => (typeof selector === "function" ? selector(mockUserStoreState) : mockUserStoreState);
|
||||||
|
store.getState = () => mockUserStoreState;
|
||||||
|
return { useUserStore: store };
|
||||||
|
});
|
||||||
|
|
||||||
|
const mockSettingsStoreState: any = {
|
||||||
|
fetchSettings: vi.fn().mockResolvedValue({}),
|
||||||
|
getText: vi.fn().mockReturnValue(""),
|
||||||
|
getBoolean: vi.fn().mockReturnValue(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock("../lib/store/settingsStore", () => {
|
||||||
|
const store = (selector?: any) => (typeof selector === "function" ? selector(mockSettingsStoreState) : mockSettingsStoreState);
|
||||||
|
store.getState = () => mockSettingsStoreState;
|
||||||
|
return { useSettingsStore: store };
|
||||||
|
});
|
||||||
|
|
||||||
|
const mockUIStoreState: any = {
|
||||||
|
isCartOpen: false,
|
||||||
|
isLoginModalOpen: false,
|
||||||
|
isB2BPortalOpen: false,
|
||||||
|
advisorData: null,
|
||||||
|
setCartOpen: vi.fn(),
|
||||||
|
setLoginModalOpen: vi.fn(),
|
||||||
|
setB2BPortalOpen: vi.fn(),
|
||||||
|
clearAdvisorData: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock("../lib/store/uiStore", () => {
|
||||||
|
const store = (selector?: any) => (typeof selector === "function" ? selector(mockUIStoreState) : mockUIStoreState);
|
||||||
|
store.getState = () => mockUIStoreState;
|
||||||
|
return { useUIStore: store };
|
||||||
|
});
|
||||||
|
|
||||||
|
import ClientLayout from "../app/ClientLayout";
|
||||||
|
import LoginPage from "../app/login/page";
|
||||||
|
import CartPage from "../app/cart/page";
|
||||||
|
|
||||||
|
describe("ClientLayout Shell & Singleton Modals Integration (UX-28)", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mockUserStoreState.isAuthModalOpen = false;
|
||||||
|
mockUIStoreState.isCartOpen = false;
|
||||||
|
currentPathname = "/";
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders singleton CartDrawer and AuthModal in ClientLayout on normal routes when opened", () => {
|
||||||
|
mockUIStoreState.isCartOpen = true;
|
||||||
|
mockUserStoreState.isAuthModalOpen = true;
|
||||||
|
|
||||||
|
render(
|
||||||
|
<ClientLayout>
|
||||||
|
<div>Content</div>
|
||||||
|
</ClientLayout>
|
||||||
|
);
|
||||||
|
|
||||||
|
// On normal route, Header, Footer, and active drawers are rendered
|
||||||
|
expect(screen.getByTestId("shell-header")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("shell-footer")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("shell-cart-drawer")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("shell-auth-modal")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ensures no duplicate CartDrawer exists when user visits /cart utility route", () => {
|
||||||
|
currentPathname = "/cart";
|
||||||
|
mockUIStoreState.isCartOpen = true; // Even if UI store flag was left open
|
||||||
|
|
||||||
|
const { container } = render(
|
||||||
|
<ClientLayout>
|
||||||
|
<CartPage />
|
||||||
|
</ClientLayout>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Footer and shell-level CartDrawer must be suppressed on /cart
|
||||||
|
expect(screen.queryByTestId("shell-footer")).toBeNull();
|
||||||
|
|
||||||
|
// Page level cart drawer is present
|
||||||
|
expect(screen.getByTestId("page-cart-drawer")).toBeTruthy();
|
||||||
|
|
||||||
|
// Shell level dynamic cart drawer is NOT rendered because isUtilityRoute is true
|
||||||
|
expect(screen.queryByTestId("shell-cart-drawer")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ensures no duplicate AuthModal exists when user visits /login utility route", () => {
|
||||||
|
currentPathname = "/login";
|
||||||
|
mockUserStoreState.isAuthModalOpen = true; // Even if userStore auth flag was left open
|
||||||
|
|
||||||
|
const { container } = render(
|
||||||
|
<ClientLayout>
|
||||||
|
<LoginPage />
|
||||||
|
</ClientLayout>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Footer and shell-level AuthModal must be suppressed on /login
|
||||||
|
expect(screen.queryByTestId("shell-footer")).toBeNull();
|
||||||
|
|
||||||
|
// Page level auth modal is present
|
||||||
|
expect(screen.getByTestId("page-auth-modal")).toBeTruthy();
|
||||||
|
|
||||||
|
// Shell level dynamic auth modal is NOT rendered because isUtilityRoute is true
|
||||||
|
expect(screen.queryByTestId("shell-auth-modal")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -38,10 +38,12 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
|||||||
const setLoginModalOpen = useUIStore((state) => state.setLoginModalOpen);
|
const setLoginModalOpen = useUIStore((state) => state.setLoginModalOpen);
|
||||||
const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen);
|
const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen);
|
||||||
const clearAdvisorData = useUIStore((state) => state.clearAdvisorData);
|
const clearAdvisorData = useUIStore((state) => state.clearAdvisorData);
|
||||||
const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false);
|
const isPrescriptionModalOpen = useUIStore((state) => state.isPrescriptionModalOpen);
|
||||||
|
const setPrescriptionModalOpen = useUIStore((state) => state.setPrescriptionModalOpen);
|
||||||
|
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const isUtilityRoute = pathname === "/login" || pathname === "/cart";
|
||||||
|
|
||||||
const fetchProfile = useUserStore((state) => state.fetchProfile);
|
const fetchProfile = useUserStore((state) => state.fetchProfile);
|
||||||
const role = useUserStore((state) => state.role);
|
const role = useUserStore((state) => state.role);
|
||||||
@@ -174,20 +176,20 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
|||||||
onSearch={handleSearch}
|
onSearch={handleSearch}
|
||||||
onB2BOpen={() => setB2BPortalOpen(true)}
|
onB2BOpen={() => setB2BPortalOpen(true)}
|
||||||
/>
|
/>
|
||||||
<main className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
|
<main id="main-content" className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
|
||||||
{children}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
<Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />
|
{!isUtilityRoute && <Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />}
|
||||||
|
|
||||||
{isB2BPortalOpen && isB2BEnabled && (
|
{isB2BPortalOpen && isB2BEnabled && (
|
||||||
<B2BPortal onClose={() => setB2BPortalOpen(false)} />
|
<B2BPortal onClose={() => setB2BPortalOpen(false)} />
|
||||||
)}
|
)}
|
||||||
<CartDrawer
|
{!isUtilityRoute && <CartDrawer
|
||||||
isOpen={isCartOpen}
|
isOpen={isCartOpen}
|
||||||
onClose={() => setCartOpen(false)}
|
onClose={() => setCartOpen(false)}
|
||||||
onCheckout={() => { setCartOpen(false); router.push('/checkout'); }}
|
onCheckout={() => { setCartOpen(false); router.push('/checkout'); }}
|
||||||
onShopNavigate={navigateToShop}
|
onShopNavigate={navigateToShop}
|
||||||
/>
|
/>}
|
||||||
<LoginModal
|
<LoginModal
|
||||||
isOpen={isLoginModalOpen}
|
isOpen={isLoginModalOpen}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
@@ -223,21 +225,17 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
|||||||
petName={advisorData?.name as string | undefined}
|
petName={advisorData?.name as string | undefined}
|
||||||
isAdvisorContext={!!advisorData}
|
isAdvisorContext={!!advisorData}
|
||||||
/>
|
/>
|
||||||
<AuthModal
|
{!isUtilityRoute && <AuthModal
|
||||||
isOpen={isAuthModalOpen}
|
isOpen={isAuthModalOpen}
|
||||||
onClose={() => setAuthModalOpen(false)}
|
onClose={() => setAuthModalOpen(false)}
|
||||||
/>
|
/>}
|
||||||
<PrescriptionUploadModal
|
<PrescriptionUploadModal
|
||||||
isOpen={isPrescriptionModalOpen}
|
isOpen={isPrescriptionModalOpen}
|
||||||
onClose={() => setIsPrescriptionModalOpen(false)}
|
onClose={() => setPrescriptionModalOpen(false)}
|
||||||
/>
|
/>
|
||||||
<MobileBottomNav
|
<MobileBottomNav
|
||||||
onPrescriptionOpen={() => {
|
onPrescriptionOpen={() => {
|
||||||
if (!isLoggedIn) {
|
setPrescriptionModalOpen(true);
|
||||||
setAuthModalOpen(true);
|
|
||||||
} else {
|
|
||||||
setIsPrescriptionModalOpen(true);
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Toaster position="top-center" expand={true} richColors closeButton />
|
<Toaster position="top-center" expand={true} richColors closeButton />
|
||||||
|
|||||||
@@ -72,12 +72,12 @@ export default function HomeClient({ initialData }: HomeClientProps) {
|
|||||||
|
|
||||||
|
|
||||||
{/* Navigation to Sections */}
|
{/* Navigation to Sections */}
|
||||||
<section className="py-8 sm:py-14 bg-medical-gray-50 border-y border-medical-gray-100 font-sans">
|
<section className="py-5 sm:py-14 bg-medical-gray-50 border-y border-medical-gray-100 font-sans">
|
||||||
<div className="max-w-7xl mx-auto px-4 grid md:grid-cols-2 gap-5 sm:gap-8">
|
<div className="max-w-7xl mx-auto px-4 grid md:grid-cols-2 gap-5 sm:gap-8">
|
||||||
{/* Specialty Shop Card */}
|
{/* Specialty Shop Card */}
|
||||||
<Link
|
<Link
|
||||||
href="/shop"
|
href="/shop"
|
||||||
className="group relative overflow-hidden rounded-3xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-blue-50/50 to-canina-blue/10 p-6 sm:p-10 border border-blue-200/70 shadow-md hover:shadow-2xl hover:border-canina-blue/50 hover:-translate-y-1 transition-all duration-500 block"
|
className="group relative overflow-hidden rounded-2xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-blue-50/50 to-canina-blue/10 p-4 sm:p-10 border border-blue-200/70 shadow-xs sm:shadow-md hover:shadow-2xl hover:border-canina-blue/50 hover:-translate-y-1 transition-all duration-500 block"
|
||||||
>
|
>
|
||||||
{/* Ambient Glows */}
|
{/* Ambient Glows */}
|
||||||
<div className="absolute -top-16 -left-16 w-44 h-44 bg-canina-blue/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
|
<div className="absolute -top-16 -left-16 w-44 h-44 bg-canina-blue/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
|
||||||
@@ -112,7 +112,7 @@ export default function HomeClient({ initialData }: HomeClientProps) {
|
|||||||
{/* Scientific Wiki Card */}
|
{/* Scientific Wiki Card */}
|
||||||
<Link
|
<Link
|
||||||
href="/wiki"
|
href="/wiki"
|
||||||
className="group relative overflow-hidden rounded-3xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-emerald-50/50 to-teal-500/10 p-6 sm:p-10 border border-emerald-200/70 shadow-md hover:shadow-2xl hover:border-emerald-500/50 hover:-translate-y-1 transition-all duration-500 block"
|
className="group relative overflow-hidden rounded-2xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-emerald-50/50 to-teal-500/10 p-4 sm:p-10 border border-emerald-200/70 shadow-xs sm:shadow-md hover:shadow-2xl hover:border-emerald-500/50 hover:-translate-y-1 transition-all duration-500 block"
|
||||||
>
|
>
|
||||||
{/* Ambient Glows */}
|
{/* Ambient Glows */}
|
||||||
<div className="absolute -top-16 -left-16 w-44 h-44 bg-emerald-500/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
|
<div className="absolute -top-16 -left-16 w-44 h-44 bg-emerald-500/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
|
||||||
@@ -147,7 +147,7 @@ export default function HomeClient({ initialData }: HomeClientProps) {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* About Section Teaser */}
|
{/* About Section Teaser */}
|
||||||
<section className="py-8 sm:py-16 bg-white overflow-hidden font-sans">
|
<section className="py-5 sm:py-16 bg-white overflow-hidden font-sans">
|
||||||
<div className="max-w-7xl mx-auto px-4 grid lg:grid-cols-2 gap-8 lg:gap-24 items-center">
|
<div className="max-w-7xl mx-auto px-4 grid lg:grid-cols-2 gap-8 lg:gap-24 items-center">
|
||||||
<div className="relative overflow-hidden rounded-2xl sm:rounded-[3rem]">
|
<div className="relative overflow-hidden rounded-2xl sm:rounded-[3rem]">
|
||||||
<div className="absolute -top-10 -right-10 w-40 h-40 bg-canina-blue/5 rounded-full blur-3xl" />
|
<div className="absolute -top-10 -right-10 w-40 h-40 bg-canina-blue/5 rounded-full blur-3xl" />
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const commitSha =
|
||||||
|
process.env.NEXT_PUBLIC_GIT_COMMIT ||
|
||||||
|
process.env.GIT_COMMIT_SHA ||
|
||||||
|
process.env.COMMIT_SHA ||
|
||||||
|
'local-build';
|
||||||
|
|
||||||
|
const buildTime =
|
||||||
|
process.env.BUILD_TIMESTAMP ||
|
||||||
|
process.env.NEXT_PUBLIC_BUILD_TIME ||
|
||||||
|
new Date().toISOString();
|
||||||
|
|
||||||
|
const environment = process.env.NODE_ENV || 'production';
|
||||||
|
const service = 'frontend';
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
status: 'ok',
|
||||||
|
service,
|
||||||
|
commitSha,
|
||||||
|
buildTime,
|
||||||
|
environment,
|
||||||
|
}, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
||||||
|
'X-Commit-Sha': commitSha,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { GET } from './route';
|
||||||
|
|
||||||
|
describe('Deployment Metadata Endpoint Gate (UX-37)', () => {
|
||||||
|
it('returns valid deployment signature, status and commit header', async () => {
|
||||||
|
const response = await GET();
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
expect(data.status).toBe('ok');
|
||||||
|
expect(data.service).toBe('frontend');
|
||||||
|
expect(data).toHaveProperty('commitSha');
|
||||||
|
expect(data).toHaveProperty('buildTime');
|
||||||
|
expect(data).toHaveProperty('environment');
|
||||||
|
|
||||||
|
expect(response.headers.get('Cache-Control')).toBe('no-store, no-cache, must-revalidate');
|
||||||
|
expect(response.headers.get('X-Commit-Sha')).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import BlogPostPage from './page';
|
||||||
|
|
||||||
|
vi.mock('../../../lib/seo', () => ({
|
||||||
|
getSeoConfig: vi.fn().mockResolvedValue({
|
||||||
|
brandNameFa: 'کنینا ایران',
|
||||||
|
canonicalBaseUrl: 'https://canina.ir',
|
||||||
|
ogImageUrl: '/assets/og.jpg',
|
||||||
|
defaultMetaDescription: 'توضیحات پیشفرض',
|
||||||
|
titleSeparator: '|',
|
||||||
|
titlePosition: 'suffix',
|
||||||
|
}),
|
||||||
|
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../../components/BlogPostClient', () => ({
|
||||||
|
default: () => <div data-testid="blog-post-client" />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.unstubAllEnvs();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
|
||||||
|
const blogData = {
|
||||||
|
slug: 'joint-health',
|
||||||
|
title: 'سلامت مفاصل سگ',
|
||||||
|
content: `
|
||||||
|
<article>
|
||||||
|
<p>مقدمهای درباره مفاصل سگ.</p>
|
||||||
|
<details>
|
||||||
|
<summary>آیا این مکمل برای سگ مسن مناسب است؟</summary>
|
||||||
|
<p>بله، بسیار توصیه میشود و روند تخریب مفصل را کند میکند.</p>
|
||||||
|
</details>
|
||||||
|
</article>
|
||||||
|
`,
|
||||||
|
createdAt: '2026-01-01',
|
||||||
|
publishedAt: '2026-01-01',
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => blogData,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'joint-health' }) });
|
||||||
|
expect(jsx).toBeDefined();
|
||||||
|
|
||||||
|
// Verify scripts in JSX tree
|
||||||
|
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||||
|
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||||
|
);
|
||||||
|
|
||||||
|
// There should be 3 schemas: Article, Breadcrumb, and FAQPage
|
||||||
|
expect(scripts.length).toBe(3);
|
||||||
|
|
||||||
|
const faqScript: any = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||||
|
expect(faqScript).toBeDefined();
|
||||||
|
|
||||||
|
const faqJson = JSON.parse(faqScript.props.dangerouslySetInnerHTML.__html);
|
||||||
|
expect(faqJson['@type']).toBe('FAQPage');
|
||||||
|
expect(faqJson.mainEntity).toHaveLength(1);
|
||||||
|
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not inject FAQPage schema when article does not have FAQs', async () => {
|
||||||
|
const blogData = {
|
||||||
|
slug: 'nutrition',
|
||||||
|
title: 'تغذیه سگ',
|
||||||
|
content: '<p>یک مقاله ساده بدون سوال و جواب یا آکاردئون.</p>',
|
||||||
|
createdAt: '2026-01-01',
|
||||||
|
publishedAt: '2026-01-01',
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => blogData,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'nutrition' }) });
|
||||||
|
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||||
|
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only Article and Breadcrumb schemas
|
||||||
|
expect(scripts.length).toBe(2);
|
||||||
|
const faqScript = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||||
|
expect(faqScript).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,8 @@ import type { Metadata } from 'next';
|
|||||||
import BlogPostClient from "../../../components/BlogPostClient";
|
import BlogPostClient from "../../../components/BlogPostClient";
|
||||||
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
||||||
import { safeJsonLd } from "../../../lib/schema";
|
import { safeJsonLd } from "../../../lib/schema";
|
||||||
|
import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml";
|
||||||
|
import { extractFaqsFromHtml, generateFAQPageSchema } from "../../../lib/extractFaqs";
|
||||||
|
|
||||||
function safeIso(val: any, fallback?: string): string | undefined {
|
function safeIso(val: any, fallback?: string): string | undefined {
|
||||||
if (!val) return fallback;
|
if (!val) return fallback;
|
||||||
@@ -81,7 +83,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
|||||||
const ogTitle = blog.ogTitle || title;
|
const ogTitle = blog.ogTitle || title;
|
||||||
const ogDesc = blog.ogDescription || description;
|
const ogDesc = blog.ogDescription || description;
|
||||||
|
|
||||||
const isStaging =
|
const isStaging =
|
||||||
process.env.NEXT_PUBLIC_APP_ENV === 'staging' ||
|
process.env.NEXT_PUBLIC_APP_ENV === 'staging' ||
|
||||||
process.env.NODE_ENV !== 'production' ||
|
process.env.NODE_ENV !== 'production' ||
|
||||||
siteUrl.includes('stage') ||
|
siteUrl.includes('stage') ||
|
||||||
@@ -182,6 +184,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
|||||||
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
|
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
|
||||||
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
|
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
|
||||||
|
|
||||||
|
const sanitizedContent = sanitizeBlogHtml(blog.content);
|
||||||
const schemaType = blog.schemaType || 'BlogPosting';
|
const schemaType = blog.schemaType || 'BlogPosting';
|
||||||
|
|
||||||
const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName)
|
const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName)
|
||||||
@@ -265,6 +268,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
|||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// SEO-P1-07: Auto-detect and inject FAQPage Schema when article content contains Q&As or accordion structures
|
||||||
|
const extractedFaqs = extractFaqsFromHtml(blog.content || '');
|
||||||
|
const faqPageSchema = generateFAQPageSchema(extractedFaqs);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<script
|
<script
|
||||||
@@ -275,10 +282,18 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
|||||||
type="application/ld+json"
|
type="application/ld+json"
|
||||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }}
|
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }}
|
||||||
/>
|
/>
|
||||||
|
{faqPageSchema && (
|
||||||
|
<script
|
||||||
|
type="application/ld+json"
|
||||||
|
data-testid="faq-schema"
|
||||||
|
dangerouslySetInnerHTML={{ __html: safeJsonLd(faqPageSchema) }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<BlogPostClient
|
<BlogPostClient
|
||||||
blog={blog}
|
blog={blog}
|
||||||
publishedDate={publishedDate}
|
publishedDate={publishedDate}
|
||||||
authorName={authorName}
|
authorName={authorName}
|
||||||
|
sanitizedContent={sanitizedContent}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import CartPage from "./page";
|
||||||
|
|
||||||
|
vi.mock("../../components/CartDrawer", () => ({
|
||||||
|
default: ({ isOpen, onCheckout, onShopNavigate }: { isOpen: boolean; onCheckout: () => void; onShopNavigate: () => void }) => isOpen ? (
|
||||||
|
<div role="region" aria-label="سبد خرید">
|
||||||
|
<button onClick={onCheckout}>تکمیل سفارش</button>
|
||||||
|
<button onClick={onShopNavigate}>مشاهده محصولات</button>
|
||||||
|
</div>
|
||||||
|
) : null,
|
||||||
|
}));
|
||||||
|
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
|
||||||
|
|
||||||
|
describe("/cart route", () => {
|
||||||
|
it("renders the cart experience and provides journey actions", () => {
|
||||||
|
render(<CartPage />);
|
||||||
|
expect(screen.getByRole("heading", { name: "سبد خرید" })).toBeTruthy();
|
||||||
|
expect(screen.getAllByRole("region", { name: "سبد خرید" })).toHaveLength(1);
|
||||||
|
expect(screen.getByRole("button", { name: "تکمیل سفارش" })).toBeTruthy();
|
||||||
|
expect(screen.getByRole("button", { name: "مشاهده محصولات" })).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import CartDrawer from "../../components/CartDrawer";
|
||||||
|
|
||||||
|
export default function CartPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-medical-gray-50" dir="rtl">
|
||||||
|
<h1 className="sr-only">سبد خرید</h1>
|
||||||
|
<CartDrawer
|
||||||
|
isOpen
|
||||||
|
onClose={() => router.push("/")}
|
||||||
|
onCheckout={() => router.push("/checkout")}
|
||||||
|
onShopNavigate={() => router.push("/shop")}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import ContactFormClient from "@/components/ContactFormClient";
|
import ContactFormClient from "@/components/ContactFormClient";
|
||||||
import { getPageMetadata } from "@/lib/seo";
|
import { getPageMetadata, getSeoConfig } from "@/lib/seo";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
return getPageMetadata('contact', {
|
return getPageMetadata('contact', {
|
||||||
@@ -12,13 +12,14 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
|
|
||||||
import { generateLocalBusinessSchema, generateBreadcrumbSchema, safeJsonLd } from "@/lib/schema";
|
import { generateLocalBusinessSchema, generateBreadcrumbSchema, safeJsonLd } from "@/lib/schema";
|
||||||
|
|
||||||
export default function ContactPage() {
|
export default async function ContactPage() {
|
||||||
|
const config = await getSeoConfig();
|
||||||
const localBusinessSchema = generateLocalBusinessSchema({
|
const localBusinessSchema = generateLocalBusinessSchema({
|
||||||
name: 'کنینا ایران',
|
name: 'کنینا ایران',
|
||||||
url: 'https://canina.ir',
|
url: 'https://canina.ir',
|
||||||
telephone: '+989211231517',
|
telephone: '+989211231517',
|
||||||
address: {
|
address: {
|
||||||
streetAddress: 'تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹',
|
streetAddress: config.texts.CONTACT_ADDRESS || config.texts.contact_address || undefined,
|
||||||
addressLocality: 'تهران',
|
addressLocality: 'تهران',
|
||||||
addressRegion: 'تهران',
|
addressRegion: 'تهران',
|
||||||
postalCode: '1967812345',
|
postalCode: '1967812345',
|
||||||
@@ -41,7 +42,7 @@ export default function ContactPage() {
|
|||||||
type="application/ld+json"
|
type="application/ld+json"
|
||||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbs) }}
|
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbs) }}
|
||||||
/>
|
/>
|
||||||
<div className="bg-medical-gray-50 py-16 px-4 sm:px-6 lg:px-8 font-vazir" dir="rtl">
|
<div className="bg-medical-gray-50 pt-10 pb-28 sm:py-16 px-4 sm:px-6 lg:px-8 font-vazir" dir="rtl">
|
||||||
<div className="max-w-6xl mx-auto space-y-16">
|
<div className="max-w-6xl mx-auto space-y-16">
|
||||||
|
|
||||||
{/* Title */}
|
{/* Title */}
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ export default function ErrorBoundary({
|
|||||||
reset: () => void;
|
reset: () => void;
|
||||||
}) {
|
}) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.error("Global Application Error:", error);
|
if (process.env.NODE_ENV === "development") {
|
||||||
|
console.error("Global Application Error:", error?.message || "Unknown error");
|
||||||
|
}
|
||||||
}, [error]);
|
}, [error]);
|
||||||
|
|
||||||
return <ServerErrorPage onRetry={reset} />;
|
return <ServerErrorPage onRetry={reset} />;
|
||||||
|
|||||||
@@ -41,7 +41,7 @@
|
|||||||
|
|
||||||
html, body {
|
html, body {
|
||||||
font-family: var(--font-vazir), "Vazirmatn", sans-serif !important;
|
font-family: var(--font-vazir), "Vazirmatn", sans-serif !important;
|
||||||
@apply bg-medical-gray-50 text-medical-gray-900 antialiased max-w-[100vw] overflow-x-hidden;
|
@apply bg-medical-gray-50 text-medical-gray-900 antialiased w-full max-w-full overflow-x-clip;
|
||||||
font-feature-settings: "ss01", "ss02", "cv01", "cv11";
|
font-feature-settings: "ss01", "ss02", "cv01", "cv11";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,6 +140,12 @@
|
|||||||
background: var(--color-canina-blue);
|
background: var(--color-canina-blue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Mobile catalog filter edge affordances (clean mask-based fade) */
|
||||||
|
.mobile-filter-mask {
|
||||||
|
-webkit-mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent 100%);
|
||||||
|
mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent 100%);
|
||||||
|
}
|
||||||
|
|
||||||
/* Micro horizontal scrollbar for dark backgrounds (catalog etc.) */
|
/* Micro horizontal scrollbar for dark backgrounds (catalog etc.) */
|
||||||
.micro-hscroll-dark {
|
.micro-hscroll-dark {
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Mock child components to verify presence without side-effects
|
||||||
|
vi.mock("../components/Hero", () => ({
|
||||||
|
default: () => <section data-testid="hero-section">Hero</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/SmartAdvisor", () => ({
|
||||||
|
default: () => <section data-testid="smart-advisor-section">SmartAdvisor</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/BannerPlacement", () => ({
|
||||||
|
default: ({ position }: { position: string }) => (
|
||||||
|
<section data-testid={`banner-placement-${position}`}>BannerPlacement {position}</section>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
vi.mock("../components/FeaturedProducts", () => ({
|
||||||
|
default: () => <section data-testid="featured-products-section">FeaturedProducts</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/VetGallery", () => ({
|
||||||
|
default: () => <section data-testid="vet-gallery-section">VetGallery</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/TestimonialsSection", () => ({
|
||||||
|
default: () => <section data-testid="testimonials-section">TestimonialsSection</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/BlogPreviewSection", () => ({
|
||||||
|
default: () => <section data-testid="blog-preview-section">BlogPreviewSection</section>,
|
||||||
|
}));
|
||||||
|
vi.mock("../components/FAQSection", () => ({
|
||||||
|
default: () => <section data-testid="faq-section">FAQSection</section>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/link", () => ({
|
||||||
|
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/image", () => ({
|
||||||
|
default: ({ src, alt, ...props }: any) => <img src={src} alt={alt} {...props} />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../lib/services/api", () => ({
|
||||||
|
default: {
|
||||||
|
get: vi.fn().mockReturnValue(new Promise(() => {})), // Avoid triggering state updates during test
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../lib/store/settingsStore", () => ({
|
||||||
|
useSettingsStore: (selector?: any) => {
|
||||||
|
const s = { getText: (k: string, d: string) => d };
|
||||||
|
return typeof selector === "function" ? selector(s) : s;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import HomeClient from "./HomeClient";
|
||||||
|
|
||||||
|
describe("Home Sections Mobile Retention Gate (UX-35)", () => {
|
||||||
|
it("strictly retains 100% of all core Home sections and feature cards without mobile exclusion or deletion", () => {
|
||||||
|
const { container } = render(<HomeClient initialData={null} />);
|
||||||
|
|
||||||
|
// Verify presence of all major sections
|
||||||
|
expect(screen.getByTestId("hero-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("smart-advisor-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("banner-placement-home_middle")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("featured-products-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("vet-gallery-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("testimonials-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("blog-preview-section")).toBeTruthy();
|
||||||
|
expect(screen.getByTestId("faq-section")).toBeTruthy();
|
||||||
|
|
||||||
|
// Verify navigation specialty cards
|
||||||
|
expect(screen.getByText("داروخانه تخصصی مکملها")).toBeTruthy();
|
||||||
|
expect(screen.getByText("دانشنامه علمی و مقالات")).toBeTruthy();
|
||||||
|
|
||||||
|
// Ensure none of the sections have `hidden` alone as a display class on mobile
|
||||||
|
const sections = container.querySelectorAll("section");
|
||||||
|
expect(sections.length).toBeGreaterThanOrEqual(10);
|
||||||
|
sections.forEach((sec) => {
|
||||||
|
const classList = sec.className.split(/\s+/);
|
||||||
|
expect(classList).not.toContain("hidden");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -71,6 +71,10 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
},
|
},
|
||||||
alternates: {
|
alternates: {
|
||||||
canonical: '/',
|
canonical: '/',
|
||||||
|
languages: {
|
||||||
|
'fa-IR': `${siteUrl}/`,
|
||||||
|
'x-default': `${siteUrl}/`,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
formatDetection: {
|
formatDetection: {
|
||||||
email: false,
|
email: false,
|
||||||
@@ -116,9 +120,9 @@ export default async function RootLayout({
|
|||||||
logo: 'https://canina.ir/assets/images/logo.png',
|
logo: 'https://canina.ir/assets/images/logo.png',
|
||||||
description: 'فروشگاه تخصصی و نماینده انحصاری مکملهای دارویی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی سازمان دامپزشکی کشور.',
|
description: 'فروشگاه تخصصی و نماینده انحصاری مکملهای دارویی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی سازمان دامپزشکی کشور.',
|
||||||
telephone: '+989211231517',
|
telephone: '+989211231517',
|
||||||
email: 'caninairan@gmail.com',
|
email: config.texts.CONTACT_EMAIL || config.texts.contact_email || undefined,
|
||||||
address: {
|
address: {
|
||||||
streetAddress: 'تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹',
|
streetAddress: config.texts.CONTACT_ADDRESS || config.texts.contact_address || undefined,
|
||||||
addressLocality: 'تهران',
|
addressLocality: 'تهران',
|
||||||
addressRegion: 'تهران',
|
addressRegion: 'تهران',
|
||||||
postalCode: '1967812345',
|
postalCode: '1967812345',
|
||||||
@@ -148,7 +152,12 @@ export default async function RootLayout({
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const safeJsonLd = JSON.stringify([orgSchema, webSiteSchema]).replace(/</g, '\\u003c');
|
const rootSchemaGraph = {
|
||||||
|
'@context': 'https://schema.org',
|
||||||
|
'@graph': [orgSchema, webSiteSchema],
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeJsonLd = JSON.stringify(rootSchemaGraph).replace(/</g, '\\u003c');
|
||||||
|
|
||||||
const gaId = config.googleAnalyticsId?.trim();
|
const gaId = config.googleAnalyticsId?.trim();
|
||||||
const isGaEnabled = Boolean(gaId && config.enableGoogleAnalytics !== false);
|
const isGaEnabled = Boolean(gaId && config.enableGoogleAnalytics !== false);
|
||||||
@@ -169,6 +178,12 @@ export default async function RootLayout({
|
|||||||
<link rel="dns-prefetch" href="https://scripts.clarity.ms" />
|
<link rel="dns-prefetch" href="https://scripts.clarity.ms" />
|
||||||
</head>
|
</head>
|
||||||
<body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning>
|
<body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning>
|
||||||
|
<a
|
||||||
|
href="#main-content"
|
||||||
|
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:right-4 focus:z-[999999] focus:px-4 focus:py-2.5 focus:bg-canina-blue focus:text-white focus:font-black focus:rounded-xl focus:shadow-2xl focus:outline-none focus:ring-2 focus:ring-white font-vazir text-sm transition-all"
|
||||||
|
>
|
||||||
|
پرش به محتوای اصلی
|
||||||
|
</a>
|
||||||
{/* Google Tag Manager (noscript fallback) */}
|
{/* Google Tag Manager (noscript fallback) */}
|
||||||
{isGtmEnabled && (
|
{isGtmEnabled && (
|
||||||
<noscript>
|
<noscript>
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import LoginPage from "./page";
|
||||||
|
|
||||||
|
vi.mock("../../components/AuthModal", () => ({
|
||||||
|
default: ({ isOpen }: { isOpen: boolean }) => isOpen ? <div role="dialog">ورود به حساب</div> : null,
|
||||||
|
}));
|
||||||
|
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
|
||||||
|
|
||||||
|
describe("/login route", () => {
|
||||||
|
it("renders the authentication experience instead of a missing-page route", () => {
|
||||||
|
render(<LoginPage />);
|
||||||
|
expect(screen.getByRole("heading", { name: "ورود یا ثبتنام" })).toBeTruthy();
|
||||||
|
expect(screen.getAllByRole("dialog")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import AuthModal from "../../components/AuthModal";
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-medical-gray-50 px-4 py-12" dir="rtl">
|
||||||
|
<h1 className="sr-only">ورود یا ثبتنام</h1>
|
||||||
|
<AuthModal isOpen onClose={() => router.push("/")} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import {
|
||||||
|
Stethoscope,
|
||||||
|
Upload,
|
||||||
|
CheckCircle2,
|
||||||
|
ShieldCheck,
|
||||||
|
FileText,
|
||||||
|
Clock,
|
||||||
|
Send,
|
||||||
|
Phone,
|
||||||
|
Sparkles,
|
||||||
|
AlertCircle
|
||||||
|
} from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import api from "../../lib/services/api";
|
||||||
|
|
||||||
|
export default function PrescriptionPageClient() {
|
||||||
|
const [file, setFile] = useState<File | null>(null);
|
||||||
|
const [phone, setPhone] = useState("");
|
||||||
|
const [petName, setPetName] = useState("");
|
||||||
|
const [petType, setPetType] = useState<"سگ" | "گربه">("سگ");
|
||||||
|
const [notes, setNotes] = useState("");
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const [isSuccess, setIsSuccess] = useState(false);
|
||||||
|
|
||||||
|
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (e.target.files && e.target.files[0]) {
|
||||||
|
setFile(e.target.files[0]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!file) {
|
||||||
|
toast.error("لطفاً تصویر یا فایل PDF نسخه پزشکی را بارگذاری کنید.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cleanPhone = phone.trim();
|
||||||
|
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||||
|
toast.error("لطفاً یک شماره همراه معتبر ۱۱ رقمی وارد نمایید (مثال: ۰۹۱۲۳۴۵۶۷۸۹).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
// 1. Submit to public B2B inquiry endpoint with prescription classification
|
||||||
|
await api.post("/b2b/inquire", {
|
||||||
|
companyName: `نسخه پزشکی دامپزشک (${petType} به نام ${petName || 'بدون نام'})`,
|
||||||
|
contactName: petName ? `سرپرست: ${petName}` : "مراجعهکننده آنلاین",
|
||||||
|
email: `rx-${Date.now()}@canina.ir`,
|
||||||
|
phone: cleanPhone,
|
||||||
|
businessType: `ثبت نسخه دارویی (${petType})`,
|
||||||
|
estimatedVolume: "نسخه تکموردی بیمار",
|
||||||
|
message: `نام پت: ${petName || 'قید نشده'} | گونه: ${petType} | فایل: ${file.name} | توضیحات نسخه: ${notes || 'توضیحی ثبت نشده'}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
setIsSubmitting(false);
|
||||||
|
setIsSuccess(true);
|
||||||
|
toast.success("نسخه پزشکی شما با موفقیت ثبت شد. دامپزشک کشیک کنینا به زودی با شما تماس خواهد گرفت.");
|
||||||
|
} catch {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
toast.error("خطایی در ثبت اطلاعات نسخه رخ داد. لطفاً مجدداً تلاش کنید.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-medical-gray-50 min-h-screen font-vazir py-12 px-4 sm:px-6 lg:px-8" dir="rtl">
|
||||||
|
<div className="max-w-4xl mx-auto space-y-8">
|
||||||
|
|
||||||
|
{/* Header */}
|
||||||
|
<div className="text-center space-y-4">
|
||||||
|
<div className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-full text-xs font-bold shadow-xs">
|
||||||
|
<Stethoscope className="w-4 h-4 text-emerald-600" />
|
||||||
|
سامانه رسمی ارزیابی و تطبیق نسخه دارویی پت
|
||||||
|
</div>
|
||||||
|
<h1 className="text-3xl sm:text-4xl font-black text-medical-gray-900 tracking-tight">
|
||||||
|
ثبت آنلاین نسخه دامپزشک و تطبیق مکملهای <span className="text-canina-blue">کنینا آلمان</span>
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm sm:text-base text-medical-gray-600 max-w-2xl mx-auto leading-relaxed">
|
||||||
|
نسخه تجویزی پزشک معالج همدم خود را بارگذاری نمایید تا کادر دامپزشکان متخصص کنینا ایران مکملهای دارویی اصل و سازگار با دوز تجویزی را ارزیابی و به شما معرفی کنند.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Benefits bar */}
|
||||||
|
<div className="grid sm:grid-cols-3 gap-4">
|
||||||
|
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
|
||||||
|
<ShieldCheck className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-xs font-black text-medical-gray-900">تطبیق دقیق دارویی</h4>
|
||||||
|
<p className="text-[11px] text-medical-gray-500">معادلسازی برندهای آلمانی و دوز</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-xl bg-blue-50 text-canina-blue flex items-center justify-center shrink-0">
|
||||||
|
<Clock className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-xs font-black text-medical-gray-900">پاسخگویی سریع</h4>
|
||||||
|
<p className="text-[11px] text-medical-gray-500">بررسی توسط دامپزشک زیر ۲ ساعت</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
|
||||||
|
<Sparkles className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-xs font-black text-medical-gray-900">مشاوره تغذیه رایگان</h4>
|
||||||
|
<p className="text-[11px] text-medical-gray-500">همراه با راهنمای رژیم و دوز مصرف</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form Card */}
|
||||||
|
<div className="bg-white rounded-3xl border border-medical-gray-200 shadow-xl overflow-hidden p-6 sm:p-10">
|
||||||
|
{isSuccess ? (
|
||||||
|
<div className="text-center py-12 space-y-4">
|
||||||
|
<div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto shadow-lg shadow-emerald-500/20">
|
||||||
|
<CheckCircle2 className="w-10 h-10" />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-2xl font-black text-medical-gray-900">نسخه پزشکی با موفقیت ثبت شد</h3>
|
||||||
|
<p className="text-sm text-medical-gray-600 max-w-md mx-auto leading-relaxed">
|
||||||
|
اطلاعات نسخه برای کادر دامپزشکی کنینا ارسال شد. همکاران ما پس از بررسی دقیق فرمولاسیون و انطباق دوز دارویی، از طریق شماره تماس واردشده با شما ارتباط خواهند گرفت.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setFile(null);
|
||||||
|
setNotes("");
|
||||||
|
setPetName("");
|
||||||
|
setIsSuccess(false);
|
||||||
|
}}
|
||||||
|
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-3 rounded-xl font-bold text-xs shadow-md hover:bg-canina-blue/90 transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
ثبت نسخه جدید دیگر
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
|
||||||
|
{/* Pet Info */}
|
||||||
|
<div className="grid sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
|
||||||
|
گونه حیوان خانگی <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPetType("سگ")}
|
||||||
|
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
|
||||||
|
petType === "سگ"
|
||||||
|
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
|
||||||
|
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
🐶 سگ
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPetType("گربه")}
|
||||||
|
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
|
||||||
|
petType === "گربه"
|
||||||
|
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
|
||||||
|
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
🐱 گربه
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="rx-petName" className="block text-xs font-bold text-medical-gray-700 mb-2">
|
||||||
|
نام همدم (پت)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="rx-petName"
|
||||||
|
type="text"
|
||||||
|
placeholder="مثال: لئو، ببری، جسی..."
|
||||||
|
value={petName}
|
||||||
|
onChange={(e) => setPetName(e.target.value)}
|
||||||
|
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Phone */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="rx-phone" className="block text-xs font-bold text-medical-gray-700 mb-2">
|
||||||
|
شماره تماس همراه (جهت دریافت نتیجه ارزیابی) <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
id="rx-phone"
|
||||||
|
type="tel"
|
||||||
|
required
|
||||||
|
placeholder="۰۹۱۲۳۴۵۶۷۸۹"
|
||||||
|
value={phone}
|
||||||
|
onChange={(e) => setPhone(e.target.value)}
|
||||||
|
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 pl-10 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all dir-ltr text-right"
|
||||||
|
/>
|
||||||
|
<Phone className="w-4 h-4 text-medical-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* File Upload Zone */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
|
||||||
|
بارگذاری تصویر یا فایل PDF نسخه <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<div className="relative border-2 border-dashed border-medical-gray-300 hover:border-canina-blue rounded-3xl p-6 sm:p-8 text-center transition-all bg-medical-gray-50/50 hover:bg-blue-50/20">
|
||||||
|
<input
|
||||||
|
id="rx-file-input"
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/webp,application/pdf"
|
||||||
|
required
|
||||||
|
onChange={handleFileChange}
|
||||||
|
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
|
||||||
|
/>
|
||||||
|
<div className="space-y-3 pointer-events-none">
|
||||||
|
<div className="w-14 h-14 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center mx-auto">
|
||||||
|
<Upload className="w-7 h-7" />
|
||||||
|
</div>
|
||||||
|
{file ? (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-black text-medical-gray-900">{file.name}</p>
|
||||||
|
<p className="text-xs text-emerald-600 font-bold">فایل با موفقیت انتخاب شد (برای تغییر کلیک کنید)</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-black text-medical-gray-900">
|
||||||
|
برای انتخاب فایل یا عکس نسخه، اینجا کلیک کنید یا فایل را بکشید
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-medical-gray-400">
|
||||||
|
فرمتهای مجاز: JPG, PNG, WEBP یا PDF (حداکثر ۱۰ مگابایت)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Notes */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="rx-notes" className="block text-xs font-bold text-medical-gray-700 mb-2">
|
||||||
|
توضیحات تکمیلی یا علائم حیوان (اختیاری)
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="rx-notes"
|
||||||
|
rows={3}
|
||||||
|
placeholder="اگر حیوان به ماده غذایی خاصی حساسیت دارد یا داروی همزمانی مصرف میکند در اینجا ذکر فرمایید..."
|
||||||
|
value={notes}
|
||||||
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
|
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Submit Button */}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
className="w-full bg-canina-blue hover:bg-canina-blue/90 text-white font-black text-base py-4 rounded-2xl shadow-xl shadow-canina-blue/20 transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isSubmitting ? (
|
||||||
|
<span>در حال ارسال نسخه و ثبت درخواست...</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Send className="w-5 h-5" />
|
||||||
|
<span>ارسال و ثبت نسخه جهت ارزیابی دامپزشک</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import React from "react";
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import PrescriptionPageClient from "./PrescriptionPageClient";
|
||||||
|
import { getPageMetadata } from "../../lib/seo";
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
return getPageMetadata('prescriptions', {
|
||||||
|
canonicalPath: '/prescriptions',
|
||||||
|
fallbackTitle: 'ثبت و ارزیابی نسخه دامپزشک | مشاوره تخصصی دارویی کنینا ایران',
|
||||||
|
fallbackDesc: 'سامانه آنلاین آپلود و تحلیل نسخه دامپزشک جهت تطبیق با مکملهای دارویی اصل Canina Pharma آلمان با نظارت کادر مجرب دامپزشکان.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PrescriptionPage() {
|
||||||
|
return <PrescriptionPageClient />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
|
||||||
|
const mockPost = vi.fn().mockResolvedValue({ data: { success: true } });
|
||||||
|
vi.mock("axios", () => {
|
||||||
|
const mAxios = {
|
||||||
|
post: vi.fn(() => Promise.resolve({ data: { success: true } })),
|
||||||
|
get: vi.fn(() => Promise.resolve({ data: { success: true } })),
|
||||||
|
interceptors: {
|
||||||
|
request: { use: vi.fn(), eject: vi.fn() },
|
||||||
|
response: { use: vi.fn(), eject: vi.fn() },
|
||||||
|
},
|
||||||
|
create: () => mAxios,
|
||||||
|
};
|
||||||
|
return { default: mAxios };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("sonner", () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import api from "../../lib/services/api";
|
||||||
|
import PrescriptionPageClient from "./PrescriptionPageClient";
|
||||||
|
|
||||||
|
describe("PrescriptionPageClient Suite (B2B-03)", () => {
|
||||||
|
it("renders online prescription portal and submits without requiring login", async () => {
|
||||||
|
const { container } = render(<PrescriptionPageClient />);
|
||||||
|
|
||||||
|
const phoneInput = container.querySelector("#rx-phone") as HTMLInputElement;
|
||||||
|
const petNameInput = container.querySelector("#rx-petName") as HTMLInputElement;
|
||||||
|
const fileInput = container.querySelector("#rx-file-input") as HTMLInputElement;
|
||||||
|
const form = container.querySelector("form") as HTMLFormElement;
|
||||||
|
|
||||||
|
expect(phoneInput).not.toBeNull();
|
||||||
|
expect(fileInput).not.toBeNull();
|
||||||
|
expect(form).not.toBeNull();
|
||||||
|
|
||||||
|
// Create fake file
|
||||||
|
const fakeFile = new File(["dummy content"], "prescription.jpg", { type: "image/jpeg" });
|
||||||
|
|
||||||
|
fireEvent.change(phoneInput, { target: { value: "09121114455" } });
|
||||||
|
fireEvent.change(petNameInput, { target: { value: "لئو" } });
|
||||||
|
fireEvent.change(fileInput, { target: { files: [fakeFile] } });
|
||||||
|
|
||||||
|
fireEvent.submit(form);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(api.post).toHaveBeenCalledWith(
|
||||||
|
"/b2b/inquire",
|
||||||
|
expect.objectContaining({
|
||||||
|
phone: "09121114455",
|
||||||
|
companyName: expect.stringContaining("لئو"),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Mock next/navigation
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
usePathname: () => "/login",
|
||||||
|
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
|
||||||
|
useSearchParams: () => new URLSearchParams(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/link", () => ({
|
||||||
|
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/image", () => ({
|
||||||
|
default: (props: any) => <img {...props} />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock sub-components with exact path matching
|
||||||
|
vi.mock("../components/AuthModal", () => ({
|
||||||
|
default: ({ isOpen, onClose }: any) => (
|
||||||
|
<div data-testid="auth-modal" data-isopen={String(isOpen)}>
|
||||||
|
<button onClick={onClose}>بستن</button>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/CartDrawer", () => ({
|
||||||
|
default: ({ isOpen, onCheckout, onShopNavigate }: any) => (
|
||||||
|
<div data-testid="cart-drawer" data-isopen={String(isOpen)}>
|
||||||
|
<button onClick={onCheckout}>تکمیل سفارش</button>
|
||||||
|
<button onClick={onShopNavigate}>فروشگاه</button>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/PetProfile", () => ({
|
||||||
|
default: () => <div data-testid="pet-profile-component">Pet Profile</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/VideosPage", () => ({
|
||||||
|
default: ({ initialVideos }: any) => (
|
||||||
|
<div data-testid="videos-page-component">Videos: {initialVideos?.length || 0}</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../components/SmartAdvisor", () => ({
|
||||||
|
default: () => <div data-testid="smart-advisor-component">Smart Advisor</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import LoginPage from "./login/page";
|
||||||
|
import CartPage from "./cart/page";
|
||||||
|
import ProfilePage from "./profile/page";
|
||||||
|
import VideosPage from "./videos/page";
|
||||||
|
import SmartAdvisorPage from "./smart-advisor/page";
|
||||||
|
|
||||||
|
describe("Lightweight Utility Routes and Responsive Layouts (UX-29)", () => {
|
||||||
|
it("renders LoginPage with minimal semantic wrapper and single accessible h1", () => {
|
||||||
|
const { container } = render(<LoginPage />);
|
||||||
|
const h1 = screen.getByRole("heading", { level: 1 });
|
||||||
|
expect(h1.textContent).toContain("ورود یا ثبتنام");
|
||||||
|
expect(screen.getByTestId("auth-modal")).toBeTruthy();
|
||||||
|
const main = container.querySelector("main");
|
||||||
|
expect(main).not.toBeNull();
|
||||||
|
expect(main?.getAttribute("dir")).toBe("rtl");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders CartPage with semantic main wrapper and single accessible h1", () => {
|
||||||
|
const { container } = render(<CartPage />);
|
||||||
|
const h1 = screen.getByRole("heading", { level: 1 });
|
||||||
|
expect(h1.textContent).toContain("سبد خرید");
|
||||||
|
expect(screen.getByTestId("cart-drawer")).toBeTruthy();
|
||||||
|
const main = container.querySelector("main");
|
||||||
|
expect(main).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders ProfilePage cleanly delegating to PetProfile component", () => {
|
||||||
|
render(<ProfilePage />);
|
||||||
|
expect(screen.getByTestId("pet-profile-component")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders VideosPage cleanly passing initial videos dataset", async () => {
|
||||||
|
const component = await VideosPage();
|
||||||
|
render(component);
|
||||||
|
expect(screen.getByTestId("videos-page-component")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders SmartAdvisorPage with semantic breadcrumbs, h1 and advisor container", () => {
|
||||||
|
render(<SmartAdvisorPage />);
|
||||||
|
const h1 = screen.getByRole("heading", { level: 1 });
|
||||||
|
expect(h1.textContent).toMatch(/مشاوره تخصصی و راهنمای/);
|
||||||
|
expect(screen.getByTestId("smart-advisor-component")).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -26,13 +26,19 @@ export default function robots(): MetadataRoute.Robots {
|
|||||||
'/dashboard/',
|
'/dashboard/',
|
||||||
'/checkout/',
|
'/checkout/',
|
||||||
'/profile/',
|
'/profile/',
|
||||||
'/api/'
|
'/api/',
|
||||||
|
'/*?*sort=',
|
||||||
|
'/*?*page=',
|
||||||
|
'/*?*order=',
|
||||||
|
'/track/',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sitemap: [
|
sitemap: [
|
||||||
`${baseUrl}/sitemap.xml`,
|
`${baseUrl}/sitemap.xml`,
|
||||||
`${baseUrl}/sitemap-products.xml`,
|
`${baseUrl}/sitemap-products.xml`,
|
||||||
`${baseUrl}/sitemap-categories.xml`,
|
`${baseUrl}/sitemap-categories.xml`,
|
||||||
|
`${baseUrl}/sitemap-blog.xml`,
|
||||||
|
`${baseUrl}/sitemap-wiki.xml`,
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
canonicalPath: '/search',
|
canonicalPath: '/search',
|
||||||
fallbackTitle: 'جستجوی هوشمند مکملها و دانشنامه سلامت',
|
fallbackTitle: 'جستجوی هوشمند مکملها و دانشنامه سلامت',
|
||||||
fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماریها، علائم بالینی و مقالات سلامت کنینا ایران.',
|
fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماریها، علائم بالینی و مقالات سلامت کنینا ایران.',
|
||||||
|
noIndex: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { notFound } from 'next/navigation';
|
||||||
import ProductPage from "../../../components/ProductPage";
|
import ProductPage from "../../../components/ProductPage";
|
||||||
import { productService } from "../../../lib/services/productService";
|
import { productService } from "../../../lib/services/productService";
|
||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
@@ -133,7 +134,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
|
|||||||
const product = await productService.getProductBySlug(resolvedParams.slug);
|
const product = await productService.getProductBySlug(resolvedParams.slug);
|
||||||
|
|
||||||
if (!product) {
|
if (!product) {
|
||||||
return <ProductPage productSlug={resolvedParams.slug} />;
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||||
@@ -349,7 +350,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}>
|
}>
|
||||||
<ProductPage productSlug={resolvedParams.slug} />
|
<ProductPage productSlug={resolvedParams.slug} initialProduct={product} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import ArchivePage from "../../components/ArchivePage";
|
import ArchivePage from "../../components/ArchivePage";
|
||||||
import { getPageMetadata } from "../../lib/seo";
|
import { getPageMetadata } from "../../lib/seo";
|
||||||
|
import { productService } from "../../lib/services/productService";
|
||||||
|
import type { PetType } from "../../lib/data/products";
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
searchParams,
|
searchParams,
|
||||||
@@ -41,6 +43,9 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [
|
|||||||
const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : "";
|
const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : "";
|
||||||
const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : "";
|
const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : "";
|
||||||
const symptoms = symptomsParam || (symptomSingle ? symptomSingle : "");
|
const symptoms = symptomsParam || (symptomSingle ? symptomSingle : "");
|
||||||
|
const pageParam = typeof resolvedParams.page === "string" ? parseInt(resolvedParams.page, 10) : 1;
|
||||||
|
const initialPage = isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
|
||||||
|
const { data: initialProducts } = await productService.getProducts({ category, petType: petType as PetType | "all", query: search, symptom: symptomSingle, limit: 999 });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ArchivePage
|
<ArchivePage
|
||||||
@@ -48,6 +53,8 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [
|
|||||||
initialSearch={search}
|
initialSearch={search}
|
||||||
initialPetType={petType}
|
initialPetType={petType}
|
||||||
initialSymptoms={symptoms}
|
initialSymptoms={symptoms}
|
||||||
|
initialProducts={initialProducts}
|
||||||
|
initialPage={initialPage}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
export const revalidate = 3600; // Revalidate every hour
|
||||||
|
|
||||||
|
type SitemapBlog = {
|
||||||
|
slug: string;
|
||||||
|
noIndex?: boolean;
|
||||||
|
status: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
createdAt?: string;
|
||||||
|
featured?: boolean;
|
||||||
|
title?: string;
|
||||||
|
imageUrl?: string;
|
||||||
|
ogImage?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||||
|
const apiUrl =
|
||||||
|
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||||
|
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||||
|
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||||
|
|
||||||
|
const blogRoutes: SitemapBlog[] = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
let page = 1;
|
||||||
|
let lastPage = 1;
|
||||||
|
do {
|
||||||
|
const res = await fetch(`${apiBase}/blogs?page=${page}&limit=20`, { cache: 'no-store' });
|
||||||
|
if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`);
|
||||||
|
const data = await res.json();
|
||||||
|
const blogsList: SitemapBlog[] = data.data || [];
|
||||||
|
if (!blogsList.length) break;
|
||||||
|
|
||||||
|
const validBlogs = blogsList.filter((b) => !b.noIndex && b.status === 'PUBLISHED');
|
||||||
|
blogRoutes.push(...validBlogs);
|
||||||
|
|
||||||
|
lastPage = Number(data.meta?.lastPage) || 1;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= lastPage);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch blogs for sitemap-blog.xml:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
const urlsXml = blogRoutes
|
||||||
|
.map((blog) => {
|
||||||
|
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
|
||||||
|
const lastmod = blog.updatedAt
|
||||||
|
? new Date(blog.updatedAt).toISOString()
|
||||||
|
: blog.createdAt
|
||||||
|
? new Date(blog.createdAt).toISOString()
|
||||||
|
: new Date().toISOString();
|
||||||
|
const priority = blog.featured ? '0.9' : '0.7';
|
||||||
|
const primaryImg = blog.ogImage || blog.imageUrl;
|
||||||
|
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
|
||||||
|
|
||||||
|
const imageTag = primaryImg
|
||||||
|
? `\n <image:image>\n <image:loc>${
|
||||||
|
primaryImg.startsWith('http') ? primaryImg : `${baseUrl}${primaryImg.startsWith('/') ? '' : '/'}${primaryImg}`
|
||||||
|
}</image:loc>\n <image:title><![CDATA[${title}]]></image:title>\n </image:image>`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>${priority}</priority>${imageTag}\n </url>`;
|
||||||
|
})
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n${urlsXml}\n</urlset>`;
|
||||||
|
|
||||||
|
return new NextResponse(xmlContent, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/xml; charset=utf-8',
|
||||||
|
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
export const revalidate = 86400; // Revalidate daily
|
||||||
|
|
||||||
|
type SitemapWikiTerm = {
|
||||||
|
key: string;
|
||||||
|
term: string;
|
||||||
|
definition?: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
createdAt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||||
|
const apiUrl =
|
||||||
|
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||||
|
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||||
|
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||||
|
|
||||||
|
const wikiRoutes: SitemapWikiTerm[] = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
let page = 1;
|
||||||
|
let lastPage = 1;
|
||||||
|
do {
|
||||||
|
const res = await fetch(`${apiBase}/wiki?page=${page}&limit=50`, { cache: 'no-store' });
|
||||||
|
if (!res.ok) throw new Error(`Wiki sitemap request failed: ${res.status}`);
|
||||||
|
const data = await res.json();
|
||||||
|
const wikiList: SitemapWikiTerm[] = data.data || [];
|
||||||
|
if (!wikiList.length) break;
|
||||||
|
|
||||||
|
wikiRoutes.push(...wikiList);
|
||||||
|
|
||||||
|
lastPage = Number(data.meta?.lastPage) || 1;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= lastPage);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch wiki terms for sitemap-wiki.xml:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
const urlsXml = wikiRoutes
|
||||||
|
.map((item) => {
|
||||||
|
const loc = `${baseUrl}/wiki/${encodeURIComponent(item.key)}`;
|
||||||
|
const lastmod = item.updatedAt
|
||||||
|
? new Date(item.updatedAt).toISOString()
|
||||||
|
: item.createdAt
|
||||||
|
? new Date(item.createdAt).toISOString()
|
||||||
|
: new Date().toISOString();
|
||||||
|
|
||||||
|
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>0.8</priority>\n </url>`;
|
||||||
|
})
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urlsXml}\n</urlset>`;
|
||||||
|
|
||||||
|
return new NextResponse(xmlContent, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/xml; charset=utf-8',
|
||||||
|
'Cache-Control': 'public, max-age=86400, s-maxage=86400, stale-while-revalidate=604800',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import sitemap from './sitemap';
|
||||||
|
|
||||||
|
vi.mock('../lib/services/productService', () => ({
|
||||||
|
productService: {
|
||||||
|
getProducts: vi.fn().mockResolvedValue({ data: [] }),
|
||||||
|
getActiveFilters: vi.fn().mockResolvedValue({ categories: [] }),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||||
|
|
||||||
|
describe('sitemap blog retrieval', () => {
|
||||||
|
it('retrieves every page without putting full blog content in the Next data cache', async () => {
|
||||||
|
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api/');
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://stage.canina.ir');
|
||||||
|
const fetchMock = vi.fn()
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [
|
||||||
|
{ slug: 'first', status: 'PUBLISHED', updatedAt: '2026-10-01', featured: true },
|
||||||
|
{ slug: 'hidden', status: 'PUBLISHED', noIndex: true },
|
||||||
|
{ slug: 'draft', status: 'DRAFT' },
|
||||||
|
], meta: { lastPage: 2 } }) })
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [
|
||||||
|
{ slug: 'last', status: 'PUBLISHED' },
|
||||||
|
], meta: { lastPage: 2 } }) });
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
const routes = await sitemap();
|
||||||
|
expect(fetchMock.mock.calls).toEqual([
|
||||||
|
['http://backend:3000/api/blogs?page=1&limit=10', { cache: 'no-store' }],
|
||||||
|
['http://backend:3000/api/blogs?page=2&limit=10', { cache: 'no-store' }],
|
||||||
|
]);
|
||||||
|
const blogs = routes.filter(r => r.url.includes('/blog/'));
|
||||||
|
expect(blogs.map(r => r.url)).toEqual(['https://stage.canina.ir/blog/first', 'https://stage.canina.ir/blog/last']);
|
||||||
|
expect(blogs[0].priority).toBe(0.9);
|
||||||
|
expect(blogs[0].lastModified).toEqual(new Date('2026-10-01'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('terminates on an empty page even when pagination metadata is stale', async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { lastPage: 999 } }) });
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
expect((await sitemap()).filter(r => r.url.includes('/blog/'))).toEqual([]);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back without publishing a partial blog sitemap when a later page fails', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn()
|
||||||
|
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [{ slug: 'first', status: 'PUBLISHED' }], meta: { lastPage: 2 } }) })
|
||||||
|
.mockResolvedValueOnce({ ok: false, status: 503 }));
|
||||||
|
const routes = await sitemap();
|
||||||
|
expect(routes.filter(r => r.url.includes('/blog/'))).toEqual([]);
|
||||||
|
expect(routes.some(r => r.url.endsWith('/shop'))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -30,12 +30,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
|||||||
changeFrequency: 'weekly',
|
changeFrequency: 'weekly',
|
||||||
priority: 0.8,
|
priority: 0.8,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
url: `${baseUrl}/search`,
|
|
||||||
lastModified: new Date(),
|
|
||||||
changeFrequency: 'weekly',
|
|
||||||
priority: 0.5,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
url: `${baseUrl}/about`,
|
url: `${baseUrl}/about`,
|
||||||
lastModified: new Date(),
|
lastModified: new Date(),
|
||||||
@@ -89,20 +84,30 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
|||||||
let blogRoutes: MetadataRoute.Sitemap = [];
|
let blogRoutes: MetadataRoute.Sitemap = [];
|
||||||
try {
|
try {
|
||||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||||
const apiBase = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
|
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||||
const res = await fetch(`${apiBase}/blogs?page=1&limit=999`, { next: { revalidate: 3600 } });
|
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||||
if (res.ok) {
|
type SitemapBlog = { slug: string; noIndex?: boolean; status: string; updatedAt?: string; featured?: boolean };
|
||||||
|
// The public list includes article bodies. Keep requests small and bypass
|
||||||
|
// Next's 2MB per-entry data cache, even for an unusually large article.
|
||||||
|
let page = 1;
|
||||||
|
let lastPage = 1;
|
||||||
|
do {
|
||||||
|
const res = await fetch(`${apiBase}/blogs?page=${page}&limit=10`, { cache: 'no-store' });
|
||||||
|
if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const blogsList = data.data || [];
|
const blogsList: SitemapBlog[] = data.data || [];
|
||||||
blogRoutes = blogsList
|
if (!blogsList.length) break;
|
||||||
.filter((b: any) => !b.noIndex && b.status === 'PUBLISHED')
|
blogRoutes.push(...blogsList
|
||||||
.map((b: any) => ({
|
.filter((b) => !b.noIndex && b.status === 'PUBLISHED')
|
||||||
|
.map((b): MetadataRoute.Sitemap[number] => ({
|
||||||
url: `${baseUrl}/blog/${b.slug}`,
|
url: `${baseUrl}/blog/${b.slug}`,
|
||||||
lastModified: b.updatedAt ? new Date(b.updatedAt) : new Date(),
|
lastModified: b.updatedAt ? new Date(b.updatedAt) : new Date(),
|
||||||
changeFrequency: 'weekly',
|
changeFrequency: 'weekly',
|
||||||
priority: b.featured ? 0.9 : 0.7,
|
priority: b.featured ? 0.9 : 0.7,
|
||||||
}));
|
})));
|
||||||
}
|
lastPage = Number(data.meta?.lastPage) || 1;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= lastPage);
|
||||||
} catch {
|
} catch {
|
||||||
// Fallback if backend not reachable at build time
|
// Fallback if backend not reachable at build time
|
||||||
blogRoutes = [];
|
blogRoutes = [];
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import robots from './robots';
|
||||||
|
import { GET as getBlogSitemap } from './sitemap-blog.xml/route';
|
||||||
|
import { GET as getWikiSitemap } from './sitemap-wiki.xml/route';
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.unstubAllEnvs();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
|
||||||
|
it('registers sitemap-blog.xml and sitemap-wiki.xml in robots.ts', () => {
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
|
||||||
|
vi.stubEnv('NODE_ENV', 'production');
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||||
|
|
||||||
|
const config = robots();
|
||||||
|
const sitemaps = Array.isArray(config.sitemap) ? config.sitemap : [config.sitemap];
|
||||||
|
|
||||||
|
expect(sitemaps).toContain('https://canina.ir/sitemap.xml');
|
||||||
|
expect(sitemaps).toContain('https://canina.ir/sitemap-products.xml');
|
||||||
|
expect(sitemaps).toContain('https://canina.ir/sitemap-categories.xml');
|
||||||
|
expect(sitemaps).toContain('https://canina.ir/sitemap-blog.xml');
|
||||||
|
expect(sitemaps).toContain('https://canina.ir/sitemap-wiki.xml');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('generates sitemap-blog.xml correctly with published blogs and image tags', async () => {
|
||||||
|
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||||
|
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
slug: 'puppy-nutrition',
|
||||||
|
title: 'تغذیه توله سگ',
|
||||||
|
status: 'PUBLISHED',
|
||||||
|
updatedAt: '2026-10-10T12:00:00.000Z',
|
||||||
|
featured: true,
|
||||||
|
imageUrl: '/uploads/puppy.jpg',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'hidden-blog',
|
||||||
|
title: 'مقاله پیشنویس',
|
||||||
|
status: 'DRAFT',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
meta: { lastPage: 1 },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const res = await getBlogSitemap();
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const xml = await res.text();
|
||||||
|
|
||||||
|
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
|
||||||
|
expect(xml).toContain('<priority>0.9</priority>');
|
||||||
|
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
|
||||||
|
expect(xml).toContain('تغذیه توله سگ');
|
||||||
|
expect(xml).not.toContain('hidden-blog');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('generates sitemap-wiki.xml correctly with scientific terms', async () => {
|
||||||
|
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||||
|
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
key: 'omega-3',
|
||||||
|
term: 'امگا ۳',
|
||||||
|
updatedAt: '2026-09-01T10:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
meta: { lastPage: 1 },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const res = await getWikiSitemap();
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const xml = await res.text();
|
||||||
|
|
||||||
|
expect(xml).toContain('<loc>https://canina.ir/wiki/omega-3</loc>');
|
||||||
|
expect(xml).toContain('<priority>0.8</priority>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { notFound } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react';
|
import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react';
|
||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
@@ -11,15 +12,38 @@ const apiBase = API_URL.endsWith('/api') ? API_URL : `${API_URL.replace(/\/$/, '
|
|||||||
|
|
||||||
async function getWikiTerm(key: string) {
|
async function getWikiTerm(key: string) {
|
||||||
try {
|
try {
|
||||||
|
// 1. Try scientific terms endpoint
|
||||||
const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, {
|
const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, {
|
||||||
next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] }
|
next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] }
|
||||||
});
|
});
|
||||||
if (!res.ok) return null;
|
if (res.ok) {
|
||||||
return await res.json();
|
return await res.json();
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[Wiki] Error fetching term:', error);
|
console.warn('[Wiki] /wiki/:key failed, trying /ingredients fallback:', error);
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 2. Fallback to ingredients endpoint if slug is an ingredient slug
|
||||||
|
const ingRes = await fetch(`${apiBase}/ingredients/${encodeURIComponent(key)}`, {
|
||||||
|
next: { revalidate: 3600, tags: ['ingredients', `ing-${key}`] }
|
||||||
|
});
|
||||||
|
if (ingRes.ok) {
|
||||||
|
const ing = await ingRes.json();
|
||||||
|
return {
|
||||||
|
key: ing.slug,
|
||||||
|
term: ing.nameFa || ing.nameEn || ing.slug,
|
||||||
|
definition: ing.description || `بررسی تخصصی ترکیب دارویی و خواص ${ing.nameFa || ing.nameEn} در کاتالوگ مکملهای کنینا آلمان.`,
|
||||||
|
metaTitle: `خواص دارویی ${ing.nameFa || ing.nameEn} | دانشنامه کنینا ایران`,
|
||||||
|
metaDescription: (ing.description || '').slice(0, 155),
|
||||||
|
wikiId: ing.slug,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Wiki] Error fetching ingredient fallback:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getRelatedProducts(termName: string) {
|
async function getRelatedProducts(termName: string) {
|
||||||
@@ -81,15 +105,7 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug:
|
|||||||
const term = await getWikiTerm(slug);
|
const term = await getWikiTerm(slug);
|
||||||
|
|
||||||
if (!term) {
|
if (!term) {
|
||||||
return (
|
notFound();
|
||||||
<div className="min-h-[50vh] flex flex-col items-center justify-center font-vazir text-center px-4" dir="rtl">
|
|
||||||
<h1 className="text-3xl font-black text-medical-gray-900 mb-4">ترکیب علمی یافت نشد</h1>
|
|
||||||
<Link href="/wiki" className="text-canina-blue font-bold flex items-center gap-2">
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
بازگشت به دانشنامه
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const relatedProducts = await getRelatedProducts(term.term);
|
const relatedProducts = await getRelatedProducts(term.term);
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { useUserStore } from "../lib/store/userStore";
|
||||||
import React, { useState, useMemo, useEffect, useCallback } from "react";
|
import React, { useState, useMemo, useEffect, useCallback } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { toPersian, isProductOutOfStock } from "../lib/utils";
|
import { toPersian, isProductOutOfStock } from "../lib/utils";
|
||||||
import { Product, PetType } from "../lib/data/products";
|
import { Product, PetType } from "../lib/data/products";
|
||||||
import { usePetStore } from "../lib/store/usePetStore";
|
import { usePetStore } from "../lib/store/usePetStore";
|
||||||
@@ -76,11 +78,18 @@ const CATEGORY_MAP: Record<string, { category?: string; query?: string; symptoms
|
|||||||
"شستشوی چشم": { category: "special-care", query: "چشم" },
|
"شستشوی چشم": { category: "special-care", query: "چشم" },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const orderProductsByAvailability = (products: Product[]): Product[] => {
|
||||||
|
const available = products.filter(product => !isProductOutOfStock(product));
|
||||||
|
const unavailable = products.filter(product => isProductOutOfStock(product));
|
||||||
|
return [...available, ...unavailable];
|
||||||
|
};
|
||||||
|
|
||||||
export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product }) => {
|
export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product }) => {
|
||||||
const { addItem } = useCartStore();
|
const { addItem } = useCartStore();
|
||||||
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
|
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
|
||||||
const [isAdding, setIsAdding] = useState(false);
|
const [isAdding, setIsAdding] = useState(false);
|
||||||
const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
|
const isLoggedIn = useUserStore(s => s.isLoggedIn);
|
||||||
|
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
|
||||||
const { showPrices, allowCart, showPreorderBtn } = useCatalogMode();
|
const { showPrices, allowCart, showPreorderBtn } = useCatalogMode();
|
||||||
const productUrl = `/shop/${product.slug || product.id}`;
|
const productUrl = `/shop/${product.slug || product.id}`;
|
||||||
|
|
||||||
@@ -122,15 +131,11 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
|
|||||||
href={productUrl}
|
href={productUrl}
|
||||||
className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative"
|
className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative"
|
||||||
>
|
>
|
||||||
{product.specialBadge && (
|
{/* SpecialBadge moved below image to avoid covering product photo */}
|
||||||
<div className="absolute top-4 right-4 z-10 bg-canina-blue text-white text-2xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-lg">
|
|
||||||
{product.specialBadge}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{compatibility && (
|
{compatibility && (
|
||||||
<div className={`absolute top-14 right-4 z-10 text-3xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-md flex items-center gap-1 ${compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
|
<div className={`absolute top-4 right-4 z-10 text-3xs font-black uppercase tracking-widest px-2.5 py-1 rounded-full shadow-md flex items-center gap-1 backdrop-blur-xs ${compatibility.type === 'alert' ? 'bg-amber-500/90 text-white' :
|
||||||
compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
|
compatibility.type === 'success' ? 'bg-emerald-600/90 text-white' : 'bg-canina-blue/90 text-white'
|
||||||
}`}>
|
}`}>
|
||||||
{compatibility.type === 'alert' ? (
|
{compatibility.type === 'alert' ? (
|
||||||
forBoth ? (
|
forBoth ? (
|
||||||
@@ -177,6 +182,13 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="p-6 flex flex-col flex-1">
|
<div className="p-6 flex flex-col flex-1">
|
||||||
|
{product.specialBadge && (
|
||||||
|
<div className="mb-2">
|
||||||
|
<span className="inline-block bg-canina-blue/10 text-canina-blue border border-canina-blue/20 text-[10px] font-black px-2.5 py-1 rounded-lg line-clamp-1 font-vazir" title={product.specialBadge}>
|
||||||
|
{product.specialBadge}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div>
|
<div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div>
|
||||||
<div className="flex flex-col gap-1 mb-3">
|
<div className="flex flex-col gap-1 mb-3">
|
||||||
<h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir">
|
<h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir">
|
||||||
@@ -266,7 +278,8 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
|
|||||||
const { addItem } = useCartStore();
|
const { addItem } = useCartStore();
|
||||||
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
|
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
|
||||||
const [isAdding, setIsAdding] = useState(false);
|
const [isAdding, setIsAdding] = useState(false);
|
||||||
const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
|
const isLoggedIn = useUserStore(s => s.isLoggedIn);
|
||||||
|
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
|
||||||
const productUrl = `/shop/${product.slug || product.id}`;
|
const productUrl = `/shop/${product.slug || product.id}`;
|
||||||
|
|
||||||
const handleAddToCart = (e: React.MouseEvent) => {
|
const handleAddToCart = (e: React.MouseEvent) => {
|
||||||
@@ -318,11 +331,7 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
|
|||||||
className="w-full h-full group-hover:scale-105 transition-transform duration-500"
|
className="w-full h-full group-hover:scale-105 transition-transform duration-500"
|
||||||
imgClassName="w-full h-full object-contain"
|
imgClassName="w-full h-full object-contain"
|
||||||
/>
|
/>
|
||||||
{product.specialBadge && (
|
{/* List specialBadge moved below */}
|
||||||
<div className="absolute top-1 right-1 z-10 bg-canina-blue text-white text-[9px] font-black uppercase px-1.5 py-0.5 rounded-md shadow-xs">
|
|
||||||
{product.specialBadge}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="absolute bottom-1 left-1 flex gap-1">
|
<div className="absolute bottom-1 left-1 flex gap-1">
|
||||||
{forDog && (
|
{forDog && (
|
||||||
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ">
|
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ">
|
||||||
@@ -443,12 +452,18 @@ export default function ArchivePage({
|
|||||||
initialCategory = "all",
|
initialCategory = "all",
|
||||||
initialSearch = "",
|
initialSearch = "",
|
||||||
initialPetType = "all",
|
initialPetType = "all",
|
||||||
initialSymptoms = ""
|
initialSymptoms = "",
|
||||||
|
initialProducts = [],
|
||||||
|
initialPage = 1,
|
||||||
|
initialLimit = 12
|
||||||
}: {
|
}: {
|
||||||
initialCategory?: string,
|
initialCategory?: string,
|
||||||
initialSearch?: string,
|
initialSearch?: string,
|
||||||
initialPetType?: string,
|
initialPetType?: string,
|
||||||
initialSymptoms?: string
|
initialSymptoms?: string,
|
||||||
|
initialProducts?: Product[],
|
||||||
|
initialPage?: number,
|
||||||
|
initialLimit?: number
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const getText = useSettingsStore(state => state.getText);
|
const getText = useSettingsStore(state => state.getText);
|
||||||
@@ -457,10 +472,18 @@ export default function ArchivePage({
|
|||||||
const [activeSymptoms, setActiveSymptoms] = useState<string[]>(initialSymptoms ? initialSymptoms.split(',') : []);
|
const [activeSymptoms, setActiveSymptoms] = useState<string[]>(initialSymptoms ? initialSymptoms.split(',') : []);
|
||||||
const [searchQuery, setSearchQuery] = useState(initialSearch);
|
const [searchQuery, setSearchQuery] = useState(initialSearch);
|
||||||
const [isUpdating, setIsUpdating] = useState(false);
|
const [isUpdating, setIsUpdating] = useState(false);
|
||||||
const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
|
const [fetchError, setFetchError] = useState<string | null>(null);
|
||||||
|
const [filteredProducts, setFilteredProducts] = useState<Product[]>(() => orderProductsByAvailability(initialProducts));
|
||||||
const [sortBy, setSortBy] = useState<string>("createdAt");
|
const [sortBy, setSortBy] = useState<string>("createdAt");
|
||||||
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
|
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
|
||||||
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
|
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
|
||||||
|
const [currentPage, setCurrentPage] = useState<number>(() => Math.max(1, initialPage));
|
||||||
|
const pageSize = Math.max(1, initialLimit);
|
||||||
|
const [isMounted, setIsMounted] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsMounted(true);
|
||||||
|
}, []);
|
||||||
const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false);
|
const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false);
|
||||||
const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false);
|
const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false);
|
||||||
|
|
||||||
@@ -518,6 +541,7 @@ export default function ArchivePage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms };
|
lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms };
|
||||||
|
setCurrentPage(initialPage || 1);
|
||||||
|
|
||||||
// Normalize Input
|
// Normalize Input
|
||||||
const normSearch = (initialSearch || "").trim().toLowerCase();
|
const normSearch = (initialSearch || "").trim().toLowerCase();
|
||||||
@@ -537,6 +561,7 @@ export default function ArchivePage({
|
|||||||
setSelectedPet((initialPetType as PetType) || "all");
|
setSelectedPet((initialPetType as PetType) || "all");
|
||||||
setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []);
|
setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []);
|
||||||
}
|
}
|
||||||
|
setCurrentPage(1);
|
||||||
}, [initialCategory, initialSearch, initialPetType, initialSymptoms]);
|
}, [initialCategory, initialSearch, initialPetType, initialSymptoms]);
|
||||||
|
|
||||||
// Update URL Query Parameters
|
// Update URL Query Parameters
|
||||||
@@ -546,15 +571,20 @@ export default function ArchivePage({
|
|||||||
if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet);
|
if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet);
|
||||||
if (searchQuery) params.set('search', searchQuery);
|
if (searchQuery) params.set('search', searchQuery);
|
||||||
if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(','));
|
if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(','));
|
||||||
|
if (currentPage > 1) params.set('page', String(currentPage));
|
||||||
|
|
||||||
const queryString = params.toString();
|
const queryString = params.toString();
|
||||||
const newUrl = `/shop${queryString ? `?${queryString}` : ''}`;
|
const newUrl = `/shop${queryString ? `?${queryString}` : ''}`;
|
||||||
if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) {
|
if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) {
|
||||||
router.replace(newUrl, { scroll: false });
|
router.replace(newUrl, { scroll: false });
|
||||||
}
|
}
|
||||||
}, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]);
|
}, [selectedCategory, selectedPet, searchQuery, activeSymptoms, currentPage, router]);
|
||||||
|
|
||||||
|
const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0);
|
||||||
|
const didSkipInitialFetch = React.useRef(false);
|
||||||
|
|
||||||
const fetchProducts = useCallback(async () => {
|
const fetchProducts = useCallback(async () => {
|
||||||
|
setFetchError(null);
|
||||||
setIsUpdating(true);
|
setIsUpdating(true);
|
||||||
try {
|
try {
|
||||||
const res = await productService.getProducts({
|
const res = await productService.getProducts({
|
||||||
@@ -572,18 +602,24 @@ export default function ArchivePage({
|
|||||||
result = result.filter(p => p.symptoms && p.symptoms.some(s => activeSymptoms.includes(s)));
|
result = result.filter(p => p.symptoms && p.symptoms.some(s => activeSymptoms.includes(s)));
|
||||||
}
|
}
|
||||||
|
|
||||||
setFilteredProducts(result);
|
setFilteredProducts(orderProductsByAvailability(result));
|
||||||
|
setCurrentPage(1);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch products:", error);
|
console.error("Failed to fetch products:", error);
|
||||||
toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
|
toast.error("خطا در دریافت لیست محصولات از سرور.");
|
||||||
|
setFetchError("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات.");
|
||||||
} finally {
|
} finally {
|
||||||
setIsUpdating(false);
|
setIsUpdating(false);
|
||||||
}
|
}
|
||||||
}, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]);
|
}, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (hasInitialProducts && !didSkipInitialFetch.current) {
|
||||||
|
didSkipInitialFetch.current = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
Promise.resolve().then(() => fetchProducts());
|
Promise.resolve().then(() => fetchProducts());
|
||||||
}, [fetchProducts]);
|
}, [fetchProducts, hasInitialProducts]);
|
||||||
|
|
||||||
const toggleSymptom = (s: string) => {
|
const toggleSymptom = (s: string) => {
|
||||||
setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]);
|
setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]);
|
||||||
@@ -690,6 +726,7 @@ export default function ArchivePage({
|
|||||||
<div className="relative mb-3">
|
<div className="relative mb-3">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label="جستجوی علائم"
|
||||||
placeholder="جستجوی علائم..."
|
placeholder="جستجوی علائم..."
|
||||||
value={symptomSearch}
|
value={symptomSearch}
|
||||||
onChange={(e) => setSymptomSearch(e.target.value)}
|
onChange={(e) => setSymptomSearch(e.target.value)}
|
||||||
@@ -724,32 +761,33 @@ export default function ArchivePage({
|
|||||||
<h4 className="text-lg font-black italic mb-4 relative z-10 underline decoration-canina-blue underline-offset-8">{getText('shop_promo_card_title', 'مشاوره رایگان')}</h4>
|
<h4 className="text-lg font-black italic mb-4 relative z-10 underline decoration-canina-blue underline-offset-8">{getText('shop_promo_card_title', 'مشاوره رایگان')}</h4>
|
||||||
<p className="text-xs text-white/60 leading-relaxed mb-6 relative z-10">{getText('shop_promo_card_desc', 'اگر نمیدانید کدام ترکیب برای پت شما مناسب است، همین حالا با دامپزشکان ما تماس بگیرید.')}</p>
|
<p className="text-xs text-white/60 leading-relaxed mb-6 relative z-10">{getText('shop_promo_card_desc', 'اگر نمیدانید کدام ترکیب برای پت شما مناسب است، همین حالا با دامپزشکان ما تماس بگیرید.')}</p>
|
||||||
<a
|
<a
|
||||||
href={getText('contact_phone_link', `tel:${getText('contact_phone', '02188884444').replace(/[^0-9+]/g, '')}`)}
|
href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)}
|
||||||
className="w-full bg-white text-medical-gray-900 py-3 rounded-xl text-xs font-black hover:scale-105 transition-transform relative z-10 flex items-center justify-center font-vazir"
|
className="w-full bg-white text-medical-gray-900 py-3 rounded-xl text-xs font-black hover:scale-105 transition-transform relative z-10 flex items-center justify-center font-vazir"
|
||||||
>
|
>
|
||||||
شماره تماس: {getText('contact_phone', '۰۲۱-۸۸۸۸۴۴۴۴')}
|
شماره تماس: {getText('contact_phone', '')}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
{/* Main Content */}
|
{/* Main Content */}
|
||||||
<main className="flex-1 relative">
|
<main className="flex-1 relative">
|
||||||
{/* Desktop Top Title & Search / Sort Row */}
|
{/* Semantic Single H1 across breakpoints */}
|
||||||
<div className="hidden lg:flex flex-col sm:flex-row items-center justify-between mb-6 gap-4">
|
<div className="flex flex-col lg:flex-row items-start lg:items-center justify-between mb-2 lg:mb-6 gap-2 lg:gap-4">
|
||||||
{getText('shop_catalog_title', '').trim() ? (
|
<h1
|
||||||
<h2
|
className="text-2xl lg:text-3xl font-black text-medical-gray-900"
|
||||||
className="text-3xl font-black text-medical-gray-900"
|
dangerouslySetInnerHTML={{
|
||||||
dangerouslySetInnerHTML={{
|
__html: getText('shop_catalog_title', 'کاتالوگ و فروشگاه مکملهای دارویی <span class="text-canina-blue">کنینا</span>')
|
||||||
__html: getText('shop_catalog_title', 'کاتولوگ دارویی <span class="text-canina-blue">Canina</span>')
|
.replace(/^\s*<h1[^>]*>/i, '')
|
||||||
}}
|
.replace(/<\/h1>\s*$/i, '')
|
||||||
/>
|
}}
|
||||||
) : null}
|
/>
|
||||||
|
|
||||||
<div className="flex items-center gap-3 w-auto">
|
<div className="hidden lg:flex items-center gap-3 w-auto">
|
||||||
{/* Sort Dropdown */}
|
{/* Sort Dropdown */}
|
||||||
<div className="flex items-center gap-2 bg-white border border-medical-gray-200 rounded-2xl px-3 py-2 text-xs font-bold shadow-xs">
|
<div className="flex items-center gap-2 bg-white border border-medical-gray-200 rounded-2xl px-3 py-2 text-xs font-bold shadow-xs">
|
||||||
<span className="text-medical-gray-400 whitespace-nowrap">مرتبسازی:</span>
|
<span className="text-medical-gray-400 whitespace-nowrap">مرتبسازی:</span>
|
||||||
<select
|
<select
|
||||||
|
aria-label="مرتبسازی محصولات"
|
||||||
value={`${sortBy}:${sortOrder}`}
|
value={`${sortBy}:${sortOrder}`}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const [b, o] = e.target.value.split(':');
|
const [b, o] = e.target.value.split(':');
|
||||||
@@ -771,6 +809,7 @@ export default function ArchivePage({
|
|||||||
<input
|
<input
|
||||||
data-testid="shop-search-input"
|
data-testid="shop-search-input"
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label="جستجوی محصول"
|
||||||
placeholder="جستجوی محصول..."
|
placeholder="جستجوی محصول..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
@@ -780,18 +819,6 @@ export default function ArchivePage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile Title (Only if set in admin) */}
|
|
||||||
{getText('shop_catalog_title', '').trim() ? (
|
|
||||||
<div className="lg:hidden mb-2">
|
|
||||||
<h2
|
|
||||||
className="text-2xl font-black text-medical-gray-900"
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: getText('shop_catalog_title', 'کاتولوگ دارویی <span class="text-canina-blue">Canina</span>')
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */}
|
{/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */}
|
||||||
<div className="lg:hidden flex flex-col gap-2 mb-2">
|
<div className="lg:hidden flex flex-col gap-2 mb-2">
|
||||||
{/* Search Bar on Mobile */}
|
{/* Search Bar on Mobile */}
|
||||||
@@ -800,6 +827,7 @@ export default function ArchivePage({
|
|||||||
<input
|
<input
|
||||||
data-testid="shop-search-input-mobile"
|
data-testid="shop-search-input-mobile"
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label="جستجوی محصول"
|
||||||
placeholder="جستجوی محصول..."
|
placeholder="جستجوی محصول..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
@@ -809,7 +837,8 @@ export default function ArchivePage({
|
|||||||
|
|
||||||
|
|
||||||
{/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */}
|
{/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */}
|
||||||
<div className="flex items-center gap-2 overflow-x-auto pb-2.5 pt-0.5 micro-hscroll -mx-4 px-4 select-none touch-pan-x mt-2 mb-4">
|
<div className="relative -mx-4 mt-2 mb-4" data-testid="mobile-catalog-filters-edge">
|
||||||
|
<div data-testid="mobile-catalog-filters" aria-label="فیلترهای محصولات" className="flex items-center gap-2 overflow-x-auto pb-2.5 pt-0.5 micro-hscroll px-4 select-none touch-pan-x mobile-filter-mask">
|
||||||
|
|
||||||
{/* 1. View Mode Switch: 2 Buttons (List / Card) */}
|
{/* 1. View Mode Switch: 2 Buttons (List / Card) */}
|
||||||
<div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl p-0.5 shadow-2xs mr-auto">
|
<div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl p-0.5 shadow-2xs mr-auto">
|
||||||
@@ -896,23 +925,23 @@ export default function ArchivePage({
|
|||||||
}}
|
}}
|
||||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-[11px] font-black shadow-2xs transition-all whitespace-nowrap ${selectedCategory !== "all" ? "bg-canina-blue text-white border-canina-blue" : "bg-white border-medical-gray-200 text-medical-gray-700"}`}
|
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-[11px] font-black shadow-2xs transition-all whitespace-nowrap ${selectedCategory !== "all" ? "bg-canina-blue text-white border-canina-blue" : "bg-white border-medical-gray-200 text-medical-gray-700"}`}
|
||||||
>
|
>
|
||||||
<span>{selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "راهکار درمانی") : "راهکار درمانی"}</span>
|
<span>{selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "دستهبندی") : "دستهبندی و راهکار"}</span>
|
||||||
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSolutionsOpen ? "rotate-180" : ""}`} />
|
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSolutionsOpen ? "rotate-180" : ""}`} />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{isMobileSolutionsOpen && (
|
{isMobileSolutionsOpen && isMounted && createPortal(
|
||||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 backdrop-blur-xs font-vazir" onClick={() => setIsMobileSolutionsOpen(false)}>
|
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSolutionsOpen(false)}>
|
||||||
<div
|
<div
|
||||||
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[75vh] flex flex-col animate-in slide-in-from-bottom duration-200"
|
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[75vh] flex flex-col animate-in slide-in-from-bottom duration-200"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
<div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" />
|
<div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" />
|
||||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0">
|
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0">
|
||||||
<h4 className="font-black text-sm text-medical-gray-900">انتخاب راهکار درمانی</h4>
|
<h4 className="font-black text-sm text-medical-gray-900">فیلتر دستهبندی و راهکار درمانی</h4>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setIsMobileSolutionsOpen(false)}
|
onClick={() => setIsMobileSolutionsOpen(false)}
|
||||||
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1"
|
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer"
|
||||||
>
|
>
|
||||||
بستن ✕
|
بستن ✕
|
||||||
</button>
|
</button>
|
||||||
@@ -926,7 +955,7 @@ export default function ArchivePage({
|
|||||||
setSelectedCategory(cat.id);
|
setSelectedCategory(cat.id);
|
||||||
setIsMobileSolutionsOpen(false);
|
setIsMobileSolutionsOpen(false);
|
||||||
}}
|
}}
|
||||||
className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold text-right transition-colors border ${selectedCategory === cat.id ? "bg-canina-blue border-canina-blue text-white" : "bg-white border-medical-gray-100 hover:bg-medical-gray-50 text-medical-gray-700"}`}
|
className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold text-right transition-colors border cursor-pointer ${selectedCategory === cat.id ? "bg-canina-blue border-canina-blue text-white" : "bg-white border-medical-gray-100 hover:bg-medical-gray-50 text-medical-gray-700"}`}
|
||||||
>
|
>
|
||||||
<span className="shrink-0">{cat.icon}</span>
|
<span className="shrink-0">{cat.icon}</span>
|
||||||
<span className="truncate">{cat.label}</span>
|
<span className="truncate">{cat.label}</span>
|
||||||
@@ -934,7 +963,8 @@ export default function ArchivePage({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>,
|
||||||
|
document.body
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -952,8 +982,8 @@ export default function ArchivePage({
|
|||||||
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSymptomsOpen ? "rotate-180" : ""}`} />
|
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSymptomsOpen ? "rotate-180" : ""}`} />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{isMobileSymptomsOpen && (
|
{isMobileSymptomsOpen && isMounted && createPortal(
|
||||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 backdrop-blur-xs font-vazir" onClick={() => setIsMobileSymptomsOpen(false)}>
|
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSymptomsOpen(false)}>
|
||||||
<div
|
<div
|
||||||
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[80vh] flex flex-col animate-in slide-in-from-bottom duration-200"
|
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[80vh] flex flex-col animate-in slide-in-from-bottom duration-200"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
@@ -969,7 +999,7 @@ export default function ArchivePage({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setActiveSymptoms([])}
|
onClick={() => setActiveSymptoms([])}
|
||||||
className="text-xs font-bold text-red-500 hover:underline px-1"
|
className="text-xs font-bold text-red-500 hover:underline px-1 cursor-pointer"
|
||||||
>
|
>
|
||||||
پاک کردن همه
|
پاک کردن همه
|
||||||
</button>
|
</button>
|
||||||
@@ -977,7 +1007,7 @@ export default function ArchivePage({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setIsMobileSymptomsOpen(false)}
|
onClick={() => setIsMobileSymptomsOpen(false)}
|
||||||
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1"
|
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer"
|
||||||
>
|
>
|
||||||
بستن ✕
|
بستن ✕
|
||||||
</button>
|
</button>
|
||||||
@@ -988,6 +1018,7 @@ export default function ArchivePage({
|
|||||||
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
|
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label="جستجوی علائم"
|
||||||
placeholder="جستجوی علائم بیماری یا نیاز دارویی..."
|
placeholder="جستجوی علائم بیماری یا نیاز دارویی..."
|
||||||
value={symptomSearch}
|
value={symptomSearch}
|
||||||
onChange={(e) => setSymptomSearch(e.target.value)}
|
onChange={(e) => setSymptomSearch(e.target.value)}
|
||||||
@@ -1006,7 +1037,7 @@ export default function ArchivePage({
|
|||||||
key={s}
|
key={s}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => toggleSymptom(s)}
|
onClick={() => toggleSymptom(s)}
|
||||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap ${activeSymptoms.includes(s)
|
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap cursor-pointer ${activeSymptoms.includes(s)
|
||||||
? "bg-canina-blue border-canina-blue text-white shadow-2xs"
|
? "bg-canina-blue border-canina-blue text-white shadow-2xs"
|
||||||
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40 hover:text-canina-blue"
|
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40 hover:text-canina-blue"
|
||||||
}`}
|
}`}
|
||||||
@@ -1021,15 +1052,19 @@ export default function ArchivePage({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setIsMobileSymptomsOpen(false)}
|
onClick={() => setIsMobileSymptomsOpen(false)}
|
||||||
className="w-full bg-canina-blue text-white py-2.5 rounded-xl font-bold text-xs shadow-lg shadow-canina-blue/20"
|
className="w-full bg-canina-blue text-white py-2.5 rounded-xl font-bold text-xs shadow-lg shadow-canina-blue/20 cursor-pointer"
|
||||||
>
|
>
|
||||||
مشاهده نتایج {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)} علامت)` : ""}
|
مشاهده نتایج {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)} علامت)` : ""}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>,
|
||||||
|
document.body
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1071,7 +1106,23 @@ export default function ArchivePage({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<AnimatePresence mode="wait">
|
<AnimatePresence mode="wait">
|
||||||
{isUpdating ? (
|
{fetchError ? (
|
||||||
|
<div key="fetch-error" data-testid="shop-fetch-error" className="bg-white rounded-[2.5rem] p-10 sm:p-14 text-center border border-rose-200/80 shadow-sm flex flex-col items-center">
|
||||||
|
<div className="w-16 h-16 bg-rose-50 rounded-2xl flex items-center justify-center text-rose-500 mb-4 border border-rose-100">
|
||||||
|
<AlertCircle className="w-8 h-8" />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-xl font-black text-medical-gray-900 mb-2">خطا در دریافت اطلاعات محصولات</h3>
|
||||||
|
<p className="text-medical-gray-500 max-w-md mb-6 font-medium text-xs sm:text-sm leading-relaxed">{fetchError}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => fetchProducts()}
|
||||||
|
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-2.5 rounded-xl font-black text-xs sm:text-sm hover:bg-canina-dark transition-all shadow-md shadow-canina-blue/20 cursor-pointer active:scale-95"
|
||||||
|
>
|
||||||
|
<Activity className="w-4 h-4" />
|
||||||
|
<span>تلاش مجدد</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : isUpdating ? (
|
||||||
viewMode === "list" ? (
|
viewMode === "list" ? (
|
||||||
<div key="skeleton-list" className="flex flex-col gap-3 lg:hidden">
|
<div key="skeleton-list" className="flex flex-col gap-3 lg:hidden">
|
||||||
{Array.from({ length: 8 }).map((_, i) => (
|
{Array.from({ length: 8 }).map((_, i) => (
|
||||||
@@ -1087,35 +1138,121 @@ export default function ArchivePage({
|
|||||||
)
|
)
|
||||||
) : filteredProducts.length > 0 ? (
|
) : filteredProducts.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
{/* Mobile List View vs Card View (Desktop is always responsive multi-column grid) */}
|
{/* Progressive slice of products for optimal DOM density and mobile UX */}
|
||||||
<div
|
{(() => {
|
||||||
key={viewMode}
|
const totalPages = Math.max(1, Math.ceil(filteredProducts.length / pageSize));
|
||||||
className={
|
const safeCurrentPage = Math.min(currentPage, totalPages);
|
||||||
viewMode === "list"
|
const startIndex = (safeCurrentPage - 1) * pageSize;
|
||||||
? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6"
|
const slicedProducts = filteredProducts.slice(startIndex, startIndex + pageSize);
|
||||||
: "grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6"
|
|
||||||
}
|
const totalInStock = filteredProducts.filter(product => !isProductOutOfStock(product)).length;
|
||||||
>
|
const totalOutOfStock = filteredProducts.filter(product => isProductOutOfStock(product)).length;
|
||||||
<AnimatePresence mode="popLayout">
|
|
||||||
{filteredProducts.map((p: Product) => (
|
const sections = [
|
||||||
<React.Fragment key={p.id}>
|
{
|
||||||
{/* In list mode on mobile, render ArchiveProductListItem; on desktop (lg+), render standard card */}
|
key: "available",
|
||||||
{viewMode === "list" ? (
|
title: "محصولات موجود",
|
||||||
<>
|
totalCount: totalInStock,
|
||||||
<div className="block lg:hidden w-full">
|
products: slicedProducts.filter(product => !isProductOutOfStock(product)),
|
||||||
<ArchiveProductListItem product={p} />
|
},
|
||||||
|
{
|
||||||
|
key: "unavailable",
|
||||||
|
title: "محصولات ناموجود",
|
||||||
|
totalCount: totalOutOfStock,
|
||||||
|
products: slicedProducts.filter(product => isProductOutOfStock(product)),
|
||||||
|
}
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{sections.map(section => section.products.length > 0 && (
|
||||||
|
<section key={section.key} data-testid={`products-${section.key}`} className="mb-8 last:mb-0">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-xl font-black text-medical-gray-900">{section.title}</h2>
|
||||||
|
<span className="text-xs font-bold text-medical-gray-400">
|
||||||
|
{toPersian(section.totalCount)} محصول
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
key={viewMode}
|
||||||
|
className={
|
||||||
|
viewMode === "list"
|
||||||
|
? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6"
|
||||||
|
: "grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<AnimatePresence mode="popLayout">
|
||||||
|
{section.products.map((p: Product) => (
|
||||||
|
<React.Fragment key={p.id}>
|
||||||
|
{viewMode === "list" ? (
|
||||||
|
<ArchiveProductListItem product={p} />
|
||||||
|
) : (
|
||||||
|
<ArchiveProductCard product={p} />
|
||||||
|
)}
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
|
</AnimatePresence>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Pagination Controls */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<nav aria-label="صفحهبندی محصولات" data-testid="shop-pagination" className="mt-10 mb-4 flex flex-col sm:flex-row items-center justify-between gap-4 bg-white border border-medical-gray-200/80 rounded-2xl p-4 shadow-xs font-vazir">
|
||||||
|
<div className="text-xs text-medical-gray-500 font-bold order-2 sm:order-1">
|
||||||
|
صفحه {toPersian(safeCurrentPage)} از {toPersian(totalPages)} (کل محصولات: {toPersian(filteredProducts.length)})
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 order-1 sm:order-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={safeCurrentPage <= 1}
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentPage(prev => Math.max(1, prev - 1));
|
||||||
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
|
}}
|
||||||
|
aria-label="صفحه قبل"
|
||||||
|
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
|
||||||
|
>
|
||||||
|
قبلی
|
||||||
|
</button>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
{Array.from({ length: totalPages }).map((_, i) => {
|
||||||
|
const pageNum = i + 1;
|
||||||
|
const isActive = pageNum === safeCurrentPage;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={pageNum}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentPage(pageNum);
|
||||||
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
|
}}
|
||||||
|
aria-current={isActive ? "page" : undefined}
|
||||||
|
className={isActive ? "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer bg-canina-blue text-white shadow-sm" : "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer text-medical-gray-700 hover:bg-medical-gray-100 border border-medical-gray-200/60"}
|
||||||
|
>
|
||||||
|
{toPersian(pageNum)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
<div className="hidden lg:block h-full">
|
<button
|
||||||
<ArchiveProductCard product={p} />
|
type="button"
|
||||||
</div>
|
disabled={safeCurrentPage >= totalPages}
|
||||||
</>
|
onClick={() => {
|
||||||
) : (
|
setCurrentPage(prev => Math.min(totalPages, prev + 1));
|
||||||
<ArchiveProductCard product={p} />
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
)}
|
}}
|
||||||
</React.Fragment>
|
aria-label="صفحه بعد"
|
||||||
))}
|
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
|
||||||
</AnimatePresence>
|
>
|
||||||
</div>
|
بعدی
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
{/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */}
|
{/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */}
|
||||||
{selectedCategory !== "all" && (
|
{selectedCategory !== "all" && (
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"use client";
|
||||||
|
import React, { useMemo } from "react";
|
||||||
|
import ArticleProductCard from "./ArticleProductCard";
|
||||||
|
|
||||||
|
interface ArticleContentRendererProps {
|
||||||
|
contentHtml: string;
|
||||||
|
relatedProducts?: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseContentWithProducts(
|
||||||
|
html: string,
|
||||||
|
relatedProducts: any[] = []
|
||||||
|
): Array<{ type: "html" | "product"; content?: string; product?: any }> {
|
||||||
|
if (!html) return [];
|
||||||
|
|
||||||
|
// Match tags like [product slug_or_id], [محصول slug_or_id]
|
||||||
|
// or HTML elements like <div data-product="slug_or_id"></div>
|
||||||
|
// or <span data-product="slug_or_id"></span>
|
||||||
|
const markerRegex = /(?:<p[^>]*>\s*)?(?:\[(?:product|محصول)\s+([a-zA-Z0-9_-]+)\]|<(?:div|span)[^>]*data-product=["']([a-zA-Z0-9_-]+)["'][^>]*>(?:<\/(?:div|span)>)?)(?:\s*<\/p>)?/gi;
|
||||||
|
|
||||||
|
const parts: Array<{ type: "html" | "product"; content?: string; product?: any }> = [];
|
||||||
|
let lastIndex = 0;
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
|
||||||
|
// Build product lookup map (by slug, id)
|
||||||
|
const productMap = new Map<string, any>();
|
||||||
|
for (const prod of relatedProducts) {
|
||||||
|
if (prod.slug) productMap.set(String(prod.slug).toLowerCase(), prod);
|
||||||
|
if (prod.id) productMap.set(String(prod.id).toLowerCase(), prod);
|
||||||
|
}
|
||||||
|
|
||||||
|
while ((match = markerRegex.exec(html)) !== null) {
|
||||||
|
const matchedText = match[0];
|
||||||
|
const identifier = (match[1] || match[2] || "").trim();
|
||||||
|
const startIndex = match.index;
|
||||||
|
|
||||||
|
// Push preceding HTML
|
||||||
|
if (startIndex > lastIndex) {
|
||||||
|
const htmlSlice = html.slice(lastIndex, startIndex);
|
||||||
|
if (htmlSlice.trim()) {
|
||||||
|
parts.push({ type: "html", content: htmlSlice });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchedProduct = productMap.get(identifier.toLowerCase());
|
||||||
|
if (matchedProduct) {
|
||||||
|
parts.push({ type: "product", product: matchedProduct });
|
||||||
|
} else {
|
||||||
|
// If product not found in map, attempt fallback with slug info
|
||||||
|
parts.push({
|
||||||
|
type: "product",
|
||||||
|
product: {
|
||||||
|
id: identifier,
|
||||||
|
slug: identifier,
|
||||||
|
nameFa: `محصول ${identifier}`,
|
||||||
|
category: "مکمل دارویی کنینا",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
lastIndex = startIndex + matchedText.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push remaining HTML
|
||||||
|
if (lastIndex < html.length) {
|
||||||
|
const trailingHtml = html.slice(lastIndex);
|
||||||
|
if (trailingHtml.trim()) {
|
||||||
|
parts.push({ type: "html", content: trailingHtml });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parts.length === 0 && html) {
|
||||||
|
parts.push({ type: "html", content: html });
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ArticleContentRenderer({
|
||||||
|
contentHtml,
|
||||||
|
relatedProducts = [],
|
||||||
|
}: ArticleContentRendererProps) {
|
||||||
|
const sections = useMemo(
|
||||||
|
() => parseContentWithProducts(contentHtml, relatedProducts),
|
||||||
|
[contentHtml, relatedProducts]
|
||||||
|
);
|
||||||
|
|
||||||
|
// If there are no product cards inserted, preserve the exact original markup structure
|
||||||
|
const hasProducts = sections.some((s) => s.type === "product");
|
||||||
|
if (!hasProducts) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
|
||||||
|
dangerouslySetInnerHTML={{ __html: contentHtml }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="article-html-content space-y-6">
|
||||||
|
{sections.map((section, idx) => {
|
||||||
|
if (section.type === "product" && section.product) {
|
||||||
|
return (
|
||||||
|
<ArticleProductCard
|
||||||
|
key={`article-prod-${section.product.id || idx}`}
|
||||||
|
product={section.product}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`article-html-${idx}`}
|
||||||
|
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5"
|
||||||
|
dangerouslySetInnerHTML={{ __html: section.content || "" }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
"use client";
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ShoppingCart, Check, ExternalLink, ShieldCheck } from "lucide-react";
|
||||||
|
import SafeImage from "./SafeImage";
|
||||||
|
import { useCartStore } from "../lib/store/cartStore";
|
||||||
|
|
||||||
|
export interface ArticleProductCardProps {
|
||||||
|
product: {
|
||||||
|
id: string;
|
||||||
|
slug?: string;
|
||||||
|
nameFa: string;
|
||||||
|
nameEn?: string;
|
||||||
|
description?: string;
|
||||||
|
category?: { name: string; slug?: string } | string;
|
||||||
|
categorySlug?: string;
|
||||||
|
imageUrl?: string;
|
||||||
|
images?: string[];
|
||||||
|
priceValue?: number;
|
||||||
|
priceDisplay?: string;
|
||||||
|
prices?: { price: number; volume?: string }[];
|
||||||
|
stock?: number;
|
||||||
|
stockStatus?: string;
|
||||||
|
isOriginal?: boolean;
|
||||||
|
madeInGermany?: boolean;
|
||||||
|
rating?: number;
|
||||||
|
};
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ArticleProductCard({ product, compact = false }: ArticleProductCardProps) {
|
||||||
|
const [isAdded, setIsAdded] = useState(false);
|
||||||
|
const addItem = useCartStore((state) => state.addItem);
|
||||||
|
|
||||||
|
if (!product || !product.nameFa) return null;
|
||||||
|
|
||||||
|
const productUrl = `/shop/${encodeURIComponent(product.slug || product.id)}`;
|
||||||
|
const imageSrc =
|
||||||
|
product.imageUrl ||
|
||||||
|
(Array.isArray(product.images) && product.images[0]) ||
|
||||||
|
"/assets/images/canina-product-placeholder.png";
|
||||||
|
|
||||||
|
const categoryName =
|
||||||
|
typeof product.category === "string"
|
||||||
|
? product.category
|
||||||
|
: product.category?.name || product.categorySlug || "مکمل تخصصی کنینا";
|
||||||
|
|
||||||
|
// Price calculation
|
||||||
|
const rawPrice =
|
||||||
|
product.priceValue ||
|
||||||
|
(Array.isArray(product.prices) && product.prices[0]?.price) ||
|
||||||
|
0;
|
||||||
|
|
||||||
|
const formattedPrice =
|
||||||
|
product.priceDisplay ||
|
||||||
|
(rawPrice > 0 ? `${Number(rawPrice).toLocaleString("fa-IR")} تومان` : "تماس بگیرید");
|
||||||
|
|
||||||
|
const isOutOfStock =
|
||||||
|
product.stockStatus === "OUT_OF_STOCK" ||
|
||||||
|
product.stockStatus === "DISCONTINUED" ||
|
||||||
|
(typeof product.stock === "number" && product.stock <= 0);
|
||||||
|
|
||||||
|
const handleAddToCart = (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (isOutOfStock) return;
|
||||||
|
|
||||||
|
// Adapt to CartStore Product shape
|
||||||
|
const storeProduct: any = {
|
||||||
|
id: product.id,
|
||||||
|
slug: product.slug || product.id,
|
||||||
|
nameFa: product.nameFa,
|
||||||
|
nameEn: product.nameEn || "",
|
||||||
|
category: typeof product.category === "string" ? { name: product.category, slug: "" } : product.category,
|
||||||
|
priceValue: rawPrice,
|
||||||
|
images: [imageSrc],
|
||||||
|
stock: product.stock ?? 99,
|
||||||
|
stockStatus: product.stockStatus || "IN_STOCK",
|
||||||
|
};
|
||||||
|
|
||||||
|
addItem(storeProduct, 1);
|
||||||
|
setIsAdded(true);
|
||||||
|
setTimeout(() => {
|
||||||
|
setIsAdded(false);
|
||||||
|
}, 2500);
|
||||||
|
};
|
||||||
|
|
||||||
|
const buttonAriaLabel = isOutOfStock
|
||||||
|
? "ناموجود"
|
||||||
|
: isAdded
|
||||||
|
? "به سبد اضافه شد"
|
||||||
|
: "افزودن به سبد خرید";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="article-product-card"
|
||||||
|
className="my-6 sm:my-8 rounded-3xl bg-gradient-to-br from-white via-medical-gray-50/60 to-canina-blue/5 border-2 border-canina-blue/20 hover:border-canina-blue/40 shadow-lg hover:shadow-xl transition-all duration-300 overflow-hidden font-vazir text-right group not-prose"
|
||||||
|
dir="rtl"
|
||||||
|
>
|
||||||
|
<div className="p-4 sm:p-6 flex flex-col sm:flex-row items-center gap-4 sm:gap-6">
|
||||||
|
{/* Product Image Thumbnail */}
|
||||||
|
<Link
|
||||||
|
href={productUrl}
|
||||||
|
className="relative w-28 h-28 sm:w-32 sm:h-32 shrink-0 bg-white rounded-2xl p-2 border border-medical-gray-200/80 shadow-inner flex items-center justify-center overflow-hidden group-hover:scale-105 transition-transform duration-300"
|
||||||
|
aria-label={product.nameFa}
|
||||||
|
>
|
||||||
|
<SafeImage
|
||||||
|
src={imageSrc}
|
||||||
|
alt={product.nameFa}
|
||||||
|
className="w-full h-full"
|
||||||
|
imgClassName="w-full h-full object-contain"
|
||||||
|
/>
|
||||||
|
{/* Made In Germany Floating Pill on Image */}
|
||||||
|
<div className="absolute top-1.5 right-1.5 bg-black/80 backdrop-blur-xs text-white text-[9px] font-black px-1.5 py-0.5 rounded-md flex items-center gap-0.5 shadow-xs border border-white/20">
|
||||||
|
<span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
|
||||||
|
<span>اصل آلمان</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* Product Details */}
|
||||||
|
<div className="flex-1 min-w-0 w-full flex flex-col justify-between h-full space-y-2">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between gap-2 mb-1">
|
||||||
|
<span className="text-[11px] font-bold text-canina-blue bg-canina-blue/10 px-2.5 py-0.5 rounded-full">
|
||||||
|
{categoryName}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1 text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200/60">
|
||||||
|
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
|
||||||
|
<span>ضمانت ۱۰۰٪ اصالت آلمان</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Link href={productUrl} className="block group-hover:text-canina-blue transition-colors">
|
||||||
|
<h4 className="text-base sm:text-lg font-black text-medical-gray-900 leading-snug truncate">
|
||||||
|
{product.nameFa}
|
||||||
|
</h4>
|
||||||
|
{product.nameEn && (
|
||||||
|
<span className="text-xs font-mono font-medium text-medical-gray-400 block truncate mt-0.5 dir-ltr text-right">
|
||||||
|
{product.nameEn}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{product.description && (
|
||||||
|
<p className="text-xs text-medical-gray-600 line-clamp-2 mt-1 leading-relaxed">
|
||||||
|
{product.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Price & Action Button Row */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-medical-gray-200/60">
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-medical-gray-400 block font-bold">قیمت مصرفکننده:</span>
|
||||||
|
<span className="text-sm sm:text-base font-black text-canina-blue font-mono">
|
||||||
|
{formattedPrice}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Link
|
||||||
|
href={productUrl}
|
||||||
|
className="px-3.5 py-2 bg-white hover:bg-medical-gray-100 text-medical-gray-700 text-xs font-bold rounded-xl border border-medical-gray-200 transition-colors flex items-center gap-1.5 shadow-2xs"
|
||||||
|
>
|
||||||
|
<span>مشاهده مشخصات</span>
|
||||||
|
<ExternalLink className="w-3.5 h-3.5" />
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleAddToCart}
|
||||||
|
disabled={isOutOfStock}
|
||||||
|
aria-label={buttonAriaLabel}
|
||||||
|
className={`px-4 py-2 text-xs font-black rounded-xl transition-all duration-300 flex items-center gap-1.5 shadow-md cursor-pointer ${
|
||||||
|
isOutOfStock
|
||||||
|
? "bg-medical-gray-200 text-medical-gray-400 cursor-not-allowed"
|
||||||
|
: isAdded
|
||||||
|
? "bg-emerald-600 text-white hover:bg-emerald-700"
|
||||||
|
: "bg-canina-blue hover:bg-canina-blue/90 text-white active:scale-95"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isAdded ? (
|
||||||
|
<>
|
||||||
|
<Check className="w-4 h-4 animate-in zoom-in-50" />
|
||||||
|
<span>به سبد اضافه شد</span>
|
||||||
|
</>
|
||||||
|
) : isOutOfStock ? (
|
||||||
|
<span>ناموجود</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ShoppingCart className="w-4 h-4" />
|
||||||
|
<span>خرید مستقیم</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -422,7 +422,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
|||||||
return (
|
return (
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
{isOpen && (
|
{isOpen && (
|
||||||
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4 font-vazir overflow-y-auto" dir="rtl">
|
<div className="fixed inset-0 z-[10000] flex items-end sm:items-center justify-center p-0 sm:p-4 font-vazir overflow-y-auto" dir="rtl">
|
||||||
{/* Backdrop */}
|
{/* Backdrop */}
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0 }}
|
initial={{ opacity: 0 }}
|
||||||
@@ -434,6 +434,9 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
|||||||
|
|
||||||
{/* Modal Container */}
|
{/* Modal Container */}
|
||||||
<motion.div
|
<motion.div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="auth-modal-title"
|
||||||
initial={{ opacity: 0, scale: 0.96, y: 20 }}
|
initial={{ opacity: 0, scale: 0.96, y: 20 }}
|
||||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||||
exit={{ opacity: 0, scale: 0.96, y: 20 }}
|
exit={{ opacity: 0, scale: 0.96, y: 20 }}
|
||||||
@@ -447,11 +450,13 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
|||||||
<ShieldCheck className="w-4 h-4" />
|
<ShieldCheck className="w-4 h-4" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-sm font-black tracking-tight text-medical-gray-900 font-vazir">احراز هویت کنینا</h3>
|
<h3 id="auth-modal-title" className="text-sm font-black tracking-tight text-medical-gray-900 font-vazir">احراز هویت کنینا</h3>
|
||||||
<p className="text-[10px] text-medical-gray-400 font-bold font-vazir">ورود امن به حساب کاربری</p>
|
<p className="text-[10px] text-medical-gray-400 font-bold font-vazir">ورود امن به حساب کاربری</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="بستن پنجره احراز هویت"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="w-8 h-8 rounded-full bg-white border border-medical-gray-200 flex items-center justify-center text-medical-gray-400 hover:text-medical-gray-700 hover:bg-medical-gray-100 transition-all cursor-pointer"
|
className="w-8 h-8 rounded-full bg-white border border-medical-gray-200 flex items-center justify-center text-medical-gray-400 hover:text-medical-gray-700 hover:bg-medical-gray-100 transition-all cursor-pointer"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export default function B2BLandingClient() {
|
|||||||
const [openFaq, setOpenFaq] = useState<number | null>(null);
|
const [openFaq, setOpenFaq] = useState<number | null>(null);
|
||||||
|
|
||||||
const getText = useSettingsStore((s) => s.getText);
|
const getText = useSettingsStore((s) => s.getText);
|
||||||
const phone = getText('contact_phone', '۰۹۲۱۱۲۳۱۵۱۷');
|
const phone = getText('contact_phone', '');
|
||||||
const wholesaleDiscount = getText('B2B_DISCOUNT_PERCENT', '۳۰');
|
const wholesaleDiscount = getText('B2B_DISCOUNT_PERCENT', '۳۰');
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -49,13 +49,17 @@ export default function B2BLandingClient() {
|
|||||||
|
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
await api.post('/wholesale/apply', {
|
await api.post('/b2b/inquire', {
|
||||||
businessName: `${formData.businessName} (${formData.businessType} - ${formData.city}) - رابط: ${formData.contactName}`,
|
companyName: formData.businessName,
|
||||||
licenseNumber: formData.phone,
|
contactName: formData.contactName || formData.businessName,
|
||||||
notes: formData.notes,
|
email: `partner-${Date.now()}@canina.ir`,
|
||||||
|
phone: formData.phone,
|
||||||
|
businessType: `${formData.businessType} (شهر: ${formData.city || 'نامشخص'})`,
|
||||||
|
estimatedVolume: 'ثبت لندینگ B2B سایت',
|
||||||
|
message: formData.notes || `درخواست شراکت و تامین رسمی برای ${formData.businessName} در شهر ${formData.city}`,
|
||||||
});
|
});
|
||||||
setSubmitted(true);
|
setSubmitted(true);
|
||||||
toast.success('درخواست همکاری شما با موفقیت ثبت شد. همکاران ما حداکثر تا ۲۴ ساعت آینده با شما تماس خواهند گرفت.');
|
toast.success('درخواست همکاری تجاری شما با موفقیت ثبت شد. تیم بازرگانی و پزشکی حداکثر تا ۲۴ ساعت کاری با شما تماس خواهند گرفت.');
|
||||||
} catch {
|
} catch {
|
||||||
toast.error('خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید.');
|
toast.error('خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید.');
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -89,23 +89,24 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
|||||||
initial={{ opacity: 0 }}
|
initial={{ opacity: 0 }}
|
||||||
animate={{ opacity: 1 }}
|
animate={{ opacity: 1 }}
|
||||||
exit={{ opacity: 0 }}
|
exit={{ opacity: 0 }}
|
||||||
className="fixed inset-0 z-[100] bg-medical-gray-900/60 backdrop-blur-md flex items-center justify-center p-4 md:p-10 font-vazir"
|
className="fixed inset-0 z-[100] bg-medical-gray-900/70 backdrop-blur-md flex items-center justify-center p-2 sm:p-4 md:p-8 font-vazir"
|
||||||
dir="rtl"
|
dir="rtl"
|
||||||
>
|
>
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ scale: 0.9, opacity: 0, y: 20 }}
|
initial={{ scale: 0.9, opacity: 0, y: 20 }}
|
||||||
animate={{ scale: 1, opacity: 1, y: 0 }}
|
animate={{ scale: 1, opacity: 1, y: 0 }}
|
||||||
className="bg-white w-full max-w-6xl h-[90vh] rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative"
|
className="bg-white w-full max-w-6xl h-[95vh] sm:h-[90vh] rounded-3xl sm:rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="absolute top-6 left-6 z-20 w-10 h-10 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-500 hover:bg-red-50 hover:text-red-500 transition-all"
|
className="absolute top-4 left-4 sm:top-6 sm:left-6 z-30 min-w-[44px] min-h-[44px] w-11 h-11 bg-white/90 sm:bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-600 hover:bg-red-50 hover:text-red-500 transition-all shadow-md cursor-pointer"
|
||||||
|
aria-label="بستن پنجره"
|
||||||
>
|
>
|
||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Sidebar Info */}
|
{/* Sidebar Info */}
|
||||||
<div className="w-full md:w-80 bg-canina-blue p-10 text-white flex flex-col overflow-y-auto">
|
<div className="w-full md:w-80 bg-canina-blue p-5 sm:p-8 md:p-10 text-white flex flex-col overflow-y-auto shrink-0 max-h-[45vh] md:max-h-full">
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mb-6">
|
<div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mb-6">
|
||||||
<Building2 className="w-8 h-8" />
|
<Building2 className="w-8 h-8" />
|
||||||
@@ -162,32 +163,107 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
|||||||
{/* Main Grid Area */}
|
{/* Main Grid Area */}
|
||||||
<div className="flex-1 flex flex-col bg-medical-gray-50 overflow-hidden">
|
<div className="flex-1 flex flex-col bg-medical-gray-50 overflow-hidden">
|
||||||
{/* Header & Search */}
|
{/* Header & Search */}
|
||||||
<div className="p-8 border-b border-medical-gray-200 flex flex-col md:flex-row md:items-center justify-between gap-6 bg-white">
|
<div className="p-4 sm:p-6 md:p-8 border-b border-medical-gray-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-6 bg-white shrink-0">
|
||||||
<div className="relative flex-1 max-w-md">
|
<div className="relative flex-1 max-w-md">
|
||||||
<Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
|
<Search className="absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="جستجوی کد کالا یا نام محصول..."
|
placeholder="جستجوی کد کالا یا نام محصول..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={e => setSearchQuery(e.target.value)}
|
onChange={e => setSearchQuery(e.target.value)}
|
||||||
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-3 pr-11 pl-4 text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
|
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl sm:rounded-2xl py-2.5 sm:py-3 pr-9 sm:pr-11 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={handleAddAll}
|
onClick={handleAddAll}
|
||||||
disabled={totalItems === 0}
|
disabled={totalItems === 0}
|
||||||
className="bg-medical-gray-900 text-white px-8 py-3 rounded-2xl font-black text-sm flex items-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30"
|
className="bg-medical-gray-900 text-white px-5 sm:px-8 py-2.5 sm:py-3 rounded-xl sm:rounded-2xl font-black text-xs sm:text-sm flex items-center justify-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30 cursor-pointer shadow-md"
|
||||||
>
|
>
|
||||||
<ShoppingCart className="w-4 h-4" />
|
<ShoppingCart className="w-4 h-4" />
|
||||||
افزودن کلی ({totalItems} عدد)
|
<span>افزودن کلی ({toPersian(totalItems)} عدد)</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Table */}
|
{/* Products Container */}
|
||||||
<div className="flex-1 overflow-y-auto p-8">
|
<div className="flex-1 overflow-y-auto p-3 sm:p-6 md:p-8">
|
||||||
{loadError && <p role="alert">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
|
{loadError && <p role="alert" className="text-red-500 font-bold text-xs p-4 bg-red-50 rounded-2xl mb-4">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
|
||||||
<div className="bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
|
|
||||||
|
{/* Mobile View: Clean Card Layout for each product */}
|
||||||
|
<div className="md:hidden space-y-3">
|
||||||
|
{filteredProducts.map(product => {
|
||||||
|
const basePrice = product.priceValue || 0;
|
||||||
|
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
|
||||||
|
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
|
||||||
|
const wholesalePrice = prodWholesale
|
||||||
|
? Number(prodWholesale)
|
||||||
|
: Math.round(basePrice * (1 - wholesaleDiscountPercent / 100));
|
||||||
|
const currentQty = quantities[product.id] || 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={product.id} className="bg-white border border-medical-gray-200 rounded-2xl p-3.5 shadow-xs space-y-3">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-14 h-14 bg-medical-gray-50 rounded-xl p-1.5 shrink-0 border border-medical-gray-100 flex items-center justify-center">
|
||||||
|
<SafeImage src={product.image} className="w-full h-full" imgClassName="object-contain" alt={product.name} />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h4 className="font-black text-xs text-medical-gray-900 leading-snug line-clamp-2">{product.name}</h4>
|
||||||
|
<span className="text-[10px] font-mono text-medical-gray-400 block mt-0.5 dir-ltr text-right">کد: {product.artNo}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between border-t border-medical-gray-100 pt-2.5 text-xs">
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-medical-gray-400 block font-medium">تکفروشی</span>
|
||||||
|
<span className="font-bold text-medical-gray-600 text-xs">{toPersian(basePrice.toLocaleString())} ت</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-amber-600 block font-black">قیمت همکار B2B</span>
|
||||||
|
{isWholesaleVerified ? (
|
||||||
|
<span className="font-black text-amber-800 text-xs bg-amber-50 px-2 py-0.5 rounded-md border border-amber-200 inline-block">
|
||||||
|
{toPersian(wholesalePrice.toLocaleString())} ت
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 bg-gray-50 px-1.5 py-0.5 rounded">
|
||||||
|
<Lock className="w-2.5 h-2.5" />
|
||||||
|
تایید ادمین
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1 bg-medical-gray-50 border border-medical-gray-200 rounded-xl p-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleQuantityChange(product.id, String(Math.max(0, currentQty - 1)))}
|
||||||
|
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
|
||||||
|
>
|
||||||
|
-
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
value={currentQty || ""}
|
||||||
|
onChange={(e) => handleQuantityChange(product.id, e.target.value)}
|
||||||
|
placeholder="0"
|
||||||
|
className="w-8 text-center bg-transparent font-mono font-black text-xs outline-none"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleQuantityChange(product.id, String(currentQty + 1))}
|
||||||
|
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Desktop / Tablet View: Rich Table */}
|
||||||
|
<div className="hidden md:block bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
|
||||||
<table className="w-full text-right">
|
<table className="w-full text-right">
|
||||||
<thead className="bg-medical-gray-50 border-b border-medical-gray-200">
|
<thead className="bg-medical-gray-50 border-b border-medical-gray-200">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -201,7 +277,6 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
|||||||
<tbody className="divide-y divide-medical-gray-100">
|
<tbody className="divide-y divide-medical-gray-100">
|
||||||
{filteredProducts.map(product => {
|
{filteredProducts.map(product => {
|
||||||
const basePrice = product.priceValue || 0;
|
const basePrice = product.priceValue || 0;
|
||||||
// Priority 1: Specific product wholesalePrice, Priority 2: General settings percentage discount (default 30%)
|
|
||||||
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
|
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
|
||||||
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
|
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
|
||||||
const wholesalePrice = prodWholesale
|
const wholesalePrice = prodWholesale
|
||||||
|
|||||||
@@ -17,7 +17,9 @@ import {
|
|||||||
Pin,
|
Pin,
|
||||||
Eye,
|
Eye,
|
||||||
Filter,
|
Filter,
|
||||||
|
SlidersHorizontal,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { toPersian } from "../lib/utils";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Product } from "../lib/data/products";
|
import { Product } from "../lib/data/products";
|
||||||
import { productService } from "../lib/services/productService";
|
import { productService } from "../lib/services/productService";
|
||||||
@@ -63,11 +65,14 @@ export default function BlogPage({
|
|||||||
const [selectedCategory, setSelectedCategory] = useState<string>(initialCategoryId);
|
const [selectedCategory, setSelectedCategory] = useState<string>(initialCategoryId);
|
||||||
const [searchQuery, setSearchQuery] = useState<string>("");
|
const [searchQuery, setSearchQuery] = useState<string>("");
|
||||||
const [selectedTag, setSelectedTag] = useState<string | null>(null);
|
const [selectedTag, setSelectedTag] = useState<string | null>(null);
|
||||||
|
const [sortBy, setSortBy] = useState<"newest" | "oldest" | "most_viewed">("newest");
|
||||||
|
const [visibleCount, setVisibleCount] = useState<number>(6);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (initialCategoryId) {
|
if (initialCategoryId) {
|
||||||
setSelectedCategory(initialCategoryId);
|
setSelectedCategory(initialCategoryId);
|
||||||
}
|
}
|
||||||
|
setVisibleCount(6);
|
||||||
}, [initialCategoryId]);
|
}, [initialCategoryId]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
@@ -90,8 +95,16 @@ export default function BlogPage({
|
|||||||
(b.tags && b.tags.some((t) => t.name === selectedTag));
|
(b.tags && b.tags.some((t) => t.name === selectedTag));
|
||||||
|
|
||||||
return matchCategory && matchSearch && matchTag;
|
return matchCategory && matchSearch && matchTag;
|
||||||
|
}).sort((a, b) => {
|
||||||
|
if (sortBy === "most_viewed") {
|
||||||
|
return (b.viewCount ?? 0) - (a.viewCount ?? 0);
|
||||||
|
}
|
||||||
|
if (sortBy === "oldest") {
|
||||||
|
return new Date(a.date).getTime() - new Date(b.date).getTime();
|
||||||
|
}
|
||||||
|
return new Date(b.date).getTime() - new Date(a.date).getTime();
|
||||||
});
|
});
|
||||||
}, [blogs, selectedCategory, searchQuery, selectedTag]);
|
}, [blogs, selectedCategory, searchQuery, selectedTag, sortBy]);
|
||||||
|
|
||||||
// Featured post (prioritize featured flag, otherwise the first item)
|
// Featured post (prioritize featured flag, otherwise the first item)
|
||||||
const featuredPost = useMemo(() => {
|
const featuredPost = useMemo(() => {
|
||||||
@@ -106,6 +119,12 @@ export default function BlogPage({
|
|||||||
return filteredBlogs.filter((b) => b.id !== featuredPost.id);
|
return filteredBlogs.filter((b) => b.id !== featuredPost.id);
|
||||||
}, [filteredBlogs, featuredPost]);
|
}, [filteredBlogs, featuredPost]);
|
||||||
|
|
||||||
|
const slicedRegularPosts = useMemo(() => {
|
||||||
|
return regularPosts.slice(0, visibleCount);
|
||||||
|
}, [regularPosts, visibleCount]);
|
||||||
|
|
||||||
|
const hasMore = visibleCount < regularPosts.length;
|
||||||
|
|
||||||
// Extract all unique tags
|
// Extract all unique tags
|
||||||
const allTags = useMemo(() => {
|
const allTags = useMemo(() => {
|
||||||
const map = new Map<string, string>();
|
const map = new Map<string, string>();
|
||||||
@@ -153,35 +172,57 @@ export default function BlogPage({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Search & Category Filter Section */}
|
{/* Search & Category Filter Section - Styled like /shop filters */}
|
||||||
<div className="bg-white p-6 rounded-3xl border border-medical-gray-200 shadow-sm mb-12 space-y-5">
|
<div className="bg-white p-3.5 sm:p-6 rounded-2xl sm:rounded-3xl border border-medical-gray-200 shadow-xs mb-8 space-y-3 sm:space-y-4">
|
||||||
<div className="flex flex-col md:flex-row items-center gap-4">
|
<div className="flex flex-col sm:flex-row items-center gap-2 sm:gap-4">
|
||||||
{/* Search Input */}
|
{/* Search Input */}
|
||||||
<div className="relative flex-1 w-full">
|
<div className="relative flex-1 w-full">
|
||||||
<Search className="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-medical-gray-400" />
|
<Search className="w-4 h-4 absolute right-3.5 top-1/2 -translate-y-1/2 text-medical-gray-400" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="جستجو در موضوعات، بیماریها، ویتامینها..."
|
placeholder="جستجو در موضوعات، بیماریها، ویتامینها..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => {
|
||||||
className="w-full pl-4 pr-11 py-3 rounded-2xl bg-medical-gray-50 border border-medical-gray-200 focus:border-canina-blue focus:bg-white text-xs sm:text-sm font-bold outline-none transition-all"
|
setSearchQuery(e.target.value);
|
||||||
|
setVisibleCount(6);
|
||||||
|
}}
|
||||||
|
className="w-full pl-4 pr-10 py-2.5 rounded-xl sm:rounded-2xl bg-medical-gray-50 border border-medical-gray-200 focus:border-canina-blue focus:bg-white text-xs sm:text-sm font-bold outline-none transition-all"
|
||||||
/>
|
/>
|
||||||
{searchQuery && (
|
{searchQuery && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setSearchQuery("")}
|
onClick={() => setSearchQuery("")}
|
||||||
className="absolute left-3 top-1/2 -translate-y-1/2 text-xs font-bold text-medical-gray-400 hover:text-medical-gray-600"
|
className="absolute left-3 top-1/2 -translate-y-1/2 text-xs font-bold text-medical-gray-400 hover:text-medical-gray-600 cursor-pointer"
|
||||||
>
|
>
|
||||||
پاک کردن
|
پاک کردن
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Sort Dropdown */}
|
||||||
|
<div className="relative w-full sm:w-auto flex-shrink-0">
|
||||||
|
<div className="flex items-center bg-white border border-medical-gray-200 rounded-xl px-3 py-2 shadow-2xs text-xs font-bold text-medical-gray-700 w-full sm:w-auto justify-between sm:justify-start">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<SlidersHorizontal className="w-3.5 h-3.5 text-canina-blue shrink-0" />
|
||||||
|
<span className="text-medical-gray-400 text-[10px] whitespace-nowrap">مرتبسازی:</span>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
value={sortBy}
|
||||||
|
onChange={(e) => setSortBy(e.target.value as any)}
|
||||||
|
className="bg-transparent text-xs font-black text-medical-gray-900 outline-none cursor-pointer pr-1"
|
||||||
|
>
|
||||||
|
<option value="newest">جدیدترین مقالات</option>
|
||||||
|
<option value="oldest">قدیمیترین</option>
|
||||||
|
<option value="most_viewed">پربازدیدترینها</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{selectedTag && (
|
{selectedTag && (
|
||||||
<div className="flex items-center gap-2 px-3 py-2 bg-purple-50 text-purple-700 border border-purple-200 rounded-xl text-xs font-bold">
|
<div className="flex items-center gap-2 px-3 py-1.5 bg-purple-50 text-purple-700 border border-purple-200 rounded-xl text-xs font-bold self-start sm:self-auto">
|
||||||
<span>تگ انتخاب شده: #{selectedTag}</span>
|
<span>تگ: #{selectedTag}</span>
|
||||||
<button
|
<button
|
||||||
onClick={() => setSelectedTag(null)}
|
onClick={() => setSelectedTag(null)}
|
||||||
className="text-purple-500 hover:text-purple-900"
|
className="text-purple-500 hover:text-purple-900 cursor-pointer"
|
||||||
>
|
>
|
||||||
✕
|
✕
|
||||||
</button>
|
</button>
|
||||||
@@ -189,54 +230,61 @@ export default function BlogPage({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Category Filter Pills */}
|
{/* Category Filter Pills with smooth edge mask */}
|
||||||
<div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-none">
|
<div className="relative -mx-3.5 sm:mx-0 px-3.5 sm:px-0">
|
||||||
<button
|
<div className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto pb-1 micro-hscroll select-none mobile-filter-mask">
|
||||||
onClick={() => {
|
|
||||||
setSelectedCategory("ALL");
|
|
||||||
router.replace('/blog', { scroll: false });
|
|
||||||
}}
|
|
||||||
className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
|
|
||||||
selectedCategory === "ALL"
|
|
||||||
? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
|
|
||||||
: "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
همه دستهها ({blogs.length})
|
|
||||||
</button>
|
|
||||||
{categories.map((c) => (
|
|
||||||
<button
|
<button
|
||||||
key={c.id}
|
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setSelectedCategory(c.id);
|
setSelectedCategory("ALL");
|
||||||
router.replace(`/blog?categoryId=${c.id}`, { scroll: false });
|
setVisibleCount(6);
|
||||||
|
router.replace('/blog', { scroll: false });
|
||||||
}}
|
}}
|
||||||
className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
|
className={`px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-xl sm:rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap border shrink-0 ${
|
||||||
selectedCategory === c.id
|
selectedCategory === "ALL"
|
||||||
? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
|
? "bg-canina-blue text-white border-canina-blue shadow-xs"
|
||||||
: "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
|
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{c.name}
|
همه دستهها ({blogs.length})
|
||||||
</button>
|
</button>
|
||||||
))}
|
{categories.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.id}
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedCategory(c.id);
|
||||||
|
setVisibleCount(6);
|
||||||
|
router.replace(`/blog?categoryId=${c.id}`, { scroll: false });
|
||||||
|
}}
|
||||||
|
className={`px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-xl sm:rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap border shrink-0 ${
|
||||||
|
selectedCategory === c.id
|
||||||
|
? "bg-canina-blue text-white border-canina-blue shadow-xs"
|
||||||
|
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{c.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Quick Tag Cloud */}
|
{/* Quick Tag Cloud */}
|
||||||
{allTags.length > 0 && (
|
{allTags.length > 0 && (
|
||||||
<div className="flex flex-wrap items-center gap-1.5 pt-2 border-t border-medical-gray-100">
|
<div className="flex flex-wrap items-center gap-1.5 pt-2 border-t border-medical-gray-100">
|
||||||
<span className="text-[11px] font-bold text-medical-gray-400 flex items-center gap-1 ml-2">
|
<span className="text-[10px] sm:text-[11px] font-bold text-medical-gray-400 flex items-center gap-1 ml-1">
|
||||||
<Tag className="w-3 h-3" />
|
<Tag className="w-3 h-3" />
|
||||||
محبوبترین تگها:
|
تگهای محبوب:
|
||||||
</span>
|
</span>
|
||||||
{allTags.slice(0, 10).map((tag) => (
|
{allTags.slice(0, 8).map((tag) => (
|
||||||
<button
|
<button
|
||||||
key={tag}
|
key={tag}
|
||||||
onClick={() => setSelectedTag(selectedTag === tag ? null : tag)}
|
onClick={() => {
|
||||||
className={`text-[11px] font-bold px-2.5 py-1 rounded-lg transition-all cursor-pointer ${
|
setSelectedTag(selectedTag === tag ? null : tag);
|
||||||
|
setVisibleCount(6);
|
||||||
|
}}
|
||||||
|
className={`text-[10px] sm:text-[11px] font-bold px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-lg transition-all cursor-pointer border ${
|
||||||
selectedTag === tag
|
selectedTag === tag
|
||||||
? "bg-purple-600 text-white"
|
? "bg-purple-600 text-white border-purple-600"
|
||||||
: "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
|
: "bg-medical-gray-50 text-medical-gray-600 border-medical-gray-200 hover:bg-medical-gray-100"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
#{tag}
|
#{tag}
|
||||||
@@ -249,11 +297,11 @@ export default function BlogPage({
|
|||||||
{/* Featured Post Banner */}
|
{/* Featured Post Banner */}
|
||||||
{featuredPost && (
|
{featuredPost && (
|
||||||
<div className="mb-16">
|
<div className="mb-16">
|
||||||
<motion.div
|
<motion.a
|
||||||
|
href={`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`}
|
||||||
initial={{ opacity: 0, y: 20 }}
|
initial={{ opacity: 0, y: 20 }}
|
||||||
animate={{ opacity: 1, y: 0 }}
|
animate={{ opacity: 1, y: 0 }}
|
||||||
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
|
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
|
||||||
onClick={() => router.push(`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`)}
|
|
||||||
>
|
>
|
||||||
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
|
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
|
||||||
<SafeImage
|
<SafeImage
|
||||||
@@ -311,22 +359,30 @@ export default function BlogPage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.a>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Regular Posts Grid */}
|
{/* Regular Posts Grid - Mobile-Optimized */}
|
||||||
{regularPosts.length > 0 ? (
|
{slicedRegularPosts.length > 0 ? (
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
|
<>
|
||||||
{regularPosts.map((post, idx) => (
|
<div className="flex items-center justify-between mb-4">
|
||||||
<motion.div
|
<h2 className="text-base sm:text-xl font-black text-medical-gray-900 font-vazir">همه مقالات تخصصی</h2>
|
||||||
|
<span className="text-xs font-bold text-medical-gray-400">
|
||||||
|
{toPersian(regularPosts.length)} مقاله
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-8">
|
||||||
|
{slicedRegularPosts.map((post, idx) => (
|
||||||
|
<motion.a
|
||||||
key={post.id}
|
key={post.id}
|
||||||
|
href={`/blog/${encodeURIComponent(post.slug || post.id)}`}
|
||||||
initial={{ opacity: 0, y: 20 }}
|
initial={{ opacity: 0, y: 20 }}
|
||||||
whileInView={{ opacity: 1, y: 0 }}
|
whileInView={{ opacity: 1, y: 0 }}
|
||||||
viewport={{ once: true }}
|
viewport={{ once: true }}
|
||||||
transition={{ delay: idx * 0.05 }}
|
transition={{ delay: idx * 0.05 }}
|
||||||
className="bg-white rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-lg group hover:shadow-2xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between"
|
className="bg-white rounded-2xl sm:rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-xs sm:shadow-lg group hover:shadow-xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between"
|
||||||
onClick={() => router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)}
|
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
|
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
|
||||||
@@ -348,7 +404,7 @@ export default function BlogPage({
|
|||||||
<span>{(post.viewCount ?? 0).toLocaleString('fa-IR')}</span>
|
<span>{(post.viewCount ?? 0).toLocaleString('fa-IR')}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-6 sm:p-7">
|
<div className="p-4 sm:p-7">
|
||||||
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3">
|
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3">
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
<Calendar className="w-3 h-3" />
|
<Calendar className="w-3 h-3" />
|
||||||
@@ -374,7 +430,7 @@ export default function BlogPage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="px-6 sm:px-7 pb-6 pt-3 border-t border-medical-gray-100 flex items-center justify-between">
|
<div className="px-4 sm:px-7 pb-4 sm:pb-6 pt-2.5 border-t border-medical-gray-100 flex items-center justify-between">
|
||||||
<div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5">
|
<div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5">
|
||||||
<User className="w-3.5 h-3.5 text-medical-gray-400" />
|
<User className="w-3.5 h-3.5 text-medical-gray-400" />
|
||||||
<span>{post.author}</span>
|
<span>{post.author}</span>
|
||||||
@@ -384,9 +440,25 @@ export default function BlogPage({
|
|||||||
<ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
|
<ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.a>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{hasMore && (
|
||||||
|
<div className="mt-8 mb-4 text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setVisibleCount(prev => prev + 6)}
|
||||||
|
className="inline-flex items-center gap-2 px-6 py-3 bg-white border border-medical-gray-200 hover:border-canina-blue text-canina-blue font-black text-xs sm:text-sm rounded-2xl shadow-xs hover:shadow-md active:scale-95 transition-all cursor-pointer font-vazir"
|
||||||
|
>
|
||||||
|
<span>مشاهده ۶ مقاله بیشتر</span>
|
||||||
|
<span className="text-xs text-medical-gray-400 font-bold">
|
||||||
|
(نمایش {toPersian(slicedRegularPosts.length)} از {toPersian(regularPosts.length)})
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-center py-16 bg-white rounded-3xl border border-medical-gray-200">
|
<div className="text-center py-16 bg-white rounded-3xl border border-medical-gray-200">
|
||||||
<p className="text-medical-gray-500 font-bold text-sm">
|
<p className="text-medical-gray-500 font-bold text-sm">
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import DOMPurify from 'dompurify';
|
|
||||||
import {
|
import {
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Calendar,
|
Calendar,
|
||||||
@@ -19,14 +18,17 @@ import {
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import SafeImage from "./SafeImage";
|
import SafeImage from "./SafeImage";
|
||||||
import api from "../lib/services/api";
|
import api from "../lib/services/api";
|
||||||
|
import ArticleContentRenderer from "./ArticleContentRenderer";
|
||||||
|
|
||||||
|
|
||||||
interface BlogPostClientProps {
|
interface BlogPostClientProps {
|
||||||
blog: any;
|
blog: any;
|
||||||
publishedDate: string;
|
publishedDate: string;
|
||||||
authorName: string;
|
authorName: string;
|
||||||
|
sanitizedContent: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function BlogPostClient({ blog, publishedDate, authorName }: BlogPostClientProps) {
|
export default function BlogPostClient({ blog, publishedDate, authorName, sanitizedContent }: BlogPostClientProps) {
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0);
|
const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0);
|
||||||
const [commentName, setCommentName] = useState("");
|
const [commentName, setCommentName] = useState("");
|
||||||
@@ -173,17 +175,10 @@ export default function BlogPostClient({ blog, publishedDate, authorName }: Blog
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Main Rich Content HTML Renderer */}
|
{/* Main Rich Content HTML Renderer with In-Article Product Cards */}
|
||||||
<div
|
<ArticleContentRenderer
|
||||||
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
|
contentHtml={sanitizedContent}
|
||||||
dangerouslySetInnerHTML={{
|
relatedProducts={relatedProducts}
|
||||||
__html: typeof window !== 'undefined'
|
|
||||||
? DOMPurify.sanitize(blog.content || '', {
|
|
||||||
ADD_TAGS: ['iframe'],
|
|
||||||
ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'],
|
|
||||||
})
|
|
||||||
: blog.content || '',
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Tags Chip Footer */}
|
{/* Tags Chip Footer */}
|
||||||
|
|||||||
@@ -56,10 +56,10 @@ export default function BlogPreviewSection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="py-8 sm:py-20 bg-white font-vazir" dir="rtl">
|
<section className="py-5 sm:py-20 bg-white font-vazir" dir="rtl">
|
||||||
<div className="max-w-7xl mx-auto px-4">
|
<div className="max-w-7xl mx-auto px-4">
|
||||||
{/* Section Header */}
|
{/* Section Header */}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-end justify-between mb-6 sm:mb-12 pb-4 sm:pb-6 border-b border-medical-gray-200 gap-3 sm:gap-6">
|
<div className="flex flex-col sm:flex-row sm:items-end justify-between mb-4 sm:mb-12 pb-3 sm:pb-6 border-b border-medical-gray-200 gap-2 sm:gap-6">
|
||||||
<div className="max-w-2xl">
|
<div className="max-w-2xl">
|
||||||
<div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-full text-[10px] font-black uppercase tracking-widest mb-2 sm:mb-3 font-vazir">
|
<div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-full text-[10px] font-black uppercase tracking-widest mb-2 sm:mb-3 font-vazir">
|
||||||
<BookOpen className="w-3 h-3" />
|
<BookOpen className="w-3 h-3" />
|
||||||
|
|||||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user