Compare commits
249
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8128ebe3a | ||
|
|
6ec7a1a942 | ||
|
|
2d690b4c04 | ||
|
|
1ba352f127 | ||
|
|
f50246dc46 | ||
|
|
7d9fc8447f | ||
|
|
5be0bc6f5e | ||
|
|
2ca2650b69 | ||
|
|
42b3fc72cc | ||
|
|
6d8ede8e2a | ||
|
|
ade43fea0f | ||
|
|
65cf4e9a66 | ||
|
|
80fb5bf1bb | ||
|
|
31f45a6a31 | ||
|
|
73c87b8be4 | ||
|
|
09a60b3b5a | ||
|
|
cb5944e767 | ||
|
|
23ae273232 | ||
|
|
1c2da34983 | ||
|
|
50d7cad66e | ||
|
|
29d99cbded | ||
|
|
ce27df20ca | ||
|
|
7ae6a5837a | ||
|
|
631a3267d1 | ||
|
|
b731fe43aa | ||
|
|
15cbd62997 | ||
|
|
e6aa4c64f0 | ||
|
|
9127fa334b | ||
|
|
9a86f63f48 | ||
|
|
29398a445b | ||
|
|
bb8fd489de | ||
|
|
86e9ee6c2c | ||
|
|
adb63447ca | ||
|
|
c1b38e1737 | ||
|
|
be7ae0a1d8 | ||
|
|
bbbedc6059 | ||
|
|
f5d68d83fc | ||
|
|
f15ebb72ea | ||
|
|
8590579605 | ||
|
|
3863c5e7d1 | ||
|
|
e6f9876177 | ||
|
|
fddf22d7fe | ||
|
|
ada9a1f21f | ||
|
|
2f11105628 | ||
|
|
36eda8653e | ||
|
|
8fdd5147a5 | ||
|
|
002f697dfe | ||
|
|
96befd3867 | ||
|
|
b25b5b125a | ||
|
|
4abab55a6b | ||
|
|
8981a552fc | ||
|
|
ab538b8304 | ||
|
|
61d17c5cea | ||
|
|
23f8da2c65 | ||
|
|
9325d879a5 | ||
|
|
d62e004e90 | ||
|
|
32c722f42a | ||
|
|
f7b07f6b7a | ||
|
|
52c7306e78 | ||
|
|
960e01938d | ||
|
|
3fb5f32ac3 | ||
|
|
0ce2533066 | ||
|
|
bc68582fe2 | ||
|
|
e86841fc60 | ||
|
|
5069647f79 | ||
|
|
008733d338 | ||
|
|
c5708ed59b | ||
|
|
65d66bb331 | ||
|
|
79ba146118 | ||
|
|
02841a5b8c | ||
|
|
a04743c6df | ||
|
|
27635c0752 | ||
|
|
03e1c01023 | ||
|
|
177e5cc31b | ||
|
|
2c7c943802 | ||
|
|
9611803567 | ||
|
|
a494b5308e | ||
|
|
582733e2ea | ||
|
|
6bff9d2888 | ||
|
|
6bc5e1bec7 | ||
|
|
3a8a684aa4 | ||
|
|
831c682eb3 | ||
|
|
2cc81bb596 | ||
|
|
c04582072d | ||
|
|
42f0573a5f | ||
|
|
13ee70764b | ||
|
|
cf326d1ed9 | ||
|
|
5f4cc47c41 | ||
|
|
0e420a443f | ||
|
|
6b4bd0b03e | ||
|
|
910c7f51b0 | ||
|
|
609ce3d006 | ||
|
|
9bed6cac03 | ||
|
|
fd6e79c15d | ||
|
|
9b42fec0a8 | ||
|
|
d00f362376 | ||
|
|
fd8966e13f | ||
|
|
91eb9be1d4 | ||
|
|
ffae63edbf | ||
|
|
cba4ad6a49 | ||
|
|
faac26d07d | ||
|
|
a2b01f787e | ||
|
|
8af78047d9 | ||
|
|
b43ed68e82 | ||
|
|
f4398cdb3e | ||
|
|
17638786a8 | ||
|
|
b3b92abae9 | ||
|
|
b30f68563d | ||
|
|
51ca23b398 | ||
|
|
60d797f184 | ||
|
|
b87ebb22e0 | ||
|
|
792b3d29fa | ||
|
|
0802c2f436 | ||
|
|
37157620e2 | ||
|
|
f27b4c264a | ||
|
|
e82bd2b2df | ||
|
|
fa3fe0d364 | ||
|
|
4e26658092 | ||
|
|
287f88abc0 | ||
|
|
09f05d4ecc | ||
|
|
46a7693ea0 | ||
|
|
e6755d0c2e | ||
|
|
2f3646d085 | ||
|
|
f5b6a47f3c | ||
|
|
678cb87de7 | ||
|
|
d683932d1b | ||
|
|
13668c4ba4 | ||
|
|
aa2f39256a | ||
|
|
b4ffef9b6f | ||
|
|
b3784818fc | ||
|
|
3de2d0fa67 | ||
|
|
2a2728e5ee | ||
|
|
e08f1452ef | ||
|
|
43717392b2 | ||
|
|
bc01384551 | ||
|
|
5074c6d791 | ||
|
|
0d7555f219 | ||
|
|
f71f09c85d | ||
|
|
f88786ef61 | ||
|
|
46dcf296d3 | ||
|
|
c8753a4c4e | ||
|
|
48de552f36 | ||
|
|
71b3a7255a | ||
|
|
df8fac187e | ||
|
|
3296b1c209 | ||
|
|
23c83ffbee | ||
|
|
75ff2c36c4 | ||
|
|
39e2eb24a6 | ||
|
|
8b37525f2f | ||
|
|
e144b2277a | ||
|
|
236f73de93 | ||
|
|
60c16053a4 | ||
|
|
cbfe470f33 | ||
|
|
ac57b8ac33 | ||
|
|
d3fb92a5e2 | ||
|
|
07bdc4a3b6 | ||
|
|
c629729a9a | ||
|
|
beae16437b | ||
|
|
17628722d3 | ||
|
|
c322a24424 | ||
|
|
2e315c9cfd | ||
|
|
f8313c0ea5 | ||
|
|
3b128bd980 | ||
|
|
9f97371391 | ||
|
|
1309da2281 | ||
|
|
989c03b381 | ||
|
|
5784b09232 | ||
|
|
5d5b3a3213 | ||
|
|
ae21d9bbc7 | ||
|
|
e94600a02e | ||
|
|
75b83b7f1b | ||
|
|
d3986da28b | ||
|
|
c7a60c524d | ||
|
|
3c0ed3369e | ||
|
|
a3ed6187e9 | ||
|
|
e1d456ad11 | ||
|
|
b978708487 | ||
|
|
4c8731122b | ||
|
|
f71e78f3a7 | ||
|
|
7c4b24fad6 | ||
|
|
e6fb5c3700 | ||
|
|
298b3316b4 | ||
|
|
58e89246d9 | ||
|
|
5bb8e68521 | ||
|
|
88dc7c5a1c | ||
|
|
83504816c5 | ||
|
|
c20dc0a7ca | ||
|
|
e20b904bbe | ||
|
|
7996fc7f73 | ||
|
|
70bcd15847 | ||
|
|
b0f05b6a27 | ||
|
|
d4972891f1 | ||
|
|
032eb70524 | ||
|
|
2309e2c5ab | ||
|
|
66af7e577c | ||
|
|
125976f3eb | ||
|
|
0670067e7f | ||
|
|
a1655432fc | ||
|
|
589c763ef8 | ||
|
|
d2c82f2115 | ||
|
|
319493171f | ||
|
|
f20206b045 | ||
|
|
32e27d45f7 | ||
|
|
8effd4cbc6 | ||
|
|
7e73ba9936 | ||
|
|
647503810d | ||
|
|
ec5c7639e3 | ||
|
|
3833788aa8 | ||
|
|
9edbb92b13 | ||
|
|
05f205cadf | ||
|
|
ac3ffb8ab2 | ||
|
|
c079295ff4 | ||
|
|
22980e5152 | ||
|
|
c5c903d4b4 | ||
|
|
c06c92b333 | ||
|
|
00f8b91d78 | ||
|
|
55a287563d | ||
|
|
a16c2f0a9b | ||
|
|
6a9e864b07 | ||
|
|
d133c8ca34 | ||
|
|
db65b55660 | ||
|
|
26085b54a9 | ||
|
|
1b160c8cd3 | ||
|
|
499d13d1df | ||
|
|
ef600d149d | ||
|
|
ccddd009e3 | ||
|
|
6463275c3d | ||
|
|
35a618d0af | ||
|
|
011b316b5b | ||
|
|
b7e3d1e290 | ||
|
|
7dc4344e0e | ||
|
|
99df327ded | ||
|
|
230d7b3bf6 | ||
|
|
58c3e25db6 | ||
|
|
75a73559b5 | ||
|
|
41f0025883 | ||
|
|
42db5919e1 | ||
|
|
d53136d91c | ||
|
|
dac0454e69 | ||
|
|
4b335aa7ff | ||
|
|
17fb33b3e7 | ||
|
|
be97a067f9 | ||
|
|
9249302eac | ||
|
|
5d9a572ff8 | ||
|
|
f4cb41d96f | ||
|
|
7a58b9d469 | ||
|
|
1adc217375 | ||
|
|
d7d82102af | ||
|
|
f5a4eb577b |
@@ -0,0 +1,85 @@
|
|||||||
|
---
|
||||||
|
description: Hard governance for Ant Design Vue v4 migration — isolated page-by-page, no manual CSS, 24-col grid, default controlHeight 36
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ant Design Vue v4 — Strict Governance (locked)
|
||||||
|
|
||||||
|
Source of truth for migrated UI: **Ant Design Vue 4** + central theme [`apps/web/src/theme/antdTheme.ts`](apps/web/src/theme/antdTheme.ts).
|
||||||
|
|
||||||
|
Legacy CRM UI (`components/ui/*`, `.crm-*`, `.btn` / `.field` in `styles/`) remains for **unmigrated** screens only. Never mix systems inside one page.
|
||||||
|
|
||||||
|
## Hard rules
|
||||||
|
|
||||||
|
1. **Single-page migration lock**
|
||||||
|
Migrate **exactly one** route/view (or one clearly named page folder) per change set. Do not “clean up” neighboring pages, shared legacy primitives, or global CSS while migrating a page.
|
||||||
|
|
||||||
|
2. **No edits to legacy kit during Ant work**
|
||||||
|
Do **not** modify `apps/web/src/components/ui/**` or broaden changes across `views/` beyond the single page under migration, unless the user explicitly names that page.
|
||||||
|
|
||||||
|
2b. **Child components of a migrated View (mandatory)**
|
||||||
|
هنگام بازنویسی یک صفحه (View)، ایجنت موظف است علاوه بر خود فایل View، تمام کامپوننتهای فرزندی را که در آن View ایمپورت شدهاند و حاوی اینپوت/سلکت/دکمه هستند نیز بازبینی کرده و درون آنها را به کامپوننتهای رسمی `ant-design-vue` تبدیل کند. هیچ تگ `<input>`, `<select>`, `<textarea>`, `<button>` خامی نباید در صفحه یا کامپوننتهای فرزندِ مصرفی آن باقی بماند.
|
||||||
|
When rewriting a View, the agent **must** also review every component imported by that View that contains inputs/selects/buttons, and convert their internals to official `ant-design-vue` controls.
|
||||||
|
**No raw** `<input>`, `<select>`, `<textarea>`, or `<button>` may remain in the View **or** in those consumed child components. Prefer native Ant equivalents (`a-select` / `mode="multiple|tags"` / `a-time-picker` / …) over custom pickers when logic allows; if domain logic is required (e.g. Jalali), convert that child file to Ant chrome (`a-input` + `a-popover`, etc.) instead of leaving raw HTML. Do **not** leave legacy `UiInput` / `UiSelect` / `UiButton` / `UiField` / `UiTextarea` in the View or those children.
|
||||||
|
|
||||||
|
3. **Ant-only UI on migrated pages**
|
||||||
|
On a migrated page, build controls with Ant Design Vue (`a-button`, `a-form`, `a-table`, `a-card`, …) and `@ant-design/icons-vue`. Do **not** introduce new usage of `UiButton`, `UiInput`, `.btn`, `.field`, or ad-hoc HTML form controls for the same job.
|
||||||
|
|
||||||
|
4. **Ban manual CSS for layout/look**
|
||||||
|
On migrated pages:
|
||||||
|
- No new `<style scoped>` rules for color, spacing, radius, shadow, typography, or layout that Ant already covers.
|
||||||
|
- No hardcoded hex / `rgb()` for chrome UI (charts/data palettes may be excepted when not chrome).
|
||||||
|
- Prefer ConfigProvider theme tokens, component props, and Ant space/grid utilities.
|
||||||
|
- Inline `style` only for rare one-off values that tokens cannot express; prefer tokens first.
|
||||||
|
|
||||||
|
5. **Default Ant control size (`controlHeight: 36`) — no manual `size`**
|
||||||
|
- Global default comes from theme token `controlHeight: 36` in `antdTheme.ts` (Ant derives SM/LG from this).
|
||||||
|
- Do **not** set `size="small"`, `size="middle"`, `size="large"`, or `:size` on `a-button`, `a-input`, `a-select`, `a-input-number`, `a-date-picker`, `a-radio-group`, `a-pagination`, or similar controls on migrated pages.
|
||||||
|
- Do **not** override `controlHeight` / `controlHeightSM` / `controlHeightLG` inside `components.*` of the theme — inherit the token default.
|
||||||
|
- Exception: only if the user explicitly requests a one-off non-default size for a named control.
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
10. **Icons**
|
||||||
|
Use `@ant-design/icons-vue` on migrated pages. Do not expand `UiIcon` for Ant pages.
|
||||||
|
|
||||||
|
11. **Isolation guarantee**
|
||||||
|
Infrastructure PRs (deps, vite plugin, theme, App `ConfigProvider`) must not change behavior of unmigrated pages. No `ant-design-vue/dist/reset.css` (or similar global reset) unless explicitly approved — it can break legacy CSS.
|
||||||
|
|
||||||
|
## Allowed on migrated pages
|
||||||
|
|
||||||
|
- Ant Design Vue 4 components and their props/slots (except banned manual `size` on controls)
|
||||||
|
- `a-row` / `a-col` (24 columns), `a-space`, `a-flex` where appropriate
|
||||||
|
- Theme tokens via ConfigProvider
|
||||||
|
- Minimal page-local script logic (data fetching, forms) unchanged in spirit
|
||||||
|
|
||||||
|
## Forbidden on migrated pages
|
||||||
|
|
||||||
|
- New legacy `components/ui` usage
|
||||||
|
- Parallel button/input CSS classes (`.btn`, `.field`, `.crm-*` for chrome that Ant replaces)
|
||||||
|
- Custom CSS that re-skins Ant components
|
||||||
|
- Manual `size` props on form/action controls (use theme default 36px)
|
||||||
|
- Multi-page refactors “while we’re here”
|
||||||
|
- Adding Tailwind/Bootstrap/other UI kits
|
||||||
|
|
||||||
|
## Agent checklist before finishing a migration PR
|
||||||
|
|
||||||
|
- [ ] Only one page/route touched for UI migration
|
||||||
|
- [ ] Imported child components with controls also converted to Ant (no raw HTML left)
|
||||||
|
- [ ] Grep verification: `<input|<select|<textarea|<button|UiInput|UiSelect|UiField|UiTextarea|UiButton` count is **0** in the View + those children
|
||||||
|
- [ ] No changes under `components/ui/`
|
||||||
|
- [ ] No new scoped CSS for look-and-feel
|
||||||
|
- [ ] No manual `size` on Ant controls
|
||||||
|
- [ ] Layout uses 24-col Ant grid
|
||||||
|
- [ ] Uses `antdTheme` / ConfigProvider / StyleProvider `hash-priority="high"` — no local theme fork
|
||||||
|
- [ ] `npm run build -w @mento/web` (or `vue-tsc`) passes
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
name: antd-system-architect
|
||||||
|
description: >-
|
||||||
|
Architect and migrate Montact web UI to Ant Design Vue v4 under strict
|
||||||
|
governance: single-page lock, no manual CSS, no manual size props, default
|
||||||
|
controlHeight 36, 24-column grid, central antdTheme, isolated from legacy
|
||||||
|
components/ui. Use when migrating a page to Ant Design, adding Ant components,
|
||||||
|
editing antdTheme, or reviewing Ant PRs.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ant Design Vue System Architect (Montact)
|
||||||
|
|
||||||
|
## When to use
|
||||||
|
|
||||||
|
- Migrating any `apps/web` view/page to Ant Design Vue 4
|
||||||
|
- Extending [`apps/web/src/theme/antdTheme.ts`](../../../apps/web/src/theme/antdTheme.ts)
|
||||||
|
- Touching Ant ConfigProvider / vite Ant auto-import
|
||||||
|
- Reviewing whether a change violates isolation from legacy UI
|
||||||
|
|
||||||
|
Also read and obey [`.cursor/rules/antd-strict-governance.mdc`](../../rules/antd-strict-governance.mdc).
|
||||||
|
|
||||||
|
## Non-negotiables
|
||||||
|
|
||||||
|
1. **One page per migration** — never batch unrelated views.
|
||||||
|
2. **Do not edit** `apps/web/src/components/ui/**` during Ant migration work.
|
||||||
|
3. **Child components of the View are in scope (mandatory)** — هنگام بازنویسی یک صفحه (View)، ایجنت موظف است علاوه بر خود فایل View، تمام کامپوننتهای فرزندی را که در آن View ایمپورت شدهاند و حاوی اینپوت/سلکت/دکمه هستند نیز بازبینی کرده و درون آنها را به کامپوننتهای رسمی `ant-design-vue` تبدیل کند. هیچ تگ `<input>`, `<select>`, `<textarea>`, `<button>` خامی نباید در صفحه یا کامپوننتهای فرزندِ مصرفی آن باقی بماند. When rewriting a View, also open every imported child that renders inputs/selects/buttons and convert them to official `ant-design-vue` controls. No raw `<input>`, `<select>`, `<textarea>`, or `<button>` (and no `UiInput` / `UiSelect` / `UiButton` / `UiField` / `UiTextarea`) may remain in the View or those children. Prefer Ant natives (`a-select` multiple/tags, `a-time-picker`, …); for Jalali/domain pickers, convert the child file to Ant chrome (`a-input` + `a-popover`, etc.).
|
||||||
|
4. **No manual look CSS** on migrated pages (no new scoped colors/spacing/radius/shadows for chrome).
|
||||||
|
5. **24-column Ant grid** (`a-row` / `a-col`) for page layout.
|
||||||
|
6. **Theme only in** `apps/web/src/theme/antdTheme.ts`.
|
||||||
|
7. **Default control height is 36** via token `controlHeight: 36`. Do **not** pass `size` / `:size` on buttons, inputs, selects, or similar controls; do **not** set per-component `controlHeight*` in the theme `components` map.
|
||||||
|
8. **Auto-import** `<a-*>` via `AntDesignVueResolver({ importStyle: false })` — no per-file style imports. Root uses `StyleProvider` with `hash-priority="high"` so legacy `main.css` cannot override Ant.
|
||||||
|
9. **No global Ant reset CSS** that would restyle legacy pages.
|
||||||
|
|
||||||
|
## Stack facts (this repo)
|
||||||
|
|
||||||
|
| Piece | Location |
|
||||||
|
|---|---|
|
||||||
|
| 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">` |
|
||||||
|
| Legacy kit (do not touch) | `apps/web/src/components/ui/*`, `styles/main.css` utilities |
|
||||||
|
|
||||||
|
## Migration workflow
|
||||||
|
|
||||||
|
1. Confirm the **single** route/view the user named.
|
||||||
|
2. Inventory current UI: legacy `Ui*`, `.btn`/`.field`, `.crm-*`, custom tables.
|
||||||
|
3. List all imported children that contain controls; convert them in the same pass (except `components/ui/**`).
|
||||||
|
4. Replace with Ant equivalents:
|
||||||
|
- Button → `a-button` (**no** `size` prop)
|
||||||
|
- Input/Select/Form field → `a-form` + `a-form-item` + `a-input` / `a-select` / … (**no** `size`)
|
||||||
|
- Modal/Drawer → `a-modal` / `a-drawer`
|
||||||
|
- Table → `a-table` (columns via Ant API)
|
||||||
|
- Page chrome → `a-card`, title + `a-space`, layout via `a-row`/`a-col`
|
||||||
|
- Icons → `@ant-design/icons-vue`
|
||||||
|
5. Remove page-local CSS that only existed to skin the old controls.
|
||||||
|
6. Keep business logic, API calls, and router behavior intact.
|
||||||
|
7. Grep-verify zero hits for `<input|<select|<textarea|<button|UiInput|UiSelect|UiField|UiTextarea|UiButton` in the View + converted children.
|
||||||
|
8. Run `npm run build -w @mento/web` (or at least `vue-tsc -b` in `apps/web`).
|
||||||
|
9. Smoke-check that **other** routes still render with legacy UI unchanged.
|
||||||
|
|
||||||
|
## Theme extension rules
|
||||||
|
|
||||||
|
- Change tokens in `antdTheme.ts` only when the user asks or when a migrated page proves a missing token.
|
||||||
|
- Keep `controlHeight: 36` as the single source for control sizing; let Ant derive SM/LG.
|
||||||
|
- Prefer `token` and limited `components.Card` / `components.Form` overrides — never per-control `controlHeight` forks.
|
||||||
|
- Do not duplicate `ThemeConfig` objects inside views.
|
||||||
|
|
||||||
|
## Anti-patterns (reject)
|
||||||
|
|
||||||
|
- Importing both `UiButton` and `a-button` on the same migrated page
|
||||||
|
- Adding `ant-design-vue/dist/reset.css` “to fix spacing”
|
||||||
|
- Editing `components/ui` to “look more like Ant”
|
||||||
|
- `size="small|middle|large"` on Ant controls
|
||||||
|
- Multi-page visual refactors in one PR
|
||||||
|
- Custom CSS overriding `.ant-btn` / `.ant-input` selectors
|
||||||
|
|
||||||
|
## Done criteria
|
||||||
|
|
||||||
|
- Migrated page uses Ant components + 24-col grid
|
||||||
|
- Imported control-bearing children also Ant-pure (grep = 0)
|
||||||
|
- Controls use theme default height (no manual `size`)
|
||||||
|
- No new manual chrome CSS
|
||||||
|
- Legacy kit untouched
|
||||||
|
- Build/typecheck clean
|
||||||
|
- Unmigrated pages untouched in the diff
|
||||||
+1
-1
@@ -17,7 +17,7 @@ SMS_PASSWORD=
|
|||||||
SMS_SENDER=
|
SMS_SENDER=
|
||||||
# SMS_BASE_URL=http://smspanel.Trez.ir
|
# SMS_BASE_URL=http://smspanel.Trez.ir
|
||||||
# SMS_SEND_PATH=/SendMessageWithCode.ashx
|
# SMS_SEND_PATH=/SendMessageWithCode.ashx
|
||||||
# SMS_OTP_TEMPLATE=کد ورود پرتال منتکت: {code}
|
# SMS_OTP_TEMPLATE=کد ورود منتکت: {code}
|
||||||
# SMS_TIMEOUT_MS=20000
|
# SMS_TIMEOUT_MS=20000
|
||||||
|
|
||||||
# رمزنگاری توکنهای اتصال حسابداری (تهحساب) — ۳۲ بایت بهصورت hex (۶۴ کاراکتر)
|
# رمزنگاری توکنهای اتصال حسابداری (تهحساب) — ۳۲ بایت بهصورت hex (۶۴ کاراکتر)
|
||||||
|
|||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# فعالسازی: npm install (اسکریپت prepare) یا git config core.hooksPath .githooks
|
||||||
|
npm run check
|
||||||
+15
@@ -21,3 +21,18 @@ docs/~$*
|
|||||||
*.py[cod]
|
*.py[cod]
|
||||||
apps/stt/.venv/
|
apps/stt/.venv/
|
||||||
crm-node_modules.tgz
|
crm-node_modules.tgz
|
||||||
|
|
||||||
|
# Playwright
|
||||||
|
e2e/.auth/
|
||||||
|
e2e/.env
|
||||||
|
test-results/
|
||||||
|
playwright-report/
|
||||||
|
|
||||||
|
# Graphify (local architecture graph — do not commit)
|
||||||
|
graphify-out/
|
||||||
|
**/graphify-out/
|
||||||
|
.cursor/rules/graphify.mdc
|
||||||
|
|
||||||
|
# Local git worktrees + SDD scratch
|
||||||
|
.worktrees/
|
||||||
|
.superpowers/
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ $env:MENTO_DEV_API="http://127.0.0.1:3000"; npm run dev
|
|||||||
|
|
||||||
## فاز فعلی
|
## فاز فعلی
|
||||||
|
|
||||||
فاز ۱ هسته فروش/پشتیبانی و Smart Notes عملاً کامل است. جزئیات تیکخورده و باقیمانده:
|
فاز ۱ هسته فروش/پشتیبانی، Smart Notes، مالی سبک و اتصالها (API، ووکامرس، VoIP، پیامک گروهی) عملاً کامل است. جزئیات تیکخورده و باقیمانده:
|
||||||
|
|
||||||
- [`docs/وضعیت-پیشرفت.md`](docs/وضعیت-پیشرفت.md) ← **چکلیست زنده**
|
- [`docs/وضعیت-پیشرفت.md`](docs/وضعیت-پیشرفت.md) ← **چکلیست زنده**
|
||||||
- [`docs/قابلیتهای-منتکت.md`](docs/قابلیتهای-منتکت.md) ← فهرست کوتاه قابلیتها
|
- [`docs/قابلیتهای-منتکت.md`](docs/قابلیتهای-منتکت.md) ← فهرست کوتاه قابلیتها
|
||||||
|
|||||||
@@ -10,7 +10,9 @@
|
|||||||
"prisma:generate": "prisma generate",
|
"prisma:generate": "prisma generate",
|
||||||
"prisma:migrate": "prisma migrate dev",
|
"prisma:migrate": "prisma migrate dev",
|
||||||
"prisma:seed": "tsx prisma/seed.ts",
|
"prisma:seed": "tsx prisma/seed.ts",
|
||||||
"lint": "echo \"api lint placeholder\""
|
"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/attendance-time.test.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@mento/shared": "*",
|
"@mento/shared": "*",
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ProductAccountingLink" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"productId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"externalName" TEXT NOT NULL,
|
||||||
|
"ayar" INTEGER,
|
||||||
|
"vaznSabet" DOUBLE PRECISION,
|
||||||
|
"matchMethod" TEXT NOT NULL DEFAULT 'import',
|
||||||
|
"linkedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ProductAccountingLink_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ProductAccountingLink_productId_idx" ON "ProductAccountingLink"("productId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ProductAccountingLink_connectionId_idx" ON "ProductAccountingLink"("connectionId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ProductAccountingLink_productId_connectionId_key" ON "ProductAccountingLink"("productId", "connectionId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ProductAccountingLink_connectionId_externalName_key" ON "ProductAccountingLink"("connectionId", "externalName");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ProductAccountingLink" ADD CONSTRAINT "ProductAccountingLink_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ProductAccountingLink" ADD CONSTRAINT "ProductAccountingLink_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "AccountingConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN "website" TEXT;
|
||||||
|
ALTER TABLE "Person" ADD COLUMN "referrer" TEXT;
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "tags" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "tags" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN IF NOT EXISTS "tags" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ProjectCard" ADD COLUMN IF NOT EXISTS "tags" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "AuditLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"actorUserId" TEXT,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"method" TEXT NOT NULL,
|
||||||
|
"path" TEXT NOT NULL,
|
||||||
|
"entityType" TEXT,
|
||||||
|
"entityId" TEXT,
|
||||||
|
"summary" TEXT NOT NULL,
|
||||||
|
"meta" JSONB,
|
||||||
|
"ip" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "SavedView" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"ownerUserId" TEXT,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"scope" TEXT NOT NULL,
|
||||||
|
"filters" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"isShared" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "SavedView_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable (implicit many-to-many ProjectCard <-> User assignees)
|
||||||
|
CREATE TABLE IF NOT EXISTS "_ProjectCardAssignees" (
|
||||||
|
"A" TEXT NOT NULL,
|
||||||
|
"B" TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_organizationId_createdAt_idx" ON "AuditLog"("organizationId", "createdAt");
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_organizationId_actorUserId_createdAt_idx" ON "AuditLog"("organizationId", "actorUserId", "createdAt");
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_organizationId_entityType_createdAt_idx" ON "AuditLog"("organizationId", "entityType", "createdAt");
|
||||||
|
CREATE INDEX IF NOT EXISTS "SavedView_organizationId_scope_idx" ON "SavedView"("organizationId", "scope");
|
||||||
|
CREATE INDEX IF NOT EXISTS "SavedView_organizationId_ownerUserId_idx" ON "SavedView"("organizationId", "ownerUserId");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "_ProjectCardAssignees_AB_unique" ON "_ProjectCardAssignees"("A", "B");
|
||||||
|
CREATE INDEX IF NOT EXISTS "_ProjectCardAssignees_B_index" ON "_ProjectCardAssignees"("B");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_actorUserId_fkey" FOREIGN KEY ("actorUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "SavedView" ADD CONSTRAINT "SavedView_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "SavedView" ADD CONSTRAINT "SavedView_ownerUserId_fkey" FOREIGN KEY ("ownerUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "_ProjectCardAssignees" ADD CONSTRAINT "_ProjectCardAssignees_A_fkey" FOREIGN KEY ("A") REFERENCES "ProjectCard"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "_ProjectCardAssignees" ADD CONSTRAINT "_ProjectCardAssignees_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
+93
@@ -0,0 +1,93 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "OrganizationApiKey" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"prefix" TEXT NOT NULL,
|
||||||
|
"keyHash" TEXT NOT NULL,
|
||||||
|
"lastUsedAt" TIMESTAMP(3),
|
||||||
|
"revokedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "OrganizationApiKey_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "WebhookEndpoint" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"secret" TEXT NOT NULL,
|
||||||
|
"events" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "WebhookDelivery" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"endpointId" TEXT NOT NULL,
|
||||||
|
"event" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"statusCode" INTEGER,
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"lastError" TEXT,
|
||||||
|
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"deliveredAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "SmsCampaign" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'draft',
|
||||||
|
"scheduledAt" TIMESTAMP(3),
|
||||||
|
"totalCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"sentCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"failedCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"skippedCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "SmsCampaign_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "SmsCampaignRecipient" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"campaignId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT,
|
||||||
|
"mobile" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"error" TEXT,
|
||||||
|
"sentAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "SmsCampaignRecipient_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "OrganizationApiKey_keyHash_key" ON "OrganizationApiKey"("keyHash");
|
||||||
|
CREATE INDEX "OrganizationApiKey_organizationId_revokedAt_idx" ON "OrganizationApiKey"("organizationId", "revokedAt");
|
||||||
|
CREATE INDEX "OrganizationApiKey_prefix_idx" ON "OrganizationApiKey"("prefix");
|
||||||
|
CREATE INDEX "WebhookEndpoint_organizationId_isActive_idx" ON "WebhookEndpoint"("organizationId", "isActive");
|
||||||
|
CREATE INDEX "WebhookDelivery_organizationId_createdAt_idx" ON "WebhookDelivery"("organizationId", "createdAt");
|
||||||
|
CREATE INDEX "WebhookDelivery_status_nextAttemptAt_idx" ON "WebhookDelivery"("status", "nextAttemptAt");
|
||||||
|
CREATE INDEX "WebhookDelivery_endpointId_createdAt_idx" ON "WebhookDelivery"("endpointId", "createdAt");
|
||||||
|
CREATE INDEX "SmsCampaign_organizationId_status_scheduledAt_idx" ON "SmsCampaign"("organizationId", "status", "scheduledAt");
|
||||||
|
CREATE INDEX "SmsCampaignRecipient_campaignId_status_idx" ON "SmsCampaignRecipient"("campaignId", "status");
|
||||||
|
|
||||||
|
ALTER TABLE "OrganizationApiKey" ADD CONSTRAINT "OrganizationApiKey_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "WebhookEndpoint" ADD CONSTRAINT "WebhookEndpoint_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SmsCampaign" ADD CONSTRAINT "SmsCampaign_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SmsCampaignRecipient" ADD CONSTRAINT "SmsCampaignRecipient_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "SmsCampaign"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN "dataVisibility" TEXT NOT NULL DEFAULT 'own';
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Team" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL DEFAULT '',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Team_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TeamMember" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"teamId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"role" TEXT NOT NULL DEFAULT 'member',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TeamMember_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Team_organizationId_idx" ON "Team"("organizationId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Team_organizationId_name_key" ON "Team"("organizationId", "name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TeamMember_userId_idx" ON "TeamMember"("userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "TeamMember_teamId_idx" ON "TeamMember"("teamId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TeamMember_teamId_userId_key" ON "TeamMember"("teamId", "userId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Team" ADD CONSTRAINT "Team_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TeamMember" ADD CONSTRAINT "TeamMember_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TeamMember" ADD CONSTRAINT "TeamMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "WooCommerceConnection" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"storeUrl" TEXT NOT NULL,
|
||||||
|
"consumerKeyCiphertext" TEXT NOT NULL,
|
||||||
|
"consumerKeyIv" TEXT NOT NULL,
|
||||||
|
"consumerKeyTag" TEXT NOT NULL,
|
||||||
|
"consumerKeyLast4" TEXT NOT NULL DEFAULT '',
|
||||||
|
"consumerSecretCiphertext" TEXT NOT NULL,
|
||||||
|
"consumerSecretIv" TEXT NOT NULL,
|
||||||
|
"consumerSecretTag" TEXT NOT NULL,
|
||||||
|
"webhookSecretCiphertext" TEXT,
|
||||||
|
"webhookSecretIv" TEXT,
|
||||||
|
"webhookSecretTag" TEXT,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"lastSyncAt" TIMESTAMP(3),
|
||||||
|
"lastHealthAt" TIMESTAMP(3),
|
||||||
|
"lastHealthOk" BOOLEAN,
|
||||||
|
"lastError" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "WooCommerceConnection_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "WooCommerceOrderLink" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"wooOrderId" TEXT NOT NULL,
|
||||||
|
"wooOrderNumber" TEXT,
|
||||||
|
"invoiceId" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT '',
|
||||||
|
"total" DECIMAL(18,2) NOT NULL DEFAULT 0,
|
||||||
|
"currency" TEXT NOT NULL DEFAULT 'IRR',
|
||||||
|
"rawPayload" JSONB,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "WooCommerceOrderLink_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "WooCommerceConnection_organizationId_enabled_idx" ON "WooCommerceConnection"("organizationId", "enabled");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "WooCommerceOrderLink_organizationId_syncedAt_idx" ON "WooCommerceOrderLink"("organizationId", "syncedAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "WooCommerceOrderLink_invoiceId_idx" ON "WooCommerceOrderLink"("invoiceId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "WooCommerceOrderLink_connectionId_wooOrderId_key" ON "WooCommerceOrderLink"("connectionId", "wooOrderId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "WooCommerceConnection" ADD CONSTRAINT "WooCommerceConnection_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "WooCommerceOrderLink" ADD CONSTRAINT "WooCommerceOrderLink_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "WooCommerceConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "VoipConnection" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"webhookSecretCiphertext" TEXT,
|
||||||
|
"webhookSecretIv" TEXT,
|
||||||
|
"webhookSecretTag" TEXT,
|
||||||
|
"clickToCallUrl" TEXT,
|
||||||
|
"lastEventAt" TIMESTAMP(3),
|
||||||
|
"lastError" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "VoipConnection_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "VoipCallLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"externalCallId" TEXT NOT NULL,
|
||||||
|
"direction" TEXT NOT NULL DEFAULT 'inbound',
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'completed',
|
||||||
|
"fromNumber" TEXT,
|
||||||
|
"toNumber" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"activityId" TEXT,
|
||||||
|
"durationSec" INTEGER,
|
||||||
|
"startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"endedAt" TIMESTAMP(3),
|
||||||
|
"rawPayload" JSONB,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "VoipCallLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipConnection_organizationId_enabled_idx" ON "VoipConnection"("organizationId", "enabled");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipCallLog_organizationId_syncedAt_idx" ON "VoipCallLog"("organizationId", "syncedAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipCallLog_personId_idx" ON "VoipCallLog"("personId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipCallLog_activityId_idx" ON "VoipCallLog"("activityId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "VoipCallLog_connectionId_externalCallId_key" ON "VoipCallLog"("connectionId", "externalCallId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "VoipConnection" ADD CONSTRAINT "VoipConnection_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "VoipCallLog" ADD CONSTRAINT "VoipCallLog_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "VoipConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ReservationService" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL DEFAULT '',
|
||||||
|
"durationMinutes" INTEGER NOT NULL DEFAULT 30,
|
||||||
|
"workDays" INTEGER[] DEFAULT ARRAY[0, 1, 2, 3, 4, 5, 6]::INTEGER[],
|
||||||
|
"dayStartHour" INTEGER NOT NULL DEFAULT 9,
|
||||||
|
"dayEndHour" INTEGER NOT NULL DEFAULT 17,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ReservationService_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ReservationAppointment" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"serviceId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT NOT NULL,
|
||||||
|
"assigneeId" TEXT,
|
||||||
|
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"endsAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"notes" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ReservationAppointment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationService_organizationId_isActive_idx" ON "ReservationService"("organizationId", "isActive");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationAppointment_organizationId_startsAt_idx" ON "ReservationAppointment"("organizationId", "startsAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationAppointment_organizationId_status_idx" ON "ReservationAppointment"("organizationId", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationAppointment_serviceId_startsAt_idx" ON "ReservationAppointment"("serviceId", "startsAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationAppointment_personId_idx" ON "ReservationAppointment"("personId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ReservationAppointment_assigneeId_startsAt_idx" ON "ReservationAppointment"("assigneeId", "startsAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ReservationService" ADD CONSTRAINT "ReservationService_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ReservationAppointment" ADD CONSTRAINT "ReservationAppointment_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ReservationAppointment" ADD CONSTRAINT "ReservationAppointment_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "ReservationService"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ReservationAppointment" ADD CONSTRAINT "ReservationAppointment_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ReservationAppointment" ADD CONSTRAINT "ReservationAppointment_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Note" ADD COLUMN "visibility" TEXT NOT NULL DEFAULT 'team';
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Note_organizationId_visibility_idx" ON "Note"("organizationId", "visibility");
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "NoteRevision" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"noteId" TEXT NOT NULL,
|
||||||
|
"editorId" TEXT,
|
||||||
|
"title" TEXT,
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"noteType" TEXT NOT NULL,
|
||||||
|
"visibility" TEXT NOT NULL DEFAULT 'team',
|
||||||
|
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"checklist" JSONB,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "NoteRevision_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "NoteRevision_noteId_createdAt_idx" ON "NoteRevision"("noteId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "NoteRevision_organizationId_idx" ON "NoteRevision"("organizationId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "NoteRevision_editorId_idx" ON "NoteRevision"("editorId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "NoteRevision" ADD CONSTRAINT "NoteRevision_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "NoteRevision" ADD CONSTRAINT "NoteRevision_noteId_fkey" FOREIGN KEY ("noteId") REFERENCES "Note"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "NoteRevision" ADD CONSTRAINT "NoteRevision_editorId_fkey" FOREIGN KEY ("editorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "_DealAssignees" (
|
||||||
|
"A" TEXT NOT NULL,
|
||||||
|
"B" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "_DealAssignees_AB_pkey" PRIMARY KEY ("A","B")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "_DealAssignees_B_index" ON "_DealAssignees"("B");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "_DealAssignees" ADD CONSTRAINT "_DealAssignees_A_fkey" FOREIGN KEY ("A") REFERENCES "Deal"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "_DealAssignees" ADD CONSTRAINT "_DealAssignees_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "recordingUrl" TEXT;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "transcript" TEXT;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summary" TEXT;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summaryStatus" TEXT NOT NULL DEFAULT 'none';
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summaryNoteId" TEXT;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summaryError" TEXT;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summaryAttempts" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "VoipCallLog" ADD COLUMN "summaryNextAttemptAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipCallLog_summaryStatus_summaryNextAttemptAt_idx" ON "VoipCallLog"("summaryStatus", "summaryNextAttemptAt");
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "LeadStage" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"color" TEXT NOT NULL DEFAULT 'teal',
|
||||||
|
"showOnBoard" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"isConverted" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"isLost" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"isUnqualified" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "LeadStage_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Lead" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"contactName" TEXT,
|
||||||
|
"mobile" TEXT NOT NULL,
|
||||||
|
"phone" TEXT,
|
||||||
|
"city" TEXT,
|
||||||
|
"region" TEXT,
|
||||||
|
"trade" TEXT,
|
||||||
|
"source" TEXT,
|
||||||
|
"notes" TEXT,
|
||||||
|
"estimatedValue" DECIMAL(18,2),
|
||||||
|
"stageId" TEXT NOT NULL,
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"assigneeId" TEXT,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"lastContactAt" TIMESTAMP(3),
|
||||||
|
"nextFollowUpAt" TIMESTAMP(3),
|
||||||
|
"convertedPersonId" TEXT,
|
||||||
|
"convertedAt" TIMESTAMP(3),
|
||||||
|
"archivedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Lead_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "LeadEvent" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"leadId" TEXT NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"body" TEXT,
|
||||||
|
"meta" JSONB,
|
||||||
|
"actorId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "LeadEvent_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "LeadImportJob" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"fileName" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"totalCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"processedCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"successCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"duplicateCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"errorCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"rows" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"errorSamples" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"startedAt" TIMESTAMP(3),
|
||||||
|
"finishedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "LeadImportJob_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "LeadStage_organizationId_position_idx" ON "LeadStage"("organizationId", "position");
|
||||||
|
CREATE UNIQUE INDEX "LeadStage_organizationId_name_key" ON "LeadStage"("organizationId", "name");
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "Lead_organizationId_mobile_key" ON "Lead"("organizationId", "mobile");
|
||||||
|
CREATE INDEX "Lead_organizationId_stageId_position_idx" ON "Lead"("organizationId", "stageId", "position");
|
||||||
|
CREATE INDEX "Lead_organizationId_assigneeId_idx" ON "Lead"("organizationId", "assigneeId");
|
||||||
|
CREATE INDEX "Lead_organizationId_nextFollowUpAt_idx" ON "Lead"("organizationId", "nextFollowUpAt");
|
||||||
|
CREATE INDEX "Lead_organizationId_lastContactAt_idx" ON "Lead"("organizationId", "lastContactAt");
|
||||||
|
CREATE INDEX "Lead_organizationId_archivedAt_idx" ON "Lead"("organizationId", "archivedAt");
|
||||||
|
CREATE INDEX "Lead_organizationId_createdAt_idx" ON "Lead"("organizationId", "createdAt");
|
||||||
|
CREATE INDEX "Lead_organizationId_city_idx" ON "Lead"("organizationId", "city");
|
||||||
|
CREATE INDEX "Lead_organizationId_trade_idx" ON "Lead"("organizationId", "trade");
|
||||||
|
CREATE INDEX "Lead_organizationId_source_idx" ON "Lead"("organizationId", "source");
|
||||||
|
|
||||||
|
CREATE INDEX "LeadEvent_leadId_createdAt_idx" ON "LeadEvent"("leadId", "createdAt");
|
||||||
|
CREATE INDEX "LeadEvent_organizationId_createdAt_idx" ON "LeadEvent"("organizationId", "createdAt");
|
||||||
|
|
||||||
|
CREATE INDEX "LeadImportJob_organizationId_status_createdAt_idx" ON "LeadImportJob"("organizationId", "status", "createdAt");
|
||||||
|
CREATE INDEX "LeadImportJob_status_createdAt_idx" ON "LeadImportJob"("status", "createdAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "LeadStage" ADD CONSTRAINT "LeadStage_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "Lead" ADD CONSTRAINT "Lead_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "Lead" ADD CONSTRAINT "Lead_stageId_fkey" FOREIGN KEY ("stageId") REFERENCES "LeadStage"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "Lead" ADD CONSTRAINT "Lead_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "Lead" ADD CONSTRAINT "Lead_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "LeadEvent" ADD CONSTRAINT "LeadEvent_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "LeadEvent" ADD CONSTRAINT "LeadEvent_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "LeadImportJob" ADD CONSTRAINT "LeadImportJob_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Lead" ADD COLUMN IF NOT EXISTS "logoStorageKey" TEXT;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- AlterTable LeadForm: publish → Lead connection
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "createLead" BOOLEAN NOT NULL DEFAULT true;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "leadStageId" TEXT;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "duplicateMode" TEXT NOT NULL DEFAULT 'update';
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "viewCount" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "startCount" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "submitCount" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "leadCreateCount" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE "LeadForm" ADD COLUMN IF NOT EXISTS "duplicateCount" INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- Existing forms: keep person/deal behavior unless already lead-oriented
|
||||||
|
ALTER TABLE "LeadForm" ALTER COLUMN "createPerson" SET DEFAULT false;
|
||||||
|
ALTER TABLE "LeadForm" ALTER COLUMN "createDeal" SET DEFAULT false;
|
||||||
|
|
||||||
|
-- AlterTable LeadFormSubmission
|
||||||
|
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "leadId" TEXT;
|
||||||
|
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "status" TEXT NOT NULL DEFAULT 'created';
|
||||||
|
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "utm" JSONB;
|
||||||
|
ALTER TABLE "LeadFormSubmission" ADD COLUMN IF NOT EXISTS "meta" JSONB;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "LeadFormSubmission_leadId_idx" ON "LeadFormSubmission"("leadId");
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationSettings" (
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"chatHost" TEXT NOT NULL,
|
||||||
|
"apiKeyCipher" TEXT NOT NULL,
|
||||||
|
"apiKeyIv" TEXT NOT NULL,
|
||||||
|
"apiKeyTag" TEXT NOT NULL,
|
||||||
|
"uploadUrl" TEXT NOT NULL DEFAULT '',
|
||||||
|
"downloadUrl" TEXT NOT NULL DEFAULT '',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationSettings_pkey" PRIMARY KEY ("organizationId")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationRoom" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"dmUserMinId" TEXT,
|
||||||
|
"dmUserMaxId" TEXT,
|
||||||
|
"createdByUserId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationRoom_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationRoom_organizationId_externalRoomId_key" ON "ConversationRoom"("organizationId", "externalRoomId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationRoom_organizationId_dmUserMinId_dmUserMaxId_key" ON "ConversationRoom"("organizationId", "dmUserMinId", "dmUserMaxId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConversationRoom_organizationId_kind_idx" ON "ConversationRoom"("organizationId", "kind");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationSettings" ADD CONSTRAINT "ConversationSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationRoom" ADD CONSTRAINT "ConversationRoom_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationHiddenMessage" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"messageId" TEXT NOT NULL,
|
||||||
|
"hiddenByUserId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationHiddenMessage_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConversationHiddenMessage_organizationId_externalRoomId_idx" ON "ConversationHiddenMessage"("organizationId", "externalRoomId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationHiddenMessage_organizationId_externalRoomId_messageId_key" ON "ConversationHiddenMessage"("organizationId", "externalRoomId", "messageId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationHiddenMessage" ADD CONSTRAINT "ConversationHiddenMessage_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ConversationHiddenMessage" ADD COLUMN "scope" TEXT NOT NULL DEFAULT 'all';
|
||||||
|
|
||||||
|
-- DropIndex
|
||||||
|
DROP INDEX "ConversationHiddenMessage_organizationId_externalRoomId_messageId_key";
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationHiddenMessage_organizationId_externalRoomId_messageId_scope_hiddenByUserId_key" ON "ConversationHiddenMessage"("organizationId", "externalRoomId", "messageId", "scope", "hiddenByUserId");
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationPinnedMessage" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"messageId" TEXT NOT NULL,
|
||||||
|
"preview" TEXT NOT NULL DEFAULT '',
|
||||||
|
"pinnedByUserId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationPinnedMessage_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationRoomUserPin" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationRoomUserPin_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationPinnedMessage_organizationId_externalRoomId_key" ON "ConversationPinnedMessage"("organizationId", "externalRoomId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConversationPinnedMessage_organizationId_externalRoomId_idx" ON "ConversationPinnedMessage"("organizationId", "externalRoomId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationRoomUserPin_organizationId_userId_externalRoomId_key" ON "ConversationRoomUserPin"("organizationId", "userId", "externalRoomId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConversationRoomUserPin_organizationId_userId_idx" ON "ConversationRoomUserPin"("organizationId", "userId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationPinnedMessage" ADD CONSTRAINT "ConversationPinnedMessage_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationRoomUserPin" ADD CONSTRAINT "ConversationRoomUserPin_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConversationRoomMember" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"role" TEXT NOT NULL DEFAULT 'member',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationRoomMember_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ConversationRoomMember_organizationId_externalRoomId_userId_key" ON "ConversationRoomMember"("organizationId", "externalRoomId", "userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConversationRoomMember_organizationId_externalRoomId_idx" ON "ConversationRoomMember"("organizationId", "externalRoomId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConversationRoomMember" ADD CONSTRAINT "ConversationRoomMember_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- Mute per-user (smart: mentions can still notify)
|
||||||
|
CREATE TABLE "ConversationRoomUserMute" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"allowMentions" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationRoomUserMute_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "ConversationRoomUserMute_organizationId_userId_externalRoomId_key" ON "ConversationRoomUserMute"("organizationId", "userId", "externalRoomId");
|
||||||
|
CREATE INDEX "ConversationRoomUserMute_organizationId_userId_idx" ON "ConversationRoomUserMute"("organizationId", "userId");
|
||||||
|
ALTER TABLE "ConversationRoomUserMute" ADD CONSTRAINT "ConversationRoomUserMute_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Message emoji reactions
|
||||||
|
CREATE TABLE "ConversationMessageReaction" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"externalRoomId" TEXT NOT NULL,
|
||||||
|
"messageId" TEXT NOT NULL,
|
||||||
|
"emoji" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ConversationMessageReaction_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "ConversationMessageReaction_organizationId_externalRoomId_messageId_userId_emoji_key" ON "ConversationMessageReaction"("organizationId", "externalRoomId", "messageId", "userId", "emoji");
|
||||||
|
CREATE INDEX "ConversationMessageReaction_organizationId_externalRoomId_idx" ON "ConversationMessageReaction"("organizationId", "externalRoomId");
|
||||||
|
ALTER TABLE "ConversationMessageReaction" ADD CONSTRAINT "ConversationMessageReaction_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
-- Extend AutomationTrigger
|
||||||
|
CREATE TYPE "AutomationTrigger_new" AS ENUM (
|
||||||
|
'person_created',
|
||||||
|
'lead_submitted',
|
||||||
|
'deal_created',
|
||||||
|
'deal_stage_changed',
|
||||||
|
'deal_won',
|
||||||
|
'deal_lost',
|
||||||
|
'ticket_created',
|
||||||
|
'ticket_resolved',
|
||||||
|
'invoice_issued',
|
||||||
|
'invoice_paid',
|
||||||
|
'activity_done',
|
||||||
|
'sms_link_clicked'
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE "AutomationRule"
|
||||||
|
ALTER COLUMN "trigger" TYPE "AutomationTrigger_new"
|
||||||
|
USING ("trigger"::text::"AutomationTrigger_new");
|
||||||
|
|
||||||
|
ALTER TYPE "AutomationTrigger" RENAME TO "AutomationTrigger_old";
|
||||||
|
ALTER TYPE "AutomationTrigger_new" RENAME TO "AutomationTrigger";
|
||||||
|
DROP TYPE "AutomationTrigger_old";
|
||||||
|
|
||||||
|
-- Extend MessageAutomationTrigger
|
||||||
|
CREATE TYPE "MessageAutomationTrigger_new" AS ENUM (
|
||||||
|
'person_created',
|
||||||
|
'lead_submitted',
|
||||||
|
'deal_created',
|
||||||
|
'deal_stage_changed',
|
||||||
|
'deal_won',
|
||||||
|
'deal_lost',
|
||||||
|
'ticket_created',
|
||||||
|
'ticket_resolved',
|
||||||
|
'invoice_issued',
|
||||||
|
'invoice_paid',
|
||||||
|
'activity_created',
|
||||||
|
'activity_done',
|
||||||
|
'sms_link_clicked'
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE "MessageAutomationRule"
|
||||||
|
ALTER COLUMN "trigger" TYPE "MessageAutomationTrigger_new"
|
||||||
|
USING ("trigger"::text::"MessageAutomationTrigger_new");
|
||||||
|
|
||||||
|
ALTER TABLE "MessageAutomationJob"
|
||||||
|
ALTER COLUMN "trigger" TYPE "MessageAutomationTrigger_new"
|
||||||
|
USING ("trigger"::text::"MessageAutomationTrigger_new");
|
||||||
|
|
||||||
|
ALTER TYPE "MessageAutomationTrigger" RENAME TO "MessageAutomationTrigger_old";
|
||||||
|
ALTER TYPE "MessageAutomationTrigger_new" RENAME TO "MessageAutomationTrigger";
|
||||||
|
DROP TYPE "MessageAutomationTrigger_old";
|
||||||
|
|
||||||
|
-- Recipient: optional leadId for future Lead campaigns
|
||||||
|
ALTER TABLE "SmsCampaignRecipient" ADD COLUMN "leadId" TEXT;
|
||||||
|
CREATE INDEX "SmsCampaignRecipient_personId_idx" ON "SmsCampaignRecipient"("personId");
|
||||||
|
CREATE INDEX "SmsCampaignRecipient_leadId_idx" ON "SmsCampaignRecipient"("leadId");
|
||||||
|
|
||||||
|
-- TrackingLink
|
||||||
|
CREATE TABLE "TrackingLink" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"token" TEXT NOT NULL,
|
||||||
|
"originalUrl" TEXT NOT NULL,
|
||||||
|
"channel" TEXT NOT NULL DEFAULT 'sms',
|
||||||
|
"sourceType" TEXT NOT NULL,
|
||||||
|
"sourceId" TEXT NOT NULL,
|
||||||
|
"recipientType" TEXT,
|
||||||
|
"recipientId" TEXT,
|
||||||
|
"smsRecipientId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"leadId" TEXT,
|
||||||
|
"clickCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"firstClickedAt" TIMESTAMP(3),
|
||||||
|
"lastClickedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TrackingLink_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "TrackingLink_token_key" ON "TrackingLink"("token");
|
||||||
|
CREATE INDEX "TrackingLink_organizationId_sourceType_sourceId_idx" ON "TrackingLink"("organizationId", "sourceType", "sourceId");
|
||||||
|
CREATE INDEX "TrackingLink_organizationId_personId_idx" ON "TrackingLink"("organizationId", "personId");
|
||||||
|
CREATE INDEX "TrackingLink_organizationId_leadId_idx" ON "TrackingLink"("organizationId", "leadId");
|
||||||
|
CREATE INDEX "TrackingLink_smsRecipientId_idx" ON "TrackingLink"("smsRecipientId");
|
||||||
|
CREATE INDEX "TrackingLink_token_idx" ON "TrackingLink"("token");
|
||||||
|
|
||||||
|
ALTER TABLE "TrackingLink" ADD CONSTRAINT "TrackingLink_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingLink" ADD CONSTRAINT "TrackingLink_smsRecipientId_fkey" FOREIGN KEY ("smsRecipientId") REFERENCES "SmsCampaignRecipient"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingLink" ADD CONSTRAINT "TrackingLink_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingLink" ADD CONSTRAINT "TrackingLink_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- TrackingEvent
|
||||||
|
CREATE TABLE "TrackingEvent" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"trackingLinkId" TEXT,
|
||||||
|
"eventType" TEXT NOT NULL,
|
||||||
|
"channel" TEXT NOT NULL DEFAULT 'sms',
|
||||||
|
"sourceType" TEXT,
|
||||||
|
"sourceId" TEXT,
|
||||||
|
"recipientType" TEXT,
|
||||||
|
"recipientId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"leadId" TEXT,
|
||||||
|
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"metadata" JSONB,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TrackingEvent_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "TrackingEvent_organizationId_eventType_occurredAt_idx" ON "TrackingEvent"("organizationId", "eventType", "occurredAt");
|
||||||
|
CREATE INDEX "TrackingEvent_organizationId_sourceType_sourceId_eventType_idx" ON "TrackingEvent"("organizationId", "sourceType", "sourceId", "eventType");
|
||||||
|
CREATE INDEX "TrackingEvent_organizationId_personId_eventType_idx" ON "TrackingEvent"("organizationId", "personId", "eventType");
|
||||||
|
CREATE INDEX "TrackingEvent_organizationId_leadId_eventType_idx" ON "TrackingEvent"("organizationId", "leadId", "eventType");
|
||||||
|
CREATE INDEX "TrackingEvent_trackingLinkId_occurredAt_idx" ON "TrackingEvent"("trackingLinkId", "occurredAt");
|
||||||
|
|
||||||
|
ALTER TABLE "TrackingEvent" ADD CONSTRAINT "TrackingEvent_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingEvent" ADD CONSTRAINT "TrackingEvent_trackingLinkId_fkey" FOREIGN KEY ("trackingLinkId") REFERENCES "TrackingLink"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingEvent" ADD CONSTRAINT "TrackingEvent_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "TrackingEvent" ADD CONSTRAINT "TrackingEvent_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "instagram" TEXT;
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "addresses" JSONB NOT NULL DEFAULT '[]';
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Lead" ADD COLUMN IF NOT EXISTS "instagram" TEXT;
|
||||||
|
ALTER TABLE "Lead" ADD COLUMN IF NOT EXISTS "addresses" JSONB NOT NULL DEFAULT '[]';
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- OrgRole hierarchy (parent / child sub-roles)
|
||||||
|
ALTER TABLE "OrgRole" ADD COLUMN IF NOT EXISTS "parentId" TEXT;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "OrgRole_parentId_idx" ON "OrgRole"("parentId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "OrgRole_organizationId_parentId_idx" ON "OrgRole"("organizationId", "parentId");
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'OrgRole_parentId_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "OrgRole"
|
||||||
|
ADD CONSTRAINT "OrgRole_parentId_fkey"
|
||||||
|
FOREIGN KEY ("parentId") REFERENCES "OrgRole"("id")
|
||||||
|
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
-- Multi-assignee support for activities (implicit many-to-many)
|
||||||
|
CREATE TABLE IF NOT EXISTS "_ActivityAssignees" (
|
||||||
|
"A" TEXT NOT NULL,
|
||||||
|
"B" TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "_ActivityAssignees_AB_unique" ON "_ActivityAssignees"("A", "B");
|
||||||
|
CREATE INDEX IF NOT EXISTS "_ActivityAssignees_B_index" ON "_ActivityAssignees"("B");
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = '_ActivityAssignees_A_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "_ActivityAssignees"
|
||||||
|
ADD CONSTRAINT "_ActivityAssignees_A_fkey"
|
||||||
|
FOREIGN KEY ("A") REFERENCES "Activity"("id")
|
||||||
|
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = '_ActivityAssignees_B_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "_ActivityAssignees"
|
||||||
|
ADD CONSTRAINT "_ActivityAssignees_B_fkey"
|
||||||
|
FOREIGN KEY ("B") REFERENCES "User"("id")
|
||||||
|
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Backfill from legacy single assigneeId
|
||||||
|
INSERT INTO "_ActivityAssignees" ("A", "B")
|
||||||
|
SELECT a."id", a."assigneeId"
|
||||||
|
FROM "Activity" a
|
||||||
|
WHERE a."assigneeId" IS NOT NULL
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "previousFirstName" TEXT;
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "previousLastName" TEXT;
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "importSource" TEXT NOT NULL DEFAULT 'manual';
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "sourceRef" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX IF NOT EXISTS "Person_organizationId_importSource_idx" ON "Person"("organizationId", "importSource");
|
||||||
|
CREATE INDEX IF NOT EXISTS "Person_organizationId_sourceRef_idx" ON "Person"("organizationId", "sourceRef");
|
||||||
|
|
||||||
|
-- Backfill from legacy customFields / notes
|
||||||
|
UPDATE "Person"
|
||||||
|
SET
|
||||||
|
"importSource" = 'didar',
|
||||||
|
"sourceRef" = COALESCE(NULLIF(BTRIM("sourceRef"), ''), NULLIF(BTRIM("customFields"->>'didarId'), ''))
|
||||||
|
WHERE COALESCE(BTRIM("customFields"->>'didarId'), '') <> '';
|
||||||
|
|
||||||
|
UPDATE "Person"
|
||||||
|
SET "importSource" = 'tahesab'
|
||||||
|
WHERE "importSource" = 'manual'
|
||||||
|
AND notes ILIKE '%تهحساب%';
|
||||||
|
|
||||||
|
UPDATE "Person"
|
||||||
|
SET "importSource" = 'excel'
|
||||||
|
WHERE "importSource" = 'manual'
|
||||||
|
AND COALESCE(BTRIM("customFields"->>'customerCode'), '') <> ''
|
||||||
|
AND COALESCE(BTRIM("customFields"->>'didarId'), '') = '';
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "UserTablePreference" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"tableKey" TEXT NOT NULL,
|
||||||
|
"hiddenColumns" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "UserTablePreference_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "UserTablePreference_userId_organizationId_tableKey_key" ON "UserTablePreference"("userId", "organizationId", "tableKey");
|
||||||
|
CREATE INDEX IF NOT EXISTS "UserTablePreference_userId_organizationId_idx" ON "UserTablePreference"("userId", "organizationId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "UserTablePreference" ADD CONSTRAINT "UserTablePreference_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "previousImportSource" TEXT;
|
||||||
|
ALTER TABLE "Person" ADD COLUMN IF NOT EXISTS "previousSourceRef" TEXT;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Person_organizationId_previousSourceRef_idx" ON "Person"("organizationId", "previousSourceRef");
|
||||||
|
|
||||||
|
-- اشخاصی که قبلاً از دیدار آمدهاند و بعد با تهحساب بازنویسی شدهاند: کد دیدار را بهعنوان کد قبلی بازیابی کن
|
||||||
|
UPDATE "Person"
|
||||||
|
SET "previousImportSource" = 'didar',
|
||||||
|
"previousSourceRef" = TRIM("customFields"->>'didarId')
|
||||||
|
WHERE "importSource" = 'tahesab'
|
||||||
|
AND "previousSourceRef" IS NULL
|
||||||
|
AND "customFields" IS NOT NULL
|
||||||
|
AND jsonb_typeof("customFields") = 'object'
|
||||||
|
AND COALESCE(TRIM("customFields"->>'didarId'), '') <> '';
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "code" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "importSource" TEXT NOT NULL DEFAULT 'manual';
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "sourceRef" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "economicCode" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "registrationNumber" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "otherPhones" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "fax" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "otherEmails" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "province" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "city" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "postalCode" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "groupName" TEXT;
|
||||||
|
ALTER TABLE "Company" ADD COLUMN IF NOT EXISTS "registeredAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Company_organizationId_sourceRef_idx" ON "Company"("organizationId", "sourceRef");
|
||||||
|
CREATE INDEX IF NOT EXISTS "Company_organizationId_code_idx" ON "Company"("organizationId", "code");
|
||||||
|
|
||||||
|
-- شرکتهایی که از ورود اشخاص دیدار ساخته شدهاند: کد دیدار شرکت را از customFields اشخاص بازیابی کن
|
||||||
|
UPDATE "Company" c
|
||||||
|
SET "sourceRef" = sub.didar_code,
|
||||||
|
"importSource" = 'didar'
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT ON (p."companyId")
|
||||||
|
p."companyId" AS company_id,
|
||||||
|
TRIM(p."customFields"->>'companyDidarId') AS didar_code
|
||||||
|
FROM "Person" p
|
||||||
|
WHERE p."companyId" IS NOT NULL
|
||||||
|
AND jsonb_typeof(p."customFields") = 'object'
|
||||||
|
AND COALESCE(TRIM(p."customFields"->>'companyDidarId'), '') <> ''
|
||||||
|
ORDER BY p."companyId", p."createdAt"
|
||||||
|
) sub
|
||||||
|
WHERE c."id" = sub.company_id
|
||||||
|
AND c."sourceRef" IS NULL;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE "Activity" ADD COLUMN IF NOT EXISTS "reminderSentAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Activity_reminderAt_reminderSentAt_idx" ON "Activity"("reminderAt", "reminderSentAt");
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "Membership" ADD COLUMN IF NOT EXISTS "dataVisibilityScopes" JSONB NOT NULL DEFAULT '{}';
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "code" TEXT;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "importSource" TEXT NOT NULL DEFAULT 'manual';
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "sourceRef" TEXT;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "probability" INTEGER;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "sourceDetail" TEXT;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "referrer" TEXT;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "lostNote" TEXT;
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "closedAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN IF NOT EXISTS "createdById" TEXT;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "Deal" ADD CONSTRAINT "Deal_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Deal_organizationId_sourceRef_idx" ON "Deal"("organizationId", "sourceRef");
|
||||||
|
|
||||||
|
UPDATE "Deal"
|
||||||
|
SET "importSource" = 'didar', "sourceRef" = "customFields"->>'didarId'
|
||||||
|
WHERE "sourceRef" IS NULL AND COALESCE("customFields"->>'didarId', '') <> '';
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "MontifyConnection" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"baseUrl" TEXT NOT NULL,
|
||||||
|
"storeId" TEXT NOT NULL DEFAULT '',
|
||||||
|
"tokenCiphertext" TEXT NOT NULL,
|
||||||
|
"tokenIv" TEXT NOT NULL,
|
||||||
|
"tokenTag" TEXT NOT NULL,
|
||||||
|
"tokenLast4" TEXT NOT NULL DEFAULT '',
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"webhookRemoteId" TEXT,
|
||||||
|
"webhookSecretCiphertext" TEXT,
|
||||||
|
"webhookSecretIv" TEXT,
|
||||||
|
"webhookSecretTag" TEXT,
|
||||||
|
"customersCursor" TIMESTAMP(3),
|
||||||
|
"syncStatus" TEXT NOT NULL DEFAULT 'idle',
|
||||||
|
"syncStartedAt" TIMESTAMP(3),
|
||||||
|
"lastSyncAt" TIMESTAMP(3),
|
||||||
|
"lastSyncResult" JSONB,
|
||||||
|
"lastHealthAt" TIMESTAMP(3),
|
||||||
|
"lastHealthOk" BOOLEAN,
|
||||||
|
"lastError" TEXT,
|
||||||
|
"lastWebhookAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "MontifyConnection_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "MontifyLink" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"entityType" TEXT NOT NULL,
|
||||||
|
"externalId" TEXT NOT NULL,
|
||||||
|
"entityId" TEXT NOT NULL,
|
||||||
|
"externalUpdatedAt" TIMESTAMP(3),
|
||||||
|
"ordersSyncedAt" TIMESTAMP(3),
|
||||||
|
"data" JSONB,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "MontifyLink_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "MontifyOrder" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"externalId" TEXT NOT NULL,
|
||||||
|
"customerExternalId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"orderReference" TEXT,
|
||||||
|
"orderStatus" TEXT,
|
||||||
|
"paymentStatus" TEXT,
|
||||||
|
"paymentType" TEXT,
|
||||||
|
"totalPrice" DECIMAL(20,2),
|
||||||
|
"discountTotalPrice" DECIMAL(20,2),
|
||||||
|
"totalDiscounts" DECIMAL(20,2),
|
||||||
|
"totalTax" DECIMAL(20,2),
|
||||||
|
"totalQty" DECIMAL(14,3),
|
||||||
|
"profit" DECIMAL(20,2),
|
||||||
|
"percentProfit" DECIMAL(10,3),
|
||||||
|
"sumGold" DECIMAL(14,3),
|
||||||
|
"sumSilver" DECIMAL(14,3),
|
||||||
|
"address" JSONB,
|
||||||
|
"note" TEXT,
|
||||||
|
"cancelReason" TEXT,
|
||||||
|
"cancelledAt" TIMESTAMP(3),
|
||||||
|
"closedAt" TIMESTAMP(3),
|
||||||
|
"codeDiscount" TEXT,
|
||||||
|
"items" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"externalCreatedAt" TIMESTAMP(3),
|
||||||
|
"externalUpdatedAt" TIMESTAMP(3),
|
||||||
|
"deletedAt" TIMESTAMP(3),
|
||||||
|
"raw" JSONB,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "MontifyOrder_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "MontifyTransaction" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"externalId" TEXT NOT NULL,
|
||||||
|
"customerExternalId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"type" TEXT,
|
||||||
|
"amount" DECIMAL(24,4),
|
||||||
|
"currency" TEXT,
|
||||||
|
"status" TEXT,
|
||||||
|
"referenceCode" TEXT,
|
||||||
|
"externalCreatedAt" TIMESTAMP(3),
|
||||||
|
"raw" JSONB,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "MontifyTransaction_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE IF NOT EXISTS "MontifyWebhookDelivery" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"deliveryId" TEXT NOT NULL,
|
||||||
|
"event" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'received',
|
||||||
|
"error" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "MontifyWebhookDelivery_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyConnection_organizationId_enabled_idx" ON "MontifyConnection"("organizationId", "enabled");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "MontifyLink_connectionId_entityType_externalId_key" ON "MontifyLink"("connectionId", "entityType", "externalId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyLink_organizationId_entityType_entityId_idx" ON "MontifyLink"("organizationId", "entityType", "entityId");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "MontifyOrder_connectionId_externalId_key" ON "MontifyOrder"("connectionId", "externalId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyOrder_organizationId_personId_idx" ON "MontifyOrder"("organizationId", "personId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyOrder_organizationId_externalCreatedAt_idx" ON "MontifyOrder"("organizationId", "externalCreatedAt");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "MontifyTransaction_connectionId_externalId_key" ON "MontifyTransaction"("connectionId", "externalId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyTransaction_organizationId_personId_idx" ON "MontifyTransaction"("organizationId", "personId");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "MontifyWebhookDelivery_connectionId_deliveryId_key" ON "MontifyWebhookDelivery"("connectionId", "deliveryId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "MontifyWebhookDelivery_connectionId_createdAt_idx" ON "MontifyWebhookDelivery"("connectionId", "createdAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "MontifyConnection" ADD CONSTRAINT "MontifyConnection_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "MontifyLink" ADD CONSTRAINT "MontifyLink_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "MontifyConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "MontifyOrder" ADD CONSTRAINT "MontifyOrder_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "MontifyConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "MontifyTransaction" ADD CONSTRAINT "MontifyTransaction_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "MontifyConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "MontifyWebhookDelivery" ADD CONSTRAINT "MontifyWebhookDelivery_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "MontifyConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
-- ماژول جدید برای محیطهایی که فهرست ماژول ذخیرهشده دارند و ووکامرس فعال است
|
||||||
|
UPDATE "Organization"
|
||||||
|
SET "enabledModules" = array_append("enabledModules", 'montify')
|
||||||
|
WHERE cardinality("enabledModules") > 0
|
||||||
|
AND 'woocommerce' = ANY("enabledModules")
|
||||||
|
AND NOT ('montify' = ANY("enabledModules"));
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "RoutineTaskStatus" AS ENUM ('todo', 'in_progress', 'completed', 'overdue', 'skipped', 'cancelled');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "RoutineRecurrence" AS ENUM ('daily', 'weekdays', 'weekly', 'biweekly', 'monthly', 'every_n_days', 'specific_dates');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "RoutineTaskSource" AS ENUM ('routine', 'manual', 'follow_up', 'lead', 'customer', 'deal');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "RoutineCategory" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"color" TEXT NOT NULL DEFAULT '#14b8a6',
|
||||||
|
"sortOrder" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "RoutineCategory_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Routine" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"assigneeId" TEXT,
|
||||||
|
"teamId" TEXT,
|
||||||
|
"categoryId" TEXT,
|
||||||
|
"priority" "ActivityPriority" NOT NULL DEFAULT 'medium',
|
||||||
|
"timeOfDay" TEXT NOT NULL DEFAULT '09:00',
|
||||||
|
"durationMinutes" INTEGER,
|
||||||
|
"startDate" DATE NOT NULL,
|
||||||
|
"endDate" DATE,
|
||||||
|
"recurrence" "RoutineRecurrence" NOT NULL DEFAULT 'daily',
|
||||||
|
"weekdays" INTEGER[] DEFAULT ARRAY[]::INTEGER[],
|
||||||
|
"intervalDays" INTEGER,
|
||||||
|
"monthDay" INTEGER,
|
||||||
|
"specificDates" DATE[],
|
||||||
|
"isMandatory" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"allowSkip" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"skipReasonRequired" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"reportRequired" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"allowAfterDeadline" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"carryOverOverdue" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"entityLink" TEXT NOT NULL DEFAULT 'none',
|
||||||
|
"reminderMinutesBefore" INTEGER,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"deletedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Routine_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "RoutineTask" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"routineId" TEXT,
|
||||||
|
"assigneeId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"categoryId" TEXT,
|
||||||
|
"priority" "ActivityPriority" NOT NULL DEFAULT 'medium',
|
||||||
|
"status" "RoutineTaskStatus" NOT NULL DEFAULT 'todo',
|
||||||
|
"scheduledFor" DATE NOT NULL,
|
||||||
|
"dueAt" TIMESTAMP(3),
|
||||||
|
"startedAt" TIMESTAMP(3),
|
||||||
|
"completedAt" TIMESTAMP(3),
|
||||||
|
"resultNote" TEXT,
|
||||||
|
"skipReason" TEXT,
|
||||||
|
"source" "RoutineTaskSource" NOT NULL DEFAULT 'manual',
|
||||||
|
"isMandatory" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"leadId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"companyId" TEXT,
|
||||||
|
"dealId" TEXT,
|
||||||
|
"invoiceId" TEXT,
|
||||||
|
"activityId" TEXT,
|
||||||
|
"reminderAt" TIMESTAMP(3),
|
||||||
|
"reminderSentAt" TIMESTAMP(3),
|
||||||
|
"overdueNotifiedAt" TIMESTAMP(3),
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "RoutineTask_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "RoutineTaskEvent" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"taskId" TEXT NOT NULL,
|
||||||
|
"actorId" TEXT,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"fromStatus" "RoutineTaskStatus",
|
||||||
|
"toStatus" "RoutineTaskStatus",
|
||||||
|
"note" TEXT,
|
||||||
|
"meta" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "RoutineTaskEvent_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "RoutineUserSettings" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"remindBeforeMinutes" INTEGER DEFAULT 30,
|
||||||
|
"endOfDaySummary" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"overdueAlert" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"summaryHour" INTEGER NOT NULL DEFAULT 16,
|
||||||
|
"lastSummaryOn" DATE,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "RoutineUserSettings_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineCategory_organizationId_sortOrder_idx" ON "RoutineCategory"("organizationId", "sortOrder");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "RoutineCategory_organizationId_name_key" ON "RoutineCategory"("organizationId", "name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Routine_organizationId_isActive_deletedAt_idx" ON "Routine"("organizationId", "isActive", "deletedAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Routine_assigneeId_idx" ON "Routine"("assigneeId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Routine_teamId_idx" ON "Routine"("teamId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_organizationId_assigneeId_scheduledFor_idx" ON "RoutineTask"("organizationId", "assigneeId", "scheduledFor");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_organizationId_status_dueAt_idx" ON "RoutineTask"("organizationId", "status", "dueAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_reminderAt_reminderSentAt_idx" ON "RoutineTask"("reminderAt", "reminderSentAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_leadId_idx" ON "RoutineTask"("leadId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_personId_idx" ON "RoutineTask"("personId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_companyId_idx" ON "RoutineTask"("companyId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_dealId_idx" ON "RoutineTask"("dealId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTask_activityId_idx" ON "RoutineTask"("activityId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "RoutineTask_routineId_assigneeId_scheduledFor_key" ON "RoutineTask"("routineId", "assigneeId", "scheduledFor");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTaskEvent_taskId_createdAt_idx" ON "RoutineTaskEvent"("taskId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RoutineTaskEvent_organizationId_createdAt_idx" ON "RoutineTaskEvent"("organizationId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "RoutineUserSettings_organizationId_userId_key" ON "RoutineUserSettings"("organizationId", "userId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineCategory" ADD CONSTRAINT "RoutineCategory_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Routine" ADD CONSTRAINT "Routine_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Routine" ADD CONSTRAINT "Routine_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Routine" ADD CONSTRAINT "Routine_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Routine" ADD CONSTRAINT "Routine_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "RoutineCategory"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Routine" ADD CONSTRAINT "Routine_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_routineId_fkey" FOREIGN KEY ("routineId") REFERENCES "Routine"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "RoutineCategory"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_dealId_fkey" FOREIGN KEY ("dealId") REFERENCES "Deal"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_activityId_fkey" FOREIGN KEY ("activityId") REFERENCES "Activity"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTask" ADD CONSTRAINT "RoutineTask_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTaskEvent" ADD CONSTRAINT "RoutineTaskEvent_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTaskEvent" ADD CONSTRAINT "RoutineTaskEvent_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "RoutineTask"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineTaskEvent" ADD CONSTRAINT "RoutineTaskEvent_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineUserSettings" ADD CONSTRAINT "RoutineUserSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RoutineUserSettings" ADD CONSTRAINT "RoutineUserSettings_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
|
||||||
|
-- Enable the new routines module for organizations with an explicit module list
|
||||||
|
UPDATE "Organization"
|
||||||
|
SET "enabledModules" = array_append("enabledModules", 'routines')
|
||||||
|
WHERE cardinality("enabledModules") > 0 AND NOT ('routines' = ANY("enabledModules"));
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Rename the default sales pipeline: «کاریز فروش» → «مسیر فروش»
|
||||||
|
UPDATE "Pipeline" SET "name" = 'مسیر فروش' WHERE "name" = 'کاریز فروش';
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ActivityStage" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"color" TEXT NOT NULL DEFAULT 'green',
|
||||||
|
"kind" "ActivityStatus" NOT NULL DEFAULT 'open',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ActivityStage_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "stageId" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ActivityStage_organizationId_name_key" ON "ActivityStage"("organizationId", "name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ActivityStage_organizationId_position_idx" ON "ActivityStage"("organizationId", "position");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Activity_stageId_idx" ON "Activity"("stageId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ActivityStage" ADD CONSTRAINT "ActivityStage_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_stageId_fkey" FOREIGN KEY ("stageId") REFERENCES "ActivityStage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "fields" JSONB,
|
||||||
|
ADD COLUMN "participantIds" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
ADD COLUMN "typeDefId" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ActivityTypeDef" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"baseType" "ActivityType" NOT NULL DEFAULT 'task',
|
||||||
|
"icon" TEXT NOT NULL DEFAULT 'check',
|
||||||
|
"color" TEXT NOT NULL DEFAULT 'green',
|
||||||
|
"fields" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"isSystem" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ActivityTypeDef_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ActivityTypeDef_organizationId_position_idx" ON "ActivityTypeDef"("organizationId", "position");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ActivityTypeDef_organizationId_name_key" ON "ActivityTypeDef"("organizationId", "name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Activity_typeDefId_idx" ON "Activity"("typeDefId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ActivityTypeDef" ADD CONSTRAINT "ActivityTypeDef_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_typeDefId_fkey" FOREIGN KEY ("typeDefId") REFERENCES "ActivityTypeDef"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationSettings" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"levels" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"monthlyGoal" INTEGER NOT NULL DEFAULT 1500,
|
||||||
|
"showFullLeaderboard" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"enabledAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationSettings_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationRule" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"event" TEXT NOT NULL,
|
||||||
|
"score" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"coins" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"conditions" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"maxPerDay" INTEGER,
|
||||||
|
"maxCoinsPerDay" INTEGER,
|
||||||
|
"maxPerUser" INTEGER,
|
||||||
|
"cooldownMinutes" INTEGER,
|
||||||
|
"oncePerEntity" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"firstTimeOnly" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"requiresApproval" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"roles" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"teamIds" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationRule_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationTransaction" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"event" TEXT,
|
||||||
|
"ruleId" TEXT,
|
||||||
|
"bonusId" TEXT,
|
||||||
|
"badgeId" TEXT,
|
||||||
|
"score" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"coins" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'approved',
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"entityType" TEXT,
|
||||||
|
"entityId" TEXT,
|
||||||
|
"entityTitle" TEXT,
|
||||||
|
"idempotencyKey" TEXT,
|
||||||
|
"reason" TEXT,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"decidedById" TEXT,
|
||||||
|
"decidedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationTransaction_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationWallet" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"score" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"coins" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"coinsEarned" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"bestMonthScore" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationWallet_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationReward" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"cost" INTEGER NOT NULL,
|
||||||
|
"icon" TEXT NOT NULL DEFAULT 'gift',
|
||||||
|
"color" TEXT NOT NULL DEFAULT '#14b8a6',
|
||||||
|
"stock" INTEGER,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"requiresApproval" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationReward_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationRedemption" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"rewardId" TEXT NOT NULL,
|
||||||
|
"cost" INTEGER NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"note" TEXT,
|
||||||
|
"decisionNote" TEXT,
|
||||||
|
"decidedById" TEXT,
|
||||||
|
"decidedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationRedemption_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationBadge" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"icon" TEXT NOT NULL DEFAULT 'medal',
|
||||||
|
"color" TEXT NOT NULL DEFAULT '#f59e0b',
|
||||||
|
"metric" TEXT NOT NULL,
|
||||||
|
"event" TEXT,
|
||||||
|
"threshold" INTEGER NOT NULL,
|
||||||
|
"coins" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationBadge_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationUserBadge" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"badgeId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"earnedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationUserBadge_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "GamificationBonus" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"event" TEXT,
|
||||||
|
"threshold" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"period" TEXT NOT NULL DEFAULT 'month',
|
||||||
|
"score" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"coins" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "GamificationBonus_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "GamificationSettings_organizationId_key" ON "GamificationSettings"("organizationId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationRule_organizationId_event_isActive_idx" ON "GamificationRule"("organizationId", "event", "isActive");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationTransaction_organizationId_createdAt_idx" ON "GamificationTransaction"("organizationId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationTransaction_organizationId_userId_createdAt_idx" ON "GamificationTransaction"("organizationId", "userId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationTransaction_organizationId_ruleId_userId_create_idx" ON "GamificationTransaction"("organizationId", "ruleId", "userId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationTransaction_organizationId_status_idx" ON "GamificationTransaction"("organizationId", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "GamificationTransaction_organizationId_idempotencyKey_key" ON "GamificationTransaction"("organizationId", "idempotencyKey");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationWallet_organizationId_score_idx" ON "GamificationWallet"("organizationId", "score");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "GamificationWallet_organizationId_userId_key" ON "GamificationWallet"("organizationId", "userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationReward_organizationId_isActive_idx" ON "GamificationReward"("organizationId", "isActive");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationRedemption_organizationId_status_idx" ON "GamificationRedemption"("organizationId", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationRedemption_organizationId_userId_idx" ON "GamificationRedemption"("organizationId", "userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationBadge_organizationId_isActive_idx" ON "GamificationBadge"("organizationId", "isActive");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationUserBadge_organizationId_userId_idx" ON "GamificationUserBadge"("organizationId", "userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "GamificationUserBadge_badgeId_userId_key" ON "GamificationUserBadge"("badgeId", "userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "GamificationBonus_organizationId_isActive_idx" ON "GamificationBonus"("organizationId", "isActive");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationSettings" ADD CONSTRAINT "GamificationSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationRule" ADD CONSTRAINT "GamificationRule_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationTransaction" ADD CONSTRAINT "GamificationTransaction_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationWallet" ADD CONSTRAINT "GamificationWallet_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationReward" ADD CONSTRAINT "GamificationReward_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationRedemption" ADD CONSTRAINT "GamificationRedemption_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationRedemption" ADD CONSTRAINT "GamificationRedemption_rewardId_fkey" FOREIGN KEY ("rewardId") REFERENCES "GamificationReward"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationBadge" ADD CONSTRAINT "GamificationBadge_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationUserBadge" ADD CONSTRAINT "GamificationUserBadge_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationUserBadge" ADD CONSTRAINT "GamificationUserBadge_badgeId_fkey" FOREIGN KEY ("badgeId") REFERENCES "GamificationBadge"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "GamificationBonus" ADD CONSTRAINT "GamificationBonus_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Enable the new module for orgs with an explicit module list
|
||||||
|
UPDATE "Organization"
|
||||||
|
SET "enabledModules" = array_append("enabledModules", 'gamification')
|
||||||
|
WHERE cardinality("enabledModules") > 0 AND NOT ('gamification' = ANY("enabledModules"));
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "leadId" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AutomationCursor" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"ruleId" TEXT NOT NULL,
|
||||||
|
"stepId" TEXT NOT NULL,
|
||||||
|
"counter" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "AutomationCursor_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Activity_leadId_idx" ON "Activity"("leadId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "AutomationCursor_ruleId_stepId_key" ON "AutomationCursor"("ruleId", "stepId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AutomationCursor" ADD CONSTRAINT "AutomationCursor_ruleId_fkey" FOREIGN KEY ("ruleId") REFERENCES "AutomationRule"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN "birthDate" TIMESTAMP(3);
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Lead" ADD COLUMN "birthDate" TIMESTAMP(3);
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
ALTER TABLE "Organization" ADD COLUMN "deletionRetention" TEXT NOT NULL DEFAULT 'never';
|
||||||
|
|
||||||
|
CREATE TABLE "DeletionArchive" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"model" TEXT NOT NULL,
|
||||||
|
"entityId" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"snapshot" JSONB NOT NULL,
|
||||||
|
"deletedById" TEXT,
|
||||||
|
"deletedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "DeletionArchive_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "DeletionArchive_organizationId_deletedAt_idx" ON "DeletionArchive"("organizationId", "deletedAt");
|
||||||
|
CREATE INDEX "DeletionArchive_organizationId_model_idx" ON "DeletionArchive"("organizationId", "model");
|
||||||
|
|
||||||
|
ALTER TABLE "DeletionArchive" ADD CONSTRAINT "DeletionArchive_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "DeletionArchive" ADD CONSTRAINT "DeletionArchive_deletedById_fkey" FOREIGN KEY ("deletedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- بایگانی اطلاعات قبل: مرز محیط، مجوز عضو، و منبع فعالیت
|
||||||
|
ALTER TABLE "Organization" ADD COLUMN "priorArchiveEnabledAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN "priorArchiveEnabled" BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN "priorArchiveLens" TEXT NOT NULL DEFAULT 'current';
|
||||||
|
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "importSource" TEXT NOT NULL DEFAULT 'manual';
|
||||||
|
|
||||||
|
CREATE INDEX "Activity_organizationId_importSource_idx" ON "Activity"("organizationId", "importSource");
|
||||||
|
|
||||||
|
-- فعالیت وصل به معاملهٔ دیدار از همین حالا قبلی است. بقیه بعد از روشن شدن ماژول و با تاریخ مرز پر میشوند.
|
||||||
|
UPDATE "Activity" AS a
|
||||||
|
SET "importSource" = 'didar'
|
||||||
|
WHERE a."importSource" = 'manual'
|
||||||
|
AND a."dealId" IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM "Deal" AS d
|
||||||
|
WHERE d."id" = a."dealId" AND d."importSource" = 'didar'
|
||||||
|
);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Prior archive: promote tag + cutoff query indexes
|
||||||
|
ALTER TABLE "Deal" ADD COLUMN "promotedFromPriorAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "promotedFromPriorAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE INDEX "Deal_organizationId_createdAt_idx" ON "Deal"("organizationId", "createdAt");
|
||||||
|
|
||||||
|
CREATE INDEX "Activity_organizationId_createdAt_idx" ON "Activity"("organizationId", "createdAt");
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "OutboundSmsLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT,
|
||||||
|
"leadId" TEXT,
|
||||||
|
"mobile" TEXT NOT NULL,
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"source" TEXT NOT NULL,
|
||||||
|
"sourceId" TEXT,
|
||||||
|
"status" TEXT NOT NULL,
|
||||||
|
"error" TEXT,
|
||||||
|
"actorUserId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "OutboundSmsLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OutboundSmsLog_organizationId_personId_createdAt_idx" ON "OutboundSmsLog"("organizationId", "personId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OutboundSmsLog_organizationId_leadId_createdAt_idx" ON "OutboundSmsLog"("organizationId", "leadId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OutboundSmsLog_organizationId_createdAt_idx" ON "OutboundSmsLog"("organizationId", "createdAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "OutboundSmsLog" ADD CONSTRAINT "OutboundSmsLog_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "OutboundSmsLog" ADD CONSTRAINT "OutboundSmsLog_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "OutboundSmsLog" ADD CONSTRAINT "OutboundSmsLog_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "FinancialAccount" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"bankName" TEXT,
|
||||||
|
"accountRef" TEXT,
|
||||||
|
"responsibleName" TEXT,
|
||||||
|
"openingBalance" DECIMAL(18,2) NOT NULL DEFAULT 0,
|
||||||
|
"openingDate" TIMESTAMP(3) NOT NULL,
|
||||||
|
"notes" TEXT,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"currency" TEXT NOT NULL DEFAULT 'IRR',
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "FinancialAccount_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialCategory" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "FinancialCategory_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialDocument" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"bookedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"dueAt" TIMESTAMP(3),
|
||||||
|
"categoryId" TEXT,
|
||||||
|
"personId" TEXT,
|
||||||
|
"partyName" TEXT,
|
||||||
|
"accountId" TEXT,
|
||||||
|
"method" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'open',
|
||||||
|
"reference" TEXT,
|
||||||
|
"notes" TEXT,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"voidedAt" TIMESTAMP(3),
|
||||||
|
"voidReason" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "FinancialDocument_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialMovement" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"documentId" TEXT,
|
||||||
|
"direction" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"transferGroupId" TEXT,
|
||||||
|
"occurredAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"memo" TEXT,
|
||||||
|
"reference" TEXT,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"voidedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "FinancialMovement_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "FinancialAccount_organizationId_isActive_idx" ON "FinancialAccount"("organizationId", "isActive");
|
||||||
|
CREATE UNIQUE INDEX "FinancialCategory_organizationId_kind_name_key" ON "FinancialCategory"("organizationId", "kind", "name");
|
||||||
|
CREATE INDEX "FinancialCategory_organizationId_kind_idx" ON "FinancialCategory"("organizationId", "kind");
|
||||||
|
CREATE INDEX "FinancialDocument_organizationId_kind_bookedAt_idx" ON "FinancialDocument"("organizationId", "kind", "bookedAt");
|
||||||
|
CREATE INDEX "FinancialDocument_organizationId_status_idx" ON "FinancialDocument"("organizationId", "status");
|
||||||
|
CREATE INDEX "FinancialDocument_personId_idx" ON "FinancialDocument"("personId");
|
||||||
|
CREATE INDEX "FinancialMovement_organizationId_accountId_occurredAt_idx" ON "FinancialMovement"("organizationId", "accountId", "occurredAt");
|
||||||
|
CREATE INDEX "FinancialMovement_transferGroupId_idx" ON "FinancialMovement"("transferGroupId");
|
||||||
|
CREATE INDEX "FinancialMovement_documentId_idx" ON "FinancialMovement"("documentId");
|
||||||
|
|
||||||
|
ALTER TABLE "FinancialAccount" ADD CONSTRAINT "FinancialAccount_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialCategory" ADD CONSTRAINT "FinancialCategory_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "FinancialCategory"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "FinancialAccount"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "FinancialAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "FinancialDocument"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN "discLabel" TEXT,
|
||||||
|
ADD COLUMN "discReliable" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN "discAssessedAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Person_organizationId_discLabel_idx" ON "Person"("organizationId", "discLabel");
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "DiscAssessment" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT NOT NULL,
|
||||||
|
"assessorId" TEXT NOT NULL,
|
||||||
|
"answers" JSONB NOT NULL,
|
||||||
|
"scoreD" INTEGER NOT NULL,
|
||||||
|
"scoreI" INTEGER NOT NULL,
|
||||||
|
"scoreS" INTEGER NOT NULL,
|
||||||
|
"scoreC" INTEGER NOT NULL,
|
||||||
|
"percentD" INTEGER NOT NULL,
|
||||||
|
"percentI" INTEGER NOT NULL,
|
||||||
|
"percentS" INTEGER NOT NULL,
|
||||||
|
"percentC" INTEGER NOT NULL,
|
||||||
|
"validCount" INTEGER NOT NULL,
|
||||||
|
"primaryTypes" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"secondaryTypes" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"secondaryLabel" TEXT,
|
||||||
|
"reliable" BOOLEAN NOT NULL,
|
||||||
|
"confidence" TEXT NOT NULL,
|
||||||
|
"note" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'confirmed',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "DiscAssessment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "SalesCopilotSession" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT,
|
||||||
|
"leadId" TEXT,
|
||||||
|
"dealId" TEXT,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"topic" TEXT NOT NULL,
|
||||||
|
"goal" TEXT NOT NULL,
|
||||||
|
"customerStatement" TEXT NOT NULL,
|
||||||
|
"behaviorNotes" TEXT,
|
||||||
|
"analysis" JSONB NOT NULL,
|
||||||
|
"confirmedResponse" TEXT,
|
||||||
|
"nextAction" TEXT,
|
||||||
|
"followUpAt" TIMESTAMP(3),
|
||||||
|
"callOutcome" TEXT,
|
||||||
|
"agentNote" TEXT,
|
||||||
|
"status" TEXT NOT NULL,
|
||||||
|
"messageDraft" TEXT,
|
||||||
|
"activityId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "SalesCopilotSession_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "DiscAssessment_organizationId_personId_createdAt_idx" ON "DiscAssessment"("organizationId", "personId", "createdAt");
|
||||||
|
CREATE INDEX "DiscAssessment_personId_idx" ON "DiscAssessment"("personId");
|
||||||
|
CREATE INDEX "SalesCopilotSession_organizationId_personId_createdAt_idx" ON "SalesCopilotSession"("organizationId", "personId", "createdAt");
|
||||||
|
CREATE INDEX "SalesCopilotSession_organizationId_leadId_idx" ON "SalesCopilotSession"("organizationId", "leadId");
|
||||||
|
CREATE INDEX "SalesCopilotSession_dealId_idx" ON "SalesCopilotSession"("dealId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "DiscAssessment" ADD CONSTRAINT "DiscAssessment_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "DiscAssessment" ADD CONSTRAINT "DiscAssessment_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "DiscAssessment" ADD CONSTRAINT "DiscAssessment_assessorId_fkey" FOREIGN KEY ("assessorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE "SalesCopilotSession" ADD CONSTRAINT "SalesCopilotSession_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SalesCopilotSession" ADD CONSTRAINT "SalesCopilotSession_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SalesCopilotSession" ADD CONSTRAINT "SalesCopilotSession_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "Lead"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SalesCopilotSession" ADD CONSTRAINT "SalesCopilotSession_dealId_fkey" FOREIGN KEY ("dealId") REFERENCES "Deal"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "SalesCopilotSession" ADD CONSTRAINT "SalesCopilotSession_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- ماژول برای محیطهایی که از قبل ماژول دارند روشن میشود و در سوپرادمین قابل خاموش کردن است
|
||||||
|
UPDATE "Organization"
|
||||||
|
SET "enabledModules" = array_append("enabledModules", 'behavior')
|
||||||
|
WHERE cardinality("enabledModules") > 0
|
||||||
|
AND NOT ('behavior' = ANY("enabledModules"));
|
||||||
|
|
||||||
|
-- مجوز رفتار برای نقشهایی که فروش دارند؛ پشتیبانی بدون این کلید میماند
|
||||||
|
UPDATE "OrgRole"
|
||||||
|
SET "permissions" = array_append("permissions", 'behavior')
|
||||||
|
WHERE NOT ('behavior' = ANY("permissions"))
|
||||||
|
AND (
|
||||||
|
"systemKey" IN ('owner', 'admin', 'sales')
|
||||||
|
OR 'sales' = ANY("permissions")
|
||||||
|
);
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
ALTER TABLE "FinancialMovement" ADD COLUMN "receivableId" TEXT;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD COLUMN "installmentId" TEXT;
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialReceivable" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"personId" TEXT,
|
||||||
|
"partyName" TEXT,
|
||||||
|
"totalAmount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"notes" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'open',
|
||||||
|
"createdById" TEXT,
|
||||||
|
"voidedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
CONSTRAINT "FinancialReceivable_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialInstallment" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"receivableId" TEXT NOT NULL,
|
||||||
|
"position" INTEGER NOT NULL,
|
||||||
|
"dueDate" TIMESTAMP(3) NOT NULL,
|
||||||
|
"amount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"reminderNotifiedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "FinancialInstallment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "FinancialMovement_receivableId_idx" ON "FinancialMovement"("receivableId");
|
||||||
|
CREATE INDEX "FinancialMovement_installmentId_idx" ON "FinancialMovement"("installmentId");
|
||||||
|
CREATE INDEX "FinancialReceivable_organizationId_status_idx" ON "FinancialReceivable"("organizationId", "status");
|
||||||
|
CREATE INDEX "FinancialReceivable_personId_idx" ON "FinancialReceivable"("personId");
|
||||||
|
CREATE UNIQUE INDEX "FinancialInstallment_receivableId_position_key" ON "FinancialInstallment"("receivableId", "position");
|
||||||
|
CREATE INDEX "FinancialInstallment_dueDate_idx" ON "FinancialInstallment"("dueDate");
|
||||||
|
|
||||||
|
ALTER TABLE "FinancialReceivable" ADD CONSTRAINT "FinancialReceivable_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialReceivable" ADD CONSTRAINT "FinancialReceivable_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialInstallment" ADD CONSTRAINT "FinancialInstallment_receivableId_fkey" FOREIGN KEY ("receivableId") REFERENCES "FinancialReceivable"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_receivableId_fkey" FOREIGN KEY ("receivableId") REFERENCES "FinancialReceivable"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_installmentId_fkey" FOREIGN KEY ("installmentId") REFERENCES "FinancialInstallment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
ALTER TABLE "FinancialMovement" ADD COLUMN "payrollId" TEXT;
|
||||||
|
CREATE INDEX "FinancialMovement_payrollId_idx" ON "FinancialMovement"("payrollId");
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialPayroll" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"period" TEXT NOT NULL,
|
||||||
|
"baseAmount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"benefits" DECIMAL(18,2) NOT NULL DEFAULT 0,
|
||||||
|
"bonus" DECIMAL(18,2) NOT NULL DEFAULT 0,
|
||||||
|
"deductions" DECIMAL(18,2) NOT NULL DEFAULT 0,
|
||||||
|
"payable" DECIMAL(18,2) NOT NULL,
|
||||||
|
"dueDate" TIMESTAMP(3) NOT NULL,
|
||||||
|
"notes" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'open',
|
||||||
|
"createdById" TEXT,
|
||||||
|
"voidedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
CONSTRAINT "FinancialPayroll_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialRecurringItem" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(18,2) NOT NULL,
|
||||||
|
"interval" TEXT NOT NULL,
|
||||||
|
"startDate" TIMESTAMP(3) NOT NULL,
|
||||||
|
"endDate" TIMESTAMP(3),
|
||||||
|
"nextDue" TIMESTAMP(3) NOT NULL,
|
||||||
|
"accountId" TEXT,
|
||||||
|
"categoryId" TEXT,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
CONSTRAINT "FinancialRecurringItem_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialRecurringOccurrence" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"itemId" TEXT NOT NULL,
|
||||||
|
"periodKey" TEXT NOT NULL,
|
||||||
|
"dueDate" TIMESTAMP(3) NOT NULL,
|
||||||
|
"documentId" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "FinancialRecurringOccurrence_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialReconciliation" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"reconciledAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"statedBalance" DECIMAL(18,2) NOT NULL,
|
||||||
|
"systemBalance" DECIMAL(18,2) NOT NULL,
|
||||||
|
"difference" DECIMAL(18,2) NOT NULL,
|
||||||
|
"notes" TEXT,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "FinancialReconciliation_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "FinancialPayroll_organizationId_userId_period_key" ON "FinancialPayroll"("organizationId", "userId", "period");
|
||||||
|
CREATE INDEX "FinancialPayroll_organizationId_status_idx" ON "FinancialPayroll"("organizationId", "status");
|
||||||
|
CREATE INDEX "FinancialRecurringItem_organizationId_isActive_nextDue_idx" ON "FinancialRecurringItem"("organizationId", "isActive", "nextDue");
|
||||||
|
CREATE UNIQUE INDEX "FinancialRecurringOccurrence_itemId_periodKey_key" ON "FinancialRecurringOccurrence"("itemId", "periodKey");
|
||||||
|
CREATE INDEX "FinancialReconciliation_organizationId_accountId_reconciledAt_idx" ON "FinancialReconciliation"("organizationId", "accountId", "reconciledAt");
|
||||||
|
|
||||||
|
ALTER TABLE "FinancialPayroll" ADD CONSTRAINT "FinancialPayroll_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD CONSTRAINT "FinancialMovement_payrollId_fkey" FOREIGN KEY ("payrollId") REFERENCES "FinancialPayroll"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialRecurringItem" ADD CONSTRAINT "FinancialRecurringItem_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialRecurringOccurrence" ADD CONSTRAINT "FinancialRecurringOccurrence_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "FinancialRecurringItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialReconciliation" ADD CONSTRAINT "FinancialReconciliation_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialReconciliation" ADD CONSTRAINT "FinancialReconciliation_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "FinancialAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
ALTER TABLE "Payment" ADD COLUMN "financialAccountId" TEXT;
|
||||||
|
ALTER TABLE "Cheque" ADD COLUMN "financialAccountId" TEXT;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD COLUMN "paymentId" TEXT;
|
||||||
|
ALTER TABLE "FinancialMovement" ADD COLUMN "chequeId" TEXT;
|
||||||
|
CREATE INDEX "FinancialMovement_paymentId_idx" ON "FinancialMovement"("paymentId");
|
||||||
|
CREATE INDEX "FinancialMovement_chequeId_idx" ON "FinancialMovement"("chequeId");
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialAuditLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"entityType" TEXT NOT NULL,
|
||||||
|
"entityId" TEXT NOT NULL,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"before" JSONB,
|
||||||
|
"after" JSONB,
|
||||||
|
"actorUserId" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "FinancialAuditLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
CREATE INDEX "FinancialAuditLog_organizationId_entityType_entityId_createdAt_idx" ON "FinancialAuditLog"("organizationId", "entityType", "entityId", "createdAt");
|
||||||
|
|
||||||
|
CREATE TABLE "FinancialAttachment" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"documentId" TEXT NOT NULL,
|
||||||
|
"fileName" TEXT NOT NULL,
|
||||||
|
"mimeType" TEXT NOT NULL,
|
||||||
|
"storageKey" TEXT NOT NULL,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "FinancialAttachment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
CREATE INDEX "FinancialAttachment_documentId_idx" ON "FinancialAttachment"("documentId");
|
||||||
|
|
||||||
|
ALTER TABLE "FinancialAuditLog" ADD CONSTRAINT "FinancialAuditLog_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialAttachment" ADD CONSTRAINT "FinancialAttachment_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "FinancialAttachment" ADD CONSTRAINT "FinancialAttachment_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "FinancialDocument"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -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;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- تیکهای مجوز نقش از این نسخه واقعاً اعمال میشوند.
|
||||||
|
-- تا امروز همهٔ نقشها عملاً به این بخشها دسترسی داشتند؛ همان دسترسی را برای نقشهای موجود حفظ میکنیم.
|
||||||
|
UPDATE "OrgRole"
|
||||||
|
SET "permissions" = ARRAY(
|
||||||
|
SELECT DISTINCT p
|
||||||
|
FROM unnest(
|
||||||
|
"permissions" || ARRAY['customers', 'leads', 'sales', 'billing', 'products', 'activities', 'notes', 'reports']
|
||||||
|
) AS p
|
||||||
|
);
|
||||||
|
|
||||||
|
-- لاگ فعالیت کاربران تا امروز فقط برای مالک و مدیر باز بود (مستقل از تیک)؛ همان را حفظ میکنیم.
|
||||||
|
UPDATE "OrgRole"
|
||||||
|
SET "permissions" = array_remove("permissions", 'audit')
|
||||||
|
WHERE "systemKey" IS NULL OR "systemKey" NOT IN ('owner', 'admin');
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN "blockLoginAfterLogout" BOOLEAN NOT NULL DEFAULT false;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "CustomerGroup" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"color" TEXT NOT NULL DEFAULT 'teal',
|
||||||
|
"position" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"tahesabConnectionId" TEXT,
|
||||||
|
"tahesabGid" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "CustomerGroup_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PersonGroupLink" (
|
||||||
|
"personId" TEXT NOT NULL,
|
||||||
|
"groupId" TEXT NOT NULL,
|
||||||
|
"source" TEXT NOT NULL DEFAULT 'manual',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "PersonGroupLink_pkey" PRIMARY KEY ("personId","groupId")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "CompanyGroupLink" (
|
||||||
|
"companyId" TEXT NOT NULL,
|
||||||
|
"groupId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "CompanyGroupLink_pkey" PRIMARY KEY ("companyId","groupId")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "CustomerGroup_organizationId_name_key" ON "CustomerGroup"("organizationId", "name");
|
||||||
|
CREATE INDEX "CustomerGroup_organizationId_position_idx" ON "CustomerGroup"("organizationId", "position");
|
||||||
|
CREATE INDEX "CustomerGroup_tahesabConnectionId_tahesabGid_idx" ON "CustomerGroup"("tahesabConnectionId", "tahesabGid");
|
||||||
|
CREATE INDEX "PersonGroupLink_groupId_idx" ON "PersonGroupLink"("groupId");
|
||||||
|
CREATE INDEX "CompanyGroupLink_groupId_idx" ON "CompanyGroupLink"("groupId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "CustomerGroup" ADD CONSTRAINT "CustomerGroup_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "PersonGroupLink" ADD CONSTRAINT "PersonGroupLink_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "PersonGroupLink" ADD CONSTRAINT "PersonGroupLink_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "CustomerGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "CompanyGroupLink" ADD CONSTRAINT "CompanyGroupLink_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "CompanyGroupLink" ADD CONSTRAINT "CompanyGroupLink_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "CustomerGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- تبدیل دادههای قبلی: «گروه مشتری» اکسل (customFields.group) و «گروهبندی شرکت» (groupName).
|
||||||
|
-- مقدارهای چندتایی با «،» «,» «/» جدا میشوند. برچسبهای «وضعیت مشتری» که دیدار در همان ستون میگذارد گروه حساب نمیشوند.
|
||||||
|
CREATE TEMP TABLE "_cg_src" AS
|
||||||
|
SELECT p."organizationId" AS org, 'person' AS kind, p."id" AS ref, left(btrim(x), 80) AS name
|
||||||
|
FROM "Person" p
|
||||||
|
CROSS JOIN LATERAL regexp_split_to_table(p."customFields"->>'group', '\s*[،,/]\s*') AS x
|
||||||
|
WHERE COALESCE(p."customFields"->>'group', '') <> ''
|
||||||
|
UNION ALL
|
||||||
|
SELECT c."organizationId", 'company', c."id", left(btrim(x), 80)
|
||||||
|
FROM "Company" c
|
||||||
|
CROSS JOIN LATERAL regexp_split_to_table(c."groupName", '\s*[،,/]\s*') AS x
|
||||||
|
WHERE COALESCE(c."groupName", '') <> '';
|
||||||
|
|
||||||
|
DELETE FROM "_cg_src"
|
||||||
|
WHERE name = ''
|
||||||
|
OR name IN ('مشتری تازه وارد', 'مشتری خوشحال', 'مشتری ناراضی', 'مشتری خاص');
|
||||||
|
|
||||||
|
INSERT INTO "CustomerGroup" ("id", "organizationId", "name", "color", "position", "createdAt", "updatedAt")
|
||||||
|
SELECT 'cgrp_' || md5(d.org || '|' || d.name), d.org, d.name, 'teal', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||||
|
FROM (SELECT DISTINCT org, name FROM "_cg_src") AS d
|
||||||
|
ON CONFLICT ("organizationId", "name") DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO "PersonGroupLink" ("personId", "groupId", "source", "createdAt")
|
||||||
|
SELECT DISTINCT s.ref, g."id", 'manual', CURRENT_TIMESTAMP
|
||||||
|
FROM "_cg_src" s
|
||||||
|
JOIN "CustomerGroup" g ON g."organizationId" = s.org AND g."name" = s.name
|
||||||
|
WHERE s.kind = 'person'
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO "CompanyGroupLink" ("companyId", "groupId", "createdAt")
|
||||||
|
SELECT DISTINCT s.ref, g."id", CURRENT_TIMESTAMP
|
||||||
|
FROM "_cg_src" s
|
||||||
|
JOIN "CustomerGroup" g ON g."organizationId" = s.org AND g."name" = s.name
|
||||||
|
WHERE s.kind = 'company'
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
DROP TABLE "_cg_src";
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
-- Deep data access: role default + membership override (phase 1: customers)
|
||||||
|
|
||||||
|
ALTER TABLE "OrgRole" ADD COLUMN IF NOT EXISTS "dataAccessPolicy" JSONB NOT NULL DEFAULT '{}';
|
||||||
|
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN IF NOT EXISTS "dataAccessOverride" JSONB NOT NULL DEFAULT '{}';
|
||||||
|
|
||||||
|
-- Migrate legacy own/team/org (+ optional contacts scope) into customers override
|
||||||
|
UPDATE "Membership" m
|
||||||
|
SET "dataAccessOverride" = jsonb_build_object(
|
||||||
|
'customers',
|
||||||
|
CASE
|
||||||
|
WHEN COALESCE(
|
||||||
|
NULLIF(m."dataVisibilityScopes"::jsonb ->> 'contacts', ''),
|
||||||
|
m."dataVisibility"
|
||||||
|
) = 'org' THEN '{"mode":"all","rules":[]}'::jsonb
|
||||||
|
WHEN COALESCE(
|
||||||
|
NULLIF(m."dataVisibilityScopes"::jsonb ->> 'contacts', ''),
|
||||||
|
m."dataVisibility"
|
||||||
|
) = 'team' THEN '{"mode":"rules","rules":[{"owners":["self","team"]}]}'::jsonb
|
||||||
|
ELSE '{"mode":"rules","rules":[{"owners":["self"]}]}'::jsonb
|
||||||
|
END
|
||||||
|
)
|
||||||
|
WHERE m."role" NOT IN ('owner', 'admin')
|
||||||
|
AND (
|
||||||
|
m."dataAccessOverride" IS NULL
|
||||||
|
OR m."dataAccessOverride"::text IN ('{}', 'null')
|
||||||
|
);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Membership" ADD COLUMN "loginOtpOnly" BOOLEAN NOT NULL DEFAULT false;
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AccountingAsnadLine" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"connectionId" TEXT NOT NULL,
|
||||||
|
"personId" TEXT,
|
||||||
|
"linkId" TEXT,
|
||||||
|
"moshtariCode" INTEGER NOT NULL,
|
||||||
|
"lineKey" TEXT NOT NULL,
|
||||||
|
"tahesabId" INTEGER,
|
||||||
|
"factorCode" TEXT,
|
||||||
|
"shFactor" INTEGER,
|
||||||
|
"radif" INTEGER,
|
||||||
|
"tarikh" TEXT NOT NULL,
|
||||||
|
"noRaw" TEXT NOT NULL DEFAULT '',
|
||||||
|
"kind" TEXT NOT NULL DEFAULT 'other',
|
||||||
|
"jensFelez" INTEGER,
|
||||||
|
"noKar" TEXT,
|
||||||
|
"vazn" DOUBLE PRECISION,
|
||||||
|
"tabdilVazn" DOUBLE PRECISION,
|
||||||
|
"mali" DOUBLE PRECISION,
|
||||||
|
"count" DOUBLE PRECISION,
|
||||||
|
"ayar" DOUBLE PRECISION,
|
||||||
|
"mazaneh" DOUBLE PRECISION,
|
||||||
|
"fi" DOUBLE PRECISION,
|
||||||
|
"sharh1" TEXT,
|
||||||
|
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "AccountingAsnadLine_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "AccountingAsnadLine_connectionId_lineKey_key" ON "AccountingAsnadLine"("connectionId", "lineKey");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccountingAsnadLine_organizationId_connectionId_tarikh_idx" ON "AccountingAsnadLine"("organizationId", "connectionId", "tarikh");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccountingAsnadLine_organizationId_kind_idx" ON "AccountingAsnadLine"("organizationId", "kind");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccountingAsnadLine_personId_idx" ON "AccountingAsnadLine"("personId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccountingAsnadLine_linkId_idx" ON "AccountingAsnadLine"("linkId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccountingAsnadLine_moshtariCode_idx" ON "AccountingAsnadLine"("moshtariCode");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AccountingAsnadLine" ADD CONSTRAINT "AccountingAsnadLine_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AccountingAsnadLine" ADD CONSTRAINT "AccountingAsnadLine_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "AccountingConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AccountingAsnadLine" ADD CONSTRAINT "AccountingAsnadLine_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AccountingAsnadLine" ADD CONSTRAINT "AccountingAsnadLine_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "PersonAccountingLink"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TahesabInvoiceSettings" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"organizationId" TEXT NOT NULL,
|
||||||
|
"logoDataUrl" TEXT,
|
||||||
|
"companyName" TEXT NOT NULL DEFAULT '',
|
||||||
|
"companySubtitle" TEXT NOT NULL DEFAULT '',
|
||||||
|
"address" TEXT NOT NULL DEFAULT '',
|
||||||
|
"phone" TEXT NOT NULL DEFAULT '',
|
||||||
|
"headerText" TEXT NOT NULL DEFAULT '',
|
||||||
|
"footerText" TEXT NOT NULL DEFAULT '',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "TahesabInvoiceSettings_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TahesabInvoiceSettings_organizationId_key" ON "TahesabInvoiceSettings"("organizationId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TahesabInvoiceSettings" ADD CONSTRAINT "TahesabInvoiceSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
+2582
-435
File diff suppressed because it is too large
Load Diff
+10
-10
@@ -335,7 +335,7 @@ async function main() {
|
|||||||
pipeline = await prisma.pipeline.create({
|
pipeline = await prisma.pipeline.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId: org.id,
|
organizationId: org.id,
|
||||||
name: 'کاریز فروش',
|
name: 'مسیر فروش',
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
stages: {
|
stages: {
|
||||||
create: DEFAULT_STAGES.map((s, index) => ({
|
create: DEFAULT_STAGES.map((s, index) => ({
|
||||||
@@ -354,13 +354,13 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const servicesPipeline = await prisma.pipeline.findFirst({
|
const servicesPipeline = await prisma.pipeline.findFirst({
|
||||||
where: { organizationId: org.id, name: 'کاریز خدمات' },
|
where: { organizationId: org.id, name: 'مسیر خدمات' },
|
||||||
});
|
});
|
||||||
if (!servicesPipeline) {
|
if (!servicesPipeline) {
|
||||||
await prisma.pipeline.create({
|
await prisma.pipeline.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId: org.id,
|
organizationId: org.id,
|
||||||
name: 'کاریز خدمات',
|
name: 'مسیر خدمات',
|
||||||
isDefault: false,
|
isDefault: false,
|
||||||
stages: {
|
stages: {
|
||||||
create: DEFAULT_STAGES.map((s, index) => ({
|
create: DEFAULT_STAGES.map((s, index) => ({
|
||||||
@@ -377,7 +377,7 @@ async function main() {
|
|||||||
console.log('Services pipeline already seeded');
|
console.log('Services pipeline already seeded');
|
||||||
}
|
}
|
||||||
|
|
||||||
// کاریز منتظر — مطابق طراحی UI (۳ مرحله + معاملات نمونه)
|
// مسیر منتظر — مطابق طراحی UI (۳ مرحله + معاملات نمونه)
|
||||||
const WAITING_STAGES = [
|
const WAITING_STAGES = [
|
||||||
{ name: 'پیگیری', isWon: false, isLost: false },
|
{ name: 'پیگیری', isWon: false, isLost: false },
|
||||||
{ name: 'مذاکرات اولیه', isWon: false, isLost: false },
|
{ name: 'مذاکرات اولیه', isWon: false, isLost: false },
|
||||||
@@ -483,7 +483,7 @@ async function main() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
let waitingPipeline = await prisma.pipeline.findFirst({
|
let waitingPipeline = await prisma.pipeline.findFirst({
|
||||||
where: { organizationId: org.id, name: 'کاریز منتظر' },
|
where: { organizationId: org.id, name: 'مسیر منتظر' },
|
||||||
include: { stages: { orderBy: { position: 'asc' } } },
|
include: { stages: { orderBy: { position: 'asc' } } },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -491,7 +491,7 @@ async function main() {
|
|||||||
waitingPipeline = await prisma.pipeline.create({
|
waitingPipeline = await prisma.pipeline.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId: org.id,
|
organizationId: org.id,
|
||||||
name: 'کاریز منتظر',
|
name: 'مسیر منتظر',
|
||||||
isDefault: false,
|
isDefault: false,
|
||||||
stages: {
|
stages: {
|
||||||
create: WAITING_STAGES.map((s, index) => ({
|
create: WAITING_STAGES.map((s, index) => ({
|
||||||
@@ -504,7 +504,7 @@ async function main() {
|
|||||||
},
|
},
|
||||||
include: { stages: { orderBy: { position: 'asc' } } },
|
include: { stages: { orderBy: { position: 'asc' } } },
|
||||||
});
|
});
|
||||||
console.log('Seeded waiting pipeline (کاریز منتظر)');
|
console.log('Seeded waiting pipeline (مسیر منتظر)');
|
||||||
} else {
|
} else {
|
||||||
console.log('Waiting pipeline already seeded');
|
console.log('Waiting pipeline already seeded');
|
||||||
}
|
}
|
||||||
@@ -534,7 +534,7 @@ async function main() {
|
|||||||
expectedCloseAt: new Date(d.expectedCloseAt),
|
expectedCloseAt: new Date(d.expectedCloseAt),
|
||||||
ownerId: owner?.id,
|
ownerId: owner?.id,
|
||||||
position: d.position,
|
position: d.position,
|
||||||
tags: ['دمو-کاریز'],
|
tags: ['دمو-مسیر'],
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -763,7 +763,7 @@ async function main() {
|
|||||||
{
|
{
|
||||||
organizationId: org.id,
|
organizationId: org.id,
|
||||||
authorId: owner?.id,
|
authorId: owner?.id,
|
||||||
body: 'در دمو نوا روی گزارش کاریز خیلی حساس بودند. نسخه چاپی PDF را آماده کنیم.',
|
body: 'در دمو نوا روی گزارش مسیر فروش خیلی حساس بودند. نسخه چاپی PDF را آماده کنیم.',
|
||||||
noteType: 'call_result',
|
noteType: 'call_result',
|
||||||
color: 'sky',
|
color: 'sky',
|
||||||
tags: ['دمو'],
|
tags: ['دمو'],
|
||||||
@@ -971,7 +971,7 @@ async function main() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
await ensure('deal_moved', {
|
await ensure('deal_moved', {
|
||||||
title: 'جابهجایی معامله در کاریز',
|
title: 'جابهجایی معامله در مسیر فروش',
|
||||||
body: sampleDeal
|
body: sampleDeal
|
||||||
? `«${sampleDeal.title}» به مرحله جدید منتقل شد`
|
? `«${sampleDeal.title}» به مرحله جدید منتقل شد`
|
||||||
: 'یک معامله جابهجا شد',
|
: 'یک معامله جابهجا شد',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||||
import type { ActivityType, ImportContactsResult } from '@mento/shared';
|
import type { ActivityType, ImportContactsResult } from '@mento/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import type { Actor } from '../common/record-scope';
|
import type { Actor } from '../common/record-scope';
|
||||||
@@ -16,35 +16,60 @@ import {
|
|||||||
writeXlsx,
|
writeXlsx,
|
||||||
type ExcelPreviewResult,
|
type ExcelPreviewResult,
|
||||||
} from '../common/excel';
|
} from '../common/excel';
|
||||||
|
import {
|
||||||
|
beginExcelImportPrepare,
|
||||||
|
chunkImportMeta,
|
||||||
|
createExcelImportCacheSession,
|
||||||
|
destroyExcelImportSession,
|
||||||
|
getExcelImportPrepareStatus,
|
||||||
|
getExcelImportSessionCaches,
|
||||||
|
resolveExcelImportChunk,
|
||||||
|
type ExcelImportLookupCaches,
|
||||||
|
type ExcelImportSessionStatus,
|
||||||
|
} from '../common/excel-import-session';
|
||||||
|
import type { ImportActivityRowsDto } from './dto';
|
||||||
|
|
||||||
const ACTIVITY_COLUMNS = [
|
/** ترتیب دقیق خروجی فعالیت دیدار — برای فایلهای بدون ردیف هدر */
|
||||||
{ header: '_type', key: '_type', width: 12 },
|
const DIDAR_ACTIVITY_POSITIONAL = [
|
||||||
{ header: 'نوع فعالیت', key: 'kind', width: 16 },
|
{ key: '_type', label: '_type' },
|
||||||
{ header: 'عنوان فعالیت', key: 'title', width: 24 },
|
{ key: 'kind', label: 'نوع فعالیت' },
|
||||||
{ header: 'متن فعالیت', key: 'body', width: 36 },
|
{ key: 'title', label: 'عنوان فعالیت' },
|
||||||
{ header: 'نتیجه فعالیت', key: 'result', width: 20 },
|
{ key: 'body', label: 'متن فعالیت' },
|
||||||
{ header: 'مسئول اجرا فعالیت', key: 'assignee', width: 18 },
|
{ key: 'result', label: 'نتیجه فعالیت' },
|
||||||
{ header: 'ثبت کننده فعالیت', key: 'creator', width: 18 },
|
{ key: 'assignee', label: 'مسئول اجرا فعالیت' },
|
||||||
{ header: 'تاریخ برنامه ریزی شده اجرا فعالیت', key: 'dueDate', width: 18 },
|
{ key: 'creator', label: 'ثبت کننده فعالیت' },
|
||||||
{ header: 'زمان برنامه ریزی شده اجرا فعالیت', key: 'dueTime', width: 14 },
|
{ key: 'dueDate', label: 'تاریخ برنامه ریزی شده اجرا فعالیت' },
|
||||||
{ header: 'وضعیت اجرای فعالیت', key: 'status', width: 16 },
|
{ key: 'dueTime', label: 'زمان برنامه ریزی شده اجرا فعالیت' },
|
||||||
{ header: 'تاریخ انجام شدن فعالیت', key: 'doneDate', width: 16 },
|
{ key: 'status', label: 'وضعیت اجرای فعالیت' },
|
||||||
{ header: 'کد معامله فعالیت', key: 'dealCode', width: 14 },
|
{ key: 'doneDate', label: 'تاریخ انجام شدن فعالیت' },
|
||||||
{ header: 'کد کارت فعالیت', key: 'cardCode', width: 14 },
|
{ key: 'dealCode', label: 'کد معامله فعالیت' },
|
||||||
{ header: 'زمان انجام شدن فعالیت', key: 'doneTime', width: 14 },
|
{ key: 'cardCode', label: 'کد کارت فعالیت' },
|
||||||
{ header: 'اشخاص فعالیت', key: 'personName', width: 18 },
|
{ key: 'doneTime', label: 'زمان انجام شدن فعالیت' },
|
||||||
{ header: 'کد اشخاص فعالیت', key: 'personCode', width: 14 },
|
{ key: 'personName', label: 'اشخاص فعالیت' },
|
||||||
{ header: 'موبایل اشخاص فعالیت', key: 'personMobile', width: 16 },
|
{ key: 'personCode', label: 'کد اشخاص فعالیت' },
|
||||||
{ header: 'شرکت های فعالیت', key: 'companyName', width: 20 },
|
{ key: 'personMobile', label: 'موبایل اشخاص فعالیت' },
|
||||||
{ header: 'کد شرکت های فعالیت', key: 'companyCode', width: 14 },
|
{ key: 'companyName', label: 'شرکت های فعالیت' },
|
||||||
{ header: 'معامله فعالیت_1', key: 'dealTitle', width: 24 },
|
{ key: 'companyCode', label: 'کد شرکت های فعالیت' },
|
||||||
{ header: 'کارت فعالیت_1', key: 'cardTitle', width: 20 },
|
{ key: 'dealTitle', label: 'معامله فعالیت_1' },
|
||||||
{ header: 'هشتگ', key: 'hashtag', width: 16 },
|
{ key: 'cardTitle', label: 'کارت فعالیت_1' },
|
||||||
];
|
{ key: 'hashtag', label: 'هشتگ' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ACTIVITY_COLUMNS = DIDAR_ACTIVITY_POSITIONAL.map((c) => ({
|
||||||
|
header: c.label,
|
||||||
|
key: c.key,
|
||||||
|
width:
|
||||||
|
c.key === 'body' || c.key === 'result'
|
||||||
|
? 36
|
||||||
|
: c.key === 'title' || c.key === 'dealTitle'
|
||||||
|
? 24
|
||||||
|
: 16,
|
||||||
|
}));
|
||||||
|
|
||||||
const ACTIVITY_ALIASES: Record<string, string> = {
|
const ACTIVITY_ALIASES: Record<string, string> = {
|
||||||
_type: '_type',
|
_type: '_type',
|
||||||
type: '_type',
|
type: '_type',
|
||||||
|
activity: '_type',
|
||||||
نوعفعالیت: 'kind',
|
نوعفعالیت: 'kind',
|
||||||
عنوانفعالیت: 'title',
|
عنوانفعالیت: 'title',
|
||||||
عنوان: 'title',
|
عنوان: 'title',
|
||||||
@@ -65,10 +90,27 @@ const ACTIVITY_ALIASES: Record<string, string> = {
|
|||||||
شرکتهایفعالیت: 'companyName',
|
شرکتهایفعالیت: 'companyName',
|
||||||
کدشرکتهایفعالیت: 'companyCode',
|
کدشرکتهایفعالیت: 'companyCode',
|
||||||
معاملهفعالیت1: 'dealTitle',
|
معاملهفعالیت1: 'dealTitle',
|
||||||
|
معاملهفعالیت_1: 'dealTitle',
|
||||||
کارتفعالیت1: 'cardTitle',
|
کارتفعالیت1: 'cardTitle',
|
||||||
|
کارتفعالیت_1: 'cardTitle',
|
||||||
هشتگ: 'hashtag',
|
هشتگ: 'hashtag',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function looksLikeDidarActivityHeaderless(firstRow: string[]) {
|
||||||
|
const first = (firstRow[0] ?? '').trim().toLowerCase();
|
||||||
|
if (first !== 'activity' && first !== '_type') return false;
|
||||||
|
const kind = (firstRow[1] ?? '').trim();
|
||||||
|
return /تماس|پیگیری|جلسه|یادداشت|ملاقات|call|task|meeting|note|پیام/i.test(kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ACTIVITY_EXCEL_OPTIONS = {
|
||||||
|
positionalColumns: DIDAR_ACTIVITY_POSITIONAL.map((c) => ({
|
||||||
|
key: c.key,
|
||||||
|
label: c.label,
|
||||||
|
})),
|
||||||
|
detectHeaderless: looksLikeDidarActivityHeaderless,
|
||||||
|
};
|
||||||
|
|
||||||
const TYPE_LABEL: Record<ActivityType, string> = {
|
const TYPE_LABEL: Record<ActivityType, string> = {
|
||||||
call: 'تماس با مشتری',
|
call: 'تماس با مشتری',
|
||||||
meeting: 'جلسه',
|
meeting: 'جلسه',
|
||||||
@@ -109,6 +151,7 @@ export class ActivitiesExcelService {
|
|||||||
company: { select: { id: true, name: true } },
|
company: { select: { id: true, name: true } },
|
||||||
deal: { select: { id: true, title: true } },
|
deal: { select: { id: true, title: true } },
|
||||||
assignee: { select: { fullName: true } },
|
assignee: { select: { fullName: true } },
|
||||||
|
assignees: { select: { fullName: true } },
|
||||||
createdBy: { select: { fullName: true } },
|
createdBy: { select: { fullName: true } },
|
||||||
},
|
},
|
||||||
orderBy: [{ dueAt: 'desc' }, { createdAt: 'desc' }],
|
orderBy: [{ dueAt: 'desc' }, { createdAt: 'desc' }],
|
||||||
@@ -124,7 +167,9 @@ export class ActivitiesExcelService {
|
|||||||
title: row.title,
|
title: row.title,
|
||||||
body: row.description ?? '',
|
body: row.description ?? '',
|
||||||
result: '',
|
result: '',
|
||||||
assignee: row.assignee?.fullName ?? '',
|
assignee: row.assignees?.length
|
||||||
|
? row.assignees.map((a) => a.fullName).join('، ')
|
||||||
|
: (row.assignee?.fullName ?? ''),
|
||||||
creator: row.createdBy?.fullName ?? '',
|
creator: row.createdBy?.fullName ?? '',
|
||||||
dueDate: formatJalaliDate(row.dueAt),
|
dueDate: formatJalaliDate(row.dueAt),
|
||||||
dueTime: formatClock(row.dueAt),
|
dueTime: formatClock(row.dueAt),
|
||||||
@@ -148,20 +193,199 @@ export class ActivitiesExcelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
preview(file: Express.Multer.File): Promise<ExcelPreviewResult> {
|
preview(file: Express.Multer.File): Promise<ExcelPreviewResult> {
|
||||||
return previewExcel(file, ACTIVITY_ALIASES, excelFieldsFromColumns(ACTIVITY_COLUMNS, ['title']));
|
return previewExcel(
|
||||||
|
file,
|
||||||
|
ACTIVITY_ALIASES,
|
||||||
|
excelFieldsFromColumns(ACTIVITY_COLUMNS, ['title']),
|
||||||
|
ACTIVITY_EXCEL_OPTIONS,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* آپلود فوری + پارس در پسزمینه (جلوگیری از ۵۰۲ nginx روی فایلهای بزرگ).
|
||||||
|
* وضعیت را با prepareStatus پول کنید.
|
||||||
|
*/
|
||||||
|
prepare(
|
||||||
|
actor: Actor,
|
||||||
|
file: Express.Multer.File,
|
||||||
|
mappingRaw?: string,
|
||||||
|
): ImportContactsResult {
|
||||||
|
if (!file?.buffer?.length) {
|
||||||
|
throw new BadRequestException('فایل ارسال نشده');
|
||||||
|
}
|
||||||
|
const mapping = parseExcelMapping(mappingRaw);
|
||||||
|
const sessionId = beginExcelImportPrepare(
|
||||||
|
actor.organizationId,
|
||||||
|
file.buffer,
|
||||||
|
(f) =>
|
||||||
|
readMappedRows(f, ACTIVITY_ALIASES, mapping, ACTIVITY_EXCEL_OPTIONS),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
created: 0,
|
||||||
|
skipped: 0,
|
||||||
|
errors: [],
|
||||||
|
sessionId,
|
||||||
|
status: 'parsing',
|
||||||
|
total: 0,
|
||||||
|
parsed: 0,
|
||||||
|
processed: 0,
|
||||||
|
hasMore: true,
|
||||||
|
nextOffset: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
prepareStatus(
|
||||||
|
actor: Actor,
|
||||||
|
sessionId: string,
|
||||||
|
): ExcelImportSessionStatus {
|
||||||
|
return getExcelImportPrepareStatus(sessionId, actor.organizationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async import(
|
async import(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
file: Express.Multer.File,
|
file: Express.Multer.File | undefined,
|
||||||
mappingRaw?: string,
|
mappingRaw?: string,
|
||||||
|
chunk?: { sessionId?: string; offset?: string | number; limit?: string | number },
|
||||||
): Promise<ImportContactsResult> {
|
): Promise<ImportContactsResult> {
|
||||||
const rows = await readMappedRows(file, ACTIVITY_ALIASES, parseExcelMapping(mappingRaw));
|
|
||||||
const result: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
const result: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
||||||
|
let ctx;
|
||||||
|
try {
|
||||||
|
ctx = await resolveExcelImportChunk({
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
file,
|
||||||
|
sessionId: chunk?.sessionId,
|
||||||
|
offset: chunk?.offset,
|
||||||
|
limit: chunk?.limit,
|
||||||
|
loadRows: () =>
|
||||||
|
readMappedRows(
|
||||||
|
file!,
|
||||||
|
ACTIVITY_ALIASES,
|
||||||
|
parseExcelMapping(mappingRaw),
|
||||||
|
ACTIVITY_EXCEL_OPTIONS,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof BadRequestException) throw e;
|
||||||
|
const message =
|
||||||
|
e instanceof Error ? e.message : 'خواندن فایل اکسل ناموفق بود';
|
||||||
|
result.errors.push({ row: 1, message });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < rows.length; i++) {
|
const MAX_ROWS = 100_000;
|
||||||
const row = rows[i]!;
|
if (ctx.total > MAX_ROWS) {
|
||||||
const rowNum = i + 2;
|
destroyExcelImportSession(ctx.sessionId);
|
||||||
|
result.errors.push({
|
||||||
|
row: 1,
|
||||||
|
message: `فایل بیش از ${MAX_ROWS} ردیف دارد. فایل را تقسیم کنید.`,
|
||||||
|
});
|
||||||
|
return { ...result, hasMore: false, total: ctx.total, processed: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const caches = getExcelImportSessionCaches(ctx.sessionId, actor.organizationId);
|
||||||
|
await this.processActivityRows(
|
||||||
|
actor,
|
||||||
|
ctx.slice,
|
||||||
|
ctx.offset,
|
||||||
|
result,
|
||||||
|
caches,
|
||||||
|
{ skipDuplicateCheck: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
return { ...result, ...chunkImportMeta(ctx) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ایمپورت تکهای JSON از مرورگر — فایل اکسل روی سرور آپلود/پارس نمیشود.
|
||||||
|
*/
|
||||||
|
async importRows(
|
||||||
|
actor: Actor,
|
||||||
|
dto: ImportActivityRowsDto,
|
||||||
|
): Promise<ImportContactsResult> {
|
||||||
|
const result: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
||||||
|
const rows = Array.isArray(dto.rows) ? dto.rows : [];
|
||||||
|
if (!rows.length) {
|
||||||
|
result.errors.push({ row: 1, message: 'ردیف ارسالشده خالی است' });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (rows.length > 80) {
|
||||||
|
result.errors.push({ row: 1, message: 'حداکثر ۸۰ ردیف در هر درخواست' });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = Math.max(0, Number(dto.total) || 0);
|
||||||
|
const offset = Math.max(0, Number(dto.offset) || 0);
|
||||||
|
let sessionId = (dto.sessionId ?? '').trim();
|
||||||
|
if (!sessionId) {
|
||||||
|
sessionId = createExcelImportCacheSession(actor.organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const caches = getExcelImportSessionCaches(sessionId, actor.organizationId);
|
||||||
|
await this.processActivityRows(actor, rows, offset, result, caches, {
|
||||||
|
// برای فایلهای خیلی بزرگ، بررسی تکراری هر ردیف درخواست را طولانی و ۵۰۲ میکند
|
||||||
|
skipDuplicateCheck: total > 2000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const processed = offset + rows.length;
|
||||||
|
const hasMore = total > 0 ? processed < total : false;
|
||||||
|
if (!hasMore) destroyExcelImportSession(sessionId);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
sessionId: hasMore ? sessionId : undefined,
|
||||||
|
total,
|
||||||
|
processed,
|
||||||
|
hasMore,
|
||||||
|
nextOffset: hasMore ? processed : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async processActivityRows(
|
||||||
|
actor: Actor,
|
||||||
|
slice: Array<Record<string, string>>,
|
||||||
|
offset: number,
|
||||||
|
result: ImportContactsResult,
|
||||||
|
caches: ExcelImportLookupCaches,
|
||||||
|
opts: { skipDuplicateCheck: boolean },
|
||||||
|
) {
|
||||||
|
const resolveUser = async (name?: string) => {
|
||||||
|
const key = (name ?? '').trim().toLowerCase();
|
||||||
|
if (!key) return null;
|
||||||
|
if (caches.user.has(key)) return caches.user.get(key) ?? null;
|
||||||
|
const id = await this.findUserId(actor.organizationId, name);
|
||||||
|
caches.user.set(key, id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
const resolvePerson = async (row: Record<string, string>) => {
|
||||||
|
const mobile = normalizePhone(row.personMobile);
|
||||||
|
const name = (row.personName ?? '').trim().toLowerCase();
|
||||||
|
const key = mobile ? `m:${mobile}` : name ? `n:${name}` : '';
|
||||||
|
if (!key) return null;
|
||||||
|
if (caches.person.has(key)) return caches.person.get(key) ?? null;
|
||||||
|
const id = await this.findPersonId(actor.organizationId, row);
|
||||||
|
caches.person.set(key, id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
const resolveCompany = async (name?: string) => {
|
||||||
|
const key = (name ?? '').trim().toLowerCase();
|
||||||
|
if (!key) return null;
|
||||||
|
if (caches.company.has(key)) return caches.company.get(key) ?? null;
|
||||||
|
const id = await this.findCompanyId(actor.organizationId, name);
|
||||||
|
caches.company.set(key, id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
const resolveDeal = async (title?: string) => {
|
||||||
|
const key = (title ?? '').trim().toLowerCase();
|
||||||
|
if (!key) return null;
|
||||||
|
if (caches.deal.has(key)) return caches.deal.get(key) ?? null;
|
||||||
|
const id = await this.findDealId(actor.organizationId, title);
|
||||||
|
caches.deal.set(key, id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < slice.length; i++) {
|
||||||
|
const row = slice[i]!;
|
||||||
|
const rowNum = offset + i + 2;
|
||||||
if ((row._type || '').trim() && row._type.trim().toLowerCase() !== 'activity') {
|
if ((row._type || '').trim() && row._type.trim().toLowerCase() !== 'activity') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -179,31 +403,40 @@ export class ActivitiesExcelService {
|
|||||||
const status = parseStatus(row.status);
|
const status = parseStatus(row.status);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const personId = await this.findPersonId(actor.organizationId, row);
|
const personId = await resolvePerson(row);
|
||||||
const companyId = await this.findCompanyId(actor.organizationId, row.companyName);
|
const companyId = await resolveCompany(row.companyName);
|
||||||
const dealId = await this.findDealId(actor.organizationId, row.dealTitle);
|
const dealId = await resolveDeal(row.dealTitle);
|
||||||
const assigneeId =
|
const assigneeNames = String(row.assignee ?? '')
|
||||||
(await this.findUserId(actor.organizationId, row.assignee)) ?? actor.userId;
|
.split(/[,،]/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const assigneeIds: string[] = [];
|
||||||
|
for (const name of assigneeNames) {
|
||||||
|
const uid = await resolveUser(name);
|
||||||
|
if (uid && !assigneeIds.includes(uid)) assigneeIds.push(uid);
|
||||||
|
}
|
||||||
|
if (!assigneeIds.length) assigneeIds.push(actor.userId);
|
||||||
|
const assigneeId = assigneeIds[0]!;
|
||||||
const creatorId =
|
const creatorId =
|
||||||
(await this.findUserId(actor.organizationId, row.creator)) ?? actor.userId;
|
(await resolveUser(row.creator)) ?? actor.userId;
|
||||||
|
|
||||||
const duplicate = dueAt
|
if (!opts.skipDuplicateCheck && dueAt) {
|
||||||
? await this.prisma.activity.findFirst({
|
const duplicate = await this.prisma.activity.findFirst({
|
||||||
where: {
|
where: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
title,
|
title,
|
||||||
dueAt,
|
dueAt,
|
||||||
personId: personId ?? null,
|
personId: personId ?? null,
|
||||||
},
|
},
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
})
|
});
|
||||||
: null;
|
if (duplicate) {
|
||||||
if (duplicate) {
|
result.skipped += 1;
|
||||||
result.skipped += 1;
|
continue;
|
||||||
continue;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.prisma.activity.create({
|
const created = await this.prisma.activity.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
title,
|
title,
|
||||||
@@ -220,7 +453,20 @@ export class ActivitiesExcelService {
|
|||||||
assigneeId,
|
assigneeId,
|
||||||
createdById: creatorId,
|
createdById: creatorId,
|
||||||
},
|
},
|
||||||
|
select: { id: true },
|
||||||
});
|
});
|
||||||
|
if (assigneeIds.length > 1) {
|
||||||
|
try {
|
||||||
|
await this.prisma.activity.update({
|
||||||
|
where: { id: created.id },
|
||||||
|
data: {
|
||||||
|
assignees: { set: assigneeIds.map((id) => ({ id })) },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* assigneeId بهتنهایی کافی است */
|
||||||
|
}
|
||||||
|
}
|
||||||
result.created += 1;
|
result.created += 1;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
result.errors.push({
|
result.errors.push({
|
||||||
@@ -229,8 +475,6 @@ export class ActivitiesExcelService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async findPersonId(organizationId: string, row: Record<string, string>) {
|
private async findPersonId(organizationId: string, row: Record<string, string>) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
@@ -17,28 +18,184 @@ import { FileInterceptor } from '@nestjs/platform-express';
|
|||||||
import { memoryStorage } from 'multer';
|
import { memoryStorage } from 'multer';
|
||||||
import type { Response } from 'express';
|
import type { Response } from 'express';
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { RequirePermission, SectionPermissionGuard } from '../auth/section-permission.guard';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import type { Actor } from '../common/record-scope';
|
import type { Actor } from '../common/record-scope';
|
||||||
import { ActivitiesService } from './activities.service';
|
import { ActivitiesService } from './activities.service';
|
||||||
import { ActivitiesExcelService } from './activities-excel.service';
|
import { ActivitiesExcelService } from './activities-excel.service';
|
||||||
|
import { ActivityStagesService } from './activity-stages.service';
|
||||||
|
import { ActivityTypesService } from './activity-types.service';
|
||||||
import {
|
import {
|
||||||
|
CreateActivityBoardDto,
|
||||||
CreateActivityDto,
|
CreateActivityDto,
|
||||||
|
CreateActivityStageDto,
|
||||||
|
CreateActivityTypeDto,
|
||||||
|
ImportActivityRowsDto,
|
||||||
ListActivitiesQueryDto,
|
ListActivitiesQueryDto,
|
||||||
|
ListActivityStagesQueryDto,
|
||||||
|
MoveActivityStageDto,
|
||||||
|
ReorderActivityStagesDto,
|
||||||
|
ReorderActivityTypesDto,
|
||||||
|
UpdateActivityBoardDto,
|
||||||
UpdateActivityDto,
|
UpdateActivityDto,
|
||||||
|
UpdateActivityStageDto,
|
||||||
|
UpdateActivityTypeDto,
|
||||||
} from './dto';
|
} from './dto';
|
||||||
import { brand } from '@mento/shared';
|
import { brand } from '@mento/shared';
|
||||||
|
|
||||||
|
const excelUpload = FileInterceptor('file', {
|
||||||
|
storage: memoryStorage(),
|
||||||
|
limits: { fileSize: 15_000_000 },
|
||||||
|
});
|
||||||
|
|
||||||
@Controller('activities')
|
@Controller('activities')
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard, SectionPermissionGuard)
|
||||||
|
@RequirePermission('activities')
|
||||||
export class ActivitiesController {
|
export class ActivitiesController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly activitiesService: ActivitiesService,
|
private readonly activitiesService: ActivitiesService,
|
||||||
private readonly excelService: ActivitiesExcelService,
|
private readonly excelService: ActivitiesExcelService,
|
||||||
|
private readonly stagesService: ActivityStagesService,
|
||||||
|
private readonly typesService: ActivityTypesService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get('summary')
|
@Get('summary')
|
||||||
summary(@CurrentUser() user: Actor) {
|
summary(
|
||||||
return this.activitiesService.summary(user.organizationId, user);
|
@CurrentUser() user: Actor,
|
||||||
|
@Query('desk') desk?: string,
|
||||||
|
) {
|
||||||
|
const scope = desk === 'mine' || desk === 'team' ? desk : undefined;
|
||||||
|
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, @Query() query: ListActivityStagesQueryDto) {
|
||||||
|
return this.stagesService.list(user.organizationId, query.boardId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('stages')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
createStage(@CurrentUser() user: Actor, @Body() dto: CreateActivityStageDto) {
|
||||||
|
return this.stagesService.create(user.organizationId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('stages/reorder')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
reorderStages(@CurrentUser() user: Actor, @Body() dto: ReorderActivityStagesDto) {
|
||||||
|
return this.stagesService.reorder(user.organizationId, dto.stageIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('stages/:id')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
updateStage(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateActivityStageDto,
|
||||||
|
) {
|
||||||
|
return this.stagesService.update(user.organizationId, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('stages/:id')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
async removeStage(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
await this.stagesService.remove(user.organizationId, id);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('types')
|
||||||
|
listTypes(@CurrentUser() user: Actor) {
|
||||||
|
return this.typesService.list(user.organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('types')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
createType(@CurrentUser() user: Actor, @Body() dto: CreateActivityTypeDto) {
|
||||||
|
return this.typesService.create(user.organizationId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('types/reorder')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
reorderTypes(@CurrentUser() user: Actor, @Body() dto: ReorderActivityTypesDto) {
|
||||||
|
return this.typesService.reorder(user.organizationId, dto.typeIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('types/:id')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
updateType(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateActivityTypeDto,
|
||||||
|
) {
|
||||||
|
return this.typesService.update(user.organizationId, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('types/:id')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
async removeType(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
await this.typesService.remove(user.organizationId, id);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('stage-counts')
|
||||||
|
stageCounts(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Query() query: ListActivitiesQueryDto,
|
||||||
|
) {
|
||||||
|
return this.activitiesService.stageCounts(
|
||||||
|
user.organizationId,
|
||||||
|
user,
|
||||||
|
query.filter ?? 'all',
|
||||||
|
query.q,
|
||||||
|
query.desk,
|
||||||
|
{
|
||||||
|
type: query.type,
|
||||||
|
typeDefId: query.typeDefId,
|
||||||
|
status: query.status,
|
||||||
|
assigneeId: query.assigneeId,
|
||||||
|
boardId: query.boardId,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -57,11 +214,21 @@ export class ActivitiesController {
|
|||||||
personId: query.personId,
|
personId: query.personId,
|
||||||
companyId: query.companyId,
|
companyId: query.companyId,
|
||||||
dealId: query.dealId,
|
dealId: query.dealId,
|
||||||
|
leadId: query.leadId,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
from: query.from,
|
from: query.from,
|
||||||
to: query.to,
|
to: query.to,
|
||||||
},
|
},
|
||||||
|
query.desk,
|
||||||
|
{
|
||||||
|
type: query.type,
|
||||||
|
typeDefId: query.typeDefId,
|
||||||
|
status: query.status,
|
||||||
|
assigneeId: query.assigneeId,
|
||||||
|
boardId: query.boardId,
|
||||||
|
},
|
||||||
|
query.stageId ? { stageId: query.stageId } : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,29 +247,61 @@ export class ActivitiesController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('import/preview')
|
@Post('import/preview')
|
||||||
@UseInterceptors(
|
@UseInterceptors(excelUpload)
|
||||||
FileInterceptor('file', {
|
importPreview(@UploadedFile() file?: Express.Multer.File) {
|
||||||
storage: memoryStorage(),
|
if (!file?.buffer?.length) {
|
||||||
limits: { fileSize: 15_000_000 },
|
throw new BadRequestException('فایل ارسال نشده');
|
||||||
}),
|
}
|
||||||
)
|
|
||||||
importPreview(@UploadedFile() file: Express.Multer.File) {
|
|
||||||
return this.excelService.preview(file);
|
return this.excelService.preview(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('import')
|
@Post('import/prepare')
|
||||||
@UseInterceptors(
|
@UseInterceptors(excelUpload)
|
||||||
FileInterceptor('file', {
|
importPrepare(
|
||||||
storage: memoryStorage(),
|
|
||||||
limits: { fileSize: 15_000_000 },
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
import(
|
|
||||||
@CurrentUser() user: Actor,
|
@CurrentUser() user: Actor,
|
||||||
@UploadedFile() file: Express.Multer.File,
|
@UploadedFile() file?: Express.Multer.File,
|
||||||
@Body('mapping') mapping?: string,
|
@Body('mapping') mapping?: string,
|
||||||
) {
|
) {
|
||||||
return this.excelService.import(user, file, mapping);
|
if (!file?.buffer?.length) {
|
||||||
|
throw new BadRequestException('فایل ارسال نشده');
|
||||||
|
}
|
||||||
|
return this.excelService.prepare(user, file, mapping);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('import/prepare/:sessionId')
|
||||||
|
importPrepareStatus(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('sessionId') sessionId: string,
|
||||||
|
) {
|
||||||
|
return this.excelService.prepareStatus(user, sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('import/rows')
|
||||||
|
importRows(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Body() dto: ImportActivityRowsDto,
|
||||||
|
) {
|
||||||
|
return this.excelService.importRows(user, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('import')
|
||||||
|
@UseInterceptors(excelUpload)
|
||||||
|
import(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@UploadedFile() file?: Express.Multer.File,
|
||||||
|
@Body('mapping') mapping?: string,
|
||||||
|
@Body('sessionId') sessionId?: string,
|
||||||
|
@Body('offset') offset?: string,
|
||||||
|
@Body('limit') limit?: string,
|
||||||
|
) {
|
||||||
|
if (!file?.buffer?.length && !sessionId) {
|
||||||
|
throw new BadRequestException('فایل ارسال نشده');
|
||||||
|
}
|
||||||
|
return this.excelService.import(user, file, mapping, {
|
||||||
|
sessionId,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@@ -110,6 +309,11 @@ export class ActivitiesController {
|
|||||||
return this.activitiesService.get(user.organizationId, id, user);
|
return this.activitiesService.get(user.organizationId, id, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post(':id/promote-from-prior')
|
||||||
|
promoteFromPrior(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
return this.activitiesService.promoteFromPrior(user, id);
|
||||||
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
create(@CurrentUser() user: Actor, @Body() dto: CreateActivityDto) {
|
create(@CurrentUser() user: Actor, @Body() dto: CreateActivityDto) {
|
||||||
return this.activitiesService.create(
|
return this.activitiesService.create(
|
||||||
@@ -129,6 +333,15 @@ export class ActivitiesController {
|
|||||||
return this.activitiesService.update(user.organizationId, id, user, dto);
|
return this.activitiesService.update(user.organizationId, id, user, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Patch(':id/stage')
|
||||||
|
moveStage(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: MoveActivityStageDto,
|
||||||
|
) {
|
||||||
|
return this.activitiesService.moveToStage(user.organizationId, id, user, dto.stageId);
|
||||||
|
}
|
||||||
|
|
||||||
@Patch(':id/complete')
|
@Patch(':id/complete')
|
||||||
complete(@CurrentUser() user: Actor, @Param('id') id: string) {
|
complete(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
return this.activitiesService.complete(user.organizationId, id, user);
|
return this.activitiesService.complete(user.organizationId, id, user);
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { Module } from '@nestjs/common';
|
|||||||
import { ActivitiesController } from './activities.controller';
|
import { ActivitiesController } from './activities.controller';
|
||||||
import { ActivitiesService } from './activities.service';
|
import { ActivitiesService } from './activities.service';
|
||||||
import { ActivitiesExcelService } from './activities-excel.service';
|
import { ActivitiesExcelService } from './activities-excel.service';
|
||||||
|
import { ActivityStagesService } from './activity-stages.service';
|
||||||
|
import { ActivityTypesService } from './activity-types.service';
|
||||||
import { NotificationsModule } from '../notifications/notifications.module';
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
import { AutomationsModule } from '../automations/automations.module';
|
import { AutomationsModule } from '../automations/automations.module';
|
||||||
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
||||||
@@ -9,7 +11,12 @@ import { MessageAutomationsModule } from '../message-automations/message-automat
|
|||||||
@Module({
|
@Module({
|
||||||
imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule],
|
imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule],
|
||||||
controllers: [ActivitiesController],
|
controllers: [ActivitiesController],
|
||||||
providers: [ActivitiesService, ActivitiesExcelService],
|
providers: [
|
||||||
exports: [ActivitiesService],
|
ActivitiesService,
|
||||||
|
ActivitiesExcelService,
|
||||||
|
ActivityStagesService,
|
||||||
|
ActivityTypesService,
|
||||||
|
],
|
||||||
|
exports: [ActivitiesService, ActivityStagesService, ActivityTypesService],
|
||||||
})
|
})
|
||||||
export class ActivitiesModule {}
|
export class ActivitiesModule {}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type {
|
import type {
|
||||||
ActivityDto,
|
ActivityDto,
|
||||||
|
ActivityFieldValues,
|
||||||
ActivityFilter,
|
ActivityFilter,
|
||||||
ActivitySummaryDto,
|
ActivitySummaryDto,
|
||||||
|
ActivityStageCountsDto,
|
||||||
CreateActivityRequest,
|
CreateActivityRequest,
|
||||||
PaginatedResponse,
|
PaginatedResponse,
|
||||||
UpdateActivityRequest,
|
UpdateActivityRequest,
|
||||||
@@ -16,9 +19,39 @@ import { PrismaService } from '../prisma/prisma.service';
|
|||||||
import { NotificationsService } from '../notifications/notifications.service';
|
import { NotificationsService } from '../notifications/notifications.service';
|
||||||
import { AutomationsService } from '../automations/automations.service';
|
import { AutomationsService } from '../automations/automations.service';
|
||||||
import { MessageAutomationsService } from '../message-automations/message-automations.service';
|
import { MessageAutomationsService } from '../message-automations/message-automations.service';
|
||||||
import { type Actor, assigneeWhere, ownerWhere } from '../common/record-scope';
|
import {
|
||||||
|
type Actor,
|
||||||
|
activityAccessWhere,
|
||||||
|
dealAccessWhere,
|
||||||
|
ownerWhere,
|
||||||
|
} from '../common/record-scope';
|
||||||
|
import { normalizeTags } from '../common/tags';
|
||||||
|
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 BoardStageContext } from './activity-stages.service';
|
||||||
|
import {
|
||||||
|
ActivityTypesService,
|
||||||
|
type SystemTypes,
|
||||||
|
type TypeRow,
|
||||||
|
} from './activity-types.service';
|
||||||
|
|
||||||
type ActivityActor = Pick<Actor, 'userId' | 'role'>;
|
type DtoContext = { stages?: BoardStageContext; types?: SystemTypes };
|
||||||
|
|
||||||
|
type ActivityActor = Pick<Actor, 'userId' | 'role' | 'priorLens' | 'priorCutoff'>;
|
||||||
|
|
||||||
|
/** stageId = شناسهٔ مرحله یا 'all'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمیکند (جز عقبافتاده) */
|
||||||
|
type StageScope = { stageId: string };
|
||||||
|
|
||||||
|
type ListFacets = {
|
||||||
|
type?: ActivityDto['type'];
|
||||||
|
typeDefId?: string;
|
||||||
|
status?: ActivityDto['status'];
|
||||||
|
assigneeId?: string;
|
||||||
|
/** گروه فعالیت؛ خالی = همهٔ گروهها */
|
||||||
|
boardId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
type ActivityRow = {
|
type ActivityRow = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -32,21 +65,36 @@ type ActivityRow = {
|
|||||||
reminderAt: Date | null;
|
reminderAt: Date | null;
|
||||||
reminderNotifyApp: boolean;
|
reminderNotifyApp: boolean;
|
||||||
reminderNotifySms: boolean;
|
reminderNotifySms: boolean;
|
||||||
|
reminderSentAt: Date | null;
|
||||||
completedAt: Date | null;
|
completedAt: Date | null;
|
||||||
|
importSource?: string;
|
||||||
|
promotedFromPriorAt?: Date | null;
|
||||||
|
tags: string[];
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
person: { id: string; firstName: string; lastName: string } | null;
|
person: { id: string; firstName: string; lastName: string } | null;
|
||||||
company: { id: string; name: string } | null;
|
company: { id: string; name: string } | null;
|
||||||
deal: { id: string; title: string } | null;
|
deal: { id: string; title: string } | null;
|
||||||
|
lead?: { id: string; title: string } | null;
|
||||||
assignee: { id: string; fullName: string } | null;
|
assignee: { id: string; fullName: string } | null;
|
||||||
|
assignees: Array<{ id: string; fullName: string }>;
|
||||||
createdBy: { id: string; fullName: string } | null;
|
createdBy: { id: string; fullName: string } | 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 = {
|
const include = {
|
||||||
|
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 } },
|
person: { select: { id: true, firstName: true, lastName: true } },
|
||||||
company: { select: { id: true, name: true } },
|
company: { select: { id: true, name: true } },
|
||||||
deal: { select: { id: true, title: true } },
|
deal: { select: { id: true, title: true } },
|
||||||
|
lead: { select: { id: true, title: true } },
|
||||||
assignee: { select: { id: true, fullName: true } },
|
assignee: { select: { id: true, fullName: true } },
|
||||||
|
assignees: { select: { id: true, fullName: true }, orderBy: { fullName: 'asc' as const } },
|
||||||
createdBy: { select: { id: true, fullName: true } },
|
createdBy: { select: { id: true, fullName: true } },
|
||||||
} satisfies Prisma.ActivityInclude;
|
} satisfies Prisma.ActivityInclude;
|
||||||
|
|
||||||
@@ -57,21 +105,76 @@ export class ActivitiesService {
|
|||||||
private readonly notifications: NotificationsService,
|
private readonly notifications: NotificationsService,
|
||||||
private readonly automations: AutomationsService,
|
private readonly automations: AutomationsService,
|
||||||
private readonly messageAutomations: MessageAutomationsService,
|
private readonly messageAutomations: MessageAutomationsService,
|
||||||
|
private readonly stages: ActivityStagesService,
|
||||||
|
private readonly types: ActivityTypesService,
|
||||||
|
private readonly game: GamificationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
private async ctx(organizationId: string): Promise<DtoContext> {
|
||||||
|
const [stages, types] = await Promise.all([
|
||||||
|
this.stages.boardContext(organizationId),
|
||||||
|
this.types.system(organizationId),
|
||||||
|
]);
|
||||||
|
return { stages, types };
|
||||||
|
}
|
||||||
|
|
||||||
async summary(
|
async summary(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
|
desk?: 'mine' | 'team',
|
||||||
): Promise<ActivitySummaryDto> {
|
): Promise<ActivitySummaryDto> {
|
||||||
const { start, end } = dayBounds();
|
const { start, end } = dayBounds();
|
||||||
const scope = assigneeWhere(actor);
|
const scope: Prisma.ActivityWhereInput =
|
||||||
|
desk === 'mine'
|
||||||
|
? {
|
||||||
|
OR: [
|
||||||
|
{ assigneeId: actor.userId },
|
||||||
|
{ assignees: { some: { id: actor.userId } } },
|
||||||
|
{ participantIds: { has: actor.userId } },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: activityAccessWhere(actor);
|
||||||
|
const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
|
||||||
|
const [todayCount, overdueCount] = await Promise.all([
|
||||||
|
this.prisma.activity.count({
|
||||||
|
where: {
|
||||||
|
AND: [
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
...scope,
|
||||||
|
status: 'open',
|
||||||
|
dueAt: { gte: start, lt: end },
|
||||||
|
},
|
||||||
|
prior,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.activity.count({
|
||||||
|
where: {
|
||||||
|
AND: [
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
...scope,
|
||||||
|
status: 'open',
|
||||||
|
dueAt: { lt: start },
|
||||||
|
},
|
||||||
|
prior,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
const [today, overdue, upcoming] = await Promise.all([
|
const [today, overdue, upcoming] = await Promise.all([
|
||||||
this.prisma.activity.findMany({
|
this.prisma.activity.findMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId,
|
AND: [
|
||||||
...scope,
|
{
|
||||||
status: 'open',
|
organizationId,
|
||||||
dueAt: { gte: start, lt: end },
|
...scope,
|
||||||
|
status: 'open',
|
||||||
|
dueAt: { gte: start, lt: end },
|
||||||
|
},
|
||||||
|
prior,
|
||||||
|
],
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
||||||
@@ -79,10 +182,15 @@ export class ActivitiesService {
|
|||||||
}),
|
}),
|
||||||
this.prisma.activity.findMany({
|
this.prisma.activity.findMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId,
|
AND: [
|
||||||
...scope,
|
{
|
||||||
status: 'open',
|
organizationId,
|
||||||
dueAt: { lt: start },
|
...scope,
|
||||||
|
status: 'open',
|
||||||
|
dueAt: { lt: start },
|
||||||
|
},
|
||||||
|
prior,
|
||||||
|
],
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
orderBy: [{ dueAt: 'asc' }],
|
orderBy: [{ dueAt: 'asc' }],
|
||||||
@@ -90,10 +198,15 @@ export class ActivitiesService {
|
|||||||
}),
|
}),
|
||||||
this.prisma.activity.findMany({
|
this.prisma.activity.findMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId,
|
AND: [
|
||||||
...scope,
|
{
|
||||||
status: 'open',
|
organizationId,
|
||||||
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
...scope,
|
||||||
|
status: 'open',
|
||||||
|
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
||||||
|
},
|
||||||
|
prior,
|
||||||
|
],
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
||||||
@@ -101,12 +214,13 @@ export class ActivitiesService {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const ctx = await this.ctx(organizationId);
|
||||||
return {
|
return {
|
||||||
today: today.map((row) => this.toDto(row)),
|
today: today.map((row) => this.toDto(row, ctx)),
|
||||||
overdue: overdue.map((row) => this.toDto(row)),
|
overdue: overdue.map((row) => this.toDto(row, ctx)),
|
||||||
upcoming: upcoming.map((row) => this.toDto(row)),
|
upcoming: upcoming.map((row) => this.toDto(row, ctx)),
|
||||||
todayCount: today.length,
|
todayCount,
|
||||||
overdueCount: overdue.length,
|
overdueCount,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,12 +235,17 @@ export class ActivitiesService {
|
|||||||
personId?: string;
|
personId?: string;
|
||||||
companyId?: string;
|
companyId?: string;
|
||||||
dealId?: string;
|
dealId?: string;
|
||||||
|
leadId?: string;
|
||||||
},
|
},
|
||||||
range?: {
|
range?: {
|
||||||
from?: string;
|
from?: string;
|
||||||
to?: string;
|
to?: string;
|
||||||
},
|
},
|
||||||
|
desk?: 'mine' | 'team',
|
||||||
|
facets?: ListFacets,
|
||||||
|
stageScope?: StageScope,
|
||||||
): Promise<PaginatedResponse<ActivityDto>> {
|
): Promise<PaginatedResponse<ActivityDto>> {
|
||||||
|
const typeRows = await this.types.rows(organizationId);
|
||||||
const where = this.buildWhere(
|
const where = this.buildWhere(
|
||||||
organizationId,
|
organizationId,
|
||||||
actor,
|
actor,
|
||||||
@@ -134,7 +253,27 @@ export class ActivitiesService {
|
|||||||
q,
|
q,
|
||||||
entity,
|
entity,
|
||||||
range,
|
range,
|
||||||
|
desk,
|
||||||
|
facets,
|
||||||
|
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: boardCtx,
|
||||||
|
types: this.types.systemOf(typeRows),
|
||||||
|
};
|
||||||
const take = Math.min(Math.max(limit, 1), 200);
|
const take = Math.min(Math.max(limit, 1), 200);
|
||||||
const [rows, total] = await this.prisma.$transaction([
|
const [rows, total] = await this.prisma.$transaction([
|
||||||
this.prisma.activity.findMany({
|
this.prisma.activity.findMany({
|
||||||
@@ -148,24 +287,113 @@ export class ActivitiesService {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: rows.map((row) => this.toDto(row)),
|
items: rows.map((row) => this.toDto(row, ctx)),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
limit: take,
|
limit: take,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** تعداد فعالیت هر مرحله با همان فیلترهای لیست (زمان، جستجو، میز، نوع، کارشناس) */
|
||||||
|
async stageCounts(
|
||||||
|
organizationId: string,
|
||||||
|
actor: ActivityActor,
|
||||||
|
filter: ActivityFilter,
|
||||||
|
q?: string,
|
||||||
|
desk?: 'mine' | 'team',
|
||||||
|
facets?: ListFacets,
|
||||||
|
): Promise<ActivityStageCountsDto> {
|
||||||
|
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(
|
||||||
|
organizationId,
|
||||||
|
actor,
|
||||||
|
filter,
|
||||||
|
q,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
desk,
|
||||||
|
facets,
|
||||||
|
{ 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,
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
const counts: Record<string, number> = Object.fromEntries(rows.map((r) => [r.id, 0]));
|
||||||
|
let total = 0;
|
||||||
|
for (const g of groups) {
|
||||||
|
const n = g._count._all;
|
||||||
|
total += n;
|
||||||
|
const target =
|
||||||
|
g.stageId && kindOf.get(g.stageId) === g.status ? g.stageId : defaults[g.status];
|
||||||
|
if (target) counts[target] = (counts[target] ?? 0) + n;
|
||||||
|
}
|
||||||
|
return { counts, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
async moveToStage(
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
actor: ActivityActor,
|
||||||
|
stageId: string,
|
||||||
|
): Promise<ActivityDto> {
|
||||||
|
await this.ensureExists(organizationId, id, actor);
|
||||||
|
const stage = await this.stages.get(organizationId, stageId);
|
||||||
|
const existing = await this.prisma.activity.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
select: { status: true, completedAt: true },
|
||||||
|
});
|
||||||
|
const row = await this.prisma.activity.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
stageId: stage.id,
|
||||||
|
boardId: stage.boardId,
|
||||||
|
status: stage.kind,
|
||||||
|
completedAt:
|
||||||
|
stage.kind === 'done'
|
||||||
|
? existing?.status === 'done'
|
||||||
|
? existing.completedAt ?? new Date()
|
||||||
|
: new Date()
|
||||||
|
: stage.kind === 'open'
|
||||||
|
? null
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
include,
|
||||||
|
});
|
||||||
|
if (stage.kind === 'done' && existing?.status !== 'done') {
|
||||||
|
await this.fireDone(organizationId, row);
|
||||||
|
}
|
||||||
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
|
}
|
||||||
|
|
||||||
async get(
|
async get(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
id: string,
|
id: string,
|
||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
): Promise<ActivityDto> {
|
): Promise<ActivityDto> {
|
||||||
const row = await this.prisma.activity.findFirst({
|
const row = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId, ...assigneeWhere(actor) },
|
where: { id, organizationId, ...activityAccessWhere(actor) },
|
||||||
include,
|
include,
|
||||||
});
|
});
|
||||||
if (!row) throw new NotFoundException('فعالیت پیدا نشد');
|
if (!row) throw new NotFoundException('فعالیت پیدا نشد');
|
||||||
return this.toDto(row);
|
const dto = this.toDto(row, await this.ctx(organizationId));
|
||||||
|
if (row.participantIds.length) {
|
||||||
|
dto.participantUsers = await this.prisma.user.findMany({
|
||||||
|
where: { id: { in: row.participantIds } },
|
||||||
|
select: { id: true, fullName: true },
|
||||||
|
orderBy: { fullName: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(
|
async create(
|
||||||
@@ -176,14 +404,51 @@ export class ActivitiesService {
|
|||||||
): Promise<ActivityDto> {
|
): Promise<ActivityDto> {
|
||||||
const linkActor = actor ?? { userId, role: 'owner' };
|
const linkActor = actor ?? { userId, role: 'owner' };
|
||||||
await this.assertLinks(organizationId, linkActor, dto);
|
await this.assertLinks(organizationId, linkActor, dto);
|
||||||
const assigneeId = emptyToNull(dto.assigneeId ?? null) ?? userId;
|
const assigneeIds = await this.normalizeAssigneeIds(
|
||||||
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
organizationId,
|
||||||
|
dto.assigneeIds?.length
|
||||||
|
? dto.assigneeIds
|
||||||
|
: dto.assigneeId
|
||||||
|
? [dto.assigneeId]
|
||||||
|
: [userId],
|
||||||
|
);
|
||||||
|
const assigneeId = assigneeIds[0] ?? userId;
|
||||||
|
const initialStageId = emptyToNull(dto.stageId ?? null);
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
const { fields, participantIds } = await this.types.sanitizeValues(
|
||||||
|
organizationId,
|
||||||
|
resolved.fields,
|
||||||
|
dto.fields,
|
||||||
|
);
|
||||||
|
|
||||||
const row = await this.prisma.activity.create({
|
const row = await this.prisma.activity.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId,
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
...(initialStage
|
||||||
|
? {
|
||||||
|
stageId: initialStage.id,
|
||||||
|
status: initialStage.kind,
|
||||||
|
completedAt: initialStage.kind === 'done' ? new Date() : null,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
title: dto.title.trim(),
|
title: dto.title.trim(),
|
||||||
type: dto.type ?? 'task',
|
type: resolved.baseType,
|
||||||
|
typeDefId: resolved.typeDefId,
|
||||||
|
fields: fields as Prisma.InputJsonValue,
|
||||||
|
participantIds,
|
||||||
priority: dto.priority ?? 'medium',
|
priority: dto.priority ?? 'medium',
|
||||||
description: emptyToNull(dto.description),
|
description: emptyToNull(dto.description),
|
||||||
dueAt: dto.dueAt ? new Date(dto.dueAt) : null,
|
dueAt: dto.dueAt ? new Date(dto.dueAt) : null,
|
||||||
@@ -191,19 +456,23 @@ export class ActivitiesService {
|
|||||||
reminderAt: dto.reminderAt ? new Date(dto.reminderAt) : null,
|
reminderAt: dto.reminderAt ? new Date(dto.reminderAt) : null,
|
||||||
reminderNotifyApp: dto.reminderNotifyApp ?? true,
|
reminderNotifyApp: dto.reminderNotifyApp ?? true,
|
||||||
reminderNotifySms: dto.reminderNotifySms ?? false,
|
reminderNotifySms: dto.reminderNotifySms ?? false,
|
||||||
|
tags: normalizeTags(dto.tags),
|
||||||
personId: emptyToNull(dto.personId ?? null),
|
personId: emptyToNull(dto.personId ?? null),
|
||||||
companyId: emptyToNull(dto.companyId ?? null),
|
companyId: emptyToNull(dto.companyId ?? null),
|
||||||
dealId: emptyToNull(dto.dealId ?? null),
|
dealId: emptyToNull(dto.dealId ?? null),
|
||||||
assigneeId,
|
assigneeId,
|
||||||
|
assignees: assigneeIds.length
|
||||||
|
? { connect: assigneeIds.map((id) => ({ id })) }
|
||||||
|
: undefined,
|
||||||
createdById: userId,
|
createdById: userId,
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (assigneeId) {
|
for (const uid of assigneeIds) {
|
||||||
await this.notifications.create({
|
await this.notifications.create({
|
||||||
organizationId,
|
organizationId,
|
||||||
userId: assigneeId,
|
userId: uid,
|
||||||
type: 'activity_assigned',
|
type: 'activity_assigned',
|
||||||
title: 'فعالیت جدید برای شما',
|
title: 'فعالیت جدید برای شما',
|
||||||
body: row.title,
|
body: row.title,
|
||||||
@@ -212,6 +481,11 @@ export class ActivitiesService {
|
|||||||
entityId: row.id,
|
entityId: row.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
await this.notifyParticipants(
|
||||||
|
organizationId,
|
||||||
|
row,
|
||||||
|
participantIds.filter((uid) => !assigneeIds.includes(uid) && uid !== userId),
|
||||||
|
);
|
||||||
|
|
||||||
await this.messageAutomations.onEvent('activity_created', {
|
await this.messageAutomations.onEvent('activity_created', {
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -224,8 +498,27 @@ export class ActivitiesService {
|
|||||||
assigneeId: row.assignee?.id ?? null,
|
assigneeId: row.assignee?.id ?? null,
|
||||||
ownerId: row.assignee?.id ?? null,
|
ownerId: row.assignee?.id ?? null,
|
||||||
});
|
});
|
||||||
|
const gameBase = {
|
||||||
|
organizationId,
|
||||||
|
userId,
|
||||||
|
entityType: 'activity',
|
||||||
|
entityId: row.id,
|
||||||
|
entityTitle: row.title,
|
||||||
|
facts: {
|
||||||
|
activityType: row.type,
|
||||||
|
typeName: row.typeDef?.name ?? null,
|
||||||
|
priority: row.priority,
|
||||||
|
hasDescription: !!row.description?.trim(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
this.game.emit({ ...gameBase, event: 'ACTIVITY_CREATED' });
|
||||||
|
if (row.type === 'call') this.game.emit({ ...gameBase, event: 'CALL_LOGGED' });
|
||||||
|
if (row.type === 'meeting') this.game.emit({ ...gameBase, event: 'MEETING_CREATED' });
|
||||||
|
if (initialStage?.kind === 'done') {
|
||||||
|
await this.fireDone(organizationId, row);
|
||||||
|
}
|
||||||
|
|
||||||
return this.toDto(row);
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(
|
async update(
|
||||||
@@ -237,23 +530,84 @@ export class ActivitiesService {
|
|||||||
await this.ensureExists(organizationId, id, actor);
|
await this.ensureExists(organizationId, id, actor);
|
||||||
await this.assertLinks(organizationId, actor, dto);
|
await this.assertLinks(organizationId, actor, dto);
|
||||||
|
|
||||||
|
const existing = await this.prisma.activity.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
select: { status: true, type: true, typeDefId: true, fields: true, participantIds: true },
|
||||||
|
});
|
||||||
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
||||||
if (dto.title !== undefined) data.title = dto.title.trim();
|
if (dto.title !== undefined) data.title = dto.title.trim();
|
||||||
if (dto.type !== undefined) data.type = dto.type;
|
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) {
|
||||||
|
const resolved = await this.types.resolve(
|
||||||
|
organizationId,
|
||||||
|
typeChanged
|
||||||
|
? { typeDefId: dto.typeDefId, type: dto.type }
|
||||||
|
: { typeDefId: existing?.typeDefId, type: existing?.type },
|
||||||
|
);
|
||||||
|
const { fields, participantIds } = await this.types.sanitizeValues(
|
||||||
|
organizationId,
|
||||||
|
resolved.fields,
|
||||||
|
dto.fields ?? existing?.fields,
|
||||||
|
);
|
||||||
|
data.type = resolved.baseType;
|
||||||
|
data.typeDefId = resolved.typeDefId;
|
||||||
|
data.fields = fields as Prisma.InputJsonValue;
|
||||||
|
data.participantIds = participantIds;
|
||||||
|
const before = new Set(existing?.participantIds ?? []);
|
||||||
|
addedParticipants = participantIds.filter((uid) => !before.has(uid) && uid !== actor.userId);
|
||||||
|
}
|
||||||
if (dto.priority !== undefined) data.priority = dto.priority;
|
if (dto.priority !== undefined) data.priority = dto.priority;
|
||||||
if ('description' in dto) data.description = emptyToNull(dto.description);
|
if ('description' in dto) data.description = emptyToNull(dto.description);
|
||||||
if ('dueAt' in dto) data.dueAt = dto.dueAt ? new Date(dto.dueAt) : null;
|
if ('dueAt' in dto) data.dueAt = dto.dueAt ? new Date(dto.dueAt) : null;
|
||||||
if ('durationMinutes' in dto) data.durationMinutes = dto.durationMinutes ?? null;
|
if ('durationMinutes' in dto) data.durationMinutes = dto.durationMinutes ?? null;
|
||||||
if ('reminderAt' in dto) data.reminderAt = dto.reminderAt ? new Date(dto.reminderAt) : null;
|
if ('reminderAt' in dto) {
|
||||||
|
const nextReminder = dto.reminderAt ? new Date(dto.reminderAt) : null;
|
||||||
|
const current = await this.prisma.activity.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { reminderAt: true },
|
||||||
|
});
|
||||||
|
const prevMs = current?.reminderAt?.getTime() ?? null;
|
||||||
|
const nextMs = nextReminder?.getTime() ?? null;
|
||||||
|
data.reminderAt = nextReminder;
|
||||||
|
if (prevMs !== nextMs) data.reminderSentAt = null;
|
||||||
|
}
|
||||||
if (dto.reminderNotifyApp !== undefined) data.reminderNotifyApp = dto.reminderNotifyApp;
|
if (dto.reminderNotifyApp !== undefined) data.reminderNotifyApp = dto.reminderNotifyApp;
|
||||||
if (dto.reminderNotifySms !== undefined) data.reminderNotifySms = dto.reminderNotifySms;
|
if (dto.reminderNotifySms !== undefined) data.reminderNotifySms = dto.reminderNotifySms;
|
||||||
|
if ('tags' in dto) data.tags = normalizeTags(dto.tags);
|
||||||
if ('personId' in dto) data.personId = emptyToNull(dto.personId ?? null);
|
if ('personId' in dto) data.personId = emptyToNull(dto.personId ?? null);
|
||||||
if ('companyId' in dto) data.companyId = emptyToNull(dto.companyId ?? null);
|
if ('companyId' in dto) data.companyId = emptyToNull(dto.companyId ?? null);
|
||||||
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
||||||
if ('assigneeId' in dto) {
|
let assigneeConnect: Array<{ id: string }> | undefined;
|
||||||
|
if (dto.assigneeIds !== undefined) {
|
||||||
|
const assigneeIds = await this.normalizeAssigneeIds(
|
||||||
|
organizationId,
|
||||||
|
dto.assigneeIds,
|
||||||
|
);
|
||||||
|
if (!assigneeIds.length) {
|
||||||
|
throw new BadRequestException('حداقل یک مسئول لازم است');
|
||||||
|
}
|
||||||
|
data.assigneeId = assigneeIds[0]!;
|
||||||
|
assigneeConnect = assigneeIds.map((uid) => ({ id: uid }));
|
||||||
|
} else if ('assigneeId' in dto) {
|
||||||
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
||||||
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
||||||
data.assigneeId = assigneeId;
|
data.assigneeId = assigneeId;
|
||||||
|
if (assigneeId) assigneeConnect = [{ id: assigneeId }];
|
||||||
|
else assigneeConnect = [];
|
||||||
}
|
}
|
||||||
if (dto.status !== undefined) {
|
if (dto.status !== undefined) {
|
||||||
data.status = dto.status;
|
data.status = dto.status;
|
||||||
@@ -261,19 +615,31 @@ export class ActivitiesService {
|
|||||||
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
|
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = await this.prisma.activity.findFirst({
|
|
||||||
where: { id, organizationId },
|
|
||||||
select: { status: true },
|
|
||||||
});
|
|
||||||
const row = await this.prisma.activity.update({
|
const row = await this.prisma.activity.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data,
|
data: {
|
||||||
|
...data,
|
||||||
|
...(assigneeConnect
|
||||||
|
? { assignees: { set: assigneeConnect } }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
include,
|
include,
|
||||||
});
|
});
|
||||||
|
if (addedParticipants.length) {
|
||||||
|
const assigneeSet = new Set([
|
||||||
|
...(row.assignee ? [row.assignee.id] : []),
|
||||||
|
...row.assignees.map((a) => a.id),
|
||||||
|
]);
|
||||||
|
await this.notifyParticipants(
|
||||||
|
organizationId,
|
||||||
|
row,
|
||||||
|
addedParticipants.filter((uid) => !assigneeSet.has(uid)),
|
||||||
|
);
|
||||||
|
}
|
||||||
if (dto.status === 'done' && existing?.status !== 'done') {
|
if (dto.status === 'done' && existing?.status !== 'done') {
|
||||||
await this.fireDone(organizationId, row);
|
await this.fireDone(organizationId, row);
|
||||||
}
|
}
|
||||||
return this.toDto(row);
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
}
|
}
|
||||||
|
|
||||||
async complete(
|
async complete(
|
||||||
@@ -294,7 +660,39 @@ export class ActivitiesService {
|
|||||||
if (existing?.status !== 'done') {
|
if (existing?.status !== 'done') {
|
||||||
await this.fireDone(organizationId, row);
|
await this.fireDone(organizationId, row);
|
||||||
}
|
}
|
||||||
return this.toDto(row);
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async promoteFromPrior(actor: Actor, id: string): Promise<ActivityDto> {
|
||||||
|
if (
|
||||||
|
(actor.priorLens !== 'current' && actor.priorLens !== 'archive') ||
|
||||||
|
!actor.priorCutoff
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException('بایگانی اطلاعات قبل برای شما فعال نیست.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await this.prisma.activity.findFirst({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...activityAccessWhere(actor),
|
||||||
|
},
|
||||||
|
select: { id: true, createdAt: true, promotedFromPriorAt: true },
|
||||||
|
});
|
||||||
|
if (!row) throw new NotFoundException('فعالیت پیدا نشد');
|
||||||
|
if (row.promotedFromPriorAt) {
|
||||||
|
throw new BadRequestException('این فعالیت قبلاً منتقل شده است.');
|
||||||
|
}
|
||||||
|
if (row.createdAt >= actor.priorCutoff) {
|
||||||
|
throw new BadRequestException('این فعالیت در بایگانی نیست.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await this.prisma.activity.update({
|
||||||
|
where: { id },
|
||||||
|
data: { promotedFromPriorAt: new Date() },
|
||||||
|
include,
|
||||||
|
});
|
||||||
|
return this.toDto(updated, await this.ctx(actor.organizationId));
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(
|
async remove(
|
||||||
@@ -315,36 +713,76 @@ export class ActivitiesService {
|
|||||||
personId?: string;
|
personId?: string;
|
||||||
companyId?: string;
|
companyId?: string;
|
||||||
dealId?: string;
|
dealId?: string;
|
||||||
|
leadId?: string;
|
||||||
},
|
},
|
||||||
range?: {
|
range?: {
|
||||||
from?: string;
|
from?: string;
|
||||||
to?: string;
|
to?: string;
|
||||||
},
|
},
|
||||||
|
desk?: 'mine' | 'team',
|
||||||
|
facets?: ListFacets,
|
||||||
|
stageScope?: StageScope,
|
||||||
|
typeRows: TypeRow[] = [],
|
||||||
): Prisma.ActivityWhereInput {
|
): Prisma.ActivityWhereInput {
|
||||||
const { start, end } = dayBounds();
|
const { start, end } = dayBounds();
|
||||||
const base: Prisma.ActivityWhereInput = {
|
const scope: Prisma.ActivityWhereInput =
|
||||||
organizationId,
|
desk === 'mine'
|
||||||
...assigneeWhere(actor),
|
|
||||||
...(entity?.personId ? { personId: entity.personId } : {}),
|
|
||||||
...(entity?.companyId ? { companyId: entity.companyId } : {}),
|
|
||||||
...(entity?.dealId ? { dealId: entity.dealId } : {}),
|
|
||||||
...(q?.trim()
|
|
||||||
? {
|
? {
|
||||||
OR: [
|
OR: [
|
||||||
{ title: { contains: q.trim(), mode: 'insensitive' } },
|
{ assigneeId: actor.userId },
|
||||||
{ description: { contains: q.trim(), mode: 'insensitive' } },
|
{ assignees: { some: { id: actor.userId } } },
|
||||||
{
|
{ participantIds: { has: actor.userId } },
|
||||||
person: {
|
|
||||||
OR: [
|
|
||||||
{ firstName: { contains: q.trim(), mode: 'insensitive' } },
|
|
||||||
{ lastName: { contains: q.trim(), mode: 'insensitive' } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ deal: { title: { contains: q.trim(), mode: 'insensitive' } } },
|
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
: {}),
|
: activityAccessWhere(actor);
|
||||||
|
const facetAssignee = facets?.assigneeId?.trim();
|
||||||
|
const facetTypeDef = facets?.typeDefId?.trim();
|
||||||
|
const andParts: Prisma.ActivityWhereInput[] = [
|
||||||
|
scope,
|
||||||
|
...(facets?.type ? [{ type: facets.type }] : []),
|
||||||
|
...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []),
|
||||||
|
...(facets?.status ? [{ status: facets.status }] : []),
|
||||||
|
...(facetAssignee
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
OR: [
|
||||||
|
{ assigneeId: facetAssignee },
|
||||||
|
{ assignees: { some: { id: facetAssignee } } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(entity?.personId ? [{ personId: entity.personId }] : []),
|
||||||
|
...(entity?.companyId ? [{ companyId: entity.companyId }] : []),
|
||||||
|
...(entity?.dealId ? [{ dealId: entity.dealId }] : []),
|
||||||
|
...(entity?.leadId ? [{ leadId: entity.leadId }] : []),
|
||||||
|
];
|
||||||
|
const search = buildSearchWhere<Prisma.ActivityWhereInput>(q, (t) => [
|
||||||
|
{ title: ci(t) },
|
||||||
|
{ description: ci(t) },
|
||||||
|
{ tags: { has: t.replace(/^#/, '') } },
|
||||||
|
{
|
||||||
|
person: {
|
||||||
|
OR: [
|
||||||
|
{ firstName: ci(t) },
|
||||||
|
{ lastName: ci(t) },
|
||||||
|
{ mobile: { contains: t } },
|
||||||
|
{ phone: { contains: t } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ company: { name: ci(t) } },
|
||||||
|
{ deal: { title: ci(t) } },
|
||||||
|
{ assignee: { fullName: ci(t) } },
|
||||||
|
{ assignees: { some: { fullName: ci(t) } } },
|
||||||
|
...typesMatching(t).map((type) => ({ type })),
|
||||||
|
...this.types.searchByName(typeRows, t),
|
||||||
|
]);
|
||||||
|
if (search) andParts.push(search);
|
||||||
|
andParts.push(activityPriorWhere(actor.priorLens, actor.priorCutoff));
|
||||||
|
const base: Prisma.ActivityWhereInput = {
|
||||||
|
organizationId,
|
||||||
|
AND: andParts,
|
||||||
};
|
};
|
||||||
|
|
||||||
const fromDate = range?.from ? new Date(range.from) : null;
|
const fromDate = range?.from ? new Date(range.from) : null;
|
||||||
@@ -361,19 +799,33 @@ export class ActivitiesService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Explicit status facet overrides the status implied by time tabs.
|
||||||
|
// With stage tabs/columns the stage decides status; time filters only narrow dueAt.
|
||||||
|
const impliedOpen = facets?.status
|
||||||
|
? { status: facets.status }
|
||||||
|
: stageScope
|
||||||
|
? {}
|
||||||
|
: { status: 'open' as const };
|
||||||
|
const impliedDone = facets?.status ? { status: facets.status } : { status: 'done' as const };
|
||||||
|
|
||||||
switch (filter) {
|
switch (filter) {
|
||||||
case 'today':
|
case 'today':
|
||||||
return { ...base, status: 'open', dueAt: { gte: start, lt: end } };
|
return { ...base, ...impliedOpen, dueAt: { gte: start, lt: end } };
|
||||||
case 'overdue':
|
case 'overdue':
|
||||||
return { ...base, status: 'open', dueAt: { lt: start } };
|
// عقبافتاده ذاتاً یعنی باز و موعدگذشته
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
...(facets?.status ? { status: facets.status } : { status: 'open' as const }),
|
||||||
|
dueAt: { lt: start },
|
||||||
|
};
|
||||||
case 'upcoming':
|
case 'upcoming':
|
||||||
return {
|
return {
|
||||||
...base,
|
...base,
|
||||||
status: 'open',
|
...impliedOpen,
|
||||||
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
||||||
};
|
};
|
||||||
case 'done':
|
case 'done':
|
||||||
return { ...base, status: 'done' };
|
return { ...base, ...impliedDone };
|
||||||
case 'all':
|
case 'all':
|
||||||
default:
|
default:
|
||||||
return base;
|
return base;
|
||||||
@@ -389,8 +841,26 @@ export class ActivitiesService {
|
|||||||
company: { id: string } | null;
|
company: { id: string } | null;
|
||||||
deal: { id: string } | null;
|
deal: { id: string } | null;
|
||||||
assignee: { id: string } | null;
|
assignee: { id: string } | null;
|
||||||
|
type: string;
|
||||||
|
priority: string;
|
||||||
|
dueAt: Date | null;
|
||||||
|
typeDef?: { name: string } | null;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
|
this.game.emit({
|
||||||
|
organizationId,
|
||||||
|
userId: row.assignee?.id,
|
||||||
|
event: 'TASK_COMPLETED',
|
||||||
|
entityType: 'activity',
|
||||||
|
entityId: row.id,
|
||||||
|
entityTitle: row.title,
|
||||||
|
facts: {
|
||||||
|
activityType: row.type,
|
||||||
|
typeName: row.typeDef?.name ?? null,
|
||||||
|
priority: row.priority,
|
||||||
|
onTime: !row.dueAt || tehranDayKey() <= tehranDayKey(row.dueAt),
|
||||||
|
},
|
||||||
|
});
|
||||||
const ctx = {
|
const ctx = {
|
||||||
organizationId,
|
organizationId,
|
||||||
entityType: 'activity' as const,
|
entityType: 'activity' as const,
|
||||||
@@ -412,7 +882,7 @@ export class ActivitiesService {
|
|||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
) {
|
) {
|
||||||
const found = await this.prisma.activity.findFirst({
|
const found = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId, ...assigneeWhere(actor) },
|
where: { id, organizationId, ...activityAccessWhere(actor) },
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
});
|
});
|
||||||
if (!found) throw new NotFoundException('فعالیت پیدا نشد');
|
if (!found) throw new NotFoundException('فعالیت پیدا نشد');
|
||||||
@@ -456,15 +926,45 @@ export class ActivitiesService {
|
|||||||
}
|
}
|
||||||
if (dealId) {
|
if (dealId) {
|
||||||
const deal = await this.prisma.deal.findFirst({
|
const deal = await this.prisma.deal.findFirst({
|
||||||
where: { id: dealId, organizationId, ...scope },
|
where: { id: dealId, organizationId, ...dealAccessWhere(actor) },
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
});
|
});
|
||||||
if (!deal) throw new BadRequestException('معامله انتخابشده معتبر نیست');
|
if (!deal) throw new BadRequestException('معامله انتخابشده معتبر نیست');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private toDto(row: ActivityRow): ActivityDto {
|
private async notifyParticipants(
|
||||||
|
organizationId: string,
|
||||||
|
row: { id: string; title: string },
|
||||||
|
userIds: string[],
|
||||||
|
) {
|
||||||
|
for (const uid of new Set(userIds)) {
|
||||||
|
await this.notifications.create({
|
||||||
|
organizationId,
|
||||||
|
userId: uid,
|
||||||
|
type: 'activity_assigned',
|
||||||
|
title: 'شما بهعنوان شرکتکننده اضافه شدید',
|
||||||
|
body: row.title,
|
||||||
|
link: `/activities/${row.id}`,
|
||||||
|
entityType: 'activity',
|
||||||
|
entityId: row.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
|
||||||
|
const fields =
|
||||||
|
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
|
||||||
|
? (row.fields as unknown as ActivityFieldValues)
|
||||||
|
: {};
|
||||||
return {
|
return {
|
||||||
|
boardId: this.stages.effectiveBoardId(row, ctx?.stages),
|
||||||
|
stageId: this.stages.effectiveStageId(row, ctx?.stages),
|
||||||
|
typeDef: row.typeDef
|
||||||
|
? this.types.toSummary(row.typeDef)
|
||||||
|
: (ctx?.types?.[row.type] ?? null),
|
||||||
|
fields,
|
||||||
|
participantIds: row.participantIds ?? [],
|
||||||
id: row.id,
|
id: row.id,
|
||||||
type: row.type,
|
type: row.type,
|
||||||
status: row.status,
|
status: row.status,
|
||||||
@@ -476,7 +976,11 @@ export class ActivitiesService {
|
|||||||
reminderAt: row.reminderAt?.toISOString() ?? null,
|
reminderAt: row.reminderAt?.toISOString() ?? null,
|
||||||
reminderNotifyApp: row.reminderNotifyApp,
|
reminderNotifyApp: row.reminderNotifyApp,
|
||||||
reminderNotifySms: row.reminderNotifySms,
|
reminderNotifySms: row.reminderNotifySms,
|
||||||
|
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
|
||||||
completedAt: row.completedAt?.toISOString() ?? null,
|
completedAt: row.completedAt?.toISOString() ?? null,
|
||||||
|
importSource: row.importSource ?? 'manual',
|
||||||
|
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
|
||||||
|
tags: row.tags ?? [],
|
||||||
person: row.person
|
person: row.person
|
||||||
? {
|
? {
|
||||||
id: row.person.id,
|
id: row.person.id,
|
||||||
@@ -485,12 +989,57 @@ export class ActivitiesService {
|
|||||||
: null,
|
: null,
|
||||||
company: row.company,
|
company: row.company,
|
||||||
deal: row.deal,
|
deal: row.deal,
|
||||||
|
lead: row.lead ?? null,
|
||||||
assignee: row.assignee,
|
assignee: row.assignee,
|
||||||
|
assignees: (() => {
|
||||||
|
const list = [...(row.assignees ?? [])];
|
||||||
|
if (row.assignee && !list.some((a) => a.id === row.assignee!.id)) {
|
||||||
|
list.unshift(row.assignee);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
})(),
|
||||||
createdBy: row.createdBy,
|
createdBy: row.createdBy,
|
||||||
createdAt: row.createdAt.toISOString(),
|
createdAt: row.createdAt.toISOString(),
|
||||||
updatedAt: row.updatedAt.toISOString(),
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async normalizeAssigneeIds(
|
||||||
|
organizationId: string,
|
||||||
|
raw?: string[] | null,
|
||||||
|
): Promise<string[]> {
|
||||||
|
const ids = [
|
||||||
|
...new Set((raw ?? []).map((id) => id.trim()).filter(Boolean)),
|
||||||
|
];
|
||||||
|
if (!ids.length) return [];
|
||||||
|
const count = await this.prisma.user.count({
|
||||||
|
where: {
|
||||||
|
id: { in: ids },
|
||||||
|
isActive: true,
|
||||||
|
memberships: { some: { organizationId, isActive: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (count !== ids.length) {
|
||||||
|
throw new BadRequestException('یکی از مسئولان انتخابشده معتبر نیست');
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TYPE_SEARCH_TERMS: Record<ActivityDto['type'], string[]> = {
|
||||||
|
call: ['تماس', 'تلفن', 'call'],
|
||||||
|
meeting: ['جلسه', 'ملاقات', 'meeting'],
|
||||||
|
task: ['وظیفه', 'تسک', 'task'],
|
||||||
|
note: ['پیام', 'یادداشت', 'note'],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** جستجوی «جلسه» یا «تماس» → فیلتر نوع فعالیت */
|
||||||
|
function typesMatching(term: string): ActivityDto['type'][] {
|
||||||
|
const t = term.trim().toLowerCase();
|
||||||
|
if (t.length < 2) return [];
|
||||||
|
return (Object.keys(TYPE_SEARCH_TERMS) as ActivityDto['type'][]).filter((type) =>
|
||||||
|
TYPE_SEARCH_TERMS[type].some((label) => label.includes(t) || t.includes(label)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function emptyToNull(value?: string | null): string | null {
|
function emptyToNull(value?: string | null): string | null {
|
||||||
|
|||||||
@@ -0,0 +1,456 @@
|
|||||||
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
ActivityBoardDto,
|
||||||
|
ActivityStageColor,
|
||||||
|
ActivityStageDto,
|
||||||
|
ActivityStatus,
|
||||||
|
} from '@mento/shared';
|
||||||
|
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' },
|
||||||
|
{ name: 'انجامشده', color: 'green', kind: 'done' },
|
||||||
|
{ name: 'لغو شده', color: 'rose', kind: 'canceled' },
|
||||||
|
];
|
||||||
|
|
||||||
|
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 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,
|
||||||
|
position: i,
|
||||||
|
})),
|
||||||
|
skipDuplicates: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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: STAGE_SELECT,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(organizationId: string, boardId?: string | null): Promise<ActivityStageDto[]> {
|
||||||
|
return (await this.rows(organizationId, boardId)).map((r) => this.toDto(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** اولین مرحلهٔ هر نوع = مقصد فعالیتهای بدون مرحله یا با مرحلهٔ ناهمنوع */
|
||||||
|
defaultsOf(rows: StageRow[]): StageDefaults {
|
||||||
|
const out: StageDefaults = { open: null, done: null, canceled: null };
|
||||||
|
for (const r of rows) {
|
||||||
|
if (!out[r.kind]) out[r.kind] = r.id;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** پیشفرضهای ستون برای همهٔ گروههای محیط */
|
||||||
|
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 برای فعالیتهایی که «مؤثراً» در این مرحله هستند */
|
||||||
|
async whereForStage(
|
||||||
|
organizationId: string,
|
||||||
|
stageId: string,
|
||||||
|
): Promise<Prisma.ActivityWhereInput> {
|
||||||
|
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 {
|
||||||
|
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;
|
||||||
|
boardId?: string | null;
|
||||||
|
stage?: { id: string; kind: ActivityStatus; boardId: string } | null;
|
||||||
|
},
|
||||||
|
ctx?: BoardStageContext,
|
||||||
|
): string | 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: STAGE_SELECT,
|
||||||
|
});
|
||||||
|
if (!row) throw new NotFoundException('مرحله پیدا نشد');
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
organizationId: string,
|
||||||
|
dto: { boardId?: string; name: string; color?: string; kind?: ActivityStatus },
|
||||||
|
): Promise<ActivityStageDto> {
|
||||||
|
const boardId = await this.resolveBoardId(organizationId, dto.boardId);
|
||||||
|
await this.ensureBoardStages(organizationId, boardId);
|
||||||
|
const max = await this.prisma.activityStage.aggregate({
|
||||||
|
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) {
|
||||||
|
throw this.mapError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
dto: { name?: string; color?: string; kind?: ActivityStatus },
|
||||||
|
): Promise<ActivityStageDto> {
|
||||||
|
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(stage);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const row = await this.prisma.$transaction(async (tx) => {
|
||||||
|
if (nextKind !== stage.kind) {
|
||||||
|
// فعالیتها وضعیتشان را نگه میدارند و به اولین مرحلهٔ همنوع خودشان برمیگردند
|
||||||
|
await tx.activity.updateMany({
|
||||||
|
where: { organizationId, stageId: id },
|
||||||
|
data: { stageId: null },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return tx.activityStage.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...(dto.name != null ? { name: this.cleanName(dto.name) } : {}),
|
||||||
|
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
|
||||||
|
kind: nextKind,
|
||||||
|
},
|
||||||
|
select: STAGE_SELECT,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return this.toDto(row);
|
||||||
|
} catch (e) {
|
||||||
|
throw this.mapError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ترتیب ستونهای یک گروه؛ همهٔ شناسهها باید از همان گروه باشند */
|
||||||
|
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, boardId },
|
||||||
|
data: { position },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return this.list(organizationId, boardId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(organizationId: string, id: string): Promise<void> {
|
||||||
|
const stage = await this.get(organizationId, id);
|
||||||
|
await this.assertNotLastOfKind(stage);
|
||||||
|
// onDelete: SetNull → فعالیتها به اولین مرحلهٔ همنوع وضعیتشان در همان گروه منتقل میشوند
|
||||||
|
await this.prisma.activityStage.delete({ where: { id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertNotLastOfKind(stage: StageRow) {
|
||||||
|
const sameKind = await this.prisma.activityStage.count({
|
||||||
|
where: { boardId: stage.boardId, kind: stage.kind },
|
||||||
|
});
|
||||||
|
if (sameKind <= 1) {
|
||||||
|
const label =
|
||||||
|
stage.kind === 'done' ? 'انجامشده' : stage.kind === 'canceled' ? 'لغو شده' : 'باز';
|
||||||
|
throw new BadRequestException(
|
||||||
|
`حداقل یک ستون از نوع «${label}» در هر گروه لازم است؛ اول یک ستون دیگر از همین نوع بسازید`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanName(raw: string): string {
|
||||||
|
const name = raw?.trim() ?? '';
|
||||||
|
if (!name) throw new BadRequestException('نام ستون لازم است');
|
||||||
|
if (name.length > 80) throw new BadRequestException('نام ستون حداکثر ۸۰ کاراکتر است');
|
||||||
|
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)
|
||||||
|
: 'green';
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapError(e: unknown) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||||
|
return new BadRequestException('ستونی با این نام در این گروه وجود دارد');
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapBoardError(e: unknown) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||||
|
return new BadRequestException('گروهی با این نام وجود دارد');
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: StageRow): ActivityStageDto {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
boardId: row.boardId,
|
||||||
|
name: row.name,
|
||||||
|
position: row.position,
|
||||||
|
color: this.cleanColor(row.color),
|
||||||
|
kind: row.kind,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,649 @@
|
|||||||
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
ActivityChecklistItem,
|
||||||
|
ActivityFieldDef,
|
||||||
|
ActivityFieldType,
|
||||||
|
ActivityFieldValue,
|
||||||
|
ActivityFieldValues,
|
||||||
|
ActivityParticipantsValue,
|
||||||
|
ActivityStageColor,
|
||||||
|
ActivityType,
|
||||||
|
ActivityTypeDefDto,
|
||||||
|
ActivityTypeIcon,
|
||||||
|
ActivityTypeSummaryDto,
|
||||||
|
CreateActivityTypeRequest,
|
||||||
|
UpdateActivityTypeRequest,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import {
|
||||||
|
ACTIVITY_FIELD_TYPES,
|
||||||
|
ACTIVITY_FIELD_TYPES_WITH_OPTIONS,
|
||||||
|
ACTIVITY_STAGE_COLORS,
|
||||||
|
ACTIVITY_TYPE_ICONS,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
const BASE_TYPES: ActivityType[] = ['call', 'meeting', 'task', 'note'];
|
||||||
|
const MAX_FIELDS = 30;
|
||||||
|
const MAX_OPTIONS = 50;
|
||||||
|
const MAX_CHECKLIST = 100;
|
||||||
|
const MAX_PARTICIPANTS = 100;
|
||||||
|
|
||||||
|
type Seed = {
|
||||||
|
name: string;
|
||||||
|
baseType: ActivityType;
|
||||||
|
icon: ActivityTypeIcon;
|
||||||
|
color: ActivityStageColor;
|
||||||
|
isSystem?: boolean;
|
||||||
|
fields: ActivityFieldDef[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_TYPES: Seed[] = [
|
||||||
|
{
|
||||||
|
name: 'تماس',
|
||||||
|
baseType: 'call',
|
||||||
|
icon: 'phone',
|
||||||
|
color: 'green',
|
||||||
|
isSystem: true,
|
||||||
|
fields: [
|
||||||
|
{ key: 'call_direction', label: 'جهت تماس', type: 'select', options: ['خروجی', 'ورودی'] },
|
||||||
|
{
|
||||||
|
key: 'call_result',
|
||||||
|
label: 'نتیجه تماس',
|
||||||
|
type: 'select',
|
||||||
|
options: [
|
||||||
|
'پاسخ داد',
|
||||||
|
'پاسخ نداد',
|
||||||
|
'مشغول بود',
|
||||||
|
'خاموش / در دسترس نبود',
|
||||||
|
'شماره اشتباه',
|
||||||
|
'نیاز به پیگیری مجدد',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'جلسه',
|
||||||
|
baseType: 'meeting',
|
||||||
|
icon: 'users',
|
||||||
|
color: 'purple',
|
||||||
|
isSystem: true,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
key: 'meeting_subject',
|
||||||
|
label: 'موضوع جلسه',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'مثلاً: بررسی پیشفاکتور و شرایط پرداخت',
|
||||||
|
},
|
||||||
|
{ key: 'meeting_participants', label: 'شرکتکنندگان', type: 'participants' },
|
||||||
|
{
|
||||||
|
key: 'meeting_location',
|
||||||
|
label: 'محل برگزاری / لینک جلسه',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'آدرس یا لینک جلسهٔ آنلاین',
|
||||||
|
},
|
||||||
|
{ key: 'meeting_minutes', label: 'صورتجلسه', type: 'textarea' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'وظیفه',
|
||||||
|
baseType: 'task',
|
||||||
|
icon: 'check',
|
||||||
|
color: 'orange',
|
||||||
|
isSystem: true,
|
||||||
|
fields: [{ key: 'task_checklist', label: 'لیست کارها', type: 'checklist' }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'پیام',
|
||||||
|
baseType: 'note',
|
||||||
|
icon: 'chat',
|
||||||
|
color: 'blue',
|
||||||
|
isSystem: true,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
key: 'message_channel',
|
||||||
|
label: 'کانال ارسال',
|
||||||
|
type: 'select',
|
||||||
|
options: ['پیامک', 'واتساپ', 'تلگرام', 'ایتا', 'بله', 'ایمیل', 'دایرکت اینستاگرام'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'بازدید حضوری',
|
||||||
|
baseType: 'meeting',
|
||||||
|
icon: 'pin',
|
||||||
|
color: 'rose',
|
||||||
|
fields: [
|
||||||
|
{ key: 'visit_address', label: 'آدرس محل بازدید', type: 'text' },
|
||||||
|
{ key: 'visit_participants', label: 'همراهان بازدید', type: 'participants' },
|
||||||
|
{ key: 'visit_result', label: 'نتیجهٔ بازدید', type: 'textarea' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'ارائه / دمو محصول',
|
||||||
|
baseType: 'meeting',
|
||||||
|
icon: 'star',
|
||||||
|
color: 'purple',
|
||||||
|
fields: [
|
||||||
|
{ key: 'demo_product', label: 'محصول / خدمت', type: 'text' },
|
||||||
|
{ key: 'demo_participants', label: 'شرکتکنندگان', type: 'participants' },
|
||||||
|
{ key: 'demo_link', label: 'لینک جلسه', type: 'url' },
|
||||||
|
{
|
||||||
|
key: 'demo_result',
|
||||||
|
label: 'نتیجهٔ دمو',
|
||||||
|
type: 'select',
|
||||||
|
options: ['علاقهمند', 'نیاز به بررسی بیشتر', 'درخواست پیشفاکتور', 'عدم علاقه'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'پیگیری',
|
||||||
|
baseType: 'call',
|
||||||
|
icon: 'bell',
|
||||||
|
color: 'orange',
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
key: 'followup_reason',
|
||||||
|
label: 'دلیل پیگیری',
|
||||||
|
type: 'select',
|
||||||
|
options: ['پیشفاکتور', 'پرداخت', 'ارسال کالا', 'پشتیبانی', 'تمدید قرارداد', 'سایر'],
|
||||||
|
},
|
||||||
|
{ key: 'followup_result', label: 'نتیجهٔ پیگیری', type: 'textarea' },
|
||||||
|
{ key: 'followup_next', label: 'تاریخ پیگیری بعدی', type: 'date' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'ایمیل',
|
||||||
|
baseType: 'note',
|
||||||
|
icon: 'mail',
|
||||||
|
color: 'slate',
|
||||||
|
fields: [
|
||||||
|
{ key: 'email_subject', label: 'موضوع ایمیل', type: 'text' },
|
||||||
|
{ key: 'email_to', label: 'گیرنده', type: 'text', placeholder: 'example@domain.com' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export type TypeRow = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
baseType: ActivityType;
|
||||||
|
icon: string;
|
||||||
|
color: string;
|
||||||
|
fields: Prisma.JsonValue;
|
||||||
|
position: number;
|
||||||
|
isActive: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** نوع اصلی هر baseType — مقصد فعالیتهای بدون typeDefId */
|
||||||
|
export type SystemTypes = Record<ActivityType, ActivityTypeSummaryDto | null>;
|
||||||
|
|
||||||
|
export type ResolvedType = {
|
||||||
|
/** مقداری که در Activity.typeDefId ذخیره میشود (نوع اصلی → null) */
|
||||||
|
typeDefId: string | null;
|
||||||
|
baseType: ActivityType;
|
||||||
|
fields: ActivityFieldDef[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const select = {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
baseType: true,
|
||||||
|
icon: true,
|
||||||
|
color: true,
|
||||||
|
fields: true,
|
||||||
|
position: true,
|
||||||
|
isActive: true,
|
||||||
|
isSystem: true,
|
||||||
|
} satisfies Prisma.ActivityTypeDefSelect;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ActivityTypesService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async ensureDefaults(organizationId: string): Promise<void> {
|
||||||
|
const count = await this.prisma.activityTypeDef.count({ where: { organizationId } });
|
||||||
|
if (count > 0) return;
|
||||||
|
await this.prisma.activityTypeDef.createMany({
|
||||||
|
data: DEFAULT_TYPES.map((t, i) => ({
|
||||||
|
organizationId,
|
||||||
|
name: t.name,
|
||||||
|
baseType: t.baseType,
|
||||||
|
icon: t.icon,
|
||||||
|
color: t.color,
|
||||||
|
isSystem: Boolean(t.isSystem),
|
||||||
|
fields: t.fields as unknown as Prisma.InputJsonValue,
|
||||||
|
position: i,
|
||||||
|
})),
|
||||||
|
skipDuplicates: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async rows(organizationId: string): Promise<TypeRow[]> {
|
||||||
|
await this.ensureDefaults(organizationId);
|
||||||
|
return this.prisma.activityTypeDef.findMany({
|
||||||
|
where: { organizationId },
|
||||||
|
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
select,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(organizationId: string): Promise<ActivityTypeDefDto[]> {
|
||||||
|
return (await this.rows(organizationId)).map((r) => this.toDto(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
systemOf(rows: TypeRow[]): SystemTypes {
|
||||||
|
const out: SystemTypes = { call: null, meeting: null, task: null, note: null };
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.isSystem && !out[r.baseType]) out[r.baseType] = this.toSummary(r);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async system(organizationId: string): Promise<SystemTypes> {
|
||||||
|
return this.systemOf(await this.rows(organizationId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** فیلتر Prisma برای فعالیتهایی که «مؤثراً» از این نوع هستند */
|
||||||
|
whereForType(rows: TypeRow[], typeDefId: string): Prisma.ActivityWhereInput {
|
||||||
|
const def = rows.find((r) => r.id === typeDefId);
|
||||||
|
if (!def) return { id: '__none__' };
|
||||||
|
if (!def.isSystem) return { typeDefId: def.id };
|
||||||
|
return { OR: [{ typeDefId: def.id }, { typeDefId: null, type: def.baseType }] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** جستجوی نام نوع → شرطهای OR */
|
||||||
|
searchByName(rows: TypeRow[], term: string): Prisma.ActivityWhereInput[] {
|
||||||
|
const t = term.trim();
|
||||||
|
if (t.length < 2) return [];
|
||||||
|
return rows
|
||||||
|
.filter((r) => r.name.includes(t))
|
||||||
|
.map((r) => this.whereForType(rows, r.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* نوع مؤثر برای ذخیره: typeDefId صریح، یا نوع اصلیِ type.
|
||||||
|
* نوع اصلی با typeDefId=null ذخیره میشود تا با دادههای قدیمی یکسان باشد.
|
||||||
|
*/
|
||||||
|
async resolve(
|
||||||
|
organizationId: string,
|
||||||
|
input: { typeDefId?: string | null; type?: ActivityType | null },
|
||||||
|
): Promise<ResolvedType> {
|
||||||
|
const rows = await this.rows(organizationId);
|
||||||
|
const requested = input.typeDefId?.trim();
|
||||||
|
if (requested) {
|
||||||
|
const def = rows.find((r) => r.id === requested);
|
||||||
|
if (!def) throw new BadRequestException('نوع فعالیت انتخابشده معتبر نیست');
|
||||||
|
return {
|
||||||
|
typeDefId: def.isSystem ? null : def.id,
|
||||||
|
baseType: def.baseType,
|
||||||
|
fields: this.parseFields(def.fields),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const baseType = input.type && BASE_TYPES.includes(input.type) ? input.type : 'task';
|
||||||
|
const sys = rows.find((r) => r.isSystem && r.baseType === baseType);
|
||||||
|
return { typeDefId: null, baseType, fields: sys ? this.parseFields(sys.fields) : [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* پاکسازی مقادیر بر اساس تعریف فیلدها؛ فقط کلیدهای همین نوع نگه داشته میشوند.
|
||||||
|
* participantIds = کاربران معتبر همهٔ فیلدهای شرکتکنندگان.
|
||||||
|
*/
|
||||||
|
async sanitizeValues(
|
||||||
|
organizationId: string,
|
||||||
|
defs: ActivityFieldDef[],
|
||||||
|
raw: unknown,
|
||||||
|
): Promise<{ fields: ActivityFieldValues; participantIds: string[] }> {
|
||||||
|
const input =
|
||||||
|
raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
|
||||||
|
const out: ActivityFieldValues = {};
|
||||||
|
const participantFields: Array<{ key: string; value: ActivityParticipantsValue }> = [];
|
||||||
|
|
||||||
|
for (const def of defs) {
|
||||||
|
const value = this.cleanValue(def, input[def.key]);
|
||||||
|
if (value === null) {
|
||||||
|
if (def.required && def.type !== 'checkbox') {
|
||||||
|
throw new BadRequestException(`فیلد «${def.label}» را تکمیل کنید`);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (def.type === 'participants') {
|
||||||
|
participantFields.push({ key: def.key, value: value as ActivityParticipantsValue });
|
||||||
|
}
|
||||||
|
out[def.key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userIds = [...new Set(participantFields.flatMap((p) => p.value.userIds))];
|
||||||
|
const personIds = [...new Set(participantFields.flatMap((p) => p.value.people.map((x) => x.id)))];
|
||||||
|
const [validUsers, validPeople] = await Promise.all([
|
||||||
|
userIds.length
|
||||||
|
? this.prisma.user.findMany({
|
||||||
|
where: { id: { in: userIds }, memberships: { some: { organizationId } } },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
: Promise.resolve([]),
|
||||||
|
personIds.length
|
||||||
|
? this.prisma.person.findMany({
|
||||||
|
where: { id: { in: personIds }, organizationId },
|
||||||
|
select: { id: true, firstName: true, lastName: true },
|
||||||
|
})
|
||||||
|
: Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
const userSet = new Set(validUsers.map((u) => u.id));
|
||||||
|
const personNames = new Map(
|
||||||
|
validPeople.map((p) => [p.id, `${p.firstName} ${p.lastName}`.trim()]),
|
||||||
|
);
|
||||||
|
for (const p of participantFields) {
|
||||||
|
const next: ActivityParticipantsValue = {
|
||||||
|
userIds: p.value.userIds.filter((id) => userSet.has(id)),
|
||||||
|
people: p.value.people
|
||||||
|
.filter((x) => personNames.has(x.id))
|
||||||
|
.map((x) => ({ id: x.id, name: personNames.get(x.id) || x.name })),
|
||||||
|
guests: p.value.guests,
|
||||||
|
};
|
||||||
|
const def = defs.find((d) => d.key === p.key)!;
|
||||||
|
if (!next.userIds.length && !next.people.length && !next.guests.length) {
|
||||||
|
if (def.required) throw new BadRequestException(`فیلد «${def.label}» را تکمیل کنید`);
|
||||||
|
delete out[p.key];
|
||||||
|
} else {
|
||||||
|
out[p.key] = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const participantIds = [
|
||||||
|
...new Set(
|
||||||
|
Object.values(out)
|
||||||
|
.filter((v): v is ActivityParticipantsValue => isParticipants(v))
|
||||||
|
.flatMap((v) => v.userIds),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return { fields: out, participantIds };
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
organizationId: string,
|
||||||
|
dto: CreateActivityTypeRequest,
|
||||||
|
): Promise<ActivityTypeDefDto> {
|
||||||
|
await this.ensureDefaults(organizationId);
|
||||||
|
const max = await this.prisma.activityTypeDef.aggregate({
|
||||||
|
where: { organizationId },
|
||||||
|
_max: { position: true },
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const row = await this.prisma.activityTypeDef.create({
|
||||||
|
data: {
|
||||||
|
organizationId,
|
||||||
|
name: this.cleanName(dto.name),
|
||||||
|
baseType: this.cleanBase(dto.baseType),
|
||||||
|
icon: this.cleanIcon(dto.icon),
|
||||||
|
color: this.cleanColor(dto.color),
|
||||||
|
fields: this.cleanFieldDefs(dto.fields ?? []) as unknown as Prisma.InputJsonValue,
|
||||||
|
position: (max._max.position ?? -1) + 1,
|
||||||
|
},
|
||||||
|
select,
|
||||||
|
});
|
||||||
|
return this.toDto(row);
|
||||||
|
} catch (e) {
|
||||||
|
throw this.mapError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
dto: UpdateActivityTypeRequest,
|
||||||
|
): Promise<ActivityTypeDefDto> {
|
||||||
|
const current = await this.get(organizationId, id);
|
||||||
|
if (current.isSystem && dto.baseType && dto.baseType !== current.baseType) {
|
||||||
|
throw new BadRequestException('نوع پایهٔ انواع اصلی قابل تغییر نیست');
|
||||||
|
}
|
||||||
|
if (current.isSystem && dto.isActive === false) {
|
||||||
|
throw new BadRequestException('انواع اصلی را نمیتوان غیرفعال کرد');
|
||||||
|
}
|
||||||
|
const nextBase = dto.baseType ? this.cleanBase(dto.baseType) : current.baseType;
|
||||||
|
try {
|
||||||
|
const row = await this.prisma.$transaction(async (tx) => {
|
||||||
|
if (nextBase !== current.baseType) {
|
||||||
|
await tx.activity.updateMany({
|
||||||
|
where: { organizationId, typeDefId: id },
|
||||||
|
data: { type: nextBase },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return tx.activityTypeDef.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...(dto.name != null ? { name: this.cleanName(dto.name) } : {}),
|
||||||
|
...(dto.icon != null ? { icon: this.cleanIcon(dto.icon) } : {}),
|
||||||
|
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
|
||||||
|
...(dto.fields != null
|
||||||
|
? { fields: this.cleanFieldDefs(dto.fields) as unknown as Prisma.InputJsonValue }
|
||||||
|
: {}),
|
||||||
|
...(dto.isActive != null ? { isActive: dto.isActive } : {}),
|
||||||
|
baseType: nextBase,
|
||||||
|
},
|
||||||
|
select,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return this.toDto(row);
|
||||||
|
} catch (e) {
|
||||||
|
throw this.mapError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async reorder(organizationId: string, typeIds: string[]): Promise<ActivityTypeDefDto[]> {
|
||||||
|
await this.prisma.$transaction(
|
||||||
|
typeIds.map((id, position) =>
|
||||||
|
this.prisma.activityTypeDef.updateMany({
|
||||||
|
where: { id, organizationId },
|
||||||
|
data: { position },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return this.list(organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(organizationId: string, id: string): Promise<void> {
|
||||||
|
const def = await this.get(organizationId, id);
|
||||||
|
if (def.isSystem) throw new BadRequestException('انواع اصلی قابل حذف نیستند');
|
||||||
|
// onDelete: SetNull → فعالیتها به نوع اصلیِ نوع پایهٔ خود برمیگردند
|
||||||
|
await this.prisma.activityTypeDef.delete({ where: { id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
toSummary(row: Pick<TypeRow, 'id' | 'name' | 'icon' | 'color'>): ActivityTypeSummaryDto {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
icon: this.cleanIcon(row.icon),
|
||||||
|
color: this.cleanColor(row.color),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
parseFields(raw: Prisma.JsonValue): ActivityFieldDef[] {
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
return raw.filter(
|
||||||
|
(f): f is ActivityFieldDef & Prisma.JsonObject =>
|
||||||
|
Boolean(f) && typeof f === 'object' && !Array.isArray(f) && typeof (f as { key?: unknown }).key === 'string',
|
||||||
|
) as ActivityFieldDef[];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async get(organizationId: string, id: string): Promise<TypeRow> {
|
||||||
|
const row = await this.prisma.activityTypeDef.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
select,
|
||||||
|
});
|
||||||
|
if (!row) throw new NotFoundException('نوع فعالیت پیدا نشد');
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanValue(def: ActivityFieldDef, raw: unknown): ActivityFieldValue {
|
||||||
|
switch (def.type) {
|
||||||
|
case 'text':
|
||||||
|
return cleanText(raw, 500);
|
||||||
|
case 'textarea':
|
||||||
|
return cleanText(raw, 5000);
|
||||||
|
case 'url':
|
||||||
|
return cleanText(raw, 1000);
|
||||||
|
case 'number': {
|
||||||
|
if (raw === '' || raw == null) return null;
|
||||||
|
const n = typeof raw === 'number' ? raw : Number(String(raw).replace(/,/g, ''));
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
case 'date': {
|
||||||
|
const s = cleanText(raw, 40);
|
||||||
|
return s && /^\d{4}-\d{2}-\d{2}/.test(s) && !Number.isNaN(new Date(s).getTime())
|
||||||
|
? s
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
case 'select': {
|
||||||
|
const s = cleanText(raw, 200);
|
||||||
|
return s && (def.options ?? []).includes(s) ? s : null;
|
||||||
|
}
|
||||||
|
case 'multiselect': {
|
||||||
|
if (!Array.isArray(raw)) return null;
|
||||||
|
const opts = new Set(def.options ?? []);
|
||||||
|
const list = [...new Set(raw.filter((v): v is string => typeof v === 'string' && opts.has(v)))];
|
||||||
|
return list.length ? list : null;
|
||||||
|
}
|
||||||
|
case 'checkbox':
|
||||||
|
return raw === true ? true : raw === false ? false : null;
|
||||||
|
case 'checklist': {
|
||||||
|
if (!Array.isArray(raw)) return null;
|
||||||
|
const items: ActivityChecklistItem[] = [];
|
||||||
|
for (const it of raw.slice(0, MAX_CHECKLIST)) {
|
||||||
|
if (!it || typeof it !== 'object') continue;
|
||||||
|
const o = it as Record<string, unknown>;
|
||||||
|
const text = cleanText(o.text, 300);
|
||||||
|
if (!text) continue;
|
||||||
|
const id = typeof o.id === 'string' && o.id.trim() ? o.id.trim().slice(0, 64) : randomUUID();
|
||||||
|
items.push({ id, text, done: o.done === true });
|
||||||
|
}
|
||||||
|
return items.length ? items : null;
|
||||||
|
}
|
||||||
|
case 'participants': {
|
||||||
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
||||||
|
const o = raw as Record<string, unknown>;
|
||||||
|
const userIds = Array.isArray(o.userIds)
|
||||||
|
? [...new Set(o.userIds.filter((v): v is string => typeof v === 'string' && Boolean(v.trim())))]
|
||||||
|
: [];
|
||||||
|
const people = Array.isArray(o.people)
|
||||||
|
? o.people
|
||||||
|
.filter(
|
||||||
|
(p): p is { id: string; name?: unknown } =>
|
||||||
|
Boolean(p) && typeof p === 'object' && typeof (p as { id?: unknown }).id === 'string',
|
||||||
|
)
|
||||||
|
.map((p) => ({ id: p.id, name: cleanText(p.name, 200) ?? '' }))
|
||||||
|
: [];
|
||||||
|
const guests = Array.isArray(o.guests)
|
||||||
|
? [
|
||||||
|
...new Set(
|
||||||
|
o.guests
|
||||||
|
.map((g) => cleanText(g, 120))
|
||||||
|
.filter((g): g is string => Boolean(g)),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
if (!userIds.length && !people.length && !guests.length) return null;
|
||||||
|
return {
|
||||||
|
userIds: userIds.slice(0, MAX_PARTICIPANTS),
|
||||||
|
people: people.slice(0, MAX_PARTICIPANTS),
|
||||||
|
guests: guests.slice(0, MAX_PARTICIPANTS),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanFieldDefs(raw: ActivityFieldDef[]): ActivityFieldDef[] {
|
||||||
|
if (!Array.isArray(raw)) throw new BadRequestException('تعریف فیلدها نامعتبر است');
|
||||||
|
if (raw.length > MAX_FIELDS) {
|
||||||
|
throw new BadRequestException(`حداکثر ${MAX_FIELDS} فیلد برای هر نوع مجاز است`);
|
||||||
|
}
|
||||||
|
const keys = new Set<string>();
|
||||||
|
return raw.map((f, i) => {
|
||||||
|
const label = typeof f?.label === 'string' ? f.label.trim() : '';
|
||||||
|
if (!label) throw new BadRequestException(`عنوان فیلد ${i + 1} لازم است`);
|
||||||
|
if (label.length > 80) throw new BadRequestException('عنوان فیلد حداکثر ۸۰ کاراکتر است');
|
||||||
|
const type = ACTIVITY_FIELD_TYPES.includes(f.type as ActivityFieldType)
|
||||||
|
? (f.type as ActivityFieldType)
|
||||||
|
: null;
|
||||||
|
if (!type) throw new BadRequestException(`نوع فیلد «${label}» معتبر نیست`);
|
||||||
|
let key = typeof f.key === 'string' ? f.key.trim().toLowerCase() : '';
|
||||||
|
if (!/^[a-z][a-z0-9_]{0,39}$/.test(key)) key = `f_${randomUUID().slice(0, 8)}`;
|
||||||
|
if (keys.has(key)) throw new BadRequestException(`کلید فیلد «${label}» تکراری است`);
|
||||||
|
keys.add(key);
|
||||||
|
const def: ActivityFieldDef = { key, label, type };
|
||||||
|
if (ACTIVITY_FIELD_TYPES_WITH_OPTIONS.includes(type)) {
|
||||||
|
const options = [
|
||||||
|
...new Set(
|
||||||
|
(Array.isArray(f.options) ? f.options : [])
|
||||||
|
.map((o) => (typeof o === 'string' ? o.trim() : ''))
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((o) => o.slice(0, 200)),
|
||||||
|
),
|
||||||
|
].slice(0, MAX_OPTIONS);
|
||||||
|
if (!options.length) {
|
||||||
|
throw new BadRequestException(`برای فیلد «${label}» حداقل یک گزینه تعریف کنید`);
|
||||||
|
}
|
||||||
|
def.options = options;
|
||||||
|
}
|
||||||
|
if (f.required) def.required = true;
|
||||||
|
const placeholder = typeof f.placeholder === 'string' ? f.placeholder.trim().slice(0, 200) : '';
|
||||||
|
if (placeholder) def.placeholder = placeholder;
|
||||||
|
return def;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanName(raw: string): string {
|
||||||
|
const name = raw?.trim() ?? '';
|
||||||
|
if (!name) throw new BadRequestException('نام نوع فعالیت لازم است');
|
||||||
|
if (name.length > 60) throw new BadRequestException('نام نوع فعالیت حداکثر ۶۰ کاراکتر است');
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanBase(raw?: ActivityType): ActivityType {
|
||||||
|
return raw && BASE_TYPES.includes(raw) ? raw : 'task';
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanIcon(raw?: string): ActivityTypeIcon {
|
||||||
|
return (ACTIVITY_TYPE_ICONS as readonly string[]).includes(raw ?? '')
|
||||||
|
? (raw as ActivityTypeIcon)
|
||||||
|
: 'check';
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanColor(raw?: string): ActivityStageColor {
|
||||||
|
return ACTIVITY_STAGE_COLORS.includes(raw as ActivityStageColor)
|
||||||
|
? (raw as ActivityStageColor)
|
||||||
|
: 'green';
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapError(e: unknown) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||||
|
return new BadRequestException('نوع فعالیتی با این نام وجود دارد');
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: TypeRow): ActivityTypeDefDto {
|
||||||
|
return {
|
||||||
|
...this.toSummary(row),
|
||||||
|
baseType: row.baseType,
|
||||||
|
fields: this.parseFields(row.fields),
|
||||||
|
position: row.position,
|
||||||
|
isActive: row.isActive,
|
||||||
|
isSystem: row.isSystem,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanText(raw: unknown, max: number): string | null {
|
||||||
|
if (typeof raw !== 'string' && typeof raw !== 'number') return null;
|
||||||
|
const s = String(raw).trim();
|
||||||
|
return s ? s.slice(0, max) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isParticipants(v: unknown): v is ActivityParticipantsValue {
|
||||||
|
return Boolean(v) && typeof v === 'object' && !Array.isArray(v) && Array.isArray((v as ActivityParticipantsValue).userIds);
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
|
Allow,
|
||||||
|
IsArray,
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
IsDateString,
|
IsDateString,
|
||||||
IsIn,
|
IsIn,
|
||||||
IsInt,
|
IsInt,
|
||||||
|
IsObject,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
Max,
|
Max,
|
||||||
@@ -12,6 +15,29 @@ import {
|
|||||||
MinLength,
|
MinLength,
|
||||||
ValidateIf,
|
ValidateIf,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
import type { ActivityFieldDef, ActivityFieldValues, ActivityTypeIcon } from '@mento/shared';
|
||||||
|
import { ACTIVITY_TYPE_ICONS } from '@mento/shared';
|
||||||
|
|
||||||
|
/** تکههای JSON از ایمپورت مرورگرگرا */
|
||||||
|
export class ImportActivityRowsDto {
|
||||||
|
@IsArray()
|
||||||
|
@Allow()
|
||||||
|
rows!: Array<Record<string, string>>;
|
||||||
|
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
offset!: number;
|
||||||
|
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
total!: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
sessionId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
const ACTIVITY_TYPES = ['call', 'meeting', 'task', 'note'] as const;
|
const ACTIVITY_TYPES = ['call', 'meeting', 'task', 'note'] as const;
|
||||||
const ACTIVITY_STATUSES = ['open', 'done', 'canceled'] as const;
|
const ACTIVITY_STATUSES = ['open', 'done', 'canceled'] as const;
|
||||||
@@ -27,6 +53,37 @@ export class ListActivitiesQueryDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
q?: string;
|
q?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['mine', 'team'])
|
||||||
|
desk?: 'mine' | 'team';
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_TYPES)
|
||||||
|
type?: (typeof ACTIVITY_TYPES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_STATUSES)
|
||||||
|
status?: (typeof ACTIVITY_STATUSES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
assigneeId?: string;
|
||||||
|
|
||||||
|
/** نوع فعالیت (تعریفشده در سازمان) */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
typeDefId?: string;
|
||||||
|
|
||||||
|
/** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
stageId?: string;
|
||||||
|
|
||||||
|
/** گروه فعالیت؛ خالی = همهٔ گروهها (در شمارش ستونها = گروه پیشفرض) */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
boardId?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
personId?: string;
|
personId?: string;
|
||||||
@@ -39,6 +96,10 @@ export class ListActivitiesQueryDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
dealId?: string;
|
dealId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
leadId?: string;
|
||||||
|
|
||||||
/** Inclusive start (ISO). When set with/without filter, restricts dueAt. */
|
/** Inclusive start (ISO). When set with/without filter, restricts dueAt. */
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsDateString()
|
@IsDateString()
|
||||||
@@ -63,16 +124,165 @@ export class ListActivitiesQueryDto {
|
|||||||
limit?: number = 50;
|
limit?: number = 50;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(STAGE_COLORS)
|
||||||
|
color?: (typeof STAGE_COLORS)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_STATUSES)
|
||||||
|
kind?: (typeof ACTIVITY_STATUSES)[number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateActivityStageDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(80)
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(STAGE_COLORS)
|
||||||
|
color?: (typeof STAGE_COLORS)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_STATUSES)
|
||||||
|
kind?: (typeof ACTIVITY_STATUSES)[number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReorderActivityStagesDto {
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
stageIds!: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MoveActivityStageDto {
|
||||||
|
@IsString()
|
||||||
|
stageId!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** محتوای fields در سرویس بر اساس تعریف نوع اعتبارسنجی میشود */
|
||||||
|
export class CreateActivityTypeDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(60)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_TYPES)
|
||||||
|
baseType?: (typeof ACTIVITY_TYPES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_TYPE_ICONS)
|
||||||
|
icon?: ActivityTypeIcon;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(STAGE_COLORS)
|
||||||
|
color?: (typeof STAGE_COLORS)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@Allow()
|
||||||
|
fields?: ActivityFieldDef[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateActivityTypeDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(60)
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_TYPES)
|
||||||
|
baseType?: (typeof ACTIVITY_TYPES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_TYPE_ICONS)
|
||||||
|
icon?: ActivityTypeIcon;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(STAGE_COLORS)
|
||||||
|
color?: (typeof STAGE_COLORS)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@Allow()
|
||||||
|
fields?: ActivityFieldDef[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReorderActivityTypesDto {
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
typeIds!: string[];
|
||||||
|
}
|
||||||
|
|
||||||
export class CreateActivityDto {
|
export class CreateActivityDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
@MaxLength(200)
|
@MaxLength(200)
|
||||||
title!: string;
|
title!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
|
@IsString()
|
||||||
|
boardId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
|
@IsString()
|
||||||
|
stageId?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(ACTIVITY_TYPES)
|
@IsIn(ACTIVITY_TYPES)
|
||||||
type?: (typeof ACTIVITY_TYPES)[number];
|
type?: (typeof ACTIVITY_TYPES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
|
@IsString()
|
||||||
|
typeDefId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
fields?: ActivityFieldValues;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(ACTIVITY_PRIORITIES)
|
@IsIn(ACTIVITY_PRIORITIES)
|
||||||
priority?: (typeof ACTIVITY_PRIORITIES)[number];
|
priority?: (typeof ACTIVITY_PRIORITIES)[number];
|
||||||
@@ -107,6 +317,11 @@ export class CreateActivityDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
reminderNotifySms?: boolean;
|
reminderNotifySms?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
tags?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((_, v) => v !== '' && v != null)
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -126,6 +341,11 @@ export class CreateActivityDto {
|
|||||||
@ValidateIf((_, v) => v !== '' && v != null)
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
@IsString()
|
@IsString()
|
||||||
assigneeId?: string | null;
|
assigneeId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
assigneeIds?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateActivityDto {
|
export class UpdateActivityDto {
|
||||||
@@ -135,10 +355,25 @@ export class UpdateActivityDto {
|
|||||||
@MaxLength(200)
|
@MaxLength(200)
|
||||||
title?: string;
|
title?: string;
|
||||||
|
|
||||||
|
/** null/خالی = گروه پیشفرض */
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
|
@IsString()
|
||||||
|
boardId?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(ACTIVITY_TYPES)
|
@IsIn(ACTIVITY_TYPES)
|
||||||
type?: (typeof ACTIVITY_TYPES)[number];
|
type?: (typeof ACTIVITY_TYPES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
|
@IsString()
|
||||||
|
typeDefId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
fields?: ActivityFieldValues;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(ACTIVITY_STATUSES)
|
@IsIn(ACTIVITY_STATUSES)
|
||||||
status?: (typeof ACTIVITY_STATUSES)[number];
|
status?: (typeof ACTIVITY_STATUSES)[number];
|
||||||
@@ -177,6 +412,11 @@ export class UpdateActivityDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
reminderNotifySms?: boolean;
|
reminderNotifySms?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
tags?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((_, v) => v !== '' && v != null)
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -196,4 +436,9 @@ export class UpdateActivityDto {
|
|||||||
@ValidateIf((_, v) => v !== '' && v != null)
|
@ValidateIf((_, v) => v !== '' && v != null)
|
||||||
@IsString()
|
@IsString()
|
||||||
assigneeId?: string | null;
|
assigneeId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
assigneeIds?: string[];
|
||||||
}
|
}
|
||||||
|
|||||||
+1037
-24
File diff suppressed because it is too large
Load Diff
@@ -1,80 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
Injectable,
|
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
|
|
||||||
const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AiSttService {
|
|
||||||
constructor(private readonly config: ConfigService) {}
|
|
||||||
|
|
||||||
isEnabled(): boolean {
|
|
||||||
return (
|
|
||||||
this.config.get<string>('STT_ENABLED') === 'true' &&
|
|
||||||
Boolean(this.sttUrl())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async transcribe(file: Express.Multer.File | undefined) {
|
|
||||||
if (!this.isEnabled()) {
|
|
||||||
throw new ServiceUnavailableException('تبدیل صوت به متن فعال نیست');
|
|
||||||
}
|
|
||||||
if (!file?.buffer?.length) {
|
|
||||||
throw new BadRequestException('فایل صوتی ارسال نشده است');
|
|
||||||
}
|
|
||||||
if (file.size > MAX_AUDIO_BYTES) {
|
|
||||||
throw new BadRequestException('حجم فایل صوتی بیش از حد مجاز است');
|
|
||||||
}
|
|
||||||
|
|
||||||
const form = new FormData();
|
|
||||||
form.append(
|
|
||||||
'audio',
|
|
||||||
new Blob([new Uint8Array(file.buffer)], {
|
|
||||||
type: file.mimetype || 'audio/wav',
|
|
||||||
}),
|
|
||||||
file.originalname || 'audio.wav',
|
|
||||||
);
|
|
||||||
|
|
||||||
const timeoutMs = Number(this.config.get<string>('STT_TIMEOUT_MS') || 60000);
|
|
||||||
const headers: Record<string, string> = {};
|
|
||||||
const token = this.config.get<string>('STT_INTERNAL_TOKEN')?.trim();
|
|
||||||
if (token) headers['X-STT-Token'] = token;
|
|
||||||
|
|
||||||
let res: Response;
|
|
||||||
try {
|
|
||||||
res = await fetch(`${this.sttUrl()}/transcribe`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers,
|
|
||||||
body: form,
|
|
||||||
signal: AbortSignal.timeout(timeoutMs),
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
throw new ServiceUnavailableException(
|
|
||||||
'سرویس تبدیل صوت در دسترس نیست. Pipecat STT را اجرا کنید.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = (await res.json().catch(() => ({}))) as {
|
|
||||||
text?: string;
|
|
||||||
detail?: string | Array<{ msg?: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const detail = Array.isArray(payload.detail)
|
|
||||||
? payload.detail.map((item) => item.msg).filter(Boolean).join('، ')
|
|
||||||
: payload.detail;
|
|
||||||
throw new ServiceUnavailableException(
|
|
||||||
detail || 'تبدیل صوت به متن ناموفق بود',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { text: (payload.text ?? '').trim() };
|
|
||||||
}
|
|
||||||
|
|
||||||
private sttUrl(): string {
|
|
||||||
return (this.config.get<string>('STT_URL') ?? '').trim().replace(/\/$/, '');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +1,10 @@
|
|||||||
import {
|
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
UploadedFile,
|
|
||||||
UseGuards,
|
|
||||||
UseInterceptors,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
|
||||||
import { memoryStorage } from 'multer';
|
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import type { Actor } from '../common/record-scope';
|
import type { Actor } from '../common/record-scope';
|
||||||
import { AiAskService } from './ai-ask.service';
|
import { AiAskService } from './ai-ask.service';
|
||||||
import { AskMentoDto } from './dto';
|
import { AskMentoDto, VoiceCommandDto } from './dto';
|
||||||
import { AiService } from './ai.service';
|
import { AiService } from './ai.service';
|
||||||
import { AiSttService } from './ai-stt.service';
|
|
||||||
|
|
||||||
@Controller('ai')
|
@Controller('ai')
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@@ -24,28 +12,21 @@ export class AiController {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly ai: AiService,
|
private readonly ai: AiService,
|
||||||
private readonly ask: AiAskService,
|
private readonly ask: AiAskService,
|
||||||
private readonly stt: AiSttService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get('status')
|
@Get('status')
|
||||||
status() {
|
status() {
|
||||||
return { enabled: this.ai.isEnabled(), stt: this.stt.isEnabled() };
|
return { enabled: this.ai.isEnabled() };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('transcribe')
|
@Post('voice-command')
|
||||||
@UseInterceptors(
|
voiceCommand(@CurrentUser() user: Actor, @Body() dto: VoiceCommandDto) {
|
||||||
FileInterceptor('audio', {
|
return this.ask.parseVoiceCommand(user, dto.text);
|
||||||
storage: memoryStorage(),
|
|
||||||
limits: { fileSize: 8 * 1024 * 1024 },
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
transcribe(@UploadedFile() file: Express.Multer.File) {
|
|
||||||
return this.stt.transcribe(file);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('ask')
|
@Post('ask')
|
||||||
askMento(@CurrentUser() user: Actor, @Body() dto: AskMentoDto) {
|
askMento(@CurrentUser() user: Actor, @Body() dto: AskMentoDto) {
|
||||||
return this.ask.ask(user, dto.question, dto.personId);
|
return this.ask.ask(user, dto.question, dto.personId, dto.chatContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('people/:personId/summary')
|
@Get('people/:personId/summary')
|
||||||
|
|||||||
@@ -2,12 +2,11 @@ import { Global, Module } from '@nestjs/common';
|
|||||||
import { AiAskService } from './ai-ask.service';
|
import { AiAskService } from './ai-ask.service';
|
||||||
import { AiController } from './ai.controller';
|
import { AiController } from './ai.controller';
|
||||||
import { AiService } from './ai.service';
|
import { AiService } from './ai.service';
|
||||||
import { AiSttService } from './ai-stt.service';
|
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [AiController],
|
controllers: [AiController],
|
||||||
providers: [AiService, AiAskService, AiSttService],
|
providers: [AiService, AiAskService],
|
||||||
exports: [AiService, AiSttService],
|
exports: [AiService],
|
||||||
})
|
})
|
||||||
export class AiModule {}
|
export class AiModule {}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { rewriteGregorianDates } from '../common/jalali';
|
||||||
|
|
||||||
export type NoteAiExtract = {
|
export type NoteAiExtract = {
|
||||||
nextAction: {
|
nextAction: {
|
||||||
@@ -44,6 +45,7 @@ Rules:
|
|||||||
- dueAt: ISO 8601 date-time if a deadline is mentioned; otherwise null.
|
- dueAt: ISO 8601 date-time if a deadline is mentioned; otherwise null.
|
||||||
- memoryItems: durable facts about the customer (preferences, budget, decisions, family, objections) — NOT tasks.
|
- memoryItems: durable facts about the customer (preferences, budget, decisions, family, objections) — NOT tasks.
|
||||||
- Keep text in Persian when the note is Persian.
|
- Keep text in Persian when the note is Persian.
|
||||||
|
- If summary mentions a date, write it Shamsi/Jalali like ۱۴۰۴/۰۷/۲۱, never Gregorian month names such as سپتامبر.
|
||||||
- Do not invent facts not supported by the note.
|
- Do not invent facts not supported by the note.
|
||||||
- Maximum 5 memory items.`;
|
- Maximum 5 memory items.`;
|
||||||
|
|
||||||
@@ -61,6 +63,45 @@ Rules:
|
|||||||
return this.normalizeExtract(raw);
|
return this.normalizeExtract(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async summarizeCallTranscript(input: {
|
||||||
|
transcript: string;
|
||||||
|
personName?: string | null;
|
||||||
|
direction?: string | null;
|
||||||
|
}): Promise<{ summary: string; nextAction: string | null }> {
|
||||||
|
const system = `You summarize phone call transcripts for a Persian CRM.
|
||||||
|
Return ONLY valid JSON:
|
||||||
|
{
|
||||||
|
"summary": string,
|
||||||
|
"nextAction": string | null
|
||||||
|
}
|
||||||
|
Rules:
|
||||||
|
- summary: 3–8 concise Persian sentences covering purpose, customer needs, outcomes, and commitments.
|
||||||
|
- nextAction: one short Persian follow-up if needed; otherwise null.
|
||||||
|
- Do not invent facts not in the transcript.
|
||||||
|
- Keep names, numbers, and amounts accurate.
|
||||||
|
- Dates in summary and nextAction must be Shamsi/Jalali like ۱۴۰۴/۰۷/۲۱, never Gregorian month names such as سپتامبر.`;
|
||||||
|
|
||||||
|
const userParts = [
|
||||||
|
input.personName ? `Customer: ${input.personName}` : null,
|
||||||
|
input.direction ? `Direction: ${input.direction}` : null,
|
||||||
|
`Transcript:\n${input.transcript.trim().slice(0, 12000)}`,
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
const raw = await this.completeJson<{
|
||||||
|
summary?: string;
|
||||||
|
nextAction?: string | null;
|
||||||
|
}>(system, userParts.join('\n'));
|
||||||
|
|
||||||
|
const summary = rewriteGregorianDates(String(raw.summary ?? '').trim()).slice(0, 4000);
|
||||||
|
if (!summary) {
|
||||||
|
throw new BadRequestException('خلاصه تماس خالی بود');
|
||||||
|
}
|
||||||
|
const nextAction = raw.nextAction
|
||||||
|
? rewriteGregorianDates(String(raw.nextAction).trim()).slice(0, 500) || null
|
||||||
|
: null;
|
||||||
|
return { summary, nextAction };
|
||||||
|
}
|
||||||
|
|
||||||
async completeJson<T>(system: string, user: string): Promise<T> {
|
async completeJson<T>(system: string, user: string): Promise<T> {
|
||||||
if (!this.isEnabled()) {
|
if (!this.isEnabled()) {
|
||||||
throw new ServiceUnavailableException('هوش مصنوعی فعال نیست');
|
throw new ServiceUnavailableException('هوش مصنوعی فعال نیست');
|
||||||
@@ -131,9 +172,9 @@ Rules:
|
|||||||
const nextAction =
|
const nextAction =
|
||||||
raw.nextAction && typeof raw.nextAction === 'object'
|
raw.nextAction && typeof raw.nextAction === 'object'
|
||||||
? {
|
? {
|
||||||
title: String(raw.nextAction.title ?? '').trim().slice(0, 200),
|
title: rewriteGregorianDates(String(raw.nextAction.title ?? '').trim()).slice(0, 200),
|
||||||
description: raw.nextAction.description
|
description: raw.nextAction.description
|
||||||
? String(raw.nextAction.description).trim().slice(0, 2000)
|
? rewriteGregorianDates(String(raw.nextAction.description).trim()).slice(0, 2000)
|
||||||
: undefined,
|
: undefined,
|
||||||
dueAt: raw.nextAction.dueAt
|
dueAt: raw.nextAction.dueAt
|
||||||
? String(raw.nextAction.dueAt).trim()
|
? String(raw.nextAction.dueAt).trim()
|
||||||
@@ -144,7 +185,7 @@ Rules:
|
|||||||
const memoryItems = Array.isArray(raw.memoryItems)
|
const memoryItems = Array.isArray(raw.memoryItems)
|
||||||
? raw.memoryItems
|
? raw.memoryItems
|
||||||
.map((item) => ({
|
.map((item) => ({
|
||||||
content: String(item?.content ?? '').trim().slice(0, 500),
|
content: rewriteGregorianDates(String(item?.content ?? '').trim()).slice(0, 500),
|
||||||
category: item?.category
|
category: item?.category
|
||||||
? String(item.category).trim().slice(0, 40)
|
? String(item.category).trim().slice(0, 40)
|
||||||
: undefined,
|
: undefined,
|
||||||
@@ -159,7 +200,7 @@ Rules:
|
|||||||
return {
|
return {
|
||||||
nextAction: cleanedNext,
|
nextAction: cleanedNext,
|
||||||
memoryItems,
|
memoryItems,
|
||||||
summary: raw.summary ? String(raw.summary).trim().slice(0, 500) : undefined,
|
summary: raw.summary ? rewriteGregorianDates(String(raw.summary).trim()).slice(0, 500) : undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import {
|
||||||
|
PERSON_IMPORT_SOURCES,
|
||||||
|
type PersonImportSource,
|
||||||
|
} from '@mento/shared';
|
||||||
|
|
||||||
|
export type CountEntity =
|
||||||
|
| 'lead'
|
||||||
|
| 'person'
|
||||||
|
| 'company'
|
||||||
|
| 'deal'
|
||||||
|
| 'invoice'
|
||||||
|
| 'quote'
|
||||||
|
| 'product'
|
||||||
|
| 'activity'
|
||||||
|
| 'ticket'
|
||||||
|
| 'note'
|
||||||
|
| 'cheque'
|
||||||
|
| 'reservation'
|
||||||
|
| 'routine'
|
||||||
|
| 'project';
|
||||||
|
|
||||||
|
export type CountPeriod = 'today' | 'yesterday' | 'week' | 'last_week' | 'month' | 'last_month';
|
||||||
|
|
||||||
|
export type LeadBucket = 'summary' | 'open' | 'archived' | 'converted';
|
||||||
|
export type DealBucket = 'all' | 'open' | 'won' | 'lost' | 'stale';
|
||||||
|
|
||||||
|
export type CountIntent = {
|
||||||
|
entity: CountEntity;
|
||||||
|
personSource?: PersonImportSource;
|
||||||
|
mood?: 'newcomer' | 'happy' | 'unhappy' | 'special';
|
||||||
|
leadBucket: LeadBucket;
|
||||||
|
dealBucket: DealBucket;
|
||||||
|
period?: CountPeriod;
|
||||||
|
/** متن باقیمانده برای تطبیق مرحله یا منبع لید */
|
||||||
|
hint: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SOURCE_PATTERNS: Array<{ re: RegExp; source: PersonImportSource }> = [
|
||||||
|
{ re: /دستی/, source: 'manual' },
|
||||||
|
{ re: /اکسل/, source: 'excel' },
|
||||||
|
{ re: /دیدار/, source: 'didar' },
|
||||||
|
{ re: /ته\s*حساب/, source: 'tahesab' },
|
||||||
|
{ re: /گوشی|مخاطب\s*گوشی|مخاطبین/, source: 'phone' },
|
||||||
|
{ re: /فرم/, source: 'lead_form' },
|
||||||
|
{ re: /مونتیفای/, source: 'montify' },
|
||||||
|
{ re: /سایر|بقیه/, source: 'other' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function normalizeAskText(raw: string) {
|
||||||
|
return raw
|
||||||
|
.replace(/ي/g, 'ی')
|
||||||
|
.replace(/ك/g, 'ک')
|
||||||
|
.replace(//g, ' ')
|
||||||
|
.replace(/[؟?!.,،؛:]+/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isCountQuestion(q: string) {
|
||||||
|
return /چند|تعداد|چقدر|چنتا|چند\s*تا/.test(q);
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectEntity(q: string): CountEntity | null {
|
||||||
|
if (/لید|سرنخ/.test(q)) return 'lead';
|
||||||
|
if (/پیش\s*فاکتور/.test(q)) return 'quote';
|
||||||
|
if (/فاکتور/.test(q)) return 'invoice';
|
||||||
|
if (/معاملات|معامله/.test(q)) return 'deal';
|
||||||
|
if (/چک/.test(q)) return 'cheque';
|
||||||
|
if (/رزرو|نوبت/.test(q)) return 'reservation';
|
||||||
|
if (/روتین/.test(q)) return 'routine';
|
||||||
|
if (/پروژه/.test(q)) return 'project';
|
||||||
|
if (/تیکت/.test(q)) return 'ticket';
|
||||||
|
if (/یادداشت/.test(q)) return 'note';
|
||||||
|
if (/فعالیت/.test(q)) return 'activity';
|
||||||
|
if (/محصول|کالا/.test(q)) return 'product';
|
||||||
|
if (/شرکت/.test(q) && !/مشتری/.test(q)) return 'company';
|
||||||
|
if (/مشتری|اشخاص|شخص ها|افراد|مخاطب/.test(q)) return 'person';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectPeriod(q: string): CountPeriod | undefined {
|
||||||
|
if (/دیروز/.test(q)) return 'yesterday';
|
||||||
|
if (/امروز/.test(q)) return 'today';
|
||||||
|
if (/هفته\s*(?:ی\s+)?(گذشته|قبل|پیش)/.test(q)) return 'last_week';
|
||||||
|
if (/این\s*هفته|هفته\s*جاری/.test(q)) return 'week';
|
||||||
|
if (/ماه\s*(?:ی\s+)?(گذشته|قبل|پیش)/.test(q)) return 'last_month';
|
||||||
|
if (/این\s*ماه|ماه\s*جاری/.test(q)) return 'month';
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectLeadBucket(q: string): LeadBucket {
|
||||||
|
if (/بایگانی/.test(q)) return 'archived';
|
||||||
|
if (/تبدیل/.test(q)) return 'converted';
|
||||||
|
if (/باز|فعال|جاری/.test(q)) return 'open';
|
||||||
|
return 'summary';
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectDealBucket(q: string): DealBucket {
|
||||||
|
if (/در\s*خطر|راکد|گندیده/.test(q)) return 'stale';
|
||||||
|
if (/برنده|موفق|بسته\s*شده\s*موفق/.test(q)) return 'won';
|
||||||
|
if (/باخته|از\s*دست\s*رفته|ناموفق/.test(q)) return 'lost';
|
||||||
|
if (/باز|جاری|فعال/.test(q)) return 'open';
|
||||||
|
return 'all';
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectMood(q: string): CountIntent['mood'] {
|
||||||
|
if (/ناراضی/.test(q)) return 'unhappy';
|
||||||
|
if (/خوشحال/.test(q)) return 'happy';
|
||||||
|
if (/خاص/.test(q)) return 'special';
|
||||||
|
if (/تازه/.test(q)) return 'newcomer';
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HINT_STOP = [
|
||||||
|
'چند تا',
|
||||||
|
'ته حساب',
|
||||||
|
'مخاطب گوشی',
|
||||||
|
'مخاطبین',
|
||||||
|
'پیش فاکتور',
|
||||||
|
'بایگانی',
|
||||||
|
'مونتیفای',
|
||||||
|
'معاملات',
|
||||||
|
'مشتریان',
|
||||||
|
'سرنخ',
|
||||||
|
'لیدها',
|
||||||
|
'فعالیت',
|
||||||
|
'یادداشت',
|
||||||
|
'بگویید',
|
||||||
|
'داریم',
|
||||||
|
'دارید',
|
||||||
|
'هستند',
|
||||||
|
'تعداد',
|
||||||
|
'چقدر',
|
||||||
|
'چنتا',
|
||||||
|
'امروز',
|
||||||
|
'دیروز',
|
||||||
|
'جاری',
|
||||||
|
'تبدیل',
|
||||||
|
'برنده',
|
||||||
|
'باخته',
|
||||||
|
'ناراضی',
|
||||||
|
'خوشحال',
|
||||||
|
'محصول',
|
||||||
|
'فاکتور',
|
||||||
|
'معامله',
|
||||||
|
'مشتری',
|
||||||
|
'شرکت',
|
||||||
|
'پروژه',
|
||||||
|
'روتین',
|
||||||
|
'رزرو',
|
||||||
|
'نوبت',
|
||||||
|
'تیکت',
|
||||||
|
'منبع',
|
||||||
|
'مرحله',
|
||||||
|
'وضعیت',
|
||||||
|
'هفته',
|
||||||
|
'گذشته',
|
||||||
|
'پیش',
|
||||||
|
'قبل',
|
||||||
|
'لطفا',
|
||||||
|
'الان',
|
||||||
|
'شده',
|
||||||
|
'وارد',
|
||||||
|
'تازه',
|
||||||
|
'خاص',
|
||||||
|
'بگو',
|
||||||
|
'دارم',
|
||||||
|
'هست',
|
||||||
|
'است',
|
||||||
|
'جاری',
|
||||||
|
'فعال',
|
||||||
|
'باز',
|
||||||
|
'لید',
|
||||||
|
'کالا',
|
||||||
|
'چک',
|
||||||
|
'ماه',
|
||||||
|
'پیش',
|
||||||
|
'های',
|
||||||
|
'چند',
|
||||||
|
'کل',
|
||||||
|
'همه',
|
||||||
|
'این',
|
||||||
|
'یک',
|
||||||
|
'یه',
|
||||||
|
'از',
|
||||||
|
'با',
|
||||||
|
'در',
|
||||||
|
'تا',
|
||||||
|
'ها',
|
||||||
|
].sort((a, b) => b.length - a.length);
|
||||||
|
|
||||||
|
const PERSON_HINT_STOP = [
|
||||||
|
'ته حساب',
|
||||||
|
'مخاطب گوشی',
|
||||||
|
'مخاطبین',
|
||||||
|
'مونتیفای',
|
||||||
|
'ناراضی',
|
||||||
|
'خوشحال',
|
||||||
|
'دستی',
|
||||||
|
'اکسل',
|
||||||
|
'دیدار',
|
||||||
|
'گوشی',
|
||||||
|
'مخاطب',
|
||||||
|
'فرم',
|
||||||
|
'سایر',
|
||||||
|
'تازه',
|
||||||
|
'خاص',
|
||||||
|
].sort((a, b) => b.length - a.length);
|
||||||
|
|
||||||
|
function leftoverHint(q: string, entity: CountEntity) {
|
||||||
|
let text = ` ${q} `;
|
||||||
|
const words = entity === 'person' || entity === 'company'
|
||||||
|
? [...HINT_STOP, ...PERSON_HINT_STOP]
|
||||||
|
: HINT_STOP;
|
||||||
|
for (const word of [...words].sort((a, b) => b.length - a.length)) {
|
||||||
|
text = text.replaceAll(word, ' ');
|
||||||
|
}
|
||||||
|
return text.replace(/\s+/g, ' ').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function classifyCountQuestion(raw: string): CountIntent | null {
|
||||||
|
const q = normalizeAskText(raw);
|
||||||
|
if (!isCountQuestion(q)) return null;
|
||||||
|
const entity = detectEntity(q);
|
||||||
|
if (!entity) return null;
|
||||||
|
const personSource = SOURCE_PATTERNS.find((item) => item.re.test(q))?.source;
|
||||||
|
const period = detectPeriod(q);
|
||||||
|
let hint = leftoverHint(q, entity);
|
||||||
|
if (period && entity === 'lead' && !/مرحله|وضعیت|ستون/.test(q)) {
|
||||||
|
hint = hint.replace(/(^|\s)جدید(?=\s|$)/g, ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
entity,
|
||||||
|
personSource:
|
||||||
|
entity === 'person' || entity === 'company' ? personSource : undefined,
|
||||||
|
mood: entity === 'person' ? detectMood(q) : undefined,
|
||||||
|
leadBucket: detectLeadBucket(q),
|
||||||
|
dealBucket: detectDealBucket(q),
|
||||||
|
period,
|
||||||
|
hint,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function personSourceKeys(): readonly PersonImportSource[] {
|
||||||
|
return PERSON_IMPORT_SOURCES;
|
||||||
|
}
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class VoiceCommandDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(800)
|
||||||
|
text!: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class AskMentoDto {
|
export class AskMentoDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
@@ -9,4 +16,9 @@ export class AskMentoDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
personId?: string;
|
personId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(4000)
|
||||||
|
chatContext?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,12 +28,33 @@ import { LoyaltyModule } from './loyalty/loyalty.module';
|
|||||||
import { AutomationsModule } from './automations/automations.module';
|
import { AutomationsModule } from './automations/automations.module';
|
||||||
import { MessageAutomationsModule } from './message-automations/message-automations.module';
|
import { MessageAutomationsModule } from './message-automations/message-automations.module';
|
||||||
import { AiModule } from './ai/ai.module';
|
import { AiModule } from './ai/ai.module';
|
||||||
|
import { TrackingModule } from './tracking/tracking.module';
|
||||||
import { MemoryModule } from './memory/memory.module';
|
import { MemoryModule } from './memory/memory.module';
|
||||||
import { TahesabModule } from './integrations/tahesab/tahesab.module';
|
import { TahesabModule } from './integrations/tahesab/tahesab.module';
|
||||||
import { InventoryModule } from './inventory/inventory.module';
|
import { InventoryModule } from './inventory/inventory.module';
|
||||||
import { FinanceModule } from './finance/finance.module';
|
import { FinanceModule } from './finance/finance.module';
|
||||||
|
import { TreasuryModule } from './treasury/treasury.module';
|
||||||
import { PlatformModule } from './platform/platform.module';
|
import { PlatformModule } from './platform/platform.module';
|
||||||
import { BillingModule } from './billing/billing.module';
|
import { BillingModule } from './billing/billing.module';
|
||||||
|
import { AuditLogsModule } from './audit-logs/audit-logs.module';
|
||||||
|
import { SavedViewsModule } from './saved-views/saved-views.module';
|
||||||
|
import { TablePrefsModule } from './table-prefs/table-prefs.module';
|
||||||
|
import { PublicApiModule } from './public-api/public-api.module';
|
||||||
|
import { SmsCampaignsModule } from './sms-campaigns/sms-campaigns.module';
|
||||||
|
import { TeamsModule } from './teams/teams.module';
|
||||||
|
import { WooCommerceModule } from './integrations/woocommerce/woocommerce.module';
|
||||||
|
import { MontifyModule } from './integrations/montify/montify.module';
|
||||||
|
import { VoipModule } from './integrations/voip/voip.module';
|
||||||
|
import { ReservationsModule } from './reservations/reservations.module';
|
||||||
|
import { LeadsModule } from './leads/leads.module';
|
||||||
|
import { ConversationsModule } from './conversations/conversations.module';
|
||||||
|
import { RoutinesModule } from './routines/routines.module';
|
||||||
|
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';
|
||||||
|
import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -44,6 +65,9 @@ import { BillingModule } from './billing/billing.module';
|
|||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
AiModule,
|
AiModule,
|
||||||
PrismaModule,
|
PrismaModule,
|
||||||
|
SmsBillingModule,
|
||||||
|
CustomerGroupsModule,
|
||||||
|
OutboundSmsModule,
|
||||||
StorageModule,
|
StorageModule,
|
||||||
HealthModule,
|
HealthModule,
|
||||||
BillingModule,
|
BillingModule,
|
||||||
@@ -53,6 +77,7 @@ import { BillingModule } from './billing/billing.module';
|
|||||||
OrgRolesModule,
|
OrgRolesModule,
|
||||||
OrganizationsModule,
|
OrganizationsModule,
|
||||||
ContactsModule,
|
ContactsModule,
|
||||||
|
LeadsModule,
|
||||||
PipelinesModule,
|
PipelinesModule,
|
||||||
ActivitiesModule,
|
ActivitiesModule,
|
||||||
NotesModule,
|
NotesModule,
|
||||||
@@ -64,6 +89,7 @@ import { BillingModule } from './billing/billing.module';
|
|||||||
InvoicesModule,
|
InvoicesModule,
|
||||||
InventoryModule,
|
InventoryModule,
|
||||||
FinanceModule,
|
FinanceModule,
|
||||||
|
TreasuryModule,
|
||||||
SalesModule,
|
SalesModule,
|
||||||
TicketsModule,
|
TicketsModule,
|
||||||
FaqModule,
|
FaqModule,
|
||||||
@@ -75,6 +101,22 @@ import { BillingModule } from './billing/billing.module';
|
|||||||
MessageAutomationsModule,
|
MessageAutomationsModule,
|
||||||
MemoryModule,
|
MemoryModule,
|
||||||
TahesabModule,
|
TahesabModule,
|
||||||
|
AuditLogsModule,
|
||||||
|
SavedViewsModule,
|
||||||
|
TablePrefsModule,
|
||||||
|
PublicApiModule,
|
||||||
|
SmsCampaignsModule,
|
||||||
|
TrackingModule,
|
||||||
|
TeamsModule,
|
||||||
|
WooCommerceModule,
|
||||||
|
MontifyModule,
|
||||||
|
VoipModule,
|
||||||
|
ReservationsModule,
|
||||||
|
ConversationsModule,
|
||||||
|
RoutinesModule,
|
||||||
|
GamificationModule,
|
||||||
|
DeletionsModule,
|
||||||
|
BehaviorModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -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,216 @@
|
|||||||
|
import { ForbiddenException, 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 =
|
||||||
|
'ساعت کاری امروز تمام شده است. برای ادامه دوباره وارد شوید.';
|
||||||
|
|
||||||
|
export const LOGIN_BLOCKED_AFTER_HOURS_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 assertLoginAllowed(organizationId: string, userId: string, at = new Date()) {
|
||||||
|
const membership = await this.prisma.membership.findFirst({
|
||||||
|
where: { organizationId, userId, isActive: true },
|
||||||
|
select: { role: true, logoutTime: true, blockLoginAfterLogout: true },
|
||||||
|
});
|
||||||
|
if (!membership || membership.role === 'owner' || !membership.blockLoginAfterLogout) return;
|
||||||
|
if (loggedInAfterCutoff(at, membership.logoutTime)) {
|
||||||
|
throw new ForbiddenException(LOGIN_BLOCKED_AFTER_HOURS_MESSAGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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, blockLoginAfterLogout: 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() &&
|
||||||
|
!membership?.blockLoginAfterLogout
|
||||||
|
) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
const FIELD_LABELS: Record<string, string> = {
|
||||||
|
title: 'عنوان',
|
||||||
|
name: 'نام',
|
||||||
|
firstName: 'نام',
|
||||||
|
lastName: 'نام خانوادگی',
|
||||||
|
fullName: 'نام',
|
||||||
|
description: 'توضیحات',
|
||||||
|
body: 'متن',
|
||||||
|
mobile: 'موبایل',
|
||||||
|
phone: 'تلفن',
|
||||||
|
email: 'ایمیل',
|
||||||
|
status: 'وضعیت',
|
||||||
|
stageId: 'مرحله',
|
||||||
|
priority: 'اولویت',
|
||||||
|
dueAt: 'موعد',
|
||||||
|
amount: 'مبلغ',
|
||||||
|
subject: 'موضوع',
|
||||||
|
type: 'نوع',
|
||||||
|
city: 'شهر',
|
||||||
|
address: 'آدرس',
|
||||||
|
notes: 'یادداشت',
|
||||||
|
contactName: 'نام مخاطب',
|
||||||
|
};
|
||||||
|
|
||||||
|
const SECRET = /password|token|secret|otp|pin/i;
|
||||||
|
|
||||||
|
function textOf(value: unknown) {
|
||||||
|
if (typeof value === 'string') return value.trim().replace(/\s+/g, ' ');
|
||||||
|
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelOf(source: unknown) {
|
||||||
|
if (!source || typeof source !== 'object' || Array.isArray(source)) return '';
|
||||||
|
const body = source as Record<string, unknown>;
|
||||||
|
const person = [textOf(body.firstName), textOf(body.lastName)].filter(Boolean).join(' ');
|
||||||
|
return (
|
||||||
|
person ||
|
||||||
|
textOf(body.title) ||
|
||||||
|
textOf(body.name) ||
|
||||||
|
textOf(body.subject) ||
|
||||||
|
textOf(body.fullName)
|
||||||
|
).slice(0, 120);
|
||||||
|
}
|
||||||
|
|
||||||
|
function changesOf(source: unknown) {
|
||||||
|
if (!source || typeof source !== 'object' || Array.isArray(source)) return '';
|
||||||
|
const bits: string[] = [];
|
||||||
|
for (const [key, value] of Object.entries(source as Record<string, unknown>)) {
|
||||||
|
if (SECRET.test(key)) continue;
|
||||||
|
const name = FIELD_LABELS[key];
|
||||||
|
if (!name) continue;
|
||||||
|
if (key.endsWith('Id')) {
|
||||||
|
bits.push(name);
|
||||||
|
} else {
|
||||||
|
const text = textOf(value).slice(0, 40);
|
||||||
|
if (!text) continue;
|
||||||
|
bits.push(`${name}: ${text}`);
|
||||||
|
}
|
||||||
|
if (bits.length >= 4) break;
|
||||||
|
}
|
||||||
|
return bits.join('، ');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function auditStory(
|
||||||
|
method: string,
|
||||||
|
requestBody: unknown,
|
||||||
|
responseBody: unknown,
|
||||||
|
) {
|
||||||
|
const label = labelOf(responseBody) || labelOf(requestBody);
|
||||||
|
const detail = method === 'DELETE' ? '' : changesOf(requestBody);
|
||||||
|
const summary = [label, detail].filter(Boolean).join(' — ').slice(0, 500);
|
||||||
|
return {
|
||||||
|
label,
|
||||||
|
detail: detail.slice(0, 240),
|
||||||
|
summary,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { RequirePermission, SectionPermissionGuard } from '../auth/section-permission.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()
|
||||||
|
@IsString()
|
||||||
|
q?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
actorUserId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
entityType?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
action?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
page?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(100)
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Controller('audit-logs')
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard, SectionPermissionGuard)
|
||||||
|
@RequireOrgModule('audit_logs')
|
||||||
|
@RequirePermission('audit', { reads: true })
|
||||||
|
export class AuditLogsController {
|
||||||
|
constructor(
|
||||||
|
private readonly auditLogs: AuditLogsService,
|
||||||
|
private readonly attendance: AttendanceService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get('attendance')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
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(
|
||||||
|
@CurrentUser() user: { organizationId: string },
|
||||||
|
@Query() query: ListAuditQueryDto,
|
||||||
|
) {
|
||||||
|
return this.auditLogs.list(user.organizationId, {
|
||||||
|
q: query.q,
|
||||||
|
actorUserId: query.actorUserId,
|
||||||
|
entityType: query.entityType,
|
||||||
|
action: query.action,
|
||||||
|
page: query.page,
|
||||||
|
limit: query.limit,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import {
|
||||||
|
CallHandler,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import { Observable, tap } from 'rxjs';
|
||||||
|
import { auditStory } from './audit-detail';
|
||||||
|
import { AuditLogsService } from './audit-logs.service';
|
||||||
|
|
||||||
|
const SKIP_PREFIXES = [
|
||||||
|
'/api/health',
|
||||||
|
'/api/auth/login',
|
||||||
|
'/api/auth/register',
|
||||||
|
'/api/auth/otp',
|
||||||
|
'/api/auth/refresh',
|
||||||
|
'/api/portal',
|
||||||
|
'/api/public',
|
||||||
|
'/api/platform',
|
||||||
|
'/api/audit-logs',
|
||||||
|
];
|
||||||
|
|
||||||
|
type AuthedRequest = Request & {
|
||||||
|
user?: {
|
||||||
|
userId?: string;
|
||||||
|
id?: string;
|
||||||
|
organizationId?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function inferEntity(path: string): { entityType: string | null; entityId: string | null } {
|
||||||
|
const clean = path.replace(/^\/api\/?/, '').split('?')[0] ?? '';
|
||||||
|
const parts = clean.split('/').filter(Boolean);
|
||||||
|
if (!parts.length) return { entityType: null, entityId: null };
|
||||||
|
const entityType = parts[0] ?? null;
|
||||||
|
const maybeId = parts[1];
|
||||||
|
const entityId =
|
||||||
|
maybeId && !['new', 'me', 'summary', 'dashboard', 'board'].includes(maybeId)
|
||||||
|
? maybeId
|
||||||
|
: null;
|
||||||
|
return { entityType, entityId };
|
||||||
|
}
|
||||||
|
|
||||||
|
function actionLabel(method: string, path: string): string {
|
||||||
|
const m = method.toUpperCase();
|
||||||
|
if (m === 'POST') return 'ایجاد';
|
||||||
|
if (m === 'PATCH' || m === 'PUT') return 'ویرایش';
|
||||||
|
if (m === 'DELETE') return 'حذف';
|
||||||
|
return m;
|
||||||
|
void path;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuditLogsInterceptor implements NestInterceptor {
|
||||||
|
constructor(private readonly audit: AuditLogsService) {}
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
|
const http = context.switchToHttp();
|
||||||
|
const req = http.getRequest<AuthedRequest>();
|
||||||
|
const method = (req.method ?? 'GET').toUpperCase();
|
||||||
|
if (!['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
|
||||||
|
const path = req.originalUrl || req.url || '';
|
||||||
|
if (SKIP_PREFIXES.some((p) => path.startsWith(p))) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
|
||||||
|
const organizationId = req.user?.organizationId;
|
||||||
|
if (!organizationId) return next.handle();
|
||||||
|
|
||||||
|
const actorUserId = req.user?.userId ?? req.user?.id ?? null;
|
||||||
|
const { entityType, entityId } = inferEntity(path);
|
||||||
|
const action = actionLabel(method, path);
|
||||||
|
const ip =
|
||||||
|
(req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim() ||
|
||||||
|
req.ip ||
|
||||||
|
null;
|
||||||
|
|
||||||
|
return next.handle().pipe(
|
||||||
|
tap({
|
||||||
|
next: (response) => {
|
||||||
|
const story = auditStory(method, req.body, response);
|
||||||
|
const summary =
|
||||||
|
story.summary ||
|
||||||
|
`${action} ${entityType ?? 'منبع'} از مسیر ${path.split('?')[0]}`;
|
||||||
|
void this.audit.write({
|
||||||
|
organizationId,
|
||||||
|
actorUserId,
|
||||||
|
action,
|
||||||
|
method,
|
||||||
|
path: path.split('?')[0] ?? path,
|
||||||
|
entityType,
|
||||||
|
entityId,
|
||||||
|
summary,
|
||||||
|
meta: story.label || story.detail ? { label: story.label, detail: story.detail } : null,
|
||||||
|
ip,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
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, AttendanceModule],
|
||||||
|
controllers: [AuditLogsController],
|
||||||
|
providers: [
|
||||||
|
AuditLogsService,
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: AuditLogsInterceptor,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
exports: [AuditLogsService],
|
||||||
|
})
|
||||||
|
export class AuditLogsModule {}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import type { AuditLogDto, AuditLogListResponse } from '@mento/shared';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { buildSearchWhere, ci } from '../common/search';
|
||||||
|
|
||||||
|
export type AuditWriteInput = {
|
||||||
|
organizationId: string;
|
||||||
|
actorUserId?: string | null;
|
||||||
|
action: string;
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
entityType?: string | null;
|
||||||
|
entityId?: string | null;
|
||||||
|
summary: string;
|
||||||
|
meta?: Record<string, unknown> | null;
|
||||||
|
ip?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuditLogsService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async write(input: AuditWriteInput): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.prisma.auditLog.create({
|
||||||
|
data: {
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
actorUserId: input.actorUserId ?? null,
|
||||||
|
action: input.action,
|
||||||
|
method: input.method.slice(0, 16),
|
||||||
|
path: input.path.slice(0, 400),
|
||||||
|
entityType: input.entityType ?? null,
|
||||||
|
entityId: input.entityId ?? null,
|
||||||
|
summary: input.summary.slice(0, 500),
|
||||||
|
meta:
|
||||||
|
input.meta == null
|
||||||
|
? undefined
|
||||||
|
: (input.meta as Prisma.InputJsonValue),
|
||||||
|
ip: input.ip ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// never break the main request because of audit write failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(
|
||||||
|
organizationId: string,
|
||||||
|
opts: {
|
||||||
|
q?: string;
|
||||||
|
actorUserId?: string;
|
||||||
|
entityType?: string;
|
||||||
|
action?: string;
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
},
|
||||||
|
): Promise<AuditLogListResponse> {
|
||||||
|
const page = Math.max(1, opts.page ?? 1);
|
||||||
|
const limit = Math.min(100, Math.max(1, opts.limit ?? 30));
|
||||||
|
const where: Prisma.AuditLogWhereInput = {
|
||||||
|
organizationId,
|
||||||
|
...(opts.actorUserId ? { actorUserId: opts.actorUserId } : {}),
|
||||||
|
...(opts.entityType ? { entityType: opts.entityType } : {}),
|
||||||
|
...(opts.action ? { action: opts.action } : {}),
|
||||||
|
};
|
||||||
|
const search = buildSearchWhere<Prisma.AuditLogWhereInput>(opts.q, (t) => [
|
||||||
|
{ summary: ci(t) },
|
||||||
|
{ path: ci(t) },
|
||||||
|
{ action: ci(t) },
|
||||||
|
{ actor: { fullName: ci(t) } },
|
||||||
|
]);
|
||||||
|
if (search) where.AND = [search];
|
||||||
|
|
||||||
|
const [total, rows] = await Promise.all([
|
||||||
|
this.prisma.auditLog.count({ where }),
|
||||||
|
this.prisma.auditLog.findMany({
|
||||||
|
where,
|
||||||
|
include: { actor: { select: { id: true, fullName: true } } },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
items: rows.map((row) => this.toDto(row)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: {
|
||||||
|
id: string;
|
||||||
|
action: string;
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
entityType: string | null;
|
||||||
|
entityId: string | null;
|
||||||
|
summary: string;
|
||||||
|
meta: Prisma.JsonValue | null;
|
||||||
|
ip: string | null;
|
||||||
|
createdAt: Date;
|
||||||
|
actor: { id: string; fullName: string } | null;
|
||||||
|
}): AuditLogDto {
|
||||||
|
const meta =
|
||||||
|
row.meta && typeof row.meta === 'object' && !Array.isArray(row.meta)
|
||||||
|
? (row.meta as { label?: unknown; detail?: unknown })
|
||||||
|
: null;
|
||||||
|
const label = typeof meta?.label === 'string' ? meta.label : null;
|
||||||
|
const detail = typeof meta?.detail === 'string' ? meta.detail : null;
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
action: row.action,
|
||||||
|
method: row.method,
|
||||||
|
path: row.path,
|
||||||
|
entityType: row.entityType,
|
||||||
|
entityId: row.entityId,
|
||||||
|
summary: row.summary,
|
||||||
|
label,
|
||||||
|
detail,
|
||||||
|
actor: row.actor,
|
||||||
|
ip: row.ip,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
@@ -25,8 +26,7 @@ import {
|
|||||||
} from './dto';
|
} from './dto';
|
||||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
import { CurrentUser } from './current-user.decorator';
|
import { CurrentUser } from './current-user.decorator';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
type AuthActor = { userId: string; organizationId: string };
|
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@@ -68,7 +68,7 @@ export class AuthController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('switch-organization')
|
@Post('switch-organization')
|
||||||
switchOrganization(
|
switchOrganization(
|
||||||
@CurrentUser() user: AuthActor,
|
@CurrentUser() user: Actor,
|
||||||
@Body() dto: SwitchOrganizationDto,
|
@Body() dto: SwitchOrganizationDto,
|
||||||
) {
|
) {
|
||||||
return this.authService.switchOrganization(user.userId, dto.organizationId);
|
return this.authService.switchOrganization(user.userId, dto.organizationId);
|
||||||
@@ -76,26 +76,61 @@ export class AuthController {
|
|||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('organizations')
|
@Get('organizations')
|
||||||
listOrganizations(@CurrentUser() user: AuthActor) {
|
listOrganizations(@CurrentUser() user: Actor) {
|
||||||
return this.authService.listMyOrganizations(user.userId);
|
return this.authService.listMyOrganizations(user.userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post('logout')
|
||||||
|
logout(@CurrentUser() user: Actor) {
|
||||||
|
return this.authService.logout(user);
|
||||||
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('me')
|
@Get('me')
|
||||||
me(@CurrentUser() user: AuthActor) {
|
me(@CurrentUser() user: Actor) {
|
||||||
return this.authService.me(user.userId, user.organizationId);
|
return this.authService.me(user.userId, user.organizationId, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post('view-as')
|
||||||
|
viewAs(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Body() body: { targetUserId?: string },
|
||||||
|
) {
|
||||||
|
if (!body.targetUserId?.trim()) {
|
||||||
|
throw new BadRequestException('کاربر هدف مشخص نیست.');
|
||||||
|
}
|
||||||
|
return this.authService.viewAs(user, body.targetUserId.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Patch('me')
|
@Patch('me')
|
||||||
updateMe(@CurrentUser() user: AuthActor, @Body() dto: UpdateProfileDto) {
|
updateMe(@CurrentUser() user: Actor, @Body() dto: UpdateProfileDto) {
|
||||||
return this.authService.updateMe(user.userId, user.organizationId, dto);
|
return this.authService.updateMe(user.userId, user.organizationId, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Patch('me/prior-archive')
|
||||||
|
setPriorLens(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Body() body: { lens?: string },
|
||||||
|
) {
|
||||||
|
if (body.lens !== 'archive' && body.lens !== 'current') {
|
||||||
|
throw new BadRequestException('حالت بایگانی نامعتبر است');
|
||||||
|
}
|
||||||
|
return this.authService.setPriorLens(
|
||||||
|
user.userId,
|
||||||
|
user.organizationId,
|
||||||
|
body.lens,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** عکس پروفایل کاربر جاری */
|
/** عکس پروفایل کاربر جاری */
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('me/avatar')
|
@Get('me/avatar')
|
||||||
async avatar(@CurrentUser() user: AuthActor) {
|
async avatar(@CurrentUser() user: Actor) {
|
||||||
const file = await this.authService.openAvatar(user.userId);
|
const file = await this.authService.openAvatar(user.userId);
|
||||||
return new StreamableFile(file.stream, { type: file.mimeType });
|
return new StreamableFile(file.stream, { type: file.mimeType });
|
||||||
}
|
}
|
||||||
@@ -109,7 +144,7 @@ export class AuthController {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
uploadAvatar(
|
uploadAvatar(
|
||||||
@CurrentUser() user: AuthActor,
|
@CurrentUser() user: Actor,
|
||||||
@UploadedFile() file: Express.Multer.File,
|
@UploadedFile() file: Express.Multer.File,
|
||||||
) {
|
) {
|
||||||
return this.authService.saveAvatar(user.userId, user.organizationId, file);
|
return this.authService.saveAvatar(user.userId, user.organizationId, file);
|
||||||
@@ -117,7 +152,7 @@ export class AuthController {
|
|||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Delete('me/avatar')
|
@Delete('me/avatar')
|
||||||
removeAvatar(@CurrentUser() user: AuthActor) {
|
removeAvatar(@CurrentUser() user: Actor) {
|
||||||
return this.authService.removeAvatar(user.userId, user.organizationId);
|
return this.authService.removeAvatar(user.userId, user.organizationId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,24 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { MembershipsModule } from '../memberships/memberships.module';
|
import { MembershipsModule } from '../memberships/memberships.module';
|
||||||
import { BillingModule } from '../billing/billing.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 { AuthService } from './auth.service';
|
||||||
import { AuthController } from './auth.controller';
|
import { AuthController } from './auth.controller';
|
||||||
import { JwtStrategy } from './jwt.strategy';
|
import { JwtStrategy } from './jwt.strategy';
|
||||||
import { RolesGuard } from './roles.guard';
|
import { RolesGuard } from './roles.guard';
|
||||||
import { SmsService } from '../common/sms.service';
|
import { ViewAsReadOnlyInterceptor } from './view-as-readonly.interceptor';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule,
|
ConfigModule,
|
||||||
MembershipsModule,
|
MembershipsModule,
|
||||||
BillingModule,
|
BillingModule,
|
||||||
|
AttendanceModule,
|
||||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
@@ -28,7 +32,19 @@ import { SmsService } from '../common/sms.service';
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [AuthService, JwtStrategy, RolesGuard, SmsService],
|
providers: [
|
||||||
|
AuthService,
|
||||||
|
JwtStrategy,
|
||||||
|
RolesGuard,
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: ViewAsReadOnlyInterceptor,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: WorkdayInterceptor,
|
||||||
|
},
|
||||||
|
],
|
||||||
exports: [AuthService, RolesGuard, JwtModule],
|
exports: [AuthService, RolesGuard, JwtModule],
|
||||||
})
|
})
|
||||||
export class AuthModule {}
|
export class AuthModule {}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
ConflictException,
|
ConflictException,
|
||||||
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -18,11 +19,15 @@ import type {
|
|||||||
SubscriptionSummaryDto,
|
SubscriptionSummaryDto,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
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 { 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 { LocalFileStorage } from '../storage/local-file.storage';
|
||||||
import { MembershipsService } from '../memberships/memberships.service';
|
import { MembershipsService } from '../memberships/memberships.service';
|
||||||
import { BillingService } from '../billing/billing.service';
|
import { BillingService } from '../billing/billing.service';
|
||||||
|
import { AttendanceService } from '../attendance/attendance.service';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
import {
|
import {
|
||||||
LoginDto,
|
LoginDto,
|
||||||
LoginOtpRequestDto,
|
LoginOtpRequestDto,
|
||||||
@@ -33,7 +38,7 @@ import {
|
|||||||
} from './dto';
|
} from './dto';
|
||||||
|
|
||||||
const OTP_LENGTH = 6;
|
const OTP_LENGTH = 6;
|
||||||
const OTP_TTL_SECONDS = 5 * 60;
|
const OTP_TTL_SECONDS = 90;
|
||||||
const AVATAR_MAX_BYTES = 2 * 1024 * 1024;
|
const AVATAR_MAX_BYTES = 2 * 1024 * 1024;
|
||||||
const AVATAR_EXT: Record<string, string> = {
|
const AVATAR_EXT: Record<string, string> = {
|
||||||
'image/jpeg': 'jpg',
|
'image/jpeg': 'jpg',
|
||||||
@@ -77,7 +82,8 @@ function maskEmail(email: string): string {
|
|||||||
|
|
||||||
function maskMobile(mobile: string): string {
|
function maskMobile(mobile: string): string {
|
||||||
if (mobile.length < 4) return '****';
|
if (mobile.length < 4) return '****';
|
||||||
return `${mobile.slice(0, 4)}***${mobile.slice(-2)}`;
|
// نمایش RTL: دو رقم آخر سپس *** سپس پیششماره (مثلاً 69***0913)
|
||||||
|
return `${mobile.slice(-2)}***${mobile.slice(0, 4)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateOtp(): string {
|
function generateOtp(): string {
|
||||||
@@ -101,10 +107,11 @@ export class AuthService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly jwt: JwtService,
|
private readonly jwt: JwtService,
|
||||||
private readonly config: ConfigService,
|
private readonly config: ConfigService,
|
||||||
private readonly sms: SmsService,
|
private readonly sms: SmsGatewayService,
|
||||||
private readonly files: LocalFileStorage,
|
private readonly files: LocalFileStorage,
|
||||||
private readonly memberships: MembershipsService,
|
private readonly memberships: MembershipsService,
|
||||||
private readonly billing: BillingService,
|
private readonly billing: BillingService,
|
||||||
|
private readonly attendance: AttendanceService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -167,7 +174,7 @@ export class AuthService {
|
|||||||
if (emailOtpEnabled && emailCode) {
|
if (emailOtpEnabled && emailCode) {
|
||||||
await this.dispatchEmailOtp(email, emailCode, returnOtp);
|
await this.dispatchEmailOtp(email, emailCode, returnOtp);
|
||||||
}
|
}
|
||||||
await this.dispatchMobileOtp(mobile, mobileCode, returnOtp);
|
await this.dispatchMobileOtp(mobile, mobileCode, returnOtp, null);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
challengeId: challenge.id,
|
challengeId: challenge.id,
|
||||||
@@ -312,7 +319,7 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException('اطلاعات ورود نادرست است');
|
throw new UnauthorizedException('اطلاعات ورود نادرست است');
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.finishLogin(user.id);
|
return this.finishLogin(user.id, { fromPassword: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** ورود اختیاری با موبایل + OTP (بدون رمز) — فقط کاربران ثبتشده */
|
/** ورود اختیاری با موبایل + OTP (بدون رمز) — فقط کاربران ثبتشده */
|
||||||
@@ -346,7 +353,7 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.dispatchMobileOtp(mobile, code, returnOtp);
|
await this.dispatchMobileOtp(mobile, code, returnOtp, user.organizationId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
challengeId: challenge.id,
|
challengeId: challenge.id,
|
||||||
@@ -402,13 +409,134 @@ export class AuthService {
|
|||||||
return this.finishLogin(user.id);
|
return this.finishLogin(user.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
async me(userId: string, organizationId: string): Promise<AuthUserDto> {
|
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);
|
await this.memberships.requireActive(userId, organizationId);
|
||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
return this.toAuthUserDto(user, organizationId);
|
let impersonatorFullName: string | undefined;
|
||||||
|
if (actor?.viewAsReadOnly && actor.impersonatorUserId) {
|
||||||
|
const owner = await this.prisma.user.findUnique({
|
||||||
|
where: { id: actor.impersonatorUserId },
|
||||||
|
select: { fullName: true },
|
||||||
|
});
|
||||||
|
impersonatorFullName = owner?.fullName;
|
||||||
|
}
|
||||||
|
return this.toAuthUserDto(user, organizationId, undefined, actor, impersonatorFullName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* مالک محیط: مشاهده فقطخواندنی بهجای کاربر هدف، یا بازگشت به حساب خودش.
|
||||||
|
*/
|
||||||
|
async viewAs(actor: Actor, targetUserId: string): Promise<LoginResponse> {
|
||||||
|
const ownerId = actor.impersonatorUserId ?? actor.userId;
|
||||||
|
const ownerMembership = await this.prisma.membership.findFirst({
|
||||||
|
where: {
|
||||||
|
userId: ownerId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
isActive: true,
|
||||||
|
role: 'owner',
|
||||||
|
},
|
||||||
|
select: { userId: true, organizationId: true },
|
||||||
|
});
|
||||||
|
if (!ownerMembership) {
|
||||||
|
throw new ForbiddenException('فقط مالک محیط میتواند بهجای کاربر دیگر مشاهده کند.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetUserId?.trim()) {
|
||||||
|
throw new BadRequestException('کاربر هدف مشخص نیست.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetUserId === ownerId) {
|
||||||
|
return this.issueLogin(ownerId, actor.organizationId, { skipLastLogin: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = await this.prisma.user.findFirst({
|
||||||
|
where: {
|
||||||
|
id: targetUserId,
|
||||||
|
isActive: true,
|
||||||
|
memberships: {
|
||||||
|
some: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
email: true,
|
||||||
|
mobile: true,
|
||||||
|
fullName: true,
|
||||||
|
memberships: {
|
||||||
|
where: { organizationId: actor.organizationId, isActive: true },
|
||||||
|
select: { role: true },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!target?.memberships[0]) {
|
||||||
|
throw new NotFoundException('کاربر در این محیط پیدا نشد.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = target.memberships[0].role as AuthUserDto['role'];
|
||||||
|
const subscription = await this.billing.requireActiveForOrganization(
|
||||||
|
actor.organizationId,
|
||||||
|
);
|
||||||
|
const accessToken = this.jwt.sign({
|
||||||
|
sub: target.id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
role,
|
||||||
|
impersonatorUserId: ownerId,
|
||||||
|
viewAsReadOnly: true,
|
||||||
|
});
|
||||||
|
const ownerUser = await this.prisma.user.findUnique({
|
||||||
|
where: { id: ownerId },
|
||||||
|
select: { fullName: true },
|
||||||
|
});
|
||||||
|
const userDto = await this.toAuthUserDto(
|
||||||
|
{ ...target, role, organizationId: actor.organizationId },
|
||||||
|
actor.organizationId,
|
||||||
|
subscription,
|
||||||
|
{
|
||||||
|
userId: target.id,
|
||||||
|
role,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
impersonatorUserId: ownerId,
|
||||||
|
impersonatorRole: 'owner',
|
||||||
|
viewAsReadOnly: true,
|
||||||
|
},
|
||||||
|
ownerUser?.fullName ?? 'مالک',
|
||||||
|
);
|
||||||
|
return { accessToken, user: userDto };
|
||||||
|
}
|
||||||
|
|
||||||
|
async setPriorLens(
|
||||||
|
userId: string,
|
||||||
|
organizationId: string,
|
||||||
|
lens: 'current' | 'archive',
|
||||||
|
actor?: Actor,
|
||||||
|
): Promise<AuthUserDto> {
|
||||||
|
const membership = await this.prisma.membership.findFirst({
|
||||||
|
where: { userId, organizationId, isActive: true },
|
||||||
|
include: { organization: { select: { enabledModules: true } } },
|
||||||
|
});
|
||||||
|
if (!membership?.priorArchiveEnabled) {
|
||||||
|
throw new ForbiddenException('بایگانی اطلاعات قبل برای شما فعال نیست');
|
||||||
|
}
|
||||||
|
const modules = this.billing.normalizeModules(membership.organization.enabledModules);
|
||||||
|
if (!modules.includes('prior_data_archive')) {
|
||||||
|
throw new ForbiddenException('بایگانی اطلاعات قبل برای این محیط فعال نیست');
|
||||||
|
}
|
||||||
|
await this.prisma.membership.update({
|
||||||
|
where: { id: membership.id },
|
||||||
|
data: { priorArchiveLens: lens },
|
||||||
|
});
|
||||||
|
return this.me(userId, organizationId, actor);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateMe(userId: string, organizationId: string, dto: UpdateProfileDto): Promise<AuthUserDto> {
|
async updateMe(userId: string, organizationId: string, dto: UpdateProfileDto): Promise<AuthUserDto> {
|
||||||
@@ -545,16 +673,20 @@ export class AuthService {
|
|||||||
selectionToken: string,
|
selectionToken: string,
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
): Promise<LoginResponse> {
|
): Promise<LoginResponse> {
|
||||||
let payload: { sub?: string; typ?: string };
|
let payload: { sub?: string; typ?: string; pwd?: boolean };
|
||||||
try {
|
try {
|
||||||
payload = this.jwt.verify<{ sub?: string; typ?: string }>(selectionToken);
|
payload = this.jwt.verify<{ sub?: string; typ?: string; pwd?: boolean }>(
|
||||||
|
selectionToken,
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
throw new UnauthorizedException('نشست انتخاب محیط منقضی شده است');
|
throw new UnauthorizedException('نشست انتخاب محیط منقضی شده است');
|
||||||
}
|
}
|
||||||
if (payload.typ !== 'org-select' || !payload.sub) {
|
if (payload.typ !== 'org-select' || !payload.sub) {
|
||||||
throw new UnauthorizedException('توکن انتخاب محیط نامعتبر است');
|
throw new UnauthorizedException('توکن انتخاب محیط نامعتبر است');
|
||||||
}
|
}
|
||||||
return this.issueLogin(payload.sub, organizationId);
|
return this.issueLogin(payload.sub, organizationId, {
|
||||||
|
fromPassword: payload.pwd === true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async switchOrganization(
|
async switchOrganization(
|
||||||
@@ -564,29 +696,58 @@ export class AuthService {
|
|||||||
return this.issueLogin(userId, organizationId);
|
return this.issueLogin(userId, organizationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async finishLogin(userId: string): Promise<LoginResult> {
|
private async finishLogin(
|
||||||
|
userId: string,
|
||||||
|
opts?: { fromPassword?: boolean },
|
||||||
|
): Promise<LoginResult> {
|
||||||
const rows = await this.memberships.listActive(userId);
|
const rows = await this.memberships.listActive(userId);
|
||||||
if (!rows.length) {
|
if (!rows.length) {
|
||||||
throw new UnauthorizedException('به هیچ محیطی دسترسی ندارید');
|
throw new UnauthorizedException('به هیچ محیطی دسترسی ندارید');
|
||||||
}
|
}
|
||||||
if (rows.length === 1) {
|
const usable = opts?.fromPassword
|
||||||
return this.issueLogin(userId, rows[0]!.organization.id);
|
? rows.filter((row) => !row.loginOtpOnly)
|
||||||
|
: rows;
|
||||||
|
if (!usable.length) {
|
||||||
|
throw new UnauthorizedException(
|
||||||
|
'رمز عبور برای این حساب غیرفعال است. مدیر ورود را روی «ورود با کد» گذاشته؛ از تب ورود با کد (پیامک) وارد شوید.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (usable.length === 1) {
|
||||||
|
return this.issueLogin(userId, usable[0]!.organization.id, {
|
||||||
|
fromPassword: opts?.fromPassword,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
requiresOrganizationChoice: true,
|
requiresOrganizationChoice: true,
|
||||||
selectionToken: this.jwt.sign(
|
selectionToken: this.jwt.sign(
|
||||||
{ sub: userId, typ: 'org-select' },
|
{
|
||||||
|
sub: userId,
|
||||||
|
typ: 'org-select',
|
||||||
|
...(opts?.fromPassword ? { pwd: true } : {}),
|
||||||
|
},
|
||||||
{ expiresIn: '10m' },
|
{ expiresIn: '10m' },
|
||||||
),
|
),
|
||||||
organizations: this.memberships.toChoices(rows),
|
organizations: this.memberships.toChoices(usable),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async issueLogin(
|
private async issueLogin(
|
||||||
userId: string,
|
userId: string,
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
|
opts?: { skipLastLogin?: boolean; fromPassword?: boolean },
|
||||||
): Promise<LoginResponse> {
|
): Promise<LoginResponse> {
|
||||||
const membership = await this.memberships.requireActive(userId, organizationId);
|
const membership = await this.memberships.requireActive(userId, organizationId);
|
||||||
|
if (opts?.fromPassword) {
|
||||||
|
const gate = await this.prisma.membership.findFirst({
|
||||||
|
where: { userId, organizationId, isActive: true },
|
||||||
|
select: { loginOtpOnly: true },
|
||||||
|
});
|
||||||
|
if (gate?.loginOtpOnly) {
|
||||||
|
throw new UnauthorizedException(
|
||||||
|
'رمز عبور برای این حساب غیرفعال است. مدیر ورود را روی «ورود با کد» گذاشته؛ از تب ورود با کد (پیامک) وارد شوید.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (!user || user.isActive === false) {
|
if (!user || user.isActive === false) {
|
||||||
throw new UnauthorizedException('حساب کاربری غیرفعال است');
|
throw new UnauthorizedException('حساب کاربری غیرفعال است');
|
||||||
@@ -594,15 +755,21 @@ export class AuthService {
|
|||||||
const subscription = await this.billing.requireActiveForOrganization(
|
const subscription = await this.billing.requireActiveForOrganization(
|
||||||
organizationId,
|
organizationId,
|
||||||
);
|
);
|
||||||
|
if (!opts?.skipLastLogin) {
|
||||||
|
await this.attendance.assertLoginAllowed(organizationId, userId);
|
||||||
|
}
|
||||||
await this.memberships.syncUserLastOrg(
|
await this.memberships.syncUserLastOrg(
|
||||||
userId,
|
userId,
|
||||||
organizationId,
|
organizationId,
|
||||||
membership.role,
|
membership.role,
|
||||||
);
|
);
|
||||||
await this.prisma.user.update({
|
if (!opts?.skipLastLogin) {
|
||||||
where: { id: userId },
|
await this.prisma.user.update({
|
||||||
data: { lastLoginAt: new Date() },
|
where: { id: userId },
|
||||||
});
|
data: { lastLoginAt: new Date() },
|
||||||
|
});
|
||||||
|
await this.attendance.recordLogin(organizationId, userId, membership.role);
|
||||||
|
}
|
||||||
const accessToken = this.jwt.sign({
|
const accessToken = this.jwt.sign({
|
||||||
sub: userId,
|
sub: userId,
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -629,11 +796,16 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
subscription?: SubscriptionSummaryDto | null,
|
subscription?: SubscriptionSummaryDto | null,
|
||||||
|
actor?: Actor,
|
||||||
|
impersonatorFullName?: string,
|
||||||
): Promise<AuthUserDto> {
|
): Promise<AuthUserDto> {
|
||||||
const membership = await this.prisma.membership.findFirst({
|
const membership = await this.prisma.membership.findFirst({
|
||||||
where: { userId: user.id, organizationId, isActive: true },
|
where: { userId: user.id, organizationId, isActive: true },
|
||||||
include: {
|
include: {
|
||||||
organization: { select: { name: true, enabledModules: true } },
|
organization: {
|
||||||
|
select: { name: true, enabledModules: true, priorArchiveEnabledAt: true },
|
||||||
|
},
|
||||||
|
orgRole: { select: { permissions: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const role = membership?.role ?? user.role;
|
const role = membership?.role ?? user.role;
|
||||||
@@ -641,6 +813,14 @@ export class AuthService {
|
|||||||
const sub =
|
const sub =
|
||||||
subscription ??
|
subscription ??
|
||||||
(await this.billing.requireActiveForOrganization(organizationId));
|
(await this.billing.requireActiveForOrganization(organizationId));
|
||||||
|
const viewAs =
|
||||||
|
actor?.viewAsReadOnly && actor.impersonatorUserId
|
||||||
|
? {
|
||||||
|
impersonatorId: actor.impersonatorUserId,
|
||||||
|
impersonatorFullName: impersonatorFullName?.trim() || 'مالک',
|
||||||
|
canOpenTeamSettings: true,
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
return this.toAuthUser({
|
return this.toAuthUser({
|
||||||
...user,
|
...user,
|
||||||
role,
|
role,
|
||||||
@@ -652,9 +832,31 @@ export class AuthService {
|
|||||||
),
|
),
|
||||||
subscription: sub,
|
subscription: sub,
|
||||||
isOrgOwner: role === 'owner',
|
isOrgOwner: role === 'owner',
|
||||||
|
priorArchive: this.priorArchiveFor(membership),
|
||||||
|
permissions: (Array.isArray(membership?.orgRole?.permissions)
|
||||||
|
? membership.orgRole.permissions.filter((item) => typeof item === 'string')
|
||||||
|
: []) as AuthUserDto['permissions'],
|
||||||
|
...(viewAs ? { viewAs } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private priorArchiveFor(
|
||||||
|
membership: {
|
||||||
|
priorArchiveEnabled?: boolean;
|
||||||
|
priorArchiveLens?: string;
|
||||||
|
organization?: { enabledModules?: string[]; priorArchiveEnabledAt?: Date | null };
|
||||||
|
} | null,
|
||||||
|
): AuthUserDto['priorArchive'] {
|
||||||
|
if (!membership?.priorArchiveEnabled) return undefined;
|
||||||
|
const modules = this.billing.normalizeModules(membership.organization?.enabledModules);
|
||||||
|
if (!modules.includes('prior_data_archive')) return undefined;
|
||||||
|
const orgCutoff = membership.organization?.priorArchiveEnabledAt ?? null;
|
||||||
|
return {
|
||||||
|
lens: membership.priorArchiveLens === 'archive' ? 'archive' : 'current',
|
||||||
|
cutoffAt: orgCutoff ? orgCutoff.toISOString() : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private async throttleChallenges(
|
private async throttleChallenges(
|
||||||
kind: string,
|
kind: string,
|
||||||
email: string | null | undefined,
|
email: string | null | undefined,
|
||||||
@@ -708,9 +910,10 @@ export class AuthService {
|
|||||||
mobile: string,
|
mobile: string,
|
||||||
code: string,
|
code: string,
|
||||||
returnOtp: boolean,
|
returnOtp: boolean,
|
||||||
|
organizationId: string | null,
|
||||||
) {
|
) {
|
||||||
if (this.sms.isConfigured()) {
|
if (this.sms.isConfigured() || organizationId) {
|
||||||
const sent = await this.sms.sendOtpSms(mobile, code);
|
const sent = await this.sms.sendOtp(organizationId, mobile, code);
|
||||||
if (!sent && !returnOtp) {
|
if (!sent && !returnOtp) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'ارسال پیامک ناموفق بود؛ کمی بعد دوباره تلاش کنید',
|
'ارسال پیامک ناموفق بود؛ کمی بعد دوباره تلاش کنید',
|
||||||
@@ -739,6 +942,9 @@ export class AuthService {
|
|||||||
enabledModules?: OrgModuleKey[];
|
enabledModules?: OrgModuleKey[];
|
||||||
subscription?: SubscriptionSummaryDto | null;
|
subscription?: SubscriptionSummaryDto | null;
|
||||||
isOrgOwner?: boolean;
|
isOrgOwner?: boolean;
|
||||||
|
priorArchive?: AuthUserDto['priorArchive'];
|
||||||
|
viewAs?: AuthUserDto['viewAs'];
|
||||||
|
permissions?: AuthUserDto['permissions'];
|
||||||
}): AuthUserDto {
|
}): AuthUserDto {
|
||||||
return {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
@@ -752,6 +958,9 @@ export class AuthService {
|
|||||||
...(user.enabledModules ? { enabledModules: user.enabledModules } : {}),
|
...(user.enabledModules ? { enabledModules: user.enabledModules } : {}),
|
||||||
...(user.subscription ? { subscription: user.subscription } : {}),
|
...(user.subscription ? { subscription: user.subscription } : {}),
|
||||||
...(user.isOrgOwner !== undefined ? { isOrgOwner: user.isOrgOwner } : {}),
|
...(user.isOrgOwner !== undefined ? { isOrgOwner: user.isOrgOwner } : {}),
|
||||||
|
...(user.priorArchive ? { priorArchive: user.priorArchive } : {}),
|
||||||
|
...(user.viewAs ? { viewAs: user.viewAs } : {}),
|
||||||
|
...(user.permissions ? { permissions: user.permissions } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,26 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { PassportStrategy } from '@nestjs/passport';
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
import type { DataVisibility } from '@mento/shared';
|
||||||
import { BillingService } from '../billing/billing.service';
|
import { BillingService } from '../billing/billing.service';
|
||||||
|
import {
|
||||||
|
resolveAllSectionAccess,
|
||||||
|
sectionNeedsTeamPeers,
|
||||||
|
} from '../common/data-access';
|
||||||
|
import {
|
||||||
|
type Actor,
|
||||||
|
normalizeDataVisibility,
|
||||||
|
parseVisibilityScopes,
|
||||||
|
} from '../common/record-scope';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { DATA_SCOPES, canViewAllRecords } from '@mento/shared';
|
||||||
|
|
||||||
export type JwtPayload = {
|
export type JwtPayload = {
|
||||||
sub: string;
|
sub: string;
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
impersonatorUserId?: string;
|
||||||
|
viewAsReadOnly?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -25,7 +38,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 (
|
if (
|
||||||
payload.typ === 'portal' ||
|
payload.typ === 'portal' ||
|
||||||
payload.typ === 'org-select' ||
|
payload.typ === 'org-select' ||
|
||||||
@@ -36,6 +49,28 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
if (!payload.sub || !payload.organizationId) {
|
if (!payload.sub || !payload.organizationId) {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let impersonatorUserId: string | undefined;
|
||||||
|
let impersonatorRole: string | undefined;
|
||||||
|
const viewAsReadOnly = Boolean(payload.viewAsReadOnly && payload.impersonatorUserId);
|
||||||
|
if (viewAsReadOnly && payload.impersonatorUserId) {
|
||||||
|
const ownerMembership = await this.prisma.membership.findFirst({
|
||||||
|
where: {
|
||||||
|
userId: payload.impersonatorUserId,
|
||||||
|
organizationId: payload.organizationId,
|
||||||
|
isActive: true,
|
||||||
|
role: 'owner',
|
||||||
|
organization: { isActive: true },
|
||||||
|
},
|
||||||
|
select: { userId: true, role: true },
|
||||||
|
});
|
||||||
|
if (!ownerMembership) {
|
||||||
|
throw new UnauthorizedException();
|
||||||
|
}
|
||||||
|
impersonatorUserId = ownerMembership.userId;
|
||||||
|
impersonatorRole = ownerMembership.role;
|
||||||
|
}
|
||||||
|
|
||||||
const user = await this.prisma.user.findUnique({
|
const user = await this.prisma.user.findUnique({
|
||||||
where: { id: payload.sub },
|
where: { id: payload.sub },
|
||||||
select: { id: true, isActive: true },
|
select: { id: true, isActive: true },
|
||||||
@@ -50,16 +85,119 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
isActive: true,
|
isActive: true,
|
||||||
organization: { isActive: true },
|
organization: { isActive: true },
|
||||||
},
|
},
|
||||||
select: { organizationId: true, role: true },
|
select: {
|
||||||
|
organizationId: true,
|
||||||
|
role: true,
|
||||||
|
dataVisibility: true,
|
||||||
|
dataVisibilityScopes: true,
|
||||||
|
dataAccessOverride: true,
|
||||||
|
priorArchiveEnabled: true,
|
||||||
|
priorArchiveLens: true,
|
||||||
|
orgRole: { select: { dataAccessPolicy: true } },
|
||||||
|
organization: { select: { enabledModules: true, priorArchiveEnabledAt: true } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (!membership) {
|
if (!membership) {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
await this.billing.requireActiveForOrganization(membership.organizationId);
|
await this.billing.requireActiveForOrganization(membership.organizationId);
|
||||||
|
|
||||||
|
const dataVisibility = normalizeDataVisibility(membership.dataVisibility);
|
||||||
|
const scopeLevels = parseVisibilityScopes(membership.dataVisibilityScopes);
|
||||||
|
const elevatedRole = canViewAllRecords(membership.role);
|
||||||
|
|
||||||
|
let teamIds: string[] | undefined;
|
||||||
|
const resolve = async (level: DataVisibility): Promise<string[] | null> => {
|
||||||
|
if (elevatedRole || level === 'org') return null;
|
||||||
|
if (level === 'own') return [user.id];
|
||||||
|
teamIds ??= await this.teamPeerIds(membership.organizationId, user.id);
|
||||||
|
return teamIds;
|
||||||
|
};
|
||||||
|
|
||||||
|
const visibleUserIds = await resolve(dataVisibility);
|
||||||
|
const scopes: Actor['scopes'] = {};
|
||||||
|
if (!elevatedRole) {
|
||||||
|
for (const scope of DATA_SCOPES) {
|
||||||
|
const level = scopeLevels[scope];
|
||||||
|
if (!level || level === dataVisibility) continue;
|
||||||
|
scopes[scope] = { dataVisibility: level, visibleUserIds: await resolve(level) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deepAccess = resolveAllSectionAccess({
|
||||||
|
role: membership.role,
|
||||||
|
rolePolicy: membership.orgRole?.dataAccessPolicy,
|
||||||
|
override: membership.dataAccessOverride,
|
||||||
|
legacyVisibility: dataVisibility,
|
||||||
|
legacyScopes: scopeLevels,
|
||||||
|
});
|
||||||
|
const needsTeamPeers =
|
||||||
|
!elevatedRole &&
|
||||||
|
(sectionNeedsTeamPeers(deepAccess.customers) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.leads) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.sales) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.activities) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.notes) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.routines) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.projects) ||
|
||||||
|
sectionNeedsTeamPeers(deepAccess.tickets));
|
||||||
|
if (needsTeamPeers) {
|
||||||
|
teamIds ??= await this.teamPeerIds(membership.organizationId, user.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const modules = this.billing.normalizeModules(membership.organization.enabledModules);
|
||||||
|
const priorGranted =
|
||||||
|
modules.includes('prior_data_archive') && membership.priorArchiveEnabled;
|
||||||
|
const priorLens = membership.priorArchiveLens === 'archive' ? 'archive' : 'current';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
organizationId: membership.organizationId,
|
organizationId: membership.organizationId,
|
||||||
role: membership.role,
|
role: membership.role,
|
||||||
|
dataVisibility,
|
||||||
|
visibleUserIds,
|
||||||
|
scopes,
|
||||||
|
customersAccess: deepAccess.customers,
|
||||||
|
leadsAccess: deepAccess.leads,
|
||||||
|
salesAccess: deepAccess.sales,
|
||||||
|
activitiesAccess: deepAccess.activities,
|
||||||
|
notesAccess: deepAccess.notes,
|
||||||
|
routinesAccess: deepAccess.routines,
|
||||||
|
projectsAccess: deepAccess.projects,
|
||||||
|
ticketsAccess: deepAccess.tickets,
|
||||||
|
teamPeerIds: teamIds ?? (elevatedRole ? null : [user.id]),
|
||||||
|
priorLens: priorGranted ? priorLens : 'off',
|
||||||
|
priorCutoff:
|
||||||
|
priorGranted && membership.organization.priorArchiveEnabledAt
|
||||||
|
? membership.organization.priorArchiveEnabledAt
|
||||||
|
: null,
|
||||||
|
sessionStartedAt: payload.iat ? new Date(payload.iat * 1000) : new Date(),
|
||||||
|
...(viewAsReadOnly && impersonatorUserId
|
||||||
|
? {
|
||||||
|
impersonatorUserId,
|
||||||
|
impersonatorRole: impersonatorRole ?? 'owner',
|
||||||
|
viewAsReadOnly: true,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async teamPeerIds(organizationId: string, userId: string): Promise<string[]> {
|
||||||
|
const memberships = await this.prisma.teamMember.findMany({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
team: { organizationId },
|
||||||
|
},
|
||||||
|
select: { teamId: true },
|
||||||
|
});
|
||||||
|
if (!memberships.length) return [userId];
|
||||||
|
|
||||||
|
const peers = await this.prisma.teamMember.findMany({
|
||||||
|
where: {
|
||||||
|
teamId: { in: memberships.map((m) => m.teamId) },
|
||||||
|
},
|
||||||
|
select: { userId: true },
|
||||||
|
});
|
||||||
|
return [...new Set([userId, ...peers.map((p) => p.userId)])];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,26 +6,79 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
import type { UserRole } from '@mento/shared';
|
import type { UserRole } from '@mento/shared';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
import { ROLES_KEY } from './roles.decorator';
|
import { ROLES_KEY } from './roles.decorator';
|
||||||
|
|
||||||
|
const VIEW_AS_MESSAGE =
|
||||||
|
'در حالت مشاهده بهجای کاربر دیگر امکان تغییر وجود ندارد.';
|
||||||
|
|
||||||
|
/** خواندنهای صفحهٔ تیم وقتی مالک در حالت مشاهده است. */
|
||||||
|
function isTeamSettingsRead(method: string, url: string): boolean {
|
||||||
|
if (method.toUpperCase() !== 'GET') return false;
|
||||||
|
const path = (url.split('?')[0] || '').replace(/\/+$/, '');
|
||||||
|
return (
|
||||||
|
/\/users(\/|$)/.test(path) ||
|
||||||
|
/\/org-roles(\/|$)/.test(path) ||
|
||||||
|
/\/teams(\/|$)/.test(path) ||
|
||||||
|
/\/organizations\/current/.test(path)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isViewAsAllowedMutation(method: string, url: string): boolean {
|
||||||
|
const path = (url.split('?')[0] || '').replace(/\/+$/, '') || '/';
|
||||||
|
const m = method.toUpperCase();
|
||||||
|
if (m === 'POST' && (path.endsWith('/auth/view-as') || path.endsWith('/auth/view-as/stop'))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (m === 'PATCH' && path.endsWith('/auth/me/prior-archive')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class RolesGuard implements CanActivate {
|
export class RolesGuard implements CanActivate {
|
||||||
constructor(private readonly reflector: Reflector) {}
|
constructor(private readonly reflector: Reflector) {}
|
||||||
|
|
||||||
canActivate(context: ExecutionContext): boolean {
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const request = context.switchToHttp().getRequest<{
|
||||||
|
user?: Actor;
|
||||||
|
method?: string;
|
||||||
|
originalUrl?: string;
|
||||||
|
url?: string;
|
||||||
|
}>();
|
||||||
|
const method = (request.method || 'GET').toUpperCase();
|
||||||
|
const url = request.originalUrl || request.url || '';
|
||||||
|
const actor = request.user;
|
||||||
|
|
||||||
|
if (
|
||||||
|
actor?.viewAsReadOnly &&
|
||||||
|
method !== 'GET' &&
|
||||||
|
method !== 'HEAD' &&
|
||||||
|
method !== 'OPTIONS' &&
|
||||||
|
!isViewAsAllowedMutation(method, url)
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(VIEW_AS_MESSAGE);
|
||||||
|
}
|
||||||
|
|
||||||
const roles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
const roles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||||||
context.getHandler(),
|
context.getHandler(),
|
||||||
context.getClass(),
|
context.getClass(),
|
||||||
]);
|
]);
|
||||||
if (!roles?.length) return true;
|
if (!roles?.length) return true;
|
||||||
|
|
||||||
const request = context.switchToHttp().getRequest<{
|
const role = actor?.role as UserRole | undefined;
|
||||||
user?: { role?: string };
|
if (role && roles.includes(role)) return true;
|
||||||
}>();
|
|
||||||
const role = request.user?.role as UserRole | undefined;
|
if (
|
||||||
if (!role || !roles.includes(role)) {
|
actor?.viewAsReadOnly &&
|
||||||
throw new ForbiddenException('دسترسی به این بخش برای نقش شما مجاز نیست');
|
actor.impersonatorRole === 'owner' &&
|
||||||
|
roles.includes('owner') &&
|
||||||
|
isTeamSettingsRead(method, url)
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
|
throw new ForbiddenException('دسترسی به این بخش برای نقش شما مجاز نیست');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
SetMetadata,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import type { RolePermissionKey } from '@mento/shared';
|
||||||
|
import { ROLE_PERMISSION_ITEMS } from '@mento/shared';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
const SECTION_PERMISSION_KEY = 'sectionPermission';
|
||||||
|
|
||||||
|
type SectionPermissionMeta = {
|
||||||
|
key: RolePermissionKey;
|
||||||
|
/** true: خواندن هم مجوز میخواهد. false: فقط مدیریت (ثبت/ویرایش/حذف/ورود/خروجی) */
|
||||||
|
reads: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* مجوز «بخش» از نقش سازمانی. مالک و مدیر همیشه مجازند.
|
||||||
|
* پیشفرض فقط مدیریت را میبندد تا انتخاب رکورد در فرمهای بخشهای دیگر کار کند.
|
||||||
|
*/
|
||||||
|
export const RequirePermission = (key: RolePermissionKey, opts?: { reads?: boolean }) =>
|
||||||
|
SetMetadata(SECTION_PERMISSION_KEY, { key, reads: opts?.reads ?? false } satisfies SectionPermissionMeta);
|
||||||
|
|
||||||
|
function isReadRequest(method: string, url: string): boolean {
|
||||||
|
if (method !== 'GET' && method !== 'HEAD') return false;
|
||||||
|
const path = (url.split('?')[0] || '').replace(/\/+$/, '');
|
||||||
|
return !path.endsWith('/export');
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SectionPermissionGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private readonly reflector: Reflector,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const meta = this.reflector.getAllAndOverride<SectionPermissionMeta | undefined>(
|
||||||
|
SECTION_PERMISSION_KEY,
|
||||||
|
[context.getHandler(), context.getClass()],
|
||||||
|
);
|
||||||
|
if (!meta) return true;
|
||||||
|
|
||||||
|
const req = context.switchToHttp().getRequest<{
|
||||||
|
user?: Actor;
|
||||||
|
method?: string;
|
||||||
|
originalUrl?: string;
|
||||||
|
url?: string;
|
||||||
|
}>();
|
||||||
|
const actor = req.user;
|
||||||
|
const label = ROLE_PERMISSION_ITEMS.find((item) => item.key === meta.key)?.label ?? meta.key;
|
||||||
|
if (!actor) throw new ForbiddenException(`دسترسی به «${label}» مجاز نیست.`);
|
||||||
|
if (actor.role === 'owner' || actor.role === 'admin') return true;
|
||||||
|
|
||||||
|
const method = (req.method || 'GET').toUpperCase();
|
||||||
|
if (!meta.reads && isReadRequest(method, req.originalUrl || req.url || '')) return true;
|
||||||
|
|
||||||
|
const membership = await this.prisma.membership.findFirst({
|
||||||
|
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
|
||||||
|
select: { orgRole: { select: { permissions: true } } },
|
||||||
|
});
|
||||||
|
const permissions = membership?.orgRole?.permissions ?? [];
|
||||||
|
if (!permissions.includes(meta.key)) {
|
||||||
|
throw new ForbiddenException(`دسترسی به «${label}» برای نقش شما مجاز نیست.`);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import {
|
||||||
|
CallHandler,
|
||||||
|
ExecutionContext,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { Observable } from 'rxjs';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
|
|
||||||
|
const VIEW_AS_MESSAGE =
|
||||||
|
'در حالت مشاهده بهجای کاربر دیگر امکان تغییر وجود ندارد.';
|
||||||
|
|
||||||
|
function normalizePath(url: string): string {
|
||||||
|
const path = (url.split('?')[0] || '').replace(/\/+$/, '') || '/';
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** مسیرهایی که در حالت مشاهده مجاز به تغییرند (خروج از مشاهده و لنز بایگانی). */
|
||||||
|
function isAllowedWhileViewing(method: string, url: string): boolean {
|
||||||
|
const path = normalizePath(url);
|
||||||
|
const m = method.toUpperCase();
|
||||||
|
if (m === 'POST' && (path.endsWith('/auth/view-as') || path.endsWith('/auth/view-as/stop'))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (m === 'PATCH' && path.endsWith('/auth/me/prior-archive')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ViewAsReadOnlyInterceptor implements NestInterceptor {
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
|
const req = context.switchToHttp().getRequest<Request & { user?: Actor }>();
|
||||||
|
const method = (req.method || 'GET').toUpperCase();
|
||||||
|
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
const actor = req.user;
|
||||||
|
if (!actor?.viewAsReadOnly) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
const url = req.originalUrl || req.url || '';
|
||||||
|
if (isAllowedWhileViewing(method, url)) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
throw new ForbiddenException(VIEW_AS_MESSAGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
export type FormFieldLabel = { key: string; label: string };
|
||||||
|
|
||||||
|
export type TemplateVars = {
|
||||||
|
title: string;
|
||||||
|
mobile?: string | null;
|
||||||
|
formName?: string | null;
|
||||||
|
formValues?: Record<string, unknown> | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** counter یکواحد افزایشیافته از AutomationCursor است (از ۱ شروع میشود) */
|
||||||
|
export function pickRoundRobin(memberIds: string[], counter: number): string | null {
|
||||||
|
const ids = [...new Set(memberIds.filter(Boolean))].sort();
|
||||||
|
if (!ids.length) return null;
|
||||||
|
const n = Math.max(1, Math.trunc(counter));
|
||||||
|
return ids[(n - 1) % ids.length] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** جایگزینی {{title}}، {{mobile}}، {{form}} و {{field.<key>}} */
|
||||||
|
export function renderAutomationTemplate(text: string, vars: TemplateVars): string {
|
||||||
|
return text.replace(/\{\{\s*([\w.\u0600-\u06FF-]+)\s*\}\}/g, (_m, name: string) => {
|
||||||
|
if (name === 'title') return vars.title ?? '';
|
||||||
|
if (name === 'mobile') return vars.mobile ?? '';
|
||||||
|
if (name === 'form') return vars.formName ?? '';
|
||||||
|
if (name.startsWith('field.')) {
|
||||||
|
const v = vars.formValues?.[name.slice(6)];
|
||||||
|
return v == null ? '' : String(v);
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFormAnswers(
|
||||||
|
fields: FormFieldLabel[] | null | undefined,
|
||||||
|
values: Record<string, unknown> | null | undefined,
|
||||||
|
): string {
|
||||||
|
if (!values) return '';
|
||||||
|
const lines: string[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const f of fields ?? []) {
|
||||||
|
seen.add(f.key);
|
||||||
|
const raw = values[f.key];
|
||||||
|
const v = raw == null ? '' : String(raw).trim();
|
||||||
|
if (v) lines.push(`${f.label}: ${v}`);
|
||||||
|
}
|
||||||
|
for (const [key, raw] of Object.entries(values)) {
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
const v = raw == null ? '' : String(raw).trim();
|
||||||
|
if (v) lines.push(`${key}: ${v}`);
|
||||||
|
}
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
@@ -2,14 +2,13 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
import { LoyaltyModule } from '../loyalty/loyalty.module';
|
import { LoyaltyModule } from '../loyalty/loyalty.module';
|
||||||
import { NotificationsModule } from '../notifications/notifications.module';
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
import { SmsService } from '../common/sms.service';
|
|
||||||
import { AutomationsController } from './automations.controller';
|
import { AutomationsController } from './automations.controller';
|
||||||
import { AutomationsService } from './automations.service';
|
import { AutomationsService } from './automations.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [AuthModule, NotificationsModule, LoyaltyModule],
|
imports: [AuthModule, NotificationsModule, LoyaltyModule],
|
||||||
controllers: [AutomationsController],
|
controllers: [AutomationsController],
|
||||||
providers: [AutomationsService, SmsService],
|
providers: [AutomationsService],
|
||||||
exports: [AutomationsService],
|
exports: [AutomationsService],
|
||||||
})
|
})
|
||||||
export class AutomationsModule {}
|
export class AutomationsModule {}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user