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

459 lines
16 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
import axios from 'axios';
import { api } from '@/lib/api';
import type {
CreateOrganizationApiKeyResponse,
CreateWebhookEndpointResponse,
OrganizationApiKeyDto,
WebhookDeliveryDto,
WebhookEndpointDto,
WebhookEvent,
} from '@mento/shared';
import { WEBHOOK_EVENTS } from '@mento/shared';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { registerTableColumns, useTableColumns } from '@/lib/tableColumns';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
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,
Row as ARow,
Space as ASpace,
Spin as ASpin,
Table as ATable,
Tag as ATag,
Typography,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { CopyOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography;
const ACheckableTag = ATag.CheckableTag;
const KEY_COL_LABELS = ['نام', 'پیشوند', 'آخرین استفاده', 'وضعیت'] as const;
const DELIVERY_COL_LABELS = ['زمان', 'رویداد', 'وضعیت', 'کد', 'تلاش'] as const;
registerTableColumns('public-api.keys', [...KEY_COL_LABELS]);
registerTableColumns('public-api.deliveries', [...DELIVERY_COL_LABELS]);
const keyTableCols = useTableColumns(() => 'public-api.keys');
const deliveryTableCols = useTableColumns(() => 'public-api.deliveries');
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const keys = ref<OrganizationApiKeyDto[]>([]);
const endpoints = ref<WebhookEndpointDto[]>([]);
const deliveries = ref<WebhookDeliveryDto[]>([]);
const newKeyName = ref('');
const createdRawKey = ref('');
const createdWebhookSecret = ref('');
const whName = ref('');
const whUrl = ref('');
const whEvents = ref<string[]>(['person.created', 'deal.created']);
const EVENT_LABELS: Record<WebhookEvent, string> = {
'person.created': 'ایجاد شخص',
'person.updated': 'ویرایش شخص',
'deal.created': 'ایجاد معامله',
'deal.updated': 'ویرایش معامله',
'deal.won': 'برد معامله',
'deal.lost': 'شکست معامله',
'invoice.paid': 'پرداخت فاکتور',
'activity.created': 'ایجاد فعالیت',
};
const keyColumns = computed<TableColumnsType<OrganizationApiKeyDto>>(() => {
const all: TableColumnsType<OrganizationApiKeyDto> = [
{ title: 'نام', key: 'نام', dataIndex: 'name' },
{ title: 'پیشوند', key: 'پیشوند' },
{ title: 'آخرین استفاده', key: 'آخرین استفاده' },
{ title: 'وضعیت', key: 'وضعیت', width: 100 },
{ title: '', key: 'عملیات', width: 120 },
];
return all.filter((col) => {
const key = String(col.key ?? '');
if (key === 'عملیات') return true;
if (!KEY_COL_LABELS.includes(key as (typeof KEY_COL_LABELS)[number])) return true;
return keyTableCols.isVisible(key);
});
});
const deliveryColumns = computed<TableColumnsType<WebhookDeliveryDto>>(() => {
const all: TableColumnsType<WebhookDeliveryDto> = [
{ title: 'زمان', key: 'زمان' },
{ title: 'رویداد', key: 'رویداد' },
{ title: 'وضعیت', key: 'وضعیت' },
{ title: 'کد', key: 'کد', width: 80 },
{ title: 'تلاش', key: 'تلاش', width: 80 },
];
return all.filter((col) => {
const key = String(col.key ?? '');
if (!DELIVERY_COL_LABELS.includes(key as (typeof DELIVERY_COL_LABELS)[number])) return true;
return deliveryTableCols.isVisible(key);
});
});
async function load() {
loading.value = true;
error.value = '';
try {
const [keysRes, epRes, delRes] = await Promise.all([
api.get<OrganizationApiKeyDto[]>('/api-keys'),
api.get<WebhookEndpointDto[]>('/webhooks'),
api.get<WebhookDeliveryDto[]>('/webhooks/deliveries'),
]);
keys.value = keysRes.data;
endpoints.value = epRes.data;
deliveries.value = delRes.data;
} catch (e) {
if (axios.isAxiosError(e) && e.response?.status === 403) {
error.value = 'ماژول API و وب‌هوک برای این محیط فعال نیست.';
} else {
error.value = 'بارگذاری تنظیمات ناموفق بود.';
}
} finally {
loading.value = false;
}
}
async function createKey() {
if (!newKeyName.value.trim()) {
error.value = 'نام کلید را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
ok.value = '';
createdRawKey.value = '';
try {
const { data } = await api.post<CreateOrganizationApiKeyResponse>(
'/api-keys',
{ name: newKeyName.value.trim() },
);
createdRawKey.value = data.rawKey;
newKeyName.value = '';
ok.value = 'کلید ساخته شد. همین الان کپی کنید؛ دوباره نمایش داده نمی‌شود.';
await load();
} catch {
error.value = 'ساخت کلید ناموفق بود.';
} finally {
saving.value = false;
}
}
async function revokeKey(id: string) {
if (!confirm('این کلید باطل شود؟')) return;
try {
await api.delete(`/api-keys/${id}`);
await load();
} catch {
error.value = 'باطل‌سازی کلید ناموفق بود.';
}
}
function toggleEvent(ev: string) {
if (whEvents.value.includes(ev)) {
whEvents.value = whEvents.value.filter((e) => e !== ev);
} else {
whEvents.value = [...whEvents.value, ev];
}
}
async function createWebhook() {
if (!whName.value.trim() || !whUrl.value.trim() || !whEvents.value.length) {
error.value = 'نام، آدرس و حداقل یک رویداد لازم است.';
return;
}
saving.value = true;
error.value = '';
createdWebhookSecret.value = '';
try {
const { data } = await api.post<CreateWebhookEndpointResponse>('/webhooks', {
name: whName.value.trim(),
url: whUrl.value.trim(),
events: whEvents.value,
});
whName.value = '';
whUrl.value = '';
createdWebhookSecret.value = data.secret;
ok.value = 'وب‌هوک ذخیره شد. secret را همین الان کپی کنید.';
await load();
} catch {
error.value = 'ذخیره وب‌هوک ناموفق بود.';
} finally {
saving.value = false;
}
}
async function removeWebhook(id: string) {
if (!confirm('وب‌هوک حذف شود؟')) return;
try {
await api.delete(`/webhooks/${id}`);
await load();
} catch {
error.value = 'حذف وب‌هوک ناموفق بود.';
}
}
async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text);
ok.value = 'کپی شد.';
} catch {
error.value = 'کپی در کلیپ‌بورد ممکن نشد.';
}
}
function endpointEventsLabel(ep: WebhookEndpointDto) {
return ep.events.map((e) => EVENT_LABELS[e as WebhookEvent] ?? e).join('، ');
}
onMounted(() => {
void load();
});
</script>
<template>
<a-flex vertical :gap="16">
<a-flex justify="space-between" align="flex-start" wrap="wrap" :gap="12">
<a-typography-title :level="3" :style="{ margin: 0 }">API و وب‌هوک</a-typography-title>
<a-button :disabled="loading" @click="load">
<template #icon><ReloadOutlined /></template>
بروزرسانی
</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 = ''" />
<a-spin :spinning="loading">
<a-card :bordered="false">
<a-divider orientation="right">کلیدهای API</a-divider>
<a-typography-paragraph type="secondary">
هدر درخواست:
<code>X-Api-Key: mk_…</code>
یا
<code>Authorization: Bearer mk_…</code>
— مسیرها:
<code>/api/public/v1/people</code>
و
<code>/api/public/v1/deals</code>
</a-typography-paragraph>
<a-form layout="vertical" @finish="createKey">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="نام کلید" required>
<a-input v-model:value="newKeyName" placeholder="مثلاً اتصال سایت" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label=" ">
<a-button type="primary" html-type="submit" :loading="saving">
<template #icon><PlusOutlined /></template>
ساخت کلید
</a-button>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-alert
v-if="createdRawKey"
type="success"
show-icon
:message="createdRawKey"
:style="{ marginBottom: '12px' }"
>
<template #action>
<a-button @click="copyText(createdRawKey)">
<template #icon><CopyOutlined /></template>
کپی
</a-button>
</template>
</a-alert>
<a-empty
v-if="!loading && !keys.length"
description="کلیدی نیست. برای دسترسی خارجی یک کلید بسازید."
/>
<template v-else-if="keys.length">
<a-flex justify="flex-end" :style="{ marginBottom: '12px' }">
<TableColumnsMenu table-key="public-api.keys" align="end" />
</a-flex>
<a-table
:columns="keyColumns"
:data-source="keys"
:pagination="false"
row-key="id"
:scroll="{ x: 640 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'نام'">
{{ (record as OrganizationApiKeyDto).name }}
</template>
<template v-else-if="column.key === 'پیشوند'">
<code>{{ (record as OrganizationApiKeyDto).prefix }}…</code>
</template>
<template v-else-if="column.key === 'آخرین استفاده'">
{{
(record as OrganizationApiKeyDto).lastUsedAt
? formatJalaliNumeric(new Date((record as OrganizationApiKeyDto).lastUsedAt!))
: '—'
}}
</template>
<template v-else-if="column.key === 'وضعیت'">
<a-tag
:color="(record as OrganizationApiKeyDto).revokedAt ? 'default' : 'success'"
:bordered="false"
>
{{ (record as OrganizationApiKeyDto).revokedAt ? 'باطل' : 'فعال' }}
</a-tag>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-button
v-if="!(record as OrganizationApiKeyDto).revokedAt"
danger
@click="revokeKey((record as OrganizationApiKeyDto).id)"
>
باطل‌سازی
</a-button>
</template>
</template>
</a-table>
</template>
<a-divider orientation="right">وب‌هوک‌های خروجی</a-divider>
<a-form layout="vertical" @finish="createWebhook">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="8">
<a-form-item label="نام" required>
<a-input v-model:value="whName" placeholder="مثلاً n8n" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="آدرس URL" required>
<a-input
v-model:value="whUrl"
placeholder="https://example.com/hook"
dir="ltr"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="رویدادها" required>
<a-space wrap>
<a-checkable-tag
v-for="ev in WEBHOOK_EVENTS"
:key="ev"
:checked="whEvents.includes(ev)"
@change="() => toggleEvent(ev)"
>
{{ EVENT_LABELS[ev] }}
</a-checkable-tag>
</a-space>
</a-form-item>
</a-col>
<a-col :span="24">
<a-button type="primary" html-type="submit" :loading="saving">
<template #icon><PlusOutlined /></template>
افزودن وب‌هوک
</a-button>
</a-col>
</a-row>
</a-form>
<a-alert
v-if="createdWebhookSecret"
type="success"
show-icon
:message="`HMAC secret: ${createdWebhookSecret}`"
:style="{ marginTop: '12px', marginBottom: '12px' }"
>
<template #action>
<a-button @click="copyText(createdWebhookSecret)">
<template #icon><CopyOutlined /></template>
کپی
</a-button>
</template>
</a-alert>
<a-empty
v-if="!loading && !endpoints.length"
description="وب‌هوکی نیست. رویدادهای CRM به آدرس شما POST می‌شوند."
/>
<a-list v-else-if="endpoints.length" item-layout="horizontal" :data-source="endpoints">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a-button danger @click="removeWebhook(item.id)">حذف</a-button>
</template>
<a-list-item-meta
:description="`${item.url} · ${endpointEventsLabel(item)}`"
>
<template #title>
<a-typography-text strong>{{ item.name }}</a-typography-text>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<a-divider orientation="right">آخرین ارسال‌های وب‌هوک</a-divider>
<a-empty
v-if="!deliveries.length"
description="ارسالی ثبت نشده. پس از وقوع رویدادها اینجا دیده می‌شوند."
/>
<template v-else>
<a-flex justify="flex-end" :style="{ marginBottom: '12px' }">
<TableColumnsMenu table-key="public-api.deliveries" align="end" />
</a-flex>
<a-table
:columns="deliveryColumns"
:data-source="deliveries"
:pagination="false"
row-key="id"
:scroll="{ x: 640 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'زمان'">
{{ formatJalaliNumeric(new Date((record as WebhookDeliveryDto).createdAt)) }}
</template>
<template v-else-if="column.key === 'رویداد'">
{{
EVENT_LABELS[(record as WebhookDeliveryDto).event as WebhookEvent] ??
(record as WebhookDeliveryDto).event
}}
</template>
<template v-else-if="column.key === 'وضعیت'">
{{ (record as WebhookDeliveryDto).status }}
</template>
<template v-else-if="column.key === 'کد'">
{{ (record as WebhookDeliveryDto).statusCode ?? '—' }}
</template>
<template v-else-if="column.key === 'تلاش'">
{{ toFaDigits((record as WebhookDeliveryDto).attempts) }}
</template>
</template>
</a-table>
</template>
</a-card>
</a-spin>
</a-flex>
</template>