Author SHA1 Message Date
mahmood 0ca9540524 Fix change build level for test docker build
Build & Push Docker Image / build (push) Successful in 6m11s
2026-11-05 19:53:52 +03:30
mahmood dc691c5192 Preparation for MONSYS
Build & Push Docker Image / build (push) Failing after 7s
2026-11-05 19:48:41 +03:30
MahdiandCursor 1ef7f91771 fix(contacts): keep one customer when Tahesab repeats a mobile
A Tahesab import now updates the person who already has that mobile instead of creating another, and the boot merge runs once more so existing pairs collapse.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 13:34:41 +03:30
MahdiandCursor 94f0383c79 feat(tahesab): import and refresh customers at chosen hours
Each connection can set how many times a day and at which Tehran hours the server pulls Tahesab customers, including name updates for people already linked.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:31:27 +03:30
MahdiandCursor c976c0bcd6 fix(contacts): merge the same mobile stored on phone or mobile
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:27:05 +03:30
MahdiandCursor 57a0b379f6 fix(tahesab): store a matched mobile as 09xxxxxxxxx
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:11:40 +03:30
MahdiandCursor 7f6d9a84d6 fix(contacts): treat Iranian mobile formats as one person
Tahesab import still replaces the name and keeps the previous name.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 10:51:36 +03:30
MahdiandCursor 6abbf8e8fd fix(sms): keep the charge dialog fully on screen
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 21:52:35 +03:30
MahdiandCursor 39cb5c2548 feat(public-api): let external sites register a lead with their key
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 21:34:07 +03:30
MahdiandCursor 004d1dff93 feat(boards): ease dragging a card toward an off-screen spot
Scroll the column while a card is held near its edge and show a light gap where the card will land.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 20:05:50 +03:30
MahdiandCursor 78a7d6a68a feat(routines): let each person create a routine for themselves
Open the new-routine action to every member, while keeping assignment to other people and teams limited to managers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 19:34:36 +03:30
MahdiandCursor 5b18749005 feat(treasury): list debtors and creditors on the finance report
Show open receivable and payable balances on separate report tabs, and include each list in an Excel export.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 14:16:38 +03:30
MahdiandCursor 08a278e1c8 feat(treasury): number documents and manage categories on their tab
Save a system tracking number on each income and expense, reuse the full contact dialogs for a new party, and create, rename, or delete categories only from the categories tab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 13:11:09 +03:30
MahdiandCursor d71c2dbef4 feat(treasury): show who still owes on the finance pages
Partial receipts and payments stay tied to a customer, company, or user, and the open balance is listed on the income and expense screens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 11:36:55 +03:30
MahdiandCursor 1ccbefa7a3 fix(treasury): scope finance access and hide it when the module is off
Accounts can be edited, including the opening balance, and finance sections and accounts can be granted on a role or on one user. The finance menu stays hidden when the organization module is disabled.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 10:02:31 +03:30
MahdiandCursor 14f4e9d7d8 fix(activities): put the priority flag on the date row and recolor medium and low
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 21:32:49 +03:30
MahdiandCursor 52edccf74e fix(boards): keep card order inside a column and show activity priority
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 21:22:30 +03:30
MahdiandCursor bffe174162 fix(activities): show form photos in the note instead of the raw file link
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 17:30:45 +03:30
MahdiandCursor 35d74d33ed fix(activities): keep lead activity actions in the detail card
The action row stretched off-screen and comments on automation activities were rejected once the saved note passed 2000 characters.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 17:04:59 +03:30
MahdiandCursor c337b0b4c7 fix(leads): keep a future follow-up as an activity on the lead
A scheduled follow-up only stored a date, and activities opened from a lead were not linked back, so they disappeared from the lead.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 16:19:32 +03:30
MahdiandCursor c26353624e fix(leads): keep Persian digits when saving contact-form phones
Mixed Persian and Latin digits were stripped down to the Latin part, so some website leads stored a truncated mobile.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 15:50:05 +03:30
MahdiandCursor 534dae45b2 feat(roles): let each section decide who may assign work to others
Section access now only creates a record for yourself. Assigning it to a colleague requires a separate permission on that section.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 13:15:21 +03:30
MahdiandCursor 79733e6c96 feat(tahesab): sync filtered customers and pick Jalali periods
Document refresh can follow the selected group or person instead of every linked customer, and the sales report picks a named month or season.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 10:09:40 +03:30
MahdiandCursor fdabdc54a3 feat(billing): default the 7-day demo to 3 users
Applying or creating a trial plan sets the owner seat cap to 3, and existing demos without a cap get the same default.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 19:55:51 +03:30
MahdiandCursor 1b10ee30df fix(web): keep the sidebar org name inside the footer
Long organization names wrap beside the logout button instead of spilling out of the sidebar card.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 19:43:47 +03:30
MahdiandCursor c273dd6c58 feat(adm): split chat and billing settings and add a master login
Super admin can filter dashboard counts, edit or delete admins, and sign into a user's CRM account with one shared password.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 19:13:57 +03:30
MahdiandCursor acb5d51f24 feat(billing): cap active users on an owner subscription
Super admin can set a seat limit of 3, 10, 20, or a negotiated number so an owner cannot add users past that cap.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 18:33:51 +03:30
MahdiandCursor 06977d27ed feat(activities): attach voice and files on activity notes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 16:34:03 +03:30
MahdiandCursor 43437b0280 fix(test): pass the storage quota service into activity tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 15:47:32 +03:30
MahdiandCursor 28938e8f77 feat(billing): cap each owner's stored file volume
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 15:44:36 +03:30
MahdiandCursor e6e90aabf3 feat(activities): step through the same desk list from a detail
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 14:30:17 +03:30
MahdiandCursor a0936bf19f feat(web): assign an activity to a whole team
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 10:50:08 +03:30
MahdiandCursor 18a7cd3b5a fix(web): rename the activities nav item
The sidebar says فعالیت‌ها, and the phone tab stays فعالیت so the five-item bar still fits.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 22:45:34 +03:30
MahdiandCursor 4af248b06a feat(activities): filter the desk from each column
Assignees are searched instead of listed in full, and start time only filters whether a time is set.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 21:20:42 +03:30
MahdiandCursor d5dd13863a feat(web): add next Saturday and next week to postpone
Saturday is the start of the work week, so the sheet can defer a task to next Saturday morning or the same time one week later.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 21:20:15 +03:30
MahdiandCursor 81edf61065 feat(notes): let organizations edit the note category bar
The filter chips were fixed labels. Owners can rename, hide, reorder, and add categories.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 16:34:34 +03:30
MahdiandCursor 8e1e94a439 feat(notes): let organizations define their own note fields
The note form was fixed. Owners can add fields and each note keeps those values.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 15:38:05 +03:30
MahdiandCursor 590f8114cc fix(sms): send form confirmations to the lead number
Lead-only website forms had no person mobile, so the confirmation was marked sent without a number. Use the lead phone and send the full text.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 16:41:41 +03:30
MahdiandCursor 8d01bce0c2 fix(web): keep the activity desk usable on a phone
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 15:05:05 +03:30
MahdiandCursor 8b2777be4e fix(web): pack the activity desk header so the columns stay visible
The toolbar keeps every control, just on two shorter rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 13:57:01 +03:30
MahdiandCursor d7b5085096 feat(leads): keep gender on leads and form submissions
A lead can carry the same honorific as a person, and a form that asks gender writes it onto the lead.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 12:49:42 +03:30
MahdiandCursor cbc2e4ee8a fix(web): keep the Jalali picker above Ant modals
The date and time panel was opening behind the new-task dialog because its layer sat under the modal.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-31 10:16:02 +03:30
MahdiandCursor a17c7dbabc fix(routines): keep the daily desk for internal team work
Customer-linked tasks stay on their record and no longer appear in today, calendar, score, or reminders.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 20:53:26 +03:30
MahdiandCursor 99d686fefb fix(leads): give a new form lead the same owner as its first call
When a form has no round-robin assignees, the lead now follows the person the automation assigns to the first call.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 19:30:13 +03:30
MahdiandCursor b9bb2ff9fa feat(contacts): keep Tahesab honorifics with person gender
Male and female names can store the title when requested, and Tahesab import and export use the same gender.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 18:46:10 +03:30
MahdiandCursor 0d5e1034e5 feat(leads): edit lead-board columns from the board
New-lead counts follow the first open column instead of its name, and cards no longer show an initials mark.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 17:23:40 +03:30
MahdiandCursor 6f42440b3b fix(activities): return to the same group after opening a card
The back link dropped the board from the address, so the desk reopened on the default group.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 09:22:23 +03:30
MahdiandCursor 63a1803adc feat(activities): let a group show and limit its members
Empty membership stays open to the whole workspace; picking people restricts who can see that activity group.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 20:24:40 +03:30
MahdiandCursor 2cc2d358e4 fix(web): make kanban column titles readable
Widen board columns and keep counts inside the add button so stage and card titles have room.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 17:24:58 +03:30
MahdiandCursor 463a1652a6 feat(platform): text admins when an account opens or a subscription ends
Signup and admin-created accounts notify platform managers, and an ended plan sends one SMS instead of repeating for old expirations.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 22:27:05 +03:30
MahdiandCursor f15c5b9141 feat(activities): add photos when registering a follow-up comment
A later comment can attach photos with the same compressor, and they stay on the activity note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 21:52:37 +03:30
MahdiandCursor 1d3588a69d feat(activities): attach compressed photos to activity notes
Photos on an activity are shrunk with the form-builder compressor and stored only when they fit under 200KB.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 21:30:45 +03:30
MahdiandCursor 9812e4e5ba fix(crm): honor open data scopes and role assignees
Unset sections on a saved role policy were still filtered as own-only, so full lead access showed nothing. Activities can now be assigned by org role, and the Tahesab sales report reads as a result instead of a tag wall.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 18:07:42 +03:30
MahdiandCursor 8ae6a928f4 fix(web): type the customer group parent picker
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 11:14:30 +03:30
MahdiandCursor 2ff35e55fc feat(tahesab): net sales by factor, group, and commission
Report weight after returns for the selected period, with parent customer groups and separate silver and investment commission.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 11:05:34 +03:30
Mahdi 15f89aec04 Readjusting the dashboard header height 2026-10-25 20:53:06 +03:30
Mahdi bebd1be29b Adjusting the lead note and dashboard header height 2026-10-25 20:21:33 +03:30
MahdiandCursor 0daaef0b39 fix(web): calm hero flash, lead detail, and scope sources
Keep the dashboard backdrop out of flow on first paint, clamp long lead notes, scroll the quick-actions rail, return to the lead board, and only list import sources that exist in this environment.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 19:22:30 +03:30
MahdiandCursor 91637cb3a6 fix(web): search and multi-select data scope filters
Long group and source lists overflowed the team settings panel.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 10:48:15 +03:30
Mahdi 546a7a7e46 fix(web): keep jalali day cells inside calendar panel 2026-10-25 10:05:16 +03:30
Mahdi 48815852fc fix(crm): mesghal by metal, jalali fit, scoped group filters 2026-10-24 22:25:27 +03:30
Mahdi f8128ebe3a fix(tahesab): rename invoice timestamp label to زمان چاپ 2026-10-24 21:54:55 +03:30
MahdiandCursor 6ec7a1a942 fix(tahesab): label invoice timestamp as print date
Rename تاریخ ایجاد to تاریخ چاپ on the asnad invoice preview and PDF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 21:51:32 +03:30
MahdiandCursor 2d690b4c04 feat(tahesab): polish asnad invoice PDF and prior balance
Compute حساب قبل from asnad before this doc date/number, add in-app preview layout, and leave a blank mesghal line for handwriting after print.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 21:47:46 +03:30
Mahdi 1ba352f127 fix(tahesab): open invoice PDF window synchronously on click
Awaiting settings before window.open left a blank tab; open about:blank on click then fill via blob URL.
2026-10-24 14:09:46 +03:30
Mahdi f50246dc46 feat(tahesab): PDF invoice export for asnad cards
Add per-document PDF print from account details, plus org invoice settings for logo and texts separate from CRM invoices.
2026-10-24 12:34:02 +03:30
Mahdi 7d9fc8447f fix(reports): show Tahesab sales link only when connection exists
Require both the tahesab org module and at least one enabled accounting connection.
2026-10-24 09:39:45 +03:30
Mahdi 5be0bc6f5e fix(tahesab): register Ant components on sales report page
Without explicit imports the a-button tags rendered as raw custom elements with no styles or click behavior.
2026-10-22 20:35:21 +03:30
Mahdi 2ca2650b69 fix(tahesab): make sales report apply and sync actions fire
Bypass Ant form required validation that blocked the apply button, and surface API errors with toasts.
2026-10-22 20:04:59 +03:30
Mahdi 42b3fc72cc fix(tahesab): type sales report statistic value for vue-tsc 2026-10-22 19:52:11 +03:30
Mahdi 6d8ede8e2a fix(tahesab): polish sales report page chrome
Match leads/invoices header layout, keep title clean, and add a clear apply-filters action for the date range.
2026-10-22 19:47:58 +03:30
Mahdi ade43fea0f feat(tahesab): sales report snapshot with org-module gate
Sync linked asnad into CRM, filter by group/kind/metal, and require the tahesab superadmin module plus reports role access.
2026-10-22 18:20:46 +03:30
Mahdi 65cf4e9a66 feat(auth): allow owner to force OTP-only login per user
Team menu «ورود با کد» blocks password login with a clear message and switches the login screen to OTP.
2026-10-22 15:43:24 +03:30
Mahdi 80fb5bf1bb feat(lead-forms): real file upload under 200KB and Jalali date
Public form file fields compress images or reject oversized files; dates use the full Jalali picker.
2026-10-22 14:28:42 +03:30
Mahdi 31f45a6a31 fix(acl): simplify data access UI to a single filter
Drop multi-rule OR/AND editing; one all-or-filter form per section with clear hints.
2026-10-22 13:13:59 +03:30
Mahdi 73c87b8be4 fix(acl): keep empty draft rules and clarify OR/AND hint
Empty rules were stripped on re-parse so Add rule looked broken; editor now keeps drafts until filled.
2026-10-22 12:18:05 +03:30
Mahdi 09a60b3b5a feat(acl): deep data access by section for roles and users
Role default + user override with OR rules; covers customers, leads, sales, activities, notes, routines, projects, and tickets.
2026-10-22 11:53:26 +03:30
MahdiandCursor cb5944e767 fix(finance): shared treasury layout so tab switches stop jumping
Keep title and nav mounted in TreasuryLayout with stable header height, and finish Ant form chrome (MoneyInput, Jalali) on finance pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 21:47:00 +03:30
Mahdi 23ae273232 feat(contacts): compact layout, mobile filter sheet and redesigned cards 2026-10-21 20:01:16 +03:30
Mahdi 1c2da34983 fix: persist and re-apply contact saved filters correctly 2026-10-21 18:46:12 +03:30
Mahdi 50d7cad66e feat: multi-select contacts filter panel for groups sources and mood 2026-10-21 18:07:21 +03:30
Mahdi 29d99cbded feat: customer groups for people and companies with tahesab group sync and bulk register
Multiple groups per contact, legacy group text migrated, excel import/export, contacts filter and column, richer create-in-tahesab, match-first bulk export
2026-10-21 17:16:31 +03:30
Mahdi ce27df20ca feat: compact logout-time cell and optional login block after logout time
Owners set the daily logout time in a modal and can block re-login until the next Tehran day.
2026-10-21 14:20:15 +03:30
Mahdi 7ae6a5837a feat: enforce role section permissions and add a leads permission
Unticking a section hides it from the menu, closes its routes and blocks its writes on the server; existing roles keep their current access via migration.
2026-10-21 13:45:16 +03:30
Mahdi 631a3267d1 fix: accept createIfMissing when converting a lead to a customer 2026-10-20 21:07:39 +03:30
Mahdi b731fe43aa fix: fold the activity board picker and its actions into one dropdown 2026-10-20 17:59:34 +03:30
Mahdi 15cbd62997 test: update promote-from-prior stage service mock for activity boards 2026-10-20 17:36:30 +03:30
Mahdi e6aa4c64f0 feat: group activities into boards with their own stages, like sales pipelines
Existing stages and activities move into a default board per environment; new activities pick a board in the form.
2026-10-20 17:23:27 +03:30
Mahdi 9127fa334b fix: stop birth dates from saving one day early in Tehran time 2026-10-20 15:20:47 +03:30
Mahdi 9a86f63f48 feat: let the Jalali date picker jump to any month or year from its title 2026-10-20 14:47:25 +03:30
Mahdi 29398a445b fix: validate activity, deal and lead assignees by active membership in the current environment 2026-10-20 14:47:08 +03:30
Mahdi bb8fd489de fix: let owners and admins change a user's role from the edit-user modal 2026-10-20 12:50:32 +03:30
Mahdi 86e9ee6c2c fix: treat Tahesab no-records as an empty customer list instead of a 502
Listing all customers no longer fails on the final empty code range, and importing a missing code no longer creates a placeholder person.
2026-10-20 12:26:20 +03:30
Mahdi adb63447ca fix: stop Tahesab imports from stealing links between shared-mobile customers
List all Tahesab customers in one paginated table with a page-size picker instead of 2000-code pages.
2026-10-20 12:00:11 +03:30
Mahdi c1b38e1737 feat: filter Tahesab sync results to customers not yet imported 2026-10-20 11:07:58 +03:30
Mahdi be7ae0a1d8 fix: keep the SMS credit chip pastel green when the balance is healthy 2026-10-20 10:25:38 +03:30
Mahdi bbbedc6059 fix: polish SMS header chip and add deposit info in adm panel
Tighten the wallet chip layout and let super-admins set charge deposit details shown in the header charge modal.
2026-10-19 21:47:17 +03:30
Mahdi f5d68d83fc feat: add per-org SMS wallet with adm panel and header credit
Bill all platform SMS (including OTP), allow negative balance with manual/auto cutoffs, and support own-panel bypass without wallet debit.
2026-10-19 15:55:48 +03:30
Mahdi f15ebb72ea fix: let only the owner set logout time and move the attendance tab 2026-10-19 13:54:09 +03:30
Mahdi 8590579605 feat: log staff sign-in and sign-out and force logout at a set time 2026-10-19 13:34:55 +03:30
Mahdi 3863c5e7d1 fix: hide role permissions for modules disabled in super admin 2026-10-19 12:20:52 +03:30
Mahdi e6f9876177 fix: keep the customers menu visible when the owner views as another user 2026-10-19 11:56:05 +03:30
MahdiandCursor fddf22d7fe fix: open the card menu from the three-dot button
Anchor the activity and deal menus to the button so they show beside the card.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 11:40:25 +03:30
MahdiandCursor ada9a1f21f fix: show activity board columns again
Give the kanban the remaining page height so the columns are no longer collapsed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 11:18:19 +03:30
MahdiandCursor 2f11105628 fix: keep customer profile tabs from overlapping on mobile
Let the tab row scroll sideways so long labels stay readable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 09:40:59 +03:30
MahdiandCursor 36eda8653e merge: bring Ant Design UI from dev into main
Keep the design refresh together with DISC, the sales copilot, and treasury behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:33:56 +03:30
MahdiandCursor 8fdd5147a5 feat(web): migrate finance treasury pages to Ant Design Vue
Replace legacy Ui* chrome on treasury routes with Ant layout, and polish mobile incomes stats colors plus nav visibility.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:06:18 +03:30
MahdiandCursor 002f697dfe feat: add DISC profiles and a sales copilot as an org module
Help reps capture a customer's likely behavior style and get negotiation guidance, with the feature gated from super admin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:04:26 +03:30
MahdiandCursor 96befd3867 feat: add treasury audit, attachment download, and installment SMS
Let cheque clearance pick a cash account and export income, expense, and installment lists to Excel.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:59:24 +03:30
MahdiandCursor b25b5b125a fix(web): resolve vue-tsc errors blocking push of Ant migration
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:48:16 +03:30
MahdiandCursor 4abab55a6b feat(web): migrate CRM screens to Ant Design Vue with central theme
Adopt ant-design-vue and a shared antdTheme for leads, pipeline, invoices, and shared form controls under strict single-page governance.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:39:59 +03:30
MahdiandCursor 8981a552fc feat: gate treasury as an org module and group money inputs
Link optional invoice and cheque settlements to cash accounts, and let superadmin enable the finance module per organization.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:33:09 +03:30
MahdiandCursor ab538b8304 feat: add internal finance ledger for accounts, claims, and payroll
Keep booked income and expense separate from cash balances, with installments, recurring items, and reports.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:49:49 +03:30
MahdiandCursor 61d17c5cea fix: persist the prior-archive cutoff date when the owner changes it
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:31:19 +03:30
MahdiandCursor 23f8da2c65 feat: log outbound SMS and show history in compose modal
Persist manual, campaign, and automation SMS; expose history APIs for people and leads.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 21:23:07 +03:30
MahdiandCursor 9325d879a5 docs: spec unified outbound SMS log in compose modal
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 21:16:08 +03:30
MahdiandCursor d62e004e90 feat: SMS campaigns for people or leads with filters and batching
Add audience tabs, province/city filters, select-all ids, dynamic SMS tokens, and 50-sized create/send chunks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 20:54:32 +03:30
MahdiandCursor 32c722f42a docs: spec SMS campaign people/leads tabs and batch send
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 20:47:48 +03:30
MahdiandCursor f7b07f6b7a feat: owner read-only view-as from team users table
Allow org owners to inspect any member's data scope via dual JWT; server blocks mutations and team page stays reachable for return.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 19:57:26 +03:30
MahdiandCursor 52c7306e78 fix(web): shorten prior-switch label to اطلاعات قبل
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 19:19:31 +03:30
MahdiandCursor 960e01938d fix(web): apply prior lens on user ProfileView timeline
Filter my-desk activities and deals by archive cutoff so current work stays clean.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 19:12:48 +03:30
MahdiandCursor 3fb5f32ac3 fix: align activity badge and person profile with prior lens
Count nav badge for desk=mine, always apply activity prior filter on person records, and stop loading prior=all deals on profiles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 18:56:44 +03:30
MahdiandCursor 0ce2533066 fix(api): load multer types for avatar upload typecheck
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 18:08:31 +03:30
MahdiandCursor bc68582fe2 Fix prior archive filter collisions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:49:51 +03:30
MahdiandCursor e86841fc60 feat(web): add prior archive promote actions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:28:57 +03:30
MahdiandCursor 5069647f79 Add prior archive team settings UI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:20:28 +03:30
MahdiandCursor 008733d338 Add prior promotion endpoints
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:13:01 +03:30
Mahdi c5708ed59b chore: stop tracking local SDD scratch files 2026-10-17 17:03:23 +03:30
MahdiandCursor 65d66bb331 Implement prior archive cutoff API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:01:52 +03:30
MahdiandCursor 79ba146118 Wire prior archive cutoff through API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:52:20 +03:30
MahdiandCursor 02841a5b8c refactor(api): cutoff-based prior-archive where helpers
Replace didar/live-deal filters with createdAt cutoff and promotedFromPriorAt; add unit tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:33:32 +03:30
Mahdi a04743c6df feat: add prior-archive promote fields and shared cutoff DTOs 2026-10-17 16:27:29 +03:30
MahdiandCursor 27635c0752 docs: add prior-archive cutoff plan and ignore worktrees
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:07:59 +03:30
MahdiandCursor 03e1c01023 docs: specify date-cutoff prior archive and one-way promote
Replace Didar-source classification with org cutoff date, deals/activities-only filter, and a promote tag that does not mutate record fields.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 15:29:37 +03:30
MahdiandCursor 177e5cc31b fix: keep list menus on screen and clip long activity subtitles
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 13:26:11 +03:30
MahdiandCursor 2c7c943802 feat: allow bulk select and delete on activities and deal list
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 12:47:07 +03:30
MahdiandCursor 9611803567 feat: serve the same CRM on crm.montact.ir as an alias
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 23:24:50 +03:30
MahdiandCursor a494b5308e fix: make the user activity log readable and show Montact
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:18:56 +03:30
MahdiandCursor 582733e2ea fix: hide unlinked old activities from current work
Imported follow-ups with no person, company, or deal stayed on the board because only linked prior records were archived.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:02:01 +03:30
MahdiandCursor 6bff9d2888 fix: keep imported follow-ups out of current work
They stayed on the board when a non-prior deal was attached, even though the person was prior.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 12:34:40 +03:30
MahdiandCursor 6bc5e1bec7 feat: separate prior records behind an owner switch and count last-period questions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:48:30 +03:30
MahdiandCursor 3a8a684aa4 docs: lock the prior-data archive design for a later start
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 20:44:30 +03:30
MahdiandCursor 831c682eb3 feat: show the full work history and load every lead stage on the board
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 19:47:32 +03:30
MahdiandCursor 2cc81bb596 feat: keep deletions restorable and confirm a pipeline's deals before it is removed
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 22:23:09 +03:30
MahdiandCursor c04582072d fix: drop the unused button import that blocked the type check
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 21:08:14 +03:30
MahdiandCursor 42f0573a5f feat: send one SMS from a person or lead and keep the dashboard inside the phone frame
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 21:05:17 +03:30
MahdiandCursor 13ee70764b feat: show this month's birthdays and send a greeting SMS
Each owner sees their customers born this Jalali month and can text a custom greeting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 19:55:11 +03:30
MahdiandCursor cf326d1ed9 fix: keep birthdays and show Shamsi dates
Imported customers keep their birthday, and assistant text plus remaining calendars use the Jalali date.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 18:04:53 +03:30
MahdiandCursor 5f4cc47c41 fix: share the dashboard assistant and count leads from data
The hero ask box now uses the same confirm-before-create path as the assistant, count questions use real filters, and lead mobile, Jalali follow-ups, and rial labels stay consistent.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 14:45:29 +03:30
MahdiandCursor 0e420a443f fix: keep deal edits and right-align club leaderboard
Empty product lists were wiping the manual amount on update, and follow-ups were only created for new deals. Leaderboard rows were laid out left-to-right on an RTL page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 11:38:59 +03:30
MahdiandCursor 6b4bd0b03e fix(web): drop unused merge wizard props after preview load fix
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 22:02:56 +03:30
MahdiandCursor 910c7f51b0 fix(web): load pipeline merge preview when wizard opens
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 21:59:46 +03:30
MahdiandCursor 609ce3d006 rename pipeline settings hub card to تنظیمات مسیر فروش
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 21:46:04 +03:30
MahdiandCursor 9bed6cac03 fix(api): guard unmoved deals before pipeline merge delete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 21:32:21 +03:30
MahdiandCursor fd6e79c15d feat(web): pipeline merge wizard
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:55:14 +03:30
MahdiandCursor 9b42fec0a8 feat(web): pipeline settings page and nav entry
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:33:29 +03:30
MahdiandCursor d00f362376 feat(api): pipeline merge preview and merge endpoints
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:23:56 +03:30
MahdiandCursor fd8966e13f feat(pipelines): merge stage-map util and shared DTOs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:15:11 +03:30
MahdiandCursor 91eb9be1d4 docs: add pipeline merge implementation plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:10:03 +03:30
MahdiandCursor ffae63edbf docs: add pipeline merge design spec
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:07:09 +03:30
Mahdi cba4ad6a49 fix deal edit save; add new person from deal form; club and multi-select 2026-10-12 19:23:07 +03:30
Mahdi faac26d07d club home redesign; deal multi-select delete; anchored card menus 2026-10-12 17:59:07 +03:30
Mahdi a2b01f787e club home redesign; deal card menu anchored to button + delete 2026-10-12 14:54:32 +03:30
Mahdi 8af78047d9 club home redesign; deal card menu: delete with confirmation 2026-10-12 12:39:52 +03:30
Mahdi b43ed68e82 feat(automations): multi-option form-field conditions (all / any / none / exact) 2026-10-11 17:26:17 +03:30
Mahdi f4398cdb3e fix(web): mobile automation canvas/inspector, compact activity row, timestamped comments 2026-10-11 16:48:37 +03:30
Mahdi 17638786a8 feat(automations): parallel branch canvas, simple/advanced level per org, rules list UX 2026-10-11 14:48:12 +03:30
Mahdi b3b92abae9 feat(automations): form-driven branching rules, round-robin assignment, lead-linked activities 2026-10-11 14:12:36 +03:30
Mahdi b30f68563d docs: update user guide, roadmap and progress; comprehensive features catalog 2026-10-11 12:06:23 +03:30
Mahdi 51ca23b398 docs: update user guide, roadmap and progress; add comprehensive features catalog 2026-10-11 11:54:08 +03:30
MahdiandCursor 60d797f184 feat: باشگاه امتیازات کارکنان (موتور امتیاز، جدول رتبه، فروشگاه پاداش، نشان‌ها، پنل مدیریت و گزارش ROI)
- موتور رویدادمحور با شرط، محدودیت، تأیید مدیر و idempotency
- اتصال به لید، مشتری، معامله، فعالیت، روتین، پیش‌فاکتور، فاکتور و تیکت
- صفحه /club و /club/admin، اعلان زنده امتیاز، آیتم منو
- انتقال فرم‌ساز سرنخ به ابزارها

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-10 21:28:49 +03:30
Mahdi b87ebb22e0 Montify: robust pagination (beyond 50), endpoint diagnose button 2026-10-10 18:01:55 +03:30
Mahdi 792b3d29fa Montify: allow restarting stuck sync from UI; log sync progress 2026-10-10 17:11:51 +03:30
Mahdi 0802c2f436 Montify sync: save progress every 5 customers; skip endpoints returning 404, summarize instead of per-customer errors 2026-10-10 16:56:58 +03:30
Mahdi 37157620e2 Montify settings: send empty JSON body on sync (fix 400 null body) 2026-10-10 16:35:23 +03:30
Mahdi f27b4c264a Montify: mark sync running before responding; no 400 when already running 2026-10-10 16:18:25 +03:30
Mahdi e82bd2b2df Montify stores integration: multi-store connections, customer/order/transaction sync, webhooks 2026-10-10 15:59:12 +03:30
MahdiandCursor fa3fe0d364 Web: fix mobile overflow on activities, activity form, assets panel, routines, team/audit/API settings
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-10 11:58:45 +03:30
MahdiandCursor 4e26658092 e2e: public form test finds an active form itself; drop E2E_FORM_TOKEN
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 21:05:38 +03:30
MahdiandCursor 287f88abc0 e2e: public form test stays read-only and reports a wrong token clearly
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 20:49:55 +03:30
MahdiandCursor 09f05d4ecc e2e: fix ambiguous selector in Tahesab assets test
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 20:28:38 +03:30
MahdiandCursor 46a7693ea0 QA: unit tests for API logic, Playwright smoke tests, pre-push check, manual QA checklist
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 20:11:07 +03:30
MahdiandCursor e6755d0c2e Tahesab: show raw data from Tahesab, invoice-style document view with metal labels
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 13:49:54 +03:30
MahdiandCursor 2f3646d085 feat(ui): modals close only via Esc/X/cancel; standard 3:1 form cover processing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 15:23:14 +03:30
MahdiandCursor f5b6a47f3c feat(lead-forms): public form matches builder preview; live unsaved preview in new tab
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 14:25:52 +03:30
MahdiandCursor 678cb87de7 fix(lead-forms): multiline options, editable title, color palette, builder validation and unique new form names
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 13:49:27 +03:30
MahdiandCursor d683932d1b feat(forms): merge notes tab into main info for activity and deal forms; show activity hashtags
- Activity form: notes/tags card inline, live hashtag preview, focus notes when required
- Hashtags shown in activity detail (clickable search) and list rows; search accepts #tag
- Deal form: remove mobile tabs

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 13:17:29 +03:30
MahdiandCursor 13668c4ba4 feat(activities): split customer column, wider search, custom activity types with type-specific fields
- Table: separate assignee and customer columns; search by assignee and activity type
- ActivityTypeDef model with per-type field definitions (text, select, checklist, participants, ...)
- Default types incl. meeting subject/participants and task checklist; admins manage types
- Participants see activities in their lists and get notified

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 12:29:23 +03:30
MahdiandCursor aa2f39256a feat(activities): editable stages with tab and kanban views
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 11:18:53 +03:30
MahdiandCursor b4ffef9b6f rename: کاریز فروش → مسیر فروش, کاریز پروژه → تابلوی پروژه
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 20:51:50 +03:30
MahdiandCursor b3784818fc feat: routines module; super admin subscription badge, 7-day trial and lifetime plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 19:54:38 +03:30
Mahdi 3de2d0fa67 Deals import: imported pipelines keep only Didar stages; remove unused default stages 2026-10-06 16:58:25 +03:30
Mahdi 2a2728e5ee Deals Excel import/export aligned with Didar: browser-side import, new deal fields (code, probability, closedAt, creator, lostNote, referrer), Didar custom fields 2026-10-06 16:36:04 +03:30
Mahdi e08f1452ef Unified search algorithm across all lists; per-section record visibility (contacts, deals, activities, leads, finance, tickets, notes, projects) 2026-10-06 15:04:46 +03:30
Mahdi 43717392b2 Profile picture display has been standardized across the board. 2026-10-06 14:23:59 +03:30
Mahdi bc01384551 Fix error sending reminder SMS 2026-10-06 13:49:03 +03:30
Mahdi 5074c6d791 Add column visibility menu to activities and API keys tables, and make related person optional when creating an activity 2026-10-06 13:35:13 +03:30
Mahdi 0d7555f219 Fixing the error in today's task count 2026-10-06 12:44:09 +03:30
Mahdi f71f09c85d Align companies with the Didar export: new fields, Didar-format Excel import/export, and people linked to companies by Didar code 2026-10-06 12:25:20 +03:30
MahdiandCursor f88786ef61 Import Tahesab customers in batches with progress overlay and prefetched rows
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 21:08:38 +03:30
MahdiandCursor 46dcf296d3 Keep previous import source and code when a person is re-imported from another source
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 20:54:23 +03:30
MahdiandCursor c8753a4c4e Fix person profile more-menu opening twice
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 20:18:05 +03:30
MahdiandCursor 48de552f36 Add row selection, bulk delete, row numbers and page size picker to tables; redesign person profile header
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 20:00:21 +03:30
MahdiandCursor 71b3a7255a Polish activity person picker layout and move add-person action beside the label
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 18:19:37 +03:30
MahdiandCursor df8fac187e Improve assignee and person pickers with search, chips and inline person creation
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 17:49:17 +03:30
MahdiandCursor 3296b1c209 Remove BOM from user table preferences migration
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 11:59:59 +03:30
MahdiandCursor 23c83ffbee Add per-user saved column visibility for tables
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 11:56:49 +03:30
MahdiandCursor 75ff2c36c4 Allow editing org team member name, mobile, and password from settings.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 12:31:07 +03:30
MahdiandCursor 39e2eb24a6 Keep desktop modals open on outside click and allow larger group member lists.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 12:12:05 +03:30
MahdiandCursor 8b37525f2f Track person import source and previous names; add source report and edit UX.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 12:01:21 +03:30
MahdiandCursor e144b2277a Normalize chat uploads for montifyshop file-type whitelist to stop 400 errors.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 11:33:48 +03:30
MahdiandCursor 236f73de93 Paginate Tahesab customer list by code windows past the 5000 cap.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 11:09:40 +03:30
MahdiandCursor 60c16053a4 Support Didar activity Excel exports without header rows via positional columns.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 10:44:00 +03:30
MahdiandCursor cbfe470f33 Import large activity Excel in the browser via JSON chunks to avoid 502.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 18:28:47 +03:30
MahdiandCursor ac57b8ac33 Parse large Excel imports asynchronously to avoid gateway 502 timeouts.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 18:14:17 +03:30
MahdiandCursor d3fb92a5e2 Split large activity Excel prepare from chunk import and clarify errors.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 17:58:41 +03:30
MahdiandCursor 07bdc4a3b6 Show percent progress bar during long Excel imports.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 17:45:08 +03:30
MahdiandCursor c629729a9a Allow large activity Excel imports (40k+ rows) with bigger chunks and caches.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 17:42:11 +03:30
MahdiandCursor beae16437b Harden Tahesab HTTP client against keep-alive hangs and retry health on alt ports.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 17:02:14 +03:30
MahdiandCursor 17628722d3 Fix Tahesab health check to match Postman root-endpoint flow.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 16:45:04 +03:30
Mahdi c322a24424 Fixing the account balance entry error 2026-10-03 15:28:08 +03:30
Mahdi 2e315c9cfd Fixing the error when importing a large Excel file 2026-10-03 15:01:01 +03:30
Mahdi f8313c0ea5 Fixed error regarding the selection of multiple assignees and role sub-categories. 2026-10-03 13:27:16 +03:30
Mahdi 3b128bd980 Selection of multiple officials and role sub-categories 2026-10-03 13:16:13 +03:30
Mahdi 9f97371391 Fixed error when adding creation date and multiple addresses for contacts and leads. 2026-10-03 12:40:16 +03:30
Mahdi 1309da2281 Adding registration date and multiple addresses for contacts and leads. 2026-10-03 12:29:11 +03:30
Mahdi 989c03b381 Filtering tasks and assigning a person in charge during Excel import 2026-10-03 12:00:46 +03:30
Mahdi 5784b09232 Fixing Excel login error 2026-10-03 11:32:37 +03:30
Mahdi 5d5b3a3213 Implementing a link tracking and user click logging system.Implementing a link tracking and user click logging system. 2026-10-01 15:59:18 +03:30
Mahdi ae21d9bbc7 Addition of an AI chat assistant and a 100MB file upload limit. 2026-09-30 16:30:41 +03:30
Mahdi e94600a02e Adjusted the bold button, added italics, and fixed the broken emoji box. 2026-09-30 15:23:19 +03:30
Mahdi 75b83b7f1b Edit text and links, mute and unmute chat 2026-09-30 14:58:44 +03:30
Mahdi d3986da28b Editing applyTypingFromServer & clearTypingForRoom 2026-09-30 14:22:07 +03:30
Mahdi c7a60c524d Editing correction (in progress) 2026-09-30 13:01:42 +03:30
Mahdi 3c0ed3369e Editing and error correction (in progress) 2026-09-30 12:43:19 +03:30
Mahdi a3ed6187e9 Edit typing... indicator, loading older message. 2026-09-30 12:20:49 +03:30
Mahdi e1d456ad11 Adding the typing... indicator, loading older messages, and managing members/admins after creation. 2026-09-30 11:53:04 +03:30
Mahdi b978708487 Added message-to-activity conversion and edited the colleague selection modal. 2026-09-30 11:24:58 +03:30
Mahdi 4c8731122b Add channel to conversation 2026-09-30 11:08:33 +03:30
Mahdi f71e78f3a7 Add mentions, pin messages and conversations, and search within chats 2026-09-30 10:40:29 +03:30
Mahdi 7c4b24fad6 Wrapping to the next line in mobile view 2026-09-30 10:04:54 +03:30
Mahdi e6fb5c3700 Fixing the pop-up error and enabling the ability to reply to messages. 2026-09-30 09:41:49 +03:30
Mahdi 298b3316b4 Fixed message deletion error and layout changes for the message input box. 2026-09-30 09:19:36 +03:30
Mahdi 58e89246d9 Fix chat filter typescript error 2026-09-29 21:54:54 +03:30
Mahdi 5bb8e68521 Fixing the issue with complete deletion from the database 2026-09-29 21:46:41 +03:30
Mahdi 88dc7c5a1c Fixing the complete removal 2026-09-29 21:36:31 +03:30
Mahdi 83504816c5 Add, edit, delete, and resend messages. 2026-09-29 21:26:07 +03:30
Mahdi c20dc0a7ca Aligning the chat bar with Telegram 2026-09-29 21:06:04 +03:30
Mahdi e20b904bbe Fixing video retrieval error 2026-09-29 20:48:14 +03:30
Mahdi 7996fc7f73 Fixing the video-to-file conversion error and audio appearance changes. 2026-09-29 20:36:15 +03:30
Mahdi 70bcd15847 Convert video to file and change the appearance of mobile chat 2026-09-29 20:18:17 +03:30
Mahdi b0f05b6a27 Add file & video & voice in chat Crm 2026-09-29 17:22:34 +03:30
Mahdi d4972891f1 Updating ConversationsView wiring and the nav badge next. 2026-09-29 16:22:37 +03:30
Mahdi 032eb70524 Edit BadGatewayException 2026-09-29 15:27:14 +03:30
Mahdi 2309e2c5ab Edit ExcelImportFlow 2026-09-29 14:57:10 +03:30
Mahdi 66af7e577c Chat settings in Super Admin and changing the chat title and position. 2026-09-29 14:45:19 +03:30
Mahdi 125976f3eb Refining the CRM chat interface 2026-09-29 11:56:32 +03:30
Mahdi 0670067e7f Add conversations settings link to settings hub menu. 2026-09-29 11:34:31 +03:30
MahdiandCursor a1655432fc Add internal org chat (phase 1) with DM, groups, and org settings.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 10:34:01 +03:30
Mahdi 589c763ef8 Polish desktop sidebar branding and tighten automation rules card.
Move profile and collapse control, show org even for one workspace, and center rules labels in the toolbar-height card.
2026-09-28 17:35:03 +03:30
Mahdi d2c82f2115 Restore Persian UTF-8 labels in shared package.
Undo double-encoding mojibake so automation and other UI strings render correctly.
2026-09-28 16:18:54 +03:30
MahdiandCursor 319493171f Polish lead form builder header and settings layout.
Use shared UiPageHeader back control, align ready-field chips with the toolbox, and organize CRM settings into clearer mobile/desktop cards.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 14:29:57 +03:30
Mahdi f20206b045 Connect public lead forms to CRM Leads on submit. 2026-09-28 13:39:44 +03:30
Mahdi 32e27d45f7 Add desk-style task workflow on Activities and Project boards.
Managers can switch my desk vs team, reassign activities, and filter project cards to their work; assignees can see and move cards.
2026-09-28 12:28:14 +03:30
Mahdi 8effd4cbc6 Improve Leads mobile UX and nest leads under Customers nav.
Restore the 5-tab mobile bar, add responsive lead cards with long-press select, and fix stats/filters layout.
2026-09-28 11:50:44 +03:30
Mahdi 7e73ba9936 Fix web build failure from corrupted Tahesab status types.
Restore MandehValueDto status encoding and derive بس/بد labels from amount.
2026-09-27 21:26:56 +03:30
Mahdi 647503810d Add lead company logos and refine Leads stats cards.
Leads can upload/change/remove a logo shown in the list; stats use fixed stage labels with accurate non-archived counts.
2026-09-27 21:17:42 +03:30
Mahdi ec5c7639e3 Match Leads stats cards to the mockup and fix Contacts double menus.
Stage summary uses the green total card plus paired/solo white cells; people row menus use separate mobile/desktop keys.
2026-09-27 20:35:57 +03:30
Mahdi 3833788aa8 Fix Leads row menu overflow and add edit/delete actions.
Use a teleported dropdown so the menu stays above the table, with edit modal and archive delete.
2026-09-27 20:18:44 +03:30
Mahdi 9edbb92b13 Align Leads header with Contacts and add phone-contact lead import.
Leads actions mirror people import/export, and create-lead can fill fields from device contacts like Person form.
2026-09-27 19:51:02 +03:30
Mahdi 05f205cadf Redesign Leads list to match the dashboard mockup.
Add stage stats cards, richer filters/table columns, create modal, and mockup-style pagination.
2026-09-27 18:22:35 +03:30
Mahdi ac3ffb8ab2 Promote Leads to a top-level nav hub and expire login OTP after 90s.
Leads items sit under their own hub after Customers; login OTP shows a countdown and returns to the mobile step when time runs out.
2026-09-27 18:00:59 +03:30
MahdiandCursor c079295ff4 Add standalone Leads module for prospect outreach before customers.
Import large Excel lists with duplicate checks, assign and kanban follow-up, convert to Person when ready; also fix OTP mobile mask order and SMS brand name to منتکت.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 17:05:11 +03:30
MahdiandCursor 22980e5152 Add Didar-style conversion rate to sales reports.
Show won-over-incoming deals for the selected period with time, user, and source breakdowns alongside the existing win-rate metric.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 15:36:34 +03:30
MahdiandCursor c5c903d4b4 Add automatic VoIP call summaries and sync progress checklist.
When a PBX webhook includes recordingUrl or transcript, queue STT and AI to create a call_result note; mark API, bulk SMS, WooCommerce, and VoIP as done and defer online payments.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 15:06:41 +03:30
Mahdi c06c92b333 Add deal co-assignees and saved filters on people/pipeline lists.
Deals keep a primary owner plus shared assignees with matching visibility; Contacts and Pipeline can save and reuse filter presets.
2026-09-27 14:25:32 +03:30
Mahdi 00f8b91d78 Add personal/team note visibility and edit history.
Notes can be marked personal or team, with revision snapshots and restore from the notes UI.
2026-09-27 13:19:08 +03:30
Mahdi 55a287563d Add simple report builder with metrics, dimensions, and user/team filters. 2026-09-27 11:54:23 +03:30
Mahdi a16c2f0a9b Add saved report views with personal/org filters and in-org share links. 2026-09-27 11:11:33 +03:30
Mahdi 6a9e864b07 Add deeper reports: stage conversion, period compare, and deal drill-down. 2026-09-27 10:39:09 +03:30
MahdiandCursor d133c8ca34 Add reservations module and rename teams visibility label to file-access level.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 09:38:17 +03:30
Mahdi db65b55660 Add VoIP webhook connector for call logging, notifications, and optional click-to-call; align brand to Montact. 2026-09-27 08:47:11 +03:30
Mahdi 26085b54a9 Add WooCommerce integration: sync orders to invoices/people with webhook, cron, and settings UI. 2026-09-26 17:59:16 +03:30
Mahdi 1b160c8cd3 Add named teams and per-user data visibility (own/team/org) with settings UI and org module. 2026-09-26 17:15:09 +03:30
Mahdi 499d13d1df Fix SMS campaigns people list 400 by capping limit at 100 and searching via API. 2026-09-26 16:39:11 +03:30
Mahdi ef600d149d Add public API keys, outbound webhooks, and bulk SMS campaigns with settings UI and org modules. 2026-09-26 16:12:29 +03:30
Mahdi ccddd009e3 Edit Didar gap features: lost-reason report 2026-09-26 15:20:38 +03:30
Mahdi 6463275c3d Add Didar gap features: lost-reason reports, audit logs, tags, card assignees, and saved-views API.
Ignore Graphify local artifacts and expose new modules in superadmin.
2026-09-26 14:59:48 +03:30
Mahdi 35a618d0af Edit a modal for the assistant 2026-09-23 17:30:30 +03:30
Mahdi 011b316b5b Creating a modal for the assistant 2026-09-23 17:18:04 +03:30
Mahdi b7e3d1e290 Create a project workflow by typing to generate approval cards. 2026-09-23 16:32:41 +03:30
Mahdi 7dc4344e0e Creating a project workflow using a voice assistant and converting it into an approval card. 2026-09-23 15:49:44 +03:30
Mahdi 99df327ded Adding two fields to the mesh form 2026-09-23 14:41:16 +03:30
Mahdi 230d7b3bf6 AI-powered speech-to-text transformation 2026-09-23 13:58:43 +03:30
Mahdi 58c3e25db6 Correcting the speech-to-text output 2026-09-22 12:24:53 +03:30
Mahdi 75a73559b5 Modification of the structure 2026-09-22 12:04:35 +03:30
Mahdi 41f0025883 Modification of the STT structure 2026-09-22 11:56:16 +03:30
Mahdi 42db5919e1 Modification of the STT structure timeout 2026-09-22 11:37:59 +03:30
Mahdi d53136d91c Restructuring the STT structure 2026-09-22 11:30:07 +03:30
Mahdi dac0454e69 Restructuring STT 2026-09-22 11:16:17 +03:30
Mahdi 4b335aa7ff Refining the speech-to-text conversion structure 2026-09-22 11:02:08 +03:30
Mahdi 17fb33b3e7 Adding a task generated from the account balance to products 2026-09-21 21:25:34 +03:30
Mahdi be97a067f9 Edit: Add from Android phone contacts 2026-09-21 20:51:06 +03:30
Mahdi 9249302eac Edit from phone contacts 2026-09-21 20:26:19 +03:30
Mahdi 5d9a572ff8 Edit: Add from phone contacts 2026-09-21 20:04:18 +03:30
Mahdi f4cb41d96f Configure the AI assistant for more information. 2026-09-21 19:24:39 +03:30
Mahdi 7a58b9d469 Adding contacts from the phone to the customer list 2026-09-21 18:27:37 +03:30
Mahdi 1adc217375 Edit dashboard appearance 2026-09-21 17:55:05 +03:30
Mahdi d7d82102af Edit the artificial intelligence of the Mentact assistant 2026-09-21 16:58:49 +03:30
Mahdi f5a4eb577b Editing permissions in the CRM Super Admin 2026-09-21 16:38:24 +03:30
703 changed files with 138542 additions and 13861 deletions
+85
View File
@@ -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
+15
View File
@@ -0,0 +1,15 @@
.git
node_modules
**/dist
**/.env
**/.env.*
apps/stt/.venv
uploads
docs
e2e
test-results
playwright-report
graphify-out
.worktrees
*.md
crm-node_modules.tgz
+1 -1
View File
@@ -17,7 +17,7 @@ SMS_PASSWORD=
SMS_SENDER=
# SMS_BASE_URL=http://smspanel.Trez.ir
# SMS_SEND_PATH=/SendMessageWithCode.ashx
# SMS_OTP_TEMPLATE=کد ورود پرتال منتکت: {code}
# SMS_OTP_TEMPLATE=کد ورود منتکت: {code}
# SMS_TIMEOUT_MS=20000
# رمزنگاری توکن‌های اتصال حسابداری (ته‌حساب) — ۳۲ بایت به‌صورت hex (۶۴ کاراکتر)
+131
View File
@@ -0,0 +1,131 @@
name: Build & Push Docker Image
on:
push:
tags:
- "*"
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Start time
run: echo "BUILD_STARTED=$(date +%s)" >> "$GITHUB_ENV"
- name: Free disk space
id: prune
run: |
df -h / /workspace /var/lib/containerd 2>/dev/null || df -h /
docker builder prune -af || true
docker image prune -af || true
docker system prune -af --volumes || true
df -h / /workspace /var/lib/containerd 2>/dev/null || df -h /
- name: Checkout code
id: checkout
uses: actions/checkout@v4
- name: Resolve image tag
id: meta
run: |
if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
TAG="${GITHUB_REF_NAME}"
else
TAG="$(git rev-parse --short HEAD)"
fi
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "registry=dock.monsys.ir" >> "$GITHUB_OUTPUT"
- name: Build Docker images
id: build
run: |
set -eu
tag="${{ steps.meta.outputs.tag }}"
reg="${{ steps.meta.outputs.registry }}"
docker build -f Dockerfile.api -t "$reg/montact-api:$tag" -t "$reg/montact-api:latest" .
docker build -f Dockerfile.web -t "$reg/montact-web:$tag" -t "$reg/montact-web:latest" .
docker build -f Dockerfile.stt -t "$reg/montact-stt:$tag" -t "$reg/montact-stt:latest" .
# Registry login is unsolved. These two steps stay off so a tag run
# only proves the three images build. Remove `if: false` on both when
# dock.monsys.ir accepts the runner.
- name: Login to registry
id: login
if: false
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: |
USER_NAME="${REGISTRY_USERNAME:-admin}"
printf '%s\n' "$REGISTRY_PASSWORD" | docker login "dock.monsys.ir" -u "$USER_NAME" --password-stdin
- name: Push Docker images
id: push
if: false
run: |
set -eu
tag="${{ steps.meta.outputs.tag }}"
reg="${{ steps.meta.outputs.registry }}"
for name in montact-api montact-web montact-stt; do
docker push "$reg/$name:$tag"
docker push "$reg/$name:latest"
done
- name: Notify Bale
if: always()
continue-on-error: true
env:
BALE_TOKEN: ${{ secrets.BALE_BOT_TOKEN || vars.BALE_BOT_TOKEN }}
BALE_CHAT_ID: ${{ vars.BALE_CHAT_ID }}
TAG: ${{ steps.meta.outputs.tag }}
REG: ${{ steps.meta.outputs.registry }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
STEP_OUTCOMES: |
Checkout code=${{ steps.checkout.outcome }}
Resolve image tag=${{ steps.meta.outcome }}
Build Docker images=${{ steps.build.outcome }}
Login to registry=${{ steps.login.outcome }}
Push Docker images=${{ steps.push.outcome }}
run: |
if [ -z "$BALE_TOKEN" ] || [ -z "$BALE_CHAT_ID" ]; then
echo "BALE_BOT_TOKEN / BALE_CHAT_ID not set in Gitea — skipping notification"
exit 0
fi
failed_step=$(printf '%s\n' "$STEP_OUTCOMES" | grep -E '=(failure|cancelled)$' | head -n1 | cut -d= -f1)
if [ -n "$failed_step" ]; then
title="❌ بیلد ناموفق"
elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Push Docker images=success$'; then
title="✅ بیلد موفق"
elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Build Docker images=success$'; then
title="✅ بیلد موفق؛ پوش رجیستری هنوز خاموش است"
else
title="⚠️ بیلد کامل نشد"
fi
commit=$(git log -1 --pretty='%h — %s' 2>/dev/null || echo "${GITHUB_SHA:0:7}")
elapsed=$(( $(date +%s) - ${BUILD_STARTED:-$(date +%s)} ))
text="${title}
پروژه: ${GITHUB_REPOSITORY}
تگ: ${TAG:-${GITHUB_REF_NAME}}"
if [ -z "$failed_step" ] && [ -n "$TAG" ]; then
text="${text}
image: ${REG}/montact-api:${TAG}
image: ${REG}/montact-web:${TAG}
image: ${REG}/montact-stt:${TAG}"
fi
[ -n "$failed_step" ] && text="${text}
مرحلهٔ خطا: ${failed_step}"
text="${text}
کامیت: ${commit}
توسط: ${GITHUB_ACTOR}
مدت: $((elapsed / 60))m$((elapsed % 60))s
لاگ: ${RUN_URL}"
msg_file=$(mktemp)
printf '%s\n' "$text" | sed 's/^[[:space:]]*//' > "$msg_file"
curl -sS -m 20 -X POST "https://tapi.bale.ai/bot${BALE_TOKEN}/sendMessage" \
--data-urlencode "chat_id=${BALE_CHAT_ID}" \
--data-urlencode "text@${msg_file}"
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
# فعال‌سازی: npm install (اسکریپت prepare) یا git config core.hooksPath .githooks
npm run check
+15
View File
@@ -21,3 +21,18 @@ docs/~$*
*.py[cod]
apps/stt/.venv/
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/
+29
View File
@@ -0,0 +1,29 @@
# NestJS API + Prisma. Build context is the monorepo root.
FROM node:20-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/shared/package.json packages/shared/package.json
RUN npm ci
COPY apps/api apps/api
COPY packages/shared packages/shared
RUN npm run build -w @mento/shared \
&& npm run prisma:generate -w @mento/api \
&& npm run build -w @mento/api
FROM node:20-bookworm-slim
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends openssl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /app/package.json /app/package-lock.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/packages/shared ./packages/shared
COPY --from=build /app/apps/api/package.json ./apps/api/package.json
COPY --from=build /app/apps/api/dist ./apps/api/dist
COPY --from=build /app/apps/api/prisma ./apps/api/prisma
WORKDIR /app/apps/api
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "dist/src/main.js"]
+15
View File
@@ -0,0 +1,15 @@
# Local Faster-Whisper. Not published on Ingress.
FROM python:3.11-slim-bookworm
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY apps/stt/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY apps/stt/main.py ./main.py
ENV STT_MODEL=small \
STT_DEVICE=cpu \
STT_COMPUTE_TYPE=int8 \
HF_HOME=/models
EXPOSE 3040
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3040"]
+16
View File
@@ -0,0 +1,16 @@
# Vue panel. The built app calls /api on the same host; Traefik sends that to the API.
FROM node:20-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/shared/package.json packages/shared/package.json
RUN npm ci
COPY apps/web apps/web
COPY packages/shared packages/shared
RUN npm run build -w @mento/shared && npm run build -w @mento/web
FROM nginx:1.27-alpine
COPY docker/web.nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
EXPOSE 80
+1 -1
View File
@@ -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) ← فهرست کوتاه قابلیت‌ها
+3 -1
View File
@@ -10,7 +10,9 @@
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev",
"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 test/sales-factors.test.ts test/platform-admin-alert.test.ts test/person-name.test.ts"
},
"dependencies": {
"@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;
@@ -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 $$;
@@ -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;
@@ -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;
@@ -0,0 +1,14 @@
ALTER TABLE "CustomerGroup" ADD COLUMN IF NOT EXISTS "parentId" TEXT;
CREATE INDEX IF NOT EXISTS "CustomerGroup_parentId_idx" ON "CustomerGroup"("parentId");
DO $$ BEGIN
ALTER TABLE "CustomerGroup"
ADD CONSTRAINT "CustomerGroup_parentId_fkey"
FOREIGN KEY ("parentId") REFERENCES "CustomerGroup"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;
ALTER TABLE "AccountingAsnadLine" ADD COLUMN IF NOT EXISTS "darsad" DOUBLE PRECISION;
ALTER TABLE "AccountingAsnadLine" ADD COLUMN IF NOT EXISTS "darsadTalayee" DOUBLE PRECISION;
ALTER TABLE "AccountingAsnadLine" ADD COLUMN IF NOT EXISTS "maliatDarsad" DOUBLE PRECISION;
@@ -0,0 +1,32 @@
-- CreateTable
CREATE TABLE "ActivityImage" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"activityId" TEXT NOT NULL,
"fileName" TEXT NOT NULL,
"mimeType" TEXT NOT NULL,
"sizeBytes" INTEGER NOT NULL,
"storageKey" TEXT NOT NULL,
"uploadedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ActivityImage_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ActivityImage_activityId_createdAt_idx" ON "ActivityImage"("activityId", "createdAt");
-- CreateIndex
CREATE INDEX "ActivityImage_organizationId_idx" ON "ActivityImage"("organizationId");
-- CreateIndex
CREATE INDEX "ActivityImage_uploadedById_idx" ON "ActivityImage"("uploadedById");
-- AddForeignKey
ALTER TABLE "ActivityImage" ADD CONSTRAINT "ActivityImage_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ActivityImage" ADD CONSTRAINT "ActivityImage_activityId_fkey" FOREIGN KEY ("activityId") REFERENCES "Activity"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ActivityImage" ADD CONSTRAINT "ActivityImage_uploadedById_fkey" FOREIGN KEY ("uploadedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
-- پیامک پایان اشتراک فقط برای انقضاهای بعدی؛ حساب‌های قبلاً تمام‌شده دوباره خبر نمی‌دهند
ALTER TABLE "BillingAccount" ADD COLUMN "expiryNotifiedAt" TIMESTAMP(3);
UPDATE "BillingAccount"
SET "expiryNotifiedAt" = CURRENT_TIMESTAMP
WHERE "planCode" = 'lifetime'
OR "status" = 'expired'
OR "expiresAt" < CURRENT_TIMESTAMP;
@@ -0,0 +1,12 @@
CREATE TABLE "ActivityBoardMember" (
"boardId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "ActivityBoardMember_pkey" PRIMARY KEY ("boardId","userId")
);
CREATE INDEX "ActivityBoardMember_userId_idx" ON "ActivityBoardMember"("userId");
ALTER TABLE "ActivityBoardMember" ADD CONSTRAINT "ActivityBoardMember_boardId_fkey" FOREIGN KEY ("boardId") REFERENCES "ActivityBoard"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "ActivityBoardMember" ADD CONSTRAINT "ActivityBoardMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,22 @@
ALTER TABLE "Person" ADD COLUMN "gender" TEXT NOT NULL DEFAULT 'none';
ALTER TABLE "Person" ADD COLUMN "showGenderInName" BOOLEAN NOT NULL DEFAULT false;
-- نام‌هایی که از ته‌حساب با عنوان آمده‌اند؛ خود متن نام دست نمی‌خورد
UPDATE "Person"
SET "gender" = 'male', "showGenderInName" = true
WHERE regexp_replace(
regexp_replace(btrim("firstName" || ' ' || "lastName"), 'ي', 'ی', 'g'),
'ك',
'ک',
'g'
) ~ '^جناب[[:space:]]*آقای([[:space:]]|$)';
UPDATE "Person"
SET "gender" = 'female', "showGenderInName" = true
WHERE "gender" = 'none'
AND regexp_replace(
regexp_replace(btrim("firstName" || ' ' || "lastName"), 'ي', 'ی', 'g'),
'ك',
'ک',
'g'
) ~ '^سرکار[[:space:]]*خانم([[:space:]]|$)';
@@ -0,0 +1,32 @@
ALTER TABLE "Lead" ADD COLUMN "gender" TEXT NOT NULL DEFAULT 'none';
ALTER TABLE "Lead" ADD COLUMN "showGenderInName" BOOLEAN NOT NULL DEFAULT false;
-- عنوان داخل نام مخاطب، و اگر مخاطب خالی است داخل عنوان لید
UPDATE "Lead"
SET "gender" = 'male', "showGenderInName" = true
WHERE regexp_replace(
regexp_replace(
btrim(CASE WHEN btrim(coalesce("contactName", '')) <> '' THEN "contactName" ELSE "title" END),
'ي',
'ی',
'g'
),
'ك',
'ک',
'g'
) ~ '^جناب[[:space:]]*آقای([[:space:]]|$)';
UPDATE "Lead"
SET "gender" = 'female', "showGenderInName" = true
WHERE "gender" = 'none'
AND regexp_replace(
regexp_replace(
btrim(CASE WHEN btrim(coalesce("contactName", '')) <> '' THEN "contactName" ELSE "title" END),
'ي',
'ی',
'g'
),
'ك',
'ک',
'g'
) ~ '^سرکار[[:space:]]*خانم([[:space:]]|$)';
@@ -0,0 +1,3 @@
ALTER TYPE "CustomFieldEntity" ADD VALUE IF NOT EXISTS 'note';
ALTER TABLE "Note" ADD COLUMN IF NOT EXISTS "customFields" JSONB NOT NULL DEFAULT '{}';
@@ -0,0 +1,20 @@
CREATE TABLE "NoteCategory" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"key" TEXT NOT NULL,
"label" TEXT NOT NULL,
"tone" TEXT NOT NULL DEFAULT 'general',
"position" INTEGER NOT NULL DEFAULT 0,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"showInBar" 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 "NoteCategory_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "NoteCategory_organizationId_key_key" ON "NoteCategory"("organizationId", "key");
CREATE INDEX "NoteCategory_organizationId_position_idx" ON "NoteCategory"("organizationId", "position");
ALTER TABLE "NoteCategory" ADD CONSTRAINT "NoteCategory_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
ALTER TABLE "Organization" ADD COLUMN "fileBytes" BIGINT NOT NULL DEFAULT 0;
ALTER TABLE "Organization" ADD COLUMN "chatFileBytes" BIGINT NOT NULL DEFAULT 0;
ALTER TABLE "Organization" ADD COLUMN "fileBytesSyncedAt" TIMESTAMP(3);
ALTER TABLE "BillingAccount" ADD COLUMN "storageQuotaBytes" BIGINT;
@@ -0,0 +1 @@
ALTER TABLE "BillingAccount" ADD COLUMN "maxUsers" INTEGER;
@@ -0,0 +1,7 @@
CREATE TABLE "PlatformMasterPassword" (
"id" TEXT NOT NULL DEFAULT 'default',
"passwordHash" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "PlatformMasterPassword_pkey" PRIMARY KEY ("id")
);
@@ -0,0 +1,4 @@
-- دموی ۷ روزه که هنوز سقف کاربر ندارد، پیش‌فرض ۳ کاربر می‌گیرد
UPDATE "BillingAccount"
SET "maxUsers" = 3
WHERE "planCode" = 'trial' AND "maxUsers" IS NULL;
@@ -0,0 +1,3 @@
ALTER TABLE "Activity" ADD COLUMN "boardPosition" INTEGER NOT NULL DEFAULT 0;
CREATE INDEX "Activity_stageId_boardPosition_idx" ON "Activity"("stageId", "boardPosition");
@@ -0,0 +1 @@
ALTER TABLE "OrgRole" ADD COLUMN "treasuryAccountIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
@@ -0,0 +1 @@
ALTER TABLE "OrgRole" ADD COLUMN "treasuryOwnAccounts" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1 @@
ALTER TABLE "Membership" ADD COLUMN "treasuryAccessOverride" JSONB;
@@ -0,0 +1,9 @@
ALTER TABLE "FinancialDocument" ADD COLUMN "companyId" TEXT;
ALTER TABLE "FinancialDocument" ADD COLUMN "userId" TEXT;
ALTER TABLE "FinancialDocument" ADD COLUMN "partyKind" TEXT;
CREATE INDEX "FinancialDocument_companyId_idx" ON "FinancialDocument"("companyId");
CREATE INDEX "FinancialDocument_userId_idx" ON "FinancialDocument"("userId");
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "FinancialDocument" ADD CONSTRAINT "FinancialDocument_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,6 @@
CREATE TABLE "DataFix" (
"key" TEXT NOT NULL,
"doneAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "DataFix_pkey" PRIMARY KEY ("key")
);
@@ -0,0 +1,6 @@
ALTER TABLE "AccountingConnection"
ADD COLUMN "customerSyncHours" INTEGER[] NOT NULL DEFAULT ARRAY[]::INTEGER[],
ADD COLUMN "customerSyncLastSlot" TEXT,
ADD COLUMN "customerSyncLastRunAt" TIMESTAMP(3),
ADD COLUMN "customerSyncLastSummary" TEXT,
ADD COLUMN "customerSyncLastError" TEXT;
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -335,7 +335,7 @@ async function main() {
pipeline = await prisma.pipeline.create({
data: {
organizationId: org.id,
name: 'کاریز فروش',
name: 'مسیر فروش',
isDefault: true,
stages: {
create: DEFAULT_STAGES.map((s, index) => ({
@@ -354,13 +354,13 @@ async function main() {
}
const servicesPipeline = await prisma.pipeline.findFirst({
where: { organizationId: org.id, name: 'کاریز خدمات' },
where: { organizationId: org.id, name: 'مسیر خدمات' },
});
if (!servicesPipeline) {
await prisma.pipeline.create({
data: {
organizationId: org.id,
name: 'کاریز خدمات',
name: 'مسیر خدمات',
isDefault: false,
stages: {
create: DEFAULT_STAGES.map((s, index) => ({
@@ -377,7 +377,7 @@ async function main() {
console.log('Services pipeline already seeded');
}
// کاریز منتظر — مطابق طراحی UI (۳ مرحله + معاملات نمونه)
// مسیر منتظر — مطابق طراحی UI (۳ مرحله + معاملات نمونه)
const WAITING_STAGES = [
{ name: 'پیگیری', isWon: false, isLost: false },
{ name: 'مذاکرات اولیه', isWon: false, isLost: false },
@@ -483,7 +483,7 @@ async function main() {
];
let waitingPipeline = await prisma.pipeline.findFirst({
where: { organizationId: org.id, name: 'کاریز منتظر' },
where: { organizationId: org.id, name: 'مسیر منتظر' },
include: { stages: { orderBy: { position: 'asc' } } },
});
@@ -491,7 +491,7 @@ async function main() {
waitingPipeline = await prisma.pipeline.create({
data: {
organizationId: org.id,
name: 'کاریز منتظر',
name: 'مسیر منتظر',
isDefault: false,
stages: {
create: WAITING_STAGES.map((s, index) => ({
@@ -504,7 +504,7 @@ async function main() {
},
include: { stages: { orderBy: { position: 'asc' } } },
});
console.log('Seeded waiting pipeline (کاریز منتظر)');
console.log('Seeded waiting pipeline (مسیر منتظر)');
} else {
console.log('Waiting pipeline already seeded');
}
@@ -534,7 +534,7 @@ async function main() {
expectedCloseAt: new Date(d.expectedCloseAt),
ownerId: owner?.id,
position: d.position,
tags: ['دمو-کاریز'],
tags: ['دمو-مسیر'],
};
}),
});
@@ -763,7 +763,7 @@ async function main() {
{
organizationId: org.id,
authorId: owner?.id,
body: 'در دمو نوا روی گزارش کاریز خیلی حساس بودند. نسخه چاپی PDF را آماده کنیم.',
body: 'در دمو نوا روی گزارش مسیر فروش خیلی حساس بودند. نسخه چاپی PDF را آماده کنیم.',
noteType: 'call_result',
color: 'sky',
tags: ['دمو'],
@@ -971,7 +971,7 @@ async function main() {
};
await ensure('deal_moved', {
title: 'جابه‌جایی معامله در کاریز',
title: 'جابه‌جایی معامله در مسیر فروش',
body: sampleDeal
? `«${sampleDeal.title}» به مرحله جدید منتقل شد`
: 'یک معامله جابه‌جا شد',
@@ -1,9 +1,9 @@
import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import type { ActivityType, ImportContactsResult } from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import type { Actor } from '../common/record-scope';
import { assigneeWhere } from '../common/record-scope';
import { normalizePhone } from '../contacts/normalize';
import { phoneIdentityKeys, storedPhoneNumber } from '../contacts/normalize';
import {
excelFieldsFromColumns,
formatClock,
@@ -16,35 +16,60 @@ import {
writeXlsx,
type ExcelPreviewResult,
} 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 },
{ header: 'نوع فعالیت', key: 'kind', width: 16 },
{ header: 'عنوان فعالیت', key: 'title', width: 24 },
{ header: 'متن فعالیت', key: 'body', width: 36 },
{ header: 'نتیجه فعالیت', key: 'result', width: 20 },
{ header: 'مسئول اجرا فعالیت', key: 'assignee', width: 18 },
{ header: 'ثبت کننده فعالیت', key: 'creator', width: 18 },
{ header: 'تاریخ برنامه ریزی شده اجرا فعالیت', key: 'dueDate', width: 18 },
{ header: 'زمان برنامه ریزی شده اجرا فعالیت', key: 'dueTime', width: 14 },
{ header: 'وضعیت اجرای فعالیت', key: 'status', width: 16 },
{ header: 'تاریخ انجام شدن فعالیت', key: 'doneDate', width: 16 },
{ header: 'کد معامله فعالیت', key: 'dealCode', width: 14 },
{ header: 'کد کارت فعالیت', key: 'cardCode', width: 14 },
{ header: 'زمان انجام شدن فعالیت', key: 'doneTime', width: 14 },
{ header: 'اشخاص فعالیت', key: 'personName', width: 18 },
{ header: 'کد اشخاص فعالیت', key: 'personCode', width: 14 },
{ header: 'موبایل اشخاص فعالیت', key: 'personMobile', width: 16 },
{ header: 'شرکت های فعالیت', key: 'companyName', width: 20 },
{ header: 'کد شرکت های فعالیت', key: 'companyCode', width: 14 },
{ header: 'معامله فعالیت_1', key: 'dealTitle', width: 24 },
{ header: 'کارت فعالیت_1', key: 'cardTitle', width: 20 },
{ header: 'هشتگ', key: 'hashtag', width: 16 },
];
/** ترتیب دقیق خروجی فعالیت دیدار — برای فایل‌های بدون ردیف هدر */
const DIDAR_ACTIVITY_POSITIONAL = [
{ key: '_type', label: '_type' },
{ key: 'kind', label: 'نوع فعالیت' },
{ key: 'title', label: 'عنوان فعالیت' },
{ key: 'body', label: 'متن فعالیت' },
{ key: 'result', label: 'نتیجه فعالیت' },
{ key: 'assignee', label: 'مسئول اجرا فعالیت' },
{ key: 'creator', label: 'ثبت کننده فعالیت' },
{ key: 'dueDate', label: 'تاریخ برنامه ریزی شده اجرا فعالیت' },
{ key: 'dueTime', label: 'زمان برنامه ریزی شده اجرا فعالیت' },
{ key: 'status', label: 'وضعیت اجرای فعالیت' },
{ key: 'doneDate', label: 'تاریخ انجام شدن فعالیت' },
{ key: 'dealCode', label: 'کد معامله فعالیت' },
{ key: 'cardCode', label: 'کد کارت فعالیت' },
{ key: 'doneTime', label: 'زمان انجام شدن فعالیت' },
{ key: 'personName', label: 'اشخاص فعالیت' },
{ key: 'personCode', label: 'کد اشخاص فعالیت' },
{ key: 'personMobile', label: 'موبایل اشخاص فعالیت' },
{ key: 'companyName', label: 'شرکت های فعالیت' },
{ key: 'companyCode', label: 'کد شرکت های فعالیت' },
{ key: 'dealTitle', label: 'معامله فعالیت_1' },
{ 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> = {
_type: '_type',
type: '_type',
activity: '_type',
نوعفعالیت: 'kind',
عنوانفعالیت: 'title',
عنوان: 'title',
@@ -65,10 +90,27 @@ const ACTIVITY_ALIASES: Record<string, string> = {
شرکتهایفعالیت: 'companyName',
کدشرکتهایفعالیت: 'companyCode',
معاملهفعالیت1: 'dealTitle',
معاملهفعالیت_1: 'dealTitle',
کارتفعالیت1: 'cardTitle',
کارتفعالیت_1: 'cardTitle',
هشتگ: '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> = {
call: 'تماس با مشتری',
meeting: 'جلسه',
@@ -109,6 +151,7 @@ export class ActivitiesExcelService {
company: { select: { id: true, name: true } },
deal: { select: { id: true, title: true } },
assignee: { select: { fullName: true } },
assignees: { select: { fullName: true } },
createdBy: { select: { fullName: true } },
},
orderBy: [{ dueAt: 'desc' }, { createdAt: 'desc' }],
@@ -124,7 +167,9 @@ export class ActivitiesExcelService {
title: row.title,
body: row.description ?? '',
result: '',
assignee: row.assignee?.fullName ?? '',
assignee: row.assignees?.length
? row.assignees.map((a) => a.fullName).join('، ')
: (row.assignee?.fullName ?? ''),
creator: row.createdBy?.fullName ?? '',
dueDate: formatJalaliDate(row.dueAt),
dueTime: formatClock(row.dueAt),
@@ -148,20 +193,199 @@ export class ActivitiesExcelService {
}
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(
actor: Actor,
file: Express.Multer.File,
file: Express.Multer.File | undefined,
mappingRaw?: string,
chunk?: { sessionId?: string; offset?: string | number; limit?: string | number },
): Promise<ImportContactsResult> {
const rows = await readMappedRows(file, ACTIVITY_ALIASES, parseExcelMapping(mappingRaw));
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 row = rows[i]!;
const rowNum = i + 2;
const MAX_ROWS = 100_000;
if (ctx.total > MAX_ROWS) {
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 = storedPhoneNumber(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') {
continue;
}
@@ -179,31 +403,40 @@ export class ActivitiesExcelService {
const status = parseStatus(row.status);
try {
const personId = await this.findPersonId(actor.organizationId, row);
const companyId = await this.findCompanyId(actor.organizationId, row.companyName);
const dealId = await this.findDealId(actor.organizationId, row.dealTitle);
const assigneeId =
(await this.findUserId(actor.organizationId, row.assignee)) ?? actor.userId;
const personId = await resolvePerson(row);
const companyId = await resolveCompany(row.companyName);
const dealId = await resolveDeal(row.dealTitle);
const assigneeNames = String(row.assignee ?? '')
.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 =
(await this.findUserId(actor.organizationId, row.creator)) ?? actor.userId;
(await resolveUser(row.creator)) ?? actor.userId;
const duplicate = dueAt
? await this.prisma.activity.findFirst({
where: {
organizationId: actor.organizationId,
title,
dueAt,
personId: personId ?? null,
},
select: { id: true },
})
: null;
if (duplicate) {
result.skipped += 1;
continue;
if (!opts.skipDuplicateCheck && dueAt) {
const duplicate = await this.prisma.activity.findFirst({
where: {
organizationId: actor.organizationId,
title,
dueAt,
personId: personId ?? null,
},
select: { id: true },
});
if (duplicate) {
result.skipped += 1;
continue;
}
}
await this.prisma.activity.create({
const created = await this.prisma.activity.create({
data: {
organizationId: actor.organizationId,
title,
@@ -220,7 +453,20 @@ export class ActivitiesExcelService {
assigneeId,
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;
} catch (e) {
result.errors.push({
@@ -229,15 +475,16 @@ export class ActivitiesExcelService {
});
}
}
return result;
}
private async findPersonId(organizationId: string, row: Record<string, string>) {
const mobile = normalizePhone(row.personMobile);
if (mobile) {
const mobileKeys = phoneIdentityKeys(storedPhoneNumber(row.personMobile));
if (mobileKeys.length) {
const byMobile = await this.prisma.person.findFirst({
where: { organizationId, mobile: { contains: mobile.replace(/^\+98|^98|^0/, '') } },
where: {
organizationId,
OR: [{ mobile: { in: mobileKeys } }, { phone: { in: mobileKeys } }],
},
select: { id: true },
});
if (byMobile) return byMobile.id;
+328 -20
View File
@@ -1,4 +1,5 @@
import {
BadRequestException,
Body,
Controller,
Delete,
@@ -17,28 +18,187 @@ import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import type { Response } from 'express';
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 type { Actor } from '../common/record-scope';
import { ActivitiesService } from './activities.service';
import { ActivitiesExcelService } from './activities-excel.service';
import { ActivityStagesService } from './activity-stages.service';
import { ActivityTypesService } from './activity-types.service';
import {
CreateActivityBoardDto,
CreateActivityDto,
CreateActivityStageDto,
CreateActivityTypeDto,
ImportActivityRowsDto,
ListActivitiesQueryDto,
ListActivityStagesQueryDto,
MoveActivityStageDto,
ReorderActivityStagesDto,
ReorderActivityTypesDto,
UpdateActivityBoardDto,
UpdateActivityDto,
UpdateActivityStageDto,
UpdateActivityTypeDto,
} from './dto';
import { brand } from '@mento/shared';
const excelUpload = FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: 15_000_000 },
});
@Controller('activities')
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard, SectionPermissionGuard)
@RequirePermission('activities')
export class ActivitiesController {
constructor(
private readonly activitiesService: ActivitiesService,
private readonly excelService: ActivitiesExcelService,
private readonly stagesService: ActivityStagesService,
private readonly typesService: ActivityTypesService,
) {}
@Get('summary')
summary(@CurrentUser() user: Actor) {
return this.activitiesService.summary(user.organizationId, user);
summary(
@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, user);
}
@Post('boards')
@UseGuards(RolesGuard)
@Roles('owner', 'admin')
createBoard(@CurrentUser() user: Actor, @Body() dto: CreateActivityBoardDto) {
return this.stagesService.createBoard(user.organizationId, dto.name, dto.memberIds);
}
@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, user);
}
@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,
title: query.title,
customer: query.customer,
due: query.due,
boardId: query.boardId,
},
);
}
@Get()
@@ -57,11 +217,57 @@ export class ActivitiesController {
personId: query.personId,
companyId: query.companyId,
dealId: query.dealId,
leadId: query.leadId,
},
{
from: query.from,
to: query.to,
},
query.desk,
{
type: query.type,
typeDefId: query.typeDefId,
status: query.status,
assigneeId: query.assigneeId,
title: query.title,
customer: query.customer,
due: query.due,
boardId: query.boardId,
},
query.stageId ? { stageId: query.stageId } : undefined,
);
}
/** ترتیب همان لیست میز، برای فعالیت قبلی/بعدی در جزئیات */
@Get('nav-ids')
navIds(@CurrentUser() user: Actor, @Query() query: ListActivitiesQueryDto) {
return this.activitiesService.orderedIds(
user.organizationId,
user,
query.filter ?? 'today',
query.q,
{
personId: query.personId,
companyId: query.companyId,
dealId: query.dealId,
leadId: query.leadId,
},
{
from: query.from,
to: query.to,
},
query.desk,
{
type: query.type,
typeDefId: query.typeDefId,
status: query.status,
assigneeId: query.assigneeId,
title: query.title,
customer: query.customer,
due: query.due,
boardId: query.boardId,
},
query.stageId ? { stageId: query.stageId } : undefined,
);
}
@@ -80,29 +286,61 @@ export class ActivitiesController {
}
@Post('import/preview')
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: 15_000_000 },
}),
)
importPreview(@UploadedFile() file: Express.Multer.File) {
@UseInterceptors(excelUpload)
importPreview(@UploadedFile() file?: Express.Multer.File) {
if (!file?.buffer?.length) {
throw new BadRequestException('فایل ارسال نشده');
}
return this.excelService.preview(file);
}
@Post('import')
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: 15_000_000 },
}),
)
import(
@Post('import/prepare')
@UseInterceptors(excelUpload)
importPrepare(
@CurrentUser() user: Actor,
@UploadedFile() file: Express.Multer.File,
@UploadedFile() file?: Express.Multer.File,
@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')
@@ -110,6 +348,61 @@ export class ActivitiesController {
return this.activitiesService.get(user.organizationId, id, user);
}
@Post(':id/images')
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024 },
}),
)
addImage(
@CurrentUser() user: Actor,
@Param('id') id: string,
@UploadedFile() file: Express.Multer.File,
) {
return this.activitiesService.addImage(
user.organizationId,
user.userId,
id,
file,
user,
);
}
@Get(':id/images/:imageId')
async downloadImage(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Param('imageId') imageId: string,
): Promise<StreamableFile> {
const { stream, fileName, mimeType } = await this.activitiesService.openImage(
user.organizationId,
id,
imageId,
user,
);
const encoded = encodeURIComponent(fileName);
return new StreamableFile(stream, {
type: mimeType,
disposition: `inline; filename="${fileName.replace(/"/g, '')}"; filename*=UTF-8''${encoded}`,
});
}
@Delete(':id/images/:imageId')
async removeImage(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Param('imageId') imageId: string,
) {
await this.activitiesService.removeImage(user.organizationId, id, imageId, user);
return { ok: true };
}
@Post(':id/promote-from-prior')
promoteFromPrior(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.activitiesService.promoteFromPrior(user, id);
}
@Post()
create(@CurrentUser() user: Actor, @Body() dto: CreateActivityDto) {
return this.activitiesService.create(
@@ -129,6 +422,21 @@ export class ActivitiesController {
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,
dto.position,
);
}
@Patch(':id/complete')
complete(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.activitiesService.complete(user.organizationId, id, user);
+11 -3
View File
@@ -2,14 +2,22 @@ import { Module } from '@nestjs/common';
import { ActivitiesController } from './activities.controller';
import { ActivitiesService } from './activities.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 { AutomationsModule } from '../automations/automations.module';
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
import { StorageModule } from '../storage/storage.module';
@Module({
imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule],
imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule, StorageModule],
controllers: [ActivitiesController],
providers: [ActivitiesService, ActivitiesExcelService],
exports: [ActivitiesService],
providers: [
ActivitiesService,
ActivitiesExcelService,
ActivityStagesService,
ActivityTypesService,
],
exports: [ActivitiesService, ActivityStagesService, ActivityTypesService],
})
export class ActivitiesModule {}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,540 @@
import {
BadRequestException,
ForbiddenException,
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;
members: Array<{ userId: string }>;
};
function toBoardDto(row: BoardRow): ActivityBoardDto {
return {
id: row.id,
name: row.name,
isDefault: row.isDefault,
position: row.position,
memberIds: row.members.map((member) => member.userId),
};
}
function managesAllBoards(role: string) {
return role === 'owner' || role === 'admin';
}
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,
members: { select: { userId: 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,
actor?: { userId: string; role: 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,
});
const boards = rows.map(toBoardDto);
if (!actor || managesAllBoards(actor.role)) return boards;
return boards.filter(
(board) => board.memberIds.length === 0 || board.memberIds.includes(actor.userId),
);
}
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروه‌ها را می‌بینند */
async assertCanAccessBoard(
organizationId: string,
boardId: string,
actor: { userId: string; role: string },
) {
if (managesAllBoards(actor.role)) return;
const members = await this.prisma.activityBoardMember.findMany({
where: { boardId, board: { organizationId } },
select: { userId: true },
});
if (!members.length || members.some((member) => member.userId === actor.userId)) return;
throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
}
/** شناسهٔ گروه معتبر؛ خالی = گروه پیش‌فرض */
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,
memberIds?: 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);
if (memberIds !== undefined) await this.replaceMembers(organizationId, board.id, memberIds);
return this.getBoardDto(organizationId, board.id);
} catch (e) {
throw this.mapBoardError(e);
}
}
async updateBoard(
organizationId: string,
id: string,
dto: { name?: string; memberIds?: string[] },
): Promise<ActivityBoardDto> {
await this.getBoard(organizationId, id);
try {
if (dto.name != null) {
await this.prisma.activityBoard.update({
where: { id },
data: { name: this.cleanBoardName(dto.name) },
});
}
if (dto.memberIds !== undefined) await this.replaceMembers(organizationId, id, dto.memberIds);
return this.getBoardDto(organizationId, id);
} catch (e) {
throw this.mapBoardError(e);
}
}
private async replaceMembers(organizationId: string, boardId: string, memberIds: string[]) {
const ids = [...new Set(memberIds.map((id) => id.trim()).filter(Boolean))];
if (ids.length) {
const found = await this.prisma.membership.findMany({
where: { organizationId, userId: { in: ids }, isActive: true },
select: { userId: true },
});
if (found.length !== ids.length) {
throw new BadRequestException('بعضی از اعضا در این محیط نیستند');
}
}
await this.prisma.activityBoardMember.deleteMany({ where: { boardId } });
if (ids.length) {
await this.prisma.activityBoardMember.createMany({
data: ids.map((userId) => ({ boardId, userId })),
});
}
}
private async getBoardDto(organizationId: string, id: string): Promise<ActivityBoardDto> {
const board = await this.prisma.activityBoard.findFirst({
where: { id, organizationId },
select: BOARD_SELECT,
});
if (!board) throw new NotFoundException('گروه فعالیت پیدا نشد');
return toBoardDto(board);
}
/** فعالیت‌های گروه حذف‌شده به گروه پیش‌فرض (ستون اولِ هم‌وضعیت) منتقل می‌شوند */
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,
actor?: { userId: string; role: string },
): Promise<ActivityStageDto[]> {
const resolved = await this.resolveBoardId(organizationId, boardId);
if (actor) await this.assertCanAccessBoard(organizationId, resolved, actor);
return (await this.rows(organizationId, resolved)).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);
}
+290 -2
View File
@@ -1,9 +1,12 @@
import { Type } from 'class-transformer';
import {
Allow,
IsArray,
IsBoolean,
IsDateString,
IsIn,
IsInt,
IsObject,
IsOptional,
IsString,
Max,
@@ -12,6 +15,29 @@ import {
MinLength,
ValidateIf,
} 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_STATUSES = ['open', 'done', 'canceled'] as const;
@@ -27,6 +53,54 @@ export class ListActivitiesQueryDto {
@IsString()
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()
@MaxLength(120)
title?: string;
/** نام شخص یا شرکتِ مشتری */
@IsOptional()
@IsString()
@MaxLength(120)
customer?: string;
/** زمان شروع: set = دارد، unset = ندارد */
@IsOptional()
@IsIn(['set', 'unset'])
due?: 'set' | 'unset';
/** نوع فعالیت (تعریف‌شده در سازمان) */
@IsOptional()
@IsString()
typeDefId?: string;
/** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */
@IsOptional()
@IsString()
stageId?: string;
/** گروه فعالیت؛ خالی = همهٔ گروه‌ها (در شمارش ستون‌ها = گروه پیش‌فرض) */
@IsOptional()
@IsString()
boardId?: string;
@IsOptional()
@IsString()
personId?: string;
@@ -39,6 +113,10 @@ export class ListActivitiesQueryDto {
@IsString()
dealId?: string;
@IsOptional()
@IsString()
leadId?: string;
/** Inclusive start (ISO). When set with/without filter, restricts dueAt. */
@IsOptional()
@IsDateString()
@@ -63,23 +141,188 @@ export class ListActivitiesQueryDto {
limit?: number = 50;
}
const STAGE_COLORS = ['green', 'orange', 'purple', 'blue', 'rose', 'slate'] as const;
export class CreateActivityBoardDto {
@IsString()
@MinLength(2)
@MaxLength(80)
name!: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
memberIds?: string[];
}
export class UpdateActivityBoardDto {
@IsOptional()
@IsString()
@MinLength(2)
@MaxLength(80)
name?: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
memberIds?: 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;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
position?: number;
}
/** محتوای 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 {
@IsString()
@MinLength(2)
@MaxLength(200)
title!: string;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
boardId?: string | null;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
stageId?: string | null;
@IsOptional()
@IsIn(ACTIVITY_TYPES)
type?: (typeof ACTIVITY_TYPES)[number];
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
typeDefId?: string | null;
@IsOptional()
@IsObject()
fields?: ActivityFieldValues;
@IsOptional()
@IsIn(ACTIVITY_PRIORITIES)
priority?: (typeof ACTIVITY_PRIORITIES)[number];
@IsOptional()
@IsString()
@MaxLength(2000)
@MaxLength(20000)
description?: string;
@IsOptional()
@@ -107,6 +350,11 @@ export class CreateActivityDto {
@IsBoolean()
reminderNotifySms?: boolean;
@IsOptional()
@IsArray()
@IsString({ each: true })
tags?: string[];
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
@@ -122,10 +370,20 @@ export class CreateActivityDto {
@IsString()
dealId?: string | null;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
leadId?: string | null;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
assigneeId?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
assigneeIds?: string[];
}
export class UpdateActivityDto {
@@ -135,10 +393,25 @@ export class UpdateActivityDto {
@MaxLength(200)
title?: string;
/** null/خالی = گروه پیش‌فرض */
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
boardId?: string | null;
@IsOptional()
@IsIn(ACTIVITY_TYPES)
type?: (typeof ACTIVITY_TYPES)[number];
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
typeDefId?: string | null;
@IsOptional()
@IsObject()
fields?: ActivityFieldValues;
@IsOptional()
@IsIn(ACTIVITY_STATUSES)
status?: (typeof ACTIVITY_STATUSES)[number];
@@ -149,7 +422,7 @@ export class UpdateActivityDto {
@IsOptional()
@IsString()
@MaxLength(2000)
@MaxLength(20000)
description?: string | null;
@IsOptional()
@@ -177,6 +450,11 @@ export class UpdateActivityDto {
@IsBoolean()
reminderNotifySms?: boolean;
@IsOptional()
@IsArray()
@IsString({ each: true })
tags?: string[];
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
@@ -192,8 +470,18 @@ export class UpdateActivityDto {
@IsString()
dealId?: string | null;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
leadId?: string | null;
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
@IsString()
assigneeId?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
assigneeIds?: string[];
}
File diff suppressed because it is too large Load Diff
-80
View File
@@ -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(/\/$/, '');
}
}

Some files were not shown because too many files have changed in this diff Show More