Files
CRM_Montzar/apps/web/src/components/TeamsSettingsPanel.vue
T

635 lines
22 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth';
2026-10-17 17:20:28 +03:30
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import type {
DataAccessPolicy,
2026-10-17 17:20:28 +03:30
OrganizationDto,
OrgUserDto,
TeamDto,
TeamMemberRole,
2026-10-17 17:20:28 +03:30
UpdatePriorArchiveCutoffRequest,
} from '@mento/shared';
import {
DATA_ACCESS_SECTION_LABELS,
DATA_ACCESS_SECTIONS,
emptySectionDataAccess,
sectionHasDataAccessLimits,
} from '@mento/shared';
import DataAccessPolicyPanel from '@/components/DataAccessPolicyPanel.vue';
2026-10-17 17:20:28 +03:30
import { formatLocalDateInput, parseLocalInput, toFaDigits } from '@/lib/jalali';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Checkbox as ACheckbox,
Col as ACol,
Collapse as ACollapse,
CollapsePanel as ACollapsePanel,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
List as AList,
ListItem as AListItem,
ListItemMeta as AListItemMeta,
Radio as ARadio,
RadioGroup as ARadioGroup,
Row as ARow,
Select as ASelect,
Space as ASpace,
Spin as ASpin,
Tag as ATag,
Typography,
} from 'ant-design-vue';
const { Text: ATypographyText } = Typography;
const props = defineProps<{
users: OrgUserDto[];
canEdit: boolean;
}>();
const auth = useAuthStore();
const showPriorArchive = computed(
() =>
auth.user?.role === 'owner' &&
Boolean(auth.user.enabledModules?.includes('prior_data_archive')),
);
const priorUsers = computed(() => props.users.filter((u) => u.isActive !== false));
2026-10-17 17:20:28 +03:30
const selectedPriorUsers = computed(() => priorUsers.value.filter((u) => u.priorArchiveEnabled));
const priorSearch = ref('');
const priorPick = ref<string | undefined>(undefined);
const priorSavingId = ref('');
2026-10-17 17:20:28 +03:30
const cutoffLocal = ref('');
const cutoffSaving = ref(false);
const cutoffLoading = ref(false);
const availablePriorUsers = computed(() => {
const q = priorSearch.value.trim().toLowerCase();
return priorUsers.value.filter((u) => {
if (u.priorArchiveEnabled) return false;
if (!q) return true;
return [u.fullName, u.email, u.mobile]
.filter(Boolean)
.some((v) => String(v).toLowerCase().includes(q));
2026-10-17 17:20:28 +03:30
});
});
const availablePriorOptions = computed(() =>
availablePriorUsers.value.map((u) => ({ value: u.id, label: u.fullName })),
);
const emit = defineEmits<{
refreshUsers: [];
}>();
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const teams = ref<TeamDto[]>([]);
const newName = ref('');
const newDesc = ref('');
const editingId = ref<string | null>(null);
const editingMetaId = ref<string | null>(null);
const editName = ref('');
const editDesc = ref('');
const memberDraft = ref<Record<string, TeamMemberRole>>({});
const editableUsers = computed(() =>
props.users.filter((u) => u.isActive !== false && u.role !== 'owner' && u.role !== 'admin'),
);
const memberRoleOptions = [
{ value: 'member', label: 'عضو' },
{ value: 'manager', label: 'سرپرست' },
];
async function setPriorArchive(userId: string, enabled: boolean) {
priorSavingId.value = userId;
priorPick.value = undefined;
error.value = '';
ok.value = '';
try {
await api.patch(`/users/${userId}/prior-archive`, { enabled });
ok.value = enabled
? 'بایگانی اطلاعات قبل برای این کاربر روشن شد.'
: 'بایگانی اطلاعات قبل برای این کاربر خاموش شد.';
emit('refreshUsers');
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره ناموفق بود.')
: 'ذخیره ناموفق بود.';
} finally {
priorSavingId.value = '';
}
}
2026-10-17 17:20:28 +03:30
function cutoffPayload(value: string): UpdatePriorArchiveCutoffRequest {
const parsed = parseLocalInput(value);
if (!parsed) return { cutoffAt: null };
parsed.setHours(23, 59, 59, 999);
return { cutoffAt: parsed.toISOString() };
}
function applyCutoffFromOrg(org: Pick<OrganizationDto, 'priorArchiveCutoffAt'>) {
cutoffLocal.value = org.priorArchiveCutoffAt
? formatLocalDateInput(new Date(org.priorArchiveCutoffAt))
: '';
2026-10-17 17:20:28 +03:30
}
async function loadPriorArchiveCutoff() {
cutoffLoading.value = true;
try {
const { data } = await api.get<OrganizationDto>('/organizations/current');
applyCutoffFromOrg(data);
2026-10-17 17:20:28 +03:30
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'بارگذاری تاریخ بایگانی ناموفق بود.',
)
2026-10-17 17:20:28 +03:30
: 'بارگذاری تاریخ بایگانی ناموفق بود.';
} finally {
cutoffLoading.value = false;
}
}
async function onCutoffChange(value: string) {
cutoffLocal.value = value;
cutoffSaving.value = true;
error.value = '';
ok.value = '';
try {
const { data } = await api.patch<OrganizationDto>(
'/organizations/current/prior-archive-cutoff',
cutoffPayload(value),
);
applyCutoffFromOrg(data);
2026-10-17 17:20:28 +03:30
ok.value = value ? 'تاریخ بایگانی اطلاعات قبل ذخیره شد.' : 'تاریخ بایگانی اطلاعات قبل پاک شد.';
await auth.hydrate();
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'ذخیره تاریخ بایگانی ناموفق بود.',
)
2026-10-17 17:20:28 +03:30
: 'ذخیره تاریخ بایگانی ناموفق بود.';
await loadPriorArchiveCutoff();
} finally {
cutoffSaving.value = false;
}
}
function pickPriorUser(userId: unknown) {
const id = userId == null ? '' : String(userId);
if (!id) return;
void setPriorArchive(id, true);
2026-10-17 17:20:28 +03:30
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<TeamDto[]>('/teams');
teams.value = data;
} catch (e) {
if (axios.isAxiosError(e) && e.response?.status === 403) {
error.value = 'ماژول تیم‌ها و سطح دسترسی به پرونده‌ها برای این محیط فعال نیست.';
} else {
error.value = 'بارگذاری تیم‌ها ناموفق بود.';
}
} finally {
loading.value = false;
}
}
async function createTeam() {
if (!newName.value.trim()) {
error.value = 'نام تیم را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
try {
await api.post('/teams', {
name: newName.value.trim(),
description: newDesc.value.trim(),
});
newName.value = '';
newDesc.value = '';
ok.value = 'تیم ساخته شد.';
await load();
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'ساخت تیم ناموفق بود.')
: 'ساخت تیم ناموفق بود.';
} finally {
saving.value = false;
}
}
function startEdit(team: TeamDto) {
editingId.value = team.id;
editingMetaId.value = null;
const draft: Record<string, TeamMemberRole> = {};
for (const m of team.members) {
draft[m.userId] = m.role;
}
memberDraft.value = draft;
}
function startMetaEdit(team: TeamDto) {
editingMetaId.value = team.id;
editingId.value = null;
editName.value = team.name;
editDesc.value = team.description || '';
}
async function saveMeta() {
if (!editingMetaId.value) return;
if (!editName.value.trim()) {
error.value = 'نام تیم را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
try {
await api.patch(`/teams/${editingMetaId.value}`, {
name: editName.value.trim(),
description: editDesc.value.trim(),
});
ok.value = 'اطلاعات تیم ذخیره شد.';
editingMetaId.value = null;
await load();
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره تیم ناموفق بود.')
: 'ذخیره تیم ناموفق بود.';
} finally {
saving.value = false;
}
}
function toggleMember(userId: string) {
if (memberDraft.value[userId]) {
const next = { ...memberDraft.value };
delete next[userId];
memberDraft.value = next;
} else {
memberDraft.value = { ...memberDraft.value, [userId]: 'member' };
}
}
function setRole(userId: string, role: unknown) {
if (!memberDraft.value[userId]) return;
memberDraft.value = {
...memberDraft.value,
[userId]: String(role) as TeamMemberRole,
};
}
function teamMembersLabel(team: TeamDto) {
if (!team.members.length) return 'بدون عضو';
return team.members
.map((m) => `${m.fullName}${m.role === 'manager' ? ' (سرپرست)' : ''}`)
.join('، ');
}
async function saveMembers() {
if (!editingId.value) return;
saving.value = true;
error.value = '';
try {
await api.put(`/teams/${editingId.value}/members`, {
members: Object.entries(memberDraft.value).map(([userId, role]) => ({
userId,
role,
})),
});
ok.value = 'اعضای تیم ذخیره شد.';
editingId.value = null;
await load();
} catch {
error.value = 'ذخیره اعضا ناموفق بود.';
} finally {
saving.value = false;
}
}
async function removeTeam(id: string) {
if (!confirm('این تیم حذف شود؟')) return;
try {
await api.delete(`/teams/${id}`);
if (editingId.value === id) editingId.value = null;
await load();
} catch {
error.value = 'حذف تیم ناموفق بود.';
}
}
const expandedAccess = ref<string | null>(null);
const draftAccess = ref<DataAccessPolicy>({});
const accessMode = ref<'inherit' | 'custom'>('inherit');
const accessSaving = ref(false);
function clonePolicy(policy?: DataAccessPolicy | null): DataAccessPolicy {
const src = policy ?? {};
const out: DataAccessPolicy = {};
for (const [key, section] of Object.entries(src)) {
if (!section) continue;
out[key as keyof DataAccessPolicy] = {
mode: section.mode,
rules: (section.rules ?? []).map((r) => ({ ...r })),
};
}
return out;
}
function accessSummary(u: OrgUserDto): string {
const override = u.dataAccessOverride ?? {};
const hasOverride = DATA_ACCESS_SECTIONS.some((s) => Boolean(override[s]));
const effective = u.effectiveDataAccess ?? {};
const limited = DATA_ACCESS_SECTIONS.filter((s) =>
sectionHasDataAccessLimits(effective[s] ?? emptySectionDataAccess()),
);
if (!hasOverride && !limited.length) return 'مثل نقش · بدون محدودیت';
if (!hasOverride) {
return `مثل نقش · ${toFaDigits(limited.length)} بخش محدود`;
}
const labels = limited.map((s) => DATA_ACCESS_SECTION_LABELS[s]).slice(0, 2);
return `سفارشی · ${labels.join('، ') || 'بدون محدودیت'}${limited.length > 2 ? '…' : ''}`;
}
function openAccessEditor(u: OrgUserDto) {
if (expandedAccess.value === u.id) {
expandedAccess.value = null;
return;
}
const override = u.dataAccessOverride ?? {};
const hasOverride = DATA_ACCESS_SECTIONS.some((s) => Boolean(override[s]));
accessMode.value = hasOverride ? 'custom' : 'inherit';
draftAccess.value = hasOverride
? { ...clonePolicy(u.effectiveDataAccess), ...clonePolicy(override) }
: clonePolicy(u.effectiveDataAccess);
expandedAccess.value = u.id;
}
async function saveUserAccess(userId: string) {
accessSaving.value = true;
error.value = '';
ok.value = '';
try {
const payload =
accessMode.value === 'inherit'
? { dataAccessOverride: null }
: { dataAccessOverride: draftAccess.value };
await api.patch(`/users/${userId}/data-access`, payload);
ok.value = 'محدوده داده به‌روز شد.';
expandedAccess.value = null;
emit('refreshUsers');
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'ذخیره محدوده داده ناموفق بود.',
)
: 'ذخیره محدوده داده ناموفق بود.';
} finally {
accessSaving.value = false;
}
}
onMounted(() => {
void load();
2026-10-17 17:20:28 +03:30
if (showPriorArchive.value) void loadPriorArchiveCutoff();
});
</script>
<template>
<a-flex vertical :gap="12">
<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-card :bordered="false">
<a-form v-if="canEdit" layout="vertical" @finish="createTeam">
<a-divider orientation="right">تیم جدید</a-divider>
<a-row :gutter="[16, 0]" align="bottom">
<a-col :xs="24" :md="8">
<a-form-item label="نام تیم">
<a-input v-model:value="newName" placeholder="مثلاً فروش تهران" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="10">
<a-form-item label="توضیح">
<a-input v-model:value="newDesc" placeholder="اختیاری" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="6">
<a-form-item label=" ">
<a-button type="primary" html-type="submit" :loading="saving" block>افزودن</a-button>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-divider orientation="right">تیم‌ها</a-divider>
<a-spin :spinning="loading">
<a-empty
v-if="!loading && !teams.length"
description="تیمی تعریف نشده. تیم بسازید تا اعضای فروش پرونده‌های هم‌تیمی را ببینند."
2026-10-17 17:20:28 +03:30
/>
<a-list v-else item-layout="vertical" :data-source="teams">
<template #renderItem="{ item: t }">
<a-list-item>
<template v-if="canEdit" #actions>
<a-button type="link" @click="startMetaEdit(t)">ویرایش</a-button>
<a-button type="link" @click="startEdit(t)">اعضا</a-button>
<a-button type="link" danger @click="removeTeam(t.id)">حذف</a-button>
</template>
<a-list-item-meta>
<template #title>
<a-space wrap>
<a-typography-text strong>{{ t.name }}</a-typography-text>
<a-tag :bordered="false">{{ toFaDigits(t.memberCount) }} عضو</a-tag>
</a-space>
</template>
<template #description>
<a-typography-text type="secondary">
{{ t.description || 'بدون توضیح' }} · {{ teamMembersLabel(t) }}
</a-typography-text>
</template>
</a-list-item-meta>
<a-form
v-if="editingMetaId === t.id"
layout="vertical"
style="width: 100%"
@finish="saveMeta"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="نام تیم">
<a-input v-model:value="editName" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="توضیح">
<a-input v-model:value="editDesc" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
<a-space>
<a-button type="primary" html-type="submit" :loading="saving">ذخیره</a-button>
<a-button @click="editingMetaId = null">انصراف</a-button>
</a-space>
</a-form>
<a-flex v-if="editingId === t.id" vertical :gap="8" style="width: 100%">
<a-typography-text type="secondary">
اعضا را انتخاب کنید؛ سرپرست همان عضو تیم است.
</a-typography-text>
<a-row :gutter="[12, 8]">
<a-col
v-for="u in users.filter((x) => x.isActive !== false)"
:key="u.id"
:xs="24"
:sm="12"
:lg="8"
>
<a-space>
<a-checkbox
:checked="Boolean(memberDraft[u.id])"
@change="toggleMember(u.id)"
>
{{ u.fullName }}
</a-checkbox>
<a-select
v-if="memberDraft[u.id]"
:value="memberDraft[u.id]"
:options="memberRoleOptions"
style="width: 120px"
@update:value="setRole(u.id, $event)"
/>
</a-space>
</a-col>
</a-row>
<a-space>
<a-button type="primary" :loading="saving" @click="saveMembers">ذخیره اعضا</a-button>
<a-button @click="editingId = null">انصراف</a-button>
</a-space>
</a-flex>
</a-list-item>
</template>
</a-list>
</a-spin>
<a-collapse :bordered="false" ghost>
<a-collapse-panel v-if="showPriorArchive" key="prior" header="بایگانی اطلاعات قبل">
<a-row :gutter="[16, 12]" align="middle">
<a-col :xs="24" :lg="8">
<JalaliDateInput
:model-value="cutoffLocal"
mode="date"
placeholder="تاریخ برش"
:disabled="cutoffSaving || cutoffLoading"
@update:model-value="onCutoffChange"
/>
</a-col>
<a-col :xs="24" :lg="8">
<a-input v-model:value="priorSearch" placeholder="جستجوی کاربر…" style="width: 100%" />
</a-col>
<a-col :xs="24" :lg="8">
<a-select
:value="priorPick"
:options="availablePriorOptions"
:disabled="!availablePriorUsers.length || Boolean(priorSavingId)"
allow-clear
show-search
option-filter-prop="label"
:placeholder="
availablePriorUsers.length ? 'فعال‌سازی کاربر' : 'کاربر دیگری پیدا نشد'
"
style="width: 100%"
@update:value="pickPriorUser"
/>
</a-col>
</a-row>
<a-flex vertical :gap="8">
<a-typography-text type="secondary">
فقط این کاربران سوئیچ کار جاری / بایگانی را می‌بینند.
</a-typography-text>
<a-space v-if="selectedPriorUsers.length" wrap>
<a-tag
v-for="u in selectedPriorUsers"
:key="u.id"
closable
:disabled="priorSavingId === u.id"
@close.prevent="setPriorArchive(u.id, false)"
>
{{ u.fullName }}
</a-tag>
</a-space>
<a-typography-text v-else type="secondary">
هنوز کاربری انتخاب نشده است.
</a-typography-text>
</a-flex>
</a-collapse-panel>
<a-collapse-panel key="access" header="محدوده داده کاربران">
<a-flex vertical :gap="8">
<a-typography-text type="secondary">
پیش‌فرض از نقش است؛ برای کاربر خاص می‌توانید فیلتر جدا بگذارید.
</a-typography-text>
<a-empty
v-if="!editableUsers.length"
description="فقط نقش‌های فروش و پشتیبانی محدوده داده جدا دارند."
/>
<a-list v-else item-layout="vertical" :data-source="editableUsers">
<template #renderItem="{ item: u }">
<a-list-item>
<template v-if="canEdit" #actions>
<a-button type="link" @click="openAccessEditor(u)">
{{ expandedAccess === u.id ? 'بستن' : 'تنظیم' }}
</a-button>
</template>
<a-list-item-meta :description="accessSummary(u)">
<template #title>
<a-typography-text strong>{{ u.fullName }}</a-typography-text>
</template>
</a-list-item-meta>
<a-flex v-if="expandedAccess === u.id" vertical :gap="8" style="width: 100%">
<a-radio-group v-model:value="accessMode">
<a-space wrap>
<a-radio value="inherit">مثل نقش</a-radio>
<a-radio value="custom">سفارشی</a-radio>
</a-space>
</a-radio-group>
<DataAccessPolicyPanel
v-if="accessMode === 'custom'"
v-model="draftAccess"
compact
/>
<a-space>
<a-button type="primary" :loading="accessSaving" @click="saveUserAccess(u.id)">
ذخیره
</a-button>
<a-button @click="expandedAccess = null">انصراف</a-button>
</a-space>
</a-flex>
</a-list-item>
</template>
</a-list>
</a-flex>
</a-collapse-panel>
</a-collapse>
</a-card>
</a-flex>
</template>