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

531 lines
19 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
List as AList,
Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem,
Row as ARow,
Space as ASpace,
Table as ATable,
Tabs as ATabs,
Typography,
message,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons-vue';
import * as XLSX from 'xlsx';
import type { TreasuryPartyBalanceDto } from '@mento/shared';
import { api } from '@/lib/api';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import {
dateToJalali,
formatJalaliNumeric,
formatLocalDateInput,
jalaliMonthName,
jalaliToDate,
toFaDigits,
} from '@/lib/jalali';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
const { Text: ATypographyText } = Typography;
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ATabPane = ATabs.TabPane;
type Period = {
bookedIncome: string;
invoiceSales: string;
invoiceCredits: string;
bookedExpense: string;
operatingProfit: string;
cashIn: string;
cashOut: string;
cashNet: string;
expenseCategories: Array<{ name: string; amount: string; share: string }>;
};
type MetricRow = {
key: string;
label: string;
current: string;
previous: string;
};
type PayableMonth = { month: string; label?: string; amount: string };
const todayJalali = dateToJalali(new Date());
const fromDate = ref(formatLocalDateInput(jalaliToDate(todayJalali.jy, todayJalali.jm, 1)));
const toDate = ref(formatLocalDateInput(new Date()));
const rangeFrom = ref('');
const rangeTo = ref('');
const previousFrom = ref('');
const previousTo = ref('');
const current = ref<Period | null>(null);
const previous = ref<Period | null>(null);
const payablesByMonth = ref<PayableMonth[]>([]);
const receivablesByParty = ref<Array<{ name: string; amount: string }>>([]);
const debtors = ref<TreasuryPartyBalanceDto[]>([]);
const creditors = ref<TreasuryPartyBalanceDto[]>([]);
const reportTab = ref('periods');
const loading = ref(false);
const error = ref('');
const balanceError = ref('');
const kindLabel: Record<string, string> = {
person: 'مشتری',
company: 'شرکت',
user: 'کاربر',
};
const lines = [
['درآمد ثبت‌شده', 'bookedIncome'],
['فروش فاکتور', 'invoiceSales'],
['فاکتور برگشتی', 'invoiceCredits'],
['هزینه ثبت‌شده', 'bookedExpense'],
['سود عملیاتی', 'operatingProfit'],
['ورود وجه', 'cashIn'],
['خروج وجه', 'cashOut'],
['خالص جریان نقدی', 'cashNet'],
] as const;
const currentRangeLabel = computed(() =>
rangeFrom.value && rangeTo.value
? `${formatJalaliNumeric(new Date(rangeFrom.value))} تا ${formatJalaliNumeric(new Date(rangeTo.value))}`
: '—',
);
const previousRangeLabel = computed(() =>
previousFrom.value && previousTo.value
? `${formatJalaliNumeric(new Date(previousFrom.value))} تا ${formatJalaliNumeric(new Date(previousTo.value))}`
: '—',
);
const metricColumns: TableColumnsType<MetricRow> = [
{ title: 'شاخص', dataIndex: 'label', key: 'label' },
{ title: 'این دوره', dataIndex: 'current', key: 'current' },
{ title: 'دوره قبل', dataIndex: 'previous', key: 'previous' },
];
const metricRows = computed<MetricRow[]>(() => {
if (!current.value || !previous.value) return [];
return lines.map(([label, key]) => ({
key,
label,
current: toman(current.value![key] || '0'),
previous: toman(previous.value![key] || '0'),
}));
});
const {
page: partyPage,
pageSize: partyPageSize,
pageSizeOptions: partyPageSizeOptions,
total: partyTotal,
pagedRows: pagedPartyRows,
onPageSizeChange: onPartyPageSizeChange,
showTotal: partyShowTotal,
} = useTreasuryListPaging(() => receivablesByParty.value, 'treasury.reports-party');
const {
page: monthPage,
pageSize: monthPageSize,
pageSizeOptions: monthPageSizeOptions,
total: monthTotal,
pagedRows: pagedMonthRows,
onPageSizeChange: onMonthPageSizeChange,
showTotal: monthShowTotal,
} = useTreasuryListPaging(() => payablesByMonth.value, 'treasury.reports-month');
const {
page: expenseCatPage,
pageSize: expenseCatPageSize,
pageSizeOptions: expenseCatPageSizeOptions,
total: expenseCatTotal,
pagedRows: pagedExpenseCats,
onPageSizeChange: onExpenseCatPageSizeChange,
showTotal: expenseCatShowTotal,
} = useTreasuryListPaging(
() => current.value?.expenseCategories ?? [],
'treasury.reports-expense-cats',
);
function monthTitle(item: PayableMonth) {
if (item.label) return item.label;
const match = /^(\d{4})-(\d{2})$/.exec(item.month);
if (!match) return item.month;
const year = Number(match[1]);
const month = Number(match[2]);
if (year > 1700) {
const j = dateToJalali(new Date(year, month - 1, 15));
return `${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
}
return `${jalaliMonthName(month)} ${toFaDigits(year)}`;
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<{
from?: string;
to?: string;
previousFrom?: string;
previousTo?: string;
current: Period;
previous: Period;
payablesByMonth: PayableMonth[];
receivablesByParty: Array<{ name: string; amount: string }>;
}>('/treasury/reports', {
params: {
from: fromDate.value || undefined,
to: toDate.value || undefined,
},
});
const fromIso = data.from || `${fromDate.value}T00:00:00`;
const toIso = data.to || `${toDate.value}T23:59:59`;
const fromJ = dateToJalali(new Date(fromIso));
const prevMonth = {
jy: fromJ.jm === 1 ? fromJ.jy - 1 : fromJ.jy,
jm: fromJ.jm === 1 ? 12 : fromJ.jm - 1,
};
const fallbackPrevFrom = jalaliToDate(prevMonth.jy, prevMonth.jm, 1);
const nextOfPrev = jalaliToDate(
prevMonth.jm === 12 ? prevMonth.jy + 1 : prevMonth.jy,
prevMonth.jm === 12 ? 1 : prevMonth.jm + 1,
1,
);
const fallbackPrevTo = new Date(nextOfPrev.getTime() - 1);
rangeFrom.value = fromIso;
rangeTo.value = toIso;
previousFrom.value = data.previousFrom || fallbackPrevFrom.toISOString();
previousTo.value = data.previousTo || fallbackPrevTo.toISOString();
current.value = data.current;
previous.value = data.previous;
payablesByMonth.value = data.payablesByMonth;
receivablesByParty.value = data.receivablesByParty;
} catch {
error.value = 'گزارش بارگذاری نشد.';
} finally {
loading.value = false;
}
}
function applyRange() {
if (!fromDate.value || !toDate.value) {
message.warning('از تاریخ و تا تاریخ را مشخص کنید.');
return;
}
if (fromDate.value > toDate.value) {
message.warning('بازهٔ تاریخ نامعتبر است.');
return;
}
void load();
}
function resetToCurrentJalaliMonth() {
const today = dateToJalali(new Date());
fromDate.value = formatLocalDateInput(jalaliToDate(today.jy, today.jm, 1));
toDate.value = formatLocalDateInput(new Date());
void load();
}
function sumRemaining(rows: TreasuryPartyBalanceDto[]) {
return rows.reduce((sum, row) => sum + Number(row.remaining || 0), 0).toFixed(2);
}
function exportParties(
rows: TreasuryPartyBalanceDto[],
title: string,
settledLabel: string,
filename: string,
) {
const body = rows.map((row) => [
row.partyName,
(row.partyKind && kindLabel[row.partyKind]) || 'ثبت قبلی',
Number(row.amount),
Number(row.settledAmount),
Number(row.remaining),
]);
const totals = rows.reduce(
(sum, row) => ({
amount: sum.amount + Number(row.amount || 0),
settled: sum.settled + Number(row.settledAmount || 0),
remaining: sum.remaining + Number(row.remaining || 0),
}),
{ amount: 0, settled: 0, remaining: 0 },
);
body.push(['جمع', '', totals.amount, totals.settled, totals.remaining]);
const sheet = XLSX.utils.aoa_to_sheet([
['طرف حساب', 'نوع', 'مبلغ کل', settledLabel, 'مانده'],
...body,
]);
const book = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book, sheet, title);
XLSX.writeFile(book, filename);
}
async function loadBalances() {
const [income, expense] = await Promise.all([
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'income' } }),
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'expense' } }),
]);
debtors.value = income.data;
creditors.value = expense.data;
}
async function download() {
const { data } = await api.get<Blob>('/treasury/reports/export', {
responseType: 'blob',
params: {
from: fromDate.value || undefined,
to: toDate.value || undefined,
},
});
const url = URL.createObjectURL(data);
const link = document.createElement('a');
link.href = url;
link.download = 'treasury-report.xlsx';
link.click();
URL.revokeObjectURL(url);
}
onMounted(() => {
void load();
void loadBalances().catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 404 || e.response?.status === 403)) {
debtors.value = [];
creditors.value = [];
return;
}
balanceError.value = 'مانده بدهکاران و بستانکاران بارگذاری نشد.';
});
});
</script>
<template>
<a-flex vertical :gap="16">
<a-card :bordered="false">
<a-form layout="vertical" @finish="applyRange">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="از تاریخ">
<JalaliDateInput v-model="fromDate" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تا تاریخ">
<JalaliDateInput v-model="toDate" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label=" ">
<a-space :size="8" wrap>
<a-button type="primary" html-type="submit" :loading="loading">
<template #icon><SearchOutlined /></template>
اعمال بازه
</a-button>
<a-button :disabled="loading" @click="resetToCurrentJalaliMonth">
ماه جاری شمسی
</a-button>
<a-button :disabled="loading" @click="download">
<template #icon><DownloadOutlined /></template>
خروجی اکسل
</a-button>
</a-space>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-typography-text type="secondary">
پیش‌فرض: از اول ماه شمسی جاری تا امروز. «دوره قبل» همیشه ماه شمسی کاملِ قبل (اول تا آخر ماه) است.
</a-typography-text>
</a-card>
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="balanceError" type="error" show-icon :message="balanceError" />
<a-card :bordered="false">
<a-tabs v-model:activeKey="reportTab">
<a-tab-pane key="periods" tab="مقایسه دوره‌ها">
<a-flex vertical :gap="16">
<a-descriptions bordered :column="isMobile ? 1 : 2">
<a-descriptions-item label="این دوره">{{ currentRangeLabel }}</a-descriptions-item>
<a-descriptions-item label="دوره قبل">{{ previousRangeLabel }}</a-descriptions-item>
</a-descriptions>
<a-flex v-if="isMobile && metricRows.length" vertical :gap="12">
<a-card
v-for="item in metricRows"
:key="item.key"
:title="item.label"
:bordered="false"
>
<a-flex vertical :gap="8">
<a-flex justify="space-between" align="center" :gap="8">
<a-typography-text type="secondary">این دوره</a-typography-text>
<a-typography-text strong style="text-align: end">
{{ item.current }}
</a-typography-text>
</a-flex>
<a-flex justify="space-between" align="center" :gap="8">
<a-typography-text type="secondary">دوره قبل</a-typography-text>
<a-typography-text style="text-align: end">
{{ item.previous }}
</a-typography-text>
</a-flex>
</a-flex>
</a-card>
</a-flex>
<a-table
v-else-if="metricRows.length"
:columns="metricColumns"
:data-source="metricRows"
:pagination="false"
:loading="loading"
row-key="key"
/>
<a-empty v-else description="داده‌ای برای نمایش نیست." />
<a-divider orientation="right">مطالبات به تفکیک طرف حساب</a-divider>
<a-empty v-if="!receivablesByParty.length" description="مورد بازی نیست." />
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="pagedPartyRows"
>
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template>
<a-list-item-meta>
<template #title>{{ item.name }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="partyPage"
:total="partyTotal"
:page-size="partyPageSize"
:page-size-options="partyPageSizeOptions"
:show-total="partyShowTotal"
@update:page-size="onPartyPageSizeChange"
/>
<a-divider orientation="right">تعهدات به تفکیک ماه شمسی</a-divider>
<a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." />
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="pagedMonthRows"
>
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template>
<a-list-item-meta>
<template #title>{{ monthTitle(item) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="monthPage"
:total="monthTotal"
:page-size="monthPageSize"
:page-size-options="monthPageSizeOptions"
:show-total="monthShowTotal"
@update:page-size="onMonthPageSizeChange"
/>
<template v-if="current">
<a-divider orientation="right">سهم هزینه‌ها (این دوره)</a-divider>
<a-empty v-if="!current.expenseCategories.length" description="دسته‌ای نیست." />
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="pagedExpenseCats"
>
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a-typography-text strong>
{{ toman(item.amount) }} · {{ item.share }}٪
</a-typography-text>
</template>
<a-list-item-meta>
<template #title>{{ item.name }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="expenseCatPage"
:total="expenseCatTotal"
:page-size="expenseCatPageSize"
:page-size-options="expenseCatPageSizeOptions"
:show-total="expenseCatShowTotal"
@update:page-size="onExpenseCatPageSizeChange"
/>
</template>
</a-flex>
</a-tab-pane>
<a-tab-pane key="debtors" tab="بدهکاران">
<a-flex vertical :gap="16">
<a-typography-text type="secondary">
ماندهٔ فاکتور صادرشده و اسناد دریافتِ باز. صدور فاکتور سند درآمد جدا نمی‌سازد.
</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text type="secondary">
{{ debtors.length }} طرف حساب · جمع مانده {{ toman(sumRemaining(debtors)) }}
</a-typography-text>
<a-button @click="exportParties(debtors, 'بدهکاران', 'دریافت‌شده', 'debtors.xlsx')">
<template #icon><DownloadOutlined /></template>
خروجی اکسل
</a-button>
</a-flex>
<TreasuryPartyBalanceTable :rows="debtors" settled-label="دریافت‌شده" />
</a-flex>
</a-tab-pane>
<a-tab-pane key="creditors" tab="بستانکاران">
<a-flex vertical :gap="16">
<a-typography-text type="secondary">
ماندهٔ فاکتور برگشتی و اسناد هزینهٔ باز. برگشتی سند هزینهٔ جدا نمی‌سازد.
</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text type="secondary">
{{ creditors.length }} طرف حساب · جمع مانده {{ toman(sumRemaining(creditors)) }}
</a-typography-text>
<a-button
@click="exportParties(creditors, 'بستانکاران', 'پرداخت‌شده', 'creditors.xlsx')"
>
<template #icon><DownloadOutlined /></template>
خروجی اکسل
</a-button>
</a-flex>
<TreasuryPartyBalanceTable :rows="creditors" settled-label="پرداخت‌شده" />
</a-flex>
</a-tab-pane>
</a-tabs>
</a-card>
</a-flex>
</template>