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

501 lines
13 KiB
Vue
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import axios from 'axios';
import type { CustomerGroupColor, CustomerGroupDto, OrgUserDto } from '@mento/shared';
import { CUSTOMER_GROUP_COLORS } from '@mento/shared';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { normalizeSearchText } from '@/lib/search';
import {
CUSTOMER_GROUP_COLOR_LABELS,
groupSwatch,
useCustomerGroups,
} from '@/lib/customer-groups';
import { useAuthStore } from '@/stores/auth';
import { UiButton, UiInput, UiModal } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
import OrgUserPersonPick from '@/components/OrgUserPersonPick.vue';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; changed: [] }>();
const auth = useAuthStore();
const canManage = computed(
() => auth.user?.role === 'owner' || auth.user?.role === 'admin',
);
const { groups, load } = useCustomerGroups();
const users = ref<OrgUserDto[]>([]);
const newName = ref('');
const newColor = ref<CustomerGroupColor>('teal');
const newAssigneeIds = ref<string[]>([]);
const editingId = ref<string | null>(null);
const editName = ref('');
const assigneeDraft = ref<Record<string, string[]>>({});
const listQuery = ref('');
const busy = ref(false);
const error = ref('');
const filteredGroups = computed(() => {
const q = normalizeSearchText(listQuery.value);
if (!q) return groups.value;
return groups.value.filter((g) => {
const assigneeNames = (g.assignees ?? []).map((a) => a.fullName).join(' ');
return (
normalizeSearchText(g.name).includes(q) ||
normalizeSearchText(g.parentName ?? '').includes(q) ||
normalizeSearchText(assigneeNames).includes(q)
);
});
});
function errorText(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message;
if (Array.isArray(msg)) return msg[0] ?? fallback;
if (msg) return msg;
}
return fallback;
}
async function loadUsers() {
try {
const { data } = await api.get<OrgUserDto[]>('/users');
users.value = data.filter((u) => u.isActive !== false);
} catch {
users.value = [];
}
}
function syncAssigneeDraft() {
const next: Record<string, string[]> = {};
for (const g of groups.value) {
next[g.id] = (g.assignees ?? []).map((a) => a.id);
}
assigneeDraft.value = next;
}
async function run(task: () => Promise<unknown>, fallback: string) {
busy.value = true;
error.value = '';
try {
await task();
await load(true);
syncAssigneeDraft();
emit('changed');
return true;
} catch (e) {
error.value = errorText(e, fallback);
return false;
} finally {
busy.value = false;
}
}
async function create() {
const name = newName.value.trim();
if (!name) return;
const ok = await run(
() =>
api.post('/customer-groups', {
name,
color: newColor.value,
assigneeIds: newAssigneeIds.value,
}),
'ساخت گروه ناموفق بود.',
);
if (ok) {
newName.value = '';
newAssigneeIds.value = [];
}
}
function startEdit(g: CustomerGroupDto) {
editingId.value = g.id;
editName.value = g.name;
}
async function saveName(g: CustomerGroupDto) {
const name = editName.value.trim();
if (!name || name === g.name) {
editingId.value = null;
return;
}
const ok = await run(
() => api.patch(`/customer-groups/${g.id}`, { name }),
'تغییر نام ناموفق بود.',
);
if (ok) editingId.value = null;
}
async function setColor(g: CustomerGroupDto, color: CustomerGroupColor) {
if (g.color === color) return;
await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.');
}
async function onAssigneesChange(g: CustomerGroupDto, ids: string[]) {
assigneeDraft.value = { ...assigneeDraft.value, [g.id]: ids };
const prev = (g.assignees ?? []).map((a) => a.id).sort().join(',');
const next = [...ids].sort().join(',');
if (prev === next) return;
await run(
() => api.patch(`/customer-groups/${g.id}`, { assigneeIds: ids }),
'ذخیره مسئولان گروه ناموفق بود.',
);
}
function assigneeLabel(g: CustomerGroupDto) {
const names = (g.assignees ?? []).map((a) => a.fullName).filter(Boolean);
if (!names.length) return 'بدون مسئول';
if (names.length === 1) return names[0]!;
return `${names[0]} و ${toFaDigits(names.length - 1)} نفر دیگر`;
}
async function remove(g: CustomerGroupDto) {
const used = g.personCount + g.companyCount;
const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته می‌شود (خود مخاطب‌ها حذف نمی‌شوند).` : '';
if (!confirm(`گروه «${g.name}» حذف شود؟${note}`)) return;
await run(() => api.delete(`/customer-groups/${g.id}`), 'حذف گروه ناموفق بود.');
}
watch(
() => props.open,
(open) => {
if (!open) return;
error.value = '';
editingId.value = null;
listQuery.value = '';
void Promise.all([load(true), loadUsers()])
.then(() => syncAssigneeDraft())
.catch(() => {
error.value = 'بارگذاری گروه‌ها ناموفق بود.';
});
},
{ immediate: true },
);
</script>
<template>
<UiModal :open="open" title="گروه‌های مشتری" @close="emit('close')">
<div class="manager">
<p class="lead">
هر شخص یا شرکت می‌تواند چند گروه داشته باشد. مسئولان گروه (اختیاری) اعضای آن گروه را مثل
مشتریان خود می‌بینند. گروه‌های ته‌حساب با برچسب «ته‌حساب» مشخص شده‌اند.
</p>
<form v-if="canManage" class="create-panel" @submit.prevent="create">
<header class="create-head">
<strong>گروه جدید</strong>
<span>نام، رنگ و مسئولان را مشخص کنید و افزودن بزنید.</span>
</header>
<div class="new-row">
<UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" />
<div class="swatches">
<button
v-for="c in CUSTOMER_GROUP_COLORS"
:key="c"
type="button"
class="swatch"
:class="{ on: newColor === c }"
:style="{ background: groupSwatch(c).fg }"
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
@click="newColor = c"
/>
</div>
<UiButton type="submit" variant="primary" size="sm" :disabled="busy || !newName.trim()">
<UiIcon name="plus" :size="15" />
افزودن
</UiButton>
</div>
<div v-if="users.length" class="assignee-field create-assignees">
<span class="assignees-label">مسئولان (اختیاری)</span>
<OrgUserPersonPick
v-model="newAssigneeIds"
:users="users"
:disabled="busy"
empty-label="انتخاب مسئول"
/>
</div>
</form>
<p v-if="error" class="error">{{ error }}</p>
<div v-if="canManage || groups.length" class="list-head">
<h3 class="list-title">گروه‌های موجود</h3>
<label v-if="groups.length" class="list-search">
<UiIcon name="search" :size="15" />
<input
v-model="listQuery"
type="search"
placeholder="جستجوی گروه یا مسئول…"
/>
</label>
</div>
<ul v-if="filteredGroups.length" class="list">
<li v-for="g in filteredGroups" :key="g.id" class="row">
<div class="name-cell">
<form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)">
<UiInput v-model="editName" :maxlength="80" :disabled="busy" />
<UiButton type="submit" variant="primary" size="sm" :disabled="busy">ذخیره</UiButton>
<UiButton type="button" variant="ghost" size="sm" @click="editingId = null">انصراف</UiButton>
</form>
<template v-else>
<span
class="chip"
:style="{ color: groupSwatch(g.color).fg, background: groupSwatch(g.color).bg }"
>
{{ g.name }}
</span>
<span v-if="g.fromTahesab" class="tag">ته‌حساب</span>
<span class="count">
{{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت
</span>
<span v-if="!canManage" class="assignee-summary">{{ assigneeLabel(g) }}</span>
</template>
</div>
<div v-if="editingId !== g.id && canManage" class="row-actions">
<div class="swatches">
<button
v-for="c in CUSTOMER_GROUP_COLORS"
:key="c"
type="button"
class="swatch small"
:class="{ on: g.color === c }"
:style="{ background: groupSwatch(c).fg }"
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
:disabled="busy"
@click="setColor(g, c)"
/>
</div>
<UiButton variant="ghost" size="sm" :disabled="busy" @click="startEdit(g)">تغییر نام</UiButton>
<UiButton variant="ghost" size="sm" :disabled="busy" @click="remove(g)">
<UiIcon name="trash" :size="14" />
</UiButton>
</div>
<div v-if="canManage && users.length" class="assignee-field">
<span class="assignees-label">مسئولان</span>
<OrgUserPersonPick
:model-value="assigneeDraft[g.id] ?? []"
:users="users"
:disabled="busy"
empty-label="انتخاب مسئول"
@update:model-value="(ids) => (assigneeDraft[g.id] = ids)"
@change="(ids) => onAssigneesChange(g, ids)"
/>
</div>
</li>
</ul>
<p v-else-if="groups.length && listQuery.trim()" class="muted">گروهی با این جستجو پیدا نشد.</p>
<p v-else class="muted">هنوز گروهی ساخته نشده است.</p>
</div>
</UiModal>
</template>
<style scoped>
.manager {
display: grid;
gap: 0.85rem;
min-width: min(34rem, 100%);
}
.lead,
.muted {
margin: 0;
color: #64748b;
font-size: 0.85rem;
}
.error {
margin: 0;
color: #dc2626;
font-size: 0.85rem;
}
.create-panel {
display: grid;
gap: 0.75rem;
padding: 0.85rem 0.95rem;
border: 1px solid color-mix(in srgb, var(--accent, #0d9488) 28%, #e2e8f0);
border-radius: 12px;
background:
linear-gradient(180deg, color-mix(in srgb, var(--accent, #0d9488) 8%, #fff) 0%, #fff 72%);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
}
.create-head {
display: grid;
gap: 0.15rem;
}
.create-head strong {
color: var(--accent-deep, #0f766e);
font-size: 0.9rem;
font-weight: 700;
}
.create-head span {
color: #64748b;
font-size: 0.78rem;
}
.list-head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.list-title {
margin: 0;
color: #475569;
font-size: 0.8rem;
font-weight: 700;
}
.list-search {
display: flex;
align-items: center;
gap: 0.4rem;
min-width: min(16rem, 100%);
flex: 1 1 12rem;
max-width: 18rem;
height: 2.25rem;
padding: 0 0.65rem;
border: 1px solid #e2e8f0;
border-radius: var(--radius, 10px);
background: #fff;
color: #94a3b8;
}
.list-search:focus-within {
border-color: #5eead4;
}
.list-search input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font: inherit;
font-size: 0.85rem;
color: #0f172a;
}
.new-row,
.edit {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.new-row > :first-child,
.edit > :first-child {
flex: 1 1 12rem;
}
.swatches {
display: inline-flex;
gap: 0.3rem;
}
.swatch {
width: 1.3rem;
height: 1.3rem;
border-radius: 50%;
border: 2px solid #fff;
box-shadow: 0 0 0 1px #e2e8f0;
cursor: pointer;
padding: 0;
}
.swatch.small {
width: 1rem;
height: 1rem;
}
.swatch.on {
box-shadow: 0 0 0 2px #0f172a;
}
.list {
list-style: none;
margin: 0;
padding: 0 0 0.25rem;
display: grid;
gap: 0.4rem;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.5rem 0.65rem;
border: 1px solid #e2e8f0;
border-radius: 10px;
}
.name-cell {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem;
min-width: 0;
flex: 1 1 14rem;
}
.chip {
padding: 0.15rem 0.6rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.85rem;
}
.tag {
font-size: 0.7rem;
color: #0369a1;
background: #e0f2fe;
border-radius: 6px;
padding: 0.05rem 0.4rem;
}
.count,
.assignee-summary {
color: #94a3b8;
font-size: 0.78rem;
}
.assignee-summary {
flex: 1 1 100%;
}
.row-actions {
display: flex;
align-items: center;
gap: 0.35rem;
}
.assignee-field {
flex: 1 1 100%;
display: grid;
gap: 0.35rem;
padding-top: 0.35rem;
border-top: 1px dashed #e2e8f0;
}
.create-assignees {
border-top: 1px dashed color-mix(in srgb, var(--accent, #0d9488) 22%, #e2e8f0);
padding-top: 0.65rem;
}
.assignees-label {
font-size: 0.75rem;
color: #64748b;
font-weight: 600;
}
</style>