forked from Yara724/api
47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { FilterQuery } from "mongoose";
|
|
import { UserModel } from "src/users/entities/schema/user.schema";
|
|
|
|
/** Canonical Iranian mobile: leading 0 + 10 digits (e.g. 09123456789). */
|
|
export function normalizeIranMobile(phone?: string): string | undefined {
|
|
if (!phone) return undefined;
|
|
|
|
const digits = String(phone).replace(/\D/g, "");
|
|
if (!digits) return undefined;
|
|
if (digits.startsWith("0098")) return `0${digits.slice(4)}`;
|
|
if (digits.startsWith("98") && digits.length === 12) {
|
|
return `0${digits.slice(2)}`;
|
|
}
|
|
if (digits.length === 10 && digits.startsWith("9")) return `0${digits}`;
|
|
if (digits.length === 11 && digits.startsWith("0")) return digits;
|
|
return digits;
|
|
}
|
|
|
|
/** Variants that may exist on legacy user rows (username/mobile). */
|
|
export function iranMobileLookupVariants(phone?: string): string[] {
|
|
const raw = phone?.trim();
|
|
const canonical = normalizeIranMobile(raw);
|
|
const variants = new Set<string>();
|
|
if (raw) variants.add(raw);
|
|
if (canonical) {
|
|
variants.add(canonical);
|
|
if (canonical.startsWith("0") && canonical.length === 11) {
|
|
variants.add(canonical.slice(1));
|
|
variants.add(`98${canonical.slice(1)}`);
|
|
variants.add(`0098${canonical.slice(1)}`);
|
|
}
|
|
}
|
|
return Array.from(variants).filter(Boolean);
|
|
}
|
|
|
|
export function buildUserLookupByPhone(
|
|
phone: string,
|
|
): FilterQuery<UserModel> {
|
|
const variants = iranMobileLookupVariants(phone);
|
|
if (variants.length === 0) {
|
|
return { username: phone };
|
|
}
|
|
return {
|
|
$or: variants.flatMap((v) => [{ username: v }, { mobile: v }]),
|
|
};
|
|
}
|