Files
CRM_Montzar/apps/web/src/views/DeletionArchivesView.vue
T

705 lines
24 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import type {
AuditLogDto,
AuditLogListResponse,
DeletionArchiveDto,
DeletionArchiveListResponse,
DeletionRetention,
} from '@mento/shared';
import { api } from '@/lib/api';
import { formatJalaliDateTime, toFaDigits } from '@/lib/jalali';
import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
List as AList,
ListItem as AListItem,
ListItemMeta as AListItemMeta,
Modal as AModal,
Pagination as APagination,
Row as ARow,
Select as ASelect,
Space as ASpace,
Tabs as ATabs,
TabPane as ATabPane,
Typography,
} from 'ant-design-vue';
import { CrmSkeleton, CrmSkeletonTable } from '@/components/skeleton';
const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
type HistoryTab = 'creates' | 'edits' | 'deletes';
const TABS: Array<{ key: HistoryTab; label: string }> = [
{ key: 'creates', label: 'ایجاد' },
{ key: 'edits', label: 'ویرایش' },
{ key: 'deletes', label: 'حذف' },
];
const ENTITY_LABELS: Record<string, string> = {
people: 'مشتری',
companies: 'شرکت',
leads: 'لید',
deals: 'معامله',
activities: 'فعالیت',
notes: 'یادداشت',
tickets: 'تیکت',
quotes: 'پیش‌فاکتور',
invoices: 'فاکتور',
products: 'محصول',
'project-cards': 'کارت پروژه',
'project-boards': 'تخته پروژه',
pipelines: 'مسیر فروش',
routines: 'روتین',
'routine-tasks': 'کار روتین',
'lead-forms': 'فرم',
users: 'کاربر',
teams: 'تیم',
automations: 'اتوماسیون',
'message-automations': 'پیام خودکار',
'sms-campaigns': 'کمپین پیامک',
'custom-fields': 'فیلد سفارشی',
inventory: 'انبار',
reservations: 'رزرو',
organizations: 'سازمان',
faq: 'پرسش متداول',
conversations: 'گفتگو',
loyalty: 'باشگاه',
notifications: 'اعلان',
'table-prefs': 'ستون‌های جدول',
integrations: 'اتصال',
};
const RETENTION_OPTIONS: Array<{ value: DeletionRetention; label: string }> = [
{ value: 'month', label: 'یک ماه' },
{ value: 'two_months', label: 'دو ماه' },
{ value: 'three_months', label: 'سه ماه' },
{ value: 'six_months', label: 'شش ماه' },
{ value: 'year', label: 'یک سال' },
{ value: 'never', label: 'هرگز' },
];
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const savingRetention = ref(false);
const busyId = ref('');
const error = ref('');
const okMsg = ref('');
const q = ref('');
const actorId = ref('');
const actors = ref<Array<{ id: string; fullName: string }>>([]);
const page = ref(1);
const pageSize = usePageSize('history-log');
const retention = ref<DeletionRetention>('never');
const data = ref<DeletionArchiveListResponse | null>(null);
const audit = ref<AuditLogListResponse | null>(null);
const purgeId = ref<string | null>(null);
const tab = computed<HistoryTab>(() => {
const value = route.query.tab;
if (value === 'creates' || value === 'edits' || value === 'deletes') return value;
return 'deletes';
});
const totalPages = computed(() => {
const source = tab.value === 'deletes' ? data.value : audit.value;
if (!source) return 1;
return Math.max(1, Math.ceil(source.total / source.limit));
});
const listSource = computed(() => (tab.value === 'deletes' ? data.value : audit.value));
function rowNo(index: number) {
return (page.value - 1) * pageSize.value + index + 1;
}
const purgeItem = computed(() => data.value?.items.find((item) => item.id === purgeId.value) ?? null);
const actorOptions = computed(() => [
{ value: '', label: 'همه' },
...actors.value.map((user) => ({ value: user.id, label: user.fullName })),
]);
const showDeletesEmpty = computed(
() => tab.value === 'deletes' && !error.value && !loading.value && !data.value?.items.length,
);
const showAuditEmpty = computed(
() => tab.value !== 'deletes' && !error.value && !loading.value && !audit.value?.items.length,
);
function apiError(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
if (!e.response || e.response.status === 404) return fallback;
if (Array.isArray(msg)) return msg.join('، ');
if (msg) return msg;
}
return fallback;
}
function entityLabel(entityType: string | null) {
if (!entityType) return 'مورد';
return ENTITY_LABELS[entityType] ?? entityType;
}
function looksLikeId(id: string | null | undefined) {
return !!id && /^c[a-z0-9]{20,}$/i.test(id);
}
const ENTITY_GET: Record<string, (id: string) => string> = {
people: (id) => `/people/${id}`,
companies: (id) => `/companies/${id}`,
leads: (id) => `/leads/${id}`,
deals: (id) => `/deals/${id}`,
activities: (id) => `/activities/${id}`,
notes: (id) => `/notes/${id}`,
tickets: (id) => `/tickets/${id}`,
quotes: (id) => `/quotes/${id}`,
invoices: (id) => `/invoices/${id}`,
products: (id) => `/products/${id}`,
'project-cards': (id) => `/project-cards/${id}`,
'lead-forms': (id) => `/lead-forms/${id}`,
routines: (id) => `/routines/${id}`,
};
const recordInfo = ref<Record<string, { title: string; snippet: string }>>({});
function entityKey(row: AuditLogDto) {
if (!row.entityType || !looksLikeId(row.entityId)) return '';
return `${row.entityType}:${row.entityId}`;
}
function pathTail(row: AuditLogDto) {
const parts = row.path.replace(/^\/api\/?/, '').split('/').filter(Boolean);
const second = parts[1] ?? '';
return looksLikeId(second) ? parts.slice(2).join('/') : parts.slice(1).join('/');
}
function pathParts(row: AuditLogDto) {
return row.path.replace(/^\/api\/?/, '').split('/').filter(Boolean);
}
function pathPhrase(row: AuditLogDto) {
const parts = pathParts(row);
const tail = pathTail(row);
const kind = entityLabel(row.entityType);
const nested = !looksLikeId(parts[1]);
if (nested && parts[0] === 'activities' && parts[1] === 'types') {
return parts[2] === 'reorder' ? 'ترتیب انواع فعالیت عوض شد' : 'نوع فعالیت ویرایش شد';
}
if (nested && parts[0] === 'activities' && parts[1] === 'stages') {
return parts[2] === 'reorder' ? 'ترتیب مراحل فعالیت عوض شد' : 'مرحله فعالیت ویرایش شد';
}
if (parts[0] === 'table-prefs') return 'چینش ستون‌های جدول عوض شد';
if (parts[0] === 'notifications') return 'اعلان‌ها خوانده شد';
if (parts[0] === 'integrations' && parts[1] === 'tahesab') return 'تنظیم اتصال ته‌حساب ویرایش شد';
if (parts[0] === 'integrations' && parts[1] === 'woocommerce') return 'تنظیم ووکامرس ویرایش شد';
if (parts[0] === 'integrations' && parts[1] === 'montify') return 'تنظیم مونتیفای ویرایش شد';
if (parts[0] === 'integrations' && parts[1] === 'voip') return 'تنظیم تلفن ویرایش شد';
if (tail === 'import' || tail.startsWith('import/')) {
return kind === 'مشتری' ? 'ورود مشتریان از فایل' : `ورود ${kind} از فایل`;
}
const phrases: Record<string, string> = {
sms: 'ارسال پیامک',
'birthday-sms': 'پیامک تبریک تولد',
complete: 'تکمیل شد',
stage: 'مرحله عوض شد',
move: 'در مسیر جابه‌جا شد',
notes: 'یادداشت ثبت شد',
call: 'تماس ثبت شد',
'follow-up': 'پیگیری ثبت شد',
convert: 'به مشتری تبدیل شد',
logo: 'تصویر عوض شد',
assign: 'واگذار شد',
'bulk-stage': 'مرحله چند مورد با هم عوض شد',
'bulk-delete': 'حذف گروهی',
'auto-assign': 'واگذاری خودکار',
archive: 'بایگانی شد',
};
if (phrases[tail]) return phrases[tail];
if (row.method === 'POST') return `${kind} ساخته شد`;
if (row.method === 'DELETE') return `${kind} حذف شد`;
return `مشخصات ${kind} ویرایش شد`;
}
function pickInfo(type: string, body: Record<string, unknown>) {
const title =
type === 'people'
? [body.firstName, body.lastName].filter((part) => typeof part === 'string' && part.trim()).join(' ')
: String(body.title || body.name || body.subject || body.number || '').trim();
const raw = String(body.description || body.body || '')
.split('\n')
.map((line) => line.trim())
.find(Boolean) ?? '';
const snippet = raw.replace(/\s+/g, ' ').slice(0, 180);
return {
title: title.slice(0, 120),
snippet: snippet && snippet !== title ? snippet : '',
};
}
async function hydrate(rows: AuditLogDto[]) {
const pending = new Map<string, { type: string; id: string }>();
for (const row of rows) {
const key = entityKey(row);
if (!key || recordInfo.value[key] || pending.has(key)) continue;
const type = row.entityType ?? '';
if (!ENTITY_GET[type] || !row.entityId) continue;
pending.set(key, { type, id: row.entityId });
}
await Promise.all(
[...pending.entries()].map(async ([key, job]) => {
try {
const { data: body } = await api.get<Record<string, unknown>>(ENTITY_GET[job.type](job.id));
recordInfo.value = { ...recordInfo.value, [key]: pickInfo(job.type, body ?? {}) };
} catch {
recordInfo.value = { ...recordInfo.value, [key]: { title: '', snippet: '' } };
}
}),
);
}
function rowHeading(row: AuditLogDto) {
if (row.label) return row.label;
const cached = recordInfo.value[entityKey(row)]?.title;
if (cached) return cached;
const phrase = pathPhrase(row);
if (!looksLikeId(row.entityId)) return phrase;
return entityLabel(row.entityType);
}
function rowDetail(row: AuditLogDto) {
if (row.detail) return row.detail;
const heading = rowHeading(row);
const phrase = pathPhrase(row);
const snippet = recordInfo.value[entityKey(row)]?.snippet ?? '';
if (snippet) return snippet;
if (phrase && phrase !== heading) return phrase;
return '';
}
function recordPath(row: AuditLogDto) {
const parts = pathParts(row);
const settings: Record<string, string> = {
tahesab: '/settings/tahesab',
woocommerce: '/settings/woocommerce',
montify: '/settings/montify',
voip: '/settings/voip',
};
if (parts[0] === 'integrations' && settings[parts[1] ?? '']) return settings[parts[1] ?? ''];
if (parts[0] === 'automations') return '/settings/automations';
if (parts[0] === 'message-automations') return '/settings/message-automations';
if (parts[0] === 'custom-fields') return '/settings/custom-fields';
if (parts[0] === 'faq') return '/settings/faq';
if (parts[0] === 'pipelines') return '/settings/pipelines';
if (parts[0] === 'users' || parts[0] === 'teams' || parts[0] === 'org-roles') return '/settings/team';
const entityType = row.entityType;
const entityId = looksLikeId(parts[1]) ? parts[1] : looksLikeId(row.entityId) ? row.entityId : null;
if (!entityId || !entityType) return null;
const routes: Record<string, string> = {
people: `/contacts/people/${entityId}`,
companies: `/contacts/companies/${entityId}`,
leads: `/leads/${entityId}`,
deals: `/deals/${entityId}`,
activities: `/activities/${entityId}`,
tickets: `/tickets/${entityId}`,
quotes: `/quotes/${entityId}`,
invoices: `/invoices/${entityId}`,
products: `/settings/products/${entityId}/edit`,
'project-cards': `/project-cards/${entityId}`,
routines: `/routines/manage/${entityId}/edit`,
'lead-forms': `/settings/lead-forms/${entityId}`,
};
return routes[entityType] ?? null;
}
function openRecord(row: AuditLogDto) {
const path = recordPath(row);
if (path) void router.push(path);
}
async function loadAudit(current: 'creates' | 'edits') {
const action = current === 'creates' ? 'ایجاد' : 'ویرایش';
const search = q.value.trim();
try {
const { data: res } = await api.get<AuditLogListResponse>('/audit-logs', {
params: {
q: search || undefined,
action,
actorUserId: actorId.value || undefined,
page: page.value,
limit: pageSize.value,
},
});
return res;
} catch (e) {
if (!axios.isAxiosError(e) || e.response?.status !== 400) throw e;
const { data: res } = await api.get<AuditLogListResponse>('/audit-logs', {
params: {
q: search || action,
actorUserId: actorId.value || undefined,
page: page.value,
limit: pageSize.value,
},
});
return { ...res, items: res.items.filter((item) => item.action === action) };
}
}
async function loadDeletes() {
const params = {
q: q.value.trim() || undefined,
deletedById: actorId.value || undefined,
page: page.value,
limit: pageSize.value,
};
try {
const { data: res } = await api.get<DeletionArchiveListResponse>('/deletions', { params });
return res;
} catch (e) {
if (!axios.isAxiosError(e) || e.response?.status !== 400 || !params.deletedById) throw e;
const { data: res } = await api.get<DeletionArchiveListResponse>('/deletions', {
params: { q: params.q, page: params.page, limit: params.limit },
});
const items = res.items.filter((item) => item.deletedById === params.deletedById);
return { ...res, items, total: items.length };
}
}
async function loadActors() {
try {
const { data: rows } = await api.get<Array<{ id: string; fullName: string }>>('/users');
actors.value = rows
.filter((row) => row.fullName)
.sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa'));
} catch {
actors.value = [];
}
}
function onPaginationChange(nextPage: number, nextSize: number) {
const sizeChanged = nextSize !== pageSize.value;
page.value = nextPage;
if (sizeChanged) {
pageSize.value = nextSize;
page.value = 1;
}
void load(sizeChanged);
}
function selectTab(next: string | number) {
const key = String(next) as HistoryTab;
if (key === tab.value) return;
q.value = '';
page.value = 1;
data.value = null;
audit.value = null;
error.value = '';
okMsg.value = '';
void router.replace({ query: key === 'deletes' ? {} : { tab: key } });
}
async function load(resetPage = false) {
if (resetPage) page.value = 1;
loading.value = true;
error.value = '';
const current = tab.value;
try {
if (current === 'deletes') {
const res = await loadDeletes();
if (tab.value !== current) return;
audit.value = null;
data.value = res;
retention.value = res.retention;
} else {
const res = await loadAudit(current);
if (tab.value !== current) return;
data.value = null;
audit.value = res;
void hydrate(res.items);
}
} catch (e) {
if (tab.value !== current) return;
error.value = apiError(
e,
current === 'deletes' ? 'بارگذاری لاگ حذف ناموفق بود.' : 'بارگذاری تاریخچه ناموفق بود.',
);
} finally {
if (tab.value === current) loading.value = false;
}
}
async function saveRetention() {
savingRetention.value = true;
error.value = '';
okMsg.value = '';
try {
await api.patch('/deletions/settings', { retention: retention.value });
okMsg.value = 'مدت نگهداری ذخیره شد.';
} catch (e) {
error.value = apiError(e, 'ذخیره مدت نگهداری ناموفق بود.');
} finally {
savingRetention.value = false;
}
}
async function restore(id: string) {
busyId.value = id;
error.value = '';
okMsg.value = '';
try {
await api.post(`/deletions/${id}/restore`);
okMsg.value = 'مورد برگردانده شد.';
await load();
} catch (e) {
error.value = apiError(e, 'بازگردانی ناموفق بود.');
} finally {
busyId.value = '';
}
}
async function confirmPurge() {
const id = purgeId.value;
if (!id) return;
busyId.value = id;
error.value = '';
okMsg.value = '';
try {
await api.delete(`/deletions/${id}`);
purgeId.value = null;
okMsg.value = 'این مورد برای همیشه پاک شد.';
await load();
} catch (e) {
error.value = apiError(e, 'حذف کامل ناموفق بود.');
} finally {
busyId.value = '';
}
}
function deletionDescription(item: DeletionArchiveDto) {
return [
item.modelLabel,
`${item.deletedByName || 'سیستم'} · ${formatJalaliDateTime(new Date(item.deletedAt))}`,
].join(' · ');
}
function auditDescription(row: AuditLogDto) {
const parts: string[] = [];
if (pathPhrase(row) !== rowHeading(row)) parts.push(pathPhrase(row));
parts.push(row.actor?.fullName || 'سیستم');
parts.push(formatJalaliDateTime(new Date(row.createdAt)));
return parts.join(' · ');
}
watch(tab, () => {
void load();
}, { immediate: true });
watch(actorId, () => {
void load(true);
});
void loadActors();
</script>
<template>
<a-flex vertical :gap="16">
<a-typography-title :level="3" :style="{ margin: 0 }">تاریخچه کارها</a-typography-title>
<a-tabs :active-key="tab" @change="selectTab">
<a-tab-pane v-for="item in TABS" :key="item.key" :tab="item.label" />
</a-tabs>
<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 v-if="tab === 'deletes'" :bordered="false">
<a-form layout="vertical">
<a-row :gutter="[16, 0]" align="bottom">
<a-col :xs="24" :md="12">
<a-form-item label="حذف خودکار از این فهرست">
<a-select
v-model:value="retention"
:options="RETENTION_OPTIONS"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label=" ">
<a-button type="primary" :loading="savingRetention" @click="saveRetention">
ذخیره
</a-button>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-typography-text type="secondary">
تا پایان این مدت می‌توان مورد را برگرداند. «هرگز» یعنی فقط با حذف کامل از بین می‌رود.
</a-typography-text>
</a-card>
<a-card :bordered="false">
<a-form layout="vertical" @finish="load(true)">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="جستجو">
<a-input
v-model:value="q"
type="search"
placeholder="جستجو در عنوان یا نوع"
allow-clear
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="انجام‌دهنده">
<a-select
v-model:value="actorId"
:options="actorOptions"
style="width: 100%"
show-search
option-filter-prop="label"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="4">
<a-form-item label=" ">
<a-button type="primary" html-type="submit" block>جستجو</a-button>
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-card>
<CrmSkeleton :loading="loading">
<CrmSkeletonTable :rows="8" :columns="5">
<a-card v-if="showDeletesEmpty" :bordered="false">
<a-empty description="حذفی ثبت نشده. از این به بعد حذف‌ها با نام کاربر و زمان اینجا دیده می‌شوند." />
</a-card>
<a-card v-else-if="showAuditEmpty" :bordered="false">
<a-empty
:description="
tab === 'creates'
? 'ایجاد جدیدی ثبت نشده. با انجام کار در سامانه، نام کاربر و زمان اینجا دیده می‌شود.'
: 'ویرایشی ثبت نشده. با انجام کار در سامانه، نام کاربر و زمان اینجا دیده می‌شود.'
"
/>
</a-card>
<a-card v-else-if="tab === 'deletes' && data?.items.length" :bordered="false">
<a-list item-layout="horizontal" :data-source="data.items">
<template #renderItem="{ item, index }">
<a-list-item>
<template #actions>
<a-space wrap>
<a-button
:disabled="busyId === item.id"
@click="restore(item.id)"
>
بازگردانی
</a-button>
<a-button
danger
:disabled="busyId === item.id"
@click="purgeId = item.id"
>
حذف کامل
</a-button>
</a-space>
</template>
<a-list-item-meta :description="deletionDescription(item)">
<template #avatar>
<a-typography-text type="secondary">{{ toFaDigits(rowNo(index)) }}</a-typography-text>
</template>
<template #title>
<a-typography-text strong>{{ item.label }}</a-typography-text>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
<a-card v-else-if="audit?.items.length" :bordered="false">
<a-list item-layout="horizontal" :data-source="audit.items">
<template #renderItem="{ item, index }">
<a-list-item
:style="recordPath(item) ? { cursor: 'pointer' } : undefined"
@click="openRecord(item)"
>
<template v-if="recordPath(item)" #actions>
<a-button type="link" @click.stop="openRecord(item)">مشاهده</a-button>
</template>
<a-list-item-meta :description="auditDescription(item)">
<template #avatar>
<a-typography-text type="secondary">{{ toFaDigits(rowNo(index)) }}</a-typography-text>
</template>
<template #title>
<a-flex vertical :gap="2">
<a-typography-text strong>{{ rowHeading(item) }}</a-typography-text>
<a-typography-text v-if="rowDetail(item)" type="secondary">
{{ rowDetail(item) }}
</a-typography-text>
</a-flex>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</CrmSkeletonTable>
</CrmSkeleton>
<a-flex
v-if="listSource"
justify="space-between"
align="center"
wrap="wrap"
:gap="8"
>
<a-pagination
:current="page"
:total="listSource.total"
:page-size="pageSize"
:show-size-changer="true"
:page-size-options="PAGE_SIZE_OPTIONS.map(String)"
@change="onPaginationChange"
/>
<a-typography-text type="secondary">
صفحه {{ toFaDigits(page) }} از {{ toFaDigits(totalPages) }}
</a-typography-text>
</a-flex>
<a-modal
:open="!!purgeItem"
title="حذف کامل"
ok-text="حذف کامل"
cancel-text="انصراف"
ok-type="danger"
:confirm-loading="!!busyId"
destroy-on-close
@ok="confirmPurge"
@cancel="purgeId = null"
>
<a-typography-text v-if="purgeItem">
«{{ purgeItem.label }}» برای همیشه پاک شود؟ بعد از این دیگر قابل بازگشت نیست.
</a-typography-text>
</a-modal>
</a-flex>
</template>