68 lines
2.0 KiB
JavaScript
68 lines
2.0 KiB
JavaScript
/**
|
|
* WhatsApp Cloud API: `to` is digits with country code, no + prefix.
|
|
* Strips spaces, letters, and punctuation; only digits are kept.
|
|
* Indian mobiles: 10-digit values get country code 91 (12 digits). A leading 0
|
|
* (e.g. 09823488138) is removed before applying the 10-digit rule.
|
|
* @param {string} raw
|
|
* @returns {string} digits only, or empty if unusable
|
|
*/
|
|
function normalizeWhatsAppTo(raw) {
|
|
let digits = String(raw || '').replace(/\D/g, '');
|
|
if (!digits) return '';
|
|
|
|
if (digits.length === 11 && digits.startsWith('0')) {
|
|
digits = digits.slice(1);
|
|
}
|
|
|
|
if (digits.length === 10) {
|
|
digits = `91${digits}`;
|
|
}
|
|
|
|
if (digits.length < 8 || digits.length > 15) return '';
|
|
return digits;
|
|
}
|
|
|
|
/**
|
|
* Last 10 digits of a phone for duplicate registration matching.
|
|
* Strips all non-digits, then takes the trailing 10 (so +91 / leading 0 are ignored).
|
|
* @param {string} raw
|
|
* @returns {string} up to 10 digits, or empty string
|
|
*/
|
|
function phoneLast10Digits(raw) {
|
|
const digits = String(raw || '').replace(/\D/g, '');
|
|
if (!digits) return '';
|
|
if (digits.length <= 10) return digits;
|
|
return digits.slice(-10);
|
|
}
|
|
|
|
/**
|
|
* All last-10 digit keys from a stored phone field that may contain two numbers,
|
|
* separators, +91, spaces, or a leading 0.
|
|
* @param {string} raw
|
|
* @returns {string[]}
|
|
*/
|
|
function extractPhoneLast10Keys(raw) {
|
|
const text = String(raw || '');
|
|
if (!text.trim()) return [];
|
|
const parts = text.split(/\s*(?:\/|,|&|;|\||\band\b)\s*/i);
|
|
const keys = new Set();
|
|
const consider = (chunk) => {
|
|
const digits = String(chunk || '').replace(/\D/g, '');
|
|
if (!digits) return;
|
|
if (digits.length >= 10) {
|
|
keys.add(digits.slice(-10));
|
|
return;
|
|
}
|
|
if (digits.length >= 8) keys.add(digits);
|
|
};
|
|
if (parts.length > 1) {
|
|
parts.forEach(consider);
|
|
}
|
|
const runs = text.match(/\d[\d\s.+()-]{7,}/g) || [];
|
|
runs.forEach(consider);
|
|
consider(text);
|
|
return [...keys];
|
|
}
|
|
|
|
module.exports = { normalizeWhatsAppTo, phoneLast10Digits, extractPhoneLast10Keys };
|