Files
CRM_Montzar/apps/web/src/views/adm/AdmOrganizationsView.vue
T

934 lines
24 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 { onMounted, reactive, ref } from 'vue';
import axios from 'axios';
import type {
ApplyBillingPlanRequest,
BillingPlanCode,
ConversationSettingsDto,
CreatePlatformOrganizationRequest,
OrgModuleKey,
PlatformOrganizationDto,
PlatformUserDto,
UpdateConversationSettingsRequest,
UpdatePlatformOrganizationRequest,
UserRole,
} from '@mento/shared';
import {
BILLING_PLAN_LABELS,
ORG_MODULE_GROUPS,
ORG_MODULE_LABELS,
USER_ROLE_LABELS,
USER_ROLES,
isBusinessField,
} from '@mento/shared';
import { platformApi } from '@/lib/platform-api';
import { BUSINESS_FIELDS, BUSINESS_FIELD_LABELS } from '@/lib/business-fields';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import AdmBillingPanel from './AdmBillingPanel.vue';
const query = ref('');
const loading = ref(false);
const error = ref('');
const success = ref('');
const items = ref<PlatformOrganizationDto[]>([]);
const openId = ref<string | null>(null);
const detail = ref<PlatformOrganizationDto | null>(null);
const busyId = ref('');
const showCreate = ref(false);
const creating = ref(false);
const createForm = reactive<CreatePlatformOrganizationRequest>({
name: '',
businessField: 'personal',
ownerFullName: '',
ownerEmail: '',
ownerPassword: '',
ownerMobile: '',
});
const editingId = ref<string | null>(null);
const savingEdit = ref(false);
const editForm = reactive({
name: '',
slug: '',
businessField: '' as string,
});
const moduleDraft = ref<OrgModuleKey[]>([]);
const savingModules = ref(false);
const chatForm = reactive({
chatHost: '',
apiKey: '',
uploadUrl: '',
downloadUrl: '',
});
const chatApiKeySet = ref(false);
const savingChat = ref(false);
const chatLoadedFor = ref<string | null>(null);
function fieldLabel(value?: string | null) {
if (!value) return '—';
return isBusinessField(value) ? BUSINESS_FIELD_LABELS[value] : value;
}
function apiError(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
return Array.isArray(msg) ? msg.join('، ') : (msg ?? fallback);
}
return fallback;
}
function resetCreateForm() {
createForm.name = '';
createForm.businessField = 'personal';
createForm.ownerFullName = '';
createForm.ownerEmail = '';
createForm.ownerPassword = '';
createForm.ownerMobile = '';
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await platformApi.get<PlatformOrganizationDto[]>(
'/platform/organizations',
{ params: query.value.trim() ? { q: query.value.trim() } : undefined },
);
items.value = data;
} catch (e) {
error.value = apiError(e, 'بارگذاری محیط‌ها ناموفق بود');
} finally {
loading.value = false;
}
}
async function toggleOpen(org: PlatformOrganizationDto) {
if (openId.value === org.id) {
openId.value = null;
detail.value = null;
editingId.value = null;
chatLoadedFor.value = null;
return;
}
openId.value = org.id;
editingId.value = null;
try {
const { data } = await platformApi.get<PlatformOrganizationDto>(
`/platform/organizations/${org.id}`,
);
detail.value = data;
moduleDraft.value = [...(data.enabledModules ?? [])];
await loadChatSettings(org.id);
} catch (e) {
error.value = apiError(e, 'بارگذاری اعضا ناموفق بود');
}
}
async function loadChatSettings(orgId: string) {
try {
const { data } = await platformApi.get<ConversationSettingsDto>(
`/platform/organizations/${orgId}/conversations/settings`,
);
chatForm.chatHost = data.chatHost;
chatForm.uploadUrl = data.uploadUrl;
chatForm.downloadUrl = data.downloadUrl;
chatApiKeySet.value = data.apiKeySet;
chatForm.apiKey = '';
chatLoadedFor.value = orgId;
} catch (e) {
error.value = apiError(e, 'بارگذاری تنظیمات گفتگو ناموفق بود');
}
}
async function saveChatSettings(orgId: string) {
savingChat.value = true;
error.value = '';
success.value = '';
try {
const payload: UpdateConversationSettingsRequest = {
chatHost: chatForm.chatHost.trim(),
uploadUrl: chatForm.uploadUrl.trim() || undefined,
downloadUrl: chatForm.downloadUrl.trim() || undefined,
};
if (chatForm.apiKey.trim()) payload.apiKey = chatForm.apiKey.trim();
const { data } = await platformApi.patch<ConversationSettingsDto>(
`/platform/organizations/${orgId}/conversations/settings`,
payload,
);
chatApiKeySet.value = data.apiKeySet;
chatForm.apiKey = '';
chatForm.chatHost = data.chatHost;
chatForm.uploadUrl = data.uploadUrl;
chatForm.downloadUrl = data.downloadUrl;
success.value = 'تنظیمات گفتگو ذخیره شد';
} catch (e) {
error.value = apiError(e, 'ذخیره تنظیمات گفتگو ناموفق بود');
} finally {
savingChat.value = false;
}
}
function startEdit(org: PlatformOrganizationDto) {
editingId.value = org.id;
editForm.name = org.name;
editForm.slug = org.slug;
editForm.businessField = org.businessField ?? '';
success.value = '';
error.value = '';
}
function cancelEdit() {
editingId.value = null;
}
async function saveEdit(orgId: string) {
savingEdit.value = true;
error.value = '';
success.value = '';
try {
const body: UpdatePlatformOrganizationRequest = {
name: editForm.name.trim(),
slug: editForm.slug.trim(),
businessField: editForm.businessField || null,
};
const { data } = await platformApi.patch<PlatformOrganizationDto>(
`/platform/organizations/${orgId}`,
body,
);
items.value = items.value.map((row) =>
row.id === orgId
? {
...row,
name: data.name,
slug: data.slug,
businessField: data.businessField,
isActive: data.isActive,
}
: row,
);
if (detail.value?.id === orgId) {
detail.value = { ...detail.value, ...data };
}
editingId.value = null;
success.value = 'اطلاعات محیط ذخیره شد';
} catch (e) {
error.value = apiError(e, 'ذخیره تغییرات ناموفق بود');
} finally {
savingEdit.value = false;
}
}
async function createOrganization() {
creating.value = true;
error.value = '';
success.value = '';
try {
const body: CreatePlatformOrganizationRequest = {
name: createForm.name.trim(),
businessField: createForm.businessField || undefined,
ownerFullName: createForm.ownerFullName.trim(),
ownerEmail: createForm.ownerEmail.trim(),
ownerPassword: createForm.ownerPassword,
ownerMobile: createForm.ownerMobile?.trim() || undefined,
};
const { data } = await platformApi.post<PlatformOrganizationDto>(
'/platform/organizations',
body,
);
items.value = [data, ...items.value];
showCreate.value = false;
resetCreateForm();
success.value = `محیط «${data.name}» ساخته شد`;
} catch (e) {
error.value = apiError(e, 'ساخت محیط ناموفق بود');
} finally {
creating.value = false;
}
}
async function setOrgActive(org: PlatformOrganizationDto, isActive: boolean) {
busyId.value = org.id;
error.value = '';
try {
const { data } = await platformApi.patch<PlatformOrganizationDto>(
`/platform/organizations/${org.id}`,
{ isActive },
);
items.value = items.value.map((row) => (row.id === org.id ? { ...row, isActive } : row));
if (detail.value?.id === org.id) {
detail.value = { ...detail.value, ...data };
}
} catch (e) {
error.value = apiError(e, 'تغییر وضعیت محیط ناموفق بود');
} finally {
busyId.value = '';
}
}
async function setMembershipActive(membershipId: string, isActive: boolean) {
busyId.value = membershipId;
error.value = '';
try {
await platformApi.patch(`/platform/memberships/${membershipId}`, { isActive });
if (openId.value) {
const { data } = await platformApi.get<PlatformOrganizationDto>(
`/platform/organizations/${openId.value}`,
);
detail.value = data;
}
} catch (e) {
error.value = apiError(e, 'تغییر عضویت ناموفق بود');
} finally {
busyId.value = '';
}
}
async function setMembershipRole(membershipId: string, role: UserRole) {
busyId.value = `role-${membershipId}`;
error.value = '';
try {
await platformApi.patch(`/platform/memberships/${membershipId}/role`, { role });
if (openId.value) {
const { data } = await platformApi.get<PlatformOrganizationDto>(
`/platform/organizations/${openId.value}`,
);
detail.value = data;
moduleDraft.value = [...(data.enabledModules ?? [])];
}
} catch (e) {
error.value = apiError(e, 'تغییر نقش ناموفق بود');
} finally {
busyId.value = '';
}
}
function toggleModule(key: OrgModuleKey) {
if (moduleDraft.value.includes(key)) {
moduleDraft.value = moduleDraft.value.filter((k) => k !== key);
} else {
moduleDraft.value = [...moduleDraft.value, key];
}
}
function selectGroup(keys: OrgModuleKey[], on: boolean) {
if (on) {
moduleDraft.value = [...new Set([...moduleDraft.value, ...keys])];
} else {
moduleDraft.value = moduleDraft.value.filter((k) => !keys.includes(k));
}
}
async function saveModules(orgId: string) {
savingModules.value = true;
error.value = '';
success.value = '';
try {
const { data } = await platformApi.patch<PlatformOrganizationDto>(
`/platform/organizations/${orgId}/modules`,
{ enabledModules: moduleDraft.value },
);
detail.value = data;
moduleDraft.value = [...(data.enabledModules ?? [])];
success.value = 'ماژول‌های محیط ذخیره شد';
} catch (e) {
error.value = apiError(e, 'ذخیره ماژول‌ها ناموفق بود');
} finally {
savingModules.value = false;
}
}
async function applyPlan(userId: string, planCode: BillingPlanCode) {
busyId.value = `plan-${userId}-${planCode}`;
error.value = '';
success.value = '';
try {
const body: ApplyBillingPlanRequest = { planCode };
await platformApi.post<PlatformUserDto>(
`/platform/users/${userId}/billing/apply-plan`,
body,
);
if (openId.value) {
const { data } = await platformApi.get<PlatformOrganizationDto>(
`/platform/organizations/${openId.value}`,
);
detail.value = data;
}
success.value = `پلن «${BILLING_PLAN_LABELS[planCode]}» اعمال شد`;
} catch (e) {
error.value = apiError(e, 'اعمال پلن ناموفق بود');
} finally {
busyId.value = '';
}
}
onMounted(() => {
void load();
});
</script>
<template>
<div class="page">
<header class="head">
<p class="lead">ساخت، ویرایش، ماژول‌ها و نقش اعضا.</p>
<div class="head-actions">
<form class="search" @submit.prevent="load">
<input v-model="query" type="search" placeholder="جستجوی نام یا اسلاگ" />
<button class="btn" type="submit" :disabled="loading">جستجو</button>
</form>
<button class="btn" type="button" @click="showCreate = !showCreate">
{{ showCreate ? 'بستن فرم' : 'محیط جدید' }}
</button>
</div>
</header>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="success" class="ok">{{ success }}</p>
<form v-if="showCreate" class="panel" @submit.prevent="createOrganization">
<h2>ساخت محیط جدید</h2>
<div class="grid">
<label>
<span>نام محیط</span>
<input v-model="createForm.name" required minlength="2" />
</label>
<label>
<span>زمینه فعالیت</span>
<select v-model="createForm.businessField">
<option v-for="field in BUSINESS_FIELDS" :key="field" :value="field">
{{ BUSINESS_FIELD_LABELS[field] }}
</option>
</select>
</label>
<label>
<span>نام مالک</span>
<input v-model="createForm.ownerFullName" required minlength="2" />
</label>
<label>
<span>ایمیل مالک</span>
<input v-model="createForm.ownerEmail" type="email" required />
</label>
<label>
<span>رمز مالک</span>
<input v-model="createForm.ownerPassword" type="password" required minlength="8" />
</label>
<label>
<span>موبایل مالک (اختیاری)</span>
<input v-model="createForm.ownerMobile" type="tel" dir="ltr" />
</label>
</div>
<div class="panel-actions">
<button class="btn" type="submit" :disabled="creating">
{{ creating ? 'در حال ساخت…' : 'ساخت محیط' }}
</button>
</div>
</form>
<p v-if="loading" class="muted">در حال بارگذاری…</p>
<p v-else-if="!items.length" class="muted">محیطی پیدا نشد.</p>
<div v-else class="list">
<article v-for="org in items" :key="org.id" class="row">
<button type="button" class="row-main" @click="toggleOpen(org)">
<div>
<strong>{{ org.name }}</strong>
<span>{{ org.slug }} · {{ fieldLabel(org.businessField) }}</span>
</div>
<div class="meta">
<em :class="org.isActive ? 'on' : 'off'">{{ org.isActive ? 'فعال' : 'غیرفعال' }}</em>
<small>
{{ toFaDigits(org.memberCount) }} عضو ·
{{ toFaDigits(org.personCount) }} شخص ·
{{ formatJalaliNumeric(new Date(org.createdAt)) }}
</small>
</div>
</button>
<div class="actions">
<button class="btn btn-ghost" type="button" @click="startEdit(org)">ویرایش</button>
<button
class="btn"
type="button"
:disabled="busyId === org.id"
@click="setOrgActive(org, !org.isActive)"
>
{{ org.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
</button>
</div>
<form
v-if="editingId === org.id"
class="edit-panel"
@submit.prevent="saveEdit(org.id)"
>
<label>
<span>نام</span>
<input v-model="editForm.name" required minlength="2" />
</label>
<label>
<span>اسلاگ</span>
<input v-model="editForm.slug" required minlength="2" dir="ltr" />
</label>
<label>
<span>زمینه فعالیت</span>
<select v-model="editForm.businessField">
<option value="">—</option>
<option v-for="field in BUSINESS_FIELDS" :key="field" :value="field">
{{ BUSINESS_FIELD_LABELS[field] }}
</option>
</select>
</label>
<div class="panel-actions">
<button class="btn" type="submit" :disabled="savingEdit">ذخیره</button>
<button class="btn btn-ghost" type="button" @click="cancelEdit">انصراف</button>
</div>
</form>
<div v-if="openId === org.id" class="detail">
<div class="modules">
<div class="modules-head">
<strong>ماژول‌های فعال</strong>
<button
class="btn"
type="button"
:disabled="savingModules"
@click="saveModules(org.id)"
>
{{ savingModules ? 'ذخیره…' : 'ذخیره ماژول‌ها' }}
</button>
</div>
<div v-for="group in ORG_MODULE_GROUPS" :key="group.title" class="mod-group">
<div class="mod-group-head">
<span>{{ group.title }}</span>
<button
class="btn btn-ghost"
type="button"
@click="selectGroup(group.keys, true)"
>
همه
</button>
<button
class="btn btn-ghost"
type="button"
@click="selectGroup(group.keys, false)"
>
هیچ‌کدام
</button>
</div>
<label v-for="key in group.keys" :key="key" class="mod-item">
<input
type="checkbox"
:checked="moduleDraft.includes(key)"
@change="toggleModule(key)"
/>
{{ ORG_MODULE_LABELS[key] }}
</label>
</div>
</div>
<div class="chat-settings">
<div class="modules-head">
<strong>تنظیمات گفتگو</strong>
<button
class="btn"
type="button"
:disabled="savingChat || chatLoadedFor !== org.id"
@click="saveChatSettings(org.id)"
>
{{ savingChat ? 'ذخیره…' : 'ذخیره گفتگو' }}
</button>
</div>
<p class="chat-hint">
Host، API Key و آدرس آپلود/دانلود — فقط از سوپرادمین و برای همین محیط.
</p>
<div class="chat-grid">
<label>
<span>Host سرویس چت</span>
<input
v-model="chatForm.chatHost"
dir="ltr"
placeholder="chat.example.ir"
autocomplete="off"
/>
</label>
<label>
<span>{{ chatApiKeySet ? 'API Key (برای تغییر وارد کنید)' : 'API Key' }}</span>
<input
v-model="chatForm.apiKey"
type="password"
dir="ltr"
autocomplete="new-password"
/>
</label>
<label>
<span>آدرس آپلود فایل</span>
<input
v-model="chatForm.uploadUrl"
dir="ltr"
placeholder="https://chat.example.ir/upload"
/>
</label>
<label>
<span>آدرس پایه دانلود فایل</span>
<input
v-model="chatForm.downloadUrl"
dir="ltr"
placeholder="https://chat.example.ir/files"
/>
</label>
</div>
</div>
<p v-if="!detail?.members?.length" class="muted">عضوی ثبت نشده.</p>
<ul v-else>
<li v-for="member in detail.members" :key="member.membershipId">
<div class="member-head">
<div>
<strong>{{ member.fullName }}</strong>
<span>
{{ member.email }}
· حساب {{ member.userIsActive ? 'فعال' : 'غیرفعال' }}
</span>
</div>
<div class="member-actions">
<select
:value="member.role"
:disabled="busyId === `role-${member.membershipId}`"
@change="
setMembershipRole(
member.membershipId,
($event.target as HTMLSelectElement).value as UserRole,
)
"
>
<option v-for="role in USER_ROLES" :key="role" :value="role">
{{ USER_ROLE_LABELS[role] }}
</option>
</select>
<button
class="btn btn-ghost"
type="button"
:disabled="busyId === member.membershipId"
@click="setMembershipActive(member.membershipId, !member.isActive)"
>
{{ member.isActive ? 'قطع دسترسی' : 'بازگشت دسترسی' }}
</button>
</div>
</div>
<AdmBillingPanel
v-if="member.role === 'owner'"
:user-id="member.userId"
:billing="member.billing"
:busy-id="busyId"
@apply="applyPlan(member.userId, $event)"
/>
</li>
</ul>
</div>
</article>
</div>
</div>
</template>
<style scoped>
.page {
display: grid;
gap: 0.95rem;
max-width: 1080px;
}
.head {
display: flex;
justify-content: space-between;
gap: 0.85rem;
flex-wrap: wrap;
align-items: center;
}
.lead,
.head p,
.muted {
margin: 0;
color: var(--muted);
font-size: 0.88rem;
}
.head-actions {
display: flex;
gap: 0.55rem;
flex-wrap: wrap;
align-items: center;
}
.search {
display: flex;
gap: 0.45rem;
padding: 0.25rem;
border-radius: 14px;
background: #fff;
border: 1px solid var(--line-light);
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.04);
}
.search input,
.panel input,
.panel select,
.edit-panel input,
.edit-panel select,
.member-actions select {
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.6rem 0.75rem;
font: inherit;
background: #fff;
}
.search input {
min-width: 180px;
border: 0;
box-shadow: none;
}
.error {
margin: 0;
color: var(--danger);
}
.ok {
margin: 0;
color: var(--success-deep);
}
.panel,
.edit-panel {
background: #fff;
border: 1px solid #eef2f7;
border-radius: 18px;
padding: 1rem;
display: grid;
gap: 0.85rem;
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.04);
}
.panel h2 {
margin: 0;
font-size: 1rem;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.75rem;
}
label {
display: grid;
gap: 0.35rem;
}
label span {
font-size: 0.82rem;
color: var(--muted);
font-weight: 700;
}
.panel-actions {
display: flex;
gap: 0.5rem;
}
.list {
display: grid;
gap: 0.7rem;
}
.row {
background: #fff;
border: 1px solid #eef2f7;
border-radius: 18px;
padding: 0.95rem 1rem;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 0.7rem 1rem;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.035);
}
.row-main {
display: flex;
justify-content: space-between;
gap: 1rem;
border: 0;
background: transparent;
text-align: start;
cursor: pointer;
padding: 0;
font: inherit;
color: inherit;
}
.row-main span,
.row-main small {
display: block;
color: var(--muted);
font-size: 0.8rem;
margin-top: 0.2rem;
}
.meta {
text-align: end;
}
.actions {
display: flex;
gap: 0.45rem;
align-items: flex-start;
}
.on,
.off {
font-style: normal;
font-size: 0.78rem;
font-weight: 800;
}
.on {
color: var(--success-deep);
}
.off {
color: var(--danger);
}
.edit-panel {
grid-column: 1 / -1;
grid-template-columns: repeat(3, minmax(0, 1fr));
align-items: end;
}
.edit-panel .panel-actions {
grid-column: 1 / -1;
}
.detail {
grid-column: 1 / -1;
border-top: 1px solid var(--line);
padding-top: 0.75rem;
display: grid;
gap: 1rem;
}
.modules {
display: grid;
gap: 0.75rem;
padding: 0.85rem;
border-radius: 12px;
background: #f8fafc;
border: 1px solid var(--line);
}
.chat-settings {
display: grid;
gap: 0.75rem;
padding: 0.85rem;
border-radius: 12px;
background: #f5f3ff;
border: 1px solid #e9e5ff;
}
.chat-hint {
margin: 0;
font-size: 0.82rem;
color: var(--muted);
}
.chat-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.75rem;
}
@media (max-width: 720px) {
.chat-grid {
grid-template-columns: 1fr;
}
}
.modules-head,
.mod-group-head {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.mod-group {
display: grid;
gap: 0.35rem;
}
.mod-item {
display: flex;
align-items: center;
gap: 0.45rem;
font-size: 0.88rem;
}
.detail ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.55rem;
}
.detail li {
display: grid;
gap: 0.75rem;
}
.member-head {
display: flex;
justify-content: space-between;
gap: 0.8rem;
align-items: center;
flex-wrap: wrap;
}
.detail span {
display: block;
color: var(--muted);
font-size: 0.8rem;
}
.member-actions {
display: flex;
gap: 0.45rem;
align-items: center;
}
:deep(.billing) {
margin-bottom: 0;
}
@media (max-width: 720px) {
.grid,
.edit-panel {
grid-template-columns: 1fr;
}
.search {
width: 100%;
}
.search input {
flex: 1;
min-width: 0;
}
.row {
grid-template-columns: 1fr;
}
}
</style>