merge: bring latest origin/main into dev (main wins conflicts)

This commit is contained in:
jarvis
2026-11-15 11:44:04 +03:30
154 changed files with 20772 additions and 3734 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+63
View File
@@ -18,6 +18,7 @@ import {
FormItem as AFormItem,
Input as AInput,
InputNumber as AInputNumber,
Modal,
Modal as AModal,
Row as ARow,
Segmented as ASegmented,
@@ -44,9 +45,11 @@ import { toFaDigits } from '@/lib/jalali';
import { currencySuffix, formatMoney } from '@/lib/money';
import CustomFieldsSection from '@/components/CustomFieldsSection.vue';
import EntityTimeline from '@/components/EntityTimeline.vue';
import RelatedActivitiesPanel from '@/components/activities/RelatedActivitiesPanel.vue';
import RelatedTasksPanel from '@/components/routines/RelatedTasksPanel.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import StagePathStrip from '@/components/StagePathStrip.vue';
import UserMultiSelect from '@/components/UserMultiSelect.vue';
import PersonFormView from '@/views/PersonFormView.vue';
import type {
@@ -104,6 +107,7 @@ const pageTitle = computed(() => (isNew.value ? 'ایجاد معامله جدی
const loading = ref(false);
const saving = ref(false);
const stageMoving = ref(false);
const error = ref('');
const showOthers = ref(true);
const othersKeys = ref<string[]>(['others']);
@@ -197,6 +201,43 @@ const pipelineSelectOptions = computed(() =>
const stageSelectOptions = computed(() =>
stages.value.map((s) => ({ value: s.id, label: s.name })),
);
const stagePathItems = computed(() => stages.value.map((s) => ({ id: s.id, name: s.name })));
function onStageSelect(nextId: string) {
if (!nextId || nextId === stageId.value || stageMoving.value || saving.value) return;
const target = stages.value.find((stage) => stage.id === nextId);
if (!target) return;
const prev = stageId.value;
Modal.confirm({
title: 'جابه‌جایی مرحله',
content: `به مرحله «${target.name}» منتقل می‌شود. انجام شود؟`,
okText: 'انجام بده',
cancelText: 'انجام نده',
centered: true,
async onOk() {
stageId.value = nextId;
if (isNew.value || !id.value) return;
stageMoving.value = true;
error.value = '';
try {
await api.patch(`/deals/${id.value}/move`, { stageId: nextId });
} catch (e) {
stageId.value = prev;
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
error.value = Array.isArray(msg)
? msg.join('، ')
: (msg ?? 'جابه‌جایی مرحله ناموفق بود.');
} else {
error.value = 'جابه‌جایی مرحله ناموفق بود.';
}
throw e;
} finally {
stageMoving.value = false;
}
},
});
}
const productSelectOptions = computed(() =>
products.value.map((p) => ({ value: p.id, label: p.name })),
);
@@ -666,6 +707,20 @@ onMounted(load);
</a-space>
</a-flex>
<div
v-if="stagePathItems.length"
:style="{ marginBottom: '16px' }"
>
<StagePathStrip
:stages="stagePathItems"
:value="stageId"
:loading="stageMoving"
:disabled="saving || loading"
aria-label="مراحل مسیر فروش"
@select="onStageSelect"
/>
</div>
<a-alert v-if="error" type="error" show-icon :message="error" :style="{ marginBottom: '16px' }" />
<a-form layout="vertical" @finish="submit">
@@ -961,6 +1016,14 @@ onMounted(load);
</a-form-item>
</a-card>
<RelatedActivitiesPanel
v-if="!isNew && id"
:style="{ marginTop: '16px' }"
:deal-id="id"
:person-id="personId || null"
:company-id="companyId || null"
:deal-title="title"
/>
<RelatedTasksPanel
v-if="!isNew && id"
:style="{ marginTop: '16px' }"
+1 -1
View File
@@ -1177,7 +1177,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.contactName ? lead.title : ''"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template>
+757 -119
View File
@@ -40,6 +40,7 @@ import type { TableColumnsType, UploadProps } from 'ant-design-vue';
import {
AppstoreOutlined,
DeleteOutlined,
DownOutlined,
EditOutlined,
ExportOutlined,
FileExcelOutlined,
@@ -49,11 +50,12 @@ import {
PlusOutlined,
SearchOutlined,
UnorderedListOutlined,
} from '@/icons/ant-bridge';
} from '@ant-design/icons-vue';
import { api } from '@/lib/api';
import {
formatJalaliNumeric,
formatRelativeContact,
parseLocalInput,
toFaDigits,
} from '@/lib/jalali';
import { useAuthStore } from '@/stores/auth';
@@ -61,6 +63,7 @@ import { canManageSettings } from '@/lib/roles';
import { canAssignToOthers } from '@/lib/assign-access';
import { registerTableColumns, useTableColumns } from '@/lib/tableColumns';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import ExcelImportFlow from '@/components/ExcelImportFlow.vue';
import PhoneContactsImport from '@/components/PhoneContactsImport.vue';
import { CrmSkeleton, CrmSkeletonTable } from '@/components/skeleton';
@@ -94,8 +97,25 @@ const emptySimple = AEmpty.PRESENTED_IMAGE_SIMPLE;
const PAGE_SIZE = 10;
type SortKey = 'updated' | 'newest' | 'follow_up' | 'last_contact';
type FollowUpKey =
| ''
| 'due_today'
| 'overdue'
| 'called_today'
| 'missed_today'
| 'no_follow_up';
type StageTint = 'mint' | 'amber' | 'peach' | 'sky' | 'violet' | 'rose' | 'teal';
const FOLLOW_UP_OPTIONS: Array<{ value: FollowUpKey; label: string }> = [
{ value: '', label: 'همه پیگیری‌ها' },
{ value: 'due_today', label: 'قرار امروز' },
{ value: 'overdue', label: 'عقب‌افتاده' },
{ value: 'called_today', label: 'امروز تماس گرفته' },
{ value: 'missed_today', label: 'امروز باید می‌گرفت و نگرفته' },
{ value: 'no_follow_up', label: 'بدون پیگیری' },
];
const UNASSIGNED_VALUE = '__unassigned__';
/** ردیف آمار صفحه لیدها — ترتیب و نام‌ها مطابق طرح */
const LEAD_STAT_DEFS: Array<{
label: string;
@@ -164,8 +184,11 @@ const stages = ref<LeadStageDto[]>([]);
const stats = ref<LeadStatsDto | null>(null);
const users = ref<OrgUserDto[]>([]);
const cityOptions = ref<string[]>([]);
const regionOptions = ref<string[]>([]);
const tradeOptions = ref<string[]>([]);
const sourceOptions = ref<string[]>([]);
const selected = ref<Set<string>>(new Set());
const moreFiltersOpen = ref(false);
const sortOpen = ref(false);
const rowMenuId = ref<string | null>(null);
const logoMenuId = ref<string | null>(null);
@@ -237,12 +260,283 @@ const assigneeId = computed(() =>
const cityFilter = computed(() =>
typeof route.query.city === 'string' ? route.query.city : '',
);
const regionFilter = computed(() =>
typeof route.query.region === 'string' ? route.query.region : '',
);
const tradeFilter = computed(() =>
typeof route.query.trade === 'string' ? route.query.trade : '',
);
const sourceFilter = computed(() =>
typeof route.query.source === 'string' ? route.query.source : '',
);
const followUpFilter = computed<FollowUpKey>(() => {
const value = route.query.followUp;
if (
value === 'due_today' ||
value === 'overdue' ||
value === 'called_today' ||
value === 'missed_today' ||
value === 'no_follow_up'
) {
return value;
}
return '';
});
const createdFromFilter = computed(() =>
typeof route.query.createdFrom === 'string' ? route.query.createdFrom : '',
);
const createdToFilter = computed(() =>
typeof route.query.createdTo === 'string' ? route.query.createdTo : '',
);
const unassigned = computed(
() => route.query.unassigned === '1' || route.query.unassigned === 'true',
);
const archivedFilter = computed(
() => route.query.archived === '1' || route.query.archived === 'true',
);
const convertedFilter = computed(
() => route.query.converted === '1' || route.query.converted === 'true',
);
const assigneeSelectValue = computed(() => {
if (unassigned.value) return UNASSIGNED_VALUE;
return assigneeId.value || undefined;
});
/** شمارش فیلترهای داخل پاپ‌آور، مثل فعالیت‌ها. */
const mobileFilterBadgeCount = computed(() =>
[
stageId.value,
assigneeSelectValue.value ? '1' : '',
followUpFilter.value,
cityFilter.value,
regionFilter.value,
tradeFilter.value,
sourceFilter.value,
createdFromFilter.value,
createdToFilter.value,
archivedFilter.value ? '1' : '',
convertedFilter.value ? '1' : '',
].filter(Boolean).length,
);
const filterBtnLabel = computed(() =>
mobileFilterBadgeCount.value
? `فیلتر (${toFaDigits(mobileFilterBadgeCount.value)})`
: 'فیلتر',
);
type LeadFacetKey = 'assignee' | 'stage' | 'source' | 'followUp' | 'city' | 'region' | 'trade';
const filterSection = ref<LeadFacetKey | 'createdFrom' | 'createdTo' | 'converted' | 'archived' | null>(
null,
);
const filterQuery = ref('');
const FACET_LIST_CAP = 40;
function normFilter(value: string) {
return value.trim().replace(/ي/g, 'ی').replace(/ك/g, 'ک').toLowerCase();
}
function toggleFilterSection(name: NonNullable<typeof filterSection.value>) {
filterSection.value = filterSection.value === name ? null : name;
filterQuery.value = '';
}
const filterAnchor = ref<HTMLElement | null>(null);
const filterPopoverMaxHeight = ref('min(70vh, 32rem)');
const filterPanelStyle = computed(() => ({
position: 'absolute' as const,
top: 'calc(100% + 6px)',
insetInlineStart: '0',
zIndex: 1050,
width: 'min(20rem, calc(100vw - 1.5rem))',
maxHeight: filterPopoverMaxHeight.value,
overflow: 'auto',
background: token.value.colorBgElevated,
borderRadius: `${token.value.borderRadiusLG}px`,
boxShadow: token.value.boxShadowSecondary,
padding: `${token.value.paddingSM}px`,
}));
function placeFilterPopover() {
const el = filterAnchor.value;
if (!el) return;
const space = Math.floor(window.innerHeight - el.getBoundingClientRect().bottom - 12);
filterPopoverMaxHeight.value = `${Math.max(220, space)}px`;
}
function onFilterDocPointer(event: Event) {
const target = event.target;
if (!(target instanceof Node)) return;
if (filterAnchor.value?.contains(target)) return;
if (document.getElementById('jalali-picker')?.contains(target)) return;
moreFiltersOpen.value = false;
filterSection.value = null;
document.removeEventListener('pointerdown', onFilterDocPointer, true);
}
function toggleFilterPopover() {
if (moreFiltersOpen.value) {
moreFiltersOpen.value = false;
filterSection.value = null;
document.removeEventListener('pointerdown', onFilterDocPointer, true);
return;
}
placeFilterPopover();
moreFiltersOpen.value = true;
document.addEventListener('pointerdown', onFilterDocPointer, true);
}
function dateFacetLabel(value: string) {
if (!value) return 'همه';
const parsed = parseLocalInput(value);
return parsed ? formatJalaliNumeric(parsed) : value;
}
function facetValueStyle(active: boolean) {
return {
color: active ? token.value.colorPrimary : token.value.colorTextQuaternary,
fontWeight: active ? 700 : 400,
maxWidth: '9.5rem',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
} as const;
}
const textFacets = computed(() => [
{
key: 'assignee' as const,
label: 'کارشناس',
value: unassigned.value
? 'بدون کارشناس'
: users.value.find((user) => user.id === assigneeId.value)?.fullName || 'همه',
active: Boolean(assigneeSelectValue.value),
current: assigneeSelectValue.value || '',
searchable: true,
options: [
{ value: '', label: 'همه' },
{ value: UNASSIGNED_VALUE, label: 'بدون کارشناس' },
...users.value.map((user) => ({ value: user.id, label: user.fullName })),
],
},
{
key: 'stage' as const,
label: 'مرحله',
value: stages.value.find((stage) => stage.id === stageId.value)?.name || 'همه',
active: Boolean(stageId.value),
current: stageId.value,
searchable: stages.value.length > 8,
options: [
{ value: '', label: 'همه' },
...stages.value.map((stage) => ({ value: stage.id, label: stage.name })),
],
},
{
key: 'source' as const,
label: 'منبع',
value: sourceFilter.value || 'همه',
active: Boolean(sourceFilter.value),
current: sourceFilter.value,
searchable: sourceOptions.value.length > 8,
options: [
{ value: '', label: 'همه' },
...sourceOptions.value.map((item) => ({ value: item, label: item })),
],
},
{
key: 'followUp' as const,
label: 'پیگیری',
value:
FOLLOW_UP_OPTIONS.find((item) => item.value === followUpFilter.value && item.value)?.label ||
'همه',
active: Boolean(followUpFilter.value),
current: followUpFilter.value,
searchable: false,
options: [
{ value: '', label: 'همه' },
...FOLLOW_UP_OPTIONS.filter((item) => item.value).map((item) => ({
value: item.value,
label: item.label,
})),
],
},
{
key: 'city' as const,
label: 'شهر',
value: cityFilter.value || 'همه',
active: Boolean(cityFilter.value),
current: cityFilter.value,
searchable: cityOptions.value.length > 8,
options: [
{ value: '', label: 'همه' },
...cityOptions.value.map((item) => ({ value: item, label: item })),
],
},
{
key: 'region' as const,
label: 'منطقه',
value: regionFilter.value || 'همه',
active: Boolean(regionFilter.value),
current: regionFilter.value,
searchable: regionOptions.value.length > 8,
options: [
{ value: '', label: 'همه' },
...regionOptions.value.map((item) => ({ value: item, label: item })),
],
},
{
key: 'trade' as const,
label: 'صنف',
value: tradeFilter.value || 'همه',
active: Boolean(tradeFilter.value),
current: tradeFilter.value,
searchable: tradeOptions.value.length > 8,
options: [
{ value: '', label: 'همه' },
...tradeOptions.value.map((item) => ({ value: item, label: item })),
],
},
]);
function visibleFacetOptions(options: Array<{ value: string; label: string }>) {
const query = normFilter(filterQuery.value);
const rest = options.filter(
(item) => item.value !== '' && (!query || normFilter(item.label).includes(query)),
);
return {
options: [...options.filter((item) => item.value === ''), ...rest.slice(0, FACET_LIST_CAP)],
hidden: Math.max(0, rest.length - FACET_LIST_CAP),
empty: Boolean(query) && rest.length === 0,
};
}
function pickFacet(key: LeadFacetKey, value: string) {
const facet = textFacets.value.find((item) => item.key === key);
const next = facet && facet.current === value ? '' : value;
if (key === 'assignee') setAssigneeFilter(next || undefined);
else if (key === 'stage') setStageFilter(next);
else if (key === 'source') setSourceFilter(next);
else if (key === 'followUp') setFollowUpFilter(next || undefined);
else if (key === 'city') setCityFilter(next);
else if (key === 'region') setRegionFilter(next);
else if (key === 'trade') setTradeFilter(next);
filterSection.value = null;
}
function pickFlag(which: 'converted' | 'archived', on: boolean) {
const current = which === 'converted' ? convertedFilter.value : archivedFilter.value;
const next = on ? !current : false;
if (which === 'converted') setConvertedFilter(next);
else setArchivedFilter(next);
filterSection.value = null;
}
function facetOptionStyle(selected: boolean) {
return {
textAlign: 'start' as const,
background: selected ? token.value.colorPrimaryBg : 'transparent',
color: selected ? token.value.colorPrimary : token.value.colorText,
};
}
const total = computed(() => data.value?.total ?? 0);
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)));
@@ -516,14 +810,76 @@ function setStageFilter(id: string) {
patchQuery({ stageId: id || undefined, page: undefined });
}
function setAssigneeFilter(value: string | undefined) {
if (value === UNASSIGNED_VALUE) {
patchQuery({ assigneeId: undefined, unassigned: '1', page: undefined });
return;
}
patchQuery({
assigneeId: value || undefined,
unassigned: undefined,
page: undefined,
});
}
function setFollowUpFilter(value: string | undefined) {
patchQuery({
followUp: value || undefined,
page: undefined,
});
}
function setCityFilter(value: string) {
patchQuery({ city: value || undefined, page: undefined });
}
function setRegionFilter(value: string) {
patchQuery({ region: value || undefined, page: undefined });
}
function setTradeFilter(value: string) {
patchQuery({ trade: value || undefined, page: undefined });
}
function setSourceFilter(value: string) {
patchQuery({ source: value || undefined, page: undefined });
}
function setCreatedFromFilter(value: string) {
patchQuery({ createdFrom: value || undefined, page: undefined });
}
function setCreatedToFilter(value: string) {
patchQuery({ createdTo: value || undefined, page: undefined });
}
function setArchivedFilter(checked: boolean) {
patchQuery({ archived: checked ? '1' : undefined, page: undefined });
}
function setConvertedFilter(checked: boolean) {
patchQuery({ converted: checked ? '1' : undefined, page: undefined });
}
function clearMoreFilters() {
patchQuery({
stageId: undefined,
assigneeId: undefined,
unassigned: undefined,
followUp: undefined,
city: undefined,
region: undefined,
trade: undefined,
source: undefined,
createdFrom: undefined,
createdTo: undefined,
archived: undefined,
converted: undefined,
page: undefined,
});
filterSection.value = null;
}
function setPage(next: number) {
if (next < 1 || next > pageCount.value) return;
patchQuery({ page: next === 1 ? undefined : String(next) });
@@ -596,12 +952,18 @@ function onCardClick(lead: LeadDto) {
function mergeFacets(items: LeadDto[]) {
const cities = new Set(cityOptions.value);
const regions = new Set(regionOptions.value);
const trades = new Set(tradeOptions.value);
const sources = new Set(sourceOptions.value);
for (const lead of items) {
if (lead.city?.trim()) cities.add(lead.city.trim());
if (lead.region?.trim()) regions.add(lead.region.trim());
if (lead.trade?.trim()) trades.add(lead.trade.trim());
if (lead.source?.trim()) sources.add(lead.source.trim());
}
cityOptions.value = [...cities].sort((a, b) => a.localeCompare(b, 'fa'));
regionOptions.value = [...regions].sort((a, b) => a.localeCompare(b, 'fa'));
tradeOptions.value = [...trades].sort((a, b) => a.localeCompare(b, 'fa'));
sourceOptions.value = [...sources].sort((a, b) => a.localeCompare(b, 'fa'));
}
@@ -633,8 +995,15 @@ async function load() {
stageId: stageId.value || undefined,
assigneeId: assigneeId.value || undefined,
city: cityFilter.value || undefined,
region: regionFilter.value || undefined,
trade: tradeFilter.value || undefined,
source: sourceFilter.value || undefined,
unassigned: unassigned.value ? '1' : undefined,
archived: archivedFilter.value ? '1' : undefined,
converted: convertedFilter.value ? '1' : undefined,
followUp: followUpFilter.value || undefined,
createdFrom: createdFromFilter.value || undefined,
createdTo: createdToFilter.value || undefined,
},
});
data.value = res;
@@ -1116,8 +1485,15 @@ watch(
route.query.stageId,
route.query.assigneeId,
route.query.city,
route.query.region,
route.query.trade,
route.query.source,
route.query.unassigned,
route.query.archived,
route.query.converted,
route.query.followUp,
route.query.createdFrom,
route.query.createdTo,
],
() => {
q.value = typeof route.query.q === 'string' ? route.query.q : '';
@@ -1193,141 +1569,403 @@ onMounted(async () => {
onBeforeUnmount(() => {
stopImportPoll();
revokeLogoUrls();
document.removeEventListener('pointerdown', onFilterDocPointer, true);
});
</script>
<template>
<!-- wrapper absorbs AppLayout flex:1 so a-row/a-flex children are not stretch-spaced -->
<div :style="{ width: '100%' }" @click="closePopups">
<a-flex vertical :gap="token.marginSM" :style="{ width: '100%' }">
<a-row :gutter="[12, 12]" align="middle">
<a-col :xs="24" :md="6" :lg="5">
<a-row :gutter="[16, 16]" align="top" :style="{ alignContent: 'flex-start' }" @click="closePopups">
<a-col :span="24">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="token.marginSM">
<a-typography-title :level="3" :style="{ margin: 0 }">لیدها</a-typography-title>
</a-col>
<a-col :xs="24" :md="18" :lg="19">
<a-flex justify="end" wrap="wrap" :gap="8">
<a-button :disabled="busy" :loading="pageBusy && busyMessage.includes('خروجی')" @click.stop="exportExcel">
<template #icon><ExportOutlined /></template>
خروجی اکسل
</a-button>
<ExcelImportFlow
preview-path="/leads/import/preview"
import-path="/leads/import/file"
:disabled="busy"
@start="onExcelImportStart"
@done="onExcelImportDone"
@fail="onExcelImportFail"
@settled="onExcelImportSettled"
>
<template #default="{ loading: excelLoading }">
<a-button :disabled="busy" :loading="excelLoading">
<template #icon><FileExcelOutlined /></template>
ورود از اکسل
<a-space :size="8" wrap>
<template v-if="isMobile">
<a-dropdown :trigger="['click']" placement="bottomLeft">
<a-button :disabled="busy">
<template #icon><MoreOutlined /></template>
بیشتر
</a-button>
</template>
</ExcelImportFlow>
<PhoneContactsImport
target="leads"
:disabled="busy"
@start="onPhoneImportStart"
@done="onPhoneImportDone"
@fail="onPhoneImportFail"
@settled="onPhoneImportSettled"
>
<a-button :disabled="busy">
<template #icon><PhoneOutlined /></template>
از مخاطبین گوشی
<template #overlay>
<a-menu>
<a-menu-item
key="export"
:disabled="busy || (pageBusy && busyMessage.includes('خروجی'))"
@click="exportExcel"
>
<ExportOutlined />
خروجی اکسل
</a-menu-item>
<a-menu-item key="excel" :disabled="busy">
<ExcelImportFlow
preview-path="/leads/import/preview"
import-path="/leads/import/file"
:disabled="busy"
@start="onExcelImportStart"
@done="onExcelImportDone"
@fail="onExcelImportFail"
@settled="onExcelImportSettled"
>
<template #default="{ loading: excelLoading }">
<a-flex align="center" :gap="8" :style="{ opacity: excelLoading ? 0.6 : 1 }">
<FileExcelOutlined />
ورود از اکسل
</a-flex>
</template>
</ExcelImportFlow>
</a-menu-item>
<a-menu-item key="phone" :disabled="busy">
<PhoneContactsImport
target="leads"
:disabled="busy"
@start="onPhoneImportStart"
@done="onPhoneImportDone"
@fail="onPhoneImportFail"
@settled="onPhoneImportSettled"
>
<a-flex align="center" :gap="8">
<PhoneOutlined />
از مخاطبین گوشی
</a-flex>
</PhoneContactsImport>
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
<template v-else>
<a-button :disabled="busy" :loading="pageBusy && busyMessage.includes('خروجی')" @click.stop="exportExcel">
<template #icon><ExportOutlined /></template>
خروجی اکسل
</a-button>
</PhoneContactsImport>
<ExcelImportFlow
preview-path="/leads/import/preview"
import-path="/leads/import/file"
:disabled="busy"
@start="onExcelImportStart"
@done="onExcelImportDone"
@fail="onExcelImportFail"
@settled="onExcelImportSettled"
>
<template #default="{ loading: excelLoading }">
<a-button :disabled="busy" :loading="excelLoading">
<template #icon><FileExcelOutlined /></template>
ورود از اکسل
</a-button>
</template>
</ExcelImportFlow>
<PhoneContactsImport
target="leads"
:disabled="busy"
@start="onPhoneImportStart"
@done="onPhoneImportDone"
@fail="onPhoneImportFail"
@settled="onPhoneImportSettled"
>
<a-button :disabled="busy">
<template #icon><PhoneOutlined /></template>
از مخاطبین گوشی
</a-button>
</PhoneContactsImport>
</template>
<a-radio-group
v-if="isMobile"
value="list"
button-style="solid"
@change="(e: any) => { if (e?.target?.value === 'board') void router.push({ name: 'leads-board' }) }"
>
<a-radio-button value="list">
<UnorderedListOutlined />
</a-radio-button>
<a-radio-button value="board">
<AppstoreOutlined />
</a-radio-button>
</a-radio-group>
<a-button type="primary" @click.stop="openCreate">
<template #icon><PlusOutlined /></template>
لید جدید
{{ isMobile ? 'جدید' : 'لید جدید' }}
</a-button>
</a-flex>
</a-col>
</a-row>
<a-row :gutter="[12, 12]">
<a-col :xs="12" :sm="8" :md="4">
<a-card
hoverable
:body-style="{ padding: `${token.paddingSM}px` }"
:style="{
height: '100%',
borderColor: !stageId ? token.colorPrimary : undefined,
cursor: 'pointer',
}"
@click="setStageFilter('')"
>
<a-flex vertical :gap="4">
<a-typography-text type="secondary">همه لیدها</a-typography-text>
<a-typography-text strong :style="{ color: token.colorPrimary, fontSize: `${token.fontSizeHeading3}px` }">
{{ formatCount(totalLeadsCount) }}
</a-typography-text>
<a-col :span="24" @click.stop>
<a-card :bordered="true">
<a-flex vertical :gap="12">
<a-flex v-if="!isMobile" justify="space-between" align="center" wrap="wrap" :gap="8">
<a-flex wrap="wrap" :gap="8" align="center" flex="1 1 auto">
<a-button :type="!stageId ? 'primary' : 'default'" @click="setStageFilter('')">
همه لیدها
<a-typography-text
:type="!stageId ? undefined : 'secondary'"
:style="{ color: !stageId ? 'inherit' : undefined, marginInlineStart: '6px' }"
>
{{ formatCount(totalLeadsCount) }}
</a-typography-text>
</a-button>
<a-button
v-for="card in stageCards"
:key="card.key"
:type="isStatActive(card) ? 'primary' : 'default'"
:disabled="!card.stageId"
@click="selectStatCard(card)"
>
{{ card.label }}
<a-typography-text
:type="isStatActive(card) ? undefined : 'secondary'"
:style="{ color: isStatActive(card) ? 'inherit' : undefined, marginInlineStart: '6px' }"
>
{{ formatCount(card.count) }}
</a-typography-text>
</a-button>
</a-flex>
<a-space :size="8">
<TableColumnsMenu table-key="leads" align="end" />
<a-radio-group
value="list"
button-style="solid"
@change="(e: any) => { if (e?.target?.value === 'board') void router.push({ name: 'leads-board' }) }"
>
<a-radio-button value="list">
<UnorderedListOutlined />
</a-radio-button>
<a-radio-button value="board">
<AppstoreOutlined />
</a-radio-button>
</a-radio-group>
</a-space>
</a-flex>
</a-card>
</a-col>
<a-col
v-for="card in stageCards"
:key="card.key"
:xs="12"
:sm="8"
:md="4"
>
<a-card
hoverable
:body-style="{ padding: `${token.paddingSM}px` }"
:style="{
height: '100%',
borderColor: isStatActive(card) ? token.colorPrimary : undefined,
cursor: card.stageId ? 'pointer' : 'not-allowed',
opacity: card.stageId ? 1 : 0.55,
}"
@click="card.stageId && selectStatCard(card)"
>
<a-flex vertical :gap="4">
<a-typography-text type="secondary">{{ card.label }}</a-typography-text>
<a-typography-text strong :style="{ color: tintAccent(card.tint), fontSize: `${token.fontSizeHeading3}px` }">
{{ formatCount(card.count) }}
</a-typography-text>
</a-flex>
</a-card>
</a-col>
</a-row>
<a-alert
v-if="importJob && importJob.status !== 'done' && importJob.status !== 'completed' && importJob.status !== 'failed'"
type="info"
show-icon
:message="`ورود فایل: ${toFaDigits(importJob.processedCount)} / ${toFaDigits(importJob.totalCount)}`"
/>
<a-alert v-if="okMsg" type="success" show-icon :message="okMsg" closable @close="okMsg = ''" />
<a-alert v-if="error" type="error" show-icon :message="error" closable @close="error = ''" />
<a-card @click.stop>
<template #title>
<a-space :size="8">
<FilterOutlined />
<span>فیلترها</span>
</a-space>
</template>
<template #extra>
<a-space :size="8" wrap>
<TableColumnsMenu table-key="leads" align="end" />
<a-radio-group
value="list"
button-style="solid"
@change="(e: any) => { if (e?.target?.value === 'board') void router.push({ name: 'leads-board' }) }"
<a-flex :vertical="isMobile" align="center" wrap="wrap" :gap="8">
<a-input-search
v-model:value="q"
allow-clear
placeholder="جستجو نام، موبایل، شهر…"
:style="isMobile ? { width: '100%' } : { width: '15rem', maxWidth: '100%' }"
@search="onSearch"
>
<a-radio-button value="list">
<UnorderedListOutlined />
</a-radio-button>
<a-radio-button value="board">
<AppstoreOutlined />
</a-radio-button>
</a-radio-group>
</a-space>
</template>
<template #enterButton>
<a-button type="primary">
<template #icon><SearchOutlined /></template>
</a-button>
</template>
</a-input-search>
<div
ref="filterAnchor"
:style="{ position: 'relative', width: isMobile ? '100%' : undefined }"
>
<a-button
:block="isMobile"
:style="mobileFilterBadgeCount
? {
borderColor: token.colorPrimary,
color: token.colorPrimary,
background: token.colorPrimaryBg,
}
: undefined"
@click.stop="toggleFilterPopover"
>
<a-flex align="center" justify="center" :gap="6">
<FilterOutlined />
<span>{{ filterBtnLabel }}</span>
<DownOutlined />
</a-flex>
</a-button>
<div v-if="moreFiltersOpen" data-lead-filter :style="filterPanelStyle" @click.stop>
<a-flex vertical :gap="10">
<div v-for="facet in textFacets" :key="facet.key">
<div
role="button"
tabindex="0"
:style="{ cursor: 'pointer' }"
@click="toggleFilterSection(facet.key)"
@keydown.enter.prevent="toggleFilterSection(facet.key)"
>
<a-flex justify="space-between" align="center">
<span>{{ facet.label }}</span>
<a-typography-text :style="facetValueStyle(facet.active)">
{{ facet.value }}
</a-typography-text>
</a-flex>
</div>
<a-flex
v-if="filterSection === facet.key"
vertical
:gap="4"
:style="{ marginTop: '6px' }"
>
<a-input
v-if="facet.searchable"
v-model:value="filterQuery"
allow-clear
placeholder="جستجو"
/>
<div :style="{ maxHeight: '11.5rem', overflow: 'auto' }">
<a-button
v-for="option in visibleFacetOptions(facet.options).options"
:key="option.value || 'all'"
type="text"
block
:style="facetOptionStyle(facet.current === option.value)"
@click="pickFacet(facet.key, option.value)"
>
{{ option.label }}
</a-button>
<a-typography-text
v-if="visibleFacetOptions(facet.options).empty"
type="secondary"
>
موردی پیدا نشد
</a-typography-text>
</div>
<a-typography-text
v-if="visibleFacetOptions(facet.options).hidden"
type="secondary"
>
برای دیدن بقیه، نام را دقیق‌تر بنویسید
</a-typography-text>
</a-flex>
</div>
<div>
<div
role="button"
tabindex="0"
:style="{ cursor: 'pointer' }"
@click="toggleFilterSection('createdFrom')"
@keydown.enter.prevent="toggleFilterSection('createdFrom')"
>
<a-flex justify="space-between" align="center">
<span>از تاریخ ثبت</span>
<a-typography-text :style="facetValueStyle(Boolean(createdFromFilter))">
{{ dateFacetLabel(createdFromFilter) }}
</a-typography-text>
</a-flex>
</div>
<div v-if="filterSection === 'createdFrom'" :style="{ marginTop: '6px' }">
<JalaliDateInput
:model-value="createdFromFilter"
placeholder="از تاریخ"
@update:model-value="(value: string) => { setCreatedFromFilter(value); filterSection = null }"
/>
</div>
</div>
<div>
<div
role="button"
tabindex="0"
:style="{ cursor: 'pointer' }"
@click="toggleFilterSection('createdTo')"
@keydown.enter.prevent="toggleFilterSection('createdTo')"
>
<a-flex justify="space-between" align="center">
<span>تا تاریخ ثبت</span>
<a-typography-text :style="facetValueStyle(Boolean(createdToFilter))">
{{ dateFacetLabel(createdToFilter) }}
</a-typography-text>
</a-flex>
</div>
<div v-if="filterSection === 'createdTo'" :style="{ marginTop: '6px' }">
<JalaliDateInput
:model-value="createdToFilter"
placeholder="تا تاریخ"
@update:model-value="(value: string) => { setCreatedToFilter(value); filterSection = null }"
/>
</div>
</div>
<div>
<div
role="button"
tabindex="0"
:style="{ cursor: 'pointer' }"
@click="toggleFilterSection('converted')"
@keydown.enter.prevent="toggleFilterSection('converted')"
>
<a-flex justify="space-between" align="center">
<span>تبدیل‌شده</span>
<a-typography-text :style="facetValueStyle(convertedFilter)">
{{ convertedFilter ? 'فقط' : 'همه' }}
</a-typography-text>
</a-flex>
</div>
<a-flex v-if="filterSection === 'converted'" vertical :style="{ marginTop: '6px' }">
<a-button
type="text"
block
:style="facetOptionStyle(!convertedFilter)"
@click="pickFlag('converted', false)"
>
همه
</a-button>
<a-button
type="text"
block
:style="facetOptionStyle(convertedFilter)"
@click="pickFlag('converted', true)"
>
فقط تبدیل‌شده‌ها
</a-button>
</a-flex>
</div>
<div>
<div
role="button"
tabindex="0"
:style="{ cursor: 'pointer' }"
@click="toggleFilterSection('archived')"
@keydown.enter.prevent="toggleFilterSection('archived')"
>
<a-flex justify="space-between" align="center">
<span>بایگانی</span>
<a-typography-text :style="facetValueStyle(archivedFilter)">
{{ archivedFilter ? 'فقط' : 'همه' }}
</a-typography-text>
</a-flex>
</div>
<a-flex v-if="filterSection === 'archived'" vertical :style="{ marginTop: '6px' }">
<a-button
type="text"
block
:style="facetOptionStyle(!archivedFilter)"
@click="pickFlag('archived', false)"
>
همه
</a-button>
<a-button
type="text"
block
:style="facetOptionStyle(archivedFilter)"
@click="pickFlag('archived', true)"
>
فقط بایگانی‌شده‌ها
</a-button>
</a-flex>
</div>
<a-button
v-if="mobileFilterBadgeCount"
type="text"
danger
block
@click="clearMoreFilters"
>
پاک کردن فیلترها
</a-button>
</a-flex>
</div>
</div>
<a-select
:value="sort"
:style="isMobile ? { width: '100%' } : { width: '10rem' }"
:options="Object.entries(sortLabels).map(([value, label]) => ({ value, label }))"
@update:value="(v) => setSort(String(v ?? 'updated') as SortKey)"
/>
</a-flex>
</a-flex>
</a-card>
</a-col>
<a-row :gutter="[12, 12]">
<a-col :xs="24" :sm="12" :md="8" :lg="5">
File diff suppressed because it is too large Load Diff
+41 -1
View File
@@ -97,6 +97,9 @@ const website = ref('');
const instagram = ref('');
const birthDate = ref('');
const referrer = ref('');
const nationalId = ref('');
const city = ref('');
const rasteh = ref('');
const addresses = ref<string[]>(['']);
const notes = ref('');
const tagsRaw = ref('');
@@ -283,6 +286,16 @@ function fill(p: PersonDto) {
mood.value = p.mood || 'newcomer';
groupIds.value = (p.groups ?? []).map((g) => g.id);
customFields.value = { ...(p.customFields ?? {}) };
const cf = customFields.value;
nationalId.value =
typeof cf.nationalId === 'string'
? cf.nationalId
: typeof cf.nationalId === 'number'
? String(cf.nationalId)
: '';
city.value = typeof cf.city === 'string' ? cf.city : '';
rasteh.value =
typeof cf.rasteh === 'string' || typeof cf.rasteh === 'number' ? String(cf.rasteh) : '';
loyaltyPoints.value = p.loyaltyPoints ?? 0;
loyaltyTierName.value = p.loyaltyTier?.name ?? '';
}
@@ -344,6 +357,18 @@ function parseTags(raw: string): string[] {
}
function payload(): CreatePersonRequest {
const fields: Record<string, unknown> = { ...customFields.value };
const nid = nationalId.value.trim();
if (nid) fields.nationalId = nid;
else delete fields.nationalId;
const cityVal = city.value.trim();
if (cityVal) fields.city = cityVal;
else delete fields.city;
const rastehRaw = rasteh.value.trim();
if (rastehRaw) {
const n = Number(rastehRaw);
fields.rasteh = Number.isFinite(n) && String(n) === rastehRaw ? n : rastehRaw;
} else delete fields.rasteh;
return {
firstName: firstName.value,
lastName: lastName.value,
@@ -363,7 +388,7 @@ function payload(): CreatePersonRequest {
companyId: companyId.value || null,
mood: mood.value,
groupIds: groupIds.value,
customFields: customFields.value,
customFields: fields,
};
}
@@ -547,6 +572,21 @@ onMounted(load);
<a-input v-model:value="referrer" placeholder="نام معرف" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="کد ملی">
<a-input v-model:value="nationalId" dir="ltr" placeholder="کد ملی (ته‌حساب)" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="شهر">
<a-input v-model:value="city" placeholder="شهر" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="رسته">
<a-input v-model:value="rasteh" dir="ltr" placeholder="رسته حساب ته‌حساب" />
</a-form-item>
</a-col>
</a-row>
<a-divider orientation="right">آدرس‌ها</a-divider>
+167 -79
View File
@@ -224,6 +224,18 @@ const externalCode = computed(() => {
}
return '';
});
function customFieldText(...keys: string[]) {
const fields = person.value?.customFields ?? {};
for (const key of keys) {
const raw = fields[key];
if (typeof raw === 'string' && raw.trim()) return raw.trim();
if (typeof raw === 'number' && Number.isFinite(raw)) return String(raw);
}
return '';
}
const nationalIdLabel = computed(() => customFieldText('nationalId', 'CodeMelli', 'codeMeli'));
const cityLabel = computed(() => customFieldText('city', 'City'));
const rastehLabel = computed(() => customFieldText('rasteh', 'Rasteh'));
const SOURCE_LABELS: Record<string, string> = {
manual: 'دستی',
tahesab: 'ته‌حساب',
@@ -484,6 +496,9 @@ const infoEmpty = computed(() => {
!p.instagram &&
!p.birthDate &&
!p.referrer &&
!nationalIdLabel.value &&
!cityLabel.value &&
!rastehLabel.value &&
!(p.addresses?.length) &&
!p.company &&
!externalCode.value &&
@@ -811,28 +826,63 @@ watch(() => route.query.tab, readTab, { immediate: true });
</a-col>
</a-row>
<a-descriptions :column="{ xs: 1, sm: 2, md: 3, lg: 4 }" bordered style="margin-top: 16px">
<a-descriptions-item label="گروه‌ها">
<CustomerGroupChips :groups="person.groups" empty="—" />
</a-descriptions-item>
<a-descriptions-item label="شرکت">{{ person.company?.name || '—' }}</a-descriptions-item>
<a-descriptions-item label="سمت">{{ person.position || '—' }}</a-descriptions-item>
<a-descriptions-item label="جنسیت">{{ genderLabel }}</a-descriptions-item>
<a-descriptions-item label="تاریخ تولد">{{ birthDateLabel }}</a-descriptions-item>
<a-descriptions-item label="تاریخ ثبت">{{ registeredAt }}</a-descriptions-item>
<a-descriptions-item v-if="person.referrer" label="معرف">{{ person.referrer }}</a-descriptions-item>
<a-descriptions-item v-if="person.website" label="وب‌سایت">
<span dir="ltr">{{ person.website }}</span>
</a-descriptions-item>
<a-descriptions-item v-if="person.instagram" label="اینستاگرام">
<span dir="ltr">{{ person.instagram }}</span>
</a-descriptions-item>
<a-descriptions-item v-if="person.addresses?.length" label="آدرس‌ها" :span="2">
<div v-for="(addr, i) in person.addresses" :key="i">{{ addr }}</div>
</a-descriptions-item>
</a-descriptions>
</a-card>
</a-col>
<dl class="facts-grid">
<div class="fact">
<dt>گروه‌ها</dt>
<dd><CustomerGroupChips :groups="person.groups" empty="—" /></dd>
</div>
<div class="fact">
<dt>شرکت</dt>
<dd>{{ person.company?.name || '—' }}</dd>
</div>
<div class="fact">
<dt>سمت</dt>
<dd>{{ person.position || '—' }}</dd>
</div>
<div class="fact">
<dt>جنسیت</dt>
<dd>{{ genderLabel }}</dd>
</div>
<div class="fact">
<dt>تاریخ تولد</dt>
<dd>{{ birthDateLabel }}</dd>
</div>
<div class="fact">
<dt>تاریخ ثبت</dt>
<dd>{{ registeredAt }}</dd>
</div>
<div v-if="person.referrer" class="fact">
<dt>معرف</dt>
<dd>{{ person.referrer }}</dd>
</div>
<div v-if="nationalIdLabel" class="fact">
<dt>کد ملی</dt>
<dd dir="ltr">{{ toFaDigits(nationalIdLabel) }}</dd>
</div>
<div v-if="cityLabel" class="fact">
<dt>شهر</dt>
<dd>{{ cityLabel }}</dd>
</div>
<div v-if="rastehLabel" class="fact">
<dt>رسته</dt>
<dd dir="ltr">{{ toFaDigits(rastehLabel) }}</dd>
</div>
<div v-if="person.website" class="fact">
<dt>وب‌سایت</dt>
<dd dir="ltr">{{ person.website }}</dd>
</div>
<div v-if="person.instagram" class="fact">
<dt>اینستاگرام</dt>
<dd dir="ltr">{{ person.instagram }}</dd>
</div>
<div v-if="person.addresses?.length" class="fact wide">
<dt>آدرس‌ها</dt>
<dd>
<p v-for="(addr, i) in person.addresses" :key="i" class="addr-line">{{ addr }}</p>
</dd>
</div>
</dl>
</article>
<a-col :span="24">
<a-tabs :active-key="tab" @change="onTabChange">
@@ -1088,62 +1138,72 @@ watch(() => route.query.tab, readTab, { immediate: true });
secondary-label="افزودن اولین فعالیت"
:secondary-to="{ name: 'activity-new', query: { personId: id } }"
/>
<template v-if="!infoEmpty">
<a-card :bordered="false">
<a-descriptions :column="{ xs: 1, sm: 2 }" bordered>
<a-descriptions-item label="موبایل">{{ person.mobile ? toFaDigits(person.mobile) : '—' }}</a-descriptions-item>
<a-descriptions-item label="تلفن">{{ person.phone ? toFaDigits(person.phone) : '—' }}</a-descriptions-item>
<a-descriptions-item label="ایمیل">{{ person.email || '—' }}</a-descriptions-item>
<a-descriptions-item label="سمت">{{ person.position || '—' }}</a-descriptions-item>
<a-descriptions-item label="جنسیت">{{ genderLabel }}</a-descriptions-item>
<a-descriptions-item label="منبع ورود">{{ importSourceLabel }}</a-descriptions-item>
<a-descriptions-item label="کد مبدأ">
<span dir="ltr">{{ externalCode ? toFaDigits(externalCode) : '—' }}</span>
</a-descriptions-item>
<a-descriptions-item label="نام قبلی">{{ person.previousFullName || '—' }}</a-descriptions-item>
<a-descriptions-item label="وب‌سایت">{{ person.website || '—' }}</a-descriptions-item>
<a-descriptions-item label="اینستاگرام">
<span dir="ltr">{{ person.instagram || '—' }}</span>
</a-descriptions-item>
<a-descriptions-item label="معرف">{{ person.referrer || '—' }}</a-descriptions-item>
<a-descriptions-item label="آدرس‌ها" :span="2">
<template v-if="person.addresses?.length">
<div v-for="(addr, i) in person.addresses" :key="i">{{ addr }}</div>
</template>
<template v-else>—</template>
</a-descriptions-item>
<a-descriptions-item label="شرکت">{{ person.company?.name || '—' }}</a-descriptions-item>
<a-descriptions-item label="مسئول">{{ person.owner?.fullName || '—' }}</a-descriptions-item>
<a-descriptions-item label="تاریخ تولد">{{ birthDateLabel }}</a-descriptions-item>
<a-descriptions-item label="تاریخ ثبت">{{ registeredAt }}</a-descriptions-item>
<a-descriptions-item label="باشگاه">
{{ toFaDigits(person.loyaltyPoints) }} امتیاز
<span v-if="person.loyaltyTier"> · {{ person.loyaltyTier.name }}</span>
</a-descriptions-item>
<a-descriptions-item v-if="person.notes" label="یادداشت" :span="2">{{ person.notes }}</a-descriptions-item>
</a-descriptions>
</a-card>
<template v-if="tickets.length">
<a-typography-title :level="5">تیکت‌ها</a-typography-title>
<RouterLink
v-for="ticket in tickets"
:key="ticket.id"
:to="{ name: 'ticket-detail', params: { id: ticket.id } }"
>
<a-card :bordered="false" hoverable style="margin-bottom: 8px">
<a-flex justify="space-between" wrap="wrap" gap="8">
<a-typography-text strong>{{ ticket.number }} · {{ ticket.subject }}</a-typography-text>
<a-tag>{{ ticket.status }}</a-tag>
</a-flex>
</a-card>
</RouterLink>
</template>
<MentoMemoryPanel :person-id="id" />
<RouterLink :to="{ name: 'person-edit', params: { id } }">
<a-button type="link">ویرایش اطلاعات</a-button>
<button class="smart-cta" type="button" @click="onSmartCta">
<span>{{ shownSmart.cta }}</span>
<UiIcon name="chevron" :size="16" />
</button>
</article>
<ProfileEmptyState
v-if="infoEmpty"
primary-label="افزودن اطلاعات مشتری"
:primary-to="{ name: 'person-edit', params: { id } }"
secondary-label="افزودن اولین فعالیت"
:secondary-to="{ name: 'activity-new', query: { personId: id } }"
/>
<div v-if="!infoEmpty">
<dl>
<div><dt>موبایل</dt><dd>{{ person.mobile ? toFaDigits(person.mobile) : '—' }}</dd></div>
<div><dt>تلفن</dt><dd>{{ person.phone ? toFaDigits(person.phone) : '—' }}</dd></div>
<div><dt>ایمیل</dt><dd>{{ person.email || '—' }}</dd></div>
<div><dt>سمت</dt><dd>{{ person.position || '—' }}</dd></div>
<div><dt>جنسیت</dt><dd>{{ genderLabel }}</dd></div>
<div><dt>منبع ورود</dt><dd>{{ importSourceLabel }}</dd></div>
<div><dt>کد مبدأ</dt><dd dir="ltr">{{ externalCode ? toFaDigits(externalCode) : '—' }}</dd></div>
<div><dt>نام قبلی</dt><dd>{{ person.previousFullName || '—' }}</dd></div>
<div><dt>وب‌سایت</dt><dd>{{ person.website || '—' }}</dd></div>
<div><dt>اینستاگرام</dt><dd dir="ltr">{{ person.instagram || '—' }}</dd></div>
<div><dt>معرف</dt><dd>{{ person.referrer || '—' }}</dd></div>
<div>
<dt>کد ملی</dt>
<dd dir="ltr">{{ nationalIdLabel ? toFaDigits(nationalIdLabel) : '—' }}</dd>
</div>
<div><dt>شهر</dt><dd>{{ cityLabel || '—' }}</dd></div>
<div>
<dt>رسته</dt>
<dd dir="ltr">{{ rastehLabel ? toFaDigits(rastehLabel) : '—' }}</dd>
</div>
<div class="wide">
<dt>آدرس‌ها</dt>
<dd>
<template v-if="person.addresses?.length">
<p v-for="(addr, i) in person.addresses" :key="i" class="addr-line">{{ addr }}</p>
</template>
<template v-else>—</template>
</dd>
</div>
<div><dt>شرکت</dt><dd>{{ person.company?.name || '—' }}</dd></div>
<div><dt>مسئول</dt><dd>{{ person.owner?.fullName || '—' }}</dd></div>
<div><dt>تاریخ تولد</dt><dd>{{ birthDateLabel }}</dd></div>
<div><dt>تاریخ ثبت</dt><dd>{{ registeredAt }}</dd></div>
<div>
<dt>باشگاه</dt>
<dd>
{{ toFaDigits(person.loyaltyPoints) }} امتیاز
<span v-if="person.loyaltyTier"> · {{ person.loyaltyTier.name }}</span>
</dd>
</div>
<div v-if="person.notes" class="wide"><dt>یادداشت</dt><dd>{{ person.notes }}</dd></div>
</dl>
<div v-if="tickets.length" class="subblock">
<h3>تیکت‌ها</h3>
<RouterLink
v-for="ticket in tickets"
:key="ticket.id"
class="row-card"
:to="{ name: 'ticket-detail', params: { id: ticket.id } }"
>
<strong>{{ ticket.number }} · {{ ticket.subject }}</strong>
<span>{{ ticket.status }}</span>
</RouterLink>
</template>
</a-space>
@@ -1179,5 +1239,33 @@ watch(() => route.query.tab, readTab, { immediate: true });
<template #icon><PlusOutlined /></template>
</a-float-button>
</template>
</a-row>
<SmsComposeModal
v-if="person"
:open="smsOpen"
title="ارسال پیامک"
:endpoint="`/people/${id}/sms`"
:history-endpoint="`/people/${id}/sms-history`"
:name="fullName"
:phone="phoneNumber"
:record-title="person.position?.trim() || ''"
:company="person.company?.name ?? ''"
@close="smsOpen = false"
/>
<div v-if="person" class="dock">
<button class="fab-item call" type="button" :disabled="!telHref" @click="goCall">
<span class="fab-circle">
<UiIcon name="phone" :size="22" />
</span>
<span class="fab-label">تماس</span>
</button>
<button class="fab-item add" type="button" @click="goAddActivity">
<span class="fab-circle">
<UiIcon name="plus" :size="22" />
</span>
<span class="fab-label">افزودن فعالیت</span>
</button>
</div>
</section>
</template>
+77 -46
View File
@@ -3,7 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { api } from '@/lib/api';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { formatRelativeDayLabel, toFaDigits } from '@/lib/jalali';
import PipelineToolbar from '@/components/pipeline/PipelineToolbar.vue';
import type { PipelineViewMode } from '@/components/pipeline/PipelineToolbar.vue';
import PipelineBoard from '@/components/pipeline/PipelineBoard.vue';
@@ -109,6 +109,7 @@ const overlayAccent = ref<PipelineStage['color']>('green');
const overlayPos = ref({ x: 0, y: 0 });
const menuOpenId = ref<string | null>(null);
const moving = ref(false);
let dragSessionId: string | null = null;
const pipelineOptions = computed(() =>
pipelines.value.map((p) => ({
@@ -165,9 +166,7 @@ function applyDealsSavedFilters(filters: Record<string, unknown>) {
}
function formatDealDate(iso: string) {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return formatJalaliNumeric(d);
return formatRelativeDayLabel(iso);
}
function findAccent(dealId: string): PipelineStage['color'] {
@@ -178,7 +177,9 @@ function findAccent(dealId: string): PipelineStage['color'] {
}
async function loadPipelines() {
const { data } = await api.get<PipelineDto[]>('/pipelines');
const { data } = await api.get<PipelineDto[]>('/pipelines', {
params: { forLens: '1' },
});
pipelines.value = data;
}
@@ -187,16 +188,23 @@ async function load() {
error.value = '';
try {
await loadPipelines();
const pipelineId =
typeof route.query.pipelineId === 'string'
? route.query.pipelineId
: undefined;
const requested =
typeof route.query.pipelineId === 'string' ? route.query.pipelineId : '';
const pipelineId = pipelines.value.some((item) => item.id === requested)
? requested
: pipelines.value[0]?.id;
if (!pipelineId) {
boardPipelineId.value = '';
stages.value = [];
if (requested) await router.replace({ name: 'pipeline', query: {} });
return;
}
const { data } = await api.get<PipelineBoardDto>('/pipelines/board', {
params: pipelineId ? { pipelineId } : undefined,
params: { pipelineId },
});
boardPipelineId.value = data.pipeline.id;
stages.value = mapBoardToStages(data, formatDealDate);
if (!pipelineId || pipelineId !== data.pipeline.id) {
if (requested !== data.pipeline.id) {
await router.replace({
name: 'pipeline',
query: { pipelineId: data.pipeline.id },
@@ -236,13 +244,9 @@ function onPointerMove(event: PointerEvent | MouseEvent) {
}
function onDragStart(deal: PipelineDeal, event: DragEvent) {
draggingId.value = deal.id;
overlayDeal.value = deal;
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
draggingColumnId.value = null;
if (moving.value) moving.value = false;
dragSessionId = deal.id;
event.dataTransfer?.setData('text/plain', deal.id);
event.dataTransfer!.effectAllowed = 'move';
if (event.dataTransfer) {
@@ -251,12 +255,29 @@ function onDragStart(deal: PipelineDeal, event: DragEvent) {
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
event.dataTransfer.setDragImage(img, 0, 0);
}
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
// DOM را بعد از dragstart عوض کن تا کروم درگ را لغو نکند
window.setTimeout(() => {
if (dragSessionId !== deal.id) return;
draggingId.value = deal.id;
overlayDeal.value = deal;
}, 0);
}
function onDragEnd() {
draggingId.value = null;
dropStageId.value = null;
overlayDeal.value = null;
const endedId = dragSessionId ?? draggingId.value;
window.setTimeout(() => {
if (dragSessionId && dragSessionId !== endedId) return;
if (draggingId.value && draggingId.value !== endedId) return;
dragSessionId = null;
draggingId.value = null;
dropStageId.value = null;
overlayDeal.value = null;
}, 0);
}
function onDragOver(stageId: string, event: DragEvent) {
@@ -296,37 +317,45 @@ async function applyUpdateDealStage(
async function onDrop(stageId: string, event: DragEvent, index?: number) {
event.preventDefault();
const raw =
event.dataTransfer?.getData('text/plain') ||
draggingColumnId.value ||
draggingId.value ||
'';
const transfer = event.dataTransfer?.getData('text/plain') || '';
const draggedCardId = dragSessionId || draggingId.value;
const columnId = draggingColumnId.value;
dropStageId.value = null;
dragSessionId = null;
draggingId.value = null;
overlayDeal.value = null;
if (raw.startsWith('stage:') || draggingColumnId.value) {
const fromId = raw.replace(/^stage:/, '') || draggingColumnId.value;
draggingColumnId.value = null;
if (fromId) await reorderColumn(fromId, stageId);
draggingColumnId.value = null;
// کارت بر payload ستون اولویت دارد
const dealId =
draggedCardId || (transfer && !transfer.startsWith('stage:') ? transfer : '');
if (dealId) {
const current = stages.value.find((stage) => stage.deals.some((deal) => deal.id === dealId));
if (current?.id === stageId && index == null) return;
const next = updateDealStage(stages.value, dealId, stageId, index);
const unchanged = next.every((stage, stageIndex) => {
const prev = stages.value[stageIndex];
return (
stage.deals.length === (prev?.deals.length ?? -1) &&
stage.deals.every((deal, dealIndex) => deal.id === prev?.deals[dealIndex]?.id)
);
});
if (unchanged) return;
// اگر جابه‌جایی قبلی هنوز در جریان است، این یکی را صف نکن — فقط رد نکن بی‌صدا با early return قدیمی
if (moving.value) {
moving.value = false;
}
await applyUpdateDealStage(dealId, stageId, index);
return;
}
const dealId = raw;
if (!dealId || moving.value) return;
const current = stages.value.find((stage) => stage.deals.some((deal) => deal.id === dealId));
if (current?.id === stageId && index == null) return;
const next = updateDealStage(stages.value, dealId, stageId, index);
const unchanged = next.every((stage, stageIndex) => {
const prev = stages.value[stageIndex];
return (
stage.deals.length === (prev?.deals.length ?? -1) &&
stage.deals.every((deal, dealIndex) => deal.id === prev?.deals[dealIndex]?.id)
);
});
if (unchanged) return;
await applyUpdateDealStage(dealId, stageId, index);
const isStageDrag = transfer.startsWith('stage:');
if (isStageDrag || columnId) {
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId;
if (fromId) await reorderColumn(fromId, stageId);
}
}
function apiMessage(e: unknown, fallback: string) {
@@ -343,6 +372,8 @@ function onAddDeal(stageId: string) {
}
function onColumnDragStart(stageId: string) {
draggingId.value = null;
overlayDeal.value = null;
draggingColumnId.value = stageId;
}
+397 -140
View File
@@ -480,149 +480,121 @@ onMounted(load);
:options="statusOptions"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8" :lg="5">
<a-form-item label="مرتب‌سازی">
<a-select v-model:value="sort" :options="sortOptions" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-divider orientation="right">لیست محصولات</a-divider>
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8" @click.stop>
<a-typography-text v-if="selected.size" type="secondary">
{{ toFaDigits(selected.size) }} محصول انتخاب شده است
</a-typography-text>
<a-typography-text v-else type="secondary">
{{ toFaDigits(filtered.length) }} محصول
</a-typography-text>
<TableColumnsMenu table-key="products" align="end" />
</a-flex>
<a-alert
v-if="error"
type="error"
show-icon
:message="error"
:style="{ marginTop: '16px' }"
/>
<a-alert
v-if="importMsg"
type="success"
show-icon
:message="importMsg"
:style="{ marginTop: '16px' }"
/>
<a-spin :spinning="pageBusy" :tip="busyMessage">
<CrmSkeleton :loading="loading">
<CrmSkeletonTable :rows="8" :columns="8" :card="false">
<a-table
:columns="columns"
:data-source="pageItems"
:pagination="false"
row-key="id"
:row-selection="{
selectedRowKeys: selectedKeys,
onChange: onTableSelectChange,
onSelectAll: toggleSelectAll,
}"
:scroll="{ x: 'max-content' }"
:style="{ marginTop: '16px' }"
>
<template #emptyText>
<a-empty
description="محصولی یافت نشد؛ هیچ محصولی با معیارهای جستجو مطابقت ندارد."
/>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'نام محصول'">
<a-space :size="12" align="start">
<a-avatar shape="square">
<template #icon>
<ToolOutlined v-if="record.kind === 'service'" />
<ShoppingOutlined v-else />
</template>
</a-avatar>
<a-flex vertical :gap="0">
<a-typography-text strong>{{ record.name }}</a-typography-text>
<a-typography-text v-if="record.description" type="secondary">
{{ record.description }}
</a-typography-text>
</a-flex>
</a-space>
</template>
<template v-else-if="column.key === 'دسته‌بندی'">
<a-tag v-if="record.category" :bordered="false">{{ record.category }}</a-tag>
<a-typography-text v-else type="secondary">—</a-typography-text>
</template>
<template v-else-if="column.key === 'قیمت'">
<a-flex vertical :gap="0">
<a-typography-text strong>
{{ formatPrice(record.unitPrice, record.currency) }}
</a-typography-text>
<a-typography-text type="secondary">
{{ currencyLabel(record.currency) }}
</a-typography-text>
</a-flex>
</template>
<template v-else-if="column.key === 'وضعیت'">
<a-tag :color="record.isActive ? 'success' : 'default'" :bordered="false">
{{ record.isActive ? 'فعال' : 'غیرفعال' }}
</a-tag>
</template>
<template v-else-if="column.key === 'تاریخ ایجاد'">
<a-flex vertical :gap="0">
<a-typography-text>{{ formatDate(record.createdAt) }}</a-typography-text>
<a-typography-text type="secondary">
{{ formatTime(record.createdAt) }}
</a-typography-text>
</a-flex>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-dropdown
:open="menuId === record.id"
trigger="click"
@update:open="(v: boolean) => (menuId = v ? record.id : null)"
</td>
<td class="num-col">{{ toFaDigits((page - 1) * pageSize + idx + 1) }}</td>
<td>
<div class="name-cell">
<span class="thumb" :class="p.kind">
<UiIcon :name="p.kind === 'service' ? 'briefcase' : 'box'" :size="20" />
</span>
<div>
<strong>{{ p.name }}</strong>
<span v-if="p.description" class="desc">{{ p.description }}</span>
</div>
</div>
</td>
<td class="sku" dir="ltr">{{ p.sku || '—' }}</td>
<td>
<UiBadge v-if="p.category" variant="neutral" size="sm">{{ p.category }}</UiBadge>
<span v-else class="muted">—</span>
</td>
<td class="price">
<strong>{{ formatPrice(p.unitPrice, p.currency) }}</strong>
<small>{{ currencyLabel(p.currency) }}</small>
</td>
<td class="stock">{{ p.stockQty != null ? toFaDigits(p.stockQty) : '—' }}</td>
<td>
<UiBadge :variant="p.isActive ? 'success' : 'neutral'" size="sm" dot>
{{ p.isActive ? 'فعال' : 'غیرفعال' }}
</UiBadge>
</td>
<td class="when">
<span>{{ formatDate(p.createdAt) }}</span>
<small>{{ formatTime(p.createdAt) }}</small>
</td>
<td class="ops" @click.stop>
<UiDropdownMenu
:open="menuId === `d:${p.id}`"
align="end"
@update:open="(v) => (menuId = v ? `d:${p.id}` : null)"
>
<template #trigger="{ toggle }">
<button
type="button"
class="more"
aria-label="عملیات"
@click.stop="toggle"
>
<a-button type="text" aria-label="عملیات" @click.stop>
<template #icon><MoreOutlined /></template>
</a-button>
<template #overlay>
<a-menu @click="(info) => onRowMenu(info, record as ProductDto)">
<a-menu-item key="edit">ویرایش</a-menu-item>
<a-menu-item key="toggle-active">
{{ record.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
</a-menu-item>
<a-menu-item key="remove" danger>حذف</a-menu-item>
</a-menu>
</template>
</a-dropdown>
<UiIcon name="dots-v" :size="16" />
</button>
</template>
</template>
</a-table>
<button type="button" @click.stop="goEdit(p.id)">ویرایش</button>
<button type="button" @click.stop="toggleActive(p)">
{{ p.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
</button>
<button type="button" class="danger" @click.stop="removeProduct(p)">حذف</button>
</UiDropdownMenu>
</td>
</tr>
</tbody>
</table>
<UiEmptyState
v-if="!pageItems.length"
icon="box"
title="محصولی یافت نشد"
description="هیچ محصولی با معیارهای جستجو مطابقت ندارد."
/>
</div>
<a-flex v-if="filtered.length" justify="flex-end" :style="{ marginTop: '16px' }">
<a-pagination
v-model:current="page"
v-model:page-size="pageSize"
:total="filtered.length"
:show-size-changer="true"
:page-size-options="PAGE_SIZE_OPTIONS.map(String)"
:show-total="
(total: number) =>
`${toFaDigits(total)} مورد · ${toFaDigits(Math.max(1, Math.ceil(total / pageSize)))} صفحه`
"
/>
</a-flex>
</CrmSkeletonTable>
</CrmSkeleton>
</a-spin>
</a-card>
</a-flex>
<!-- Mobile cards -->
<div class="mob-list">
<article v-for="p in pageItems" :key="p.id" class="mob-card" @click.stop>
<span class="thumb" :class="p.kind">
<UiIcon :name="p.kind === 'service' ? 'briefcase' : 'box'" :size="22" />
</span>
<div class="mob-body">
<strong>{{ p.name }}</strong>
<span class="sku" dir="ltr">{{ p.sku || '—' }}</span>
<UiBadge v-if="p.category" variant="neutral" size="sm">{{ p.category }}</UiBadge>
<span class="mob-price">
{{ formatPrice(p.unitPrice, p.currency) }}
{{ currencyLabel(p.currency) }}
</span>
</div>
<div class="mob-side">
<UiDropdownMenu
:open="menuId === `m:${p.id}`"
align="end"
@update:open="(v) => (menuId = v ? `m:${p.id}` : null)"
>
<template #trigger="{ toggle }">
<button
type="button"
class="more"
aria-label="عملیات"
@click.stop="toggle"
>
<UiIcon name="dots-v" :size="16" />
</button>
</template>
<button type="button" @click.stop="goEdit(p.id)">ویرایش</button>
<button type="button" @click.stop="toggleActive(p)">
{{ p.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
</button>
<button type="button" class="danger" @click.stop="removeProduct(p)">حذف</button>
</UiDropdownMenu>
<UiBadge :variant="p.isActive ? 'success' : 'neutral'" size="sm" dot>
{{ p.isActive ? 'فعال' : 'غیرفعال' }}
</UiBadge>
</div>
</article>
<UiEmptyState
v-if="!pageItems.length"
icon="box"
title="محصولی یافت نشد"
description="هیچ محصولی با معیارهای جستجو مطابقت ندارد."
/>
</div>
<a-modal
v-model:open="productModal"
@@ -640,3 +612,288 @@ onMounted(load);
</a-modal>
</div>
</template>
<style scoped>
.more-wrap,
.sort-wrap,
.row-more {
position: relative;
}
.search-box {
flex: 1 1 240px;
min-width: 200px;
}
.more-wrap,
.sort-wrap,
.row-more {
position: relative;
}
.menu {
position: absolute;
top: calc(100% + 6px);
left: 0;
z-index: 20;
min-width: 160px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: 0 12px 28px rgba(15, 23, 42, 0.1);
padding: 0.35rem;
display: grid;
}
.menu.left {
left: auto;
right: 0;
}
.menu button {
border: 0;
background: transparent;
text-align: right;
padding: 0.55rem 0.7rem;
border-radius: var(--radius);
cursor: pointer;
color: var(--text);
}
.menu button:hover,
.menu button.on {
background: var(--accent-soft);
color: var(--accent);
}
.menu button.danger {
color: #b91c1c;
}
.table-wrap {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
overflow: auto;
}
table {
width: 100%;
border-collapse: collapse;
min-width: 900px;
}
th,
td {
padding: 0.85rem 0.75rem;
border-bottom: 1px solid var(--line);
text-align: right;
vertical-align: middle;
font-size: 0.92rem;
}
th {
color: var(--muted);
font-weight: 600;
background: #f8fafc;
white-space: nowrap;
}
tr:last-child td {
border-bottom: 0;
}
.check {
width: 42px;
}
.name-cell {
display: flex;
gap: 0.7rem;
align-items: flex-start;
}
.thumb {
width: 44px;
height: 44px;
border-radius: var(--radius);
display: grid;
place-items: center;
background: var(--accent-soft);
color: var(--accent);
flex-shrink: 0;
}
.thumb.service {
background: #e0f2fe;
color: #0369a1;
}
.name-cell strong,
.mob-body strong {
display: block;
}
.desc {
display: block;
margin-top: 0.15rem;
color: var(--muted);
font-size: 0.82rem;
}
.sku {
font-family: ui-monospace, monospace;
color: #475569;
direction: ltr;
text-align: left;
}
.pill {
display: inline-flex;
padding: 0.2rem 0.55rem;
border-radius: 999px;
background: #f1f5f9;
color: #334155;
font-size: 0.8rem;
font-weight: 600;
}
.pill.soft {
background: var(--accent-soft);
color: var(--accent);
margin-top: 0.25rem;
}
.price,
.when {
display: grid;
gap: 0.1rem;
}
.price small,
.when small {
color: var(--muted);
font-size: 0.78rem;
}
.status {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.22rem 0.55rem;
border-radius: 999px;
font-size: 0.8rem;
font-weight: 700;
}
.status i {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
.status.on {
background: #ccfbf1;
color: #0f766e;
}
.status.off {
background: #fee2e2;
color: #b91c1c;
}
.ops {
width: 64px;
}
.more {
width: 32px;
height: 32px;
border: 0;
background: none;
color: #94a3b8;
border-radius: var(--radius);
display: grid;
place-items: center;
cursor: pointer;
padding: 0;
}
.more:hover {
background: var(--accent-soft);
color: var(--accent);
}
.mob-list {
display: none;
gap: 0.65rem;
}
.mob-card {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 0.75rem;
align-items: start;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.85rem;
}
.mob-body {
display: grid;
gap: 0.15rem;
min-width: 0;
}
.mob-price {
margin-top: 0.25rem;
font-weight: 700;
color: #0f172a;
}
.mob-side {
display: grid;
justify-items: end;
gap: 0.45rem;
}
.pager {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.75rem;
align-items: center;
}
.pages {
display: flex;
gap: 0.35rem;
align-items: center;
}
.page-btn {
min-width: 36px;
height: 36px;
border-radius: 999px;
border: 1px solid var(--line);
background: var(--surface);
cursor: pointer;
}
.page-btn.on {
background: var(--accent);
color: #fff;
border-color: transparent;
}
.page-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.empty,
.muted {
color: var(--muted);
}
.error {
color: #b91c1c;
}
.ok {
color: #0f766e;
font-weight: 600;
}
.fab {
display: none;
position: fixed;
left: 1.1rem;
bottom: calc(1.1rem + var(--mobile-tabbar-h));
width: 56px;
height: 56px;
border-radius: 999px;
background: var(--accent);
color: #fff;
place-items: center;
text-decoration: none;
box-shadow: 0 10px 24px rgba(13, 148, 136, 0.35);
z-index: 30;
}
@media (max-width: 900px) {
.desk {
display: none;
}
.mob-list {
display: grid;
}
.fab {
display: grid;
}
.head-actions .btn.primary {
display: none;
}
.toolbar .filter-select:nth-of-type(2) {
display: none;
}
}
</style>
+47 -29
View File
@@ -90,6 +90,7 @@ const busy = ref(false);
const importMsg = ref('');
const draggingId = ref<string | null>(null);
let dragSessionId: string | null = null;
const draggingColumnId = ref<string | null>(null);
const dropStageId = ref<string | null>(null);
const overlayDeal = ref<PipelineDeal | null>(null);
@@ -211,13 +212,9 @@ function onPointerMove(event: PointerEvent | MouseEvent) {
}
function onDragStart(deal: PipelineDeal, event: DragEvent) {
draggingId.value = deal.id;
overlayDeal.value = deal;
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
draggingColumnId.value = null;
if (moving.value) moving.value = false;
dragSessionId = deal.id;
event.dataTransfer?.setData('text/plain', deal.id);
event.dataTransfer!.effectAllowed = 'move';
if (event.dataTransfer) {
@@ -226,12 +223,28 @@ function onDragStart(deal: PipelineDeal, event: DragEvent) {
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
event.dataTransfer.setDragImage(img, 0, 0);
}
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
window.setTimeout(() => {
if (dragSessionId !== deal.id) return;
draggingId.value = deal.id;
overlayDeal.value = deal;
}, 0);
}
function onDragEnd() {
draggingId.value = null;
dropStageId.value = null;
overlayDeal.value = null;
const endedId = dragSessionId ?? draggingId.value;
window.setTimeout(() => {
if (dragSessionId && dragSessionId !== endedId) return;
if (draggingId.value && draggingId.value !== endedId) return;
dragSessionId = null;
draggingId.value = null;
dropStageId.value = null;
overlayDeal.value = null;
}, 0);
}
function onDragOver(stageId: string, event: DragEvent) {
@@ -271,30 +284,33 @@ async function applyUpdateCardStage(
async function onDrop(stageId: string, event: DragEvent, index?: number) {
event.preventDefault();
const raw =
event.dataTransfer?.getData('text/plain') ||
draggingColumnId.value ||
draggingId.value ||
'';
const transfer = event.dataTransfer?.getData('text/plain') || '';
const draggedCardId = dragSessionId || draggingId.value;
const columnId = draggingColumnId.value;
dropStageId.value = null;
dragSessionId = null;
draggingId.value = null;
overlayDeal.value = null;
if (raw.startsWith('stage:') || draggingColumnId.value) {
const fromId = raw.replace(/^stage:/, '') || draggingColumnId.value;
draggingColumnId.value = null;
draggingColumnId.value = null;
const cardId =
draggedCardId || (transfer && !transfer.startsWith('stage:') ? transfer : '');
if (cardId) {
const current = stages.value.find((s) => s.deals.some((d) => d.id === cardId));
const currentIndex = current?.deals.findIndex((d) => d.id === cardId) ?? -1;
if (current?.id === stageId && (index == null || index === currentIndex)) {
return;
}
if (moving.value) moving.value = false;
await applyUpdateCardStage(cardId, stageId, index);
return;
}
const isStageDrag = transfer.startsWith('stage:');
if (isStageDrag || columnId) {
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId;
if (fromId) await reorderColumn(fromId, stageId);
return;
}
const cardId = raw;
if (!cardId || moving.value) return;
const current = stages.value.find((s) => s.deals.some((d) => d.id === cardId));
const currentIndex = current?.deals.findIndex((d) => d.id === cardId) ?? -1;
if (current?.id === stageId && (index == null || index === currentIndex)) {
return;
}
await applyUpdateCardStage(cardId, stageId, index);
}
function onAddCard(stageId: string) {
@@ -302,6 +318,8 @@ function onAddCard(stageId: string) {
}
function onColumnDragStart(stageId: string) {
draggingId.value = null;
overlayDeal.value = null;
draggingColumnId.value = stageId;
}
+318 -87
View File
@@ -86,6 +86,9 @@ type SyncResult = {
alreadyLinked?: boolean;
personId?: string | null;
personName?: string | null;
duplicateOfCode?: number | null;
duplicatePersonId?: string | null;
duplicatePersonName?: string | null;
};
const syncResults = ref<SyncResult[]>([]);
/** هر درخواست listAll یک بازهٔ ۲۰۰۰ کدی است؛ بعد از دو بازهٔ خالی پشت‌سرهم، خواندن تمام می‌شود */
@@ -188,9 +191,95 @@ async function saveAutoSync() {
}
}
/** همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها وارد، لینک‌شده‌ها پروفایل‌شان به‌روز می‌شود */
async function syncCustomersNow() {
if (!sync.connectionId) {
error.value = 'اتصال را انتخاب کنید.';
return;
}
syncBusy.value = true;
importOverlay.open = true;
importOverlay.progress = null;
importOverlay.message =
'در حال همگام‌سازی همهٔ مشتریان… نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه به‌روز می‌شود.';
error.value = '';
ok.value = '';
try {
const { data } = await api.post<{
imported: number;
updated: number;
duplicate: number;
failed: number;
summary: string;
error: string | null;
}>('/integrations/tahesab/sync/customers-now', {
connectionId: sync.connectionId,
});
ok.value = data.summary;
if (data.error) error.value = data.error;
await load();
} catch (e) {
error.value = apiErr(e, 'همگام‌سازی مشتریان ناموفق بود');
} finally {
syncBusy.value = false;
importOverlay.open = false;
}
}
/** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شماره‌ها فقط رقم‌اند. */
function customerPhoneKey(value?: string | null): string {
const fa = '۰۱۲۳۴۵۶۷۸۹';
const ar = '٠١٢٣٤٥٦٧٨٩';
let digits = String(value ?? '')
.replace(/[۰-۹٠-٩]/g, (ch) => {
const faIndex = fa.indexOf(ch);
return String(faIndex >= 0 ? faIndex : ar.indexOf(ch));
})
.replace(/\D/g, '');
if (!digits) return '';
if (digits.startsWith('0098') && digits.length >= 14) digits = digits.slice(4);
else if (digits.startsWith('98') && digits.length >= 12) digits = digits.slice(2);
if (digits.length === 10 && digits.startsWith('9')) digits = `0${digits}`;
return digits;
}
const linkedPhoneOwners = computed(() => {
const owners = new Map<string, { code: number; personId: string | null; personName: string | null }>();
for (const row of syncResults.value) {
if (!row.alreadyLinked || row.moshtariCode == null) continue;
const key = customerPhoneKey(row.tel);
if (key && !owners.has(key)) {
owners.set(key, {
code: row.moshtariCode,
personId: row.personId ?? null,
personName: row.personName ?? null,
});
}
}
return owners;
});
function duplicateOwner(row: SyncResult) {
if (row.alreadyLinked || row.moshtariCode == null) return null;
if (row.duplicateOfCode != null) {
return {
code: row.duplicateOfCode,
personId: row.duplicatePersonId ?? null,
personName: row.duplicatePersonName ?? null,
};
}
const key = customerPhoneKey(row.tel);
if (!key) return null;
const owner = linkedPhoneOwners.value.get(key);
if (!owner || owner.code === row.moshtariCode) return null;
return owner;
}
const duplicateCustomerCount = computed(
() => syncResults.value.filter((row) => duplicateOwner(row)).length,
);
const syncVisibleResults = computed(() =>
syncOnlyNew.value
? syncResults.value.filter((r) => !r.alreadyLinked)
? syncResults.value.filter((row) => !row.alreadyLinked && !duplicateOwner(row))
: syncResults.value,
);
const syncTableTotalPages = computed(() =>
@@ -227,7 +316,7 @@ const productCategoryLabel = ref('کارساخته');
function pendingImportCodes() {
return syncResults.value
.filter((r) => r.moshtariCode != null && !r.alreadyLinked)
.filter((r) => r.moshtariCode != null && !r.alreadyLinked && !duplicateOwner(r))
.map((r) => r.moshtariCode as number);
}
@@ -501,10 +590,12 @@ async function searchTahesab(mode: 'range' | 'filter') {
ok.value = 'نتیجه‌ای یافت نشد.';
} else {
const linked = syncResults.value.filter((r) => r.alreadyLinked).length;
const pending = syncResults.value.length - linked;
const duplicate = syncResults.value.filter((r) => duplicateOwner(r)).length;
const pending = syncResults.value.length - linked - duplicate;
ok.value =
`${toFaDigits(syncResults.value.length)} مشتری پیدا شد` +
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده`;
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده` +
(duplicate ? ` · ${toFaDigits(duplicate)} شماره تکراری` : '');
}
} catch (e) {
error.value = apiErr(e, 'جستجو ناموفق');
@@ -973,29 +1064,154 @@ onMounted(load);
extra="آدرس سرور وب‌سرویس ته‌حساب"
:rules="[{ required: true, message: 'آدرس وب‌سرویس را وارد کنید.' }]"
>
<a-input
v-model:value="form.baseUrl"
dir="ltr"
placeholder="https://IP:8081 یا https://api.tahesab.ir"
@blur="onBaseUrlBlur"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="نام دیتابیس (DBName)"
name="dbName"
:rules="[{ required: true, message: 'نام دیتابیس را وارد کنید.' }]"
فعال‌سازی SSL خودامضا
</UiButton>
<UiButton variant="ghost" size="sm" @click="startEdit(row)">
<template #icon>
<UiIcon name="pencil" />
</template>
ویرایش
</UiButton>
<UiButton variant="ghost" size="sm" @click="testConn(row.id)">
<template #icon>
<UiIcon name="refresh" />
</template>
تست اتصال
</UiButton>
<UiButton variant="danger" size="sm" @click="removeConn(row.id)">
<template #icon>
<UiIcon name="trash" />
</template>
حذف
</UiButton>
</div>
</div>
</div>
</UiCard>
<UiCard :title="editingId ? 'ویرایش اتصال ته‌حساب' : 'افزودن اتصال جدید ته‌حساب'" class="section-card">
<form class="crm-form" @submit.prevent="save">
<div class="crm-form-grid-2">
<UiField label="عنوان اتصال" required>
<UiInput v-model="form.label" required maxlength="120" placeholder="مثلاً شعبه مرکزی، دیتابیس مالی" />
</UiField>
<UiField label="آدرس وب‌سرویس (Base URL)" required hint="آدرس سرور وب‌سرویس ته‌حساب">
<UiInput
v-model="form.baseUrl"
required
dir="ltr"
placeholder="https://IP:8081 یا https://api.tahesab.ir"
@blur="onBaseUrlBlur"
/>
</UiField>
<UiField label="نام دیتابیس (DBName)" required>
<UiInput v-model="form.dbName" required dir="ltr" placeholder="DB یا TahesabDB" />
</UiField>
<UiField label="توکن دسترسی (Bearer Token)" :required="!editingId" :hint="editingId ? 'خالی بگذارید تا توکن فعلی تغییر نکند.' : 'توکن احراز هویت وب‌سرویس'">
<UiInput
v-model="form.token"
:required="!editingId"
type="password"
dir="ltr"
autocomplete="new-password"
placeholder="توکن امنیتی..."
/>
</UiField>
</div>
<div class="checkbox-group">
<label class="custom-check">
<input v-model="form.isDefault" type="checkbox" />
<span>اتصال پیش‌فرض سازمان</span>
</label>
<label class="custom-check">
<input v-model="form.enabled" type="checkbox" />
<span>اتصال فعال باشد</span>
</label>
<label class="custom-check highlight">
<input v-model="form.allowInsecureTls" type="checkbox" />
<span>پذیرش گواهی SSL خودامضا (برای IP محلی یا پورت داخلی بدون گواهی رسمی)</span>
</label>
</div>
<div class="form-actions-row">
<UiButton type="submit" :loading="saving">
{{ editingId ? 'به‌روزرسانی اتصال' : 'افزودن اتصال' }}
</UiButton>
<UiButton v-if="editingId" variant="ghost" type="button" @click="resetForm">
انصراف
</UiButton>
</div>
</form>
</UiCard>
<UiCard title="وارد کردن و همگام‌سازی مشتریان از ته‌حساب" class="section-card">
<p class="sync-desc">
با استفاده از این بخش می‌توانید اشخاص و طرف‌حساب‌های ته‌حساب را به عنوان مخاطب وارد نرم‌افزار کرده و سوابق مالی آن‌ها را پیوند دهید.
</p>
<div class="crm-form">
<UiField label="اتصال مورد نظر جهت همگام‌سازی" required>
<UiSelect v-model="sync.connectionId">
<option disabled value="">انتخاب اتصال</option>
<option v-for="row in items" :key="row.id" :value="row.id">
{{ row.label }} ({{ row.dbName }})
</option>
</UiSelect>
</UiField>
<div class="sync-sub-section">
<h4 class="sync-subhead">بروزرسانی خودکار</h4>
<p class="sync-sub-desc">
«همگام‌سازی الان» همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها را وارد می‌کند و برای مشتری‌های از قبل
لینک‌شده نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه را از ته‌حساب تازه می‌کند. زمان‌بندی زیر
همان کار را در ساعت‌های انتخابی (به وقت تهران) تکرار می‌کند. خاموش یعنی فقط ورود دستی.
</p>
<UiField label="تعداد در روز">
<UiSelect
:model-value="autoCount"
:disabled="!sync.connectionId || autoSyncSaving"
@update:model-value="onAutoCount"
>
<a-input v-model:value="form.dbName" dir="ltr" placeholder="DB یا TahesabDB" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="توکن دسترسی (Bearer Token)"
name="token"
:extra="editingId ? 'خالی بگذارید تا توکن فعلی تغییر نکند.' : 'توکن احراز هویت وب‌سرویس'"
:rules="[{ required: !editingId, message: 'توکن الزامی است.' }]"
<option value="0">خاموش</option>
<option v-for="n in 6" :key="n" :value="String(n)">
{{ toFaDigits(n) }} بار
</option>
</UiSelect>
</UiField>
<div v-if="Number(autoCount) > 0" class="crm-form-grid-3">
<UiField
v-for="(_, index) in autoHours"
:key="index"
:label="`ساعت ${toFaDigits(index + 1)}`"
>
<UiSelect
:model-value="autoHours[index]"
:disabled="autoSyncSaving"
@update:model-value="setAutoHour(index, $event)"
>
<option v-for="hour in 24" :key="hour - 1" :value="String(hour - 1)">
{{ hourLabel(hour - 1) }}
</option>
</UiSelect>
</UiField>
</div>
<div class="sync-buttons">
<UiButton
:loading="syncBusy"
:disabled="!sync.connectionId || syncBusy || autoSyncSaving"
@click="syncCustomersNow"
>
همگام‌سازی الان (وارد + به‌روز کردن قبلی‌ها)
</UiButton>
<UiButton
variant="secondary"
:loading="autoSyncSaving"
:disabled="!sync.connectionId || syncBusy"
@click="saveAutoSync"
>
<a-input-password
v-model:value="form.token"
@@ -1223,68 +1439,83 @@ onMounted(load);
<a-card v-if="syncResults.length" type="inner">
<template #title>
نتایج جستجو ({{ syncVisibleResults.length }}<template v-if="syncOnlyNew"> از {{ syncResults.length }}</template>)
</template>
<a-flex vertical :gap="12">
<a-flex justify="flex-end">
<TableColumnsMenu table-key="tahesab.customers" align="end" />
</a-flex>
<a-table
:columns="customerColumns"
:data-source="syncPagedResults"
:pagination="false"
:row-key="(r: SyncResult) => String(r.moshtariCode)"
:scroll="{ x: 640 }"
</h4>
<p v-if="duplicateCustomerCount" class="sync-sub-desc">
{{ toFaDigits(duplicateCustomerCount) }} مشتری شمارهٔ تکراری دارند و جداگانه وارد نمی‌شوند؛ همان شخص با کد دیگری از قبل لینک است.
</p>
<div class="tc-row">
<TableColumnsMenu table-key="tahesab.customers" align="end" />
</div>
<div class="crm-table-container">
<table
v-table-cols="'tahesab.customers'"
class="crm-table"
:style="{ '--row-start': (syncTablePage - 1) * syncTablePageSize }"
>
<template #emptyText>همهٔ مشتریان این نتایج قبلاً وارد شده‌اند.</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'کد مشتری'">
{{ (record as SyncResult).moshtariCode }}
</template>
<template v-else-if="column.key === 'نام و نام خانوادگی'">
<a-typography-text strong>{{ (record as SyncResult).name || 'بدون نام' }}</a-typography-text>
</template>
<template v-else-if="column.key === 'تلفن'">
<span dir="ltr">{{ (record as SyncResult).tel }}</span>
</template>
<template v-else-if="column.key === 'وضعیت لینک'">
<a-tag v-if="(record as SyncResult).alreadyLinked" color="success" :bordered="false">
لینک شده{{ (record as SyncResult).personName ? ` (${(record as SyncResult).personName})` : '' }}
</a-tag>
<a-tag v-else color="default" :bordered="false">آماده ورود</a-tag>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-button
v-if="!(record as SyncResult).alreadyLinked"
type="primary"
:disabled="!(record as SyncResult).moshtariCode || syncBusy"
@click="importOne((record as SyncResult).moshtariCode!)"
>
وارد کردن
</a-button>
<RouterLink
v-else-if="(record as SyncResult).personId"
:to="{ name: 'person-detail', params: { id: (record as SyncResult).personId } }"
>
<a-button type="text">مشاهده شخص</a-button>
</RouterLink>
</template>
</template>
</a-table>
<a-flex v-if="syncVisibleResults.length > SYNC_TABLE_PAGE_SIZES[0]" justify="flex-end">
<a-pagination
:current="syncTablePage"
:total="syncVisibleResults.length"
:page-size="syncTablePageSize"
:page-size-options="SYNC_TABLE_PAGE_SIZES.map(String)"
show-size-changer
@change="onSyncTablePageChange"
@update:page-size="(n: number) => (syncTablePageSize = n)"
/>
</a-flex>
</a-flex>
</a-card>
</a-flex>
</a-card>
<thead>
<tr>
<th>کد مشتری</th>
<th>نام و نام خانوادگی</th>
<th>تلفن</th>
<th>وضعیت لینک</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
<tr v-if="!syncPagedResults.length">
<td colspan="5" class="sync-empty-row">
مشتری تازه‌ای برای ورود نیست. شماره‌های تکراری از قبل با کد دیگری لینک شده‌اند.
</td>
</tr>
<tr v-for="r in syncPagedResults" :key="String(r.moshtariCode)">
<td class="font-mono">{{ r.moshtariCode }}</td>
<td class="font-bold">{{ r.name || 'بدون نام' }}</td>
<td class="font-mono" dir="ltr">{{ r.tel }}</td>
<td>
<UiBadge v-if="r.alreadyLinked" variant="success">
لینک شده{{ r.personName ? ` (${r.personName})` : '' }}
</UiBadge>
<UiBadge v-else-if="duplicateOwner(r)" variant="warning">
شماره تکراری، کد {{ toFaDigits(duplicateOwner(r)!.code) }}
</UiBadge>
<UiBadge v-else variant="neutral">آماده ورود</UiBadge>
</td>
<td>
<UiButton
v-if="!r.alreadyLinked && !duplicateOwner(r)"
size="sm"
:disabled="!r.moshtariCode || syncBusy"
@click="importOne(r.moshtariCode!)"
>
وارد کردن
</UiButton>
<RouterLink
v-else-if="r.personId || duplicateOwner(r)?.personId"
:to="{ name: 'person-detail', params: { id: (r.personId || duplicateOwner(r)?.personId)! } }"
>
<UiButton variant="ghost" size="sm">
مشاهده شخص
</UiButton>
</RouterLink>
</td>
</tr>
</tbody>
</table>
</div>
<UiPagination
v-if="syncVisibleResults.length > SYNC_TABLE_PAGE_SIZES[0]"
:page="syncTablePage"
:total-pages="syncTableTotalPages"
:total-items="syncVisibleResults.length"
:page-size="syncTablePageSize"
:page-size-options="SYNC_TABLE_PAGE_SIZES"
class="sync-table-pagination"
@update:page="onSyncTablePageChange"
@update:page-size="syncTablePageSize = $event"
/>
</div>
</div>
</UiCard>
<a-card title="وارد کردن کارساخته از ته‌حساب به محصولات" :bordered="false">
<a-flex vertical :gap="16">
File diff suppressed because it is too large Load Diff
+575 -212
View File
@@ -47,12 +47,20 @@ const CALL_COL_LABELS = [
registerTableColumns('voip.calls', [...CALL_COL_LABELS]);
const callTableCols = useTableColumns(() => 'voip.calls');
type TabKey = 'generic' | 'daftareshoma';
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const items = ref<VoipConnectionDto[]>([]);
const calls = ref<VoipCallLogDto[]>([]);
const tab = ref<TabKey>('daftareshoma');
const callFilters = reactive({
direction: '',
status: '',
lineExtension: '',
});
const form = reactive({
label: 'سانترال اصلی',
@@ -61,12 +69,44 @@ const form = reactive({
enabled: true,
});
const webhookUrl = computed(() => {
if (!items.value[0]) return '';
const origin = typeof window !== 'undefined' ? window.location.origin : '';
return `${origin}/api/public/integrations/voip/${items.value[0].id}/webhook`;
const daftaForm = reactive({
label: 'دفتر شما',
apiToken: '',
fromNumber: '',
callerExtension: '',
enabled: true,
});
const genericItems = computed(() =>
items.value.filter((c) => c.provider !== 'daftareshoma'),
);
const daftaItems = computed(() =>
items.value.filter((c) => c.provider === 'daftareshoma'),
);
const activeDafta = computed(() => daftaItems.value[0] ?? null);
const knownLines = ref<string[]>([]);
const lineOptions = computed(() => {
const set = new Set(knownLines.value);
for (const c of calls.value) {
if (c.lineExtension) set.add(c.lineExtension);
}
if (callFilters.lineExtension) set.add(callFilters.lineExtension);
return [...set].sort();
});
const webhookUrlFor = (id: string | undefined) => {
if (!id) return '';
const origin = typeof window !== 'undefined' ? window.location.origin : '';
return `${origin}/api/public/integrations/voip/${id}/webhook`;
};
const genericWebhookUrl = computed(() =>
webhookUrlFor(genericItems.value[0]?.id),
);
const daftaWebhookUrl = computed(() => webhookUrlFor(activeDafta.value?.id));
const statusLabel: Record<string, string> = {
ringing: 'زنگ',
answered: 'پاسخ',
@@ -103,30 +143,32 @@ function noteLink(c: VoipCallLogDto): string | null {
return '/notes';
}
function summaryColor(status: string | null | undefined): string {
switch (status) {
case 'done':
return 'success';
case 'pending':
case 'processing':
return 'processing';
case 'failed':
return 'error';
default:
return 'default';
async function loadCalls() {
const params: Record<string, string> = {};
if (callFilters.direction) params.direction = callFilters.direction;
if (callFilters.status) params.status = callFilters.status;
if (callFilters.lineExtension) params.lineExtension = callFilters.lineExtension;
const callRes = await api.get<VoipCallLogDto[]>('/integrations/voip/calls', {
params,
});
calls.value = callRes.data;
const merged = new Set(knownLines.value);
for (const c of callRes.data) {
if (c.lineExtension) merged.add(c.lineExtension);
}
knownLines.value = [...merged].sort();
}
async function load() {
loading.value = true;
error.value = '';
try {
const [connRes, callRes] = await Promise.all([
const [connRes] = await Promise.all([
api.get<VoipConnectionDto[]>('/integrations/voip/connections'),
api.get<VoipCallLogDto[]>('/integrations/voip/calls'),
loadCalls(),
]);
items.value = connRes.data;
calls.value = callRes.data;
fillDaftaFromActive();
} catch (e) {
if (axios.isAxiosError(e) && e.response?.status === 403) {
error.value = 'ماژول تلفن سازمانی برای این محیط فعال نیست.';
@@ -138,16 +180,30 @@ async function load() {
}
}
async function create() {
async function applyCallFilters() {
loading.value = true;
error.value = '';
try {
await loadCalls();
} catch {
error.value = 'فیلتر تماس‌ها ناموفق بود.';
} finally {
loading.value = false;
}
}
async function createGeneric() {
if (!form.label.trim()) {
error.value = 'نام اتصال را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
ok.value = '';
try {
const payload: CreateVoipConnectionRequest = {
label: form.label.trim(),
provider: 'generic',
webhookSecret: form.webhookSecret.trim() || undefined,
clickToCallUrl: form.clickToCallUrl.trim() || null,
enabled: form.enabled,
@@ -165,6 +221,65 @@ async function create() {
}
}
async function saveDafta() {
if (!daftaForm.label.trim()) {
error.value = 'نام اتصال را وارد کنید.';
return;
}
if (!activeDafta.value && !daftaForm.apiToken.trim()) {
error.value = 'توکن API دفتر شما را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
ok.value = '';
try {
if (activeDafta.value) {
await api.patch(`/integrations/voip/connections/${activeDafta.value.id}`, {
label: daftaForm.label.trim(),
fromNumber: daftaForm.fromNumber.trim() || null,
callerExtension: daftaForm.callerExtension.trim() || null,
enabled: daftaForm.enabled,
...(daftaForm.apiToken.trim()
? { apiToken: daftaForm.apiToken.trim() }
: {}),
});
daftaForm.apiToken = '';
ok.value = 'اتصال دفتر شما بروزرسانی شد.';
} else {
const payload: CreateVoipConnectionRequest = {
label: daftaForm.label.trim(),
provider: 'daftareshoma',
apiToken: daftaForm.apiToken.trim(),
fromNumber: daftaForm.fromNumber.trim() || null,
callerExtension: daftaForm.callerExtension.trim() || null,
enabled: daftaForm.enabled,
};
await api.post('/integrations/voip/connections', payload);
daftaForm.apiToken = '';
ok.value =
'اتصال دفتر شما ذخیره شد. آدرس وب‌هوک را در پرتال دفتر شما ثبت کنید.';
}
await load();
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره ناموفق بود.')
: 'ذخیره ناموفق بود.';
} finally {
saving.value = false;
}
}
function fillDaftaFromActive() {
const c = activeDafta.value;
if (!c) return;
daftaForm.label = c.label;
daftaForm.fromNumber = c.fromNumber ?? '';
daftaForm.callerExtension = c.callerExtension ?? '';
daftaForm.enabled = c.enabled;
daftaForm.apiToken = '';
}
async function remove(id: string) {
if (!confirm('این اتصال حذف شود؟')) return;
try {
@@ -175,18 +290,19 @@ async function remove(id: string) {
}
}
async function copyWebhook() {
if (!webhookUrl.value) return;
async function copyText(text: string, msg: string) {
if (!text) return;
try {
await navigator.clipboard.writeText(webhookUrl.value);
ok.value = 'آدرس وب‌هوک کپی شد.';
await navigator.clipboard.writeText(text);
ok.value = msg;
} catch {
error.value = 'کپی ممکن نشد.';
}
}
onMounted(() => {
void load();
onMounted(async () => {
await load();
fillDaftaFromActive();
});
</script>
@@ -200,196 +316,443 @@ onMounted(() => {
</a-button>
</a-flex>
<a-alert v-if="error" type="error" show-icon :message="error" closable @close="error = ''" />
<a-alert v-if="ok" type="success" show-icon :message="ok" closable @close="ok = ''" />
<nav class="tabs" aria-label="نوع اتصال تلفن">
<button
type="button"
:class="{ on: tab === 'daftareshoma' }"
@click="tab = 'daftareshoma'"
>
دفتر شما
</button>
<button
type="button"
:class="{ on: tab === 'generic' }"
@click="tab = 'generic'"
>
وب‌هوک عمومی
</button>
</nav>
<CrmSkeleton :loading="loading">
<CrmSkeletonCard :rows="8">
<a-flex vertical :gap="16">
<a-card title="اتصال جدید" :bordered="false">
<a-typography-paragraph type="secondary">
سانترال یا سرویس VoIP شما باید رویداد تماس را با JSON به آدرس وب‌هوک بفرستد. فیلدهای اصلی:
<code>callId</code>، <code>direction</code> (inbound/outbound)، <code>status</code>،
<code>from</code>، <code>to</code>. برای خلاصه خودکار یکی از <code>recordingUrl</code>
(لینک فایل ضبط) یا <code>transcript</code> (متن آماده) را بفرستید؛ پس از
<code>completed</code> / <code>answered</code> صف خلاصه ساخته می‌شود. امضا اختیاری با هدر
<code>X-Voip-Signature</code> (HMAC-SHA256 هگز).
</a-typography-paragraph>
<a-form layout="vertical" @finish="create">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="نام" required>
<a-input
v-model:value="form.label"
placeholder="سانترال اصلی"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="رمز وب‌هوک (اختیاری)">
<a-input-password
v-model:value="form.webhookSecret"
dir="ltr"
placeholder="برای تأیید امضا"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="آدرس Click-to-Call (اختیاری)">
<a-input
v-model:value="form.clickToCallUrl"
dir="ltr"
placeholder="https://pbx.example/originate?num={number}"
style="width: 100%"
/>
</a-form-item>
</a-col>
</a-row>
<a-form-item>
<a-button type="primary" html-type="submit" :loading="saving">ذخیره اتصال</a-button>
</a-form-item>
</a-form>
</a-card>
<p v-if="error" class="error">{{ error }}</p>
<p v-if="ok" class="ok">{{ ok }}</p>
<a-card title="اتصال‌ها" :bordered="false">
<a-flex vertical :gap="12">
<a-empty
v-if="!loading && !items.length"
description="اتصالی نیست. یک اتصال برای دریافت رویداد تماس بسازید."
<template v-if="tab === 'daftareshoma'">
<UiCard title="اتصال دفتر شما">
<p class="hint">
برای ثبت همه تماس‌های ورودی و خروجی فقط توکن و وب‌هوک لازم است.
توکن را از پرتال (توسعه‌دهندگان → API) بگیرید؛ بعد آدرس وب‌هوک را در
<strong>تنظیمات → هوک</strong>
با رویدادهای شروع/پایان ورودی و پایان خروجی ثبت کنید.
فیلدهای شماره مبدأ و خط فقط برای «تماس از داخل CRM» اختیاری‌اند و بعداً قابل تکمیل‌اند.
</p>
<div class="form-grid">
<UiField label="نام">
<UiInput v-model="daftaForm.label" placeholder="دفتر شما" />
</UiField>
<UiField
:label="activeDafta?.apiTokenSet ? 'توکن API (خالی = بدون تغییر)' : 'توکن API'"
>
<UiInput
v-model="daftaForm.apiToken"
type="password"
placeholder="توکن از پرتال دفتر شما"
autocomplete="off"
/>
<a-card v-for="c in items" :key="c.id" type="inner">
<a-row :gutter="[16, 12]" align="middle">
<a-col :xs="24" :lg="18">
<a-flex vertical :gap="4">
<a-typography-text strong>{{ c.label }}</a-typography-text>
<a-typography-text type="secondary">
تماس‌های ثبت‌شده {{ toFaDigits(c.callCount) }} ·
{{
c.lastEventAt
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
: 'هنوز رویدادی نیامده'
}}
</a-typography-text>
<a-tag v-if="c.clickToCallUrl" color="processing" :bordered="false">
Click-to-Call فعال
</a-tag>
<a-alert
v-if="c.lastError"
type="warning"
show-icon
:message="c.lastError"
/>
</a-flex>
</a-col>
<a-col :xs="24" :lg="6">
<a-button danger @click="remove(c.id)">حذف</a-button>
</a-col>
</a-row>
</a-card>
</UiField>
<UiField label="شماره مبدأ — اختیاری (فقط تماس خروجی از CRM)">
<UiInput
v-model="daftaForm.fromNumber"
placeholder="موبایل همکار برای click-to-call"
dir="ltr"
/>
</UiField>
<UiField label="خط پیش‌فرض — اختیاری (فقط تماس خروجی از CRM)">
<UiInput
v-model="daftaForm.callerExtension"
placeholder="مثلاً 02128425990"
dir="ltr"
/>
</UiField>
</div>
<UiButton :loading="saving" @click="saveDafta">
{{ activeDafta ? 'بروزرسانی اتصال' : 'ذخیره اتصال دفتر شما' }}
</UiButton>
</UiCard>
<a-card v-if="webhookUrl" type="inner" title="آدرس وب‌هوک">
<a-flex vertical :gap="8">
<a-typography-text dir="ltr" code>{{ webhookUrl }}</a-typography-text>
<div>
<a-button @click="copyWebhook">
<template #icon><CopyOutlined /></template>
کپی
</a-button>
</div>
</a-flex>
</a-card>
</a-flex>
</a-card>
<UiCard title="اتصال‌های دفتر شما">
<UiEmptyState
v-if="!loading && !daftaItems.length"
title="اتصالی نیست"
description="توکن و مشخصات خط را ذخیره کنید."
/>
<div v-else class="list">
<article v-for="c in daftaItems" :key="c.id" class="item">
<div>
<strong>{{ c.label }}</strong>
<p class="muted">
تماس‌های ثبت‌شده {{ toFaDigits(c.callCount) }}
·
{{
c.lastEventAt
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
: 'هنوز رویدادی نیامده'
}}
</p>
<p class="muted">
مبدأ {{ c.fromNumber || '—' }} · خط {{ c.callerExtension || '—' }}
· توکن {{ c.apiTokenSet ? 'ثبت شده' : 'ندارد' }}
</p>
<p v-if="c.lastError" class="warn">{{ c.lastError }}</p>
</div>
<UiButton variant="secondary" @click="remove(c.id)">حذف</UiButton>
</article>
</div>
<div v-if="daftaWebhookUrl" class="webhook">
<p class="hint">
آدرس وب‌هوک برای پرتال دفتر شما (رویدادها را با JSON به این آدرس POST کنید):
</p>
<code>{{ daftaWebhookUrl }}</code>
<UiButton
variant="secondary"
@click="copyText(daftaWebhookUrl, 'آدرس وب‌هوک دفتر شما کپی شد.')"
>
کپی
</UiButton>
</div>
</UiCard>
</template>
<a-card title="آخرین تماس‌ها" :bordered="false">
<a-empty
v-if="!calls.length"
description="تماسی نیست. پس از ارسال رویداد از سانترال اینجا دیده می‌شوند."
/>
<a-flex v-else vertical :gap="12">
<a-flex justify="flex-end">
<TableColumnsMenu table-key="voip.calls" align="end" />
</a-flex>
<a-table
:columns="callColumns"
:data-source="calls"
:pagination="false"
row-key="id"
:scroll="{ x: 'max-content' }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'جهت'">
{{ (record as VoipCallLogDto).direction === 'outbound' ? 'خروجی' : 'ورودی' }}
</template>
<template v-else-if="column.key === 'وضعیت'">
{{
statusLabel[(record as VoipCallLogDto).status] ??
(record as VoipCallLogDto).status
}}
</template>
<template v-else-if="column.key === 'از / به'">
<span dir="ltr">
{{ (record as VoipCallLogDto).fromNumber || '—' }} →
{{ (record as VoipCallLogDto).toNumber || '—' }}
</span>
</template>
<template v-else-if="column.key === 'مشتری'">
{{ (record as VoipCallLogDto).personName || '—' }}
</template>
<template v-else-if="column.key === 'مدت'">
{{
(record as VoipCallLogDto).durationSec != null
? `${toFaDigits((record as VoipCallLogDto).durationSec!)} ثانیه`
: '—'
}}
</template>
<template v-else-if="column.key === 'خلاصه'">
<a-flex vertical :gap="4">
<a-tag
:color="summaryColor((record as VoipCallLogDto).summaryStatus)"
:bordered="false"
>
{{
summaryLabel[(record as VoipCallLogDto).summaryStatus] ??
(record as VoipCallLogDto).summaryStatus ??
'—'
}}
</a-tag>
<a-typography-text
v-if="(record as VoipCallLogDto).summary"
type="secondary"
>
{{
rewriteGregorianDates((record as VoipCallLogDto).summary!).slice(0, 120)
}}{{
(record as VoipCallLogDto).summary!.length > 120 ? '…' : ''
}}
</a-typography-text>
<a-typography-text
v-if="
(record as VoipCallLogDto).summaryError &&
(record as VoipCallLogDto).summaryStatus === 'failed'
"
type="danger"
>
{{ (record as VoipCallLogDto).summaryError }}
</a-typography-text>
<RouterLink v-if="noteLink(record as VoipCallLogDto)" :to="noteLink(record as VoipCallLogDto)!">
مشاهده در پرونده
</RouterLink>
</a-flex>
</template>
<template v-else-if="column.key === 'زمان'">
{{ formatJalaliNumeric(new Date((record as VoipCallLogDto).startedAt)) }}
</template>
</template>
</a-table>
</a-flex>
</a-card>
</a-flex>
</CrmSkeletonCard>
</CrmSkeleton>
</a-flex>
<template v-else>
<UiCard title="اتصال جدید">
<p class="hint">
سانترال یا سرویس VoIP شما باید رویداد تماس را با JSON به آدرس وب‌هوک بفرستد.
فیلدهای اصلی:
<code>callId</code>،
<code>direction</code> (inbound/outbound)،
<code>status</code>،
<code>from</code>،
<code>to</code>.
برای خلاصه خودکار یکی از
<code>recordingUrl</code>
(لینک فایل ضبط) یا
<code>transcript</code>
(متن آماده) را بفرستید؛ پس از
<code>completed</code>
/
<code>answered</code>
صف خلاصه ساخته می‌شود.
امضا اختیاری با هدر
<code>X-Voip-Signature</code>
(HMAC-SHA256 هگز).
</p>
<div class="form-grid">
<UiField label="نام">
<UiInput v-model="form.label" placeholder="سانترال اصلی" />
</UiField>
<UiField label="رمز وب‌هوک (اختیاری)">
<UiInput v-model="form.webhookSecret" placeholder="برای تأیید امضا" />
</UiField>
<UiField label="آدرس Click-to-Call (اختیاری)">
<UiInput
v-model="form.clickToCallUrl"
placeholder="https://pbx.example/originate?num={number}"
/>
</UiField>
</div>
<UiButton :loading="saving" @click="createGeneric">ذخیره اتصال</UiButton>
</UiCard>
<UiCard title="اتصال‌ها">
<UiEmptyState
v-if="!loading && !genericItems.length"
title="اتصالی نیست"
description="یک اتصال برای دریافت رویداد تماس بسازید."
/>
<div v-else class="list">
<article v-for="c in genericItems" :key="c.id" class="item">
<div>
<strong>{{ c.label }}</strong>
<p class="muted">
تماس‌های ثبت‌شده {{ toFaDigits(c.callCount) }}
·
{{
c.lastEventAt
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
: 'هنوز رویدادی نیامده'
}}
</p>
<p v-if="c.clickToCallUrl" class="muted">Click-to-Call فعال</p>
<p v-if="c.lastError" class="warn">{{ c.lastError }}</p>
</div>
<UiButton variant="secondary" @click="remove(c.id)">حذف</UiButton>
</article>
</div>
<div v-if="genericWebhookUrl" class="webhook">
<p class="hint">آدرس وب‌هوک:</p>
<code>{{ genericWebhookUrl }}</code>
<UiButton
variant="secondary"
@click="copyText(genericWebhookUrl, 'آدرس وب‌هوک کپی شد.')"
>
کپی
</UiButton>
</div>
</UiCard>
</template>
<UiCard title="آخرین تماس‌ها">
<div class="call-filters">
<UiField label="جهت">
<select v-model="callFilters.direction" class="filter-select" @change="applyCallFilters">
<option value="">همه</option>
<option value="inbound">ورودی</option>
<option value="outbound">خروجی</option>
</select>
</UiField>
<UiField label="وضعیت">
<select v-model="callFilters.status" class="filter-select" @change="applyCallFilters">
<option value="">همه</option>
<option value="ringing">زنگ</option>
<option value="answered">پاسخ</option>
<option value="missed">از دست‌رفته</option>
<option value="completed">تمام‌شده</option>
<option value="failed">ناموفق</option>
</select>
</UiField>
<UiField label="خط">
<select
v-model="callFilters.lineExtension"
class="filter-select"
@change="applyCallFilters"
>
<option value="">همه خطوط</option>
<option v-for="line in lineOptions" :key="line" :value="line">
{{ line }}
</option>
</select>
</UiField>
</div>
<UiEmptyState
v-if="!calls.length"
title="تماسی نیست"
description="پس از ارسال رویداد از سانترال اینجا دیده می‌شوند."
/>
<div v-else class="table-wrap">
<div class="tc-row">
<TableColumnsMenu table-key="voip.calls" align="end" />
</div>
<table v-table-cols="'voip.calls'">
<thead>
<tr>
<th>جهت</th>
<th>وضعیت</th>
<th>خط</th>
<th>از / به</th>
<th>مشتری</th>
<th>مدت</th>
<th>خلاصه</th>
<th>زمان</th>
</tr>
</thead>
<tbody>
<tr v-for="c in calls" :key="c.id">
<td>{{ c.direction === 'outbound' ? 'خروجی' : 'ورودی' }}</td>
<td>{{ statusLabel[c.status] ?? c.status }}</td>
<td dir="ltr">{{ c.lineExtension || '—' }}</td>
<td>{{ c.fromNumber || '—' }} → {{ c.toNumber || '—' }}</td>
<td>{{ c.personName || '—' }}</td>
<td>
{{
c.durationSec != null
? `${toFaDigits(c.durationSec)} ثانیه`
: '—'
}}
</td>
<td class="summary-cell">
<span
class="summary-badge"
:data-status="c.summaryStatus || 'none'"
>
{{ summaryLabel[c.summaryStatus] ?? c.summaryStatus ?? '—' }}
</span>
<p v-if="c.summary" class="summary-preview">
{{ rewriteGregorianDates(c.summary).slice(0, 120) }}{{ c.summary.length > 120 ? '…' : '' }}
</p>
<p v-if="c.summaryError && c.summaryStatus === 'failed'" class="warn">
{{ c.summaryError }}
</p>
<RouterLink
v-if="noteLink(c)"
class="note-link"
:to="noteLink(c)!"
>
مشاهده در پرونده
</RouterLink>
</td>
<td>{{ formatJalaliNumeric(new Date(c.startedAt)) }}</td>
</tr>
</tbody>
</table>
</div>
</UiCard>
</div>
</template>
<style scoped>
.page {
display: grid;
gap: 1rem;
}
.tabs {
display: flex;
justify-content: flex-start;
gap: 1.75rem;
border-bottom: 1px solid #e2e8f0;
}
.tabs button {
appearance: none;
background: none;
border: 0;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
padding: 0.55rem 0.15rem;
color: #94a3b8;
font: inherit;
font-weight: 600;
cursor: pointer;
}
.tabs button.on {
color: #0d9488;
border-bottom-color: #14b8a6;
}
.hint,
.muted {
color: #64748b;
font-size: 0.88rem;
line-height: 1.7;
}
.hint code {
background: #f1f5f9;
padding: 0.1rem 0.35rem;
border-radius: 6px;
font-size: 0.8rem;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
margin: 0.75rem 0 1rem;
}
.call-filters {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
margin-bottom: 1rem;
}
.filter-select {
width: 100%;
min-height: 36px;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 0.35rem 0.6rem;
background: #fff;
font: inherit;
}
.list {
display: grid;
gap: 0.75rem;
}
.item {
display: flex;
justify-content: space-between;
gap: 0.75rem;
padding: 0.85rem;
border: 1px solid #eef2f7;
border-radius: var(--radius);
}
.webhook {
margin-top: 1rem;
padding: 0.75rem;
background: #f8fafc;
border-radius: var(--radius);
display: grid;
gap: 0.5rem;
}
.webhook code {
word-break: break-all;
font-size: 0.85rem;
}
.warn {
color: #b45309;
font-size: 0.85rem;
}
.error {
color: #b91c1c;
font-weight: 600;
}
.ok {
color: #0f766e;
font-weight: 600;
}
.table-wrap {
overflow: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
th,
td {
text-align: right;
padding: 0.55rem;
border-bottom: 1px solid #eef2f7;
vertical-align: top;
}
th {
color: #64748b;
font-size: 0.8rem;
}
.summary-cell {
max-width: 16rem;
}
.summary-badge {
display: inline-block;
font-size: 0.78rem;
padding: 0.15rem 0.45rem;
border-radius: 6px;
background: #f1f5f9;
color: #475569;
}
.summary-badge[data-status='done'] {
background: #ecfdf5;
color: #047857;
}
.summary-badge[data-status='pending'],
.summary-badge[data-status='processing'] {
background: #eff6ff;
color: #1d4ed8;
}
.summary-badge[data-status='failed'] {
background: #fef2f2;
color: #b91c1c;
}
.summary-preview {
margin: 0.35rem 0 0;
font-size: 0.82rem;
color: #334155;
line-height: 1.5;
}
.note-link {
display: inline-block;
margin-top: 0.35rem;
font-size: 0.8rem;
color: #0f766e;
}
@media (max-width: 800px) {
.form-grid,
.call-filters {
grid-template-columns: 1fr;
}
}
</style>
+20 -1
View File
@@ -1,11 +1,13 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import type { BillingAccountDto, BillingPlanCode, OwnerSeatUsageDto, StorageUsageDto } from '@mento/shared';
import type { BillingAccountDto, BillingPlanCode, OwnerSeatUsageDto, ProductPlanCode, StorageUsageDto } from '@mento/shared';
import {
BILLING_PLAN_CODES,
BILLING_PLAN_LABELS,
BILLING_USER_CAPS,
PRODUCT_PLAN_CODES,
PRODUCT_PLAN_LABELS,
isPermanentBillingPlan,
} from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
@@ -19,6 +21,7 @@ const props = defineProps<{
const emit = defineEmits<{
apply: [planCode: BillingPlanCode];
product: [planCode: ProductPlanCode];
}>();
const usage = ref<StorageUsageDto | null>(null);
@@ -178,6 +181,22 @@ onMounted(() => {
{{ BILLING_PLAN_LABELS[code] }}
</button>
</div>
<strong>سطح امکانات</strong>
<p class="muted">
انتخاب سطح، دسترسی محیط‌های این مالک را طبق تعرفه تیک می‌زند. هسته و تیم و سازمان سقف کاربر و محیط را هم تنظیم می‌کنند. ثبت‌نام دمو از هسته شروع می‌شود.
</p>
<div class="plan-row">
<button
v-for="code in PRODUCT_PLAN_CODES"
:key="code"
class="btn btn-ghost"
type="button"
:disabled="busyId === `product-${userId}-${code}`"
@click="emit('product', code)"
>
{{ PRODUCT_PLAN_LABELS[code] }}
</button>
</div>
<div v-if="billing" class="storage">
<strong>تعداد کاربر</strong>
<p v-if="seats" class="muted">
@@ -6,8 +6,9 @@ import type {
BillingPlanCode,
PlatformOrganizationDto,
PlatformOrgMemberDto,
ProductPlanCode,
} from '@mento/shared';
import { BILLING_PLAN_LABELS } from '@mento/shared';
import { BILLING_PLAN_LABELS, PRODUCT_PLAN_LABELS } from '@mento/shared';
import { platformApi } from '@/lib/platform-api';
import AdmBillingPanel from './AdmBillingPanel.vue';
@@ -50,7 +51,8 @@ async function loadOwners() {
const { data } = await platformApi.get<PlatformOrganizationDto>(
`/platform/organizations/${orgId.value}`,
);
owners.value = (data.members ?? []).filter((member) => member.role === 'owner');
const ownersInOrder = (data.members ?? []).filter((member) => member.role === 'owner');
owners.value = ownersInOrder.slice(0, 1);
} catch (e) {
error.value = apiError(e, 'بارگذاری اشتراک محیط ناموفق بود');
} finally {
@@ -58,6 +60,21 @@ async function loadOwners() {
}
}
async function applyProduct(userId: string, planCode: ProductPlanCode) {
busyId.value = `product-${userId}-${planCode}`;
error.value = '';
success.value = '';
try {
await platformApi.post(`/platform/organizations/${orgId.value}/product-plan`, { planCode });
await loadOwners();
success.value = `سطح «${PRODUCT_PLAN_LABELS[planCode]}» روی دسترسی‌ها اعمال شد`;
} catch (e) {
error.value = apiError(e, 'اعمال سطح امکانات ناموفق بود');
} finally {
busyId.value = '';
}
}
async function applyPlan(userId: string, planCode: BillingPlanCode) {
busyId.value = `plan-${userId}-${planCode}`;
error.value = '';
@@ -100,11 +117,12 @@ onMounted(() => {
<p v-else-if="orgId && !owners.length" class="muted">این محیط مالک فعالی ندارد.</p>
<AdmBillingPanel
v-for="owner in owners"
:key="`${owner.userId}-${owner.billing?.planCode ?? ''}-${owner.billing?.expiresAt ?? ''}`"
:key="`${owner.userId}-${owner.billing?.planCode ?? ''}-${owner.billing?.expiresAt ?? ''}-${owner.billing?.maxUsers ?? ''}-${owner.billing?.maxOrganizations ?? ''}`"
:user-id="owner.userId"
:billing="owner.billing"
:busy-id="busyId"
@apply="applyPlan(owner.userId, $event)"
@product="applyProduct(owner.userId, $event)"
/>
</div>
</div>
@@ -5,6 +5,7 @@ import type {
CreatePlatformOrganizationRequest,
OrgModuleKey,
PlatformOrganizationDto,
ProductPlanCode,
UpdatePlatformOrganizationRequest,
UserRole,
} from '@mento/shared';
@@ -12,6 +13,8 @@ import {
BILLING_PLAN_LABELS,
ORG_MODULE_GROUPS,
ORG_MODULE_LABELS,
PRODUCT_PLAN_CODES,
PRODUCT_PLAN_LABELS,
USER_ROLE_LABELS,
USER_ROLES,
isBusinessField,
@@ -265,6 +268,25 @@ async function setMembershipRole(membershipId: string, role: UserRole) {
}
}
async function applyProductPlan(orgId: string, planCode: ProductPlanCode) {
savingModules.value = true;
error.value = '';
success.value = '';
try {
const { data } = await platformApi.post<PlatformOrganizationDto>(
`/platform/organizations/${orgId}/product-plan`,
{ planCode },
);
moduleDraft.value = [...(data.enabledModules ?? [])];
if (detail.value?.id === orgId) detail.value = data;
success.value = `سطح «${PRODUCT_PLAN_LABELS[planCode]}» روی دسترسی‌ها اعمال شد`;
} catch (e) {
error.value = apiError(e, 'اعمال سطح امکانات ناموفق بود');
} finally {
savingModules.value = false;
}
}
function toggleModule(key: OrgModuleKey) {
if (moduleDraft.value.includes(key)) {
moduleDraft.value = moduleDraft.value.filter((k) => k !== key);
@@ -434,6 +456,16 @@ onMounted(() => {
<div class="modules">
<div class="modules-head">
<strong>ماژول‌های فعال</strong>
<button
v-for="code in PRODUCT_PLAN_CODES"
:key="code"
class="btn btn-ghost"
type="button"
:disabled="savingModules"
@click="applyProductPlan(org.id, code)"
>
{{ PRODUCT_PLAN_LABELS[code] }}
</button>
<button
class="btn"
type="button"
@@ -522,7 +554,8 @@ onMounted(() => {
<div class="member-actions">
<select
:value="member.role"
:disabled="busyId === `role-${member.membershipId}`"
:disabled="member.role === 'owner' || busyId === `role-${member.membershipId}`"
:title="member.role === 'owner' ? 'مالک همان ثبت‌نام‌کننده است و عوض نمی‌شود' : undefined"
@change="
setMembershipRole(
member.membershipId,
@@ -530,7 +563,11 @@ onMounted(() => {
)
"
>
<option v-for="role in USER_ROLES" :key="role" :value="role">
<option
v-for="role in USER_ROLES.filter((role) => role !== 'owner' || member.role === 'owner')"
:key="role"
:value="role"
>
{{ USER_ROLE_LABELS[role] }}
</option>
</select>
+7 -2
View File
@@ -247,7 +247,8 @@ onMounted(() => {
<div class="member-actions">
<select
:value="mem.role"
:disabled="busyId === `role-${mem.membershipId}`"
:disabled="mem.role === 'owner' || busyId === `role-${mem.membershipId}`"
:title="mem.role === 'owner' ? 'مالک همان ثبت‌نام‌کننده است و عوض نمی‌شود' : undefined"
@change="
setMembershipRole(
user.id,
@@ -256,7 +257,11 @@ onMounted(() => {
)
"
>
<option v-for="role in USER_ROLES" :key="role" :value="role">
<option
v-for="role in USER_ROLES.filter((role) => role !== 'owner' || mem.role === 'owner')"
:key="role"
:value="role"
>
{{ USER_ROLE_LABELS[role] }}
</option>
</select>
@@ -29,7 +29,8 @@ import JalaliDateInput from '@/components/JalaliDateInput.vue';
import RecurrencePicker, { type RecurrenceValue } from '@/components/routines/RecurrencePicker.vue';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { PRIORITY_LABELS, ROUTINES_CTX, apiError, formatDayNumeric, todayKey } from '@/lib/routines';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { ROUTINES_CTX, apiError, formatDayNumeric, todayKey } from '@/lib/routines';
import { useAuthStore } from '@/stores/auth';
const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyParagraph } =
@@ -84,7 +85,16 @@ const error = ref('');
const loaded = ref<RoutineDto | null>(null);
const foreign = ref(false);
const priorities = Object.entries(PRIORITY_LABELS) as Array<[ActivityPriority, string]>;
const targetOptions = [
{ value: 'user' as const, label: 'یک کاربر' },
{ value: 'team' as const, label: 'همه اعضای یک تیم' },
];
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const priorities = computed(() =>
activityPriorities.items.value.map((r) => [r.key, r.label] as [ActivityPriority, string]),
);
const entityLinks = Object.entries(ROUTINE_ENTITY_LINK_LABELS) as Array<[RoutineEntityLink, string]>;
const categoryOptions = computed(() => [
@@ -5,8 +5,8 @@ import type { RoutineDto } from '@mento/shared';
import { useAuthStore } from '@/stores/auth';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import {
PRIORITY_LABELS,
PRIORITY_VARIANTS,
ROUTINES_CTX,
apiError,
@@ -37,6 +37,8 @@ const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyPa
const { token } = theme.useToken();
const shell = inject(ROUTINES_CTX)!;
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const auth = useAuthStore();
const meId = computed(() => auth.user?.id ?? '');
@@ -124,71 +126,39 @@ const TONE_COLORS: Record<string, string> = {
"
/>
<a-row v-else :gutter="[16, 16]">
<a-col v-for="r in filtered" :key="r.id" :xs="24" :sm="12" :xl="8">
<a-card :bordered="false" :style="{ height: '100%', background: token.colorFillQuaternary }">
<a-flex vertical :gap="12" :style="{ height: '100%' }">
<a-flex align="center" :gap="12">
<a-avatar
shape="square"
:style="{
background: r.category?.color ?? token.colorPrimary,
color: token.colorWhite,
flexShrink: 0,
}"
>
<template #icon><SyncOutlined /></template>
</a-avatar>
<a-flex vertical :gap="0" :style="{ minWidth: 0 }">
<a-typography-title :level="5" :style="{ margin: 0 }">
{{ r.title }}
</a-typography-title>
<a-typography-text type="secondary">
{{ r.recurrenceLabel }} · ساعت {{ toFaDigits(r.timeOfDay) }}
</a-typography-text>
</a-flex>
</a-flex>
<a-typography-paragraph v-if="r.description" type="secondary" :style="{ margin: 0 }">
{{ r.description }}
</a-typography-paragraph>
<a-space :size="6" wrap>
<a-tag v-if="r.category" :bordered="false">{{ r.category.name }}</a-tag>
<a-tag :color="priorityColor(r.priority)" :bordered="false">
{{ PRIORITY_LABELS[r.priority] }}
</a-tag>
<a-tag v-if="r.isMandatory" color="warning" :bordered="false">اجباری</a-tag>
<a-tag v-if="r.reportRequired" color="processing" :bordered="false">گزارش الزامی</a-tag>
<a-tag v-if="r.team" color="cyan" :bordered="false">تیم {{ r.team.name }}</a-tag>
</a-space>
<a-flex vertical :gap="4" :style="{ marginTop: 'auto' }">
<a-divider :style="{ margin: 0 }" />
<a-flex justify="space-between" align="center" :gap="8">
<a-typography-text type="secondary">اجرا در ۳۰ روز اخیر</a-typography-text>
<a-typography-text strong>{{ formatPercent(r.executionRate) }}</a-typography-text>
</a-flex>
<a-progress
:percent="Math.max(0, Math.min(100, Math.round(r.executionRate ?? 0)))"
:show-info="false"
:stroke-color="TONE_COLORS[percentTone(r.executionRate)]"
/>
<a-flex justify="space-between" align="center" :gap="8">
<a-typography-text type="secondary">
از {{ formatDayNumeric(r.startDate) }}{{ r.endDate ? ` تا ${formatDayNumeric(r.endDate)}` : '' }}
</a-typography-text>
<RouterLink v-if="r.createdById === meId" :to="`/routines/manage/${r.id}/edit`">
ویرایش
</RouterLink>
</a-flex>
</a-flex>
</a-flex>
</a-card>
</a-col>
</a-row>
</template>
</CrmSkeleton>
</a-flex>
</a-card>
<div v-else class="cards">
<article v-for="r in filtered" :key="r.id" class="rcard">
<header>
<span class="ico" :style="{ background: r.category?.color ?? 'var(--accent)' }">
<UiIcon name="refresh" :size="16" />
</span>
<div class="titles">
<h3>{{ r.title }}</h3>
<p>{{ r.recurrenceLabel }} · ساعت {{ toFaDigits(r.timeOfDay) }}</p>
</div>
</header>
<p v-if="r.description" class="desc">{{ r.description }}</p>
<div class="tags">
<UiBadge v-if="r.category" size="sm">{{ r.category.name }}</UiBadge>
<UiBadge size="sm" :variant="PRIORITY_VARIANTS[r.priority]">{{ activityPriorities.labelOf(r.priority) }}</UiBadge>
<UiBadge v-if="r.isMandatory" size="sm" variant="warning">اجباری</UiBadge>
<UiBadge v-if="r.reportRequired" size="sm" variant="info">گزارش الزامی</UiBadge>
<UiBadge v-if="r.team" size="sm" variant="accent">تیم {{ r.team.name }}</UiBadge>
</div>
<footer>
<div class="exec" :class="`tone-${percentTone(r.executionRate)}`">
<span>اجرا در ۳۰ روز اخیر</span>
<strong>{{ formatPercent(r.executionRate) }}</strong>
<i class="bar"><b :style="{ width: `${r.executionRate ?? 0}%` }" /></i>
</div>
<small class="since">
از {{ formatDayNumeric(r.startDate) }}{{ r.endDate ? ` تا ${formatDayNumeric(r.endDate)}` : '' }}
</small>
<RouterLink v-if="r.createdById === meId" :to="`/routines/manage/${r.id}/edit`" class="edit">
ویرایش
</RouterLink>
</footer>
</article>
</div>
</div>
</template>
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Select as ASelect } from 'ant-design-vue';
import type { RoutineCategoryDto, RoutineDto } from '@mento/shared';
import UserAvatar from '@/components/UserAvatar.vue';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
@@ -72,7 +73,8 @@ const loading = ref(true);
const error = ref('');
const q = ref('');
const status = ref<'all' | 'active' | 'inactive'>('all');
const assignee = ref('');
const assignee = ref<string | undefined>(undefined);
const creator = ref<string | undefined>(undefined);
const busyId = ref<string | null>(null);
const menuFor = ref<string | null>(null);
@@ -135,6 +137,7 @@ const filtered = computed(() => {
if (status.value === 'active' && !r.isActive) return false;
if (status.value === 'inactive' && r.isActive) return false;
if (assignee.value && r.assignee?.id !== assignee.value && `team:${r.team?.id}` !== assignee.value) return false;
if (creator.value && (r.createdBy?.id ?? r.createdById) !== creator.value) return false;
if (term && !r.title.includes(term)) return false;
return true;
});
@@ -322,46 +325,68 @@ function onRowMenu({ key }: { key: string | number }, r: RoutineDto) {
const users = computed(() => shell.context.value?.users ?? []);
const teams = computed(() => shell.context.value?.teams ?? []);
const assigneeFilterOptions = computed(() => [
...users.value.map((u) => ({ value: u.id, label: u.fullName })),
...teams.value.map((t) => ({ value: `team:${t.id}`, label: `تیم ${t.name}` })),
]);
const creatorFilterOptions = computed(() =>
users.value.map((u) => ({ value: u.id, label: u.fullName })),
);
function filterSelectOption(input: string, option?: { label?: string }) {
const q = input.trim().toLocaleLowerCase('fa');
if (!q) return true;
return String(option?.label ?? '')
.toLocaleLowerCase('fa')
.includes(q);
}
function selectPopupContainer(node: HTMLElement) {
return node.parentElement ?? document.body;
}
</script>
<template>
<a-card :bordered="false">
<a-flex vertical :gap="16">
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12" :lg="6">
<a-form-item label="جستجو">
<a-input v-model:value="q" allow-clear placeholder="جستجوی عنوان…">
<template #prefix><SearchOutlined /></template>
</a-input>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8" :lg="5">
<a-form-item label="مسئول">
<a-select v-model:value="assignee" :options="assigneeOptions" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8" :lg="5">
<a-form-item label="وضعیت">
<a-segmented v-model:value="status" :options="statusOptions" block />
</a-form-item>
</a-col>
<a-col :xs="24" :lg="8">
<a-form-item label=" ">
<a-flex justify="flex-end" :gap="8" wrap="wrap">
<a-button @click="catsOpen = true; editCat(null)">
<template #icon><AppstoreOutlined /></template>
دسته‌بندی‌ها
</a-button>
<a-button type="primary" @click="router.push('/routines/manage/new')">
<template #icon><PlusOutlined /></template>
روتین جدید
</a-button>
</a-flex>
</a-form-item>
</a-col>
</a-row>
</a-form>
<div class="manage">
<div class="toolbar">
<UiSearch v-model="q" placeholder="جستجوی عنوان…" class="search" />
<div class="who">
<ASelect
v-model:value="assignee"
allow-clear
show-search
placeholder="همه مسئول‌ها"
:options="assigneeFilterOptions"
:filter-option="filterSelectOption"
:get-popup-container="selectPopupContainer"
style="width: 100%"
/>
</div>
<div class="who">
<ASelect
v-model:value="creator"
allow-clear
show-search
placeholder="همه سازنده‌ها"
:options="creatorFilterOptions"
:filter-option="filterSelectOption"
:get-popup-container="selectPopupContainer"
style="width: 100%"
/>
</div>
<UiSegmented v-model="status" :options="statusOptions" />
<span class="spacer" />
<UiButton variant="ghost" size="sm" @click="catsOpen = true; editCat(null)">
<template #icon><UiIcon name="layers" :size="15" /></template>
دسته‌بندی‌ها
</UiButton>
<UiButton @click="router.push('/routines/manage/new')">
<template #icon><UiIcon name="plus" :size="16" /></template>
روتین جدید
</UiButton>
</div>
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-typography-text type="secondary">
@@ -372,22 +397,71 @@ const teams = computed(() => shell.context.value?.teams ?? []);
<a-alert v-if="error" type="error" show-icon :message="error" />
<CrmSkeleton :loading="loading">
<CrmSkeletonTable :rows="8" :columns="5" :card="false">
<a-table
:columns="columns"
:data-source="filtered"
:pagination="false"
row-key="id"
:scroll="{ x: 'max-content' }"
>
<template #emptyText>
<a-empty
:description="
items.length
? 'روتینی با این فیلتر پیدا نشد'
: 'هنوز روتینی تعریف نشده؛ روتین‌ها کارهای تکرارشونده‌ای هستند که هر روز به‌صورت خودکار برای مسئولشان ساخته می‌شوند.'
"
<UiEmptyState
v-else-if="!filtered.length"
icon="refresh"
:title="items.length ? 'روتینی با این فیلتر پیدا نشد' : 'هنوز روتینی تعریف نشده'"
description="روتین‌ها کارهای تکرارشونده‌ای هستند که هر روز به‌صورت خودکار برای مسئولشان ساخته می‌شوند."
>
<template v-if="!items.length" #action>
<UiButton @click="router.push('/routines/manage/new')">ساخت اولین روتین</UiButton>
</template>
</UiEmptyState>
<div v-else class="crm-table-container">
<table class="crm-table">
<thead>
<tr>
<th>عنوان</th>
<th>مسئول</th>
<th>سازنده</th>
<th>تکرار</th>
<th>ساعت</th>
<th>وضعیت</th>
<th>درصد انجام</th>
<th />
</tr>
</thead>
<tbody>
<tr v-for="r in filtered" :key="r.id" :class="{ inactive: !r.isActive }">
<td class="title-cell">
<span class="cat-dot" :style="{ background: r.category?.color ?? 'var(--line-strong)' }" />
<div>
<strong>{{ r.title }}</strong>
<small>
{{ r.category?.name ?? 'بدون دسته' }}
<template v-if="r.isMandatory"> · اجباری</template>
</small>
</div>
</td>
<td>
<span v-if="r.team" class="who-cell">
<span class="team-ico"><UiIcon name="users" :size="13" /></span>
تیم {{ r.team.name }}
</span>
<span v-else-if="r.assignee" class="who-cell">
<UserAvatar :name="r.assignee.fullName" :user-id="r.assignee.id" :size="24" />
{{ r.assignee.fullName }}
</span>
</td>
<td>
<span v-if="r.createdBy" class="who-cell">
<UserAvatar :name="r.createdBy.fullName" :user-id="r.createdBy.id" :size="24" />
{{ r.createdBy.fullName }}
</span>
<span v-else>—</span>
</td>
<td class="nowrap">{{ r.recurrenceLabel }}</td>
<td class="nowrap">{{ toFaDigits(r.timeOfDay) }}</td>
<td>
<button
type="button"
class="switch"
:class="{ on: r.isActive }"
:disabled="busyId === r.id"
:aria-pressed="r.isActive"
:aria-label="r.isActive ? 'غیرفعال کردن' : 'فعال کردن'"
@click="toggle(r)"
>
<a-button
v-if="!items.length"
@@ -7,9 +7,9 @@ import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
import RoutineTaskModals from '@/components/routines/RoutineTaskModals.vue';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import {
ENTITY_TYPE_LABELS,
PRIORITY_LABELS,
PRIORITY_VARIANTS,
ROUTINES_CTX,
apiError,
@@ -56,6 +56,8 @@ registerTableColumns('routines-overdue', [...OVERDUE_COL_LABELS]);
const tableCols = useTableColumns(() => 'routines-overdue');
const shell = inject(ROUTINES_CTX)!;
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const items = ref<RoutineTaskDto[]>([]);
const loading = ref(true);
@@ -182,82 +184,67 @@ function rowProps(record: RoutineTaskDto) {
<TableColumnsMenu table-key="routines-overdue" align="end" />
</a-flex>
<CrmSkeleton :loading="loading">
<CrmSkeletonTable :rows="8" :columns="7" :card="false">
<a-table
:columns="columns"
:data-source="items"
:pagination="false"
row-key="id"
:custom-row="rowProps"
:scroll="{ x: 'max-content' }"
:style="{ marginTop: '16px' }"
>
<template #emptyText>
<a-empty description="همه چیز به‌روز است؛ هیچ کاری از مهلتش عقب نیفتاده." />
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'کار'">
<a-flex vertical :gap="0">
<a-typography-text strong>{{ record.title }}</a-typography-text>
<a-space v-if="record.category" :size="6">
<a-badge :color="record.category.color" />
<a-typography-text type="secondary">{{ record.category.name }}</a-typography-text>
</a-space>
</a-flex>
</template>
<template v-else-if="column.key === 'مهلت'">
<a-typography-text>
{{ formatDayNumeric(record.scheduledFor) }}
</a-typography-text>
<a-typography-text v-if="hasExplicitTime(record as RoutineTaskDto)" type="secondary">
· {{ formatTime((record as RoutineTaskDto).dueAt) }}
</a-typography-text>
</template>
<template v-else-if="column.key === 'تأخیر'">
<a-typography-text strong type="danger">
{{ formatDelay((record as RoutineTaskDto).dueAt) }}
</a-typography-text>
</template>
<template v-else-if="column.key === 'مسئول'">
<a-space v-if="record.assignee" :size="8">
<UserAvatar
:name="record.assignee.fullName"
:user-id="record.assignee.id"
:size="24"
/>
<a-typography-text>{{ record.assignee.fullName }}</a-typography-text>
</a-space>
</template>
<template v-else-if="column.key === 'اولویت'">
<a-tag :color="priorityColor((record as RoutineTaskDto).priority)" :bordered="false">
{{ PRIORITY_LABELS[(record as RoutineTaskDto).priority] }}
</a-tag>
</template>
<template v-else-if="column.key === 'پرونده'">
<a-flex vertical align="start" :gap="2" @click.stop>
<RouterLink
v-for="ent in (record as RoutineTaskDto).entities"
:key="ent.id"
:to="entityRoute(ent)"
custom
v-slot="{ href, navigate }"
>
<a-typography-link :href="href" @click="navigate">
{{ ENTITY_TYPE_LABELS[ent.type] }}: {{ ent.label }}
</a-typography-link>
</RouterLink>
<a-typography-text v-if="!record.entities.length" type="secondary">
—
</a-typography-text>
</a-flex>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-space :size="8" wrap @click.stop>
<a-button
type="primary"
:loading="actions.busyId.value === record.id"
@click="actions.toggle(record as RoutineTaskDto)"
<UiEmptyState
v-else-if="!items.length"
icon="check"
title="همه چیز به‌روز است"
description="هیچ کاری از مهلتش عقب نیفتاده."
/>
<template v-else>
<!-- دسکتاپ: جدول -->
<div class="crm-table-container desk">
<table class="crm-table">
<thead>
<tr>
<th>کار</th>
<th>مهلت</th>
<th>تأخیر</th>
<th v-if="showAssignee">مسئول</th>
<th>اولویت</th>
<th>پرونده</th>
<th />
</tr>
</thead>
<tbody>
<tr v-for="t in items" :key="t.id" class="clickable" @click="shell.openTask(t.id)">
<td class="title-cell">
<strong>{{ t.title }}</strong>
<small v-if="t.category" class="cat"><i :style="{ background: t.category.color }" />{{ t.category.name }}</small>
</td>
<td class="nowrap">
{{ formatDayNumeric(t.scheduledFor) }}
<small v-if="hasExplicitTime(t)" class="muted">· {{ formatTime(t.dueAt) }}</small>
</td>
<td class="nowrap late">{{ formatDelay(t.dueAt) }}</td>
<td v-if="showAssignee">
<span v-if="t.assignee" class="who-cell">
<UserAvatar :name="t.assignee.fullName" :user-id="t.assignee.id" :size="24" />
{{ t.assignee.fullName }}
</span>
</td>
<td>
<UiBadge size="sm" :variant="PRIORITY_VARIANTS[t.priority]">{{ activityPriorities.labelOf(t.priority) }}</UiBadge>
</td>
<td>
<RouterLink
v-for="ent in t.entities"
:key="ent.id"
:to="entityRoute(ent)"
class="ent"
@click.stop
>
{{ ENTITY_TYPE_LABELS[ent.type] }}: {{ ent.label }}
</RouterLink>
<span v-if="!t.entities.length" class="muted">—</span>
</td>
<td class="actions-cell" @click.stop>
<div class="crm-table-actions">
<UiButton
size="sm"
variant="success"
:loading="actions.busyId.value === t.id"
@click="actions.toggle(t)"
>
انجام شد
</a-button>
@@ -16,12 +16,16 @@ import {
Space as ASpace,
Statistic as AStatistic,
Table as ATable,
Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem,
List as AList,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { api } from '@/lib/api';
import type { FinancialAccountDto, FinancialMovementDto } from '@mento/shared';
import MoneyInput from '@/components/MoneyInput.vue';
import { toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
import { useTreasuryPageChrome } from './treasuryPageChrome';
@@ -37,6 +41,8 @@ const reason = ref('');
const note = ref('');
const busy = ref(false);
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const columns: TableColumnsType<FinancialMovementDto> = [
{
title: 'تاریخ',
@@ -168,7 +174,7 @@ onUnmounted(() => {
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="8">
<a-form-item label="موجودی واقعی">
<MoneyInput v-model="stated" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="stated" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
@@ -190,8 +196,29 @@ onUnmounted(() => {
<a-divider orientation="right">گردش حساب</a-divider>
<a-empty v-if="!items.length" description="گردشی ثبت نشده است." />
<a-list v-else-if="isMobile" :data-source="items">
<template #renderItem="{ item }">
<a-list-item>
<a-card :title="formatJalaliNumeric(new Date(item.occurredAt))" style="width: 100%">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="شرح">{{ item.memo || '—' }}</a-descriptions-item>
<a-descriptions-item label="نوع">{{ item.kindLabel }}</a-descriptions-item>
<a-descriptions-item label="ورودی">
{{ item.direction === 'in' ? toman(item.amount) : '—' }}
</a-descriptions-item>
<a-descriptions-item label="خروجی">
{{ item.direction === 'out' ? toman(item.amount) : '—' }}
</a-descriptions-item>
<a-descriptions-item label="مانده">
{{ item.balanceAfter ? toman(item.balanceAfter) : '—' }}
</a-descriptions-item>
</a-descriptions>
</a-card>
</a-list-item>
</template>
</a-list>
<a-table
v-else
v-else-if="items.length"
:columns="columns"
:data-source="items"
:pagination="false"
@@ -27,9 +27,11 @@ import type { FinancialAccountDto, FinancialAccountType, OrgUserDto } from '@men
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
@@ -315,7 +317,7 @@ onMounted(() => {
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="موجودی اولیه" name="openingBalance">
<MoneyInput v-model="form.openingBalance" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.openingBalance" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
@@ -400,7 +402,7 @@ onMounted(() => {
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput v-model="transfer.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="transfer.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
@@ -420,7 +422,7 @@ onMounted(() => {
<a-divider orientation="right">فهرست حساب‌ها</a-divider>
<a-empty v-if="!accounts.length" description="حسابی ثبت نشده است." />
<a-list v-else item-layout="horizontal" :data-source="accounts">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="accounts">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -23,8 +23,10 @@ import {
} from 'ant-design-vue';
import { api } from '@/lib/api';
import type { FinancialCategoryDto } from '@mento/shared';
import { useTreasuryMobile } from './useTreasuryMobile';
const { Text: ATypographyText } = Typography;
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
@@ -151,7 +153,7 @@ onMounted(() => {
<a-divider orientation="right">درآمد</a-divider>
<a-empty v-if="!incomeRows.length" description="دسته درآمدی نیست." />
<a-list v-else item-layout="horizontal" :data-source="incomeRows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="incomeRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -176,7 +178,7 @@ onMounted(() => {
<a-divider orientation="right">هزینه</a-divider>
<a-empty v-if="!expenseRows.length" description="دسته هزینه‌ای نیست." />
<a-list v-else item-layout="horizontal" :data-source="expenseRows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="expenseRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -158,7 +158,7 @@ onMounted(() => {
<UiCard title="سند جدید">
<div class="grid">
<UiField label="عنوان"><UiInput v-model="form.title" /></UiField>
<UiField label="مبلغ کل"><MoneyInput v-model="form.amount" :decimals="0" /></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>
@@ -166,7 +166,7 @@ onMounted(() => {
</select>
</UiField>
<UiField label="طرف حساب"><UiInput v-model="form.partyName" /></UiField>
<UiField :label="settleLabel"><MoneyInput v-model="form.settleAmount" :decimals="0" /></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>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import {
Alert as AAlert,
@@ -14,11 +14,13 @@ import {
Input as AInput,
List as AList,
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
Typography,
message,
} from 'ant-design-vue';
import { api } from '@/lib/api';
import { formatLocalDateInput } from '@/lib/jalali';
import type {
FinancialAccountDto,
FinancialCategoryDto,
@@ -26,11 +28,13 @@ import type {
FinancialPartyKind,
TreasuryPartyBalanceDto,
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
import { toman } from './treasury-format';
import { partyNetPosition, toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
@@ -38,9 +42,11 @@ const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
const isMobile = useTreasuryMobile();
const kind = 'expense' as const;
const rows = ref<FinancialDocumentDto[]>([]);
const balances = ref<TreasuryPartyBalanceDto[]>([]);
const receivableBalances = ref<TreasuryPartyBalanceDto[]>([]);
const categories = ref<FinancialCategoryDto[]>([]);
const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
@@ -57,10 +63,17 @@ const form = ref({
settleAmount: '',
method: 'transfer',
notes: '',
bookedAt: formatLocalDateInput(new Date()),
});
const settleMirror = useSettleDefault(form);
const settleLabel = 'مبلغ پرداخت‌شده';
const entryMode = ref<'settlement' | 'accrual'>('settlement');
const isSettlement = computed(() => entryMode.value === 'settlement');
const entryOptions = [
{ label: 'پرداخت', value: 'settlement' },
{ label: 'هزینه', value: 'accrual' },
];
const statusLabel: Record<string, string> = {
open: 'پرداخت‌نشده',
partial: 'جزئی',
@@ -94,17 +107,32 @@ function docLine(item: FinancialDocumentDto) {
}
async function load() {
const [docs, cats, acc, bals] = await Promise.all([
const [docs, cats, acc, bals, receivables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }),
api.get<FinancialAccountDto[]>('/treasury/accounts'),
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
return { data: [] as FinancialCategoryDto[] };
}
throw e;
}),
api.get<FinancialAccountDto[]>('/treasury/accounts').catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
return { data: [] as FinancialAccountDto[] };
}
throw e;
}),
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
throw e;
}),
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'income' } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
throw e;
}),
]);
rows.value = docs.data;
balances.value = bals.data;
receivableBalances.value = receivables.data;
categories.value = cats.data.filter((row) => row.isActive);
accounts.value = acc.data.filter((row) => row.isActive);
}
@@ -118,33 +146,61 @@ async function createDoc() {
error.value = '';
ok.value = '';
try {
const amount = parseMoneyNumber(String(form.value.amount ?? ''), 0);
const settlement = isSettlement.value;
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
const amount = settlement
? settleAmount
: parseMoneyNumber(String(form.value.amount ?? ''), 0);
if (amount == null || amount <= 0) {
error.value = 'مبلغ کل معتبر نیست.';
error.value = settlement ? 'مبلغ پرداخت‌شده معتبر نیست.' : 'مبلغ کل معتبر نیست.';
return;
}
if (!form.value.partyKind || (form.value.partyKind !== 'other' && !form.value.partyId)) {
error.value = 'طرف حساب را انتخاب کنید.';
return;
}
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
if (form.value.partyKind === 'other' && settleAmount !== amount) {
if (settlement && form.value.partyKind === 'other') {
error.value = 'برای پرداخت، طرف حساب واقعی لازم است.';
return;
}
if (!settlement && form.value.partyKind === 'other' && settleAmount !== amount) {
error.value = 'برای سایر، مبلغ پرداخت‌شده باید با مبلغ کل یکی باشد.';
return;
}
if (!settlement && settleAmount > amount) {
error.value = 'مبلغ پرداخت‌شده از مبلغ کل بیشتر است.';
return;
}
if ((settlement || settleAmount > 0) && !form.value.accountId) {
error.value = 'حساب را انتخاب کنید.';
return;
}
const partyKey =
form.value.partyKind && form.value.partyKind !== 'other' && form.value.partyId
? `${form.value.partyKind}:${form.value.partyId}`
: '';
const payable = partyKey
? Number(balances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
: 0;
const receivable = partyKey
? Number(receivableBalances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
: 0;
const collectsBalance = settlement && (payable > 0 || receivable > 0);
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
kind,
settlement,
title: form.value.title,
amount,
categoryId: form.value.categoryId || null,
categoryId: settlement ? null : form.value.categoryId || null,
partyKind: form.value.partyKind,
personId: form.value.partyKind === 'person' ? form.value.partyId : null,
companyId: form.value.partyKind === 'company' ? form.value.partyId : null,
userId: form.value.partyKind === 'user' ? form.value.partyId : null,
accountId: form.value.accountId || null,
settleAmount,
settleAmount: settlement ? amount : settleAmount,
method: form.value.method,
notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined,
});
settleMirror.reset();
form.value = {
@@ -157,10 +213,13 @@ async function createDoc() {
settleAmount: '',
method: 'transfer',
notes: '',
bookedAt: formatLocalDateInput(new Date()),
};
ok.value = data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
ok.value = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
await load();
} catch (e) {
error.value = apiMessage(e);
@@ -169,6 +228,57 @@ async function createDoc() {
}
}
const partyRules = [
{
validator: async () => {
if (!form.value.partyKind) throw new Error('طرف حساب الزامی است');
if (isSettlement.value && form.value.partyKind === 'other') {
throw new Error('برای پرداخت، طرف حساب واقعی لازم است');
}
if (form.value.partyKind !== 'other' && !form.value.partyId) {
throw new Error('طرف حساب را انتخاب کنید');
}
},
},
];
const accountRules = [
{
validator: async () => {
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
if ((isSettlement.value || settled > 0) && !form.value.accountId) {
throw new Error('حساب را انتخاب کنید');
}
},
},
];
const remainingAmount = computed(() => {
const total = parseMoneyNumber(String(form.value.amount ?? ''), 0) ?? 0;
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
return Math.max(0, total - settled);
});
watch(entryMode, () => {
settleMirror.reset();
form.value.amount = '';
form.value.settleAmount = '';
if (isSettlement.value && form.value.partyKind === 'other') {
form.value.partyKind = undefined;
form.value.partyId = undefined;
}
});
const partyPosition = computed(() => {
const partyKind = form.value.partyKind;
const id = form.value.partyId;
if (!partyKind || partyKind === 'other' || !id) return null;
const key = `${partyKind}:${id}`;
const receivable = Number(receivableBalances.value.find((item) => item.key === key)?.remaining || 0);
const payable = Number(balances.value.find((item) => item.key === key)?.remaining || 0);
return partyNetPosition(receivable, payable);
});
async function voidDoc(id: string) {
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
try {
@@ -192,7 +302,10 @@ onMounted(() => {
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false">
<a-divider orientation="right">سند جدید</a-divider>
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex>
<a-form
layout="vertical"
:model="form"
@@ -200,6 +313,23 @@ onMounted(() => {
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
@@ -209,21 +339,35 @@ onMounted(() => {
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput v-model="form.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item :label="settleLabel" name="settleAmount">
<MoneyInput v-model="form.settleAmount" :decimals="0" :disabled="form.partyKind === 'other'" />
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label"
v-model:value="form.categoryId"
@@ -238,12 +382,7 @@ onMounted(() => {
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="طرف حساب" name="partyKind">
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="حساب" name="accountId">
<a-form-item label="حساب" name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
@@ -265,8 +404,18 @@ onMounted(() => {
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :span="24">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
</a-row>
<a-button type="primary" html-type="submit" :loading="saving">ثبت</a-button>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-form>
<a-divider orientation="right">مانده پرداختنی</a-divider>
@@ -290,10 +439,10 @@ onMounted(() => {
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-list v-else item-layout="horizontal" :data-source="rows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<template v-if="!isMobile" #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
@@ -304,7 +453,29 @@ onMounted(() => {
ابطال
</a-button>
</template>
<a-list-item-meta>
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
</a-typography-text>
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
>
ابطال
</a-button>
</a-flex>
</a-flex>
<a-list-item-meta v-else>
<template #title>{{ item.title }}</template>
<template #description>{{ docLine(item) }}</template>
</a-list-item-meta>
+92 -393
View File
@@ -48,6 +48,7 @@ import { api } from '@/lib/api';
import axios from 'axios';
import type { TreasuryDashboardDto } from '@mento/shared';
import { toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
use([CanvasRenderer, BarChart, PieChart, GridComponent, TooltipComponent, LegendComponent]);
@@ -60,227 +61,24 @@ type ChartOption = ComposeOption<
>;
const { Text: ATypographyText } = Typography;
const { token } = theme.useToken();
function num(value: string | number | null | undefined) {
const n = Number(value ?? 0);
return Number.isFinite(n) ? n : 0;
}
type MetricKey = keyof Pick<
TreasuryDashboardDto,
| 'bookedIncome'
| 'actualReceipts'
| 'bookedExpense'
| 'actualPayments'
| 'operatingProfit'
| 'receivables'
| 'payables'
| 'totalBalance'
>;
type MetricCard = {
key: MetricKey;
label: string;
hint: string;
icon: Component;
};
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const data = ref<TreasuryDashboardDto | null>(null);
const error = ref('');
const loading = ref(true);
const heroCards: MetricCard[] = [
{
key: 'totalBalance',
label: 'موجودی حساب‌ها',
hint: 'صندوق و بانک',
icon: WalletOutlined,
},
{
key: 'operatingProfit',
label: 'سود یا زیان عملیاتی',
hint: 'درآمد ثبت‌شده − هزینه ثبت‌شده',
icon: RiseOutlined,
},
{
key: 'receivables',
label: 'مطالبات وصول‌نشده',
hint: 'درآمد بدون دریافت کامل',
icon: CalendarOutlined,
},
];
const secondaryCards: MetricCard[] = [
{
key: 'bookedIncome',
label: 'درآمد ثبت‌شده',
hint: 'تعهدی',
icon: ArrowDownOutlined,
},
{
key: 'actualReceipts',
label: 'دریافت واقعی',
hint: 'ورود به حساب',
icon: BankOutlined,
},
{
key: 'bookedExpense',
label: 'هزینه ثبت‌شده',
hint: 'تعهدی',
icon: FallOutlined,
},
{
key: 'actualPayments',
label: 'پرداخت واقعی',
hint: 'خروج از حساب',
icon: ArrowUpOutlined,
},
{
key: 'payables',
label: 'تعهدات پرداخت',
hint: 'هزینه بدون پرداخت کامل',
icon: AccountBookOutlined,
},
];
const softCardStyle = computed(() => ({
background: token.value.colorPrimaryBg,
borderRadius: `${token.value.borderRadiusLG}px`,
boxShadow: token.value.boxShadow,
height: '100%',
}));
/** کارت سفید بدون بردر (KPI فرعی و چارت‌ها) */
const secondaryCardStyle = computed(() => ({
background: token.value.colorBgContainer,
borderRadius: `${token.value.borderRadiusLG}px`,
boxShadow: token.value.boxShadow,
height: '100%',
}));
/** Soft teal family — primary + muted companions (not loud rainbow) */
const chartColors = computed(() => {
const primary = token.value.colorPrimary;
return {
primary,
primarySoft: token.value.colorPrimaryBg,
muted: token.value.colorTextQuaternary || '#a7f3d0',
ink: token.value.colorTextSecondary,
axis: token.value.colorBorderSecondary,
tooltipBg: token.value.colorBgElevated,
font: token.value.fontFamily,
};
});
const flowChartOption = computed<ChartOption>(() => {
if (!data.value) return {};
const c = chartColors.value;
const categories = ['درآمد تعهدی', 'دریافت واقعی', 'هزینه تعهدی', 'پرداخت واقعی'];
const values = [
num(data.value.bookedIncome),
num(data.value.actualReceipts),
num(data.value.bookedExpense),
num(data.value.actualPayments),
];
return {
color: [c.primary, '#34d399', '#6ee7b7', '#a7f3d0'],
textStyle: { fontFamily: c.font, color: c.ink },
tooltip: {
trigger: 'axis',
backgroundColor: c.tooltipBg,
borderColor: c.axis,
textStyle: { fontFamily: c.font, color: c.ink },
valueFormatter: (v) => toman(Number(v)),
},
grid: { left: 8, right: 12, top: 24, bottom: 8, containLabel: true },
xAxis: {
type: 'category',
data: categories,
axisLine: { lineStyle: { color: c.axis } },
axisTick: { show: false },
axisLabel: {
fontFamily: c.font,
color: c.ink,
interval: 0,
rotate: 0,
fontSize: 11,
},
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: c.axis, type: 'dashed' } },
axisLabel: {
fontFamily: c.font,
color: c.ink,
formatter: (v: number) =>
new Intl.NumberFormat('fa-IR', { notation: 'compact' }).format(v),
},
},
series: [
{
type: 'bar',
data: values.map((value, index) => ({
value,
itemStyle: {
color: [c.primary, '#34d399', '#6ee7b7', '#a7f3d0'][index],
borderRadius: [8, 8, 0, 0],
},
})),
barMaxWidth: 36,
},
],
};
});
const mixChartOption = computed<ChartOption>(() => {
if (!data.value) return {};
const c = chartColors.value;
const slices = [
{ name: 'موجودی حساب‌ها', value: Math.max(0, num(data.value.totalBalance)) },
{ name: 'مطالبات', value: Math.max(0, num(data.value.receivables)) },
{ name: 'تعهدات', value: Math.max(0, num(data.value.payables)) },
];
const hasValue = slices.some((s) => s.value > 0);
return {
color: [c.primary, '#34d399', '#a7f3d0'],
textStyle: { fontFamily: c.font, color: c.ink },
tooltip: {
trigger: 'item',
backgroundColor: c.tooltipBg,
borderColor: c.axis,
textStyle: { fontFamily: c.font, color: c.ink },
formatter: (params: unknown) => {
const p = params as { name?: string; value?: number; percent?: number };
return `${p.name}<br/>${toman(p.value)} (${p.percent ?? 0}٪)`;
},
},
legend: {
bottom: 0,
icon: 'circle',
itemWidth: 8,
itemHeight: 8,
textStyle: { fontFamily: c.font, color: c.ink, fontSize: 12 },
},
series: [
{
type: 'pie',
radius: ['52%', '72%'],
center: ['50%', '46%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 8,
borderColor: token.value.colorBgContainer,
borderWidth: 3,
},
label: { show: false },
data: hasValue
? slices
: [{ name: 'بدون داده', value: 1, itemStyle: { color: c.primarySoft } }],
},
],
};
});
const cards = [
{ key: 'bookedIncome', label: 'درآمد ثبت‌شده', hint: 'تعهدی' },
{ key: 'actualReceipts', label: 'دریافت واقعی', hint: 'ورود به حساب' },
{ key: 'bookedExpense', label: 'هزینه ثبت‌شده', hint: 'تعهدی' },
{ key: 'actualPayments', label: 'پرداخت واقعی', hint: 'خروج از حساب' },
{ key: 'operatingProfit', label: 'سود یا زیان عملیاتی', hint: 'درآمد و فروش فاکتور − هزینه' },
{ key: 'receivables', label: 'مطالبات وصول‌نشده', hint: 'اسناد باز و مانده فاکتور' },
{ key: 'payables', label: 'تعهدات پرداخت', hint: 'هزینه باز، حقوق و برگشتی' },
{ key: 'totalBalance', label: 'موجودی حساب‌ها', hint: 'صندوق و بانک' },
] as const;
onMounted(async () => {
loading.value = true;
@@ -407,185 +205,86 @@ onMounted(async () => {
</a-col>
</a-row>
<template v-if="data">
<a-row :gutter="[token.marginSM, token.marginSM]" :style="{ marginTop: `${token.margin}px` }">
<a-col :xs="24" :lg="14">
<CrmSkeletonCard :rows="6" :min-height="320">
<a-card
:bordered="false"
:style="secondaryCardStyle"
>
<a-typography-text strong>جریان تعهدی و نقدی</a-typography-text>
<a-typography-text
type="secondary"
:style="{ display: 'block', marginBottom: `${token.marginSM}px`, fontSize: '12px' }"
>
مقایسه درآمد/هزینه ثبت‌شده با دریافت و پرداخت واقعی
</a-typography-text>
<VChart
:option="flowChartOption"
autoresize
:style="{ height: '260px', width: '100%' }"
/>
</a-card>
</CrmSkeletonCard>
<a-card :bordered="false">
<a-row :gutter="[16, 16]">
<a-col :xs="24" :lg="12">
<a-divider orientation="right">اقساط نزدیک یا معوق</a-divider>
<a-empty
v-if="!data.upcomingInstallments.length"
description="قسط بازی نیست."
/>
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.upcomingInstallments"
>
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #title>قسط {{ item.position }}</template>
<template #description>
{{ item.status === 'overdue' ? 'معوق' : 'باز' }} · مانده {{ toman(item.remaining) }}
</template>
</a-list-item-meta>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template>
</a-list-item>
</template>
</a-list>
</a-col>
<a-col :xs="24" :lg="10">
<CrmSkeletonCard :rows="6" :min-height="320">
<a-card
:bordered="false"
:style="secondaryCardStyle"
>
<a-typography-text strong>ترکیب وضعیت مالی</a-typography-text>
<a-typography-text
type="secondary"
:style="{ display: 'block', marginBottom: `${token.marginSM}px`, fontSize: '12px' }"
>
سهم موجودی، مطالبات و تعهدات
</a-typography-text>
<VChart
:option="mixChartOption"
autoresize
:style="{ height: '260px', width: '100%' }"
/>
</a-card>
</CrmSkeletonCard>
<a-col :xs="24" :lg="12">
<a-divider orientation="right">پرداخت‌های آینده</a-divider>
<a-empty
v-if="!data.upcomingPayables.length"
description="تعهد پرداخت بازی نیست."
/>
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.upcomingPayables"
>
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #title>{{ item.title }}</template>
<template #description>مانده {{ toman(item.remaining) }}</template>
</a-list-item-meta>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template>
</a-list-item>
</template>
</a-list>
</a-col>
</a-row>
<a-row :gutter="[token.marginSM, token.marginSM]" :style="{ marginTop: `${token.margin}px` }">
<a-col :xs="24" :lg="8">
<CrmSkeletonList :rows="4" :avatar="false">
<a-card
:bordered="false"
title="اقساط نزدیک یا معوق"
:style="secondaryCardStyle"
:body-style="{ paddingBlock: `${token.paddingSM}px` }"
>
<a-empty
v-if="!data.upcomingInstallments.length"
description="قسط بازی نیست."
:image-style="{ height: '48px' }"
/>
<a-flex v-else vertical :gap="token.marginXS">
<a-flex
v-for="item in data.upcomingInstallments"
:key="item.id"
justify="space-between"
align="flex-start"
:gap="8"
>
<div :style="{ minWidth: 0 }">
<a-typography-text>قسط {{ item.position }}</a-typography-text>
<div>
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
{{ item.status === 'overdue' ? 'معوق' : item.status === 'partial' ? 'جزئی' : 'باز' }}
· مانده {{ toman(item.remaining) }}
</a-typography-text>
</div>
</div>
<a-typography-text strong :style="{ color: token.colorPrimary, whiteSpace: 'nowrap' }">
{{ toman(item.amount) }}
</a-typography-text>
</a-flex>
</a-flex>
</a-card>
</CrmSkeletonList>
</a-col>
<a-col :xs="24" :lg="8">
<CrmSkeletonList :rows="4" :avatar="false">
<a-card
:bordered="false"
title="پرداخت‌های آینده"
:style="secondaryCardStyle"
:body-style="{ paddingBlock: `${token.paddingSM}px` }"
>
<a-empty
v-if="!data.upcomingPayables.length"
description="تعهد پرداخت بازی نیست."
:image-style="{ height: '48px' }"
/>
<a-flex v-else vertical :gap="token.marginXS">
<a-flex
v-for="item in data.upcomingPayables"
:key="item.id"
justify="space-between"
align="flex-start"
:gap="8"
>
<div :style="{ minWidth: 0 }">
<a-typography-text>{{ item.title }}</a-typography-text>
<div>
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
مانده {{ toman(item.remaining) }}
</a-typography-text>
</div>
</div>
<a-typography-text strong :style="{ color: token.colorPrimary, whiteSpace: 'nowrap' }">
{{ toman(item.amount) }}
</a-typography-text>
</a-flex>
</a-flex>
</a-card>
</CrmSkeletonList>
</a-col>
<a-col :xs="24" :lg="8">
<CrmSkeletonList :rows="4" :avatar="false">
<a-card
:bordered="false"
title="آخرین اسناد"
:style="secondaryCardStyle"
:body-style="{ paddingBlock: `${token.paddingSM}px` }"
>
<a-empty
v-if="!data.recent.length"
description="هنوز سندی ثبت نشده است."
:image-style="{ height: '48px' }"
/>
<a-flex v-else vertical :gap="token.marginXS">
<a-flex
v-for="item in data.recent"
:key="item.id"
justify="space-between"
align="flex-start"
:gap="8"
>
<div :style="{ minWidth: 0 }">
<a-typography-text>{{ item.title }}</a-typography-text>
<div>
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
{{ item.kind === 'income' ? 'درآمد' : 'هزینه' }} · {{ item.status }}
</a-typography-text>
</div>
</div>
<a-typography-text strong :style="{ color: token.colorPrimary, whiteSpace: 'nowrap' }">
{{ toman(item.amount) }}
</a-typography-text>
</a-flex>
</a-flex>
</a-card>
</CrmSkeletonList>
</a-col>
</a-row>
</template>
<template v-else-if="loading">
<a-row :gutter="[token.marginSM, token.marginSM]" :style="{ marginTop: `${token.margin}px` }">
<a-col :xs="24" :lg="14">
<CrmSkeletonCard :rows="6" :min-height="320" />
</a-col>
<a-col :xs="24" :lg="10">
<CrmSkeletonCard :rows="6" :min-height="320" />
</a-col>
</a-row>
<a-row :gutter="[token.marginSM, token.marginSM]" :style="{ marginTop: `${token.margin}px` }">
<a-col v-for="i in 3" :key="i" :xs="24" :lg="8">
<CrmSkeletonList :rows="4" :avatar="false" />
</a-col>
</a-row>
</template>
</CrmSkeleton>
</a-flex>
</div>
<a-divider orientation="right">آخرین اسناد</a-divider>
<a-empty
v-if="!data.recent.length"
description="هنوز سندی ثبت نشده است."
/>
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.recent"
>
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #title>{{ item.title }}</template>
<template #description>
{{ item.kind === 'income' ? 'درآمد' : 'هزینه' }} · {{ item.status }}
</template>
</a-list-item-meta>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template>
</a-list-item>
</template>
</a-list>
</a-card>
</template>
</a-flex>
</template>
@@ -1,9 +1,8 @@
<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import {
Alert as AAlert,
Avatar as AAvatar,
Button as AButton,
Card as ACard,
Col as ACol,
@@ -18,23 +17,9 @@ import {
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
Space as ASpace,
Textarea as ATextarea,
Typography,
message,
theme,
} from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import {
ArrowDownOutlined,
BankOutlined,
CheckOutlined,
ClockCircleOutlined,
CreditCardOutlined,
FileTextOutlined,
InfoCircleOutlined,
TagOutlined,
} from '@/icons/ant-bridge';
import { api } from '@/lib/api';
import { formatLocalDateInput } from '@/lib/jalali';
import type {
@@ -42,7 +27,6 @@ import type {
FinancialCategoryDto,
FinancialDocumentDto,
FinancialPartyKind,
TreasuryDashboardDto,
TreasuryPartyBalanceDto,
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
@@ -50,29 +34,26 @@ import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
import { toman } from './treasury-format';
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 { token } = theme.useToken();
const screens = Grid.useBreakpoint();
const isMobile = computed(() => !screens.value.md);
const kind = 'income' as const;
const rows = ref<FinancialDocumentDto[]>([]);
const balances = ref<TreasuryPartyBalanceDto[]>([]);
const payableBalances = ref<TreasuryPartyBalanceDto[]>([]);
const categories = ref<FinancialCategoryDto[]>([]);
const accounts = ref<FinancialAccountDto[]>([]);
const dashboard = ref<TreasuryDashboardDto | null>(null);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const q = ref('');
const formTab = ref<'main' | 'extra'>('main');
const mobileFormRef = ref<FormInstance>();
function emptyForm() {
return {
@@ -93,6 +74,12 @@ const form = ref(emptyForm());
const settleMirror = useSettleDefault(form);
const settleLabel = 'مبلغ دریافت‌شده';
const entryMode = ref<'settlement' | 'accrual'>('settlement');
const isSettlement = computed(() => entryMode.value === 'settlement');
const entryOptions = [
{ label: 'دریافت', value: 'settlement' },
{ label: 'درآمد', value: 'accrual' },
];
const statusLabel: Record<string, string> = {
open: 'دریافت‌نشده',
partial: 'جزئی',
@@ -108,19 +95,51 @@ const methodOptions = [
{ value: 'other', label: 'سایر' },
];
const formTabOptions = [
const partyRules = [
{
value: 'main',
payload: 'main',
label: h('span', {}, [h(InfoCircleOutlined), ' اطلاعات اصلی']),
},
{
value: 'extra',
payload: 'extra',
label: h('span', {}, [h(FileTextOutlined), ' جزئیات تکمیلی']),
validator: async () => {
if (!form.value.partyKind) throw new Error('طرف حساب الزامی است');
if (isSettlement.value && form.value.partyKind === 'other') {
throw new Error('برای دریافت، طرف حساب واقعی لازم است');
}
if (form.value.partyKind !== 'other' && !form.value.partyId) {
throw new Error('طرف حساب را انتخاب کنید');
}
},
},
];
const accountRules = [
{
validator: async () => {
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
if ((isSettlement.value || settled > 0) && !form.value.accountId) {
throw new Error('حساب را انتخاب کنید');
}
},
},
];
const partyPosition = computed(() => {
const partyKind = form.value.partyKind;
const id = form.value.partyId;
if (!partyKind || partyKind === 'other' || !id) return null;
const key = `${partyKind}:${id}`;
const receivable = Number(balances.value.find((item) => item.key === key)?.remaining || 0);
const payable = Number(payableBalances.value.find((item) => item.key === key)?.remaining || 0);
return partyNetPosition(receivable, payable);
});
watch(entryMode, () => {
settleMirror.reset();
form.value.amount = '';
form.value.settleAmount = '';
if (isSettlement.value && form.value.partyKind === 'other') {
form.value.partyKind = undefined;
form.value.partyId = undefined;
}
});
const remainingAmount = computed(() => {
const total = parseMoneyNumber(String(form.value.amount ?? ''), 0) ?? 0;
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
@@ -149,27 +168,39 @@ function docLine(item: FinancialDocumentDto) {
}
async function load() {
const [docs, cats, acc, dash, bals] = await Promise.all([
const [docs, cats, acc, bals, payables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }),
api.get<FinancialAccountDto[]>('/treasury/accounts'),
api.get<TreasuryDashboardDto>('/treasury/dashboard').catch(() => null),
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
return { data: [] as FinancialCategoryDto[] };
}
throw e;
}),
api.get<FinancialAccountDto[]>('/treasury/accounts').catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
return { data: [] as FinancialAccountDto[] };
}
throw e;
}),
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
throw e;
}),
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'expense' } }).catch((e: unknown) => {
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
throw e;
}),
]);
rows.value = docs.data;
balances.value = bals.data;
payableBalances.value = payables.data;
categories.value = cats.data.filter((row) => row.isActive);
accounts.value = acc.data.filter((row) => row.isActive);
if (dash) dashboard.value = dash.data;
}
function resetForm() {
settleMirror.reset();
form.value = emptyForm();
formTab.value = 'main';
error.value = '';
ok.value = '';
}
@@ -179,39 +210,68 @@ async function createDoc() {
error.value = '';
ok.value = '';
try {
const amount = parseMoneyNumber(String(form.value.amount ?? ''), 0);
const settlement = isSettlement.value;
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
const amount = settlement
? settleAmount
: parseMoneyNumber(String(form.value.amount ?? ''), 0);
if (amount == null || amount <= 0) {
error.value = 'مبلغ کل معتبر نیست.';
error.value = settlement ? 'مبلغ دریافت‌شده معتبر نیست.' : 'مبلغ کل معتبر نیست.';
return;
}
if (!form.value.partyKind || (form.value.partyKind !== 'other' && !form.value.partyId)) {
error.value = 'طرف حساب را انتخاب کنید.';
return;
}
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
if (form.value.partyKind === 'other' && settleAmount !== amount) {
if (settlement && form.value.partyKind === 'other') {
error.value = 'برای دریافت، طرف حساب واقعی لازم است.';
return;
}
if (!settlement && form.value.partyKind === 'other' && settleAmount !== amount) {
error.value = 'برای سایر، مبلغ دریافت‌شده باید با مبلغ کل یکی باشد.';
return;
}
if (!settlement && settleAmount > amount) {
error.value = 'مبلغ دریافت‌شده از مبلغ کل بیشتر است.';
return;
}
if ((settlement || settleAmount > 0) && !form.value.accountId) {
error.value = 'حساب را انتخاب کنید.';
return;
}
const partyKey =
form.value.partyKind && form.value.partyKind !== 'other' && form.value.partyId
? `${form.value.partyKind}:${form.value.partyId}`
: '';
const receivable = partyKey
? Number(balances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
: 0;
const payable = partyKey
? Number(payableBalances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
: 0;
const collectsBalance = settlement && (receivable > 0 || payable > 0);
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
kind,
settlement,
title: form.value.title,
amount,
categoryId: form.value.categoryId || null,
categoryId: settlement ? null : form.value.categoryId || null,
partyKind: form.value.partyKind,
personId: form.value.partyKind === 'person' ? form.value.partyId : null,
companyId: form.value.partyKind === 'company' ? form.value.partyId : null,
userId: form.value.partyKind === 'user' ? form.value.partyId : null,
accountId: form.value.accountId || null,
settleAmount,
settleAmount: settlement ? amount : settleAmount,
method: form.value.method,
notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined,
});
resetForm();
ok.value = data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
ok.value = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
await load();
} catch (e) {
error.value = apiMessage(e);
@@ -220,16 +280,6 @@ async function createDoc() {
}
}
async function submitMobileForm() {
try {
await mobileFormRef.value?.validate();
} catch {
formTab.value = 'main';
return;
}
await createDoc();
}
async function voidDoc(id: string) {
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
try {
@@ -248,340 +298,15 @@ onMounted(() => {
</script>
<template>
<div
:style="
isMobile
? { paddingBottom: 'calc(96px + var(--mobile-tabbar-h, 3.65rem))' }
: undefined
"
>
<!-- ─── Mobile app experience ─── -->
<template v-if="isMobile">
<a-flex vertical :gap="token.margin">
<a-row :gutter="[12, 12]">
<a-col :span="12">
<a-card
:bordered="false"
:body-style="{ padding: `${token.paddingSM}px` }"
:style="{
background: token.colorPrimaryBg,
borderRadius: `${token.borderRadiusLG}px`,
boxShadow: token.boxShadow,
}"
>
<a-flex align="center" justify="space-between" :gap="8">
<div :style="{ minWidth: 0, flex: 1 }">
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
دریافت‌های این ماه
</a-typography-text>
<div>
<a-typography-text
strong
:style="{ fontSize: '15px', color: token.colorPrimary }"
>
{{ toman(dashboard?.actualReceipts) }}
</a-typography-text>
</div>
</div>
<a-avatar
:size="36"
:style="{
background: token.colorPrimary,
color: token.colorTextLightSolid,
flexShrink: 0,
}"
>
<template #icon><ArrowDownOutlined /></template>
</a-avatar>
</a-flex>
</a-card>
</a-col>
<a-col :span="12">
<a-card
:bordered="false"
:body-style="{ padding: `${token.paddingSM}px` }"
:style="{
background: token.colorPrimaryBg,
borderRadius: `${token.borderRadiusLG}px`,
boxShadow: token.boxShadow,
}"
>
<a-flex align="center" justify="space-between" :gap="8">
<div :style="{ minWidth: 0, flex: 1 }">
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
در انتظار دریافت
</a-typography-text>
<div>
<a-typography-text
strong
:style="{ fontSize: '15px', color: token.colorPrimary }"
>
{{ toman(dashboard?.receivables) }}
</a-typography-text>
</div>
</div>
<a-avatar
:size="36"
:style="{
background: token.colorPrimary,
color: token.colorTextLightSolid,
flexShrink: 0,
}"
>
<template #icon><ClockCircleOutlined /></template>
</a-avatar>
</a-flex>
</a-card>
</a-col>
</a-row>
<a-alert v-if="error" type="error" show-icon :message="error" closable @close="error = ''" />
<a-alert v-if="ok" type="success" show-icon :message="ok" closable @close="ok = ''" />
<a-segmented
v-model:value="formTab"
block
:options="formTabOptions"
:style="{ background: token.colorFillTertiary }"
/>
<a-card :bordered="false">
<a-form ref="mobileFormRef" layout="vertical" :model="form" @finish="createDoc">
<div v-show="formTab === 'main'">
<a-form-item
label="عنوان درآمد"
name="title"
:rules="[{ required: true, message: 'عنوان را وارد کنید' }]"
>
<a-input
v-model:value="form.title"
placeholder="مثلاً: دریافت قسط پروژه الف"
>
<template #prefix><FileTextOutlined /></template>
</a-input>
</a-form-item>
<a-row :gutter="[12, 0]">
<a-col :span="12">
<a-form-item label="طرف حساب" name="partyKind">
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item name="method">
<template #label>
<a-space :size="6">
<CreditCardOutlined />
<span>روش دریافت</span>
</a-space>
</template>
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option
v-for="opt in methodOptions"
:key="opt.value"
:value="opt.value"
:label="opt.label"
>
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
</a-row>
<a-form-item name="categoryId">
<template #label>
<a-space :size="6">
<TagOutlined />
<span>دسته‌بندی درآمد</span>
</a-space>
</template>
<a-select show-search option-filter-prop="label"
v-model:value="form.categoryId"
allow-clear
placeholder="انتخاب دسته"
style="width: 100%"
>
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
{{ cat.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-row :gutter="[12, 0]">
<a-col :span="12">
<a-form-item
label="مبلغ کل (تومان)"
name="amount"
:rules="[{ required: true, message: 'مبلغ کل را وارد کنید' }]"
>
<MoneyInput v-model="form.amount" :decimals="0" placeholder="۰" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item
:label="`${settleLabel} (تومان)`"
name="settleAmount"
:rules="[{ required: true, message: 'مبلغ دریافت‌شده را وارد کنید' }]"
>
<MoneyInput
v-model="form.settleAmount"
:decimals="0"
:disabled="form.partyKind === 'other'"
placeholder="۰"
/>
</a-form-item>
</a-col>
</a-row>
<a-flex
align="center"
justify="space-between"
:style="{
background: token.colorSuccessBg,
borderRadius: `${token.borderRadiusLG * 2}px`,
padding: `${token.paddingSM}px ${token.padding}px`,
marginBottom: `${token.margin}px`,
}"
>
<a-space :size="8">
<span
:style="{
width: '8px',
height: '8px',
borderRadius: '50%',
background: token.colorSuccess,
display: 'inline-block',
}"
/>
<a-typography-text type="secondary">مانده قابل دریافت</a-typography-text>
</a-space>
<a-typography-text strong :style="{ color: token.colorSuccess }">
{{ toman(remainingAmount) }}
</a-typography-text>
</a-flex>
<a-row :gutter="[12, 0]">
<a-col :span="12">
<a-form-item label="تاریخ دریافت" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item name="accountId">
<template #label>
<a-space :size="6">
<BankOutlined />
<span>حساب مقصد</span>
</a-space>
</template>
<a-select show-search option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
placeholder="انتخاب حساب"
style="width: 100%"
>
<a-select-option
v-for="account in accounts"
:key="account.id"
:value="account.id"
:label="account.name"
>
{{ account.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
</a-row>
</div>
<div v-show="formTab === 'extra'">
<a-form-item label="توضیحات" name="notes">
<a-textarea
v-model:value="form.notes"
:rows="4"
placeholder="توضیحات اختیاری…"
/>
</a-form-item>
</div>
</a-form>
</a-card>
<a-card :bordered="false">
<a-divider orientation="right">مانده دریافتنی</a-divider>
<TreasuryPartyBalanceTable :rows="balances" settled-label="دریافت‌شده" />
<a-divider orientation="right">فهرست اسناد</a-divider>
<a-form layout="vertical">
<a-form-item label="جستجو">
<a-input
v-model:value="q"
allow-clear
placeholder="عنوان یا شماره پیگیری"
@press-enter="load"
@change="load"
/>
</a-form-item>
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-list v-else item-layout="horizontal" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
>
ابطال
</a-button>
</template>
<a-list-item-meta>
<template #title>{{ item.title }}</template>
<template #description>{{ docLine(item) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</a-flex>
<div
:style="{
position: 'fixed',
left: 0,
right: 0,
bottom: 'var(--mobile-tabbar-h, 3.65rem)',
zIndex: 90,
background: token.colorBgElevated,
borderTop: `1px solid ${token.colorBorderSecondary}`,
padding: `${token.paddingSM}px ${token.padding}px`,
boxShadow: token.boxShadowSecondary,
}"
>
<a-row :gutter="12">
<a-col :span="8">
<a-button block @click="resetForm">انصراف</a-button>
</a-col>
<a-col :span="16">
<a-button type="primary" block :loading="saving" @click="submitMobileForm">
<template #icon><CheckOutlined /></template>
ثبت دریافت
</a-button>
</a-col>
</a-row>
</div>
</template>
<!-- ─── Desktop (unchanged interaction model) ─── -->
<template v-else>
<a-flex vertical :gap="16">
<a-flex vertical :gap="16">
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false">
<a-divider orientation="right">سند جدید</a-divider>
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex>
<a-form
layout="vertical"
:model="form"
@@ -589,6 +314,23 @@ onMounted(() => {
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
@@ -598,21 +340,35 @@ onMounted(() => {
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput v-model="form.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item :label="settleLabel" name="settleAmount">
<MoneyInput v-model="form.settleAmount" :decimals="0" :disabled="form.partyKind === 'other'" />
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label"
v-model:value="form.categoryId"
@@ -627,12 +383,7 @@ onMounted(() => {
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="طرف حساب" name="partyKind">
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="حساب" name="accountId">
<a-form-item label="حساب" name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
@@ -669,13 +420,13 @@ onMounted(() => {
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="16">
<a-col v-if="!isSettlement" :xs="24" :md="16">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
</a-row>
<a-button type="primary" html-type="submit" :loading="saving">ثبت</a-button>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-form>
<a-divider orientation="right">مانده دریافتنی</a-divider>
@@ -698,10 +449,10 @@ onMounted(() => {
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-list v-else item-layout="horizontal" :data-source="rows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<template v-if="!isMobile" #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
@@ -712,7 +463,29 @@ onMounted(() => {
ابطال
</a-button>
</template>
<a-list-item-meta>
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
</a-typography-text>
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
>
ابطال
</a-button>
</a-flex>
</a-flex>
<a-list-item-meta v-else>
<template #title>{{ item.title }}</template>
<template #description>{{ docLine(item) }}</template>
</a-list-item-meta>
@@ -720,8 +493,5 @@ onMounted(() => {
</template>
</a-list>
</a-card>
</a-flex>
</template>
</div>
</a-flex>
</template>
+12 -7
View File
@@ -1,12 +1,14 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
import { RouterView, useRoute } from 'vue-router';
import { Flex as AFlex, Typography, theme } from 'ant-design-vue';
import { Flex as AFlex, Grid, Typography, theme } from 'ant-design-vue';
import TreasuryNav from '@/components/treasury/TreasuryNav.vue';
import { provideTreasuryPageChrome } from './treasuryPageChrome';
const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
const { token } = theme.useToken();
const screens = Grid.useBreakpoint();
const isMobile = computed(() => !screens.value.md);
const route = useRoute();
const chrome = provideTreasuryPageChrome();
@@ -31,16 +33,19 @@ const description = computed(
(typeof route.meta.treasuryDescription === 'string' ? route.meta.treasuryDescription : ''),
);
/** Keep title+subtitle block height stable across tabs (one-line subtitle). */
const headerStyle = computed(() => ({
minHeight: `${token.value.controlHeightLG + token.value.fontSizeLG + token.value.marginXXS}px`,
}));
const headerStyle = computed(() =>
isMobile.value
? undefined
: {
minHeight: `${token.value.controlHeightLG + token.value.fontSizeLG + token.value.marginXXS}px`,
},
);
</script>
<template>
<a-flex vertical :gap="token.margin" :style="{ width: '100%' }">
<a-flex vertical :gap="isMobile ? token.marginSM : token.margin" :style="{ width: '100%' }">
<div :style="headerStyle">
<a-typography-title :level="3" :style="{ margin: 0 }">{{ title }}</a-typography-title>
<a-typography-title :level="isMobile ? 4 : 3" :style="{ margin: 0 }">{{ title }}</a-typography-title>
<a-typography-text
type="secondary"
:ellipsis="description ? { tooltip: description } : false"
File diff suppressed because it is too large Load Diff
@@ -7,12 +7,15 @@ import {
Card as ACard,
Checkbox as ACheckbox,
Col as ACol,
Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
List as AList,
Row as ARow,
Select as ASelect,
Space as ASpace,
@@ -27,6 +30,7 @@ import type { FinancialAccountDto, FinancialReceivableDto } from '@mento/shared'
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
@@ -87,6 +91,9 @@ const installmentColumns: TableColumnsType<InstallmentRow> = [
{ title: '', key: 'actions' },
];
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
function apiMessage(e: unknown) {
if (!axios.isAxiosError(e)) return 'عملیات ناموفق بود.';
const msg = (e.response?.data as { message?: string | string[] })?.message;
@@ -234,12 +241,12 @@ onMounted(() => {
name="totalAmount"
:rules="[{ required: true, message: 'مبلغ کل الزامی است' }]"
>
<MoneyInput v-model="form.totalAmount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.totalAmount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="پیش‌پرداخت" name="prepaidAmount">
<MoneyInput v-model="form.prepaidAmount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.prepaidAmount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
@@ -285,7 +292,7 @@ onMounted(() => {
<a-row v-for="(line, index) in customLines" :key="index" :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item :label="`مبلغ قسط ${index + 1}`">
<MoneyInput v-model="line.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="line.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
@@ -320,7 +327,7 @@ onMounted(() => {
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput v-model="collect.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="collect.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
@@ -365,7 +372,33 @@ onMounted(() => {
</div>
<a-typography-text strong>{{ toman(row.totalAmount) }}</a-typography-text>
</a-flex>
<a-list v-if="isMobile" :data-source="row.installments">
<template #renderItem="{ item }">
<a-list-item>
<a-card :title="`قسط ${item.position}`" style="width: 100%">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="سررسید">
{{ formatJalaliNumeric(new Date(item.dueDate)) }}
</a-descriptions-item>
<a-descriptions-item label="مبلغ">{{ toman(item.amount) }}</a-descriptions-item>
<a-descriptions-item label="مانده">{{ toman(item.remaining) }}</a-descriptions-item>
<a-descriptions-item label="وضعیت">
{{ statusLabel[item.status] ?? item.status }}
</a-descriptions-item>
</a-descriptions>
<a-button
v-if="item.status !== 'settled'"
type="link"
@click="startCollect(row, item)"
>
دریافت
</a-button>
</a-card>
</a-list-item>
</template>
</a-list>
<a-table
v-else
:columns="installmentColumns"
:data-source="row.installments"
:pagination="false"
@@ -22,10 +22,12 @@ import { api } from '@/lib/api';
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
@@ -123,7 +125,7 @@ onMounted(() => {
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput v-model="form.amount" :decimals="0" />
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
@@ -146,7 +148,7 @@ onMounted(() => {
<a-divider orientation="right">فهرست الگوها</a-divider>
<a-empty v-if="!rows.length" description="الگویی ثبت نشده است." />
<a-list v-else item-layout="horizontal" :data-source="rows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -9,6 +9,8 @@ import {
Empty as AEmpty,
Flex as AFlex,
List as AList,
Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem,
Table as ATable,
Tabs as ATabs,
Typography,
@@ -20,14 +22,18 @@ import type { TreasuryPartyBalanceDto } from '@mento/shared';
import { api } from '@/lib/api';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import { toman } from './treasury-format';
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;
@@ -61,6 +67,8 @@ const kindLabel: Record<string, string> = {
const lines = [
['درآمد ثبت‌شده', 'bookedIncome'],
['فروش فاکتور', 'invoiceSales'],
['فاکتور برگشتی', 'invoiceCredits'],
['هزینه ثبت‌شده', 'bookedExpense'],
['سود عملیاتی', 'operatingProfit'],
['ورود وجه', 'cashIn'],
@@ -79,8 +87,8 @@ const metricRows = computed<MetricRow[]>(() => {
return lines.map(([label, key]) => ({
key,
label,
current: toman(current.value![key]),
previous: toman(previous.value![key]),
current: toman(current.value![key] || '0'),
previous: toman(previous.value![key] || '0'),
}));
});
@@ -182,8 +190,20 @@ onMounted(() => {
<a-tabs v-model:activeKey="reportTab">
<a-tab-pane key="periods" tab="مقایسه دوره‌ها">
<a-flex vertical :gap="16">
<a-list v-if="isMobile && metricRows.length" :data-source="metricRows">
<template #renderItem="{ item }">
<a-list-item>
<a-card :title="item.label" style="width: 100%">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="این دوره">{{ item.current }}</a-descriptions-item>
<a-descriptions-item label="دوره قبل">{{ item.previous }}</a-descriptions-item>
</a-descriptions>
</a-card>
</a-list-item>
</template>
</a-list>
<a-table
v-if="metricRows.length"
v-else-if="metricRows.length"
:columns="metricColumns"
:data-source="metricRows"
:pagination="false"
@@ -193,7 +213,7 @@ onMounted(() => {
<a-divider orientation="right">مطالبات به تفکیک طرف حساب</a-divider>
<a-empty v-if="!receivablesByParty.length" description="مورد بازی نیست." />
<a-list v-else item-layout="horizontal" :data-source="receivablesByParty">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="receivablesByParty">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -208,7 +228,7 @@ onMounted(() => {
<a-divider orientation="right">تعهدات به تفکیک ماه</a-divider>
<a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." />
<a-list v-else item-layout="horizontal" :data-source="payablesByMonth">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="payablesByMonth">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -224,7 +244,7 @@ onMounted(() => {
<template v-if="current">
<a-divider orientation="right">سهم هزینه‌ها</a-divider>
<a-empty v-if="!current.expenseCategories.length" description="دسته‌ای نیست." />
<a-list v-else item-layout="horizontal" :data-source="current.expenseCategories">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="current.expenseCategories">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -244,6 +264,9 @@ onMounted(() => {
<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)) }}
@@ -259,6 +282,9 @@ onMounted(() => {
<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)) }}
@@ -3,3 +3,11 @@ export function toman(value: string | number | null | undefined) {
if (!Number.isFinite(n)) return '۰';
return `${new Intl.NumberFormat('fa-IR').format(Math.round(n))} تومان`;
}
/** ماندهٔ دریافتنی منهای ماندهٔ پرداختنی: بد قرمز، بس سبز، صفر خاکستری. */
export function partyNetPosition(receivable: number, payable: number) {
const net = receivable - payable;
if (net > 0) return { text: `بد ${toman(net)}`, type: 'danger' as const };
if (net < 0) return { text: `بس ${toman(-net)}`, type: 'success' as const };
return { text: `مانده ${toman(0)}`, type: 'secondary' as const };
}
@@ -0,0 +1,7 @@
import { computed } from 'vue';
import { Grid } from 'ant-design-vue';
export function useTreasuryMobile() {
const screens = Grid.useBreakpoint();
return computed(() => !screens.value.md);
}