From 4409ded0ab6d2bbd3ce21f676683ae64228396aa Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 15 Nov 2026 12:42:01 +0330 Subject: [PATCH 01/25] Add treasury document photos, table list, and manage permission. Income/expense lists are table-or-card with detail, edit, void, and delete; edit/delete require owner, admin, or the new finance manage permission. Co-authored-by: Cursor --- apps/api/src/treasury/treasury.controller.ts | 27 + apps/api/src/treasury/treasury.service.ts | 126 +++- .../treasury/TreasuryDocPhotoField.vue | 89 +++ .../treasury/TreasuryDocumentsPanel.vue | 594 ++++++++++++++++++ apps/web/src/lib/treasury-doc-photos.ts | 22 + apps/web/src/views/TeamSettingsView.vue | 1 + .../src/views/treasury/TreasuryDocsView.vue | 203 +++++- .../views/treasury/TreasuryExpensesView.vue | 368 +++++------ .../views/treasury/TreasuryIncomesView.vue | 391 +++++------- packages/shared/src/index.ts | 13 +- 10 files changed, 1383 insertions(+), 451 deletions(-) create mode 100644 apps/web/src/components/treasury/TreasuryDocPhotoField.vue create mode 100644 apps/web/src/components/treasury/TreasuryDocumentsPanel.vue create mode 100644 apps/web/src/lib/treasury-doc-photos.ts diff --git a/apps/api/src/treasury/treasury.controller.ts b/apps/api/src/treasury/treasury.controller.ts index 75880d4..f0ec94f 100644 --- a/apps/api/src/treasury/treasury.controller.ts +++ b/apps/api/src/treasury/treasury.controller.ts @@ -181,6 +181,33 @@ export class TreasuryController { }); } + @Get('documents/:id') + getDocument(@CurrentUser() user: Actor, @Param('id') id: string) { + return this.treasury.getDocument(user, id); + } + + @Patch('documents/:id') + updateDocument( + @CurrentUser() user: Actor, + @Param('id') id: string, + @Body() + body: { + title?: string; + notes?: string | null; + categoryId?: string | null; + method?: string | null; + bookedAt?: string; + amount?: string | number; + }, + ) { + return this.treasury.updateDocument(user, id, body); + } + + @Delete('documents/:id') + deleteDocument(@CurrentUser() user: Actor, @Param('id') id: string) { + return this.treasury.deleteDocument(user, id); + } + @Get('attachments/:id') async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) { const file = await this.treasury.openAttachment(user, id); diff --git a/apps/api/src/treasury/treasury.service.ts b/apps/api/src/treasury/treasury.service.ts index d9cfdc3..6a3abc6 100644 --- a/apps/api/src/treasury/treasury.service.ts +++ b/apps/api/src/treasury/treasury.service.ts @@ -4,7 +4,11 @@ import { Injectable, NotFoundException, } from '@nestjs/common'; -import { parseUserTreasuryAccess } from '@mento/shared'; +import { + canManageTreasuryDocuments, + parseUserTreasuryAccess, + permissionsWithTreasuryOverride, +} from '@mento/shared'; import { randomUUID } from 'node:crypto'; import { Prisma } from '@prisma/client'; import ExcelJS from 'exceljs'; @@ -506,13 +510,87 @@ export class TreasuryService { } : {}), }, - include: { category: true, account: true, movements: true, attachments: { select: { id: true, fileName: true } } }, + include: { + category: true, + account: true, + movements: true, + attachments: { select: { id: true, fileName: true, mimeType: true } }, + }, orderBy: { bookedAt: 'desc' }, take: 200, }); return rows.map((row) => this.toDocumentDto(row)); } + async getDocument(actor: Actor, id: string): Promise { + const doc = await this.requireScopedDocument(actor, id); + return this.toDocumentDto(doc); + } + + async updateDocument( + actor: Actor, + id: string, + input: { + title?: string; + notes?: string | null; + categoryId?: string | null; + method?: string | null; + bookedAt?: string; + amount?: string | number; + }, + ): Promise { + await this.assertDocumentsManage(actor); + const doc = await this.requireScopedDocument(actor, id); + if (doc.status === 'void' || doc.voidedAt) { + throw new BadRequestException('سند باطل‌شده قابل ویرایش نیست.'); + } + const data: Prisma.FinancialDocumentUncheckedUpdateInput = {}; + if (input.title !== undefined) { + const title = input.title.trim(); + if (title.length < 2) throw new BadRequestException('عنوان را وارد کنید.'); + data.title = title; + } + if (input.notes !== undefined) data.notes = input.notes?.trim() || null; + if (input.categoryId !== undefined) data.categoryId = input.categoryId || null; + if (input.method !== undefined) data.method = input.method || null; + if (input.bookedAt !== undefined) { + const bookedAt = startOfDay(input.bookedAt); + if (!bookedAt) throw new BadRequestException('تاریخ نامعتبر است.'); + data.bookedAt = bookedAt; + } + if (input.amount !== undefined) { + const active = doc.movements.filter((row) => !row.voidedAt); + if (active.length > 0 || doc.status !== 'open') { + throw new BadRequestException('مبلغ فقط برای سند باز بدون دریافت/پرداخت قابل تغییر است.'); + } + const amount = dec(input.amount); + if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ باید بزرگ‌تر از صفر باشد.'); + data.amount = amount; + } + await this.prisma.financialDocument.update({ where: { id: doc.id }, data }); + return this.getDocument(actor, id); + } + + async deleteDocument(actor: Actor, id: string): Promise<{ ok: true }> { + await this.assertDocumentsManage(actor); + const doc = await this.requireScopedDocument(actor, id); + const active = doc.movements.filter((row) => !row.voidedAt); + if (doc.status !== 'void' && active.length > 0) { + throw new BadRequestException('ابتدا سند را ابطال کنید، سپس حذف کنید.'); + } + const attachments = await this.prisma.financialAttachment.findMany({ + where: { documentId: doc.id, organizationId: actor.organizationId }, + select: { id: true, storageKey: true }, + }); + for (const file of attachments) { + const bytes = await this.files.sizeOf(file.storageKey); + await this.files.remove(file.storageKey); + if (bytes) await this.storage.addLocal(actor.organizationId, -bytes); + } + await this.prisma.financialDocument.delete({ where: { id: doc.id } }); + return { ok: true }; + } + async createDocument( actor: Actor, input: { @@ -1443,6 +1521,47 @@ export class TreasuryService { ); } + private async actorPermissions(actor: Actor): Promise { + const membership = await this.prisma.membership.findFirst({ + where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true }, + select: { + orgRole: { select: { permissions: true } }, + treasuryAccessOverride: true, + }, + }); + const rolePermissions = Array.isArray(membership?.orgRole?.permissions) + ? membership.orgRole.permissions.map(String) + : []; + return permissionsWithTreasuryOverride( + rolePermissions, + parseUserTreasuryAccess(membership?.treasuryAccessOverride), + ); + } + + private async assertDocumentsManage(actor: Actor) { + if (canManageTreasuryDocuments(actor.role, await this.actorPermissions(actor))) return; + throw new ForbiddenException('اجازه ویرایش یا حذف اسناد را ندارید.'); + } + + private async requireScopedDocument(actor: Actor, id: string) { + const scope = await this.accountScope(actor); + const doc = await this.prisma.financialDocument.findFirst({ + where: { + id, + organizationId: actor.organizationId, + ...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}), + }, + include: { + category: true, + account: true, + movements: true, + attachments: { select: { id: true, fileName: true, mimeType: true } }, + }, + }); + if (!doc) throw new NotFoundException('سند پیدا نشد.'); + return doc; + } + private async accountScope(actor: Actor): Promise { if (actor.role === 'owner' || actor.role === 'admin') return null; const membership = await this.prisma.membership.findFirst({ @@ -1566,7 +1685,8 @@ export class TreasuryService { category?: { name: string } | null; account?: { name: string } | null; movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>; - attachments?: Array<{ id: string; fileName: string }>; + attachments?: Array<{ id: string; fileName: string; mimeType?: string }>; + voidedAt?: Date | null; }): FinancialDocumentDto { const settled = this.settledOf(row.movements); const rawRemaining = row.amount.minus(settled); diff --git a/apps/web/src/components/treasury/TreasuryDocPhotoField.vue b/apps/web/src/components/treasury/TreasuryDocPhotoField.vue new file mode 100644 index 0000000..d8fb89e --- /dev/null +++ b/apps/web/src/components/treasury/TreasuryDocPhotoField.vue @@ -0,0 +1,89 @@ + + + diff --git a/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue new file mode 100644 index 0000000..8821efc --- /dev/null +++ b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue @@ -0,0 +1,594 @@ + + + diff --git a/apps/web/src/lib/treasury-doc-photos.ts b/apps/web/src/lib/treasury-doc-photos.ts new file mode 100644 index 0000000..7c9692a --- /dev/null +++ b/apps/web/src/lib/treasury-doc-photos.ts @@ -0,0 +1,22 @@ +import { api } from '@/lib/api'; + +export type TreasuryPendingPhoto = { + localId: string; + name: string; + dataUrl: string; + file: File; +}; + +export async function uploadTreasuryDocumentPhotos( + documentId: string, + photos: TreasuryPendingPhoto[], +): Promise { + let attached = 0; + for (const photo of photos) { + const body = new FormData(); + body.append('file', photo.file); + await api.post(`/treasury/documents/${documentId}/attachments`, body); + attached += 1; + } + return attached; +} diff --git a/apps/web/src/views/TeamSettingsView.vue b/apps/web/src/views/TeamSettingsView.vue index 2d3b723..b006079 100644 --- a/apps/web/src/views/TeamSettingsView.vue +++ b/apps/web/src/views/TeamSettingsView.vue @@ -86,6 +86,7 @@ const PERMISSION_MODULES: Partial> = { treasury_reports: ['treasury'], treasury_audit: ['treasury'], treasury_categories: ['treasury'], + treasury_documents_manage: ['treasury'], behavior: ['behavior'], }; diff --git a/apps/web/src/views/treasury/TreasuryDocsView.vue b/apps/web/src/views/treasury/TreasuryDocsView.vue index b998549..19a7a09 100644 --- a/apps/web/src/views/treasury/TreasuryDocsView.vue +++ b/apps/web/src/views/treasury/TreasuryDocsView.vue @@ -6,15 +6,21 @@ import type { FinancialAccountDto, FinancialCategoryDto, FinancialDocumentDto } import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui'; import MoneyInput from '@/components/MoneyInput.vue'; import TreasuryNav from '@/components/treasury/TreasuryNav.vue'; +import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress'; import { toman } from './treasury-format'; const props = defineProps<{ kind: 'income' | 'expense' }>(); +const PHOTO_LIMIT = 8; +type PendingPhoto = { localId: string; name: string; dataUrl: string; file: File }; + const rows = ref([]); const categories = ref([]); const accounts = ref([]); const error = ref(''); const ok = ref(''); const saving = ref(false); +const photoBusy = ref(false); +const pendingPhotos = ref([]); const q = ref(''); const form = ref({ title: '', @@ -43,6 +49,76 @@ function apiMessage(e: unknown) { return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; } +function resetForm() { + form.value = { + title: '', + amount: '', + categoryId: '', + partyName: '', + accountId: '', + settleAmount: '', + method: 'transfer', + reference: '', + notes: '', + }; + pendingPhotos.value = []; +} + +async function prepareTreasuryImage(file: File) { + if (!file.type.startsWith('image/')) { + throw new Error('فقط فایل تصویری مجاز است.'); + } + try { + return await prepareFormFieldFile(file); + } catch (e) { + if (e instanceof FormFileTooLargeError) { + throw new Error('حجم عکس باید زیر ۲۰۰ کیلوبایت باشد'); + } + throw new Error('فشرده‌سازی عکس ناموفق بود.'); + } +} + +async function onPhotosPicked(event: Event) { + const input = event.target as HTMLInputElement; + const files = Array.from(input.files ?? []); + input.value = ''; + if (!files.length) return; + error.value = ''; + for (const file of files) { + if (pendingPhotos.value.length >= PHOTO_LIMIT) { + error.value = `حداکثر ${PHOTO_LIMIT} عکس برای هر سند.`; + break; + } + photoBusy.value = true; + try { + const prepared = await prepareTreasuryImage(file); + pendingPhotos.value = [ + ...pendingPhotos.value, + { + localId: crypto.randomUUID(), + name: prepared.name, + dataUrl: prepared.dataUrl, + file: prepared.file, + }, + ]; + } catch (e) { + error.value = e instanceof Error ? e.message : 'افزودن عکس ناموفق بود.'; + } finally { + photoBusy.value = false; + } + } +} + +function removePendingPhoto(localId: string) { + pendingPhotos.value = pendingPhotos.value.filter((photo) => photo.localId !== localId); +} + +async function uploadPreparedFile(documentId: string, file: File) { + const body = new FormData(); + body.append('file', file); + await api.post(`/treasury/documents/${documentId}/attachments`, body); +} + async function load() { const [docs, cats, acc] = await Promise.all([ api.get('/treasury/documents', { params: { kind: props.kind, q: q.value || undefined } }), @@ -59,7 +135,7 @@ async function createDoc() { error.value = ''; ok.value = ''; try { - await api.post('/treasury/documents', { + const { data } = await api.post('/treasury/documents', { kind: props.kind, title: form.value.title, amount: form.value.amount, @@ -71,18 +147,22 @@ async function createDoc() { reference: form.value.reference || null, notes: form.value.notes || null, }); - form.value = { - title: '', - amount: '', - categoryId: '', - partyName: '', - accountId: '', - settleAmount: '', - method: 'transfer', - reference: '', - notes: '', - }; - ok.value = 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.'; + const photos = [...pendingPhotos.value]; + let attached = 0; + for (const photo of photos) { + try { + await uploadPreparedFile(data.id, photo.file); + attached += 1; + } catch (e) { + error.value = apiMessage(e); + break; + } + } + resetForm(); + ok.value = + attached > 0 + ? `سند ثبت شد و ${attached} عکس پیوست شد.` + : 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.'; await load(); } catch (e) { error.value = apiMessage(e); @@ -115,16 +195,22 @@ async function downloadAttachment(id: string, fileName: string) { } async function upload(id: string, event: Event) { - const file = (event.target as HTMLInputElement).files?.[0]; + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + input.value = ''; if (!file) return; - const body = new FormData(); - body.append('file', file); + error.value = ''; + ok.value = ''; + photoBusy.value = true; try { - await api.post(`/treasury/documents/${id}/attachments`, body); - ok.value = 'پیوست ذخیره شد.'; + const prepared = await prepareTreasuryImage(file); + await uploadPreparedFile(id, prepared.file); + ok.value = 'عکس پیوست ذخیره شد.'; await load(); } catch (e) { - error.value = apiMessage(e); + error.value = e instanceof Error && !(axios.isAxiosError(e)) ? e.message : apiMessage(e); + } finally { + photoBusy.value = false; } } @@ -139,6 +225,9 @@ async function voidDoc(id: string) { } watch(() => props.kind, () => { + resetForm(); + error.value = ''; + ok.value = ''; void load(); }); @@ -184,8 +273,30 @@ onMounted(() => { - ثبت - خروجی اکسل +
+
+ عکس فاکتور / رسید + اختیاری · فشرده‌سازی خودکار · حداکثر ۲۰۰ کیلوبایت برای هر عکس · تا {{ PHOTO_LIMIT }} عکس +
+
+
+ + +
+
+ +
+ ثبت + خروجی اکسل
@@ -210,9 +321,9 @@ onMounted(() => { > {{ file.fileName }} -
@@ -231,7 +342,51 @@ onMounted(() => { .side { display: grid; justify-items: end; gap: 0.3rem; } .side button, .file { border: 0; background: transparent; color: #b91c1c; cursor: pointer; font: inherit; } .file { color: #0f766e; font-weight: 700; } +.file.busy { opacity: 0.6; pointer-events: none; } .file input { display: none; } +.photos { display: grid; gap: 0.55rem; margin-bottom: 0.85rem; } +.photos-head { display: grid; gap: 0.15rem; } +.photos-head small { color: #64748b; font-size: 0.82rem; } +.thumbs { display: flex; flex-wrap: wrap; gap: 0.55rem; } +.thumbs figure { + margin: 0; + width: 88px; + display: grid; + gap: 0.25rem; + justify-items: center; +} +.thumbs img { + width: 88px; + height: 88px; + object-fit: cover; + border-radius: 12px; + border: 1px solid #e2e8f0; + background: #f8fafc; +} +.thumbs button { + border: 0; + background: transparent; + color: #b91c1c; + cursor: pointer; + font: inherit; + font-size: 0.8rem; +} +.add-photo { + display: inline-flex; + align-items: center; + justify-content: center; + width: fit-content; + min-height: var(--control-h); + padding: 0 0.9rem; + border: 1px dashed #94a3b8; + border-radius: 12px; + background: #fff; + color: #0f766e; + font-weight: 700; + cursor: pointer; +} +.add-photo.busy { opacity: 0.55; pointer-events: none; } +.add-photo input { display: none; } .err { color: #b91c1c; font-weight: 700; } .ok { color: #0f766e; font-weight: 700; } diff --git a/apps/web/src/views/treasury/TreasuryExpensesView.vue b/apps/web/src/views/treasury/TreasuryExpensesView.vue index 7c4054c..75d0043 100644 --- a/apps/web/src/views/treasury/TreasuryExpensesView.vue +++ b/apps/web/src/views/treasury/TreasuryExpensesView.vue @@ -6,13 +6,10 @@ import { Button as AButton, Card as ACard, Col as ACol, - Divider as ADivider, - Empty as AEmpty, Flex as AFlex, Form as AForm, FormItem as AFormItem, Input as AInput, - List as AList, Row as ARow, Segmented as ASegmented, Select as ASelect, @@ -30,16 +27,20 @@ import type { } from '@mento/shared'; import JalaliDateInput from '@/components/JalaliDateInput.vue'; import MoneyInput from '@/components/MoneyInput.vue'; +import TreasuryDocPhotoField from '@/components/treasury/TreasuryDocPhotoField.vue'; +import TreasuryDocumentsPanel from '@/components/treasury/TreasuryDocumentsPanel.vue'; import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue'; import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue'; import { useSettleDefault } from '@/components/treasury/useSettleDefault'; +import { + uploadTreasuryDocumentPhotos, + type TreasuryPendingPhoto, +} from '@/lib/treasury-doc-photos'; import { partyNetPosition, toman } from './treasury-format'; import { useTreasuryMobile } from './useTreasuryMobile'; import { parseMoneyNumber } from '@/lib/money'; const { Text: ATypographyText } = Typography; -const AListItem = AList.Item; -const AListItemMeta = AList.Item.Meta; const ASelectOption = ASelect.Option; const isMobile = useTreasuryMobile(); @@ -52,6 +53,7 @@ const accounts = ref([]); const error = ref(''); const ok = ref(''); const saving = ref(false); +const pendingPhotos = ref([]); const q = ref(''); const form = ref({ title: '', @@ -95,17 +97,6 @@ function apiMessage(e: unknown) { return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; } -function docLine(item: FinancialDocumentDto) { - const parts = [ - item.reference ? `پیگیری ${item.reference}` : '', - item.partyName || 'بدون طرف حساب', - statusLabel[item.status] ?? item.status, - `مانده ${toman(item.remaining)}`, - ].filter(Boolean); - if (item.categoryName) parts.push(item.categoryName); - return parts.join(' · '); -} - async function load() { const [docs, cats, acc, bals, receivables] = await Promise.all([ api.get('/treasury/documents', { params: { kind, q: q.value || undefined } }), @@ -202,7 +193,17 @@ async function createDoc() { notes: form.value.notes || null, bookedAt: form.value.bookedAt || undefined, }); + const photos = [...pendingPhotos.value]; + let attached = 0; + if (photos.length) { + try { + attached = await uploadTreasuryDocumentPhotos(data.id, photos); + } catch (e) { + error.value = apiMessage(e); + } + } settleMirror.reset(); + pendingPhotos.value = []; form.value = { title: '', amount: '', @@ -215,11 +216,12 @@ async function createDoc() { notes: '', bookedAt: formatLocalDateInput(new Date()), }; - ok.value = collectsBalance + const base = collectsBalance ? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.` : data.reference ? `سند ثبت شد. شماره پیگیری: ${data.reference}` : 'سند ثبت شد.'; + ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base; await load(); } catch (e) { error.value = apiMessage(e); @@ -279,16 +281,6 @@ const partyPosition = computed(() => { return partyNetPosition(receivable, payable); }); -async function voidDoc(id: string) { - if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return; - try { - await api.post(`/treasury/documents/${id}/void`, { reason: 'ابطال توسط مدیر' }); - await load(); - } catch (e) { - error.value = apiMessage(e); - } -} - onMounted(() => { void load().catch(() => { error.value = 'بارگذاری ناموفق بود.'; @@ -298,190 +290,154 @@ onMounted(() => { diff --git a/apps/web/src/views/treasury/TreasuryIncomesView.vue b/apps/web/src/views/treasury/TreasuryIncomesView.vue index 23eb27b..2eae861 100644 --- a/apps/web/src/views/treasury/TreasuryIncomesView.vue +++ b/apps/web/src/views/treasury/TreasuryIncomesView.vue @@ -6,14 +6,11 @@ import { Button as AButton, Card as ACard, Col as ACol, - Divider as ADivider, - Empty as AEmpty, Flex as AFlex, Form as AForm, FormItem as AFormItem, Grid, Input as AInput, - List as AList, Row as ARow, Segmented as ASegmented, Select as ASelect, @@ -31,15 +28,19 @@ import type { } from '@mento/shared'; import JalaliDateInput from '@/components/JalaliDateInput.vue'; import MoneyInput from '@/components/MoneyInput.vue'; +import TreasuryDocPhotoField from '@/components/treasury/TreasuryDocPhotoField.vue'; +import TreasuryDocumentsPanel from '@/components/treasury/TreasuryDocumentsPanel.vue'; import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue'; import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue'; import { useSettleDefault } from '@/components/treasury/useSettleDefault'; +import { + uploadTreasuryDocumentPhotos, + type TreasuryPendingPhoto, +} from '@/lib/treasury-doc-photos'; import { partyNetPosition, toman } from './treasury-format'; import { parseMoneyNumber } from '@/lib/money'; const { Text: ATypographyText } = Typography; -const AListItem = AList.Item; -const AListItemMeta = AList.Item.Meta; const ASelectOption = ASelect.Option; const screens = Grid.useBreakpoint(); const isMobile = computed(() => !screens.value.md); @@ -53,6 +54,7 @@ const accounts = ref([]); const error = ref(''); const ok = ref(''); const saving = ref(false); +const pendingPhotos = ref([]); const q = ref(''); function emptyForm() { @@ -156,17 +158,6 @@ function apiMessage(e: unknown) { return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; } -function docLine(item: FinancialDocumentDto) { - const parts = [ - item.reference ? `پیگیری ${item.reference}` : '', - item.partyName || 'بدون طرف حساب', - statusLabel[item.status] ?? item.status, - `مانده ${toman(item.remaining)}`, - ].filter(Boolean); - if (item.categoryName) parts.push(item.categoryName); - return parts.join(' · '); -} - async function load() { const [docs, cats, acc, bals, payables] = await Promise.all([ api.get('/treasury/documents', { params: { kind, q: q.value || undefined } }), @@ -201,6 +192,7 @@ async function load() { function resetForm() { settleMirror.reset(); form.value = emptyForm(); + pendingPhotos.value = []; error.value = ''; ok.value = ''; } @@ -266,12 +258,22 @@ async function createDoc() { notes: form.value.notes || null, bookedAt: form.value.bookedAt || undefined, }); + const photos = [...pendingPhotos.value]; + let attached = 0; + if (photos.length) { + try { + attached = await uploadTreasuryDocumentPhotos(data.id, photos); + } catch (e) { + error.value = apiMessage(e); + } + } resetForm(); - ok.value = collectsBalance + const base = collectsBalance ? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.` : data.reference ? `سند ثبت شد. شماره پیگیری: ${data.reference}` : 'سند ثبت شد.'; + ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base; await load(); } catch (e) { error.value = apiMessage(e); @@ -280,16 +282,6 @@ async function createDoc() { } } -async function voidDoc(id: string) { - if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return; - try { - await api.post(`/treasury/documents/${id}/void`, { reason: 'ابطال توسط مدیر' }); - await load(); - } catch (e) { - error.value = apiMessage(e); - } -} - onMounted(() => { void load().catch(() => { error.value = 'بارگذاری ناموفق بود.'; @@ -299,199 +291,164 @@ onMounted(() => { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 0475a5d..00193ee 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -892,6 +892,7 @@ export type RolePermissionKey = | "treasury_reports" | "treasury_audit" | "treasury_categories" + | "treasury_documents_manage" | "behavior"; /** بخشی که مسئولش را می‌شود به کاربر دیگری داد */ @@ -947,6 +948,7 @@ export const ROLE_PERMISSION_ITEMS: Array<{ { key: "treasury_reports", label: "مالی — گزارش" }, { key: "treasury_audit", label: "مالی — سوابق" }, { key: "treasury_categories", label: "مالی — دسته‌بندی" }, + { key: "treasury_documents_manage", label: "مالی — ویرایش و حذف اسناد" }, { key: "behavior", label: "شخصیت‌شناسی و دستیار فروش" }, ]; @@ -990,6 +992,15 @@ export function treasurySectionAllowed( return perms.includes(section); } +/** ویرایش/حذف اسناد مالی — مالک، مدیر، یا کلید اختصاصی در نقش/override */ +export function canManageTreasuryDocuments( + role: string | null | undefined, + permissions: readonly string[] | null | undefined, +): boolean { + if (role === "owner" || role === "admin") return true; + return (permissions ?? []).includes("treasury_documents_manage"); +} + export interface OrgRoleMemberDto { id: string; fullName: string; @@ -6801,7 +6812,7 @@ export interface FinancialDocumentDto { reference: string | null; notes: string | null; createdAt: string; - attachments?: Array<{ id: string; fileName: string }>; + attachments?: Array<{ id: string; fileName: string; mimeType?: string }>; } export interface FinancialMovementDto { From 1b08ab1230a3bd7e0bb4f16b1148497e43c016c1 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 15 Nov 2026 13:48:30 +0330 Subject: [PATCH 02/25] Show selected account balance beside the treasury account field. Color the balance green, red, or gray on income and expense forms so users see cash position before posting. Co-authored-by: Cursor --- .../views/treasury/TreasuryExpensesView.vue | 23 +++++++++++++++++-- .../views/treasury/TreasuryIncomesView.vue | 23 +++++++++++++++++-- .../web/src/views/treasury/treasury-format.ts | 10 ++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/apps/web/src/views/treasury/TreasuryExpensesView.vue b/apps/web/src/views/treasury/TreasuryExpensesView.vue index 75d0043..abe01b8 100644 --- a/apps/web/src/views/treasury/TreasuryExpensesView.vue +++ b/apps/web/src/views/treasury/TreasuryExpensesView.vue @@ -36,7 +36,7 @@ import { uploadTreasuryDocumentPhotos, type TreasuryPendingPhoto, } from '@/lib/treasury-doc-photos'; -import { partyNetPosition, toman } from './treasury-format'; +import { accountBalanceTone, partyNetPosition, toman } from './treasury-format'; import { useTreasuryMobile } from './useTreasuryMobile'; import { parseMoneyNumber } from '@/lib/money'; @@ -281,6 +281,14 @@ const partyPosition = computed(() => { return partyNetPosition(receivable, payable); }); +const selectedAccountBalance = computed(() => { + const id = form.value.accountId; + if (!id) return null; + const account = accounts.value.find((row) => row.id === id); + if (!account) return null; + return accountBalanceTone(account.balance); +}); + onMounted(() => { void load().catch(() => { error.value = 'بارگذاری ناموفق بود.'; @@ -382,7 +390,18 @@ onMounted(() => { - + + { return partyNetPosition(receivable, payable); }); +const selectedAccountBalance = computed(() => { + const id = form.value.accountId; + if (!id) return null; + const account = accounts.value.find((row) => row.id === id); + if (!account) return null; + return accountBalanceTone(account.balance); +}); + watch(entryMode, () => { settleMirror.reset(); form.value.amount = ''; @@ -383,7 +391,18 @@ onMounted(() => { - + + 0) return { text: `موجودی ${toman(n)}`, type: 'success' as const }; + return { text: `موجودی ${toman(n)}`, type: 'danger' as const }; +} From 70524f4f2cb7875148cdf3d191465180f2fbe47b Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 15 Nov 2026 16:43:25 +0330 Subject: [PATCH 03/25] Allow treasury payments when account balance goes negative. Remove insufficient-balance blocks on document create, settle, and party collection so income/expense posting can overdraw an account. Co-authored-by: Cursor --- apps/api/src/treasury/treasury.service.ts | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/apps/api/src/treasury/treasury.service.ts b/apps/api/src/treasury/treasury.service.ts index 6a3abc6..0899246 100644 --- a/apps/api/src/treasury/treasury.service.ts +++ b/apps/api/src/treasury/treasury.service.ts @@ -635,12 +635,6 @@ export class TreasuryService { if (input.accountId) { const account = await this.requireAccount(actor.organizationId, input.accountId, actor); if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.'); - if (input.kind === 'expense' && settle.greaterThan(0)) { - const balance = await this.accountBalance(account.id); - if (balance.lessThan(settle)) { - throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.'); - } - } } const bookedAt = startOfDay(input.bookedAt) ?? new Date(); const settlement = input.settlement === true; @@ -983,12 +977,6 @@ export class TreasuryService { if (amount.greaterThan(available)) { throw new BadRequestException('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.'); } - if (input.kind === 'expense') { - const balance = await this.accountBalance(account.id); - if (balance.lessThan(amount)) { - throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.'); - } - } const occurredAt = startOfDay(input.occurredAt) ?? new Date(); let left = amount; const touched: string[] = []; @@ -1128,12 +1116,6 @@ export class TreasuryService { } const account = await this.requireAccount(actor.organizationId, input.accountId, actor); if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.'); - if (doc.kind === 'expense') { - const balance = await this.accountBalance(account.id); - if (balance.lessThan(amount)) { - throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.'); - } - } const nextSettled = settled.plus(amount); const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial'; await this.prisma.$transaction([ From abaf012342d8ac819566301751d6d1a693574580 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Tue, 17 Nov 2026 11:09:14 +0330 Subject: [PATCH 04/25] Fix activity comment file attach text and download. Link uploaded attachment ids to the comment entry, label photo-only notes as file attached, and expose view/download actions for non-image files. Co-authored-by: Cursor --- .../activities/ActivityCommentSheet.vue | 35 +++++--- .../activities/ActivityQuickView.vue | 83 +++++++++++++++++-- apps/web/src/views/ActivityDetailView.vue | 75 +++++++++++++++-- 3 files changed, 170 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/activities/ActivityCommentSheet.vue b/apps/web/src/components/activities/ActivityCommentSheet.vue index 5cd8345..80e9e04 100644 --- a/apps/web/src/components/activities/ActivityCommentSheet.vue +++ b/apps/web/src/components/activities/ActivityCommentSheet.vue @@ -16,7 +16,11 @@ import type { ActivityDto, ActivityType, OrganizationDto, OrgUserDto } from '@me const props = defineProps<{ activity: ActivityDto; saving?: boolean; - save: (payload: { text: string; photoOnly: boolean }) => Promise; + save: (payload: { + text: string; + photoOnly: boolean; + attachmentIds?: string[]; + }) => Promise; /** بالاتر از مودال خلاصهٔ فعالیت */ overlayZIndex?: number; }>(); @@ -233,28 +237,35 @@ async function toggleVoiceNote() { } } -async function uploadQueue(items: Array<{ localId: string; name: string; file: File }>, drop: (localId: string) => void) { +async function uploadQueue( + items: Array<{ localId: string; name: string; file: File }>, + drop: (localId: string) => void, +): Promise { + const ids: string[] = []; for (const item of items) { const form = new FormData(); form.append('file', item.file, item.name); - await api.post(`/activities/${props.activity.id}/images`, form); + const { data } = await api.post<{ id: string }>(`/activities/${props.activity.id}/images`, form); + ids.push(data.id); drop(item.localId); uploadedCount.value += 1; } + return ids; } -async function uploadPendingPhotos() { - await uploadQueue([...pendingPhotos.value], (localId) => { +async function uploadPendingPhotos(): Promise { + const photoIds = await uploadQueue([...pendingPhotos.value], (localId) => { pendingPhotos.value = pendingPhotos.value.filter((item) => item.localId !== localId); }); - await uploadQueue([...pendingVoices.value], (localId) => { + const voiceIds = await uploadQueue([...pendingVoices.value], (localId) => { const voice = pendingVoices.value.find((item) => item.localId === localId); if (voice) URL.revokeObjectURL(voice.url); pendingVoices.value = pendingVoices.value.filter((item) => item.localId !== localId); }); - await uploadQueue([...pendingFiles.value], (localId) => { + const fileIds = await uploadQueue([...pendingFiles.value], (localId) => { pendingFiles.value = pendingFiles.value.filter((item) => item.localId !== localId); }); + return [...photoIds, ...voiceIds, ...fileIds]; } async function submit() { @@ -268,11 +279,15 @@ async function submit() { pendingFiles.value.length > 0 || uploadedCount.value > 0; try { - await uploadPendingPhotos(); - await props.save({ text, photoOnly: hadPhoto && !text }); + const attachmentIds = await uploadPendingPhotos(); + await props.save({ + text, + photoOnly: hadPhoto && !text, + attachmentIds, + }); } catch (error) { photoError.value = - pendingPhotos.value.length > 0 + pendingPhotos.value.length > 0 || pendingFiles.value.length > 0 || pendingVoices.value.length > 0 ? apiMessage(error, 'افزودن فایل ناموفق بود.') : apiMessage(error, 'ثبت نظر ناموفق بود.'); } finally { diff --git a/apps/web/src/components/activities/ActivityQuickView.vue b/apps/web/src/components/activities/ActivityQuickView.vue index 56073a1..d0af29f 100644 --- a/apps/web/src/components/activities/ActivityQuickView.vue +++ b/apps/web/src/components/activities/ActivityQuickView.vue @@ -309,17 +309,35 @@ function apiMessage(e: unknown, fallback: string) { return fallback; } +function viewMedia(item: NoteMedia) { + window.open(item.url, '_blank', 'noopener,noreferrer'); +} + +function downloadMedia(item: NoteMedia) { + const link = document.createElement('a'); + link.href = item.url; + link.download = item.name || 'file'; + link.rel = 'noopener'; + document.body.appendChild(link); + link.click(); + link.remove(); +} + async function loadNoteMedia(row: ActivityDto) { clearNoteMedia(); const next: NoteMedia[] = []; for (const image of row.images ?? []) { - const mime = image.mimeType.toLowerCase(); + const mime = (image.mimeType || 'application/octet-stream').toLowerCase(); const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file'; try { const { data } = await api.get(`/activities/${row.id}/images/${image.id}`, { responseType: 'blob', }); - const url = URL.createObjectURL(data); + const blob = + data.type && data.type !== 'application/octet-stream' && !data.type.includes('json') + ? data + : new Blob([data], { type: mime }); + const url = URL.createObjectURL(blob); if (props.activityId !== row.id) { URL.revokeObjectURL(url); continue; @@ -455,10 +473,14 @@ async function postponeTo(iso: string) { } } -async function submitComment(payload: { text: string; photoOnly: boolean }) { +async function submitComment(payload: { + text: string; + photoOnly: boolean; + attachmentIds?: string[]; +}) { const id = props.activityId; const row = activity.value; - const body = payload.text.trim() || (payload.photoOnly ? 'عکس پیوست شد.' : ''); + const body = payload.text.trim() || (payload.photoOnly ? 'فایل پیوست شد.' : ''); if (!id || !row || !body) return; saving.value = true; error.value = ''; @@ -467,7 +489,9 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) { const now = new Date(); const author = auth.user?.fullName?.trim(); const stamp = `[${formatJalaliNumeric(now)} ساعت ${formatClockFa(now)}${author ? ` — ${author}` : ''}]`; - const entry = `${stamp}\n${body}`; + const ids = [...new Set((payload.attachmentIds ?? []).filter(Boolean))]; + const attachLine = ids.length ? `\n[[attachments:${ids.join(',')}]]` : ''; + const entry = `${stamp}\n${body}${attachLine}`; await api.patch(`/activities/${id}`, { description: prev ? `${prev}\n\n${entry}` : entry }); commentOpen.value = false; await load(id); @@ -597,11 +621,60 @@ function openFull() { :preview="{ zIndex: 1300 }" /> + + + + + {{ file.name }} + + مشاهده + دانلود + + +
+
+ + {{ file.name }} + + مشاهده + دانلود + + +
diff --git a/apps/web/src/views/ActivityDetailView.vue b/apps/web/src/views/ActivityDetailView.vue index 6243e82..d5af3e9 100644 --- a/apps/web/src/views/ActivityDetailView.vue +++ b/apps/web/src/views/ActivityDetailView.vue @@ -865,16 +865,20 @@ async function loadActivityImages(row: ActivityDto) { clearImageUrls(); const next: NoteMedia[] = []; for (const image of row.images ?? []) { - const mime = image.mimeType.toLowerCase(); + const mime = (image.mimeType || 'application/octet-stream').toLowerCase(); const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file'; try { const { data } = await api.get(`/activities/${row.id}/images/${image.id}`, { responseType: 'blob', }); + const blob = + data.type && data.type !== 'application/octet-stream' && !data.type.includes('json') + ? data + : new Blob([data], { type: mime }); next.push({ id: image.id, name: image.fileName, - url: URL.createObjectURL(data), + url: URL.createObjectURL(blob), kind, createdAt: image.createdAt, }); @@ -885,6 +889,20 @@ async function loadActivityImages(row: ActivityDto) { imageUrls.value = next; } +function viewMedia(item: NoteMedia) { + window.open(item.url, '_blank', 'noopener,noreferrer'); +} + +function downloadMedia(item: NoteMedia) { + const link = document.createElement('a'); + link.href = item.url; + link.download = item.name || 'file'; + link.rel = 'noopener'; + document.body.appendChild(link); + link.click(); + link.remove(); +} + async function loadUsers() { try { @@ -1004,8 +1022,12 @@ async function postponeTo(iso: string) { } } -async function submitComment(payload: { text: string; photoOnly: boolean }) { - const body = payload.text.trim() || (payload.photoOnly ? 'عکس پیوست شد.' : ''); +async function submitComment(payload: { + text: string; + photoOnly: boolean; + attachmentIds?: string[]; +}) { + const body = payload.text.trim() || (payload.photoOnly ? 'فایل پیوست شد.' : ''); if (!id.value || !activity.value || !body) return; saving.value = true; error.value = ''; @@ -1014,7 +1036,9 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) { const now = new Date(); const author = auth.user?.fullName?.trim(); const stamp = `[${formatJalaliNumeric(now)} ساعت ${formatClockFa(now)}${author ? ` — ${author}` : ''}]`; - const entry = `${stamp}\n${body}`; + const ids = [...new Set((payload.attachmentIds ?? []).filter(Boolean))]; + const attachLine = ids.length ? `\n[[attachments:${ids.join(',')}]]` : ''; + const entry = `${stamp}\n${body}${attachLine}`; const next = prev ? `${prev}\n\n${entry}` : entry; await api.patch(`/activities/${id.value}`, { description: next }); commentOpen.value = false; @@ -1663,7 +1687,11 @@ onUnmounted(() => {
@@ -1746,7 +1774,11 @@ onUnmounted(() => { @@ -2677,8 +2709,35 @@ dd { gap: 0.35rem; } -.note-files a { +.note-files li { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.note-file-name { color: #0f766e; + font-weight: 600; + word-break: break-word; +} + +.note-file-actions { + display: inline-flex; + gap: 0.35rem; +} + +.note-file-btn { + border: 1px solid #99f6e4; + background: #fff; + color: #0f766e; + border-radius: 0.45rem; + font: inherit; + font-size: 0.85rem; + font-weight: 700; + padding: 0.2rem 0.55rem; + cursor: pointer; } .dock { From 64280e85c454996ee777c347adab7c6ec4f80836 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Tue, 17 Nov 2026 15:40:14 +0330 Subject: [PATCH 05/25] Open treasury document detail/edit in centered modals with pagination. Register Ant Modal correctly so overlays are not stuck under the table, and add page size controls for the documents list. Co-authored-by: Cursor --- .../treasury/TreasuryDocumentsPanel.vue | 64 +++++++++++++++++-- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue index 8821efc..b18e266 100644 --- a/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue +++ b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue @@ -12,7 +12,8 @@ import { FormItem as AFormItem, Image as AImage, Input as AInput, - Modal, + Modal as AModal, + Pagination as APagination, Row as ARow, Select as ASelect, Space as ASpace, @@ -37,8 +38,9 @@ import { import JalaliDateInput from '@/components/JalaliDateInput.vue'; import MoneyInput from '@/components/MoneyInput.vue'; import { api } from '@/lib/api'; -import { formatJalaliNumeric, formatLocalDateInput } from '@/lib/jalali'; +import { formatJalaliNumeric, formatLocalDateInput, toFaDigits } from '@/lib/jalali'; import { parseMoneyNumber } from '@/lib/money'; +import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize'; import { useAuthStore } from '@/stores/auth'; import { toman } from '@/views/treasury/treasury-format'; import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile'; @@ -98,6 +100,9 @@ const previewUrls = ref>({}); const editOpen = ref(false); const editSaving = ref(false); const editId = ref(null); +const page = ref(1); +const pageSize = usePageSize('treasury.documents', 10); +const pageSizeOptions = PAGE_SIZE_OPTIONS.map(String); const editForm = reactive({ title: '', notes: '', @@ -210,12 +215,13 @@ async function saveEdit() { } function confirmVoid(row: FinancialDocumentDto) { - Modal.confirm({ + AModal.confirm({ title: 'ابطال سند', content: 'این سند و گردش متصل به آن باطل شود؟', okText: 'ابطال', okType: 'danger', cancelText: 'انصراف', + centered: true, async onOk() { try { await api.post(`/treasury/documents/${row.id}/void`, { reason: 'ابطال توسط کاربر' }); @@ -230,7 +236,7 @@ function confirmVoid(row: FinancialDocumentDto) { } function confirmDelete(row: FinancialDocumentDto) { - Modal.confirm({ + AModal.confirm({ title: 'حذف سند', content: row.status === 'void' @@ -239,6 +245,7 @@ function confirmDelete(row: FinancialDocumentDto) { okText: 'حذف', okType: 'danger', cancelText: 'انصراف', + centered: true, async onOk() { try { await api.delete(`/treasury/documents/${row.id}`); @@ -286,13 +293,42 @@ const searchModel = computed({ set: (value: string) => emit('update:q', value), }); +const pageCount = computed(() => Math.max(1, Math.ceil(props.rows.length / pageSize.value))); + +const pagedRows = computed(() => { + const start = (page.value - 1) * pageSize.value; + return props.rows.slice(start, start + pageSize.value); +}); + +watch( + () => [props.rows.length, props.q, pageSize.value] as const, + () => { + if (page.value > pageCount.value) page.value = pageCount.value; + if (page.value < 1) page.value = 1; + }, +); + function onSearch() { + page.value = 1; emit('reload'); } +function onPageSizeChange(size: number) { + pageSize.value = size; + page.value = 1; +} + +function paginationTotal(total: number) { + return `مجموع: ${toFaDigits(total)} مورد (صفحه ${toFaDigits(page.value)} از ${toFaDigits(pageCount.value)})`; +} + function asDoc(record: unknown): FinancialDocumentDto { return record as FinancialDocumentDto; } + +function modalContainer() { + return document.body; +} diff --git a/apps/web/src/views/LeadDetailView.vue b/apps/web/src/views/LeadDetailView.vue index f3a130f..df756be 100644 --- a/apps/web/src/views/LeadDetailView.vue +++ b/apps/web/src/views/LeadDetailView.vue @@ -97,6 +97,9 @@ const users = ref([]); const activities = ref([]); const stageId = ref(''); +const stageMoveOpen = ref(false); +const stageMoveReason = ref(''); +const stageMoveError = ref(''); const assigneeId = ref(''); const callOutcome = ref(''); const callBody = ref(''); @@ -270,18 +273,48 @@ async function saveEdit() { } } -async function changeStage() { +function openStageMove() { if (!stageId.value || stageId.value === lead.value?.stageId) return; + stageMoveReason.value = ''; + stageMoveError.value = ''; + stageMoveOpen.value = true; +} + +function cancelStageMove() { + stageMoveOpen.value = false; + stageMoveReason.value = ''; + stageMoveError.value = ''; + if (lead.value) stageId.value = lead.value.stageId; +} + +async function changeStage() { + if (!stageId.value || stageId.value === lead.value?.stageId) { + return Promise.reject(); + } + const reason = stageMoveReason.value.trim(); + if (!reason) { + stageMoveError.value = 'دلیل تغییر ستون را بنویسید.'; + return Promise.reject(); + } busy.value = true; error.value = ''; + stageMoveError.value = ''; try { - await api.patch(`/leads/${id.value}/move`, { stageId: stageId.value }); + await api.patch(`/leads/${id.value}/move`, { + stageId: stageId.value, + reason, + }); okMsg.value = 'وضعیت به‌روز شد.'; message.success(okMsg.value); moreOpen.value = false; + stageMoveOpen.value = false; + stageMoveReason.value = ''; await load(); } catch (e) { - error.value = apiError(e, 'تغییر وضعیت ناموفق بود.'); + const msg = apiError(e, 'تغییر وضعیت ناموفق بود.'); + stageMoveError.value = msg; + error.value = msg; + return Promise.reject(e); } finally { busy.value = false; } @@ -438,10 +471,15 @@ function openTel() { const feed = computed(() => { const rows: Array<{ key: string; title: string; by: string; at: string }> = []; for (const ev of lead.value?.events ?? []) { + const body = ev.body?.trim(); rows.push({ key: `ev-${ev.id}`, title: ev.title, - by: ev.body?.trim() || 'توسط سیستم', + by: body + ? ev.type === 'stage_changed' + ? `دلیل: ${body}` + : body + : 'توسط سیستم', at: ev.createdAt, }); } @@ -866,7 +904,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); - {{ ev.body }} + {{ ev.body }} @@ -936,7 +974,12 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); :options="stages.map((s) => ({ value: s.id, label: s.name }))" />
- + اعمال وضعیت @@ -1082,7 +1125,13 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); :options="stages.map((s) => ({ value: s.id, label: s.name }))" />
- اعمال وضعیت + + اعمال وضعیت + بایگانی @@ -2450,5 +2477,36 @@ onBeforeUnmount(() => { + + + + + انتقال {{ toFaDigits(selectedIds.length) }} لید به + «{{ stages.find((s) => s.id === bulkStageId)?.name || '—' }}» + + + + + diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 8577989..29c5290 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -6356,6 +6356,8 @@ export interface UpdateLeadRequest { notes?: string | null; estimatedValue?: number | null; stageId?: string; + /** الزامی هنگام تغییر ستون؛ در جدول زمانی لید ثبت می‌شود */ + reason?: string | null; assigneeId?: string | null; nextFollowUpAt?: string | null; lastContactAt?: string | null; @@ -6364,6 +6366,8 @@ export interface UpdateLeadRequest { export interface MoveLeadRequest { stageId: string; position?: number; + /** الزامی هنگام تغییر ستون؛ در جدول زمانی لید ثبت می‌شود */ + reason?: string | null; } export interface AssignLeadsRequest { @@ -6374,6 +6378,8 @@ export interface AssignLeadsRequest { export interface BulkLeadStageRequest { leadIds: string[]; stageId: string; + /** الزامی؛ در جدول زمانی هر لید ثبت می‌شود */ + reason?: string | null; } export interface AutoAssignLeadsRequest { From 749fca67387efe0fdccf37d1f5774330001c87c4 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Wed, 18 Nov 2026 18:50:51 +0330 Subject: [PATCH 16/25] Stop auto-assigning org owner on form leads; leave unassigned unless chosen. Co-authored-by: Cursor --- .../src/automations/automations.service.ts | 7 ++++- apps/api/src/lead-forms/lead-forms.service.ts | 26 ++++++++++++------- apps/web/src/views/LeadFormBuilderView.vue | 2 +- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/apps/api/src/automations/automations.service.ts b/apps/api/src/automations/automations.service.ts index ebbfd36..4d91cba 100644 --- a/apps/api/src/automations/automations.service.ts +++ b/apps/api/src/automations/automations.service.ts @@ -416,7 +416,10 @@ export class AutomationsService { await this.syncLeadAssigneeFromActivity(ctx, type === 'call' ? assigneeId : null); } - /** سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس را می‌گیرد. */ + /** + * سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس اتوماسیون را می‌گیرد. + * مالک سازمان به‌عنوان fallback ست نمی‌شود — فقط مسئول صریح فعالیت. + */ private async syncLeadAssigneeFromActivity( ctx: AutomationContext, activityAssigneeId: string | null, @@ -468,6 +471,7 @@ export class AutomationsService { ctx: AutomationContext, ref: StepRef, ): Promise { + /** مسئول فعلی رکورد؛ هرگز مالک سازمان را به‌صورت ضمنی اضافه نکن */ const fallback = ctx.assigneeId || ctx.ownerId || null; const mode = config.assignMode ?? (config.assigneeId ? 'user' : 'owner'); @@ -502,6 +506,7 @@ export class AutomationsService { return pickRoundRobin(valid, cursor.counter) ?? fallback; } + // mode === 'owner' → مسئول فعلی رکورد؛ اگر نباشد فعالیت بدون مسئول می‌ماند return fallback; } diff --git a/apps/api/src/lead-forms/lead-forms.service.ts b/apps/api/src/lead-forms/lead-forms.service.ts index 28f9fd6..ec38073 100644 --- a/apps/api/src/lead-forms/lead-forms.service.ts +++ b/apps/api/src/lead-forms/lead-forms.service.ts @@ -298,14 +298,20 @@ export class LeadFormsService { mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n'); } - const ownerId = await this.nextAssignee(form); + /** فقط از لیست صریح «توزیع نوبتی»؛ بدون fallback به مالک سازمان */ + const formAssigneeId = await this.nextAssignee(form); + /** فقط برای createdBy / رویدادها — مسئول لید نمی‌شود */ const actorId = - ownerId ?? + formAssigneeId ?? ( await this.prisma.user.findFirst({ where: { memberships: { - some: { organizationId: form.organizationId, role: 'owner' }, + some: { + organizationId: form.organizationId, + role: { in: ['owner', 'admin'] }, + isActive: true, + }, }, }, select: { id: true }, @@ -324,7 +330,7 @@ export class LeadFormsService { let message: string | null = null; if (form.createLead) { - const result = await this.upsertLead(form, mapped, ownerId ?? actorId, actorId); + const result = await this.upsertLead(form, mapped, formAssigneeId, actorId); leadId = result.leadId; status = result.status; leadCreated = result.created; @@ -344,12 +350,12 @@ export class LeadFormsService { personId = await this.upsertPerson( form.organizationId, mapped, - ownerId ?? actorId, + formAssigneeId ?? actorId, ); } if (form.createDeal) { - await this.createDeal(form, mapped, personId, actorId, ownerId); + await this.createDeal(form, mapped, personId, actorId, formAssigneeId); } else if (personId && mapped.notes && !form.createLead) { await this.prisma.person.update({ where: { id: personId }, @@ -394,7 +400,9 @@ export class LeadFormsService { entityId: personId ?? leadId ?? form.id, title, personId, - ownerId: ownerId ?? actorId, + /** فقط مسئول صریح فرم؛ مالک سازمان به‌عنوان fallback ست نمی‌شود */ + ownerId: formAssigneeId, + assigneeId: formAssigneeId, }; await this.automations.runTrigger('lead_submitted', { ...leadCtx, @@ -402,7 +410,7 @@ export class LeadFormsService { sourceId: form.id, sourceType: 'lead_form', leadId, - syncLeadAssignee: !ownerId && leadCreated && !!leadId, + syncLeadAssignee: !formAssigneeId && leadCreated && !!leadId, mobile: mapped.mobile ?? mapped.phone ?? null, formName: form.name, formValues: values, @@ -437,7 +445,7 @@ export class LeadFormsService { private async upsertLead( form: FormRow, mapped: MappedValues, - assigneeId: string, + assigneeId: string | null, actorId: string, ): Promise<{ leadId: string | null; diff --git a/apps/web/src/views/LeadFormBuilderView.vue b/apps/web/src/views/LeadFormBuilderView.vue index 733aad0..fd2a22d 100644 --- a/apps/web/src/views/LeadFormBuilderView.vue +++ b/apps/web/src/views/LeadFormBuilderView.vue @@ -855,7 +855,7 @@ onMounted(load); {{ u.fullName }} -

مسئولی انتخاب نشده. سرنخ جدید مسئولش همان مسئول اولین تماس اتوماسیون می‌شود؛ اگر تماسی ساخته نشود، مالک سازمان مسئول می‌ماند.

+

مسئولی انتخاب نشده. سرنخ جدید بدون مسئول ساخته می‌شود؛ اگر اتوماسیون تماس بسازد و مسئول مشخص داشته باشد، همان فرد روی لید هم ست می‌شود. مالک سازمان می‌تواند همهٔ لیدها را ببیند و کارشناس تعیین کند.

From 5c866e9b7555da3681888f8980e1060b734a90fa Mon Sep 17 00:00:00 2001 From: Mahdi Date: Wed, 18 Nov 2026 19:47:17 +0330 Subject: [PATCH 17/25] Improve Leads list filters and mobile toolbar layout. Co-authored-by: Cursor --- apps/web/src/views/LeadsView.vue | 795 ++++++++++++++++--------------- 1 file changed, 422 insertions(+), 373 deletions(-) diff --git a/apps/web/src/views/LeadsView.vue b/apps/web/src/views/LeadsView.vue index de33092..aeda5dc 100644 --- a/apps/web/src/views/LeadsView.vue +++ b/apps/web/src/views/LeadsView.vue @@ -114,54 +114,13 @@ const FOLLOW_UP_OPTIONS: Array<{ value: FollowUpKey; label: string }> = [ ]; const UNASSIGNED_VALUE = '__unassigned__'; -/** ردیف آمار صفحه لیدها — ترتیب و نام‌ها مطابق طرح */ -const LEAD_STAT_DEFS: Array<{ - label: string; - /** نام وضعیت‌های متناظر در دیتابیس */ - match: string[]; - tint: StageTint; - slot: 'pair' | 'solo'; -}> = [ - { - label: 'جدید', - match: ['جدید'], - tint: 'amber', - slot: 'pair', - }, - { - label: 'در حال پیگیری', - match: ['در حال پیگیری', 'پیگیری مجدد', 'تماس اولیه', 'تماس موفق'], - tint: 'peach', - slot: 'pair', - }, - { - label: 'مذاکره', - match: ['مذاکره'], - tint: 'mint', - slot: 'solo', - }, - { - label: 'آماده خرید', - match: ['آماده خرید'], - tint: 'violet', - slot: 'solo', - }, - { - label: 'عدم پاسخ', - match: ['عدم پاسخ'], - tint: 'rose', - slot: 'solo', - }, -]; - type LeadStatCard = { key: string; label: string; tint: StageTint; count: number; - /** مرحله اصلی برای فیلتر */ + /** شناسهٔ واقعی ستون برای فیلتر */ stageId: string; - slot: 'pair' | 'solo'; }; const route = useRoute(); @@ -342,11 +301,12 @@ function toggleFilterSection(name: NonNullable) { const filterAnchor = ref(null); const filterPopoverMaxHeight = ref('min(70vh, 32rem)'); +const filterPanelPos = ref({ top: 0, inlineEnd: 8 }); const filterPanelStyle = computed(() => ({ - position: 'absolute' as const, - top: 'calc(100% + 6px)', - insetInlineStart: '0', + position: 'fixed' as const, + top: `${filterPanelPos.value.top}px`, + insetInlineEnd: `${filterPanelPos.value.inlineEnd}px`, zIndex: 1050, width: 'min(20rem, calc(100vw - 1.5rem))', maxHeight: filterPopoverMaxHeight.value, @@ -360,13 +320,19 @@ const filterPanelStyle = computed(() => ({ function placeFilterPopover() { const el = filterAnchor.value; if (!el) return; - const space = Math.floor(window.innerHeight - el.getBoundingClientRect().bottom - 12); + const rect = el.getBoundingClientRect(); + const space = Math.floor(window.innerHeight - rect.bottom - 12); filterPopoverMaxHeight.value = `${Math.max(220, space)}px`; + filterPanelPos.value = { + top: rect.bottom + 6, + inlineEnd: Math.max(8, Math.round(window.innerWidth - rect.right)), + }; } function onFilterDocPointer(event: Event) { const target = event.target; if (!(target instanceof Node)) return; + if (target instanceof Element && target.closest('[data-lead-filter]')) return; if (filterAnchor.value?.contains(target)) return; if (document.getElementById('jalali-picker')?.contains(target)) return; moreFiltersOpen.value = false; @@ -556,23 +522,15 @@ const sortLabels: Record = { last_contact: 'آخرین تماس', }; +/** چیپ‌های فیلتر = ستون‌های واقعی سازمان (نه نام‌های ثابت قدیمی) */ const stageCards = computed((): LeadStatCard[] => { - return LEAD_STAT_DEFS.map((def) => { - const matched = stages.value.filter((s) => - def.match.some((name) => s.name.trim() === name), - ); - const count = matched.reduce((sum, s) => sum + (s.leadCount ?? 0), 0); - const primary = - matched.find((s) => s.name.trim() === def.match[0]) ?? matched[0]; - return { - key: def.label, - label: def.label, - tint: def.tint, - count, - stageId: primary?.id ?? '', - slot: def.slot, - }; - }); + return stages.value.map((s) => ({ + key: s.id, + label: s.name, + tint: stageTint(s.color), + count: s.leadCount ?? 0, + stageId: s.id, + })); }); const totalLeadsCount = computed(() => { @@ -580,22 +538,24 @@ const totalLeadsCount = computed(() => { return stages.value.reduce((sum, s) => sum + (s.leadCount ?? 0), 0) || total.value; }); +/** گزینه‌های سلکت موبایل — برچسب + تعداد */ +const stageFilterOptions = computed(() => [ + { + value: '', + label: `همه لیدها (${formatCount(totalLeadsCount.value)})`, + }, + ...stageCards.value.map((card) => ({ + value: card.stageId, + label: `${card.label} (${formatCount(card.count)})`, + })), +]); + function isStatActive(card: LeadStatCard) { - if (!card.stageId || !stageId.value) return false; - if (stageId.value === card.stageId) return true; - const def = LEAD_STAT_DEFS.find((d) => d.label === card.label); - if (!def) return false; - const matchedIds = stages.value - .filter((s) => def.match.some((name) => s.name.trim() === name)) - .map((s) => s.id); - return matchedIds.includes(stageId.value); + return Boolean(card.stageId && stageId.value === card.stageId); } function selectStatCard(card: LeadStatCard) { - if (!card.stageId) { - setStageFilter(''); - return; - } + if (!card.stageId) return; setStageFilter(isStatActive(card) ? '' : card.stageId); } @@ -1586,14 +1546,36 @@ onBeforeUnmount(() => { + + + + + + انتقال از «{{ lead?.stageName || '—' }}» به «{{ stages.find((s) => s.id === stageId)?.name || '—' }}» + + + + + + + diff --git a/apps/web/src/views/LeadsView.vue b/apps/web/src/views/LeadsView.vue index ec749c2..debfb7b 100644 --- a/apps/web/src/views/LeadsView.vue +++ b/apps/web/src/views/LeadsView.vue @@ -1293,7 +1293,7 @@ async function bulkStageSelected() { if (!bulkStageId.value || !selectedIds.value.length) return Promise.reject(); const reason = bulkStageReason.value.trim(); if (!reason) { - bulkStageReasonError.value = 'دلیل تغییر ستون را بنویسید.'; + bulkStageReasonError.value = 'دلیل تغییر وضعیت را بنویسید.'; return Promise.reject(); } busy.value = true; @@ -2194,7 +2194,10 @@ onBeforeUnmount(() => { :pagination="false" :row-key="(r: LeadDto) => r.id" :scroll="{ x: 1100 }" - :custom-row="(record: LeadDto) => ({ onClick: () => goDetail(record.id) })" + :custom-row="(record: LeadDto) => ({ + onClick: () => goDetail(record.id), + style: { cursor: 'pointer' }, + })" >