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

1288 lines
49 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
import { RouterLink } from 'vue-router';
import axios from 'axios';
import { api } from '@/lib/api';
import type {
CreateTahesabConnectionRequest,
TahesabConnectionDto,
UpdateTahesabConnectionRequest,
} from '@mento/shared';
import { brand } from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
import { registerTableColumns, useTableColumns } from '@/lib/tableColumns';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Checkbox as ACheckbox,
Col as ACol,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
InputPassword as AInputPassword,
List as AList,
ListItem as AListItem,
Modal as AModal,
Pagination as APagination,
Progress as AProgress,
Row as ARow,
Select as ASelect,
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 {
DeleteOutlined,
EditOutlined,
ReloadOutlined,
SafetyCertificateOutlined,
} from '@ant-design/icons-vue';
const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography;
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const items = ref<TahesabConnectionDto[]>([]);
const editingId = ref<string | null>(null);
const form = reactive({
label: '',
baseUrl: '',
dbName: 'DB',
token: '',
isDefault: false,
allowInsecureTls: false,
enabled: true,
});
const sync = reactive({
connectionId: '',
phone: '',
name: '',
moshtariCode: '' as string | number,
fromCode: '',
toCode: '',
});
const syncBusy = ref(false);
/** تعداد مشتری در هر درخواست ورود دسته‌ای (برای جلوگیری از تایم‌اوت و نمایش درصد) */
const IMPORT_CHUNK = 25;
const importOverlay = reactive<{ open: boolean; message: string; progress: number | null }>({
open: false,
message: '',
progress: null,
});
type SyncResult = {
moshtariCode: number | null;
name: string;
tel: string;
alreadyLinked?: boolean;
personId?: string | null;
personName?: string | null;
};
const syncResults = ref<SyncResult[]>([]);
/** هر درخواست listAll یک بازهٔ ۲۰۰۰ کدی است؛ بعد از دو بازهٔ خالی پشت‌سرهم، خواندن تمام می‌شود */
const LIST_ALL_CODE_PAGE = 2000;
const LIST_ALL_EMPTY_STOP = 2;
const SYNC_TABLE_PAGE_SIZES = [10, 20, 50, 100];
const CUSTOMER_COL_LABELS = ['کد مشتری', 'نام و نام خانوادگی', 'تلفن', 'وضعیت لینک'] as const;
const PRODUCT_COL_LABELS = ['نام', 'عیار', 'آخرین سند', 'وضعیت'] as const;
registerTableColumns('tahesab.customers', [...CUSTOMER_COL_LABELS]);
registerTableColumns('tahesab.products', [...PRODUCT_COL_LABELS]);
const customerTableCols = useTableColumns(() => 'tahesab.customers');
const productTableCols = useTableColumns(() => 'tahesab.products');
const syncTablePageSize = ref(50);
const syncTablePage = ref(1);
const syncOnlyNew = ref(false);
const syncVisibleResults = computed(() =>
syncOnlyNew.value
? syncResults.value.filter((r) => !r.alreadyLinked)
: syncResults.value,
);
const syncTableTotalPages = computed(() =>
Math.max(1, Math.ceil(syncVisibleResults.value.length / syncTablePageSize.value)),
);
const syncPagedResults = computed(() => {
const start = (syncTablePage.value - 1) * syncTablePageSize.value;
return syncVisibleResults.value.slice(start, start + syncTablePageSize.value);
});
watch([syncOnlyNew, syncTablePageSize], () => {
syncTablePage.value = 1;
});
watch(syncTableTotalPages, (total) => {
if (syncTablePage.value > total) syncTablePage.value = total;
});
const productSync = reactive({
connectionId: '',
q: '',
});
const productSyncBusy = ref(false);
type ProductSyncResult = {
name: string;
ayar: number | null;
vaznSabet: number | null;
lastSanad: string;
alreadyImported?: boolean;
productId?: string | null;
productName?: string | null;
};
const productSyncResults = ref<ProductSyncResult[]>([]);
const productCategoryLabel = ref('کارساخته');
function pendingImportCodes() {
return syncResults.value
.filter((r) => r.moshtariCode != null && !r.alreadyLinked)
.map((r) => r.moshtariCode as number);
}
function pendingProductNames() {
return productSyncResults.value
.filter((r) => !r.alreadyImported)
.map((r) => r.name);
}
function apiErr(e: unknown, fallback: string) {
if (!axios.isAxiosError(e)) return fallback;
const msg = (e.response?.data as { message?: string | string[] })?.message;
if (Array.isArray(msg)) return msg.join('، ') || fallback;
if (typeof msg === 'string' && msg.trim()) return msg;
return fallback;
}
function resetForm() {
editingId.value = null;
form.label = '';
form.baseUrl = '';
form.dbName = 'DB';
form.token = '';
form.isDefault = items.value.length === 0;
form.allowInsecureTls = false;
form.enabled = true;
}
function looksLikePrivateHttps(url: string) {
return /^https:\/\/(\d{1,3}\.){3}\d{1,3}(:\d+)?/i.test(url.trim());
}
function isTlsError(text: string | null | undefined) {
if (!text) return false;
return /self-signed|certificate|UNABLE_TO_VERIFY|CERT_|گواهی/i.test(text);
}
function onBaseUrlBlur() {
if (!editingId.value && looksLikePrivateHttps(form.baseUrl)) {
form.allowInsecureTls = true;
}
}
function startEdit(row: TahesabConnectionDto) {
editingId.value = row.id;
form.label = row.label;
form.baseUrl = row.baseUrl;
form.dbName = row.dbName;
form.token = '';
form.isDefault = row.isDefault;
form.allowInsecureTls = row.allowInsecureTls;
form.enabled = row.enabled;
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<TahesabConnectionDto[]>(
'/integrations/tahesab/connections',
);
items.value = data;
if (!editingId.value) form.isDefault = data.length === 0;
if (!sync.connectionId && data[0]) sync.connectionId = data[0].id;
if (!productSync.connectionId && data[0]) productSync.connectionId = data[0].id;
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'بارگذاری اتصالات ناموفق بود.',
)
: 'بارگذاری اتصالات ناموفق بود.';
} finally {
loading.value = false;
}
}
async function save() {
saving.value = true;
error.value = '';
ok.value = '';
try {
if (editingId.value) {
const body: UpdateTahesabConnectionRequest = {
label: form.label.trim(),
baseUrl: form.baseUrl.trim(),
dbName: form.dbName.trim(),
isDefault: form.isDefault,
allowInsecureTls: form.allowInsecureTls,
enabled: form.enabled,
};
if (form.token.trim()) body.token = form.token.trim();
await api.patch(
`/integrations/tahesab/connections/${editingId.value}`,
body,
);
ok.value = 'اتصال به‌روزرسانی شد.';
} else {
if (!form.token.trim()) {
error.value = 'توکن الزامی است.';
return;
}
const body: CreateTahesabConnectionRequest = {
label: form.label.trim(),
baseUrl: form.baseUrl.trim(),
dbName: form.dbName.trim(),
token: form.token.trim(),
isDefault: form.isDefault,
allowInsecureTls: form.allowInsecureTls,
enabled: form.enabled,
};
await api.post('/integrations/tahesab/connections', body);
ok.value = 'اتصال افزوده شد.';
}
resetForm();
await load();
} catch (e) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
error.value = Array.isArray(msg) ? msg.join('، ') : (msg ?? 'ذخیره ناموفق بود');
} else {
error.value = 'ذخیره ناموفق بود';
}
} finally {
saving.value = false;
}
}
async function testConn(id: string) {
error.value = '';
ok.value = '';
try {
const { data } = await api.post<{ ok: boolean; error?: string }>(
`/integrations/tahesab/connections/${id}/test`,
);
if (data.ok) ok.value = 'اتصال سالم است.';
else {
error.value = data.error ?? 'تست اتصال ناموفق بود.';
if (isTlsError(data.error)) {
error.value +=
' → دکمه «فعال‌سازی SSL خودامضا» را بزنید یا در ویرایش اتصال تیک آن را بگذارید.';
}
}
await load();
} catch (e) {
error.value = apiErr(e, 'تست ناموفق');
}
}
async function enableInsecureTls(id: string) {
error.value = '';
ok.value = '';
try {
await api.patch(`/integrations/tahesab/connections/${id}`, {
allowInsecureTls: true,
});
ok.value = 'پذیرش گواهی خودامضا فعال شد. در حال تست…';
await load();
await testConn(id);
} catch (e) {
error.value = apiErr(e, 'فعال‌سازی ناموفق بود');
}
}
async function removeConn(id: string) {
if (!confirm('این اتصال حذف شود؟ لینک مشتریان مرتبط هم پاک می‌شود.')) return;
error.value = '';
try {
await api.delete(`/integrations/tahesab/connections/${id}`);
ok.value = 'اتصال حذف شد.';
if (editingId.value === id) resetForm();
await load();
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'حذف ناموفق')
: 'حذف ناموفق';
}
}
type SyncSearchResponse = { results: SyncResult[] };
async function fetchAllCustomers(): Promise<SyncResult[]> {
const all: SyncResult[] = [];
let page = 1;
let emptyStreak = 0;
importOverlay.open = true;
importOverlay.progress = null;
try {
while (emptyStreak < LIST_ALL_EMPTY_STOP) {
importOverlay.message = `در حال خواندن مشتریان از ته‌حساب… ${toFaDigits(all.length)} مشتری`;
const { data } = await api.post<SyncSearchResponse>(
'/integrations/tahesab/sync/search',
{
connectionId: sync.connectionId,
listAll: true,
page,
pageSize: LIST_ALL_CODE_PAGE,
},
{ timeout: 90_000 },
);
const rows = data.results ?? [];
if (rows.length) {
all.push(...rows);
emptyStreak = 0;
} else {
emptyStreak += 1;
}
page += 1;
}
} finally {
importOverlay.open = false;
}
return all;
}
async function searchTahesab(mode: 'range' | 'filter') {
error.value = '';
ok.value = '';
if (!sync.connectionId) {
error.value = 'ابتدا یک اتصال انتخاب کنید.';
return;
}
syncBusy.value = true;
try {
const body: Record<string, unknown> = { connectionId: sync.connectionId };
let listAll = false;
if (mode === 'range') {
const fromRaw = String(sync.fromCode ?? '').trim();
const toRaw = String(sync.toCode ?? '').trim();
if (!fromRaw && !toRaw) {
listAll = true;
} else {
const fromCode = fromRaw ? Number(fromRaw) : 1;
const toCode = toRaw ? Number(toRaw) : fromCode + 1999;
if (Number.isNaN(fromCode) || Number.isNaN(toCode) || fromCode < 1 || toCode < fromCode) {
error.value = 'بازه کد مشتری نامعتبر است.';
return;
}
2026-10-03 15:28:08 +03:30
if (toCode - fromCode > 2000) {
error.value = 'حداکثر طول بازه در هر درخواست ۲۰۰۰ کد است. برای همه، از و تا را خالی بگذارید.';
return;
}
body.fromCode = fromCode;
body.toCode = toCode;
}
} else if (sync.moshtariCode !== '' && sync.moshtariCode != null) {
body.moshtariCode = Number(sync.moshtariCode);
} else if (sync.phone.trim()) {
body.phone = sync.phone.trim();
} else if (sync.name.trim()) {
body.name = sync.name.trim();
} else {
error.value = 'موبایل، نام، کد مشتری یا بازهٔ کد را وارد کنید.';
return;
}
if (listAll) {
syncResults.value = await fetchAllCustomers();
} else {
const { data } = await api.post<SyncSearchResponse>(
'/integrations/tahesab/sync/search',
body,
{ timeout: 60_000 },
);
syncResults.value = data.results ?? [];
}
syncTablePage.value = 1;
if (!syncResults.value.length) {
ok.value = 'نتیجه‌ای یافت نشد.';
} else {
const linked = syncResults.value.filter((r) => r.alreadyLinked).length;
const pending = syncResults.value.length - linked;
ok.value =
`${toFaDigits(syncResults.value.length)} مشتری پیدا شد` +
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده`;
}
} catch (e) {
error.value = apiErr(e, 'جستجو ناموفق');
} finally {
syncBusy.value = false;
}
}
function onSyncTablePageChange(page: number) {
syncTablePage.value = page;
}
async function importOne(moshtariCode: number) {
error.value = '';
ok.value = '';
try {
syncBusy.value = true;
const { data } = await api.post<{ personId: string }>(
'/integrations/tahesab/sync/import',
{ connectionId: sync.connectionId, moshtariCode },
);
ok.value = `وارد شد — در مخاطبین با شناسه ${data.personId}`;
const row = syncResults.value.find((r) => r.moshtariCode === moshtariCode);
if (row) {
row.alreadyLinked = true;
row.personId = data.personId;
}
} catch (e) {
error.value = apiErr(e, 'وارد کردن ناموفق');
} finally {
syncBusy.value = false;
}
}
async function importBulk() {
error.value = '';
ok.value = '';
if (!sync.connectionId) {
error.value = 'ابتدا اتصال را انتخاب کنید.';
return;
}
const codes = pendingImportCodes();
if (!codes.length) {
error.value = 'مشتری جدیدی در نتایج برای وارد کردن نیست (همه وارد شده‌اند یا لیست خالی است).';
return;
}
if (
!confirm(
`${codes.length} مشتری جدید از ته‌حساب به‌عنوان شخص در ${brand.nameFa} ساخته و لینک می‌شوند. ادامه؟`,
)
) {
return;
}
syncBusy.value = true;
importOverlay.open = true;
importOverlay.progress = 0;
importOverlay.message = 'در حال آماده‌سازی فهرست مشتریان…';
const totals = { imported: 0, skipped: 0, failed: 0 };
let firstError = '';
try {
const total = codes.length;
for (let i = 0; i < total; i += IMPORT_CHUNK) {
const chunk = codes.slice(i, i + IMPORT_CHUNK);
importOverlay.message = `در حال وارد کردن مشتریان… ${toFaDigits(Math.min(i + chunk.length, total))} از ${toFaDigits(total)}`;
try {
const { data } = await api.post<{
imported: number;
skipped: number;
failed: number;
items?: Array<{ moshtariCode: number; ok: boolean; personId?: string; error?: string }>;
}>(
'/integrations/tahesab/sync/import-bulk',
{ connectionId: sync.connectionId, moshtariCodes: chunk },
{ timeout: 120_000 },
);
totals.imported += data.imported;
totals.skipped += data.skipped;
totals.failed += data.failed;
for (const item of data.items ?? []) {
if (!item.ok) {
if (!firstError && item.error) firstError = item.error;
continue;
}
const row = syncResults.value.find((r) => r.moshtariCode === item.moshtariCode);
if (row) {
row.alreadyLinked = true;
if (item.personId) row.personId = item.personId;
}
}
} catch (e) {
totals.failed += chunk.length;
if (!firstError) firstError = apiErr(e, 'خطا در ارسال');
}
importOverlay.progress = total ? ((i + chunk.length) / total) * 100 : 100;
}
ok.value = `وارد شد: ${toFaDigits(totals.imported)} · قبلاً بود: ${toFaDigits(totals.skipped)} · ناموفق: ${toFaDigits(totals.failed)}`;
if (firstError) error.value = `برخی موارد وارد نشدند: ${firstError}`;
} catch (e) {
error.value = apiErr(e, 'وارد کردن دسته‌ای ناموفق');
} finally {
importOverlay.open = false;
importOverlay.progress = null;
syncBusy.value = false;
}
}
/** همهٔ بازه‌های کد خوانده می‌شود و گروه ته‌حساب روی مشتری‌های لینک‌شده نشانده می‌شود */
async function syncGroups() {
error.value = '';
ok.value = '';
if (!sync.connectionId) {
error.value = 'ابتدا اتصال را انتخاب کنید.';
return;
}
syncBusy.value = true;
importOverlay.open = true;
importOverlay.progress = null;
const totals = { rows: 0, linked: 0, updated: 0 };
try {
let page = 1;
let emptyStreak = 0;
while (emptyStreak < LIST_ALL_EMPTY_STOP) {
importOverlay.message = `در حال همگام‌سازی گروه‌ها… ${toFaDigits(totals.rows)} مشتری بررسی شد · ${toFaDigits(totals.updated)} تغییر`;
const { data } = await api.post<{ rows: number; linked: number; updated: number }>(
'/integrations/tahesab/sync/groups',
{ connectionId: sync.connectionId, page, pageSize: LIST_ALL_CODE_PAGE },
{ timeout: 120_000 },
);
totals.rows += data.rows;
totals.linked += data.linked;
totals.updated += data.updated;
emptyStreak = data.rows ? 0 : emptyStreak + 1;
page += 1;
}
ok.value = `گروه‌ها همگام شد: ${toFaDigits(totals.linked)} مشتری لینک‌شده بررسی شد · گروه ${toFaDigits(totals.updated)} نفر به‌روز شد.`;
} catch (e) {
error.value = apiErr(e, 'همگام‌سازی گروه‌ها ناموفق بود');
} finally {
importOverlay.open = false;
syncBusy.value = false;
}
}
type ExportItem = {
personId: string;
name: string;
status: 'matched' | 'created' | 'ambiguous' | 'skipped' | 'error';
moshtariCode?: number;
error?: string;
};
const EXPORT_CHUNK = 10;
const exportIssues = ref<ExportItem[]>([]);
/** شخص‌های لینک‌نشده: اول تطبیق، بعد ساخت در ته‌حساب (بدون ساخت تکراری) */
async function exportUnlinked() {
error.value = '';
ok.value = '';
exportIssues.value = [];
if (!sync.connectionId) {
error.value = 'ابتدا اتصال را انتخاب کنید.';
return;
}
syncBusy.value = true;
try {
const { data: unlinked } = await api.get<{ ids: string[]; total: number }>(
'/integrations/tahesab/sync/unlinked-people',
{ params: { connectionId: sync.connectionId } },
);
if (!unlinked.total) {
ok.value = 'همهٔ اشخاص به ته‌حساب لینک هستند.';
return;
}
if (
!confirm(
`${toFaDigits(unlinked.total)} شخص به ته‌حساب لینک نیستند.\n` +
'برای هر نفر اول با موبایل/نام در ته‌حساب جستجو می‌شود: اگر دقیقاً یک نفر پیدا شد فقط لینک می‌شود، ' +
'اگر چند نفر پیدا شد رد می‌شود تا دستی بررسی کنید، و اگر پیدا نشد در ته‌حساب ساخته می‌شود. ادامه؟',
)
) {
return;
}
importOverlay.open = true;
importOverlay.progress = 0;
const totals = { matched: 0, created: 0, ambiguous: 0, skipped: 0, failed: 0 };
const ids = unlinked.ids;
for (let i = 0; i < ids.length; i += EXPORT_CHUNK) {
const chunk = ids.slice(i, i + EXPORT_CHUNK);
importOverlay.message = `در حال ثبت در ته‌حساب… ${toFaDigits(Math.min(i + chunk.length, ids.length))} از ${toFaDigits(ids.length)}`;
try {
const { data } = await api.post<typeof totals & { items: ExportItem[] }>(
'/integrations/tahesab/sync/export-people',
{ connectionId: sync.connectionId, personIds: chunk },
{ timeout: 180_000 },
);
totals.matched += data.matched;
totals.created += data.created;
totals.ambiguous += data.ambiguous;
totals.skipped += data.skipped;
totals.failed += data.failed;
exportIssues.value.push(
...data.items.filter((it) => it.status === 'ambiguous' || it.status === 'error'),
);
} catch (e) {
totals.failed += chunk.length;
exportIssues.value.push(
...chunk.map((personId) => ({
personId,
name: '',
status: 'error' as const,
error: apiErr(e, 'خطا در ارسال'),
})),
);
}
importOverlay.progress = ((i + chunk.length) / ids.length) * 100;
}
ok.value =
`ثبت در ته‌حساب تمام شد: لینک با مشتری موجود ${toFaDigits(totals.matched)} · ` +
`ساخته‌شده ${toFaDigits(totals.created)} · چند نتیجه (نیاز به بررسی) ${toFaDigits(totals.ambiguous)} · ` +
`ناموفق ${toFaDigits(totals.failed)}`;
} catch (e) {
error.value = apiErr(e, 'ثبت گروهی در ته‌حساب ناموفق بود');
} finally {
importOverlay.open = false;
importOverlay.progress = null;
syncBusy.value = false;
}
}
async function searchProducts() {
error.value = '';
ok.value = '';
if (!productSync.connectionId) {
error.value = 'ابتدا اتصال را برای کارساخته انتخاب کنید.';
return;
}
try {
productSyncBusy.value = true;
const body: Record<string, unknown> = {
connectionId: productSync.connectionId,
};
if (productSync.q.trim()) body.q = productSync.q.trim();
const { data } = await api.post<{
results: ProductSyncResult[];
categoryLabel?: string;
}>('/integrations/tahesab/sync/products/search', body, { timeout: 60_000 });
productSyncResults.value = data.results ?? [];
if (data.categoryLabel) productCategoryLabel.value = data.categoryLabel;
if (!productSyncResults.value.length) {
ok.value = 'کارساخته‌ای یافت نشد.';
} else {
const linked = productSyncResults.value.filter((r) => r.alreadyImported).length;
ok.value =
`${productSyncResults.value.length} ${productCategoryLabel.value} پیدا شد` +
(linked ? ` (${linked} قبلاً وارد شده)` : '');
}
} catch (e) {
error.value = apiErr(e, 'دریافت لیست کارساخته ناموفق');
} finally {
productSyncBusy.value = false;
}
}
async function importProductOne(name: string) {
error.value = '';
ok.value = '';
try {
productSyncBusy.value = true;
const { data } = await api.post<{ productId: string }>(
'/integrations/tahesab/sync/products/import',
{ connectionId: productSync.connectionId, name },
);
ok.value = `وارد شد — در محصولات با شناسه ${data.productId}`;
const row = productSyncResults.value.find((r) => r.name === name);
if (row) {
row.alreadyImported = true;
row.productId = data.productId;
}
} catch (e) {
error.value = apiErr(e, 'وارد کردن محصول ناموفق');
} finally {
productSyncBusy.value = false;
}
}
async function importProductsBulk(mode: 'pending' | 'all') {
error.value = '';
ok.value = '';
if (!productSync.connectionId) {
error.value = 'ابتدا اتصال را انتخاب کنید.';
return;
}
const body: Record<string, unknown> = { connectionId: productSync.connectionId };
if (mode === 'pending') {
const names = pendingProductNames();
if (!names.length) {
error.value = `${productCategoryLabel.value} جدیدی برای وارد کردن نیست.`;
return;
}
if (
!confirm(
`${names.length} ${productCategoryLabel.value} به‌عنوان محصول در ${brand.nameFa} ساخته می‌شود. ادامه؟`,
)
) {
return;
}
body.names = names;
} else if (
!confirm(
`همهٔ نام‌های ${productCategoryLabel.value} از ته‌حساب وارد محصولات ${brand.nameFa} می‌شوند. ادامه؟`,
)
) {
return;
}
try {
productSyncBusy.value = true;
const { data } = await api.post<{
imported: number;
skipped: number;
failed: number;
}>('/integrations/tahesab/sync/products/import-bulk', body, { timeout: 120_000 });
ok.value = `وارد شد: ${data.imported} · قبلاً بود: ${data.skipped} · ناموفق: ${data.failed}`;
await searchProducts();
} catch (e) {
error.value = apiErr(e, 'وارد کردن دسته‌ای محصولات ناموفق');
} finally {
productSyncBusy.value = false;
}
}
const connectionOptions = computed(() =>
items.value.map((row) => ({ value: row.id, label: `${row.label} (${row.dbName})` })),
);
const customerColumns = computed<TableColumnsType<SyncResult>>(() => {
const all: TableColumnsType<SyncResult> = [
{ title: 'کد مشتری', key: 'کد مشتری' },
{ title: 'نام و نام خانوادگی', key: 'نام و نام خانوادگی' },
{ title: 'تلفن', key: 'تلفن' },
{ title: 'وضعیت لینک', key: 'وضعیت لینک' },
{ title: 'عملیات', key: 'عملیات' },
];
return all.filter((col) => {
const key = String(col.key ?? '');
if (key === 'عملیات') return true;
return customerTableCols.isVisible(key);
});
});
const productColumns = computed<TableColumnsType<ProductSyncResult>>(() => {
const all: TableColumnsType<ProductSyncResult> = [
{ title: 'نام', key: 'نام' },
{ title: 'عیار', key: 'عیار' },
{ title: 'آخرین سند', key: 'آخرین سند' },
{ title: 'وضعیت', key: 'وضعیت' },
{ title: 'عملیات', key: 'عملیات' },
];
return all.filter((col) => {
const key = String(col.key ?? '');
if (key === 'عملیات') return true;
return productTableCols.isVisible(key);
});
});
onMounted(load);
</script>
<template>
<a-flex vertical :gap="16">
<a-typography-title :level="3" :style="{ margin: 0 }">
اتصال نرم‌افزار مالی ته‌حساب
</a-typography-title>
<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-alert
v-if="items.some((r) => !r.allowInsecureTls && isTlsError(r.lastError))"
type="warning"
show-icon
>
<template #message>
اتصال شما به‌خاطر گواهی SSL خودامضا قطع است. روی همان کارت اتصال،
<strong>فعال‌سازی SSL خودامضا</strong> را بزنید؛ بعد دوباره «نمایش مشتریان» را امتحان کنید.
</template>
</a-alert>
<a-card v-if="!loading && items.length" title="اتصالات تعریف‌شده" :bordered="false">
<a-flex vertical :gap="12">
<a-card v-for="row in items" :key="row.id" type="inner">
<a-row :gutter="[16, 12]" align="top">
<a-col :xs="24" :lg="14">
<a-flex vertical :gap="4">
<a-space wrap>
<a-typography-text strong>{{ row.label }}</a-typography-text>
<a-tag v-if="row.isDefault" color="blue" :bordered="false">پیش‌فرض</a-tag>
<a-tag :color="row.enabled ? 'success' : 'default'" :bordered="false">
{{ row.enabled ? 'فعال' : 'غیرفعال' }}
</a-tag>
<a-tag v-if="row.allowInsecureTls" color="warning" :bordered="false">
SSL خودامضا
</a-tag>
</a-space>
<a-typography-text type="secondary" code dir="ltr">{{ row.baseUrl }}</a-typography-text>
<a-typography-text type="secondary">
بانک: {{ row.dbName }} · توکن: {{ row.tokenMasked }}
</a-typography-text>
<a-typography-text
v-if="row.lastHealthAt"
:type="row.lastHealthOk ? 'success' : 'danger'"
>
آخرین وضعیت: {{ row.lastHealthOk ? 'موفق' : 'ناموفق' }}<template
v-if="row.lastError"
> — {{ row.lastError }}</template>
</a-typography-text>
</a-flex>
</a-col>
<a-col :xs="24" :lg="10">
<a-flex justify="flex-end" wrap="wrap" :gap="8">
<a-button
v-if="!row.allowInsecureTls && isTlsError(row.lastError)"
@click="enableInsecureTls(row.id)"
>
<template #icon><SafetyCertificateOutlined /></template>
فعال‌سازی SSL خودامضا
</a-button>
<a-button type="text" @click="startEdit(row)">
<template #icon><EditOutlined /></template>
ویرایش
</a-button>
<a-button type="text" @click="testConn(row.id)">
<template #icon><ReloadOutlined /></template>
تست اتصال
</a-button>
<a-button danger @click="removeConn(row.id)">
<template #icon><DeleteOutlined /></template>
حذف
</a-button>
</a-flex>
</a-col>
</a-row>
</a-card>
</a-flex>
</a-card>
<a-card :title="editingId ? 'ویرایش اتصال ته‌حساب' : 'افزودن اتصال جدید ته‌حساب'" :bordered="false">
<a-form :model="form" layout="vertical" @finish="save">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان اتصال"
name="label"
:rules="[{ required: true, message: 'عنوان اتصال را وارد کنید.' }]"
>
<a-input
v-model:value="form.label"
:maxlength="120"
placeholder="مثلاً شعبه مرکزی، دیتابیس مالی"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="آدرس وب‌سرویس (Base URL)"
name="baseUrl"
extra="آدرس سرور وب‌سرویس ته‌حساب"
:rules="[{ required: true, message: 'آدرس وب‌سرویس را وارد کنید.' }]"
>
<a-input
v-model:value="form.baseUrl"
dir="ltr"
placeholder="https://IP:8081 یا https://api.tahesab.ir"
@blur="onBaseUrlBlur"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="نام دیتابیس (DBName)"
name="dbName"
:rules="[{ required: true, message: 'نام دیتابیس را وارد کنید.' }]"
>
<a-input v-model:value="form.dbName" dir="ltr" placeholder="DB یا TahesabDB" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="توکن دسترسی (Bearer Token)"
name="token"
:extra="editingId ? 'خالی بگذارید تا توکن فعلی تغییر نکند.' : 'توکن احراز هویت وب‌سرویس'"
:rules="[{ required: !editingId, message: 'توکن الزامی است.' }]"
>
<a-input-password
v-model:value="form.token"
dir="ltr"
autocomplete="new-password"
placeholder="توکن امنیتی..."
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-flex vertical :gap="8" :style="{ marginBottom: '16px' }">
<a-checkbox v-model:checked="form.isDefault">اتصال پیش‌فرض سازمان</a-checkbox>
<a-checkbox v-model:checked="form.enabled">اتصال فعال باشد</a-checkbox>
<a-alert type="warning" :show-icon="false">
<template #message>
<a-checkbox v-model:checked="form.allowInsecureTls">
پذیرش گواهی SSL خودامضا (برای IP محلی یا پورت داخلی بدون گواهی رسمی)
</a-checkbox>
</template>
</a-alert>
</a-flex>
</a-col>
<a-col :span="24">
<a-space>
<a-button type="primary" html-type="submit" :loading="saving">
{{ editingId ? 'به‌روزرسانی اتصال' : 'افزودن اتصال' }}
</a-button>
<a-button v-if="editingId" @click="resetForm">انصراف</a-button>
</a-space>
</a-col>
</a-row>
</a-form>
</a-card>
<a-card title="وارد کردن و همگام‌سازی مشتریان از ته‌حساب" :bordered="false">
<a-flex vertical :gap="16">
<a-typography-paragraph type="secondary" :style="{ marginBottom: 0 }">
با استفاده از این بخش می‌توانید اشخاص و طرف‌حساب‌های ته‌حساب را به عنوان مخاطب وارد نرم‌افزار کرده و سوابق مالی آن‌ها را پیوند دهید.
</a-typography-paragraph>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="اتصال مورد نظر جهت همگام‌سازی" required>
<a-select
:value="sync.connectionId || undefined"
:options="connectionOptions"
placeholder="انتخاب اتصال"
@update:value="(v) => (sync.connectionId = (v as string | undefined) ?? '')"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-card type="inner" title="۱) وارد کردن دسته‌ای با بازه کد مشتری">
<a-flex vertical :gap="12">
<a-typography-text type="secondary">
اگر «از» و «تا» خالی باشد، همهٔ مشتریان ته‌حساب خوانده و در جدول زیر نمایش داده می‌شوند. بازهٔ دستی حداکثر ۲۰۰۰ کد است.
</a-typography-text>
<a-row :gutter="[16, 12]">
<a-col :xs="24" :md="12">
<a-input
v-model:value="sync.fromCode"
type="number"
min="1"
dir="ltr"
placeholder="از کد (اختیاری)"
/>
</a-col>
<a-col :xs="24" :md="12">
<a-input
v-model:value="sync.toCode"
type="number"
min="1"
dir="ltr"
placeholder="تا کد (اختیاری)"
/>
</a-col>
</a-row>
<a-space wrap>
<a-button
:disabled="!sync.connectionId || syncBusy"
@click="searchTahesab('range')"
>
نمایش مشتریان
</a-button>
<a-button
type="primary"
:disabled="!sync.connectionId || syncBusy || !pendingImportCodes().length"
@click="importBulk"
>
وارد کردن همهٔ واردنشده‌ها ({{ toFaDigits(pendingImportCodes().length) }})
</a-button>
</a-space>
<a-checkbox v-model:checked="syncOnlyNew">فقط مشتریانی که وارد نشده‌اند</a-checkbox>
</a-flex>
</a-card>
<a-card type="inner" title="۲) جستجوی تکی یا فیلتر مشخصات">
<a-flex vertical :gap="12">
<a-row :gutter="[16, 12]">
<a-col :xs="24" :md="8">
<a-input v-model:value="sync.phone" dir="ltr" placeholder="موبایل یا تلفن..." />
</a-col>
<a-col :xs="24" :md="8">
<a-input v-model:value="sync.name" placeholder="نام یا عنوان مشتری..." />
</a-col>
<a-col :xs="24" :md="8">
<a-input
v-model:value="sync.moshtariCode"
type="number"
dir="ltr"
placeholder="کد مشتری ته‌حساب..."
/>
</a-col>
</a-row>
<a-space wrap>
<a-button
:disabled="!sync.connectionId || syncBusy"
@click="searchTahesab('filter')"
>
جستجو در ته‌حساب
</a-button>
<a-button
type="primary"
:disabled="!sync.connectionId || syncBusy || !pendingImportCodes().length"
@click="importBulk"
>
وارد کردن نتایج جدید ({{ toFaDigits(pendingImportCodes().length) }})
</a-button>
</a-space>
</a-flex>
</a-card>
<a-card type="inner" title="۳) گروه‌ها و ثبت مشتری‌های منتکت در ته‌حساب">
<a-flex vertical :gap="12">
<a-typography-text type="secondary">
«همگام‌سازی گروه‌ها» گروه هر مشتری لینک‌شده را از ته‌حساب می‌خواند؛ فقط گروهِ آمده از ته‌حساب عوض
می‌شود و گروه‌هایی که دستی داده‌اید می‌مانند.
«ثبت لینک‌نشده‌ها» برای هر شخصی که به ته‌حساب لینک نیست اول تطبیق (موبایل، بعد نام) را امتحان
می‌کند تا مشتری تکراری ساخته نشود؛ اگر پیدا نشد با گروه، آدرس، کد ملی و تاریخ تولد ساخته می‌شود.
</a-typography-text>
<a-space wrap>
<a-button :disabled="!sync.connectionId || syncBusy" @click="syncGroups">
همگام‌سازی گروه‌ها از ته‌حساب
</a-button>
<a-button
type="primary"
:disabled="!sync.connectionId || syncBusy"
@click="exportUnlinked"
>
ثبت مشتری‌های لینک‌نشده در ته‌حساب
</a-button>
</a-space>
<a-alert v-if="exportIssues.length" type="warning" show-icon>
<template #message>
این اشخاص ثبت نشدند ({{ toFaDigits(exportIssues.length) }}). از پرونده، بخش «ته‌حساب و دارایی»
دستی لینک یا ثبت کنید:
</template>
<template #description>
<a-list :data-source="exportIssues" :style="{ maxHeight: '14rem', overflowY: 'auto' }">
<template #renderItem="{ item }">
<a-list-item>
<RouterLink :to="{ name: 'person-detail', params: { id: item.personId } }">
{{ item.name || 'بدون نام' }}
</RouterLink>
&nbsp;—&nbsp;
{{ item.status === 'ambiguous' ? 'چند مشتری مشابه در ته‌حساب پیدا شد' : item.error || 'خطا' }}
</a-list-item>
</template>
</a-list>
</template>
</a-alert>
</a-flex>
</a-card>
<a-card v-if="syncResults.length" type="inner">
<template #title>
نتایج جستجو ({{ syncVisibleResults.length }}<template v-if="syncOnlyNew"> از {{ syncResults.length }}</template>)
</template>
<a-flex vertical :gap="12">
<a-flex justify="flex-end">
<TableColumnsMenu table-key="tahesab.customers" align="end" />
</a-flex>
<a-table
:columns="customerColumns"
:data-source="syncPagedResults"
:pagination="false"
:row-key="(r: SyncResult) => String(r.moshtariCode)"
:scroll="{ x: 640 }"
>
<template #emptyText>همهٔ مشتریان این نتایج قبلاً وارد شده‌اند.</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'کد مشتری'">
{{ (record as SyncResult).moshtariCode }}
</template>
<template v-else-if="column.key === 'نام و نام خانوادگی'">
<a-typography-text strong>{{ (record as SyncResult).name || 'بدون نام' }}</a-typography-text>
</template>
<template v-else-if="column.key === 'تلفن'">
<span dir="ltr">{{ (record as SyncResult).tel }}</span>
</template>
<template v-else-if="column.key === 'وضعیت لینک'">
<a-tag v-if="(record as SyncResult).alreadyLinked" color="success" :bordered="false">
لینک شده{{ (record as SyncResult).personName ? ` (${(record as SyncResult).personName})` : '' }}
</a-tag>
<a-tag v-else color="default" :bordered="false">آماده ورود</a-tag>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-button
v-if="!(record as SyncResult).alreadyLinked"
type="primary"
:disabled="!(record as SyncResult).moshtariCode || syncBusy"
@click="importOne((record as SyncResult).moshtariCode!)"
>
وارد کردن
</a-button>
<RouterLink
v-else-if="(record as SyncResult).personId"
:to="{ name: 'person-detail', params: { id: (record as SyncResult).personId } }"
>
<a-button type="text">مشاهده شخص</a-button>
</RouterLink>
</template>
</template>
</a-table>
<a-flex v-if="syncVisibleResults.length > SYNC_TABLE_PAGE_SIZES[0]" justify="flex-end">
<a-pagination
:current="syncTablePage"
:total="syncVisibleResults.length"
:page-size="syncTablePageSize"
:page-size-options="SYNC_TABLE_PAGE_SIZES.map(String)"
show-size-changer
@change="onSyncTablePageChange"
@update:page-size="(n: number) => (syncTablePageSize = n)"
/>
</a-flex>
</a-flex>
</a-card>
</a-flex>
</a-card>
<a-card title="وارد کردن کارساخته از ته‌حساب به محصولات" :bordered="false">
<a-flex vertical :gap="16">
<a-typography-paragraph type="secondary" :style="{ marginBottom: 0 }">
نام‌های کارساختهٔ ته‌حساب (لیست <code dir="ltr">DoListNameKarsakhte</code>)
را به‌عنوان محصول با دستهٔ «{{ productCategoryLabel }}» وارد کنید.
موجودی همچنان از ته‌حساب است؛ اینجا فقط کاتالوگ برای معامله/فاکتور ساخته می‌شود.
</a-typography-paragraph>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="اتصال مورد نظر" required>
<a-select
:value="productSync.connectionId || undefined"
:options="connectionOptions"
placeholder="انتخاب اتصال"
@update:value="(v) => (productSync.connectionId = (v as string | undefined) ?? '')"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-card type="inner" title="لیست و جستجو">
<a-row :gutter="[16, 12]" align="middle">
<a-col :xs="24" :md="8">
<a-input
v-model:value="productSync.q"
placeholder="جستجو نام یا عیار…"
@press-enter="searchProducts"
/>
</a-col>
<a-col :xs="24" :md="16">
<a-space wrap>
<a-button
:disabled="!productSync.connectionId || productSyncBusy"
@click="searchProducts"
>
دریافت لیست
</a-button>
<a-button
type="primary"
:disabled="!productSync.connectionId || productSyncBusy || !pendingProductNames().length"
@click="importProductsBulk('pending')"
>
ورود نتایج جدید ({{ pendingProductNames().length }})
</a-button>
<a-button
type="text"
:disabled="!productSync.connectionId || productSyncBusy"
@click="importProductsBulk('all')"
>
ورود همه
</a-button>
</a-space>
</a-col>
</a-row>
</a-card>
<a-card v-if="productSyncResults.length" type="inner">
<template #title>
نتایج ({{ productSyncResults.length }}) — دسته: {{ productCategoryLabel }}
</template>
<a-flex vertical :gap="12">
<a-flex justify="flex-end">
<TableColumnsMenu table-key="tahesab.products" align="end" />
</a-flex>
<a-table
:columns="productColumns"
:data-source="productSyncResults"
:pagination="false"
row-key="name"
:scroll="{ x: 640 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'نام'">
<a-typography-text strong>{{ (record as ProductSyncResult).name }}</a-typography-text>
</template>
<template v-else-if="column.key === 'عیار'">
<span dir="ltr">{{ (record as ProductSyncResult).ayar ?? '—' }}</span>
</template>
<template v-else-if="column.key === 'آخرین سند'">
{{ (record as ProductSyncResult).lastSanad || '—' }}
</template>
<template v-else-if="column.key === 'وضعیت'">
<a-tag v-if="(record as ProductSyncResult).alreadyImported" color="success" :bordered="false">
وارد شده{{ (record as ProductSyncResult).productName ? ` (${(record as ProductSyncResult).productName})` : '' }}
</a-tag>
<a-tag v-else color="default" :bordered="false">آماده ورود</a-tag>
</template>
<template v-else-if="column.key === 'عملیات'">
<a-button
v-if="!(record as ProductSyncResult).alreadyImported"
type="primary"
:disabled="productSyncBusy"
@click="importProductOne((record as ProductSyncResult).name)"
>
وارد کردن
</a-button>
<RouterLink
v-else-if="(record as ProductSyncResult).productId"
:to="{ name: 'product-edit', params: { id: (record as ProductSyncResult).productId } }"
>
<a-button type="text">مشاهده محصول</a-button>
</RouterLink>
</template>
</template>
</a-table>
</a-flex>
</a-card>
</a-flex>
</a-card>
<a-modal
:open="importOverlay.open"
:closable="false"
:mask-closable="false"
:keyboard="false"
:footer="null"
centered
>
<a-flex vertical align="center" :gap="16" :style="{ padding: '16px 0' }">
<a-typography-text>{{ importOverlay.message }}</a-typography-text>
<a-progress
v-if="importOverlay.progress != null"
:percent="Math.round(importOverlay.progress)"
:style="{ width: '100%' }"
/>
<a-spin v-else />
</a-flex>
</a-modal>
</a-flex>
</template>