/ scripts / fix-contacts-phones.mjs
fix-contacts-phones.mjs
 1  #!/usr/bin/env node
 2  import { createDatabaseConnection } from '../src/utils/db.js';
 3  import { normalizePhoneNumber } from '../src/utils/phone-normalizer.js';
 4  
 5  const db = createDatabaseConnection();
 6  
 7  const sites = db
 8    .prepare(
 9      "SELECT id, contacts_json FROM sites WHERE contacts_json IS NOT NULL AND contacts_json LIKE '%phone%'"
10    )
11    .all();
12  
13  let sitesFixed = 0,
14    numbersFixed = 0;
15  const update = db.prepare('UPDATE sites SET contacts_json = ? WHERE id = ?');
16  
17  for (const site of sites) {
18    try {
19      const contacts = JSON.parse(site.contacts_json);
20      if (!contacts.phone_numbers || !Array.isArray(contacts.phone_numbers)) continue;
21  
22      let changed = false;
23      for (const phone of contacts.phone_numbers) {
24        if (phone.number) {
25          const normalized = normalizePhoneNumber(phone.number);
26          if (normalized !== phone.number) {
27            phone.number = normalized;
28            changed = true;
29            numbersFixed++;
30          }
31        }
32      }
33  
34      if (changed) {
35        update.run(JSON.stringify(contacts), site.id);
36        sitesFixed++;
37      }
38    } catch {
39      /* skip malformed JSON */
40    }
41  }
42  
43  console.log(
44    `${sitesFixed} sites updated, ${numbersFixed} phone numbers normalized in contacts_json`
45  );
46  db.close();