Compare commits
23
Commits
36eda8653e
...
39c62834e7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39c62834e7 | ||
|
|
26792f9a37 | ||
|
|
631a3267d1 | ||
|
|
b731fe43aa | ||
|
|
15cbd62997 | ||
|
|
e6aa4c64f0 | ||
|
|
9127fa334b | ||
|
|
9a86f63f48 | ||
|
|
29398a445b | ||
|
|
bb8fd489de | ||
|
|
86e9ee6c2c | ||
|
|
adb63447ca | ||
|
|
c1b38e1737 | ||
|
|
be7ae0a1d8 | ||
|
|
bbbedc6059 | ||
|
|
f5d68d83fc | ||
|
|
f15ebb72ea | ||
|
|
8590579605 | ||
|
|
3863c5e7d1 | ||
|
|
e6f9876177 | ||
|
|
fddf22d7fe | ||
|
|
ada9a1f21f | ||
|
|
2f11105628 |
@@ -41,11 +41,19 @@ Legacy CRM UI (`components/ui/*`, `.crm-*`, `.btn` / `.field` in `styles/`) rema
|
||||
6. **24-column grid only**
|
||||
Page layout on migrated screens uses Ant Grid: `a-row` / `a-col` with the **24-column** system (`:span`, `:xs`, `:sm`, `:md`, `:lg`, `:xl`). Do not invent parallel flex/grid CSS layouts for page chrome.
|
||||
|
||||
7. **RTL + locale**
|
||||
App root is wrapped with `<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">`. Do not override direction to LTR on whole pages; use local `direction="ltr"` only for inherently LTR fragments (e.g. phone numbers, codes).
|
||||
7. **RTL + locale + StyleProvider**
|
||||
App root in `App.vue` **must** wrap ConfigProvider with `<a-style-provider hash-priority="high">` so legacy `main.css` cannot override Ant controls via higher specificity:
|
||||
```vue
|
||||
<a-style-provider hash-priority="high">
|
||||
<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">
|
||||
<RouterView />
|
||||
</a-config-provider>
|
||||
</a-style-provider>
|
||||
```
|
||||
Do not override direction to LTR on whole pages; use local `direction="ltr"` only for inherently LTR fragments (e.g. phone numbers, codes).
|
||||
|
||||
8. **Auto-import**
|
||||
`<a-*>` components are resolved via `unplugin-vue-components` + `AntDesignVueResolver({ importStyle: false })`. Do not add blanket `app.use(antd)` unless there is a documented exception. Do not per-component CSS imports (`importStyle` stays `false`; CSS-in-JS + theme).
|
||||
`<a-*>` components are resolved via `unplugin-vue-components` + `AntDesignVueResolver({ importStyle: false })`. Do not add blanket `app.use(antd)` unless there is a documented exception. Do not per-component CSS imports (`importStyle` stays `false`; CSS-in-JS + theme). Prefer **explicit** `import { Button as AButton, … } from 'ant-design-vue'` in migrated files when the Vite resolver is missing or unreliable.
|
||||
|
||||
9. **Theme is central**
|
||||
Visual tokens (primary, radius, `controlHeight`, padding/margin scale, shadows, Form/Card overrides) live only in `antdTheme.ts`. Do not fork theme objects inside views.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"plugins": {
|
||||
"hex": {
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,13 @@ Also read and obey [`.cursor/rules/antd-strict-governance.mdc`](../../rules/antd
|
||||
| Dependency | `ant-design-vue` ^4, `@ant-design/icons-vue`, `unplugin-vue-components` in `@mento/web` |
|
||||
| Vite plugin | `apps/web/vite.config.ts` — `Components` + `AntDesignVueResolver` |
|
||||
| Theme | `apps/web/src/theme/antdTheme.ts` (`controlHeight: 36`) |
|
||||
| RTL + locale + theme | `apps/web/src/App.vue` — `<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">` |
|
||||
| RTL + locale + theme + StyleProvider | `apps/web/src/App.vue` — `<a-style-provider hash-priority="high">` wrapping `<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">` (mandatory so legacy `main.css` cannot override Ant) |
|
||||
| Legacy kit (do not touch) | `apps/web/src/components/ui/*`, `styles/main.css` utilities |
|
||||
|
||||
### Mandatory child-control conversion (same pass)
|
||||
|
||||
هنگام بازنویسی یک صفحه (View)، ایجنت موظف است علاوه بر خود فایل View، تمام کامپوننتهای فرزندی را که در آن View ایمپورت شدهاند و حاوی اینپوت/سلکت/دکمه هستند نیز بازبینی کرده و درون آنها را به کامپوننتهای رسمی `ant-design-vue` تبدیل کند. هیچ تگ `<input>`, `<select>`, `<textarea>`, `<button>` خامی نباید در صفحه یا کامپوننتهای فرزندِ مصرفی آن باقی بماند.
|
||||
|
||||
## Migration workflow
|
||||
|
||||
1. Confirm the **single** route/view the user named.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
description: حاکمیت مطلق معماری رابط کاربری بر پایه Ant Design Vue v4، قفل مهاجرت صفحه به صفحه، ممنوعیت کامل CSS دستی و استاندارد ریاضی چیدمان
|
||||
globs: apps/web/src/**/*.{vue,ts,tsx,css}
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# قرارداد حاکمیتی و غیرقابلمذاکرهٔ رابط کاربری (Ant Design Vue v4 Strict Contract)
|
||||
|
||||
تنها منبع مجاز برای ساخت و بازنویسی عناصر رابط کاربری در این پروژه `ant-design-vue` (نسخه ۴) است. هرگونه تخطی از قوانین زیر خطای معماری محسوب میشود:
|
||||
|
||||
## ۱. قفل ایزولاسیون و مهاجرت صفحه به صفحه (Single-Page Blast Radius Lock)
|
||||
1. **ممنوعیت ویرایش دستهجمعی:** تو فقط و فقط مجاز به ویرایش صفحه (View) یا کامپوننتی هستی که کاربر صراحتاً در همان نوبت نام برده است. دست زدن به سایر صفحات پروژه مطلقاً ممنوع است.
|
||||
2. **حفظ لایهٔ قدیمی برای صفحات مهاجرتنکرده:** فایلهای داخل `apps/web/src/components/ui/Ui*.vue` و استایلهای سراسری `main.css` / `tokens.css` نباید حذف یا ویرایش شوند تا صفحات قدیمی پروژه بدون خطا به کار خود ادامه دهند.
|
||||
3. **قطع کامل وابستگی در صفحهٔ هدف:** در صفحهای که کاربر دستور بازنویسی آن را میدهد، تمام ایمپورتهای `@/components/ui` و کلاسهای قدیمی باید از آن فایل حذف شوند و ۱۰۰٪ با کامپوننتهای رسمی `<a-...>` جایگزین گردند.
|
||||
4. **کامپوننتهای تخصصی تاریخ شمسی و مبالغ:** در صفحات بازنویسیشده، اگر از `JalaliDateInput` یا `MoneyInput` استفاده شده است، منطق آنها را حفظ کن اما مطمئن شو ظاهر ورودی آنها با ارتفاع `40px`، ردیوس `10px` و عرض `style="width: 100%"` کاملاً همتراز با فیلدهای Ant Design نمایش داده میشود.
|
||||
|
||||
## ۲. لیست سیاه سینتکس و تگهای ممنوعه در صفحات بازنویسیشده (Banned Syntax)
|
||||
در هر فایلی که بازنویسی یا ایجاد میکنی، وجود موارد زیر خطای بحرانی است و باید فوراً حذف شوند:
|
||||
- **تگهای خام HTML برای فرم و جدول:** `<button>`, `<input>`, `<select>`, `<textarea>`, `<label>`, `<form>`, `<table>`, `<thead>`, `<tbody>`, `<tr>`, `<td>`.
|
||||
- **کلاسهای لگسی پروژه:** `.btn`, `.btn-primary`, `.btn-ghost`, `.btn-danger`, `.btn-save`, `.field`, `.crm-page`, `.crm-page-header`, `.crm-card`, `.crm-table`, `.crm-empty-state`.
|
||||
- **کلاسهای Tailwind (پروژه فاقد Tailwind است):** استفاده از کلاسهای ناموجود مانند `w-full`, `flex`, `gap-4`, `p-4`, `mb-4` مطلقاً ممنوع است. برای عرض کامل کنترلها فقط از `style="width: 100%"` یا پراپ `block` استفاده کن.
|
||||
|
||||
## ۳. قوانین ریاضی چیدمان، گرید و ریتم فضایی (Spatial & Layout Mathematics)
|
||||
1. **ممنوعیت تکهتکه کردن فرم به کارتهای متعدد (Anti-Card-Fragmentation):**
|
||||
- خرد کردن یک فرم به چندین باکس یا کارت مجزا زیر هم ممنوع است.
|
||||
- کل فیلدهای یک فرم اصلی باید در **حداکثر ۱ `<a-card :bordered="false">`** تجمیع شوند.
|
||||
- برای تفکیک بخشهای منطقی در داخل آن کارت واحد، فقط از `<a-divider orientation="right">عنوان بخش</a-divider>` استفاده کن.
|
||||
2. **چیدمان استاندارد دو ستونه (فرم اصلی + پنل خلاصه):**
|
||||
- ردیف اصلی صفحه: `<a-row :gutter="[24, 24]">`
|
||||
- ستون اصلی (فرم/محتوا): `<a-col :xs="24" :lg="17" :xl="18">`
|
||||
- ستون کناری (خلاصه وضعیت): `<a-col :xs="24" :lg="7" :xl="6">` همراه با `<a-affix :offset-top="24">`.
|
||||
- محتوای پنل خلاصه باید الزاماً با `<a-descriptions :column="1" size="small" bordered>` داخل `<a-card title="..." :bordered="false">` پیادهسازی شود، نه با `div` و `span` دستی.
|
||||
3. **قانون عرض فیلدها در فرم (Form Grid Allocation):**
|
||||
- تمام فرمها باید `<a-form layout="vertical" :model="...">` باشند و تمام فیلدها بدون استثنا داخل `<a-form-item label="..." name="...">` قرار گیرند.
|
||||
- رها کردن فیلدهای کوتاه در عرض ۱۰۰٪ (`span="24"`) ممنوع است. چیدمان درون فرم باید با `<a-row :gutter="[16, 0]">` به شکل زیر باشد:
|
||||
- **فیلدهای کوتاه** (تاریخ، ساعت، مدت زمان، مبلغ، وضعیت، نوع، کد): `<a-col :xs="24" :sm="12" :md="8">` (۳ ستونه).
|
||||
- **فیلدهای متوسط** (انتخاب مشتری، مسئول انجام، فرصت مرتبط، دستهبندی، عنوان): `<a-col :xs="24" :md="12">` (۲ ستونه).
|
||||
- **فیلدهای تمامعرض** (توضیحات، یادداشت، چکلیست، برچسبها): `<a-col :span="24">`.
|
||||
- **سوییچها و چکباکسهای همخانواده:** قرارگیری در یک ردیف با `<a-space :size="24" wrap>`.
|
||||
4. **مدیریت Margin و Padding بدون CSS دستی:**
|
||||
- فاصلهٔ عمودی فیلدها فقط توسط `itemMarginBottom` در کانفیگ تم `<a-form-item>` کنترل میشود.
|
||||
- فاصلهٔ افقی/عمودی دکمهها و المانها فقط با `<a-space :size="8 | 12 | 16">` یا `<a-flex gap="small | middle | large" align="center" justify="space-between">` کنترل میشود.
|
||||
|
||||
## ۴. قفل سینتکس اختصاصی Ant Design Vue v4
|
||||
- **بایندینگ مقدار (`v-model`):** استفاده از `v-model="..."` بدون آرگومان روی کامپوننتهای Ant Design Vue خطاست:
|
||||
- برای `a-input`, `a-textarea`, `a-input-number`, `a-select`, `a-radio-group`, `a-segmented`, `a-date-picker`, `a-time-picker`: الزاماً `v-model:value="..."`.
|
||||
- برای `a-checkbox`, `a-switch`: الزاماً `v-model:checked="..."`.
|
||||
- برای `a-modal`, `a-drawer`, `a-dropdown`, `a-popover`, `a-tooltip`: الزاماً `v-model:open="..."` (پراپ `:visible` منسوخ و ممنوع است).
|
||||
- **الزام عرض ۱۰۰٪ روی کنترلهای خاص:** کامپوننتهای `<a-input-number>`, `<a-date-picker>`, `<a-time-picker>` و `<a-select>` در داخل `<a-form-item>` باید دارای `style="width: 100%"` باشند.
|
||||
- **فیدبک و پیامها:** برای نمایش پیام از `import { message, notification, Modal } from 'ant-design-vue'` استفاده کن.
|
||||
|
||||
## ۵. حاکمیت مطلق توکنها و ممنوعیت CSS دستی (Zero Manual Styling & RTL Lock)
|
||||
1. نوشتن کد رنگ (`#hex`, `rgb`, `rgba`, `hsl`)، سایه (`box-shadow`)، ردیوس (`border-radius`) و فاصلههای دستی (`margin`, `padding` با `px`/`rem`) در `<style scoped>` ممنوع است.
|
||||
2. تمام تنظیمات ظاهری (ردیوس، شدو، ارتفاع کنترلها، پدینگ و رنگها) فقط در فایل مرکزی `apps/web/src/theme/antdTheme.ts` تعریف میشوند.
|
||||
3. در صورت نیاز ضروری به خواندن توکن در یک کانتینر، فقط از هوک `const { token } = theme.useToken()` در `ant-design-vue` استفاده کن.
|
||||
4. استفاده از `:deep(.ant-...)` برای دستکاری ظاهر کامپوننتهای انت ممنوع است.
|
||||
5. در RTL، استفاده از `left`, `right`, `margin-left`, `margin-right`, `padding-left`, `padding-right` ممنوع است؛ فقط از خواص منطقی (`inset-inline-start`, `inset-inline-end`, `margin-inline`, `padding-inline`) استفاده شود.
|
||||
|
||||
## ۶. گیت خودارزیابی پیش از تحویل کد (Self-Verification Gate)
|
||||
قبل از اتمام کار روی فایلِ درخواستی، این ۵ شرط را بررسی کن:
|
||||
- [ ] آیا فقط فایل درخواستی کاربر ویرایش شده و سایر صفحات دستنخورده ماندهاند؟
|
||||
- [ ] آیا تمام تگهای خام فرم، کامپوننتهای `Ui*`، کلاسهای `.btn`/`.field`/`.crm-*` و کلاسهای ناموجود مثل `w-full` از این صفحه حذف شدهاند؟
|
||||
- [ ] آیا فرم در ۱ کارت واحد با `<a-divider>` و گرید `<a-row :gutter="[16, 0]">` چیده شده و فیلدهای کوتاه از حالت تمامعرض خارج شدهاند؟
|
||||
- [ ] آیا تمام بایندینگها از `v-model:value`، `v-model:checked` و `v-model:open` به همراه `style="width: 100%"` روی سلکتها و شمارندهها استفاده میکنند؟
|
||||
- [ ] آیا `<style scoped>` کاملاً از رنگهای Hex، مارجین/پدینگ دستی، ردیوس، شدو و `:deep(.ant-*)` پاکسازی شده است؟
|
||||
@@ -12,7 +12,7 @@
|
||||
"prisma:seed": "tsx prisma/seed.ts",
|
||||
"lint": "echo \"api lint placeholder\"",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p test/tsconfig.json",
|
||||
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/birthdays.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts test/pipeline-merge.test.ts test/ask-count.test.ts test/prior-archive.test.ts test/organizations.test.ts test/promote-from-prior.test.ts test/behavior.test.ts"
|
||||
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/birthdays.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts test/pipeline-merge.test.ts test/ask-count.test.ts test/prior-archive.test.ts test/organizations.test.ts test/promote-from-prior.test.ts test/behavior.test.ts test/attendance-time.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mento/shared": "*",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Membership" ADD COLUMN "logoutTime" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AttendanceEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"organizationId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"kind" TEXT NOT NULL,
|
||||
"at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"afterHours" BOOLEAN NOT NULL DEFAULT false,
|
||||
"sessionStartedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AttendanceEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AttendanceEvent_organizationId_at_idx" ON "AttendanceEvent"("organizationId", "at");
|
||||
CREATE INDEX "AttendanceEvent_organizationId_userId_at_idx" ON "AttendanceEvent"("organizationId", "userId", "at");
|
||||
CREATE UNIQUE INDEX "AttendanceEvent_organizationId_userId_kind_sessionStartedAt_key" ON "AttendanceEvent"("organizationId", "userId", "kind", "sessionStartedAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AttendanceEvent" ADD CONSTRAINT "AttendanceEvent_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "AttendanceEvent" ADD CONSTRAINT "AttendanceEvent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,90 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "SmsAccount" (
|
||||
"id" TEXT NOT NULL,
|
||||
"organizationId" TEXT NOT NULL,
|
||||
"balanceRials" INTEGER NOT NULL DEFAULT 0,
|
||||
"pricePerPartRials" INTEGER NOT NULL DEFAULT 2500,
|
||||
"isBlocked" BOOLEAN NOT NULL DEFAULT false,
|
||||
"autoBlockBelowRials" INTEGER,
|
||||
"alertCriticalRials" INTEGER NOT NULL DEFAULT 10000,
|
||||
"alertWarningRials" INTEGER NOT NULL DEFAULT 100000,
|
||||
"panelMode" TEXT NOT NULL DEFAULT 'platform',
|
||||
"ownPanelType" TEXT NOT NULL DEFAULT '0098',
|
||||
"ownPanelUsername" TEXT,
|
||||
"ownPanelPassword" TEXT,
|
||||
"ownPanelFrom" TEXT,
|
||||
"chargeCard" TEXT,
|
||||
"chargeIban" TEXT,
|
||||
"chargeHolder" TEXT,
|
||||
"chargeInstruction" TEXT,
|
||||
"alertDaysSent" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastAlertDate" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "SmsAccount_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SmsLedger" (
|
||||
"id" TEXT NOT NULL,
|
||||
"smsAccountId" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"amountRials" INTEGER NOT NULL,
|
||||
"balanceAfterRials" INTEGER NOT NULL,
|
||||
"parts" INTEGER,
|
||||
"pricePerPartRials" INTEGER,
|
||||
"note" TEXT,
|
||||
"smsSendLogId" TEXT,
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SmsLedger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SmsBillingSendLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"smsAccountId" TEXT NOT NULL,
|
||||
"receiver" TEXT NOT NULL,
|
||||
"body" TEXT NOT NULL,
|
||||
"parts" INTEGER NOT NULL,
|
||||
"pricePerPartRials" INTEGER NOT NULL,
|
||||
"totalAmountRials" INTEGER NOT NULL,
|
||||
"provider" TEXT,
|
||||
"source" TEXT,
|
||||
"isAlert" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SmsBillingSendLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SmsAccount_organizationId_key" ON "SmsAccount"("organizationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsAccount_isBlocked_idx" ON "SmsAccount"("isBlocked");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsAccount_balanceRials_idx" ON "SmsAccount"("balanceRials");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsLedger_smsAccountId_createdAt_idx" ON "SmsLedger"("smsAccountId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsLedger_type_idx" ON "SmsLedger"("type");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsBillingSendLog_smsAccountId_createdAt_idx" ON "SmsBillingSendLog"("smsAccountId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SmsBillingSendLog_source_idx" ON "SmsBillingSendLog"("source");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SmsAccount" ADD CONSTRAINT "SmsAccount_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SmsLedger" ADD CONSTRAINT "SmsLedger_smsAccountId_fkey" FOREIGN KEY ("smsAccountId") REFERENCES "SmsAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SmsBillingSendLog" ADD CONSTRAINT "SmsBillingSendLog_smsAccountId_fkey" FOREIGN KEY ("smsAccountId") REFERENCES "SmsAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,57 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "ActivityBoard" (
|
||||
"id" TEXT NOT NULL,
|
||||
"organizationId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"isDefault" BOOLEAN NOT NULL DEFAULT false,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ActivityBoard_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ActivityBoard_organizationId_name_key" ON "ActivityBoard"("organizationId", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ActivityBoard_organizationId_position_idx" ON "ActivityBoard"("organizationId", "position");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ActivityBoard" ADD CONSTRAINT "ActivityBoard_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- Backfill: one default board per organization that already has activity stages
|
||||
INSERT INTO "ActivityBoard" ("id", "organizationId", "name", "isDefault", "position", "createdAt", "updatedAt")
|
||||
SELECT 'actb_' || md5(s."organizationId" || clock_timestamp()::text), s."organizationId", 'کارهای اصلی', true, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
FROM (SELECT DISTINCT "organizationId" FROM "ActivityStage") AS s;
|
||||
|
||||
-- AlterTable: stages belong to a board
|
||||
ALTER TABLE "ActivityStage" ADD COLUMN "boardId" TEXT;
|
||||
|
||||
UPDATE "ActivityStage" AS st
|
||||
SET "boardId" = b."id"
|
||||
FROM "ActivityBoard" AS b
|
||||
WHERE b."organizationId" = st."organizationId" AND b."isDefault" = true;
|
||||
|
||||
ALTER TABLE "ActivityStage" ALTER COLUMN "boardId" SET NOT NULL;
|
||||
|
||||
-- Stage names are unique per board (not per organization)
|
||||
DROP INDEX "ActivityStage_organizationId_name_key";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ActivityStage_boardId_name_key" ON "ActivityStage"("boardId", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ActivityStage_boardId_position_idx" ON "ActivityStage"("boardId", "position");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ActivityStage" ADD CONSTRAINT "ActivityStage_boardId_fkey" FOREIGN KEY ("boardId") REFERENCES "ActivityBoard"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AlterTable: activities optionally point at a board (null = default board)
|
||||
ALTER TABLE "Activity" ADD COLUMN "boardId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Activity_boardId_idx" ON "Activity"("boardId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_boardId_fkey" FOREIGN KEY ("boardId") REFERENCES "ActivityBoard"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -161,6 +161,7 @@ model Organization {
|
||||
teams Team[]
|
||||
companies Company[]
|
||||
people Person[]
|
||||
attendanceEvents AttendanceEvent[]
|
||||
discAssessments DiscAssessment[]
|
||||
salesCopilotSessions SalesCopilotSession[]
|
||||
pipelines Pipeline[]
|
||||
@@ -205,6 +206,7 @@ model Organization {
|
||||
webhookEndpoints WebhookEndpoint[]
|
||||
smsCampaigns SmsCampaign[]
|
||||
outboundSmsLogs OutboundSmsLog[]
|
||||
smsAccount SmsAccount?
|
||||
financialAccounts FinancialAccount[]
|
||||
financialCategories FinancialCategory[]
|
||||
financialDocuments FinancialDocument[]
|
||||
@@ -222,6 +224,7 @@ model Organization {
|
||||
reservationAppointments ReservationAppointment[]
|
||||
leads Lead[]
|
||||
leadStages LeadStage[]
|
||||
activityBoards ActivityBoard[]
|
||||
activityStages ActivityStage[]
|
||||
activityTypeDefs ActivityTypeDef[]
|
||||
leadEvents LeadEvent[]
|
||||
@@ -312,6 +315,7 @@ model User {
|
||||
createdRoutineTasks RoutineTask[] @relation("RoutineTaskCreator")
|
||||
routineTaskEvents RoutineTaskEvent[]
|
||||
routineSettings RoutineUserSettings[]
|
||||
attendanceEvents AttendanceEvent[]
|
||||
deletionArchives DeletionArchive[] @relation("DeletionActor")
|
||||
discAssessments DiscAssessment[] @relation("DiscAssessor")
|
||||
salesCopilotSessions SalesCopilotSession[] @relation("CopilotAuthor")
|
||||
@@ -369,6 +373,8 @@ model Membership {
|
||||
priorArchiveEnabled Boolean @default(false)
|
||||
/// current | archive
|
||||
priorArchiveLens String @default("current")
|
||||
/// ساعت خروج روزانه به وقت تهران، مثل 18:00؛ خالی یعنی بدون محدودیت
|
||||
logoutTime String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -681,10 +687,29 @@ model Deal {
|
||||
}
|
||||
|
||||
/// مراحل/ستونهای فعالیت (تب و کانبان) — kind وضعیت فعالیت داخل این مرحله را تعیین میکند
|
||||
/// گروه فعالیت (مثل مسیر فروش برای معاملات): هر گروه ستونهای خودش را دارد
|
||||
model ActivityBoard {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
isDefault Boolean @default(false)
|
||||
position Int @default(0)
|
||||
stages ActivityStage[]
|
||||
activities Activity[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([organizationId, name])
|
||||
@@index([organizationId, position])
|
||||
}
|
||||
|
||||
model ActivityStage {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
boardId String
|
||||
board ActivityBoard @relation(fields: [boardId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
position Int @default(0)
|
||||
color String @default("green")
|
||||
@@ -693,8 +718,9 @@ model ActivityStage {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([organizationId, name])
|
||||
@@unique([boardId, name])
|
||||
@@index([organizationId, position])
|
||||
@@index([boardId, position])
|
||||
}
|
||||
|
||||
/// نوع فعالیت قابل تعریف توسط سازمان با فیلدهای اختصاصی
|
||||
@@ -759,6 +785,9 @@ model Activity {
|
||||
createdBy User? @relation("ActivityCreator", fields: [createdById], references: [id], onDelete: SetNull)
|
||||
notes Note[]
|
||||
routineTasks RoutineTask[]
|
||||
/// گروه فعالیت؛ null = گروه پیشفرض محیط
|
||||
boardId String?
|
||||
board ActivityBoard? @relation(fields: [boardId], references: [id], onDelete: SetNull)
|
||||
/// مرحله (ستون کانبان)؛ null یا مرحلهٔ ناهمنوع با status → اولین مرحلهٔ همنوع
|
||||
stageId String?
|
||||
stage ActivityStage? @relation(fields: [stageId], references: [id], onDelete: SetNull)
|
||||
@@ -776,6 +805,7 @@ model Activity {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([stageId])
|
||||
@@index([boardId])
|
||||
@@index([typeDefId])
|
||||
@@index([leadId])
|
||||
@@index([organizationId, status, dueAt])
|
||||
@@ -2286,6 +2316,78 @@ model FinancialInstallment {
|
||||
@@index([dueDate])
|
||||
}
|
||||
|
||||
/// کیفپول و تنظیمات پیامک هر محیط (الگوی همکار / سوپرادمین آبشُده)
|
||||
model SmsAccount {
|
||||
id String @id @default(cuid())
|
||||
organizationId String @unique
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
balanceRials Int @default(0)
|
||||
pricePerPartRials Int @default(2500)
|
||||
isBlocked Boolean @default(false)
|
||||
/// اگر ست باشد: وقتی موجودی < این مقدار، ارسال قطع میشود (میتواند منفی باشد). null = فقط کلید دستی
|
||||
autoBlockBelowRials Int?
|
||||
alertCriticalRials Int @default(10000)
|
||||
alertWarningRials Int @default(100000)
|
||||
/// platform = سامانهٔ ما | own = پنل اختصاصی مشتری (بدون کسر/لاگ کیف)
|
||||
panelMode String @default("platform")
|
||||
/// وقتی panelMode=own: 0098 | asanak | trez
|
||||
ownPanelType String @default("0098")
|
||||
ownPanelUsername String?
|
||||
ownPanelPassword String?
|
||||
ownPanelFrom String?
|
||||
chargeCard String?
|
||||
chargeIban String?
|
||||
chargeHolder String?
|
||||
chargeInstruction String?
|
||||
alertDaysSent Int @default(0)
|
||||
lastAlertDate DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
ledgers SmsLedger[]
|
||||
sendLogs SmsBillingSendLog[]
|
||||
|
||||
@@index([isBlocked])
|
||||
@@index([balanceRials])
|
||||
}
|
||||
|
||||
model SmsLedger {
|
||||
id String @id @default(cuid())
|
||||
smsAccountId String
|
||||
smsAccount SmsAccount @relation(fields: [smsAccountId], references: [id], onDelete: Cascade)
|
||||
/// charge | debit | alert_debit
|
||||
type String
|
||||
amountRials Int
|
||||
balanceAfterRials Int
|
||||
parts Int?
|
||||
pricePerPartRials Int?
|
||||
note String?
|
||||
smsSendLogId String?
|
||||
createdById String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([smsAccountId, createdAt])
|
||||
@@index([type])
|
||||
}
|
||||
|
||||
/// لاگ ارسال صورتحسابشده (همهٔ مسیرها وقتی panelMode=platform)
|
||||
model SmsBillingSendLog {
|
||||
id String @id @default(cuid())
|
||||
smsAccountId String
|
||||
smsAccount SmsAccount @relation(fields: [smsAccountId], references: [id], onDelete: Cascade)
|
||||
receiver String
|
||||
body String
|
||||
parts Int
|
||||
pricePerPartRials Int
|
||||
totalAmountRials Int
|
||||
provider String?
|
||||
source String?
|
||||
isAlert Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([smsAccountId, createdAt])
|
||||
@@index([source])
|
||||
}
|
||||
|
||||
/// لاگ یکپارچهٔ پیامک خروجی (دستی / کمپین / اتوماسیون)
|
||||
model OutboundSmsLog {
|
||||
id String @id @default(cuid())
|
||||
@@ -3417,3 +3519,24 @@ model SalesCopilotSession {
|
||||
@@index([organizationId, leadId])
|
||||
@@index([dealId])
|
||||
}
|
||||
|
||||
/// ورود و خروج کارمندان به سامانه
|
||||
model AttendanceEvent {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
/// login | logout | forced_logout
|
||||
kind String
|
||||
at DateTime @default(now())
|
||||
/// ورود بعد از ساعت خروج تعیینشده
|
||||
afterHours Boolean @default(false)
|
||||
/// شروع نشست؛ برای اینکه خروج اجباری هر نشست فقط یک بار ثبت شود
|
||||
sessionStartedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([organizationId, at])
|
||||
@@index([organizationId, userId, at])
|
||||
@@unique([organizationId, userId, kind, sessionStartedAt])
|
||||
}
|
||||
|
||||
@@ -27,14 +27,17 @@ import { ActivitiesExcelService } from './activities-excel.service';
|
||||
import { ActivityStagesService } from './activity-stages.service';
|
||||
import { ActivityTypesService } from './activity-types.service';
|
||||
import {
|
||||
CreateActivityBoardDto,
|
||||
CreateActivityDto,
|
||||
CreateActivityStageDto,
|
||||
CreateActivityTypeDto,
|
||||
ImportActivityRowsDto,
|
||||
ListActivitiesQueryDto,
|
||||
ListActivityStagesQueryDto,
|
||||
MoveActivityStageDto,
|
||||
ReorderActivityStagesDto,
|
||||
ReorderActivityTypesDto,
|
||||
UpdateActivityBoardDto,
|
||||
UpdateActivityDto,
|
||||
UpdateActivityStageDto,
|
||||
UpdateActivityTypeDto,
|
||||
@@ -65,9 +68,40 @@ export class ActivitiesController {
|
||||
return this.activitiesService.summary(user.organizationId, user, scope);
|
||||
}
|
||||
|
||||
@Get('boards')
|
||||
listBoards(@CurrentUser() user: Actor) {
|
||||
return this.stagesService.listBoards(user.organizationId);
|
||||
}
|
||||
|
||||
@Post('boards')
|
||||
@UseGuards(RolesGuard)
|
||||
@Roles('owner', 'admin')
|
||||
createBoard(@CurrentUser() user: Actor, @Body() dto: CreateActivityBoardDto) {
|
||||
return this.stagesService.createBoard(user.organizationId, dto.name);
|
||||
}
|
||||
|
||||
@Patch('boards/:id')
|
||||
@UseGuards(RolesGuard)
|
||||
@Roles('owner', 'admin')
|
||||
updateBoard(
|
||||
@CurrentUser() user: Actor,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateActivityBoardDto,
|
||||
) {
|
||||
return this.stagesService.updateBoard(user.organizationId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('boards/:id')
|
||||
@UseGuards(RolesGuard)
|
||||
@Roles('owner', 'admin')
|
||||
async removeBoard(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||
await this.stagesService.removeBoard(user.organizationId, id);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@Get('stages')
|
||||
listStages(@CurrentUser() user: Actor) {
|
||||
return this.stagesService.list(user.organizationId);
|
||||
listStages(@CurrentUser() user: Actor, @Query() query: ListActivityStagesQueryDto) {
|
||||
return this.stagesService.list(user.organizationId, query.boardId);
|
||||
}
|
||||
|
||||
@Post('stages')
|
||||
@@ -157,6 +191,7 @@ export class ActivitiesController {
|
||||
typeDefId: query.typeDefId,
|
||||
status: query.status,
|
||||
assigneeId: query.assigneeId,
|
||||
boardId: query.boardId,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -189,6 +224,7 @@ export class ActivitiesController {
|
||||
typeDefId: query.typeDefId,
|
||||
status: query.status,
|
||||
assigneeId: query.assigneeId,
|
||||
boardId: query.boardId,
|
||||
},
|
||||
query.stageId ? { stageId: query.stageId } : undefined,
|
||||
);
|
||||
|
||||
@@ -30,14 +30,14 @@ import { GamificationService } from '../gamification/gamification.service';
|
||||
import { tehranDayKey } from '../routines/routine-dates';
|
||||
import { buildSearchWhere, ci } from '../common/search';
|
||||
import { activityPriorWhere } from '../common/prior-archive';
|
||||
import { ActivityStagesService, type StageDefaults } from './activity-stages.service';
|
||||
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
|
||||
import {
|
||||
ActivityTypesService,
|
||||
type SystemTypes,
|
||||
type TypeRow,
|
||||
} from './activity-types.service';
|
||||
|
||||
type DtoContext = { stages?: StageDefaults; types?: SystemTypes };
|
||||
type DtoContext = { stages?: BoardStageContext; types?: SystemTypes };
|
||||
|
||||
type ActivityActor = Pick<Actor, 'userId' | 'role' | 'priorLens' | 'priorCutoff'>;
|
||||
|
||||
@@ -49,6 +49,8 @@ type ListFacets = {
|
||||
typeDefId?: string;
|
||||
status?: ActivityDto['status'];
|
||||
assigneeId?: string;
|
||||
/** گروه فعالیت؛ خالی = همهٔ گروهها */
|
||||
boardId?: string;
|
||||
};
|
||||
|
||||
type ActivityRow = {
|
||||
@@ -77,14 +79,15 @@ type ActivityRow = {
|
||||
assignee: { id: string; fullName: string } | null;
|
||||
assignees: Array<{ id: string; fullName: string }>;
|
||||
createdBy: { id: string; fullName: string } | null;
|
||||
stage?: { id: string; kind: ActivityDto['status'] } | null;
|
||||
boardId?: string | null;
|
||||
stage?: { id: string; kind: ActivityDto['status']; boardId: string } | null;
|
||||
typeDef?: { id: string; name: string; icon: string; color: string } | null;
|
||||
fields?: Prisma.JsonValue | null;
|
||||
participantIds?: string[];
|
||||
};
|
||||
|
||||
const include = {
|
||||
stage: { select: { id: true, kind: true } },
|
||||
stage: { select: { id: true, kind: true, boardId: true } },
|
||||
typeDef: { select: { id: true, name: true, icon: true, color: true } },
|
||||
person: { select: { id: true, firstName: true, lastName: true } },
|
||||
company: { select: { id: true, name: true } },
|
||||
@@ -109,7 +112,7 @@ export class ActivitiesService {
|
||||
|
||||
private async ctx(organizationId: string): Promise<DtoContext> {
|
||||
const [stages, types] = await Promise.all([
|
||||
this.stages.defaults(organizationId),
|
||||
this.stages.boardContext(organizationId),
|
||||
this.types.system(organizationId),
|
||||
]);
|
||||
return { stages, types };
|
||||
@@ -255,13 +258,20 @@ export class ActivitiesService {
|
||||
stageScope,
|
||||
typeRows,
|
||||
);
|
||||
const boardCtx = await this.stages.boardContext(organizationId);
|
||||
if (facets?.boardId) {
|
||||
const boardId = await this.stages.resolveBoardId(organizationId, facets.boardId);
|
||||
(where.AND as Prisma.ActivityWhereInput[]).push(
|
||||
this.stages.boardWhere(boardId, boardCtx.defaultBoardId),
|
||||
);
|
||||
}
|
||||
if (stageScope && stageScope.stageId !== 'all') {
|
||||
(where.AND as Prisma.ActivityWhereInput[]).push(
|
||||
await this.stages.whereForStage(organizationId, stageScope.stageId),
|
||||
);
|
||||
}
|
||||
const ctx: DtoContext = {
|
||||
stages: await this.stages.defaults(organizationId),
|
||||
stages: boardCtx,
|
||||
types: this.types.systemOf(typeRows),
|
||||
};
|
||||
const take = Math.min(Math.max(limit, 1), 200);
|
||||
@@ -293,7 +303,9 @@ export class ActivitiesService {
|
||||
desk?: 'mine' | 'team',
|
||||
facets?: ListFacets,
|
||||
): Promise<ActivityStageCountsDto> {
|
||||
const rows = await this.stages.rows(organizationId);
|
||||
const boardId = await this.stages.resolveBoardId(organizationId, facets?.boardId);
|
||||
const defaultBoard = await this.stages.ensureDefaultBoard(organizationId);
|
||||
const rows = await this.stages.rows(organizationId, boardId);
|
||||
const defaults = this.stages.defaultsOf(rows);
|
||||
const kindOf = new Map(rows.map((r) => [r.id, r.kind]));
|
||||
const where = this.buildWhere(
|
||||
@@ -308,6 +320,9 @@ export class ActivitiesService {
|
||||
{ stageId: 'all' },
|
||||
await this.types.rows(organizationId),
|
||||
);
|
||||
(where.AND as Prisma.ActivityWhereInput[]).push(
|
||||
this.stages.boardWhere(boardId, defaultBoard.id),
|
||||
);
|
||||
const groups = await this.prisma.activity.groupBy({
|
||||
by: ['status', 'stageId'],
|
||||
where,
|
||||
@@ -341,6 +356,7 @@ export class ActivitiesService {
|
||||
where: { id },
|
||||
data: {
|
||||
stageId: stage.id,
|
||||
boardId: stage.boardId,
|
||||
status: stage.kind,
|
||||
completedAt:
|
||||
stage.kind === 'done'
|
||||
@@ -401,6 +417,12 @@ export class ActivitiesService {
|
||||
const initialStage = initialStageId
|
||||
? await this.stages.get(organizationId, initialStageId)
|
||||
: null;
|
||||
const requestedBoardId = emptyToNull(dto.boardId ?? null);
|
||||
const boardId = initialStage
|
||||
? initialStage.boardId
|
||||
: requestedBoardId
|
||||
? await this.stages.resolveBoardId(organizationId, requestedBoardId)
|
||||
: null;
|
||||
const resolved = await this.types.resolve(organizationId, {
|
||||
typeDefId: dto.typeDefId,
|
||||
type: dto.type,
|
||||
@@ -414,6 +436,7 @@ export class ActivitiesService {
|
||||
const row = await this.prisma.activity.create({
|
||||
data: {
|
||||
organizationId,
|
||||
boardId,
|
||||
...(initialStage
|
||||
? {
|
||||
stageId: initialStage.id,
|
||||
@@ -513,6 +536,19 @@ export class ActivitiesService {
|
||||
});
|
||||
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
||||
if (dto.title !== undefined) data.title = dto.title.trim();
|
||||
if ('boardId' in dto) {
|
||||
const nextBoardId = await this.stages.resolveBoardId(organizationId, dto.boardId);
|
||||
const current = await this.prisma.activity.findUnique({
|
||||
where: { id },
|
||||
select: { boardId: true },
|
||||
});
|
||||
const defaultBoard = await this.stages.ensureDefaultBoard(organizationId);
|
||||
if (nextBoardId !== (current?.boardId ?? defaultBoard.id)) {
|
||||
// ستون قبلی مال گروه دیگر است؛ فعالیت به ستون اولِ هموضعیت گروه جدید میرود
|
||||
data.boardId = nextBoardId;
|
||||
data.stageId = null;
|
||||
}
|
||||
}
|
||||
let addedParticipants: string[] = [];
|
||||
const typeChanged = 'typeDefId' in dto || dto.type !== undefined;
|
||||
if (typeChanged || dto.fields !== undefined) {
|
||||
@@ -922,6 +958,7 @@ export class ActivitiesService {
|
||||
? (row.fields as unknown as ActivityFieldValues)
|
||||
: {};
|
||||
return {
|
||||
boardId: this.stages.effectiveBoardId(row, ctx?.stages),
|
||||
stageId: this.stages.effectiveStageId(row, ctx?.stages),
|
||||
typeDef: row.typeDef
|
||||
? this.types.toSummary(row.typeDef)
|
||||
@@ -976,7 +1013,11 @@ export class ActivitiesService {
|
||||
];
|
||||
if (!ids.length) return [];
|
||||
const count = await this.prisma.user.count({
|
||||
where: { organizationId, id: { in: ids }, isActive: true },
|
||||
where: {
|
||||
id: { in: ids },
|
||||
isActive: true,
|
||||
memberships: { some: { organizationId, isActive: true } },
|
||||
},
|
||||
});
|
||||
if (count !== ids.length) {
|
||||
throw new BadRequestException('یکی از مسئولان انتخابشده معتبر نیست');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import type {
|
||||
ActivityBoardDto,
|
||||
ActivityStageColor,
|
||||
ActivityStageDto,
|
||||
ActivityStatus,
|
||||
@@ -8,6 +9,8 @@ import { ACTIVITY_STAGE_COLORS } from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const DEFAULT_BOARD_NAME = 'کارهای اصلی';
|
||||
|
||||
const DEFAULT_STAGES: Array<{ name: string; color: ActivityStageColor; kind: ActivityStatus }> = [
|
||||
{ name: 'در صف', color: 'orange', kind: 'open' },
|
||||
{ name: 'در حال انجام', color: 'blue', kind: 'open' },
|
||||
@@ -19,24 +22,84 @@ const KINDS: ActivityStatus[] = ['open', 'done', 'canceled'];
|
||||
|
||||
type StageRow = {
|
||||
id: string;
|
||||
boardId: string;
|
||||
name: string;
|
||||
position: number;
|
||||
color: string;
|
||||
kind: ActivityStatus;
|
||||
};
|
||||
|
||||
type BoardRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
isDefault: boolean;
|
||||
position: number;
|
||||
};
|
||||
|
||||
const STAGE_SELECT = {
|
||||
id: true,
|
||||
boardId: true,
|
||||
name: true,
|
||||
position: true,
|
||||
color: true,
|
||||
kind: true,
|
||||
} satisfies Prisma.ActivityStageSelect;
|
||||
|
||||
const BOARD_SELECT = {
|
||||
id: true,
|
||||
name: true,
|
||||
isDefault: true,
|
||||
position: true,
|
||||
} satisfies Prisma.ActivityBoardSelect;
|
||||
|
||||
export type StageDefaults = Record<ActivityStatus, string | null>;
|
||||
|
||||
/** پیشفرضهای هر گروه برای محاسبهٔ «ستون مؤثر» فعالیتها */
|
||||
export type BoardStageContext = {
|
||||
defaultBoardId: string;
|
||||
defaults: Map<string, StageDefaults>;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class ActivityStagesService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async ensureDefaults(organizationId: string): Promise<void> {
|
||||
const count = await this.prisma.activityStage.count({ where: { organizationId } });
|
||||
// —— گروهها ——
|
||||
|
||||
/** گروه پیشفرض محیط را (با ستونهای اولیه) تضمین میکند */
|
||||
async ensureDefaultBoard(organizationId: string): Promise<BoardRow> {
|
||||
let board = await this.prisma.activityBoard.findFirst({
|
||||
where: { organizationId, isDefault: true },
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
if (!board) {
|
||||
board = await this.prisma.activityBoard
|
||||
.create({
|
||||
data: { organizationId, name: DEFAULT_BOARD_NAME, isDefault: true, position: 0 },
|
||||
select: BOARD_SELECT,
|
||||
})
|
||||
.catch(async (e) => {
|
||||
// ساخت همزمان در دو درخواست
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||
return this.prisma.activityBoard.findFirstOrThrow({
|
||||
where: { organizationId, isDefault: true },
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
await this.ensureBoardStages(organizationId, board.id);
|
||||
return board;
|
||||
}
|
||||
|
||||
private async ensureBoardStages(organizationId: string, boardId: string) {
|
||||
const count = await this.prisma.activityStage.count({ where: { boardId } });
|
||||
if (count > 0) return;
|
||||
await this.prisma.activityStage.createMany({
|
||||
data: DEFAULT_STAGES.map((s, i) => ({
|
||||
organizationId,
|
||||
boardId,
|
||||
name: s.name,
|
||||
color: s.color,
|
||||
kind: s.kind,
|
||||
@@ -46,17 +109,112 @@ export class ActivityStagesService {
|
||||
});
|
||||
}
|
||||
|
||||
async rows(organizationId: string): Promise<StageRow[]> {
|
||||
await this.ensureDefaults(organizationId);
|
||||
return this.prisma.activityStage.findMany({
|
||||
async listBoards(organizationId: string): Promise<ActivityBoardDto[]> {
|
||||
await this.ensureDefaultBoard(organizationId);
|
||||
const rows = await this.prisma.activityBoard.findMany({
|
||||
where: { organizationId },
|
||||
orderBy: [{ isDefault: 'desc' }, { position: 'asc' }, { createdAt: 'asc' }],
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
return rows.map((b) => ({ ...b }));
|
||||
}
|
||||
|
||||
/** شناسهٔ گروه معتبر؛ خالی = گروه پیشفرض */
|
||||
async resolveBoardId(organizationId: string, boardId?: string | null): Promise<string> {
|
||||
const id = boardId?.trim();
|
||||
if (!id) return (await this.ensureDefaultBoard(organizationId)).id;
|
||||
const board = await this.prisma.activityBoard.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!board) throw new BadRequestException('گروه فعالیت انتخابشده معتبر نیست');
|
||||
return board.id;
|
||||
}
|
||||
|
||||
async createBoard(organizationId: string, name: string): Promise<ActivityBoardDto> {
|
||||
await this.ensureDefaultBoard(organizationId);
|
||||
const max = await this.prisma.activityBoard.aggregate({
|
||||
where: { organizationId },
|
||||
_max: { position: true },
|
||||
});
|
||||
try {
|
||||
const board = await this.prisma.activityBoard.create({
|
||||
data: {
|
||||
organizationId,
|
||||
name: this.cleanBoardName(name),
|
||||
position: (max._max.position ?? 0) + 1,
|
||||
},
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
await this.ensureBoardStages(organizationId, board.id);
|
||||
return { ...board };
|
||||
} catch (e) {
|
||||
throw this.mapBoardError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async updateBoard(
|
||||
organizationId: string,
|
||||
id: string,
|
||||
dto: { name?: string },
|
||||
): Promise<ActivityBoardDto> {
|
||||
await this.getBoard(organizationId, id);
|
||||
try {
|
||||
const board = await this.prisma.activityBoard.update({
|
||||
where: { id },
|
||||
data: dto.name != null ? { name: this.cleanBoardName(dto.name) } : {},
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
return { ...board };
|
||||
} catch (e) {
|
||||
throw this.mapBoardError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** فعالیتهای گروه حذفشده به گروه پیشفرض (ستون اولِ هموضعیت) منتقل میشوند */
|
||||
async removeBoard(organizationId: string, id: string): Promise<void> {
|
||||
const board = await this.getBoard(organizationId, id);
|
||||
if (board.isDefault) {
|
||||
throw new BadRequestException('گروه پیشفرض قابل حذف نیست');
|
||||
}
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.activity.updateMany({
|
||||
where: { organizationId, boardId: id },
|
||||
data: { boardId: null, stageId: null },
|
||||
}),
|
||||
this.prisma.activityBoard.delete({ where: { id } }),
|
||||
]);
|
||||
}
|
||||
|
||||
private async getBoard(organizationId: string, id: string): Promise<BoardRow> {
|
||||
const board = await this.prisma.activityBoard.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: BOARD_SELECT,
|
||||
});
|
||||
if (!board) throw new NotFoundException('گروه فعالیت پیدا نشد');
|
||||
return board;
|
||||
}
|
||||
|
||||
/** شرط Prisma برای فعالیتهای یک گروه (فعالیت بدون گروه = گروه پیشفرض) */
|
||||
boardWhere(boardId: string, defaultBoardId: string): Prisma.ActivityWhereInput {
|
||||
return boardId === defaultBoardId
|
||||
? { OR: [{ boardId }, { boardId: null }] }
|
||||
: { boardId };
|
||||
}
|
||||
|
||||
// —— ستونها ——
|
||||
|
||||
async rows(organizationId: string, boardId?: string | null): Promise<StageRow[]> {
|
||||
const resolved = await this.resolveBoardId(organizationId, boardId);
|
||||
return this.prisma.activityStage.findMany({
|
||||
where: { organizationId, boardId: resolved },
|
||||
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
||||
select: { id: true, name: true, position: true, color: true, kind: true },
|
||||
select: STAGE_SELECT,
|
||||
});
|
||||
}
|
||||
|
||||
async list(organizationId: string): Promise<ActivityStageDto[]> {
|
||||
return (await this.rows(organizationId)).map((r) => this.toDto(r));
|
||||
async list(organizationId: string, boardId?: string | null): Promise<ActivityStageDto[]> {
|
||||
return (await this.rows(organizationId, boardId)).map((r) => this.toDto(r));
|
||||
}
|
||||
|
||||
/** اولین مرحلهٔ هر نوع = مقصد فعالیتهای بدون مرحله یا با مرحلهٔ ناهمنوع */
|
||||
@@ -68,8 +226,23 @@ export class ActivityStagesService {
|
||||
return out;
|
||||
}
|
||||
|
||||
async defaults(organizationId: string): Promise<StageDefaults> {
|
||||
return this.defaultsOf(await this.rows(organizationId));
|
||||
/** پیشفرضهای ستون برای همهٔ گروههای محیط */
|
||||
async boardContext(organizationId: string): Promise<BoardStageContext> {
|
||||
const defaultBoard = await this.ensureDefaultBoard(organizationId);
|
||||
const rows = await this.prisma.activityStage.findMany({
|
||||
where: { organizationId },
|
||||
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
||||
select: STAGE_SELECT,
|
||||
});
|
||||
const byBoard = new Map<string, StageRow[]>();
|
||||
for (const r of rows) {
|
||||
const list = byBoard.get(r.boardId) ?? [];
|
||||
list.push(r);
|
||||
byBoard.set(r.boardId, list);
|
||||
}
|
||||
const defaults = new Map<string, StageDefaults>();
|
||||
for (const [boardId, list] of byBoard) defaults.set(boardId, this.defaultsOf(list));
|
||||
return { defaultBoardId: defaultBoard.id, defaults };
|
||||
}
|
||||
|
||||
/** شرط Prisma برای فعالیتهایی که «مؤثراً» در این مرحله هستند */
|
||||
@@ -77,33 +250,54 @@ export class ActivityStagesService {
|
||||
organizationId: string,
|
||||
stageId: string,
|
||||
): Promise<Prisma.ActivityWhereInput> {
|
||||
const rows = await this.rows(organizationId);
|
||||
const stage = rows.find((r) => r.id === stageId);
|
||||
if (!stage) throw new BadRequestException('مرحلهٔ انتخابشده معتبر نیست');
|
||||
const isDefault = this.defaultsOf(rows)[stage.kind] === stage.id;
|
||||
if (!isDefault) return { status: stage.kind, stageId: stage.id };
|
||||
const stage = await this.get(organizationId, stageId);
|
||||
const defaultBoard = await this.ensureDefaultBoard(organizationId);
|
||||
const boardRows = await this.rows(organizationId, stage.boardId);
|
||||
const inBoard = this.boardWhere(stage.boardId, defaultBoard.id);
|
||||
const isDefault = this.defaultsOf(boardRows)[stage.kind] === stage.id;
|
||||
if (!isDefault) {
|
||||
return { AND: [inBoard, { status: stage.kind, stageId: stage.id }] };
|
||||
}
|
||||
return {
|
||||
status: stage.kind,
|
||||
OR: [
|
||||
{ stageId: stage.id },
|
||||
{ stageId: null },
|
||||
{ stage: { kind: { not: stage.kind } } },
|
||||
AND: [
|
||||
inBoard,
|
||||
{ status: stage.kind },
|
||||
{
|
||||
OR: [
|
||||
{ stageId: stage.id },
|
||||
{ stageId: null },
|
||||
{ stage: { kind: { not: stage.kind } } },
|
||||
{ stage: { boardId: { not: stage.boardId } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
effectiveBoardId(row: { boardId?: string | null }, ctx?: BoardStageContext): string | null {
|
||||
return row.boardId ?? ctx?.defaultBoardId ?? null;
|
||||
}
|
||||
|
||||
effectiveStageId(
|
||||
row: { status: ActivityStatus; stage?: { id: string; kind: ActivityStatus } | null },
|
||||
defaults?: StageDefaults,
|
||||
row: {
|
||||
status: ActivityStatus;
|
||||
boardId?: string | null;
|
||||
stage?: { id: string; kind: ActivityStatus; boardId: string } | null;
|
||||
},
|
||||
ctx?: BoardStageContext,
|
||||
): string | null {
|
||||
if (row.stage && row.stage.kind === row.status) return row.stage.id;
|
||||
return defaults?.[row.status] ?? null;
|
||||
const boardId = this.effectiveBoardId(row, ctx);
|
||||
if (row.stage && row.stage.kind === row.status && (!boardId || row.stage.boardId === boardId)) {
|
||||
return row.stage.id;
|
||||
}
|
||||
if (!ctx || !boardId) return null;
|
||||
return ctx.defaults.get(boardId)?.[row.status] ?? null;
|
||||
}
|
||||
|
||||
async get(organizationId: string, id: string): Promise<StageRow> {
|
||||
const row = await this.prisma.activityStage.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: { id: true, name: true, position: true, color: true, kind: true },
|
||||
select: STAGE_SELECT,
|
||||
});
|
||||
if (!row) throw new NotFoundException('مرحله پیدا نشد');
|
||||
return row;
|
||||
@@ -111,22 +305,25 @@ export class ActivityStagesService {
|
||||
|
||||
async create(
|
||||
organizationId: string,
|
||||
dto: { name: string; color?: string; kind?: ActivityStatus },
|
||||
dto: { boardId?: string; name: string; color?: string; kind?: ActivityStatus },
|
||||
): Promise<ActivityStageDto> {
|
||||
await this.ensureDefaults(organizationId);
|
||||
const boardId = await this.resolveBoardId(organizationId, dto.boardId);
|
||||
await this.ensureBoardStages(organizationId, boardId);
|
||||
const max = await this.prisma.activityStage.aggregate({
|
||||
where: { organizationId },
|
||||
where: { boardId },
|
||||
_max: { position: true },
|
||||
});
|
||||
try {
|
||||
const row = await this.prisma.activityStage.create({
|
||||
data: {
|
||||
organizationId,
|
||||
boardId,
|
||||
name: this.cleanName(dto.name),
|
||||
color: this.cleanColor(dto.color),
|
||||
kind: dto.kind && KINDS.includes(dto.kind) ? dto.kind : 'open',
|
||||
position: (max._max.position ?? -1) + 1,
|
||||
},
|
||||
select: STAGE_SELECT,
|
||||
});
|
||||
return this.toDto(row);
|
||||
} catch (e) {
|
||||
@@ -142,7 +339,7 @@ export class ActivityStagesService {
|
||||
const stage = await this.get(organizationId, id);
|
||||
const nextKind = dto.kind && KINDS.includes(dto.kind) ? dto.kind : stage.kind;
|
||||
if (nextKind !== stage.kind) {
|
||||
await this.assertNotLastOfKind(organizationId, stage);
|
||||
await this.assertNotLastOfKind(stage);
|
||||
}
|
||||
try {
|
||||
const row = await this.prisma.$transaction(async (tx) => {
|
||||
@@ -160,6 +357,7 @@ export class ActivityStagesService {
|
||||
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
|
||||
kind: nextKind,
|
||||
},
|
||||
select: STAGE_SELECT,
|
||||
});
|
||||
});
|
||||
return this.toDto(row);
|
||||
@@ -168,34 +366,45 @@ export class ActivityStagesService {
|
||||
}
|
||||
}
|
||||
|
||||
/** ترتیب ستونهای یک گروه؛ همهٔ شناسهها باید از همان گروه باشند */
|
||||
async reorder(organizationId: string, stageIds: string[]): Promise<ActivityStageDto[]> {
|
||||
if (!stageIds.length) return [];
|
||||
const rows = await this.prisma.activityStage.findMany({
|
||||
where: { organizationId, id: { in: stageIds } },
|
||||
select: { id: true, boardId: true },
|
||||
});
|
||||
const boardIds = new Set(rows.map((r) => r.boardId));
|
||||
if (rows.length !== new Set(stageIds).size || boardIds.size !== 1) {
|
||||
throw new BadRequestException('ستونهای ارسالی باید همه از یک گروه باشند');
|
||||
}
|
||||
const [boardId] = [...boardIds];
|
||||
await this.prisma.$transaction(
|
||||
stageIds.map((id, position) =>
|
||||
this.prisma.activityStage.updateMany({
|
||||
where: { id, organizationId },
|
||||
where: { id, organizationId, boardId },
|
||||
data: { position },
|
||||
}),
|
||||
),
|
||||
);
|
||||
return this.list(organizationId);
|
||||
return this.list(organizationId, boardId);
|
||||
}
|
||||
|
||||
async remove(organizationId: string, id: string): Promise<void> {
|
||||
const stage = await this.get(organizationId, id);
|
||||
await this.assertNotLastOfKind(organizationId, stage);
|
||||
// onDelete: SetNull → فعالیتها به اولین مرحلهٔ همنوع وضعیتشان منتقل میشوند
|
||||
await this.assertNotLastOfKind(stage);
|
||||
// onDelete: SetNull → فعالیتها به اولین مرحلهٔ همنوع وضعیتشان در همان گروه منتقل میشوند
|
||||
await this.prisma.activityStage.delete({ where: { id } });
|
||||
}
|
||||
|
||||
private async assertNotLastOfKind(organizationId: string, stage: StageRow) {
|
||||
private async assertNotLastOfKind(stage: StageRow) {
|
||||
const sameKind = await this.prisma.activityStage.count({
|
||||
where: { organizationId, kind: stage.kind },
|
||||
where: { boardId: stage.boardId, kind: stage.kind },
|
||||
});
|
||||
if (sameKind <= 1) {
|
||||
const label =
|
||||
stage.kind === 'done' ? 'انجامشده' : stage.kind === 'canceled' ? 'لغو شده' : 'باز';
|
||||
throw new BadRequestException(
|
||||
`حداقل یک ستون از نوع «${label}» لازم است؛ اول یک ستون دیگر از همین نوع بسازید`,
|
||||
`حداقل یک ستون از نوع «${label}» در هر گروه لازم است؛ اول یک ستون دیگر از همین نوع بسازید`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -207,6 +416,13 @@ export class ActivityStagesService {
|
||||
return name;
|
||||
}
|
||||
|
||||
private cleanBoardName(raw: string): string {
|
||||
const name = raw?.trim() ?? '';
|
||||
if (name.length < 2) throw new BadRequestException('نام گروه حداقل ۲ کاراکتر است');
|
||||
if (name.length > 80) throw new BadRequestException('نام گروه حداکثر ۸۰ کاراکتر است');
|
||||
return name;
|
||||
}
|
||||
|
||||
private cleanColor(raw?: string): ActivityStageColor {
|
||||
return ACTIVITY_STAGE_COLORS.includes(raw as ActivityStageColor)
|
||||
? (raw as ActivityStageColor)
|
||||
@@ -215,7 +431,14 @@ export class ActivityStagesService {
|
||||
|
||||
private mapError(e: unknown) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||
return new BadRequestException('ستونی با این نام وجود دارد');
|
||||
return new BadRequestException('ستونی با این نام در این گروه وجود دارد');
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
private mapBoardError(e: unknown) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||
return new BadRequestException('گروهی با این نام وجود دارد');
|
||||
}
|
||||
return e;
|
||||
}
|
||||
@@ -223,6 +446,7 @@ export class ActivityStagesService {
|
||||
private toDto(row: StageRow): ActivityStageDto {
|
||||
return {
|
||||
id: row.id,
|
||||
boardId: row.boardId,
|
||||
name: row.name,
|
||||
position: row.position,
|
||||
color: this.cleanColor(row.color),
|
||||
|
||||
@@ -79,6 +79,11 @@ export class ListActivitiesQueryDto {
|
||||
@IsString()
|
||||
stageId?: string;
|
||||
|
||||
/** گروه فعالیت؛ خالی = همهٔ گروهها (در شمارش ستونها = گروه پیشفرض) */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
boardId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
personId?: string;
|
||||
@@ -121,7 +126,33 @@ export class ListActivitiesQueryDto {
|
||||
|
||||
const STAGE_COLORS = ['green', 'orange', 'purple', 'blue', 'rose', 'slate'] as const;
|
||||
|
||||
export class CreateActivityBoardDto {
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
@MaxLength(80)
|
||||
name!: string;
|
||||
}
|
||||
|
||||
export class UpdateActivityBoardDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
@MaxLength(80)
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export class ListActivityStagesQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
boardId?: string;
|
||||
}
|
||||
|
||||
export class CreateActivityStageDto {
|
||||
/** خالی = گروه پیشفرض */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
boardId?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(80)
|
||||
@@ -229,6 +260,11 @@ export class CreateActivityDto {
|
||||
@MaxLength(200)
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@ValidateIf((_, v) => v !== '' && v != null)
|
||||
@IsString()
|
||||
boardId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@ValidateIf((_, v) => v !== '' && v != null)
|
||||
@IsString()
|
||||
@@ -319,6 +355,12 @@ export class UpdateActivityDto {
|
||||
@MaxLength(200)
|
||||
title?: string;
|
||||
|
||||
/** null/خالی = گروه پیشفرض */
|
||||
@IsOptional()
|
||||
@ValidateIf((_, v) => v !== '' && v != null)
|
||||
@IsString()
|
||||
boardId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(ACTIVITY_TYPES)
|
||||
type?: (typeof ACTIVITY_TYPES)[number];
|
||||
|
||||
@@ -53,6 +53,7 @@ import { GamificationModule } from './gamification/gamification.module';
|
||||
import { DeletionsModule } from './deletions/deletions.module';
|
||||
import { OutboundSmsModule } from './outbound-sms/outbound-sms.module';
|
||||
import { BehaviorModule } from './behavior/behavior.module';
|
||||
import { SmsBillingModule } from './sms-billing/sms-billing.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -63,6 +64,7 @@ import { BehaviorModule } from './behavior/behavior.module';
|
||||
ScheduleModule.forRoot(),
|
||||
AiModule,
|
||||
PrismaModule,
|
||||
SmsBillingModule,
|
||||
OutboundSmsModule,
|
||||
StorageModule,
|
||||
HealthModule,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const TEHRAN = 'Asia/Tehran';
|
||||
|
||||
export type AttendanceKind = 'login' | 'logout' | 'forced_logout';
|
||||
|
||||
export function tehranDateKey(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: TEHRAN,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).format(date);
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** ساعت HH:mm امروز به وقت تهران، به صورت لحظهٔ مطلق */
|
||||
export function tehranCutoff(now: Date, hhmm: string): Date | null {
|
||||
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(hhmm.trim());
|
||||
if (!match) return null;
|
||||
const day = tehranDateKey(now);
|
||||
return new Date(`${day}T${match[1]}:${match[2]}:00+03:30`);
|
||||
}
|
||||
|
||||
export function isPastLogoutTime(now: Date, hhmm: string | null | undefined): boolean {
|
||||
if (!hhmm) return false;
|
||||
const cutoff = tehranCutoff(now, hhmm);
|
||||
if (!cutoff) return false;
|
||||
return now.getTime() >= cutoff.getTime();
|
||||
}
|
||||
|
||||
export function loggedInAfterCutoff(at: Date, hhmm: string | null | undefined): boolean {
|
||||
if (!hhmm) return false;
|
||||
const cutoff = tehranCutoff(at, hhmm);
|
||||
if (!cutoff) return false;
|
||||
return at.getTime() >= cutoff.getTime();
|
||||
}
|
||||
|
||||
export function tehranClock(date: Date): string {
|
||||
return new Intl.DateTimeFormat('fa-IR', {
|
||||
timeZone: TEHRAN,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
}).format(date);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AttendanceService } from './attendance.service';
|
||||
|
||||
@Module({
|
||||
providers: [AttendanceService],
|
||||
exports: [AttendanceService],
|
||||
})
|
||||
export class AttendanceModule {}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import {
|
||||
loggedInAfterCutoff,
|
||||
tehranClock,
|
||||
tehranCutoff,
|
||||
type AttendanceKind,
|
||||
} from './attendance-time';
|
||||
|
||||
export const WORKDAY_ENDED_MESSAGE =
|
||||
'ساعت کاری امروز تمام شده است. برای ادامه دوباره وارد شوید.';
|
||||
|
||||
type RecordInput = {
|
||||
organizationId: string;
|
||||
userId: string;
|
||||
role: string;
|
||||
kind: AttendanceKind;
|
||||
at: Date;
|
||||
afterHours: boolean;
|
||||
sessionStartedAt: Date | null;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AttendanceService {
|
||||
private readonly logger = new Logger(AttendanceService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async recordLogin(organizationId: string, userId: string, role: string, at = new Date()) {
|
||||
if (role === 'owner') {
|
||||
await this.write({
|
||||
organizationId,
|
||||
userId,
|
||||
role,
|
||||
kind: 'login',
|
||||
at,
|
||||
afterHours: false,
|
||||
sessionStartedAt: at,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const membership = await this.prisma.membership.findFirst({
|
||||
where: { organizationId, userId, isActive: true },
|
||||
select: { logoutTime: true },
|
||||
});
|
||||
const afterHours = loggedInAfterCutoff(at, membership?.logoutTime);
|
||||
await this.write({
|
||||
organizationId,
|
||||
userId,
|
||||
role,
|
||||
kind: 'login',
|
||||
at,
|
||||
afterHours,
|
||||
sessionStartedAt: at,
|
||||
});
|
||||
}
|
||||
|
||||
async recordLogout(actor: Actor) {
|
||||
if (actor.viewAsReadOnly) return { ok: true };
|
||||
const at = new Date();
|
||||
await this.write({
|
||||
organizationId: actor.organizationId,
|
||||
userId: actor.userId,
|
||||
role: actor.role,
|
||||
kind: 'logout',
|
||||
at,
|
||||
afterHours: false,
|
||||
sessionStartedAt: actor.sessionStartedAt ?? at,
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** اگر نشست قبل از ساعت خروج امروز شروع شده و آن ساعت گذشته، یک بار خروج اجباری ثبت و رد میشود. */
|
||||
async assertSession(actor: Actor) {
|
||||
if (actor.viewAsReadOnly || actor.role === 'owner' || !actor.sessionStartedAt) return;
|
||||
const membership = await this.prisma.membership.findFirst({
|
||||
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
|
||||
select: { logoutTime: true, role: true },
|
||||
});
|
||||
const logoutTime = membership?.logoutTime;
|
||||
if (!logoutTime || membership?.role === 'owner') return;
|
||||
const now = new Date();
|
||||
const cutoff = tehranCutoff(now, logoutTime);
|
||||
if (!cutoff || now.getTime() < cutoff.getTime()) return;
|
||||
if (actor.sessionStartedAt.getTime() >= cutoff.getTime()) return;
|
||||
|
||||
await this.write({
|
||||
organizationId: actor.organizationId,
|
||||
userId: actor.userId,
|
||||
role: actor.role,
|
||||
kind: 'forced_logout',
|
||||
at: now,
|
||||
afterHours: false,
|
||||
sessionStartedAt: actor.sessionStartedAt,
|
||||
});
|
||||
throw new UnauthorizedException(WORKDAY_ENDED_MESSAGE);
|
||||
}
|
||||
|
||||
async list(
|
||||
organizationId: string,
|
||||
opts: { q?: string; userId?: string; page?: number; limit?: number },
|
||||
) {
|
||||
const page = opts.page ?? 1;
|
||||
const limit = opts.limit ?? 20;
|
||||
const q = opts.q?.trim();
|
||||
const where: Prisma.AttendanceEventWhereInput = {
|
||||
organizationId,
|
||||
...(opts.userId ? { userId: opts.userId } : {}),
|
||||
...(q
|
||||
? { user: { fullName: { contains: q, mode: 'insensitive' } } }
|
||||
: {}),
|
||||
};
|
||||
const [rows, total] = await this.prisma.$transaction([
|
||||
this.prisma.attendanceEvent.findMany({
|
||||
where,
|
||||
include: { user: { select: { fullName: true } } },
|
||||
orderBy: { at: 'desc' },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
}),
|
||||
this.prisma.attendanceEvent.count({ where }),
|
||||
]);
|
||||
return {
|
||||
items: rows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
fullName: row.user.fullName,
|
||||
kind: row.kind as AttendanceKind,
|
||||
at: row.at.toISOString(),
|
||||
afterHours: row.afterHours,
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
};
|
||||
}
|
||||
|
||||
private async write(input: RecordInput) {
|
||||
try {
|
||||
await this.prisma.attendanceEvent.create({
|
||||
data: {
|
||||
organizationId: input.organizationId,
|
||||
userId: input.userId,
|
||||
kind: input.kind,
|
||||
at: input.at,
|
||||
afterHours: input.afterHours,
|
||||
sessionStartedAt: input.sessionStartedAt,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (input.role === 'owner') return;
|
||||
void this.notifyOwner(input).catch((err) => {
|
||||
this.logger.warn(`پیامک ورود و خروج ناموفق بود: ${err instanceof Error ? err.message : err}`);
|
||||
});
|
||||
}
|
||||
|
||||
private async notifyOwner(input: RecordInput) {
|
||||
const owner = await this.prisma.membership.findFirst({
|
||||
where: { organizationId: input.organizationId, role: 'owner', isActive: true },
|
||||
select: { userId: true, user: { select: { mobile: true } } },
|
||||
});
|
||||
if (!owner?.user.mobile || owner.userId === input.userId) return;
|
||||
const person = await this.prisma.user.findUnique({
|
||||
where: { id: input.userId },
|
||||
select: { fullName: true },
|
||||
});
|
||||
const name = person?.fullName?.trim() || 'کارمند';
|
||||
const clock = tehranClock(input.at);
|
||||
const text =
|
||||
input.kind === 'login'
|
||||
? input.afterHours
|
||||
? `${name} بعد از ساعت خروج دوباره وارد منتکت شد. ساعت ${clock}`
|
||||
: `${name} وارد منتکت شد. ساعت ${clock}`
|
||||
: input.kind === 'forced_logout'
|
||||
? `${name} در ساعت تعیینشده از منتکت خارج شد. ساعت ${clock}`
|
||||
: `${name} از منتکت خارج شد. ساعت ${clock}`;
|
||||
await this.sms.send({
|
||||
organizationId: input.organizationId,
|
||||
phone: owner.user.mobile,
|
||||
text,
|
||||
source: 'attendance',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { AttendanceService } from './attendance.service';
|
||||
|
||||
@Injectable()
|
||||
export class WorkdayInterceptor implements NestInterceptor {
|
||||
constructor(private readonly attendance: AttendanceService) {}
|
||||
|
||||
async intercept(context: ExecutionContext, next: CallHandler) {
|
||||
if (context.getType() !== 'http') return next.handle();
|
||||
const req = context.switchToHttp().getRequest<{
|
||||
user?: Actor;
|
||||
originalUrl?: string;
|
||||
url?: string;
|
||||
}>();
|
||||
const actor = req.user;
|
||||
const path = req.originalUrl || req.url || '';
|
||||
if (!actor?.userId || path.includes('/auth/logout')) return next.handle();
|
||||
await this.attendance.assertSession(actor);
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { RolesGuard } from '../auth/roles.guard';
|
||||
import { OrgModuleGuard } from '../billing/org-module.guard';
|
||||
import { RequireOrgModule } from '../billing/org-module.decorator';
|
||||
import { AuditLogsService } from './audit-logs.service';
|
||||
import { AttendanceService } from '../attendance/attendance.service';
|
||||
|
||||
class ListAuditQueryDto {
|
||||
@IsOptional()
|
||||
@@ -45,7 +46,23 @@ class ListAuditQueryDto {
|
||||
@RequireOrgModule('audit_logs')
|
||||
@Roles('owner', 'admin')
|
||||
export class AuditLogsController {
|
||||
constructor(private readonly auditLogs: AuditLogsService) {}
|
||||
constructor(
|
||||
private readonly auditLogs: AuditLogsService,
|
||||
private readonly attendance: AttendanceService,
|
||||
) {}
|
||||
|
||||
@Get('attendance')
|
||||
attendanceList(
|
||||
@CurrentUser() user: { organizationId: string },
|
||||
@Query() query: ListAuditQueryDto,
|
||||
) {
|
||||
return this.attendance.list(user.organizationId, {
|
||||
q: query.q,
|
||||
userId: query.actorUserId,
|
||||
page: query.page,
|
||||
limit: query.limit,
|
||||
});
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
|
||||
@@ -2,12 +2,13 @@ import { Module } from '@nestjs/common';
|
||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { AttendanceModule } from '../attendance/attendance.module';
|
||||
import { AuditLogsController } from './audit-logs.controller';
|
||||
import { AuditLogsInterceptor } from './audit-logs.interceptor';
|
||||
import { AuditLogsService } from './audit-logs.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, BillingModule],
|
||||
imports: [AuthModule, BillingModule, AttendanceModule],
|
||||
controllers: [AuditLogsController],
|
||||
providers: [
|
||||
AuditLogsService,
|
||||
|
||||
@@ -80,6 +80,12 @@ export class AuthController {
|
||||
return this.authService.listMyOrganizations(user.userId);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('logout')
|
||||
logout(@CurrentUser() user: Actor) {
|
||||
return this.authService.logout(user);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('me')
|
||||
me(@CurrentUser() user: Actor) {
|
||||
|
||||
@@ -5,18 +5,20 @@ import { PassportModule } from '@nestjs/passport';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { MembershipsModule } from '../memberships/memberships.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { AttendanceModule } from '../attendance/attendance.module';
|
||||
import { WorkdayInterceptor } from '../attendance/workday.interceptor';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { ViewAsReadOnlyInterceptor } from './view-as-readonly.interceptor';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
MembershipsModule,
|
||||
BillingModule,
|
||||
AttendanceModule,
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -34,11 +36,14 @@ import { SmsService } from '../common/sms.service';
|
||||
AuthService,
|
||||
JwtStrategy,
|
||||
RolesGuard,
|
||||
SmsService,
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: ViewAsReadOnlyInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: WorkdayInterceptor,
|
||||
},
|
||||
],
|
||||
exports: [AuthService, RolesGuard, JwtModule],
|
||||
})
|
||||
|
||||
@@ -22,10 +22,11 @@ import { Prisma } from '@prisma/client';
|
||||
/** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */
|
||||
import type {} from 'multer';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||
import { MembershipsService } from '../memberships/memberships.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { AttendanceService } from '../attendance/attendance.service';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import {
|
||||
LoginDto,
|
||||
@@ -106,10 +107,11 @@ export class AuthService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwt: JwtService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
private readonly files: LocalFileStorage,
|
||||
private readonly memberships: MembershipsService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly attendance: AttendanceService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -172,7 +174,7 @@ export class AuthService {
|
||||
if (emailOtpEnabled && emailCode) {
|
||||
await this.dispatchEmailOtp(email, emailCode, returnOtp);
|
||||
}
|
||||
await this.dispatchMobileOtp(mobile, mobileCode, returnOtp);
|
||||
await this.dispatchMobileOtp(mobile, mobileCode, returnOtp, null);
|
||||
|
||||
return {
|
||||
challengeId: challenge.id,
|
||||
@@ -351,7 +353,7 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
await this.dispatchMobileOtp(mobile, code, returnOtp);
|
||||
await this.dispatchMobileOtp(mobile, code, returnOtp, user.organizationId);
|
||||
|
||||
return {
|
||||
challengeId: challenge.id,
|
||||
@@ -407,6 +409,10 @@ export class AuthService {
|
||||
return this.finishLogin(user.id);
|
||||
}
|
||||
|
||||
async logout(actor: Actor) {
|
||||
return this.attendance.recordLogout(actor);
|
||||
}
|
||||
|
||||
async me(userId: string, organizationId: string, actor?: Actor): Promise<AuthUserDto> {
|
||||
await this.memberships.requireActive(userId, organizationId);
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
@@ -727,6 +733,7 @@ export class AuthService {
|
||||
where: { id: userId },
|
||||
data: { lastLoginAt: new Date() },
|
||||
});
|
||||
await this.attendance.recordLogin(organizationId, userId, membership.role);
|
||||
}
|
||||
const accessToken = this.jwt.sign({
|
||||
sub: userId,
|
||||
@@ -868,9 +875,10 @@ export class AuthService {
|
||||
mobile: string,
|
||||
code: string,
|
||||
returnOtp: boolean,
|
||||
organizationId: string | null,
|
||||
) {
|
||||
if (this.sms.isConfigured()) {
|
||||
const sent = await this.sms.sendOtpSms(mobile, code);
|
||||
if (this.sms.isConfigured() || organizationId) {
|
||||
const sent = await this.sms.sendOtp(organizationId, mobile, code);
|
||||
if (!sent && !returnOtp) {
|
||||
throw new BadRequestException(
|
||||
'ارسال پیامک ناموفق بود؛ کمی بعد دوباره تلاش کنید',
|
||||
|
||||
@@ -34,7 +34,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload & { typ?: string; mobile?: string }) {
|
||||
async validate(payload: JwtPayload & { typ?: string; mobile?: string; iat?: number }) {
|
||||
if (
|
||||
payload.typ === 'portal' ||
|
||||
payload.typ === 'org-select' ||
|
||||
@@ -135,6 +135,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
priorGranted && membership.organization.priorArchiveEnabledAt
|
||||
? membership.organization.priorArchiveEnabledAt
|
||||
: null,
|
||||
sessionStartedAt: payload.iat ? new Date(payload.iat * 1000) : new Date(),
|
||||
...(viewAsReadOnly && impersonatorUserId
|
||||
? {
|
||||
impersonatorUserId,
|
||||
|
||||
@@ -2,14 +2,13 @@ import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { LoyaltyModule } from '../loyalty/loyalty.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { AutomationsController } from './automations.controller';
|
||||
import { AutomationsService } from './automations.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, NotificationsModule, LoyaltyModule],
|
||||
controllers: [AutomationsController],
|
||||
providers: [AutomationsService, SmsService],
|
||||
providers: [AutomationsService],
|
||||
exports: [AutomationsService],
|
||||
})
|
||||
export class AutomationsModule {}
|
||||
|
||||
@@ -32,7 +32,7 @@ import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { LoyaltyService } from '../loyalty/loyalty.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import {
|
||||
formatFormAnswers,
|
||||
pickRoundRobin,
|
||||
@@ -79,7 +79,7 @@ export class AutomationsService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly loyalty: LoyaltyService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async list(organizationId: string): Promise<AutomationRuleDto[]> {
|
||||
@@ -537,7 +537,11 @@ export class AutomationsService {
|
||||
select: { mobile: true, phone: true },
|
||||
})
|
||||
: null;
|
||||
await this.sendAutomationSms(person?.mobile || person?.phone, smsText);
|
||||
await this.sendAutomationSms(
|
||||
ctx.organizationId,
|
||||
person?.mobile || person?.phone,
|
||||
smsText,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -570,11 +574,12 @@ export class AutomationsService {
|
||||
},
|
||||
select: { mobile: true },
|
||||
});
|
||||
await this.sendAutomationSms(user?.mobile, smsText);
|
||||
await this.sendAutomationSms(ctx.organizationId, user?.mobile, smsText);
|
||||
}
|
||||
}
|
||||
|
||||
private async sendAutomationSms(
|
||||
organizationId: string,
|
||||
mobile: string | null | undefined,
|
||||
text: string,
|
||||
) {
|
||||
@@ -582,11 +587,12 @@ export class AutomationsService {
|
||||
this.logger.warn('Automation SMS skipped: no mobile');
|
||||
return;
|
||||
}
|
||||
if (!this.sms.isConfigured()) {
|
||||
this.logger.warn('Automation SMS skipped: SMS not configured');
|
||||
return;
|
||||
}
|
||||
const result = await this.sms.sendSmsDetailed(mobile, text);
|
||||
const result = await this.sms.send({
|
||||
organizationId,
|
||||
phone: mobile,
|
||||
text,
|
||||
source: 'automation',
|
||||
});
|
||||
if (!result.ok) {
|
||||
this.logger.warn(`Automation SMS failed: ${result.reason ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
@@ -170,9 +170,34 @@ export function parseAmount(raw?: string): number | null {
|
||||
}
|
||||
|
||||
/** تاریخ تولد: سال زیر ۱۷۰۰ شمسی است، سال ۱۷۰۰ به بعد میلادی. ظهر UTC تا روز جابهجا نشود. */
|
||||
/** «۲۰۲۴-۰۵-۰۱T۱۹:۳۰:۰۰Z» و مشابه: لحظهٔ دقیق با منطقهٔ زمانی */
|
||||
const ZONED_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/i;
|
||||
|
||||
function tehranCalendarDay(d: Date): { y: number; m: number; d: number } {
|
||||
const [y, m, day] = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Tehran',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
})
|
||||
.format(d)
|
||||
.split('-')
|
||||
.map(Number);
|
||||
return { y, m, d: day };
|
||||
}
|
||||
|
||||
export function parseBirthDate(raw?: string | null): Date | null {
|
||||
const text = toAsciiDigits(String(raw ?? '')).trim();
|
||||
if (!text || text === '-' || text === '0' || text === '0000-00-00') return null;
|
||||
// تاریخ تولد فقط «روز» است. لحظهٔ UTC (مثلاً نیمهشب تهران که به روز قبلِ UTC میافتد)
|
||||
// باید با تقویم تهران به روز تبدیل شود، نه با بریدن بخش تاریخِ UTC.
|
||||
if (ZONED_TIMESTAMP.test(text)) {
|
||||
const instant = new Date(text);
|
||||
if (!Number.isNaN(instant.getTime())) {
|
||||
const day = tehranCalendarDay(instant);
|
||||
return new Date(Date.UTC(day.y, day.m - 1, day.d, 12, 0, 0));
|
||||
}
|
||||
}
|
||||
const datePart = text.split(/[T\s]/)[0] ?? text;
|
||||
const match = /^(\d{3,4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})$/.exec(datePart);
|
||||
if (!match) {
|
||||
|
||||
@@ -27,6 +27,8 @@ export type Actor = {
|
||||
/** مالک واقعی وقتی در حالت مشاهده بهجای کاربر دیگر است */
|
||||
impersonatorUserId?: string;
|
||||
impersonatorRole?: string;
|
||||
/** شروع این نشست؛ برای ساعت خروج روزانه */
|
||||
sessionStartedAt?: Date;
|
||||
/** در حالت مشاهده، سرور تغییر را رد میکند */
|
||||
viewAsReadOnly?: boolean;
|
||||
};
|
||||
|
||||
@@ -10,8 +10,19 @@ const SMS_0098_SOAP_URL = 'https://webservice.0098sms.com/service.asmx';
|
||||
|
||||
export type SmsSendResult = {
|
||||
ok: boolean;
|
||||
transport: 'trez' | 'soap' | 'link';
|
||||
blocked?: boolean;
|
||||
transport: 'trez' | 'soap' | 'link' | 'none';
|
||||
reason?: string;
|
||||
parts?: number;
|
||||
costRials?: number;
|
||||
};
|
||||
|
||||
export type SmsTransportOverride = {
|
||||
username: string;
|
||||
password: string;
|
||||
sender: string;
|
||||
/** trez | 0098 — default 0098 for own panels */
|
||||
provider?: 'trez' | '0098';
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
@@ -50,17 +61,29 @@ export class SmsService {
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
async sendSmsDetailed(phone: string, text: string): Promise<SmsSendResult> {
|
||||
const username = this.config.get<string>('SMS_USERNAME');
|
||||
const password = this.getPassword();
|
||||
const sender = this.config.get<string>('SMS_SENDER');
|
||||
buildOtpText(code: string): string {
|
||||
const template =
|
||||
this.config.get<string>('SMS_OTP_TEMPLATE')?.trim() ||
|
||||
`کد ورود منتکت: {code}`;
|
||||
return template.replace('{code}', code);
|
||||
}
|
||||
|
||||
async sendSmsDetailed(
|
||||
phone: string,
|
||||
text: string,
|
||||
override?: SmsTransportOverride,
|
||||
): Promise<SmsSendResult> {
|
||||
const username = override?.username || this.config.get<string>('SMS_USERNAME');
|
||||
const password = override?.password || this.getPassword();
|
||||
const sender = override?.sender || this.config.get<string>('SMS_SENDER');
|
||||
|
||||
if (!username || !password || !sender) {
|
||||
return { ok: false, transport: 'trez', reason: 'SMS not configured' };
|
||||
return { ok: false, transport: 'none', reason: 'SMS not configured' };
|
||||
}
|
||||
|
||||
const to = this.normalizePhoneForSms(phone);
|
||||
const provider = this.resolveProvider();
|
||||
const provider =
|
||||
override?.provider ?? this.resolveProvider();
|
||||
|
||||
if (provider === 'trez') {
|
||||
return this.sendViaTrez(username, password, sender, to, text);
|
||||
|
||||
@@ -8,7 +8,6 @@ import { CompaniesService } from './companies.service';
|
||||
import { PeopleController } from './people.controller';
|
||||
import { PeopleService } from './people.service';
|
||||
import { ContactsExcelService } from './contacts-excel.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { BehaviorModule } from '../behavior/behavior.module';
|
||||
|
||||
@Module({
|
||||
@@ -20,7 +19,7 @@ import { BehaviorModule } from '../behavior/behavior.module';
|
||||
BehaviorModule,
|
||||
],
|
||||
controllers: [PeopleController, CompaniesController],
|
||||
providers: [PeopleService, CompaniesService, ContactsExcelService, SmsService],
|
||||
providers: [PeopleService, CompaniesService, ContactsExcelService],
|
||||
exports: [PeopleService, CompaniesService],
|
||||
})
|
||||
export class ContactsModule {}
|
||||
|
||||
@@ -41,7 +41,7 @@ import { MessageAutomationsService } from '../message-automations/message-automa
|
||||
import { WebhooksService } from '../public-api/webhooks.service';
|
||||
import { GamificationService } from '../gamification/gamification.service';
|
||||
import { parseBirthDate } from '../common/excel';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import { selectMonthBirthdays } from './birthday-month';
|
||||
import { renderSmsText } from '../common/sms-text';
|
||||
import { normalizeTags } from '../common/tags';
|
||||
@@ -131,7 +131,7 @@ export class PeopleService implements OnModuleInit {
|
||||
private readonly messageAutomations: MessageAutomationsService,
|
||||
private readonly webhooks: WebhooksService,
|
||||
private readonly game: GamificationService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
private readonly outboundSms: OutboundSmsLogService,
|
||||
private readonly behaviorAccess: BehaviorAccessService,
|
||||
) {}
|
||||
@@ -662,7 +662,12 @@ export class PeopleService implements OnModuleInit {
|
||||
company: person.company?.name ?? '',
|
||||
});
|
||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||
const result = await this.sms.sendSmsDetailed(mobile, message);
|
||||
const result = await this.sms.send({
|
||||
organizationId: actor.organizationId,
|
||||
phone: mobile,
|
||||
text: message,
|
||||
source: 'manual',
|
||||
});
|
||||
await this.outboundSms.record({
|
||||
organizationId: actor.organizationId,
|
||||
personId: person.id,
|
||||
@@ -675,9 +680,11 @@ export class PeopleService implements OnModuleInit {
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new ServiceUnavailableException(
|
||||
result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
result.blocked
|
||||
? 'ارسال پیامک بهخاطر محدودیت اعتبار مسدود است.'
|
||||
: result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
);
|
||||
}
|
||||
return { ok: true };
|
||||
@@ -698,7 +705,12 @@ export class PeopleService implements OnModuleInit {
|
||||
company: person.company?.name ?? '',
|
||||
});
|
||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||
const result = await this.sms.sendSmsDetailed(mobile, message);
|
||||
const result = await this.sms.send({
|
||||
organizationId: actor.organizationId,
|
||||
phone: mobile,
|
||||
text: message,
|
||||
source: 'manual',
|
||||
});
|
||||
await this.outboundSms.record({
|
||||
organizationId: actor.organizationId,
|
||||
personId: person.id,
|
||||
@@ -711,9 +723,11 @@ export class PeopleService implements OnModuleInit {
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new ServiceUnavailableException(
|
||||
result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
result.blocked
|
||||
? 'ارسال پیامک بهخاطر محدودیت اعتبار مسدود است.'
|
||||
: result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
);
|
||||
}
|
||||
return { ok: true };
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import {
|
||||
CHEQUE_REMINDER_DAYS,
|
||||
isDueInDays,
|
||||
@@ -18,7 +18,7 @@ export class ChequeRemindersService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
@Cron('0 8 * * *', { timeZone: 'Asia/Tehran' })
|
||||
@@ -134,20 +134,27 @@ export class ChequeRemindersService {
|
||||
dedupe: true,
|
||||
});
|
||||
if (user.mobile) {
|
||||
await this.sms.sendSmsDetailed(user.mobile, staffText);
|
||||
await this.sms.send({
|
||||
organizationId: row.organizationId,
|
||||
phone: user.mobile,
|
||||
text: staffText,
|
||||
source: 'cheque_reminder',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (incoming && row.person?.mobile) {
|
||||
await this.sms.sendSmsDetailed(
|
||||
row.person.mobile,
|
||||
personIncomingSms({
|
||||
await this.sms.send({
|
||||
organizationId: row.organizationId,
|
||||
phone: row.person.mobile,
|
||||
text: personIncomingSms({
|
||||
number: row.number,
|
||||
amount,
|
||||
currency: row.currency,
|
||||
dueDate: row.dueDate,
|
||||
}),
|
||||
);
|
||||
source: 'cheque_reminder',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { TreasuryModule } from '../treasury/treasury.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { ChequesService } from './cheques.service';
|
||||
import { ChequeRemindersService } from './cheque-reminders.service';
|
||||
import { CommissionsService } from './commissions.service';
|
||||
@@ -11,7 +10,7 @@ import { FinanceController } from './finance.controller';
|
||||
@Module({
|
||||
imports: [AuthModule, NotificationsModule, TreasuryModule],
|
||||
controllers: [FinanceController],
|
||||
providers: [ChequesService, ChequeRemindersService, CommissionsService, SmsService],
|
||||
providers: [ChequesService, ChequeRemindersService, CommissionsService],
|
||||
exports: [ChequesService, CommissionsService],
|
||||
})
|
||||
export class FinanceModule {}
|
||||
|
||||
@@ -507,7 +507,13 @@ export class TahesabPersonLinkService {
|
||||
dto.moshtariCode,
|
||||
dto.moshtariCode,
|
||||
);
|
||||
row = (asMoshtariList(raw)[0] ?? {}) as Record<string, unknown>;
|
||||
const found = asMoshtariList(raw)[0];
|
||||
if (!found) {
|
||||
throw new NotFoundException(
|
||||
`مشتری با کد ${dto.moshtariCode} در تهحساب یافت نشد.`,
|
||||
);
|
||||
}
|
||||
row = found as Record<string, unknown>;
|
||||
}
|
||||
const name = pickName(row) || `مشتری تهحساب ${dto.moshtariCode}`;
|
||||
const tel = pickTel(row);
|
||||
@@ -548,12 +554,15 @@ export class TahesabPersonLinkService {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام تهحساب جایگزین
|
||||
// اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام تهحساب جایگزین.
|
||||
// شخصی که روی همین اتصال به کد دیگری لینک است کنار گذاشته میشود؛
|
||||
// وگرنه upsert لینک، کد قبلی را جابهجا و آن مشتری را دوباره «واردنشده» میکند.
|
||||
const byMobile = mobile
|
||||
? await this.prisma.person.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
OR: [{ mobile }, { phone: mobile }],
|
||||
accountingLinks: { none: { connectionId: dto.connectionId } },
|
||||
},
|
||||
})
|
||||
: null;
|
||||
|
||||
@@ -176,6 +176,9 @@ export function normalizeMandehResponse(raw: unknown): NormalizedAssets {
|
||||
};
|
||||
}
|
||||
|
||||
/** تهحساب برای بازه/جستجوی بدون نتیجه بهجای لیست خالی خطای «هیچ رکوردی یافت نشد» میدهد */
|
||||
const NO_RECORDS = { emptyResultOnError: /رکوردی یافت نشد/i };
|
||||
|
||||
export class TahesabApi {
|
||||
constructor(
|
||||
private readonly http: TahesabHttpClient,
|
||||
@@ -307,15 +310,30 @@ export class TahesabApi {
|
||||
[fromCode, toCode],
|
||||
'POST',
|
||||
opts?.timeoutMs,
|
||||
NO_RECORDS,
|
||||
);
|
||||
}
|
||||
|
||||
doListMoshtariByPhone(phone: string | number) {
|
||||
return this.call('DoListMoshtari-ByPhone', 'DoListMoshtari', [phone]);
|
||||
return this.call(
|
||||
'DoListMoshtari-ByPhone',
|
||||
'DoListMoshtari',
|
||||
[phone],
|
||||
undefined,
|
||||
undefined,
|
||||
NO_RECORDS,
|
||||
);
|
||||
}
|
||||
|
||||
doListMoshtariByName(name: string) {
|
||||
return this.call('DoListMoshtari-ByName', 'DoListMoshtari', [name]);
|
||||
return this.call(
|
||||
'DoListMoshtari-ByName',
|
||||
'DoListMoshtari',
|
||||
[name],
|
||||
undefined,
|
||||
undefined,
|
||||
NO_RECORDS,
|
||||
);
|
||||
}
|
||||
|
||||
/** body key حساس به حروف کوچک مثل همکار */
|
||||
|
||||
@@ -104,6 +104,8 @@ export class LeadFollowUpDto {
|
||||
export class ConvertLeadDto {
|
||||
@IsOptional() @IsString() firstName?: string;
|
||||
@IsOptional() @IsString() lastName?: string;
|
||||
/** سرویس همیشه در نبود شخص همموبایل، شخص جدید میسازد؛ برای سازگاری با کلاینت پذیرفته میشود */
|
||||
@IsOptional() @IsBoolean() createIfMissing?: boolean;
|
||||
}
|
||||
|
||||
export class CreateLeadStageDto {
|
||||
|
||||
@@ -5,12 +5,11 @@ import { LeadStagesService } from './lead-stages.service';
|
||||
import { LeadsController } from './leads.controller';
|
||||
import { LeadsImportService } from './leads-import.service';
|
||||
import { LeadsService } from './leads.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, BillingModule],
|
||||
controllers: [LeadsController],
|
||||
providers: [LeadsService, LeadStagesService, LeadsImportService, SmsService],
|
||||
providers: [LeadsService, LeadStagesService, LeadsImportService],
|
||||
exports: [LeadsService, LeadStagesService],
|
||||
})
|
||||
export class LeadsModule {}
|
||||
|
||||
@@ -21,7 +21,7 @@ import type {
|
||||
} from '@mento/shared';
|
||||
import { FILTERED_IDS_MAX } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import { renderSmsText } from '../common/sms-text';
|
||||
import { OutboundSmsLogService } from '../outbound-sms/outbound-sms-log.service';
|
||||
import {
|
||||
@@ -87,7 +87,7 @@ export class LeadsService {
|
||||
private readonly stages: LeadStagesService,
|
||||
private readonly files: LocalFileStorage,
|
||||
private readonly game: GamificationService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
private readonly outboundSms: OutboundSmsLogService,
|
||||
) {}
|
||||
|
||||
@@ -596,7 +596,11 @@ export class LeadsService {
|
||||
throw new BadRequestException('فقط مدیر میتواند تخصیص دهد');
|
||||
}
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: { id: assigneeId, organizationId: actor.organizationId },
|
||||
where: {
|
||||
id: assigneeId,
|
||||
isActive: true,
|
||||
memberships: { some: { organizationId: actor.organizationId, isActive: true } },
|
||||
},
|
||||
});
|
||||
if (!user) throw new NotFoundException('کارشناس پیدا نشد');
|
||||
|
||||
@@ -669,15 +673,14 @@ export class LeadsService {
|
||||
let assignees = opts.assigneeIds?.length
|
||||
? await this.prisma.user.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
id: { in: opts.assigneeIds },
|
||||
isActive: true,
|
||||
memberships: { some: { organizationId: actor.organizationId, isActive: true } },
|
||||
},
|
||||
select: { id: true, fullName: true },
|
||||
})
|
||||
: await this.prisma.user.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
isActive: true,
|
||||
memberships: {
|
||||
some: {
|
||||
@@ -1291,7 +1294,12 @@ export class LeadsService {
|
||||
company: lead.contactName ? lead.title : '',
|
||||
});
|
||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||
const result = await this.sms.sendSmsDetailed(mobile, message);
|
||||
const result = await this.sms.send({
|
||||
organizationId: actor.organizationId,
|
||||
phone: mobile,
|
||||
text: message,
|
||||
source: 'manual',
|
||||
});
|
||||
await this.outboundSms.record({
|
||||
organizationId: actor.organizationId,
|
||||
leadId: id,
|
||||
@@ -1304,9 +1312,11 @@ export class LeadsService {
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new ServiceUnavailableException(
|
||||
result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
result.blocked
|
||||
? 'ارسال پیامک بهخاطر محدودیت اعتبار مسدود است.'
|
||||
: result.reason === 'SMS not configured'
|
||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||
);
|
||||
}
|
||||
await this.addEvent(actor, id, 'note', 'پیامک ارسال شد', message);
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { LoyaltyController } from './loyalty.controller';
|
||||
import { LoyaltyService } from './loyalty.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [LoyaltyController],
|
||||
providers: [LoyaltyService, SmsService],
|
||||
providers: [LoyaltyService],
|
||||
exports: [LoyaltyService],
|
||||
})
|
||||
export class LoyaltyModule {}
|
||||
|
||||
@@ -22,7 +22,7 @@ import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { buildSearchWhere, ci } from '../common/search';
|
||||
import { type Actor, ownerWhere } from '../common/record-scope';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
|
||||
const DEFAULT_TIERS = [
|
||||
{ name: 'برنزی', minPoints: 0, color: '#c9843a' },
|
||||
@@ -57,7 +57,7 @@ const DAY_MS = 86_400_000;
|
||||
export class LoyaltyService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async ensureDefaults(organizationId: string): Promise<void> {
|
||||
@@ -447,10 +447,12 @@ export class LoyaltyService {
|
||||
const settings = await this.ensureSettings(actor.organizationId);
|
||||
if (settings.notifyOnAdjust && updated.mobile) {
|
||||
const sign = delta > 0 ? '+' : '';
|
||||
void this.sms.sendSmsDetailed(
|
||||
updated.mobile,
|
||||
`باشگاه مشتریان: ${sign}${Math.trunc(delta)} امتیاز. موجودی: ${updated.loyaltyPoints}`,
|
||||
);
|
||||
void this.sms.send({
|
||||
organizationId: actor.organizationId,
|
||||
phone: updated.mobile,
|
||||
text: `باشگاه مشتریان: ${sign}${Math.trunc(delta)} امتیاز. موجودی: ${updated.loyaltyPoints}`,
|
||||
source: 'loyalty',
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
@@ -504,7 +506,12 @@ export class LoyaltyService {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const result = await this.sms.sendSmsDetailed(p.mobile, body);
|
||||
const result = await this.sms.send({
|
||||
organizationId: actor.organizationId,
|
||||
phone: p.mobile,
|
||||
text: body,
|
||||
source: 'loyalty',
|
||||
});
|
||||
if (result.ok) sent += 1;
|
||||
else failed += 1;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { MessageAutomationsController } from './message-automations.controller';
|
||||
import { MessageAutomationsService } from './message-automations.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, NotificationsModule],
|
||||
controllers: [MessageAutomationsController],
|
||||
providers: [MessageAutomationsService, SmsService],
|
||||
providers: [MessageAutomationsService],
|
||||
exports: [MessageAutomationsService],
|
||||
})
|
||||
export class MessageAutomationsModule {}
|
||||
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import { dateToJalali, jalaliMonthName } from '../common/jalali';
|
||||
import { OutboundSmsLogService } from '../outbound-sms/outbound-sms-log.service';
|
||||
import {
|
||||
@@ -47,7 +47,7 @@ export class MessageAutomationsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
private readonly outboundSms: OutboundSmsLogService,
|
||||
) {}
|
||||
|
||||
@@ -397,7 +397,10 @@ export class MessageAutomationsService {
|
||||
},
|
||||
select: { mobile: true },
|
||||
});
|
||||
await this.sendSms(user?.mobile, smsText);
|
||||
await this.sendSms(user?.mobile, smsText, {
|
||||
organizationId: job.organizationId,
|
||||
ruleId: job.ruleId || job.rule.id || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +416,7 @@ export class MessageAutomationsService {
|
||||
private async sendSms(
|
||||
mobile: string | null | undefined,
|
||||
text: string,
|
||||
log?: {
|
||||
log: {
|
||||
organizationId: string;
|
||||
personId?: string | null;
|
||||
ruleId: string;
|
||||
@@ -423,12 +426,13 @@ export class MessageAutomationsService {
|
||||
this.logger.warn('Message automation SMS skipped: no mobile');
|
||||
return;
|
||||
}
|
||||
if (!this.sms.isConfigured()) {
|
||||
this.logger.warn('Message automation SMS skipped: SMS not configured');
|
||||
return;
|
||||
}
|
||||
const result = await this.sms.sendSmsDetailed(mobile, text);
|
||||
if (log?.personId) {
|
||||
const result = await this.sms.send({
|
||||
organizationId: log.organizationId,
|
||||
phone: mobile,
|
||||
text,
|
||||
source: 'automation',
|
||||
});
|
||||
if (log.personId) {
|
||||
await this.outboundSms.record({
|
||||
organizationId: log.organizationId,
|
||||
personId: log.personId,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NotificationsController } from './notifications.controller';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
|
||||
@Module({
|
||||
controllers: [NotificationsController],
|
||||
providers: [NotificationsService, SmsService],
|
||||
providers: [NotificationsService],
|
||||
exports: [NotificationsService],
|
||||
})
|
||||
export class NotificationsModule {}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Cron } from '@nestjs/schedule';
|
||||
import { brand } from '@mento/shared';
|
||||
import type { NotificationDto, NotificationsListDto } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
|
||||
/** یادآورهایی که بیش از این دیرتر پردازش شوند (مثلاً قطعی سرور) فقط اعلان میگیرند، نه پیامک. */
|
||||
const REMINDER_SMS_MAX_DELAY_MS = 6 * 60 * 60 * 1000;
|
||||
@@ -41,7 +41,7 @@ export class NotificationsService {
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async list(
|
||||
@@ -249,7 +249,7 @@ export class NotificationsService {
|
||||
});
|
||||
}
|
||||
if (activity.reminderNotifySms && !stale) {
|
||||
await this.sendActivityReminderSms(mobile, {
|
||||
await this.sendActivityReminderSms(activity.organizationId, mobile, {
|
||||
title: activity.title,
|
||||
related,
|
||||
relatedMobile: activity.person?.mobile ?? null,
|
||||
@@ -295,6 +295,7 @@ export class NotificationsService {
|
||||
}
|
||||
|
||||
private async sendActivityReminderSms(
|
||||
organizationId: string,
|
||||
mobile: string | null | undefined,
|
||||
info: { title: string; related: string; relatedMobile: string | null; dueAt: Date | null },
|
||||
) {
|
||||
@@ -302,10 +303,6 @@ export class NotificationsService {
|
||||
this.logger.warn('Activity reminder SMS skipped: assignee has no mobile');
|
||||
return;
|
||||
}
|
||||
if (!this.sms.isConfigured()) {
|
||||
this.logger.warn('Activity reminder SMS skipped: SMS not configured');
|
||||
return;
|
||||
}
|
||||
const lines = [`${brand.reminderPrefixFa} ${info.title}`];
|
||||
if (info.related) {
|
||||
lines.push(
|
||||
@@ -314,7 +311,12 @@ export class NotificationsService {
|
||||
}
|
||||
if (info.dueAt) lines.push(`زمان: ${formatTehranDateTime(info.dueAt)}`);
|
||||
const text = lines.join('\n').slice(0, 300);
|
||||
const result = await this.sms.sendSmsDetailed(mobile, text);
|
||||
const result = await this.sms.send({
|
||||
organizationId,
|
||||
phone: mobile,
|
||||
text,
|
||||
source: 'activity_reminder',
|
||||
});
|
||||
if (!result.ok) {
|
||||
this.logger.warn(`Activity reminder SMS failed: ${result.reason ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
@@ -519,7 +519,11 @@ export class DealsService {
|
||||
];
|
||||
if (!ids.length) return [];
|
||||
const count = await this.prisma.user.count({
|
||||
where: { organizationId, id: { in: ids }, isActive: true },
|
||||
where: {
|
||||
id: { in: ids },
|
||||
isActive: true,
|
||||
memberships: { some: { organizationId, isActive: true } },
|
||||
},
|
||||
});
|
||||
if (count !== ids.length) {
|
||||
throw new BadRequestException('یکی از مسئولان انتخابشده معتبر نیست');
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { PortalController } from './portal.controller';
|
||||
import { PortalService } from './portal.service';
|
||||
import { PortalAuthGuard } from './portal-auth';
|
||||
@@ -8,6 +7,6 @@ import { PortalAuthGuard } from './portal-auth';
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [PortalController],
|
||||
providers: [PortalService, PortalAuthGuard, SmsService],
|
||||
providers: [PortalService, PortalAuthGuard],
|
||||
})
|
||||
export class PortalModule {}
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
} from '@mento/shared';
|
||||
import { TICKET_SLA_HOURS } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import type { PortalActor } from './portal-auth';
|
||||
|
||||
const OTP_TTL_SECONDS = 5 * 60;
|
||||
@@ -31,7 +31,7 @@ export class PortalService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwt: JwtService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async getOrgInfo(slug: string): Promise<PortalOrgInfoDto> {
|
||||
@@ -99,16 +99,13 @@ export class PortalService {
|
||||
(this.config.get<string>('NODE_ENV') !== 'production' &&
|
||||
this.config.get<string>('PORTAL_SHOW_OTP') !== 'false');
|
||||
|
||||
if (this.sms.isConfigured()) {
|
||||
const sent = await this.sms.sendOtpSms(mobile, code);
|
||||
if (!sent && !returnOtp) {
|
||||
throw new BadRequestException(
|
||||
'ارسال پیامک ناموفق بود؛ کمی بعد دوباره تلاش کنید',
|
||||
);
|
||||
}
|
||||
} else if (!returnOtp) {
|
||||
throw new BadRequestException('سامانه پیامک پیکربندی نشده است');
|
||||
} else {
|
||||
const sent = await this.sms.sendOtp(org.id, mobile, code);
|
||||
if (!sent && !returnOtp) {
|
||||
throw new BadRequestException(
|
||||
'ارسال پیامک ناموفق بود؛ کمی بعد دوباره تلاش کنید',
|
||||
);
|
||||
}
|
||||
if (!sent) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[portal-otp] ${org.slug} ${mobile} => ${code}`);
|
||||
}
|
||||
|
||||
@@ -1533,6 +1533,7 @@ export class ReportsService {
|
||||
async home(actor: Actor): Promise<HomeDashboardDto> {
|
||||
const orgId = actor.organizationId;
|
||||
const dealScope = ownerWhere(actor, 'deals');
|
||||
const invoiceScope = ownerWhere(actor, 'finance');
|
||||
const activityScope = assigneeWhere(actor);
|
||||
const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId };
|
||||
const rates = await loadOrgRates(this.prisma, orgId);
|
||||
@@ -1543,6 +1544,7 @@ export class ReportsService {
|
||||
const prev = addJalaliMonths(jy, jm, -1);
|
||||
const prevMonthStart = startOfJalaliMonth(prev.jy, prev.jm);
|
||||
const prevMonthEnd = endOfJalaliMonth(prev.jy, prev.jm);
|
||||
const trendWindowStart = addMonthsStart(now, -12);
|
||||
|
||||
const todayStart = startOfDay(now);
|
||||
const todayEnd = endOfDay(now);
|
||||
@@ -1555,17 +1557,25 @@ export class ReportsService {
|
||||
const dealsPrior = dealPriorWhere(actor.priorLens, actor.priorCutoff);
|
||||
const activitiesPrior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
|
||||
|
||||
const invoiceStatuses: Array<'issued' | 'partially_paid' | 'paid'> = [
|
||||
'issued',
|
||||
'partially_paid',
|
||||
'paid',
|
||||
];
|
||||
|
||||
const [
|
||||
wonDeals,
|
||||
openDeals,
|
||||
openDealRows,
|
||||
lostDeals,
|
||||
staleDeals,
|
||||
peopleCur,
|
||||
peoplePrev,
|
||||
peopleRecent,
|
||||
openActivitiesToday,
|
||||
openActivitiesYesterday,
|
||||
openDealsWeekAgo,
|
||||
goals,
|
||||
overdueCount,
|
||||
invoices,
|
||||
activityTypeGroups,
|
||||
] = await Promise.all([
|
||||
this.prisma.deal.findMany({
|
||||
where: {
|
||||
@@ -1573,7 +1583,7 @@ export class ReportsService {
|
||||
{
|
||||
organizationId: orgId,
|
||||
status: 'won',
|
||||
updatedAt: { gte: addMonthsStart(now, -5) },
|
||||
updatedAt: { gte: trendWindowStart },
|
||||
},
|
||||
dealScope,
|
||||
dealsPrior,
|
||||
@@ -1590,7 +1600,7 @@ export class ReportsService {
|
||||
person: { select: { id: true, firstName: true, lastName: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.deal.count({
|
||||
this.prisma.deal.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
{ organizationId: orgId, status: 'open' },
|
||||
@@ -1598,6 +1608,30 @@ export class ReportsService {
|
||||
dealsPrior,
|
||||
],
|
||||
},
|
||||
select: {
|
||||
amount: true,
|
||||
currency: true,
|
||||
stageId: true,
|
||||
stage: { select: { id: true, name: true, position: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.deal.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
organizationId: orgId,
|
||||
status: 'lost',
|
||||
updatedAt: { gte: trendWindowStart },
|
||||
},
|
||||
dealScope,
|
||||
dealsPrior,
|
||||
],
|
||||
},
|
||||
select: {
|
||||
amount: true,
|
||||
currency: true,
|
||||
lostReason: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.deal.findMany({
|
||||
where: {
|
||||
@@ -1624,19 +1658,13 @@ export class ReportsService {
|
||||
orderBy: { updatedAt: 'asc' },
|
||||
take: 5,
|
||||
}),
|
||||
this.prisma.person.count({
|
||||
this.prisma.person.findMany({
|
||||
where: {
|
||||
organizationId: orgId,
|
||||
...personScope,
|
||||
createdAt: { gte: curMonthStart, lte: curMonthEnd },
|
||||
},
|
||||
}),
|
||||
this.prisma.person.count({
|
||||
where: {
|
||||
organizationId: orgId,
|
||||
...personScope,
|
||||
createdAt: { gte: prevMonthStart, lte: prevMonthEnd },
|
||||
createdAt: { gte: trendWindowStart, lte: curMonthEnd },
|
||||
},
|
||||
select: { createdAt: true, importSource: true },
|
||||
}),
|
||||
this.prisma.activity.count({
|
||||
where: {
|
||||
@@ -1656,6 +1684,7 @@ export class ReportsService {
|
||||
AND: [
|
||||
{
|
||||
organizationId: orgId,
|
||||
status: 'open',
|
||||
dueAt: { gte: yesterdayStart, lte: yesterdayEnd },
|
||||
},
|
||||
activityScope,
|
||||
@@ -1697,8 +1726,67 @@ export class ReportsService {
|
||||
],
|
||||
},
|
||||
}),
|
||||
this.prisma.invoice.findMany({
|
||||
where: {
|
||||
organizationId: orgId,
|
||||
...invoiceScope,
|
||||
status: { in: invoiceStatuses },
|
||||
OR: [
|
||||
{ issuedAt: { gte: trendWindowStart, lte: curMonthEnd } },
|
||||
{ createdAt: { gte: trendWindowStart, lte: curMonthEnd } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
issuedAt: true,
|
||||
createdAt: true,
|
||||
lineItems: {
|
||||
select: {
|
||||
quantity: true,
|
||||
unitPrice: true,
|
||||
currency: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.activity.groupBy({
|
||||
by: ['type'],
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
organizationId: orgId,
|
||||
status: 'open',
|
||||
},
|
||||
activityScope,
|
||||
activitiesPrior,
|
||||
],
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const openDeals = openDealRows.length;
|
||||
|
||||
const invoiceInRange = (
|
||||
inv: { issuedAt: Date | null; createdAt: Date },
|
||||
from: Date,
|
||||
to: Date,
|
||||
) => {
|
||||
const anchor = inv.issuedAt ?? inv.createdAt;
|
||||
return anchor >= from && anchor <= to;
|
||||
};
|
||||
|
||||
const sumInvoiceInRange = (from: Date, to: Date) => {
|
||||
let amount = 0;
|
||||
for (const inv of invoices) {
|
||||
if (!invoiceInRange(inv, from, to)) continue;
|
||||
for (const line of inv.lineItems) {
|
||||
const lineTotal = Number(line.quantity) * Number(line.unitPrice);
|
||||
amount += toBaseAmount(lineTotal, line.currency, rates);
|
||||
}
|
||||
}
|
||||
return amount;
|
||||
};
|
||||
|
||||
const sumWonInRange = (start: Date, end: Date) =>
|
||||
wonDeals
|
||||
.filter((d) => d.updatedAt >= start && d.updatedAt <= end)
|
||||
@@ -1707,8 +1795,21 @@ export class ReportsService {
|
||||
0,
|
||||
);
|
||||
|
||||
const salesCur = sumWonInRange(curMonthStart, curMonthEnd);
|
||||
const salesPrev = sumWonInRange(prevMonthStart, prevMonthEnd);
|
||||
const salesInRange = (start: Date, end: Date) => {
|
||||
const inv = sumInvoiceInRange(start, end);
|
||||
const won = sumWonInRange(start, end);
|
||||
return Math.round(inv > 0 ? inv : won);
|
||||
};
|
||||
|
||||
const peopleCur = peopleRecent.filter(
|
||||
(p) => p.createdAt >= curMonthStart && p.createdAt <= curMonthEnd,
|
||||
).length;
|
||||
const peoplePrev = peopleRecent.filter(
|
||||
(p) => p.createdAt >= prevMonthStart && p.createdAt <= prevMonthEnd,
|
||||
).length;
|
||||
|
||||
const salesCur = salesInRange(curMonthStart, curMonthEnd);
|
||||
const salesPrev = salesInRange(prevMonthStart, prevMonthEnd);
|
||||
const targetAmount = goals.reduce(
|
||||
(acc, g) => acc + Number(g.targetAmount),
|
||||
0,
|
||||
@@ -1716,7 +1817,7 @@ export class ReportsService {
|
||||
|
||||
const trendMonths: Array<{ key: string; label: string; start: Date; end: Date }> =
|
||||
[];
|
||||
for (let i = 4; i >= 0; i -= 1) {
|
||||
for (let i = 11; i >= 0; i -= 1) {
|
||||
const m = addJalaliMonths(jy, jm, -i);
|
||||
trendMonths.push({
|
||||
key: `${m.jy}-${String(m.jm).padStart(2, '0')}`,
|
||||
@@ -1729,14 +1830,28 @@ export class ReportsService {
|
||||
const salesTrend = trendMonths.map((m) => ({
|
||||
monthKey: m.key,
|
||||
monthLabel: m.label,
|
||||
amount: Math.round(sumWonInRange(m.start, m.end)),
|
||||
amount: salesInRange(m.start, m.end),
|
||||
}));
|
||||
|
||||
const customerGrowth = trendMonths.map((m) => ({
|
||||
monthKey: m.key,
|
||||
monthLabel: m.label,
|
||||
value: peopleRecent.filter(
|
||||
(p) => p.createdAt >= m.start && p.createdAt <= m.end,
|
||||
).length,
|
||||
}));
|
||||
|
||||
const sourceMap = new Map<string, number>();
|
||||
for (const d of wonDeals) {
|
||||
const label = normalizeSource(d.source);
|
||||
for (const p of peopleRecent) {
|
||||
const label = normalizeImportSource(p.importSource);
|
||||
sourceMap.set(label, (sourceMap.get(label) ?? 0) + 1);
|
||||
}
|
||||
if (sourceMap.size === 0) {
|
||||
for (const d of wonDeals) {
|
||||
const label = normalizeSource(d.source);
|
||||
sourceMap.set(label, (sourceMap.get(label) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
const sourceTotal = [...sourceMap.values()].reduce((a, b) => a + b, 0) || 1;
|
||||
const sources = [...sourceMap.entries()]
|
||||
.map(([label, count]) => ({
|
||||
@@ -1780,6 +1895,101 @@ export class ReportsService {
|
||||
.slice(0, 5)
|
||||
.map((row, index) => ({ ...row, rank: index + 1 }));
|
||||
|
||||
const wonAmountAll = Math.round(
|
||||
wonDeals.reduce(
|
||||
(acc, d) => acc + decimalToBase(d.amount, d.currency, rates),
|
||||
0,
|
||||
),
|
||||
);
|
||||
const lostAmountAll = Math.round(
|
||||
lostDeals.reduce(
|
||||
(acc, d) => acc + decimalToBase(d.amount, d.currency, rates),
|
||||
0,
|
||||
),
|
||||
);
|
||||
const openAmountAll = Math.round(
|
||||
openDealRows.reduce(
|
||||
(acc, d) => acc + decimalToBase(d.amount, d.currency, rates),
|
||||
0,
|
||||
),
|
||||
);
|
||||
const closedCount = wonDeals.length + lostDeals.length;
|
||||
const winRate = closedCount
|
||||
? Math.round((wonDeals.length / closedCount) * 1000) / 10
|
||||
: 0;
|
||||
const salesSummary: HomeDashboardDto['salesSummary'] = {
|
||||
openCount: openDeals,
|
||||
wonCount: wonDeals.length,
|
||||
lostCount: lostDeals.length,
|
||||
openAmount: openAmountAll,
|
||||
wonAmount: wonAmountAll,
|
||||
lostAmount: lostAmountAll,
|
||||
winRate,
|
||||
};
|
||||
|
||||
const funnelMap = new Map<
|
||||
string,
|
||||
{ stageId: string; stageName: string; position: number; count: number; amount: number }
|
||||
>();
|
||||
for (const d of openDealRows) {
|
||||
const stageId = d.stage?.id ?? d.stageId ?? 'unknown';
|
||||
const stageName = d.stage?.name ?? 'بدون مرحله';
|
||||
const position = d.stage?.position ?? 999;
|
||||
const cur = funnelMap.get(stageId) ?? {
|
||||
stageId,
|
||||
stageName,
|
||||
position,
|
||||
count: 0,
|
||||
amount: 0,
|
||||
};
|
||||
cur.count += 1;
|
||||
cur.amount += decimalToBase(d.amount, d.currency, rates);
|
||||
funnelMap.set(stageId, cur);
|
||||
}
|
||||
const funnel = [...funnelMap.values()]
|
||||
.sort((a, b) => a.position - b.position)
|
||||
.slice(0, 8)
|
||||
.map((row) => ({
|
||||
stageId: row.stageId,
|
||||
stageName: row.stageName,
|
||||
count: row.count,
|
||||
amount: Math.round(row.amount),
|
||||
}));
|
||||
|
||||
const lostReasonMap = new Map<string, { count: number; amount: number }>();
|
||||
for (const d of lostDeals) {
|
||||
const label = normalizeLostReason(d.lostReason);
|
||||
const prevRow = lostReasonMap.get(label) ?? { count: 0, amount: 0 };
|
||||
prevRow.count += 1;
|
||||
prevRow.amount += decimalToBase(d.amount, d.currency, rates);
|
||||
lostReasonMap.set(label, prevRow);
|
||||
}
|
||||
const lostReasonTotal =
|
||||
[...lostReasonMap.values()].reduce((a, b) => a + b.count, 0) || 1;
|
||||
const lostReasons = [...lostReasonMap.entries()]
|
||||
.map(([label, row]) => ({
|
||||
label,
|
||||
count: row.count,
|
||||
amount: Math.round(row.amount),
|
||||
percent: Math.round((row.count / lostReasonTotal) * 1000) / 10,
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 6);
|
||||
|
||||
const activityTypeLabel: Record<string, string> = {
|
||||
call: 'تماس',
|
||||
meeting: 'جلسه',
|
||||
task: 'کار',
|
||||
note: 'یادداشت',
|
||||
};
|
||||
const activityByType = activityTypeGroups
|
||||
.map((row) => ({
|
||||
type: row.type,
|
||||
label: activityTypeLabel[row.type] ?? row.type,
|
||||
count: row._count._all,
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
|
||||
const alerts: HomeDashboardDto['alerts'] = [];
|
||||
if (staleDeals.length) {
|
||||
const first = staleDeals[0]!;
|
||||
@@ -1857,11 +2067,30 @@ export class ReportsService {
|
||||
changePercent: pctChange(openActivitiesToday, openActivitiesYesterday),
|
||||
changeLabel: 'نسبت به دیروز',
|
||||
},
|
||||
{
|
||||
key: 'win-rate',
|
||||
label: 'نرخ برد',
|
||||
value: winRate,
|
||||
changePercent: null,
|
||||
changeLabel: '۱۲ ماه اخیر',
|
||||
},
|
||||
{
|
||||
key: 'overdue',
|
||||
label: 'عقبافتاده',
|
||||
value: overdueCount,
|
||||
changePercent: null,
|
||||
changeLabel: 'فعالیت باز',
|
||||
},
|
||||
],
|
||||
alerts,
|
||||
salesTrend,
|
||||
customerGrowth,
|
||||
sources,
|
||||
topCustomers,
|
||||
salesSummary,
|
||||
funnel,
|
||||
lostReasons,
|
||||
activityByType,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1919,6 +2148,21 @@ function normalizeSource(raw: string | null | undefined): string {
|
||||
return map[value.toLowerCase()] ?? value;
|
||||
}
|
||||
|
||||
function normalizeImportSource(raw: string | null | undefined): string {
|
||||
const value = raw?.trim().toLowerCase();
|
||||
if (!value) return 'سایر';
|
||||
const map: Record<string, string> = {
|
||||
manual: 'دستی',
|
||||
tahesab: 'تهحساب',
|
||||
didar: 'دیدار',
|
||||
excel: 'اکسل',
|
||||
phone: 'تلفن',
|
||||
lead_form: 'فرم لید',
|
||||
other: 'سایر',
|
||||
};
|
||||
return map[value] ?? normalizeSource(raw);
|
||||
}
|
||||
|
||||
function normalizeLostReason(raw: string | null | undefined): string {
|
||||
const value = raw?.trim();
|
||||
if (!value) return 'بدون دلیل ثبتشده';
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
IsBoolean,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
Min,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { Transform, Type } from 'class-transformer';
|
||||
|
||||
export class PlatformSmsChargeDto {
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
amountRials!: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export class PlatformSmsUpdateAccountDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
pricePerPartRials?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isBlocked?: boolean;
|
||||
|
||||
/** null = غیرفعال کردن آستانه خودکار */
|
||||
@IsOptional()
|
||||
@Transform(({ value }) =>
|
||||
value === null || value === '' || value === undefined ? null : Number(value),
|
||||
)
|
||||
@ValidateIf((_, v) => v !== null && v !== undefined)
|
||||
@IsInt()
|
||||
autoBlockBelowRials?: number | null;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
alertCriticalRials?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
alertWarningRials?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['platform', 'own'])
|
||||
panelMode?: 'platform' | 'own';
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
ownPanelType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
ownPanelUsername?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
ownPanelPassword?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
ownPanelFrom?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
chargeCard?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
chargeIban?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
chargeHolder?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(2000)
|
||||
chargeInstruction?: string | null;
|
||||
}
|
||||
|
||||
export class PlatformSmsBlockDto {
|
||||
@IsBoolean()
|
||||
isBlocked!: boolean;
|
||||
}
|
||||
|
||||
export class PlatformSmsPriceDto {
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
pricePerPartRials!: number;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { SmsWalletService } from './sms-wallet.service';
|
||||
|
||||
@Controller('sms-wallet')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class OrgSmsController {
|
||||
constructor(private readonly wallet: SmsWalletService) {}
|
||||
|
||||
/** خلاصه برای نشان اعتبار در هدر CRM */
|
||||
@Get('summary')
|
||||
async summary(@CurrentUser() user: { organizationId: string }) {
|
||||
const account = await this.wallet.ensureAccount(user.organizationId);
|
||||
const billingEnabled = this.wallet.isBillingEnabled(account);
|
||||
return {
|
||||
billingEnabled,
|
||||
balanceRials: account.balanceRials,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
isBlocked: account.isBlocked,
|
||||
autoBlocked: this.wallet.isAutoBlocked(account),
|
||||
balanceLevel: this.wallet.balanceLevel(account),
|
||||
panelMode: account.panelMode,
|
||||
chargeInfo: billingEnabled ? this.wallet.chargeInfoOf(account) : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { PlatformAuthGuard } from '../platform/platform-auth.guard';
|
||||
import type { PlatformActor } from '../platform/platform-jwt.strategy';
|
||||
import {
|
||||
PlatformSmsBlockDto,
|
||||
PlatformSmsChargeDto,
|
||||
PlatformSmsPriceDto,
|
||||
PlatformSmsUpdateAccountDto,
|
||||
} from './dto';
|
||||
import { SmsWalletService } from './sms-wallet.service';
|
||||
|
||||
@Controller('platform/sms')
|
||||
@UseGuards(PlatformAuthGuard)
|
||||
export class PlatformSmsController {
|
||||
constructor(private readonly wallet: SmsWalletService) {}
|
||||
|
||||
@Get('tenants')
|
||||
listTenants(@Query('q') q?: string) {
|
||||
return this.wallet.listTenantSummaries(q);
|
||||
}
|
||||
|
||||
@Get('organizations/:organizationId')
|
||||
overview(@Param('organizationId') organizationId: string) {
|
||||
return this.wallet.getOverview(organizationId);
|
||||
}
|
||||
|
||||
@Post('organizations/:organizationId/charge')
|
||||
charge(
|
||||
@Param('organizationId') organizationId: string,
|
||||
@Body() dto: PlatformSmsChargeDto,
|
||||
@CurrentUser() actor: PlatformActor,
|
||||
) {
|
||||
return this.wallet
|
||||
.charge(organizationId, dto.amountRials, actor.platformAdminId, dto.note)
|
||||
.then((account) => this.wallet.getOverview(organizationId).then((o) => ({
|
||||
...o,
|
||||
account: this.wallet.publicAccount(account),
|
||||
})));
|
||||
}
|
||||
|
||||
@Put('organizations/:organizationId/price')
|
||||
updatePrice(
|
||||
@Param('organizationId') organizationId: string,
|
||||
@Body() dto: PlatformSmsPriceDto,
|
||||
) {
|
||||
return this.wallet
|
||||
.updateAccount(organizationId, {
|
||||
pricePerPartRials: dto.pricePerPartRials,
|
||||
})
|
||||
.then(() => this.wallet.getOverview(organizationId));
|
||||
}
|
||||
|
||||
@Put('organizations/:organizationId/block')
|
||||
setBlocked(
|
||||
@Param('organizationId') organizationId: string,
|
||||
@Body() dto: PlatformSmsBlockDto,
|
||||
) {
|
||||
return this.wallet
|
||||
.updateAccount(organizationId, { isBlocked: dto.isBlocked })
|
||||
.then(() => this.wallet.getOverview(organizationId));
|
||||
}
|
||||
|
||||
@Patch('organizations/:organizationId')
|
||||
updateAccount(
|
||||
@Param('organizationId') organizationId: string,
|
||||
@Body() dto: PlatformSmsUpdateAccountDto,
|
||||
) {
|
||||
return this.wallet
|
||||
.updateAccount(organizationId, dto)
|
||||
.then(() => this.wallet.getOverview(organizationId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { OrgSmsController } from './org-sms.controller';
|
||||
import { PlatformSmsController } from './platform-sms.controller';
|
||||
import { SmsGatewayService } from './sms-gateway.service';
|
||||
import { SmsWalletService } from './sms-wallet.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [PlatformSmsController, OrgSmsController],
|
||||
providers: [SmsService, SmsWalletService, SmsGatewayService],
|
||||
exports: [SmsService, SmsWalletService, SmsGatewayService],
|
||||
})
|
||||
export class SmsBillingModule {}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
SmsService,
|
||||
type SmsSendResult,
|
||||
type SmsTransportOverride,
|
||||
} from '../common/sms.service';
|
||||
import { countSmsParts } from './sms-segment.util';
|
||||
import { SmsWalletService } from './sms-wallet.service';
|
||||
|
||||
export type SmsGatewaySendInput = {
|
||||
/** اگر نباشد (مثلاً ثبتنام قبل از ساخت محیط) فقط ارسال پلتفرم بدون کسر */
|
||||
organizationId?: string | null;
|
||||
phone: string;
|
||||
text: string;
|
||||
source?: string | null;
|
||||
isAlert?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class SmsGatewayService {
|
||||
private readonly logger = new Logger(SmsGatewayService.name);
|
||||
|
||||
constructor(
|
||||
private readonly transport: SmsService,
|
||||
private readonly wallet: SmsWalletService,
|
||||
) {}
|
||||
|
||||
isConfigured(): boolean {
|
||||
return this.transport.isConfigured();
|
||||
}
|
||||
|
||||
normalizePhoneForSms(mobile: string): string {
|
||||
return this.transport.normalizePhoneForSms(mobile);
|
||||
}
|
||||
|
||||
async sendOtp(
|
||||
organizationId: string | null | undefined,
|
||||
mobile: string,
|
||||
code: string,
|
||||
): Promise<boolean> {
|
||||
const text = this.transport.buildOtpText(code);
|
||||
const result = await this.send({
|
||||
organizationId,
|
||||
phone: mobile,
|
||||
text,
|
||||
source: 'otp',
|
||||
});
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
async send(input: SmsGatewaySendInput): Promise<SmsSendResult> {
|
||||
const text = String(input.text ?? '').trim();
|
||||
if (!text) {
|
||||
return { ok: false, transport: 'none', reason: 'empty body' };
|
||||
}
|
||||
|
||||
const partsEstimate = Math.max(1, countSmsParts(text));
|
||||
let override: SmsTransportOverride | undefined;
|
||||
let billable = false;
|
||||
let providerLabel = 'platform';
|
||||
|
||||
if (input.organizationId) {
|
||||
const account = await this.wallet.ensureAccount(input.organizationId);
|
||||
const billingEnabled = this.wallet.isBillingEnabled(account);
|
||||
|
||||
if (billingEnabled) {
|
||||
if (!this.wallet.canSend(account, Boolean(input.isAlert))) {
|
||||
return {
|
||||
ok: false,
|
||||
blocked: true,
|
||||
transport: 'none',
|
||||
reason: account.isBlocked ? 'blocked' : 'auto_blocked',
|
||||
parts: partsEstimate,
|
||||
};
|
||||
}
|
||||
billable = true;
|
||||
} else {
|
||||
// پنل اختصاصی مشتری: بدون کسر/لاگ کیف
|
||||
const user = account.ownPanelUsername?.trim();
|
||||
const pass = account.ownPanelPassword?.trim();
|
||||
const from = account.ownPanelFrom?.trim();
|
||||
if (!user || !pass || !from) {
|
||||
return {
|
||||
ok: false,
|
||||
transport: 'none',
|
||||
reason: 'own SMS panel not configured',
|
||||
};
|
||||
}
|
||||
const type = (account.ownPanelType || '0098').toLowerCase();
|
||||
override = {
|
||||
username: user,
|
||||
password: pass,
|
||||
sender: from,
|
||||
provider: type === 'trez' ? 'trez' : '0098',
|
||||
};
|
||||
providerLabel = `own:${type || '0098'}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!override && !this.transport.isConfigured()) {
|
||||
return { ok: false, transport: 'none', reason: 'SMS not configured' };
|
||||
}
|
||||
|
||||
const result = await this.transport.sendSmsDetailed(
|
||||
input.phone,
|
||||
text,
|
||||
override,
|
||||
);
|
||||
|
||||
if (!result.ok) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const parts = Math.max(1, countSmsParts(text));
|
||||
const to = this.transport.normalizePhoneForSms(input.phone);
|
||||
|
||||
if (billable && input.organizationId) {
|
||||
try {
|
||||
const debit = await this.wallet.debitSuccessfulSms({
|
||||
organizationId: input.organizationId,
|
||||
receiver: to,
|
||||
body: text,
|
||||
parts,
|
||||
provider: result.transport || providerLabel,
|
||||
source: input.source,
|
||||
isAlert: input.isAlert,
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
parts,
|
||||
costRials: debit.costRials,
|
||||
};
|
||||
} catch (e) {
|
||||
this.logger.error(
|
||||
`SMS debit failed after send org=${input.organizationId}: ${
|
||||
e instanceof Error ? e.message : String(e)
|
||||
}`,
|
||||
);
|
||||
return { ...result, parts };
|
||||
}
|
||||
}
|
||||
|
||||
return { ...result, parts, costRials: 0 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Persian SMS parts (same rules as Hamkar SmsSegmentCalculator). */
|
||||
const PERSIAN_LIMITS = [70, 64, 67] as const;
|
||||
|
||||
export function countSmsParts(text: string): number {
|
||||
const length = [...String(text ?? '').trim()].length;
|
||||
if (length <= 0) return 0;
|
||||
|
||||
const [first, second, rest] = PERSIAN_LIMITS;
|
||||
if (length <= first) return 1;
|
||||
if (length <= first + second) return 2;
|
||||
const thirdThreshold = first + second + rest;
|
||||
if (length <= thirdThreshold) return 3;
|
||||
return 3 + Math.ceil((length - thirdThreshold) / rest);
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import type { SmsAccount } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { countSmsParts } from './sms-segment.util';
|
||||
|
||||
export type SmsBalanceLevel = 'healthy' | 'warning' | 'critical' | 'unknown';
|
||||
|
||||
const DEFAULT_CHARGE_INSTRUCTION =
|
||||
'لطفا مبلغ مورد نظر خود جهت شارژ سامانه پیامکی را به شماره کارت یا حساب زیر واریز نمایید و تصویر فیش پرداختی را برای پشتیبانی بفرستید.';
|
||||
|
||||
@Injectable()
|
||||
export class SmsWalletService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async ensureAccount(organizationId: string): Promise<SmsAccount> {
|
||||
return this.prisma.smsAccount.upsert({
|
||||
where: { organizationId },
|
||||
create: { organizationId },
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
|
||||
isBillingEnabled(account: SmsAccount): boolean {
|
||||
return (account.panelMode ?? 'platform') !== 'own';
|
||||
}
|
||||
|
||||
isAutoBlocked(account: SmsAccount): boolean {
|
||||
return (
|
||||
account.autoBlockBelowRials != null &&
|
||||
account.balanceRials < account.autoBlockBelowRials
|
||||
);
|
||||
}
|
||||
|
||||
canSend(account: SmsAccount, isAlert = false): boolean {
|
||||
if (!this.isBillingEnabled(account)) return true;
|
||||
if (isAlert) return true;
|
||||
if (account.isBlocked) return false;
|
||||
if (this.isAutoBlocked(account)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
balanceLevel(account: SmsAccount): SmsBalanceLevel {
|
||||
if (!this.isBillingEnabled(account)) return 'unknown';
|
||||
const bal = account.balanceRials;
|
||||
if (bal <= account.alertCriticalRials) return 'critical';
|
||||
if (bal <= account.alertWarningRials) return 'warning';
|
||||
return 'healthy';
|
||||
}
|
||||
|
||||
estimateCost(account: SmsAccount, text: string): { parts: number; costRials: number } {
|
||||
const parts = Math.max(1, countSmsParts(text));
|
||||
return { parts, costRials: parts * account.pricePerPartRials };
|
||||
}
|
||||
|
||||
chargeInfoOf(account: SmsAccount) {
|
||||
return {
|
||||
card: account.chargeCard?.trim() || '',
|
||||
iban: account.chargeIban?.trim() || '',
|
||||
accountHolder: account.chargeHolder?.trim() || '',
|
||||
instruction:
|
||||
account.chargeInstruction?.trim() || DEFAULT_CHARGE_INSTRUCTION,
|
||||
};
|
||||
}
|
||||
|
||||
async status(organizationId: string, parts = 1, isAlert = false) {
|
||||
const account = await this.ensureAccount(organizationId);
|
||||
const safeParts = Math.max(1, Math.min(50, Math.floor(parts) || 1));
|
||||
const estimatedCostRials = safeParts * account.pricePerPartRials;
|
||||
const billingEnabled = this.isBillingEnabled(account);
|
||||
|
||||
let reason: string | null = null;
|
||||
let allowed = true;
|
||||
|
||||
if (billingEnabled) {
|
||||
if (account.isBlocked && !isAlert) {
|
||||
allowed = false;
|
||||
reason = 'blocked';
|
||||
} else if (this.isAutoBlocked(account) && !isAlert) {
|
||||
allowed = false;
|
||||
reason = 'auto_blocked';
|
||||
} else if (!isAlert && account.balanceRials < estimatedCostRials) {
|
||||
reason = 'insufficient_balance';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
billingEnabled,
|
||||
allowed,
|
||||
blocked: billingEnabled && (account.isBlocked || this.isAutoBlocked(account)),
|
||||
reason,
|
||||
balanceRials: account.balanceRials,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
autoBlockBelowRials: account.autoBlockBelowRials,
|
||||
panelMode: account.panelMode,
|
||||
parts: safeParts,
|
||||
estimatedCostRials,
|
||||
balanceLevel: this.balanceLevel(account),
|
||||
isBlocked: account.isBlocked,
|
||||
};
|
||||
}
|
||||
|
||||
async charge(
|
||||
organizationId: string,
|
||||
amountRials: number,
|
||||
createdById?: string | null,
|
||||
note?: string | null,
|
||||
) {
|
||||
if (!Number.isFinite(amountRials) || amountRials === 0) {
|
||||
throw new BadRequestException('مبلغ شارژ نامعتبر است');
|
||||
}
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const account = await tx.smsAccount.upsert({
|
||||
where: { organizationId },
|
||||
create: { organizationId },
|
||||
update: {},
|
||||
});
|
||||
const next = account.balanceRials + Math.trunc(amountRials);
|
||||
const updated = await tx.smsAccount.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
balanceRials: next,
|
||||
...(next > 0 ? { alertDaysSent: 0, lastAlertDate: null } : {}),
|
||||
},
|
||||
});
|
||||
await tx.smsLedger.create({
|
||||
data: {
|
||||
smsAccountId: account.id,
|
||||
type: 'charge',
|
||||
amountRials: Math.trunc(amountRials),
|
||||
balanceAfterRials: next,
|
||||
note: note?.trim() || null,
|
||||
createdById: createdById ?? null,
|
||||
},
|
||||
});
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async debitSuccessfulSms(input: {
|
||||
organizationId: string;
|
||||
receiver: string;
|
||||
body: string;
|
||||
parts: number;
|
||||
provider: string;
|
||||
source?: string | null;
|
||||
isAlert?: boolean;
|
||||
}) {
|
||||
const parts = Math.max(1, input.parts);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const account = await tx.smsAccount.findUnique({
|
||||
where: { organizationId: input.organizationId },
|
||||
});
|
||||
if (!account) {
|
||||
throw new BadRequestException('حساب پیامک یافت نشد');
|
||||
}
|
||||
if (!this.isBillingEnabled(account)) {
|
||||
return { account, costRials: 0, logId: null as string | null };
|
||||
}
|
||||
|
||||
const costRials = parts * account.pricePerPartRials;
|
||||
const next = account.balanceRials - costRials;
|
||||
const updated = await tx.smsAccount.update({
|
||||
where: { id: account.id },
|
||||
data: { balanceRials: next },
|
||||
});
|
||||
|
||||
const log = await tx.smsBillingSendLog.create({
|
||||
data: {
|
||||
smsAccountId: account.id,
|
||||
receiver: input.receiver.slice(0, 32),
|
||||
body: input.body.slice(0, 2000),
|
||||
parts,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
totalAmountRials: costRials,
|
||||
provider: input.provider.slice(0, 64),
|
||||
source: input.source?.slice(0, 64) ?? null,
|
||||
isAlert: Boolean(input.isAlert),
|
||||
},
|
||||
});
|
||||
|
||||
await tx.smsLedger.create({
|
||||
data: {
|
||||
smsAccountId: account.id,
|
||||
type: input.isAlert ? 'alert_debit' : 'debit',
|
||||
amountRials: -costRials,
|
||||
balanceAfterRials: next,
|
||||
parts,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
smsSendLogId: log.id,
|
||||
note: input.isAlert
|
||||
? 'هشدار موجودی پیامک'
|
||||
: input.source
|
||||
? `مصرف ارسال (${input.source})`
|
||||
: 'مصرف ارسال',
|
||||
},
|
||||
});
|
||||
|
||||
return { account: updated, costRials, logId: log.id };
|
||||
});
|
||||
}
|
||||
|
||||
async listTenantSummaries(q?: string) {
|
||||
const term = q?.trim();
|
||||
const orgs = await this.prisma.organization.findMany({
|
||||
where: term
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: term, mode: 'insensitive' } },
|
||||
{ slug: { contains: term, mode: 'insensitive' } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
orderBy: { name: 'asc' },
|
||||
take: 500,
|
||||
include: { smsAccount: true },
|
||||
});
|
||||
|
||||
const rows = await Promise.all(
|
||||
orgs.map(async (org) => {
|
||||
const account = org.smsAccount ?? (await this.ensureAccount(org.id));
|
||||
return {
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
slug: org.slug,
|
||||
isActive: org.isActive,
|
||||
isBlocked: account.isBlocked,
|
||||
panelMode: account.panelMode,
|
||||
sms: {
|
||||
balanceRials: account.balanceRials,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
autoBlockBelowRials: account.autoBlockBelowRials,
|
||||
balanceLevel: this.balanceLevel(account),
|
||||
billingEnabled: this.isBillingEnabled(account),
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
async getOverview(organizationId: string) {
|
||||
const account = await this.ensureAccount(organizationId);
|
||||
const org = await this.prisma.organization.findUniqueOrThrow({
|
||||
where: { id: organizationId },
|
||||
select: { id: true, name: true, slug: true, isActive: true },
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
const startOfDay = new Date(now);
|
||||
startOfDay.setHours(0, 0, 0, 0);
|
||||
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
|
||||
const [todayAgg, monthAgg, recentLedgers, recentLogs] = await Promise.all([
|
||||
this.prisma.smsBillingSendLog.aggregate({
|
||||
where: {
|
||||
smsAccountId: account.id,
|
||||
createdAt: { gte: startOfDay },
|
||||
isAlert: false,
|
||||
},
|
||||
_count: { _all: true },
|
||||
_sum: { parts: true, totalAmountRials: true },
|
||||
}),
|
||||
this.prisma.smsBillingSendLog.aggregate({
|
||||
where: {
|
||||
smsAccountId: account.id,
|
||||
createdAt: { gte: startOfMonth },
|
||||
isAlert: false,
|
||||
},
|
||||
_count: { _all: true },
|
||||
_sum: { parts: true, totalAmountRials: true },
|
||||
}),
|
||||
this.prisma.smsLedger.findMany({
|
||||
where: { smsAccountId: account.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 30,
|
||||
}),
|
||||
this.prisma.smsBillingSendLog.findMany({
|
||||
where: { smsAccountId: account.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 30,
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
organization: org,
|
||||
account: this.publicAccount(account),
|
||||
chargeInfo: this.chargeInfoOf(account),
|
||||
today: {
|
||||
messages: todayAgg._count._all,
|
||||
parts: todayAgg._sum.parts ?? 0,
|
||||
amountRials: todayAgg._sum.totalAmountRials ?? 0,
|
||||
},
|
||||
month: {
|
||||
messages: monthAgg._count._all,
|
||||
parts: monthAgg._sum.parts ?? 0,
|
||||
amountRials: monthAgg._sum.totalAmountRials ?? 0,
|
||||
},
|
||||
ledgers: recentLedgers.map((l) => ({
|
||||
id: l.id,
|
||||
type: l.type,
|
||||
amountRials: l.amountRials,
|
||||
balanceAfterRials: l.balanceAfterRials,
|
||||
parts: l.parts,
|
||||
note: l.note,
|
||||
createdAt: l.createdAt.toISOString(),
|
||||
})),
|
||||
sendLogs: recentLogs.map((l) => ({
|
||||
id: l.id,
|
||||
receiver: l.receiver,
|
||||
body: l.body,
|
||||
parts: l.parts,
|
||||
totalAmountRials: l.totalAmountRials,
|
||||
provider: l.provider,
|
||||
source: l.source,
|
||||
isAlert: l.isAlert,
|
||||
createdAt: l.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
publicAccount(account: SmsAccount) {
|
||||
return {
|
||||
id: account.id,
|
||||
organizationId: account.organizationId,
|
||||
balanceRials: account.balanceRials,
|
||||
pricePerPartRials: account.pricePerPartRials,
|
||||
isBlocked: account.isBlocked,
|
||||
autoBlockBelowRials: account.autoBlockBelowRials,
|
||||
alertCriticalRials: account.alertCriticalRials,
|
||||
alertWarningRials: account.alertWarningRials,
|
||||
panelMode: account.panelMode as 'platform' | 'own',
|
||||
ownPanelType: account.ownPanelType,
|
||||
ownPanelUsername: account.ownPanelUsername,
|
||||
ownPanelFrom: account.ownPanelFrom,
|
||||
hasOwnPanelPassword: Boolean(account.ownPanelPassword),
|
||||
balanceLevel: this.balanceLevel(account),
|
||||
billingEnabled: this.isBillingEnabled(account),
|
||||
};
|
||||
}
|
||||
|
||||
async updateAccount(
|
||||
organizationId: string,
|
||||
data: {
|
||||
pricePerPartRials?: number;
|
||||
isBlocked?: boolean;
|
||||
autoBlockBelowRials?: number | null;
|
||||
alertCriticalRials?: number;
|
||||
alertWarningRials?: number;
|
||||
panelMode?: 'platform' | 'own';
|
||||
ownPanelType?: string;
|
||||
ownPanelUsername?: string | null;
|
||||
ownPanelPassword?: string | null;
|
||||
ownPanelFrom?: string | null;
|
||||
chargeCard?: string | null;
|
||||
chargeIban?: string | null;
|
||||
chargeHolder?: string | null;
|
||||
chargeInstruction?: string | null;
|
||||
},
|
||||
) {
|
||||
await this.ensureAccount(organizationId);
|
||||
if (
|
||||
data.alertCriticalRials != null &&
|
||||
data.alertWarningRials != null &&
|
||||
data.alertCriticalRials > data.alertWarningRials
|
||||
) {
|
||||
throw new BadRequestException('آستانه قرمز نباید از آستانه زرد بزرگتر باشد');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.smsAccount.update({
|
||||
where: { organizationId },
|
||||
data: {
|
||||
pricePerPartRials:
|
||||
data.pricePerPartRials === undefined
|
||||
? undefined
|
||||
: Math.max(0, Math.trunc(data.pricePerPartRials)),
|
||||
isBlocked: data.isBlocked,
|
||||
autoBlockBelowRials:
|
||||
data.autoBlockBelowRials === undefined
|
||||
? undefined
|
||||
: data.autoBlockBelowRials,
|
||||
alertCriticalRials:
|
||||
data.alertCriticalRials === undefined
|
||||
? undefined
|
||||
: Math.max(0, Math.trunc(data.alertCriticalRials)),
|
||||
alertWarningRials:
|
||||
data.alertWarningRials === undefined
|
||||
? undefined
|
||||
: Math.max(0, Math.trunc(data.alertWarningRials)),
|
||||
panelMode: data.panelMode,
|
||||
ownPanelType: data.ownPanelType?.trim() || undefined,
|
||||
ownPanelUsername:
|
||||
data.ownPanelUsername === undefined
|
||||
? undefined
|
||||
: data.ownPanelUsername?.trim() || null,
|
||||
ownPanelPassword:
|
||||
data.ownPanelPassword === undefined
|
||||
? undefined
|
||||
: data.ownPanelPassword?.trim() || null,
|
||||
ownPanelFrom:
|
||||
data.ownPanelFrom === undefined
|
||||
? undefined
|
||||
: data.ownPanelFrom?.trim() || null,
|
||||
chargeCard:
|
||||
data.chargeCard === undefined
|
||||
? undefined
|
||||
: data.chargeCard?.trim() || null,
|
||||
chargeIban:
|
||||
data.chargeIban === undefined
|
||||
? undefined
|
||||
: data.chargeIban?.trim() || null,
|
||||
chargeHolder:
|
||||
data.chargeHolder === undefined
|
||||
? undefined
|
||||
: data.chargeHolder?.trim() || null,
|
||||
chargeInstruction:
|
||||
data.chargeInstruction === undefined
|
||||
? undefined
|
||||
: data.chargeInstruction?.trim() || null,
|
||||
},
|
||||
});
|
||||
return this.publicAccount(updated);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { TrackingModule } from '../tracking/tracking.module';
|
||||
import { SmsCampaignsController } from './sms-campaigns.controller';
|
||||
import { SmsCampaignsService } from './sms-campaigns.service';
|
||||
@@ -9,7 +8,7 @@ import { SmsCampaignsService } from './sms-campaigns.service';
|
||||
@Module({
|
||||
imports: [AuthModule, BillingModule, TrackingModule],
|
||||
controllers: [SmsCampaignsController],
|
||||
providers: [SmsCampaignsService, SmsService],
|
||||
providers: [SmsCampaignsService],
|
||||
exports: [SmsCampaignsService],
|
||||
})
|
||||
export class SmsCampaignsModule {}
|
||||
|
||||
@@ -15,7 +15,7 @@ import type {
|
||||
} from '@mento/shared';
|
||||
import { SMS_CAMPAIGN_CHUNK_SIZE } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import { renderSmsText } from '../common/sms-text';
|
||||
import {
|
||||
type Actor,
|
||||
@@ -45,7 +45,7 @@ function leadAccessWhere(baseActor: Actor): Prisma.LeadWhereInput {
|
||||
export class SmsCampaignsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
private readonly tracking: TrackingService,
|
||||
private readonly outboundSms: OutboundSmsLogService,
|
||||
) {}
|
||||
@@ -583,10 +583,12 @@ export class SmsCampaignsService {
|
||||
body: withTokens,
|
||||
});
|
||||
|
||||
const result = await this.sms.sendSmsDetailed(
|
||||
recipient.mobile,
|
||||
personalized.body,
|
||||
);
|
||||
const result = await this.sms.send({
|
||||
organizationId: campaign.organizationId,
|
||||
phone: recipient.mobile,
|
||||
text: personalized.body,
|
||||
source: 'campaign',
|
||||
});
|
||||
await this.outboundSms.record({
|
||||
organizationId: campaign.organizationId,
|
||||
personId: recipient.personId,
|
||||
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
} from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||
import ExcelJS from 'exceljs';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
|
||||
@@ -47,7 +47,7 @@ export class TreasuryReceivablesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly sms: SmsService,
|
||||
private readonly sms: SmsGatewayService,
|
||||
) {}
|
||||
|
||||
async list(actor: Actor): Promise<FinancialReceivableDto[]> {
|
||||
@@ -306,8 +306,15 @@ export class TreasuryReceivablesService {
|
||||
where: { id: admin.userId },
|
||||
select: { mobile: true },
|
||||
});
|
||||
if (user?.mobile && this.sms.isConfigured()) {
|
||||
await this.sms.sendSmsDetailed(user.mobile, `${title}: ${body}`).catch(() => undefined);
|
||||
if (user?.mobile) {
|
||||
await this.sms
|
||||
.send({
|
||||
organizationId: row.receivable.organizationId,
|
||||
phone: user.mobile,
|
||||
text: `${title}: ${body}`,
|
||||
source: 'treasury_reminder',
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
await this.prisma.financialInstallment.update({
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { TreasuryController } from './treasury.controller';
|
||||
import { TreasuryAccessGuard } from './treasury-access.guard';
|
||||
import { TreasuryBridgeService } from './treasury-bridge.service';
|
||||
@@ -18,7 +17,6 @@ import { TreasuryService } from './treasury.service';
|
||||
TreasuryOpsService,
|
||||
TreasuryBridgeService,
|
||||
TreasuryAccessGuard,
|
||||
SmsService,
|
||||
],
|
||||
exports: [TreasuryService, TreasuryBridgeService],
|
||||
})
|
||||
|
||||
@@ -89,6 +89,14 @@ export class UpdateUserCommissionDto {
|
||||
commissionPercent!: number;
|
||||
}
|
||||
|
||||
export class UpdateLogoutTimeDto {
|
||||
@IsOptional()
|
||||
@ValidateIf((_, value) => value != null && value !== '')
|
||||
@IsString()
|
||||
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/, { message: 'ساعت خروج معتبر نیست' })
|
||||
logoutTime?: string | null;
|
||||
}
|
||||
|
||||
export class UpdateUserVisibilityDto {
|
||||
@IsOptional()
|
||||
@IsIn(['own', 'team', 'org'])
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
InviteUserDto,
|
||||
UpdateOrgUserDto,
|
||||
UpdateUserCommissionDto,
|
||||
UpdateLogoutTimeDto,
|
||||
UpdateUserRoleDto,
|
||||
UpdateUserStatusDto,
|
||||
UpdateUserVisibilityDto,
|
||||
@@ -66,6 +67,21 @@ export class UsersController {
|
||||
);
|
||||
}
|
||||
|
||||
@Patch(':id/logout-time')
|
||||
@Roles('owner')
|
||||
updateLogoutTime(
|
||||
@CurrentUser() user: { organizationId: string; role: UserRole },
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateLogoutTimeDto,
|
||||
) {
|
||||
return this.usersService.updateLogoutTime(
|
||||
user.organizationId,
|
||||
user.role,
|
||||
id,
|
||||
dto.logoutTime ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
@Patch(':id/commission')
|
||||
@Roles('owner', 'admin')
|
||||
updateCommission(
|
||||
|
||||
@@ -45,6 +45,7 @@ type MembershipRow = {
|
||||
dataVisibility?: string | null;
|
||||
dataVisibilityScopes?: unknown;
|
||||
priorArchiveEnabled?: boolean;
|
||||
logoutTime?: string | null;
|
||||
createdAt: Date;
|
||||
orgRole: { id: string; name: string; color: string } | null;
|
||||
user: {
|
||||
@@ -242,6 +243,31 @@ export class UsersService {
|
||||
return this.dtoOf(organizationId, targetId);
|
||||
}
|
||||
|
||||
async updateLogoutTime(
|
||||
organizationId: string,
|
||||
actorRole: UserRole,
|
||||
targetId: string,
|
||||
logoutTime: string | null,
|
||||
): Promise<OrgUserDto> {
|
||||
if (actorRole !== 'owner') {
|
||||
throw new ForbiddenException('فقط مالک میتواند ساعت خروج را تعیین کند');
|
||||
}
|
||||
const target = await this.memberships.findUserInOrgById(organizationId, targetId);
|
||||
if (!target) throw new NotFoundException('کاربر پیدا نشد');
|
||||
if (target.role === 'owner') {
|
||||
throw new BadRequestException('برای مالک ساعت خروج تعیین نمیشود');
|
||||
}
|
||||
const value = logoutTime?.trim() || null;
|
||||
if (value && !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) {
|
||||
throw new BadRequestException('ساعت خروج معتبر نیست');
|
||||
}
|
||||
await this.prisma.membership.update({
|
||||
where: { id: target.id },
|
||||
data: { logoutTime: value },
|
||||
});
|
||||
return this.dtoOf(organizationId, targetId);
|
||||
}
|
||||
|
||||
async updatePriorArchive(
|
||||
organizationId: string,
|
||||
actorRole: UserRole,
|
||||
@@ -506,6 +532,7 @@ export class UsersService {
|
||||
? {}
|
||||
: parseVisibilityScopes(row.dataVisibilityScopes),
|
||||
priorArchiveEnabled: Boolean(row.priorArchiveEnabled),
|
||||
logoutTime: row.role === 'owner' ? null : row.logoutTime ?? null,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { loggedInAfterCutoff, tehranCutoff } from '../src/attendance/attendance-time';
|
||||
|
||||
describe('ساعت خروج تهران', () => {
|
||||
it('ورود قبل از ۱۸ خروج اجباری میخواهد و ورود بعد از آن نه', () => {
|
||||
const morning = new Date('2026-10-19T05:30:00.000Z'); // ۰۹:۰۰ تهران
|
||||
const evening = new Date('2026-10-19T15:30:00.000Z'); // ۱۹:۰۰ تهران
|
||||
const cutoff = tehranCutoff(evening, '18:00');
|
||||
assert.ok(cutoff);
|
||||
assert.equal(morning.getTime() < cutoff.getTime(), true);
|
||||
assert.equal(evening.getTime() >= cutoff.getTime(), true);
|
||||
assert.equal(loggedInAfterCutoff(morning, '18:00'), false);
|
||||
assert.equal(loggedInAfterCutoff(evening, '18:00'), true);
|
||||
assert.equal(loggedInAfterCutoff(evening, null), false);
|
||||
});
|
||||
});
|
||||
@@ -155,7 +155,11 @@ describe('promote from prior', () => {
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ defaults: async () => ({}), effectiveStageId: () => null } as never,
|
||||
{
|
||||
boardContext: async () => ({ defaultBoardId: '', defaults: new Map() }),
|
||||
effectiveBoardId: () => null,
|
||||
effectiveStageId: () => null,
|
||||
} as never,
|
||||
{ system: async () => ({}), toSummary: (row: unknown) => row } as never,
|
||||
{} as never,
|
||||
);
|
||||
@@ -180,7 +184,11 @@ describe('promote from prior', () => {
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ defaults: async () => ({}), effectiveStageId: () => null } as never,
|
||||
{
|
||||
boardContext: async () => ({ defaultBoardId: '', defaults: new Map() }),
|
||||
effectiveBoardId: () => null,
|
||||
effectiveStageId: () => null,
|
||||
} as never,
|
||||
{ system: async () => ({}), toSummary: (row: unknown) => row } as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
@@ -22,7 +22,9 @@
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@vitejs/plugin-vue": "^5.2.3",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^5.8.2",
|
||||
"vite": "^6.2.2",
|
||||
"vue-tsc": "^2.2.8"
|
||||
|
||||
@@ -4,8 +4,20 @@ import { RouterLink } from 'vue-router';
|
||||
import axios from 'axios';
|
||||
import { api } from '@/lib/api';
|
||||
import { rewriteGregorianDates } from '@/lib/jalali';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { brand, type AskMentoResponse, type AskMentoSourceDto } from '@mento/shared';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Button as AButton,
|
||||
Card as ACard,
|
||||
Flex as AFlex,
|
||||
Input as AInput,
|
||||
Space as ASpace,
|
||||
Tag as ATag,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import { ThunderboltOutlined } from '@ant-design/icons-vue';
|
||||
|
||||
const { Paragraph: ATypographyParagraph } = Typography;
|
||||
|
||||
const props = defineProps<{
|
||||
personId?: string;
|
||||
@@ -65,127 +77,53 @@ function insertAnswer() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="ask">
|
||||
<form @submit.prevent="submit">
|
||||
<UiIcon name="sparkle" :size="16" class="ico" />
|
||||
<input
|
||||
v-model="question"
|
||||
type="search"
|
||||
<a-flex vertical :gap="8" :style="{ minWidth: 0 }">
|
||||
<a-flex :gap="8" align="center" :style="{ width: '100%' }">
|
||||
<a-input
|
||||
v-model:value="question"
|
||||
allow-clear
|
||||
:placeholder="placeholder || brand.askPlaceholderFa"
|
||||
/>
|
||||
<button type="submit" :disabled="asking || question.trim().length < 2">
|
||||
{{ asking ? '…' : 'بپرس' }}
|
||||
</button>
|
||||
</form>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<div v-else-if="result" class="answer">
|
||||
<p>{{ result.answer }}</p>
|
||||
<div v-if="result.sources.length" class="sources">
|
||||
:style="{ flex: 1, minWidth: 0 }"
|
||||
@pressEnter="submit"
|
||||
>
|
||||
<template #prefix>
|
||||
<ThunderboltOutlined />
|
||||
</template>
|
||||
</a-input>
|
||||
<a-button
|
||||
type="primary"
|
||||
:disabled="asking || question.trim().length < 2"
|
||||
:loading="asking"
|
||||
@click="submit"
|
||||
>
|
||||
بپرس
|
||||
</a-button>
|
||||
</a-flex>
|
||||
|
||||
<a-alert v-if="error" type="error" show-icon :message="error" />
|
||||
|
||||
<a-card v-else-if="result" :bordered="false">
|
||||
<a-typography-paragraph :style="{ marginBottom: 0 }">
|
||||
{{ result.answer }}
|
||||
</a-typography-paragraph>
|
||||
<a-space v-if="result.sources.length" wrap :size="6" :style="{ marginTop: '8px' }">
|
||||
<RouterLink
|
||||
v-for="source in result.sources"
|
||||
:key="`${source.type}-${source.id}`"
|
||||
:to="sourceTo(source)"
|
||||
>
|
||||
{{ source.label }}
|
||||
<a-tag color="cyan" :bordered="false">{{ source.label }}</a-tag>
|
||||
</RouterLink>
|
||||
</div>
|
||||
<button
|
||||
</a-space>
|
||||
<a-button
|
||||
v-if="allowInsert && result.answer.trim()"
|
||||
type="button"
|
||||
class="insert-btn"
|
||||
type="primary"
|
||||
block
|
||||
:style="{ marginTop: '8px' }"
|
||||
@click="insertAnswer"
|
||||
>
|
||||
درج در پیام
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</a-button>
|
||||
</a-card>
|
||||
</a-flex>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ask {
|
||||
display: grid;
|
||||
gap: 0.55rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.35rem 0.4rem 0.35rem 0.7rem;
|
||||
}
|
||||
|
||||
.ico {
|
||||
color: #0f766e;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
padding: 0.45rem 0;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
padding: 0.45rem 0.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.answer {
|
||||
background: #f0fdfa;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.7rem 0.85rem;
|
||||
}
|
||||
|
||||
.answer p {
|
||||
margin: 0;
|
||||
color: #134e4a;
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.sources {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
margin-top: 0.55rem;
|
||||
}
|
||||
|
||||
.sources a {
|
||||
font-size: 0.74rem;
|
||||
font-weight: 700;
|
||||
color: #0f766e;
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 0.18rem 0.55rem;
|
||||
}
|
||||
|
||||
.insert-btn {
|
||||
margin-top: 0.65rem;
|
||||
width: 100%;
|
||||
background: #0f766e;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: #b91c1c;
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,568 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import { api } from '@/lib/api';
|
||||
import type {
|
||||
ExcelFieldOption,
|
||||
ExcelImportPrepareStatus,
|
||||
ExcelPreviewResult,
|
||||
ImportContactsResult,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
previewExcelClient,
|
||||
readMappedRowsClient,
|
||||
type ClientExcelReadOptions,
|
||||
} from '@/lib/excel-client';
|
||||
import { UiBusyOverlay, UiButton, UiModal, UiSelect } from '@/components/ui';
|
||||
|
||||
const props = defineProps<{
|
||||
previewPath: string;
|
||||
importPath: string;
|
||||
/** اگر باشد: ابتدا فقط فایل خوانده میشود، بعد تکهتکه وارد میشود (برای فایلهای خیلی بزرگ) */
|
||||
preparePath?: string;
|
||||
/**
|
||||
* ایمپورت مرورگرگرا: اکسل در مرورگر خوانده میشود و فقط JSON کوچک به API میرود.
|
||||
* برای فایلهای دهها هزار ردیفی (جلوگیری از ۵۰۲ nginx).
|
||||
*/
|
||||
rowsImportPath?: string;
|
||||
clientAliases?: Record<string, string>;
|
||||
clientFields?: ExcelFieldOption[];
|
||||
/** تشخیص خروجی بدونهدر (مثل فعالیت دیدار) */
|
||||
clientReadOptions?: ClientExcelReadOptions;
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
|
||||
const useClientImport = computed(
|
||||
() =>
|
||||
Boolean(
|
||||
props.rowsImportPath &&
|
||||
props.clientAliases &&
|
||||
props.clientFields?.length,
|
||||
),
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
start: [];
|
||||
done: [result: ImportContactsResult];
|
||||
fail: [message: string];
|
||||
settled: [];
|
||||
}>();
|
||||
|
||||
const input = ref<HTMLInputElement | null>(null);
|
||||
const pending = ref<File | null>(null);
|
||||
const preview = ref<ExcelPreviewResult | null>(null);
|
||||
const mapping = reactive<Record<string, string>>({});
|
||||
const submitting = ref(false);
|
||||
const phase = ref<'idle' | 'preview' | 'import'>('idle');
|
||||
const progressLabel = ref('');
|
||||
/** درصد ۰–۱۰۰؛ در مرحلهٔ خواندن فایل null */
|
||||
const progressPct = ref<number | null>(null);
|
||||
|
||||
const requiredKeys = computed(
|
||||
() => preview.value?.fields.filter((f) => f.required).map((f) => f.key) ?? [],
|
||||
);
|
||||
|
||||
const mappedFields = computed(() => new Set(Object.values(mapping).filter(Boolean)));
|
||||
|
||||
const canImport = computed(() => requiredKeys.value.every((key) => mappedFields.value.has(key)));
|
||||
|
||||
const busyOpen = computed(() => submitting.value && phase.value !== 'idle');
|
||||
const busyMessage = computed(() => {
|
||||
if (phase.value === 'import') {
|
||||
return progressLabel.value || 'در حال ورود اطلاعات از اکسل…';
|
||||
}
|
||||
return 'در حال خواندن و بررسی فایل اکسل…';
|
||||
});
|
||||
const busyProgress = computed(() =>
|
||||
phase.value === 'import' ? progressPct.value : null,
|
||||
);
|
||||
|
||||
function pick() {
|
||||
if (props.disabled || submitting.value) return;
|
||||
input.value?.click();
|
||||
}
|
||||
|
||||
function reset() {
|
||||
pending.value = null;
|
||||
preview.value = null;
|
||||
submitting.value = false;
|
||||
phase.value = 'idle';
|
||||
progressLabel.value = '';
|
||||
progressPct.value = null;
|
||||
for (const key of Object.keys(mapping)) delete mapping[key];
|
||||
}
|
||||
|
||||
function closeMapper() {
|
||||
if (submitting.value) return;
|
||||
reset();
|
||||
emit('settled');
|
||||
}
|
||||
|
||||
function setColumnField(header: string, field: string) {
|
||||
if (field) {
|
||||
for (const [col, current] of Object.entries(mapping)) {
|
||||
if (col !== header && current === field) mapping[col] = '';
|
||||
}
|
||||
}
|
||||
mapping[header] = field;
|
||||
}
|
||||
|
||||
function mergeImportResults(
|
||||
acc: ImportContactsResult,
|
||||
part: ImportContactsResult,
|
||||
): ImportContactsResult {
|
||||
const errors = [...acc.errors, ...(part.errors ?? [])];
|
||||
return {
|
||||
created: acc.created + (part.created ?? 0),
|
||||
skipped: acc.skipped + (part.skipped ?? 0),
|
||||
errors: errors.slice(0, 200),
|
||||
boardId: part.boardId ?? acc.boardId,
|
||||
boards: part.boards?.length ? part.boards : acc.boards,
|
||||
sessionId: part.sessionId,
|
||||
total: part.total ?? acc.total,
|
||||
processed: part.processed ?? acc.processed,
|
||||
hasMore: part.hasMore,
|
||||
nextOffset: part.nextOffset,
|
||||
};
|
||||
}
|
||||
|
||||
async function postImportChunk(opts: {
|
||||
file?: File;
|
||||
map?: Record<string, string>;
|
||||
sessionId?: string;
|
||||
offset?: number;
|
||||
}) {
|
||||
const form = new FormData();
|
||||
if (opts.file) form.append('file', opts.file);
|
||||
if (opts.map && Object.values(opts.map).some(Boolean)) {
|
||||
form.append('mapping', JSON.stringify(opts.map));
|
||||
}
|
||||
if (opts.sessionId) form.append('sessionId', opts.sessionId);
|
||||
if (opts.offset != null) form.append('offset', String(opts.offset));
|
||||
form.append('limit', '250');
|
||||
const { data } = await api.post<ImportContactsResult>(props.importPath, form, {
|
||||
headers: { 'Content-Type': undefined },
|
||||
// خواندن فایلهای خیلی بزرگ در مرحلهٔ اول ممکن است طول بکشد
|
||||
timeout: opts.file ? 10 * 60 * 1000 : 3 * 60 * 1000,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
function updateImportProgress(processed: number, total: number) {
|
||||
if (total <= 0) {
|
||||
progressPct.value = null;
|
||||
progressLabel.value = 'در حال ورود اطلاعات از اکسل…';
|
||||
return;
|
||||
}
|
||||
const pct = Math.max(0, Math.min(100, Math.round((processed / total) * 100)));
|
||||
progressPct.value = pct;
|
||||
progressLabel.value = `ورود فایل: ${processed.toLocaleString('fa-IR')} از ${total.toLocaleString('fa-IR')} ردیف`;
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
async function postPrepare(file: File, map?: Record<string, string>) {
|
||||
if (!props.preparePath) {
|
||||
throw new Error('preparePath تنظیم نشده');
|
||||
}
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (map && Object.values(map).some(Boolean)) {
|
||||
form.append('mapping', JSON.stringify(map));
|
||||
}
|
||||
// فقط آپلود — پارس روی سرور ناهمگام است؛ تایماوت کوتاه کافی است
|
||||
const { data } = await api.post<ImportContactsResult>(props.preparePath, form, {
|
||||
headers: { 'Content-Type': undefined },
|
||||
timeout: 3 * 60 * 1000,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
async function waitPrepareReady(sessionId: string) {
|
||||
if (!props.preparePath) throw new Error('preparePath تنظیم نشده');
|
||||
const statusUrl = `${props.preparePath}/${sessionId}`;
|
||||
const started = Date.now();
|
||||
const maxMs = 15 * 60 * 1000;
|
||||
while (Date.now() - started < maxMs) {
|
||||
const { data } = await api.get<ExcelImportPrepareStatus>(statusUrl, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
if (data.status === 'ready') {
|
||||
progressLabel.value = `فایل آماده شد — ${data.total.toLocaleString('fa-IR')} ردیف`;
|
||||
return data;
|
||||
}
|
||||
if (data.status === 'error') {
|
||||
throw new Error(data.error || 'آمادهسازی فایل اکسل ناموفق بود');
|
||||
}
|
||||
const parsed = data.parsed || 0;
|
||||
progressPct.value = null;
|
||||
progressLabel.value = parsed
|
||||
? `در حال خواندن فایل روی سرور… ${parsed.toLocaleString('fa-IR')} ردیف`
|
||||
: 'در حال خواندن فایل روی سرور… لطفاً صبر کنید';
|
||||
await sleep(1200);
|
||||
}
|
||||
throw new Error('آمادهسازی فایل بیش از حد طول کشید. دوباره تلاش کنید.');
|
||||
}
|
||||
|
||||
async function runClientRowsImport(file: File, map?: Record<string, string>) {
|
||||
if (!props.rowsImportPath || !props.clientAliases) {
|
||||
throw new Error('پیکربندی ایمپورت مرورگر ناقص است');
|
||||
}
|
||||
phase.value = 'import';
|
||||
progressLabel.value = 'در حال خواندن فایل در مرورگر…';
|
||||
progressPct.value = 0;
|
||||
|
||||
const rows = await readMappedRowsClient(
|
||||
file,
|
||||
props.clientAliases,
|
||||
map,
|
||||
props.clientReadOptions,
|
||||
);
|
||||
const total = rows.length;
|
||||
if (total > 100_000) {
|
||||
return {
|
||||
created: 0,
|
||||
skipped: 0,
|
||||
errors: [{ row: 1, message: 'فایل بیش از ۱۰۰۰۰۰ ردیف دارد. فایل را تقسیم کنید.' }],
|
||||
total,
|
||||
processed: 0,
|
||||
hasMore: false,
|
||||
};
|
||||
}
|
||||
|
||||
updateImportProgress(0, total);
|
||||
let acc: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
||||
let sessionId: string | undefined;
|
||||
const chunkSize = 60;
|
||||
|
||||
for (let offset = 0; offset < total; offset += chunkSize) {
|
||||
const slice = rows.slice(offset, offset + chunkSize);
|
||||
const { data: part } = await api.post<ImportContactsResult>(
|
||||
props.rowsImportPath,
|
||||
{
|
||||
rows: slice,
|
||||
offset,
|
||||
total,
|
||||
sessionId,
|
||||
},
|
||||
{ timeout: 120_000 },
|
||||
);
|
||||
acc = mergeImportResults(acc, part);
|
||||
updateImportProgress(part.processed ?? offset + slice.length, total);
|
||||
if (part.errors?.some((e) => e.row === 1 && /حداکثر|بیش از/.test(e.message))) {
|
||||
break;
|
||||
}
|
||||
sessionId = part.sessionId;
|
||||
if (!part.hasMore) break;
|
||||
}
|
||||
|
||||
updateImportProgress(total, total);
|
||||
return acc;
|
||||
}
|
||||
|
||||
async function runChunkedImport(file: File, map?: Record<string, string>) {
|
||||
if (useClientImport.value) {
|
||||
return runClientRowsImport(file, map);
|
||||
}
|
||||
|
||||
phase.value = 'import';
|
||||
progressLabel.value = 'در حال ارسال فایل…';
|
||||
progressPct.value = 0;
|
||||
|
||||
let acc: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
||||
let sessionId: string | undefined;
|
||||
let offset = 0;
|
||||
let guard = 0;
|
||||
const maxChunks = 2000;
|
||||
|
||||
if (props.preparePath) {
|
||||
const prep = await postPrepare(file, map);
|
||||
if (!prep.sessionId) {
|
||||
throw new Error(prep.errors[0]?.message || 'آمادهسازی فایل ناموفق بود');
|
||||
}
|
||||
sessionId = prep.sessionId;
|
||||
progressLabel.value = 'در حال خواندن فایل روی سرور…';
|
||||
const ready = await waitPrepareReady(sessionId);
|
||||
if (!ready.total) {
|
||||
return {
|
||||
...acc,
|
||||
total: 0,
|
||||
processed: 0,
|
||||
hasMore: false,
|
||||
errors: ready.error
|
||||
? [{ row: 1, message: ready.error }]
|
||||
: [{ row: 1, message: 'هیچ ردیف دادهای در فایل نیست' }],
|
||||
};
|
||||
}
|
||||
updateImportProgress(0, ready.total);
|
||||
}
|
||||
|
||||
while (guard < maxChunks) {
|
||||
guard += 1;
|
||||
const part = await postImportChunk({
|
||||
file: sessionId ? undefined : file,
|
||||
map: sessionId ? undefined : map,
|
||||
sessionId,
|
||||
offset: sessionId ? offset : undefined,
|
||||
});
|
||||
acc = mergeImportResults(acc, part);
|
||||
|
||||
const total = part.total ?? 0;
|
||||
const processed = part.processed ?? 0;
|
||||
updateImportProgress(processed, total);
|
||||
|
||||
if (
|
||||
part.errors?.some((e) => e.row === 1 && /بیش از .* ردیف/.test(e.message))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!part.hasMore || !part.sessionId) {
|
||||
if (total > 0) updateImportProgress(total, total);
|
||||
break;
|
||||
}
|
||||
sessionId = part.sessionId;
|
||||
offset = part.nextOffset ?? processed;
|
||||
}
|
||||
|
||||
if (guard >= maxChunks && acc.hasMore) {
|
||||
acc.errors = [
|
||||
...acc.errors,
|
||||
{
|
||||
row: 1,
|
||||
message: 'ورود بهخاطر تعداد مراحل زیاد متوقف شد. از جایی که مانده ادامه دهید یا فایل را تقسیم کنید.',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return acc;
|
||||
}
|
||||
|
||||
function apiMessage(e: unknown, fallback: string) {
|
||||
if (!axios.isAxiosError(e)) {
|
||||
return e instanceof Error && e.message ? e.message : fallback;
|
||||
}
|
||||
if (e.code === 'ECONNABORTED' || /timeout/i.test(e.message)) {
|
||||
return 'مهلت درخواست تمام شد — فایل خیلی بزرگ است یا سرور دیر جواب داد. دوباره تلاش کنید.';
|
||||
}
|
||||
if (!e.response) {
|
||||
return 'ارتباط با سرور برقرار نشد. اتصال را بررسی کنید و دوباره تلاش کنید.';
|
||||
}
|
||||
const status = e.response.status;
|
||||
const data = e.response.data as { message?: string | string[] } | string | undefined;
|
||||
let msg: string | undefined;
|
||||
if (typeof data === 'string' && data.trim() && !data.trim().startsWith('<')) {
|
||||
msg = data.trim().slice(0, 280);
|
||||
} else if (data && typeof data === 'object') {
|
||||
const m = data.message;
|
||||
msg = Array.isArray(m) ? m.join('، ') : m;
|
||||
}
|
||||
if (msg) return msg;
|
||||
if (status === 413) return 'حجم فایل بیش از حد مجاز سرور است.';
|
||||
if (status === 502 || status === 504) {
|
||||
return 'سرور میانی قطع شد (معمولاً بهخاطر حجم/زمان فایل). چند دقیقه بعد دوباره تلاش کنید.';
|
||||
}
|
||||
return `${fallback} (کد ${status})`;
|
||||
}
|
||||
|
||||
async function onFile(ev: Event) {
|
||||
const el = ev.target as HTMLInputElement;
|
||||
const file = el.files?.[0];
|
||||
el.value = '';
|
||||
if (!file) return;
|
||||
emit('start');
|
||||
submitting.value = true;
|
||||
phase.value = 'preview';
|
||||
try {
|
||||
let data: ExcelPreviewResult;
|
||||
if (useClientImport.value && props.clientAliases && props.clientFields) {
|
||||
progressLabel.value = 'در حال خواندن فایل در مرورگر…';
|
||||
data = await previewExcelClient(
|
||||
file,
|
||||
props.clientAliases,
|
||||
props.clientFields,
|
||||
props.clientReadOptions,
|
||||
);
|
||||
} else {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api.post<ExcelPreviewResult>(props.previewPath, form, {
|
||||
headers: { 'Content-Type': undefined },
|
||||
timeout: 5 * 60 * 1000,
|
||||
});
|
||||
data = res.data;
|
||||
}
|
||||
if (!data.needsMapping) {
|
||||
try {
|
||||
emit('done', await runChunkedImport(file));
|
||||
reset();
|
||||
emit('settled');
|
||||
} catch (impErr) {
|
||||
emit('fail', apiMessage(impErr, 'ایمپورت ناموفق بود'));
|
||||
reset();
|
||||
emit('settled');
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.value = file;
|
||||
preview.value = data;
|
||||
for (const col of data.columns) {
|
||||
mapping[col.header] = data.suggested[col.header] ?? '';
|
||||
}
|
||||
phase.value = 'idle';
|
||||
submitting.value = false;
|
||||
// Allow parent toolbar while user maps columns.
|
||||
emit('settled');
|
||||
} catch (e) {
|
||||
emit('fail', apiMessage(e, 'خواندن فایل اکسل ناموفق بود'));
|
||||
reset();
|
||||
emit('settled');
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmMapping() {
|
||||
if (!pending.value || !canImport.value || submitting.value) return;
|
||||
emit('start');
|
||||
submitting.value = true;
|
||||
phase.value = 'import';
|
||||
try {
|
||||
emit('done', await runChunkedImport(pending.value, { ...mapping }));
|
||||
reset();
|
||||
emit('settled');
|
||||
} catch (e) {
|
||||
emit('fail', apiMessage(e, 'ایمپورت ناموفق بود'));
|
||||
phase.value = 'idle';
|
||||
submitting.value = false;
|
||||
progressLabel.value = '';
|
||||
progressPct.value = null;
|
||||
emit('settled');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="excel-import" :class="{ isBusy: submitting }" @click.stop="pick">
|
||||
<slot :loading="submitting" :disabled="disabled || submitting" />
|
||||
<input
|
||||
ref="input"
|
||||
type="file"
|
||||
accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
hidden
|
||||
:disabled="disabled || submitting"
|
||||
@change="onFile"
|
||||
@click.stop
|
||||
/>
|
||||
</span>
|
||||
|
||||
<UiBusyOverlay
|
||||
:open="busyOpen"
|
||||
:message="busyMessage"
|
||||
:progress="busyProgress"
|
||||
nest
|
||||
/>
|
||||
|
||||
<UiModal :open="!!preview" title="تطبیق ستونهای اکسل" @close="closeMapper">
|
||||
<p class="lead">
|
||||
ستونهای این فایل با قالب سیستم یکی نیست. مشخص کنید هر ستون فایل در کدام فیلد ریخته شود.
|
||||
</p>
|
||||
<p v-if="preview?.largeFile" class="large-hint">
|
||||
فایل بزرگ است ({{ (preview.rowCount ?? 0).toLocaleString('fa-IR') }} ردیف) — ورود بهصورت چندمرحلهای انجام میشود.
|
||||
</p>
|
||||
<div class="rows">
|
||||
<div v-for="col in preview?.columns ?? []" :key="col.header" class="row">
|
||||
<div class="source">
|
||||
<strong>{{ col.header }}</strong>
|
||||
<small v-if="col.samples.length">نمونه: {{ col.samples.join('، ') }}</small>
|
||||
</div>
|
||||
<UiSelect
|
||||
:model-value="mapping[col.header] ?? ''"
|
||||
:disabled="submitting"
|
||||
@update:model-value="setColumnField(col.header, $event)"
|
||||
>
|
||||
<option value="">نادیده بگیر</option>
|
||||
<option v-for="field in preview?.fields ?? []" :key="field.key" :value="field.key">
|
||||
{{ field.label }}{{ field.required ? ' *' : '' }}
|
||||
</option>
|
||||
</UiSelect>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="!canImport" class="hint">فیلدهای ستارهدار را حتماً به یک ستون وصل کنید.</p>
|
||||
<template #footer>
|
||||
<UiButton variant="ghost" :disabled="submitting" @click="closeMapper">انصراف</UiButton>
|
||||
<UiButton :disabled="!canImport" :loading="submitting" @click="confirmMapping">
|
||||
ورود فایل
|
||||
</UiButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.excel-import {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.excel-import.isBusy {
|
||||
pointer-events: none;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.lead {
|
||||
margin: 0 0 1rem;
|
||||
color: var(--muted);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.large-hint {
|
||||
margin: -0.35rem 0 1rem;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 10px;
|
||||
background: color-mix(in srgb, var(--accent, #2563eb) 12%, transparent);
|
||||
color: var(--fg, inherit);
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.rows {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr);
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.source {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.source strong {
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.source small {
|
||||
color: var(--muted);
|
||||
font-size: 0.78rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0.85rem 0 0;
|
||||
color: var(--danger);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -59,6 +59,11 @@ const draftMinute = ref(0);
|
||||
const clockFace = ref<'hour' | 'minute'>('hour');
|
||||
const isMobile = ref(false);
|
||||
const dragging = ref(false);
|
||||
/** نمای تقویم: روزها ← کلیک عنوان → ماهها ← کلیک عنوان → سالها */
|
||||
const calView = ref<'days' | 'months' | 'years'>('days');
|
||||
const YEAR_PAGE = 12;
|
||||
const yearPageStart = ref(todayJ.jy - 5);
|
||||
const MONTHS = Array.from({ length: 12 }, (_, i) => i + 1);
|
||||
|
||||
type Cell = {
|
||||
key: string;
|
||||
@@ -107,6 +112,26 @@ const monthTitle = computed(
|
||||
() => `${jalaliMonthName(cursor.value.jm)} ${toFaDigits(cursor.value.jy)}`,
|
||||
);
|
||||
|
||||
const navTitle = computed(() => {
|
||||
if (calView.value === 'months') return toFaDigits(cursor.value.jy);
|
||||
if (calView.value === 'years') {
|
||||
return `${toFaDigits(yearPageStart.value)} – ${toFaDigits(yearPageStart.value + YEAR_PAGE - 1)}`;
|
||||
}
|
||||
return monthTitle.value;
|
||||
});
|
||||
|
||||
const navLabels = computed(() => {
|
||||
if (calView.value === 'months') return { forward: 'سال بعد', back: 'سال قبل' };
|
||||
if (calView.value === 'years') return { forward: 'سالهای بعد', back: 'سالهای قبل' };
|
||||
return { forward: 'ماه بعد', back: 'ماه قبل' };
|
||||
});
|
||||
|
||||
const yearOptions = computed(() =>
|
||||
Array.from({ length: YEAR_PAGE }, (_, i) => yearPageStart.value + i),
|
||||
);
|
||||
|
||||
const selectedJ = computed(() => (parsed.value ? dateToJalali(parsed.value) : null));
|
||||
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i);
|
||||
const minuteMarks = Array.from({ length: 12 }, (_, i) => i * 5);
|
||||
const columnMinutes = Array.from({ length: 60 }, (_, i) => i);
|
||||
@@ -316,6 +341,7 @@ function onWindowChange() {
|
||||
async function show() {
|
||||
if (props.disabled) return;
|
||||
syncDraftFrom(parsed.value);
|
||||
calView.value = 'days';
|
||||
clockFace.value = 'hour';
|
||||
syncViewport();
|
||||
open.value = true;
|
||||
@@ -341,6 +367,38 @@ function goMonth(delta: number) {
|
||||
void nextTick(place);
|
||||
}
|
||||
|
||||
function navStep(delta: number) {
|
||||
if (calView.value === 'months') {
|
||||
cursor.value = { jy: cursor.value.jy + delta, jm: cursor.value.jm };
|
||||
} else if (calView.value === 'years') {
|
||||
yearPageStart.value += delta * YEAR_PAGE;
|
||||
} else {
|
||||
goMonth(delta);
|
||||
}
|
||||
}
|
||||
|
||||
function onTitleClick() {
|
||||
if (calView.value === 'days') {
|
||||
calView.value = 'months';
|
||||
} else if (calView.value === 'months') {
|
||||
yearPageStart.value = cursor.value.jy - 5;
|
||||
calView.value = 'years';
|
||||
}
|
||||
void nextTick(place);
|
||||
}
|
||||
|
||||
function pickMonth(jm: number) {
|
||||
cursor.value = { jy: cursor.value.jy, jm };
|
||||
calView.value = 'days';
|
||||
void nextTick(place);
|
||||
}
|
||||
|
||||
function pickYear(jy: number) {
|
||||
cursor.value = { jy, jm: cursor.value.jm };
|
||||
calView.value = 'months';
|
||||
void nextTick(place);
|
||||
}
|
||||
|
||||
function pickDay(cell: Cell) {
|
||||
if (!cell.inMonth) {
|
||||
cursor.value = { jy: cell.jy, jm: cell.jm };
|
||||
@@ -483,16 +541,53 @@ onBeforeUnmount(() => {
|
||||
:style="{ top: `${top}px`, left: `${left}px` }"
|
||||
>
|
||||
<header v-if="mode !== 'time'" class="nav">
|
||||
<a-button type="text" class="nav-btn" aria-label="ماه بعد" @click="goMonth(1)">
|
||||
<a-button type="text" class="nav-btn" :aria-label="navLabels.forward" @click="navStep(1)">
|
||||
<template #icon><RightOutlined /></template>
|
||||
</a-button>
|
||||
<strong>{{ monthTitle }}</strong>
|
||||
<a-button type="text" class="nav-btn next" aria-label="ماه قبل" @click="goMonth(-1)">
|
||||
<a-button
|
||||
type="text"
|
||||
class="nav-title"
|
||||
:class="{ static: calView === 'years' }"
|
||||
:aria-label="calView === 'days' ? 'انتخاب ماه و سال' : calView === 'months' ? 'انتخاب سال' : undefined"
|
||||
@click="onTitleClick"
|
||||
>
|
||||
{{ navTitle }}
|
||||
</a-button>
|
||||
<a-button type="text" class="nav-btn next" :aria-label="navLabels.back" @click="navStep(-1)">
|
||||
<template #icon><LeftOutlined /></template>
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<template v-if="mode !== 'time'">
|
||||
<div v-if="mode !== 'time' && calView === 'months'" class="pick-grid">
|
||||
<a-button
|
||||
v-for="m in MONTHS"
|
||||
:key="`pm-${m}`"
|
||||
type="text"
|
||||
class="pick-cell"
|
||||
:class="{
|
||||
on: selectedJ?.jy === cursor.jy && selectedJ?.jm === m,
|
||||
today: todayJ.jy === cursor.jy && todayJ.jm === m,
|
||||
}"
|
||||
@click="pickMonth(m)"
|
||||
>
|
||||
{{ jalaliMonthName(m) }}
|
||||
</a-button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="mode !== 'time' && calView === 'years'" class="pick-grid">
|
||||
<a-button
|
||||
v-for="y in yearOptions"
|
||||
:key="`py-${y}`"
|
||||
type="text"
|
||||
class="pick-cell"
|
||||
:class="{ on: selectedJ?.jy === y, today: todayJ.jy === y }"
|
||||
@click="pickYear(y)"
|
||||
>
|
||||
{{ toFaDigits(y) }}
|
||||
</a-button>
|
||||
</div>
|
||||
|
||||
<template v-if="mode !== 'time' && calView === 'days'">
|
||||
<div class="week">
|
||||
<span v-for="day in WEEKDAYS" :key="day">{{ day }}</span>
|
||||
</div>
|
||||
@@ -631,7 +726,7 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
پاک کردن
|
||||
</a-button>
|
||||
<a-button type="primary" @click="hide">تأیید</a-button>
|
||||
<a-button type="primary" class="done" @click="hide">تأیید</a-button>
|
||||
</footer>
|
||||
</div>
|
||||
</Teleport>
|
||||
@@ -758,7 +853,8 @@ onBeforeUnmount(() => {
|
||||
z-index: 120;
|
||||
width: min(20.5rem, calc(100vw - 16px));
|
||||
max-height: calc(100vh - 16px);
|
||||
overflow: auto;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18);
|
||||
@@ -781,19 +877,61 @@ onBeforeUnmount(() => {
|
||||
margin-bottom: 0.55rem;
|
||||
}
|
||||
|
||||
.nav strong {
|
||||
.nav-title {
|
||||
font-size: 0.92rem;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.nav-btn {
|
||||
.nav-title:not(.static):hover {
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.nav-title.static {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.pick-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.35rem;
|
||||
padding: 0.25rem 0;
|
||||
}
|
||||
|
||||
.panel :deep(.ant-btn.pick-cell) {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 44px;
|
||||
margin: 0;
|
||||
padding: 0 4px;
|
||||
border-radius: var(--radius);
|
||||
color: #0f172a;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.panel :deep(.ant-btn.pick-cell.today) {
|
||||
box-shadow: inset 0 0 0 1px #99f6e4;
|
||||
}
|
||||
|
||||
.panel :deep(.ant-btn.pick-cell.on),
|
||||
.panel :deep(.ant-btn.pick-cell:hover) {
|
||||
background: #0d9488;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.panel :deep(.ant-btn.nav-btn) {
|
||||
width: 32px;
|
||||
min-width: 32px;
|
||||
height: 32px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: #f1f5f9;
|
||||
color: #0f766e;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@@ -804,8 +942,9 @@ onBeforeUnmount(() => {
|
||||
.week,
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
grid-template-columns: repeat(7, minmax(0, 1fr));
|
||||
gap: 0.15rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.week span {
|
||||
@@ -815,31 +954,40 @@ onBeforeUnmount(() => {
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.day {
|
||||
.panel :deep(.ant-btn.day) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 34px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: #0f172a;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.day.mute {
|
||||
.panel :deep(.ant-btn.day.mute) {
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.day.today {
|
||||
.panel :deep(.ant-btn.day.today) {
|
||||
box-shadow: inset 0 0 0 1px #99f6e4;
|
||||
}
|
||||
|
||||
.day.on,
|
||||
.day:hover {
|
||||
.panel :deep(.ant-btn.day.on),
|
||||
.panel :deep(.ant-btn.day:hover) {
|
||||
background: #0d9488;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.day.mute:hover {
|
||||
.panel :deep(.ant-btn.day.mute:hover) {
|
||||
background: #f1f5f9;
|
||||
color: #64748b;
|
||||
}
|
||||
@@ -869,9 +1017,11 @@ onBeforeUnmount(() => {
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
|
||||
.md-chip {
|
||||
.panel :deep(.ant-btn.md-chip) {
|
||||
min-width: 5.1rem;
|
||||
height: 4.1rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: #f1f5f9;
|
||||
@@ -884,7 +1034,7 @@ onBeforeUnmount(() => {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.md-chip.on {
|
||||
.panel :deep(.ant-btn.md-chip.on) {
|
||||
background: #ccfbf1;
|
||||
color: #0f766e;
|
||||
box-shadow: inset 0 0 0 2px #99f6e4;
|
||||
@@ -958,10 +1108,11 @@ onBeforeUnmount(() => {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.md-tick {
|
||||
.panel :deep(.ant-btn.md-tick) {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
width: 36px;
|
||||
min-width: 36px;
|
||||
height: 36px;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
@@ -978,12 +1129,12 @@ onBeforeUnmount(() => {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.md-tick.inner {
|
||||
.panel :deep(.ant-btn.md-tick.inner) {
|
||||
font-size: 0.74rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.md-tick.on {
|
||||
.panel :deep(.ant-btn.md-tick.on) {
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
}
|
||||
@@ -1032,9 +1183,12 @@ onBeforeUnmount(() => {
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.col-item {
|
||||
.panel :deep(.ant-btn.col-item) {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: transparent;
|
||||
@@ -1045,11 +1199,11 @@ onBeforeUnmount(() => {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.col-item:hover {
|
||||
.panel :deep(.ant-btn.col-item:hover) {
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
.col-item.on {
|
||||
.panel :deep(.ant-btn.col-item.on) {
|
||||
background: #0d9488;
|
||||
color: #fff;
|
||||
}
|
||||
@@ -1061,28 +1215,8 @@ onBeforeUnmount(() => {
|
||||
margin-top: 0.7rem;
|
||||
}
|
||||
|
||||
.link,
|
||||
.done {
|
||||
border: 0;
|
||||
background: none;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.link {
|
||||
color: #0f766e;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.done {
|
||||
.panel :deep(.ant-btn.done) {
|
||||
margin-inline-start: auto;
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.4rem 0.8rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.panel.is-mobile .time-box {
|
||||
|
||||
@@ -5,6 +5,20 @@ import { api } from '@/lib/api';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import { brand, type NoteAiPayloadDto, type NoteAiSuggestionDto } from '@mento/shared';
|
||||
import { rewriteGregorianDates } from '@/lib/jalali';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Button as AButton,
|
||||
Card as ACard,
|
||||
Checkbox as ACheckbox,
|
||||
Flex as AFlex,
|
||||
Input as AInput,
|
||||
Space as ASpace,
|
||||
Textarea as ATextarea,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
const { Text: ATypographyText, Paragraph: ATypographyParagraph, Title: ATypographyTitle } =
|
||||
Typography;
|
||||
|
||||
const props = defineProps<{
|
||||
noteId: string;
|
||||
@@ -148,193 +162,108 @@ function formatPayloadSummary(value: NoteAiPayloadDto | null) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="ai-panel">
|
||||
<header>
|
||||
<strong>پیشنهاد {{ brand.aiName }}</strong>
|
||||
<button
|
||||
<a-card :bordered="true" :style="{ marginTop: '12px' }">
|
||||
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
|
||||
<a-typography-text strong>پیشنهاد {{ brand.aiName }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="!isPending"
|
||||
type="button"
|
||||
class="link"
|
||||
type="link"
|
||||
:disabled="loading"
|
||||
@click="analyze"
|
||||
>
|
||||
{{ loading ? '…' : 'تحلیل مجدد' }}
|
||||
</button>
|
||||
<button
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else-if="!suggestion"
|
||||
type="button"
|
||||
class="link"
|
||||
type="link"
|
||||
:disabled="loading"
|
||||
@click="analyze"
|
||||
>
|
||||
{{ loading ? 'در حال تحلیل…' : 'تحلیل با AI' }}
|
||||
</button>
|
||||
</header>
|
||||
</a-button>
|
||||
</a-flex>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<p v-else-if="loading && !suggestion" class="muted">در حال تحلیل یادداشت…</p>
|
||||
<p v-else-if="suggestion?.status === 'failed'" class="error">
|
||||
{{ suggestion.errorMessage || 'تحلیل ناموفق بود' }}
|
||||
<button type="button" class="link" @click="analyze">تلاش دوباره</button>
|
||||
</p>
|
||||
<p v-else-if="!suggestion" class="muted">
|
||||
<button type="button" class="link" :disabled="loading" @click="analyze">
|
||||
تحلیل این یادداشت با AI
|
||||
</button>
|
||||
</p>
|
||||
<a-alert v-if="error" type="error" show-icon :message="error" :style="{ marginTop: '8px' }" />
|
||||
<a-typography-text v-else-if="loading && !suggestion" type="secondary">
|
||||
در حال تحلیل یادداشت…
|
||||
</a-typography-text>
|
||||
<a-flex v-else-if="suggestion?.status === 'failed'" vertical :gap="4">
|
||||
<a-alert
|
||||
type="error"
|
||||
show-icon
|
||||
:message="suggestion.errorMessage || 'تحلیل ناموفق بود'"
|
||||
/>
|
||||
<a-button type="link" @click="analyze">تلاش دوباره</a-button>
|
||||
</a-flex>
|
||||
<a-button
|
||||
v-else-if="!suggestion"
|
||||
type="link"
|
||||
:disabled="loading"
|
||||
@click="analyze"
|
||||
>
|
||||
تحلیل این یادداشت با AI
|
||||
</a-button>
|
||||
|
||||
<template v-else-if="isPending && payload">
|
||||
<p v-if="formatPayloadSummary(payload)" class="summary">{{ formatPayloadSummary(payload) }}</p>
|
||||
<a-typography-paragraph
|
||||
v-if="formatPayloadSummary(payload)"
|
||||
type="secondary"
|
||||
:style="{ marginTop: '8px' }"
|
||||
>
|
||||
{{ formatPayloadSummary(payload) }}
|
||||
</a-typography-paragraph>
|
||||
|
||||
<div v-if="payload.nextAction" class="block">
|
||||
<label class="check">
|
||||
<input v-model="applyNextAction" type="checkbox" />
|
||||
کار بعدی
|
||||
</label>
|
||||
<input v-model="nextTitle" type="text" placeholder="عنوان کار بعدی" />
|
||||
<JalaliDateInput v-model="nextDueAt" mode="datetime" />
|
||||
</div>
|
||||
<a-flex v-if="payload.nextAction" vertical :gap="8" :style="{ marginTop: '8px' }">
|
||||
<a-checkbox v-model:checked="applyNextAction">کار بعدی</a-checkbox>
|
||||
<a-input v-model:value="nextTitle" placeholder="عنوان کار بعدی" style="width: 100%" />
|
||||
<JalaliDateInput v-model="nextDueAt" mode="datetime" style="width: 100%" />
|
||||
</a-flex>
|
||||
|
||||
<div v-if="memoryItems.length" class="block">
|
||||
<p class="block-title">حافظه مشتری (با تأیید شما ذخیره میشود)</p>
|
||||
<p v-if="!hasPerson" class="warn">برای ذخیره حافظه، یادداشت باید به یک شخص متصل باشد.</p>
|
||||
<label
|
||||
<a-flex v-if="memoryItems.length" vertical :gap="8" :style="{ marginTop: '12px' }">
|
||||
<a-typography-title :level="5" :style="{ margin: 0 }">
|
||||
حافظه مشتری (با تأیید شما ذخیره میشود)
|
||||
</a-typography-title>
|
||||
<a-alert
|
||||
v-if="!hasPerson"
|
||||
type="warning"
|
||||
show-icon
|
||||
message="برای ذخیره حافظه، یادداشت باید به یک شخص متصل باشد."
|
||||
/>
|
||||
<a-flex
|
||||
v-for="(_, index) in memoryItems"
|
||||
:key="index"
|
||||
class="memory-row"
|
||||
:gap="8"
|
||||
align="flex-start"
|
||||
>
|
||||
<input
|
||||
v-model="selectedMemory[index]"
|
||||
type="checkbox"
|
||||
<a-checkbox
|
||||
v-model:checked="selectedMemory[index]"
|
||||
:disabled="!hasPerson"
|
||||
/>
|
||||
<textarea v-model="memoryEdits[index]" rows="2" />
|
||||
</label>
|
||||
</div>
|
||||
<a-textarea v-model:value="memoryEdits[index]" :rows="2" style="width: 100%" />
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
|
||||
<div class="actions">
|
||||
<button type="button" class="btn" :disabled="applying" @click="apply">
|
||||
{{ applying ? '…' : 'اعمال انتخابشده' }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-ghost" :disabled="applying" @click="dismiss">
|
||||
رد کردن
|
||||
</button>
|
||||
</div>
|
||||
<a-space :size="8" wrap :style="{ marginTop: '12px' }">
|
||||
<a-button type="primary" :disabled="applying" :loading="applying" @click="apply">
|
||||
اعمال انتخابشده
|
||||
</a-button>
|
||||
<a-button :disabled="applying" @click="dismiss">رد کردن</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<p v-else-if="suggestion?.status === 'applied'" class="muted ok">پیشنهاد اعمال شد.</p>
|
||||
<p v-else-if="suggestion?.status === 'dismissed'" class="muted">پیشنهاد رد شد.</p>
|
||||
</section>
|
||||
<a-typography-text
|
||||
v-else-if="suggestion?.status === 'applied'"
|
||||
type="success"
|
||||
:style="{ display: 'block', marginTop: '8px' }"
|
||||
>
|
||||
پیشنهاد اعمال شد.
|
||||
</a-typography-text>
|
||||
<a-typography-text
|
||||
v-else-if="suggestion?.status === 'dismissed'"
|
||||
type="secondary"
|
||||
:style="{ display: 'block', marginTop: '8px' }"
|
||||
>
|
||||
پیشنهاد رد شد.
|
||||
</a-typography-text>
|
||||
</a-card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ai-panel {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.75rem 0.85rem;
|
||||
border: 1px dashed var(--accent);
|
||||
border-radius: var(--radius);
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
display: grid;
|
||||
gap: 0.6rem;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.link {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.block {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.block-title {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.memory-row {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.45rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
textarea {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.55rem 0.7rem;
|
||||
font: inherit;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.actions .btn {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.actions .btn,
|
||||
.actions .btn-ghost {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.summary {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: #067647;
|
||||
}
|
||||
|
||||
.warn {
|
||||
margin: 0;
|
||||
color: #b54708;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: #b42318;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import axios from 'axios';
|
||||
import type { OutboundSmsHistoryResponse, OutboundSmsLogDto } from '@mento/shared';
|
||||
import { MESSAGE_AUTOMATION_FIELDS, MESSAGE_AUTOMATION_SMS_SEGMENT } from '@mento/shared';
|
||||
import { MESSAGE_AUTOMATION_FIELDS, countSmsParts } from '@mento/shared';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
||||
import { UiButton, UiModal } from '@/components/ui';
|
||||
@@ -46,7 +46,7 @@ const historyLoading = ref(false);
|
||||
|
||||
const preview = computed(() => fill(text.value));
|
||||
const count = computed(() => text.value.length);
|
||||
const parts = computed(() => (count.value === 0 ? 0 : Math.ceil(count.value / MESSAGE_AUTOMATION_SMS_SEGMENT)));
|
||||
const parts = computed(() => countSmsParts(text.value));
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import type { SmsWalletSummaryDto } from '@mento/shared';
|
||||
import { api } from '@/lib/api';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
const auth = useAuthStore();
|
||||
const summary = ref<SmsWalletSummaryDto | null>(null);
|
||||
const loading = ref(false);
|
||||
const chargeOpen = ref(false);
|
||||
const warnOpen = ref(false);
|
||||
const copyHint = ref('');
|
||||
const NEGATIVE_KEY = 'mento_sms_negative_warning_shown';
|
||||
|
||||
const visible = computed(() => Boolean(summary.value?.billingEnabled));
|
||||
|
||||
const balanceLabel = computed(() => {
|
||||
const n = summary.value?.balanceRials ?? 0;
|
||||
return toFaDigits(new Intl.NumberFormat('fa-IR').format(n));
|
||||
});
|
||||
|
||||
const toneClass = computed(() => {
|
||||
const level = summary.value?.balanceLevel;
|
||||
if (level === 'critical') return 'critical';
|
||||
if (level === 'warning') return 'warning';
|
||||
if ((summary.value?.balanceRials ?? 0) < 0) return 'negative';
|
||||
return 'healthy';
|
||||
});
|
||||
|
||||
const chargeInfo = computed(() => summary.value?.chargeInfo ?? null);
|
||||
|
||||
function normalizeCopyText(value: string) {
|
||||
const persianDigits = '۰۱۲۳۴۵۶۷۸۹';
|
||||
const arabicDigits = '٠١٢٣٤٥٦٧٨٩';
|
||||
return value
|
||||
.replace(/[\u06F0-\u06F9]/g, (digit) => String(persianDigits.indexOf(digit)))
|
||||
.replace(/[\u0660-\u0669]/g, (digit) => String(arabicDigits.indexOf(digit)))
|
||||
.replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
function formatCardDisplay(value: string) {
|
||||
const digits = normalizeCopyText(value);
|
||||
if (!digits) return '—';
|
||||
return digits.replace(/(\d{4})(?=\d)/g, '$1 ').trim();
|
||||
}
|
||||
|
||||
async function copyValue(label: string, value: string) {
|
||||
const text = normalizeCopyText(value);
|
||||
if (!text) {
|
||||
copyHint.value = `${label} ثبت نشده است`;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
copyHint.value = `${label} کپی شد`;
|
||||
} catch {
|
||||
copyHint.value = 'کپی انجام نشد';
|
||||
}
|
||||
}
|
||||
|
||||
function closeCharge() {
|
||||
chargeOpen.value = false;
|
||||
copyHint.value = '';
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!auth.isAuthenticated || !auth.user?.organizationId) {
|
||||
summary.value = null;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await api.get<SmsWalletSummaryDto>('/sms-wallet/summary');
|
||||
summary.value = data;
|
||||
syncWarn(data);
|
||||
} catch {
|
||||
summary.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function syncWarn(data: SmsWalletSummaryDto) {
|
||||
if (!data.billingEnabled || data.balanceRials >= 0) {
|
||||
warnOpen.value = false;
|
||||
try {
|
||||
sessionStorage.removeItem(NEGATIVE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (sessionStorage.getItem(NEGATIVE_KEY) === '1') return;
|
||||
sessionStorage.setItem(NEGATIVE_KEY, '1');
|
||||
warnOpen.value = true;
|
||||
} catch {
|
||||
warnOpen.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => auth.user?.organizationId,
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
|
||||
defineExpose({ refresh: load });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="sms-wallet">
|
||||
<div
|
||||
class="chip"
|
||||
:class="[toneClass, (summary?.balanceRials ?? 0) < 0 ? 'is-debt' : '']"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:title="loading ? '…' : `اعتبار پیامک: ${balanceLabel} ریال`"
|
||||
aria-label="شارژ اعتبار پیامک"
|
||||
@click="chargeOpen = true"
|
||||
@keydown.enter.prevent="chargeOpen = true"
|
||||
@keydown.space.prevent="chargeOpen = true"
|
||||
>
|
||||
<span class="label">پیامک</span>
|
||||
<span class="amount">{{ balanceLabel }}</span>
|
||||
</div>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="chargeOpen" class="layer">
|
||||
<div class="backdrop" @click="closeCharge" />
|
||||
<div class="modal charge-modal" role="dialog" aria-label="شارژ پیامک">
|
||||
<header>
|
||||
<strong>شارژ اعتبار پیامک</strong>
|
||||
<button type="button" class="x" @click="closeCharge">×</button>
|
||||
</header>
|
||||
|
||||
<div v-if="chargeInfo" class="charge-body">
|
||||
<div class="instruction-box">
|
||||
<p>{{ chargeInfo.instruction }}</p>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="info-head">
|
||||
<span>شماره کارت</span>
|
||||
<button type="button" class="copy violet" @click="copyValue('شماره کارت', chargeInfo.card)">
|
||||
کپی
|
||||
</button>
|
||||
</div>
|
||||
<p class="mono" dir="ltr">{{ formatCardDisplay(chargeInfo.card) }}</p>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="info-head">
|
||||
<span>شماره شبا</span>
|
||||
<button type="button" class="copy emerald" @click="copyValue('شماره شبا', chargeInfo.iban)">
|
||||
کپی
|
||||
</button>
|
||||
</div>
|
||||
<p class="mono" dir="ltr">{{ chargeInfo.iban || '—' }}</p>
|
||||
</div>
|
||||
|
||||
<div class="info-card muted-card">
|
||||
<span class="small">به نام</span>
|
||||
<p class="holder">{{ chargeInfo.accountHolder || '—' }}</p>
|
||||
</div>
|
||||
|
||||
<p v-if="copyHint" class="copy-hint">{{ copyHint }}</p>
|
||||
</div>
|
||||
|
||||
<p v-else class="muted">اطلاعات واریز در دسترس نیست.</p>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="warnOpen" class="layer">
|
||||
<div class="backdrop" @click="warnOpen = false" />
|
||||
<div class="modal warn" role="dialog" aria-label="هشدار موجودی منفی">
|
||||
<header>
|
||||
<strong>موجودی پیامک منفی است</strong>
|
||||
<button type="button" class="x" @click="warnOpen = false">×</button>
|
||||
</header>
|
||||
<p>
|
||||
اعتبار پیامک محیط شما منفی شده
|
||||
({{ balanceLabel }} ریال). ارسال تا رسیدن به آستانه قطع یا مسدودسازی دستی ادامه دارد؛ لطفاً
|
||||
شارژ کنید.
|
||||
</p>
|
||||
<button type="button" class="ok" @click="warnOpen = false">متوجه شدم</button>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sms-wallet {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* چیپ جمعوجور؛ کلیک کل سطح، پنجرهٔ شارژ را باز میکند */
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: var(--control-h);
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0 8px;
|
||||
border: 1px solid #c3ead6;
|
||||
border-radius: 10px;
|
||||
background: #f2fbf6;
|
||||
color: #1f7a52;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chip.warning {
|
||||
border-color: #fde68a;
|
||||
background: color-mix(in srgb, #fffbeb 75%, #fff);
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
.chip.critical,
|
||||
.chip.negative {
|
||||
border-color: #fecaca;
|
||||
background: color-mix(in srgb, #fef2f2 75%, #fff);
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.chip.is-debt {
|
||||
border-color: var(--danger);
|
||||
background: var(--danger);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.chip.is-debt .label {
|
||||
color: inherit;
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: 600;
|
||||
font-size: 0.7rem;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.amount {
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.35);
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: relative;
|
||||
width: min(420px, 100%);
|
||||
max-height: min(90vh, 640px);
|
||||
overflow: auto;
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
padding: 1rem 1.1rem 1.15rem;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
box-shadow: 0 20px 50px rgba(15, 23, 42, 0.18);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.modal header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 0.35rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
}
|
||||
|
||||
.x {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: 1.3rem;
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.6;
|
||||
text-align: center;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.charge-body {
|
||||
display: grid;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.instruction-box {
|
||||
border: 1px solid #e0f2fe;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #f0f9ff, #fff);
|
||||
padding: 0.85rem 0.95rem;
|
||||
}
|
||||
|
||||
.instruction-box p {
|
||||
margin: 0;
|
||||
color: #475569;
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.info-card {
|
||||
border: 1px solid #f3f4f6;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
padding: 0.75rem 0.85rem;
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.info-card.muted-card {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.info-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.info-head > span,
|
||||
.small {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.mono {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 1rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
color: #0f172a;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.holder {
|
||||
margin: 0.15rem 0 0;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.copy {
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
padding: 0.25rem 0.55rem;
|
||||
font: inherit;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.copy.violet {
|
||||
background: #f5f3ff;
|
||||
color: #6d28d9;
|
||||
}
|
||||
|
||||
.copy.violet:hover {
|
||||
background: #ede9fe;
|
||||
}
|
||||
|
||||
.copy.emerald {
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.copy.emerald:hover {
|
||||
background: #d1fae5;
|
||||
}
|
||||
|
||||
.copy-hint {
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
font-size: 0.8rem;
|
||||
color: #0f766e;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ok {
|
||||
border: 0;
|
||||
background: #0f766e;
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
padding: 0.45rem 0.9rem;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
import { api } from '@/lib/api';
|
||||
import { activityTypeView } from '@/lib/activity-types';
|
||||
import { calendarDaysBetween, formatClockFa, formatJalaliDay, startOfLocalDay, toFaDigits } from '@/lib/jalali';
|
||||
import { Spin as ASpin } from 'ant-design-vue';
|
||||
import PipelineBoard from '@/components/pipeline/PipelineBoard.vue';
|
||||
import DealCardOverlay from '@/components/pipeline/DealCardOverlay.vue';
|
||||
import {
|
||||
@@ -380,7 +381,7 @@ async function onAddStage(name: string) {
|
||||
if (stageBusy.value) return;
|
||||
stageBusy.value = true;
|
||||
try {
|
||||
await api.post('/activities/stages', { name, kind: 'open' });
|
||||
await api.post('/activities/stages', { name, kind: 'open', boardId: props.params.boardId });
|
||||
emit('stagesChanged');
|
||||
} catch (e) {
|
||||
emit('error', apiMessage(e, 'افزودن ستون ناموفق بود.'));
|
||||
@@ -395,8 +396,21 @@ function openActivity(id: string) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kanban-wrap">
|
||||
<p v-if="initialLoading && !Object.keys(columns).length" class="muted">در حال بارگذاری ستونها…</p>
|
||||
<div
|
||||
class="kanban-wrap"
|
||||
:style="{
|
||||
flex: '1 1 auto',
|
||||
minHeight: 0,
|
||||
height: '100%',
|
||||
minWidth: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}"
|
||||
>
|
||||
<a-spin
|
||||
v-if="initialLoading && !Object.keys(columns).length"
|
||||
tip="در حال بارگذاری ستونها…"
|
||||
/>
|
||||
<PipelineBoard
|
||||
v-else
|
||||
:stages="boardStages"
|
||||
@@ -440,11 +454,10 @@ function openActivity(id: string) {
|
||||
.kanban-wrap {
|
||||
container-type: inline-size;
|
||||
container-name: pipeline;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import type {
|
||||
ActivityChecklistItem,
|
||||
ActivityFieldDef,
|
||||
@@ -14,7 +14,31 @@ import { api } from '@/lib/api';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import UserMultiSelect from '@/components/UserMultiSelect.vue';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import {
|
||||
Button as AButton,
|
||||
Checkbox as ACheckbox,
|
||||
Col as ACol,
|
||||
Flex as AFlex,
|
||||
FormItem as AFormItem,
|
||||
Input as AInput,
|
||||
InputNumber as AInputNumber,
|
||||
Row as ARow,
|
||||
Select as ASelect,
|
||||
Space as ASpace,
|
||||
Switch as ASwitch,
|
||||
Tag as ATag,
|
||||
Textarea as ATextarea,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import {
|
||||
CloseOutlined,
|
||||
DownOutlined,
|
||||
PlusOutlined,
|
||||
UpOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
|
||||
const props = defineProps<{
|
||||
fields: ActivityFieldDef[];
|
||||
@@ -42,9 +66,20 @@ function multi(key: string): string[] {
|
||||
return Array.isArray(v) && v.every((x) => typeof x === 'string') ? (v as string[]) : [];
|
||||
}
|
||||
|
||||
function toggleMulti(key: string, opt: string) {
|
||||
const list = multi(key);
|
||||
set(key, list.includes(opt) ? list.filter((x) => x !== opt) : [...list, opt]);
|
||||
function fieldSpan(type: ActivityFieldDef['type']): number {
|
||||
return ['textarea', 'checklist', 'participants', 'multiselect'].includes(type) ? 24 : 12;
|
||||
}
|
||||
|
||||
function selectOptions(f: ActivityFieldDef) {
|
||||
return (f.options ?? []).map((opt) => ({ value: opt, label: opt }));
|
||||
}
|
||||
|
||||
function onNumberUpdate(key: string, value: number | string | null) {
|
||||
if (value == null || value === '') {
|
||||
set(key, null);
|
||||
return;
|
||||
}
|
||||
set(key, Number(value));
|
||||
}
|
||||
|
||||
/* ---------- چکلیست ---------- */
|
||||
@@ -52,7 +87,9 @@ const checklistDraft = ref<Record<string, string>>({});
|
||||
|
||||
function checklist(key: string): ActivityChecklistItem[] {
|
||||
const v = model.value[key];
|
||||
return Array.isArray(v) ? (v as ActivityChecklistItem[]).filter((x) => x && typeof x === 'object') : [];
|
||||
return Array.isArray(v)
|
||||
? (v as ActivityChecklistItem[]).filter((x) => x && typeof x === 'object')
|
||||
: [];
|
||||
}
|
||||
|
||||
function addChecklistItem(key: string) {
|
||||
@@ -111,39 +148,82 @@ function addGuest(key: string) {
|
||||
|
||||
const personQuery = ref<Record<string, string>>({});
|
||||
const personResults = ref<Record<string, PersonDto[]>>({});
|
||||
const personOpenKey = ref('');
|
||||
const personSearching = ref<Record<string, boolean>>({});
|
||||
let personTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let personSeq = 0;
|
||||
|
||||
function searchPeople(key: string) {
|
||||
personOpenKey.value = key;
|
||||
function searchPeople(key: string, raw: string) {
|
||||
personQuery.value = { ...personQuery.value, [key]: raw };
|
||||
if (personTimer) clearTimeout(personTimer);
|
||||
const q = (personQuery.value[key] ?? '').trim();
|
||||
const q = raw.trim();
|
||||
if (!q) {
|
||||
personResults.value = { ...personResults.value, [key]: [] };
|
||||
personSearching.value = { ...personSearching.value, [key]: false };
|
||||
return;
|
||||
}
|
||||
personSearching.value = { ...personSearching.value, [key]: true };
|
||||
const seq = ++personSeq;
|
||||
personTimer = setTimeout(async () => {
|
||||
try {
|
||||
const { data } = await api.get<PaginatedResponse<PersonDto>>('/people', {
|
||||
params: { q, limit: 8 },
|
||||
});
|
||||
if (seq === personSeq) personResults.value = { ...personResults.value, [key]: data.items };
|
||||
if (seq === personSeq) {
|
||||
personResults.value = { ...personResults.value, [key]: data.items };
|
||||
}
|
||||
} catch {
|
||||
if (seq === personSeq) personResults.value = { ...personResults.value, [key]: [] };
|
||||
if (seq === personSeq) {
|
||||
personResults.value = { ...personResults.value, [key]: [] };
|
||||
}
|
||||
} finally {
|
||||
if (seq === personSeq) {
|
||||
personSearching.value = { ...personSearching.value, [key]: false };
|
||||
}
|
||||
}
|
||||
}, 280);
|
||||
}
|
||||
|
||||
function addPerson(key: string, p: PersonDto) {
|
||||
const personSelectOptions = computed(() => {
|
||||
const map: Record<string, Array<{ value: string; label: string; company: string }>> = {};
|
||||
for (const f of props.fields) {
|
||||
if (f.type !== 'participants') continue;
|
||||
const selectedIds = new Set(participants(f.key).people.map((p) => p.id));
|
||||
map[f.key] = (personResults.value[f.key] ?? [])
|
||||
.filter((p) => !selectedIds.has(p.id))
|
||||
.map((p) => ({
|
||||
value: p.id,
|
||||
label: p.fullName,
|
||||
company: p.company?.name ?? '',
|
||||
}));
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
function onPersonPick(key: string, value: unknown) {
|
||||
const id = value == null ? '' : String(value);
|
||||
if (!id) return;
|
||||
const hit =
|
||||
(personResults.value[key] ?? []).find((p) => p.id === id) ??
|
||||
null;
|
||||
if (!hit) return;
|
||||
const cur = participants(key);
|
||||
if (!cur.people.some((x) => x.id === p.id)) {
|
||||
patchParticipants(key, { people: [...cur.people, { id: p.id, name: p.fullName }] });
|
||||
if (!cur.people.some((x) => x.id === hit.id)) {
|
||||
patchParticipants(key, { people: [...cur.people, { id: hit.id, name: hit.fullName }] });
|
||||
}
|
||||
personQuery.value = { ...personQuery.value, [key]: '' };
|
||||
personResults.value = { ...personResults.value, [key]: [] };
|
||||
personOpenKey.value = '';
|
||||
}
|
||||
|
||||
function removePerson(key: string, id: string) {
|
||||
patchParticipants(key, {
|
||||
people: participants(key).people.filter((x) => x.id !== id),
|
||||
});
|
||||
}
|
||||
|
||||
function removeGuest(key: string, name: string) {
|
||||
patchParticipants(key, {
|
||||
guests: participants(key).guests.filter((x) => x !== name),
|
||||
});
|
||||
}
|
||||
|
||||
watch(
|
||||
@@ -153,522 +233,237 @@ watch(
|
||||
guestDraft.value = {};
|
||||
personQuery.value = {};
|
||||
personResults.value = {};
|
||||
personSearching.value = {};
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="fields-grid">
|
||||
<div
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col
|
||||
v-for="f in fields"
|
||||
:key="f.key"
|
||||
class="cf"
|
||||
:class="{ wide: ['textarea', 'checklist', 'participants', 'multiselect'].includes(f.type) }"
|
||||
:xs="24"
|
||||
:md="fieldSpan(f.type)"
|
||||
>
|
||||
<label :for="`cf-${f.key}`">
|
||||
{{ f.label }}
|
||||
<i v-if="f.required">*</i>
|
||||
</label>
|
||||
<a-form-item :required="f.required">
|
||||
<template #label>
|
||||
{{ f.label }}
|
||||
</template>
|
||||
|
||||
<input
|
||||
v-if="f.type === 'text' || f.type === 'url'"
|
||||
:id="`cf-${f.key}`"
|
||||
:type="f.type === 'url' ? 'url' : 'text'"
|
||||
:dir="f.type === 'url' ? 'ltr' : undefined"
|
||||
:value="str(f.key)"
|
||||
:placeholder="f.placeholder || ''"
|
||||
maxlength="1000"
|
||||
@input="set(f.key, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
|
||||
<textarea
|
||||
v-else-if="f.type === 'textarea'"
|
||||
:id="`cf-${f.key}`"
|
||||
:value="str(f.key)"
|
||||
:placeholder="f.placeholder || ''"
|
||||
rows="3"
|
||||
@input="set(f.key, ($event.target as HTMLTextAreaElement).value)"
|
||||
/>
|
||||
|
||||
<input
|
||||
v-else-if="f.type === 'number'"
|
||||
:id="`cf-${f.key}`"
|
||||
type="number"
|
||||
inputmode="decimal"
|
||||
dir="ltr"
|
||||
:value="str(f.key)"
|
||||
:placeholder="f.placeholder || ''"
|
||||
@input="
|
||||
set(
|
||||
f.key,
|
||||
($event.target as HTMLInputElement).value === ''
|
||||
? null
|
||||
: Number(($event.target as HTMLInputElement).value),
|
||||
)
|
||||
"
|
||||
/>
|
||||
|
||||
<JalaliDateInput
|
||||
v-else-if="f.type === 'date'"
|
||||
:id="`cf-${f.key}`"
|
||||
:model-value="str(f.key)"
|
||||
@update:model-value="(v: string) => set(f.key, v || null)"
|
||||
/>
|
||||
|
||||
<select
|
||||
v-else-if="f.type === 'select'"
|
||||
:id="`cf-${f.key}`"
|
||||
:value="str(f.key)"
|
||||
@change="set(f.key, ($event.target as HTMLSelectElement).value || null)"
|
||||
>
|
||||
<option value="">— انتخاب کنید —</option>
|
||||
<option v-for="opt in f.options ?? []" :key="opt" :value="opt">{{ opt }}</option>
|
||||
</select>
|
||||
|
||||
<div v-else-if="f.type === 'multiselect'" class="chips">
|
||||
<button
|
||||
v-for="opt in f.options ?? []"
|
||||
:key="opt"
|
||||
type="button"
|
||||
class="chip-opt"
|
||||
:class="{ on: multi(f.key).includes(opt) }"
|
||||
@click="toggleMulti(f.key, opt)"
|
||||
>
|
||||
<UiIcon v-if="multi(f.key).includes(opt)" name="check-plain" :size="12" />
|
||||
{{ opt }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label v-else-if="f.type === 'checkbox'" class="switch">
|
||||
<input
|
||||
:id="`cf-${f.key}`"
|
||||
type="checkbox"
|
||||
:checked="get<boolean>(f.key, false) === true"
|
||||
@change="set(f.key, ($event.target as HTMLInputElement).checked)"
|
||||
<a-input
|
||||
v-if="f.type === 'text' || f.type === 'url'"
|
||||
:value="str(f.key)"
|
||||
:type="f.type === 'url' ? 'url' : 'text'"
|
||||
:dir="f.type === 'url' ? 'ltr' : undefined"
|
||||
:placeholder="f.placeholder || ''"
|
||||
:maxlength="1000"
|
||||
style="width: 100%"
|
||||
@update:value="(v: string) => set(f.key, v)"
|
||||
/>
|
||||
<i />
|
||||
<span>{{ get<boolean>(f.key, false) === true ? 'بله' : 'خیر' }}</span>
|
||||
</label>
|
||||
|
||||
<div v-else-if="f.type === 'checklist'" class="checklist">
|
||||
<p v-if="checklist(f.key).length" class="progress">
|
||||
{{ toFaDigits(checklist(f.key).filter((x) => x.done).length) }} از
|
||||
{{ toFaDigits(checklist(f.key).length) }} انجام شده
|
||||
</p>
|
||||
<ul>
|
||||
<li v-for="(it, idx) in checklist(f.key)" :key="it.id" :class="{ done: it.done }">
|
||||
<input
|
||||
type="checkbox"
|
||||
<a-textarea
|
||||
v-else-if="f.type === 'textarea'"
|
||||
:value="str(f.key)"
|
||||
:placeholder="f.placeholder || ''"
|
||||
:rows="3"
|
||||
style="width: 100%"
|
||||
@update:value="(v: string) => set(f.key, v)"
|
||||
/>
|
||||
|
||||
<a-input-number
|
||||
v-else-if="f.type === 'number'"
|
||||
:value="str(f.key) === '' ? undefined : Number(str(f.key))"
|
||||
:placeholder="f.placeholder || ''"
|
||||
style="width: 100%"
|
||||
@update:value="(v: number | string | null) => onNumberUpdate(f.key, v)"
|
||||
/>
|
||||
|
||||
<JalaliDateInput
|
||||
v-else-if="f.type === 'date'"
|
||||
:model-value="str(f.key)"
|
||||
style="width: 100%"
|
||||
@update:model-value="(v: string) => set(f.key, v || null)"
|
||||
/>
|
||||
|
||||
<a-select
|
||||
v-else-if="f.type === 'select'"
|
||||
:value="str(f.key) || undefined"
|
||||
:options="selectOptions(f)"
|
||||
allow-clear
|
||||
placeholder="— انتخاب کنید —"
|
||||
style="width: 100%"
|
||||
@update:value="(v: unknown) => set(f.key, v == null || v === '' ? null : String(v))"
|
||||
/>
|
||||
|
||||
<a-select
|
||||
v-else-if="f.type === 'multiselect'"
|
||||
mode="multiple"
|
||||
:value="multi(f.key)"
|
||||
:options="selectOptions(f)"
|
||||
:placeholder="f.placeholder || 'انتخاب کنید'"
|
||||
style="width: 100%"
|
||||
@update:value="(v: unknown) => set(f.key, Array.isArray(v) ? v.map(String) : [])"
|
||||
/>
|
||||
|
||||
<a-space v-else-if="f.type === 'checkbox'" :size="8">
|
||||
<a-switch
|
||||
:checked="get<boolean>(f.key, false) === true"
|
||||
@update:checked="(v) => set(f.key, v === true)"
|
||||
/>
|
||||
<a-typography-text>
|
||||
{{ get<boolean>(f.key, false) === true ? 'بله' : 'خیر' }}
|
||||
</a-typography-text>
|
||||
</a-space>
|
||||
|
||||
<a-flex v-else-if="f.type === 'checklist'" vertical :gap="8">
|
||||
<a-typography-text v-if="checklist(f.key).length" type="success">
|
||||
{{ toFaDigits(checklist(f.key).filter((x) => x.done).length) }} از
|
||||
{{ toFaDigits(checklist(f.key).length) }} انجام شده
|
||||
</a-typography-text>
|
||||
<a-flex
|
||||
v-for="(it, idx) in checklist(f.key)"
|
||||
:key="it.id"
|
||||
align="center"
|
||||
:gap="8"
|
||||
>
|
||||
<a-checkbox
|
||||
:checked="it.done"
|
||||
aria-label="انجام شد"
|
||||
@change="updateChecklistItem(f.key, it.id, { done: ($event.target as HTMLInputElement).checked })"
|
||||
@update:checked="(v: boolean) => updateChecklistItem(f.key, it.id, { done: v })"
|
||||
/>
|
||||
<input
|
||||
class="item-text"
|
||||
<a-input
|
||||
:value="it.text"
|
||||
maxlength="300"
|
||||
@input="updateChecklistItem(f.key, it.id, { text: ($event.target as HTMLInputElement).value })"
|
||||
:maxlength="300"
|
||||
:style="{
|
||||
flex: 1,
|
||||
textDecoration: it.done ? 'line-through' : undefined,
|
||||
}"
|
||||
@update:value="(v: string) => updateChecklistItem(f.key, it.id, { text: v })"
|
||||
/>
|
||||
<button type="button" class="mini" :disabled="idx === 0" aria-label="بالا" @click="moveChecklistItem(f.key, idx, -1)">▲</button>
|
||||
<button
|
||||
type="button"
|
||||
class="mini"
|
||||
<a-button
|
||||
:disabled="idx === 0"
|
||||
aria-label="بالا"
|
||||
@click="moveChecklistItem(f.key, idx, -1)"
|
||||
>
|
||||
<template #icon><UpOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
:disabled="idx === checklist(f.key).length - 1"
|
||||
aria-label="پایین"
|
||||
@click="moveChecklistItem(f.key, idx, 1)"
|
||||
>
|
||||
▼
|
||||
</button>
|
||||
<button type="button" class="mini danger" aria-label="حذف" @click="removeChecklistItem(f.key, it.id)">
|
||||
<UiIcon name="x" :size="13" />
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="add-row">
|
||||
<input
|
||||
v-model="checklistDraft[f.key]"
|
||||
maxlength="300"
|
||||
:placeholder="f.placeholder || 'مورد جدید را بنویسید و Enter بزنید'"
|
||||
@keydown.enter.prevent="addChecklistItem(f.key)"
|
||||
/>
|
||||
<button type="button" class="add-btn" @click="addChecklistItem(f.key)">
|
||||
<UiIcon name="plus" :size="14" />
|
||||
افزودن
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="f.type === 'participants'" class="participants">
|
||||
<div class="p-block">
|
||||
<small>همکاران (فعالیت در لیست آنها هم نمایش داده میشود)</small>
|
||||
<UserMultiSelect
|
||||
:model-value="participants(f.key).userIds"
|
||||
:users="users"
|
||||
add-label="افزودن همکار"
|
||||
empty-label="همکاری انتخاب نشده"
|
||||
@update:model-value="(ids: string[]) => patchParticipants(f.key, { userIds: ids })"
|
||||
/>
|
||||
</div>
|
||||
<div class="p-block">
|
||||
<small>اشخاص / مشتریان</small>
|
||||
<div class="tags">
|
||||
<span v-for="p in participants(f.key).people" :key="p.id" class="tag">
|
||||
<UiIcon name="user" :size="12" />
|
||||
{{ p.name }}
|
||||
<button
|
||||
type="button"
|
||||
aria-label="حذف"
|
||||
@click="patchParticipants(f.key, { people: participants(f.key).people.filter((x) => x.id !== p.id) })"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="person-search">
|
||||
<input
|
||||
v-model="personQuery[f.key]"
|
||||
type="search"
|
||||
placeholder="جستجوی نام یا موبایل شخص…"
|
||||
@input="searchPeople(f.key)"
|
||||
@focus="personOpenKey = f.key"
|
||||
<template #icon><DownOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
danger
|
||||
aria-label="حذف"
|
||||
@click="removeChecklistItem(f.key, it.id)"
|
||||
>
|
||||
<template #icon><CloseOutlined /></template>
|
||||
</a-button>
|
||||
</a-flex>
|
||||
<a-space :size="8" style="width: 100%">
|
||||
<a-input
|
||||
:value="checklistDraft[f.key] ?? ''"
|
||||
:maxlength="300"
|
||||
:placeholder="f.placeholder || 'مورد جدید را بنویسید و Enter بزنید'"
|
||||
style="width: 100%"
|
||||
@update:value="(v: string) => (checklistDraft[f.key] = v)"
|
||||
@pressEnter="addChecklistItem(f.key)"
|
||||
/>
|
||||
<ul v-if="personOpenKey === f.key && (personResults[f.key]?.length ?? 0) > 0" class="results">
|
||||
<li v-for="p in personResults[f.key]" :key="p.id">
|
||||
<button type="button" @click="addPerson(f.key, p)">
|
||||
<b>{{ p.fullName }}</b>
|
||||
<small v-if="p.company?.name">{{ p.company.name }}</small>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-block">
|
||||
<small>مهمانان دیگر (نام آزاد)</small>
|
||||
<div class="tags">
|
||||
<span v-for="g in participants(f.key).guests" :key="g" class="tag guest">
|
||||
{{ g }}
|
||||
<button
|
||||
type="button"
|
||||
aria-label="حذف"
|
||||
@click="patchParticipants(f.key, { guests: participants(f.key).guests.filter((x) => x !== g) })"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="add-row">
|
||||
<input
|
||||
v-model="guestDraft[f.key]"
|
||||
maxlength="120"
|
||||
placeholder="نام مهمان و Enter"
|
||||
@keydown.enter.prevent="addGuest(f.key)"
|
||||
/>
|
||||
<button type="button" class="add-btn" @click="addGuest(f.key)">
|
||||
<UiIcon name="plus" :size="14" />
|
||||
<a-button type="dashed" @click="addChecklistItem(f.key)">
|
||||
<template #icon><PlusOutlined /></template>
|
||||
افزودن
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-button>
|
||||
</a-space>
|
||||
</a-flex>
|
||||
|
||||
<a-flex v-else-if="f.type === 'participants'" vertical :gap="16">
|
||||
<a-flex vertical :gap="4">
|
||||
<a-typography-text type="secondary">
|
||||
همکاران (فعالیت در لیست آنها هم نمایش داده میشود)
|
||||
</a-typography-text>
|
||||
<UserMultiSelect
|
||||
:model-value="participants(f.key).userIds"
|
||||
:users="users"
|
||||
add-label="افزودن همکار"
|
||||
empty-label="همکاری انتخاب نشده"
|
||||
@update:model-value="(ids: string[]) => patchParticipants(f.key, { userIds: ids })"
|
||||
/>
|
||||
</a-flex>
|
||||
|
||||
<a-flex vertical :gap="8">
|
||||
<a-typography-text type="secondary">اشخاص / مشتریان</a-typography-text>
|
||||
<a-space v-if="participants(f.key).people.length" :size="6" wrap>
|
||||
<a-tag
|
||||
v-for="p in participants(f.key).people"
|
||||
:key="p.id"
|
||||
closable
|
||||
color="cyan"
|
||||
:bordered="false"
|
||||
@close="removePerson(f.key, p.id)"
|
||||
>
|
||||
<UserOutlined />
|
||||
{{ p.name }}
|
||||
</a-tag>
|
||||
</a-space>
|
||||
<a-select
|
||||
show-search
|
||||
allow-clear
|
||||
:filter-option="false"
|
||||
:value="undefined"
|
||||
:options="personSelectOptions[f.key] ?? []"
|
||||
:not-found-content="
|
||||
personSearching[f.key]
|
||||
? 'در حال جستجو…'
|
||||
: (personQuery[f.key] || '').trim()
|
||||
? 'شخصی پیدا نشد.'
|
||||
: 'نام یا موبایل را جستجو کنید'
|
||||
"
|
||||
placeholder="جستجوی نام یا موبایل شخص…"
|
||||
style="width: 100%"
|
||||
@search="(q: string) => searchPeople(f.key, q)"
|
||||
@update:value="(v: unknown) => onPersonPick(f.key, v)"
|
||||
>
|
||||
<template #option="{ label, company }">
|
||||
<a-flex vertical :gap="0">
|
||||
<a-typography-text>{{ label }}</a-typography-text>
|
||||
<a-typography-text v-if="company" type="secondary">{{ company }}</a-typography-text>
|
||||
</a-flex>
|
||||
</template>
|
||||
</a-select>
|
||||
</a-flex>
|
||||
|
||||
<a-flex vertical :gap="8">
|
||||
<a-typography-text type="secondary">مهمانان دیگر (نام آزاد)</a-typography-text>
|
||||
<a-space v-if="participants(f.key).guests.length" :size="6" wrap>
|
||||
<a-tag
|
||||
v-for="g in participants(f.key).guests"
|
||||
:key="g"
|
||||
closable
|
||||
:bordered="false"
|
||||
@close="removeGuest(f.key, g)"
|
||||
>
|
||||
{{ g }}
|
||||
</a-tag>
|
||||
</a-space>
|
||||
<a-space :size="8" style="width: 100%">
|
||||
<a-input
|
||||
:value="guestDraft[f.key] ?? ''"
|
||||
:maxlength="120"
|
||||
placeholder="نام مهمان و Enter"
|
||||
style="width: 100%"
|
||||
@update:value="(v: string) => (guestDraft[f.key] = v)"
|
||||
@pressEnter="addGuest(f.key)"
|
||||
/>
|
||||
<a-button type="dashed" @click="addGuest(f.key)">
|
||||
<template #icon><PlusOutlined /></template>
|
||||
افزودن
|
||||
</a-button>
|
||||
</a-space>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.fields-grid {
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
}
|
||||
|
||||
.cf {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cf > label {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted, #64748b);
|
||||
font-size: var(--fs-xs, 0.78rem);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cf > label i {
|
||||
color: var(--color-danger, #dc2626);
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
.cf input:not([type='checkbox']),
|
||||
.cf select,
|
||||
.cf textarea {
|
||||
width: 100%;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
min-height: var(--control-h);
|
||||
padding: 0 0.85rem;
|
||||
font: inherit;
|
||||
background: #fff;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.cf textarea {
|
||||
min-height: 5rem;
|
||||
padding: 0.6rem 0.85rem;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.chips,
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.chip-opt {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 0.3rem 0.75rem;
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chip-opt.on {
|
||||
border-color: #5eead4;
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.switch i {
|
||||
width: 44px;
|
||||
height: 26px;
|
||||
border-radius: 999px;
|
||||
background: #e2e8f0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.switch i::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset-inline-start: 3px;
|
||||
top: 3px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
transition: 0.18s;
|
||||
}
|
||||
|
||||
.switch input:checked + i {
|
||||
background: #14b8a6;
|
||||
}
|
||||
|
||||
.switch input:checked + i::after {
|
||||
inset-inline-start: 21px;
|
||||
}
|
||||
|
||||
.checklist ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.checklist li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.checklist li input[type='checkbox'] {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
accent-color: #14b8a6;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.checklist .item-text {
|
||||
flex: 1;
|
||||
min-height: 2.2rem !important;
|
||||
}
|
||||
|
||||
.checklist li.done .item-text {
|
||||
text-decoration: line-through;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.progress {
|
||||
margin: 0;
|
||||
font-size: 0.78rem;
|
||||
color: #0f766e;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.mini {
|
||||
width: 1.9rem;
|
||||
height: 1.9rem;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 0.65rem;
|
||||
color: #64748b;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mini:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.mini.danger {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.add-row {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.add-row input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.add-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
border: 1px dashed #5eead4;
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
border-radius: var(--radius);
|
||||
padding: 0 0.8rem;
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.participants {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
border: 1px dashed #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.p-block {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.p-block > small {
|
||||
color: #94a3b8;
|
||||
font-size: 0.74rem;
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
border-radius: 999px;
|
||||
padding: 0.2rem 0.6rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tag.guest {
|
||||
background: #f1f5f9;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.tag button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #64748b;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
line-height: 1;
|
||||
padding: 0 0.1rem;
|
||||
}
|
||||
|
||||
.person-search {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.results {
|
||||
position: absolute;
|
||||
inset-inline: 0;
|
||||
top: calc(100% + 4px);
|
||||
z-index: 20;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0.3rem;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
|
||||
max-height: 14rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.results button {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
gap: 0.1rem;
|
||||
text-align: start;
|
||||
border: 0;
|
||||
background: none;
|
||||
padding: 0.45rem 0.55rem;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.results button:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.results b {
|
||||
font-size: 0.86rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.results small {
|
||||
color: #94a3b8;
|
||||
font-size: 0.74rem;
|
||||
}
|
||||
|
||||
@media (min-width: 960px) {
|
||||
.fields-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.cf.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -12,14 +12,32 @@ import {
|
||||
ACTIVITY_STAGE_COLORS,
|
||||
ACTIVITY_STAGE_KIND_LABELS,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
ArrowDownOutlined,
|
||||
ArrowUpOutlined,
|
||||
DeleteOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Button as AButton,
|
||||
Col as ACol,
|
||||
Divider as ADivider,
|
||||
Flex as AFlex,
|
||||
Input as AInput,
|
||||
Modal as AModal,
|
||||
Row as ARow,
|
||||
Select as ASelect,
|
||||
} from 'ant-design-vue';
|
||||
import { Modal } from 'ant-design-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import { PIPELINE_ACCENT } from '@/lib/pipeline-board';
|
||||
import { UiButton, UiModal } from '@/components/ui';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
stages: ActivityStageDto[];
|
||||
/** ستونهای جدید در همین گروه ساخته میشوند */
|
||||
boardId?: string;
|
||||
boardName?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -34,7 +52,7 @@ type Draft = { name: string; color: ActivityStageColor; kind: ActivityStatus };
|
||||
const drafts = ref<Record<string, Draft>>({});
|
||||
const busyId = ref('');
|
||||
const error = ref('');
|
||||
const createForm = reactive<Required<CreateActivityStageRequest>>({
|
||||
const createForm = reactive<Required<Omit<CreateActivityStageRequest, 'boardId'>>>({
|
||||
name: '',
|
||||
color: 'blue',
|
||||
kind: 'open',
|
||||
@@ -59,6 +77,19 @@ function apiMessage(e: unknown, fallback: string) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function confirmAsync(content: string, title = 'تأیید'): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
Modal.confirm({
|
||||
title,
|
||||
content,
|
||||
okText: 'ادامه',
|
||||
cancelText: 'انصراف',
|
||||
onOk: () => resolve(true),
|
||||
onCancel: () => resolve(false),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isDirty(stage: ActivityStageDto) {
|
||||
const d = drafts.value[stage.id];
|
||||
return Boolean(
|
||||
@@ -75,9 +106,9 @@ async function save(stage: ActivityStageDto) {
|
||||
}
|
||||
if (
|
||||
d.kind !== stage.kind &&
|
||||
!window.confirm(
|
||||
!(await confirmAsync(
|
||||
'با تغییر نوع ستون، فعالیتهای فعلی آن وضعیتشان را نگه میدارند و به اولین ستون هموضعیت خودشان منتقل میشوند. ادامه میدهید؟',
|
||||
)
|
||||
))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -116,23 +147,25 @@ async function move(index: number, dir: -1 | 1) {
|
||||
}
|
||||
|
||||
async function remove(stage: ActivityStageDto) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`ستون «${stage.name}» حذف شود؟ فعالیتهای آن به اولین ستون هموضعیت منتقل میشوند.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
busyId.value = stage.id;
|
||||
error.value = '';
|
||||
try {
|
||||
await api.delete(`/activities/stages/${stage.id}`);
|
||||
emit('changed');
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e, 'حذف ستون ناموفق بود.');
|
||||
} finally {
|
||||
busyId.value = '';
|
||||
}
|
||||
Modal.confirm({
|
||||
title: 'حذف ستون',
|
||||
content: `ستون «${stage.name}» حذف شود؟ فعالیتهای آن به اولین ستون هموضعیت منتقل میشوند.`,
|
||||
okText: 'حذف',
|
||||
cancelText: 'انصراف',
|
||||
okButtonProps: { danger: true },
|
||||
async onOk() {
|
||||
busyId.value = stage.id;
|
||||
error.value = '';
|
||||
try {
|
||||
await api.delete(`/activities/stages/${stage.id}`);
|
||||
emit('changed');
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e, 'حذف ستون ناموفق بود.');
|
||||
} finally {
|
||||
busyId.value = '';
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function create() {
|
||||
@@ -140,7 +173,11 @@ async function create() {
|
||||
busyId.value = 'create';
|
||||
error.value = '';
|
||||
try {
|
||||
await api.post('/activities/stages', { ...createForm, name: createForm.name.trim() });
|
||||
await api.post('/activities/stages', {
|
||||
...createForm,
|
||||
name: createForm.name.trim(),
|
||||
boardId: props.boardId,
|
||||
});
|
||||
createForm.name = '';
|
||||
emit('changed');
|
||||
} catch (e) {
|
||||
@@ -149,222 +186,163 @@ async function create() {
|
||||
busyId.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
function dotColor(stage: ActivityStageDto) {
|
||||
const color = drafts.value[stage.id]?.color ?? stage.color;
|
||||
return PIPELINE_ACCENT[color].solid;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UiModal :open="open" title="مدیریت ستونها و تبهای فعالیت" @close="emit('close')">
|
||||
<div class="manager">
|
||||
<p class="hint">
|
||||
هر ستون یک «نوع» دارد: فعالیتی که به ستون <b>انجامشده</b> کشیده شود خودکار انجامشده ثبت
|
||||
میشود و در ستون <b>لغو شده</b> لغو میشود. از هر نوع حداقل یک ستون لازم است.
|
||||
</p>
|
||||
<a-modal
|
||||
:open="open"
|
||||
:title="boardName ? `مدیریت ستونهای گروه «${boardName}»` : 'مدیریت ستونها و تبهای فعالیت'"
|
||||
:footer="null"
|
||||
@cancel="emit('close')"
|
||||
>
|
||||
<a-flex vertical gap="middle">
|
||||
<a-typography-text type="secondary">
|
||||
هر ستون یک «نوع» دارد: فعالیتی که به ستون <strong>انجامشده</strong> کشیده شود خودکار انجامشده ثبت
|
||||
میشود و در ستون <strong>لغو شده</strong> لغو میشود. از هر نوع حداقل یک ستون لازم است.
|
||||
</a-typography-text>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<a-alert v-if="error" type="error" :message="error" show-icon />
|
||||
|
||||
<div class="rows">
|
||||
<div
|
||||
<a-flex vertical gap="small">
|
||||
<a-row
|
||||
v-for="(stage, index) in stages"
|
||||
:key="stage.id"
|
||||
class="row"
|
||||
:style="{ '--dot': PIPELINE_ACCENT[drafts[stage.id]?.color ?? stage.color].solid }"
|
||||
:gutter="[8, 8]"
|
||||
align="middle"
|
||||
>
|
||||
<span class="dot" aria-hidden="true" />
|
||||
<input
|
||||
v-if="drafts[stage.id]"
|
||||
v-model="drafts[stage.id]!.name"
|
||||
class="name"
|
||||
maxlength="80"
|
||||
aria-label="نام ستون"
|
||||
@keydown.enter.prevent="save(stage)"
|
||||
/>
|
||||
<select v-if="drafts[stage.id]" v-model="drafts[stage.id]!.kind" aria-label="نوع ستون">
|
||||
<option v-for="k in KINDS" :key="k" :value="k">{{ ACTIVITY_STAGE_KIND_LABELS[k] }}</option>
|
||||
</select>
|
||||
<select v-if="drafts[stage.id]" v-model="drafts[stage.id]!.color" aria-label="رنگ ستون">
|
||||
<option v-for="c in ACTIVITY_STAGE_COLORS" :key="c" :value="c">
|
||||
{{ ACTIVITY_STAGE_COLOR_LABELS[c] }}
|
||||
</option>
|
||||
</select>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="icon"
|
||||
:disabled="index === 0 || Boolean(busyId)"
|
||||
title="انتقال به قبل"
|
||||
aria-label="انتقال به قبل"
|
||||
@click="move(index, -1)"
|
||||
<a-col flex="none">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
:style="{
|
||||
display: 'inline-block',
|
||||
width: '0.65rem',
|
||||
height: '0.65rem',
|
||||
borderRadius: '999px',
|
||||
background: dotColor(stage),
|
||||
}"
|
||||
/>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="8">
|
||||
<a-input
|
||||
v-if="drafts[stage.id]"
|
||||
v-model:value="drafts[stage.id]!.name"
|
||||
:maxlength="80"
|
||||
aria-label="نام ستون"
|
||||
@keydown.enter.prevent="save(stage)"
|
||||
/>
|
||||
</a-col>
|
||||
<a-col :xs="12" :sm="6">
|
||||
<a-select
|
||||
v-if="drafts[stage.id]"
|
||||
v-model:value="drafts[stage.id]!.kind"
|
||||
aria-label="نوع ستون"
|
||||
style="width: 100%"
|
||||
>
|
||||
▲
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="icon"
|
||||
:disabled="index === stages.length - 1 || Boolean(busyId)"
|
||||
title="انتقال به بعد"
|
||||
aria-label="انتقال به بعد"
|
||||
@click="move(index, 1)"
|
||||
<a-select-option v-for="k in KINDS" :key="k" :value="k">
|
||||
{{ ACTIVITY_STAGE_KIND_LABELS[k] }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-col>
|
||||
<a-col :xs="12" :sm="5">
|
||||
<a-select
|
||||
v-if="drafts[stage.id]"
|
||||
v-model:value="drafts[stage.id]!.color"
|
||||
aria-label="رنگ ستون"
|
||||
style="width: 100%"
|
||||
>
|
||||
▼
|
||||
</button>
|
||||
<UiButton
|
||||
size="sm"
|
||||
type="button"
|
||||
:disabled="!isDirty(stage) || Boolean(busyId)"
|
||||
:loading="busyId === stage.id"
|
||||
@click="save(stage)"
|
||||
>
|
||||
ذخیره
|
||||
</UiButton>
|
||||
<button
|
||||
type="button"
|
||||
class="icon danger"
|
||||
:disabled="Boolean(busyId)"
|
||||
title="حذف ستون"
|
||||
aria-label="حذف ستون"
|
||||
@click="remove(stage)"
|
||||
>
|
||||
<UiIcon name="trash" :size="15" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<a-select-option v-for="c in ACTIVITY_STAGE_COLORS" :key="c" :value="c">
|
||||
{{ ACTIVITY_STAGE_COLOR_LABELS[c] }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="5">
|
||||
<a-flex align="center" gap="small" wrap="wrap" justify="flex-end">
|
||||
<a-button
|
||||
type="text"
|
||||
:disabled="index === 0 || Boolean(busyId)"
|
||||
title="انتقال به قبل"
|
||||
aria-label="انتقال به قبل"
|
||||
@click="move(index, -1)"
|
||||
>
|
||||
<template #icon><ArrowUpOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
type="text"
|
||||
:disabled="index === stages.length - 1 || Boolean(busyId)"
|
||||
title="انتقال به بعد"
|
||||
aria-label="انتقال به بعد"
|
||||
@click="move(index, 1)"
|
||||
>
|
||||
<template #icon><ArrowDownOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
:disabled="!isDirty(stage) || Boolean(busyId)"
|
||||
:loading="busyId === stage.id"
|
||||
@click="save(stage)"
|
||||
>
|
||||
ذخیره
|
||||
</a-button>
|
||||
<a-button
|
||||
type="text"
|
||||
danger
|
||||
:disabled="Boolean(busyId)"
|
||||
title="حذف ستون"
|
||||
aria-label="حذف ستون"
|
||||
@click="remove(stage)"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
</a-flex>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-flex>
|
||||
|
||||
<form class="create" @submit.prevent="create">
|
||||
<strong>ستون جدید</strong>
|
||||
<div class="create-fields">
|
||||
<input v-model="createForm.name" maxlength="80" placeholder="مثلاً: منتظر پاسخ مشتری" />
|
||||
<select v-model="createForm.kind" aria-label="نوع ستون جدید">
|
||||
<option v-for="k in KINDS" :key="k" :value="k">{{ ACTIVITY_STAGE_KIND_LABELS[k] }}</option>
|
||||
</select>
|
||||
<select v-model="createForm.color" aria-label="رنگ ستون جدید">
|
||||
<option v-for="c in ACTIVITY_STAGE_COLORS" :key="c" :value="c">
|
||||
{{ ACTIVITY_STAGE_COLOR_LABELS[c] }}
|
||||
</option>
|
||||
</select>
|
||||
<UiButton
|
||||
variant="primary"
|
||||
type="submit"
|
||||
:disabled="!createForm.name.trim() || Boolean(busyId)"
|
||||
:loading="busyId === 'create'"
|
||||
>
|
||||
افزودن
|
||||
</UiButton>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</UiModal>
|
||||
<a-divider />
|
||||
|
||||
<a-flex vertical gap="small" @submit.prevent="create">
|
||||
<a-typography-text strong>ستون جدید</a-typography-text>
|
||||
<a-row :gutter="[8, 8]" align="middle">
|
||||
<a-col :xs="24" :sm="10">
|
||||
<a-input
|
||||
v-model:value="createForm.name"
|
||||
:maxlength="80"
|
||||
placeholder="مثلاً: منتظر پاسخ مشتری"
|
||||
/>
|
||||
</a-col>
|
||||
<a-col :xs="12" :sm="5">
|
||||
<a-select v-model:value="createForm.kind" aria-label="نوع ستون جدید" style="width: 100%">
|
||||
<a-select-option v-for="k in KINDS" :key="k" :value="k">
|
||||
{{ ACTIVITY_STAGE_KIND_LABELS[k] }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-col>
|
||||
<a-col :xs="12" :sm="5">
|
||||
<a-select v-model:value="createForm.color" aria-label="رنگ ستون جدید" style="width: 100%">
|
||||
<a-select-option v-for="c in ACTIVITY_STAGE_COLORS" :key="c" :value="c">
|
||||
{{ ACTIVITY_STAGE_COLOR_LABELS[c] }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="4">
|
||||
<a-button
|
||||
type="primary"
|
||||
html-type="button"
|
||||
block
|
||||
:disabled="!createForm.name.trim() || Boolean(busyId)"
|
||||
:loading="busyId === 'create'"
|
||||
@click="create"
|
||||
>
|
||||
افزودن
|
||||
</a-button>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</a-modal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.manager {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 0.84rem;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.rows {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 0.7rem minmax(0, 1fr) 9rem 6.5rem auto;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
padding: 0.5rem 0.6rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 0.65rem;
|
||||
height: 0.65rem;
|
||||
border-radius: 999px;
|
||||
background: var(--dot);
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
min-height: var(--control-h);
|
||||
padding: 0 0.6rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
font: inherit;
|
||||
font-size: 0.86rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.icon {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
color: #475569;
|
||||
font-size: 0.7rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.icon.danger {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.create {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
padding-top: 0.8rem;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.create-fields {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 9rem 6.5rem auto;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.row {
|
||||
grid-template-columns: 0.7rem minmax(0, 1fr) auto;
|
||||
}
|
||||
|
||||
.row select {
|
||||
grid-column: 2 / -1;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
grid-column: 1 / -1;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.create-fields {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { computed, ref, type Component } from 'vue';
|
||||
import AutomationNode from '@/components/automations/AutomationNode.vue';
|
||||
import {
|
||||
AUTOMATION_ACTION_LABELS,
|
||||
@@ -22,6 +21,21 @@ import {
|
||||
type TeamDto,
|
||||
} from '@mento/shared';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import { Button as AButton, Divider as ADivider, Space as ASpace, Tooltip as ATooltip } from 'ant-design-vue';
|
||||
import {
|
||||
BellOutlined,
|
||||
DeleteOutlined,
|
||||
DragOutlined,
|
||||
ExpandOutlined,
|
||||
FilterOutlined,
|
||||
FlagOutlined,
|
||||
GiftOutlined,
|
||||
PlusOutlined,
|
||||
SelectOutlined,
|
||||
ThunderboltOutlined,
|
||||
ZoomInOutlined,
|
||||
ZoomOutOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
|
||||
export type AutomationAddPayload =
|
||||
| { kind: 'action'; action: AutomationAction }
|
||||
@@ -60,6 +74,101 @@ const actionCount = computed(
|
||||
() => props.steps.filter((s) => !isAutomationCondition(s)).length,
|
||||
);
|
||||
|
||||
type CanvasTool = 'select' | 'hand';
|
||||
const Z_MIN = 0.4;
|
||||
const Z_MAX = 2;
|
||||
const Z_STEP = 0.1;
|
||||
|
||||
const tool = ref<CanvasTool>('select');
|
||||
const zoom = ref(1);
|
||||
const pan = ref({ x: 0, y: 0 });
|
||||
const viewportRef = ref<HTMLElement | null>(null);
|
||||
const panning = ref(false);
|
||||
const panOrigin = ref({ x: 0, y: 0, panX: 0, panY: 0 });
|
||||
const didPan = ref(false);
|
||||
|
||||
const zoomLabel = computed(() => `${toFaDigits(Math.round(zoom.value * 100))}٪`);
|
||||
const worldStyle = computed(() => ({
|
||||
transform: `translate(${pan.value.x}px, ${pan.value.y}px) scale(${zoom.value})`,
|
||||
}));
|
||||
|
||||
function clampZoom(v: number) {
|
||||
return Math.min(Z_MAX, Math.max(Z_MIN, Math.round(v * 100) / 100));
|
||||
}
|
||||
|
||||
function setTool(next: CanvasTool) {
|
||||
tool.value = next;
|
||||
addAt.value = null;
|
||||
}
|
||||
|
||||
function zoomBy(delta: number) {
|
||||
zoom.value = clampZoom(zoom.value + delta);
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
zoom.value = 1;
|
||||
pan.value = { x: 0, y: 0 };
|
||||
}
|
||||
|
||||
function onWheel(e: WheelEvent) {
|
||||
const el = viewportRef.value;
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const mx = e.clientX - rect.left;
|
||||
const my = e.clientY - rect.top;
|
||||
const prev = zoom.value;
|
||||
const next = clampZoom(prev * (e.deltaY > 0 ? 0.9 : 1.1));
|
||||
if (next === prev) return;
|
||||
const wx = (mx - pan.value.x) / prev;
|
||||
const wy = (my - pan.value.y) / prev;
|
||||
pan.value = { x: mx - wx * next, y: my - wy * next };
|
||||
zoom.value = next;
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
const hand = tool.value === 'hand' || e.button === 1 || e.altKey;
|
||||
if (!hand || e.button === 2) return;
|
||||
e.preventDefault();
|
||||
panning.value = true;
|
||||
didPan.value = false;
|
||||
panOrigin.value = {
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
panX: pan.value.x,
|
||||
panY: pan.value.y,
|
||||
};
|
||||
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!panning.value) return;
|
||||
const dx = e.clientX - panOrigin.value.x;
|
||||
const dy = e.clientY - panOrigin.value.y;
|
||||
if (Math.abs(dx) + Math.abs(dy) > 3) didPan.value = true;
|
||||
pan.value = {
|
||||
x: panOrigin.value.panX + dx,
|
||||
y: panOrigin.value.panY + dy,
|
||||
};
|
||||
}
|
||||
|
||||
function onPointerUp(e: PointerEvent) {
|
||||
if (!panning.value) return;
|
||||
panning.value = false;
|
||||
try {
|
||||
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function onViewportClick() {
|
||||
if (didPan.value) {
|
||||
didPan.value = false;
|
||||
return;
|
||||
}
|
||||
addAt.value = null;
|
||||
}
|
||||
|
||||
const layout = computed((): { main: LaneItem[]; branches: BranchLane[] } => {
|
||||
const steps = props.steps;
|
||||
const { prefixEnd, branches } = splitAutomationBranches(steps);
|
||||
@@ -151,10 +260,10 @@ function assignHint(step: AutomationStep) {
|
||||
return 'مسئول پرونده';
|
||||
}
|
||||
|
||||
function actionIcon(action: AutomationAction) {
|
||||
if (action === 'create_notification') return 'bell';
|
||||
if (action === 'add_loyalty_points') return 'gift';
|
||||
return 'flag';
|
||||
function actionIcon(action: AutomationAction): Component {
|
||||
if (action === 'create_notification') return BellOutlined;
|
||||
if (action === 'add_loyalty_points') return GiftOutlined;
|
||||
return FlagOutlined;
|
||||
}
|
||||
|
||||
function stepTitle(step: AutomationStep) {
|
||||
@@ -208,13 +317,20 @@ function stepHint(step: AutomationStep) {
|
||||
}
|
||||
|
||||
function openAdd(item: { key: string; index: number; allow: AddAllow }) {
|
||||
if (!canAdd.value) return;
|
||||
if (!canAdd.value || tool.value === 'hand') return;
|
||||
addAt.value =
|
||||
addAt.value?.key === item.key
|
||||
? null
|
||||
: { key: item.key, index: item.index, allow: item.allow };
|
||||
}
|
||||
|
||||
function actionShort(action: AutomationAction) {
|
||||
if (action === 'create_activity') return 'فعالیت';
|
||||
if (action === 'create_notification') return 'اعلان / پیامک';
|
||||
if (action === 'add_loyalty_points') return 'امتیاز باشگاه';
|
||||
return AUTOMATION_ACTION_LABELS[action];
|
||||
}
|
||||
|
||||
function pickAction(action: AutomationAction) {
|
||||
if (!addAt.value) return;
|
||||
emit('add', { kind: 'action', action }, addAt.value.index);
|
||||
@@ -234,7 +350,19 @@ function removeBranch(lane: BranchLane) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="canvas" @click.self="addAt = null">
|
||||
<div class="canvas-shell">
|
||||
<div
|
||||
ref="viewportRef"
|
||||
class="canvas"
|
||||
:class="{ hand: tool === 'hand', panning }"
|
||||
@wheel.prevent="onWheel"
|
||||
@pointerdown="onPointerDown"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointercancel="onPointerUp"
|
||||
@click.self="onViewportClick"
|
||||
>
|
||||
<div class="world" :style="worldStyle" :class="{ locked: tool === 'hand' }">
|
||||
<div class="flow">
|
||||
<button
|
||||
class="node trigger"
|
||||
@@ -243,7 +371,7 @@ function removeBranch(lane: BranchLane) {
|
||||
@click="emit('select', 'trigger')"
|
||||
>
|
||||
<span class="icon">
|
||||
<UiIcon name="sparkle" :size="18" />
|
||||
<ThunderboltOutlined />
|
||||
</span>
|
||||
<span class="copy">
|
||||
<span class="kind">اگر</span>
|
||||
@@ -265,8 +393,44 @@ function removeBranch(lane: BranchLane) {
|
||||
title="افزودن گره"
|
||||
@click.stop="openAdd(item)"
|
||||
>
|
||||
<UiIcon name="plus" :size="item.end ? 16 : 14" />
|
||||
<PlusOutlined :style="{ fontSize: item.end ? '16px' : '14px' }" />
|
||||
</button>
|
||||
<div
|
||||
v-if="addAt?.key === item.key"
|
||||
class="picker"
|
||||
@click.stop
|
||||
@pointerdown.stop
|
||||
>
|
||||
<div class="picker-head">افزودن گره</div>
|
||||
<button
|
||||
v-if="addAt.allow !== 'action'"
|
||||
type="button"
|
||||
class="pick condition"
|
||||
@click="pickCondition"
|
||||
>
|
||||
<span class="pick-ico"><FilterOutlined /></span>
|
||||
<span class="pick-copy">
|
||||
<strong>شرط</strong>
|
||||
<small>اگر … آنگاه</small>
|
||||
</span>
|
||||
</button>
|
||||
<template v-if="addAt.allow !== 'condition'">
|
||||
<button
|
||||
v-for="action in AUTOMATION_ACTIONS"
|
||||
:key="action"
|
||||
type="button"
|
||||
class="pick"
|
||||
:class="action"
|
||||
@click="pickAction(action)"
|
||||
>
|
||||
<span class="pick-ico"><component :is="actionIcon(action)" /></span>
|
||||
<span class="pick-copy">
|
||||
<strong>{{ actionShort(action) }}</strong>
|
||||
<small>{{ AUTOMATION_ACTION_LABELS[action] }}</small>
|
||||
</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<AutomationNode
|
||||
v-else
|
||||
@@ -292,7 +456,7 @@ function removeBranch(lane: BranchLane) {
|
||||
title="حذف این شاخه"
|
||||
@click.stop="removeBranch(lane)"
|
||||
>
|
||||
<UiIcon name="trash" :size="12" />
|
||||
<DeleteOutlined :style="{ fontSize: '12px' }" />
|
||||
</button>
|
||||
</div>
|
||||
<template v-for="item in lane.items" :key="item.key">
|
||||
@@ -308,8 +472,44 @@ function removeBranch(lane: BranchLane) {
|
||||
:title="item.allow === 'condition' ? 'افزودن شرط («و»)' : 'افزودن گره'"
|
||||
@click.stop="openAdd(item)"
|
||||
>
|
||||
<UiIcon name="plus" :size="14" />
|
||||
<PlusOutlined :style="{ fontSize: '14px' }" />
|
||||
</button>
|
||||
<div
|
||||
v-if="addAt?.key === item.key"
|
||||
class="picker"
|
||||
@click.stop
|
||||
@pointerdown.stop
|
||||
>
|
||||
<div class="picker-head">افزودن گره</div>
|
||||
<button
|
||||
v-if="addAt.allow !== 'action'"
|
||||
type="button"
|
||||
class="pick condition"
|
||||
@click="pickCondition"
|
||||
>
|
||||
<span class="pick-ico"><FilterOutlined /></span>
|
||||
<span class="pick-copy">
|
||||
<strong>شرط</strong>
|
||||
<small>اگر … آنگاه</small>
|
||||
</span>
|
||||
</button>
|
||||
<template v-if="addAt.allow !== 'condition'">
|
||||
<button
|
||||
v-for="action in AUTOMATION_ACTIONS"
|
||||
:key="action"
|
||||
type="button"
|
||||
class="pick"
|
||||
:class="action"
|
||||
@click="pickAction(action)"
|
||||
>
|
||||
<span class="pick-ico"><component :is="actionIcon(action)" /></span>
|
||||
<span class="pick-copy">
|
||||
<strong>{{ actionShort(action) }}</strong>
|
||||
<small>{{ AUTOMATION_ACTION_LABELS[action] }}</small>
|
||||
</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<AutomationNode
|
||||
v-else
|
||||
@@ -330,65 +530,133 @@ function removeBranch(lane: BranchLane) {
|
||||
:title="canAddBranch ? '' : 'ابتدا برای شاخهٔ آخر یک عمل بگذارید'"
|
||||
@click.stop="emit('addBranch')"
|
||||
>
|
||||
<UiIcon name="plus" :size="14" />
|
||||
<PlusOutlined :style="{ fontSize: '14px' }" />
|
||||
شاخهٔ جدید
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="addAt" class="picker" @click.stop>
|
||||
<p>
|
||||
{{
|
||||
addAt.allow === 'condition'
|
||||
? 'شرط جدید با «و» به شرطهای این شاخه اضافه میشود'
|
||||
: 'گره بعدی را انتخاب کنید'
|
||||
}}
|
||||
</p>
|
||||
<div class="picks">
|
||||
<button
|
||||
v-if="addAt.allow !== 'action'"
|
||||
type="button"
|
||||
class="condition"
|
||||
@click="pickCondition"
|
||||
>
|
||||
<UiIcon name="filter" :size="16" />
|
||||
شرط
|
||||
</button>
|
||||
<template v-if="addAt.allow !== 'condition'">
|
||||
<button
|
||||
v-for="action in AUTOMATION_ACTIONS"
|
||||
:key="action"
|
||||
type="button"
|
||||
:class="action"
|
||||
@click="pickAction(action)"
|
||||
>
|
||||
<UiIcon :name="actionIcon(action)" :size="16" />
|
||||
{{ AUTOMATION_ACTION_LABELS[action] }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
<button class="cancel" type="button" @click="addAt = null">انصراف</button>
|
||||
</div>
|
||||
|
||||
<p v-if="!canAdd" class="cap">
|
||||
حداکثر {{ toFaDigits(MAX_AUTOMATION_STEPS) }} گره در یک قانون
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="island" @pointerdown.stop @click.stop>
|
||||
<a-space :size="4">
|
||||
<a-tooltip title="انتخاب">
|
||||
<a-button
|
||||
type="text"
|
||||
:class="{ on: tool === 'select' }"
|
||||
@click="setTool('select')"
|
||||
>
|
||||
<template #icon><SelectOutlined /></template>
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
<a-tooltip title="جابهجایی (دست)">
|
||||
<a-button
|
||||
type="text"
|
||||
:class="{ on: tool === 'hand' }"
|
||||
@click="setTool('hand')"
|
||||
>
|
||||
<template #icon><DragOutlined /></template>
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
<a-divider type="vertical" :style="{ height: '20px', margin: 0 }" />
|
||||
<a-tooltip title="کوچکنمایی">
|
||||
<a-button type="text" :disabled="zoom <= Z_MIN" @click="zoomBy(-Z_STEP)">
|
||||
<template #icon><ZoomOutOutlined /></template>
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
<a-button type="text" class="zoom-label" @click="resetView">
|
||||
{{ zoomLabel }}
|
||||
</a-button>
|
||||
<a-tooltip title="بزرگنمایی">
|
||||
<a-button type="text" :disabled="zoom >= Z_MAX" @click="zoomBy(Z_STEP)">
|
||||
<template #icon><ZoomInOutlined /></template>
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
<a-tooltip title="بازنشانی نما">
|
||||
<a-button type="text" @click="resetView">
|
||||
<template #icon><ExpandOutlined /></template>
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
</a-space>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.canvas-shell {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 14rem;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 22rem;
|
||||
border-radius: var(--radius);
|
||||
overflow: auto;
|
||||
overflow: hidden;
|
||||
background-color: #f3f6f5;
|
||||
background-image: radial-gradient(#c9d4cf 1.1px, transparent 1.2px);
|
||||
background-size: 16px 16px;
|
||||
padding: 1.6rem 1.1rem 1.25rem;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.canvas.hand {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.canvas.hand.panning {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.world {
|
||||
transform-origin: 0 0;
|
||||
width: max-content;
|
||||
min-height: 100%;
|
||||
padding: 1.1rem 1rem 4rem;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.world.locked {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.island {
|
||||
position: absolute;
|
||||
z-index: 6;
|
||||
bottom: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
border: 1px solid #d5ddd8;
|
||||
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.12);
|
||||
}
|
||||
|
||||
.island :deep(.ant-btn.on) {
|
||||
color: #0f766e;
|
||||
background: #ecfdf8;
|
||||
}
|
||||
|
||||
.island :deep(.zoom-label) {
|
||||
min-width: 3.2rem;
|
||||
padding-inline: 4px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.flow {
|
||||
@@ -396,7 +664,7 @@ function removeBranch(lane: BranchLane) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
min-width: max-content;
|
||||
min-height: 16rem;
|
||||
min-height: calc(100% - 2rem);
|
||||
}
|
||||
|
||||
.node.trigger {
|
||||
@@ -433,6 +701,7 @@ function removeBranch(lane: BranchLane) {
|
||||
flex-shrink: 0;
|
||||
color: #c2410c;
|
||||
background: #ffedd5;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.copy {
|
||||
@@ -535,7 +804,7 @@ strong {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-block: 1.3rem;
|
||||
padding-block: 0.7rem;
|
||||
}
|
||||
|
||||
.branch::before {
|
||||
@@ -608,66 +877,92 @@ strong {
|
||||
}
|
||||
|
||||
.picker {
|
||||
margin-top: 1rem;
|
||||
position: absolute;
|
||||
top: calc(100% + 10px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 30;
|
||||
width: 220px;
|
||||
padding: 6px;
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
background: #fff;
|
||||
border: 1px solid #d5ddd8;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.85rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.16);
|
||||
}
|
||||
|
||||
.picker-head {
|
||||
padding: 6px 8px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.pick {
|
||||
display: grid;
|
||||
gap: 0.65rem;
|
||||
max-width: 40rem;
|
||||
box-shadow: 0 16px 32px rgba(15, 23, 42, 0.08);
|
||||
}
|
||||
|
||||
.picker p {
|
||||
margin: 0;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.picks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.picks button {
|
||||
display: inline-flex;
|
||||
grid-template-columns: 32px 1fr;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 0.45rem 0.75rem;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
font-size: 0.8rem;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
padding: 6px 8px;
|
||||
text-align: start;
|
||||
cursor: pointer;
|
||||
color: #0f172a;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.picks .create_activity {
|
||||
.pick:hover {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
|
||||
.pick-ico {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 15px;
|
||||
background: #ecfdf8;
|
||||
color: #0f766e;
|
||||
}
|
||||
.picks .create_notification {
|
||||
color: #1d4ed8;
|
||||
}
|
||||
.picks .add_loyalty_points {
|
||||
color: #7c3aed;
|
||||
}
|
||||
.picks .condition {
|
||||
|
||||
.pick.condition .pick-ico {
|
||||
background: #fff7ed;
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
.cancel {
|
||||
justify-self: start;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: #64748b;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
.pick.create_notification .pick-ico {
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.pick.add_loyalty_points .pick-ico {
|
||||
background: #f5f3ff;
|
||||
color: #7c3aed;
|
||||
}
|
||||
|
||||
.pick-copy {
|
||||
display: grid;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pick-copy strong {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.pick-copy small {
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cap {
|
||||
@@ -680,7 +975,10 @@ strong {
|
||||
@media (max-width: 700px) {
|
||||
.canvas {
|
||||
min-height: 0;
|
||||
padding: 1rem 0.75rem;
|
||||
}
|
||||
|
||||
.world {
|
||||
padding: 1rem 0.75rem 4rem;
|
||||
}
|
||||
|
||||
.flow,
|
||||
@@ -749,7 +1047,7 @@ strong {
|
||||
}
|
||||
|
||||
.picker {
|
||||
max-width: none;
|
||||
width: min(220px, 70vw);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -31,6 +31,24 @@ import {
|
||||
formConditionValues,
|
||||
isAutomationCondition,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Checkbox as ACheckbox,
|
||||
CheckboxGroup as ACheckboxGroup,
|
||||
Flex as AFlex,
|
||||
Form as AForm,
|
||||
FormItem as AFormItem,
|
||||
Input as AInput,
|
||||
InputNumber as AInputNumber,
|
||||
RadioGroup as ARadioGroup,
|
||||
Select as ASelect,
|
||||
Textarea as ATextarea,
|
||||
Typography,
|
||||
theme,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const { token } = theme.useToken();
|
||||
|
||||
const props = defineProps<{
|
||||
selected: 'trigger' | string;
|
||||
@@ -124,6 +142,87 @@ function toggleUser(step: AutomationStep, id: string, on: boolean) {
|
||||
step.assigneeUserIds = [...cur];
|
||||
}
|
||||
|
||||
function onUserCheck(step: AutomationStep, id: string, e: { target: { checked: boolean } }) {
|
||||
toggleUser(step, id, e.target.checked);
|
||||
}
|
||||
|
||||
function onConditionFieldChange(v: unknown) {
|
||||
if (typeof v === 'string' && selectedStep.value) {
|
||||
setConditionField(selectedStep.value, v as AutomationConditionField);
|
||||
}
|
||||
}
|
||||
|
||||
function onConditionKeyChange(v: unknown) {
|
||||
if (typeof v === 'string' && selectedStep.value) setConditionKey(selectedStep.value, v);
|
||||
}
|
||||
|
||||
function onActionChange(v: unknown) {
|
||||
if (typeof v === 'string' && selectedStep.value) {
|
||||
setAction(selectedStep.value, v as AutomationAction);
|
||||
}
|
||||
}
|
||||
|
||||
function onDueUnitChange(v: unknown) {
|
||||
if (!selectedStep.value || typeof v !== 'string') return;
|
||||
setDue(selectedStep.value, v as DueUnit, dueAmountOf(selectedStep.value) || 1);
|
||||
}
|
||||
|
||||
function onDueAmountChange(v: string | number | null) {
|
||||
if (!selectedStep.value) return;
|
||||
setDue(selectedStep.value, dueUnitOf(selectedStep.value), Number(v ?? 1));
|
||||
}
|
||||
|
||||
function onFormOptionValuesChange(vals: Array<string | number | boolean>) {
|
||||
if (!selectedStep.value) return;
|
||||
const next = vals.map(String);
|
||||
const order = conditionFormField.value?.options ?? [];
|
||||
next.sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
||||
selectedStep.value.conditionValues = next;
|
||||
selectedStep.value.conditionValue = next[0] ?? '';
|
||||
}
|
||||
|
||||
const dealAmountValue = computed({
|
||||
get: () =>
|
||||
typeof selectedStep.value?.conditionValue === 'number'
|
||||
? selectedStep.value.conditionValue
|
||||
: Number(selectedStep.value?.conditionValue ?? 0),
|
||||
set: (v: number | null) => {
|
||||
if (selectedStep.value) selectedStep.value.conditionValue = Number(v ?? 0);
|
||||
},
|
||||
});
|
||||
|
||||
const formTextValue = computed({
|
||||
get: () => String(selectedStep.value?.conditionValue ?? ''),
|
||||
set: (v: string) => {
|
||||
if (selectedStep.value) selectedStep.value.conditionValue = v;
|
||||
},
|
||||
});
|
||||
|
||||
function nullableId(value: string | null | undefined) {
|
||||
return value ?? '';
|
||||
}
|
||||
|
||||
function setNullableId(
|
||||
key: 'activityTypeDefId' | 'assigneeId' | 'assigneeTeamId' | 'notifyUserId',
|
||||
v: unknown,
|
||||
) {
|
||||
if (!selectedStep.value) return;
|
||||
selectedStep.value[key] = typeof v === 'string' && v ? v : null;
|
||||
}
|
||||
|
||||
function onActivityTypeDefChange(v: unknown) {
|
||||
setNullableId('activityTypeDefId', v);
|
||||
}
|
||||
function onAssigneeIdChange(v: unknown) {
|
||||
setNullableId('assigneeId', v);
|
||||
}
|
||||
function onAssigneeTeamIdChange(v: unknown) {
|
||||
setNullableId('assigneeTeamId', v);
|
||||
}
|
||||
function onNotifyUserIdChange(v: unknown) {
|
||||
setNullableId('notifyUserId', v);
|
||||
}
|
||||
|
||||
function setConditionKey(step: AutomationStep, key: string) {
|
||||
step.conditionKey = key || null;
|
||||
const field = formFields.value.find((f) => f.key === key);
|
||||
@@ -131,15 +230,6 @@ function setConditionKey(step: AutomationStep, key: string) {
|
||||
step.conditionValues = step.conditionValue ? [step.conditionValue] : [];
|
||||
}
|
||||
|
||||
function toggleConditionValue(step: AutomationStep, option: string, on: boolean) {
|
||||
const cur = formConditionValues(step).filter((v) => v !== option);
|
||||
if (on) cur.push(option);
|
||||
const order = conditionFormField.value?.options ?? [];
|
||||
cur.sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
||||
step.conditionValues = cur;
|
||||
step.conditionValue = cur[0] ?? '';
|
||||
}
|
||||
|
||||
function multiValueHint(op: AutomationConditionOp | undefined) {
|
||||
if (op === 'contains_any') return 'کافی است حداقل یکی از این گزینهها انتخاب شده باشد.';
|
||||
if (op === 'not_contains') return 'هیچکدام از این گزینهها نباید انتخاب شده باشد.';
|
||||
@@ -162,6 +252,94 @@ const ticketPriorities: Array<{ value: TicketPriority; label: string }> = [
|
||||
{ value: 'urgent', label: 'فوری' },
|
||||
];
|
||||
|
||||
const triggerOptions = AUTOMATION_TRIGGER_GROUPS.map((group) => ({
|
||||
label: group.label,
|
||||
options: group.items.map((t) => ({
|
||||
value: t,
|
||||
label: AUTOMATION_TRIGGER_LABELS[t],
|
||||
})),
|
||||
}));
|
||||
|
||||
const formOptions = computed(() => [
|
||||
{ value: '', label: 'همه فرمها' },
|
||||
...props.forms.map((f) => ({ value: f.id, label: f.name })),
|
||||
]);
|
||||
|
||||
const sourceIdSelect = computed({
|
||||
get: () => sourceId.value ?? '',
|
||||
set: (v: string) => {
|
||||
sourceId.value = v || null;
|
||||
},
|
||||
});
|
||||
|
||||
const chainModeOptions = [
|
||||
{ value: 'branches' as const, label: AUTOMATION_CHAIN_MODE_LABELS.branches },
|
||||
{ value: 'stop' as const, label: AUTOMATION_CHAIN_MODE_LABELS.stop },
|
||||
];
|
||||
|
||||
const conditionFieldOptions = computed(() =>
|
||||
conditionFields.value.map((f) => ({
|
||||
value: f,
|
||||
label: AUTOMATION_CONDITION_FIELD_LABELS[f],
|
||||
})),
|
||||
);
|
||||
|
||||
const conditionOpOptions = computed(() =>
|
||||
conditionOps.value.map((op) => ({
|
||||
value: op,
|
||||
label: AUTOMATION_CONDITION_OP_LABELS[op],
|
||||
})),
|
||||
);
|
||||
|
||||
const formFieldOptions = computed(() =>
|
||||
formFields.value.map((f) => ({ value: f.key, label: f.label })),
|
||||
);
|
||||
|
||||
const actionOptions = AUTOMATION_ACTIONS.map((a) => ({
|
||||
value: a,
|
||||
label: AUTOMATION_ACTION_LABELS[a],
|
||||
}));
|
||||
|
||||
const activityTypeOptions = activityTypes.map((t) => ({
|
||||
value: t.value,
|
||||
label: t.label,
|
||||
}));
|
||||
|
||||
const activityTypeDefOptions = computed(() => [
|
||||
{ value: '', label: '— بدون نوع سفارشی —' },
|
||||
...props.activityTypeDefs.map((t) => ({ value: t.id, label: t.name })),
|
||||
]);
|
||||
|
||||
const assignModeOptions = computed(() =>
|
||||
assignModes.value.map((m) => ({
|
||||
value: m,
|
||||
label: AUTOMATION_ASSIGN_MODE_LABELS[m],
|
||||
})),
|
||||
);
|
||||
|
||||
const userOptions = computed(() =>
|
||||
props.users.map((u) => ({ value: u.id, label: u.fullName })),
|
||||
);
|
||||
|
||||
const teamOptions = computed(() =>
|
||||
props.teams.map((t) => ({
|
||||
value: t.id,
|
||||
label: `${t.name} (${t.memberCount} نفر)`,
|
||||
})),
|
||||
);
|
||||
|
||||
const notifyUserOptions = computed(() => [
|
||||
{ value: '', label: 'مسئول معامله / تیکت' },
|
||||
...userOptions.value,
|
||||
]);
|
||||
|
||||
const notifyChannelOptions = AUTOMATION_NOTIFY_CHANNELS.map((ch) => ({
|
||||
value: ch,
|
||||
label: AUTOMATION_NOTIFY_CHANNEL_LABELS[ch],
|
||||
}));
|
||||
|
||||
const dueUnitOptions = dueUnits.map((u) => ({ value: u.value, label: u.label }));
|
||||
|
||||
function setAction(step: AutomationStep, action: AutomationAction) {
|
||||
step.kind = 'action';
|
||||
step.action = action;
|
||||
@@ -202,440 +380,273 @@ watch(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="inspector">
|
||||
<a-form layout="vertical" :style="{ marginBottom: 0 }">
|
||||
<template v-if="selected === 'trigger'">
|
||||
<h2>گره محرک</h2>
|
||||
<p class="hint">وقتی این اتفاق بیفتد، زنجیره از راست به چپ اجرا میشود.</p>
|
||||
<label>
|
||||
اگر
|
||||
<select v-model="trigger">
|
||||
<optgroup
|
||||
v-for="group in AUTOMATION_TRIGGER_GROUPS"
|
||||
:key="group.label"
|
||||
:label="group.label"
|
||||
>
|
||||
<option v-for="t in group.items" :key="t" :value="t">
|
||||
{{ AUTOMATION_TRIGGER_LABELS[t] }}
|
||||
</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="trigger === 'lead_submitted'">
|
||||
فرم
|
||||
<select v-model="sourceId">
|
||||
<option :value="null">همه فرمها</option>
|
||||
<option v-for="f in forms" :key="f.id" :value="f.id">{{ f.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="trigger === 'lead_submitted' && !sourceId" class="hint">
|
||||
برای شرط روی پاسخهای فرم، یک فرم مشخص را انتخاب کنید.
|
||||
</p>
|
||||
<label v-if="advanced || chainMode === 'branches'">
|
||||
رفتار شرطها
|
||||
<select v-model="chainMode">
|
||||
<option value="branches">{{ AUTOMATION_CHAIN_MODE_LABELS.branches }}</option>
|
||||
<option value="stop">{{ AUTOMATION_CHAIN_MODE_LABELS.stop }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="chainMode === 'branches'" class="hint">
|
||||
شاخهها روی بوم موازی نمایش داده میشوند و هر کدام جدا بررسی میشود. شرطهای یک شاخه با «و»
|
||||
ترکیب میشوند؛ مثلاً اگر دو گزینه تیک بخورد، هر دو شاخه اجرا میشود. برای شاخهٔ تازه از
|
||||
دکمهٔ «شاخهٔ جدید» زیر بوم استفاده کنید.
|
||||
</p>
|
||||
<p v-else-if="!advanced" class="hint">
|
||||
اتوماسیون ساده: شرطها پشتسرهم بررسی میشوند و اولین شرط ناموفق بقیهٔ زنجیره را متوقف
|
||||
میکند. اتوماسیون چندشاخه در نسخهٔ حرفهای فعال است.
|
||||
</p>
|
||||
<a-form-item label="اگر" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select v-model:value="trigger" :options="triggerOptions" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="trigger === 'lead_submitted'"
|
||||
label="فرم"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select v-model:value="sourceIdSelect" :options="formOptions" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="advanced || chainMode === 'branches'"
|
||||
label="رفتار شرطها"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select v-model:value="chainMode" :options="chainModeOptions" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-alert
|
||||
v-if="trigger === 'lead_submitted' && !sourceId"
|
||||
type="info"
|
||||
show-icon
|
||||
message="برای شرط روی پاسخ فرم، یک فرم مشخص انتخاب کنید."
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="selectedStep && isCondition">
|
||||
<h2>گره شرط</h2>
|
||||
<p class="hint">
|
||||
{{
|
||||
chainMode === 'branches'
|
||||
? 'اگر شرط برقرار نباشد، فقط عملهای این شاخه (تا شرط بعدی) اجرا نمیشوند.'
|
||||
: 'اگر شرط برقرار نباشد، عملهای بعد از این گره اجرا نمیشوند.'
|
||||
}}
|
||||
</p>
|
||||
<label>
|
||||
فیلد
|
||||
<select
|
||||
<a-form-item label="فیلد" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
:value="selectedStep.conditionField"
|
||||
@change="
|
||||
setConditionField(
|
||||
selectedStep,
|
||||
($event.target as HTMLSelectElement).value as AutomationConditionField,
|
||||
)
|
||||
"
|
||||
>
|
||||
<option v-for="f in conditionFields" :key="f" :value="f">
|
||||
{{ AUTOMATION_CONDITION_FIELD_LABELS[f] }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<template v-if="selectedStep.conditionField === 'form_field'">
|
||||
<p v-if="!selectedForm" class="hint warn">
|
||||
ابتدا در گره محرک یک فرم مشخص انتخاب کنید.
|
||||
</p>
|
||||
<label v-else>
|
||||
فیلد فرم
|
||||
<select
|
||||
:value="selectedStep.conditionKey ?? ''"
|
||||
@change="setConditionKey(selectedStep, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="" disabled>انتخاب فیلد…</option>
|
||||
<option v-for="f in formFields" :key="f.key" :value="f.key">{{ f.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</template>
|
||||
<label>
|
||||
مقایسه
|
||||
<select v-model="selectedStep.conditionOp">
|
||||
<option v-for="op in conditionOps" :key="op" :value="op">
|
||||
{{ AUTOMATION_CONDITION_OP_LABELS[op] }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="selectedStep.conditionField === 'deal_amount'">
|
||||
مبلغ
|
||||
<input v-model.number="selectedStep.conditionValue" type="number" min="0" />
|
||||
</label>
|
||||
<label v-if="selectedStep.conditionField === 'ticket_priority'">
|
||||
اولویت
|
||||
<select v-model="selectedStep.conditionValue">
|
||||
<option v-for="p in ticketPriorities" :key="p.value" :value="p.value">
|
||||
{{ p.label }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
:options="conditionFieldOptions"
|
||||
style="width: 100%"
|
||||
@change="onConditionFieldChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.conditionField === 'form_field' && selectedForm"
|
||||
label="فیلد فرم"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select
|
||||
:value="selectedStep.conditionKey ?? undefined"
|
||||
:options="formFieldOptions"
|
||||
placeholder="انتخاب فیلد…"
|
||||
style="width: 100%"
|
||||
@change="onConditionKeyChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="مقایسه" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
v-model:value="selectedStep.conditionOp"
|
||||
:options="conditionOpOptions"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.conditionField === 'deal_amount'"
|
||||
label="مبلغ"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-input-number v-model:value="dealAmountValue" :min="0" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.conditionField === 'ticket_priority'"
|
||||
label="اولویت"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select
|
||||
v-model:value="selectedStep.conditionValue"
|
||||
:options="ticketPriorities"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-alert
|
||||
v-if="selectedStep.conditionField === 'form_field' && !selectedForm"
|
||||
type="warning"
|
||||
show-icon
|
||||
message="ابتدا در گره محرک یک فرم مشخص انتخاب کنید."
|
||||
/>
|
||||
<template v-if="selectedStep.conditionField === 'form_field' && needsConditionValue">
|
||||
<div v-if="conditionFormField?.options?.length" class="user-picks">
|
||||
<p class="field-label">گزینهها (یک یا چند مورد)</p>
|
||||
<label v-for="o in conditionFormField.options" :key="o" class="ch">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="formConditionValues(selectedStep).includes(o)"
|
||||
@change="toggleConditionValue(selectedStep, o, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ o }}
|
||||
</label>
|
||||
<p v-if="formConditionValues(selectedStep).length > 1" class="hint">
|
||||
<a-form-item
|
||||
v-if="conditionFormField?.options?.length"
|
||||
label="گزینهها"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-checkbox-group
|
||||
:value="formConditionValues(selectedStep)"
|
||||
:options="conditionFormField.options.map((o) => ({ value: o, label: o }))"
|
||||
@change="onFormOptionValuesChange"
|
||||
/>
|
||||
<a-typography-text
|
||||
v-if="formConditionValues(selectedStep).length > 1"
|
||||
type="secondary"
|
||||
:style="{ display: 'block', marginTop: `${token.marginXXS}px` }"
|
||||
>
|
||||
{{ multiValueHint(selectedStep.conditionOp) }}
|
||||
</p>
|
||||
</div>
|
||||
<label v-else>
|
||||
مقدار
|
||||
<input v-model.trim="selectedStep.conditionValue" type="text" maxlength="200" />
|
||||
</label>
|
||||
</a-typography-text>
|
||||
</a-form-item>
|
||||
<a-form-item v-else label="مقدار" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-input v-model:value="formTextValue" :maxlength="200" />
|
||||
</a-form-item>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<template v-else-if="selectedStep">
|
||||
<h2>گره عمل</h2>
|
||||
<p class="hint">بعد از محرک (و شرطها)، این کار به ترتیب انجام میشود.</p>
|
||||
<label>
|
||||
آنگاه
|
||||
<select
|
||||
<a-form-item label="آنگاه" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
:value="selectedStep.action"
|
||||
@change="
|
||||
setAction(
|
||||
selectedStep,
|
||||
($event.target as HTMLSelectElement).value as AutomationAction,
|
||||
)
|
||||
"
|
||||
>
|
||||
<option v-for="a in AUTOMATION_ACTIONS" :key="a" :value="a">
|
||||
{{ AUTOMATION_ACTION_LABELS[a] }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
عنوان
|
||||
<input
|
||||
v-model="selectedStep.title"
|
||||
type="text"
|
||||
maxlength="200"
|
||||
:options="actionOptions"
|
||||
style="width: 100%"
|
||||
@change="onActionChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="عنوان" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-input
|
||||
v-model:value="selectedStep.title"
|
||||
:maxlength="200"
|
||||
placeholder="اختیاری"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
توضیح / متن پیام
|
||||
<textarea
|
||||
v-model="selectedStep.body"
|
||||
rows="3"
|
||||
maxlength="1000"
|
||||
</a-form-item>
|
||||
<a-form-item label="توضیح / متن" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-textarea
|
||||
v-model:value="selectedStep.body"
|
||||
:rows="2"
|
||||
:maxlength="1000"
|
||||
placeholder="اختیاری"
|
||||
/>
|
||||
</label>
|
||||
</a-form-item>
|
||||
|
||||
<label v-if="selectedStep.action === 'create_activity'">
|
||||
نوع فعالیت
|
||||
<select v-model="selectedStep.activityType">
|
||||
<option v-for="t in activityTypes" :key="t.value" :value="t.value">
|
||||
{{ t.label }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<template v-if="selectedStep.action === 'create_activity'">
|
||||
<label v-if="activityTypeDefs.length">
|
||||
نوع سفارشی (اختیاری)
|
||||
<select v-model="selectedStep.activityTypeDefId">
|
||||
<option :value="null">— بدون نوع سفارشی —</option>
|
||||
<option v-for="t in activityTypeDefs" :key="t.id" :value="t.id">{{ t.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
تخصیص به
|
||||
<select v-model="selectedStep.assignMode">
|
||||
<option v-for="m in assignModes" :key="m" :value="m">
|
||||
{{ AUTOMATION_ASSIGN_MODE_LABELS[m] }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="selectedStep.assignMode === 'user'">
|
||||
کاربر
|
||||
<select v-model="selectedStep.assigneeId">
|
||||
<option :value="null" disabled>انتخاب کاربر…</option>
|
||||
<option v-for="u in users" :key="u.id" :value="u.id">{{ u.fullName }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<template v-else-if="selectedStep.assignMode === 'team_round_robin'">
|
||||
<label>
|
||||
تیم
|
||||
<select v-model="selectedStep.assigneeTeamId">
|
||||
<option :value="null" disabled>انتخاب تیم…</option>
|
||||
<option v-for="t in teams" :key="t.id" :value="t.id">
|
||||
{{ t.name }} ({{ t.memberCount }} نفر)
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="!teams.length" class="hint warn">
|
||||
هنوز تیمی تعریف نشده؛ از «تنظیمات ← تیمها و سطح دسترسی» بسازید.
|
||||
</p>
|
||||
</template>
|
||||
<div v-else-if="selectedStep.assignMode === 'users_round_robin'" class="user-picks">
|
||||
<p class="field-label">کاربران</p>
|
||||
<label v-for="u in users" :key="u.id" class="ch">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="(selectedStep.assigneeUserIds ?? []).includes(u.id)"
|
||||
@change="toggleUser(selectedStep, u.id, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ u.fullName }}
|
||||
</label>
|
||||
</div>
|
||||
<p
|
||||
v-if="selectedStep.assignMode === 'team_round_robin' || selectedStep.assignMode === 'users_round_robin'"
|
||||
class="hint"
|
||||
<a-form-item label="نوع فعالیت" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
v-model:value="selectedStep.activityType"
|
||||
:options="activityTypeOptions"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="activityTypeDefs.length"
|
||||
label="نوع سفارشی"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
هر بار نفر بعدی به نوبت انتخاب میشود تا کارها مساوی تقسیم شوند.
|
||||
</p>
|
||||
|
||||
<div class="due">
|
||||
<label>
|
||||
موعد
|
||||
<select
|
||||
:value="dueUnitOf(selectedStep)"
|
||||
@change="
|
||||
setDue(
|
||||
selectedStep,
|
||||
($event.target as HTMLSelectElement).value as DueUnit,
|
||||
dueAmountOf(selectedStep) || 1,
|
||||
)
|
||||
"
|
||||
<a-select
|
||||
:value="nullableId(selectedStep.activityTypeDefId)"
|
||||
:options="activityTypeDefOptions"
|
||||
style="width: 100%"
|
||||
@change="onActivityTypeDefChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="تخصیص به" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
v-model:value="selectedStep.assignMode"
|
||||
:options="assignModeOptions"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.assignMode === 'user'"
|
||||
label="کاربر"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select
|
||||
:value="nullableId(selectedStep.assigneeId)"
|
||||
:options="userOptions"
|
||||
placeholder="انتخاب کاربر…"
|
||||
style="width: 100%"
|
||||
@change="onAssigneeIdChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-else-if="selectedStep.assignMode === 'team_round_robin'"
|
||||
label="تیم"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-select
|
||||
:value="nullableId(selectedStep.assigneeTeamId)"
|
||||
:options="teamOptions"
|
||||
placeholder="انتخاب تیم…"
|
||||
style="width: 100%"
|
||||
@change="onAssigneeTeamIdChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.assignMode === 'users_round_robin'"
|
||||
label="کاربران"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-flex vertical :gap="token.marginXXS">
|
||||
<a-checkbox
|
||||
v-for="u in users"
|
||||
:key="u.id"
|
||||
:checked="(selectedStep.assigneeUserIds ?? []).includes(u.id)"
|
||||
@change="onUserCheck(selectedStep, u.id, $event)"
|
||||
>
|
||||
<option v-for="u in dueUnits" :key="u.value" :value="u.value">{{ u.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="dueUnitOf(selectedStep) !== 'now'">
|
||||
تعداد
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
:value="dueAmountOf(selectedStep)"
|
||||
@input="
|
||||
setDue(
|
||||
selectedStep,
|
||||
dueUnitOf(selectedStep),
|
||||
Number(($event.target as HTMLInputElement).value),
|
||||
)
|
||||
"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{{ u.fullName }}
|
||||
</a-checkbox>
|
||||
</a-flex>
|
||||
</a-form-item>
|
||||
<a-form-item label="موعد" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
:value="dueUnitOf(selectedStep)"
|
||||
:options="dueUnitOptions"
|
||||
style="width: 100%"
|
||||
@change="onDueUnitChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="dueUnitOf(selectedStep) !== 'now'"
|
||||
label="تعداد"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-input-number
|
||||
:min="1"
|
||||
:value="dueAmountOf(selectedStep)"
|
||||
style="width: 100%"
|
||||
@change="onDueAmountChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-alert
|
||||
v-if="selectedStep.assignMode === 'team_round_robin' && !teams.length"
|
||||
type="warning"
|
||||
show-icon
|
||||
message="هنوز تیمی تعریف نشده."
|
||||
/>
|
||||
</template>
|
||||
<p v-if="selectedStep.action === 'create_activity' || selectedStep.action === 'create_notification'" class="hint">
|
||||
در عنوان و متن میتوانید از
|
||||
<code v-pre>{{title}}</code>، <code v-pre>{{mobile}}</code>، <code v-pre>{{form}}</code> و
|
||||
<code v-pre>{{field.کلید}}</code> استفاده کنید.
|
||||
<template v-if="formFields.length">
|
||||
کلیدها:
|
||||
<span v-for="(f, i) in formFields" :key="f.key">
|
||||
<code>{{ f.key }}</code> ({{ f.label }})<template v-if="i < formFields.length - 1">، </template>
|
||||
</span>
|
||||
</template>
|
||||
</p>
|
||||
|
||||
<template v-if="selectedStep.action === 'create_notification'">
|
||||
<p class="field-label">نحوه ارسال</p>
|
||||
<div class="channels">
|
||||
<label
|
||||
v-for="ch in AUTOMATION_NOTIFY_CHANNELS"
|
||||
:key="ch"
|
||||
class="ch"
|
||||
>
|
||||
<input
|
||||
v-model="selectedStep.notifyChannel"
|
||||
type="radio"
|
||||
:value="ch"
|
||||
/>
|
||||
{{ AUTOMATION_NOTIFY_CHANNEL_LABELS[ch] }}
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
گیرنده
|
||||
<select v-model="selectedStep.notifyTarget">
|
||||
<option value="staff">کاربر تیم</option>
|
||||
<option value="person">مخاطب معامله / تیکت</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="selectedStep.notifyTarget !== 'person'">
|
||||
کاربر
|
||||
<select v-model="selectedStep.notifyUserId">
|
||||
<option :value="null">مسئول معامله / تیکت</option>
|
||||
<option v-for="u in users" :key="u.id" :value="u.id">
|
||||
{{ u.fullName }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="selectedStep.notifyTarget === 'person'" class="hint">
|
||||
پیامک به موبایل مخاطب ارسال میشود. ناتیفیکیشن داخلی برای مخاطب نیست.
|
||||
</p>
|
||||
<p
|
||||
v-else-if="selectedStep.notifyChannel === 'sms' || selectedStep.notifyChannel === 'both'"
|
||||
class="hint"
|
||||
<a-form-item label="نحوه ارسال" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-radio-group
|
||||
v-model:value="selectedStep.notifyChannel"
|
||||
:options="notifyChannelOptions"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="گیرنده" :style="{ marginBottom: `${token.marginSM}px` }">
|
||||
<a-select
|
||||
v-model:value="selectedStep.notifyTarget"
|
||||
:options="[
|
||||
{ value: 'staff', label: 'کاربر تیم' },
|
||||
{ value: 'person', label: 'مخاطب معامله / تیکت' },
|
||||
]"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
v-if="selectedStep.notifyTarget !== 'person'"
|
||||
label="کاربر"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
پیامک به موبایل همان کاربر ارسال میشود.
|
||||
</p>
|
||||
<a-select
|
||||
:value="nullableId(selectedStep.notifyUserId)"
|
||||
:options="notifyUserOptions"
|
||||
style="width: 100%"
|
||||
@change="onNotifyUserIdChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
</template>
|
||||
|
||||
<label v-if="selectedStep.action === 'add_loyalty_points'">
|
||||
امتیاز
|
||||
<input v-model.number="selectedStep.points" type="number" min="1" />
|
||||
</label>
|
||||
<a-form-item
|
||||
v-if="selectedStep.action === 'add_loyalty_points'"
|
||||
label="امتیاز"
|
||||
:style="{ marginBottom: `${token.marginSM}px` }"
|
||||
>
|
||||
<a-input-number v-model:value="selectedStep.points" :min="1" style="width: 100%" />
|
||||
</a-form-item>
|
||||
</template>
|
||||
|
||||
<p v-else class="hint">یک گره را از بوم انتخاب کنید.</p>
|
||||
</aside>
|
||||
<a-typography-text v-else type="secondary">یک گره را از بوم انتخاب کنید.</a-typography-text>
|
||||
</a-form>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.inspector {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
align-content: start;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.98rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
label,
|
||||
.field-label {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.84rem;
|
||||
color: #64748b;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.55rem 0.7rem;
|
||||
font: inherit;
|
||||
color: #0f172a;
|
||||
background: #fff;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.channels {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.55rem 0.85rem;
|
||||
}
|
||||
|
||||
.ch {
|
||||
display: inline-flex !important;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.32rem;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ch input {
|
||||
accent-color: #14b8a6;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.hint.warn {
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
.hint code {
|
||||
font-size: 0.76rem;
|
||||
background: #f1f5f9;
|
||||
border-radius: 4px;
|
||||
padding: 0 0.25rem;
|
||||
direction: ltr;
|
||||
unicode-bidi: embed;
|
||||
}
|
||||
|
||||
.user-picks {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
max-height: 12rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.due {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 0.5rem;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.due input {
|
||||
width: 5.5rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { computed, type Component } from 'vue';
|
||||
import {
|
||||
BellOutlined,
|
||||
DeleteOutlined,
|
||||
FilterOutlined,
|
||||
FlagOutlined,
|
||||
GiftOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { isAutomationCondition, type AutomationStep } from '@mento/shared';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -15,11 +21,11 @@ const emit = defineEmits<{ select: []; remove: [] }>();
|
||||
|
||||
const isCondition = computed(() => isAutomationCondition(props.step));
|
||||
|
||||
const icon = computed(() => {
|
||||
if (isCondition.value) return 'filter';
|
||||
if (props.step.action === 'create_notification') return 'bell';
|
||||
if (props.step.action === 'add_loyalty_points') return 'gift';
|
||||
return 'flag';
|
||||
const icon = computed((): Component => {
|
||||
if (isCondition.value) return FilterOutlined;
|
||||
if (props.step.action === 'create_notification') return BellOutlined;
|
||||
if (props.step.action === 'add_loyalty_points') return GiftOutlined;
|
||||
return FlagOutlined;
|
||||
});
|
||||
|
||||
const kindClass = computed(() =>
|
||||
@@ -36,7 +42,7 @@ const kindClass = computed(() =>
|
||||
@click="emit('select')"
|
||||
>
|
||||
<span class="icon">
|
||||
<UiIcon :name="icon" :size="18" />
|
||||
<component :is="icon" />
|
||||
</span>
|
||||
<span class="copy">
|
||||
<span class="kind">{{ isCondition ? 'شرط' : 'آنگاه' }}</span>
|
||||
@@ -51,7 +57,7 @@ const kindClass = computed(() =>
|
||||
title="حذف"
|
||||
@click.stop="emit('remove')"
|
||||
>
|
||||
<UiIcon name="trash" :size="14" />
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -125,6 +131,7 @@ const kindClass = computed(() =>
|
||||
flex-shrink: 0;
|
||||
color: #0f766e;
|
||||
background: #ecfdf8;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.node.create_notification .icon {
|
||||
@@ -184,6 +191,7 @@ em {
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.node-wrap:hover .trash,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Empty as AEmpty } from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardActivityTypeDto } from '@mento/shared';
|
||||
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
items: HomeDashboardActivityTypeDto[];
|
||||
}>();
|
||||
|
||||
const rows = computed(() => props.items);
|
||||
const hasData = computed(() => rows.value.some((r) => r.count > 0));
|
||||
const total = computed(() => rows.value.reduce((a, r) => a + r.count, 0));
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 400,
|
||||
grid: { top: 28, right: 8, bottom: 28, left: 8, containLabel: true },
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: { type: 'shadow' },
|
||||
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
|
||||
formatter: (params) => {
|
||||
const row = Array.isArray(params) ? params[0] : params;
|
||||
const point = rows.value[row.dataIndex ?? 0];
|
||||
if (!point) return '';
|
||||
return `${point.label}<br/>${toFaDigits(point.count)} فعالیت باز`;
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.value.map((r) => r.label),
|
||||
axisLine: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLabel: {
|
||||
color: '#94a3b8',
|
||||
fontFamily: 'IRANSans, Tahoma, sans-serif',
|
||||
fontSize: 11,
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
minInterval: 1,
|
||||
...(hasData.value ? {} : { max: 1 }),
|
||||
splitLine: { lineStyle: { color: '#e5e7eb', type: 'dashed' } },
|
||||
axisLabel: { show: false },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'bar',
|
||||
data: rows.value.map((r) => r.count),
|
||||
barMaxWidth: 36,
|
||||
itemStyle: {
|
||||
color: '#14b8a6',
|
||||
borderRadius: [8, 8, 0, 0],
|
||||
},
|
||||
label: {
|
||||
show: true,
|
||||
position: 'top',
|
||||
color: '#0f172a',
|
||||
fontWeight: 700,
|
||||
fontFamily: 'IRANSans, Tahoma, sans-serif',
|
||||
formatter: (p) => toFaDigits(Number(p.value ?? 0)),
|
||||
},
|
||||
},
|
||||
],
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="font-bold text-slate-800 text-base">ترکیب فعالیتهای باز</h3>
|
||||
<span v-if="hasData" class="text-xs text-slate-400">{{ toFaDigits(total) }} مورد</span>
|
||||
</div>
|
||||
<a-empty v-if="!hasData" description="فعالیت بازی نیست" />
|
||||
<div v-else class="h-56">
|
||||
<UiChart :option="option" height="224px" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -2,13 +2,25 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import axios from 'axios';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { RobotOutlined } from '@ant-design/icons-vue';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Button as AButton,
|
||||
Col as ACol,
|
||||
Form as AForm,
|
||||
Input as AInput,
|
||||
Modal as AModal,
|
||||
Row as ARow,
|
||||
Select as ASelect,
|
||||
Space as ASpace,
|
||||
Tag as ATag,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import VoiceToTextButton from '@/components/VoiceToTextButton.vue';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import { formatLocalDateTimeInput, rewriteGregorianDates } from '@/lib/jalali';
|
||||
import { UiButton, UiModal } from '@/components/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import { brand, type ActivityType, type AskMentoSourceDto, type PersonDto, type VoiceCommandDraft } from '@mento/shared';
|
||||
import { brand, type AskMentoSourceDto, type PersonDto, type VoiceCommandDraft } from '@mento/shared';
|
||||
|
||||
const props = defineProps<{
|
||||
askQuery: string;
|
||||
@@ -26,11 +38,23 @@ const emit = defineEmits<{
|
||||
notice: [value: { error: string; done: string }];
|
||||
}>();
|
||||
|
||||
const { Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography;
|
||||
|
||||
const AFormItem = AForm.Item;
|
||||
const ATextarea = AInput.TextArea;
|
||||
|
||||
const shortcuts = [
|
||||
{ label: 'معاملات باز و در خطر را بگو', icon: 'warning' as const },
|
||||
{ label: 'فعالیتهای عقبافتاده چیست؟', icon: 'calendar' as const },
|
||||
{ label: 'مهمترین پیگیری امروز چیست؟', icon: 'send' as const },
|
||||
{ label: 'خلاصه وضعیت فروش را بده', icon: 'chart' as const },
|
||||
{ label: 'معاملات در خطر', prompt: 'معاملات باز و در خطر را بگو' },
|
||||
{ label: 'عقبافتادهها', prompt: 'فعالیتهای عقبافتاده چیست؟' },
|
||||
{ label: 'پیگیری امروز', prompt: 'مهمترین پیگیری امروز چیست؟' },
|
||||
{ label: 'خلاصه فروش', prompt: 'خلاصه وضعیت فروش را بده' },
|
||||
];
|
||||
|
||||
const activityTypeOptions = [
|
||||
{ value: 'call', label: 'تماس' },
|
||||
{ value: 'meeting', label: 'جلسه' },
|
||||
{ value: 'task', label: 'کار' },
|
||||
{ value: 'note', label: 'یادداشت' },
|
||||
];
|
||||
|
||||
function sourceTo(source: AskMentoSourceDto) {
|
||||
@@ -45,13 +69,6 @@ function pick(label: string) {
|
||||
emit('ask', label);
|
||||
}
|
||||
|
||||
const ACTIVITY_LABEL: Record<ActivityType, string> = {
|
||||
call: 'تماس',
|
||||
meeting: 'جلسه',
|
||||
task: 'کار',
|
||||
note: 'یادداشت',
|
||||
};
|
||||
|
||||
const voiceBuf = ref('');
|
||||
const voiceBusy = ref(false);
|
||||
const voiceError = ref('');
|
||||
@@ -60,6 +77,13 @@ const draft = ref<VoiceCommandDraft | null>(null);
|
||||
const confirming = ref(false);
|
||||
const answerOpen = ref(false);
|
||||
|
||||
const draftOpen = computed({
|
||||
get: () => Boolean(draft.value && draft.value.intent !== 'none'),
|
||||
set: (open: boolean) => {
|
||||
if (!open) cancelDraft();
|
||||
},
|
||||
});
|
||||
|
||||
function apiMessage(e: unknown, fallback: string) {
|
||||
if (!axios.isAxiosError(e)) return fallback;
|
||||
const msg = (e.response?.data as { message?: string | string[] })?.message;
|
||||
@@ -272,12 +296,36 @@ watch(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article id="home-ai-assistant" class="panel">
|
||||
<header class="panel-head">
|
||||
<h2>
|
||||
<span class="spark"><UiIcon name="sparkle" :size="15" /></span>
|
||||
{{ brand.aiNameFa }}
|
||||
</h2>
|
||||
<section id="home-ai-assistant" class="bg-white rounded-2xl border border-slate-200/80 p-3 shadow-sm flex flex-col justify-between h-[330px] gap-3">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<span class="w-10 h-10 rounded-xl bg-emerald-600 text-white flex items-center justify-center shrink-0">
|
||||
<RobotOutlined />
|
||||
</span>
|
||||
<h3 class="font-bold text-slate-800 text-base truncate">{{ brand.aiNameFa }}</h3>
|
||||
</div>
|
||||
<a-tag color="success" class="!m-0 shrink-0">هوش مصنوعی</a-tag>
|
||||
</div>
|
||||
|
||||
<div class="bg-emerald-50/50 border border-emerald-200/60 rounded-xl p-3 text-xs text-slate-600 leading-relaxed">
|
||||
<template v-if="answer">{{ answer }}</template>
|
||||
<template v-else-if="error">{{ error }}</template>
|
||||
<template v-else>
|
||||
<strong class="text-slate-800">پیشنهاد هوشمند امروز:</strong>
|
||||
از پیشنهادهای سریع استفاده کنید یا پرسش خود را بنویسید.
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="bg-slate-50 border border-slate-200/90 rounded-xl p-1.5 flex items-center gap-2">
|
||||
<a-input
|
||||
:value="askQuery"
|
||||
:placeholder="brand.askPlaceholderFa"
|
||||
:bordered="false"
|
||||
:disabled="asking || voiceBusy || confirming"
|
||||
class="flex-1"
|
||||
@update:value="emit('update:askQuery', $event)"
|
||||
@press-enter="onTypedSubmit"
|
||||
/>
|
||||
<VoiceToTextButton
|
||||
variant="toolbar"
|
||||
hide-error
|
||||
@@ -286,322 +334,181 @@ watch(
|
||||
@recording="onVoiceRecording"
|
||||
@error="voiceError = $event"
|
||||
/>
|
||||
</header>
|
||||
|
||||
<p class="ai-lead">چه کمکی میتونم بکنم؟</p>
|
||||
|
||||
<div class="ai-shortcuts">
|
||||
<button
|
||||
v-for="item in shortcuts"
|
||||
:key="item.label"
|
||||
class="ai-chip"
|
||||
type="button"
|
||||
:disabled="asking"
|
||||
@click="pick(item.label)"
|
||||
>
|
||||
<span class="chip-ico"><UiIcon :name="item.icon" :size="14" /></span>
|
||||
<span>{{ item.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="voiceBusy" class="ai-answer"><p>در حال فهمیدن دستور…</p></div>
|
||||
<div v-else-if="confirming" class="ai-answer"><p>در حال ثبت…</p></div>
|
||||
<div v-else-if="voiceDone" class="ai-answer"><p>{{ voiceDone }}</p></div>
|
||||
<p v-else-if="voiceError" class="ai-error">{{ voiceError }}</p>
|
||||
<p v-else-if="error" class="ai-error">{{ error }}</p>
|
||||
<div v-else-if="asking" class="ai-answer">
|
||||
<p>در حال پاسخ…</p>
|
||||
</div>
|
||||
|
||||
<form class="ai-input" @submit.prevent="onTypedSubmit">
|
||||
<input
|
||||
:value="askQuery"
|
||||
type="search"
|
||||
:placeholder="brand.askPlaceholderFa"
|
||||
<a-button
|
||||
type="primary"
|
||||
:disabled="asking || voiceBusy || confirming"
|
||||
@input="emit('update:askQuery', ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<button type="submit" aria-label="ارسال" :disabled="asking || voiceBusy || confirming">
|
||||
<UiIcon name="send" :size="15" />
|
||||
</button>
|
||||
</form>
|
||||
:loading="asking || voiceBusy"
|
||||
aria-label="ارسال"
|
||||
@click="onTypedSubmit"
|
||||
>
|
||||
بپرس
|
||||
</a-button>
|
||||
</div>
|
||||
|
||||
<UiModal
|
||||
:open="Boolean(draft && draft.intent !== 'none')"
|
||||
<div class="pt-3 border-t border-slate-100 flex items-center justify-between flex-wrap gap-2">
|
||||
<span class="text-[11px] font-semibold text-slate-400">پیشنهادهای سریع</span>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<button
|
||||
v-for="item in shortcuts"
|
||||
:key="item.label"
|
||||
type="button"
|
||||
class="!text-[11px] !leading-4 !font-medium bg-emerald-50/70 text-emerald-700 border border-emerald-200/60 px-2 py-0.5 rounded-md disabled:opacity-50"
|
||||
:disabled="asking"
|
||||
@click="pick(item.prompt)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a-alert v-if="voiceBusy" type="info" show-icon message="در حال فهمیدن دستور…" />
|
||||
<a-alert v-else-if="confirming" type="info" show-icon message="در حال ثبت…" />
|
||||
<a-alert v-else-if="voiceDone" type="success" show-icon :message="voiceDone" />
|
||||
<a-alert v-else-if="voiceError" type="error" show-icon :message="voiceError" />
|
||||
</section>
|
||||
|
||||
<a-modal
|
||||
v-model:open="draftOpen"
|
||||
:title="draft?.intent === 'create_person' ? 'تأیید ساخت مشتری' : 'تأیید ثبت فعالیت'"
|
||||
@close="cancelDraft"
|
||||
destroy-on-close
|
||||
@cancel="cancelDraft"
|
||||
>
|
||||
<p v-if="draft" class="modal-lead">{{ rewriteGregorianDates(draft.summary) }}</p>
|
||||
<p class="edit-hint">قبل از تأیید میتوانید متن را اصلاح کنید.</p>
|
||||
<div v-if="draft?.person" class="modal-fields">
|
||||
<label>نام <input v-model="draft.person.firstName" @input="onPersonNameEdit" /></label>
|
||||
<label>نام خانوادگی <input v-model="draft.person.lastName" /></label>
|
||||
<label>موبایل <input v-model="draft.person.mobile" dir="ltr" /></label>
|
||||
<label>تلفن <input v-model="draft.person.phone" dir="ltr" /></label>
|
||||
<label>ایمیل <input v-model="draft.person.email" dir="ltr" /></label>
|
||||
<label>وبسایت <input v-model="draft.person.website" dir="ltr" /></label>
|
||||
<label>معرف <input v-model="draft.person.referrer" /></label>
|
||||
<label>سمت <input v-model="draft.person.position" /></label>
|
||||
<label>یادداشت <textarea v-model="draft.person.notes" rows="2" /></label>
|
||||
</div>
|
||||
<div v-else-if="draft?.activity" class="modal-fields">
|
||||
<label>عنوان <input v-model="draft.activity.title" @input="onActivityTitleEdit" /></label>
|
||||
<label>
|
||||
نوع
|
||||
<select v-model="draft.activity.type">
|
||||
<option v-for="(label, key) in ACTIVITY_LABEL" :key="key" :value="key">{{ label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
زمان
|
||||
<JalaliDateInput :model-value="dueLocal" mode="datetime" @update:model-value="onDueLocal" />
|
||||
</label>
|
||||
<label>
|
||||
مشتری
|
||||
<input v-model="draft.activity.personName" @input="onActivityPersonEdit" @change="rematchActivityPerson" />
|
||||
</label>
|
||||
<p v-if="draft.activity.personName && !draft.activity.personId" class="warn">
|
||||
در فهرست مشتریان پروندهای با این نام پیدا نشد. فعالیت ذخیره میشود، ولی داخل پروندهٔ آن شخص دیده نمیشود.
|
||||
</p>
|
||||
<label>توضیح <textarea v-model="draft.activity.description" rows="2" /></label>
|
||||
</div>
|
||||
<p v-if="draft?.missing.length" class="ai-error">ناقص است: {{ draft.missing.join('، ') }}</p>
|
||||
<template #footer>
|
||||
<UiButton variant="ghost" :disabled="confirming" @click="cancelDraft">انصراف</UiButton>
|
||||
<UiButton variant="primary" :disabled="!draft?.canConfirm || confirming" :loading="confirming" @click="confirmDraft">
|
||||
تأیید و انجام
|
||||
</UiButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
<a-typography-paragraph v-if="draft">
|
||||
{{ rewriteGregorianDates(draft.summary) }}
|
||||
</a-typography-paragraph>
|
||||
<a-typography-text type="secondary">قبل از تأیید میتوانید متن را اصلاح کنید.</a-typography-text>
|
||||
|
||||
<UiModal :open="answerOpen && Boolean(answer)" title="پاسخ دستیار" @close="closeAnswer">
|
||||
<p class="modal-lead answer-body">{{ rewriteGregorianDates(answer || '') }}</p>
|
||||
<div v-if="sources?.length" class="sources">
|
||||
<a-form v-if="draft?.person" layout="vertical" style="margin-top: 16px">
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="نام">
|
||||
<a-input v-model:value="draft.person.firstName" @update:value="onPersonNameEdit" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="نام خانوادگی">
|
||||
<a-input v-model:value="draft.person.lastName" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="موبایل">
|
||||
<a-input v-model:value="draft.person.mobile" dir="ltr" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="تلفن">
|
||||
<a-input v-model:value="draft.person.phone" dir="ltr" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="ایمیل">
|
||||
<a-input v-model:value="draft.person.email" dir="ltr" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="وبسایت">
|
||||
<a-input v-model:value="draft.person.website" dir="ltr" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="معرف">
|
||||
<a-input v-model:value="draft.person.referrer" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="سمت">
|
||||
<a-input v-model:value="draft.person.position" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="24">
|
||||
<a-form-item label="یادداشت">
|
||||
<a-textarea v-model:value="draft.person.notes" :rows="2" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-form>
|
||||
|
||||
<a-form v-else-if="draft?.activity" layout="vertical" style="margin-top: 16px">
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :span="24">
|
||||
<a-form-item label="عنوان">
|
||||
<a-input v-model:value="draft.activity.title" @update:value="onActivityTitleEdit" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="نوع">
|
||||
<a-select
|
||||
v-model:value="draft.activity.type"
|
||||
:options="activityTypeOptions"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="زمان">
|
||||
<JalaliDateInput :model-value="dueLocal" mode="datetime" @update:model-value="onDueLocal" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="24">
|
||||
<a-form-item label="مشتری">
|
||||
<a-input
|
||||
v-model:value="draft.activity.personName"
|
||||
@update:value="onActivityPersonEdit"
|
||||
@blur="rematchActivityPerson"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-alert
|
||||
v-if="draft.activity.personName && !draft.activity.personId"
|
||||
type="warning"
|
||||
show-icon
|
||||
message="در فهرست مشتریان پروندهای با این نام پیدا نشد. فعالیت ذخیره میشود، ولی داخل پروندهٔ آن شخص دیده نمیشود."
|
||||
/>
|
||||
</a-col>
|
||||
<a-col :span="24">
|
||||
<a-form-item label="توضیح">
|
||||
<a-textarea v-model:value="draft.activity.description" :rows="2" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-form>
|
||||
|
||||
<a-alert
|
||||
v-if="draft?.missing.length"
|
||||
type="error"
|
||||
show-icon
|
||||
:message="`ناقص است: ${draft.missing.join('، ')}`"
|
||||
style="margin-top: 12px"
|
||||
/>
|
||||
|
||||
<template #footer>
|
||||
<a-button :disabled="confirming" @click="cancelDraft">انصراف</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
:disabled="!draft?.canConfirm || confirming"
|
||||
:loading="confirming"
|
||||
@click="confirmDraft"
|
||||
>
|
||||
تأیید و انجام
|
||||
</a-button>
|
||||
</template>
|
||||
</a-modal>
|
||||
|
||||
<a-modal v-model:open="answerOpen" title="پاسخ دستیار" destroy-on-close @cancel="closeAnswer">
|
||||
<a-typography-paragraph style="white-space: pre-wrap">
|
||||
{{ rewriteGregorianDates(answer || '') }}
|
||||
</a-typography-paragraph>
|
||||
<a-space v-if="sources?.length" wrap>
|
||||
<RouterLink
|
||||
v-for="source in sources"
|
||||
:key="`${source.type}-${source.id}`"
|
||||
:to="sourceTo(source)"
|
||||
@click="closeAnswer"
|
||||
>
|
||||
{{ source.label }}
|
||||
<a-tag color="processing">{{ source.label }}</a-tag>
|
||||
</RouterLink>
|
||||
</div>
|
||||
</a-space>
|
||||
<template #footer>
|
||||
<UiButton variant="primary" @click="closeAnswer">بستن</UiButton>
|
||||
<a-button type="primary" @click="closeAnswer">بستن</a-button>
|
||||
</template>
|
||||
</UiModal>
|
||||
</article>
|
||||
</a-modal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1rem 0.95rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #eef2f7;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
margin-bottom: 0.55rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.modal-lead {
|
||||
margin: 0 0 0.85rem;
|
||||
color: #334155;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.answer-body {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.edit-hint {
|
||||
margin: -0.35rem 0 0.75rem;
|
||||
color: #64748b;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.modal-fields {
|
||||
display: grid;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.modal-fields label {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modal-fields input,
|
||||
.modal-fields select,
|
||||
.modal-fields textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
color: #0f172a;
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
font-weight: 500;
|
||||
padding: 0.5rem 0.65rem;
|
||||
}
|
||||
|
||||
.modal-fields textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.warn {
|
||||
display: inline-block;
|
||||
margin-inline-start: 0.35rem;
|
||||
color: #b45309;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.92rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.spark {
|
||||
color: #eab308;
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.ai-lead {
|
||||
margin: 0 0 0.75rem;
|
||||
padding: 0.55rem 0.75rem;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
background: #d1fae5;
|
||||
color: #115e59;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
border-radius: 14px 14px 4px 14px;
|
||||
}
|
||||
|
||||
.ai-shortcuts {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
margin-bottom: 0.8rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.ai-chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
padding: 0.58rem 0.7rem;
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
color: #334155;
|
||||
font-size: 0.76rem;
|
||||
text-align: start;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);
|
||||
}
|
||||
|
||||
.ai-chip:hover:not(:disabled) {
|
||||
background: #f0fdfa;
|
||||
border-color: #99f6e4;
|
||||
}
|
||||
|
||||
.ai-chip:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.chip-ico {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: var(--radius);
|
||||
background: #ecfdf8;
|
||||
color: #14b8a6;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ai-input {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.ai-input input {
|
||||
flex: 1;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.58rem 0.75rem;
|
||||
background: #f8fafc;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.ai-input button {
|
||||
width: 40px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.ai-input button:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.ai-answer {
|
||||
background: #f0fdfa;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.7rem 0.8rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.ai-answer p {
|
||||
margin: 0;
|
||||
color: #134e4a;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.sources {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.3rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.sources a {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
color: #0f766e;
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 0.15rem 0.5rem;
|
||||
}
|
||||
|
||||
.ai-error {
|
||||
margin: 0 0 0.7rem;
|
||||
color: #b91c1c;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { Component } from 'vue';
|
||||
import {
|
||||
AlertOutlined,
|
||||
CheckCircleOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
InfoCircleOutlined,
|
||||
LeftOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardAlertDto } from '@mento/shared';
|
||||
|
||||
const props = defineProps<{
|
||||
alerts: HomeDashboardAlertDto[];
|
||||
}>();
|
||||
|
||||
type Tone = HomeDashboardAlertDto['tone'];
|
||||
|
||||
type AlertRow = {
|
||||
key: string;
|
||||
tone: Tone;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
const TONE_ORDER: Record<Tone, number> = {
|
||||
urgent: 0,
|
||||
warning: 1,
|
||||
info: 2,
|
||||
success: 3,
|
||||
};
|
||||
|
||||
const rows = computed<AlertRow[]>(() =>
|
||||
[...(props.alerts ?? [])]
|
||||
.map((a) => {
|
||||
const parts = a.text.split(/\s*[—\-–]\s*|\n/);
|
||||
const title = parts[0]?.trim() || a.text;
|
||||
const subtitle = parts.slice(1).join(' ').trim() || undefined;
|
||||
return {
|
||||
key: a.key,
|
||||
tone: a.tone,
|
||||
title,
|
||||
subtitle,
|
||||
link: a.link || '/',
|
||||
};
|
||||
})
|
||||
.sort((a, b) => TONE_ORDER[a.tone] - TONE_ORDER[b.tone]),
|
||||
);
|
||||
|
||||
const urgentCount = computed(() => rows.value.filter((r) => r.tone === 'urgent').length);
|
||||
const warningCount = computed(() => rows.value.filter((r) => r.tone === 'warning').length);
|
||||
|
||||
function toneIcon(tone: Tone): Component {
|
||||
if (tone === 'urgent') return ExclamationCircleOutlined;
|
||||
if (tone === 'warning') return AlertOutlined;
|
||||
if (tone === 'success') return CheckCircleOutlined;
|
||||
return InfoCircleOutlined;
|
||||
}
|
||||
|
||||
function toneLabel(tone: Tone) {
|
||||
if (tone === 'urgent') return 'فوری';
|
||||
if (tone === 'warning') return 'هشدار';
|
||||
if (tone === 'success') return 'موفق';
|
||||
return 'اطلاع';
|
||||
}
|
||||
|
||||
function actionLabel(tone: Tone) {
|
||||
if (tone === 'urgent') return 'اقدام';
|
||||
if (tone === 'warning') return 'بررسی';
|
||||
return 'مشاهده';
|
||||
}
|
||||
|
||||
function rowClass(tone: Tone) {
|
||||
if (tone === 'urgent') return 'border-rose-200/80 bg-rose-50/50 hover:bg-rose-50';
|
||||
if (tone === 'warning') return 'border-amber-200/80 bg-amber-50/50 hover:bg-amber-50';
|
||||
if (tone === 'success') return 'border-emerald-200/70 bg-emerald-50/40 hover:bg-emerald-50/80';
|
||||
return 'border-slate-200/80 bg-slate-50/70 hover:bg-slate-100/80';
|
||||
}
|
||||
|
||||
function barClass(tone: Tone) {
|
||||
if (tone === 'urgent') return 'bg-rose-500';
|
||||
if (tone === 'warning') return 'bg-amber-500';
|
||||
if (tone === 'success') return 'bg-emerald-500';
|
||||
return 'bg-blue-500';
|
||||
}
|
||||
|
||||
function iconWrapClass(tone: Tone) {
|
||||
if (tone === 'urgent') return 'bg-rose-100 text-rose-600';
|
||||
if (tone === 'warning') return 'bg-amber-100 text-amber-600';
|
||||
if (tone === 'success') return 'bg-emerald-100 text-emerald-600';
|
||||
return 'bg-blue-100 text-blue-600';
|
||||
}
|
||||
|
||||
function badgeClass(tone: Tone) {
|
||||
if (tone === 'urgent') return 'bg-rose-100 text-rose-700';
|
||||
if (tone === 'warning') return 'bg-amber-100 text-amber-700';
|
||||
if (tone === 'success') return 'bg-emerald-100 text-emerald-700';
|
||||
return 'bg-blue-100 text-blue-700';
|
||||
}
|
||||
|
||||
function actionClass(tone: Tone) {
|
||||
if (tone === 'urgent') return 'text-rose-600 group-hover:text-rose-700';
|
||||
if (tone === 'warning') return 'text-amber-600 group-hover:text-amber-700';
|
||||
if (tone === 'success') return 'text-emerald-600 group-hover:text-emerald-700';
|
||||
return 'text-blue-600 group-hover:text-blue-700';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="rows.length"
|
||||
class="bg-white rounded-2xl border border-slate-200/80 p-5 shadow-sm flex flex-col h-[330px]"
|
||||
>
|
||||
<header class="flex items-center justify-between gap-3 pb-3 mb-3 border-b border-slate-100 shrink-0">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<span class="relative flex h-2.5 w-2.5 shrink-0" aria-hidden="true">
|
||||
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75" />
|
||||
<span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-rose-500" />
|
||||
</span>
|
||||
<div class="min-w-0">
|
||||
<h3 class="m-0 font-bold text-slate-800 text-base leading-6">نیازمند توجه</h3>
|
||||
<p class="m-0 mt-0.5 text-xs text-slate-400 truncate">
|
||||
موارد با اولویت بالاتر اول آمدهاند
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5 shrink-0">
|
||||
<span
|
||||
v-if="urgentCount"
|
||||
class="text-[11px] font-bold bg-rose-50 text-rose-600 border border-rose-200/70 px-2 py-0.5 rounded-full"
|
||||
>
|
||||
{{ toFaDigits(urgentCount) }} فوری
|
||||
</span>
|
||||
<span
|
||||
v-if="warningCount"
|
||||
class="text-[11px] font-bold bg-amber-50 text-amber-700 border border-amber-200/70 px-2 py-0.5 rounded-full"
|
||||
>
|
||||
{{ toFaDigits(warningCount) }} هشدار
|
||||
</span>
|
||||
<span class="text-[11px] font-semibold text-slate-500 bg-slate-100 px-2 py-0.5 rounded-full">
|
||||
{{ toFaDigits(rows.length) }} مورد
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="flex-1 overflow-y-auto space-y-2 pe-1 min-h-0">
|
||||
<RouterLink
|
||||
v-for="item in rows"
|
||||
:key="item.key"
|
||||
:to="item.link"
|
||||
class="group relative overflow-hidden rounded-xl border px-3 py-2.5 flex items-center gap-3 transition-all"
|
||||
:class="rowClass(item.tone)"
|
||||
>
|
||||
<span
|
||||
class="absolute inset-y-0 right-0 w-1 rounded-s-full"
|
||||
:class="barClass(item.tone)"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<span
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 text-sm"
|
||||
:class="iconWrapClass(item.tone)"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="toneIcon(item.tone)" />
|
||||
</span>
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<h4 class="m-0 font-bold text-[13px] text-slate-800 leading-5 truncate">
|
||||
{{ item.title }}
|
||||
</h4>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span
|
||||
class="text-[10px] font-bold px-1.5 py-0.5 rounded shrink-0"
|
||||
:class="badgeClass(item.tone)"
|
||||
>
|
||||
{{ toneLabel(item.tone) }}
|
||||
</span>
|
||||
<span v-if="item.subtitle" class="text-[11px] text-slate-500 truncate">
|
||||
{{ item.subtitle }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="shrink-0 flex items-center gap-1 text-[11px] font-semibold"
|
||||
:class="actionClass(item.tone)"
|
||||
>
|
||||
<span class="opacity-0 group-hover:opacity-100 transition-opacity hidden sm:inline">
|
||||
{{ actionLabel(item.tone) }}
|
||||
</span>
|
||||
<LeftOutlined class="text-slate-400 group-hover:-translate-x-0.5 transition-transform" />
|
||||
</div>
|
||||
</RouterLink>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,10 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { GiftOutlined } from '@ant-design/icons-vue';
|
||||
import {
|
||||
Button as AButton,
|
||||
Flex as AFlex,
|
||||
List as AList,
|
||||
Modal as AModal,
|
||||
Space as ASpace,
|
||||
Tag as ATag,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { UiModal } from '@/components/ui';
|
||||
import SmsComposeModal from '@/components/SmsComposeModal.vue';
|
||||
|
||||
type BirthdayItem = {
|
||||
@@ -28,6 +36,10 @@ type BirthdayMonth = {
|
||||
const data = ref<BirthdayMonth | null>(null);
|
||||
const listOpen = ref(false);
|
||||
const smsTarget = ref<BirthdayItem | null>(null);
|
||||
const { Text: ATypographyText } = Typography;
|
||||
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
|
||||
const groups = computed(() => {
|
||||
const map = new Map<number, BirthdayItem[]>();
|
||||
@@ -54,63 +66,78 @@ onMounted(async () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="data" class="birthdays">
|
||||
<div class="head">
|
||||
<span class="ico"><UiIcon name="gift" :size="18" /></span>
|
||||
<div>
|
||||
<strong>تولدهای {{ data.monthName }}</strong>
|
||||
<p>{{ toFaDigits(data.total) }} مشتری این ماه تولد دارند</p>
|
||||
</div>
|
||||
</div>
|
||||
<section v-if="data" class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm">
|
||||
<a-flex align="center" wrap="wrap" gap="middle" justify="space-between">
|
||||
<a-flex align="center" gap="middle">
|
||||
<a-typography-text type="secondary"><GiftOutlined /></a-typography-text>
|
||||
<div>
|
||||
<a-typography-text strong>تولدهای {{ data.monthName }}</a-typography-text>
|
||||
<br />
|
||||
<a-typography-text type="secondary">
|
||||
{{ toFaDigits(data.total) }} مشتری این ماه تولد دارند
|
||||
</a-typography-text>
|
||||
</div>
|
||||
</a-flex>
|
||||
|
||||
<div class="chips">
|
||||
<RouterLink
|
||||
v-for="person in data.preview"
|
||||
:key="person.id"
|
||||
class="chip"
|
||||
:title="person.fullName"
|
||||
:to="{ name: 'person-detail', params: { id: person.id } }"
|
||||
>
|
||||
<b>{{ toFaDigits(person.day) }}</b>
|
||||
<span>{{ person.fullName }}</span>
|
||||
</RouterLink>
|
||||
</div>
|
||||
<button type="button" class="more" @click="listOpen = true">
|
||||
{{ data.total > data.preview.length ? 'همه' : 'فهرست' }}
|
||||
</button>
|
||||
|
||||
<UiModal :open="listOpen" :title="`تولدهای ${data.monthName}`" @close="listOpen = false">
|
||||
<div class="days">
|
||||
<section
|
||||
v-for="[day, people] in groups"
|
||||
:key="day"
|
||||
class="day"
|
||||
:class="{ past: day < data.today, today: day === data.today }"
|
||||
<a-space wrap>
|
||||
<RouterLink
|
||||
v-for="person in data.preview"
|
||||
:key="person.id"
|
||||
:to="{ name: 'person-detail', params: { id: person.id } }"
|
||||
>
|
||||
<h3>
|
||||
<b>{{ toFaDigits(day) }}</b>
|
||||
<span>{{ data.monthName }}</span>
|
||||
<em v-if="day < data.today">گذشته</em>
|
||||
<em v-else-if="day === data.today">امروز</em>
|
||||
</h3>
|
||||
<ul>
|
||||
<li v-for="person in people" :key="person.id">
|
||||
<RouterLink :to="{ name: 'person-detail', params: { id: person.id } }" @click="listOpen = false">
|
||||
{{ person.fullName }}
|
||||
</RouterLink>
|
||||
<button
|
||||
type="button"
|
||||
class="sms"
|
||||
:disabled="!person.mobile"
|
||||
@click="openSms(person)"
|
||||
>
|
||||
{{ person.mobile ? 'پیامک تبریک' : 'بدون شماره' }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</UiModal>
|
||||
<a-tag>
|
||||
{{ toFaDigits(person.day) }} — {{ person.fullName }}
|
||||
</a-tag>
|
||||
</RouterLink>
|
||||
<a-button type="link" @click="listOpen = true">
|
||||
{{ data.total > data.preview.length ? 'همه' : 'فهرست' }}
|
||||
</a-button>
|
||||
</a-space>
|
||||
</a-flex>
|
||||
|
||||
<a-modal
|
||||
v-model:open="listOpen"
|
||||
:title="`تولدهای ${data.monthName}`"
|
||||
:footer="null"
|
||||
destroy-on-close
|
||||
>
|
||||
<a-list item-layout="vertical" :data-source="groups">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
<a-tag v-if="item[0] < data!.today">گذشته</a-tag>
|
||||
<a-tag v-else-if="item[0] === data!.today" color="processing">امروز</a-tag>
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<template #title>
|
||||
{{ toFaDigits(item[0]) }} {{ data!.monthName }}
|
||||
</template>
|
||||
</a-list-item-meta>
|
||||
<a-list :data-source="item[1]">
|
||||
<template #renderItem="{ item: person }">
|
||||
<a-list-item>
|
||||
<RouterLink
|
||||
:to="{ name: 'person-detail', params: { id: person.id } }"
|
||||
@click="listOpen = false"
|
||||
>
|
||||
{{ person.fullName }}
|
||||
</RouterLink>
|
||||
<template #actions>
|
||||
<a-button
|
||||
type="link"
|
||||
:disabled="!person.mobile"
|
||||
@click="openSms(person)"
|
||||
>
|
||||
{{ person.mobile ? 'پیامک تبریک' : 'بدون شماره' }}
|
||||
</a-button>
|
||||
</template>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
</a-modal>
|
||||
|
||||
<SmsComposeModal
|
||||
nest
|
||||
@@ -126,289 +153,3 @@ onMounted(async () => {
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.birthdays {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
background:
|
||||
linear-gradient(90deg, rgba(255, 255, 255, 0.35), transparent 42%),
|
||||
linear-gradient(100deg, var(--accent-subtle) 0%, #fff 58%, #fff7f4 100%);
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 22%, #fff);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 6px 18px rgba(15, 118, 110, 0.05);
|
||||
padding: 0.55rem 0.75rem;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ico {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 10px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #fff;
|
||||
color: #e11d48;
|
||||
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 18%, #fff);
|
||||
}
|
||||
|
||||
.head strong {
|
||||
display: block;
|
||||
color: var(--accent-deep);
|
||||
font-size: 0.88rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.head p {
|
||||
margin: 0.05rem 0 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chips {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
flex-wrap: nowrap;
|
||||
gap: 0.35rem;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
max-width: 11.5rem;
|
||||
min-width: 0;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 24%, #fff);
|
||||
background: rgba(255, 255, 255, 0.86);
|
||||
color: #134e4a;
|
||||
padding: 0.22rem 0.55rem 0.22rem 0.28rem;
|
||||
text-decoration: none;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.chip b {
|
||||
flex-shrink: 0;
|
||||
font-weight: 700;
|
||||
font-size: 0.72rem;
|
||||
color: var(--accent-deep);
|
||||
background: var(--accent-soft);
|
||||
border-radius: 999px;
|
||||
padding: 0.12rem 0.38rem;
|
||||
}
|
||||
|
||||
.chip span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.more {
|
||||
flex-shrink: 0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
padding: 0.32rem 0.7rem;
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.more:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.days {
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
max-height: 62vh;
|
||||
overflow: auto;
|
||||
padding-inline-end: 0.15rem;
|
||||
}
|
||||
|
||||
.day {
|
||||
background: #fff;
|
||||
border: 1px solid #e7eef2;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.day h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin: 0;
|
||||
padding: 0.55rem 0.8rem;
|
||||
background: var(--accent-subtle);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--accent) 16%, #fff);
|
||||
font-size: 0.86rem;
|
||||
font-weight: 600;
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.day h3 b {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 1.7rem;
|
||||
height: 1.7rem;
|
||||
padding: 0 0.3rem;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.day em {
|
||||
margin-inline-start: auto;
|
||||
font-style: normal;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
color: #94a3b8;
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 0.1rem 0.45rem;
|
||||
}
|
||||
|
||||
.day.today h3 {
|
||||
background: color-mix(in srgb, var(--accent-soft) 70%, #fff);
|
||||
}
|
||||
|
||||
.day.today em {
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.day.past {
|
||||
opacity: 0.82;
|
||||
}
|
||||
|
||||
.day ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.day li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.62rem 0.85rem;
|
||||
border-top: 1px solid #eef2f6;
|
||||
}
|
||||
|
||||
.day li:first-child {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.day a {
|
||||
flex: 1 1 auto;
|
||||
color: #0f172a;
|
||||
text-decoration: none;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.day a:hover {
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.sms {
|
||||
flex-shrink: 0;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 35%, #fff);
|
||||
background: #fff;
|
||||
color: var(--accent-deep);
|
||||
border-radius: 999px;
|
||||
padding: 0.28rem 0.65rem;
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sms:hover:not(:disabled) {
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
|
||||
.sms:disabled {
|
||||
border-color: #e2e8f0;
|
||||
color: #94a3b8;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.lead {
|
||||
margin: 0 0 0.6rem;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.err,
|
||||
.ok {
|
||||
margin: 0.55rem 0 0;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.err {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.ok {
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.birthdays {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.45rem 0.6rem;
|
||||
}
|
||||
|
||||
.head {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.head p {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.more {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
}
|
||||
|
||||
.chips {
|
||||
grid-column: 1 / -1;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.chips::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.day li {
|
||||
gap: 0.45rem;
|
||||
padding-inline: 0.7rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardSeriesPointDto } from '@mento/shared';
|
||||
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
series: HomeDashboardSeriesPointDto[];
|
||||
}>();
|
||||
|
||||
const points = computed(() => props.series);
|
||||
const hasData = computed(() => points.value.some((p) => p.value > 0));
|
||||
const total = computed(() => points.value.reduce((a, p) => a + p.value, 0));
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 450,
|
||||
grid: { top: 36, right: 12, bottom: 28, left: 12, containLabel: true },
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
|
||||
formatter: (params) => {
|
||||
const row = Array.isArray(params) ? params[0] : params;
|
||||
const point = points.value[row.dataIndex ?? 0];
|
||||
if (!point) return '';
|
||||
return `${point.monthLabel}<br/><strong>${toFaDigits(point.value)}</strong> مشتری جدید`;
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: points.value.map((p) => p.monthLabel),
|
||||
axisLine: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLabel: {
|
||||
color: '#94a3b8',
|
||||
fontFamily: 'IRANSans, Tahoma, sans-serif',
|
||||
fontSize: 11,
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
min: 0,
|
||||
minInterval: 1,
|
||||
...(hasData.value ? {} : { max: 1 }),
|
||||
splitLine: { lineStyle: { color: '#e5e7eb', type: 'dashed' } },
|
||||
axisLabel: { show: false },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'bar',
|
||||
data: points.value.map((p) => p.value),
|
||||
barMaxWidth: 32,
|
||||
itemStyle: {
|
||||
color: {
|
||||
type: 'linear',
|
||||
x: 0,
|
||||
y: 0,
|
||||
x2: 0,
|
||||
y2: 1,
|
||||
colorStops: [
|
||||
{ offset: 0, color: '#34d399' },
|
||||
{ offset: 1, color: '#059669' },
|
||||
],
|
||||
},
|
||||
borderRadius: [8, 8, 0, 0],
|
||||
},
|
||||
label: {
|
||||
show: true,
|
||||
position: 'top',
|
||||
color: '#64748b',
|
||||
fontFamily: 'IRANSans, Tahoma, sans-serif',
|
||||
fontSize: 11,
|
||||
formatter: (p) => toFaDigits(Number(p.value ?? 0)),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
data: points.value.map((p) => p.value),
|
||||
smooth: 0.35,
|
||||
symbol: 'none',
|
||||
lineStyle: { color: '#0f766e', width: 2, opacity: 0.55 },
|
||||
},
|
||||
],
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="font-bold text-slate-800 text-base">روند رشد مشتریان</h3>
|
||||
<span v-if="hasData" class="text-xs font-bold bg-emerald-50 text-emerald-700 px-2.5 py-1 rounded-lg">
|
||||
{{ toFaDigits(total) }} در ۱۲ ماه
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-56">
|
||||
<UiChart :option="option" height="224px" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardSalesSummaryDto } from '@mento/shared';
|
||||
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
summary: HomeDashboardSalesSummaryDto;
|
||||
formatAmount: (value: number) => string;
|
||||
}>();
|
||||
|
||||
const slices = computed(() => [
|
||||
{ name: 'باز', value: props.summary.openCount, color: '#3b82f6' },
|
||||
{ name: 'برنده', value: props.summary.wonCount, color: '#10b981' },
|
||||
{ name: 'باخته', value: props.summary.lostCount, color: '#f43f5e' },
|
||||
]);
|
||||
|
||||
const total = computed(() => slices.value.reduce((a, s) => a + s.value, 0));
|
||||
const hasData = computed(() => total.value > 0);
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 400,
|
||||
color: slices.value.map((s) => s.color),
|
||||
tooltip: {
|
||||
trigger: 'item',
|
||||
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
|
||||
formatter: (p) => {
|
||||
const item = Array.isArray(p) ? p[0] : p;
|
||||
return `${item.name}<br/>${toFaDigits(Number(item.value ?? 0))} — ${toFaDigits(item.percent ?? 0)}٪`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'pie',
|
||||
radius: ['58%', '82%'],
|
||||
center: ['50%', '50%'],
|
||||
silent: !hasData.value,
|
||||
avoidLabelOverlap: true,
|
||||
itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
|
||||
label: { show: false },
|
||||
labelLine: { show: false },
|
||||
data: hasData.value
|
||||
? slices.value.map((s) => ({ name: s.name, value: s.value }))
|
||||
: [{ name: '', value: 1, itemStyle: { color: '#e5e7eb' } }],
|
||||
},
|
||||
],
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full flex flex-col">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="!m-0 !leading-6 font-bold text-slate-800 text-base">وضعیت معاملات</h3>
|
||||
<span class="text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200/60 px-2.5 py-1 rounded-lg">
|
||||
نرخ برد {{ toFaDigits(summary.winRate) }}٪
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col sm:flex-row items-center gap-4">
|
||||
<div class="w-full sm:w-[48%] sm:max-w-[240px] shrink-0">
|
||||
<div class="relative w-full aspect-square">
|
||||
<UiChart :option="option" height="100%" />
|
||||
<div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
|
||||
<span class="text-2xl font-black text-slate-800 leading-none">{{ toFaDigits(total) }}</span>
|
||||
<span class="text-xs text-slate-400 mt-1">معامله کل</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="w-full sm:flex-1 min-w-0 space-y-2.5">
|
||||
<div class="p-3 rounded-xl bg-slate-50/80 border border-slate-100 flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs font-bold text-slate-700">باز</div>
|
||||
<div class="text-[11px] text-slate-400">در جریان</div>
|
||||
</div>
|
||||
<div class="text-left">
|
||||
<div class="text-sm font-black text-slate-800">{{ toFaDigits(summary.openCount) }}</div>
|
||||
<div class="text-xs text-slate-500">{{ formatAmount(summary.openAmount) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-3 rounded-xl bg-emerald-50/50 border border-emerald-100 flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs font-bold text-emerald-900">برنده (۱۲ ماه)</div>
|
||||
<div class="text-[11px] text-emerald-600/80">تکمیل موفق</div>
|
||||
</div>
|
||||
<div class="text-left">
|
||||
<div class="text-sm font-black text-emerald-700">{{ toFaDigits(summary.wonCount) }}</div>
|
||||
<div class="text-xs text-emerald-600">{{ formatAmount(summary.wonAmount) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-3 rounded-xl bg-rose-50/40 border border-rose-100 flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs font-bold text-rose-900">باخته (۱۲ ماه)</div>
|
||||
<div class="text-[11px] text-rose-500">لغو یا عدم توافق</div>
|
||||
</div>
|
||||
<div class="text-left">
|
||||
<div class="text-sm font-black text-rose-600">{{ toFaDigits(summary.lostCount) }}</div>
|
||||
<div class="text-xs text-rose-500">{{ formatAmount(summary.lostAmount) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Empty as AEmpty, Progress as AProgress } from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardFunnelStageDto } from '@mento/shared';
|
||||
|
||||
const props = defineProps<{
|
||||
funnel: HomeDashboardFunnelStageDto[];
|
||||
formatAmount: (value: number) => string;
|
||||
}>();
|
||||
|
||||
const rows = computed(() => props.funnel);
|
||||
const hasData = computed(() => rows.value.some((r) => r.count > 0));
|
||||
const openTotal = computed(() => rows.value.reduce((a, r) => a + r.count, 0));
|
||||
|
||||
function share(count: number) {
|
||||
if (!openTotal.value) return 0;
|
||||
return Math.round((count / openTotal.value) * 100);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="font-bold text-slate-800 text-base">قیف فروش باز</h3>
|
||||
<span v-if="hasData" class="text-xs font-semibold text-slate-500">
|
||||
{{ toFaDigits(openTotal) }} معامله باز
|
||||
</span>
|
||||
</div>
|
||||
<a-empty v-if="!hasData" description="معاملهٔ بازی در مسیر فروش نیست" />
|
||||
<div v-else class="space-y-4">
|
||||
<div v-for="row in rows" :key="row.stageId ?? row.stageName">
|
||||
<div class="flex items-center justify-between gap-2 mb-1">
|
||||
<span class="text-xs font-bold text-slate-700">{{ row.stageName }}</span>
|
||||
<span class="text-xs font-semibold text-slate-500">
|
||||
{{ toFaDigits(row.count) }} · {{ toFaDigits(share(row.count)) }}٪
|
||||
</span>
|
||||
</div>
|
||||
<a-progress :percent="share(row.count)" :show-info="false" stroke-color="#10b981" />
|
||||
<div class="text-[11px] text-slate-400">{{ formatAmount(row.amount) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,16 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import MentoAiAvatar from '@/components/brand/MentoAiAvatar.vue';
|
||||
import { brand, type HomeDashboardAlertDto } from '@mento/shared';
|
||||
import { SearchOutlined, SendOutlined } from '@ant-design/icons-vue';
|
||||
import {
|
||||
Button as AButton,
|
||||
Input as AInput,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import { brand } from '@mento/shared';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
const props = defineProps<{
|
||||
greeting: string;
|
||||
firstName: string;
|
||||
userInitial: string;
|
||||
alerts: HomeDashboardAlertDto[];
|
||||
askQuery: string;
|
||||
asking?: boolean;
|
||||
askAnswer?: string;
|
||||
@@ -24,438 +26,218 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const auth = useAuthStore();
|
||||
const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyParagraph } =
|
||||
Typography;
|
||||
|
||||
type HeroChip = {
|
||||
key: string;
|
||||
tone: HomeDashboardAlertDto['tone'];
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
const chips = computed<HeroChip[]>(() =>
|
||||
props.alerts.slice(0, 3).map((a) => {
|
||||
const parts = a.text.split(/\s*[—\-–]\s*|\n/);
|
||||
const title = parts[0]?.trim() || a.text;
|
||||
const subtitle = parts.slice(1).join(' ').trim() || undefined;
|
||||
return {
|
||||
key: a.key,
|
||||
tone: a.tone,
|
||||
title,
|
||||
subtitle,
|
||||
link: a.link || '/',
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
function alertIcon(tone: string) {
|
||||
if (tone === 'urgent') return 'fire' as const;
|
||||
if (tone === 'warning') return 'warning' as const;
|
||||
if (tone === 'success') return 'trend' as const;
|
||||
return 'sparkle' as const;
|
||||
}
|
||||
/** فقط عکس واقعی کاربر؛ پیشفرض عمومی را نشان نده */
|
||||
const hasCustomPhoto = computed(() => Boolean(auth.user?.hasAvatar));
|
||||
|
||||
const shortcutLabel = computed(() =>
|
||||
typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.platform)
|
||||
? '⌘K'
|
||||
: 'Ctrl+K',
|
||||
);
|
||||
|
||||
const statusMessage = computed(() => {
|
||||
if (props.asking) return props.statusText || 'در حال پاسخ…';
|
||||
if (props.askError) return props.askError;
|
||||
if (props.askAnswer) return props.askAnswer;
|
||||
return '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="hero">
|
||||
<div class="hero-surface" aria-hidden="true">
|
||||
<div class="hero-glow" />
|
||||
<div class="hero-mist" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="home-hero relative overflow-hidden rounded-2xl border border-emerald-300/50 shadow-sm">
|
||||
<!-- base gradient -->
|
||||
<div class="home-hero__gradient pointer-events-none absolute inset-0" aria-hidden="true" />
|
||||
<!-- geometric pattern -->
|
||||
<div class="home-hero__pattern pointer-events-none absolute inset-0" aria-hidden="true" />
|
||||
<!-- soft orbs -->
|
||||
<div
|
||||
class="pointer-events-none absolute -left-20 -top-24 h-52 w-52 rounded-full bg-emerald-400/20 blur-3xl"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
class="pointer-events-none absolute -right-16 -bottom-20 h-48 w-48 rounded-full bg-teal-500/15 blur-3xl"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<div class="hero-body">
|
||||
<div class="hero-greet">
|
||||
<span class="hero-avatar">
|
||||
<img :src="auth.avatarSrc" :alt="firstName" width="72" height="72" />
|
||||
<i class="online" />
|
||||
</span>
|
||||
<div class="greet-text">
|
||||
<h1>{{ greeting }} {{ firstName }} 👋</h1>
|
||||
<p v-if="chips.length">{{ brand.nameFa }} اینا رو برات پیدا کرده</p>
|
||||
<p v-else>از {{ brand.nameFa }} بپرس یا کار امروز را شروع کن</p>
|
||||
<div
|
||||
class="relative flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-4 p-4 sm:p-5"
|
||||
>
|
||||
<div class="flex items-center gap-3.5 min-w-0">
|
||||
<div class="home-hero__identity relative shrink-0" :aria-label="firstName">
|
||||
<div class="home-hero__frame">
|
||||
<img
|
||||
v-if="hasCustomPhoto"
|
||||
:src="auth.avatarSrc"
|
||||
:alt="firstName"
|
||||
class="home-hero__photo"
|
||||
/>
|
||||
<span v-else class="home-hero__monogram" aria-hidden="true">
|
||||
{{ userInitial }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="home-hero__online" title="آنلاین" aria-hidden="true" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="m-0 text-[11px] font-semibold tracking-wide text-emerald-700/80">
|
||||
{{ brand.nameFa }}
|
||||
</p>
|
||||
<a-typography-title
|
||||
:level="4"
|
||||
class="!m-0 !mt-0.5 !text-slate-800 !text-lg sm:!text-xl !font-extrabold !leading-7 truncate"
|
||||
>
|
||||
{{ greeting }}، {{ firstName }}
|
||||
</a-typography-title>
|
||||
<a-typography-text class="!text-slate-500 !text-sm !mt-0.5 block">
|
||||
از دادهها بپرسید یا کار امروز را از همینجا شروع کنید
|
||||
</a-typography-text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="chips.length" class="hero-chips">
|
||||
<RouterLink
|
||||
v-for="chip in chips"
|
||||
:key="chip.key"
|
||||
class="chip"
|
||||
:class="`chip-${chip.tone}`"
|
||||
:to="chip.link"
|
||||
<div
|
||||
class="flex items-center gap-2 w-full lg:max-w-xl bg-white border border-white/80 rounded-2xl px-3 py-2 shadow-md shadow-emerald-900/5 focus-within:border-emerald-300 focus-within:ring-2 focus-within:ring-emerald-200/70 transition"
|
||||
>
|
||||
<span class="chip-ico"><UiIcon :name="alertIcon(chip.tone)" :size="13" /></span>
|
||||
<span class="chip-text">
|
||||
<strong>{{ chip.title }}</strong>
|
||||
<small v-if="chip.subtitle">{{ chip.subtitle }}</small>
|
||||
<span
|
||||
class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<SearchOutlined />
|
||||
</span>
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<div class="hero-ask-wrap">
|
||||
<form class="hero-ask" @submit.prevent="emit('ask')">
|
||||
<UiIcon name="sparkle" :size="18" class="ask-ico" />
|
||||
<input
|
||||
<a-input
|
||||
id="home-hero-ask"
|
||||
:value="askQuery"
|
||||
type="search"
|
||||
:placeholder="brand.askPlaceholderFa"
|
||||
:disabled="asking"
|
||||
@input="emit('update:askQuery', ($event.target as HTMLInputElement).value)"
|
||||
:bordered="false"
|
||||
class="flex-1 !bg-transparent"
|
||||
@update:value="emit('update:askQuery', $event)"
|
||||
@press-enter="emit('ask')"
|
||||
/>
|
||||
<kbd>{{ shortcutLabel }}</kbd>
|
||||
<button type="submit" class="ask-send" aria-label="ارسال" :disabled="asking">
|
||||
<UiIcon name="send" :size="15" />
|
||||
</button>
|
||||
</form>
|
||||
<p v-if="asking" class="hero-ask-status">{{ statusText || 'در حال پاسخ…' }}</p>
|
||||
<p v-else-if="askError" class="hero-ask-status err">{{ askError }}</p>
|
||||
<p v-else-if="askAnswer" class="hero-ask-status">{{ askAnswer }}</p>
|
||||
<kbd
|
||||
class="hidden sm:inline-flex items-center text-[11px] font-sans text-slate-400 bg-slate-50 px-2 py-1 rounded-lg border border-slate-200 shrink-0"
|
||||
>
|
||||
{{ shortcutLabel }}
|
||||
</kbd>
|
||||
<a-button
|
||||
type="primary"
|
||||
shape="round"
|
||||
:disabled="asking"
|
||||
:loading="asking"
|
||||
aria-label="ارسال"
|
||||
@click="emit('ask')"
|
||||
>
|
||||
<template #icon><SendOutlined /></template>
|
||||
<span class="hidden sm:inline">بپرس</span>
|
||||
</a-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MentoAiAvatar class="hero-bot" :size="156" />
|
||||
</header>
|
||||
<div
|
||||
v-if="statusMessage"
|
||||
class="rounded-xl border px-3.5 py-2.5"
|
||||
:class="
|
||||
askError
|
||||
? 'border-rose-200 bg-rose-50/70'
|
||||
: asking
|
||||
? 'border-emerald-200/70 bg-emerald-50/50'
|
||||
: 'border-slate-200 bg-slate-50/80'
|
||||
"
|
||||
>
|
||||
<a-typography-paragraph
|
||||
:type="askError ? 'danger' : 'secondary'"
|
||||
:ellipsis="{ rows: 3 }"
|
||||
class="!mb-0 !text-sm"
|
||||
>
|
||||
{{ statusMessage }}
|
||||
</a-typography-paragraph>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.hero {
|
||||
position: relative;
|
||||
display: grid;
|
||||
/* RTL: body سمت راست، ربات سمت چپ — فضای اضافه برای پاپآپ */
|
||||
grid-template-columns: minmax(0, 1fr) 210px;
|
||||
gap: 0.7rem 1rem;
|
||||
align-items: start;
|
||||
min-height: 0;
|
||||
padding: 0.8rem 1.5rem 0.9rem;
|
||||
border-radius: var(--radius);
|
||||
overflow: visible;
|
||||
color: #fff;
|
||||
background: transparent;
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.hero-surface {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
background-color: #134e4a;
|
||||
background-image:
|
||||
radial-gradient(ellipse 55% 90% at 8% 55%, rgba(103, 232, 249, 0.55) 0%, rgba(45, 212, 191, 0.22) 35%, transparent 68%),
|
||||
radial-gradient(ellipse 50% 80% at 92% 40%, rgba(153, 246, 228, 0.28) 0%, transparent 55%),
|
||||
radial-gradient(ellipse 70% 60% at 45% 30%, rgba(45, 212, 191, 0.18) 0%, transparent 60%),
|
||||
radial-gradient(ellipse 60% 50% at 60% 85%, rgba(15, 23, 42, 0.28) 0%, transparent 55%),
|
||||
.home-hero__gradient {
|
||||
background:
|
||||
linear-gradient(
|
||||
105deg,
|
||||
#0b3d3a 0%,
|
||||
#115e59 22%,
|
||||
#0f766e 48%,
|
||||
#134e4a 72%,
|
||||
#0f3f3c 100%
|
||||
115deg,
|
||||
#ecfdf5 0%,
|
||||
#d1fae5 28%,
|
||||
#ccfbf1 55%,
|
||||
#f0fdfa 78%,
|
||||
#ffffff 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 16px 36px rgba(15, 118, 110, 0.22),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.18),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.hero-glow {
|
||||
position: absolute;
|
||||
width: 320px;
|
||||
height: 320px;
|
||||
border-radius: 999px;
|
||||
inset-inline-end: -70px;
|
||||
top: 40%;
|
||||
transform: translateY(-50%);
|
||||
background:
|
||||
radial-gradient(circle, rgba(165, 243, 252, 0.65) 0%, rgba(34, 211, 238, 0.28) 32%, transparent 68%);
|
||||
filter: blur(8px);
|
||||
pointer-events: none;
|
||||
.home-hero__pattern {
|
||||
opacity: 0.45;
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(16, 185, 129, 0.28) 1px, transparent 0),
|
||||
linear-gradient(
|
||||
135deg,
|
||||
rgba(20, 184, 166, 0.08) 25%,
|
||||
transparent 25%,
|
||||
transparent 50%,
|
||||
rgba(20, 184, 166, 0.08) 50%,
|
||||
rgba(20, 184, 166, 0.08) 75%,
|
||||
transparent 75%,
|
||||
transparent
|
||||
);
|
||||
background-size:
|
||||
18px 18px,
|
||||
28px 28px;
|
||||
mask-image: linear-gradient(90deg, rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.25));
|
||||
}
|
||||
|
||||
.hero-mist {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(ellipse 40% 35% at 25% 20%, rgba(255, 255, 255, 0.14) 0%, transparent 70%),
|
||||
radial-gradient(ellipse 35% 40% at 70% 75%, rgba(204, 251, 241, 0.12) 0%, transparent 70%),
|
||||
radial-gradient(ellipse 50% 45% at 50% 50%, rgba(15, 118, 110, 0.35) 0%, transparent 75%);
|
||||
pointer-events: none;
|
||||
.home-hero__identity {
|
||||
width: 3.25rem;
|
||||
height: 3.25rem;
|
||||
}
|
||||
|
||||
.hero-body,
|
||||
.hero-bot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.hero-body {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.hero-greet {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.9rem;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.greet-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hero-avatar {
|
||||
position: relative;
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
border-radius: 999px;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 8px 18px rgba(15, 23, 42, 0.12);
|
||||
}
|
||||
|
||||
.hero-avatar img {
|
||||
.home-hero__frame {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 1rem;
|
||||
padding: 2px;
|
||||
background: linear-gradient(145deg, #34d399 0%, #0d9488 48%, #059669 100%);
|
||||
box-shadow:
|
||||
0 0 0 3px rgba(255, 255, 255, 0.85),
|
||||
0 8px 18px -10px rgba(4, 120, 87, 0.55);
|
||||
}
|
||||
|
||||
.home-hero__photo,
|
||||
.home-hero__monogram {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: calc(1rem - 2px);
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
border-radius: 999px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.65);
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.online {
|
||||
.home-hero__monogram {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.15rem;
|
||||
font-weight: 800;
|
||||
color: #ecfdf5;
|
||||
background:
|
||||
radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.22), transparent 45%),
|
||||
linear-gradient(160deg, #10b981 0%, #0f766e 100%);
|
||||
letter-spacing: -0.02em;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.home-hero__online {
|
||||
position: absolute;
|
||||
bottom: 3px;
|
||||
inset-inline-start: 3px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
left: -1px;
|
||||
bottom: -1px;
|
||||
width: 0.85rem;
|
||||
height: 0.85rem;
|
||||
border-radius: 999px;
|
||||
background: #22c55e;
|
||||
background: #10b981;
|
||||
border: 2px solid #fff;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.greet-text h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(1.35rem, 2vw, 1.75rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.greet-text p {
|
||||
margin: 0.25rem 0 0;
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.hero-chips {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.4rem;
|
||||
max-width: min(580px, 100%);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-radius: var(--radius);
|
||||
background: #fff;
|
||||
color: #0f172a;
|
||||
text-decoration: none;
|
||||
box-shadow: 0 6px 14px rgba(15, 23, 42, 0.07);
|
||||
}
|
||||
|
||||
.chip-text {
|
||||
display: grid;
|
||||
gap: 0.04rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chip-text strong {
|
||||
font-size: 0.68rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chip-text small {
|
||||
font-size: 0.6rem;
|
||||
color: #64748b;
|
||||
font-weight: 500;
|
||||
line-height: 1.25;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chip-ico {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: var(--radius);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chip-urgent .chip-ico {
|
||||
background: #fee2e2;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.chip-warning .chip-ico {
|
||||
background: #fef3c7;
|
||||
color: #d97706;
|
||||
}
|
||||
|
||||
.chip-success .chip-ico,
|
||||
.chip-info .chip-ico {
|
||||
background: #dcfce7;
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
.hero-ask-wrap {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
max-width: min(520px, 100%);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hero-ask {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
background: #fff;
|
||||
color: #0f172a;
|
||||
border-radius: 999px;
|
||||
padding: 0.45rem 0.45rem 0.45rem 0.9rem;
|
||||
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.1);
|
||||
}
|
||||
|
||||
.ask-ico {
|
||||
color: #14b8a6;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.hero-ask input {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
flex: 1;
|
||||
outline: none;
|
||||
font-size: 0.9rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hero-ask input::placeholder {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.hero-ask kbd {
|
||||
font-size: 0.68rem;
|
||||
color: #94a3b8;
|
||||
background: #f1f5f9;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.14rem 0.38rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ask-send {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ask-send:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.hero-ask-status {
|
||||
margin: 0;
|
||||
padding: 0.55rem 0.85rem;
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
color: #fff;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.7;
|
||||
max-height: 7.5rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.hero-ask-status.err {
|
||||
background: rgba(185, 28, 28, 0.28);
|
||||
}
|
||||
|
||||
.hero-bot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
/* در RTL ستون ربات سمت چپ است؛ end = لبه بیرونی چپ */
|
||||
justify-self: end;
|
||||
align-self: center;
|
||||
margin-inline-start: 0;
|
||||
margin-inline-end: 0.35rem;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.hero {
|
||||
grid-template-columns: minmax(0, 1fr) 160px;
|
||||
}
|
||||
|
||||
.hero-chips {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
max-width: min(420px, 100%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.hero {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
min-height: auto;
|
||||
padding-inline: 0.85rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.hero-bot {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hero-ask kbd {
|
||||
display: none;
|
||||
}
|
||||
box-shadow: 0 0 0 1px rgba(16, 185, 129, 0.25);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,125 +1,97 @@
|
||||
<script setup lang="ts">
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import {
|
||||
CalendarOutlined,
|
||||
CheckCircleOutlined,
|
||||
FundOutlined,
|
||||
RiseOutlined,
|
||||
TeamOutlined,
|
||||
WarningOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import type { Component } from 'vue';
|
||||
import type { HomeDashboardKpiDto } from '@mento/shared';
|
||||
import { currencySuffix } from '@/lib/money';
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
kpis: HomeDashboardKpiDto[];
|
||||
currency: string;
|
||||
formatValue: (key: string, value: number) => string;
|
||||
formatChange: (value: number | null) => string;
|
||||
}>();
|
||||
|
||||
const icons: Record<string, 'calendar' | 'users' | 'briefcase' | 'check'> = {
|
||||
sales: 'calendar',
|
||||
customers: 'users',
|
||||
'open-deals': 'briefcase',
|
||||
followups: 'check',
|
||||
function salesAmount(value: number) {
|
||||
return new Intl.NumberFormat('fa-IR').format(value);
|
||||
}
|
||||
|
||||
function salesUnit() {
|
||||
return currencySuffix(props.currency);
|
||||
}
|
||||
|
||||
const icons: Record<string, Component> = {
|
||||
sales: FundOutlined,
|
||||
customers: TeamOutlined,
|
||||
'open-deals': CalendarOutlined,
|
||||
followups: CheckCircleOutlined,
|
||||
'win-rate': RiseOutlined,
|
||||
overdue: WarningOutlined,
|
||||
};
|
||||
|
||||
const iconTones: Record<string, string> = {
|
||||
sales: '#14b8a6',
|
||||
customers: '#38bdf8',
|
||||
'open-deals': '#fb923c',
|
||||
followups: '#a78bfa',
|
||||
};
|
||||
function pillClass(kpi: HomeDashboardKpiDto) {
|
||||
if (kpi.key === 'overdue') return 'bg-rose-100/70 text-rose-600';
|
||||
if (kpi.changePercent == null) return 'text-slate-400';
|
||||
return kpi.changePercent < 0 ? 'bg-rose-50 text-rose-600' : 'bg-emerald-50 text-emerald-600';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kpi-row">
|
||||
<article v-for="kpi in kpis" :key="kpi.key" class="kpi-card">
|
||||
<div class="kpi-icon" :style="{ color: iconTones[kpi.key] ?? '#14b8a6' }">
|
||||
<UiIcon :name="icons[kpi.key] ?? 'chart'" :size="20" />
|
||||
</div>
|
||||
<div class="kpi-text">
|
||||
<p class="kpi-label">{{ kpi.label }}</p>
|
||||
<strong class="kpi-value">{{ formatValue(kpi.key, kpi.value) }}</strong>
|
||||
<section class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
|
||||
<div
|
||||
v-for="kpi in kpis"
|
||||
:key="kpi.key"
|
||||
class="rounded-2xl p-4 border shadow-sm flex flex-col justify-between transition duration-200 hover:-translate-y-0.5"
|
||||
:class="
|
||||
kpi.key === 'overdue'
|
||||
? 'border-rose-200/70 bg-gradient-to-b from-white to-rose-50/20'
|
||||
: 'bg-white border-slate-200/80'
|
||||
"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<span class="text-xs font-semibold" :class="kpi.key === 'overdue' ? 'text-rose-700' : 'text-slate-500'">
|
||||
{{ kpi.label }}
|
||||
</span>
|
||||
<span
|
||||
v-if="kpi.changePercent != null"
|
||||
class="kpi-change"
|
||||
:class="{ down: kpi.changePercent < 0 }"
|
||||
class="w-8 h-8 rounded-xl flex items-center justify-center"
|
||||
:class="kpi.key === 'overdue' ? 'bg-rose-100/80 text-rose-600' : 'bg-emerald-50 text-emerald-600'"
|
||||
>
|
||||
<span class="arrow">{{ kpi.changePercent >= 0 ? '↑' : '↓' }}</span>
|
||||
{{ formatChange(kpi.changePercent) }} {{ kpi.changeLabel }}
|
||||
<component :is="icons[kpi.key] ?? FundOutlined" />
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
class="!font-bold !text-[24px] !leading-8 tracking-tight"
|
||||
:class="kpi.key === 'overdue' ? 'text-rose-600' : 'text-slate-800'"
|
||||
>
|
||||
<template v-if="kpi.key === 'sales'">
|
||||
<span>{{ salesAmount(kpi.value) }}</span><span class="text-[16px] leading-6 font-semibold ms-1.5">{{ salesUnit() }}</span>
|
||||
</template>
|
||||
<template v-else>{{ formatValue(kpi.key, kpi.value) }}</template>
|
||||
</div>
|
||||
<div
|
||||
v-if="kpi.changePercent != null"
|
||||
class="mt-2.5 inline-flex text-[11px] font-semibold px-2 py-0.5 rounded-md"
|
||||
:class="pillClass(kpi)"
|
||||
>
|
||||
{{ formatChange(kpi.changePercent) }} {{ kpi.changeLabel }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="kpi.key === 'overdue'"
|
||||
class="mt-2.5 inline-flex text-[11px] font-semibold px-2 py-0.5 rounded-md bg-rose-100/70 text-rose-600"
|
||||
>
|
||||
نیازمند اقدام فوری
|
||||
</div>
|
||||
<div v-else class="mt-2.5 text-[11px] font-medium text-slate-400">
|
||||
{{ kpi.changeLabel || '—' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.kpi-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.kpi-card {
|
||||
display: flex;
|
||||
gap: 0.85rem;
|
||||
align-items: flex-start;
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 1.1rem 1.15rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #eef2f7;
|
||||
}
|
||||
|
||||
.kpi-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: var(--radius);
|
||||
background: #f8fafc;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.kpi-label {
|
||||
margin: 0;
|
||||
color: #94a3b8;
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.kpi-value {
|
||||
display: block;
|
||||
margin-top: 0.25rem;
|
||||
font-size: 1.18rem;
|
||||
color: #0f172a;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.kpi-change {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
margin-top: 0.45rem;
|
||||
padding: 0.18rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
background: #dcfce7;
|
||||
color: #16a34a;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.arrow {
|
||||
font-size: 0.82rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.kpi-change.down {
|
||||
background: #fee2e2;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.kpi-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.kpi-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Empty as AEmpty } from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardSliceDto } from '@mento/shared';
|
||||
import UiChart, { CHART_PALETTE, type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
reasons: HomeDashboardSliceDto[];
|
||||
formatAmount: (value: number) => string;
|
||||
}>();
|
||||
|
||||
const rows = computed(() => props.reasons);
|
||||
const hasData = computed(() => rows.value.some((r) => r.count > 0));
|
||||
const total = computed(() => rows.value.reduce((sum, row) => sum + row.count, 0));
|
||||
|
||||
function share(count: number) {
|
||||
if (!total.value) return 0;
|
||||
return Math.round((count / total.value) * 100);
|
||||
}
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 400,
|
||||
color: CHART_PALETTE,
|
||||
tooltip: {
|
||||
trigger: 'item',
|
||||
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
|
||||
formatter: (p) => {
|
||||
const item = Array.isArray(p) ? p[0] : p;
|
||||
const row = rows.value.find((r) => r.label === item.name);
|
||||
const amount =
|
||||
row?.amount != null ? `<br/>${props.formatAmount(row.amount)}` : '';
|
||||
return `${item.name}<br/>${toFaDigits(Number(item.value ?? 0))} — ${toFaDigits(item.percent ?? 0)}٪${amount}`;
|
||||
},
|
||||
},
|
||||
legend: { show: false },
|
||||
series: [
|
||||
{
|
||||
type: 'pie',
|
||||
radius: ['58%', '78%'],
|
||||
center: ['50%', '50%'],
|
||||
itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
|
||||
label: { show: false },
|
||||
data: rows.value.map((r) => ({ name: r.label, value: r.count })),
|
||||
},
|
||||
],
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full flex flex-col">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h3 class="font-bold text-slate-800 text-base">دلایل باخت</h3>
|
||||
<span v-if="hasData" class="text-xs text-slate-400">۱۲ ماه اخیر</span>
|
||||
</div>
|
||||
<a-empty v-if="!hasData" description="معاملهٔ باختهای ثبت نشده" />
|
||||
<template v-else>
|
||||
<div class="relative w-36 h-36 mx-auto">
|
||||
<UiChart :option="option" height="144px" />
|
||||
<div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
|
||||
<span class="text-2xl font-black text-slate-800">{{ toFaDigits(total) }}</span>
|
||||
<span class="text-[11px] text-slate-400">معامله باخته</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2 mt-3">
|
||||
<div
|
||||
v-for="(item, index) in rows"
|
||||
:key="item.label"
|
||||
class="rounded-xl border border-slate-200/70 bg-slate-50 px-2.5 py-2"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span
|
||||
class="w-2 h-2 rounded-full shrink-0"
|
||||
:style="{ background: CHART_PALETTE[index % CHART_PALETTE.length] }"
|
||||
></span>
|
||||
<span class="text-[11px] text-slate-600 truncate">{{ item.label }}</span>
|
||||
</div>
|
||||
<div class="text-sm font-black text-slate-800 mt-1">{{ toFaDigits(share(item.count)) }}٪</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,8 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import {
|
||||
FundOutlined,
|
||||
LeftOutlined,
|
||||
PlusOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { PipelineBoardDto } from '@mento/shared';
|
||||
import {
|
||||
PIPELINE_ACCENT,
|
||||
type PipelineAccent,
|
||||
} from '@/lib/pipeline-board';
|
||||
import HomePanelEmpty from '@/components/dashboard/HomePanelEmpty.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -10,41 +19,100 @@ const props = defineProps<{
|
||||
formatMoney: (amount: number, currency: string) => string;
|
||||
}>();
|
||||
|
||||
type Card = { id: string; name: string; amount: string; when: string };
|
||||
type Col = { id: string; name: string; count: number; cards: Card[] };
|
||||
const ACCENT_CYCLE: PipelineAccent[] = ['green', 'blue', 'orange'];
|
||||
|
||||
function relativeWhen(iso: string | null | undefined) {
|
||||
if (!iso) return '';
|
||||
type Card = {
|
||||
id: string;
|
||||
name: string;
|
||||
initial: string;
|
||||
amount: string;
|
||||
when: string;
|
||||
isToday: boolean;
|
||||
};
|
||||
|
||||
type Col = {
|
||||
id: string;
|
||||
name: string;
|
||||
count: number;
|
||||
totalLabel: string;
|
||||
accent: PipelineAccent;
|
||||
cards: Card[];
|
||||
};
|
||||
|
||||
function relativeWhen(iso: string | null | undefined): { label: string; isToday: boolean } {
|
||||
if (!iso) return { label: '', isToday: false };
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const days = Math.floor(diff / 86400000);
|
||||
if (days <= 0) return 'امروز';
|
||||
if (days === 1) return 'دیروز';
|
||||
return `${toFaDigits(days)} روز پیش`;
|
||||
if (days <= 0) return { label: 'امروز', isToday: true };
|
||||
if (days === 1) return { label: 'دیروز', isToday: false };
|
||||
return { label: `${toFaDigits(days)} روز پیش`, isToday: false };
|
||||
}
|
||||
|
||||
function initialOf(name: string | undefined | null) {
|
||||
const t = (name ?? '').trim();
|
||||
return t ? t.slice(0, 1) : '؟';
|
||||
}
|
||||
|
||||
const cols = computed<Col[]>(() => {
|
||||
const stages = props.board?.stages ?? [];
|
||||
const hasDeals = stages.some((s) => s.deals.length);
|
||||
if (!hasDeals) return [];
|
||||
return stages.slice(0, 3).map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
count: stage.deals.length,
|
||||
cards: stage.deals.slice(0, 2).map((deal) => ({
|
||||
id: deal.id,
|
||||
name: deal.company?.name || deal.person?.fullName || deal.title,
|
||||
amount: deal.amount ? props.formatMoney(deal.amount, deal.currency) : '',
|
||||
when: relativeWhen(deal.updatedAt || deal.createdAt),
|
||||
})),
|
||||
}));
|
||||
|
||||
return stages.slice(0, 3).map((stage, index) => {
|
||||
const accent = ACCENT_CYCLE[index % ACCENT_CYCLE.length]!;
|
||||
const currency = stage.deals[0]?.currency ?? 'IRR';
|
||||
return {
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
count: stage.deals.length,
|
||||
totalLabel:
|
||||
stage.totalAmount > 0 ? props.formatMoney(stage.totalAmount, currency) : '',
|
||||
accent,
|
||||
cards: stage.deals.slice(0, 2).map((deal) => {
|
||||
const name = deal.company?.name || deal.person?.fullName || deal.title;
|
||||
const when = relativeWhen(deal.updatedAt || deal.createdAt);
|
||||
return {
|
||||
id: deal.id,
|
||||
name,
|
||||
initial: initialOf(name),
|
||||
amount: deal.amount ? props.formatMoney(deal.amount, deal.currency) : '',
|
||||
when: when.label,
|
||||
isToday: when.isToday,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
function accentOf(key: PipelineAccent) {
|
||||
return PIPELINE_ACCENT[key];
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="panel">
|
||||
<header class="panel-head">
|
||||
<h2>جریان فروش</h2>
|
||||
<RouterLink :to="{ name: 'pipeline' }">نمایش همه</RouterLink>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-5 sm:p-6 shadow-sm">
|
||||
<header class="flex items-center justify-between gap-3 mb-5">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<div
|
||||
class="w-9 h-9 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<FundOutlined />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="font-bold text-slate-800 text-base m-0">جریان فروش</h3>
|
||||
<p class="text-xs text-slate-400 m-0 mt-0.5">
|
||||
نمای سریع معاملات در مراحل کلیدی
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink
|
||||
:to="{ name: 'pipeline' }"
|
||||
class="shrink-0 inline-flex items-center gap-1 text-xs font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 px-3 py-1.5 rounded-xl transition-colors"
|
||||
>
|
||||
<span>نمایش همه</span>
|
||||
<LeftOutlined />
|
||||
</RouterLink>
|
||||
</header>
|
||||
|
||||
<HomePanelEmpty
|
||||
@@ -54,132 +122,85 @@ const cols = computed<Col[]>(() => {
|
||||
action-label="معامله جدید"
|
||||
:action-to="{ name: 'deal-new' }"
|
||||
/>
|
||||
<div v-else class="mini-pipeline">
|
||||
<div v-for="col in cols" :key="col.id" class="pipe-col">
|
||||
<header>
|
||||
<strong>{{ col.name }} ({{ toFaDigits(col.count) }})</strong>
|
||||
</header>
|
||||
<div class="pipe-cards">
|
||||
<RouterLink
|
||||
v-for="card in col.cards"
|
||||
:key="card.id"
|
||||
class="pipe-card"
|
||||
:to="{ name: 'deal-detail', params: { id: card.id } }"
|
||||
|
||||
<div v-else class="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-5">
|
||||
<article
|
||||
v-for="col in cols"
|
||||
:key="col.id"
|
||||
class="rounded-2xl border border-slate-200/70 bg-slate-50/90 p-4 flex flex-col gap-3 min-w-0"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2 pb-2 border-b border-slate-200/80">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2 min-w-0">
|
||||
<span
|
||||
class="w-2.5 h-2.5 rounded-full shrink-0"
|
||||
:style="{ background: accentOf(col.accent).solid }"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<h4 class="font-bold text-sm text-slate-700 m-0 truncate">{{ col.name }}</h4>
|
||||
</div>
|
||||
<p v-if="col.totalLabel" class="text-[11px] text-slate-400 m-0 mt-1 truncate">
|
||||
مجموع {{ col.totalLabel }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="shrink-0 bg-white border border-slate-200 text-slate-700 text-xs font-bold px-2.5 py-0.5 rounded-full"
|
||||
>
|
||||
<span class="deal-mark">{{ card.name.slice(0, 1) }}</span>
|
||||
<div>
|
||||
<strong>{{ card.name }}</strong>
|
||||
<span v-if="card.amount">{{ card.amount }}</span>
|
||||
<em>{{ card.when }}</em>
|
||||
{{ toFaDigits(col.count) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2.5 flex-1">
|
||||
<RouterLink
|
||||
v-for="item in col.cards"
|
||||
:key="item.id"
|
||||
:to="{ name: 'deal-detail', params: { id: item.id } }"
|
||||
class="group bg-white p-3 rounded-xl border border-slate-200/80 shadow-sm hover:border-emerald-400 hover:shadow transition-all flex items-center gap-3 min-w-0"
|
||||
>
|
||||
<span
|
||||
class="w-9 h-9 rounded-full font-bold text-xs flex items-center justify-center shrink-0 border"
|
||||
:style="{
|
||||
background: accentOf(col.accent).soft,
|
||||
color: accentOf(col.accent).text,
|
||||
borderColor: accentOf(col.accent).border,
|
||||
}"
|
||||
>
|
||||
{{ item.initial }}
|
||||
</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="font-bold text-sm text-slate-800 truncate">{{ item.name }}</div>
|
||||
<div class="text-xs text-slate-500 mt-0.5 truncate">
|
||||
<template v-if="item.amount">
|
||||
<span class="font-medium">{{ item.amount }}</span>
|
||||
<span v-if="item.when" class="text-slate-300 mx-1">·</span>
|
||||
</template>
|
||||
<span
|
||||
v-if="item.when"
|
||||
:class="item.isToday ? 'text-emerald-600 font-semibold' : 'text-slate-400'"
|
||||
>
|
||||
{{ item.when }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</RouterLink>
|
||||
|
||||
<div
|
||||
v-if="!col.cards.length"
|
||||
class="border border-dashed border-slate-200 rounded-xl px-3 py-5 text-center text-xs text-slate-400"
|
||||
>
|
||||
معاملهای در این مرحله نیست
|
||||
</div>
|
||||
|
||||
<RouterLink
|
||||
v-else-if="col.cards.length < 2"
|
||||
:to="{ name: 'deal-new', query: { stageId: col.id } }"
|
||||
class="mt-auto border border-dashed border-slate-200 hover:border-emerald-300 hover:bg-white rounded-xl px-3 py-3 text-center text-xs text-slate-400 hover:text-emerald-700 transition-colors inline-flex items-center justify-center gap-1"
|
||||
>
|
||||
<PlusOutlined />
|
||||
افزودن معامله
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.05rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #eef2f7;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #14b8a6;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.mini-pipeline {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(120px, 1fr));
|
||||
gap: 0.65rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.pipe-col > header {
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.78rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.pipe-cards {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.pipe-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.55rem 0.6rem;
|
||||
border-radius: var(--radius);
|
||||
background: #f8fafc;
|
||||
border: 1px solid #eef2f7;
|
||||
color: inherit;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.pipe-card div {
|
||||
display: grid;
|
||||
gap: 0.1rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pipe-card strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.pipe-card span {
|
||||
color: #94a3b8;
|
||||
font-size: 0.68rem;
|
||||
}
|
||||
|
||||
.pipe-card em {
|
||||
color: #cbd5e1;
|
||||
font-size: 0.66rem;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
.deal-mark {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--radius);
|
||||
background: #ecfdf8;
|
||||
color: #0f766e;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-weight: 600;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.mini-pipeline {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { RouteLocationRaw } from 'vue-router';
|
||||
import { Button as AButton, Empty as AEmpty, Typography } from 'ant-design-vue';
|
||||
|
||||
defineProps<{
|
||||
title: string;
|
||||
@@ -8,70 +9,19 @@ defineProps<{
|
||||
actionLabel: string;
|
||||
actionTo: RouteLocationRaw;
|
||||
}>();
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="empty-card">
|
||||
<div class="art" aria-hidden="true">
|
||||
<svg viewBox="0 0 168 148" fill="none">
|
||||
<rect x="38" y="18" width="92" height="112" rx="16" fill="#E7F6F3" />
|
||||
<rect x="50" y="32" width="68" height="84" rx="10" fill="#fff" />
|
||||
<path d="M62 52h28" stroke="#14b8a6" stroke-width="4" stroke-linecap="round" />
|
||||
<path d="M62 68h36" stroke="#99f6e4" stroke-width="4" stroke-linecap="round" />
|
||||
<path d="M62 84h22" stroke="#99f6e4" stroke-width="4" stroke-linecap="round" />
|
||||
<circle cx="118" cy="112" r="20" fill="#14b8a6" />
|
||||
<path d="M118 104v16M110 112h16" stroke="#fff" stroke-width="3" stroke-linecap="round" />
|
||||
</svg>
|
||||
</div>
|
||||
<strong>{{ title }}</strong>
|
||||
<p>{{ description }}</p>
|
||||
<RouterLink class="cta" :to="actionTo">{{ actionLabel }}</RouterLink>
|
||||
</div>
|
||||
<a-empty :description="null">
|
||||
<template #description>
|
||||
<a-typography-text strong>{{ title }}</a-typography-text>
|
||||
<br />
|
||||
<a-typography-text type="secondary">{{ description }}</a-typography-text>
|
||||
</template>
|
||||
<RouterLink :to="actionTo">
|
||||
<a-button type="primary">{{ actionLabel }}</a-button>
|
||||
</RouterLink>
|
||||
</a-empty>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.empty-card {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
align-content: center;
|
||||
text-align: center;
|
||||
gap: 0.45rem;
|
||||
padding: 0.4rem 0.2rem 0.15rem;
|
||||
}
|
||||
|
||||
.art svg {
|
||||
width: 92px;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
strong {
|
||||
font-size: 0.88rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
max-width: 16rem;
|
||||
color: #94a3b8;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.cta {
|
||||
margin-top: 0.25rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 36px;
|
||||
padding: 0 0.9rem;
|
||||
border-radius: var(--radius);
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, type Component } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import {
|
||||
CalendarOutlined,
|
||||
CheckOutlined,
|
||||
MailOutlined,
|
||||
PhoneOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import {
|
||||
Flex as AFlex,
|
||||
Tag as ATag,
|
||||
Timeline as ATimeline,
|
||||
Typography,
|
||||
theme,
|
||||
} from 'ant-design-vue';
|
||||
import HomePanelEmpty from '@/components/dashboard/HomePanelEmpty.vue';
|
||||
import type { ActivityDto } from '@mento/shared';
|
||||
|
||||
@@ -10,16 +22,21 @@ const props = defineProps<{
|
||||
formatWhen: (value: string | null) => string;
|
||||
}>();
|
||||
|
||||
const { token } = theme.useToken();
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const ATimelineItem = ATimeline.Item;
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
title: string;
|
||||
when: string;
|
||||
typeLabel: string;
|
||||
type: string;
|
||||
tone: 'done' | 'pending' | 'held' | 'late';
|
||||
label: string;
|
||||
};
|
||||
|
||||
const typeLabel: Record<string, string> = {
|
||||
const typeLabelMap: Record<string, string> = {
|
||||
call: 'تماس',
|
||||
meeting: 'جلسه',
|
||||
task: 'وظیفه',
|
||||
@@ -31,23 +48,50 @@ function activityStatus(act: ActivityDto) {
|
||||
if (act.dueAt && new Date(act.dueAt) < new Date()) {
|
||||
return { label: 'عقبافتاده', tone: 'late' as const };
|
||||
}
|
||||
return { label: 'در انتظار پاسخ', tone: 'pending' as const };
|
||||
return { label: 'در انتظار', tone: 'pending' as const };
|
||||
}
|
||||
|
||||
function activityIcon(type: string) {
|
||||
if (type === 'call') return 'phone' as const;
|
||||
if (type === 'meeting') return 'calendar' as const;
|
||||
if (type === 'task') return 'check' as const;
|
||||
return 'mail' as const;
|
||||
function activityIcon(type: string): Component {
|
||||
if (type === 'call') return PhoneOutlined;
|
||||
if (type === 'meeting') return CalendarOutlined;
|
||||
if (type === 'task') return CheckOutlined;
|
||||
return MailOutlined;
|
||||
}
|
||||
|
||||
function tagColor(tone: Row['tone']) {
|
||||
if (tone === 'late') return 'error';
|
||||
if (tone === 'done' || tone === 'held') return 'success';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
function timelineColor(tone: Row['tone']) {
|
||||
if (tone === 'late') return 'red';
|
||||
if (tone === 'done' || tone === 'held') return 'green';
|
||||
return 'blue';
|
||||
}
|
||||
|
||||
function typeBg(type: string) {
|
||||
if (type === 'call') return token.value.colorInfoBg;
|
||||
if (type === 'meeting') return token.value.colorWarningBg;
|
||||
if (type === 'task') return token.value.colorSuccessBg;
|
||||
return token.value.colorFillAlter;
|
||||
}
|
||||
|
||||
function typeFg(type: string) {
|
||||
if (type === 'call') return token.value.colorInfo;
|
||||
if (type === 'meeting') return token.value.colorWarning;
|
||||
if (type === 'task') return token.value.colorSuccess;
|
||||
return token.value.colorTextSecondary;
|
||||
}
|
||||
|
||||
const rows = computed<Row[]>(() =>
|
||||
props.activities.slice(0, 3).map((act) => {
|
||||
props.activities.slice(0, 5).map((act) => {
|
||||
const st = activityStatus(act);
|
||||
return {
|
||||
id: act.id,
|
||||
title: act.title,
|
||||
when: `${typeLabel[act.type] ?? act.type} · ${props.formatWhen(act.dueAt || act.createdAt)}`,
|
||||
when: props.formatWhen(act.dueAt || act.createdAt),
|
||||
typeLabel: typeLabelMap[act.type] ?? act.type,
|
||||
type: act.type,
|
||||
tone: st.tone,
|
||||
label: st.label,
|
||||
@@ -57,11 +101,16 @@ const rows = computed<Row[]>(() =>
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="panel">
|
||||
<header class="panel-head">
|
||||
<h2>فعالیتهای اخیر</h2>
|
||||
<RouterLink :to="{ name: 'activities' }">مشاهده همه</RouterLink>
|
||||
</header>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full w-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="font-bold text-slate-800 text-base">فعالیتهای اخیر</h3>
|
||||
<a-tag v-if="rows.length" :bordered="false">{{ rows.length }}</a-tag>
|
||||
</div>
|
||||
<RouterLink :to="{ name: 'activities' }" class="text-sm font-bold text-emerald-600">
|
||||
مشاهده همه
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<HomePanelEmpty
|
||||
v-if="!rows.length"
|
||||
@@ -70,117 +119,44 @@ const rows = computed<Row[]>(() =>
|
||||
action-label="فعالیت جدید"
|
||||
:action-to="{ name: 'activity-new' }"
|
||||
/>
|
||||
<ul v-else class="activity-list">
|
||||
<li v-for="act in rows" :key="act.id">
|
||||
<span class="act-icon">
|
||||
<UiIcon :name="activityIcon(act.type)" :size="16" />
|
||||
</span>
|
||||
<div class="act-body">
|
||||
<strong>{{ act.title }}</strong>
|
||||
<span>{{ act.when }}</span>
|
||||
</div>
|
||||
<span class="status-pill" :class="act.tone">{{ act.label }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</article>
|
||||
<a-timeline v-else>
|
||||
<a-timeline-item v-for="item in rows" :key="item.id" :color="timelineColor(item.tone)">
|
||||
<a-flex
|
||||
align="flex-start"
|
||||
justify="space-between"
|
||||
:gap="token.marginSM"
|
||||
:style="{
|
||||
padding: `${token.paddingXS}px ${token.paddingSM}px`,
|
||||
borderRadius: `${token.borderRadius}px`,
|
||||
background: token.colorFillAlter,
|
||||
minWidth: 0,
|
||||
}"
|
||||
>
|
||||
<a-flex :gap="token.marginSM" :style="{ minWidth: 0, flex: 1 }">
|
||||
<a-flex
|
||||
align="center"
|
||||
justify="center"
|
||||
:style="{
|
||||
width: '32px',
|
||||
height: '32px',
|
||||
borderRadius: `${token.borderRadius}px`,
|
||||
background: typeBg(item.type),
|
||||
color: typeFg(item.type),
|
||||
flexShrink: 0,
|
||||
}"
|
||||
>
|
||||
<component :is="activityIcon(item.type)" />
|
||||
</a-flex>
|
||||
<a-flex vertical :style="{ minWidth: 0, flex: 1 }">
|
||||
<a-typography-text strong ellipsis>{{ item.title }}</a-typography-text>
|
||||
<a-typography-text type="secondary" ellipsis>
|
||||
{{ item.typeLabel }} · {{ item.when }}
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
<a-tag :color="tagColor(item.tone)" style="flex-shrink: 0">{{ item.label }}</a-tag>
|
||||
</a-flex>
|
||||
</a-timeline-item>
|
||||
</a-timeline>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.05rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #eef2f7;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #14b8a6;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.activity-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.7rem;
|
||||
}
|
||||
|
||||
.activity-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.act-icon {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: var(--radius);
|
||||
background: #ecfdf8;
|
||||
color: #14b8a6;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.act-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 0.12rem;
|
||||
}
|
||||
|
||||
.act-body strong {
|
||||
font-size: 0.84rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.act-body span {
|
||||
color: #94a3b8;
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
.status-pill {
|
||||
font-size: 0.68rem;
|
||||
font-weight: 700;
|
||||
padding: 0.22rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.status-pill.done,
|
||||
.status-pill.held {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.status-pill.pending {
|
||||
background: #dbeafe;
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.status-pill.late {
|
||||
background: #fee2e2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { Segmented as ASegmented } from 'ant-design-vue';
|
||||
import type { HomeDashboardTrendPointDto } from '@mento/shared';
|
||||
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
@@ -10,26 +11,57 @@ const props = defineProps<{
|
||||
formatAmount: (value: number) => string;
|
||||
}>();
|
||||
|
||||
const trend = computed(() => props.trend);
|
||||
const hasTrend = computed(() => trend.value.some((p) => p.amount > 0));
|
||||
const change = computed(() => props.changePercent);
|
||||
type PeriodMonths = 1 | 3 | 6 | 12;
|
||||
|
||||
const period = ref<PeriodMonths>(6);
|
||||
|
||||
const periodOptions = [
|
||||
{ value: 1, label: 'این ماه' },
|
||||
{ value: 3, label: '۳ ماه' },
|
||||
{ value: 6, label: '۶ ماه' },
|
||||
{ value: 12, label: '۱۲ ماه' },
|
||||
];
|
||||
|
||||
const filteredTrend = computed(() => {
|
||||
const all = props.trend;
|
||||
if (!all.length) return [];
|
||||
const n = period.value;
|
||||
return all.slice(-Math.min(n, all.length));
|
||||
});
|
||||
|
||||
const hasTrend = computed(() => filteredTrend.value.some((p) => p.amount > 0));
|
||||
|
||||
/** تغییر آخرین ماه نسبت به ماه قبلِ همان بازه */
|
||||
const periodChange = computed(() => {
|
||||
const rows = filteredTrend.value;
|
||||
if (rows.length < 2) return props.changePercent;
|
||||
const last = rows[rows.length - 1]!.amount;
|
||||
const prev = rows[rows.length - 2]!.amount;
|
||||
if (prev === 0) return last === 0 ? 0 : 100;
|
||||
return Math.round(((last - prev) / Math.abs(prev)) * 1000) / 10;
|
||||
});
|
||||
|
||||
const changeHint = computed(() => {
|
||||
if (period.value === 1) return 'نسبت به ماه قبل';
|
||||
return 'آخرین ماه نسبت به ماه قبل';
|
||||
});
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 400,
|
||||
grid: { top: 28, right: 8, bottom: 28, left: 8, containLabel: true },
|
||||
animationDuration: 450,
|
||||
grid: { top: 36, right: 12, bottom: 28, left: 12, containLabel: true },
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
|
||||
formatter: (params) => {
|
||||
const row = Array.isArray(params) ? params[0] : params;
|
||||
const point = trend.value[row.dataIndex ?? 0];
|
||||
const point = filteredTrend.value[row.dataIndex ?? 0];
|
||||
if (!point) return '';
|
||||
return `${point.monthLabel}<br/>${props.formatAmount(point.amount)}`;
|
||||
return `${point.monthLabel}<br/><strong>${props.formatAmount(point.amount)}</strong>`;
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: trend.value.map((p) => p.monthLabel),
|
||||
data: filteredTrend.value.map((p) => p.monthLabel),
|
||||
boundaryGap: false,
|
||||
axisLine: { show: false },
|
||||
axisTick: { show: false },
|
||||
@@ -43,18 +75,19 @@ const option = computed<UiChartOption>(() => ({
|
||||
type: 'value',
|
||||
min: 0,
|
||||
...(hasTrend.value ? {} : { max: 1 }),
|
||||
splitLine: { lineStyle: { color: '#eef2f7' } },
|
||||
splitLine: { lineStyle: { color: '#e5e7eb', type: 'dashed' } },
|
||||
axisLabel: { show: false },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'line',
|
||||
data: trend.value.map((p) => p.amount),
|
||||
smooth: 0.35,
|
||||
name: 'فروش',
|
||||
data: filteredTrend.value.map((p) => p.amount),
|
||||
smooth: 0.4,
|
||||
symbol: 'circle',
|
||||
symbolSize: 8,
|
||||
itemStyle: { color: '#14b8a6', borderColor: '#fff', borderWidth: 2 },
|
||||
lineStyle: { color: '#14b8a6', width: 3 },
|
||||
symbolSize: period.value === 1 ? 10 : 8,
|
||||
itemStyle: { color: '#10b981', borderColor: '#fff', borderWidth: 2 },
|
||||
lineStyle: { color: '#10b981', width: 3 },
|
||||
areaStyle: {
|
||||
color: {
|
||||
type: 'linear',
|
||||
@@ -63,8 +96,8 @@ const option = computed<UiChartOption>(() => ({
|
||||
x2: 0,
|
||||
y2: 1,
|
||||
colorStops: [
|
||||
{ offset: 0, color: 'rgba(20, 184, 166, 0.28)' },
|
||||
{ offset: 1, color: 'rgba(20, 184, 166, 0)' },
|
||||
{ offset: 0, color: 'rgba(16, 185, 129, 0.28)' },
|
||||
{ offset: 1, color: 'rgba(16, 185, 129, 0)' },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -74,56 +107,22 @@ const option = computed<UiChartOption>(() => ({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="panel">
|
||||
<header class="panel-head">
|
||||
<h2>روند فروش</h2>
|
||||
<span v-if="hasTrend && change != null" class="mini-badge" :class="{ down: change < 0 }">
|
||||
{{ formatChange(change) }} نسبت به ماه قبل
|
||||
</span>
|
||||
</header>
|
||||
<UiChart :option="option" height="210px" />
|
||||
</article>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full flex flex-col">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<h3 class="font-bold text-slate-800 text-base">روند فروش</h3>
|
||||
<span
|
||||
v-if="hasTrend && periodChange != null"
|
||||
class="mt-1 inline-flex text-xs font-bold px-2 py-0.5 rounded-md"
|
||||
:class="periodChange < 0 ? 'text-rose-600 bg-rose-50' : 'text-emerald-600 bg-emerald-50'"
|
||||
>
|
||||
{{ formatChange(periodChange) }} {{ changeHint }}
|
||||
</span>
|
||||
</div>
|
||||
<a-segmented v-model:value="period" :options="periodOptions" />
|
||||
</div>
|
||||
<div class="h-56">
|
||||
<UiChart :option="option" height="224px" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: var(--pad-modal);
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid var(--line);
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.mini-badge {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
color: #16a34a;
|
||||
background: #dcfce7;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.18rem 0.5rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.mini-badge.down {
|
||||
color: #dc2626;
|
||||
background: #fee2e2;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Empty as AEmpty } from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardSourceDto } from '@mento/shared';
|
||||
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
import UiChart, { CHART_PALETTE, type UiChartOption } from '@/components/ui/UiChart.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
sources: HomeDashboardSourceDto[];
|
||||
}>();
|
||||
|
||||
const colors = ['#2563eb', '#14b8a6', '#22c55e', '#fb923c', '#94a3b8'];
|
||||
|
||||
const rows = computed(() => props.sources);
|
||||
const total = computed(() => rows.value.reduce((a, s) => a + s.count, 0));
|
||||
|
||||
const option = computed<UiChartOption>(() => ({
|
||||
animationDuration: 400,
|
||||
color: colors,
|
||||
color: CHART_PALETTE,
|
||||
tooltip: {
|
||||
show: total.value > 0,
|
||||
trigger: 'item',
|
||||
@@ -28,147 +27,51 @@ const option = computed<UiChartOption>(() => ({
|
||||
series: [
|
||||
{
|
||||
type: 'pie',
|
||||
radius: ['58%', '82%'],
|
||||
radius: ['55%', '78%'],
|
||||
center: ['50%', '50%'],
|
||||
silent: total.value === 0,
|
||||
avoidLabelOverlap: true,
|
||||
itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 },
|
||||
label: { show: false },
|
||||
labelLine: { show: false },
|
||||
data:
|
||||
total.value > 0
|
||||
? rows.value.map((s) => ({ name: s.label, value: s.count }))
|
||||
: [{ name: '', value: 1, itemStyle: { color: '#e2e8f0' } }],
|
||||
: [{ name: '', value: 1, itemStyle: { color: '#e5e7eb' } }],
|
||||
},
|
||||
],
|
||||
}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="panel">
|
||||
<header class="panel-head">
|
||||
<h2>منابع مشتریان</h2>
|
||||
</header>
|
||||
|
||||
<div class="donut-wrap">
|
||||
<div class="donut-chart-box">
|
||||
<UiChart :option="option" height="132px" />
|
||||
<div class="donut-center">
|
||||
<strong>{{ toFaDigits(total) }}</strong>
|
||||
<span>مشتری</span>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="font-bold text-slate-800 text-base">منابع ورود مشتریان</h3>
|
||||
<span v-if="total" class="text-xs text-slate-400">۱۲ ماه اخیر</span>
|
||||
</div>
|
||||
<div class="flex flex-col sm:flex-row items-center gap-4">
|
||||
<div class="w-full sm:w-[48%] sm:max-w-[220px] shrink-0">
|
||||
<div class="relative w-full aspect-square">
|
||||
<UiChart :option="option" height="100%" />
|
||||
<div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
|
||||
<span class="text-2xl font-black text-slate-800">{{ toFaDigits(total) }}</span>
|
||||
<span class="text-xs text-slate-400">مشتری</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="w-full sm:flex-1 min-w-0">
|
||||
<a-empty v-if="!total" description="منبعی ثبت نشده" />
|
||||
<div v-else class="divide-y divide-slate-100">
|
||||
<div v-for="(item, index) in rows" :key="item.label" class="flex items-center gap-2 py-2">
|
||||
<span
|
||||
class="w-2 h-2 rounded-full shrink-0"
|
||||
:style="{ background: CHART_PALETTE[index % CHART_PALETTE.length] }"
|
||||
></span>
|
||||
<span class="flex-1 text-sm text-slate-700 truncate">{{ item.label }}</span>
|
||||
<span class="text-sm font-bold text-slate-800">{{ toFaDigits(item.percent) }}٪</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="!total" class="legend-empty">منبعی ثبت نشده</p>
|
||||
<ul v-else class="donut-legend">
|
||||
<li v-for="(row, i) in rows" :key="row.label">
|
||||
<span class="dot" :style="{ background: colors[i % colors.length] }" />
|
||||
<span class="lbl">{{ row.label }}</span>
|
||||
<em>{{ toFaDigits(row.percent) }}٪</em>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: var(--pad-modal);
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid var(--line);
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.donut-wrap {
|
||||
display: grid;
|
||||
grid-template-columns: 132px 1fr;
|
||||
gap: 0.85rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.donut-chart-box {
|
||||
position: relative;
|
||||
width: 132px;
|
||||
height: 132px;
|
||||
}
|
||||
|
||||
.donut-center {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
text-align: center;
|
||||
gap: 0.05rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.donut-center strong {
|
||||
font-size: 1.15rem;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.donut-center span {
|
||||
font-size: 0.7rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.donut-legend {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.48rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.donut-legend li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.lbl {
|
||||
flex: 1;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.legend-empty {
|
||||
margin: 0;
|
||||
color: #94a3b8;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
em {
|
||||
font-style: normal;
|
||||
color: #94a3b8;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 500px) {
|
||||
.donut-wrap {
|
||||
grid-template-columns: 1fr;
|
||||
justify-items: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { TrophyOutlined } from '@ant-design/icons-vue';
|
||||
import {
|
||||
Avatar as AAvatar,
|
||||
Flex as AFlex,
|
||||
Progress as AProgress,
|
||||
Tag as ATag,
|
||||
Typography,
|
||||
theme,
|
||||
} from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
import type { HomeDashboardTopCustomerDto } from '@mento/shared';
|
||||
import HomePanelEmpty from '@/components/dashboard/HomePanelEmpty.vue';
|
||||
@@ -9,25 +18,61 @@ const props = defineProps<{
|
||||
customers: HomeDashboardTopCustomerDto[];
|
||||
}>();
|
||||
|
||||
const rows = computed(() => props.customers.slice(0, 3));
|
||||
const { token } = theme.useToken();
|
||||
const { Text: ATypographyText } = Typography;
|
||||
|
||||
function trophy(rank: number) {
|
||||
if (rank === 1) return '🥇';
|
||||
if (rank === 2) return '🥈';
|
||||
if (rank === 3) return '🥉';
|
||||
return `#${toFaDigits(rank)}`;
|
||||
const rows = computed(() => props.customers.slice(0, 5));
|
||||
const maxDeals = computed(() => Math.max(...rows.value.map((c) => c.dealCount), 1));
|
||||
|
||||
function rankStyle(rank: number) {
|
||||
if (rank === 1) {
|
||||
return {
|
||||
background: token.value.colorWarningBg,
|
||||
color: token.value.colorWarning,
|
||||
border: `1px solid ${token.value.colorWarningBorder}`,
|
||||
};
|
||||
}
|
||||
if (rank === 2) {
|
||||
return {
|
||||
background: token.value.colorFillSecondary,
|
||||
color: token.value.colorText,
|
||||
border: `1px solid ${token.value.colorBorder}`,
|
||||
};
|
||||
}
|
||||
if (rank === 3) {
|
||||
return {
|
||||
background: token.value.colorPrimaryBg,
|
||||
color: token.value.colorPrimary,
|
||||
border: `1px solid ${token.value.colorPrimaryBorder}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
background: token.value.colorFillAlter,
|
||||
color: token.value.colorTextSecondary,
|
||||
border: `1px solid ${token.value.colorBorderSecondary}`,
|
||||
};
|
||||
}
|
||||
|
||||
function progressPercent(count: number) {
|
||||
return Math.round((count / maxDeals.value) * 100);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="panel">
|
||||
<header class="panel-head">
|
||||
<div>
|
||||
<h2>مشتریان برتر</h2>
|
||||
<p class="hint">بر اساس معاملات برندهٔ ۵ ماه اخیر</p>
|
||||
<section class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm h-full w-full">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<TrophyOutlined class="text-amber-500" />
|
||||
<h3 class="font-bold text-slate-800 text-base">مشتریان برتر</h3>
|
||||
</div>
|
||||
<RouterLink :to="{ name: 'contacts' }">مشاهده همه</RouterLink>
|
||||
</header>
|
||||
<RouterLink :to="{ name: 'contacts' }" class="text-sm font-bold text-emerald-600">
|
||||
مشاهده همه
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<a-typography-text type="secondary" style="display: block; margin-bottom: 12px">
|
||||
بر اساس معاملات برندهٔ اخیر
|
||||
</a-typography-text>
|
||||
|
||||
<HomePanelEmpty
|
||||
v-if="!rows.length"
|
||||
@@ -36,99 +81,51 @@ function trophy(rank: number) {
|
||||
action-label="مشتری جدید"
|
||||
:action-to="{ name: 'person-new' }"
|
||||
/>
|
||||
<ul v-else class="top-list">
|
||||
<li v-for="row in rows" :key="row.id">
|
||||
<span class="cust-avatar">{{ row.name.slice(0, 1) }}</span>
|
||||
<div>
|
||||
<strong>{{ row.name }}</strong>
|
||||
<span>{{ toFaDigits(row.dealCount) }} معامله</span>
|
||||
</div>
|
||||
<span class="rank">{{ trophy(row.rank) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</article>
|
||||
<a-flex v-else vertical :gap="token.marginSM">
|
||||
<a-flex
|
||||
v-for="item in rows"
|
||||
:key="item.id"
|
||||
align="center"
|
||||
:gap="token.marginSM"
|
||||
class="rounded-xl border"
|
||||
:class="item.rank === 1 ? 'bg-amber-50/50 border-amber-200/80' : 'bg-slate-50 border-slate-200/70'"
|
||||
:style="{ padding: `${token.paddingSM}px`, minWidth: 0 }"
|
||||
>
|
||||
<a-flex
|
||||
align="center"
|
||||
justify="center"
|
||||
:style="{
|
||||
width: '36px',
|
||||
height: '36px',
|
||||
borderRadius: '50%',
|
||||
fontWeight: 700,
|
||||
flexShrink: 0,
|
||||
...rankStyle(item.rank),
|
||||
}"
|
||||
>
|
||||
{{ toFaDigits(item.rank) }}
|
||||
</a-flex>
|
||||
<a-avatar :style="{ background: token.colorPrimary, flexShrink: 0 }">
|
||||
{{ item.name.slice(0, 1) }}
|
||||
</a-avatar>
|
||||
<a-flex vertical :style="{ minWidth: 0, flex: 1 }">
|
||||
<a-flex align="center" justify="space-between" :gap="token.marginXS">
|
||||
<a-typography-text strong ellipsis>{{ item.name }}</a-typography-text>
|
||||
<a-tag v-if="item.rank === 1" color="gold" style="flex-shrink: 0">رتبه یک</a-tag>
|
||||
</a-flex>
|
||||
<a-flex align="center" :gap="token.marginSM">
|
||||
<a-progress
|
||||
:percent="progressPercent(item.dealCount)"
|
||||
:show-info="false"
|
||||
:stroke-color="item.rank === 1 ? token.colorWarning : token.colorPrimary"
|
||||
style="flex: 1; margin: 0; line-height: 1"
|
||||
/>
|
||||
<a-typography-text type="secondary" style="flex-shrink: 0; white-space: nowrap">
|
||||
{{ toFaDigits(item.dealCount) }} معامله
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.05rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #eef2f7;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.85rem;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0.15rem 0 0;
|
||||
color: #94a3b8;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #14b8a6;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.top-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.7rem;
|
||||
}
|
||||
|
||||
.top-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.cust-avatar {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: var(--radius);
|
||||
background: linear-gradient(145deg, #ccfbf1, #99f6e4);
|
||||
color: #0f766e;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-weight: 600;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.top-list div {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
.top-list strong {
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.top-list span {
|
||||
color: #94a3b8;
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
.rank {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -102,7 +102,7 @@ onUnmounted(() => {
|
||||
<style scoped>
|
||||
.hub {
|
||||
width: min(28rem, calc(100vw - var(--hub-offset, 16rem) - 1.5rem));
|
||||
max-height: calc(100dvh - 56px);
|
||||
max-height: calc(100dvh - 16px - var(--control-h) - 28px);
|
||||
overflow: hidden;
|
||||
padding: 0.9rem 0.9rem 0.8rem;
|
||||
display: grid;
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { useRouter } from 'vue-router';
|
||||
import type { RouteLocationRaw } from 'vue-router';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import {
|
||||
Button as AButton,
|
||||
Flex as AFlex,
|
||||
Space as ASpace,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import {
|
||||
CalendarOutlined,
|
||||
PlusOutlined,
|
||||
UserAddOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
|
||||
withDefaults(
|
||||
const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
title?: string;
|
||||
description?: string;
|
||||
@@ -20,15 +32,24 @@ withDefaults(
|
||||
secondaryIcon: 'calendar-plus',
|
||||
},
|
||||
);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
function go(to: RouteLocationRaw) {
|
||||
void router.push(to);
|
||||
}
|
||||
|
||||
const secondaryIconComp = () => {
|
||||
if (props.secondaryIcon === 'user-plus') return UserAddOutlined;
|
||||
return CalendarOutlined;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="empty-state">
|
||||
<div class="art" aria-hidden="true">
|
||||
<span class="spark s1">✦</span>
|
||||
<span class="spark s2">✦</span>
|
||||
<span class="spark s3">✦</span>
|
||||
<svg viewBox="0 0 168 132" fill="none">
|
||||
<a-flex vertical align="center" :gap="16" :style="{ width: '100%', textAlign: 'center' }">
|
||||
<div aria-hidden="true" :style="{ width: '168px' }">
|
||||
<span aria-hidden="true">✦</span>
|
||||
<svg viewBox="0 0 168 132" fill="none" :style="{ width: '168px', height: 'auto', display: 'block' }">
|
||||
<path
|
||||
d="M26 44c0-7.2 5.8-13 13-13h30l9 9h51c7.2 0 13 5.8 13 13v54c0 7.2-5.8 13-13 13H39c-7.2 0-13-5.8-13-13V44Z"
|
||||
fill="#D9E6E8"
|
||||
@@ -52,147 +73,24 @@ withDefaults(
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h3>{{ title }}</h3>
|
||||
<p>{{ description }}</p>
|
||||
<a-typography-title :level="4" :style="{ margin: 0 }">{{ title }}</a-typography-title>
|
||||
<a-typography-text type="secondary">{{ description }}</a-typography-text>
|
||||
|
||||
<div class="actions">
|
||||
<RouterLink class="btn-primary" :to="primaryTo">
|
||||
<span class="plus">+</span>
|
||||
<a-space direction="vertical" style="width: min(100%, 304px)">
|
||||
<a-button type="primary" block @click="go(primaryTo)">
|
||||
<template #icon><PlusOutlined /></template>
|
||||
{{ primaryLabel }}
|
||||
</RouterLink>
|
||||
<RouterLink v-if="secondaryLabel && secondaryTo" class="btn-secondary" :to="secondaryTo">
|
||||
<UiIcon :name="secondaryIcon" :size="18" />
|
||||
</a-button>
|
||||
<a-button
|
||||
v-if="secondaryLabel && secondaryTo"
|
||||
block
|
||||
@click="go(secondaryTo)"
|
||||
>
|
||||
<template #icon>
|
||||
<component :is="secondaryIconComp()" />
|
||||
</template>
|
||||
{{ secondaryLabel }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
</a-button>
|
||||
</a-space>
|
||||
</a-flex>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.empty-state {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
align-content: center;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
padding: 1.4rem 0.8rem 0.6rem;
|
||||
}
|
||||
|
||||
.art {
|
||||
position: relative;
|
||||
width: 168px;
|
||||
margin-bottom: 1.05rem;
|
||||
}
|
||||
|
||||
.art svg {
|
||||
width: 168px;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.spark {
|
||||
position: absolute;
|
||||
color: #5eead4;
|
||||
font-size: 0.68rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.s1 {
|
||||
top: 6px;
|
||||
inset-inline-end: 8px;
|
||||
}
|
||||
|
||||
.s2 {
|
||||
top: 44px;
|
||||
inset-inline-start: 2px;
|
||||
font-size: 0.52rem;
|
||||
color: #99f6e4;
|
||||
}
|
||||
|
||||
.s3 {
|
||||
bottom: 20px;
|
||||
inset-inline-end: -2px;
|
||||
font-size: 0.46rem;
|
||||
color: #99f6e4;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 1.08rem;
|
||||
font-weight: 600;
|
||||
color: #1e2937;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.5rem 0 1.25rem;
|
||||
max-width: 21.5rem;
|
||||
color: #94a3b8;
|
||||
font-size: 0.84rem;
|
||||
line-height: 1.85;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: grid;
|
||||
gap: 0.7rem;
|
||||
width: min(100%, 304px);
|
||||
}
|
||||
|
||||
.btn-primary,
|
||||
.btn-secondary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
min-height: var(--control-h);
|
||||
height: var(--control-h);
|
||||
border-radius: var(--radius);
|
||||
font-weight: 700;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #14b8a6;
|
||||
color: #fff;
|
||||
box-shadow: 0 8px 18px rgba(20, 184, 166, 0.26);
|
||||
}
|
||||
|
||||
.plus {
|
||||
font-size: 1.2rem;
|
||||
line-height: 1;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #fff;
|
||||
color: #0f766e;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
@media (max-width: 599px) {
|
||||
.empty-state {
|
||||
padding: 1.2rem 0.2rem 0.4rem;
|
||||
}
|
||||
|
||||
.art,
|
||||
.art svg {
|
||||
width: 152px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.02rem;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 1.15rem;
|
||||
}
|
||||
|
||||
.btn-primary,
|
||||
.btn-secondary {
|
||||
min-height: var(--control-h);
|
||||
height: var(--control-h);
|
||||
font-size: 0.86rem;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { RouteLocationRaw } from 'vue-router';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import {
|
||||
Button as AButton,
|
||||
Dropdown as ADropdown,
|
||||
Menu as AMenu,
|
||||
MenuItem as AMenuItem,
|
||||
} from 'ant-design-vue';
|
||||
import { MoreOutlined } from '@ant-design/icons-vue';
|
||||
|
||||
export type ProfileMoreItem = {
|
||||
key: string;
|
||||
@@ -15,207 +20,40 @@ const open = defineModel<boolean>({ default: false });
|
||||
defineProps<{ items: ProfileMoreItem[] }>();
|
||||
const emit = defineEmits<{ select: [key: string] }>();
|
||||
|
||||
const triggerRef = ref<HTMLButtonElement | null>(null);
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const top = ref(0);
|
||||
const left = ref(0);
|
||||
|
||||
function place() {
|
||||
const trigger = triggerRef.value;
|
||||
const panel = panelRef.value;
|
||||
if (!trigger) return;
|
||||
const rect = trigger.getBoundingClientRect();
|
||||
const width = panel?.offsetWidth || 220;
|
||||
const height = panel?.offsetHeight || 0;
|
||||
const rtl = getComputedStyle(document.documentElement).direction === 'rtl';
|
||||
let nextLeft = rtl ? rect.right - width : rect.left;
|
||||
nextLeft = Math.min(Math.max(8, nextLeft), window.innerWidth - width - 8);
|
||||
let nextTop = rect.bottom + 8;
|
||||
if (nextTop + height > window.innerHeight - 8) {
|
||||
nextTop = Math.max(8, rect.top - height - 8);
|
||||
}
|
||||
left.value = nextLeft;
|
||||
top.value = nextTop;
|
||||
}
|
||||
|
||||
function onWindowChange() {
|
||||
if (open.value) place();
|
||||
}
|
||||
|
||||
watch(open, async (value) => {
|
||||
if (!value) {
|
||||
window.removeEventListener('resize', onWindowChange);
|
||||
window.removeEventListener('scroll', onWindowChange, true);
|
||||
return;
|
||||
}
|
||||
await nextTick();
|
||||
place();
|
||||
await nextTick();
|
||||
place();
|
||||
window.addEventListener('resize', onWindowChange);
|
||||
window.addEventListener('scroll', onWindowChange, true);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', onWindowChange);
|
||||
window.removeEventListener('scroll', onWindowChange, true);
|
||||
});
|
||||
|
||||
function toggle() {
|
||||
open.value = !open.value;
|
||||
}
|
||||
|
||||
function close() {
|
||||
function onSelect(key: string) {
|
||||
emit('select', key);
|
||||
open.value = false;
|
||||
}
|
||||
|
||||
function scheduleClose() {
|
||||
window.setTimeout(() => {
|
||||
close();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function onSelect(key: string) {
|
||||
emit('select', key);
|
||||
nextTick(() => {
|
||||
close();
|
||||
});
|
||||
function onLinkClick() {
|
||||
open.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="wrap" @click.stop>
|
||||
<button
|
||||
ref="triggerRef"
|
||||
class="icon-btn"
|
||||
type="button"
|
||||
aria-label="منوی بیشتر"
|
||||
:aria-expanded="open"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<UiIcon name="dots-v" :size="18" />
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="layer">
|
||||
<button class="backdrop" type="button" aria-label="بستن منو" @click="close" />
|
||||
<ul
|
||||
ref="panelRef"
|
||||
class="panel"
|
||||
role="menu"
|
||||
:style="{ top: `${top}px`, left: `${left}px` }"
|
||||
@click.stop
|
||||
<a-dropdown v-model:open="open" :trigger="['click']" placement="bottomLeft">
|
||||
<a-button aria-label="منوی بیشتر" @click.stop>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
<template #overlay>
|
||||
<a-menu @click.stop>
|
||||
<a-menu-item
|
||||
v-for="item in items"
|
||||
:key="item.key"
|
||||
:danger="item.danger"
|
||||
@click="item.to ? onLinkClick() : onSelect(item.key)"
|
||||
>
|
||||
<li v-for="item in items" :key="item.key" role="none">
|
||||
<RouterLink
|
||||
v-if="item.to"
|
||||
class="item"
|
||||
:class="{ danger: item.danger }"
|
||||
role="menuitem"
|
||||
:to="item.to"
|
||||
@click.stop="scheduleClose"
|
||||
>
|
||||
{{ item.label }}
|
||||
</RouterLink>
|
||||
<button
|
||||
v-else
|
||||
class="item"
|
||||
:class="{ danger: item.danger }"
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@click.stop.prevent="onSelect(item.key)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
<RouterLink
|
||||
v-if="item.to"
|
||||
:to="item.to"
|
||||
:style="{ color: 'inherit', display: 'block' }"
|
||||
@click="onLinkClick"
|
||||
>
|
||||
{{ item.label }}
|
||||
</RouterLink>
|
||||
<span v-else>{{ item.label }}</span>
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wrap {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border: 0;
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #334155;
|
||||
box-shadow: 0 4px 12px rgba(15, 23, 42, 0.05);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
}
|
||||
|
||||
.backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.panel {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
margin: 0;
|
||||
padding: 0.4rem;
|
||||
list-style: none;
|
||||
width: 220px;
|
||||
background: #fff;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.16);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.panel > li {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: transparent;
|
||||
color: #0f172a;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.6;
|
||||
text-align: start;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
padding: 0.7rem 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.item:hover {
|
||||
background: #f0fdfa;
|
||||
}
|
||||
|
||||
.item.danger {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.item.danger:hover {
|
||||
background: #fef2f2;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -152,23 +152,27 @@ const cardStyle = computed(() => ({
|
||||
</a-typography-text>
|
||||
</div>
|
||||
|
||||
<a-button
|
||||
v-if="showTrash"
|
||||
type="text"
|
||||
danger
|
||||
aria-label="حذف انتخابشدهها"
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
type="text"
|
||||
:aria-label="copy.itemMenuAria"
|
||||
@click.stop="emit('menu', deal.id)"
|
||||
>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
<span :data-card-id="deal.id">
|
||||
<a-button
|
||||
v-if="showTrash"
|
||||
class="menu"
|
||||
type="text"
|
||||
danger
|
||||
aria-label="حذف انتخابشدهها"
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
class="menu"
|
||||
type="text"
|
||||
:aria-label="copy.itemMenuAria"
|
||||
@click.stop="emit('menu', deal.id)"
|
||||
>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
</span>
|
||||
</a-flex>
|
||||
|
||||
<a-flex
|
||||
|
||||
@@ -219,23 +219,27 @@ onUnmounted(() => {
|
||||
</a-space>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-button
|
||||
v-if="selectMode && selectedIds.has(record.deal.id)"
|
||||
type="text"
|
||||
danger
|
||||
aria-label="حذف انتخابشدهها"
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
type="text"
|
||||
:aria-label="copy.itemMenuAria"
|
||||
@click.stop="emit('menuDeal', record.deal.id)"
|
||||
>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
<span :data-card-id="record.deal.id">
|
||||
<a-button
|
||||
v-if="selectMode && selectedIds.has(record.deal.id)"
|
||||
class="menu"
|
||||
type="text"
|
||||
danger
|
||||
aria-label="حذف انتخابشدهها"
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
class="menu"
|
||||
type="text"
|
||||
:aria-label="copy.itemMenuAria"
|
||||
@click.stop="emit('menuDeal', record.deal.id)"
|
||||
>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
</span>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
@@ -299,17 +303,25 @@ onUnmounted(() => {
|
||||
{{ row.deal.description }}
|
||||
</a-typography-text>
|
||||
</div>
|
||||
<a-button
|
||||
v-if="selectMode && selectedIds.has(row.deal.id)"
|
||||
type="text"
|
||||
danger
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button v-else type="text" @click.stop="emit('menuDeal', row.deal.id)">
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
<span :data-card-id="row.deal.id">
|
||||
<a-button
|
||||
v-if="selectMode && selectedIds.has(row.deal.id)"
|
||||
class="menu"
|
||||
type="text"
|
||||
danger
|
||||
@click.stop="emit('bulkDelete')"
|
||||
>
|
||||
<template #icon><DeleteOutlined /></template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
class="menu"
|
||||
type="text"
|
||||
@click.stop="emit('menuDeal', row.deal.id)"
|
||||
>
|
||||
<template #icon><MoreOutlined /></template>
|
||||
</a-button>
|
||||
</span>
|
||||
</a-flex>
|
||||
<a-tag
|
||||
:bordered="false"
|
||||
|
||||
@@ -11,6 +11,20 @@ import {
|
||||
weekdayIndex,
|
||||
} from '@/lib/routines';
|
||||
import { ROUTINE_WEEKDAY_LABELS } from '@mento/shared';
|
||||
import {
|
||||
Card as ACard,
|
||||
Col as ACol,
|
||||
Flex as AFlex,
|
||||
Progress as AProgress,
|
||||
Row as ARow,
|
||||
Tag as ATag,
|
||||
Tooltip as ATooltip,
|
||||
Typography,
|
||||
theme,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
|
||||
const { token } = theme.useToken();
|
||||
|
||||
const props = defineProps<{
|
||||
score: RoutineScoreDto | null;
|
||||
@@ -29,216 +43,98 @@ const rows = computed(() => {
|
||||
});
|
||||
|
||||
const strip = computed(() => props.days ?? []);
|
||||
|
||||
const TONE_COLORS: Record<string, string> = {
|
||||
good: 'var(--ant-color-success)',
|
||||
mid: 'var(--ant-color-warning)',
|
||||
low: 'var(--ant-color-error)',
|
||||
none: 'var(--ant-color-text-quaternary)',
|
||||
};
|
||||
|
||||
const STATE_STYLES: Record<string, { bg: string; fg: string }> = {
|
||||
complete: { bg: 'var(--ant-color-success-bg)', fg: 'var(--ant-color-success)' },
|
||||
partial: { bg: 'var(--ant-color-warning-bg)', fg: 'var(--ant-color-warning)' },
|
||||
missed: { bg: 'var(--ant-color-error-bg)', fg: 'var(--ant-color-error)' },
|
||||
empty: { bg: 'var(--ant-color-fill-secondary)', fg: 'var(--ant-color-text-quaternary)' },
|
||||
};
|
||||
|
||||
function stateStyle(state: string) {
|
||||
return STATE_STYLES[state] ?? STATE_STYLES.empty;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="score-card">
|
||||
<header>
|
||||
<h3>امتیاز روزانه</h3>
|
||||
<span class="streak" :title="'روزهای متوالی با انجام همه کارهای اجباری'">
|
||||
<strong>{{ toFaDigits(score?.streak ?? 0) }}</strong>
|
||||
روز پیاپی کامل
|
||||
</span>
|
||||
</header>
|
||||
<a-card :bordered="false">
|
||||
<a-flex vertical :gap="16">
|
||||
<a-flex justify="space-between" align="center" :gap="8">
|
||||
<a-typography-title :level="5" :style="{ margin: 0 }">امتیاز روزانه</a-typography-title>
|
||||
<a-typography-text type="secondary" title="روزهای متوالی با انجام همه کارهای اجباری">
|
||||
<a-typography-text strong :style="{ color: 'var(--ant-color-primary)' }">
|
||||
{{ toFaDigits(score?.streak ?? 0) }}
|
||||
</a-typography-text>
|
||||
روز پیاپی کامل
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
|
||||
<div class="scores">
|
||||
<div v-for="r in rows" :key="r.label" class="score" :class="`tone-${percentTone(r.value)}`">
|
||||
<span>{{ r.label }}</span>
|
||||
<strong>{{ formatPercent(r.value) }}</strong>
|
||||
<i class="bar"><b :style="{ width: `${r.value ?? 0}%` }" /></i>
|
||||
</div>
|
||||
</div>
|
||||
<a-row :gutter="[16, 16]">
|
||||
<a-col v-for="r in rows" :key="r.label" :span="12">
|
||||
<a-flex justify="space-between" align="baseline" :gap="8">
|
||||
<a-typography-text type="secondary">{{ r.label }}</a-typography-text>
|
||||
<a-typography-text strong>{{ formatPercent(r.value) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-progress
|
||||
:percent="r.value ?? 0"
|
||||
:show-info="false"
|
||||
:stroke-color="TONE_COLORS[percentTone(r.value)]"
|
||||
/>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<div v-if="strip.length" class="strip-wrap">
|
||||
<div class="strip" role="list" aria-label="وضعیت روزهای اخیر">
|
||||
<span
|
||||
v-for="d in strip"
|
||||
:key="d.date"
|
||||
role="listitem"
|
||||
class="cell"
|
||||
:class="`s-${d.state}`"
|
||||
:title="`${formatDayNumeric(d.date)} — ${DAY_STATE_LABELS[d.state]}${d.total ? ` (${toFaDigits(d.completed)} از ${toFaDigits(d.total)})` : ''}`"
|
||||
>
|
||||
<em>{{ DAY_STATE_SYMBOLS[d.state] }}</em>
|
||||
<small>{{ ROUTINE_WEEKDAY_LABELS[weekdayIndex(d.date)]?.charAt(0) }}</small>
|
||||
</span>
|
||||
</div>
|
||||
<div class="legend">
|
||||
<span><i class="s-complete">✓</i> کامل</span>
|
||||
<span><i class="s-partial">△</i> ناقص</span>
|
||||
<span><i class="s-missed">×</i> از دست رفته</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<template v-if="strip.length">
|
||||
<a-flex :gap="4" role="list" aria-label="وضعیت روزهای اخیر">
|
||||
<a-flex
|
||||
v-for="d in strip"
|
||||
:key="d.date"
|
||||
vertical
|
||||
align="center"
|
||||
:gap="2"
|
||||
role="listitem"
|
||||
:style="{ flex: 1, minWidth: 0 }"
|
||||
>
|
||||
<a-tooltip
|
||||
:title="`${formatDayNumeric(d.date)} — ${DAY_STATE_LABELS[d.state]}${d.total ? ` (${toFaDigits(d.completed)} از ${toFaDigits(d.total)})` : ''}`"
|
||||
>
|
||||
<a-flex
|
||||
justify="center"
|
||||
align="center"
|
||||
:style="{
|
||||
width: '26px',
|
||||
height: '26px',
|
||||
flexShrink: 0,
|
||||
borderRadius: token.borderRadiusSM,
|
||||
background: stateStyle(d.state).bg,
|
||||
color: stateStyle(d.state).fg,
|
||||
}"
|
||||
>
|
||||
<a-typography-text
|
||||
strong
|
||||
:style="{ color: stateStyle(d.state).fg, lineHeight: 1 }"
|
||||
>
|
||||
{{ DAY_STATE_SYMBOLS[d.state] }}
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
</a-tooltip>
|
||||
<a-typography-text type="secondary">
|
||||
{{ ROUTINE_WEEKDAY_LABELS[weekdayIndex(d.date)]?.charAt(0) }}
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
<a-flex wrap="wrap" :gap="8">
|
||||
<a-tag color="success" :bordered="false">✓ کامل</a-tag>
|
||||
<a-tag color="warning" :bordered="false">△ ناقص</a-tag>
|
||||
<a-tag color="error" :bordered="false">× از دست رفته</a-tag>
|
||||
</a-flex>
|
||||
</template>
|
||||
</a-flex>
|
||||
</a-card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.score-card {
|
||||
display: grid;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-4);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-xs);
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: var(--fw-semibold);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.streak {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 5px;
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.streak strong {
|
||||
font-size: var(--fs-lg);
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.scores {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
.score {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: baseline;
|
||||
gap: 4px 8px;
|
||||
}
|
||||
|
||||
.score span {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.score strong {
|
||||
font-size: var(--fs-md);
|
||||
color: var(--ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.bar {
|
||||
grid-column: 1 / -1;
|
||||
height: 5px;
|
||||
border-radius: 99px;
|
||||
background: var(--surface-subtle);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bar b {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--line-strong);
|
||||
transition: width 0.4s ease;
|
||||
}
|
||||
|
||||
.tone-good .bar b {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.tone-mid .bar b {
|
||||
background: var(--warning);
|
||||
}
|
||||
|
||||
.tone-low .bar b {
|
||||
background: var(--danger);
|
||||
}
|
||||
|
||||
.strip-wrap {
|
||||
display: grid;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.strip {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.cell {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.cell em {
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
max-width: 26px;
|
||||
border-radius: 6px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-style: normal;
|
||||
font-size: 0.75rem;
|
||||
font-weight: var(--fw-bold);
|
||||
background: var(--surface-subtle);
|
||||
color: var(--muted-light);
|
||||
}
|
||||
|
||||
.cell small {
|
||||
font-size: 0.62rem;
|
||||
color: var(--muted-light);
|
||||
}
|
||||
|
||||
.s-complete,
|
||||
.cell.s-complete em {
|
||||
background: var(--success-soft);
|
||||
color: var(--success-deep);
|
||||
}
|
||||
|
||||
.s-partial,
|
||||
.cell.s-partial em {
|
||||
background: var(--warning-soft);
|
||||
color: var(--warning-deep);
|
||||
}
|
||||
|
||||
.s-missed,
|
||||
.cell.s-missed em {
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-3);
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.legend span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.legend i {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 4px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
font-style: normal;
|
||||
font-size: 0.65rem;
|
||||
font-weight: var(--fw-bold);
|
||||
}
|
||||
</style>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user