merge: bring latest origin/main into dev (design local, logic main)

Keep local template/style for conflicted Vue pages; take main script/API/shared logic.
This commit is contained in:
2026-11-24 12:16:21 +03:30
74 changed files with 8558 additions and 1727 deletions
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import type { CustomerGroupDto, PersonImportSourceStatDto, PersonMood } from '@mento/shared';
import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared';
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
import { groupSwatch } from '@/lib/customer-groups';
import { toFaDigits } from '@/lib/jalali';
@@ -12,6 +13,7 @@ export type ContactsFilterValue = {
sources: string[];
moods: PersonMood[];
disc: string;
activityExperiences: string[];
};
const props = defineProps<{
@@ -33,7 +35,13 @@ const emit = defineEmits<{
close: [];
}>();
const draft = reactive<ContactsFilterValue>({ groups: [], sources: [], moods: [], disc: '' });
const draft = reactive<ContactsFilterValue>({
groups: [],
sources: [],
moods: [],
disc: '',
activityExperiences: [],
});
const draftSort = ref('');
const groupQuery = ref('');
const GROUP_SEARCH_MIN = 8;
@@ -50,6 +58,7 @@ watch(
draft.sources = [...props.value.sources];
draft.moods = [...props.value.moods];
draft.disc = props.value.disc;
draft.activityExperiences = [...(props.value.activityExperiences ?? [])];
draftSort.value = props.sort ?? defaultSort.value;
groupQuery.value = '';
},
@@ -77,7 +86,12 @@ const filteredGroups = computed(() => {
const draftCount = computed(
() =>
draft.groups.length +
(isPeople.value ? draft.sources.length + draft.moods.length + (draft.disc ? 1 : 0) : 0) +
(isPeople.value
? draft.sources.length +
draft.moods.length +
draft.activityExperiences.length +
(draft.disc ? 1 : 0)
: 0) +
(hasSort.value && draftSort.value !== defaultSort.value ? 1 : 0),
);
@@ -92,6 +106,7 @@ function clearAll() {
draft.sources = [];
draft.moods = [];
draft.disc = '';
draft.activityExperiences = [];
if (hasSort.value) draftSort.value = defaultSort.value;
}
@@ -103,6 +118,7 @@ function apply() {
sources: [...draft.sources],
moods: [...draft.moods],
disc: draft.disc,
activityExperiences: [...draft.activityExperiences],
},
hasSort.value ? draftSort.value : undefined,
);
@@ -210,6 +226,27 @@ function apply() {
</div>
</section>
<section class="sec">
<h4>
سابقه فعالیت
<span v-if="draft.activityExperiences.length" class="sel">
{{ toFaDigits(draft.activityExperiences.length) }} انتخاب
</span>
</h4>
<div class="pills">
<button
v-for="item in ACTIVITY_EXPERIENCE_OPTIONS"
:key="item"
type="button"
class="pill"
:class="{ on: draft.activityExperiences.includes(item) }"
@click="toggle(draft.activityExperiences, item)"
>
{{ item }}
</button>
</div>
</section>
<section v-if="canBehavior" class="sec">
<h4>تیپ DISC</h4>
<div class="pills">
@@ -158,6 +158,7 @@ function toCard(item: ActivityDto, stageId: string): PipelineDeal {
assigneeIds: (item.assignees ?? []).map((a) => a.id),
priority: item.priority,
activityStatus: item.status,
accountBalance: item.accountBalance ?? null,
};
}
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { computed } from 'vue';
import { theme } from 'ant-design-vue';
import type { ActivityAccountBalanceDto } from '@mento/shared';
import { formatTahesabBedBes } from '@/lib/tahesab';
const props = withDefaults(
defineProps<{
balance: ActivityAccountBalanceDto | null | undefined;
/** فشرده‌تر برای کارت کانبان */
compact?: boolean;
}>(),
{ compact: false },
);
const { token } = theme.useToken();
type Line = {
key: string;
label: string;
text: string;
value: number | null;
};
const lines = computed<Line[]>(() => {
const bal = props.balance;
if (!bal) return [];
const out: Line[] = [];
if (bal.rialBalance != null && Number.isFinite(bal.rialBalance)) {
out.push({
key: 'rial',
label: 'مانده ریالی',
text: `${formatTahesabBedBes(bal.rialBalance, 0)} ریال`,
value: bal.rialBalance,
});
}
for (const w of bal.weights ?? []) {
if (w.value == null || !Number.isFinite(w.value)) continue;
out.push({
key: w.key,
label: w.label,
text: `${formatTahesabBedBes(w.value, 3)} گرم`,
value: w.value,
});
}
return out;
});
const visible = computed(() => lines.value.length > 0);
function toneColor(value: number | null) {
if (value == null || !Number.isFinite(value) || value === 0) {
return token.value.colorTextSecondary;
}
return value < 0 ? token.value.colorError : token.value.colorSuccess;
}
</script>
<template>
<a-flex
v-if="visible"
vertical
:gap="compact ? 2 : 4"
:style="{ minWidth: 0, width: '100%' }"
>
<a-typography-text
v-for="line in lines"
:key="line.key"
dir="ltr"
:style="{
margin: 0,
display: 'block',
fontSize: `${compact ? token.fontSizeSM : token.fontSize}px`,
fontWeight: 600,
color: toneColor(line.value),
textAlign: 'right',
direction: 'rtl',
}"
:title="`${line.label}: ${line.text}`"
>
<a-typography-text
type="secondary"
:style="{
fontSize: `${token.fontSizeSM}px`,
fontWeight: 500,
marginInlineEnd: '6px',
}"
>
{{ line.label }}:
</a-typography-text>
{{ line.text }}
</a-typography-text>
</a-flex>
</template>
@@ -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<void>;
save: (payload: {
text: string;
photoOnly: boolean;
attachmentIds?: string[];
}) => Promise<void>;
/** بالاتر از مودال خلاصهٔ فعالیت */
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<string[]> {
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<string[]> {
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 {
@@ -31,6 +31,7 @@ import {
import { useAuthStore } from '@/stores/auth';
import { canCollaborateOnActivity, canMutateActivity } from '@/lib/activity-access';
import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
const props = defineProps<{
@@ -309,17 +310,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<Blob>(`/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;
@@ -425,7 +444,7 @@ async function runAction() {
const { data } = await api.patch<ActivityDto>(`/activities/${id}/complete`, undefined, {
params: undo ? { undo: '1' } : undefined,
});
if (data.status === 'done') {
if (data.status === 'done' || (!undo && data.completionMode === 'all')) {
emit('changed');
emit('close');
return;
@@ -455,10 +474,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 +490,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);
@@ -531,6 +556,16 @@ function openFull() {
</a-col>
</a-row>
<div
v-if="activity.accountBalance"
:style="{ marginTop: '12px' }"
>
<a-typography-text type="secondary" :style="{ display: 'block', marginBottom: '4px' }">
مانده حساب
</a-typography-text>
<ActivityAccountBalances :balance="activity.accountBalance" />
</div>
<a-divider :style="{ margin: '16px 0 12px' }" />
<a-flex justify="space-between" align="center" :style="{ marginBottom: '8px' }">
<a-typography-text strong>یادداشت</a-typography-text>
@@ -597,11 +632,60 @@ function openFull() {
:preview="{ zIndex: 1300 }"
/>
</a-flex>
<a-flex
v-if="entry.media.some((item) => item.kind === 'audio')"
vertical
:gap="8"
:style="{ marginTop: '8px' }"
>
<audio
v-for="voice in entry.media.filter((item) => item.kind === 'audio')"
:key="voice.id"
:src="voice.url"
controls
preload="metadata"
style="width: 100%"
/>
</a-flex>
<a-flex
v-if="entry.media.some((item) => item.kind === 'file')"
vertical
:gap="4"
:style="{ marginTop: '8px' }"
>
<a-flex
v-for="file in entry.media.filter((item) => item.kind === 'file')"
:key="file.id"
align="center"
justify="space-between"
:gap="8"
wrap="wrap"
>
<a-typography-text>{{ file.name }}</a-typography-text>
<a-space :size="4">
<a-button type="link" @click="viewMedia(file)">مشاهده</a-button>
<a-button type="link" @click="downloadMedia(file)">دانلود</a-button>
</a-space>
</a-flex>
</a-flex>
</div>
<div v-for="image in threadBlocks.loose.filter((item) => item.kind === 'image')" :key="image.id" :style="noteBubbleStyle">
<a-image :src="image.url" :alt="image.name" :width="72"
:height="72" :preview="{ zIndex: 1300 }" />
</div>
<div
v-for="file in threadBlocks.loose.filter((item) => item.kind === 'file')"
:key="file.id"
:style="noteBubbleStyle"
>
<a-flex align="center" justify="space-between" :gap="8" wrap="wrap">
<a-typography-text>{{ file.name }}</a-typography-text>
<a-space :size="4">
<a-button type="link" @click="viewMedia(file)">مشاهده</a-button>
<a-button type="link" @click="downloadMedia(file)">دانلود</a-button>
</a-space>
</a-flex>
</div>
</a-flex>
<div v-else-if="plainNote || looseImages.length" :style="noteBubbleStyle">
<a-typography-paragraph v-if="plainNote" :style="{ margin: 0, whiteSpace: 'pre-wrap' }">
@@ -20,6 +20,7 @@ import {
theme,
} from 'ant-design-vue';
import DealQuickActivityPopover from '@/components/pipeline/DealQuickActivityPopover.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import { calendarDaysBetween, formatJalaliNumeric } from '@/lib/jalali';
import { userAvatarSrc } from '@/lib/userAvatars';
import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board';
@@ -244,6 +245,12 @@ const cardStyle = computed(() => ({
>
{{ deal.description }}
</a-typography-text>
<ActivityAccountBalances
v-if="deal.accountBalance"
:balance="deal.accountBalance"
compact
:style="{ marginTop: '6px' }"
/>
</div>
<span :data-card-id="deal.id">
@@ -0,0 +1,89 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { Button as AButton, Upload as AUpload, message } from 'ant-design-vue';
import type { UploadFile, UploadProps } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress';
import type { TreasuryPendingPhoto } from '@/lib/treasury-doc-photos';
export type { TreasuryPendingPhoto };
const PHOTO_LIMIT = 8;
const props = withDefaults(
defineProps<{
disabled?: boolean;
}>(),
{ disabled: false },
);
const model = defineModel<TreasuryPendingPhoto[]>({ default: () => [] });
const busy = ref(false);
const fileList = computed<UploadFile[]>(() =>
model.value.map((photo) => ({
uid: photo.localId,
name: photo.name,
status: 'done',
url: photo.dataUrl,
})),
);
const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
if (props.disabled || busy.value) return AUpload.LIST_IGNORE;
if (model.value.length >= PHOTO_LIMIT) {
message.warning(`حداکثر ${PHOTO_LIMIT} عکس برای هر سند.`);
return AUpload.LIST_IGNORE;
}
const raw = file as File;
if (!raw.type.startsWith('image/')) {
message.error('فقط فایل تصویری مجاز است.');
return AUpload.LIST_IGNORE;
}
busy.value = true;
try {
const prepared = await prepareFormFieldFile(raw);
model.value = [
...model.value,
{
localId: crypto.randomUUID(),
name: prepared.name,
dataUrl: prepared.dataUrl,
file: prepared.file,
},
];
} catch (e) {
if (e instanceof FormFileTooLargeError) {
message.error('حجم عکس باید زیر ۲۰۰ کیلوبایت باشد');
} else {
message.error('فشرده‌سازی عکس ناموفق بود.');
}
} finally {
busy.value = false;
}
return AUpload.LIST_IGNORE;
};
const onRemove: UploadProps['onRemove'] = (file) => {
if (props.disabled || busy.value) return false;
model.value = model.value.filter((photo) => photo.localId !== file.uid);
return true;
};
</script>
<template>
<AUpload
list-type="picture"
accept="image/*"
:file-list="fileList"
:disabled="disabled || busy || model.length >= PHOTO_LIMIT"
:before-upload="beforeUpload"
:on-remove="onRemove"
multiple
>
<AButton :disabled="disabled || busy || model.length >= PHOTO_LIMIT">
<template #icon><UploadOutlined /></template>
{{ busy ? 'آماده‌سازی…' : 'افزودن عکس' }}
</AButton>
</AUpload>
</template>
@@ -0,0 +1,626 @@
<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 as AModal,
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 { useTreasuryListPaging } from '@/views/treasury/useTreasuryListPaging';
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
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 {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
resetPage,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => props.rows, 'treasury.documents');
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) {
AModal.confirm({
title: 'ابطال سند',
content: 'این سند و گردش متصل به آن باطل شود؟',
okText: 'ابطال',
okType: 'danger',
cancelText: 'انصراف',
centered: true,
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) {
AModal.confirm({
title: 'حذف سند',
content:
row.status === 'void'
? 'سند باطل‌شده برای همیشه حذف شود؟'
: 'سند بدون گردش برای همیشه حذف شود؟ در صورت داشتن دریافت/پرداخت ابتدا ابطال کنید.',
okText: 'حذف',
okType: 'danger',
cancelText: 'انصراف',
centered: true,
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() {
resetPage();
emit('reload');
}
function asDoc(record: unknown): FinancialDocumentDto {
return record as FinancialDocumentDto;
}
function modalContainer() {
return document.body;
}
</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="pagedRows"
: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 pagedRows" :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>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
<a-modal
v-model:open="detailOpen"
title="جزئیات سند"
:footer="null"
:width="isMobile ? '100%' : 720"
:get-container="modalContainer"
centered
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"
:get-container="modalContainer"
centered
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>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { Pagination as APagination } from 'ant-design-vue';
const page = defineModel<number>('page', { required: true });
defineProps<{
total: number;
pageSize: number;
pageSizeOptions: string[];
showTotal: (total: number) => string;
}>();
const emit = defineEmits<{
'update:pageSize': [size: number];
}>();
</script>
<template>
<a-pagination
v-if="total > 0"
v-model:current="page"
:page-size="pageSize"
:total="total"
:page-size-options="pageSizeOptions"
show-size-changer
:show-total="showTotal"
style="margin-top: 16px"
@update:page-size="emit('update:pageSize', $event)"
/>
</template>
@@ -7,7 +7,9 @@ import {
Typography,
} from 'ant-design-vue';
import type { TreasuryPartyBalanceDto } from '@mento/shared';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from '@/views/treasury/treasury-format';
import { useTreasuryListPaging } from '@/views/treasury/useTreasuryListPaging';
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
const props = defineProps<{
@@ -19,6 +21,16 @@ const isMobile = useTreasuryMobile();
const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => props.rows, 'treasury.party-balances');
const kindLabel: Record<string, string> = {
person: 'مشتری',
company: 'شرکت',
@@ -58,7 +70,7 @@ function kindOf(record: TreasuryPartyBalanceDto) {
<template>
<a-list
v-if="isMobile"
:data-source="rows"
:data-source="pagedRows"
:locale="{ emptyText: 'مانده‌ای نیست.' }"
>
<template #renderItem="{ item }">
@@ -87,9 +99,17 @@ function kindOf(record: TreasuryPartyBalanceDto) {
<a-table
v-else
:columns="columns"
:data-source="rows"
:data-source="pagedRows"
:pagination="false"
row-key="key"
:locale="{ emptyText: 'مانده‌ای نیست.' }"
/>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</template>