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

1653 lines
63 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 { formatJalaliDateTime, 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 '@/icons/ant-bridge';
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;
duplicateOfCode?: number | null;
duplicatePersonId?: string | null;
duplicatePersonName?: 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 autoCount = ref('0');
const autoHours = ref<string[]>([]);
const autoSyncSaving = ref(false);
const AUTO_HOUR_PRESETS: Record<number, number[]> = {
1: [8],
2: [8, 14],
3: [8, 12, 16],
4: [8, 12, 16, 20],
5: [8, 11, 14, 17, 20],
6: [8, 10, 12, 14, 16, 20],
};
const selectedConnection = computed(() =>
items.value.find((row) => row.id === sync.connectionId),
);
function hourLabel(hour: number) {
return `${toFaDigits(String(hour).padStart(2, '0'))}:۰۰`;
}
const autoCountOptions = [
{ value: '0', label: 'خاموش' },
...Array.from({ length: 6 }, (_, index) => ({
value: String(index + 1),
label: `${toFaDigits(index + 1)} بار`,
})),
];
const hourOptions = Array.from({ length: 24 }, (_, hour) => ({
value: String(hour),
label: hourLabel(hour),
}));
function fillAutoSync() {
const hours = [...(selectedConnection.value?.customerSyncHours ?? [])]
.sort((a, b) => a - b)
.slice(0, 6);
autoCount.value = String(hours.length);
autoHours.value = hours.map(String);
}
function onAutoCount(value: string) {
const count = Math.min(6, Math.max(0, Number(value) || 0));
const preset = AUTO_HOUR_PRESETS[count] ?? [];
const next = autoHours.value.slice(0, count);
while (next.length < count) {
next.push(String(preset[next.length] ?? 8));
}
autoCount.value = String(count);
autoHours.value = next;
}
function setAutoHour(index: number, value: string) {
autoHours.value[index] = value;
}
async function saveAutoSync() {
if (!sync.connectionId) return;
const hours = autoHours.value.map((hour) => Number(hour));
if (hours.some((hour) => !Number.isInteger(hour) || hour < 0 || hour > 23)) {
error.value = 'ساعت باید بین ۰ و ۲۳ باشد.';
return;
}
if (new Set(hours).size !== hours.length) {
error.value = 'ساعت‌ها نباید تکراری باشند.';
return;
}
autoSyncSaving.value = true;
error.value = '';
ok.value = '';
try {
await api.patch(`/integrations/tahesab/connections/${sync.connectionId}`, {
customerSyncHours: hours,
});
ok.value = hours.length
? 'زمان‌بندی بروزرسانی ذخیره شد.'
: 'بروزرسانی خودکار خاموش شد.';
await load();
} catch (e) {
error.value = apiErr(e, 'ذخیره زمان‌بندی ناموفق بود');
} finally {
autoSyncSaving.value = false;
}
}
/** همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها وارد، لینک‌شده‌ها پروفایل‌شان به‌روز می‌شود */
async function syncCustomersNow() {
if (!sync.connectionId) {
error.value = 'اتصال را انتخاب کنید.';
return;
}
syncBusy.value = true;
importOverlay.open = true;
importOverlay.progress = null;
importOverlay.message =
'در حال همگام‌سازی همهٔ مشتریان… نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه به‌روز می‌شود.';
error.value = '';
ok.value = '';
try {
const { data } = await api.post<{
imported: number;
updated: number;
duplicate: number;
failed: number;
summary: string;
error: string | null;
}>('/integrations/tahesab/sync/customers-now', {
connectionId: sync.connectionId,
});
ok.value = data.summary;
if (data.error) error.value = data.error;
await load();
} catch (e) {
error.value = apiErr(e, 'همگام‌سازی مشتریان ناموفق بود');
} finally {
syncBusy.value = false;
importOverlay.open = false;
}
}
/** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شماره‌ها فقط رقم‌اند. */
function customerPhoneKey(value?: string | null): string {
const fa = '۰۱۲۳۴۵۶۷۸۹';
const ar = '٠١٢٣٤٥٦٧٨٩';
let digits = String(value ?? '')
.replace(/[۰-۹٠-٩]/g, (ch) => {
const faIndex = fa.indexOf(ch);
return String(faIndex >= 0 ? faIndex : ar.indexOf(ch));
})
.replace(/\D/g, '');
if (!digits) return '';
if (digits.startsWith('0098') && digits.length >= 14) digits = digits.slice(4);
else if (digits.startsWith('98') && digits.length >= 12) digits = digits.slice(2);
if (digits.length === 10 && digits.startsWith('9')) digits = `0${digits}`;
return digits;
}
const linkedPhoneOwners = computed(() => {
const owners = new Map<string, { code: number; personId: string | null; personName: string | null }>();
for (const row of syncResults.value) {
if (!row.alreadyLinked || row.moshtariCode == null) continue;
const key = customerPhoneKey(row.tel);
if (key && !owners.has(key)) {
owners.set(key, {
code: row.moshtariCode,
personId: row.personId ?? null,
personName: row.personName ?? null,
});
}
}
return owners;
});
function duplicateOwner(row: SyncResult) {
if (row.alreadyLinked || row.moshtariCode == null) return null;
if (row.duplicateOfCode != null) {
return {
code: row.duplicateOfCode,
personId: row.duplicatePersonId ?? null,
personName: row.duplicatePersonName ?? null,
};
}
const key = customerPhoneKey(row.tel);
if (!key) return null;
const owner = linkedPhoneOwners.value.get(key);
if (!owner || owner.code === row.moshtariCode) return null;
return owner;
}
const duplicateCustomerCount = computed(
() => syncResults.value.filter((row) => duplicateOwner(row)).length,
);
const syncVisibleResults = computed(() =>
syncOnlyNew.value
? syncResults.value.filter((row) => !row.alreadyLinked && !duplicateOwner(row))
: 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(() => sync.connectionId, () => fillAutoSync());
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 && !duplicateOwner(r))
.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;
fillAutoSync();
} 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 duplicate = syncResults.value.filter((r) => duplicateOwner(r)).length;
const pending = syncResults.value.length - linked - duplicate;
ok.value =
`${toFaDigits(syncResults.value.length)} مشتری پیدا شد` +
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده` +
(duplicate ? ` · ${toFaDigits(duplicate)} شماره تکراری` : '');
}
} 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: 'آدرس وب‌سرویس را وارد کنید.' }]"
>
فعال‌سازی SSL خودامضا
</UiButton>
<UiButton variant="ghost" size="sm" @click="startEdit(row)">
<template #icon>
<UiIcon name="pencil" />
</template>
ویرایش
</UiButton>
<UiButton variant="ghost" size="sm" @click="testConn(row.id)">
<template #icon>
<UiIcon name="refresh" />
</template>
تست اتصال
</UiButton>
<UiButton variant="danger" size="sm" @click="removeConn(row.id)">
<template #icon>
<UiIcon name="trash" />
</template>
حذف
</UiButton>
</div>
</div>
</div>
</UiCard>
<UiCard :title="editingId ? 'ویرایش اتصال ته‌حساب' : 'افزودن اتصال جدید ته‌حساب'" class="section-card">
<form class="crm-form" @submit.prevent="save">
<div class="crm-form-grid-2">
<UiField label="عنوان اتصال" required>
<UiInput v-model="form.label" required maxlength="120" placeholder="مثلاً شعبه مرکزی، دیتابیس مالی" />
</UiField>
<UiField label="آدرس وب‌سرویس (Base URL)" required hint="آدرس سرور وب‌سرویس ته‌حساب">
<UiInput
v-model="form.baseUrl"
required
dir="ltr"
placeholder="https://IP:8081 یا https://api.tahesab.ir"
@blur="onBaseUrlBlur"
/>
</UiField>
<UiField label="نام دیتابیس (DBName)" required>
<UiInput v-model="form.dbName" required dir="ltr" placeholder="DB یا TahesabDB" />
</UiField>
<UiField label="توکن دسترسی (Bearer Token)" :required="!editingId" :hint="editingId ? 'خالی بگذارید تا توکن فعلی تغییر نکند.' : 'توکن احراز هویت وب‌سرویس'">
<UiInput
v-model="form.token"
:required="!editingId"
type="password"
dir="ltr"
autocomplete="new-password"
placeholder="توکن امنیتی..."
/>
</UiField>
</div>
<div class="checkbox-group">
<label class="custom-check">
<input v-model="form.isDefault" type="checkbox" />
<span>اتصال پیش‌فرض سازمان</span>
</label>
<label class="custom-check">
<input v-model="form.enabled" type="checkbox" />
<span>اتصال فعال باشد</span>
</label>
<label class="custom-check highlight">
<input v-model="form.allowInsecureTls" type="checkbox" />
<span>پذیرش گواهی SSL خودامضا (برای IP محلی یا پورت داخلی بدون گواهی رسمی)</span>
</label>
</div>
<div class="form-actions-row">
<UiButton type="submit" :loading="saving">
{{ editingId ? 'به‌روزرسانی اتصال' : 'افزودن اتصال' }}
</UiButton>
<UiButton v-if="editingId" variant="ghost" type="button" @click="resetForm">
انصراف
</UiButton>
</div>
</form>
</UiCard>
<UiCard title="وارد کردن و همگام‌سازی مشتریان از ته‌حساب" class="section-card">
<p class="sync-desc">
با استفاده از این بخش می‌توانید اشخاص و طرف‌حساب‌های ته‌حساب را به عنوان مخاطب وارد نرم‌افزار کرده و سوابق مالی آن‌ها را پیوند دهید.
</p>
<div class="crm-form">
<UiField label="اتصال مورد نظر جهت همگام‌سازی" required>
<UiSelect v-model="sync.connectionId">
<option disabled value="">انتخاب اتصال</option>
<option v-for="row in items" :key="row.id" :value="row.id">
{{ row.label }} ({{ row.dbName }})
</option>
</UiSelect>
</UiField>
<div class="sync-sub-section">
<h4 class="sync-subhead">بروزرسانی خودکار</h4>
<p class="sync-sub-desc">
«همگام‌سازی الان» همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها را وارد می‌کند و برای مشتری‌های از قبل
لینک‌شده نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه را از ته‌حساب تازه می‌کند. زمان‌بندی زیر
همان کار را در ساعت‌های انتخابی (به وقت تهران) تکرار می‌کند. خاموش یعنی فقط ورود دستی.
</p>
<UiField label="تعداد در روز">
<UiSelect
:model-value="autoCount"
:disabled="!sync.connectionId || autoSyncSaving"
@update:model-value="onAutoCount"
>
<option value="0">خاموش</option>
<option v-for="n in 6" :key="n" :value="String(n)">
{{ toFaDigits(n) }} بار
</option>
</UiSelect>
</UiField>
<div v-if="Number(autoCount) > 0" class="crm-form-grid-3">
<UiField
v-for="(_, index) in autoHours"
:key="index"
:label="`ساعت ${toFaDigits(index + 1)}`"
>
<UiSelect
:model-value="autoHours[index]"
:disabled="autoSyncSaving"
@update:model-value="setAutoHour(index, $event)"
>
<option v-for="hour in 24" :key="hour - 1" :value="String(hour - 1)">
{{ hourLabel(hour - 1) }}
</option>
</UiSelect>
</UiField>
</div>
<div class="sync-buttons">
<UiButton
:loading="syncBusy"
:disabled="!sync.connectionId || syncBusy || autoSyncSaving"
@click="syncCustomersNow"
>
همگام‌سازی الان (وارد + به‌روز کردن قبلی‌ها)
</UiButton>
<UiButton
variant="secondary"
:loading="autoSyncSaving"
:disabled="!sync.connectionId || syncBusy"
@click="saveAutoSync"
>
<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-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="8">
<a-form-item label="تعداد در روز">
<a-select
:value="autoCount"
:options="autoCountOptions"
:disabled="!sync.connectionId || autoSyncSaving"
@update:value="(value) => onAutoCount(String(value ?? '0'))"
/>
</a-form-item>
</a-col>
<a-col v-for="(_, index) in autoHours" :key="index" :xs="24" :md="8">
<a-form-item :label="`ساعت ${toFaDigits(index + 1)}`">
<a-select
:value="autoHours[index]"
:options="hourOptions"
:disabled="autoSyncSaving"
@update:value="(value) => setAutoHour(index, String(value ?? '8'))"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-button :loading="autoSyncSaving" :disabled="!sync.connectionId" @click="saveAutoSync">
ذخیره زمان‌بندی
</a-button>
<a-typography-text v-if="selectedConnection?.customerSyncLastRunAt" type="secondary">
آخرین اجرا:
{{ formatJalaliDateTime(new Date(selectedConnection.customerSyncLastRunAt)) }}
<template v-if="selectedConnection.customerSyncLastSummary">
— {{ toFaDigits(selectedConnection.customerSyncLastSummary) }}
</template>
</a-typography-text>
<a-typography-text v-if="selectedConnection?.customerSyncLastError" type="danger">
آخرین خطا: {{ selectedConnection.customerSyncLastError }}
</a-typography-text>
</a-flex>
</a-card>
<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>)
</h4>
<p v-if="duplicateCustomerCount" class="sync-sub-desc">
{{ toFaDigits(duplicateCustomerCount) }} مشتری شمارهٔ تکراری دارند و جداگانه وارد نمی‌شوند؛ همان شخص با کد دیگری از قبل لینک است.
</p>
<div class="tc-row">
<TableColumnsMenu table-key="tahesab.customers" align="end" />
</div>
<div class="crm-table-container">
<table
v-table-cols="'tahesab.customers'"
class="crm-table"
:style="{ '--row-start': (syncTablePage - 1) * syncTablePageSize }"
>
<thead>
<tr>
<th>کد مشتری</th>
<th>نام و نام خانوادگی</th>
<th>تلفن</th>
<th>وضعیت لینک</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
<tr v-if="!syncPagedResults.length">
<td colspan="5" class="sync-empty-row">
مشتری تازه‌ای برای ورود نیست. شماره‌های تکراری از قبل با کد دیگری لینک شده‌اند.
</td>
</tr>
<tr v-for="r in syncPagedResults" :key="String(r.moshtariCode)">
<td class="font-mono">{{ r.moshtariCode }}</td>
<td class="font-bold">{{ r.name || 'بدون نام' }}</td>
<td class="font-mono" dir="ltr">{{ r.tel }}</td>
<td>
<UiBadge v-if="r.alreadyLinked" variant="success">
لینک شده{{ r.personName ? ` (${r.personName})` : '' }}
</UiBadge>
<UiBadge v-else-if="duplicateOwner(r)" variant="warning">
شماره تکراری، کد {{ toFaDigits(duplicateOwner(r)!.code) }}
</UiBadge>
<UiBadge v-else variant="neutral">آماده ورود</UiBadge>
</td>
<td>
<UiButton
v-if="!r.alreadyLinked && !duplicateOwner(r)"
size="sm"
:disabled="!r.moshtariCode || syncBusy"
@click="importOne(r.moshtariCode!)"
>
وارد کردن
</UiButton>
<RouterLink
v-else-if="r.personId || duplicateOwner(r)?.personId"
:to="{ name: 'person-detail', params: { id: (r.personId || duplicateOwner(r)?.personId)! } }"
>
<UiButton variant="ghost" size="sm">
مشاهده شخص
</UiButton>
</RouterLink>
</td>
</tr>
</tbody>
</table>
</div>
<UiPagination
v-if="syncVisibleResults.length > SYNC_TABLE_PAGE_SIZES[0]"
:page="syncTablePage"
:total-pages="syncTableTotalPages"
:total-items="syncVisibleResults.length"
:page-size="syncTablePageSize"
:page-size-options="SYNC_TABLE_PAGE_SIZES"
class="sync-table-pagination"
@update:page="onSyncTablePageChange"
@update:page-size="syncTablePageSize = $event"
/>
</div>
</div>
</UiCard>
<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>