Branchwell

Docley / app / tools / import-nppes.mjs

1#!/usr/bin/env node
2// Turns the CMS NPPES full file (npidata_pfile_*.csv) into SQL batches for D1.
3// Keeps individual physicians (Entity Type 1, primary taxonomy in the 20xxxxxxxX
4// "Allopathic & Osteopathic Physicians" group) that are not deactivated.
5//
6// Usage:
7// node tools/import-nppes.mjs --nppes npidata_pfile.csv --nucc nucc_taxonomy.csv --out out/
8// Then load with tools/load-d1.sh out/
9import { createReadStream, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
10import { createInterface } from 'node:readline';
11import { join } from 'node:path';
12import { parseCsvLine } from './csv.mjs';
13
14const args = Object.fromEntries(
15 process.argv.slice(2).reduce((acc, v, i, a) => (v.startsWith('--') ? [...acc, [v.slice(2), a[i + 1]]] : acc), [])
16);
17if (!args.nppes || !args.out) {
18 console.error('usage: --nppes <npidata_pfile.csv> [--nucc <nucc_taxonomy.csv>] --out <dir> [--batch 500] [--per-file 50000]');
19 process.exit(1);
20}
21const BATCH = Number(args.batch || 500);
22const PER_FILE = Number(args['per-file'] || 50000);
23mkdirSync(args.out, { recursive: true });
24
25function loadNucc(path) {
26 const map = new Map();
27 if (!path) return map;
28 const lines = readFileSync(path, 'utf8').split(/\r?\n/);
29 const h = parseCsvLine(lines[0]).map((s) => s.trim().replace(/^/, ''));
30 const iCode = h.indexOf('Code');
31 const iClass = h.indexOf('Classification');
32 const iSpec = h.indexOf('Specialization');
33 const iDisp = h.indexOf('Display Name');
34 for (const line of lines.slice(1)) {
35 if (!line.trim()) continue;
36 const r = parseCsvLine(line);
37 const spec = (r[iSpec] || '').trim();
38 const cls = (r[iClass] || '').trim();
39 const name = spec || cls || (iDisp >= 0 ? (r[iDisp] || '').trim() : '');
40 if (r[iCode]) map.set(r[iCode].trim(), name);
41 }
42 return map;
43}
44
45const titleCase = (s) =>
46 (s || '')
47 .toLowerCase()
48 .replace(/(^|[\s\-'’.])([a-z])/g, (m, p, c) => p + c.toUpperCase())
49 .replace(/\bMc([a-z])/g, (m, c) => 'Mc' + c.toUpperCase());
50const sq = (v) => (v === null || v === undefined || v === '' ? 'NULL' : "'" + String(v).replace(/'/g, "''") + "'");
51const isoDate = (d) => {
52 const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(d || '');
53 return m ? `${m[3]}-${m[1]}-${m[2]}` : null;
54};
55const zip5 = (z) => (z || '').slice(0, 5) || null;
56const phone = (p) => {
57 const d = (p || '').replace(/\D/g, '');
58 return d.length === 10 ? `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}` : null;
59};
60
61const nucc = loadNucc(args.nucc);
62const rl = createInterface({ input: createReadStream(args.nppes), crlfDelay: Infinity });
63let header = null;
64let idx = {};
65let rows = [];
66let fileRows = 0;
67let fileNo = 0;
68let chunks = [];
69let total = 0;
70let seen = 0;
71
72function flushFile() {
73 if (!chunks.length) return;
74 const name = join(args.out, `doctors-${String(fileNo).padStart(4, '0')}.sql`);
75 writeFileSync(name, chunks.join('\n') + '\n');
76 fileNo++;
77 chunks = [];
78 fileRows = 0;
79}
80function flushBatch() {
81 if (!rows.length) return;
82 chunks.push(
83 'INSERT OR REPLACE INTO doctors (npi,name,first_name,middle_name,last_name,suffix,credential,sex,taxonomy,specialty,address,city,state,zip,phone,enumerated,updated) VALUES\n' +
84 rows.join(',\n') +
85 ';'
86 );
87 fileRows += rows.length;
88 rows = [];
89 if (fileRows >= PER_FILE) flushFile();
90}
91
92for await (const line of rl) {
93 if (!header) {
94 header = parseCsvLine(line).map((s) => s.replace(/^/, '').trim());
95 const f = (n) => header.indexOf(n);
96 idx = {
97 npi: f('NPI'),
98 type: f('Entity Type Code'),
99 last: f('Provider Last Name (Legal Name)'),
100 first: f('Provider First Name'),
101 middle: f('Provider Middle Name'),
102 suffix: f('Provider Name Suffix Text'),
103 cred: f('Provider Credential Text'),
104 sex: f('Provider Sex Code') >= 0 ? f('Provider Sex Code') : f('Provider Gender Code'),
105 addr: f('Provider First Line Business Practice Location Address'),
106 city: f('Provider Business Practice Location Address City Name'),
107 state: f('Provider Business Practice Location Address State Name'),
108 zip: f('Provider Business Practice Location Address Postal Code'),
109 tel: f('Provider Business Practice Location Address Telephone Number'),
110 enum: f('Provider Enumeration Date'),
111 upd: f('Last Update Date'),
112 deact: f('NPI Deactivation Date'),
113 react: f('NPI Reactivation Date'),
114 tax: Array.from({ length: 15 }, (_, i) => f(`Healthcare Provider Taxonomy Code_${i + 1}`)),
115 prim: Array.from({ length: 15 }, (_, i) => f(`Healthcare Provider Primary Taxonomy Switch_${i + 1}`)),
116 };
117 if (idx.npi < 0 || idx.type < 0) throw new Error('Not an NPPES npidata file: header missing NPI / Entity Type Code');
118 continue;
119 }
120 seen++;
121 const r = parseCsvLine(line);
122 if (r[idx.type] !== '1') continue;
123 if (r[idx.deact] && !(idx.react >= 0 && r[idx.react])) continue;
124 let tax = null;
125 for (let i = 0; i < 15; i++) {
126 const code = r[idx.tax[i]];
127 if (!code) continue;
128 if (r[idx.prim[i]] === 'Y') { tax = code; break; }
129 if (!tax) tax = code;
130 }
131 if (!tax || !tax.startsWith('20')) continue;
132 const state = (r[idx.state] || '').toUpperCase() || null;
133 const cred = (r[idx.cred] || '').replace(/\./g, '').toUpperCase().trim();
134 const name = [titleCase(r[idx.first]), titleCase(r[idx.middle]), titleCase(r[idx.last]), r[idx.suffix]]
135 .filter(Boolean).join(' ');
136 rows.push(
137 '(' +
138 [
139 sq(r[idx.npi]),
140 sq(name),
141 sq(titleCase(r[idx.first])),
142 sq(titleCase(r[idx.middle])),
143 sq(titleCase(r[idx.last])),
144 sq(r[idx.suffix]),
145 sq(cred),
146 sq(r[idx.sex]),
147 sq(tax),
148 sq(nucc.get(tax) || null),
149 sq(titleCase(r[idx.addr])),
150 sq(titleCase(r[idx.city])),
151 sq(state),
152 sq(zip5(r[idx.zip])),
153 sq(phone(r[idx.tel])),
154 sq(isoDate(r[idx.enum])),
155 sq(isoDate(r[idx.upd])),
156 ].join(',') +
157 ')'
158 );
159 total++;
160 if (rows.length >= BATCH) flushBatch();
161 if (seen % 500000 === 0) console.error(`read ${seen.toLocaleString()} rows, kept ${total.toLocaleString()}`);
162}
163flushBatch();
164flushFile();
165writeFileSync(
166 join(args.out, `zz-fts.sql`),
167 "INSERT INTO doctors_fts(doctors_fts) VALUES('rebuild');\n"
168);
169console.error(`done: read ${seen.toLocaleString()}, kept ${total.toLocaleString()} physicians in ${fileNo} files`);