Files
CRM_Montzar/apps/web/src/views/treasury/TreasuryDocsView.vue
T

393 lines
14 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import type { FinancialAccountDto, FinancialCategoryDto, FinancialDocumentDto } from '@mento/shared';
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<FinancialDocumentDto[]>([]);
const categories = ref<FinancialCategoryDto[]>([]);
const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const photoBusy = ref(false);
const pendingPhotos = ref<PendingPhoto[]>([]);
const q = ref('');
const form = ref({
title: '',
amount: '',
categoryId: '',
partyName: '',
accountId: '',
settleAmount: '',
method: 'transfer',
reference: '',
notes: '',
});
const title = computed(() => (props.kind === 'income' ? 'دریافت‌ها و درآمدها' : 'پرداخت‌ها و هزینه‌ها'));
const settleLabel = computed(() => (props.kind === 'income' ? 'مبلغ دریافت‌شده' : 'مبلغ پرداخت‌شده'));
const statusLabel: Record<string, string> = {
open: props.kind === 'income' ? 'دریافت‌نشده' : 'پرداخت‌نشده',
partial: 'جزئی',
settled: props.kind === 'income' ? 'دریافت‌شده' : 'پرداخت‌شده',
void: 'باطل‌شده',
};
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 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<FinancialDocumentDto[]>('/treasury/documents', { params: { kind: props.kind, q: q.value || undefined } }),
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind: props.kind } }),
api.get<FinancialAccountDto[]>('/treasury/accounts'),
]);
rows.value = docs.data;
categories.value = cats.data.filter((row) => row.isActive);
accounts.value = acc.data.filter((row) => row.isActive);
}
async function createDoc() {
saving.value = true;
error.value = '';
ok.value = '';
try {
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
kind: props.kind,
title: form.value.title,
amount: form.value.amount,
categoryId: form.value.categoryId || null,
partyName: form.value.partyName || null,
accountId: form.value.accountId || null,
settleAmount: form.value.settleAmount || 0,
method: form.value.method,
reference: form.value.reference || null,
notes: form.value.notes || null,
});
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);
} finally {
saving.value = false;
}
}
async function downloadExcel() {
const { data } = await api.get<Blob>('/treasury/documents/export', {
params: { kind: props.kind },
responseType: 'blob',
});
const url = URL.createObjectURL(data);
const link = document.createElement('a');
link.href = url;
link.download = props.kind === 'income' ? 'incomes.xlsx' : 'expenses.xlsx';
link.click();
URL.revokeObjectURL(url);
}
async function downloadAttachment(id: string, fileName: string) {
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);
}
async function upload(id: string, event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
error.value = '';
ok.value = '';
photoBusy.value = true;
try {
const prepared = await prepareTreasuryImage(file);
await uploadPreparedFile(id, prepared.file);
ok.value = 'عکس پیوست ذخیره شد.';
await load();
} catch (e) {
error.value = e instanceof Error && !(axios.isAxiosError(e)) ? e.message : apiMessage(e);
} finally {
photoBusy.value = false;
}
}
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);
}
}
watch(() => props.kind, () => {
resetForm();
error.value = '';
ok.value = '';
void load();
});
onMounted(() => {
void load().catch(() => {
error.value = 'بارگذاری ناموفق بود.';
});
});
</script>
<template>
<section class="page">
<UiPageHeader :title="title" description="ثبت سند، موجودی را عوض نمی‌کند مگر مبلغ دریافت یا پرداخت واقعی وارد شود." />
<TreasuryNav />
<p v-if="error" class="err">{{ error }}</p>
<p v-if="ok" class="ok">{{ ok }}</p>
<UiCard title="سند جدید">
<div class="grid">
<UiField label="عنوان"><UiInput v-model="form.title" /></UiField>
<UiField label="مبلغ کل"><MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" /></UiField>
<UiField label="دسته‌بندی">
<select v-model="form.categoryId" class="select">
<option value="">بدون دسته</option>
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
</select>
</UiField>
<UiField label="طرف حساب"><UiInput v-model="form.partyName" /></UiField>
<UiField :label="settleLabel"><MoneyInput addon-after="تومان" v-model="form.settleAmount" :decimals="0" /></UiField>
<UiField label="حساب">
<select v-model="form.accountId" class="select">
<option value="">انتخاب حساب</option>
<option v-for="account in accounts" :key="account.id" :value="account.id">{{ account.name }}</option>
</select>
</UiField>
<UiField label="روش">
<select v-model="form.method" class="select">
<option value="cash">نقدی</option>
<option value="card_to_card">کارت‌به‌کارت</option>
<option value="pos">کارت‌خوان</option>
<option value="transfer">حواله</option>
<option value="other">سایر</option>
</select>
</UiField>
<UiField label="پیگیری"><UiInput v-model="form.reference" /></UiField>
</div>
<div class="photos">
<div class="photos-head">
<strong>عکس فاکتور / رسید</strong>
<small>اختیاری · فشرده‌سازی خودکار · حداکثر ۲۰۰ کیلوبایت برای هر عکس · تا {{ PHOTO_LIMIT }} عکس</small>
</div>
<div v-if="pendingPhotos.length" class="thumbs">
<figure v-for="photo in pendingPhotos" :key="photo.localId">
<img :src="photo.dataUrl" :alt="photo.name" />
<button type="button" :disabled="saving || photoBusy" @click="removePendingPhoto(photo.localId)">حذف</button>
</figure>
</div>
<label class="add-photo" :class="{ busy: photoBusy || saving || pendingPhotos.length >= PHOTO_LIMIT }">
{{ photoBusy ? 'در حال آماده‌سازی…' : 'افزودن عکس' }}
<input
type="file"
accept="image/*"
multiple
:disabled="saving || photoBusy || pendingPhotos.length >= PHOTO_LIMIT"
@change="onPhotosPicked"
/>
</label>
</div>
<UiButton :loading="saving || photoBusy" @click="createDoc">ثبت</UiButton>
<UiButton variant="secondary" :disabled="saving || photoBusy" @click="downloadExcel">خروجی اکسل</UiButton>
</UiCard>
<UiField label="جستجو"><UiInput v-model="q" @change="load" /></UiField>
<div class="list">
<article v-for="row in rows" :key="row.id">
<div>
<strong>{{ row.title }}</strong>
<small>
{{ statusLabel[row.status] }}
· مانده {{ toman(row.remaining) }}
<template v-if="row.categoryName"> · {{ row.categoryName }}</template>
</small>
</div>
<div class="side">
<b>{{ toman(row.amount) }}</b>
<button v-if="row.status !== 'void'" type="button" @click="voidDoc(row.id)">ابطال</button>
<button
v-for="file in row.attachments ?? []"
:key="file.id"
type="button"
class="file"
@click="downloadAttachment(file.id, file.fileName)"
>
{{ file.fileName }}
</button>
<label v-if="row.status !== 'void'" class="file" :class="{ busy: photoBusy }">
{{ photoBusy ? '…' : 'عکس پیوست' }}
<input type="file" accept="image/*" :disabled="photoBusy || saving" @change="upload(row.id, $event)" />
</label>
</div>
</article>
<p v-if="!rows.length" class="muted">سندی نیست.</p>
</div>
</section>
</template>
<style scoped>
.page { display: grid; gap: 1rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 0.7rem; margin-bottom: 0.8rem; }
.select { width: 100%; min-height: var(--control-h); border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
.list { display: grid; gap: 0.55rem; }
.list article { display: flex; justify-content: space-between; gap: 0.75rem; background: #fff; border: 1px solid #e7eef2; border-radius: 14px; padding: 0.8rem 1rem; }
.list small, .muted { color: #64748b; }
.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; }
</style>