Compare commits
135
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55d11fa597 | ||
|
|
85ef01d337 | ||
|
|
4d41a5bbf7 | ||
|
|
625c3f5ce2 | ||
|
|
6fbbd7140d | ||
|
|
468856538c | ||
|
|
27b61ce6d5 | ||
|
|
054b9470ab | ||
|
|
55d1bb5967 | ||
|
|
6c1a11a8e2 | ||
|
|
1c4f7e9d10 | ||
|
|
d9cf64d0be | ||
|
|
3a0e0f2acc | ||
|
|
fae4b570f9 | ||
|
|
d881dc491e | ||
|
|
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 |
No files matched your search
@@ -13,6 +13,9 @@ 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 }}
|
||||||
|
DEPLOY_SHA: ${{ github.sha }}
|
||||||
|
GITHUB_ACTIONS: 'true'
|
||||||
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
|
||||||
@@ -24,7 +27,10 @@ jobs:
|
|||||||
|
|
||||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||||
mkdir -p scripts
|
mkdir -p scripts
|
||||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh
|
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||||
|
if [ "$BRANCH" = develop ]; then
|
||||||
|
wget --no-proxy -qO scripts/release-corporate-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-corporate-stage.sh
|
||||||
|
fi
|
||||||
|
|
||||||
chmod +x scripts/deploy.sh
|
chmod +x scripts/deploy.sh
|
||||||
cd scripts
|
cd scripts
|
||||||
|
|||||||
@@ -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,35 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function cleanFaqs() {
|
||||||
|
console.log('--- Cleaning Misplaced Content Tasks from FAQs ---');
|
||||||
|
const countBefore = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs before cleanup: ${countBefore}`);
|
||||||
|
|
||||||
|
const deleteResult = await prisma.fAQ.deleteMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ question: { contains: 'راهنمای' } },
|
||||||
|
{ question: { contains: 'اینفوگرافیک' } },
|
||||||
|
{ question: { contains: 'نگارش' } },
|
||||||
|
{ question: { contains: 'تدوین' } },
|
||||||
|
{ question: { contains: 'تولید' } },
|
||||||
|
{ question: { contains: 'مقاله' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks.`);
|
||||||
|
const countAfter = await prisma.fAQ.count();
|
||||||
|
console.log(`Total real customer FAQs remaining: ${countAfter}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanFaqs()
|
||||||
|
.catch((err) => {
|
||||||
|
console.error('Clean FAQs error:', err);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "advisor_contacts" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"name" VARCHAR(150) NOT NULL,
|
||||||
|
"phone" VARCHAR(20) NOT NULL,
|
||||||
|
"title" VARCHAR(100),
|
||||||
|
"is_default" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "advisor_contacts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "product_advisors" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"product_id" UUID NOT NULL,
|
||||||
|
"advisor_id" UUID NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "product_advisors_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "leads" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"first_name" VARCHAR(100) NOT NULL,
|
||||||
|
"last_name" VARCHAR(100) NOT NULL,
|
||||||
|
"phone" VARCHAR(20) NOT NULL,
|
||||||
|
"product_id" UUID,
|
||||||
|
"advisor_id" UUID,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||||
|
"notes" TEXT,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "leads_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "notification_queues" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"channel" VARCHAR(20) NOT NULL,
|
||||||
|
"recipient" VARCHAR(150) NOT NULL,
|
||||||
|
"event" VARCHAR(50) NOT NULL,
|
||||||
|
"subject" VARCHAR(255),
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"payload" JSONB,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'QUEUED',
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"max_attempts" INTEGER NOT NULL DEFAULT 3,
|
||||||
|
"last_error" TEXT,
|
||||||
|
"idempotency_key" VARCHAR(100),
|
||||||
|
"sent_at" TIMESTAMPTZ,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "notification_queues_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "notification_templates" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"channel" VARCHAR(20) NOT NULL,
|
||||||
|
"event" VARCHAR(50) NOT NULL,
|
||||||
|
"name" VARCHAR(150) NOT NULL,
|
||||||
|
"subject" VARCHAR(255),
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"pattern_code" VARCHAR(50),
|
||||||
|
"variables" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"recipient_type" VARCHAR(30) NOT NULL DEFAULT 'customer',
|
||||||
|
"custom_recipient" VARCHAR(150),
|
||||||
|
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "notification_templates_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "advisor_contacts_phone_key" ON "advisor_contacts"("phone");
|
||||||
|
CREATE INDEX "advisor_contacts_phone_idx" ON "advisor_contacts"("phone");
|
||||||
|
CREATE INDEX "advisor_contacts_is_default_idx" ON "advisor_contacts"("is_default");
|
||||||
|
CREATE INDEX "advisor_contacts_is_active_idx" ON "advisor_contacts"("is_active");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "product_advisors_product_id_advisor_id_key" ON "product_advisors"("product_id", "advisor_id");
|
||||||
|
CREATE INDEX "product_advisors_product_id_idx" ON "product_advisors"("product_id");
|
||||||
|
CREATE INDEX "product_advisors_advisor_id_idx" ON "product_advisors"("advisor_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "leads_phone_idx" ON "leads"("phone");
|
||||||
|
CREATE INDEX "leads_status_idx" ON "leads"("status");
|
||||||
|
CREATE INDEX "leads_created_at_idx" ON "leads"("created_at");
|
||||||
|
CREATE INDEX "leads_advisor_id_idx" ON "leads"("advisor_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "notification_queues_idempotency_key_key" ON "notification_queues"("idempotency_key");
|
||||||
|
CREATE INDEX "notification_queues_status_idx" ON "notification_queues"("status");
|
||||||
|
CREATE INDEX "notification_queues_channel_idx" ON "notification_queues"("channel");
|
||||||
|
CREATE INDEX "notification_queues_event_idx" ON "notification_queues"("event");
|
||||||
|
CREATE INDEX "notification_queues_created_at_idx" ON "notification_queues"("created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "notification_templates_channel_event_key" ON "notification_templates"("channel", "event");
|
||||||
|
CREATE INDEX "notification_templates_channel_idx" ON "notification_templates"("channel");
|
||||||
|
CREATE INDEX "notification_templates_event_idx" ON "notification_templates"("event");
|
||||||
|
CREATE INDEX "notification_templates_is_active_idx" ON "notification_templates"("is_active");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "leads" ADD CONSTRAINT "leads_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "leads" ADD CONSTRAINT "leads_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
-- CreateTable approval_requests
|
||||||
|
CREATE TABLE IF NOT EXISTS public.approval_requests (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"department" VARCHAR(50) NOT NULL,
|
||||||
|
"category" VARCHAR(50) NOT NULL,
|
||||||
|
"title" VARCHAR(255) NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"test_context" JSONB,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||||
|
"ceo_notes" TEXT,
|
||||||
|
"executed_at" TIMESTAMPTZ(6),
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "approval_requests_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable audit_logs
|
||||||
|
CREATE TABLE IF NOT EXISTS public.audit_logs (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"entity" VARCHAR(50) NOT NULL,
|
||||||
|
"entity_id" VARCHAR(100),
|
||||||
|
"action" VARCHAR(50) NOT NULL,
|
||||||
|
"department" VARCHAR(50),
|
||||||
|
"actor" VARCHAR(100) NOT NULL DEFAULT 'SYSTEM',
|
||||||
|
"summary" VARCHAR(255) NOT NULL,
|
||||||
|
"old_values" JSONB,
|
||||||
|
"new_values" JSONB,
|
||||||
|
"metadata" JSONB,
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable department_tasks
|
||||||
|
CREATE TABLE IF NOT EXISTS public.department_tasks (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"code" VARCHAR(50) NOT NULL,
|
||||||
|
"department" VARCHAR(50) NOT NULL,
|
||||||
|
"title" VARCHAR(255) NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'BACKLOG',
|
||||||
|
"priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM',
|
||||||
|
"assignee" VARCHAR(100),
|
||||||
|
"acceptance_criteria" JSONB,
|
||||||
|
"execution_logs" JSONB,
|
||||||
|
"deliverable_url" VARCHAR(255),
|
||||||
|
"approval_id" UUID,
|
||||||
|
"started_at" TIMESTAMPTZ(6),
|
||||||
|
"completed_at" TIMESTAMPTZ(6),
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "department_tasks_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "department_tasks_code_key" ON public.department_tasks("code");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_department_idx" ON public.approval_requests("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_category_idx" ON public.approval_requests("category");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_status_idx" ON public.approval_requests("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_created_at_idx" ON public.approval_requests("created_at");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_entity_idx" ON public.audit_logs("entity");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON public.audit_logs("action");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_department_idx" ON public.audit_logs("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_created_at_idx" ON public.audit_logs("created_at");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_department_idx" ON public.department_tasks("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_status_idx" ON public.department_tasks("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_priority_idx" ON public.department_tasks("priority");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_created_at_idx" ON public.department_tasks("created_at");
|
||||||
@@ -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
|
||||||
@@ -249,6 +286,8 @@ model Product {
|
|||||||
reviews ProductReview[]
|
reviews ProductReview[]
|
||||||
competitorPriceLogs CompetitorPriceLog[]
|
competitorPriceLogs CompetitorPriceLog[]
|
||||||
priceSuggestions PriceSuggestion[]
|
priceSuggestions PriceSuggestion[]
|
||||||
|
productAdvisors ProductAdvisor[]
|
||||||
|
leads Lead[]
|
||||||
|
|
||||||
@@index([categorySlug])
|
@@index([categorySlug])
|
||||||
@@index([suitableFor])
|
@@index([suitableFor])
|
||||||
@@ -1051,3 +1090,320 @@ model DepartmentTask {
|
|||||||
@@index([createdAt])
|
@@index([createdAt])
|
||||||
@@map("department_tasks")
|
@@map("department_tasks")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 8. AdvisorContact (مشاوران تخصصی و پاسخگویی)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model AdvisorContact {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
name String @db.VarChar(150)
|
||||||
|
phone String @unique @db.VarChar(20)
|
||||||
|
title String? @db.VarChar(100)
|
||||||
|
isDefault Boolean @default(false) @map("is_default")
|
||||||
|
isActive Boolean @default(true) @map("is_active")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
productAdvisors ProductAdvisor[]
|
||||||
|
leads Lead[]
|
||||||
|
|
||||||
|
@@index([phone])
|
||||||
|
@@index([isDefault])
|
||||||
|
@@index([isActive])
|
||||||
|
@@map("advisor_contacts")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 9. ProductAdvisor (اتصال مشاور به محصول)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model ProductAdvisor {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
productId String @map("product_id") @db.Uuid
|
||||||
|
advisorId String @map("advisor_id") @db.Uuid
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||||
|
advisor AdvisorContact @relation(fields: [advisorId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([productId, advisorId])
|
||||||
|
@@index([productId])
|
||||||
|
@@index([advisorId])
|
||||||
|
@@map("product_advisors")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 10. Lead (درخواستهای تماس و مشاوره کاربران)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model Lead {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
firstName String @map("first_name") @db.VarChar(100)
|
||||||
|
lastName String @map("last_name") @db.VarChar(100)
|
||||||
|
phone String @db.VarChar(20)
|
||||||
|
productId String? @map("product_id") @db.Uuid
|
||||||
|
advisorId String? @map("advisor_id") @db.Uuid
|
||||||
|
status String @default("PENDING") @db.VarChar(30) // PENDING, CONTACTED, CANCELLED
|
||||||
|
notes String? @db.Text
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
|
||||||
|
advisor AdvisorContact? @relation(fields: [advisorId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([phone])
|
||||||
|
@@index([status])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@index([advisorId])
|
||||||
|
@@map("leads")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 11. NotificationQueue (صف ناهمگام نوتیفیکیشنها با قابلیت Retry و Idempotency)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model NotificationQueue {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
channel String @db.VarChar(20) // SMS, EMAIL
|
||||||
|
recipient String @db.VarChar(150)
|
||||||
|
event String @db.VarChar(50)
|
||||||
|
subject String? @db.VarChar(255)
|
||||||
|
content String @db.Text
|
||||||
|
payload Json? @db.JsonB
|
||||||
|
status String @default("QUEUED") @db.VarChar(30) // QUEUED, PROCESSING, SENT, FAILED
|
||||||
|
attempts Int @default(0)
|
||||||
|
maxAttempts Int @default(3) @map("max_attempts")
|
||||||
|
lastError String? @map("last_error") @db.Text
|
||||||
|
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(100)
|
||||||
|
sentAt DateTime? @map("sent_at") @db.Timestamptz()
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
@@index([status])
|
||||||
|
@@index([channel])
|
||||||
|
@@index([event])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("notification_queues")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 12. NotificationTemplate (قالبهای رویدادها برای ایمیل و پیامک)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model NotificationTemplate {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
channel String @db.VarChar(20) // SMS, EMAIL
|
||||||
|
event String @db.VarChar(50) // ORDER_CREATED, PAYMENT_SUCCESS, NEW_LEAD, etc.
|
||||||
|
name String @db.VarChar(150)
|
||||||
|
subject String? @db.VarChar(255)
|
||||||
|
body String @db.Text
|
||||||
|
patternCode String? @map("pattern_code") @db.VarChar(50)
|
||||||
|
variables String[] @default([])
|
||||||
|
recipientType String @default("customer") @map("recipient_type") @db.VarChar(30)
|
||||||
|
customRecipient String? @map("custom_recipient") @db.VarChar(150)
|
||||||
|
isActive Boolean @default(true) @map("is_active")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
@@unique([channel, event])
|
||||||
|
@@index([channel])
|
||||||
|
@@index([event])
|
||||||
|
@@index([isActive])
|
||||||
|
@@map("notification_templates")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
enum CorporateTaskStatus {
|
||||||
|
TODO
|
||||||
|
IN_PROGRESS
|
||||||
|
TEST
|
||||||
|
DONE
|
||||||
|
BLOCKED
|
||||||
|
REJECTED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum CorporatePriority {
|
||||||
|
CEO_EXPEDITE
|
||||||
|
CRITICAL
|
||||||
|
HIGH
|
||||||
|
MEDIUM
|
||||||
|
LOW
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateTask {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskCode String @unique
|
||||||
|
title String
|
||||||
|
normalizedTitle String
|
||||||
|
normalizedCode String
|
||||||
|
description String
|
||||||
|
department String
|
||||||
|
priority CorporatePriority @default(CEO_EXPEDITE)
|
||||||
|
status CorporateTaskStatus @default(TODO)
|
||||||
|
actionType String @default("CEO_DIRECTIVE")
|
||||||
|
dueCycle String?
|
||||||
|
parentId String? @db.Uuid
|
||||||
|
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
|
||||||
|
children CorporateTask[] @relation("TaskChildren")
|
||||||
|
goalId String? @db.Uuid
|
||||||
|
goal CorporateGoal? @relation(fields: [goalId], references: [id])
|
||||||
|
assignedAgent String?
|
||||||
|
claimToken String? @db.Uuid
|
||||||
|
leasedUntil DateTime? @db.Timestamptz()
|
||||||
|
executionCount Int @default(0)
|
||||||
|
qaCount Int @default(0)
|
||||||
|
rejectionCount Int @default(0)
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
updatedAt DateTime @updatedAt @db.Timestamptz()
|
||||||
|
logs CorporateEvent[]
|
||||||
|
evidence CorporateEvidence[]
|
||||||
|
reviews CorporateReview[]
|
||||||
|
effects CorporateEffect[]
|
||||||
|
@@index([status, priority, updatedAt])
|
||||||
|
@@index([parentId])
|
||||||
|
@@index([goalId])
|
||||||
|
@@map("corporate_tasks")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEvent {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
speaker String
|
||||||
|
speakerName String
|
||||||
|
step String
|
||||||
|
content String
|
||||||
|
payload Json?
|
||||||
|
timestamp DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId, timestamp])
|
||||||
|
@@map("corporate_events")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEvidence {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
claimToken String @db.Uuid
|
||||||
|
executor String
|
||||||
|
artifactUri String
|
||||||
|
sha256 String
|
||||||
|
summary String
|
||||||
|
tool String
|
||||||
|
result String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
reviews CorporateReview[]
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_evidence")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateReview {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
evidenceId String @db.Uuid
|
||||||
|
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
|
||||||
|
reviewer String
|
||||||
|
passed Boolean
|
||||||
|
findings String
|
||||||
|
verification Json
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_reviews")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateResearch {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
title String
|
||||||
|
category String
|
||||||
|
source String
|
||||||
|
opportunity String
|
||||||
|
impact String
|
||||||
|
recommendedAction String
|
||||||
|
status String @default("DISCOVERED")
|
||||||
|
cadence String
|
||||||
|
provenance Json
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
sources CorporateSource[]
|
||||||
|
roadmaps CorporateRoadmap[]
|
||||||
|
@@map("corporate_research")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateSource {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
researchId String @db.Uuid
|
||||||
|
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||||
|
url String
|
||||||
|
title String
|
||||||
|
excerpt String
|
||||||
|
retrievedAt DateTime @db.Timestamptz()
|
||||||
|
sha256 String
|
||||||
|
@@index([researchId])
|
||||||
|
@@map("corporate_sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateRoadmap {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
researchId String @db.Uuid
|
||||||
|
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||||
|
cycleName String
|
||||||
|
month String
|
||||||
|
seasonalTheme String
|
||||||
|
strategicGoals String[]
|
||||||
|
plannedArticlesCount Int
|
||||||
|
plannedRefreshesCount Int
|
||||||
|
plannedCatalogEnrichments Int
|
||||||
|
isActive Boolean @default(false)
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
goals CorporateGoal[]
|
||||||
|
@@index([month])
|
||||||
|
@@map("corporate_roadmaps")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateGoal {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
roadmapId String @db.Uuid
|
||||||
|
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
|
||||||
|
title String
|
||||||
|
department String
|
||||||
|
acceptanceCriteria String
|
||||||
|
metric String
|
||||||
|
target Float?
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
tasks CorporateTask[]
|
||||||
|
@@index([roadmapId])
|
||||||
|
@@map("corporate_goals")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEffect {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
metric String
|
||||||
|
availability String
|
||||||
|
baseline Float?
|
||||||
|
observed Float?
|
||||||
|
source String
|
||||||
|
observedAt DateTime @db.Timestamptz()
|
||||||
|
recordedBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_effects")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateReport {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
day String @unique
|
||||||
|
summary String
|
||||||
|
snapshot Json
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@map("corporate_reports")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateOperation {
|
||||||
|
key String @id
|
||||||
|
payloadHash String
|
||||||
|
response Json
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@map("corporate_operations")
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const defaultFaqs = [
|
||||||
|
{
|
||||||
|
order: 1,
|
||||||
|
question: 'آیا برای خرید مکملهای تخصصی کنینا به نسخه دامپزشک نیاز است؟',
|
||||||
|
answer: 'خیر، مکملهای غذایی و درمانی کنینا بدون نسخه قابل سفارش هستند. با این وجود جهت تعیین دقیقترین دوز مصرفی متناسب با سن، وزن و شرایط بالینی پت دلبندتان، میتوانید از خدمات مشاوره تخصصی و رایگان دامپزشکان کنینا استفاده نمایید.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 2,
|
||||||
|
question: 'چگونه میتوانم از اصالت مکملهای آلمانی کنینا اطمینان حاصل کنم؟',
|
||||||
|
answer: 'تمامی محصولات کنینا در ایران به صورت ۱۰۰٪ اورجینال و با هولوگرام اصالت، بارکد رسمی کارخانه Canina pharma GmbH آلمان و بچنامبر معتبر عرضه میگردند و اصالت آنها تضمین بالینی و قانونی دارد.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 3,
|
||||||
|
question: 'ارسال سفارشها به چه صورت است و چقدر زمان میبرد؟',
|
||||||
|
answer: 'سفارشهای تهران از طریق پیک اختصاصی و اکسپرس در همان روز یا روز بعد و سفارشهای سراسر کشور از طریق پست پیشتاز و تیپاکس ظرف ۲ الی ۴ روز کاری با بستهبندی ایمن و استاندارد تحویل داده میشوند.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 4,
|
||||||
|
question: 'شرایط ارسال رایگان سفارشها چیست؟',
|
||||||
|
answer: 'سفارشهای بالای ۲,۰۰۰,۰۰۰ تومان در سراسر کشور مشمول ارسال کاملاً رایگان کنینا خواهند شد.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 5,
|
||||||
|
question: 'آیا امکان دریافت مشاوره قبل از خرید مکمل مفاصل یا کلسیم وجود دارد؟',
|
||||||
|
answer: 'بله، شما میتوانید از طریق کلید شناور «درخواست مشاوره تلفنی» در سایت یا شماره تماس پشتیبانی با کارشناسان و کادر دامپزشکی ما گفتگوی مستقیم و رایگان داشته باشید.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
async function seedRealFaqs() {
|
||||||
|
console.log('--- Seeding Real Customer FAQs ---');
|
||||||
|
for (const item of defaultFaqs) {
|
||||||
|
await prisma.fAQ.create({
|
||||||
|
data: item,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const count = await prisma.fAQ.count();
|
||||||
|
console.log(`Successfully seeded real customer FAQs. Total count: ${count}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
seedRealFaqs()
|
||||||
|
.catch((err) => {
|
||||||
|
console.error('Seed error:', err);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('--- Inspecting and Cleaning FAQs ---');
|
||||||
|
|
||||||
|
const totalBefore = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs before: ${totalBefore}`);
|
||||||
|
|
||||||
|
const activeCount = await prisma.fAQ.count({ where: { isActive: true } });
|
||||||
|
const inactiveCount = await prisma.fAQ.count({ where: { isActive: false } });
|
||||||
|
console.log(`Active FAQs: ${activeCount}, Inactive FAQs: ${inactiveCount}`);
|
||||||
|
|
||||||
|
// Fetch sample of active and inactive
|
||||||
|
const sampleActive = await prisma.fAQ.findMany({
|
||||||
|
where: { isActive: true },
|
||||||
|
select: { id: true, question: true, order: true },
|
||||||
|
take: 5,
|
||||||
|
});
|
||||||
|
console.log('Sample Active FAQs:', JSON.stringify(sampleActive, null, 2));
|
||||||
|
|
||||||
|
// Find tasks that contain content development phrases
|
||||||
|
const tasksToDelete = await prisma.fAQ.findMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ question: { contains: 'راهنمای' } },
|
||||||
|
{ question: { contains: 'اینفوگرافیک' } },
|
||||||
|
{ question: { contains: 'نگارش' } },
|
||||||
|
{ question: { contains: 'تدوین' } },
|
||||||
|
{ question: { contains: 'تولید' } },
|
||||||
|
{ question: { contains: 'مقاله' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { id: true, question: true, isActive: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Found ${tasksToDelete.length} content tasks inside FAQs table.`);
|
||||||
|
|
||||||
|
if (tasksToDelete.length > 0) {
|
||||||
|
const ids = tasksToDelete.map(t => t.id);
|
||||||
|
const deleteResult = await prisma.fAQ.deleteMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
});
|
||||||
|
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks from faqs.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalAfter = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs remaining: ${totalAfter}`);
|
||||||
|
|
||||||
|
const remaining = await prisma.fAQ.findMany({
|
||||||
|
select: { id: true, question: true, isActive: true, order: true },
|
||||||
|
take: 10,
|
||||||
|
});
|
||||||
|
console.log('Remaining FAQs:', JSON.stringify(remaining, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch(e => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
import { CorporateController } from "./hermes/corporate.controller";
|
||||||
|
import { CorporateService } from "./hermes/corporate.service";
|
||||||
import { AdminController } from "./admin.controller";
|
import { AdminController } from "./admin.controller";
|
||||||
import { AdminService } from "./admin.service";
|
import { AdminService } from "./admin.service";
|
||||||
import { ReportsController } from "./reports.controller";
|
import { ReportsController } from "./reports.controller";
|
||||||
@@ -27,10 +29,13 @@ 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],
|
||||||
controllers: [
|
controllers: [
|
||||||
|
CorporateController,
|
||||||
AdminController,
|
AdminController,
|
||||||
ReportsController,
|
ReportsController,
|
||||||
MediaController,
|
MediaController,
|
||||||
@@ -47,8 +52,10 @@ import { SettingsModule } from "../settings/settings.module";
|
|||||||
ApprovalsController,
|
ApprovalsController,
|
||||||
AuditLogsController,
|
AuditLogsController,
|
||||||
DepartmentTasksController,
|
DepartmentTasksController,
|
||||||
|
SupportChatAnalyticsController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
|
CorporateService,
|
||||||
AdminService,
|
AdminService,
|
||||||
ReportsService,
|
ReportsService,
|
||||||
MediaService,
|
MediaService,
|
||||||
@@ -58,6 +65,7 @@ import { SettingsModule } from "../settings/settings.module";
|
|||||||
PetsService,
|
PetsService,
|
||||||
SslService,
|
SslService,
|
||||||
ApiKeysService,
|
ApiKeysService,
|
||||||
|
SupportChatAnalyticsService,
|
||||||
],
|
],
|
||||||
exports: [ApiKeysService, MediaService],
|
exports: [ApiKeysService, MediaService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import {
|
||||||
|
normalizeSearch,
|
||||||
|
pagination,
|
||||||
|
taskInput,
|
||||||
|
monthlyPlanInput,
|
||||||
|
} from './corporate-policy';
|
||||||
|
describe('corporate contract policy', () => {
|
||||||
|
it.each([
|
||||||
|
['2027-02', 28],
|
||||||
|
['2028-02', 29],
|
||||||
|
['2028-04', 30],
|
||||||
|
['2028-01', 31],
|
||||||
|
])('enforces real calendar coverage for %s', (month, count) => {
|
||||||
|
const id = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const body = {
|
||||||
|
roadmapId: id,
|
||||||
|
month,
|
||||||
|
needs: [],
|
||||||
|
dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({
|
||||||
|
title: 'new article',
|
||||||
|
description: 'instruction',
|
||||||
|
actionType: 'BLOG_NEW',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
goalId: id,
|
||||||
|
sourceIds: [id],
|
||||||
|
dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count));
|
||||||
|
expect(() =>
|
||||||
|
monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }),
|
||||||
|
).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
monthlyPlanInput({
|
||||||
|
...body,
|
||||||
|
dailyArticles: [...body.dailyArticles, body.dailyArticles[0]],
|
||||||
|
}),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
it('normalizes Persian letters, digits and separators', () => {
|
||||||
|
expect(normalizeSearch('كيك ۱۲۳ (ة)')).toBe('کیک 123 ه');
|
||||||
|
});
|
||||||
|
it('bounds pagination and sort keys', () => {
|
||||||
|
expect(pagination({ limit: '100' }).limit).toBe(100);
|
||||||
|
expect(() => pagination({ limit: '101' })).toThrow();
|
||||||
|
expect(() => pagination({ page: '-1' })).toThrow();
|
||||||
|
expect(() => pagination({ sortBy: 'password' })).toThrow();
|
||||||
|
});
|
||||||
|
it('defaults CEO priority and rejects status/command injection', () => {
|
||||||
|
expect(
|
||||||
|
taskInput({
|
||||||
|
title: 'عنوان',
|
||||||
|
description: 'کار',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
}).priority,
|
||||||
|
).toBe('CEO_EXPEDITE');
|
||||||
|
expect(() =>
|
||||||
|
taskInput({
|
||||||
|
title: 'x',
|
||||||
|
description: 'x',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
status: 'DONE',
|
||||||
|
}),
|
||||||
|
).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
export const departments = [
|
||||||
|
'CONTENT_SEO',
|
||||||
|
'CATALOG_COMMERCE',
|
||||||
|
'WIKI_SCIENTIFIC',
|
||||||
|
'TECH_DEVOPS',
|
||||||
|
'MARKET_INTELLIGENCE',
|
||||||
|
];
|
||||||
|
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||||
|
export const statuses = [
|
||||||
|
'TODO',
|
||||||
|
'IN_PROGRESS',
|
||||||
|
'TEST',
|
||||||
|
'DONE',
|
||||||
|
'BLOCKED',
|
||||||
|
'REJECTED',
|
||||||
|
'CANCELLED',
|
||||||
|
];
|
||||||
|
export function object(value: unknown, keys: string[]): Record<string, any> {
|
||||||
|
if (
|
||||||
|
!value ||
|
||||||
|
typeof value !== 'object' ||
|
||||||
|
Array.isArray(value) ||
|
||||||
|
Object.keys(value).some((k) => !keys.includes(k))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid fields');
|
||||||
|
return value as Record<string, any>;
|
||||||
|
}
|
||||||
|
export function text(value: unknown, max = 10000): string {
|
||||||
|
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
||||||
|
throw new BadRequestException('Invalid text');
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
export function uuid(value: unknown): string {
|
||||||
|
const id = text(value, 36);
|
||||||
|
if (
|
||||||
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid UUID');
|
||||||
|
return id.toLowerCase();
|
||||||
|
}
|
||||||
|
export function choice(value: unknown, values: string[]): string {
|
||||||
|
if (typeof value !== 'string' || !values.includes(value))
|
||||||
|
throw new BadRequestException('Invalid enum');
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function normalizeSearch(value: string): string {
|
||||||
|
return value
|
||||||
|
.normalize('NFKC')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[يى]/g, 'ی')
|
||||||
|
.replace(/ك/g, 'ک')
|
||||||
|
.replace(/ة/g, 'ه')
|
||||||
|
.replace(/[۰-۹٠-٩]/g, (c) =>
|
||||||
|
String(
|
||||||
|
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
|
||||||
|
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
|
||||||
|
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.replace(/[\u200c\u200d()()]/g, ' ')
|
||||||
|
.replace(/[\u064b-\u065f]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
export function pagination(q: Record<string, any>) {
|
||||||
|
const page = Number(q.page ?? 1),
|
||||||
|
limit = Number(q.limit ?? 20);
|
||||||
|
if (
|
||||||
|
!Number.isSafeInteger(page) ||
|
||||||
|
page < 1 ||
|
||||||
|
page > 1000000 ||
|
||||||
|
!Number.isInteger(limit) ||
|
||||||
|
limit < 1 ||
|
||||||
|
limit > 100
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid pagination');
|
||||||
|
const sortBy = choice(q.sortBy ?? 'createdAt', [
|
||||||
|
'createdAt',
|
||||||
|
'updatedAt',
|
||||||
|
'title',
|
||||||
|
'taskCode',
|
||||||
|
'priority',
|
||||||
|
'status',
|
||||||
|
]);
|
||||||
|
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
|
||||||
|
| 'asc'
|
||||||
|
| 'desc';
|
||||||
|
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
|
||||||
|
}
|
||||||
|
export function meta(total: number, page: number, limit: number) {
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages,
|
||||||
|
hasNextPage: page < totalPages,
|
||||||
|
hasPrevPage: page > 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function taskInput(input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'title',
|
||||||
|
'department',
|
||||||
|
'description',
|
||||||
|
'priority',
|
||||||
|
'parentId',
|
||||||
|
'goalId',
|
||||||
|
'actionType',
|
||||||
|
'dueCycle',
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
title: text(b.title, 300),
|
||||||
|
description: text(b.description),
|
||||||
|
department: choice(b.department, departments),
|
||||||
|
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
|
||||||
|
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
|
||||||
|
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
|
||||||
|
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
|
||||||
|
'CEO_DIRECTIVE',
|
||||||
|
'BLOG_NEW',
|
||||||
|
'BLOG_UPDATE',
|
||||||
|
'CATALOG_ENRICH',
|
||||||
|
'WIKI_ENRICH',
|
||||||
|
'RESEARCH',
|
||||||
|
'ENGINEERING',
|
||||||
|
]),
|
||||||
|
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function planMonth(value: unknown): string {
|
||||||
|
const month = text(value, 7);
|
||||||
|
if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month))
|
||||||
|
throw new BadRequestException('Invalid YYYY-MM month');
|
||||||
|
return month;
|
||||||
|
}
|
||||||
|
export function monthlyPlanInput(input: unknown) {
|
||||||
|
const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']);
|
||||||
|
const month = planMonth(b.month);
|
||||||
|
const days = new Date(
|
||||||
|
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0),
|
||||||
|
).getUTCDate();
|
||||||
|
if (
|
||||||
|
!Array.isArray(b.dailyArticles) ||
|
||||||
|
b.dailyArticles.length !== days ||
|
||||||
|
!Array.isArray(b.needs) ||
|
||||||
|
b.needs.length > 200
|
||||||
|
)
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Full daily article coverage and bounded needs required',
|
||||||
|
);
|
||||||
|
const mapping: Record<string, string> = {
|
||||||
|
BLOG_NEW: 'CONTENT_SEO',
|
||||||
|
BLOG_UPDATE: 'CONTENT_SEO',
|
||||||
|
CATALOG_ENRICH: 'CATALOG_COMMERCE',
|
||||||
|
WIKI_ENRICH: 'WIKI_SCIENTIFIC',
|
||||||
|
ENGINEERING: 'TECH_DEVOPS',
|
||||||
|
};
|
||||||
|
const parse = (raw: unknown, daily: boolean) => {
|
||||||
|
const t = object(raw, [
|
||||||
|
'title',
|
||||||
|
'description',
|
||||||
|
'department',
|
||||||
|
'priority',
|
||||||
|
'goalId',
|
||||||
|
'actionType',
|
||||||
|
'dueCycle',
|
||||||
|
'sourceIds',
|
||||||
|
'target',
|
||||||
|
'reason',
|
||||||
|
]);
|
||||||
|
const actionType = choice(
|
||||||
|
t.actionType,
|
||||||
|
daily
|
||||||
|
? ['BLOG_NEW']
|
||||||
|
: ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'],
|
||||||
|
);
|
||||||
|
const department = choice(t.department, [mapping[actionType]]);
|
||||||
|
const dueCycle = text(t.dueCycle, 10);
|
||||||
|
const date = new Date(dueCycle + 'T00:00:00Z');
|
||||||
|
if (
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) ||
|
||||||
|
!dueCycle.startsWith(month + '-') ||
|
||||||
|
!Number.isFinite(date.getTime()) ||
|
||||||
|
date.toISOString().slice(0, 10) !== dueCycle
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid plan day');
|
||||||
|
if (
|
||||||
|
!Array.isArray(t.sourceIds) ||
|
||||||
|
!t.sourceIds.length ||
|
||||||
|
t.sourceIds.length > 30
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Stored sources required');
|
||||||
|
const sourceIds = t.sourceIds.map(uuid);
|
||||||
|
if (new Set(sourceIds).size !== sourceIds.length)
|
||||||
|
throw new BadRequestException('Duplicate source');
|
||||||
|
if (daily && (t.target !== undefined || t.reason !== undefined))
|
||||||
|
throw new BadRequestException('Daily new articles cannot be needs');
|
||||||
|
return {
|
||||||
|
title: text(t.title, 300),
|
||||||
|
description: text(t.description),
|
||||||
|
department,
|
||||||
|
actionType,
|
||||||
|
dueCycle,
|
||||||
|
priority: choice(t.priority ?? 'MEDIUM', priorities),
|
||||||
|
goalId: uuid(t.goalId),
|
||||||
|
sourceIds,
|
||||||
|
...(daily
|
||||||
|
? {}
|
||||||
|
: { target: text(t.target, 2000), reason: text(t.reason) }),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const dailyArticles = b.dailyArticles.map((t) => parse(t, true));
|
||||||
|
if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days)
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Exactly one new article per calendar day required',
|
||||||
|
);
|
||||||
|
const needs = b.needs.map((t) => parse(t, false));
|
||||||
|
if (
|
||||||
|
new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle])))
|
||||||
|
.size !== needs.length
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Duplicate need');
|
||||||
|
return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs };
|
||||||
|
}
|
||||||
|
export function canonical(value: any): string {
|
||||||
|
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
||||||
|
if (value && typeof value === 'object')
|
||||||
|
return (
|
||||||
|
'{' +
|
||||||
|
Object.keys(value)
|
||||||
|
.sort()
|
||||||
|
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
|
||||||
|
.join(',') +
|
||||||
|
'}'
|
||||||
|
);
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
/** Public projection must also cover nested evidence and child records. */
|
||||||
|
export function publicData(value: any): any {
|
||||||
|
if (value instanceof Date) return value;
|
||||||
|
if (Array.isArray(value)) return value.map(publicData);
|
||||||
|
if (value && typeof value === 'object')
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(value)
|
||||||
|
.filter(([key]) => key !== 'claimToken')
|
||||||
|
.map(([key, item]) => [key, publicData(item)]),
|
||||||
|
);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function httpsUrl(value: unknown): string {
|
||||||
|
const raw = text(value, 2000);
|
||||||
|
try {
|
||||||
|
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw))
|
||||||
|
throw new Error();
|
||||||
|
const u = new URL(raw);
|
||||||
|
const host = u.hostname.toLowerCase();
|
||||||
|
if (
|
||||||
|
u.protocol !== 'https:' ||
|
||||||
|
u.username ||
|
||||||
|
u.password ||
|
||||||
|
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
|
||||||
|
host === 'localhost' ||
|
||||||
|
host.endsWith('.localhost') ||
|
||||||
|
/(^|\.)example\.(com|org|net)$/.test(host)
|
||||||
|
)
|
||||||
|
throw new Error();
|
||||||
|
return raw;
|
||||||
|
} catch {
|
||||||
|
throw new BadRequestException('Valid HTTPS host URL required');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function timestamp(value: unknown, message: string): Date {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
|
||||||
|
)
|
||||||
|
throw new BadRequestException(message);
|
||||||
|
const date = new Date(value);
|
||||||
|
if (
|
||||||
|
!Number.isFinite(date.getTime()) ||
|
||||||
|
date.getTime() > Date.now() ||
|
||||||
|
date.toISOString().slice(0, 19) !== value.slice(0, 19)
|
||||||
|
)
|
||||||
|
throw new BadRequestException(message);
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
export function evidenceInput(input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'claimToken',
|
||||||
|
'artifactUri',
|
||||||
|
'sha256',
|
||||||
|
'summary',
|
||||||
|
'tool',
|
||||||
|
'result',
|
||||||
|
]);
|
||||||
|
const uri = text(b.artifactUri, 2000);
|
||||||
|
|
||||||
|
const sha = text(b.sha256, 64);
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(sha))
|
||||||
|
throw new BadRequestException('Invalid digest');
|
||||||
|
if (uri.startsWith('urn:')) {
|
||||||
|
if (uri !== 'urn:sha256:' + sha)
|
||||||
|
throw new BadRequestException('Digest locator mismatch');
|
||||||
|
} else httpsUrl(uri);
|
||||||
|
return {
|
||||||
|
claimToken: uuid(b.claimToken),
|
||||||
|
artifactUri: uri,
|
||||||
|
sha256: sha,
|
||||||
|
summary: text(b.summary),
|
||||||
|
tool: text(b.tool, 100),
|
||||||
|
result: text(b.result),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Headers,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
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 { CorporateService } from './corporate.service';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import { text } from './corporate-policy';
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles('Admin', 'SUPER_ADMIN')
|
||||||
|
@Controller('admin/hermes')
|
||||||
|
export class CorporateController {
|
||||||
|
constructor(private readonly service: CorporateService) {}
|
||||||
|
private actor(req: any) {
|
||||||
|
// API keys must use their authenticated key identity, not an editable worker label.
|
||||||
|
const user = req.user;
|
||||||
|
const id = user?.id ?? user?.sub;
|
||||||
|
if (!id) throw new UnauthorizedException('Authenticated subject required');
|
||||||
|
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
|
||||||
|
}
|
||||||
|
private key(key?: string) {
|
||||||
|
return text(key, 200);
|
||||||
|
}
|
||||||
|
@Get('runtime') runtime() {
|
||||||
|
return {
|
||||||
|
mode: 'MANUAL_DORMANT',
|
||||||
|
schedulesEnabled: false,
|
||||||
|
externalExecutionEnabled: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
@Get('tasks') tasks(@Query() query: Record<string, any>) {
|
||||||
|
return this.service.tasks(query);
|
||||||
|
}
|
||||||
|
@Get('tasks/:id') detail(@Param('id') id: string) {
|
||||||
|
return this.service.detail(id);
|
||||||
|
}
|
||||||
|
@Post('tasks') create(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.create(this.actor(req), key ?? randomUUID(), body);
|
||||||
|
}
|
||||||
|
@Post('claims') claim(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.claim(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/evidence') evidence(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.submitEvidence(
|
||||||
|
this.actor(req),
|
||||||
|
this.key(key),
|
||||||
|
id,
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/reviews') review(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.review(this.actor(req), this.key(key), id, body);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/effects') effect(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.effect(this.actor(req), this.key(key), id, body);
|
||||||
|
}
|
||||||
|
@Get('market-insights') insights(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('market-insights', q);
|
||||||
|
}
|
||||||
|
@Post('market-insights') research(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.research(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('monthly-roadmap', q);
|
||||||
|
}
|
||||||
|
@Post('monthly-roadmap') roadmap(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.roadmap(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Post('monthly-plans') persistMonthlyPlan(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.persistMonthlyPlan(
|
||||||
|
this.actor(req),
|
||||||
|
this.key(key),
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@Get('monthly-plans/:roadmapId') monthlyPlan(
|
||||||
|
@Param('roadmapId') roadmapId: string,
|
||||||
|
@Query('month') month: string,
|
||||||
|
) {
|
||||||
|
return this.service.monthlyPlan(roadmapId, month);
|
||||||
|
}
|
||||||
|
@Get('reports') reports(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('reports', q);
|
||||||
|
}
|
||||||
|
@Post('reports') report(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.report(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,840 @@
|
|||||||
|
import passport from 'passport';
|
||||||
|
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { CorporateController } from './corporate.controller';
|
||||||
|
import { CorporateService } from './corporate.service';
|
||||||
|
import { ApiKeysService } from '../api-keys.service';
|
||||||
|
|
||||||
|
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||||
|
? describe
|
||||||
|
: describe.skip;
|
||||||
|
integration('corporate API / disposable PostgreSQL', () => {
|
||||||
|
let app: INestApplication, db: PrismaService;
|
||||||
|
const key = () => randomUUID();
|
||||||
|
const post = (path: string, body: any, actor = 'executor', op = key()) =>
|
||||||
|
request(app.getHttpServer())
|
||||||
|
.post('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', actor)
|
||||||
|
.set('Idempotency-Key', op)
|
||||||
|
.send(body);
|
||||||
|
const input = {
|
||||||
|
title: 'كيك ۱۲۳',
|
||||||
|
description: 'integration fixture',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
};
|
||||||
|
beforeAll(async () => {
|
||||||
|
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
|
||||||
|
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||||
|
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||||
|
throw new Error('Disposable loopback corporate_test DB required');
|
||||||
|
passport.use(
|
||||||
|
'jwt',
|
||||||
|
new Strategy(
|
||||||
|
{
|
||||||
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
|
secretOrKey: 'test-only-not-runtime',
|
||||||
|
},
|
||||||
|
(_payload, done) => done(null, false),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
db = new PrismaClient({
|
||||||
|
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
|
||||||
|
}) as PrismaService;
|
||||||
|
const module = await Test.createTestingModule({
|
||||||
|
controllers: [CorporateController],
|
||||||
|
providers: [
|
||||||
|
CorporateService,
|
||||||
|
{ provide: PrismaService, useValue: db },
|
||||||
|
{
|
||||||
|
provide: ApiKeysService,
|
||||||
|
useValue: {
|
||||||
|
validateKey: async (id: string) => ({
|
||||||
|
id,
|
||||||
|
isApiKey: true,
|
||||||
|
role: 'Admin',
|
||||||
|
scopes: id === 'unscoped' ? [] : ['admin'],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
app = module.createNestApplication();
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
||||||
|
await app.listen(0, '127.0.0.1');
|
||||||
|
});
|
||||||
|
afterAll(async () => {
|
||||||
|
if (db)
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||||
|
);
|
||||||
|
await app?.close();
|
||||||
|
await db?.$disconnect();
|
||||||
|
passport.unuse('jwt');
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
async function planFixture(month = '2996-02') {
|
||||||
|
const research = (
|
||||||
|
await post('market-insights', {
|
||||||
|
title: 'monthly fixture',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'disposable receipt',
|
||||||
|
opportunity: 'test planning',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'plan',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: {
|
||||||
|
method: 'fixture',
|
||||||
|
collector: 'jest',
|
||||||
|
context: 'disposable',
|
||||||
|
},
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'fixture',
|
||||||
|
excerpt: 'test only',
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const roadmap = (
|
||||||
|
await post('monthly-roadmap', {
|
||||||
|
researchId: research.id,
|
||||||
|
month,
|
||||||
|
cycleName: 'monthly fixture',
|
||||||
|
seasonalTheme: 'test',
|
||||||
|
strategicGoals: ['coverage'],
|
||||||
|
plannedArticlesCount: 29,
|
||||||
|
plannedRefreshesCount: 0,
|
||||||
|
plannedCatalogEnrichments: 0,
|
||||||
|
goals: [
|
||||||
|
'CONTENT_SEO',
|
||||||
|
'CATALOG_COMMERCE',
|
||||||
|
'WIKI_SCIENTIFIC',
|
||||||
|
'TECH_DEVOPS',
|
||||||
|
].map((department) => ({
|
||||||
|
title: department,
|
||||||
|
department,
|
||||||
|
acceptanceCriteria: 'independent QA',
|
||||||
|
metric: 'coverage',
|
||||||
|
})),
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const task = (
|
||||||
|
actionType: string,
|
||||||
|
department: string,
|
||||||
|
dueCycle: string,
|
||||||
|
) => ({
|
||||||
|
title: actionType + ' ' + dueCycle,
|
||||||
|
description: 'Evidence-backed instruction requiring QA',
|
||||||
|
actionType,
|
||||||
|
department,
|
||||||
|
dueCycle,
|
||||||
|
goalId: roadmap.goals.find((g: any) => g.department === department).id,
|
||||||
|
sourceIds: [research.sources[0].id],
|
||||||
|
...(actionType === 'BLOG_NEW'
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
target: 'https://canina.ir/identified-gap',
|
||||||
|
reason: 'Documented coverage gap',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
research,
|
||||||
|
roadmap,
|
||||||
|
body: {
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
month,
|
||||||
|
dailyArticles: Array.from({ length: 29 }, (_, i) =>
|
||||||
|
task(
|
||||||
|
'BLOG_NEW',
|
||||||
|
'CONTENT_SEO',
|
||||||
|
`${month}-${String(i + 1).padStart(2, '0')}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
needs: [
|
||||||
|
task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'),
|
||||||
|
task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'),
|
||||||
|
task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'),
|
||||||
|
task('ENGINEERING', 'TECH_DEVOPS', month + '-04'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => {
|
||||||
|
const { body, research, roadmap } = await planFixture();
|
||||||
|
body.roadmapId = body.roadmapId.toUpperCase();
|
||||||
|
for (const entry of [...body.dailyArticles, ...body.needs]) {
|
||||||
|
entry.goalId = entry.goalId.toUpperCase();
|
||||||
|
entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase());
|
||||||
|
}
|
||||||
|
const op = key();
|
||||||
|
const created = (
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(created.tasks).toHaveLength(33);
|
||||||
|
const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH');
|
||||||
|
expect(need.logs[0].payload).toMatchObject({
|
||||||
|
target: body.needs[2].target,
|
||||||
|
reason: body.needs[2].reason,
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'),
|
||||||
|
).toHaveLength(29);
|
||||||
|
expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true);
|
||||||
|
expect(
|
||||||
|
(await post('monthly-plans', body, 'planner', op).expect(201)).body,
|
||||||
|
).toEqual(created);
|
||||||
|
const read = await request(app.getHttpServer())
|
||||||
|
.get(`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(read.body).toEqual(created);
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + created.tasks[0].id)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.logs[0].step).toBe('PLANNED');
|
||||||
|
expect(detail.body.logs[0].payload).toMatchObject({
|
||||||
|
researchId: research.id,
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
month: body.month,
|
||||||
|
dueCycle: body.month + '-01',
|
||||||
|
sourceIds: [research.sources[0].id],
|
||||||
|
});
|
||||||
|
expect(await db.corporateOperation.count()).toBe(3);
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||||
|
});
|
||||||
|
it('validates calendar, action separation, needs and stored lineage without partial writes', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
const mutations: Array<[number, (b: any) => void]> = [
|
||||||
|
[400, (b) => b.dailyArticles.pop()],
|
||||||
|
[400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)],
|
||||||
|
[400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')],
|
||||||
|
[400, (b) => (b.month = '2028-13')],
|
||||||
|
[400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')],
|
||||||
|
[400, (b) => (b.needs[0].actionType = 'BLOG_NEW')],
|
||||||
|
[400, (b) => (b.needs[0].reason = ' ')],
|
||||||
|
[400, (b) => delete b.needs[0].target],
|
||||||
|
[400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')],
|
||||||
|
[400, (b) => (b.dailyArticles[0].sourceIds = [])],
|
||||||
|
[409, (b) => (b.dailyArticles[0].sourceIds = [key()])],
|
||||||
|
[409, (b) => (b.dailyArticles[0].goalId = key())],
|
||||||
|
[409, (b) => (b.needs[0].goalId = b.needs[1].goalId)],
|
||||||
|
[409, (b) => (b.roadmapId = key())],
|
||||||
|
];
|
||||||
|
for (const [status, mutate] of mutations) {
|
||||||
|
const invalid = JSON.parse(JSON.stringify(body));
|
||||||
|
mutate(invalid);
|
||||||
|
await post('monthly-plans', invalid).expect(status);
|
||||||
|
expect(await db.corporateTask.count()).toBe(0);
|
||||||
|
expect(await db.corporateEvent.count()).toBe(0);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/admin/hermes/monthly-plans')
|
||||||
|
.send(body)
|
||||||
|
.expect(401);
|
||||||
|
await post('monthly-plans', body, 'unscoped').expect(403);
|
||||||
|
const op = key();
|
||||||
|
const otherOp = key();
|
||||||
|
let release!: () => void;
|
||||||
|
let ready!: () => void;
|
||||||
|
const locked = new Promise<void>((r) => (ready = r));
|
||||||
|
const hold = new Promise<void>((r) => (release = r));
|
||||||
|
const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]);
|
||||||
|
const blocker = db.$transaction(async (tx) => {
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||||
|
ready();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await locked;
|
||||||
|
const pending = [
|
||||||
|
post('monthly-plans', body, 'planner', op).then((r) => r),
|
||||||
|
post('monthly-plans', body, 'other', otherOp).then((r) => r),
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
let waiters = 0;
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity
|
||||||
|
WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`;
|
||||||
|
waiters = rows.length;
|
||||||
|
if (waiters >= 2) break;
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
expect(waiters).toBeGreaterThanOrEqual(2);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await blocker;
|
||||||
|
}
|
||||||
|
const results = await Promise.all(pending);
|
||||||
|
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
|
||||||
|
expect(await db.corporateTask.count()).toBe(33);
|
||||||
|
expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe(
|
||||||
|
33,
|
||||||
|
);
|
||||||
|
const winner = results[0].status === 201 ? 'planner' : 'other';
|
||||||
|
const winningOp = winner === 'planner' ? op : otherOp;
|
||||||
|
await post(
|
||||||
|
'monthly-plans',
|
||||||
|
{ ...body, needs: [] },
|
||||||
|
winner,
|
||||||
|
winningOp,
|
||||||
|
).expect(409);
|
||||||
|
expect(
|
||||||
|
(await post('monthly-plans', body, winner, winningOp).expect(201)).body,
|
||||||
|
).toEqual(results[winner === 'planner' ? 0 : 1].body);
|
||||||
|
const runtime = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/runtime')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(runtime.body).toEqual({
|
||||||
|
mode: 'MANUAL_DORMANT',
|
||||||
|
schedulesEnabled: false,
|
||||||
|
externalExecutionEnabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
// Disposable-only trigger fails after the first task/event have been written.
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
`CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`,
|
||||||
|
);
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()',
|
||||||
|
);
|
||||||
|
const op = key();
|
||||||
|
try {
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(500);
|
||||||
|
expect(await db.corporateTask.count()).toBe(0);
|
||||||
|
expect(await db.corporateEvent.count()).toBe(0);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(2);
|
||||||
|
} finally {
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'DROP TRIGGER reject_plan_event ON corporate_events',
|
||||||
|
);
|
||||||
|
await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()');
|
||||||
|
}
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(201);
|
||||||
|
});
|
||||||
|
it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
await post('monthly-plans', body).expect(201);
|
||||||
|
const legacy = (
|
||||||
|
await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201)
|
||||||
|
).body;
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id);
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||||
|
// Model the persisted event's due-day boundary in the disposable DB without changing system time.
|
||||||
|
const planned = await db.corporateTask.findFirstOrThrow({
|
||||||
|
where: { actionType: 'BLOG_NEW' },
|
||||||
|
});
|
||||||
|
const day = new Date().toISOString().slice(0, 10);
|
||||||
|
await db.corporateTask.update({
|
||||||
|
where: { id: planned.id },
|
||||||
|
data: { dueCycle: day },
|
||||||
|
});
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed
|
||||||
|
const event = await db.corporateEvent.findFirstOrThrow({
|
||||||
|
where: { taskId: planned.id, step: 'PLANNED' },
|
||||||
|
});
|
||||||
|
await db.corporateEvent.update({
|
||||||
|
where: { id: event.id },
|
||||||
|
data: { payload: { ...(event.payload as object), dueCycle: day } },
|
||||||
|
});
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||||
|
planned.id,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
let release!: () => void, locked!: () => void;
|
||||||
|
const ready = new Promise<void>((r) => (locked = r));
|
||||||
|
const hold = new Promise<void>((r) => (release = r));
|
||||||
|
const claiming = db.$transaction(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id: parent.id },
|
||||||
|
data: {
|
||||||
|
status: 'IN_PROGRESS',
|
||||||
|
claimToken: key(),
|
||||||
|
assignedAgent: 'executor',
|
||||||
|
leasedUntil: new Date(Date.now() + 60000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
locked();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await ready;
|
||||||
|
const pending = post('tasks', { ...input, parentId: parent.id }).then(
|
||||||
|
(r) => r,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
|
||||||
|
let waiting = false;
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const rows = await db.$queryRaw<
|
||||||
|
any[]
|
||||||
|
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
|
||||||
|
if (rows.length) {
|
||||||
|
waiting = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
expect(waiting).toBe(true);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await claiming;
|
||||||
|
}
|
||||||
|
expect((await pending).status).toBe(409);
|
||||||
|
expect(
|
||||||
|
await db.corporateTask.count({ where: { parentId: parent.id } }),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||||
|
for (const status of ['TODO', 'BLOCKED'] as const) {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
await db.corporateTask.update({
|
||||||
|
where: { id: parent.id },
|
||||||
|
data: { status },
|
||||||
|
});
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||||
|
child.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
const body = {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: '',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
};
|
||||||
|
for (const artifactUri of [
|
||||||
|
'https://',
|
||||||
|
'https://?x',
|
||||||
|
'https:///pubmed.ncbi.nlm.nih.gov/x',
|
||||||
|
'https://pubmed.ncbi.nlm.nih.gov./x',
|
||||||
|
'https://bad host/x',
|
||||||
|
'https://user:pass@host.org/a',
|
||||||
|
'https://localhost/a',
|
||||||
|
'https://127.1/a',
|
||||||
|
'https://[::1]/a',
|
||||||
|
'urn:sha256:',
|
||||||
|
'urn:sha256:' + 'b'.repeat(64),
|
||||||
|
]) {
|
||||||
|
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(await db.corporateEvidence.count()).toBe(0);
|
||||||
|
await post(`tasks/${task.id}/evidence`, {
|
||||||
|
...body,
|
||||||
|
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
|
||||||
|
}).expect(201);
|
||||||
|
});
|
||||||
|
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
|
||||||
|
const service = app.get(CorporateService);
|
||||||
|
const research = {
|
||||||
|
title: 'research',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'receipt',
|
||||||
|
opportunity: 'investigate',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'measure',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'source',
|
||||||
|
excerpt: 'receipt',
|
||||||
|
retrievedAt: '',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
for (const time of [
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
false,
|
||||||
|
[],
|
||||||
|
'2026-01-01',
|
||||||
|
'2026-02-30T00:00:00Z',
|
||||||
|
]) {
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.research('fixture', key(), {
|
||||||
|
...research,
|
||||||
|
sources: [{ ...research.sources[0], retrievedAt: time }],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow();
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.effect('fixture', key(), key(), {
|
||||||
|
metric: 'views',
|
||||||
|
availability: 'UNAVAILABLE',
|
||||||
|
source: 'none',
|
||||||
|
observedAt: time,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Invalid observation time');
|
||||||
|
}
|
||||||
|
for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.research('fixture', key(), {
|
||||||
|
...research,
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
...research.sources[0],
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
url,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(await db.corporateResearch.count()).toBe(0);
|
||||||
|
});
|
||||||
|
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
const op = key();
|
||||||
|
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
|
||||||
|
.task;
|
||||||
|
expect(claim.claimToken).toBeTruthy();
|
||||||
|
expect(
|
||||||
|
(await post('claims', {}, 'executor', op).expect(201)).body.task
|
||||||
|
.claimToken,
|
||||||
|
).toBe(claim.claimToken);
|
||||||
|
await post(`tasks/${child.id}/evidence`, {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
}).expect(201);
|
||||||
|
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||||
|
const r = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', 'competitor')
|
||||||
|
.expect(200);
|
||||||
|
expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||||
|
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
await db.corporateEvent.createMany({
|
||||||
|
data: Array.from({ length: 105 }, () => ({
|
||||||
|
taskId: task.id,
|
||||||
|
speaker: 'SYSTEM',
|
||||||
|
speakerName: 'fixture',
|
||||||
|
step: 'FIXTURE',
|
||||||
|
content: 'x'.repeat(10000),
|
||||||
|
payload: { nested: ['x'.repeat(10000)] },
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + task.id)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.logs).toHaveLength(100);
|
||||||
|
expect(detail.body.relationsMeta.logs).toEqual({
|
||||||
|
total: 106,
|
||||||
|
returned: 100,
|
||||||
|
limit: 100,
|
||||||
|
truncated: true,
|
||||||
|
});
|
||||||
|
const op = key(),
|
||||||
|
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||||
|
const report = (await post('reports', body, 'executor', op).expect(201))
|
||||||
|
.body;
|
||||||
|
expect(report.snapshot.events).toHaveLength(100);
|
||||||
|
expect(report.snapshot.meta.events).toEqual({
|
||||||
|
total: 106,
|
||||||
|
returned: 100,
|
||||||
|
limit: 100,
|
||||||
|
truncated: true,
|
||||||
|
});
|
||||||
|
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
|
||||||
|
expect(
|
||||||
|
Buffer.byteLength(JSON.stringify(report.body ?? report)),
|
||||||
|
).toBeLessThan(1000000);
|
||||||
|
await db.corporateEvent.deleteMany();
|
||||||
|
expect(
|
||||||
|
(await post('reports', body, 'executor', op).expect(201)).body,
|
||||||
|
).toEqual(report);
|
||||||
|
});
|
||||||
|
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
|
||||||
|
const service = app.get(CorporateService) as any;
|
||||||
|
const before = await db.corporateTask.count();
|
||||||
|
await expect(
|
||||||
|
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||||
|
await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
title: 'rollback',
|
||||||
|
description: 'fixture',
|
||||||
|
taskCode: key(),
|
||||||
|
normalizedTitle: 'rollback',
|
||||||
|
normalizedCode: key(),
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
createdBy: 'fixture',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { value: 'x'.repeat(1100000) };
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Operation response exceeds limit');
|
||||||
|
expect(await db.corporateTask.count()).toBe(before);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(0);
|
||||||
|
});
|
||||||
|
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
|
||||||
|
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
|
||||||
|
await post('tasks', input, 'unscoped').expect(403);
|
||||||
|
const op = key(),
|
||||||
|
a = await post('tasks', input, 'executor', op).expect(201);
|
||||||
|
const b = await post('tasks', input, 'executor', op).expect(201);
|
||||||
|
expect(b.body.id).toBe(a.body.id);
|
||||||
|
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
|
||||||
|
409,
|
||||||
|
);
|
||||||
|
const list = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(list.body.meta).toEqual({
|
||||||
|
total: 1,
|
||||||
|
page: 1,
|
||||||
|
limit: 1,
|
||||||
|
totalPages: 1,
|
||||||
|
hasNextPage: false,
|
||||||
|
hasPrevPage: false,
|
||||||
|
});
|
||||||
|
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?limit=101')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(400);
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?sortBy=password')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
const claims = await Promise.all([
|
||||||
|
post('claims', {}, 'executor'),
|
||||||
|
post('claims', {}, 'competitor'),
|
||||||
|
]);
|
||||||
|
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
|
||||||
|
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
|
||||||
|
const oldActor = claimed.assignedAgent.replace('apikey:', '');
|
||||||
|
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
|
||||||
|
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
|
||||||
|
.task;
|
||||||
|
expect(renewed.claimToken).not.toBe(claimed.claimToken);
|
||||||
|
const evidence = {
|
||||||
|
claimToken: claimed.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
};
|
||||||
|
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
|
||||||
|
const e = (
|
||||||
|
await post(
|
||||||
|
`tasks/${task.id}/evidence`,
|
||||||
|
{ ...evidence, claimToken: renewed.claimToken },
|
||||||
|
'new-executor',
|
||||||
|
).expect(201)
|
||||||
|
).body;
|
||||||
|
const review = {
|
||||||
|
evidenceId: e.id,
|
||||||
|
passed: true,
|
||||||
|
findings: 'verified',
|
||||||
|
verification: {
|
||||||
|
artifactUri: e.artifactUri,
|
||||||
|
sha256: e.sha256,
|
||||||
|
method: 'digest readback',
|
||||||
|
result: 'match',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
|
||||||
|
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + task.id)
|
||||||
|
.set('x-api-key', 'reviewer')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.status).toBe('DONE');
|
||||||
|
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
|
||||||
|
await post(`tasks/${task.id}/effects`, {
|
||||||
|
metric: 'engagement',
|
||||||
|
availability: 'UNAVAILABLE',
|
||||||
|
observed: 0,
|
||||||
|
source: 'provider unavailable',
|
||||||
|
observedAt: new Date().toISOString(),
|
||||||
|
}).expect(400);
|
||||||
|
});
|
||||||
|
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
|
||||||
|
const urgent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
|
||||||
|
.body;
|
||||||
|
let release!: () => void, locked!: () => void;
|
||||||
|
const ready = new Promise<void>((r) => (locked = r)),
|
||||||
|
hold = new Promise<void>((r) => (release = r));
|
||||||
|
const locking = db.$transaction(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
|
||||||
|
locked();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await ready;
|
||||||
|
try {
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
expect(claim.id).toBe(low.id);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await locking;
|
||||||
|
}
|
||||||
|
const next = (await post('claims', {}, 'other').expect(201)).body.task;
|
||||||
|
expect(next.id).toBe(urgent.id);
|
||||||
|
});
|
||||||
|
it('serializes simultaneous duplicate mutations into one durable record', async () => {
|
||||||
|
const op = key();
|
||||||
|
const responses = await Promise.all([
|
||||||
|
post('tasks', input, 'executor', op),
|
||||||
|
post('tasks', input, 'executor', op),
|
||||||
|
]);
|
||||||
|
expect(responses.map((r) => r.status)).toEqual([201, 201]);
|
||||||
|
expect(responses[0].body.id).toBe(responses[1].body.id);
|
||||||
|
expect(await db.corporateTask.count()).toBe(1);
|
||||||
|
});
|
||||||
|
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
expect(claim.id).toBe(child.id);
|
||||||
|
const e = (
|
||||||
|
await post(`tasks/${child.id}/evidence`, {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
|
||||||
|
sha256: 'b'.repeat(64),
|
||||||
|
summary: 'child artifact',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'receipt',
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
await post(
|
||||||
|
`tasks/${child.id}/reviews`,
|
||||||
|
{
|
||||||
|
evidenceId: e.id,
|
||||||
|
passed: false,
|
||||||
|
findings: 'needs correction',
|
||||||
|
verification: {
|
||||||
|
artifactUri: e.artifactUri,
|
||||||
|
sha256: e.sha256,
|
||||||
|
method: 'readback',
|
||||||
|
result: 'failed',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'reviewer',
|
||||||
|
).expect(201);
|
||||||
|
expect(
|
||||||
|
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('BLOCKED');
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
|
||||||
|
const research = (
|
||||||
|
await post('market-insights', {
|
||||||
|
title: 'fixture research',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'study receipt',
|
||||||
|
opportunity: 'investigate',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'measure',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: {
|
||||||
|
method: 'test fixture',
|
||||||
|
collector: 'integration',
|
||||||
|
context: 'disposable',
|
||||||
|
},
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'fixture',
|
||||||
|
excerpt: 'test-only',
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const roadmap = (
|
||||||
|
await post('monthly-roadmap', {
|
||||||
|
researchId: research.id,
|
||||||
|
cycleName: 'test',
|
||||||
|
month: '2026-10',
|
||||||
|
seasonalTheme: 'evidence pending seasonal analysis',
|
||||||
|
strategicGoals: ['measure'],
|
||||||
|
plannedArticlesCount: 31,
|
||||||
|
plannedRefreshesCount: 0,
|
||||||
|
plannedCatalogEnrichments: 0,
|
||||||
|
goals: [
|
||||||
|
{
|
||||||
|
title: 'goal',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
acceptanceCriteria: 'QA',
|
||||||
|
metric: 'engagement',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(roadmap.goals).toHaveLength(1);
|
||||||
|
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
|
||||||
|
for (const path of ['market-insights', 'monthly-roadmap']) {
|
||||||
|
const r = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(r.body.meta.total).toBe(1);
|
||||||
|
}
|
||||||
|
const report = (
|
||||||
|
await post('reports', {
|
||||||
|
day: new Date().toISOString().slice(0, 10),
|
||||||
|
summary: 'test fixture daily report',
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(report.snapshot.tasks).toHaveLength(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,828 @@
|
|||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Prisma, CorporatePriority } from '@prisma/client';
|
||||||
|
import { createHash, randomUUID } from 'crypto';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
canonical,
|
||||||
|
monthlyPlanInput,
|
||||||
|
planMonth,
|
||||||
|
publicData,
|
||||||
|
choice,
|
||||||
|
departments,
|
||||||
|
evidenceInput,
|
||||||
|
httpsUrl,
|
||||||
|
timestamp,
|
||||||
|
meta,
|
||||||
|
normalizeSearch,
|
||||||
|
object,
|
||||||
|
pagination,
|
||||||
|
priorities,
|
||||||
|
statuses,
|
||||||
|
taskInput,
|
||||||
|
text,
|
||||||
|
uuid,
|
||||||
|
} from './corporate-policy';
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
@Injectable()
|
||||||
|
export class CorporateService {
|
||||||
|
constructor(private readonly db: PrismaService) {}
|
||||||
|
private async operation(
|
||||||
|
actor: string,
|
||||||
|
op: string,
|
||||||
|
key: string,
|
||||||
|
body: unknown,
|
||||||
|
fn: (tx: Tx) => Promise<any>,
|
||||||
|
) {
|
||||||
|
text(key, 200);
|
||||||
|
const scoped = createHash('sha256')
|
||||||
|
.update(canonical([actor, op, key]))
|
||||||
|
.digest('hex');
|
||||||
|
const hash = createHash('sha256').update(canonical(body)).digest('hex');
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
|
||||||
|
const prior = await tx.corporateOperation.findUnique({
|
||||||
|
where: { key: scoped },
|
||||||
|
});
|
||||||
|
if (prior) {
|
||||||
|
if (prior.payloadHash !== hash)
|
||||||
|
throw new ConflictException('Idempotency key payload mismatch');
|
||||||
|
return prior.response;
|
||||||
|
}
|
||||||
|
const result = await fn(tx);
|
||||||
|
const serialized = JSON.stringify(result);
|
||||||
|
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
|
||||||
|
throw new BadRequestException('Operation response exceeds limit');
|
||||||
|
const response = JSON.parse(serialized);
|
||||||
|
await tx.corporateOperation.create({
|
||||||
|
data: { key: scoped, payloadHash: hash, response },
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
},
|
||||||
|
{ maxWait: 10000, timeout: 20000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
private event(
|
||||||
|
tx: Tx,
|
||||||
|
taskId: string,
|
||||||
|
actor: string,
|
||||||
|
step: string,
|
||||||
|
content: string,
|
||||||
|
speaker = 'SYSTEM',
|
||||||
|
payload?: any,
|
||||||
|
) {
|
||||||
|
return tx.corporateEvent.create({
|
||||||
|
data: { taskId, speaker, speakerName: actor, step, content, payload },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private async lock(tx: Tx, id: string) {
|
||||||
|
uuid(id);
|
||||||
|
const rows = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
|
||||||
|
if (!rows.length) throw new NotFoundException('Task not found');
|
||||||
|
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
|
||||||
|
}
|
||||||
|
private async fenced(tx: Tx, id: string, token: string, actor: string) {
|
||||||
|
const t = await this.lock(tx, id);
|
||||||
|
const rows = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
|
||||||
|
if (!rows.length) throw new ConflictException('Stale lease or owner');
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
async tasks(q: Record<string, any>) {
|
||||||
|
const p = pagination(q),
|
||||||
|
where: Prisma.CorporateTaskWhereInput = {};
|
||||||
|
if (q.department) where.department = choice(q.department, departments);
|
||||||
|
if (q.priority)
|
||||||
|
where.priority = choice(q.priority, priorities) as CorporatePriority;
|
||||||
|
if (q.status) where.status = choice(q.status, statuses) as any;
|
||||||
|
if (q.search) {
|
||||||
|
const search = normalizeSearch(text(q.search, 300));
|
||||||
|
where.OR = [
|
||||||
|
{ normalizedTitle: { contains: search } },
|
||||||
|
{ normalizedCode: { contains: search } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (q.goalId) where.goalId = uuid(q.goalId);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const total = await tx.corporateTask.count({ where });
|
||||||
|
const data = await tx.corporateTask.findMany({
|
||||||
|
where,
|
||||||
|
skip: p.skip,
|
||||||
|
take: p.limit,
|
||||||
|
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async detail(id: string) {
|
||||||
|
uuid(id);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const order = { id: 'asc' as const };
|
||||||
|
const task = await tx.corporateTask.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
|
||||||
|
evidence: { take: 100, orderBy: order },
|
||||||
|
reviews: { take: 100, orderBy: order },
|
||||||
|
effects: { take: 100, orderBy: order },
|
||||||
|
children: { take: 100, orderBy: order },
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
logs: true,
|
||||||
|
evidence: true,
|
||||||
|
reviews: true,
|
||||||
|
effects: true,
|
||||||
|
children: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!task) throw new NotFoundException('Task not found');
|
||||||
|
const { _count, ...data } = task;
|
||||||
|
const relationsMeta = Object.fromEntries(
|
||||||
|
Object.entries(_count).map(([name, total]) => [
|
||||||
|
name,
|
||||||
|
{
|
||||||
|
total,
|
||||||
|
returned: Math.min(total, 100),
|
||||||
|
limit: 100,
|
||||||
|
truncated: total > 100,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
return publicData({ ...data, relationsMeta });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
create(actor: string, key: string, input: unknown) {
|
||||||
|
const b = taskInput(input);
|
||||||
|
return this.operation(actor, 'create-task', key, b, async (tx) => {
|
||||||
|
if (b.parentId) {
|
||||||
|
const parent = await this.lock(tx, b.parentId);
|
||||||
|
if (!['TODO', 'BLOCKED'].includes(parent.status))
|
||||||
|
throw new ConflictException('Parent no longer accepts children');
|
||||||
|
}
|
||||||
|
const code = 'TSK-' + randomUUID();
|
||||||
|
const task = await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
...b,
|
||||||
|
priority: b.priority as CorporatePriority,
|
||||||
|
taskCode: code,
|
||||||
|
normalizedCode: normalizeSearch(code),
|
||||||
|
normalizedTitle: normalizeSearch(b.title),
|
||||||
|
createdBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
|
||||||
|
return task;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private plannedWhere(
|
||||||
|
roadmapId: string,
|
||||||
|
month: string,
|
||||||
|
): Prisma.CorporateEventWhereInput {
|
||||||
|
return {
|
||||||
|
step: 'PLANNED',
|
||||||
|
AND: [
|
||||||
|
{ payload: { path: ['roadmapId'], equals: roadmapId } },
|
||||||
|
{ payload: { path: ['month'], equals: month } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private async readPlan(tx: Tx, roadmapId: string, month: string) {
|
||||||
|
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||||
|
where: { id: roadmapId },
|
||||||
|
});
|
||||||
|
const tasks = await tx.corporateTask.findMany({
|
||||||
|
where: { logs: { some: this.plannedWhere(roadmapId, month) } },
|
||||||
|
include: {
|
||||||
|
logs: {
|
||||||
|
where: this.plannedWhere(roadmapId, month),
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
if (!roadmap || !tasks.length)
|
||||||
|
throw new NotFoundException('Monthly plan not found');
|
||||||
|
return publicData({
|
||||||
|
roadmapId,
|
||||||
|
month,
|
||||||
|
researchId: roadmap.researchId,
|
||||||
|
tasks,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
monthlyPlan(roadmapId: string, month: unknown) {
|
||||||
|
roadmapId = uuid(roadmapId);
|
||||||
|
const cycle = planMonth(month);
|
||||||
|
return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), {
|
||||||
|
isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
persistMonthlyPlan(actor: string, key: string, input: unknown) {
|
||||||
|
const b = monthlyPlanInput(input);
|
||||||
|
return this.operation(actor, 'monthly-plan', key, b, async (tx) => {
|
||||||
|
// Separate actor/key-independent fence: one complete plan per roadmap/month.
|
||||||
|
const scope = canonical(['monthly-plan', b.roadmapId, b.month]);
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||||
|
if (
|
||||||
|
await tx.corporateEvent.count({
|
||||||
|
where: this.plannedWhere(b.roadmapId, b.month),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
throw new ConflictException('Monthly plan already persisted');
|
||||||
|
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||||
|
where: { id: b.roadmapId },
|
||||||
|
include: { goals: true, research: { include: { sources: true } } },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
!roadmap ||
|
||||||
|
roadmap.month !== b.month ||
|
||||||
|
!roadmap.research.sources.length
|
||||||
|
)
|
||||||
|
throw new ConflictException(
|
||||||
|
'Matching evidence-backed roadmap required',
|
||||||
|
);
|
||||||
|
const entries = [...b.dailyArticles, ...b.needs];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (
|
||||||
|
!roadmap.goals.some(
|
||||||
|
(g) => g.id === entry.goalId && g.department === entry.department,
|
||||||
|
) ||
|
||||||
|
!entry.sourceIds.every((id) =>
|
||||||
|
roadmap.research.sources.some((s) => s.id === id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new ConflictException(
|
||||||
|
'Goal/department and source lineage must match roadmap research',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const { sourceIds, target, reason, ...data } = entry;
|
||||||
|
const taskCode = 'TSK-' + randomUUID();
|
||||||
|
const task = await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
priority: data.priority as CorporatePriority,
|
||||||
|
status: 'TODO',
|
||||||
|
taskCode,
|
||||||
|
normalizedCode: normalizeSearch(taskCode),
|
||||||
|
normalizedTitle: normalizeSearch(data.title),
|
||||||
|
createdBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
task.id,
|
||||||
|
actor,
|
||||||
|
'PLANNED',
|
||||||
|
entry.description,
|
||||||
|
'SYSTEM',
|
||||||
|
{
|
||||||
|
version: 1,
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
researchId: roadmap.researchId,
|
||||||
|
month: b.month,
|
||||||
|
goalId: entry.goalId,
|
||||||
|
department: entry.department,
|
||||||
|
actionType: entry.actionType,
|
||||||
|
dueCycle: entry.dueCycle,
|
||||||
|
sourceIds,
|
||||||
|
...(target ? { target, reason } : {}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.readPlan(tx, b.roadmapId, b.month);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
claim(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, ['department', 'leaseSeconds']);
|
||||||
|
const department =
|
||||||
|
b.department === undefined ? null : choice(b.department, departments);
|
||||||
|
const seconds = Number(b.leaseSeconds ?? 300);
|
||||||
|
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
|
||||||
|
throw new BadRequestException('Lease must be 30..900 seconds');
|
||||||
|
return this.operation(
|
||||||
|
actor,
|
||||||
|
'claim',
|
||||||
|
key,
|
||||||
|
{ department, seconds },
|
||||||
|
async (tx) => {
|
||||||
|
const candidates = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT t.id FROM corporate_tasks t
|
||||||
|
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED'
|
||||||
|
AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
|
||||||
|
OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle"
|
||||||
|
OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD')))
|
||||||
|
AND (${department}::text IS NULL OR t.department=${department})
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
|
||||||
|
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
|
||||||
|
if (!candidates.length) return { task: null };
|
||||||
|
const id = candidates[0].id,
|
||||||
|
token = randomUUID();
|
||||||
|
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
|
||||||
|
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
|
||||||
|
return {
|
||||||
|
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
submitEvidence(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = evidenceInput(input);
|
||||||
|
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
|
||||||
|
await this.fenced(tx, id, b.claimToken, actor);
|
||||||
|
const e = await tx.corporateEvidence.create({
|
||||||
|
data: { ...b, taskId: id, executor: actor },
|
||||||
|
});
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'TEST', leasedUntil: null },
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
'EVIDENCE_SUBMITTED',
|
||||||
|
b.summary,
|
||||||
|
'AGENT',
|
||||||
|
{ evidenceId: e.id },
|
||||||
|
);
|
||||||
|
return e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
review(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'evidenceId',
|
||||||
|
'passed',
|
||||||
|
'findings',
|
||||||
|
'verification',
|
||||||
|
]);
|
||||||
|
const evidenceId = uuid(b.evidenceId),
|
||||||
|
findings = text(b.findings);
|
||||||
|
if (typeof b.passed !== 'boolean')
|
||||||
|
throw new BadRequestException('passed must be boolean');
|
||||||
|
const v = object(b.verification, [
|
||||||
|
'artifactUri',
|
||||||
|
'sha256',
|
||||||
|
'method',
|
||||||
|
'result',
|
||||||
|
]);
|
||||||
|
const verification = {
|
||||||
|
artifactUri: text(v.artifactUri, 2000),
|
||||||
|
sha256: text(v.sha256, 64),
|
||||||
|
method: text(v.method, 1000),
|
||||||
|
result: text(v.result),
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
|
||||||
|
uuid(id);
|
||||||
|
const relation = await tx.corporateTask.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { parentId: true },
|
||||||
|
});
|
||||||
|
if (relation?.parentId) await this.lock(tx, relation.parentId);
|
||||||
|
const task = await this.lock(tx, id);
|
||||||
|
const evidence = await tx.corporateEvidence.findUnique({
|
||||||
|
where: { id: evidenceId },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
task.status !== 'TEST' ||
|
||||||
|
!evidence ||
|
||||||
|
evidence.taskId !== id ||
|
||||||
|
evidence.claimToken !== task.claimToken
|
||||||
|
)
|
||||||
|
throw new ConflictException('Current execution evidence required');
|
||||||
|
if (evidence.executor === actor)
|
||||||
|
throw new ConflictException('Independent reviewer required');
|
||||||
|
if (
|
||||||
|
verification.sha256 !== evidence.sha256 ||
|
||||||
|
verification.artifactUri !== evidence.artifactUri
|
||||||
|
)
|
||||||
|
throw new ConflictException('QA must verify exact artifact');
|
||||||
|
if (
|
||||||
|
b.passed &&
|
||||||
|
(await tx.corporateTask.count({
|
||||||
|
where: { parentId: id, status: { not: 'DONE' } },
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
throw new ConflictException('Unfinished children');
|
||||||
|
const r = await tx.corporateReview.create({
|
||||||
|
data: {
|
||||||
|
taskId: id,
|
||||||
|
evidenceId,
|
||||||
|
reviewer: actor,
|
||||||
|
passed: b.passed,
|
||||||
|
findings,
|
||||||
|
verification,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: b.passed ? 'DONE' : 'TODO',
|
||||||
|
claimToken: null,
|
||||||
|
leasedUntil: null,
|
||||||
|
qaCount: { increment: 1 },
|
||||||
|
rejectionCount: { increment: b.passed ? 0 : 1 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!b.passed && task.parentId) {
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id: task.parentId },
|
||||||
|
data: { status: 'BLOCKED' },
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
task.parentId,
|
||||||
|
actor,
|
||||||
|
'CHILD_QA_REJECTED',
|
||||||
|
'Parent blocked pending child correction',
|
||||||
|
'QA',
|
||||||
|
{ childId: id },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
|
||||||
|
findings,
|
||||||
|
'QA',
|
||||||
|
{ reviewId: r.id },
|
||||||
|
);
|
||||||
|
return r;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async collection(
|
||||||
|
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
|
||||||
|
q: Record<string, any>,
|
||||||
|
) {
|
||||||
|
const p = pagination(q);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const model =
|
||||||
|
kind === 'market-insights'
|
||||||
|
? tx.corporateResearch
|
||||||
|
: kind === 'monthly-roadmap'
|
||||||
|
? tx.corporateRoadmap
|
||||||
|
: tx.corporateReport;
|
||||||
|
const where: any = {};
|
||||||
|
if (kind === 'market-insights' && q.category)
|
||||||
|
where.category = choice(q.category, [
|
||||||
|
'TREND',
|
||||||
|
'COMPETITOR',
|
||||||
|
'NEW_CHANNEL',
|
||||||
|
'CATALOG_GAP',
|
||||||
|
]);
|
||||||
|
if (kind === 'monthly-roadmap' && q.month)
|
||||||
|
where.month = text(q.month, 40);
|
||||||
|
const delegate = model as any;
|
||||||
|
const total = await delegate.count({ where });
|
||||||
|
const data = await delegate.findMany({
|
||||||
|
where,
|
||||||
|
skip: p.skip,
|
||||||
|
take: p.limit,
|
||||||
|
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||||
|
...(kind === 'market-insights'
|
||||||
|
? { include: { sources: true } }
|
||||||
|
: kind === 'monthly-roadmap'
|
||||||
|
? { include: { goals: true } }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
research(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'title',
|
||||||
|
'category',
|
||||||
|
'source',
|
||||||
|
'opportunity',
|
||||||
|
'impact',
|
||||||
|
'recommendedAction',
|
||||||
|
'cadence',
|
||||||
|
'provenance',
|
||||||
|
'sources',
|
||||||
|
]);
|
||||||
|
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
|
||||||
|
throw new BadRequestException('1..30 sources required');
|
||||||
|
const sources = b.sources.map((raw) => {
|
||||||
|
const s = object(raw, [
|
||||||
|
'url',
|
||||||
|
'title',
|
||||||
|
'excerpt',
|
||||||
|
'retrievedAt',
|
||||||
|
'sha256',
|
||||||
|
]);
|
||||||
|
const url = httpsUrl(s.url),
|
||||||
|
sha256 = text(s.sha256, 64),
|
||||||
|
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
|
||||||
|
if (
|
||||||
|
!url.startsWith('https://') ||
|
||||||
|
!/^[a-f0-9]{64}$/.test(sha256) ||
|
||||||
|
!Number.isFinite(retrievedAt.getTime()) ||
|
||||||
|
retrievedAt.getTime() > Date.now()
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid source');
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
sha256,
|
||||||
|
retrievedAt,
|
||||||
|
title: text(s.title, 300),
|
||||||
|
excerpt: text(s.excerpt),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const provenance = object(b.provenance, ['method', 'collector', 'context']);
|
||||||
|
const data = {
|
||||||
|
title: text(b.title, 300),
|
||||||
|
category: choice(b.category, [
|
||||||
|
'TREND',
|
||||||
|
'COMPETITOR',
|
||||||
|
'NEW_CHANNEL',
|
||||||
|
'CATALOG_GAP',
|
||||||
|
]),
|
||||||
|
source: text(b.source, 2000),
|
||||||
|
opportunity: text(b.opportunity),
|
||||||
|
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
|
||||||
|
recommendedAction: text(b.recommendedAction),
|
||||||
|
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
|
||||||
|
provenance: {
|
||||||
|
method: text(provenance.method),
|
||||||
|
collector: text(provenance.collector, 300),
|
||||||
|
context: text(provenance.context),
|
||||||
|
},
|
||||||
|
createdBy: actor,
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'research', key, b, (tx) =>
|
||||||
|
tx.corporateResearch.create({
|
||||||
|
data: { ...data, sources: { create: sources } },
|
||||||
|
include: { sources: true },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
roadmap(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'researchId',
|
||||||
|
'cycleName',
|
||||||
|
'month',
|
||||||
|
'seasonalTheme',
|
||||||
|
'strategicGoals',
|
||||||
|
'plannedArticlesCount',
|
||||||
|
'plannedRefreshesCount',
|
||||||
|
'plannedCatalogEnrichments',
|
||||||
|
'isActive',
|
||||||
|
'goals',
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
!Array.isArray(b.strategicGoals) ||
|
||||||
|
!b.strategicGoals.length ||
|
||||||
|
b.strategicGoals.length > 30 ||
|
||||||
|
!Array.isArray(b.goals) ||
|
||||||
|
!b.goals.length ||
|
||||||
|
b.goals.length > 100
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Goals required');
|
||||||
|
for (const k of [
|
||||||
|
'plannedArticlesCount',
|
||||||
|
'plannedRefreshesCount',
|
||||||
|
'plannedCatalogEnrichments',
|
||||||
|
])
|
||||||
|
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
|
||||||
|
throw new BadRequestException('Invalid counts');
|
||||||
|
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
|
||||||
|
throw new BadRequestException('Invalid active flag');
|
||||||
|
const goals = b.goals.map((raw) => {
|
||||||
|
const g = object(raw, [
|
||||||
|
'title',
|
||||||
|
'department',
|
||||||
|
'acceptanceCriteria',
|
||||||
|
'metric',
|
||||||
|
'target',
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
g.target !== undefined &&
|
||||||
|
(typeof g.target !== 'number' || !Number.isFinite(g.target))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid target');
|
||||||
|
return {
|
||||||
|
title: text(g.title, 300),
|
||||||
|
department: choice(g.department, departments),
|
||||||
|
acceptanceCriteria: text(g.acceptanceCriteria),
|
||||||
|
metric: text(g.metric, 300),
|
||||||
|
target: g.target,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const data = {
|
||||||
|
researchId: uuid(b.researchId),
|
||||||
|
cycleName: text(b.cycleName, 300),
|
||||||
|
month: text(b.month, 40),
|
||||||
|
seasonalTheme: text(b.seasonalTheme),
|
||||||
|
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
|
||||||
|
plannedArticlesCount: b.plannedArticlesCount,
|
||||||
|
plannedRefreshesCount: b.plannedRefreshesCount,
|
||||||
|
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
|
||||||
|
isActive: b.isActive ?? false,
|
||||||
|
createdBy: actor,
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'roadmap', key, b, async (tx) => {
|
||||||
|
const research = await tx.corporateResearch.findUnique({
|
||||||
|
where: { id: data.researchId },
|
||||||
|
include: { sources: true },
|
||||||
|
});
|
||||||
|
if (!research || !research.sources.length)
|
||||||
|
throw new ConflictException('Evidence-backed research required');
|
||||||
|
const result = await tx.corporateRoadmap.create({
|
||||||
|
data: { ...data, goals: { create: goals } },
|
||||||
|
include: { goals: true },
|
||||||
|
});
|
||||||
|
await tx.corporateResearch.update({
|
||||||
|
where: { id: research.id },
|
||||||
|
data: { status: 'IN_BACKLOG' },
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
effect(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'metric',
|
||||||
|
'availability',
|
||||||
|
'baseline',
|
||||||
|
'observed',
|
||||||
|
'source',
|
||||||
|
'observedAt',
|
||||||
|
]);
|
||||||
|
const availability = choice(b.availability, [
|
||||||
|
'MEASURED',
|
||||||
|
'UNAVAILABLE',
|
||||||
|
'UNINSTRUMENTED',
|
||||||
|
'BUSINESS_DISABLED',
|
||||||
|
]);
|
||||||
|
for (const k of ['baseline', 'observed'])
|
||||||
|
if (
|
||||||
|
b[k] !== undefined &&
|
||||||
|
b[k] !== null &&
|
||||||
|
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid metric');
|
||||||
|
if (availability === 'MEASURED' && typeof b.observed !== 'number')
|
||||||
|
throw new BadRequestException('Measured value required');
|
||||||
|
if (
|
||||||
|
availability !== 'MEASURED' &&
|
||||||
|
(b.observed != null || b.baseline != null)
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Unavailable is not zero');
|
||||||
|
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
|
||||||
|
if (
|
||||||
|
!Number.isFinite(observedAt.getTime()) ||
|
||||||
|
observedAt.getTime() > Date.now()
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid observation time');
|
||||||
|
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
|
||||||
|
const task = await this.lock(tx, id);
|
||||||
|
if (task.status !== 'DONE')
|
||||||
|
throw new ConflictException('Effects require completed QA');
|
||||||
|
const e = await tx.corporateEffect.create({
|
||||||
|
data: {
|
||||||
|
taskId: id,
|
||||||
|
metric: text(b.metric, 300),
|
||||||
|
availability,
|
||||||
|
baseline: b.baseline,
|
||||||
|
observed: b.observed,
|
||||||
|
source: text(b.source, 2000),
|
||||||
|
observedAt,
|
||||||
|
recordedBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
|
||||||
|
effectId: e.id,
|
||||||
|
});
|
||||||
|
return e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
report(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, ['day', 'summary']);
|
||||||
|
const day = text(b.day, 10),
|
||||||
|
summary = text(b.summary);
|
||||||
|
if (
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
||||||
|
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('ISO day required');
|
||||||
|
return this.operation(actor, 'report', key, b, async (tx) => {
|
||||||
|
const start = new Date(day + 'T00:00:00Z'),
|
||||||
|
end = new Date(start.getTime() + 86400000);
|
||||||
|
const taskWhere = { updatedAt: { gte: start, lt: end } };
|
||||||
|
const eventWhere = { timestamp: { gte: start, lt: end } };
|
||||||
|
const effectWhere = { createdAt: { gte: start, lt: end } };
|
||||||
|
const totals = {
|
||||||
|
tasks: await tx.corporateTask.count({ where: taskWhere }),
|
||||||
|
events: await tx.corporateEvent.count({ where: eventWhere }),
|
||||||
|
effects: await tx.corporateEffect.count({ where: effectWhere }),
|
||||||
|
};
|
||||||
|
const tasks = await tx.corporateTask.findMany({
|
||||||
|
where: taskWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskCode: true,
|
||||||
|
title: true,
|
||||||
|
status: true,
|
||||||
|
department: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const events = await tx.corporateEvent.findMany({
|
||||||
|
where: eventWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskId: true,
|
||||||
|
timestamp: true,
|
||||||
|
speaker: true,
|
||||||
|
speakerName: true,
|
||||||
|
step: true,
|
||||||
|
content: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const effects = await tx.corporateEffect.findMany({
|
||||||
|
where: effectWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskId: true,
|
||||||
|
metric: true,
|
||||||
|
availability: true,
|
||||||
|
baseline: true,
|
||||||
|
observed: true,
|
||||||
|
source: true,
|
||||||
|
observedAt: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let fieldsTruncated = false;
|
||||||
|
const project = (rows: any[]) =>
|
||||||
|
rows.map((row) =>
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.entries(row).map(([name, value]) => {
|
||||||
|
if (typeof value === 'string' && value.length > 1000) {
|
||||||
|
fieldsTruncated = true;
|
||||||
|
return [name, value.slice(0, 1000)];
|
||||||
|
}
|
||||||
|
return [name, value];
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const bounded = {
|
||||||
|
tasks: project(tasks),
|
||||||
|
events: project(events),
|
||||||
|
effects: project(effects),
|
||||||
|
};
|
||||||
|
const counts = Object.fromEntries(
|
||||||
|
Object.entries(totals).map(([name, total]) => [
|
||||||
|
name,
|
||||||
|
{
|
||||||
|
total,
|
||||||
|
returned: Math.min(total, 100),
|
||||||
|
limit: 100,
|
||||||
|
truncated: total > 100,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const snapshot = JSON.parse(
|
||||||
|
JSON.stringify({
|
||||||
|
timezone: 'UTC',
|
||||||
|
...bounded,
|
||||||
|
meta: {
|
||||||
|
...counts,
|
||||||
|
fieldsTruncated,
|
||||||
|
stringLimit: 1000,
|
||||||
|
eventPayloadsOmitted: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return tx.corporateReport.create({
|
||||||
|
data: { day, summary, snapshot, createdBy: actor },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 } : {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Patch,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { AdvisorsService, CreateAdvisorDto } from './advisors.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
@Controller('admin')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class AdvisorsController {
|
||||||
|
constructor(
|
||||||
|
private readonly advisorsService: AdvisorsService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Advisors Management
|
||||||
|
*/
|
||||||
|
@Get('advisors')
|
||||||
|
async listAdvisors() {
|
||||||
|
const data = await this.advisorsService.listAdvisors();
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('advisors')
|
||||||
|
async createAdvisor(@Body() dto: CreateAdvisorDto) {
|
||||||
|
const data = await this.advisorsService.createAdvisor(dto);
|
||||||
|
return { success: true, message: 'مشاور جدید با موفقیت اضافه شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('advisors/:id')
|
||||||
|
async updateAdvisor(@Param('id') id: string, @Body() dto: Partial<CreateAdvisorDto>) {
|
||||||
|
const data = await this.advisorsService.updateAdvisor(id, dto);
|
||||||
|
return { success: true, message: 'اطلاعات مشاور بهروزرسانی شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('advisors/:id/set-default')
|
||||||
|
async setDefaultAdvisor(@Param('id') id: string) {
|
||||||
|
const data = await this.advisorsService.setDefaultAdvisor(id);
|
||||||
|
return { success: true, message: 'مشاور با موفقیت به عنوان پیشفرض سیستم انتخاب شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('advisors/:id')
|
||||||
|
async deleteAdvisor(@Param('id') id: string) {
|
||||||
|
return this.advisorsService.deleteAdvisor(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leads (Contact Requests) Management
|
||||||
|
*/
|
||||||
|
@Get('leads')
|
||||||
|
async listLeads(
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('limit') limit?: number,
|
||||||
|
@Query('status') status?: string,
|
||||||
|
@Query('search') search?: string,
|
||||||
|
) {
|
||||||
|
const data = await this.advisorsService.listLeads({ page, limit, status, search });
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('leads/:id/status')
|
||||||
|
async updateLeadStatus(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: { status: string; notes?: string },
|
||||||
|
) {
|
||||||
|
const data = await this.advisorsService.updateLeadStatus(id, body.status, body.notes);
|
||||||
|
return { success: true, message: 'وضعیت درخواست تماس بهروزرسانی شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('leads/:id')
|
||||||
|
async deleteLead(@Param('id') id: string) {
|
||||||
|
return this.advisorsService.deleteLead(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Product Advisor Linking
|
||||||
|
*/
|
||||||
|
@Get('products/:productId/advisor')
|
||||||
|
async getProductAdvisor(@Param('productId') productId: string) {
|
||||||
|
const pa = await this.prisma.productAdvisor.findFirst({
|
||||||
|
where: { productId },
|
||||||
|
include: { advisor: true },
|
||||||
|
});
|
||||||
|
return { success: true, data: pa?.advisor || null };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('products/:productId/advisor')
|
||||||
|
async assignProductAdvisor(
|
||||||
|
@Param('productId') productId: string,
|
||||||
|
@Body() body: { advisorId: string | null },
|
||||||
|
) {
|
||||||
|
if (!body.advisorId) {
|
||||||
|
// Remove product advisor assignment
|
||||||
|
await this.prisma.productAdvisor.deleteMany({ where: { productId } });
|
||||||
|
return { success: true, message: 'مشاور اختصاصی محصول حذف و به حالت پیشفرض بازگشت.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert assignment
|
||||||
|
await this.prisma.productAdvisor.upsert({
|
||||||
|
where: {
|
||||||
|
productId_advisorId: {
|
||||||
|
productId,
|
||||||
|
advisorId: body.advisorId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
productId,
|
||||||
|
advisorId: body.advisorId,
|
||||||
|
},
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true, message: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
|
import { AdvisorsService } from './advisors.service';
|
||||||
|
import { AdvisorsController } from './advisors.controller';
|
||||||
|
import { PublicLeadController } from './public-lead.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [PrismaModule, NotificationsModule],
|
||||||
|
controllers: [AdvisorsController, PublicLeadController],
|
||||||
|
providers: [AdvisorsService],
|
||||||
|
exports: [AdvisorsService],
|
||||||
|
})
|
||||||
|
export class AdvisorsModule {}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AdvisorsService } from './advisors.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
|
||||||
|
describe('AdvisorsService', () => {
|
||||||
|
let service: AdvisorsService;
|
||||||
|
let prisma: any;
|
||||||
|
let queueService: any;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
advisorContact: {
|
||||||
|
findMany: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
findFirst: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
updateMany: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
lead: {
|
||||||
|
findMany: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
},
|
||||||
|
productAdvisor: {
|
||||||
|
findFirst: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
queueService = {
|
||||||
|
enqueue: jest.fn().mockResolvedValue({ id: 'q-1' }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
AdvisorsService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: NotificationsQueueService, useValue: queueService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<AdvisorsService>(AdvisorsService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should list advisors with counts', async () => {
|
||||||
|
prisma.advisorContact.findMany.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: 'adv-1',
|
||||||
|
name: 'دکتر علوی',
|
||||||
|
phone: '09123456789',
|
||||||
|
isDefault: true,
|
||||||
|
isActive: true,
|
||||||
|
_count: { productAdvisors: 2, leads: 5 },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = await service.listAdvisors();
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe('دکتر علوی');
|
||||||
|
expect(result[0].productsCount).toBe(2);
|
||||||
|
expect(result[0].leadsCount).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create lead and enqueue notifications for default advisor and client', async () => {
|
||||||
|
prisma.lead.count.mockResolvedValueOnce(0); // rate limit
|
||||||
|
prisma.advisorContact.findFirst.mockResolvedValueOnce({
|
||||||
|
id: 'adv-def',
|
||||||
|
name: 'مشاور پیشفرض',
|
||||||
|
phone: '09120000000',
|
||||||
|
isDefault: true,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
prisma.lead.create.mockResolvedValueOnce({
|
||||||
|
id: 'lead-1',
|
||||||
|
firstName: 'علی',
|
||||||
|
lastName: 'رضایی',
|
||||||
|
phone: '09129876543',
|
||||||
|
advisorId: 'adv-def',
|
||||||
|
status: 'PENDING',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.handlePublicLead({
|
||||||
|
firstName: 'علی',
|
||||||
|
lastName: 'رضایی',
|
||||||
|
phone: '09129876543',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.success).toBe(true);
|
||||||
|
expect(res.leadId).toBe('lead-1');
|
||||||
|
expect(queueService.enqueue).toHaveBeenCalledTimes(2); // 1 for advisor, 1 for client
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject invalid phone format', async () => {
|
||||||
|
await expect(
|
||||||
|
service.handlePublicLead({
|
||||||
|
firstName: 'تست',
|
||||||
|
lastName: 'تستی',
|
||||||
|
phone: '1234',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(BadRequestException);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
|
||||||
|
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||||
|
|
||||||
|
export class CreateAdvisorDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
phone!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
title?: string;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isDefault?: boolean;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateLeadDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
firstName!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lastName!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
phone!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
productId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdvisorsService {
|
||||||
|
private readonly logger = new Logger(AdvisorsService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly queueService: NotificationsQueueService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all advisors with attached product count and leads count
|
||||||
|
*/
|
||||||
|
async listAdvisors() {
|
||||||
|
const advisors = await this.prisma.advisorContact.findMany({
|
||||||
|
orderBy: [{ isDefault: 'desc' }, { createdAt: 'desc' }],
|
||||||
|
include: {
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
productAdvisors: true,
|
||||||
|
leads: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return advisors.map((a) => ({
|
||||||
|
id: a.id,
|
||||||
|
name: a.name,
|
||||||
|
phone: a.phone,
|
||||||
|
title: a.title,
|
||||||
|
isDefault: a.isDefault,
|
||||||
|
isActive: a.isActive,
|
||||||
|
productsCount: a._count.productAdvisors,
|
||||||
|
leadsCount: a._count.leads,
|
||||||
|
createdAt: a.createdAt,
|
||||||
|
updatedAt: a.updatedAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new advisor
|
||||||
|
*/
|
||||||
|
async createAdvisor(dto: CreateAdvisorDto) {
|
||||||
|
if (!dto.name || !dto.phone) {
|
||||||
|
throw new BadRequestException('نام و شماره موبایل مشاور الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanPhone = dto.phone.trim();
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({
|
||||||
|
where: { phone: cleanPhone },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new BadRequestException('مشاوری با این شماره تلفن قبلاً ثبت شده است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If marked default, unset others first
|
||||||
|
if (dto.isDefault) {
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const advisor = await this.prisma.advisorContact.create({
|
||||||
|
data: {
|
||||||
|
name: dto.name.trim(),
|
||||||
|
phone: cleanPhone,
|
||||||
|
title: dto.title?.trim() || null,
|
||||||
|
isDefault: Boolean(dto.isDefault),
|
||||||
|
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return advisor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update advisor
|
||||||
|
*/
|
||||||
|
async updateAdvisor(id: string, dto: Partial<CreateAdvisorDto>) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور مورد نظر یافت نشد.');
|
||||||
|
|
||||||
|
if (dto.phone && dto.phone !== existing.phone) {
|
||||||
|
const phoneExists = await this.prisma.advisorContact.findUnique({
|
||||||
|
where: { phone: dto.phone.trim() },
|
||||||
|
});
|
||||||
|
if (phoneExists && phoneExists.id !== id) {
|
||||||
|
throw new BadRequestException('شماره تلفن وارد شده برای مشاور دیگری ثبت شده است.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.isDefault) {
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true, id: { not: id } },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.prisma.advisorContact.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name: dto.name ? dto.name.trim() : undefined,
|
||||||
|
phone: dto.phone ? dto.phone.trim() : undefined,
|
||||||
|
title: dto.title !== undefined ? dto.title?.trim() || null : undefined,
|
||||||
|
isDefault: dto.isDefault !== undefined ? Boolean(dto.isDefault) : undefined,
|
||||||
|
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set advisor as default
|
||||||
|
*/
|
||||||
|
async setDefaultAdvisor(id: string) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||||
|
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.prisma.advisorContact.update({
|
||||||
|
where: { id },
|
||||||
|
data: { isDefault: true, isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete advisor
|
||||||
|
*/
|
||||||
|
async deleteAdvisor(id: string) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||||
|
|
||||||
|
await this.prisma.advisorContact.delete({ where: { id } });
|
||||||
|
return { success: true, message: 'مشاور با موفقیت حذف شد.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List customer leads (contact requests)
|
||||||
|
*/
|
||||||
|
async listLeads(query: { page?: number; limit?: number; status?: string; search?: string }) {
|
||||||
|
const page = Math.max(1, Number(query.page || 1));
|
||||||
|
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (query.status && query.status !== 'ALL') {
|
||||||
|
where.status = query.status;
|
||||||
|
}
|
||||||
|
if (query.search) {
|
||||||
|
where.OR = [
|
||||||
|
{ firstName: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ lastName: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ phone: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.lead.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip,
|
||||||
|
take: limit,
|
||||||
|
include: {
|
||||||
|
advisor: {
|
||||||
|
select: { id: true, name: true, phone: true, title: true },
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.lead.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const [pendingCount, contactedCount, cancelledCount] = await Promise.all([
|
||||||
|
this.prisma.lead.count({ where: { status: 'PENDING' } }),
|
||||||
|
this.prisma.lead.count({ where: { status: 'CONTACTED' } }),
|
||||||
|
this.prisma.lead.count({ where: { status: 'CANCELLED' } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit) || 1,
|
||||||
|
stats: {
|
||||||
|
total,
|
||||||
|
pending: pendingCount,
|
||||||
|
contacted: contactedCount,
|
||||||
|
cancelled: cancelledCount,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update lead status or notes
|
||||||
|
*/
|
||||||
|
async updateLeadStatus(id: string, status: string, notes?: string) {
|
||||||
|
const lead = await this.prisma.lead.findUnique({ where: { id } });
|
||||||
|
if (!lead) throw new NotFoundException('درخواست تماس یافت نشد.');
|
||||||
|
|
||||||
|
return this.prisma.lead.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status,
|
||||||
|
notes: notes !== undefined ? notes : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete lead
|
||||||
|
*/
|
||||||
|
async deleteLead(id: string) {
|
||||||
|
await this.prisma.lead.delete({ where: { id } });
|
||||||
|
return { success: true, message: 'درخواست تماس با موفقیت حذف شد.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public Lead Creation from Website
|
||||||
|
*/
|
||||||
|
async handlePublicLead(dto: CreateLeadDto) {
|
||||||
|
if (!dto.firstName || !dto.lastName || !dto.phone) {
|
||||||
|
throw new BadRequestException('نام، نام خانوادگی و شماره موبایل الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanPhone = dto.phone.replace(/\s+/g, '').replace(/^(\+98|0098)/, '0');
|
||||||
|
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||||
|
throw new BadRequestException('شماره موبایل وارد شده نامعتبر است (مثال: ۰۹۱۲۳۴۵۶۷۸۹).');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limit: max 3 requests per 24 hours per phone
|
||||||
|
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||||
|
const countToday = await this.prisma.lead.count({
|
||||||
|
where: {
|
||||||
|
phone: cleanPhone,
|
||||||
|
createdAt: { gte: oneDayAgo },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (countToday >= 3) {
|
||||||
|
throw new BadRequestException('حداکثر تعداد درخواست روزانه برای این شماره تکمیل شده است. همکاران ما به زودی با شما تماس خواهند گرفت.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve advisor: Product-specific -> Default advisor -> First active advisor
|
||||||
|
let advisor = null;
|
||||||
|
let product = null;
|
||||||
|
|
||||||
|
if (dto.productId) {
|
||||||
|
product = await this.prisma.product.findUnique({
|
||||||
|
where: { id: dto.productId },
|
||||||
|
select: { id: true, nameFa: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const pa = await this.prisma.productAdvisor.findFirst({
|
||||||
|
where: { productId: dto.productId },
|
||||||
|
include: { advisor: true },
|
||||||
|
});
|
||||||
|
if (pa?.advisor?.isActive) {
|
||||||
|
advisor = pa.advisor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!advisor) {
|
||||||
|
advisor = await this.prisma.advisorContact.findFirst({
|
||||||
|
where: { isDefault: true, isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!advisor) {
|
||||||
|
advisor = await this.prisma.advisorContact.findFirst({
|
||||||
|
where: { isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create lead record in DB
|
||||||
|
const lead = await this.prisma.lead.create({
|
||||||
|
data: {
|
||||||
|
firstName: dto.firstName.trim(),
|
||||||
|
lastName: dto.lastName.trim(),
|
||||||
|
phone: cleanPhone,
|
||||||
|
productId: dto.productId || null,
|
||||||
|
advisorId: advisor?.id || null,
|
||||||
|
status: 'PENDING',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Enqueue SMS notification to Advisor
|
||||||
|
// Pattern 580260: "مشاور گرامی، درخواست تماس جدیدی از {0} با شماره {1} برای {2} ثبت شد. canina.ir"
|
||||||
|
if (advisor) {
|
||||||
|
const productName = product ? product.nameFa : 'مشاوره عمومی';
|
||||||
|
const advisorMsg = `مشاور گرامی، درخواست تماس جدیدی از ${dto.firstName} ${dto.lastName} (${cleanPhone}) برای «${productName}» ثبت شد. لطفاً در اسرع وقت تماس حاصل فرمایید.`;
|
||||||
|
const clientName = `${dto.firstName} ${dto.lastName}`.trim();
|
||||||
|
|
||||||
|
await this.queueService.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: advisor.phone,
|
||||||
|
event: 'NEW_LEAD',
|
||||||
|
content: advisorMsg,
|
||||||
|
payload: {
|
||||||
|
patternId: 580260, // Registered official advisor pattern
|
||||||
|
args: [clientName, cleanPhone, productName],
|
||||||
|
},
|
||||||
|
idempotencyKey: `lead_advisor_${lead.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enqueue confirmation SMS to Client
|
||||||
|
// Pattern 580259: "{0} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران ما به زودی با شما تماس خواهند گرفت. canina.ir"
|
||||||
|
const clientMsg = `${dto.firstName} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.`;
|
||||||
|
await this.queueService.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: cleanPhone,
|
||||||
|
event: 'LEAD_CONFIRMATION',
|
||||||
|
content: clientMsg,
|
||||||
|
payload: {
|
||||||
|
patternId: 580259, // Registered official client pattern
|
||||||
|
args: [dto.firstName.trim()],
|
||||||
|
},
|
||||||
|
idempotencyKey: `lead_client_${lead.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'درخواست مشاوره شما با موفقیت ثبت شد. مشاور ما به زودی با شما تماس خواهد گرفت.',
|
||||||
|
leadId: lead.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Post,
|
||||||
|
Body,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { AdvisorsService, CreateLeadDto } from './advisors.service';
|
||||||
|
|
||||||
|
@Controller('public')
|
||||||
|
export class PublicLeadController {
|
||||||
|
constructor(private readonly advisorsService: AdvisorsService) {}
|
||||||
|
|
||||||
|
@Post('lead')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async createLead(@Body() dto: CreateLeadDto) {
|
||||||
|
const result = await this.advisorsService.handlePublicLead(dto);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
success: true,
|
||||||
|
message: result.message,
|
||||||
|
leadId: result.leadId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,8 @@ import { DoctorsModule } from "./doctors/doctors.module";
|
|||||||
import { FaqModule } from "./faq/faq.module";
|
import { FaqModule } from "./faq/faq.module";
|
||||||
import { MenuModule } from "./menu/menu.module";
|
import { MenuModule } from "./menu/menu.module";
|
||||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||||
|
import { NotificationsModule } from "./notifications/notifications.module";
|
||||||
|
import { AdvisorsModule } from "./advisors/advisors.module";
|
||||||
|
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
@@ -79,6 +81,8 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
B2BModule,
|
B2BModule,
|
||||||
FaqModule,
|
FaqModule,
|
||||||
MenuModule,
|
MenuModule,
|
||||||
|
NotificationsModule,
|
||||||
|
AdvisorsModule,
|
||||||
],
|
],
|
||||||
controllers: [MetricsController],
|
controllers: [MetricsController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { AdminModule } from "../admin/admin.module";
|
|||||||
import { getJwtSecret } from "./auth.constants";
|
import { getJwtSecret } from "./auth.constants";
|
||||||
|
|
||||||
import { RedisModule } from "../redis/redis.module";
|
import { RedisModule } from "../redis/redis.module";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -16,6 +17,7 @@ import { RedisModule } from "../redis/redis.module";
|
|||||||
forwardRef(() => AdminModule),
|
forwardRef(() => AdminModule),
|
||||||
PassportModule,
|
PassportModule,
|
||||||
RedisModule,
|
RedisModule,
|
||||||
|
NotificationsModule,
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
useFactory: () => ({
|
useFactory: () => ({
|
||||||
secret: getJwtSecret(),
|
secret: getJwtSecret(),
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { PrismaService } from "../prisma/prisma.service";
|
|||||||
import { JwtService } from "@nestjs/jwt";
|
import { JwtService } from "@nestjs/jwt";
|
||||||
import { RedisService } from "../redis/redis.service";
|
import { RedisService } from "../redis/redis.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { BadRequestException } from "@nestjs/common";
|
import { BadRequestException } from "@nestjs/common";
|
||||||
|
|
||||||
describe("AuthService", () => {
|
describe("AuthService", () => {
|
||||||
@@ -43,6 +44,7 @@ describe("AuthService", () => {
|
|||||||
{ provide: JwtService, useValue: mockJwt },
|
{ provide: JwtService, useValue: mockJwt },
|
||||||
{ provide: RedisService, useValue: mockRedis },
|
{ provide: RedisService, useValue: mockRedis },
|
||||||
{ provide: SmsService, useValue: mockSms },
|
{ provide: SmsService, useValue: mockSms },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { RedisService } from "../redis/redis.service";
|
|||||||
import { SendOtpDto } from "./dto/send-otp.dto";
|
import { SendOtpDto } from "./dto/send-otp.dto";
|
||||||
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import * as bcrypt from "bcryptjs";
|
import * as bcrypt from "bcryptjs";
|
||||||
import * as crypto from "crypto";
|
import * as crypto from "crypto";
|
||||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||||
@@ -42,6 +43,7 @@ export class AuthService {
|
|||||||
private jwtService: JwtService,
|
private jwtService: JwtService,
|
||||||
private redisService: RedisService,
|
private redisService: RedisService,
|
||||||
private smsService: SmsService,
|
private smsService: SmsService,
|
||||||
|
private transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async generateTokens(payload: Record<string, any>) {
|
private async generateTokens(payload: Record<string, any>) {
|
||||||
@@ -257,6 +259,13 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Fire-and-forget welcome email when register provided an address
|
||||||
|
if (user.email) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendWelcome(user.email, user.firstName)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ export interface SmsConfig {
|
|||||||
shippingBodyId: number;
|
shippingBodyId: number;
|
||||||
b2bBodyId: number;
|
b2bBodyId: number;
|
||||||
petCareBodyId: number;
|
petCareBodyId: number;
|
||||||
|
leadAdvisorBodyId?: number;
|
||||||
|
leadConfirmationBodyId?: number;
|
||||||
rules?: SmsRule[];
|
rules?: SmsRule[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,6 +124,16 @@ export class SmsService {
|
|||||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||||
"0",
|
"0",
|
||||||
),
|
),
|
||||||
|
leadAdvisorBodyId: Number(
|
||||||
|
dbConfig.leadAdvisorBodyId ||
|
||||||
|
process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID ||
|
||||||
|
"580260",
|
||||||
|
),
|
||||||
|
leadConfirmationBodyId: Number(
|
||||||
|
dbConfig.leadConfirmationBodyId ||
|
||||||
|
process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID ||
|
||||||
|
"580259",
|
||||||
|
),
|
||||||
rules: Array.isArray(dbConfig.rules)
|
rules: Array.isArray(dbConfig.rules)
|
||||||
? (dbConfig.rules as SmsRule[])
|
? (dbConfig.rules as SmsRule[])
|
||||||
: DEFAULT_SMS_RULES,
|
: DEFAULT_SMS_RULES,
|
||||||
@@ -140,6 +152,8 @@ export class SmsService {
|
|||||||
),
|
),
|
||||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
||||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
||||||
|
leadAdvisorBodyId: Number(process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID || "580260"),
|
||||||
|
leadConfirmationBodyId: Number(process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID || "580259"),
|
||||||
rules: DEFAULT_SMS_RULES,
|
rules: DEFAULT_SMS_RULES,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1377,13 +1391,88 @@ export class SmsService {
|
|||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
// 2. Dispatch generic direct SMS via MeliPayamak SendSMS endpoint if fromNumber configured, else fall back to local log
|
||||||
await this.recordLog({
|
return new Promise((resolve) => {
|
||||||
receptor: phone,
|
const payload = JSON.stringify({
|
||||||
type: "GENERIC_TEXT",
|
username: config.username,
|
||||||
messageText: message,
|
password: config.password,
|
||||||
status: "SUCCESS",
|
to: phone,
|
||||||
|
from: config.fromNumber || "50004001100228",
|
||||||
|
text: message,
|
||||||
|
isFlash: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const req = https.request(
|
||||||
|
"https://rest.payamak-panel.com/api/SendSMS/SendSMS",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.byteLength(payload),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
let data = "";
|
||||||
|
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||||
|
res.on("end", () => {
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(data) as { Value?: number | string; RetStatus?: number; StrRetStatus?: string };
|
||||||
|
const val = Number(json.Value ?? 0);
|
||||||
|
if (val > 15 || json.RetStatus === 1) {
|
||||||
|
this.logger.log(`[SMS Text Sent] To: ${phone}, RecId: ${val}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "SUCCESS",
|
||||||
|
recId: String(val),
|
||||||
|
});
|
||||||
|
resolve(true);
|
||||||
|
} else {
|
||||||
|
const errMsg = `خطای ارسال پیامک متنی با کد: ${val} (${json.StrRetStatus || ''})`;
|
||||||
|
this.logger.error(`[SMS Text Error] To: ${phone}, Code: ${val}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: errMsg,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: `خطای پارس پاسخ ملی پیامک: ${data || msg}`,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
req.on("error", (err: Error) => {
|
||||||
|
void (async () => {
|
||||||
|
this.logger.error(`[SMS Text Network Error] To: ${phone}: ${err.message}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: err.message,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
|
||||||
|
req.write(payload);
|
||||||
|
req.end();
|
||||||
});
|
});
|
||||||
return Promise.resolve(true);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,10 @@ import { Module } from "@nestjs/common";
|
|||||||
import { ContactController } from "./contact.controller";
|
import { ContactController } from "./contact.controller";
|
||||||
import { ContactService } from "./contact.service";
|
import { ContactService } from "./contact.service";
|
||||||
import { SmsModule } from "../common/sms.module";
|
import { SmsModule } from "../common/sms.module";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [SmsModule],
|
imports: [SmsModule, NotificationsModule],
|
||||||
controllers: [ContactController],
|
controllers: [ContactController],
|
||||||
providers: [ContactService],
|
providers: [ContactService],
|
||||||
exports: [ContactService],
|
exports: [ContactService],
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
|||||||
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
|
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
|
|
||||||
describe("ContactService", () => {
|
describe("ContactService", () => {
|
||||||
let service: ContactService;
|
let service: ContactService;
|
||||||
@@ -13,9 +14,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(),
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -35,6 +35,17 @@ describe("ContactService", () => {
|
|||||||
provide: SmsService,
|
provide: SmsService,
|
||||||
useValue: mockSmsService,
|
useValue: mockSmsService,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: TransactionalEmailsService,
|
||||||
|
useValue: {
|
||||||
|
sendWelcome: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderCreated: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderPaid: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderShipped: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendContactConfirmation: jest.fn().mockResolvedValue(undefined),
|
||||||
|
notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@@ -82,26 +93,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", () => {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
|
|
||||||
export interface CreateContactSubmissionDto {
|
export interface CreateContactSubmissionDto {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -25,6 +26,7 @@ export class ContactService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly smsService: SmsService,
|
private readonly smsService: SmsService,
|
||||||
|
private readonly transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async submitContactForm(dto: CreateContactSubmissionDto) {
|
async submitContactForm(dto: CreateContactSubmissionDto) {
|
||||||
@@ -56,6 +58,28 @@ export class ContactService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Email confirmation to submitter + admin notify (non-blocking)
|
||||||
|
void Promise.resolve(
|
||||||
|
this.transactionalEmails.notifyAdminsAboutContact({
|
||||||
|
name: dto.name,
|
||||||
|
phone: dto.phone,
|
||||||
|
email: dto.email,
|
||||||
|
subject: dto.subject,
|
||||||
|
message: dto.message,
|
||||||
|
submissionId: submission.id,
|
||||||
|
}),
|
||||||
|
).catch(() => {});
|
||||||
|
if (dto.email) {
|
||||||
|
void Promise.resolve(
|
||||||
|
this.transactionalEmails.sendContactConfirmation(
|
||||||
|
dto.email,
|
||||||
|
dto.name,
|
||||||
|
dto.message,
|
||||||
|
submission.id,
|
||||||
|
),
|
||||||
|
).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message:
|
message:
|
||||||
@@ -65,51 +89,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) {
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
/**
|
||||||
|
* Branded HTML wrappers for Canina transactional emails.
|
||||||
|
* Colors match the storefront tokens in frontend/application/app/globals.css.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BRAND = {
|
||||||
|
blue: '#1E4053',
|
||||||
|
gold: '#F1B646',
|
||||||
|
teal: '#9BC8CC',
|
||||||
|
dark: '#060709',
|
||||||
|
soft: '#F4F7F6',
|
||||||
|
border: '#E5ECE9',
|
||||||
|
muted: '#445D60',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function escapeHtml(value: string): string {
|
||||||
|
return String(value)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function textToHtmlParagraphs(text: string): string {
|
||||||
|
return escapeHtml(text)
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => (line.trim().length === 0 ? ' ' : line))
|
||||||
|
.join('<br/>');
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CaninaEmailLayoutOptions {
|
||||||
|
title: string;
|
||||||
|
bodyHtml: string;
|
||||||
|
eyebrow?: string;
|
||||||
|
footerNote?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderCaninaEmailLayout(options: CaninaEmailLayoutOptions): string {
|
||||||
|
const title = escapeHtml(options.title);
|
||||||
|
const eyebrow = escapeHtml(options.eyebrow || 'CANINA');
|
||||||
|
const footerNote = escapeHtml(
|
||||||
|
options.footerNote || 'این پیام از طرف فروشگاه کنینا ارسال شده است.',
|
||||||
|
);
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html lang="fa" dir="rtl">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>${title}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:${BRAND.soft};color:${BRAND.dark};font-family:Tahoma,Arial,sans-serif;line-height:1.9;font-size:15px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;background:${BRAND.soft};">
|
||||||
|
<tr>
|
||||||
|
<td align="center" style="padding:28px 14px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;max-width:600px;background:#ffffff;text-align:right;border:1px solid ${BRAND.border};">
|
||||||
|
<tr>
|
||||||
|
<td style="padding:0;height:4px;background:${BRAND.gold};font-size:0;line-height:0;"> </td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:24px 28px 8px;background:${BRAND.blue};">
|
||||||
|
<p style="margin:0;font-size:11px;letter-spacing:0.18em;color:${BRAND.teal};">${eyebrow}</p>
|
||||||
|
<p style="margin:8px 0 0;font-size:22px;font-weight:700;color:#ffffff;">کنینا</p>
|
||||||
|
<p style="margin:4px 0 0;font-size:13px;color:${BRAND.gold};">مکمل تخصصی حیوانات خانگی</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:28px;">
|
||||||
|
<h1 style="margin:0 0 16px;font-size:20px;font-weight:700;color:${BRAND.blue};">${title}</h1>
|
||||||
|
<div style="color:${BRAND.muted};">${options.bodyHtml}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:18px 28px;background:${BRAND.dark};color:#d5dde0;font-size:12px;">
|
||||||
|
<p style="margin:0;color:#ffffff;font-weight:700;">کنینا ایران</p>
|
||||||
|
<p style="margin:8px 0 0;">
|
||||||
|
<a href="mailto:support@canina.ir" style="color:${BRAND.gold};text-decoration:none;" dir="ltr">support@canina.ir</a>
|
||||||
|
·
|
||||||
|
<a href="https://canina.ir" style="color:${BRAND.teal};text-decoration:none;" dir="ltr">canina.ir</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:10px 0 0;color:#9aa8ad;">${footerNote}</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderCaninaNotificationEmail(subject: string, content: string): string {
|
||||||
|
return renderCaninaEmailLayout({
|
||||||
|
title: subject || 'اطلاعیه کنینا',
|
||||||
|
bodyHtml: `<p style="margin:0;">${textToHtmlParagraphs(content || '')}</p>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import * as net from 'net';
|
||||||
|
import * as tls from 'tls';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
export interface SmtpConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
secure?: boolean; // true for 465 (TLS), false for 587/25 (STARTTLS)
|
||||||
|
user: string;
|
||||||
|
password: string;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SendMailOptions {
|
||||||
|
to: string;
|
||||||
|
subject: string;
|
||||||
|
text?: string;
|
||||||
|
html?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EmailService {
|
||||||
|
private readonly logger = new Logger(EmailService.name);
|
||||||
|
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read SMTP configuration from DB Setting table with fallback to env variables
|
||||||
|
*/
|
||||||
|
async getConfig(): Promise<SmtpConfig> {
|
||||||
|
try {
|
||||||
|
const setting = await this.prisma.setting.findFirst({
|
||||||
|
where: { category: 'email' },
|
||||||
|
});
|
||||||
|
const dbConfig = (setting?.value as Record<string, any>) || {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||||
|
host: dbConfig.host || process.env.SMTP_HOST || 'mail.canina.ir',
|
||||||
|
port: Number(dbConfig.port || process.env.SMTP_PORT || 587),
|
||||||
|
secure: dbConfig.secure !== undefined ? Boolean(dbConfig.secure) : Number(dbConfig.port || 587) === 465,
|
||||||
|
user: dbConfig.user || process.env.SMTP_USER || '',
|
||||||
|
password: dbConfig.password || process.env.SMTP_PASSWORD || '',
|
||||||
|
fromName: dbConfig.fromName || process.env.SMTP_FROM_NAME || 'کنینا ایران',
|
||||||
|
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'support@canina.ir',
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(`Error loading email config: ${err?.message}`);
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
host: process.env.SMTP_HOST || 'mail.canina.ir',
|
||||||
|
port: Number(process.env.SMTP_PORT || 587),
|
||||||
|
secure: Number(process.env.SMTP_PORT || 587) === 465,
|
||||||
|
user: process.env.SMTP_USER || '',
|
||||||
|
password: process.env.SMTP_PASSWORD || '',
|
||||||
|
fromName: 'کنینا ایران',
|
||||||
|
fromEmail: 'support@canina.ir',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save SMTP configuration to database
|
||||||
|
*/
|
||||||
|
async saveConfig(dto: Partial<SmtpConfig>): Promise<SmtpConfig> {
|
||||||
|
const current = await this.getConfig();
|
||||||
|
const port = Number(dto.port ?? current.port);
|
||||||
|
const secure = dto.secure !== undefined ? Boolean(dto.secure) : (port === 465);
|
||||||
|
|
||||||
|
const updated: SmtpConfig = {
|
||||||
|
...current,
|
||||||
|
...dto,
|
||||||
|
port,
|
||||||
|
secure,
|
||||||
|
};
|
||||||
|
|
||||||
|
const existing = await this.prisma.setting.findFirst({ where: { category: 'email' } });
|
||||||
|
if (existing) {
|
||||||
|
await this.prisma.setting.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: { value: updated as any },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await this.prisma.setting.create({
|
||||||
|
data: {
|
||||||
|
category: 'email',
|
||||||
|
key: 'smtp_config',
|
||||||
|
value: updated as any,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test SMTP connection with the given or stored configuration
|
||||||
|
*/
|
||||||
|
async testConnection(customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; message: string; banner?: string }> {
|
||||||
|
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||||
|
|
||||||
|
if (!config.host || !config.port) {
|
||||||
|
return { success: false, message: 'آدرس هاست و پورت SMTP الزامی است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
// If port is 465 or secure=true, connect via direct TLS
|
||||||
|
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||||
|
let buffer = '';
|
||||||
|
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=quit
|
||||||
|
let banner = '';
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve({ success: false, message: 'تایماوت در اتصال به سرور SMTP (بیش از ۱۰ ثانیه)' });
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
const cleanup = (res: { success: boolean; message: string; banner?: string }) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
try {
|
||||||
|
socket.end();
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve(res);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleData = (chunk: Buffer) => {
|
||||||
|
buffer += chunk.toString('utf8');
|
||||||
|
const lines = buffer.split('\r\n');
|
||||||
|
buffer = lines.pop() || '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line) continue;
|
||||||
|
const code = parseInt(line.substring(0, 3), 10);
|
||||||
|
const isFinal = line.charAt(3) === ' ';
|
||||||
|
|
||||||
|
if (!isFinal) continue; // Multi-line response continuation
|
||||||
|
|
||||||
|
if (stage === 0) {
|
||||||
|
banner = line;
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 1;
|
||||||
|
socket.write(`EHLO canina.ir\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `پاسخ ناموفق از سرور: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 1) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
if (config.user && config.password) {
|
||||||
|
stage = 2;
|
||||||
|
socket.write('AUTH LOGIN\r\n');
|
||||||
|
} else {
|
||||||
|
stage = 5;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, message: 'اتصال به سرور SMTP بدون احراز هویت با موفقیت برقرار شد.', banner });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `خطای EHLO: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 2) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 3;
|
||||||
|
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `سرور از AUTH LOGIN پشتیبانی نمیکند یا خطا داد: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 3) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 4;
|
||||||
|
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `نام کاربری پذیرفته نشد: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 4) {
|
||||||
|
if (code === 235 || (code >= 200 && code < 300)) {
|
||||||
|
stage = 5;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, message: 'اتصال و احراز هویت با سرور SMTP با موفقیت تأیید شد.', banner });
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `احراز هویت ناموفق بود (نام کاربری یا رمز عبور اشتباه است): ${line}`, banner });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let socket: net.Socket;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isExplicitTls) {
|
||||||
|
socket = tls.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
}, () => {});
|
||||||
|
} else {
|
||||||
|
socket = net.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
}, () => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.on('data', handleData);
|
||||||
|
socket.on('error', (err) => {
|
||||||
|
cleanup({ success: false, message: `خطای شبکه در ارتباط با ${config.host}:${config.port} - ${err.message}` });
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
cleanup({ success: false, message: `خطا در باز کردن سوکت: ${err?.message}` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a MIME Email message through SMTP
|
||||||
|
*/
|
||||||
|
async sendMail(options: SendMailOptions, customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; messageId?: string; error?: string }> {
|
||||||
|
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||||
|
|
||||||
|
if (!config.enabled) {
|
||||||
|
return { success: false, error: 'سرویس ارسال ایمیل در تنظیمات غیرفعال است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.host || !options.to) {
|
||||||
|
return { success: false, error: 'هاست SMTP یا آدرس گیرنده مشخص نشده است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
// If port is 465 or secure=true, connect via direct TLS
|
||||||
|
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||||
|
let buffer = '';
|
||||||
|
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=mail_from, 6=rcpt_to, 7=data_cmd, 8=data_body, 9=quit
|
||||||
|
const messageId = `<${Date.now()}.${Math.random().toString(36).substring(2)}@${config.host}>`;
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve({ success: false, error: 'تایماوت ارسال ایمیل (۱۵ ثانیه)' });
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
const cleanup = (res: { success: boolean; messageId?: string; error?: string }) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
try {
|
||||||
|
socket.end();
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve(res);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleData = (chunk: Buffer) => {
|
||||||
|
buffer += chunk.toString('utf8');
|
||||||
|
const lines = buffer.split('\r\n');
|
||||||
|
buffer = lines.pop() || '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line) continue;
|
||||||
|
const code = parseInt(line.substring(0, 3), 10);
|
||||||
|
const isFinal = line.charAt(3) === ' ';
|
||||||
|
|
||||||
|
if (!isFinal) continue;
|
||||||
|
|
||||||
|
if (stage === 0) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 1;
|
||||||
|
socket.write(`EHLO canina.ir\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `پاسخ سرور: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 1) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
if (config.user && config.password) {
|
||||||
|
stage = 2;
|
||||||
|
socket.write('AUTH LOGIN\r\n');
|
||||||
|
} else {
|
||||||
|
stage = 5;
|
||||||
|
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `خطای EHLO: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 2) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 3;
|
||||||
|
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `خطای احراز هویت: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 3) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 4;
|
||||||
|
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `نام کاربری رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 4) {
|
||||||
|
if (code === 235 || (code >= 200 && code < 300)) {
|
||||||
|
stage = 5;
|
||||||
|
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `رمز عبور رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 5) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 6;
|
||||||
|
socket.write(`RCPT TO:<${options.to}>\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `آدرس فرستنده رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 6) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 7;
|
||||||
|
socket.write('DATA\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `آدرس گیرنده رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 7) {
|
||||||
|
if (code === 354) {
|
||||||
|
stage = 8;
|
||||||
|
const encodedSubject = `=?UTF-8?B?${Buffer.from(options.subject).toString('base64')}?=`;
|
||||||
|
const encodedFromName = `=?UTF-8?B?${Buffer.from(config.fromName).toString('base64')}?=`;
|
||||||
|
const boundary = `boundary_${Date.now()}`;
|
||||||
|
|
||||||
|
let emailBody = '';
|
||||||
|
emailBody += `From: ${encodedFromName} <${config.fromEmail}>\r\n`;
|
||||||
|
emailBody += `To: <${options.to}>\r\n`;
|
||||||
|
emailBody += `Subject: ${encodedSubject}\r\n`;
|
||||||
|
emailBody += `Message-ID: ${messageId}\r\n`;
|
||||||
|
emailBody += `Date: ${new Date().toUTCString()}\r\n`;
|
||||||
|
emailBody += `MIME-Version: 1.0\r\n`;
|
||||||
|
emailBody += `Content-Type: multipart/alternative; boundary="${boundary}"\r\n\r\n`;
|
||||||
|
|
||||||
|
if (options.text) {
|
||||||
|
emailBody += `--${boundary}\r\n`;
|
||||||
|
emailBody += `Content-Type: text/plain; charset=UTF-8\r\n`;
|
||||||
|
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||||
|
emailBody += Buffer.from(options.text).toString('base64') + '\r\n\r\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
const htmlContent = options.html || options.text || '';
|
||||||
|
emailBody += `--${boundary}\r\n`;
|
||||||
|
emailBody += `Content-Type: text/html; charset=UTF-8\r\n`;
|
||||||
|
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||||
|
emailBody += Buffer.from(htmlContent).toString('base64') + '\r\n\r\n';
|
||||||
|
|
||||||
|
emailBody += `--${boundary}--\r\n.\r\n`;
|
||||||
|
|
||||||
|
socket.write(emailBody);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `دستور DATA رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 8) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 9;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, messageId });
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `رد شدن ارسال محتوا: ${line}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let socket: net.Socket;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isExplicitTls) {
|
||||||
|
socket = tls.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
}, () => {});
|
||||||
|
} else {
|
||||||
|
socket = net.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
}, () => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.on('data', handleData);
|
||||||
|
socket.on('error', (err) => {
|
||||||
|
cleanup({ success: false, error: `خطای ارسال: ${err.message}` });
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
cleanup({ success: false, error: `خطا در باز کردن اتصال: ${err?.message}` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
describe('NotificationsQueueService', () => {
|
||||||
|
let service: NotificationsQueueService;
|
||||||
|
let prisma: any;
|
||||||
|
let emailService: any;
|
||||||
|
let smsService: any;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
notificationQueue: {
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
findMany: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
emailService = {
|
||||||
|
sendMail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
|
||||||
|
};
|
||||||
|
|
||||||
|
smsService = {
|
||||||
|
sendPatternSms: jest.fn().mockResolvedValue(true),
|
||||||
|
sendSms: jest.fn().mockResolvedValue(true),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
NotificationsQueueService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: EmailService, useValue: emailService },
|
||||||
|
{ provide: SmsService, useValue: smsService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<NotificationsQueueService>(NotificationsQueueService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should enqueue notification and preserve idempotency', async () => {
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(null);
|
||||||
|
prisma.notificationQueue.create.mockResolvedValueOnce({
|
||||||
|
id: 'queue-1',
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
event: 'ORDER_CREATED',
|
||||||
|
content: 'Hello World',
|
||||||
|
idempotencyKey: 'idemp-1',
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.enqueue({
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
event: 'ORDER_CREATED',
|
||||||
|
content: 'Hello World',
|
||||||
|
idempotencyKey: 'idemp-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(prisma.notificationQueue.findUnique).toHaveBeenCalledWith({ where: { idempotencyKey: 'idemp-1' } });
|
||||||
|
expect(prisma.notificationQueue.create).toHaveBeenCalled();
|
||||||
|
expect(res.id).toBe('queue-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return existing notification if idempotency key exists', async () => {
|
||||||
|
const existing = {
|
||||||
|
id: 'existing-1',
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: '09121111111',
|
||||||
|
event: 'OTP',
|
||||||
|
content: '12345',
|
||||||
|
idempotencyKey: 'idemp-2',
|
||||||
|
status: 'SENT',
|
||||||
|
};
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(existing);
|
||||||
|
|
||||||
|
const res = await service.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: '09121111111',
|
||||||
|
event: 'OTP',
|
||||||
|
content: '12345',
|
||||||
|
idempotencyKey: 'idemp-2',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(prisma.notificationQueue.create).not.toHaveBeenCalled();
|
||||||
|
expect(res.id).toBe('existing-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should process email queue item and mark as SENT', async () => {
|
||||||
|
const item = {
|
||||||
|
id: 'item-1',
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
subject: 'Test Subject',
|
||||||
|
content: 'Test Body',
|
||||||
|
payload: {},
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
};
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(item);
|
||||||
|
prisma.notificationQueue.update.mockResolvedValue({});
|
||||||
|
|
||||||
|
await service.processItem('item-1');
|
||||||
|
|
||||||
|
expect(emailService.sendMail).toHaveBeenCalledWith({
|
||||||
|
to: 'user@example.com',
|
||||||
|
subject: 'Test Subject',
|
||||||
|
text: 'Test Body',
|
||||||
|
html: expect.stringContaining('Test Body'),
|
||||||
|
});
|
||||||
|
const sentHtml = String((emailService.sendMail as jest.Mock).mock.calls[0][0].html);
|
||||||
|
expect(sentHtml).toContain('#1E4053');
|
||||||
|
expect(sentHtml).toContain('#F1B646');
|
||||||
|
expect(sentHtml).toContain('support@canina.ir');
|
||||||
|
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
|
||||||
|
where: { id: 'item-1' },
|
||||||
|
data: expect.objectContaining({ status: 'SENT' }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { renderCaninaNotificationEmail } from './email-layout';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
|
||||||
|
export interface EnqueueOptions {
|
||||||
|
channel: 'SMS' | 'EMAIL';
|
||||||
|
recipient: string;
|
||||||
|
event: string;
|
||||||
|
subject?: string;
|
||||||
|
content: string;
|
||||||
|
payload?: any;
|
||||||
|
idempotencyKey?: string;
|
||||||
|
maxAttempts?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private readonly logger = new Logger(NotificationsQueueService.name);
|
||||||
|
private workerInterval: NodeJS.Timeout | null = null;
|
||||||
|
private isProcessing = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly emailService: EmailService,
|
||||||
|
private readonly smsService: SmsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
// Run background queue processor every 15 seconds
|
||||||
|
this.workerInterval = setInterval(() => {
|
||||||
|
this.processQueue().catch((err) => {
|
||||||
|
this.logger.error(`Error in queue worker: ${err?.message}`);
|
||||||
|
});
|
||||||
|
}, 15000);
|
||||||
|
}
|
||||||
|
|
||||||
|
onModuleDestroy() {
|
||||||
|
if (this.workerInterval) {
|
||||||
|
clearInterval(this.workerInterval);
|
||||||
|
this.workerInterval = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enqueue a durable notification with idempotency check
|
||||||
|
*/
|
||||||
|
async enqueue(options: EnqueueOptions) {
|
||||||
|
if (options.idempotencyKey) {
|
||||||
|
const existing = await this.prisma.notificationQueue.findUnique({
|
||||||
|
where: { idempotencyKey: options.idempotencyKey },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
this.logger.log(`Notification idempotency matched for key: ${options.idempotencyKey}`);
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.prisma.notificationQueue.create({
|
||||||
|
data: {
|
||||||
|
channel: options.channel,
|
||||||
|
recipient: options.recipient,
|
||||||
|
event: options.event,
|
||||||
|
subject: options.subject || null,
|
||||||
|
content: options.content,
|
||||||
|
payload: options.payload ?? null,
|
||||||
|
idempotencyKey: options.idempotencyKey || null,
|
||||||
|
maxAttempts: options.maxAttempts ?? 3,
|
||||||
|
status: 'QUEUED',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attempt immediate asynchronous process in the background
|
||||||
|
setImmediate(() => {
|
||||||
|
this.processItem(item.id).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process a single queued item by ID
|
||||||
|
*/
|
||||||
|
async processItem(id: string) {
|
||||||
|
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||||
|
if (!item || item.status === 'SENT') return;
|
||||||
|
|
||||||
|
if (item.attempts >= item.maxAttempts) {
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'FAILED' },
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'PROCESSING',
|
||||||
|
attempts: { increment: 1 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (item.channel === 'EMAIL') {
|
||||||
|
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||||
|
const subject = item.subject || 'اطلاعیه کنینا ایران';
|
||||||
|
const res = await this.emailService.sendMail({
|
||||||
|
to: item.recipient,
|
||||||
|
subject,
|
||||||
|
text: item.content,
|
||||||
|
html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.success) {
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'SENT',
|
||||||
|
sentAt: new Date(),
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
throw new Error(res.error || 'خطای نامشخص در ارسال ایمیل');
|
||||||
|
}
|
||||||
|
} else if (item.channel === 'SMS') {
|
||||||
|
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||||
|
if (payloadObj.patternId && Array.isArray(payloadObj.args)) {
|
||||||
|
const sent = await this.smsService.sendPatternSms({
|
||||||
|
to: item.recipient,
|
||||||
|
bodyId: Number(payloadObj.patternId),
|
||||||
|
args: payloadObj.args,
|
||||||
|
type: item.event,
|
||||||
|
});
|
||||||
|
if (!sent) {
|
||||||
|
throw new Error(`ارسال پیامک پترن ${payloadObj.patternId} ناموفق بود.`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const sent = await this.smsService.sendSms(item.recipient, item.content);
|
||||||
|
if (!sent) {
|
||||||
|
throw new Error(`ارسال پیامک متنی به ${item.recipient} ناموفق بود.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'SENT',
|
||||||
|
sentAt: new Date(),
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
const isFinalAttempt = item.attempts + 1 >= item.maxAttempts;
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: isFinalAttempt ? 'FAILED' : 'QUEUED',
|
||||||
|
lastError: err?.message || 'خطا در ارسال پیام',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.logger.warn(`Failed to deliver notification ${id} (${item.channel} to ${item.recipient}): ${err?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process pending batch of queue
|
||||||
|
*/
|
||||||
|
async processQueue(batchSize = 10) {
|
||||||
|
if (this.isProcessing) return;
|
||||||
|
this.isProcessing = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pendingItems = await this.prisma.notificationQueue.findMany({
|
||||||
|
where: {
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: { lt: 3 },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
take: batchSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const item of pendingItems) {
|
||||||
|
await this.processItem(item.id);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.isProcessing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retry a failed notification manually
|
||||||
|
*/
|
||||||
|
async retry(id: string) {
|
||||||
|
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||||
|
if (!item) throw new Error('آیتم صف یافت نشد.');
|
||||||
|
|
||||||
|
const updated = await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
setImmediate(() => {
|
||||||
|
this.processItem(id).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get queue items with filtering and pagination
|
||||||
|
*/
|
||||||
|
async getQueue(query: { page?: number; limit?: number; status?: string; channel?: string; search?: string }) {
|
||||||
|
const page = Math.max(1, Number(query.page || 1));
|
||||||
|
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (query.status) where.status = query.status;
|
||||||
|
if (query.channel) where.channel = query.channel;
|
||||||
|
if (query.search) {
|
||||||
|
where.OR = [
|
||||||
|
{ recipient: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ subject: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ event: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.notificationQueue.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
this.prisma.notificationQueue.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const stats = await this.getStats();
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit) || 1,
|
||||||
|
stats,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get overall stats
|
||||||
|
*/
|
||||||
|
async getStats() {
|
||||||
|
const [total, queued, processing, sent, failed] = await Promise.all([
|
||||||
|
this.prisma.notificationQueue.count(),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'QUEUED' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'PROCESSING' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'SENT' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'FAILED' } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
queued,
|
||||||
|
processing,
|
||||||
|
sent,
|
||||||
|
failed,
|
||||||
|
successRate: total > 0 ? Math.round((sent / total) * 100) : 100,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
BadRequestException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { escapeHtml, renderCaninaEmailLayout, textToHtmlParagraphs } from './email-layout';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
UpdateEmailConfigDto,
|
||||||
|
TestSmtpDto,
|
||||||
|
SendTestEmailDto,
|
||||||
|
SendTestSmsDto,
|
||||||
|
ManualSendDto,
|
||||||
|
CreateTemplateDto,
|
||||||
|
} from './notifications.dto';
|
||||||
|
|
||||||
|
@Controller('admin/notifications')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class NotificationsController {
|
||||||
|
constructor(
|
||||||
|
private readonly emailService: EmailService,
|
||||||
|
private readonly queueService: NotificationsQueueService,
|
||||||
|
private readonly smsService: SmsService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification settings (Email & SMS)
|
||||||
|
*/
|
||||||
|
@Get('config')
|
||||||
|
async getConfig() {
|
||||||
|
const [email, sms] = await Promise.all([
|
||||||
|
this.emailService.getConfig(),
|
||||||
|
this.smsService.getSmsConfig(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Mask password for security
|
||||||
|
const maskedEmail = {
|
||||||
|
...email,
|
||||||
|
password: email.password ? '••••••••' : '',
|
||||||
|
};
|
||||||
|
|
||||||
|
const maskedSms = {
|
||||||
|
...sms,
|
||||||
|
password: sms.password ? '••••••••' : '',
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
email: maskedEmail,
|
||||||
|
sms: maskedSms,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update SMTP Email config
|
||||||
|
*/
|
||||||
|
@Put('email-config')
|
||||||
|
async updateEmailConfig(@Body() dto: UpdateEmailConfigDto) {
|
||||||
|
// If password is masked, don't overwrite with dots
|
||||||
|
if (dto.password && dto.password.includes('•')) {
|
||||||
|
delete dto.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
const saved = await this.emailService.saveConfig(dto);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'تنظیمات ایمیل با موفقیت ذخیره شد.',
|
||||||
|
data: {
|
||||||
|
...saved,
|
||||||
|
password: saved.password ? '••••••••' : '',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test SMTP connection live
|
||||||
|
*/
|
||||||
|
@Post('test-smtp')
|
||||||
|
async testSmtp(@Body() customConfig?: TestSmtpDto) {
|
||||||
|
if (customConfig?.password && customConfig.password.includes('•')) {
|
||||||
|
delete customConfig.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.emailService.testConnection(customConfig);
|
||||||
|
return {
|
||||||
|
success: res.success,
|
||||||
|
message: res.message,
|
||||||
|
banner: res.banner,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send test email
|
||||||
|
*/
|
||||||
|
@Post('send-test-email')
|
||||||
|
async sendTestEmail(@Body() body: SendTestEmailDto) {
|
||||||
|
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
|
||||||
|
|
||||||
|
const subject = body.subject || 'تست اتصال ایمیل - کنینا ایران';
|
||||||
|
const message =
|
||||||
|
body.message ||
|
||||||
|
'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.';
|
||||||
|
const res = await this.emailService.sendMail({
|
||||||
|
to: body.to,
|
||||||
|
subject,
|
||||||
|
text: message,
|
||||||
|
html: renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 16px;">${textToHtmlParagraphs(message)}</p><p style="margin:0;font-size:13px;color:#7A9B9F;">زمان ارسال: ${escapeHtml(new Date().toLocaleString('fa-IR'))}</p>`,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.success) {
|
||||||
|
throw new BadRequestException(res.error || 'ارسال ایمیل تستی ناموفق بود.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `ایمیل تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||||
|
messageId: res.messageId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send test SMS
|
||||||
|
*/
|
||||||
|
@Post('send-test-sms')
|
||||||
|
async sendTestSms(@Body() body: SendTestSmsDto) {
|
||||||
|
if (!body.to || !body.message) {
|
||||||
|
throw new BadRequestException('شماره موبایل و متن پیام الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.smsService.sendSms(body.to, body.message);
|
||||||
|
if (!res) throw new BadRequestException('ارسال پیامک تستی ناموفق بود.');
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `پیامک تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual targeted notification send
|
||||||
|
*/
|
||||||
|
@Post('manual-send')
|
||||||
|
async manualSend(@Body() body: ManualSendDto) {
|
||||||
|
if (!body.channel || !body.content) {
|
||||||
|
throw new BadRequestException('کانال ارسال و متن پیام الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let targetList: string[] = [];
|
||||||
|
|
||||||
|
if (body.targetType === 'single') {
|
||||||
|
if (!body.recipient) throw new BadRequestException('گیرنده پیام مشخص نشده است.');
|
||||||
|
targetList = [body.recipient.trim()];
|
||||||
|
} else if (body.targetType === 'custom_list') {
|
||||||
|
if (!Array.isArray(body.recipients) || !body.recipients.length) {
|
||||||
|
throw new BadRequestException('لیست گیرندگان خالی است.');
|
||||||
|
}
|
||||||
|
targetList = body.recipients.map((r) => r.trim()).filter(Boolean);
|
||||||
|
} else if (body.targetType === 'all_users') {
|
||||||
|
const users = await this.prisma.user.findMany({
|
||||||
|
select: { mobile: true, email: true },
|
||||||
|
take: 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (body.channel === 'SMS') {
|
||||||
|
targetList = users.map((u) => u.mobile).filter(Boolean) as string[];
|
||||||
|
} else {
|
||||||
|
targetList = users.map((u) => u.email).filter(Boolean) as string[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetList.length) {
|
||||||
|
throw new BadRequestException('هیچ گیرنده معتبری برای ارسال یافت نشد.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enqueue all items into durable queue
|
||||||
|
const queuedItems = await Promise.all(
|
||||||
|
targetList.map((rec) =>
|
||||||
|
this.queueService.enqueue({
|
||||||
|
channel: body.channel,
|
||||||
|
recipient: rec,
|
||||||
|
event: 'MANUAL_TARGETED_SEND',
|
||||||
|
subject: body.subject,
|
||||||
|
content: body.content,
|
||||||
|
idempotencyKey: `manual_${body.channel}_${rec}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `${queuedItems.length} پیام با موفقیت در صف ارسال قرار گرفت.`,
|
||||||
|
count: queuedItems.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get queue items and statistics
|
||||||
|
*/
|
||||||
|
@Get('queue')
|
||||||
|
async getQueue(
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('limit') limit?: number,
|
||||||
|
@Query('status') status?: string,
|
||||||
|
@Query('channel') channel?: string,
|
||||||
|
@Query('search') search?: string,
|
||||||
|
) {
|
||||||
|
const data = await this.queueService.getQueue({ page, limit, status, channel, search });
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retry failed queue item
|
||||||
|
*/
|
||||||
|
@Post('queue/:id/retry')
|
||||||
|
async retryQueueItem(@Param('id') id: string) {
|
||||||
|
const retried = await this.queueService.retry(id);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'پیام مجدداً در صف ارسال قرار گرفت.',
|
||||||
|
data: retried,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification templates & event definitions
|
||||||
|
*/
|
||||||
|
@Get('templates')
|
||||||
|
async getTemplates() {
|
||||||
|
const templates = await this.prisma.notificationTemplate.findMany({
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const defaultEvents = [
|
||||||
|
{ event: 'ORDER_CREATED', name: 'ثبت سفارش جدید', variables: ['order_id', 'customer_name', 'total_amount'] },
|
||||||
|
{ event: 'PAYMENT_SUCCESS', name: 'پرداخت موفق سفارش', variables: ['order_id', 'track_id', 'amount'] },
|
||||||
|
{ event: 'ORDER_SHIPPED', name: 'ارسال سفارش پستی', variables: ['order_id', 'tracking_code', 'carrier'] },
|
||||||
|
{ event: 'NEW_LEAD', name: 'درخواست تماس یا مشاوره جدید', variables: ['lead_name', 'phone', 'product_name'] },
|
||||||
|
{ event: 'USER_REGISTERED', name: 'ثبتنام کاربر جدید', variables: ['user_name', 'mobile'] },
|
||||||
|
{ event: 'TICKET_REPLIED', name: 'پاسخ به تیکت پشتیبانی', variables: ['ticket_id', 'user_name'] },
|
||||||
|
];
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
templates,
|
||||||
|
events: defaultEvents,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update notification template
|
||||||
|
*/
|
||||||
|
@Post('templates')
|
||||||
|
async upsertTemplate(@Body() dto: CreateTemplateDto) {
|
||||||
|
if (!dto.channel || !dto.event || !dto.name || !dto.body) {
|
||||||
|
throw new BadRequestException('اطلاعات ضروری قالب ناقص است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
channel: dto.channel,
|
||||||
|
event: dto.event,
|
||||||
|
name: dto.name,
|
||||||
|
subject: dto.subject || null,
|
||||||
|
body: dto.body,
|
||||||
|
patternCode: dto.patternCode || null,
|
||||||
|
variables: dto.variables || [],
|
||||||
|
recipientType: dto.recipientType || 'customer',
|
||||||
|
customRecipient: dto.customRecipient || null,
|
||||||
|
isActive: dto.isActive !== undefined ? dto.isActive : true,
|
||||||
|
};
|
||||||
|
|
||||||
|
let template;
|
||||||
|
if (dto.id) {
|
||||||
|
template = await this.prisma.notificationTemplate.update({
|
||||||
|
where: { id: dto.id },
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
template = await this.prisma.notificationTemplate.upsert({
|
||||||
|
where: {
|
||||||
|
channel_event: {
|
||||||
|
channel: dto.channel,
|
||||||
|
event: dto.event,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: data,
|
||||||
|
update: data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'قالب رویداد با موفقیت ذخیره شد.',
|
||||||
|
data: template,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete template
|
||||||
|
*/
|
||||||
|
@Delete('templates/:id')
|
||||||
|
async deleteTemplate(@Param('id') id: string) {
|
||||||
|
await this.prisma.notificationTemplate.delete({ where: { id } });
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'قالب رویداد حذف شد.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { IsString, IsNotEmpty, IsOptional, IsNumber, IsBoolean, IsIn, IsArray } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateEmailConfigDto {
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
enabled?: boolean;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
host!: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
port!: number;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
secure?: boolean = true;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
user?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
password?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromName?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromEmail?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TestSmtpDto {
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
enabled?: boolean;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
host?: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
port?: number;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
secure?: boolean = true;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
user?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
password?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromName?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromEmail?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SendTestEmailDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
to!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SendTestSmsDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
to!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
message!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ManualSendDto {
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['SMS', 'EMAIL'])
|
||||||
|
channel!: 'SMS' | 'EMAIL';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['single', 'all_users', 'custom_list'])
|
||||||
|
targetType!: 'single' | 'all_users' | 'custom_list';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
recipient?: string;
|
||||||
|
|
||||||
|
@IsArray()
|
||||||
|
@IsOptional()
|
||||||
|
recipients?: string[];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
content!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateTemplateDto {
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
id?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['SMS', 'EMAIL'])
|
||||||
|
channel!: 'SMS' | 'EMAIL';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
event!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
body!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
patternCode?: string;
|
||||||
|
|
||||||
|
@IsArray()
|
||||||
|
@IsOptional()
|
||||||
|
variables?: string[];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
recipientType?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
customRecipient?: string;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { SmsModule } from '../common/sms.module';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { NotificationsController } from './notifications.controller';
|
||||||
|
import { TransactionalEmailsService } from './transactional-emails.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [PrismaModule, SmsModule],
|
||||||
|
controllers: [NotificationsController],
|
||||||
|
providers: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||||
|
exports: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||||
|
})
|
||||||
|
export class NotificationsModule {}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import {
|
||||||
|
escapeHtml,
|
||||||
|
renderCaninaEmailLayout,
|
||||||
|
textToHtmlParagraphs,
|
||||||
|
} from './email-layout';
|
||||||
|
|
||||||
|
const ADMIN_NOTIFY_TO = [
|
||||||
|
'support@canina.ir',
|
||||||
|
'parsa.aghaee@gmail.com',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TransactionalEmailsService {
|
||||||
|
private readonly logger = new Logger(TransactionalEmailsService.name);
|
||||||
|
|
||||||
|
constructor(private readonly emailService: EmailService) {}
|
||||||
|
|
||||||
|
private async sendSafe(to: string, subject: string, text: string, html: string) {
|
||||||
|
try {
|
||||||
|
const res = await this.emailService.sendMail({ to, subject, text, html });
|
||||||
|
if (!res.success) {
|
||||||
|
this.logger.warn(`Email to ${to} failed: ${res.error || 'unknown'}`);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(`Email to ${to} threw: ${(err as Error).message}`);
|
||||||
|
return { success: false, error: (err as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendWelcome(to: string | null | undefined, firstName?: string | null) {
|
||||||
|
if (!to) return;
|
||||||
|
const name = (firstName || '').trim() || 'کاربر گرامی';
|
||||||
|
const subject = 'به کنینا خوش آمدید';
|
||||||
|
const text = `سلام ${name}،\n\nثبتنام شما در فروشگاه کنینا با موفقیت انجام شد.\n\ncanina.ir`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0;">ثبتنام شما در فروشگاه کنینا با موفقیت انجام شد. از این به بعد میتوانید سفارشها و وضعیت حساب خود را از سایت پیگیری کنید.</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderCreated(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||||
|
if (!to) return;
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const amount = Number(order.totalAmount || 0);
|
||||||
|
const subject = 'سفارش شما در کنینا ثبت شد';
|
||||||
|
const text = `سفارش شما ثبت شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سفارش شما ثبت شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ سفارش: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p><p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">این پیام بهتنهایی بهمعنای تأیید پرداخت نیست؛ وضعیت پرداخت را در حساب کاربری بررسی کنید.</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderPaid(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||||
|
if (!to) return;
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const amount = Number(order.totalAmount || 0);
|
||||||
|
const subject = 'پرداخت سفارش کنینا تأیید شد';
|
||||||
|
const text = `پرداخت سفارش تأیید شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">پرداخت سفارش شما با موفقیت تأیید شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ پرداختشده: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderShipped(
|
||||||
|
to: string | null | undefined,
|
||||||
|
order: { id?: string; trackingNumber?: string | null },
|
||||||
|
trackingCode?: string,
|
||||||
|
) {
|
||||||
|
if (!to) return;
|
||||||
|
const track = escapeHtml(String(trackingCode || order.trackingNumber || 'ارسال با پیک شهری'));
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const subject = 'سفارش کنینا ارسال شد';
|
||||||
|
const text = `سفارش شما ارسال شد.\nسفارش: ${order.trackingNumber || order.id || ''}\nرهگیری: ${trackingCode || order.trackingNumber || 'ارسال با پیک شهری'}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">وضعیت سفارش به ارسالشده تغییر کرد.</p><p style="margin:0 0 8px;">سفارش: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">کد/روش ارسال: <b dir="ltr">${track}</b></p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendContactConfirmation(to: string | null | undefined, name: string, message: string, submissionId?: string) {
|
||||||
|
if (!to) return;
|
||||||
|
const subject = 'پیام شما در کنینا ثبت شد';
|
||||||
|
const text = `سلام ${name}،\n\nپیام شما ثبت شد و بهزودی بررسی میشود.\nشناسه: ${submissionId || ''}\n\n${message}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0 0 16px;">پیام شما از طریق فرم تماس کنینا ثبت شد و بهزودی بررسی میشود.</p><div style="padding:14px;background:#F4F7F6;border:1px solid #E5ECE9;border-right:3px solid #F1B646;"><p style="margin:0;white-space:pre-wrap;">${textToHtmlParagraphs(message || '')}</p></div>${submissionId ? `<p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">شناسه پیگیری: <span dir="ltr">#${escapeHtml(submissionId)}</span></p>` : ''}`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async notifyAdminsAboutContact(dto: {
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
email?: string;
|
||||||
|
subject?: string;
|
||||||
|
message: string;
|
||||||
|
submissionId?: string;
|
||||||
|
}) {
|
||||||
|
const subject = `پیام جدید فرم تماس کنینا${dto.subject ? ` — ${dto.subject}` : ''}`;
|
||||||
|
const text = `نام: ${dto.name}\nتلفن: ${dto.phone}\nایمیل: ${dto.email || '-'}\nموضوع: ${dto.subject || '-'}\nشناسه: ${dto.submissionId || '-'}\n\n${dto.message}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: 'پیام جدید از فرم تماس',
|
||||||
|
bodyHtml: `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;width:110px;">نام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;">${escapeHtml(dto.name)}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">تلفن</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.phone)}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">ایمیل</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.email || '-')}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;vertical-align:top;">پیام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;white-space:pre-wrap;">${textToHtmlParagraphs(dto.message || '')}</td></tr>
|
||||||
|
</table>`,
|
||||||
|
});
|
||||||
|
await Promise.all(
|
||||||
|
ADMIN_NOTIFY_TO.map((to) => this.sendSafe(to, subject, text, html)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { OrdersService } from "./orders.service";
|
import { OrdersService } from "./orders.service";
|
||||||
import { OrdersController } from "./orders.controller";
|
import { OrdersController } from "./orders.controller";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [NotificationsModule],
|
||||||
controllers: [OrdersController],
|
controllers: [OrdersController],
|
||||||
providers: [OrdersService],
|
providers: [OrdersService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
|||||||
import { OrdersService } from "./orders.service";
|
import { OrdersService } from "./orders.service";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { NotFoundException, BadRequestException } from "@nestjs/common";
|
import { NotFoundException, BadRequestException } from "@nestjs/common";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@@ -58,6 +59,7 @@ describe("OrdersService", () => {
|
|||||||
OrdersService,
|
OrdersService,
|
||||||
{ provide: PrismaService, useValue: mockPrisma },
|
{ provide: PrismaService, useValue: mockPrisma },
|
||||||
{ provide: SmsService, useValue: mockSmsService },
|
{ provide: SmsService, useValue: mockSmsService },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { PrismaService } from "../prisma/prisma.service";
|
|||||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||||
import { CreateOrderDto } from "./dto/create-order.dto";
|
import { CreateOrderDto } from "./dto/create-order.dto";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -17,6 +18,7 @@ export class OrdersService {
|
|||||||
constructor(
|
constructor(
|
||||||
private prisma: PrismaService,
|
private prisma: PrismaService,
|
||||||
private smsService: SmsService,
|
private smsService: SmsService,
|
||||||
|
private transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private generateTrackingNumber(): string {
|
private generateTrackingNumber(): string {
|
||||||
@@ -303,6 +305,9 @@ export class OrdersService {
|
|||||||
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
|
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(user.email, createdWalletOrder)
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
return createdWalletOrder;
|
return createdWalletOrder;
|
||||||
}
|
}
|
||||||
@@ -375,6 +380,11 @@ export class OrdersService {
|
|||||||
.triggerEvent("ORDER_CREATED", orderData)
|
.triggerEvent("ORDER_CREATED", orderData)
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
if (user?.email) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderCreated(user.email, createdOrder)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createdOrder;
|
return createdOrder;
|
||||||
@@ -529,6 +539,9 @@ export class OrdersService {
|
|||||||
: "پیک شهری";
|
: "پیک شهری";
|
||||||
|
|
||||||
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
|
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderShipped(updatedOrder.user?.email, updatedOrder, finalTracking)
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return updatedOrder;
|
return updatedOrder;
|
||||||
@@ -707,6 +720,9 @@ export class OrdersService {
|
|||||||
.triggerEvent("ORDER_PAID", orderData)
|
.triggerEvent("ORDER_PAID", orderData)
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(user.email, order)
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
import { PaymentController } from "./payment.controller";
|
import { PaymentController } from "./payment.controller";
|
||||||
import { PaymentService } from "./payment.service";
|
import { PaymentService } from "./payment.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
@@ -7,7 +8,7 @@ import { PrismaModule } from "../prisma/prisma.module";
|
|||||||
import { SmsModule } from "../common/sms.module";
|
import { SmsModule } from "../common/sms.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, SmsModule],
|
imports: [NotificationsModule, PrismaModule, SmsModule],
|
||||||
controllers: [PaymentController],
|
controllers: [PaymentController],
|
||||||
providers: [PaymentService, ZibalService, ZibalEBankService],
|
providers: [PaymentService, ZibalService, ZibalEBankService],
|
||||||
exports: [PaymentService, ZibalService, ZibalEBankService],
|
exports: [PaymentService, ZibalService, ZibalEBankService],
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { PaymentService } from "./payment.service";
|
|||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@@ -72,6 +73,7 @@ describe("PaymentService", () => {
|
|||||||
{ provide: PrismaService, useValue: mockPrisma },
|
{ provide: PrismaService, useValue: mockPrisma },
|
||||||
{ provide: ZibalService, useValue: mockZibalService },
|
{ provide: ZibalService, useValue: mockZibalService },
|
||||||
{ provide: SmsService, useValue: mockSmsService },
|
{ provide: SmsService, useValue: mockSmsService },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { AdminTransactionFilterDto } from "./dto/admin-transaction-filter.dto";
|
import { AdminTransactionFilterDto } from "./dto/admin-transaction-filter.dto";
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ export class PaymentService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly zibalService: ZibalService,
|
private readonly zibalService: ZibalService,
|
||||||
private readonly smsService: SmsService,
|
private readonly smsService: SmsService,
|
||||||
|
private readonly transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -641,6 +643,16 @@ export class PaymentService {
|
|||||||
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
|
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
|
||||||
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
|
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
|
||||||
});
|
});
|
||||||
|
const emailTo =
|
||||||
|
transaction.user?.email ||
|
||||||
|
order?.user?.email ||
|
||||||
|
null;
|
||||||
|
const orderForEmail = order || transaction.order;
|
||||||
|
if (emailTo && orderForEmail) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(emailTo, orderForEmail)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send SMS notification if wallet top-up
|
// Send SMS notification if wallet top-up
|
||||||
|
|||||||
@@ -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(
|
||||||
/\/$/,
|
/\/$/,
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -276,6 +276,7 @@ export class SettingsService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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()} };
|
||||||
|
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,4 +1,7 @@
|
|||||||
import { 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;
|
||||||
|
@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,11 +15,11 @@ 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());
|
||||||
@@ -27,7 +28,7 @@ describe('support HTTP boundary', () => {
|
|||||||
process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test';
|
process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test';
|
||||||
jest.spyOn(global,'fetch').mockImplementation(async (url, opts) => {
|
jest.spyOn(global,'fetch').mockImplementation(async (url, opts) => {
|
||||||
const message=JSON.parse(opts!.body as string).message;
|
const message=JSON.parse(opts!.body as string).message;
|
||||||
const intent=message==='کیف پول'?'wallet':message==='سفارش من'||message==='سفارش'?'orders':'public';
|
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;
|
return {ok:true,status:200,json:async()=>String(url).endsWith('/classify')?{intent}:{answer:'راهنمای محصولات کنینا'}} as any;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -37,6 +38,11 @@ describe('support HTTP boundary', () => {
|
|||||||
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:'سفارش من'}).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:'کیف پول'}).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();
|
||||||
|
|||||||
@@ -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('model intent routing', () => {
|
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();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';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);});
|
||||||
afterEach(()=>jest.restoreAllMocks());
|
afterEach(()=>jest.restoreAllMocks());
|
||||||
function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); }
|
function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); }
|
||||||
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();});
|
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();});
|
||||||
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:'چقدر اعتبار دارم؟'});expect(f).toHaveBeenCalledTimes(1);});
|
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:['حساسیت']}]);});
|
||||||
|
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.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();});
|
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,46 +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 }) {
|
||||||
const url = process.env.SUPPORT_CHAT_URL;
|
const config = await this.settings.read(); if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE);
|
||||||
const key = process.env.SUPPORT_CHAT_KEY;
|
const db = this.db(); let conversation: any;
|
||||||
let intent: 'public' | 'orders' | 'wallet';
|
if (input.conversationId) {
|
||||||
|
conversation = await db.supportConversation.findUnique({ where: { id: input.conversationId }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } });
|
||||||
|
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 } });
|
||||||
|
}
|
||||||
|
const conversationHistory = (conversation.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content }));
|
||||||
|
const selection = { provider: config.provider, model: config.model };
|
||||||
|
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' } }) : [];
|
||||||
|
const petContext = pets.map((pet: any) => ({ ...pet, medicalConditions: pet.medicalConditions.map((item: any) => item.condition) }));
|
||||||
|
let intent: 'public' | 'orders' | 'wallet' | 'profile';
|
||||||
try {
|
try {
|
||||||
if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled');
|
if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled');
|
||||||
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 }) });
|
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 }) });
|
||||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم. پیوند دلخواه پذیرفته نمیشود.' };
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.' };
|
||||||
if (!response.ok) throw new Error('upstream');
|
if (!response.ok) throw new Error('upstream'); const data = await response.json();
|
||||||
const data = await response.json();
|
if (!data || Object.keys(data).length !== 1 || !['public','orders','wallet','profile'].includes(data.intent)) throw new Error('intent'); intent = data.intent;
|
||||||
if (!data || Object.keys(data).length !== 1 || !['public', 'orders', 'wallet'].includes(data.intent)) throw new Error('intent');
|
|
||||||
intent = data.intent;
|
|
||||||
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
||||||
if (intent !== 'public' && !user) return { answer: 'برای مشاهده سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' };
|
if (intent !== 'public' && !user) return { answer: 'برای مشاهده اطلاعات حساب، سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.', conversationId: conversation.id, contextLimited: conversationHistory.length >= MAX_HISTORY };
|
||||||
if (intent === 'wallet') {
|
let answer: string; let products: any[] = [];
|
||||||
const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } });
|
|
||||||
if (!row) throw new ServiceUnavailableException(UNAVAILABLE);
|
|
||||||
return { answer: `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.` };
|
|
||||||
}
|
|
||||||
if (intent === 'orders') {
|
|
||||||
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' } });
|
|
||||||
return { answer: rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.' };
|
|
||||||
}
|
|
||||||
// Private account rows never leave the backend, even when the model is compromised.
|
|
||||||
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 (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 = `اطلاعات تماس ثبتشده برای حساب شما:
|
||||||
const url = process.env.SUPPORT_CHAT_URL;
|
شماره موبایل: ${row.mobile || 'ثبت نشده'}
|
||||||
const key = process.env.SUPPORT_CHAT_KEY;
|
ایمیل: ${row.email || 'ثبت نشده'}.`; }
|
||||||
if (!url || !key) throw new Error('disabled');
|
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') : 'سفارشی برای حساب شما ثبت نشده است.'; }
|
||||||
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 }) });
|
else {
|
||||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمیشود.' };
|
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 (!response.ok) throw new Error('upstream');
|
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 }) });
|
||||||
const data = await response.json();
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.', conversationId: conversation.id };
|
||||||
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');
|
if (!response.ok) throw new Error('upstream'); const data = await response.json(); answer = data.answer;
|
||||||
return { 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); }
|
} 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');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
+23
-5
@@ -1,5 +1,3 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db_stage:
|
db_stage:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
@@ -25,22 +23,36 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ./backend
|
context: ./backend
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
NPM_REGISTRY: ${NPM_REGISTRY:-}
|
||||||
container_name: canino_backend_stage
|
container_name: canino_backend_stage
|
||||||
restart: always
|
restart: always
|
||||||
|
env_file:
|
||||||
|
- path: .support-chat.env
|
||||||
|
required: false
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
|
dns:
|
||||||
|
- 217.218.127.127
|
||||||
|
- 217.218.155.155
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgresql://canino_stage:caninopassword_stage@db_stage:5432/caninodb_stage?schema=public
|
- DATABASE_URL=postgresql://canino_stage:caninopassword_stage@db_stage:5432/caninodb_stage?schema=public
|
||||||
|
- SUPPORT_CHAT_URL=http://canina-bot:8643/support/ask
|
||||||
- REDIS_HOST=redis_stage
|
- REDIS_HOST=redis_stage
|
||||||
- REDIS_PORT=6379
|
- REDIS_PORT=6379
|
||||||
- PORT=3000
|
- PORT=3000
|
||||||
- ADMIN_PASSWORD=Z6nYnJRG_sg3pnz2J9wZ7dLsPj61cd5k
|
- FRONTEND_URL=https://stage.canina.ir
|
||||||
|
- ENABLE_SWAGGER=false
|
||||||
|
# Code-only stage startup: schema/seed changes require separate authorization.
|
||||||
|
command: ["node", "dist/main.js"]
|
||||||
volumes:
|
volumes:
|
||||||
- canina_stage_uploads:/app/uploads
|
- canina_stage_uploads:/app/uploads
|
||||||
|
- /opt/services/proxy/certs/canina:/app/ssl_certs
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.canina-api-stage.rule=Host(`stageapi.canina.ir`)"
|
- "traefik.http.routers.canina-api-stage.rule=Host(`stageapi.canina.ir`)"
|
||||||
- "traefik.http.routers.canina-api-stage.entrypoints=websecure"
|
- "traefik.http.routers.canina-api-stage.entrypoints=websecure"
|
||||||
- "traefik.http.routers.canina-api-stage.tls=true"
|
- "traefik.http.routers.canina-api-stage.tls=true"
|
||||||
- "traefik.http.routers.canina-api-stage.tls.certresolver=arvan"
|
|
||||||
- "traefik.http.services.canina-api-stage.loadbalancer.server.port=3000"
|
- "traefik.http.services.canina-api-stage.loadbalancer.server.port=3000"
|
||||||
depends_on:
|
depends_on:
|
||||||
- db_stage
|
- db_stage
|
||||||
@@ -53,16 +65,22 @@ services:
|
|||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
args:
|
args:
|
||||||
|
NPM_REGISTRY: ${NPM_REGISTRY:-}
|
||||||
NEXT_PUBLIC_API_URL: "https://stageapi.canina.ir/api"
|
NEXT_PUBLIC_API_URL: "https://stageapi.canina.ir/api"
|
||||||
VITE_API_URL: "https://stageapi.canina.ir"
|
VITE_API_URL: "https://stageapi.canina.ir"
|
||||||
container_name: canino_frontend_stage
|
container_name: canino_frontend_stage
|
||||||
restart: always
|
restart: always
|
||||||
|
env_file:
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
|
dns:
|
||||||
|
- 217.218.127.127
|
||||||
|
- 217.218.155.155
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.canina-stage.rule=Host(`stage.canina.ir`) || Host(`stageadmin.canina.ir`)"
|
- "traefik.http.routers.canina-stage.rule=Host(`stage.canina.ir`) || Host(`stageadmin.canina.ir`)"
|
||||||
- "traefik.http.routers.canina-stage.entrypoints=websecure"
|
- "traefik.http.routers.canina-stage.entrypoints=websecure"
|
||||||
- "traefik.http.routers.canina-stage.tls=true"
|
- "traefik.http.routers.canina-stage.tls=true"
|
||||||
- "traefik.http.routers.canina-stage.tls.certresolver=arvan"
|
|
||||||
- "traefik.http.routers.canina-stage.middlewares=staging-robots-headers"
|
- "traefik.http.routers.canina-stage.middlewares=staging-robots-headers"
|
||||||
- "traefik.http.middlewares.staging-robots-headers.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, nosnippet, noarchive"
|
- "traefik.http.middlewares.staging-robots-headers.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, nosnippet, noarchive"
|
||||||
- "traefik.http.services.canina-stage.loadbalancer.server.port=8080"
|
- "traefik.http.services.canina-stage.loadbalancer.server.port=8080"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
Activity,
|
Activity,
|
||||||
|
Bell,
|
||||||
CheckSquare,
|
CheckSquare,
|
||||||
BookOpen,
|
BookOpen,
|
||||||
Building2,
|
Building2,
|
||||||
@@ -109,6 +110,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' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -169,6 +171,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
|||||||
{ icon: Users, label: 'مدیریت کاربران', path: '/users' },
|
{ icon: Users, label: 'مدیریت کاربران', path: '/users' },
|
||||||
{ icon: Heart, label: 'پرونده پتها (همدمها)', path: '/pets' },
|
{ icon: Heart, label: 'پرونده پتها (همدمها)', path: '/pets' },
|
||||||
{ icon: MessageSquare, label: 'تیکتها و مشاوره تخصصی', path: '/tickets' },
|
{ icon: MessageSquare, label: 'تیکتها و مشاوره تخصصی', path: '/tickets' },
|
||||||
|
{ icon: PhoneCall, label: 'مشاوران و لیدهای تماس', path: '/advisors' },
|
||||||
{ icon: Building2, label: 'پرتال B2B و همکاران', path: '/b2b' },
|
{ icon: Building2, label: 'پرتال B2B و همکاران', path: '/b2b' },
|
||||||
{ icon: PhoneCall, label: 'اطلاعات تماس و پیامها', path: '/contact' },
|
{ icon: PhoneCall, label: 'اطلاعات تماس و پیامها', path: '/contact' },
|
||||||
],
|
],
|
||||||
@@ -200,6 +203,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
|||||||
{ icon: CreditCard, label: 'روشهای پرداخت و زیبال', path: '/settings/payment-methods' },
|
{ icon: CreditCard, label: 'روشهای پرداخت و زیبال', path: '/settings/payment-methods' },
|
||||||
{ icon: Truck, label: 'تنظیمات ارسال و کرایه', path: '/settings/shipping' },
|
{ icon: Truck, label: 'تنظیمات ارسال و کرایه', path: '/settings/shipping' },
|
||||||
{ icon: DollarSign, label: 'تنظیمات مالی و مالیات', path: '/settings/financial' },
|
{ icon: DollarSign, label: 'تنظیمات مالی و مالیات', path: '/settings/financial' },
|
||||||
|
{ icon: Bell, label: 'مرکز اطلاعرسانی (ایمیل و صف)', path: '/settings/notifications' },
|
||||||
{ icon: MessageSquare, label: 'درگاه پیامک (MeliPayamak)', path: '/settings/sms' },
|
{ icon: MessageSquare, label: 'درگاه پیامک (MeliPayamak)', path: '/settings/sms' },
|
||||||
{ icon: ShieldCheck, label: 'گواهی SSL و امنیت', path: '/settings/ssl' },
|
{ icon: ShieldCheck, label: 'گواهی SSL و امنیت', path: '/settings/ssl' },
|
||||||
{ icon: Key, label: 'کلیدهای دسترسی (API Keys)', path: '/settings/api-keys' },
|
{ icon: Key, label: 'کلیدهای دسترسی (API Keys)', path: '/settings/api-keys' },
|
||||||
|
|||||||
@@ -0,0 +1,512 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
Users,
|
||||||
|
UserPlus,
|
||||||
|
PhoneCall,
|
||||||
|
CheckCircle2,
|
||||||
|
Clock,
|
||||||
|
Trash2,
|
||||||
|
Edit2,
|
||||||
|
Star,
|
||||||
|
Search,
|
||||||
|
Package,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
import Button from '../components/ui/Button';
|
||||||
|
import Spinner from '../components/ui/Spinner';
|
||||||
|
import Modal from '../components/ui/Modal';
|
||||||
|
import api from '../services/api';
|
||||||
|
|
||||||
|
interface Advisor {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
title?: string;
|
||||||
|
isDefault: boolean;
|
||||||
|
isActive: boolean;
|
||||||
|
productsCount: number;
|
||||||
|
leadsCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Lead {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
phone: string;
|
||||||
|
status: string;
|
||||||
|
notes?: string;
|
||||||
|
createdAt: string;
|
||||||
|
advisor?: { id: string; name: string; phone: string; title?: string };
|
||||||
|
product?: { id: string; nameFa: string; nameEn: string; slug: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdvisorsManagementPage() {
|
||||||
|
const [activeTab, setActiveTab] = useState<'leads' | 'advisors'>('leads');
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
|
// Advisors State
|
||||||
|
const [advisors, setAdvisors] = useState<Advisor[]>([]);
|
||||||
|
const [isAdvisorModalOpen, setIsAdvisorModalOpen] = useState(false);
|
||||||
|
const [editingAdvisor, setEditingAdvisor] = useState<Advisor | null>(null);
|
||||||
|
const [advisorForm, setAdvisorForm] = useState({
|
||||||
|
name: '',
|
||||||
|
phone: '',
|
||||||
|
title: '',
|
||||||
|
isDefault: false,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Leads State
|
||||||
|
const [leads, setLeads] = useState<Lead[]>([]);
|
||||||
|
const [leadStats, setLeadStats] = useState({ total: 0, pending: 0, contacted: 0, cancelled: 0 });
|
||||||
|
const [leadFilterStatus, setLeadFilterStatus] = useState<string>('ALL');
|
||||||
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
|
|
||||||
|
const loadAdvisors = async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get('/admin/advisors');
|
||||||
|
if (res.data?.success) {
|
||||||
|
setAdvisors(res.data.data);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
toast.error('خطا در دریافت لیست مشاوران');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadLeads = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const res = await api.get(`/admin/leads?status=${leadFilterStatus}&search=${encodeURIComponent(searchTerm)}`);
|
||||||
|
if (res.data?.success) {
|
||||||
|
setLeads(res.data.data.items);
|
||||||
|
if (res.data.data.stats) setLeadStats(res.data.data.stats);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
toast.error('خطا در دریافت لیست درخواستهای تماس');
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadAdvisors();
|
||||||
|
loadLeads();
|
||||||
|
}, [leadFilterStatus]);
|
||||||
|
|
||||||
|
const handleSearch = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
loadLeads();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveAdvisor = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!advisorForm.name.trim() || !advisorForm.phone.trim()) {
|
||||||
|
toast.error('نام و شماره موبایل الزامی است.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (editingAdvisor) {
|
||||||
|
await api.put(`/admin/advisors/${editingAdvisor.id}`, advisorForm);
|
||||||
|
toast.success('مشاور با موفقیت ویرایش شد.');
|
||||||
|
} else {
|
||||||
|
await api.post('/admin/advisors', advisorForm);
|
||||||
|
toast.success('مشاور جدید افزوده شد.');
|
||||||
|
}
|
||||||
|
setIsAdvisorModalOpen(false);
|
||||||
|
setEditingAdvisor(null);
|
||||||
|
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
|
||||||
|
loadAdvisors();
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err?.response?.data?.message || 'خطا در ثبت مشاور');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSetDefaultAdvisor = async (id: string) => {
|
||||||
|
try {
|
||||||
|
await api.patch(`/admin/advisors/${id}/set-default`);
|
||||||
|
toast.success('مشاور به عنوان پیشفرض تعیین شد.');
|
||||||
|
loadAdvisors();
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error('خطا در تغییر مشاور پیشفرض');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteAdvisor = async (id: string) => {
|
||||||
|
if (!window.confirm('آیا از حذف این مشاور اطمینان دارید؟')) return;
|
||||||
|
try {
|
||||||
|
await api.delete(`/admin/advisors/${id}`);
|
||||||
|
toast.success('مشاور حذف شد.');
|
||||||
|
loadAdvisors();
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error('خطا در حذف مشاور');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUpdateLeadStatus = async (id: string, status: string) => {
|
||||||
|
try {
|
||||||
|
await api.patch(`/admin/leads/${id}/status`, { status });
|
||||||
|
toast.success('وضعیت درخواست تماس بهروز شد.');
|
||||||
|
loadLeads();
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error('خطا در بهروزرسانی وضعیت');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 pb-12 font-vazir text-gray-800">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
|
||||||
|
<PhoneCall className="h-7 w-7 text-purple-600" />
|
||||||
|
درخواستهای تماس و مشاوران کاتالوگ
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
مدیریت لیدهای تماس وبسایت، انتساب مشاوران پیشفرض و اختصاصی محصولات
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button onClick={() => {
|
||||||
|
setEditingAdvisor(null);
|
||||||
|
setAdvisorForm({ name: '', phone: '', title: '', isDefault: false, isActive: true });
|
||||||
|
setIsAdvisorModalOpen(true);
|
||||||
|
}}>
|
||||||
|
<UserPlus className="h-4 w-4" />
|
||||||
|
افزودن مشاور جدید
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('leads')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'leads'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<PhoneCall className="h-4 w-4" />
|
||||||
|
درخواستهای تماس کاربران (Leads)
|
||||||
|
{leadStats.pending > 0 && (
|
||||||
|
<span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-700 font-bold">
|
||||||
|
{leadStats.pending} نیازمند تماس
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('advisors')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'advisors'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Users className="h-4 w-4" />
|
||||||
|
لیست مشاوران تخصصی
|
||||||
|
<span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 font-bold">
|
||||||
|
{advisors.length}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab: Leads */}
|
||||||
|
{activeTab === 'leads' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-gray-400">مجموع درخواستها</span>
|
||||||
|
<p className="mt-2 text-2xl font-black text-gray-900">{leadStats.total}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-amber-500">در انتظار تماس</span>
|
||||||
|
<p className="mt-2 text-2xl font-black text-amber-600">{leadStats.pending}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-emerald-500">تماس گرفته شده</span>
|
||||||
|
<p className="mt-2 text-2xl font-black text-emerald-600">{leadStats.contacted}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-gray-400">لغو شده / ناموفق</span>
|
||||||
|
<p className="mt-2 text-2xl font-black text-gray-600">{leadStats.cancelled}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-4">
|
||||||
|
<form onSubmit={handleSearch} className="flex gap-2 w-full sm:w-80">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="جستجو با نام یا شماره..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
/>
|
||||||
|
<Button type="submit" variant="outline" size="sm">
|
||||||
|
<Search className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{['ALL', 'PENDING', 'CONTACTED', 'CANCELLED'].map((st) => (
|
||||||
|
<button
|
||||||
|
key={st}
|
||||||
|
onClick={() => setLeadFilterStatus(st)}
|
||||||
|
className={`rounded-lg px-3 py-1.5 text-xs font-bold transition-all ${
|
||||||
|
leadFilterStatus === st
|
||||||
|
? 'bg-purple-600 text-white'
|
||||||
|
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{st === 'ALL' ? 'همه' : st === 'PENDING' ? 'در انتظار' : st === 'CONTACTED' ? 'تماس گرفته شده' : 'لغو'}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-right text-sm">
|
||||||
|
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
|
||||||
|
<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">عملیات</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{leads.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="py-8 text-center text-gray-400">
|
||||||
|
هیچ درخواست تماسی یافت نشد.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
leads.map((l) => (
|
||||||
|
<tr key={l.id} className="hover:bg-gray-50/50">
|
||||||
|
<td className="py-3.5 px-4 font-bold text-gray-900">
|
||||||
|
{l.firstName} {l.lastName}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono font-medium text-purple-700 dir-ltr text-right">
|
||||||
|
<a href={`tel:${l.phone}`} className="hover:underline">
|
||||||
|
{l.phone}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs text-gray-600">
|
||||||
|
{l.product ? l.product.nameFa : <span className="text-gray-400">مشاوره عمومی</span>}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs font-medium text-gray-700">
|
||||||
|
{l.advisor ? `${l.advisor.name} (${l.advisor.phone})` : <span className="text-gray-400">پیشفرض</span>}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs text-gray-400">
|
||||||
|
{new Date(l.createdAt).toLocaleDateString('fa-IR')} - {new Date(l.createdAt).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-bold ${
|
||||||
|
l.status === 'CONTACTED'
|
||||||
|
? 'bg-emerald-50 text-emerald-700'
|
||||||
|
: l.status === 'CANCELLED'
|
||||||
|
? 'bg-gray-100 text-gray-600'
|
||||||
|
: 'bg-amber-50 text-amber-700'
|
||||||
|
}`}>
|
||||||
|
{l.status === 'CONTACTED' ? 'تماس گرفته شد' : l.status === 'CANCELLED' ? 'لغو شده' : 'در انتظار تماس'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{l.status !== 'CONTACTED' && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleUpdateLeadStatus(l.id, 'CONTACTED')}
|
||||||
|
title="ثبت به عنوان تماس گرفته شده"
|
||||||
|
className="rounded p-1 text-emerald-600 hover:bg-emerald-50"
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{l.status !== 'CANCELLED' && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleUpdateLeadStatus(l.id, 'CANCELLED')}
|
||||||
|
title="لغو درخواست"
|
||||||
|
className="rounded p-1 text-gray-400 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab: Advisors */}
|
||||||
|
{activeTab === 'advisors' && (
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-right text-sm">
|
||||||
|
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
|
||||||
|
<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">وضعیت</th>
|
||||||
|
<th className="py-3 px-4">عملیات</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{advisors.map((adv) => (
|
||||||
|
<tr key={adv.id} className="hover:bg-gray-50/50">
|
||||||
|
<td className="py-3.5 px-4 font-bold text-gray-900">{adv.name}</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono font-medium text-gray-700">{adv.phone}</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs text-gray-500">{adv.title || '-'}</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs font-bold text-purple-600">{adv.productsCount} محصول</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs font-bold text-gray-700">{adv.leadsCount} درخواست</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
{adv.isDefault ? (
|
||||||
|
<span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2.5 py-0.5 text-xs font-bold text-amber-700">
|
||||||
|
<Star className="h-3 w-3 fill-amber-500 text-amber-500" />
|
||||||
|
پیشفرض سیستم
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => handleSetDefaultAdvisor(adv.id)}
|
||||||
|
className="text-xs text-gray-400 hover:text-purple-600 hover:underline"
|
||||||
|
>
|
||||||
|
تنظیم به عنوان پیشفرض
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
|
||||||
|
adv.isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
|
||||||
|
}`}>
|
||||||
|
{adv.isActive ? 'فعال' : 'غیرفعال'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setEditingAdvisor(adv);
|
||||||
|
setAdvisorForm({
|
||||||
|
name: adv.name,
|
||||||
|
phone: adv.phone,
|
||||||
|
title: adv.title || '',
|
||||||
|
isDefault: adv.isDefault,
|
||||||
|
isActive: adv.isActive,
|
||||||
|
});
|
||||||
|
setIsAdvisorModalOpen(true);
|
||||||
|
}}
|
||||||
|
className="rounded p-1 text-gray-500 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
<Edit2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteAdvisor(adv.id)}
|
||||||
|
className="rounded p-1 text-red-500 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Modal: Advisor Create/Edit */}
|
||||||
|
<Modal
|
||||||
|
isOpen={isAdvisorModalOpen}
|
||||||
|
onClose={() => setIsAdvisorModalOpen(false)}
|
||||||
|
title={editingAdvisor ? 'ویرایش مشاور' : 'افزودن مشاور جدید'}
|
||||||
|
>
|
||||||
|
<form onSubmit={handleSaveAdvisor} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">نام و نام خانوادگی مشاور</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={advisorForm.name}
|
||||||
|
onChange={(e) => setAdvisorForm({ ...advisorForm, name: e.target.value })}
|
||||||
|
placeholder="مثال: دکتر مهدی صابری"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">شماره تلفن همراه</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
dir="ltr"
|
||||||
|
value={advisorForm.phone}
|
||||||
|
onChange={(e) => setAdvisorForm({ ...advisorForm, phone: e.target.value })}
|
||||||
|
placeholder="09121234567"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">عنوان تخصصی یا سمت</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={advisorForm.title}
|
||||||
|
onChange={(e) => setAdvisorForm({ ...advisorForm, title: e.target.value })}
|
||||||
|
placeholder="مثال: کارشناس تغذیه سگ و گربه"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-6 pt-2">
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={advisorForm.isDefault}
|
||||||
|
onChange={(e) => setAdvisorForm({ ...advisorForm, isDefault: e.target.checked })}
|
||||||
|
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-xs font-bold text-gray-700">مشاور پیشفرض سیستم</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={advisorForm.isActive}
|
||||||
|
onChange={(e) => setAdvisorForm({ ...advisorForm, isActive: e.target.checked })}
|
||||||
|
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-xs font-bold text-gray-700">مشاور فعال</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-4 border-t border-gray-100">
|
||||||
|
<Button variant="outline" type="button" onClick={() => setIsAdvisorModalOpen(false)}>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
<Button type="submit">
|
||||||
|
ذخیره
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -214,4 +214,20 @@ describe('FAQManager Component', () => {
|
|||||||
expect(toast.success).toHaveBeenCalledWith('سوال حذف شد');
|
expect(toast.success).toHaveBeenCalledWith('سوال حذف شد');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('filters FAQs by search term', async () => {
|
||||||
|
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||||
|
render(<FAQManager />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('سوال اول تست')).toBeTruthy();
|
||||||
|
expect(screen.getByText('سوال دوم تست')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
const searchInput = screen.getByPlaceholderText('جستجو در متن سوال یا پاسخ متداول...');
|
||||||
|
fireEvent.change(searchInput, { target: { value: 'سوال اول' } });
|
||||||
|
|
||||||
|
expect(screen.getByText('سوال اول تست')).toBeTruthy();
|
||||||
|
expect(screen.queryByText('سوال دوم تست')).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Edit2,HelpCircle,Plus,ToggleLeft,ToggleRight,Trash2 } from 'lucide-react';
|
import { Edit2,HelpCircle,Plus,ToggleLeft,ToggleRight,Trash2,Search } from 'lucide-react';
|
||||||
import { useCallback,useEffect,useState } from 'react';
|
import { useCallback,useEffect,useState } from 'react';
|
||||||
import { toast } from 'react-hot-toast';
|
import { toast } from 'react-hot-toast';
|
||||||
import Button from '../components/ui/Button';
|
import Button from '../components/ui/Button';
|
||||||
@@ -20,6 +20,7 @@ interface FAQ {
|
|||||||
|
|
||||||
export default function FAQManager() {
|
export default function FAQManager() {
|
||||||
const [faqs, setFaqs] = useState<FAQ[]>([]);
|
const [faqs, setFaqs] = useState<FAQ[]>([]);
|
||||||
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
const [editingFaq, setEditingFaq] = useState<FAQ | null>(null);
|
const [editingFaq, setEditingFaq] = useState<FAQ | null>(null);
|
||||||
@@ -120,6 +121,13 @@ export default function FAQManager() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const filteredFaqs = faqs.filter(
|
||||||
|
(f) =>
|
||||||
|
!searchTerm.trim() ||
|
||||||
|
f.question.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||||
|
f.answer.toLowerCase().includes(searchTerm.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||||
@@ -142,30 +150,45 @@ export default function FAQManager() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Info Box */}
|
{/* Info Box & Search Filter */}
|
||||||
<div className="bg-orange-50 border border-orange-200 rounded-xl p-4 text-sm text-orange-800">
|
<div className="bg-orange-50 border border-orange-200 rounded-xl p-4 text-sm text-orange-800">
|
||||||
<strong>💡 نکته SEO:</strong> سوالات فعال به صورت خودکار با markup <code className="bg-orange-100 px-1 rounded">FAQPage</code> در صفحه اصلی نمایش داده میشوند و در نتایج گوگل به عنوان Rich Snippet ظاهر میشوند.
|
<strong>💡 نکته SEO:</strong> سوالات فعال به صورت خودکار با markup <code className="bg-orange-100 px-1 rounded">FAQPage</code> در صفحه اصلی نمایش داده میشوند و در نتایج گوگل به عنوان Rich Snippet ظاهر میشوند.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="w-5 h-5 text-gray-400 absolute right-3.5 top-3 pointer-events-none" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="جستجو در متن سوال یا پاسخ متداول..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="w-full pl-4 pr-11 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:border-orange-500 focus:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* List */}
|
{/* List */}
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<div className="flex justify-center py-12">
|
<div className="flex justify-center py-12">
|
||||||
<Spinner size="lg" className="text-purple-600" />
|
<Spinner size="lg" className="text-purple-600" />
|
||||||
</div>
|
</div>
|
||||||
) : faqs.length === 0 ? (
|
) : filteredFaqs.length === 0 ? (
|
||||||
<div className="bg-white rounded-2xl border border-gray-200 py-16 text-center">
|
<div className="bg-white rounded-2xl border border-gray-200 py-16 text-center">
|
||||||
<HelpCircle className="w-12 h-12 text-gray-300 mx-auto mb-3" />
|
<HelpCircle className="w-12 h-12 text-gray-300 mx-auto mb-3" />
|
||||||
<p className="text-gray-500 font-medium">هیچ سوالی ثبت نشده است</p>
|
<p className="text-gray-500 font-medium">
|
||||||
<button
|
{searchTerm ? 'هیچ سوالی با این عبارت یافت نشد' : 'هیچ سوالی ثبت نشده است'}
|
||||||
onClick={() => openModal()}
|
</p>
|
||||||
className="mt-4 text-purple-600 font-bold hover:underline text-sm cursor-pointer"
|
{!searchTerm && (
|
||||||
>
|
<button
|
||||||
اولین سوال را اضافه کنید
|
onClick={() => openModal()}
|
||||||
</button>
|
className="mt-4 text-purple-600 font-bold hover:underline text-sm cursor-pointer"
|
||||||
|
>
|
||||||
|
اولین سوال را اضافه کنید
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
faqs.map((faq) => (
|
filteredFaqs.map((faq) => (
|
||||||
<div
|
<div
|
||||||
key={faq.id}
|
key={faq.id}
|
||||||
className={`bg-white rounded-2xl border p-5 transition-all ${
|
className={`bg-white rounded-2xl border p-5 transition-all ${
|
||||||
|
|||||||
@@ -0,0 +1,725 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
Bell,
|
||||||
|
Mail,
|
||||||
|
MessageSquare,
|
||||||
|
Server,
|
||||||
|
Send,
|
||||||
|
ListFilter,
|
||||||
|
RefreshCw,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertCircle,
|
||||||
|
Clock,
|
||||||
|
ShieldCheck,
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
|
ExternalLink,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
import Button from '../components/ui/Button';
|
||||||
|
import Spinner from '../components/ui/Spinner';
|
||||||
|
import api from '../services/api';
|
||||||
|
|
||||||
|
interface EmailConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
secure: boolean;
|
||||||
|
user: string;
|
||||||
|
password?: string;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface QueueItem {
|
||||||
|
id: string;
|
||||||
|
channel: 'SMS' | 'EMAIL';
|
||||||
|
recipient: string;
|
||||||
|
event: string;
|
||||||
|
subject?: string;
|
||||||
|
content: string;
|
||||||
|
status: 'QUEUED' | 'PROCESSING' | 'SENT' | 'FAILED';
|
||||||
|
attempts: number;
|
||||||
|
maxAttempts: number;
|
||||||
|
lastError?: string;
|
||||||
|
sentAt?: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NotificationTemplate {
|
||||||
|
id: string;
|
||||||
|
channel: 'SMS' | 'EMAIL';
|
||||||
|
event: string;
|
||||||
|
name: string;
|
||||||
|
subject?: string;
|
||||||
|
body: string;
|
||||||
|
recipientType: string;
|
||||||
|
isActive: boolean;
|
||||||
|
variables: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function NotificationsSettingsPage() {
|
||||||
|
const [activeTab, setActiveTab] = useState<'overview' | 'email' | 'templates' | 'manual' | 'queue'>('overview');
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
|
// Email Config State
|
||||||
|
const [emailConfig, setEmailConfig] = useState<EmailConfig>({
|
||||||
|
enabled: true,
|
||||||
|
host: 'mail.parsaaghayi.ir',
|
||||||
|
port: 465,
|
||||||
|
secure: true,
|
||||||
|
user: '',
|
||||||
|
password: '',
|
||||||
|
fromName: 'کنینا ایران',
|
||||||
|
fromEmail: 'info@canina.ir',
|
||||||
|
});
|
||||||
|
const [isSavingEmail, setIsSavingEmail] = useState(false);
|
||||||
|
const [isTestingSmtp, setIsTestingSmtp] = useState(false);
|
||||||
|
const [smtpStatus, setSmtpStatus] = useState<{ checked: boolean; success: boolean; message: string } | null>(null);
|
||||||
|
|
||||||
|
// Queue state
|
||||||
|
const [queueItems, setQueueItems] = useState<QueueItem[]>([]);
|
||||||
|
const [queueStats, setQueueStats] = useState({ total: 0, queued: 0, sent: 0, failed: 0, successRate: 100 });
|
||||||
|
const [isLoadingQueue, setIsLoadingQueue] = useState(false);
|
||||||
|
|
||||||
|
// Templates state
|
||||||
|
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
|
||||||
|
const [eventsList, setEventsList] = useState<{ event: string; name: string; variables: string[] }[]>([]);
|
||||||
|
|
||||||
|
// Manual Send State
|
||||||
|
const [manualForm, setManualForm] = useState({
|
||||||
|
channel: 'SMS' as 'SMS' | 'EMAIL',
|
||||||
|
targetType: 'single' as 'single' | 'all_users' | 'custom_list',
|
||||||
|
recipient: '',
|
||||||
|
subject: '',
|
||||||
|
content: '',
|
||||||
|
});
|
||||||
|
const [isSendingManual, setIsSendingManual] = useState(false);
|
||||||
|
|
||||||
|
// Load Initial Config
|
||||||
|
const loadConfig = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const res = await api.get('/admin/notifications/config');
|
||||||
|
if (res.data?.success) {
|
||||||
|
setEmailConfig(res.data.data.email);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
toast.error('خطا در دریافت تنظیمات اطلاعرسانی');
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadQueue = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoadingQueue(true);
|
||||||
|
const res = await api.get('/admin/notifications/queue?limit=50');
|
||||||
|
if (res.data?.success) {
|
||||||
|
setQueueItems(res.data.data.items);
|
||||||
|
if (res.data.data.stats) setQueueStats(res.data.data.stats);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingQueue(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadTemplates = async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get('/admin/notifications/templates');
|
||||||
|
if (res.data?.success) {
|
||||||
|
setTemplates(res.data.data.templates);
|
||||||
|
setEventsList(res.data.data.events || []);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadConfig();
|
||||||
|
loadQueue();
|
||||||
|
loadTemplates();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSaveEmail = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
try {
|
||||||
|
setIsSavingEmail(true);
|
||||||
|
const res = await api.put('/admin/notifications/email-config', emailConfig);
|
||||||
|
if (res.data?.success) {
|
||||||
|
toast.success(res.data.message || 'تنظیمات سرور ایمیل ذخیره شد.');
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err?.response?.data?.message || 'خطا در ذخیره تنظیمات ایمیل');
|
||||||
|
} finally {
|
||||||
|
setIsSavingEmail(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTestSmtp = async () => {
|
||||||
|
try {
|
||||||
|
setIsTestingSmtp(true);
|
||||||
|
setSmtpStatus(null);
|
||||||
|
const res = await api.post('/admin/notifications/test-smtp', emailConfig);
|
||||||
|
setSmtpStatus({
|
||||||
|
checked: true,
|
||||||
|
success: res.data?.success,
|
||||||
|
message: res.data?.message,
|
||||||
|
});
|
||||||
|
if (res.data?.success) {
|
||||||
|
toast.success('اتصال به سرور SMTP با موفقیت برقرار شد.');
|
||||||
|
} else {
|
||||||
|
toast.error(res.data?.message || 'خطا در اتصال به سرور SMTP');
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err?.response?.data?.message || 'خطا در تست اتصال سرور';
|
||||||
|
setSmtpStatus({ checked: true, success: false, message: msg });
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setIsTestingSmtp(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleManualSend = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!manualForm.content.trim()) {
|
||||||
|
toast.error('متن پیام الزامی است.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
setIsSendingManual(true);
|
||||||
|
const res = await api.post('/admin/notifications/manual-send', manualForm);
|
||||||
|
if (res.data?.success) {
|
||||||
|
toast.success(res.data.message || 'پیام با موفقیت در صف ارسال قرار گرفت.');
|
||||||
|
setManualForm({ ...manualForm, recipient: '', subject: '', content: '' });
|
||||||
|
loadQueue();
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err?.response?.data?.message || 'خطا در ثبت پیام در صف');
|
||||||
|
} finally {
|
||||||
|
setIsSendingManual(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRetryQueue = async (id: string) => {
|
||||||
|
try {
|
||||||
|
const res = await api.post(`/admin/notifications/queue/${id}/retry`);
|
||||||
|
if (res.data?.success) {
|
||||||
|
toast.success('پیام مجدداً در صف قرار گرفت.');
|
||||||
|
loadQueue();
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error('خطا در ارسال مجدد');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-96 items-center justify-center">
|
||||||
|
<Spinner size="lg" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 pb-12 font-vazir text-gray-800">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
|
||||||
|
<Bell className="h-7 w-7 text-purple-600" />
|
||||||
|
مرکز مدیریت اطلاعرسانی و پیامها
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
پیکربندی یکپارچه ایمیل (SMTP)، سامانه پیامک، صف ارسال پایدار و رویدادهای خودکار
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('overview')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'overview'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Server className="h-4 w-4" />
|
||||||
|
داشبورد و وضعیت
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('email')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'email'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Mail className="h-4 w-4" />
|
||||||
|
تنظیمات ایمیل (SMTP)
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('templates')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'templates'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<ListFilter className="h-4 w-4" />
|
||||||
|
قالبهای رویدادها
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('manual')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'manual'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Send className="h-4 w-4" />
|
||||||
|
ارسال دستی هدفمند
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('queue')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'queue'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Clock className="h-4 w-4" />
|
||||||
|
صف ارسال و لاگها
|
||||||
|
{queueStats.failed > 0 && (
|
||||||
|
<span className="rounded-full bg-red-100 px-2 py-0.5 text-xs text-red-600 font-bold">
|
||||||
|
{queueStats.failed} خطا
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab: Overview */}
|
||||||
|
{activeTab === 'overview' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-gray-400">مجموع پیامهای صف</span>
|
||||||
|
<p className="mt-2 text-3xl font-black text-gray-900">{queueStats.total}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-emerald-500">ارسال موفق</span>
|
||||||
|
<p className="mt-2 text-3xl font-black text-emerald-600">{queueStats.sent}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-amber-500">در حال پردازش / صف</span>
|
||||||
|
<p className="mt-2 text-3xl font-black text-amber-600">{queueStats.queued}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<span className="text-xs font-bold text-red-500">ناموفق با تلاش مجدد</span>
|
||||||
|
<p className="mt-2 text-3xl font-black text-red-600">{queueStats.failed}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="rounded-xl bg-purple-50 p-3 text-purple-600">
|
||||||
|
<Mail className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold text-gray-900">سرویس ایمیل سازمانی</h3>
|
||||||
|
<p className="text-xs text-gray-400">پروتکل SMTP / TLS اختصاصی</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-bold ${
|
||||||
|
emailConfig.enabled ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
|
||||||
|
}`}>
|
||||||
|
{emailConfig.enabled ? 'فعال' : 'غیرفعال'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 space-y-2 text-sm text-gray-600">
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>سرور میزبان:</span>
|
||||||
|
<span className="font-mono text-gray-900 font-medium">{emailConfig.host || '-'}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>پورت اتصال:</span>
|
||||||
|
<span className="font-mono text-gray-900 font-medium">{emailConfig.port}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>فرستنده پیشفرض:</span>
|
||||||
|
<span className="font-mono text-gray-900 font-medium">{emailConfig.fromEmail}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="rounded-xl bg-violet-50 p-3 text-violet-600">
|
||||||
|
<MessageSquare className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold text-gray-900">درگاه پیامک (MeliPayamak)</h3>
|
||||||
|
<p className="text-xs text-gray-400">ارسال خدماتی با الگوهای تایید شده</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="inline-flex rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-bold text-emerald-700">
|
||||||
|
متصل
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 space-y-2 text-sm text-gray-600">
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>وضعیت اتصال:</span>
|
||||||
|
<span className="text-emerald-600 font-bold">برقرار</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>قالبهای پیامک:</span>
|
||||||
|
<a href="/settings/sms" className="flex items-center gap-1 text-purple-600 hover:underline">
|
||||||
|
مشاهده تنظیمات پیشرفته ملیپیامک
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab: Email SMTP */}
|
||||||
|
{activeTab === 'email' && (
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<form onSubmit={handleSaveEmail} className="space-y-6 max-w-3xl">
|
||||||
|
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-bold text-gray-900">پیکربندی سرور ارسال ایمیل (SMTP)</h3>
|
||||||
|
<p className="text-xs text-gray-500">مشخصات سرور میل اختصاصی خود را وارد نمایید</p>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={emailConfig.enabled}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, enabled: e.target.checked })}
|
||||||
|
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-bold text-gray-700">فعالسازی ارسال ایمیل</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">هاست سرور SMTP</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
dir="ltr"
|
||||||
|
value={emailConfig.host}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, host: e.target.value })}
|
||||||
|
placeholder="mail.canina.ir"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">پورت اتصال</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
dir="ltr"
|
||||||
|
value={emailConfig.port}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, port: Number(e.target.value) })}
|
||||||
|
placeholder="587 یا 465"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام کاربری (ایمیل ورود)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
dir="ltr"
|
||||||
|
value={emailConfig.user}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, user: e.target.value })}
|
||||||
|
placeholder="info@canina.ir"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">رمز عبور ایمیل</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
dir="ltr"
|
||||||
|
value={emailConfig.password}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, password: e.target.value })}
|
||||||
|
placeholder="••••••••"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام فرستنده (Sender Name)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={emailConfig.fromName}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, fromName: e.target.value })}
|
||||||
|
placeholder="کنینا ایران"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">آدرس ایمیل فرستنده (From Address)</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
dir="ltr"
|
||||||
|
value={emailConfig.fromEmail}
|
||||||
|
onChange={(e) => setEmailConfig({ ...emailConfig, fromEmail: e.target.value })}
|
||||||
|
placeholder="info@canina.ir"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Test result status */}
|
||||||
|
{smtpStatus && (
|
||||||
|
<div className={`flex items-center gap-3 rounded-xl p-4 text-sm ${
|
||||||
|
smtpStatus.success ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'
|
||||||
|
}`}>
|
||||||
|
{smtpStatus.success ? <CheckCircle2 className="h-5 w-5 shrink-0" /> : <AlertCircle className="h-5 w-5 shrink-0" />}
|
||||||
|
<span>{smtpStatus.message}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 pt-4 border-t border-gray-100">
|
||||||
|
<Button type="submit" disabled={isSavingEmail}>
|
||||||
|
{isSavingEmail ? <Spinner size="sm" /> : 'ذخیره تنظیمات'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleTestSmtp}
|
||||||
|
disabled={isTestingSmtp}
|
||||||
|
>
|
||||||
|
{isTestingSmtp ? <Spinner size="sm" /> : 'تست اتصال به سرور (SMTP Test)'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab: Templates */}
|
||||||
|
{activeTab === 'templates' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 mb-4">قالبهای خودکار سیستم بر اساس رویداد</h3>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-right text-sm">
|
||||||
|
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
|
||||||
|
<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>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{eventsList.map((ev) => (
|
||||||
|
<tr key={ev.event} className="hover:bg-gray-50/50">
|
||||||
|
<td className="py-3.5 px-4 font-bold text-gray-900">{ev.name}</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className="rounded-md bg-purple-50 px-2 py-1 text-xs font-bold text-purple-700">
|
||||||
|
SMS & EMAIL
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-gray-600 font-mono text-xs">{ev.event}</td>
|
||||||
|
<td className="py-3.5 px-4 text-gray-600">کاربر / مشتری</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs font-mono text-gray-400">
|
||||||
|
{ev.variables.join(', ')}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className="inline-flex items-center gap-1 text-xs text-emerald-600 font-bold">
|
||||||
|
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||||
|
فعال
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab: Manual Send */}
|
||||||
|
{activeTab === 'manual' && (
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm max-w-2xl">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 mb-2">ارسال دستی و هدفمند پیام</h3>
|
||||||
|
<p className="text-xs text-gray-500 mb-6">پیامک یا ایمیل دلخواه خود را به یک کاربر یا گروههای مشخص ارسال کنید</p>
|
||||||
|
|
||||||
|
<form onSubmit={handleManualSend} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">کانال ارسال</label>
|
||||||
|
<div className="flex gap-4">
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="channel"
|
||||||
|
checked={manualForm.channel === 'SMS'}
|
||||||
|
onChange={() => setManualForm({ ...manualForm, channel: 'SMS' })}
|
||||||
|
className="text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium">پیامک (SMS)</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="channel"
|
||||||
|
checked={manualForm.channel === 'EMAIL'}
|
||||||
|
onChange={() => setManualForm({ ...manualForm, channel: 'EMAIL' })}
|
||||||
|
className="text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium">ایمیل (Email)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">
|
||||||
|
{manualForm.channel === 'SMS' ? 'شماره موبایل گیرنده' : 'آدرس ایمیل گیرنده'}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
dir="ltr"
|
||||||
|
value={manualForm.recipient}
|
||||||
|
onChange={(e) => setManualForm({ ...manualForm, recipient: e.target.value })}
|
||||||
|
placeholder={manualForm.channel === 'SMS' ? '09121234567' : 'user@example.com'}
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm font-mono focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{manualForm.channel === 'EMAIL' && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">موضوع ایمیل</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={manualForm.subject}
|
||||||
|
onChange={(e) => setManualForm({ ...manualForm, subject: e.target.value })}
|
||||||
|
placeholder="موضوع اطلاعیه..."
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">متن پیام</label>
|
||||||
|
<textarea
|
||||||
|
rows={4}
|
||||||
|
value={manualForm.content}
|
||||||
|
onChange={(e) => setManualForm({ ...manualForm, content: e.target.value })}
|
||||||
|
placeholder="متن پیام خود را اینجا بنویسید..."
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button type="submit" disabled={isSendingManual}>
|
||||||
|
{isSendingManual ? <Spinner size="sm" /> : 'ثبت در صف ارسال'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab: Queue & Logs */}
|
||||||
|
{activeTab === 'queue' && (
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900">صف پردازش پایدار نوتیفیکیشنها</h3>
|
||||||
|
<Button variant="outline" size="sm" onClick={loadQueue} disabled={isLoadingQueue}>
|
||||||
|
<RefreshCw className={`h-4 w-4 ${isLoadingQueue ? 'animate-spin' : ''}`} />
|
||||||
|
بهروزرسانی صف
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-right text-sm">
|
||||||
|
<thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase">
|
||||||
|
<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">عملیات</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{queueItems.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="py-8 text-center text-gray-400">
|
||||||
|
هیچ پیامی در صف وجود ندارد.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
queueItems.map((item) => (
|
||||||
|
<tr key={item.id} className="hover:bg-gray-50/50">
|
||||||
|
<td className="py-3.5 px-4 font-mono font-medium text-gray-900">{item.recipient}</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className={`rounded-md px-2 py-0.5 text-xs font-bold ${
|
||||||
|
item.channel === 'EMAIL' ? 'bg-blue-50 text-blue-700' : 'bg-violet-50 text-violet-700'
|
||||||
|
}`}>
|
||||||
|
{item.channel}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs font-mono text-gray-600">{item.event}</td>
|
||||||
|
<td className="py-3.5 px-4 font-mono text-xs">{item.attempts} / {item.maxAttempts}</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-bold ${
|
||||||
|
item.status === 'SENT'
|
||||||
|
? 'bg-emerald-50 text-emerald-700'
|
||||||
|
: item.status === 'FAILED'
|
||||||
|
? 'bg-red-50 text-red-700'
|
||||||
|
: 'bg-amber-50 text-amber-700'
|
||||||
|
}`}>
|
||||||
|
{item.status === 'SENT' ? 'ارسال شده' : item.status === 'FAILED' ? 'ناموفق' : 'در صف'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4 text-xs text-gray-400">
|
||||||
|
{new Date(item.createdAt).toLocaleTimeString('fa-IR')}
|
||||||
|
</td>
|
||||||
|
<td className="py-3.5 px-4">
|
||||||
|
{item.status === 'FAILED' && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleRetryQueue(item.id)}
|
||||||
|
className="text-xs text-purple-600 hover:underline font-bold"
|
||||||
|
>
|
||||||
|
تلاش مجدد
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
import {
|
import {
|
||||||
Building2,
|
Bell,
|
||||||
ChevronLeft,
|
Building2,
|
||||||
CreditCard,
|
ChevronLeft,
|
||||||
DollarSign,
|
CreditCard,
|
||||||
Globe,
|
DollarSign,
|
||||||
MessageSquare,
|
Globe,
|
||||||
Palette,
|
MessageSquare,
|
||||||
Save,
|
Palette,
|
||||||
|
PhoneCall,
|
||||||
|
Save,
|
||||||
Settings as SettingsIcon,
|
Settings as SettingsIcon,
|
||||||
Share2,
|
Share2,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
@@ -114,6 +116,9 @@ export default function Settings() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const SETTING_MODULES = [
|
const SETTING_MODULES = [
|
||||||
|
{ title: 'مرکز اطلاعرسانی و ایمیل', desc: 'پیکربندی سرور SMTP، صف ارسال پیامک و ایمیل و قالبهای خودکار', path: '/settings/notifications', icon: Bell, color: 'from-fuchsia-600 to-purple-800', badge: 'جدید' },
|
||||||
|
{ title: 'مشاوران تخصصی و لیدها', desc: 'مدیریت مشاوران کاتالوگ و پیگیری درخواستهای تماس کاربران', path: '/advisors', icon: PhoneCall, color: 'from-blue-600 to-indigo-800', badge: 'جدید' },
|
||||||
|
{ title: 'پشتیبان هوشمند سایت', desc: 'فعالسازی، ارائهدهنده و مدل، نام دکمه و آیکون دستیار', path: '/settings/smart-chat', icon: MessageSquare, color: 'from-purple-600 to-purple-800', badge: 'هوشمند' },
|
||||||
{
|
{
|
||||||
title: 'روشهای پرداخت و زیبال',
|
title: 'روشهای پرداخت و زیبال',
|
||||||
desc: 'درگاه آنلاین شتاب، کیف پول کنینا، کارت به کارت و پرداخت در محل',
|
desc: 'درگاه آنلاین شتاب، کیف پول کنینا، کارت به کارت و پرداخت در محل',
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import React from 'react';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import SmartChatSettingsPage from './SmartChatSettingsPage';
|
||||||
|
import api from '../services/api';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
|
||||||
|
vi.mock('../services/api', () => ({
|
||||||
|
default: {
|
||||||
|
get: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('react-hot-toast', () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('react-router-dom', () => ({
|
||||||
|
Link: ({ children, to, className }: any) => <a href={to} className={className}>{children}</a>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('SmartChatSettingsPage Component', () => {
|
||||||
|
const mockSettings = {
|
||||||
|
enabled: true,
|
||||||
|
provider: 'configured-test-1234',
|
||||||
|
model: 'gpt-test-model',
|
||||||
|
label: 'گفتگو با پشتیبان',
|
||||||
|
icon: 'chat',
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockCatalog = {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
id: 'configured-test-1234',
|
||||||
|
label: 'ارائهدهنده کنینا',
|
||||||
|
models: ['gpt-test-model', 'claude-test-model'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockStats = {
|
||||||
|
conversations: 5,
|
||||||
|
messages: 12,
|
||||||
|
authenticated: 3,
|
||||||
|
anonymous: 2,
|
||||||
|
unanswered: 0,
|
||||||
|
followup: 1,
|
||||||
|
escalated: 0,
|
||||||
|
topics: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockConversations = {
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: 'conv-1',
|
||||||
|
createdAt: '2026-11-07T10:00:00.000Z',
|
||||||
|
updatedAt: '2026-11-07T10:05:00.000Z',
|
||||||
|
unanswered: false,
|
||||||
|
needsFollowup: false,
|
||||||
|
escalationSignal: false,
|
||||||
|
user: { firstName: 'پارسا', lastName: 'آقایی', mobile: '09211231517' },
|
||||||
|
messages: [
|
||||||
|
{ role: 'user', content: 'سلام، مکمل مفاصل موجود دارید؟', createdAt: '2026-11-07T10:00:00.000Z' },
|
||||||
|
{ role: 'assistant', content: 'بله Canhydrox GAG موجود است.', createdAt: '2026-11-07T10:01:00.000Z' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(api.get).mockImplementation(async (url: string) => {
|
||||||
|
if (url === '/support-chat/settings') return { data: { data: mockSettings } };
|
||||||
|
if (url === '/support-chat/catalog') return { data: { data: mockCatalog } };
|
||||||
|
if (url === '/admin/support-chat/stats') return { data: { data: mockStats } };
|
||||||
|
if (url === '/admin/support-chat/conversations') return { data: { data: mockConversations } };
|
||||||
|
return { data: {} };
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders settings tab and loads config correctly', async () => {
|
||||||
|
render(<SmartChatSettingsPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('پشتیبان هوشمند سایت (Smart Support Chat)')).toBeTruthy();
|
||||||
|
expect(screen.getByLabelText('نام دکمه و دستیار')).toHaveValue('گفتگو با پشتیبان');
|
||||||
|
expect(screen.getByLabelText('ارائهدهنده')).toHaveValue('configured-test-1234');
|
||||||
|
expect(screen.getByLabelText('مدل')).toHaveValue('gpt-test-model');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows saving updated settings', async () => {
|
||||||
|
vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } });
|
||||||
|
|
||||||
|
render(<SmartChatSettingsPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByLabelText('نام دکمه و دستیار')).toHaveValue('گفتگو با پشتیبان');
|
||||||
|
});
|
||||||
|
|
||||||
|
const labelInput = screen.getByLabelText('نام دکمه و دستیار');
|
||||||
|
fireEvent.change(labelInput, { target: { value: 'پشتیبان آنلاین ۲۴ ساعته' } });
|
||||||
|
|
||||||
|
const submitBtn = screen.getByRole('button', { name: 'ذخیره تنظیمات' });
|
||||||
|
fireEvent.click(submitBtn);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(api.put).toHaveBeenCalledWith(
|
||||||
|
'/support-chat/settings',
|
||||||
|
expect.objectContaining({
|
||||||
|
label: 'پشتیبان آنلاین ۲۴ ساعته',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(toast.success).toHaveBeenCalledWith('تنظیمات پشتیبان هوشمند سایت با موفقیت ذخیره شد.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('switches to analytics tab and displays stats and conversations', async () => {
|
||||||
|
render(<SmartChatSettingsPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('تحلیل و تاریخچه مکالمات')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
const analyticsTabBtn = screen.getByText('تحلیل و تاریخچه مکالمات');
|
||||||
|
fireEvent.click(analyticsTabBtn);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('گفتگوها')).toBeTruthy();
|
||||||
|
expect(screen.getByText('5')).toBeTruthy();
|
||||||
|
expect(screen.getByText('سلام، مکمل مفاصل موجود دارید؟')).toBeTruthy();
|
||||||
|
expect(screen.getByText('بله Canhydrox GAG موجود است.')).toBeTruthy();
|
||||||
|
expect(screen.getByText('پارسا آقایی')).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,539 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
MessageSquare,
|
||||||
|
Bot,
|
||||||
|
Settings,
|
||||||
|
BarChart3,
|
||||||
|
RefreshCw,
|
||||||
|
Sliders,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertCircle,
|
||||||
|
HelpCircle,
|
||||||
|
ShieldCheck,
|
||||||
|
Save,
|
||||||
|
Clock,
|
||||||
|
Sparkles,
|
||||||
|
ArrowRight,
|
||||||
|
ExternalLink,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { toast } from 'react-hot-toast';
|
||||||
|
import api from '../services/api';
|
||||||
|
import Button from '../components/ui/Button';
|
||||||
|
import Spinner from '../components/ui/Spinner';
|
||||||
|
|
||||||
|
type SettingsState = {
|
||||||
|
enabled: boolean;
|
||||||
|
provider: string;
|
||||||
|
model: string;
|
||||||
|
label: string;
|
||||||
|
icon: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Provider = {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
models: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
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 SmartChatSettingsPage() {
|
||||||
|
const [activeTab, setActiveTab] = useState<'config' | 'analytics'>('config');
|
||||||
|
|
||||||
|
// Config State
|
||||||
|
const [settings, setSettings] = useState<SettingsState | null>(null);
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([]);
|
||||||
|
const [isConfigLoading, setIsConfigLoading] = useState(true);
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
const [configError, setConfigError] = useState('');
|
||||||
|
|
||||||
|
// Analytics State
|
||||||
|
const [stats, setStats] = useState<Stats | null>(null);
|
||||||
|
const [conversations, setConversations] = useState<Conversation[]>([]);
|
||||||
|
const [isAnalyticsLoading, setIsAnalyticsLoading] = useState(false);
|
||||||
|
const [analyticsError, setAnalyticsError] = useState('');
|
||||||
|
const [dates, setDates] = useState({ startDate: '', endDate: '' });
|
||||||
|
|
||||||
|
// Load config & catalog
|
||||||
|
const loadConfig = async () => {
|
||||||
|
setIsConfigLoading(true);
|
||||||
|
setConfigError('');
|
||||||
|
try {
|
||||||
|
const [sRes, cRes] = await Promise.allSettled([
|
||||||
|
api.get('/support-chat/settings'),
|
||||||
|
api.get('/support-chat/catalog'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (sRes.status === 'fulfilled') {
|
||||||
|
setSettings(unwrap(sRes.value));
|
||||||
|
} else {
|
||||||
|
setConfigError('تنظیمات ذخیرهشده دریافت نشد. لطفاً تنظیمات جدید ایجاد و ثبت نمایید.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cRes.status === 'fulfilled') {
|
||||||
|
const cat = unwrap(cRes.value);
|
||||||
|
setProviders(cat.providers || []);
|
||||||
|
} else {
|
||||||
|
setProviders([]);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setConfigError('خطا در برقراری ارتباط با سامانه پشتیبان هوشمند.');
|
||||||
|
} finally {
|
||||||
|
setIsConfigLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Load analytics
|
||||||
|
const loadAnalytics = async () => {
|
||||||
|
setIsAnalyticsLoading(true);
|
||||||
|
setAnalyticsError('');
|
||||||
|
try {
|
||||||
|
const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v));
|
||||||
|
const [sRes, cRes] = await Promise.all([
|
||||||
|
api.get('/admin/support-chat/stats', { params }),
|
||||||
|
api.get('/admin/support-chat/conversations', { params: { ...params, page: 1, limit: 50 } }),
|
||||||
|
]);
|
||||||
|
setStats(unwrap(sRes));
|
||||||
|
setConversations(unwrap(cRes).data || []);
|
||||||
|
} catch {
|
||||||
|
setAnalyticsError('گزارش تحلیلی مکالمات پشتیبان بارگذاری نشد.');
|
||||||
|
} finally {
|
||||||
|
setIsAnalyticsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadConfig();
|
||||||
|
loadAnalytics();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSave = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!settings) return;
|
||||||
|
setIsSaving(true);
|
||||||
|
try {
|
||||||
|
await api.put('/support-chat/settings', settings);
|
||||||
|
const saved = unwrap(await api.get('/support-chat/settings'));
|
||||||
|
setSettings(saved);
|
||||||
|
setConfigError('');
|
||||||
|
toast.success('تنظیمات پشتیبان هوشمند سایت با موفقیت ذخیره شد.');
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err?.response?.data?.message || 'ذخیره تنظیمات انجام نشد؛ ارائهدهنده و مدل را بررسی نمایید.';
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const icons: Record<string, string> = {
|
||||||
|
chat: '💬',
|
||||||
|
paw: '🐾',
|
||||||
|
bot: '🤖',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 pb-12 font-vazir text-gray-800" dir="rtl">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 text-xs text-gray-400 mb-1">
|
||||||
|
<Link to="/settings" className="hover:text-purple-600 transition">تنظیمات فروشگاه</Link>
|
||||||
|
<span>/</span>
|
||||||
|
<span className="text-gray-600 font-bold">پشتیبان هوشمند سایت</span>
|
||||||
|
</div>
|
||||||
|
<h1 className="flex items-center gap-2.5 text-2xl font-black text-gray-900">
|
||||||
|
<Bot className="h-7 w-7 text-purple-600" />
|
||||||
|
پشتیبان هوشمند سایت (Smart Support Chat)
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
پیکربندی هوش مصنوعی دستیار مشتری، مدل زبانی، کلید شناور سایت و تحلیل مکالمات کاربران
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
loadConfig();
|
||||||
|
loadAnalytics();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-4 w-4" />
|
||||||
|
بروزرسانی وضعیت
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex border-b border-gray-200 bg-white px-4 rounded-xl shadow-sm">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('config')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'config'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Sliders className="h-4 w-4" />
|
||||||
|
تنظیمات و پیکربندی دستیار
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('analytics')}
|
||||||
|
className={`flex items-center gap-2 py-4 px-4 font-bold text-sm border-b-2 transition-all ${
|
||||||
|
activeTab === 'analytics'
|
||||||
|
? 'border-purple-600 text-purple-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<BarChart3 className="h-4 w-4" />
|
||||||
|
تحلیل و تاریخچه مکالمات
|
||||||
|
{stats && stats.conversations > 0 && (
|
||||||
|
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-xs font-bold text-purple-700">
|
||||||
|
{stats.conversations}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab 1: Config */}
|
||||||
|
{activeTab === 'config' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{configError && (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex items-center justify-between rounded-2xl border border-amber-200 bg-amber-50/80 p-4 text-sm text-amber-800 shadow-sm"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-5 w-5 text-amber-600 flex-shrink-0" />
|
||||||
|
<span>{configError}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={loadConfig}
|
||||||
|
className="font-bold text-purple-700 hover:underline"
|
||||||
|
>
|
||||||
|
تلاش دوباره
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isConfigLoading ? (
|
||||||
|
<div className="flex h-64 items-center justify-center rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
<Spinner size="lg" />
|
||||||
|
</div>
|
||||||
|
) : !settings ? (
|
||||||
|
<div className="rounded-2xl border border-dashed border-gray-300 bg-white p-12 text-center shadow-sm">
|
||||||
|
<Bot className="mx-auto h-12 w-12 text-gray-400 mb-3" />
|
||||||
|
<h3 className="text-lg font-bold text-gray-800 mb-1">پیکربندی اولیه یافت نشد</h3>
|
||||||
|
<p className="text-sm text-gray-500 mb-6">برای فعالسازی پشتیبان هوشمند روی فروشگاه، تنظیمات اولیه را ثبت کنید.</p>
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
setSettings({
|
||||||
|
enabled: false,
|
||||||
|
provider: providers[0]?.id || '',
|
||||||
|
model: providers[0]?.models[0] || '',
|
||||||
|
label: 'گفتگو با پشتیبان',
|
||||||
|
icon: 'chat',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
ایجاد تنظیمات جدید
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleSave} className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||||
|
{/* Main settings card */}
|
||||||
|
<div className="lg:col-span-2 space-y-6">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm space-y-5">
|
||||||
|
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-bold text-gray-900">وضعیت سرویس هوش مصنوعی</h3>
|
||||||
|
<p className="text-xs text-gray-500">فعال یا غیرفعال بودن پنجره چت در فروشگاه</p>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.enabled}
|
||||||
|
onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
|
||||||
|
className="h-4 w-4 rounded text-purple-600 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-bold text-gray-700">فعالسازی پشتیبان هوشمند</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">ارائهدهنده سرویس (Provider)</label>
|
||||||
|
<select
|
||||||
|
aria-label="ارائهدهنده"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white"
|
||||||
|
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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">مدل هوش مصنوعی (AI Model)</label>
|
||||||
|
<select
|
||||||
|
aria-label="مدل"
|
||||||
|
disabled={!settings.provider}
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white disabled:bg-gray-50 disabled:text-gray-400"
|
||||||
|
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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">نام دکمه و دستیار</label>
|
||||||
|
<input
|
||||||
|
aria-label="نام دکمه و دستیار"
|
||||||
|
required
|
||||||
|
maxLength={60}
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
value={settings.label}
|
||||||
|
onChange={(e) => setSettings({ ...settings, label: e.target.value })}
|
||||||
|
placeholder="گفتگو با پشتیبان"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">آیکون دستیار</label>
|
||||||
|
<select
|
||||||
|
aria-label="آیکون دستیار"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm focus:border-purple-600 focus:outline-none bg-white"
|
||||||
|
value={settings.icon}
|
||||||
|
onChange={(e) => setSettings({ ...settings, icon: e.target.value })}
|
||||||
|
>
|
||||||
|
<option value="chat">💬 گفتگو (Chat)</option>
|
||||||
|
<option value="paw">🐾 پنجه حیوانات (Paw)</option>
|
||||||
|
<option value="bot">🤖 ربات هوشمند (Bot)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-4 border-t border-gray-100 flex items-center justify-between">
|
||||||
|
<p className="text-xs text-gray-400">
|
||||||
|
برای امنیت کامل فروشگاه، فقط آیکونهای استاندارد داخلی سامانه مجاز هستند.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSaving || (settings.enabled && (!settings.provider || !settings.model))}
|
||||||
|
>
|
||||||
|
{isSaving ? <Spinner size="sm" /> : 'ذخیره تنظیمات'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sidebar preview card */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm space-y-4">
|
||||||
|
<h4 className="text-sm font-bold text-gray-900 flex items-center gap-2">
|
||||||
|
<Sparkles className="h-4 w-4 text-purple-600" />
|
||||||
|
پیشنمایش زنده المان در فروشگاه
|
||||||
|
</h4>
|
||||||
|
<p className="text-xs text-gray-500 leading-relaxed">
|
||||||
|
نحوه نمایش دکمه در کپسول دو تکه ناوبری مشتری:
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="p-6 rounded-2xl bg-gray-50 border border-gray-200 flex flex-col items-center justify-center gap-3">
|
||||||
|
<div
|
||||||
|
aria-label="پیشنمایش دکمه"
|
||||||
|
className="inline-flex items-center gap-2 rounded-full bg-[#1E4053] text-white px-5 py-2.5 shadow-md font-bold text-sm"
|
||||||
|
>
|
||||||
|
<span>{icons[settings.icon] || '💬'}</span>
|
||||||
|
<span>{settings.label || 'گفتگو با پشتیبان'}</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-[11px] text-gray-400">
|
||||||
|
وضعیت کنونی: {settings.enabled ? '🟢 فعال در فروشگاه' : '🔴 غیرفعال'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-xl bg-purple-50/50 p-4 border border-purple-100 text-xs text-purple-800 space-y-2">
|
||||||
|
<div className="font-bold flex items-center gap-1.5">
|
||||||
|
<ShieldCheck className="h-4 w-4 text-purple-600" />
|
||||||
|
امنیت و حریم خصوصی دادهها
|
||||||
|
</div>
|
||||||
|
<p className="leading-relaxed text-gray-600">
|
||||||
|
انتخاب مدل برای تشخیص نوع درخواست و پاسخگویی به صورت یکپارچه عمل میکند. هیچ اطلاعات هویتی یا اطلاعات حساب کاربری به مدل ارسال نخواهد شد.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tab 2: Analytics */}
|
||||||
|
{activeTab === 'analytics' && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{analyticsError && (
|
||||||
|
<div role="alert" className="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
|
||||||
|
{analyticsError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm flex flex-wrap items-end gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">از تاریخ</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className="rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
value={dates.startDate}
|
||||||
|
onChange={(e) => setDates({ ...dates, startDate: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1.5">تا تاریخ</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className="rounded-xl border border-gray-200 px-3 py-2 text-sm focus:border-purple-600 focus:outline-none"
|
||||||
|
value={dates.endDate}
|
||||||
|
onChange={(e) => setDates({ ...dates, endDate: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button variant="secondary" onClick={loadAnalytics} disabled={isAnalyticsLoading}>
|
||||||
|
اعمال فیلتر
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stats Grid */}
|
||||||
|
{stats && (
|
||||||
|
<div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">
|
||||||
|
{[
|
||||||
|
['گفتگوها', stats.conversations, 'text-blue-600', 'bg-blue-50'],
|
||||||
|
['کل پیامها', stats.messages, 'text-purple-600', 'bg-purple-50'],
|
||||||
|
['کاربران عضو', stats.authenticated, 'text-emerald-600', 'bg-emerald-50'],
|
||||||
|
['مهمان', stats.anonymous, 'text-gray-600', 'bg-gray-100'],
|
||||||
|
['بیپاسخ', stats.unanswered, 'text-red-600', 'bg-red-50'],
|
||||||
|
['نیازمند پیگیری', stats.followup, 'text-amber-600', 'bg-amber-50'],
|
||||||
|
['سیگنال هشدار', stats.escalated, 'text-rose-600', 'bg-rose-50'],
|
||||||
|
].map(([label, value, textColor, bgColor]) => (
|
||||||
|
<div key={String(label)} className="rounded-2xl border border-gray-100 bg-white p-4 shadow-sm text-center">
|
||||||
|
<div className="text-xs font-bold text-gray-500 mb-1">{label}</div>
|
||||||
|
<div className={`text-2xl font-black ${textColor}`}>{value}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Conversations list */}
|
||||||
|
{isAnalyticsLoading ? (
|
||||||
|
<div className="flex h-64 items-center justify-center rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
<Spinner size="lg" />
|
||||||
|
</div>
|
||||||
|
) : conversations.length === 0 ? (
|
||||||
|
<div className="rounded-2xl border border-dashed border-gray-300 bg-white p-12 text-center text-gray-400">
|
||||||
|
<MessageSquare className="mx-auto h-12 w-12 text-gray-300 mb-2" />
|
||||||
|
هنوز مکالمهای با پشتیبان هوشمند ثبت نشده است.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{conversations.map((row) => (
|
||||||
|
<article key={row.id} className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm space-y-3">
|
||||||
|
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-bold text-sm text-gray-900">
|
||||||
|
{row.user
|
||||||
|
? `${row.user.firstName || ''} ${row.user.lastName || ''}`.trim() || 'کاربر ثبتنامشده'
|
||||||
|
: 'مشتری مهمان'}
|
||||||
|
</span>
|
||||||
|
{row.user?.mobile && (
|
||||||
|
<span className="text-xs font-mono text-gray-500 bg-gray-100 px-2 py-0.5 rounded-lg">
|
||||||
|
{row.user.mobile}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-400 flex items-center gap-1">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
{new Date(row.updatedAt).toLocaleString('fa-IR')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2 text-xs">
|
||||||
|
{row.unanswered && <span className="rounded-lg bg-red-50 text-red-700 px-2.5 py-1 font-bold">بیپاسخ</span>}
|
||||||
|
{row.needsFollowup && <span className="rounded-lg bg-amber-50 text-amber-700 px-2.5 py-1 font-bold">نیازمند پیگیری</span>}
|
||||||
|
{row.escalationSignal && <span className="rounded-lg bg-rose-50 text-rose-700 px-2.5 py-1 font-bold">ارجاع فوری</span>}
|
||||||
|
{row.entryPath && <span className="rounded-lg bg-gray-50 text-gray-500 px-2.5 py-1 font-mono">صفحه: {row.entryPath}</span>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 pt-1">
|
||||||
|
{row.messages.map((m, i) => (
|
||||||
|
<div
|
||||||
|
key={`${row.id}-${i}`}
|
||||||
|
className={`rounded-xl p-3 text-sm leading-relaxed ${
|
||||||
|
m.role === 'user' ? 'bg-purple-50/70 border border-purple-100 text-purple-950 mr-4' : 'bg-gray-50 border border-gray-100 text-gray-800 ml-4'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="font-bold text-xs text-gray-500 mb-1">
|
||||||
|
{m.role === 'user' ? '👤 پیام مشتری:' : '🤖 پاسخ پشتیبان هوشمند:'}
|
||||||
|
</div>
|
||||||
|
<div>{m.content}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
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 } })]); setStats(unwrap(s)); setRows(unwrap(c).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>;
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ 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 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'));
|
||||||
@@ -37,6 +38,8 @@ const ZibalPortalPage = lazyWithRetry(() => import('../pages/ZibalPortalPage'));
|
|||||||
const ShippingSettingsPage = lazyWithRetry(() => import('../pages/ShippingSettingsPage'));
|
const ShippingSettingsPage = lazyWithRetry(() => import('../pages/ShippingSettingsPage'));
|
||||||
const SystemSettingsPage = lazyWithRetry(() => import('../pages/SystemSettingsPage'));
|
const SystemSettingsPage = lazyWithRetry(() => import('../pages/SystemSettingsPage'));
|
||||||
const SmsSettingsPage = lazyWithRetry(() => import('../pages/SmsSettingsPage'));
|
const SmsSettingsPage = lazyWithRetry(() => import('../pages/SmsSettingsPage'));
|
||||||
|
const NotificationsSettingsPage = lazyWithRetry(() => import('../pages/NotificationsSettingsPage'));
|
||||||
|
const AdvisorsManagementPage = lazyWithRetry(() => import('../pages/AdvisorsManagementPage'));
|
||||||
const SslSettingsPage = lazyWithRetry(() => import('../pages/SslSettingsPage'));
|
const SslSettingsPage = lazyWithRetry(() => import('../pages/SslSettingsPage'));
|
||||||
const ApiKeysPage = lazyWithRetry(() => import('../pages/ApiKeysPage'));
|
const ApiKeysPage = lazyWithRetry(() => import('../pages/ApiKeysPage'));
|
||||||
const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
|
const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
|
||||||
@@ -79,11 +82,16 @@ 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: <SmartChatSettingsPage /> },
|
||||||
|
{ 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 /> },
|
||||||
{ path: 'settings/api-keys', element: <ApiKeysPage /> },
|
{ path: 'settings/api-keys', element: <ApiKeysPage /> },
|
||||||
{ path: 'settings/sms', element: <SmsSettingsPage /> },
|
{ path: 'settings/sms', element: <SmsSettingsPage /> },
|
||||||
|
{ path: 'settings/notifications', element: <NotificationsSettingsPage /> },
|
||||||
|
{ path: 'advisors/*', element: <AdvisorsManagementPage /> },
|
||||||
|
{ path: 'leads/*', element: <AdvisorsManagementPage /> },
|
||||||
{ path: 'settings/seo', element: <SeoSettingsPage /> },
|
{ path: 'settings/seo', element: <SeoSettingsPage /> },
|
||||||
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
|
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
|
||||||
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
vi.mock('../../../lib/seo', () => ({ getSeoConfig: async () => ({brandNameFa:'Canina', ogImageUrl:'https://example.org/unrelated.webp'}), formatPageTitle: (s:string) => s }));
|
||||||
|
vi.mock('../../../components/BlogPostClient', () => ({default: () => null}));
|
||||||
|
vi.mock('next/navigation', () => ({notFound: () => {throw Error('404')}}));
|
||||||
|
import Page, {generateMetadata} from './page';
|
||||||
|
const base = {title:'Existing article',content:'Body',slug:'existing',publishedAt:'2026-11-15T05:41:53Z'};
|
||||||
|
let blog: any;
|
||||||
|
beforeEach(() => {blog={...base}; vi.stubGlobal('fetch',vi.fn(async () => ({ok:true,json:async () => blog})));});
|
||||||
|
describe('article-owned media', () => {
|
||||||
|
it.each([null,undefined,'',' '])('omits unrelated imagery for %s', async (image) => {
|
||||||
|
blog.imageUrl=image; blog.ogImage=image;
|
||||||
|
const metadata:any=await generateMetadata({params:Promise.resolve({slug:'existing'})});
|
||||||
|
expect(metadata.openGraph.images).toEqual([]);
|
||||||
|
expect(metadata.twitter.images).toEqual([]);
|
||||||
|
expect(metadata.twitter.card).toBe('summary');
|
||||||
|
const page:any=await Page({params:Promise.resolve({slug:'existing'})});
|
||||||
|
const schema=JSON.parse(page.props.children[0].props.dangerouslySetInnerHTML.__html);
|
||||||
|
expect(schema).not.toHaveProperty('image');
|
||||||
|
});
|
||||||
|
it('retains authored OG precedence and Article image', async () => {
|
||||||
|
blog.imageUrl='/uploads/article.webp'; blog.ogImage='/uploads/social.webp';
|
||||||
|
const metadata:any=await generateMetadata({params:Promise.resolve({slug:'existing'})});
|
||||||
|
expect(metadata.openGraph.images[0].url).toBe('/uploads/social.webp');
|
||||||
|
const page:any=await Page({params:Promise.resolve({slug:'existing'})});
|
||||||
|
expect(JSON.parse(page.props.children[0].props.dangerouslySetInnerHTML.__html).image[0]).toContain('/uploads/article.webp');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -77,7 +77,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
|||||||
(typeof blog.content === 'string' ? blog.content.substring(0, 155).replace(/<[^>]+>/g, '') : '') ||
|
(typeof blog.content === 'string' ? blog.content.substring(0, 155).replace(/<[^>]+>/g, '') : '') ||
|
||||||
config.defaultMetaDescription;
|
config.defaultMetaDescription;
|
||||||
const canonicalUrl = blog.canonicalUrl ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`;
|
const canonicalUrl = blog.canonicalUrl ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`;
|
||||||
const ogImageUrl = blog.ogImage || blog.imageUrl || config.ogImageUrl;
|
const ogImageUrl = (typeof blog.ogImage === 'string' ? blog.ogImage.trim() : '') || (typeof blog.imageUrl === 'string' ? blog.imageUrl.trim() : '');
|
||||||
const ogTitle = blog.ogTitle || title;
|
const ogTitle = blog.ogTitle || title;
|
||||||
const ogDesc = blog.ogDescription || description;
|
const ogDesc = blog.ogDescription || description;
|
||||||
|
|
||||||
@@ -133,14 +133,14 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
|||||||
openGraph: {
|
openGraph: {
|
||||||
title: ogTitle,
|
title: ogTitle,
|
||||||
description: ogDesc,
|
description: ogDesc,
|
||||||
images: [
|
images: ogImageUrl ? [
|
||||||
{
|
{
|
||||||
url: ogImageUrl,
|
url: ogImageUrl,
|
||||||
width: 1200,
|
width: 1200,
|
||||||
height: 630,
|
height: 630,
|
||||||
alt: blog.imageAlt || blog.title || title,
|
alt: blog.imageAlt || blog.title || title,
|
||||||
},
|
},
|
||||||
],
|
] : [],
|
||||||
url: canonicalUrl,
|
url: canonicalUrl,
|
||||||
siteName: config.brandNameFa,
|
siteName: config.brandNameFa,
|
||||||
type: "article",
|
type: "article",
|
||||||
@@ -150,10 +150,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
|||||||
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
|
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
|
||||||
},
|
},
|
||||||
twitter: {
|
twitter: {
|
||||||
card: "summary_large_image",
|
card: ogImageUrl ? "summary_large_image" : "summary",
|
||||||
title: ogTitle,
|
title: ogTitle,
|
||||||
description: ogDesc,
|
description: ogDesc,
|
||||||
images: [ogImageUrl],
|
images: ogImageUrl ? [ogImageUrl] : [],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -205,9 +205,9 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
|||||||
},
|
},
|
||||||
headline: blog.title,
|
headline: blog.title,
|
||||||
description: blog.excerpt || blog.metaDescription || blog.title,
|
description: blog.excerpt || blog.metaDescription || blog.title,
|
||||||
image: blog.imageUrl
|
...(typeof blog.imageUrl === 'string' && blog.imageUrl.trim()
|
||||||
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
|
? { image: [new URL(blog.imageUrl.trim(), siteUrl).href] }
|
||||||
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
|
: {}),
|
||||||
datePublished: publishedIso,
|
datePublished: publishedIso,
|
||||||
dateModified: modifiedIso,
|
dateModified: modifiedIso,
|
||||||
author: authorSchema,
|
author: authorSchema,
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -74,6 +74,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Authored body links remain recognizable without relying on color alone. */
|
||||||
|
.article-html-content a {
|
||||||
|
color: var(--color-canina-blue);
|
||||||
|
font-weight: 700;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-underline-offset: 4px;
|
||||||
|
}
|
||||||
|
.article-html-content a:hover { color: var(--color-medical-gray-900); }
|
||||||
|
|
||||||
/* Sonner Toasts Vazirmatn Font & Mobile Offset */
|
/* Sonner Toasts Vazirmatn Font & Mobile Offset */
|
||||||
[data-sonner-toaster] {
|
[data-sonner-toaster] {
|
||||||
font-family: "Vazirmatn", sans-serif !important;
|
font-family: "Vazirmatn", sans-serif !important;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import NextTopLoader from 'nextjs-toploader';
|
|||||||
import ClientLayout from './ClientLayout';
|
import ClientLayout from './ClientLayout';
|
||||||
import AnalyticsDeferred from '../components/AnalyticsDeferred';
|
import AnalyticsDeferred from '../components/AnalyticsDeferred';
|
||||||
import SupportChat from '../components/SupportChat';
|
import SupportChat from '../components/SupportChat';
|
||||||
|
import ContactAdvisorButton from '../components/ContactAdvisorButton';
|
||||||
import { getSeoConfig } from '../lib/seo';
|
import { getSeoConfig } from '../lib/seo';
|
||||||
import { vazirmatn, lalezar } from '../lib/fonts';
|
import { vazirmatn, lalezar } from '../lib/fonts';
|
||||||
import { generateOrganizationSchema } from '../lib/schema';
|
import { generateOrganizationSchema } from '../lib/schema';
|
||||||
@@ -116,9 +117,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',
|
||||||
@@ -201,6 +202,7 @@ export default async function RootLayout({
|
|||||||
{children}
|
{children}
|
||||||
</ClientLayout>
|
</ClientLayout>
|
||||||
<SupportChat />
|
<SupportChat />
|
||||||
|
<ContactAdvisorButton hideFloatingButton={true} />
|
||||||
|
|
||||||
{/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */}
|
{/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */}
|
||||||
<AnalyticsDeferred
|
<AnalyticsDeferred
|
||||||
|
|||||||
@@ -76,6 +76,12 @@ 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));
|
||||||
@@ -572,7 +578,7 @@ 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));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch products:", error);
|
console.error("Failed to fetch products:", error);
|
||||||
toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
|
toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
|
||||||
@@ -724,10 +730,10 @@ 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>
|
||||||
@@ -1087,35 +1093,49 @@ export default function ArchivePage({
|
|||||||
)
|
)
|
||||||
) : filteredProducts.length > 0 ? (
|
) : filteredProducts.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
{/* Mobile List View vs Card View (Desktop is always responsive multi-column grid) */}
|
{/* Keep API sort order inside each availability section. */}
|
||||||
<div
|
{([{
|
||||||
key={viewMode}
|
key: "available",
|
||||||
className={
|
title: "محصولات موجود",
|
||||||
viewMode === "list"
|
products: filteredProducts.filter(product => !isProductOutOfStock(product)),
|
||||||
? "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"
|
key: "unavailable",
|
||||||
}
|
title: "محصولات ناموجود",
|
||||||
>
|
products: filteredProducts.filter(product => isProductOutOfStock(product)),
|
||||||
<AnimatePresence mode="popLayout">
|
}] as const).map(section => section.products.length > 0 && (
|
||||||
{filteredProducts.map((p: Product) => (
|
<section key={section.key} data-testid={`products-${section.key}`} className="mb-10 last:mb-0">
|
||||||
<React.Fragment key={p.id}>
|
<h2 className="mb-5 text-xl font-black text-medical-gray-900">{section.title}</h2>
|
||||||
{/* In list mode on mobile, render ArchiveProductListItem; on desktop (lg+), render standard card */}
|
{/* Mobile List View vs Card View (Desktop is always responsive multi-column grid) */}
|
||||||
{viewMode === "list" ? (
|
<div
|
||||||
<>
|
key={viewMode}
|
||||||
<div className="block lg:hidden w-full">
|
className={
|
||||||
<ArchiveProductListItem product={p} />
|
viewMode === "list"
|
||||||
</div>
|
? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6"
|
||||||
<div className="hidden lg:block h-full">
|
: "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}>
|
||||||
|
{/* In list mode on mobile, render ArchiveProductListItem; on desktop (lg+), render standard card */}
|
||||||
|
{viewMode === "list" ? (
|
||||||
|
<>
|
||||||
|
<div className="block lg:hidden w-full">
|
||||||
|
<ArchiveProductListItem product={p} />
|
||||||
|
</div>
|
||||||
|
<div className="hidden lg:block h-full">
|
||||||
|
<ArchiveProductCard product={p} />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
<ArchiveProductCard product={p} />
|
<ArchiveProductCard product={p} />
|
||||||
</div>
|
)}
|
||||||
</>
|
</React.Fragment>
|
||||||
) : (
|
))}
|
||||||
<ArchiveProductCard product={p} />
|
</AnimatePresence>
|
||||||
)}
|
</div>
|
||||||
</React.Fragment>
|
</section>
|
||||||
))}
|
))}
|
||||||
</AnimatePresence>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 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" && (
|
||||||
|
|||||||
@@ -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 }}
|
||||||
|
|||||||
@@ -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({
|
||||||
|
|||||||
@@ -333,10 +333,10 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<a
|
<a
|
||||||
href={useSettingsStore.getState().getText('contact_phone_link', `tel:${useSettingsStore.getState().getText('contact_phone', '02188884444').replace(/[^0-9+]/g, '')}`)}
|
href={useSettingsStore.getState().getText('contact_phone_link', `tel:${useSettingsStore.getState().getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)}
|
||||||
className="px-3 py-1.5 bg-amber-600 text-white rounded-xl text-[10px] font-black hover:bg-amber-700 transition-colors whitespace-nowrap shadow-xs font-vazir"
|
className="px-3 py-1.5 bg-amber-600 text-white rounded-xl text-[10px] font-black hover:bg-amber-700 transition-colors whitespace-nowrap shadow-xs font-vazir"
|
||||||
>
|
>
|
||||||
تماس فوری ({useSettingsStore.getState().getText('contact_phone', '۰۲۱-۸۸۸۸۴۴۴۴')})
|
تماس فوری ({useSettingsStore.getState().getText('contact_phone', '')})
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -321,11 +321,11 @@ export default function CheckoutPage() {
|
|||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col sm:flex-row gap-3 pt-2">
|
<div className="flex flex-col sm:flex-row gap-3 pt-2">
|
||||||
<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="flex-1 px-4 py-3 bg-canina-blue hover:bg-canina-dark text-white rounded-xl text-xs font-black transition-all shadow-md flex items-center justify-center gap-2"
|
className="flex-1 px-4 py-3 bg-canina-blue hover:bg-canina-dark text-white rounded-xl text-xs font-black transition-all shadow-md flex items-center justify-center gap-2"
|
||||||
>
|
>
|
||||||
<Phone className="w-4 h-4" />
|
<Phone className="w-4 h-4" />
|
||||||
<span>تماس با پشتیبانی ({getText('contact_phone', '۰۲۱-۸۸۸۸۴۴۴۴')})</span>
|
<span>تماس با پشتیبانی ({getText('contact_phone', '')})</span>
|
||||||
</a>
|
</a>
|
||||||
<button
|
<button
|
||||||
onClick={() => router.push('/shop')}
|
onClick={() => router.push('/shop')}
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
'use client';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { PhoneCall, X, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
interface ContactAdvisorButtonProps {
|
||||||
|
productId?: string;
|
||||||
|
productName?: string;
|
||||||
|
hideFloatingButton?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ContactAdvisorButton({ productId, productName, hideFloatingButton = false }: ContactAdvisorButtonProps) {
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => setIsOpen(true);
|
||||||
|
window.addEventListener('canina-open-advisor-modal', handler);
|
||||||
|
return () => window.removeEventListener('canina-open-advisor-modal', handler);
|
||||||
|
}, []);
|
||||||
|
const [firstName, setFirstName] = useState('');
|
||||||
|
const [lastName, setLastName] = useState('');
|
||||||
|
const [phone, setPhone] = useState('');
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const [status, setStatus] = useState<{ success: boolean; message: string } | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setStatus(null);
|
||||||
|
|
||||||
|
const cleanPhone = phone.trim().replace(/\s+/g, '');
|
||||||
|
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||||
|
setStatus({ success: false, message: 'لطفاً شماره موبایل ۱۱ رقمی معتبر وارد کنید (مثال: ۰۹۱۲۳۴۵۶۷۸۹)' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true);
|
||||||
|
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/public/lead`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
firstName: firstName.trim(),
|
||||||
|
lastName: lastName.trim(),
|
||||||
|
phone: cleanPhone,
|
||||||
|
productId: productId || undefined,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (res.ok && (data.ok || data.success)) {
|
||||||
|
setStatus({
|
||||||
|
success: true,
|
||||||
|
message: data.message || 'درخواست شما ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.',
|
||||||
|
});
|
||||||
|
setFirstName('');
|
||||||
|
setLastName('');
|
||||||
|
setPhone('');
|
||||||
|
} else {
|
||||||
|
setStatus({
|
||||||
|
success: false,
|
||||||
|
message: data.message || 'خطا در ثبت درخواست. لطفاً دوباره تلاش کنید.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setStatus({
|
||||||
|
success: false,
|
||||||
|
message: 'خطا در برقراری ارتباط با سرور. لطفاً دقایقی دیگر تلاش فرمایید.',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Floating Action Button */}
|
||||||
|
{!hideFloatingButton && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsOpen(true)}
|
||||||
|
className="fixed bottom-6 left-6 z-40 flex items-center gap-2.5 rounded-full bg-emerald-600 px-5 py-3.5 text-white font-bold shadow-lg shadow-emerald-600/30 transition-all hover:bg-emerald-700 hover:scale-105 active:scale-95"
|
||||||
|
>
|
||||||
|
<PhoneCall className="h-5 w-5 animate-pulse" />
|
||||||
|
<span>مشاوره و تماس رایگان</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Modal */}
|
||||||
|
{isOpen && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
|
||||||
|
<div className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-2xl font-vazir text-right text-gray-800">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setIsOpen(false);
|
||||||
|
setStatus(null);
|
||||||
|
}}
|
||||||
|
className="absolute top-4 left-4 rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-700"
|
||||||
|
>
|
||||||
|
<X className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 border-b border-gray-100 pb-4">
|
||||||
|
<div className="rounded-xl bg-emerald-50 p-2.5 text-emerald-600">
|
||||||
|
<PhoneCall className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold text-gray-900 text-lg">درخواست مشاوره تخصصی کنینا</h3>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
{productName ? `برای محصول: ${productName}` : 'مشاوره اختصاصی مکملها با دامپزشک'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{status && (
|
||||||
|
<div
|
||||||
|
className={`mt-4 flex items-start gap-3 rounded-xl p-3.5 text-sm ${
|
||||||
|
status.success ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{status.success ? (
|
||||||
|
<CheckCircle2 className="h-5 w-5 shrink-0 text-emerald-600 mt-0.5" />
|
||||||
|
) : (
|
||||||
|
<AlertCircle className="h-5 w-5 shrink-0 text-red-600 mt-0.5" />
|
||||||
|
)}
|
||||||
|
<span>{status.message}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!status?.success ? (
|
||||||
|
<form onSubmit={handleSubmit} className="mt-4 space-y-3.5">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">نام</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={firstName}
|
||||||
|
onChange={(e) => setFirstName(e.target.value)}
|
||||||
|
placeholder="مثال: علی"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm focus:border-emerald-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">نام خانوادگی</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={lastName}
|
||||||
|
onChange={(e) => setLastName(e.target.value)}
|
||||||
|
placeholder="مثال: محمدی"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm focus:border-emerald-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-bold text-gray-700 mb-1">شماره تلفن همراه</label>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
dir="ltr"
|
||||||
|
value={phone}
|
||||||
|
onChange={(e) => setPhone(e.target.value)}
|
||||||
|
placeholder="09121234567"
|
||||||
|
className="w-full rounded-xl border border-gray-200 px-3.5 py-2.5 text-sm font-mono text-right focus:border-emerald-600 focus:outline-none"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-[11px] text-gray-400">مشاوران ما در کمتر از ۵ دقیقه با شما تماس خواهند گرفت.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-2">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
className="w-full rounded-xl bg-emerald-600 py-3 text-sm font-bold text-white shadow-md transition-all hover:bg-emerald-700 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isSubmitting ? 'در حال ثبت...' : 'ثبت درخواست تماس'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<div className="pt-4 text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsOpen(false)}
|
||||||
|
className="rounded-xl bg-gray-100 px-6 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-200"
|
||||||
|
>
|
||||||
|
بستن پنجره
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -110,53 +110,9 @@ export default function ContactFormClient() {
|
|||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<>
|
<div className="p-6 rounded-2xl border border-amber-200 bg-amber-50 text-amber-900 font-bold">
|
||||||
<div className="flex gap-4 p-6 bg-white border border-medical-gray-200 rounded-[2rem] shadow-sm">
|
اطلاعات تماس از تنظیمات سایت در دسترس نیست.
|
||||||
<div className="w-12 h-12 bg-canina-blue/5 text-canina-blue rounded-2xl flex items-center justify-center shrink-0">
|
</div>
|
||||||
<Phone className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-black text-medical-gray-400 uppercase tracking-wider mb-1">
|
|
||||||
تلفنهای تماس
|
|
||||||
</h4>
|
|
||||||
<p className="text-lg font-black text-medical-gray-900 tracking-wider">
|
|
||||||
۰۲۱-۸۸۸۸ ۴۴۴۴
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-medical-gray-500 font-bold">
|
|
||||||
شنبه تا چهارشنبه ۹:۰۰ الی ۱۸:۰۰
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-4 p-6 bg-white border border-medical-gray-200 rounded-[2rem] shadow-sm">
|
|
||||||
<div className="w-12 h-12 bg-canina-blue/5 text-canina-blue rounded-2xl flex items-center justify-center shrink-0">
|
|
||||||
<Mail className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-black text-medical-gray-400 uppercase tracking-wider mb-1">
|
|
||||||
پست الکترونیک
|
|
||||||
</h4>
|
|
||||||
<p className="text-sm font-black text-medical-gray-900">info@canina.ir</p>
|
|
||||||
<p className="text-xs text-medical-gray-500 font-bold">
|
|
||||||
پاسخگویی در کمتر از ۲۴ ساعت کاری
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-4 p-6 bg-white border border-medical-gray-200 rounded-[2rem] shadow-sm">
|
|
||||||
<div className="w-12 h-12 bg-canina-blue/5 text-canina-blue rounded-2xl flex items-center justify-center shrink-0">
|
|
||||||
<MapPin className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-black text-medical-gray-400 uppercase tracking-wider mb-1">
|
|
||||||
نشانی دفتر مرکزی
|
|
||||||
</h4>
|
|
||||||
<p className="text-sm font-bold text-medical-gray-900 leading-relaxed">
|
|
||||||
تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -208,22 +208,22 @@ export default function Footer({
|
|||||||
<h3 className="text-base sm:text-xl font-bold text-white border-b-2 border-canina-blue pb-1.5 sm:pb-2 max-w-max font-lalezar">{getText('footer_contact_title', "اطلاعات تماس نمایندگی")}</h3>
|
<h3 className="text-base sm:text-xl font-bold text-white border-b-2 border-canina-blue pb-1.5 sm:pb-2 max-w-max font-lalezar">{getText('footer_contact_title', "اطلاعات تماس نمایندگی")}</h3>
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-8">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-8">
|
||||||
<div className="flex flex-col sm:space-y-6 gap-2.5 sm:gap-0">
|
<div className="flex flex-col sm:space-y-6 gap-2.5 sm:gap-0">
|
||||||
<a href={getText('contact_phone_link', `tel:${getText('contact_phone', '02188884444').replace(/[^0-9+]/g, '')}`)} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
|
<a href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
|
||||||
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
|
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
|
||||||
<Phone className="w-4 h-4 sm:w-6 sm:h-6" />
|
<Phone className="w-4 h-4 sm:w-6 sm:h-6" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_phone_label', "خط ویژه فروش")}</p>
|
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_phone_label', "خط ویژه فروش")}</p>
|
||||||
<p className="text-xs sm:text-lg font-extrabold tracking-wider sm:tracking-widest text-left text-slate-200" dir="ltr">{getText('contact_phone', "۰۲۱-۸۸۸۸۴۴۴۴")}</p>
|
<p className="text-xs sm:text-lg font-extrabold tracking-wider sm:tracking-widest text-left text-slate-200" dir="ltr">{getText('contact_phone', '')}</p>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
<a href={`mailto:${getText('contact_email', 'info@canina.ir')}`} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
|
<a href={`mailto:${getText('contact_email', '')}`} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
|
||||||
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
|
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
|
||||||
<Mail className="w-4 h-4 sm:w-6 sm:h-6" />
|
<Mail className="w-4 h-4 sm:w-6 sm:h-6" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_email_label', "مکاتبات رسمی")}</p>
|
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_email_label', "مکاتبات رسمی")}</p>
|
||||||
<p className="text-xs sm:text-sm font-bold text-slate-300 truncate">{getText('contact_email', "info@canina.ir")}</p>
|
<p className="text-xs sm:text-sm font-bold text-slate-300 truncate">{getText('contact_email', '')}</p>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
@@ -234,7 +234,7 @@ export default function Footer({
|
|||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_address_label', "دفتر مرکزی")}</p>
|
<p className="text-[10px] sm:text-[11px] text-slate-400 font-extrabold uppercase mb-0.5">{getText('footer_address_label', "دفتر مرکزی")}</p>
|
||||||
<p className="text-xs sm:text-sm font-bold leading-relaxed text-slate-300">{getText('contact_address', "تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹")}</p>
|
<p className="text-xs sm:text-sm font-bold leading-relaxed text-slate-300">{getText('contact_address', '')}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ export default function MaintenancePage() {
|
|||||||
);
|
);
|
||||||
const badge = getText("maintenance_badge", "سامانه در حال بهروزرسانی و ارتقا");
|
const badge = getText("maintenance_badge", "سامانه در حال بهروزرسانی و ارتقا");
|
||||||
const eta = getText("maintenance_eta", "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده");
|
const eta = getText("maintenance_eta", "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده");
|
||||||
const phone = getText("contact_phone", getText("maintenance_contact_phone", "۰۲۱-۸۸۸۸۴۴۴۴"));
|
const phone = getText("contact_phone", "");
|
||||||
const phoneLink = getText("contact_phone_link", getText("maintenance_contact_phone_link", `tel:${phone.replace(/[^0-9+]/g, "") || "02188884444"}`));
|
const phoneLink = getText("contact_phone_link", "");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-medical-gray-900 text-white flex flex-col items-center justify-center p-6 text-center font-vazir relative overflow-hidden" dir="rtl">
|
<div className="min-h-screen bg-medical-gray-900 text-white flex flex-col items-center justify-center p-6 text-center font-vazir relative overflow-hidden" dir="rtl">
|
||||||
|
|||||||
@@ -225,7 +225,7 @@ export default function OrderDetailsModal({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="footer">
|
<div class="footer">
|
||||||
داروخانه تخصصی مکملهای کنینا ایران • تلفن پشتیبانی: ۰۲۱-۸۸۸۸۸۸۸۸ • وبسایت: www.canina.ir
|
داروخانه تخصصی مکملهای کنینا ایران • تلفن پشتیبانی: {useSettingsStore.getState().getText('contact_phone', '')} • وبسایت: www.canina.ir
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -1379,11 +1379,11 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
|||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<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 flex items-center justify-center gap-2 px-4 bg-canina-blue text-white rounded-2xl h-16 font-black text-sm hover:bg-canina-dark transition-all shadow-xl shadow-canina-blue/20 font-vazir"
|
className="w-full flex items-center justify-center gap-2 px-4 bg-canina-blue text-white rounded-2xl h-16 font-black text-sm hover:bg-canina-dark transition-all shadow-xl shadow-canina-blue/20 font-vazir"
|
||||||
>
|
>
|
||||||
<Phone className="w-5 h-5" />
|
<Phone className="w-5 h-5" />
|
||||||
<span>مشاوره تخصصی با کارشناسان ({getText('contact_phone', '۰۲۱-۸۸۸۸۴۴۴۴')})</span>
|
<span>مشاوره تخصصی با کارشناسان ({getText('contact_phone', '')})</span>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -1620,7 +1620,7 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
|||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<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="flex-1 bg-canina-blue text-white py-2.5 px-3 rounded-xl font-black text-xs hover:bg-canina-dark transition-all flex items-center justify-center gap-1.5 shadow-md shadow-canina-blue/20 whitespace-nowrap"
|
className="flex-1 bg-canina-blue text-white py-2.5 px-3 rounded-xl font-black text-xs hover:bg-canina-dark transition-all flex items-center justify-center gap-1.5 shadow-md shadow-canina-blue/20 whitespace-nowrap"
|
||||||
>
|
>
|
||||||
<Phone className="w-4 h-4" />
|
<Phone className="w-4 h-4" />
|
||||||
|
|||||||
@@ -28,4 +28,12 @@ describe('support widget', () => {
|
|||||||
localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
|
localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
|
||||||
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
|
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
|
||||||
});
|
});
|
||||||
|
it('dispatches advisor event when phone button clicked', async () => {
|
||||||
|
const handler = vi.fn();
|
||||||
|
window.addEventListener('canina-open-advisor-modal', handler);
|
||||||
|
render(<SupportChat/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /درخواست مشاوره تلفنی/ }));
|
||||||
|
expect(handler).toHaveBeenCalled();
|
||||||
|
window.removeEventListener('canina-open-advisor-modal', handler);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
import { FormEvent, useEffect, useRef, useState } from 'react';
|
import { FormEvent, useEffect, useRef, useState } from 'react';
|
||||||
|
import { PhoneCall, MessageSquare } from 'lucide-react';
|
||||||
|
|
||||||
|
type PersistedMessage = { role: 'user' | 'assistant'; content: string };
|
||||||
|
|
||||||
const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
||||||
const token = () => {
|
const token = () => {
|
||||||
@@ -11,19 +14,43 @@ const token = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function SupportChat() {
|
export default function SupportChat() {
|
||||||
|
const [config, setConfig] = useState<{ enabled: boolean; label: string; icon: string } | null>(null);
|
||||||
|
const [configError, setConfigError] = useState(false);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
const refresh = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/config`, { cache: 'no-store' });
|
||||||
|
if (!response.ok) throw new Error('config');
|
||||||
|
const raw = await response.json();
|
||||||
|
const value = raw.data ?? raw;
|
||||||
|
if (typeof value.enabled !== 'boolean' || typeof value.label !== 'string' || !['chat', 'paw', 'bot'].includes(value.icon)) throw new Error('config');
|
||||||
|
if (active) { setConfig(value); setConfigError(false); if (!value.enabled) { setOpen(false); pending.current?.abort(); setRows([]); } }
|
||||||
|
} catch { if (active) { setConfig(null); setConfigError(true); setOpen(false); pending.current?.abort(); setRows([]); } }
|
||||||
|
};
|
||||||
|
void refresh();
|
||||||
|
const timer = window.setInterval(refresh, 10000);
|
||||||
|
window.addEventListener('focus', refresh);
|
||||||
|
return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); };
|
||||||
|
}, []);
|
||||||
const [message, setMessage] = useState('');
|
const [message, setMessage] = useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
|
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
|
||||||
|
const [conversationId, setConversationId] = useState('');
|
||||||
|
const [contextLimited, setContextLimited] = useState(false);
|
||||||
const identity = useRef('');
|
const identity = useRef('');
|
||||||
const pending = useRef<AbortController | null>(null);
|
const pending = useRef<AbortController | null>(null);
|
||||||
const chatScrollRef = useRef<HTMLDivElement | null>(null);
|
const chatScrollRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const historyKey = useRef('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
identity.current = token();
|
identity.current = token();
|
||||||
|
try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {}
|
||||||
const check = () => {
|
const check = () => {
|
||||||
if (identity.current !== token()) {
|
if (identity.current !== token()) {
|
||||||
identity.current = token();
|
identity.current = token();
|
||||||
|
try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {}
|
||||||
pending.current?.abort();
|
pending.current?.abort();
|
||||||
setRows([]);
|
setRows([]);
|
||||||
setMessage('');
|
setMessage('');
|
||||||
@@ -47,9 +74,57 @@ export default function SupportChat() {
|
|||||||
}
|
}
|
||||||
}, [rows, busy]);
|
}, [rows, busy]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!conversationId || !config?.enabled) return;
|
||||||
|
const current = token();
|
||||||
|
const key = `${current}:${conversationId}`;
|
||||||
|
if (historyKey.current === key) return;
|
||||||
|
historyKey.current = key;
|
||||||
|
const controller = new AbortController();
|
||||||
|
pending.current = controller;
|
||||||
|
const loadHistory = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/${encodeURIComponent(conversationId)}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { 'X-Requested-With': 'XMLHttpRequest', ...(current ? { Authorization: `Bearer ${current}` } : {}) },
|
||||||
|
signal: controller.signal
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('history');
|
||||||
|
const data = await response.json();
|
||||||
|
if (!Array.isArray(data?.messages) || data.conversationId !== conversationId) throw new Error('history');
|
||||||
|
const messages = data.messages.filter((message: unknown): message is PersistedMessage => {
|
||||||
|
if (!message || typeof message !== 'object') return false;
|
||||||
|
const value = message as Record<string, unknown>;
|
||||||
|
return (value.role === 'user' || value.role === 'assistant') && typeof value.content === 'string';
|
||||||
|
});
|
||||||
|
const restored: { question: string; answer: string }[] = [];
|
||||||
|
for (let i = 0; i < messages.length; i += 1) {
|
||||||
|
const message = messages[i];
|
||||||
|
if (message.role === 'user') {
|
||||||
|
const next = messages[i + 1];
|
||||||
|
if (next?.role === 'assistant') i += 1;
|
||||||
|
restored.push({ question: message.content, answer: next?.role === 'assistant' ? next.content : '' });
|
||||||
|
} else if (!restored.length || restored[restored.length - 1].answer) {
|
||||||
|
restored.push({ question: '', answer: message.content });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!controller.signal.aborted && token() === current) setRows(restored);
|
||||||
|
} catch {
|
||||||
|
if (!controller.signal.aborted && token() === current) {
|
||||||
|
setRows([]); setConversationId(''); setContextLimited(false);
|
||||||
|
try { localStorage.removeItem('canina-support-conversation'); } catch {}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (pending.current === controller) pending.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
void loadHistory();
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [conversationId, config?.enabled]);
|
||||||
|
|
||||||
async function send(event: FormEvent) {
|
async function send(event: FormEvent) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (busy || !message.trim()) return;
|
if (busy || !message.trim() || !config?.enabled) return;
|
||||||
const current = token();
|
const current = token();
|
||||||
if (current !== identity.current) {
|
if (current !== identity.current) {
|
||||||
setRows([]);
|
setRows([]);
|
||||||
@@ -58,6 +133,7 @@ export default function SupportChat() {
|
|||||||
const question = message.trim();
|
const question = message.trim();
|
||||||
setMessage('');
|
setMessage('');
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
|
setRows((r) => [...r.slice(-9), { question, answer: 'در حال بررسی…' }]);
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
pending.current = controller;
|
pending.current = controller;
|
||||||
let answer = unavailable;
|
let answer = unavailable;
|
||||||
@@ -70,7 +146,7 @@ export default function SupportChat() {
|
|||||||
...(current ? { Authorization: `Bearer ${current}` } : {})
|
...(current ? { Authorization: `Bearer ${current}` } : {})
|
||||||
},
|
},
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
body: JSON.stringify({ message: question }),
|
body: JSON.stringify({ message: question, ...(conversationId ? { conversationId } : {}), entryPath: window.location.pathname }),
|
||||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)])
|
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)])
|
||||||
});
|
});
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
@@ -78,63 +154,85 @@ export default function SupportChat() {
|
|||||||
} else if (response.ok) {
|
} else if (response.ok) {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (typeof data.answer === 'string') answer = data.answer;
|
if (typeof data.answer === 'string') answer = data.answer;
|
||||||
|
if (typeof data.conversationId === 'string') { setConversationId(data.conversationId); try { localStorage.setItem('canina-support-conversation', data.conversationId); } catch {} }
|
||||||
|
setContextLimited(data.contextLimited === true);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// safe fallback kept
|
// safe fallback kept
|
||||||
}
|
}
|
||||||
if (!controller.signal.aborted && token() === current) {
|
if (!controller.signal.aborted && token() === current) {
|
||||||
setRows((r) => [...r.slice(-9), { question, answer }]);
|
setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question && next[i].answer === 'در حال بررسی…') next[i] = { question, answer }; return next; });
|
||||||
}
|
}
|
||||||
if (pending.current === controller) setBusy(false);
|
if (pending.current === controller) setBusy(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!config?.enabled) return configError ? <span role="status" className="sr-only">تنظیمات پشتیبان هوشمند در دسترس نیست.</span> : null;
|
||||||
|
const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon];
|
||||||
return (
|
return (
|
||||||
<aside dir="rtl" className="fixed bottom-20 left-5 z-[9999] max-w-[calc(100vw-2.5rem)] font-vazir select-none">
|
<aside dir="rtl" className="fixed bottom-6 left-6 z-40 max-w-[calc(100vw-2.5rem)] font-vazir select-none">
|
||||||
{/* Floating Launcher Button */}
|
{/* 2-Piece Unified Floating Action Pill */}
|
||||||
<button
|
<div className="flex items-center rounded-full bg-slate-900/90 p-1 text-white shadow-2xl backdrop-blur-md border border-white/10">
|
||||||
type="button"
|
{/* Piece 1: Online Support Chat Button */}
|
||||||
onClick={() => setOpen(!open)}
|
<button
|
||||||
aria-expanded={open}
|
type="button"
|
||||||
aria-label={open ? 'بستن گفتگو با پشتیبان' : 'گفتگو با پشتیبان هوشمند'}
|
onClick={() => setOpen(!open)}
|
||||||
className={`group relative flex items-center gap-2.5 rounded-full px-4 py-3 text-white shadow-2xl transition-all duration-300 ${
|
aria-expanded={open}
|
||||||
open
|
aria-label={open ? 'بستن گفتگو با پشتیبان' : (config.label || 'پشتیبان آنلاین')}
|
||||||
? 'bg-medical-gray-800 hover:bg-medical-gray-900 rotate-0'
|
className={`flex items-center gap-2 rounded-full px-4 py-2.5 text-xs sm:text-sm font-bold transition-all duration-200 ${
|
||||||
: 'bg-canina-blue hover:bg-opacity-95 hover:shadow-canina-blue/30 hover:scale-105'
|
open
|
||||||
}`}
|
? 'bg-rose-600 text-white shadow-md'
|
||||||
>
|
: 'bg-transparent text-white hover:bg-white/10 active:scale-95'
|
||||||
<span className="relative flex h-3 w-3">
|
}`}
|
||||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-canina-gold opacity-75"></span>
|
>
|
||||||
<span className="relative inline-flex h-3 w-3 rounded-full bg-canina-gold"></span>
|
|
||||||
</span>
|
|
||||||
<svg className="h-5 w-5 transition-transform duration-300 group-hover:scale-110" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
|
||||||
{open ? (
|
{open ? (
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
|
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
) : (
|
) : (
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
<MessageSquare className="h-4 w-4 text-amber-400" />
|
||||||
)}
|
)}
|
||||||
</svg>
|
<span>{open ? 'بستن گفتگو' : (config.label || 'پشتیبان آنلاین')}</span>
|
||||||
<span className="text-sm font-semibold tracking-wide">{open ? 'بستن گفتگو' : 'گفتگو با پشتیبان'}</span>
|
</button>
|
||||||
</button>
|
|
||||||
|
{/* Divider */}
|
||||||
|
<div className="h-4 w-px bg-white/20 mx-1" />
|
||||||
|
|
||||||
|
{/* Piece 2: Phone Advisor Request Button */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.dispatchEvent(new CustomEvent('canina-open-advisor-modal'));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label="درخواست مشاوره تلفنی"
|
||||||
|
className="flex items-center gap-2 rounded-full px-4 py-2.5 text-xs sm:text-sm font-bold bg-transparent text-white hover:bg-white/10 active:scale-95 transition-all duration-200"
|
||||||
|
>
|
||||||
|
<PhoneCall className="h-4 w-4 text-emerald-400" />
|
||||||
|
<span>درخواست مشاوره تلفنی</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Chat Window */}
|
{/* Chat Window */}
|
||||||
{open && (
|
{open && (
|
||||||
<section
|
<section
|
||||||
aria-label="پشتیبان کنینا"
|
aria-label="پشتیبان کنینا"
|
||||||
className="absolute bottom-16 left-0 flex flex-col w-[360px] sm:w-[400px] h-[540px] max-h-[calc(100vh-7rem)] rounded-2xl border border-medical-gray-200 bg-white/95 backdrop-blur-md shadow-2xl overflow-hidden transition-all duration-300 animate-in fade-in slide-in-from-bottom-4"
|
className="absolute bottom-16 left-0 flex flex-col w-[min(360px,calc(100vw-2rem))] sm:w-[400px] h-[540px] max-h-[calc(100vh-7rem)] rounded-2xl border border-medical-gray-200 bg-white/95 backdrop-blur-md shadow-2xl overflow-hidden transition-all duration-300 animate-in fade-in slide-in-from-bottom-4"
|
||||||
>
|
>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="bg-gradient-to-r from-canina-blue to-medical-gray-800 text-white p-4 flex items-center justify-between border-b border-white/10">
|
<div className="bg-gradient-to-r from-canina-blue to-medical-gray-800 text-white p-4 flex items-center justify-between border-b border-white/10">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="relative flex h-10 w-10 items-center justify-center rounded-xl bg-white/10 border border-white/20 text-canina-gold font-bold text-lg">
|
<div className="relative flex h-10 w-10 items-center justify-center rounded-xl bg-white/10 border border-white/20 text-canina-gold font-bold text-lg">
|
||||||
C
|
<span aria-label="آیکون دستیار">{botIcon}</span>
|
||||||
<span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-canina-blue bg-emerald-500"></span>
|
<span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-canina-blue bg-emerald-500"></span>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-sm font-bold flex items-center gap-1.5">
|
<h3 className="text-sm font-bold flex items-center gap-1.5">
|
||||||
پشتیبان هوشمند کنینا
|
{config.label}
|
||||||
<span className="text-[10px] bg-canina-gold/20 text-canina-gold px-1.5 py-0.5 rounded border border-canina-gold/30">AI</span>
|
<span className="text-[10px] bg-canina-gold/20 text-canina-gold px-1.5 py-0.5 rounded border border-canina-gold/30">AI</span>
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-[11px] text-white/70">راهنمای محصولات و سلامت پت</p>
|
<p className="text-[11px] text-white/70">راهنمای محصولات و سلامت پت</p>
|
||||||
|
<button type="button" className="text-[11px] text-canina-gold hover:underline" onClick={() => { setRows([]); setConversationId(''); setContextLimited(false); try { localStorage.removeItem('canina-support-conversation'); } catch {} }}>گفتگوی جدید</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@@ -159,7 +257,7 @@ export default function SupportChat() {
|
|||||||
<svg className="h-4 w-4 text-canina-blue shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
<svg className="h-4 w-4 text-canina-blue shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
||||||
</svg>
|
</svg>
|
||||||
<span>پشتیبان هوشمند کنینا · هر پیام مستقل است. اطلاعات تغذیه و مکملها جایگزین تشخیص دامپزشک نیست.</span>
|
<span>پشتیبان هوشمند کنینا · پیامها در همین گفتوگو حفظ میشوند. اطلاعات تغذیه و مکملها جایگزین تشخیص دامپزشک نیست.</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{rows.length === 0 && (
|
{rows.length === 0 && (
|
||||||
@@ -187,18 +285,7 @@ export default function SupportChat() {
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{busy && (
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<div className="rounded-2xl rounded-tl-sm bg-medical-gray-100 border border-medical-gray-200 px-4 py-2.5 text-medical-gray-600 flex items-center gap-1.5 shadow-sm">
|
|
||||||
<span className="text-[11px]">در حال بررسی و تنظیم پاسخ</span>
|
|
||||||
<span className="flex gap-1 mr-1">
|
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce"></span>
|
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce [animation-delay:0.2s]"></span>
|
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-canina-blue animate-bounce [animation-delay:0.4s]"></span>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Input & Footer */}
|
{/* Input & Footer */}
|
||||||
@@ -231,6 +318,7 @@ export default function SupportChat() {
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
{contextLimited && <div role="status" className="mb-2 rounded bg-amber-50 p-2 text-[11px] text-amber-800">برای ادامه دقیقتر، گفتگوی جدیدی شروع کنید یا با پشتیبانی تماس بگیرید.</div>}
|
||||||
<div className="mt-2 flex items-center justify-between px-1 text-[11px] text-medical-gray-500">
|
<div className="mt-2 flex items-center justify-between px-1 text-[11px] text-medical-gray-500">
|
||||||
<span>Shift+Enter خط جدید</span>
|
<span>Shift+Enter خط جدید</span>
|
||||||
<a
|
<a
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
import ArchivePage from "../ArchivePage";
|
import ArchivePage, { orderProductsByAvailability } from "../ArchivePage";
|
||||||
import { productService } from "../../lib/services/productService";
|
import { productService } from "../../lib/services/productService";
|
||||||
import { useCartStore } from "../../lib/store/cartStore";
|
import { useCartStore } from "../../lib/store/cartStore";
|
||||||
import { usePetStore } from "../../lib/store/usePetStore";
|
import { usePetStore } from "../../lib/store/usePetStore";
|
||||||
@@ -117,6 +117,32 @@ const mockProducts = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
it("puts available products first while preserving descending-price sort order within groups", () => {
|
||||||
|
const sortedByPriceDesc = [
|
||||||
|
{ id: "out-high", stock: 0 },
|
||||||
|
{ id: "in-mid", stock: 5 },
|
||||||
|
{ id: "in-low", stock: 2 },
|
||||||
|
{ id: "out-low", stock: 0 },
|
||||||
|
] as any;
|
||||||
|
|
||||||
|
expect(orderProductsByAvailability(sortedByPriceDesc).map(product => product.id)).toEqual([
|
||||||
|
"in-mid", "in-low", "out-high", "out-low",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("puts available products first while preserving ascending-price sort order and groups status fields", () => {
|
||||||
|
const sortedByPriceAsc = [
|
||||||
|
{ id: "in-low", stockStatus: "IN_STOCK" },
|
||||||
|
{ id: "out-mid", stockStatus: "OUT_OF_STOCK" },
|
||||||
|
{ id: "in-high", stockStatus: "IN_STOCK" },
|
||||||
|
{ id: "out-discontinued", stockStatus: "DISCONTINUED" },
|
||||||
|
] as any;
|
||||||
|
|
||||||
|
expect(orderProductsByAvailability(sortedByPriceAsc).map(product => product.id)).toEqual([
|
||||||
|
"in-low", "in-high", "out-mid", "out-discontinued",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
describe("ArchivePage Component", () => {
|
describe("ArchivePage Component", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
|||||||
@@ -43,13 +43,13 @@ export function generateOrganizationSchema(options: OrganizationSchemaOptions =
|
|||||||
options.description ||
|
options.description ||
|
||||||
'نماینده رسمی و انحصاری مکملهای دارویی و درمانی Canina pharma GmbH آلمان در ایران.',
|
'نماینده رسمی و انحصاری مکملهای دارویی و درمانی Canina pharma GmbH آلمان در ایران.',
|
||||||
telephone: options.telephone || '+989211231517',
|
telephone: options.telephone || '+989211231517',
|
||||||
email: options.email || 'caninairan@gmail.com',
|
email: options.email || undefined,
|
||||||
address: {
|
address: {
|
||||||
'@type': 'PostalAddress',
|
'@type': 'PostalAddress',
|
||||||
streetAddress: options.address?.streetAddress || 'جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵',
|
streetAddress: options.address?.streetAddress || undefined,
|
||||||
addressLocality: options.address?.addressLocality || 'تهران',
|
addressLocality: options.address?.addressLocality || 'تهران',
|
||||||
addressRegion: options.address?.addressRegion || 'تهران',
|
addressRegion: options.address?.addressRegion || 'تهران',
|
||||||
postalCode: options.address?.postalCode || '1967812345',
|
postalCode: options.address?.postalCode || undefined,
|
||||||
addressCountry: options.address?.addressCountry || 'IR',
|
addressCountry: options.address?.addressCountry || 'IR',
|
||||||
},
|
},
|
||||||
sameAs: options.sameAs || [
|
sameAs: options.sameAs || [
|
||||||
@@ -85,10 +85,10 @@ export function generateLocalBusinessSchema(options: OrganizationSchemaOptions =
|
|||||||
priceRange: '$$',
|
priceRange: '$$',
|
||||||
address: {
|
address: {
|
||||||
'@type': 'PostalAddress',
|
'@type': 'PostalAddress',
|
||||||
streetAddress: options.address?.streetAddress || 'تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹',
|
streetAddress: options.address?.streetAddress || undefined,
|
||||||
addressLocality: options.address?.addressLocality || 'تهران',
|
addressLocality: options.address?.addressLocality || 'تهران',
|
||||||
addressRegion: options.address?.addressRegion || 'تهران',
|
addressRegion: options.address?.addressRegion || 'تهران',
|
||||||
postalCode: options.address?.postalCode || '1967812345',
|
postalCode: options.address?.postalCode || undefined,
|
||||||
addressCountry: 'IR',
|
addressCountry: 'IR',
|
||||||
},
|
},
|
||||||
geo: {
|
geo: {
|
||||||
|
|||||||
@@ -62,8 +62,8 @@ export const useSettingsStore = create<SettingsStore>()((set, get) => ({
|
|||||||
texts[key.toUpperCase()];
|
texts[key.toUpperCase()];
|
||||||
if (value === undefined || value === null || value === '') {
|
if (value === undefined || value === null || value === '') {
|
||||||
// Special aliases
|
// Special aliases
|
||||||
if (key === 'contact_phone') return texts['CONTACT_PHONE'] || texts['footer_phone'] || texts['maintenance_contact_phone'] || fallback;
|
if (key === 'contact_phone') return texts['CONTACT_PHONE'] || fallback;
|
||||||
if (key === 'contact_phone_link') return texts['CONTACT_PHONE_LINK'] || texts['maintenance_contact_phone_link'] || (texts['contact_phone'] ? `tel:${texts['contact_phone'].replace(/[^0-9+]/g, '')}` : fallback);
|
if (key === 'contact_phone_link') return texts['CONTACT_PHONE_LINK'] || fallback;
|
||||||
if (key === 'site_logo') return texts['BRAND_LOGO_URL'] || texts['brand_logo_url'] || fallback;
|
if (key === 'site_logo') return texts['BRAND_LOGO_URL'] || texts['brand_logo_url'] || fallback;
|
||||||
if (key === 'site_logo_text_en') return texts['BRAND_LOGO_TEXT_EN'] || fallback;
|
if (key === 'site_logo_text_en') return texts['BRAND_LOGO_TEXT_EN'] || fallback;
|
||||||
if (key === 'site_logo_text_fa') return texts['BRAND_LOGO_TEXT_FA'] || texts['brand_name_fa'] || fallback;
|
if (key === 'site_logo_text_fa') return texts['BRAND_LOGO_TEXT_FA'] || texts['brand_name_fa'] || fallback;
|
||||||
|
|||||||
+4
-4
@@ -31,7 +31,7 @@ server {
|
|||||||
|
|
||||||
# Uploads Static Files
|
# Uploads Static Files
|
||||||
location /uploads {
|
location /uploads {
|
||||||
proxy_pass http://__BACKEND_HOST__:3000;
|
proxy_pass http://backend_stage:3000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection 'upgrade';
|
proxy_set_header Connection 'upgrade';
|
||||||
@@ -42,7 +42,7 @@ server {
|
|||||||
|
|
||||||
# Backend API
|
# Backend API
|
||||||
location /api {
|
location /api {
|
||||||
proxy_pass http://__BACKEND_HOST__:3000;
|
proxy_pass http://backend_stage:3000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection 'upgrade';
|
proxy_set_header Connection 'upgrade';
|
||||||
@@ -73,7 +73,7 @@ server {
|
|||||||
|
|
||||||
# Uploads Static Files for Admin
|
# Uploads Static Files for Admin
|
||||||
location /uploads {
|
location /uploads {
|
||||||
proxy_pass http://__BACKEND_HOST__:3000;
|
proxy_pass http://backend_stage:3000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection 'upgrade';
|
proxy_set_header Connection 'upgrade';
|
||||||
@@ -84,7 +84,7 @@ server {
|
|||||||
|
|
||||||
# Backend API for Admin
|
# Backend API for Admin
|
||||||
location /api {
|
location /api {
|
||||||
proxy_pass http://__BACKEND_HOST__:3000;
|
proxy_pass http://backend_stage:3000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection 'upgrade';
|
proxy_set_header Connection 'upgrade';
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Stage-only storefront repair; retain the deployed admin and nginx artifacts.
|
||||||
|
ARG STAGE_BASE_IMAGE
|
||||||
|
FROM node:20-alpine AS app-builder
|
||||||
|
WORKDIR /app
|
||||||
|
ARG NPM_REGISTRY=https://registry.parsaaghayi.ir/repository/npm/
|
||||||
|
RUN npm config set registry "$NPM_REGISTRY" && npm config set strict-ssl false
|
||||||
|
COPY frontend/application/package*.json ./
|
||||||
|
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||||
|
COPY frontend/application ./
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
ENV NEXT_PUBLIC_API_URL=https://stageapi.canina.ir/api
|
||||||
|
ENV NEXT_PUBLIC_SITE_URL=https://stage.canina.ir
|
||||||
|
ENV NEXT_PUBLIC_APP_ENV=staging
|
||||||
|
RUN npm run build
|
||||||
|
FROM ${STAGE_BASE_IMAGE}
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=app-builder /app ./
|
||||||
|
ENV NEXT_PUBLIC_SITE_URL=https://stage.canina.ir
|
||||||
|
ENV NEXT_PUBLIC_APP_ENV=staging
|
||||||
@@ -27,10 +27,16 @@ services:
|
|||||||
NPM_REGISTRY: ${NPM_REGISTRY:-}
|
NPM_REGISTRY: ${NPM_REGISTRY:-}
|
||||||
container_name: canino_backend_prod
|
container_name: canino_backend_prod
|
||||||
restart: always
|
restart: always
|
||||||
|
env_file:
|
||||||
|
- path: .support-chat.env
|
||||||
|
required: false
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
- NODE_ENV=production
|
||||||
- ENABLE_SWAGGER=false
|
- ENABLE_SWAGGER=false
|
||||||
- DATABASE_URL=postgresql://canino_prod:caninopassword_prod@db_prod:5432/caninodb_prod?schema=public
|
- DATABASE_URL=postgresql://canino_prod:caninopassword_prod@db_prod:5432/caninodb_prod?schema=public
|
||||||
|
- SUPPORT_CHAT_URL=http://canina-bot:8643/support/ask
|
||||||
- REDIS_HOST=redis_prod
|
- REDIS_HOST=redis_prod
|
||||||
- REDIS_PORT=6379
|
- REDIS_PORT=6379
|
||||||
- PORT=3000
|
- PORT=3000
|
||||||
@@ -59,6 +65,9 @@ services:
|
|||||||
VITE_API_URL: "https://api.canina.ir"
|
VITE_API_URL: "https://api.canina.ir"
|
||||||
container_name: canino_frontend_prod
|
container_name: canino_frontend_prod
|
||||||
restart: always
|
restart: always
|
||||||
|
env_file:
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.canina-prod.rule=Host(`canina.ir`) || Host(`www.canina.ir`) || Host(`admin.canina.ir`)"
|
- "traefik.http.routers.canina-prod.rule=Host(`canina.ir`) || Host(`www.canina.ir`) || Host(`admin.canina.ir`)"
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ services:
|
|||||||
env_file:
|
env_file:
|
||||||
- path: .support-chat.env
|
- path: .support-chat.env
|
||||||
required: false
|
required: false
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
dns:
|
dns:
|
||||||
- 217.218.127.127
|
- 217.218.127.127
|
||||||
- 217.218.155.155
|
- 217.218.155.155
|
||||||
@@ -39,6 +41,9 @@ services:
|
|||||||
- REDIS_HOST=redis_stage
|
- REDIS_HOST=redis_stage
|
||||||
- REDIS_PORT=6379
|
- REDIS_PORT=6379
|
||||||
- PORT=3000
|
- PORT=3000
|
||||||
|
- FRONTEND_URL=https://stage.canina.ir
|
||||||
|
# Code-only stage startup: schema/seed changes require separate authorization.
|
||||||
|
command: ["node", "dist/main.js"]
|
||||||
volumes:
|
volumes:
|
||||||
- canina_stage_uploads:/app/uploads
|
- canina_stage_uploads:/app/uploads
|
||||||
- /opt/services/proxy/certs/canina:/app/ssl_certs
|
- /opt/services/proxy/certs/canina:/app/ssl_certs
|
||||||
@@ -64,6 +69,9 @@ services:
|
|||||||
VITE_API_URL: "https://stageapi.canina.ir"
|
VITE_API_URL: "https://stageapi.canina.ir"
|
||||||
container_name: canino_frontend_stage
|
container_name: canino_frontend_stage
|
||||||
restart: always
|
restart: always
|
||||||
|
env_file:
|
||||||
|
- path: .revalidation.env
|
||||||
|
required: false
|
||||||
dns:
|
dns:
|
||||||
- 217.218.127.127
|
- 217.218.127.127
|
||||||
- 217.218.155.155
|
- 217.218.155.155
|
||||||
|
|||||||
+84
-16
@@ -1,6 +1,28 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
|
# CI-only code restoration: isolate Stage before all legacy shared side effects.
|
||||||
|
if [ "${1:-}" = develop ]; then
|
||||||
|
SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
exec bash "$SCRIPT_DIR/release-corporate-stage.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Explicit no-data-write stage rollout. Run only after testing and pushing HEAD.
|
||||||
|
if [ "${2:-}" = "stage-backend-only" ]; then
|
||||||
|
[ "${1:-}" = "develop" ] || exit 2
|
||||||
|
cd /opt/services/canina/stage
|
||||||
|
exec 9>/opt/services/canina/stage-backend-deploy.lock
|
||||||
|
flock -n 9 || { echo "Stage deployment already in progress"; exit 1; }
|
||||||
|
[ "$(git branch --show-current)" = develop ]
|
||||||
|
git fetch origin develop
|
||||||
|
[ "$(git rev-parse HEAD)" = "$(git rev-parse origin/develop)" ]
|
||||||
|
git diff --quiet -- backend scripts/compose.stage.yml scripts/deploy.sh
|
||||||
|
# Read tracked compose directly; preserve generated config and nginx.
|
||||||
|
docker compose -p stage -f scripts/compose.stage.yml --project-directory . build backend_stage
|
||||||
|
docker compose -p stage -f scripts/compose.stage.yml --project-directory . up -d --no-deps --remove-orphans backend_stage
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
export DOCKER_BUILDKIT=1
|
export DOCKER_BUILDKIT=1
|
||||||
export COMPOSE_DOCKER_CLI_BUILD=1
|
export COMPOSE_DOCKER_CLI_BUILD=1
|
||||||
|
|
||||||
@@ -45,11 +67,51 @@ else
|
|||||||
cd "$TARGET_DIR"
|
cd "$TARGET_DIR"
|
||||||
git fetch origin "$BRANCH"
|
git fetch origin "$BRANCH"
|
||||||
git reset --hard "origin/$BRANCH"
|
git reset --hard "origin/$BRANCH"
|
||||||
cd -
|
cd -
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cd "$TARGET_DIR"
|
cd "$TARGET_DIR"
|
||||||
|
|
||||||
|
# Capture the bot key from Docker before recreating the bot; runner mounts may not include the host env file.
|
||||||
|
if docker inspect canina-bot >/dev/null 2>&1; then
|
||||||
|
LIVE_BOT_KEY=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' canina-bot | awk -F= '$1 == "SUPPORT_INTERNAL_KEY" {print substr($0, index($0, "=") + 1); exit}')
|
||||||
|
if [ -n "$LIVE_BOT_KEY" ]; then
|
||||||
|
grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp 2>/dev/null || true
|
||||||
|
printf 'SUPPORT_CHAT_KEY=%s
|
||||||
|
' "$LIVE_BOT_KEY" >> .support-chat.env.tmp
|
||||||
|
mv .support-chat.env.tmp .support-chat.env
|
||||||
|
chmod 600 .support-chat.env
|
||||||
|
fi
|
||||||
|
unset LIVE_BOT_KEY
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Inject support-chat runtime configuration from CI/CD without committing secrets.
|
||||||
|
# The bot is the runtime owner of the internal key; synchronize only the
|
||||||
|
# matching value into the colocated backend env file, never into Git or logs.
|
||||||
|
BOT_ENV="/opt/services/ai/canina-bot/support.env"
|
||||||
|
if [ -r "$BOT_ENV" ]; then
|
||||||
|
BOT_KEY=$(awk -F= '$1 == "SUPPORT_INTERNAL_KEY" {print substr($0, index($0, "=") + 1); exit}' "$BOT_ENV")
|
||||||
|
if [ -n "$BOT_KEY" ]; then
|
||||||
|
touch .support-chat.env
|
||||||
|
grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp || true
|
||||||
|
printf "SUPPORT_CHAT_KEY=%s\n" "$BOT_KEY" >> .support-chat.env.tmp
|
||||||
|
mv .support-chat.env.tmp .support-chat.env
|
||||||
|
chmod 600 .support-chat.env
|
||||||
|
fi
|
||||||
|
unset BOT_KEY
|
||||||
|
fi
|
||||||
|
if [ -n "${SUPPORT_CHAT_KEY:-}" ]; then
|
||||||
|
touch .support-chat.env
|
||||||
|
grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp || true
|
||||||
|
printf 'SUPPORT_CHAT_KEY=%s\n' "$SUPPORT_CHAT_KEY" >> .support-chat.env.tmp
|
||||||
|
mv .support-chat.env.tmp .support-chat.env
|
||||||
|
chmod 600 .support-chat.env
|
||||||
|
fi
|
||||||
|
if [ ! -s .support-chat.env ]; then
|
||||||
|
echo "ERROR: missing .support-chat.env / SUPPORT_CHAT_KEY; refusing deployment" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
# ✅ فایلهای کانفیگ را از پوشهی scripts مخزن به TARGET_DIR کپی میکنیم
|
# ✅ فایلهای کانفیگ را از پوشهی scripts مخزن به TARGET_DIR کپی میکنیم
|
||||||
echo "Copying configuration files in $TARGET_DIR..."
|
echo "Copying configuration files in $TARGET_DIR..."
|
||||||
cp "scripts/$COMPOSE_FILE" "docker-compose.yml"
|
cp "scripts/$COMPOSE_FILE" "docker-compose.yml"
|
||||||
@@ -69,30 +131,36 @@ docker compose --progress plain build \
|
|||||||
--build-arg VITE_API_URL="${API_URL}" \
|
--build-arg VITE_API_URL="${API_URL}" \
|
||||||
${NPM_REGISTRY_ARG}
|
${NPM_REGISTRY_ARG}
|
||||||
|
|
||||||
|
echo "Building support-chat bot image from committed source..."
|
||||||
|
BOT_IMAGE="canina-support-bot:${BRANCH}"
|
||||||
|
DOCKER_BUILDKIT=0 docker build --pull=false -f scripts/support-chat/Dockerfile -t "${BOT_IMAGE}" .
|
||||||
|
BOT_ENV="${TARGET_DIR}/.support-bot.runtime.env"
|
||||||
|
docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' canina-bot > "${BOT_ENV}"
|
||||||
|
chmod 600 "${BOT_ENV}"
|
||||||
echo "Starting containers..."
|
echo "Starting containers..."
|
||||||
docker compose up -d --remove-orphans
|
docker compose up -d --remove-orphans
|
||||||
|
echo "Starting support-chat bot container..."
|
||||||
|
docker rm -f canina-bot >/dev/null 2>&1 || true
|
||||||
|
docker run -d --name canina-bot --restart unless-stopped --env-file "${BOT_ENV}" -e HERMES_HOME=/opt/data -e HERMES_RUNTIME_DIR=/opt/hermes/tools -e API_SERVER_HOST=0.0.0.0 -e API_SERVER_PORT=8642 --network traefik_public -v canina_bot_data:/opt/data "${BOT_IMAGE}" gateway run
|
||||||
|
docker network connect --ip 172.22.0.15 vpn_net canina-bot
|
||||||
|
rm -f "${BOT_ENV}"
|
||||||
echo "Waiting for backend to start..."
|
echo "Waiting for backend to start..."
|
||||||
sleep 15
|
sleep 15
|
||||||
|
|
||||||
echo "Running database migrations..."
|
# Apply committed Prisma migrations as part of the CI/CD deployment.
|
||||||
if [ "$BRANCH" == "develop" ]; then
|
# This is intentionally migrate deploy (not db push): it is repeatable,
|
||||||
# Staging: use db push (fast, schema sync) then seed
|
# fail-closed, and applies only migrations already reviewed and committed.
|
||||||
echo "[STAGING] Running prisma db push..."
|
echo "Applying committed database migrations..."
|
||||||
docker exec "$CONTAINER_PREFIX" npx prisma db push || true
|
if [ "$BRANCH" = "main" ]; then
|
||||||
|
docker exec "${CONTAINER_PREFIX}" npx prisma migrate resolve --applied 20261013210253_add_admin_modules >/dev/null 2>&1 || true
|
||||||
echo "[STAGING] Running prisma db seed..."
|
|
||||||
docker exec "$CONTAINER_PREFIX" npx prisma db seed || true
|
|
||||||
else
|
|
||||||
# Production: use db push to sync schema additions without data loss
|
|
||||||
echo "[PRODUCTION] Running prisma db push to ensure schema is up to date..."
|
|
||||||
docker exec "$CONTAINER_PREFIX" npx prisma db push --skip-generate || true
|
|
||||||
echo "[PRODUCTION] Seeder skipped to protect production data."
|
|
||||||
fi
|
fi
|
||||||
|
docker exec "${CONTAINER_PREFIX}" npx prisma migrate deploy
|
||||||
|
|
||||||
|
# Code-only deployment: seed and destructive data changes are not performed here.
|
||||||
|
|
||||||
# Auto-cleanup old docker builder cache to keep disk healthy (keeps latest 6GB)
|
# Auto-cleanup old docker builder cache to keep disk healthy (keeps latest 6GB)
|
||||||
echo "Cleaning up old docker build cache..."
|
echo "Cleaning up old docker build cache..."
|
||||||
docker builder prune -af --keep-storage 6GB 2>/dev/null || true
|
docker builder prune -af --keep-storage 6GB 2>/dev/null || true
|
||||||
docker image prune -f 2>/dev/null || true
|
docker image prune -f 2>/dev/null || true
|
||||||
|
|
||||||
echo "Deployment for $BRANCH completed successfully!"
|
echo "Deployment for $BRANCH completed successfully!"
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Narrow code-only Stage release in the existing CI runner/daemon boundary.
|
||||||
|
set -euo pipefail
|
||||||
|
set +x
|
||||||
|
umask 077
|
||||||
|
[[ ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && ${DEPLOY_SHA:-} =~ ^[0-9a-f]{40}$ ]] || exit 2
|
||||||
|
STAGE_DIR=/opt/services/canina/stage
|
||||||
|
# Alpine runner has BusyBox timeout; supervision needs GNU --foreground.
|
||||||
|
if ! timeout --help 2>&1 | grep -q -- --foreground; then
|
||||||
|
apk add --no-cache coreutils
|
||||||
|
fi
|
||||||
|
timeout --help 2>&1 | grep -q -- --foreground || exit 2
|
||||||
|
# The runner and host share a daemon, not a filesystem inode. The atomic
|
||||||
|
# container name serializes runners; the bind-mounted flock also fences host jobs.
|
||||||
|
# Never reclaim an existing name automatically (including stopped/stale helpers).
|
||||||
|
lock_container_id=
|
||||||
|
release_pid=
|
||||||
|
check_stage_lock() {
|
||||||
|
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.State.Running}}' "$lock_container_id") == true ]] || {
|
||||||
|
printf 'Stage host lock lost; aborting release\n' >&2
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
supervise_release() {
|
||||||
|
# A separate process group lets lock loss/signals stop the active command too.
|
||||||
|
set -m
|
||||||
|
(set +m; "$@") &
|
||||||
|
release_pid=$!
|
||||||
|
while kill -0 "$release_pid" 2>/dev/null; do
|
||||||
|
check_stage_lock || return 1
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
local status=0
|
||||||
|
wait "$release_pid" || status=$?
|
||||||
|
release_pid=
|
||||||
|
check_stage_lock || return 1
|
||||||
|
return "$status"
|
||||||
|
}
|
||||||
|
cleanup_stage_lock() {
|
||||||
|
local status=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [[ -n $release_pid ]]; then
|
||||||
|
kill -TERM -- "-$release_pid" 2>/dev/null || :
|
||||||
|
sleep 1
|
||||||
|
kill -KILL -- "-$release_pid" 2>/dev/null || :
|
||||||
|
wait "$release_pid" 2>/dev/null || :
|
||||||
|
fi
|
||||||
|
if [[ -n $lock_container_id ]]; then
|
||||||
|
if [[ $status != 0 ]]; then
|
||||||
|
# Never emit raw helper/daemon output (image entrypoints may contain
|
||||||
|
# secrets). Classify only a bounded tail before deleting the owned ID.
|
||||||
|
local helper_log diagnostic=unavailable
|
||||||
|
helper_log=$(timeout --foreground --kill-after=2s 10 docker logs --tail 10 "$lock_container_id" 2>&1 | head -c 4096) || :
|
||||||
|
case "$helper_log" in
|
||||||
|
*'Permission denied'*) diagnostic=permission-denied ;;
|
||||||
|
*'No such file or directory'*) diagnostic=missing-host-lock ;;
|
||||||
|
*'Read-only file system'*) diagnostic=read-only-filesystem ;;
|
||||||
|
*'flock: not found'*) diagnostic=flock-unavailable ;;
|
||||||
|
*CANINA_STAGE_DEPLOY_LOCK_ACQUIRED*) diagnostic=previously-acquired ;;
|
||||||
|
?*) diagnostic=unclassified-output ;;
|
||||||
|
esac
|
||||||
|
printf 'Stage lock helper diagnostic: %s\n' "$diagnostic" >&2
|
||||||
|
fi
|
||||||
|
timeout --kill-after=2s 15 docker rm -f "$lock_container_id" >/dev/null || {
|
||||||
|
printf 'Stage lock helper cleanup failed; manual inspection required\n' >&2
|
||||||
|
[[ $status != 0 ]] || status=1
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
trap cleanup_stage_lock EXIT
|
||||||
|
trap 'exit 130' INT
|
||||||
|
trap 'exit 143' TERM
|
||||||
|
runner_image=$(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.Config.Image}}' gitea_runner)
|
||||||
|
[[ -n $runner_image ]] || exit 1
|
||||||
|
lock_container_id=$(timeout --kill-after=2s 15 docker create --name canina-stage-deploy-lock \
|
||||||
|
--pull=never --network none --cap-drop=ALL --security-opt=no-new-privileges \
|
||||||
|
--mount type=bind,src=/opt/services/canina,dst=/host-canina,readonly \
|
||||||
|
--entrypoint /bin/sh "$runner_image" -c '
|
||||||
|
# Linux flock permits an exclusive lock on a read-only descriptor. Preserve
|
||||||
|
# daemon userns remapping; require the existing host inode, never create it.
|
||||||
|
exec 9</host-canina/stage-backend-deploy.lock
|
||||||
|
flock -n 9 || exit 1
|
||||||
|
printf "CANINA_STAGE_DEPLOY_LOCK_ACQUIRED\n"
|
||||||
|
while :; do sleep 60; done
|
||||||
|
') || { printf 'Stage deployment locked or helper creation failed\n' >&2; exit 1; }
|
||||||
|
[[ -n $lock_container_id ]] || exit 1
|
||||||
|
timeout --foreground --kill-after=2s 10 docker start "$lock_container_id" >/dev/null
|
||||||
|
lock_acquired=false
|
||||||
|
for lock_attempt in {1..10}; do
|
||||||
|
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.State.Running}}' "$lock_container_id") == true ]] || break
|
||||||
|
if [[ $(timeout --foreground --kill-after=2s 10 docker logs --tail 1 "$lock_container_id" 2>/dev/null) == CANINA_STAGE_DEPLOY_LOCK_ACQUIRED ]]; then
|
||||||
|
lock_acquired=true
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
[[ $lock_attempt == 10 ]] || sleep 1
|
||||||
|
done
|
||||||
|
[[ $lock_acquired == true ]] || { printf 'Stage host lock not confirmed\n' >&2; exit 1; }
|
||||||
|
release_stage() {
|
||||||
|
cd "$STAGE_DIR"
|
||||||
|
timeout --foreground --kill-after=2s 60 git fetch origin develop
|
||||||
|
[[ $(git rev-parse origin/develop) == "$DEPLOY_SHA" ]] || exit 2
|
||||||
|
RELEASE_ROOT=/opt/services/canina/cache-releases
|
||||||
|
mkdir -p "$RELEASE_ROOT"
|
||||||
|
TARGET_DIR=$(mktemp -d "$RELEASE_ROOT/$DEPLOY_SHA.corporate.XXXXXXXX")
|
||||||
|
git archive "$DEPLOY_SHA" | tar -x -C "$TARGET_DIR"
|
||||||
|
command -v python3 >/dev/null || apk add --no-cache python3
|
||||||
|
# Pin the existing frontend solely to retain operational nginx/admin artifacts.
|
||||||
|
STAGE_BASE_IMAGE="canina-stage-blog-base:$DEPLOY_SHA"
|
||||||
|
docker tag "$(docker inspect -f '{{.Image}}' canino_frontend_stage)" "$STAGE_BASE_IMAGE"
|
||||||
|
export TARGET_DIR DEPLOY_SHA STAGE_BASE_IMAGE
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, os, hashlib
|
||||||
|
from pathlib import Path
|
||||||
|
root=Path(os.environ['TARGET_DIR']); sha=os.environ['DEPLOY_SHA']
|
||||||
|
files={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(root.rglob('*')) if p.is_file() and not p.is_symlink()}
|
||||||
|
(root/'.release-manifest.json').write_text(json.dumps({'sha':sha,'files':files},sort_keys=True))
|
||||||
|
# Preserve operational runtime/env files; override only the incorrect Stage route.
|
||||||
|
service={'build':{'context':str(root/'backend'),'labels':{'org.opencontainers.image.revision':sha},'args':{'NPM_REGISTRY':'https://registry.parsaaghayi.ir/repository/npm/'}},'labels':{'ir.canina.release.sha':sha},'command':['node','dist/main.js']}
|
||||||
|
service['environment']={'FRONTEND_INTERNAL_URL':'http://frontend_stage:3000'}
|
||||||
|
frontend={'build':{'context':str(root),'dockerfile':'scripts/Dockerfile.blog-stage','args':{'STAGE_BASE_IMAGE':os.environ['STAGE_BASE_IMAGE']},'labels':{'org.opencontainers.image.revision':sha}},'labels':{'ir.canina.release.sha':sha}}
|
||||||
|
(root/'release.override.json').write_text(json.dumps({'services':{'backend_stage':service,'frontend_stage':frontend}}))
|
||||||
|
PY
|
||||||
|
compose=(docker compose -p stage --project-directory "$STAGE_DIR" -f "$STAGE_DIR/docker-compose.yml" -f "$TARGET_DIR/release.override.json")
|
||||||
|
timeout --foreground --kill-after=2s 60 "${compose[@]}" config --quiet
|
||||||
|
check_stage_lock
|
||||||
|
timeout --foreground --kill-after=2s 1800 "${compose[@]}" --progress plain build backend_stage frontend_stage
|
||||||
|
check_stage_lock
|
||||||
|
# Fail closed without exposing either service's shared secret.
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, subprocess
|
||||||
|
containers=json.loads(subprocess.check_output(['docker','inspect','canino_backend_stage','canino_frontend_stage']))
|
||||||
|
envs=[dict(v.split('=',1) for v in c['Config']['Env']) for c in containers]
|
||||||
|
assert envs[0].get('REVALIDATION_SECRET') and envs[0]['REVALIDATION_SECRET']==envs[1].get('REVALIDATION_SECRET'), 'Stage revalidation secret absent or mismatched'
|
||||||
|
PY
|
||||||
|
# No migrations, seed, DB/Redis/bot recreation or host runtime file edits.
|
||||||
|
timeout --foreground --kill-after=2s 120 "${compose[@]}" up -d --no-deps --force-recreate backend_stage frontend_stage
|
||||||
|
ready=false
|
||||||
|
for attempt in {1..30}; do
|
||||||
|
check_stage_lock
|
||||||
|
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.State.Running}} {{.RestartCount}}' canino_backend_stage) == 'true 0' ]] || exit 1
|
||||||
|
if timeout --foreground --kill-after=2s 10 docker exec canino_backend_stage node -e '
|
||||||
|
const http=require("http");
|
||||||
|
const req=http.get("http://127.0.0.1:3000/api/admin/hermes/monthly-roadmap",res=>{res.resume();process.exit(res.statusCode===401?0:1)});
|
||||||
|
req.setTimeout(5000,()=>req.destroy());req.on("error",()=>process.exit(1));'; then ready=true; break; fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
[[ $ready == true ]] || exit 1
|
||||||
|
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' canino_backend_stage) == "$DEPLOY_SHA" ]]
|
||||||
|
image=$(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.Image}}' canino_backend_stage)
|
||||||
|
[[ $(timeout --foreground --kill-after=2s 10 docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image") == "$DEPLOY_SHA" ]]
|
||||||
|
# Exercise the real consumer-to-Next route without resaving any article.
|
||||||
|
for attempt in {1..30}; do
|
||||||
|
if timeout --foreground --kill-after=2s 15 docker exec canino_backend_stage node -e '
|
||||||
|
const {RevalidationService}=require("./dist/common/revalidation/revalidation.service");
|
||||||
|
(async()=>{const s=new RevalidationService(); for(const tag of ["blogs","home-data","blog-senior-dog-l-carnitine-myocardial-energy-evidence"]) if(!await s.revalidateTag(tag)) process.exit(1); for(const path of ["/blog","/blog/senior-dog-l-carnitine-myocardial-energy-evidence"]) if(!await s.revalidatePath(path)) process.exit(1);})().catch(()=>process.exit(1));'; then break; fi
|
||||||
|
[[ $attempt != 30 ]] || exit 1
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
[[ $(docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' canino_frontend_stage) == "$DEPLOY_SHA" ]]
|
||||||
|
frontend_image=$(docker inspect -f '{{.Image}}' canino_frontend_stage)
|
||||||
|
[[ $(docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$frontend_image") == "$DEPLOY_SHA" ]]
|
||||||
|
printf 'Stage blog/corporate release complete: %s backend=%s frontend=%s\n' "$DEPLOY_SHA" "$image" "$frontend_image"
|
||||||
|
}
|
||||||
|
supervise_release release_stage
|
||||||
@@ -9,7 +9,16 @@ import hermes_yaml as yaml
|
|||||||
source = yaml.safe_load(Path('/opt/data/config.yaml').read_text())
|
source = yaml.safe_load(Path('/opt/data/config.yaml').read_text())
|
||||||
home = Path('/run/canina-support')
|
home = Path('/run/canina-support')
|
||||||
home.mkdir(mode=0o700, exist_ok=True)
|
home.mkdir(mode=0o700, exist_ok=True)
|
||||||
safe = {'model': source.get('model', {}), 'web': source.get('web', {}), 'memory': {'memory_enabled': False, 'user_profile_enabled': False}, 'telemetry': {'shared_metrics': {'enabled': False, 'send': False}}, 'agent': {'max_iterations': 2}, 'compression': {'enabled': False}}
|
safe = {
|
||||||
|
'model': source.get('model', {}),
|
||||||
|
# Provider names/models are configuration; credentials remain in env.
|
||||||
|
'custom_providers': source.get('custom_providers', []),
|
||||||
|
'web': source.get('web', {}),
|
||||||
|
'memory': {'memory_enabled': False, 'user_profile_enabled': False},
|
||||||
|
'telemetry': {'shared_metrics': {'enabled': False, 'send': False}},
|
||||||
|
'agent': {'max_iterations': 2},
|
||||||
|
'compression': {'enabled': False},
|
||||||
|
}
|
||||||
p = home/'config.yaml'
|
p = home/'config.yaml'
|
||||||
p.write_text(yaml.safe_dump(safe)); p.chmod(0o600)
|
p.write_text(yaml.safe_dump(safe)); p.chmod(0o600)
|
||||||
os.environ['HERMES_HOME']=str(home)
|
os.environ['HERMES_HOME']=str(home)
|
||||||
|
|||||||
@@ -1,50 +1,46 @@
|
|||||||
"""Fail-closed domain policy; the model is never given web or execution tools."""
|
"""Fail-closed customer policy and bounded first-party link handling."""
|
||||||
import json
|
import json,re
|
||||||
import re
|
from urllib.parse import urlsplit
|
||||||
|
DENY=re.compile(r"\b(?:localhost|ssh|sql|shell|token|password|api[._-]?key)\b|رمز\s*عبور|توکن|دستور\s*سیستمی",re.I)
|
||||||
# Structural & exploit denial only: prevent URLs/links and command/injection strings.
|
ERROR=re.compile(r"hermes|provider|api.?key|traceback|exception|authentication|rate.?limit|error|failed|ناموفق|خطای اتصال",re.I)
|
||||||
DENY = re.compile(r'https?[:/]|www\.|[a-z0-9-]+\.(?:com|net|org|ir|de|io)\b|\b(?:localhost|ssh|sql|shell|token|password|api[._-]?key)\b|رمز\s*عبور|توکن|دستور\s*سیستمی', re.I)
|
SAFE_HOSTS={"canina.ir","www.canina.ir","stage.canina.ir"}
|
||||||
ERROR = re.compile(r'hermes|provider|api.?key|traceback|exception|authentication|rate.?limit|error|failed|ناموفق|خطای اتصال', re.I)
|
URL_RE=re.compile(r"https?://[^\s<>\"']+|tel:[+0-9(). *#-]{7,30}",re.I)
|
||||||
|
|
||||||
def validate_message(message):
|
def validate_message(message):
|
||||||
if not isinstance(message, str):
|
if not isinstance(message,str): raise ValueError("type")
|
||||||
raise ValueError('type')
|
s=message.strip()
|
||||||
stripped = message.strip()
|
if not 1<=len(s)<=1500 or DENY.search(s): raise ValueError("invalid")
|
||||||
if not (1 <= len(stripped) <= 1500):
|
if re.search(r"https?://|www\.", s, re.I):
|
||||||
raise ValueError('length')
|
for match in re.findall(r"https?://[^\s]+|www\.[^\s]+", s, re.I):
|
||||||
if DENY.search(stripped):
|
if not match.lower().startswith(("https://canina.ir","https://www.canina.ir","https://stage.canina.ir")): raise ValueError("external_url")
|
||||||
raise ValueError('denied_pattern')
|
return s
|
||||||
return stripped
|
def _safe_url(m):
|
||||||
|
v=m.group(0).rstrip(".,!?)")
|
||||||
|
if v.lower().startswith("tel:"):
|
||||||
|
raw=v[4:]; d=("+" if raw.strip().startswith("+") else "")+re.sub(r"[^0-9]","",raw)
|
||||||
|
return "tel:"+d if 7<=len(d.lstrip("+"))<=15 else ""
|
||||||
|
try:
|
||||||
|
p=urlsplit(v)
|
||||||
|
if p.scheme.lower()!="https" or p.hostname.lower() not in SAFE_HOSTS or p.username or p.password or p.query or p.fragment:return ""
|
||||||
|
path=p.path or "/"
|
||||||
|
return "https://"+p.hostname.lower()+path if len(path)<=256 and re.fullmatch(r"/[A-Za-z0-9_./%-]*",path) else ""
|
||||||
|
except Exception:return ""
|
||||||
|
def sanitize_answer(text): return URL_RE.sub(_safe_url,text)
|
||||||
def safe_answer(result):
|
def safe_answer(result):
|
||||||
if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False:
|
if not isinstance(result,dict) or result.get("failed") or result.get("error") or result.get("partial") or result.get("completed") is False:raise ValueError("unavailable")
|
||||||
raise ValueError('unavailable')
|
t=result.get("final_response","")
|
||||||
text = result.get('final_response', '')
|
if not isinstance(t,str) or ERROR.search(t):raise ValueError("unavailable")
|
||||||
if not isinstance(text, str) or ERROR.search(text):
|
t=re.sub(r"^```(?:json)?\s*|\s*```$","",t); a=json.loads(t).get("answer")
|
||||||
raise ValueError('unavailable')
|
if not isinstance(a,str) or not 1<=len(a.strip())<=6000 or ERROR.search(a):raise ValueError("unavailable")
|
||||||
if text.startswith('```'):
|
return sanitize_answer(a.strip())
|
||||||
text = re.sub(r'^```(?:json)?\s*|\s*```$', '', text)
|
|
||||||
obj = json.loads(text)
|
|
||||||
answer = obj.get('answer')
|
|
||||||
if not isinstance(answer, str) or not (1 <= len(answer.strip()) <= 6000) or ERROR.search(answer):
|
|
||||||
raise ValueError('unavailable')
|
|
||||||
return answer.strip()
|
|
||||||
|
|
||||||
# Search input never contains raw customer prose: only fixed product-category terms
|
|
||||||
# and recognised pet-product brands. No extract/browser URL capability exists.
|
|
||||||
def research_query(message):
|
def research_query(message):
|
||||||
if not re.search(r'مقایسه|رقیب|جستجو|compare|research', message, re.I):
|
try: m=validate_message(message).lower()
|
||||||
return None
|
except ValueError: return None
|
||||||
validate_message(message)
|
if re.search(r"تماس|شماره|آدرس|contact|phone|address|shomare|tamas|telefon",m):return "Canina official contact phone address"
|
||||||
brands = [name for pattern, name in [(r'رویال|royal', 'Royal Canin'), (r'بیفار|beaphar', 'Beaphar'), (r'وت.?اکسپرت|vet.?expert', 'VetExpert')] if re.search(pattern, message, re.I)]
|
if not re.search(r"مقایسه|مقایسه|رقیب|رقبا|محصول رقیب|جستجو|compare|competitor|competitors|rival|rivals|research|raqib|moghayese",m,re.I):return None
|
||||||
return 'pet dog cat supplement product comparison Canina ' + ' '.join(brands)
|
brands=" ".join(n for pat,n in [(r"رویال|royal","Royal Canin"),(r"بیفار|beaphar","Beaphar"),(r"وت.?اکسپرت|vet.?expert","VetExpert")] if re.search(pat,m,re.I))
|
||||||
|
return "public pet supplement competitor product comparison Canina "+brands
|
||||||
|
|
||||||
|
|
||||||
def safe_intent(result):
|
def safe_intent(result):
|
||||||
if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False:
|
if not isinstance(result,dict) or result.get("failed") or result.get("error") or result.get("partial") or result.get("completed") is False:raise ValueError("unavailable")
|
||||||
raise ValueError('unavailable')
|
o=json.loads(result.get("final_response",""))
|
||||||
obj = json.loads(result.get('final_response', ''))
|
if not isinstance(o,dict) or set(o)!={"intent"} or o["intent"] not in ("public","orders","wallet","profile"):raise ValueError("intent")
|
||||||
if not isinstance(obj, dict) or set(obj) != {'intent'} or obj['intent'] not in ('public', 'orders', 'wallet'):
|
return o["intent"]
|
||||||
raise ValueError('intent')
|
|
||||||
return obj['intent']
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Server-owned configured provider catalog. Never accepts endpoint URLs."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from hermes_cli.config import load_config
|
||||||
|
from hermes_cli.runtime_provider import resolve_runtime_provider
|
||||||
|
|
||||||
|
_cache = (0, [])
|
||||||
|
_SAFE = re.compile(r'^[\w .:/@+\[\]()-]{1,160}$', re.ASCII)
|
||||||
|
|
||||||
|
def configured_catalog():
|
||||||
|
global _cache
|
||||||
|
if time.monotonic() - _cache[0] < 60:
|
||||||
|
return _cache[1]
|
||||||
|
result = []
|
||||||
|
config = load_config()
|
||||||
|
for provider in config.get('custom_providers', []):
|
||||||
|
name = provider.get('name', '')
|
||||||
|
if not _SAFE.fullmatch(name) or '://' in name:
|
||||||
|
continue
|
||||||
|
pid = 'configured-' + hashlib.sha256(name.encode()).hexdigest()[:16]
|
||||||
|
try:
|
||||||
|
runtime = resolve_runtime_provider(requested='custom:' + name)
|
||||||
|
endpoint = runtime['base_url'].rstrip('/') + '/models'
|
||||||
|
req = urllib.request.Request(endpoint, headers={'Authorization': 'Bearer ' + runtime['api_key']})
|
||||||
|
# Endpoint comes exclusively from server configuration, never request data.
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
return None
|
||||||
|
with urllib.request.build_opener(NoRedirect).open(req, timeout=8) as response:
|
||||||
|
raw = response.read(2000000)
|
||||||
|
live = {m.get('id') for m in json.loads(raw).get('data', []) if isinstance(m, dict)}
|
||||||
|
models = [m for m in provider.get('models', []) if isinstance(m, str) and _SAFE.fullmatch(m) and '://' not in m and m in live]
|
||||||
|
if models:
|
||||||
|
result.append({'id': pid, 'label': name, 'models': sorted(set(models))})
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if not result:
|
||||||
|
raise ValueError('catalog unavailable')
|
||||||
|
_cache = (time.monotonic(), result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def selected_runtime(selection):
|
||||||
|
if not isinstance(selection, dict) or set(selection) != {'provider', 'model'}:
|
||||||
|
raise ValueError('selection')
|
||||||
|
catalog = configured_catalog()
|
||||||
|
item = next((p for p in catalog if p['id'] == selection['provider'] and selection['model'] in p['models']), None)
|
||||||
|
if item is None:
|
||||||
|
raise ValueError('selection')
|
||||||
|
return {'default': selection['model']}, resolve_runtime_provider(requested='custom:' + item['label'], target_model=selection['model'])
|
||||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user