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 <cursoragent@cursor.com>
This commit is contained in:
2026-11-15 12:42:01 +03:30
co-authored by Cursor
parent 3696713443
commit 4409ded0ab
10 changed files with 1383 additions and 451 deletions
@@ -0,0 +1,594 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue';
import axios from 'axios';
import {
Button as AButton,
Card as ACard,
Col as ACol,
Descriptions as ADescriptions,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Image as AImage,
Input as AInput,
Modal,
Row as ARow,
Select as ASelect,
Space as ASpace,
Table as ATable,
Tag as ATag,
Tooltip as ATooltip,
Typography,
message,
theme,
} from 'ant-design-vue';
import {
DeleteOutlined,
EditOutlined,
EyeOutlined,
StopOutlined,
} from '@ant-design/icons-vue';
import {
canManageTreasuryDocuments,
type FinancialCategoryDto,
type FinancialDocumentDto,
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import { api } from '@/lib/api';
import { formatJalaliNumeric, formatLocalDateInput } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
import { useAuthStore } from '@/stores/auth';
import { toman } from '@/views/treasury/treasury-format';
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
const props = defineProps<{
rows: FinancialDocumentDto[];
categories: FinancialCategoryDto[];
statusLabel: Record<string, string>;
q: string;
}>();
const emit = defineEmits<{
'update:q': [value: string];
reload: [];
}>();
const { Text: ATypographyText } = Typography;
const ASelectOption = ASelect.Option;
const ADescriptionsItem = ADescriptions.Item;
const AImagePreviewGroup = AImage.PreviewGroup;
const { token } = theme.useToken();
const auth = useAuthStore();
const isMobile = useTreasuryMobile();
const canManage = computed(() =>
canManageTreasuryDocuments(auth.user?.role, auth.user?.permissions),
);
const methodLabel: Record<string, string> = {
cash: 'نقدی',
card_to_card: 'کارت‌به‌کارت',
pos: 'کارت‌خوان',
transfer: 'حواله',
other: 'سایر',
};
const methodOptions = [
{ value: 'cash', label: 'نقدی' },
{ value: 'card_to_card', label: 'کارت‌به‌کارت' },
{ value: 'pos', label: 'کارت‌خوان' },
{ value: 'transfer', label: 'حواله' },
{ value: 'other', label: 'سایر' },
];
const statusColor: Record<string, string> = {
open: 'default',
partial: 'processing',
settled: 'success',
void: 'error',
};
const detailOpen = ref(false);
const detailLoading = ref(false);
const detail = ref<FinancialDocumentDto | null>(null);
const previewUrls = ref<Record<string, string>>({});
const editOpen = ref(false);
const editSaving = ref(false);
const editId = ref<string | null>(null);
const editForm = reactive({
title: '',
notes: '',
categoryId: undefined as string | undefined,
method: undefined as string | undefined,
bookedAt: '',
amount: '',
});
const editAmountLocked = ref(true);
function apiMessage(e: unknown) {
if (!axios.isAxiosError(e)) return 'عملیات ناموفق بود.';
const msg = (e.response?.data as { message?: string | string[] })?.message;
return Array.isArray(msg) ? msg.join('، ') : msg || 'عملیات ناموفق بود.';
}
function clearPreviews() {
for (const url of Object.values(previewUrls.value)) {
URL.revokeObjectURL(url);
}
previewUrls.value = {};
}
onBeforeUnmount(clearPreviews);
watch(detailOpen, (open) => {
if (!open) {
clearPreviews();
detail.value = null;
}
});
async function loadAttachmentPreview(id: string, mimeType?: string) {
if (previewUrls.value[id]) return;
if (mimeType && !mimeType.startsWith('image/')) return;
try {
const { data } = await api.get<Blob>(`/treasury/attachments/${id}`, { responseType: 'blob' });
if (!data || data.type.includes('json') || data.size === 0) return;
if (data.type && !data.type.startsWith('image/')) return;
previewUrls.value = { ...previewUrls.value, [id]: URL.createObjectURL(data) };
} catch {
/* ignore preview failures */
}
}
async function openDetail(row: FinancialDocumentDto) {
detailOpen.value = true;
detailLoading.value = true;
detail.value = row;
clearPreviews();
try {
const { data } = await api.get<FinancialDocumentDto>(`/treasury/documents/${row.id}`);
detail.value = data;
await Promise.all(
(data.attachments ?? []).map((att) => loadAttachmentPreview(att.id, att.mimeType)),
);
} catch (e) {
message.error(apiMessage(e));
} finally {
detailLoading.value = false;
}
}
function openEdit(row: FinancialDocumentDto) {
editId.value = row.id;
editForm.title = row.title;
editForm.notes = row.notes ?? '';
editForm.categoryId = row.categoryId ?? undefined;
editForm.method = row.method ?? undefined;
editForm.bookedAt = formatLocalDateInput(new Date(row.bookedAt));
editForm.amount = String(row.amount ?? '');
editAmountLocked.value = row.status !== 'open' || Number(row.settledAmount) > 0;
editOpen.value = true;
}
async function saveEdit() {
if (!editId.value) return;
const title = editForm.title.trim();
if (title.length < 2) {
message.warning('عنوان را وارد کنید.');
return;
}
editSaving.value = true;
try {
const body: Record<string, unknown> = {
title,
notes: editForm.notes.trim() || null,
categoryId: editForm.categoryId || null,
method: editForm.method || null,
bookedAt: editForm.bookedAt || undefined,
};
if (!editAmountLocked.value) {
const amount = parseMoneyNumber(String(editForm.amount ?? ''), 0) ?? 0;
if (amount <= 0) {
message.warning('مبلغ معتبر نیست.');
editSaving.value = false;
return;
}
body.amount = amount;
}
await api.patch(`/treasury/documents/${editId.value}`, body);
message.success('سند به‌روز شد.');
editOpen.value = false;
emit('reload');
} catch (e) {
message.error(apiMessage(e));
} finally {
editSaving.value = false;
}
}
function confirmVoid(row: FinancialDocumentDto) {
Modal.confirm({
title: 'ابطال سند',
content: 'این سند و گردش متصل به آن باطل شود؟',
okText: 'ابطال',
okType: 'danger',
cancelText: 'انصراف',
async onOk() {
try {
await api.post(`/treasury/documents/${row.id}/void`, { reason: 'ابطال توسط کاربر' });
message.success('سند باطل شد.');
emit('reload');
} catch (e) {
message.error(apiMessage(e));
throw e;
}
},
});
}
function confirmDelete(row: FinancialDocumentDto) {
Modal.confirm({
title: 'حذف سند',
content:
row.status === 'void'
? 'سند باطل‌شده برای همیشه حذف شود؟'
: 'سند بدون گردش برای همیشه حذف شود؟ در صورت داشتن دریافت/پرداخت ابتدا ابطال کنید.',
okText: 'حذف',
okType: 'danger',
cancelText: 'انصراف',
async onOk() {
try {
await api.delete(`/treasury/documents/${row.id}`);
message.success('سند حذف شد.');
emit('reload');
} catch (e) {
message.error(apiMessage(e));
throw e;
}
},
});
}
async function downloadAttachment(id: string, fileName: string) {
try {
const { data } = await api.get<Blob>(`/treasury/attachments/${id}`, { responseType: 'blob' });
const url = URL.createObjectURL(data);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
} catch (e) {
message.error(apiMessage(e));
}
}
const columns = computed(() => {
const cols = [
{ title: 'پیگیری', dataIndex: 'reference', key: 'reference', width: 150 },
{ title: 'عنوان', dataIndex: 'title', key: 'title' },
{ title: 'طرف حساب', dataIndex: 'partyName', key: 'partyName', width: 140 },
{ title: 'دسته', dataIndex: 'categoryName', key: 'categoryName', width: 120 },
{ title: 'مبلغ', key: 'amount', width: 130 },
{ title: 'مانده', key: 'remaining', width: 130 },
{ title: 'وضعیت', key: 'status', width: 110 },
{ title: 'تاریخ', key: 'bookedAt', width: 110 },
{ title: 'عملیات', key: 'actions', width: canManage.value ? 160 : 80 },
];
return cols;
});
const searchModel = computed({
get: () => props.q,
set: (value: string) => emit('update:q', value),
});
function onSearch() {
emit('reload');
}
function asDoc(record: unknown): FinancialDocumentDto {
return record as FinancialDocumentDto;
}
</script>
<template>
<a-card :bordered="false" title="فهرست اسناد">
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="جستجو">
<a-input
v-model:value="searchModel"
allow-clear
placeholder="عنوان یا شماره پیگیری"
@press-enter="onSearch"
@change="onSearch"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-table
v-else-if="!isMobile"
:columns="columns"
:data-source="rows"
:pagination="false"
:scroll="{ x: 1100 }"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'partyName'">
{{ record.partyName || 'بدون طرف حساب' }}
</template>
<template v-else-if="column.key === 'categoryName'">
{{ record.categoryName || '—' }}
</template>
<template v-else-if="column.key === 'amount'">
{{ toman(record.amount) }}
</template>
<template v-else-if="column.key === 'remaining'">
{{ toman(record.remaining) }}
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="statusColor[record.status] || 'default'">
{{ statusLabel[record.status] ?? record.status }}
</a-tag>
</template>
<template v-else-if="column.key === 'bookedAt'">
{{ formatJalaliNumeric(new Date(record.bookedAt)) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space :size="4">
<a-tooltip title="جزئیات">
<a-button
type="text"
aria-label="جزئیات"
:style="{ color: token.colorInfo }"
@click="openDetail(asDoc(record))"
>
<template #icon><EyeOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage && record.status !== 'void'" title="ویرایش">
<a-button
type="text"
aria-label="ویرایش"
:style="{ color: token.colorPrimary }"
@click="openEdit(asDoc(record))"
>
<template #icon><EditOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="record.status !== 'void'" title="ابطال">
<a-button
type="text"
aria-label="ابطال"
:style="{ color: token.colorWarning }"
@click="confirmVoid(asDoc(record))"
>
<template #icon><StopOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage" title="حذف">
<a-button
type="text"
aria-label="حذف"
:style="{ color: token.colorError }"
@click="confirmDelete(asDoc(record))"
>
<template #icon><DeleteOutlined /></template>
</a-button>
</a-tooltip>
</a-space>
</template>
</template>
</a-table>
<a-flex v-else vertical :gap="12">
<a-card v-for="item in rows" :key="item.id" :bordered="true">
<a-flex vertical :gap="8">
<a-flex justify="space-between" align="flex-start" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-tag :color="statusColor[item.status] || 'default'">
{{ statusLabel[item.status] ?? item.status }}
</a-tag>
</a-flex>
<a-typography-text type="secondary">
{{ item.reference ? `پیگیری ${item.reference}` : 'بدون پیگیری' }}
· {{ item.partyName || 'بدون طرف حساب' }}
</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">
{{ item.categoryName }}
</a-typography-text>
<a-flex justify="space-between" wrap="wrap" :gap="8">
<a-typography-text>مبلغ {{ toman(item.amount) }}</a-typography-text>
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ formatJalaliNumeric(new Date(item.bookedAt)) }}
</a-typography-text>
<a-space wrap :size="4">
<a-tooltip title="جزئیات">
<a-button
type="text"
aria-label="جزئیات"
:style="{ color: token.colorInfo }"
@click="openDetail(item)"
>
<template #icon><EyeOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage && item.status !== 'void'" title="ویرایش">
<a-button
type="text"
aria-label="ویرایش"
:style="{ color: token.colorPrimary }"
@click="openEdit(item)"
>
<template #icon><EditOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="item.status !== 'void'" title="ابطال">
<a-button
type="text"
aria-label="ابطال"
:style="{ color: token.colorWarning }"
@click="confirmVoid(item)"
>
<template #icon><StopOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage" title="حذف">
<a-button
type="text"
aria-label="حذف"
:style="{ color: token.colorError }"
@click="confirmDelete(item)"
>
<template #icon><DeleteOutlined /></template>
</a-button>
</a-tooltip>
</a-space>
</a-flex>
</a-card>
</a-flex>
</a-card>
<a-modal
v-model:open="detailOpen"
title="جزئیات سند"
:footer="null"
:width="isMobile ? '100%' : 720"
destroy-on-close
>
<a-flex v-if="detailLoading && !detail" justify="center">
<a-typography-text type="secondary">در حال بارگذاری…</a-typography-text>
</a-flex>
<template v-else-if="detail">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="عنوان">{{ detail.title }}</a-descriptions-item>
<a-descriptions-item label="پیگیری">{{ detail.reference || '—' }}</a-descriptions-item>
<a-descriptions-item label="طرف حساب">{{ detail.partyName || 'بدون طرف حساب' }}</a-descriptions-item>
<a-descriptions-item label="دسته">{{ detail.categoryName || '—' }}</a-descriptions-item>
<a-descriptions-item label="حساب">{{ detail.accountName || '—' }}</a-descriptions-item>
<a-descriptions-item label="روش">
{{ detail.method ? methodLabel[detail.method] || detail.method : '—' }}
</a-descriptions-item>
<a-descriptions-item label="مبلغ">{{ toman(detail.amount) }}</a-descriptions-item>
<a-descriptions-item label="تسویه">{{ toman(detail.settledAmount) }}</a-descriptions-item>
<a-descriptions-item label="مانده">{{ toman(detail.remaining) }}</a-descriptions-item>
<a-descriptions-item label="وضعیت">
{{ statusLabel[detail.status] ?? detail.status }}
</a-descriptions-item>
<a-descriptions-item label="تاریخ">
{{ formatJalaliNumeric(new Date(detail.bookedAt)) }}
</a-descriptions-item>
<a-descriptions-item label="یادداشت">{{ detail.notes || '—' }}</a-descriptions-item>
</a-descriptions>
<a-flex vertical :gap="12" style="margin-top: 16px">
<a-typography-text strong>پیوست‌ها</a-typography-text>
<a-empty
v-if="!(detail.attachments && detail.attachments.length)"
description="پیوستی نیست."
/>
<a-image-preview-group v-else>
<a-row :gutter="[12, 12]">
<a-col
v-for="att in detail.attachments"
:key="att.id"
:xs="24"
:sm="12"
:md="8"
>
<a-card :bordered="true">
<a-flex vertical :gap="8" align="center">
<a-image
v-if="previewUrls[att.id]"
:src="previewUrls[att.id]"
:alt="att.fileName"
style="width: 100%"
/>
<a-typography-text v-else type="secondary">{{ att.fileName }}</a-typography-text>
<a-button type="link" @click="downloadAttachment(att.id, att.fileName)">
دانلود
</a-button>
</a-flex>
</a-card>
</a-col>
</a-row>
</a-image-preview-group>
</a-flex>
</template>
</a-modal>
<a-modal
v-model:open="editOpen"
title="ویرایش سند"
ok-text="ذخیره"
cancel-text="انصراف"
:confirm-loading="editSaving"
:width="isMobile ? '100%' : 560"
destroy-on-close
@ok="saveEdit"
>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :span="24">
<a-form-item label="عنوان" required>
<a-input v-model:value="editForm.title" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ">
<JalaliDateInput v-model="editForm.bookedAt" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش">
<a-select
v-model:value="editForm.method"
allow-clear
placeholder="روش"
style="width: 100%"
>
<a-select-option v-for="opt in methodOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="دسته‌بندی">
<a-select
v-model:value="editForm.categoryId"
allow-clear
show-search
option-filter-prop="label"
placeholder="دسته"
style="width: 100%"
:options="categories.map((c) => ({ value: c.id, label: c.name }))"
/>
</a-form-item>
</a-col>
<a-col v-if="!editAmountLocked" :xs="24" :md="12">
<a-form-item label="مبلغ">
<MoneyInput v-model="editForm.amount" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="یادداشت">
<a-input v-model:value="editForm.notes" />
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-modal>
</template>