Files
edr-platform/apps/edr-passenger-api/src/common/utils/phone.utils.ts

26 lines
1.1 KiB
TypeScript

/**
* Phone numbers reach us in every shape the UI allows — `+251912345678`, `0912345678`,
* `912345678`, and the same again with spaces or dashes. Comparing two of them as raw strings
* is a coin flip, so anything that decides access on a phone number must normalise first.
*
* Mirrors `PassengerAuthService.standardizePhone`, plus the bare-9-digit case the passenger
* form produces (its input sits behind a fixed `+251` prefix control).
*/
export function normalizePhone(phone?: string | null): string | null {
if (!phone) return null;
const digits = phone.replace(/\D/g, '');
if (!digits) return null;
if (digits.startsWith('251')) return `+${digits}`;
if (digits.startsWith('0')) return `+251${digits.slice(1)}`;
// A bare local subscriber number, e.g. "912345678" from the +251-prefixed input.
if (digits.length === 9) return `+251${digits}`;
return `+${digits}`;
}
/** True only when both numbers are present and resolve to the same E.164 form. */
export function samePhone(a?: string | null, b?: string | null): boolean {
const left = normalizePhone(a);
const right = normalizePhone(b);
return !!left && !!right && left === right;
}