Files
CRM_Montzar/apps/api/src/contacts/person-source.ts
T

81 lines
2.7 KiB
TypeScript

import {
PERSON_IMPORT_SOURCE_LABELS,
PERSON_IMPORT_SOURCES,
type PersonImportSource,
} from '@mento/shared';
export function normalizePersonImportSource(
raw?: string | null,
): PersonImportSource {
const v = String(raw ?? '')
.trim()
.toLowerCase();
if (!v) return 'manual';
if ((PERSON_IMPORT_SOURCES as readonly string[]).includes(v)) {
return v as PersonImportSource;
}
if (/دیدار|didar/.test(v)) return 'didar';
if (/ته.?حساب|tahesab|accounting/.test(v)) return 'tahesab';
if (/اکسل|excel|xlsx|csv/.test(v)) return 'excel';
if (/گوشی|phone|مخاطب|vcard|contact/.test(v)) return 'phone';
if (/لید|lead|فرم/.test(v)) return 'lead_form';
return 'other';
}
export function personImportSourceLabel(source: string): string {
if (source in PERSON_IMPORT_SOURCE_LABELS) {
return PERSON_IMPORT_SOURCE_LABELS[source as PersonImportSource];
}
return source || PERSON_IMPORT_SOURCE_LABELS.manual;
}
type SourceSnapshot = {
importSource?: string | null;
sourceRef?: string | null;
previousImportSource?: string | null;
previousSourceRef?: string | null;
customFields?: unknown;
};
function didarIdFrom(customFields: unknown): string | null {
if (!customFields || typeof customFields !== 'object') return null;
const raw = (customFields as Record<string, unknown>).didarId;
if (typeof raw === 'number' && Number.isFinite(raw)) return String(raw);
if (typeof raw === 'string' && raw.trim()) return raw.trim();
return null;
}
/**
* وقتی شخصِ موجود از منبع دیگری دوباره وارد می‌شود، منبع و کد فعلی را به‌عنوان «قبلی» نگه می‌دارد.
* اگر منبع یکسان باشد (ورود مجدد از همان منبع)، مقادیر قبلی دست نمی‌خورند.
*/
export function carryPreviousSource(
existing: SourceSnapshot,
nextSource: PersonImportSource,
): { previousImportSource?: string | null; previousSourceRef?: string | null } {
const currentSource = normalizePersonImportSource(existing.importSource);
if (currentSource === nextSource) return {};
let ref = existing.sourceRef?.trim() || null;
let source: string = currentSource;
if (!ref) {
const didarId = didarIdFrom(existing.customFields);
if (didarId && nextSource !== 'didar') {
ref = didarId;
source = 'didar';
}
}
if (source === 'manual' && !ref) return {};
return { previousImportSource: source, previousSourceRef: ref };
}
export function namesDiffer(
aFirst: string,
aLast: string,
bFirst: string,
bLast: string,
): boolean {
const a = `${aFirst} ${aLast}`.trim().replace(/\s+/g, ' ');
const b = `${bFirst} ${bLast}`.trim().replace(/\s+/g, ' ');
return Boolean(a && b && a !== b);
}