refactor: single priority authority + delete enrichment scripts

Priority is now computed in ONE place only:
- computePriorityScore() (src/lib/domain/foundation-scores.ts) is the
  single authority for priority (uses fitScore + readiness + penalties)
- Pipeline scripts NO LONGER compute priority — they set fitScore and
  write P4 as default
- Sync script recomputes priority via computePriorityScore() and writes
  corrected values back to DB before generating TS
- Zero drift possible: priority always matches what the UI displays

Deleted 4 direct-DB-write enrichment scripts:
- enrich-contacts-spheriq.ts (scraped HTML → DB)
- enrich-contacts-llm.ts (LLM extraction → DB)
- enrich-addresses.ts (scraped addresses → DB)
- deep-enrich.ts (LLM extraction → DB)
These wrote unverified data directly to production DB with no human
review step. Same pattern that caused the data poisoning incident.
Contact enrichment should happen via research links + manual entry.

Scripts: 30 → 26.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.6 committed 2026-04-09 11:38:20 +02:00
1 parent 532263a4a1
commit 98f3b58e88
9 files changed
+42 -1386

No files matched your search

-348
View File
@@ -1,348 +0,0 @@
#!/usr/bin/env tsx
/**
* ⚠️ CAUTION: Direct DB writer — no provenance tracking.
* Data written by this script has no source/confidence metadata.
* ALWAYS run with --dry-run first and verify output manually.
*
* Deep Enrichment — Extract classification signals + structured data from foundation websites
*
* Fetches website content, sends to LLM with Robert Schmuki's classification criteria,
* extracts: board members, capital, application process, past grantees, type signals.
* Updates configData JSONB directly (SSOT).
*
* Usage:
* npx tsx scripts/deep-enrich.ts --limit=10 --dry-run
* npx tsx scripts/deep-enrich.ts --limit=50
* npx tsx scripts/deep-enrich.ts --slug=mercator
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { fetchRaw, stripHtml } from './lib/web-extract';
import { THEMES } from '../src/lib/config/foundations/metadata';
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions';
const GROQ_MODEL = 'llama-3.3-70b-versatile';
const GROQ_API_KEY = process.env.GROQ_API_KEY;
if (!GROQ_API_KEY) {
console.error('GROQ_API_KEY not set');
process.exit(1);
}
const args = process.argv.slice(2);
const DRY_RUN = args.includes('--dry-run');
const LIMIT = parseInt(args.find(a => a.startsWith('--limit='))?.split('=')[1] ?? '10');
const SLUG_FILTER = args.find(a => a.startsWith('--slug='))?.split('=')[1];
const themeList = Object.values(THEMES).map(t => `${t.id}: ${t.label}`).join(', ');
function buildPrompt(name: string, esaPurpose: string, websiteText: string): string {
return `# Stiftungsanalyse: ${name}
Du analysierst eine Schweizer Stiftung anhand ihres Webauftritts und offiziellen Zwecks.
Extrahiere FAKTEN — keine Vermutungen. Wenn du etwas nicht findest, schreibe null.
## Offizieller Stiftungszweck (ESA/Zefix)
${esaPurpose || 'Nicht verfügbar'}
## Website-Inhalt
${websiteText.substring(0, 6000)}
## Aufgabe: Extrahiere folgende strukturierte Daten als JSON
{
"boardMembers": [{"name": "Vorname Nachname", "role": "Präsident|Geschäftsführer|Mitglied|..."}],
"capital": "CHF-Betrag als Text oder null",
"annualBudget": "CHF-Betrag als Text oder null",
"grantExpenditure": "Jährliche Fördersumme als Text oder null",
"pastGrantees": ["Name geförderter Organisation 1", "..."],
"applicationProcess": ["Schritt 1", "Schritt 2", "..."],
"applicationMethod": "online|email|direct|partnership|post|contact|none|unknown",
"hasApplicationForm": true/false,
"hasAnnualReport": true/false,
"hasGeschaeftsstelle": true/false,
"acceptsExternalApplications": true/false,
"criteria": {"nature": "Förderkriterien Natur/Umwelt oder null", "education": "Förderkriterien Bildung oder null"},
"deadlineText": "Eingabefrist als Text oder null",
"partners": ["Partnerorganisation 1", "..."],
"sdgs": [1, 4, 8, 12],
"typeSignals": {
"boardSize": Anzahl Stiftungsräte (Zahl oder null),
"hasFamilyName": true wenn Stiftungsname einen Familiennamen enthält,
"isCompanyAffiliated": true wenn Firmenname erkennbar (UBS, Migros, Swisscom etc.),
"hasGeschaeftsstelle": true wenn professionelle Geschäftsstelle mit Mitarbeitenden,
"hasApplicationForm": true wenn Online-Gesuchsformular vorhanden,
"hasAnnualReport": true wenn Jahresbericht/Tätigkeitsbericht veröffentlicht,
"capitalRange": "small" (<5 Mio) | "medium" (5-50 Mio) | "large" (>50 Mio) | "unknown",
"websiteQuality": "none" | "basic" | "professional"
},
"suggestedType": "A|B|C|D|network",
"typeReasoning": "Kurze Begründung der Typ-Einschätzung anhand Robert Schmuki Kriterien:
A = Potente, professionalisierte Förderstiftung (professionelle Geschäftsführung, Projektsteuerung, Analysen & Normen)
B = Potente Familienstiftung mit Verwaltung (Stiftungsrat = Entscheidungsträger, persönliche Interessen, Family Office/Anwalt)
C = Kleine bis mittlere Familienstiftung (3-5 Stiftungsräte, direkte Gesuchsannahme, wenig Ausschüttungspotential, emotional)
D = Corporate Foundation (professionelle Geschäftsführung, Zweckpräzisierung, Norm-Prozesse, wenig Transparenz)
network = Netzwerk/Verband (keine direkte Förderung)",
"suggestedFit": 0-10,
"fitReasoning": "Passung zu Revamp-IT (Kreislaufwirtschaft, Arbeitsintegration, digitale Bildung, Zürich)",
"themes": ["${themeList.split(', ').map(t => t.split(':')[0]).join('", "')}"],
"purposeSummary": "150+ Zeichen: Was fördert diese Stiftung konkret?",
"researchNotes": "250+ Zeichen: Ehrliche Einschätzung der Passung zu Revamp-IT"
}
WICHTIG:
- NUR valides JSON zurückgeben, KEIN Kommentar
- Schweizer Schriftdeutsch (ss statt ß)
- boardMembers: NUR wenn auf Website oder in Handelsregister gefunden
- capital: NUR wenn explizit erwähnt
- pastGrantees: NUR wenn explizit erwähnt
- themes: NUR aus dieser Liste wählen: ${themeList}
- Wenn nichts gefunden → null oder leeres Array []`;
}
async function callGroq(prompt: string): Promise<Record<string, unknown> | null> {
try {
const res = await fetch(GROQ_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${GROQ_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: GROQ_MODEL,
messages: [
{ role: 'system', content: 'Du bist ein Schweizer Stiftungsexperte. Antworte NUR mit validem JSON.' },
{ role: 'user', content: prompt },
],
temperature: 0.1,
max_tokens: 4096,
}),
});
if (!res.ok) {
const err = await res.text();
console.error(' Groq API error:', res.status, err.substring(0, 200));
return null;
}
const data = await res.json();
const content = data.choices?.[0]?.message?.content?.trim();
if (!content) return null;
// Extract JSON from response (handle markdown code blocks)
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
console.error(' No JSON found in response');
return null;
}
return JSON.parse(jsonMatch[0]);
} catch (err) {
console.error(' LLM error:', err instanceof Error ? err.message : err);
return null;
}
}
async function fetchWebsiteContent(url: string): Promise<string> {
try {
const html = await fetchRaw(url);
const text = stripHtml(html);
// Also try subpages for more context
const subpages = ['/kontakt', '/contact', '/foerderung', '/stiftung', '/ueber-uns', '/about', '/gesuche', '/projekte'];
let combined = text;
for (const sub of subpages.slice(0, 3)) { // Try first 3 subpages
try {
const subUrl = new URL(sub, url).href;
const subHtml = await fetchRaw(subUrl);
combined += '\n\n--- ' + sub + ' ---\n' + stripHtml(subHtml);
} catch {
// Subpage doesn't exist, skip
}
}
return combined.substring(0, 8000);
} catch {
return '';
}
}
async function main() {
const sql = neon(process.env.DATABASE_URL!);
// Get enrichment targets
let whereClause = `archived = false
AND config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' != ''
AND (config_data->>'fitScore')::int >= 3`;
if (SLUG_FILTER) {
whereClause = `id = '${SLUG_FILTER}' AND archived = false`;
}
const rows = await sql`
SELECT id, name,
config_data->>'websiteUrl' as website,
config_data->>'officialPurpose' as purpose,
config_data->>'purposeSummary' as purpose_summary,
config_data as config_data,
jsonb_array_length(COALESCE(config_data->'boardMembers', '[]'::jsonb)) as board_count
FROM fundraising_foundations
WHERE ${sql.unsafe(whereClause)}
ORDER BY (config_data->>'fitScore')::int DESC, (config_data->>'priority')::int ASC
LIMIT ${LIMIT}
`;
console.log(`Deep enrichment: ${rows.length} foundations (${DRY_RUN ? 'DRY RUN' : 'LIVE'})`);
console.log('');
let enriched = 0;
let skipped = 0;
let errors = 0;
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const slug = row.id as string;
const name = row.name as string;
const website = row.website as string;
const purpose = (row.purpose || row.purpose_summary || '') as string;
const cd = (row.config_data || {}) as Record<string, unknown>;
console.log(`[${i + 1}/${rows.length}] ${name} (${website})`);
// Fetch website
const websiteText = await fetchWebsiteContent(website);
if (!websiteText || websiteText.length < 100) {
console.log(' ⚠ Website fetch failed or too short, skipping');
skipped++;
continue;
}
console.log(` Fetched ${websiteText.length} chars`);
// Call LLM
const prompt = buildPrompt(name, purpose, websiteText);
const result = await callGroq(prompt);
if (!result) {
errors++;
continue;
}
console.log(` Type: ${result.suggestedType} (${result.typeReasoning ? (result.typeReasoning as string).substring(0, 80) : 'no reasoning'})`);
console.log(` Fit: ${result.suggestedFit}, Board: ${(result.boardMembers as unknown[])?.length ?? 0}, Capital: ${result.capital || 'unknown'}`);
if (DRY_RUN) {
enriched++;
continue;
}
// Merge into configData (SSOT)
const updates: Record<string, unknown> = {};
// Only update fields where we got new data (don't overwrite existing good data with nulls)
if (result.boardMembers && (result.boardMembers as unknown[]).length > 0) {
updates.boardMembers = result.boardMembers;
}
if (result.capital) updates.capital = result.capital;
if (result.annualBudget) updates.annualBudget = result.annualBudget;
if (result.grantExpenditure) updates.grantExpenditure = result.grantExpenditure;
if (result.pastGrantees && (result.pastGrantees as unknown[]).length > 0) {
updates.pastGrantees = result.pastGrantees;
}
if (result.applicationProcess && (result.applicationProcess as unknown[]).length > 0) {
updates.applicationProcess = result.applicationProcess;
}
if (result.applicationMethod && result.applicationMethod !== 'unknown') {
updates.applicationMethod = result.applicationMethod;
}
if (result.criteria) {
const c = result.criteria as Record<string, unknown>;
const clean: Record<string, string> = {};
if (c.nature && c.nature !== 'null') clean.nature = c.nature as string;
if (c.education && c.education !== 'null') clean.education = c.education as string;
if (Object.keys(clean).length > 0) updates.criteria = clean;
}
if (result.deadlineText) updates.deadlineText = result.deadlineText;
if (result.partners && (result.partners as unknown[]).length > 0) {
updates.partners = result.partners;
}
if (result.sdgs && (result.sdgs as unknown[]).length > 0) {
updates.sdgs = result.sdgs;
}
if (result.typeSignals) updates.typeSignals = result.typeSignals;
if (result.hasApplicationForm != null) updates.hasApplicationForm = result.hasApplicationForm;
if (result.hasAnnualReport != null) updates.hasAnnualReport = result.hasAnnualReport;
if (result.hasGeschaeftsstelle != null) updates.hasGeschaeftsstelle = result.hasGeschaeftsstelle;
if (result.acceptsExternalApplications != null) updates.acceptsExternalApplications = result.acceptsExternalApplications;
// Type: only upgrade confidence, don't downgrade
if (result.suggestedType) {
updates.type = result.suggestedType;
updates.typeSource = 'signal-derived';
updates.typeReasoning = result.typeReasoning;
}
// FitScore: use GREATEST to never downgrade
const newFit = typeof result.suggestedFit === 'number' ? result.suggestedFit : 0;
const existingFit = (cd.fitScore as number) || 0;
const finalFit = Math.max(existingFit, newFit);
// Purpose/notes: only update if new version is longer
const existingPurpose = (cd.purposeSummary as string) || '';
const newPurpose = (result.purposeSummary as string) || '';
if (newPurpose.length > existingPurpose.length) {
updates.purposeSummary = newPurpose;
}
const existingNotes = (cd.researchNotes as string) || '';
const newNotes = (result.researchNotes as string) || '';
if (newNotes.length > existingNotes.length) {
updates.researchNotes = newNotes;
}
// Themes: merge, don't replace
const existingThemes = (cd.themes as string[]) || [];
const newThemes = (result.themes as string[]) || [];
const allThemes = [...new Set([...existingThemes, ...newThemes])].filter(
t => Object.keys(THEMES).includes(t)
);
if (allThemes.length > 0) updates.themes = allThemes;
// Apply updates to configData via jsonb merge
const mergedConfig = { ...cd, ...updates, fitScore: finalFit };
await sql`
UPDATE fundraising_foundations
SET
config_data = ${JSON.stringify(mergedConfig)}::jsonb,
fit_score = ${finalFit},
research_depth = CASE
WHEN research_depth = 'deep' THEN 'deep'
ELSE 'standard'
END,
research_date = ${new Date().toISOString().split('T')[0]},
updated_at = NOW()
WHERE id = ${slug}
`;
enriched++;
console.log(` ✓ Updated (fit: ${existingFit}→${finalFit}, ${Object.keys(updates).length} fields)`);
// Rate limit: Groq free tier = 12K TPM, each request ~3-4K tokens
// Need ~20s between requests to stay under limit
await new Promise(r => setTimeout(r, 20000));
}
console.log(`\nDone: ${enriched} enriched, ${skipped} skipped, ${errors} errors`);
if (enriched > 0 && !DRY_RUN) {
console.log('Next: npm run sync && npm run build');
}
}
main().catch(console.error);
-201
View File
@@ -1,201 +0,0 @@
#!/usr/bin/env tsx
/**
* ⚠️ CAUTION: Direct DB writer — no provenance tracking.
* Data written by this script has no source/confidence metadata.
* ALWAYS run with --dry-run first and verify output manually.
* See: memory/feedback_data_integrity.md for context.
*
* Address Enrichment — Scrape foundation websites for Swiss postal addresses
*
* Targets high-priority foundations (fit>=5, P1/P2) that have a website
* but no street address. Fetches homepage + /kontakt, /contact, /impressum
* subpages and extracts Swiss postal addresses via regex.
*
* Usage:
* npx tsx scripts/enrich-addresses.ts --dry-run
* npx tsx scripts/enrich-addresses.ts --limit=20
* npx tsx scripts/enrich-addresses.ts
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import type { Foundation } from '../src/lib/schemas/foundation';
const sql = neon(process.env.DATABASE_URL!);
const DRY_RUN = process.argv.includes('--dry-run');
const LIMIT = parseInt(process.argv.find(a => a.startsWith('--limit='))?.split('=')[1] ?? '100');
const CONCURRENCY = 3;
const TIMEOUT_MS = 8000;
// Subpages to try for contact info
const SUBPAGES = ['', '/kontakt', '/contact', '/impressum', '/ueber-uns', '/about', '/stiftung'];
// Swiss postal address patterns — from specific to broad
const ADDR_PATTERNS = [
// "Strasse 123, 8001 Zürich" or "Strasse 123\n8001 Zürich"
/([A-ZÄÖÜa-zäöüéèê][\wäöüéèê. -]+\s+\d+[a-z]?)\s*[,\n\r]\s*(?:CH-)?(\d{4})\s+([A-ZÄÖÜa-zäöüéèê][\wäöüéèê .()-]+)/gm,
// "Strasse 123 · CH-8001 Zürich" (middot separator)
/([A-ZÄÖÜa-zäöüéèê][\wäöüéèê. -]+\s+\d+[a-z]?)\s*[·•|]\s*(?:CH-)?(\d{4})\s+([A-ZÄÖÜa-zäöüéèê][\wäöüéèê .()-]+)/gm,
// Postfach variant: "Strasse 123, Postfach, 8001 Zürich"
/([A-ZÄÖÜa-zäöüéèê][\wäöüéèê. -]+\s+\d+[a-z]?)\s*,\s*(?:Postfach|PO Box)\s*\d*\s*,\s*(?:CH-)?(\d{4})\s+([A-ZÄÖÜa-zäöüéèê][\wäöüéèê .()-]+)/gmi,
// Just "ZIP City" near address-like context when preceded by street-like text
/([\wäöüéèê]+(?:strasse|gasse|weg|platz|rain|ring|graben|quai|allee|str\.|weg)\s+\d+[a-z]?)\s*[,\n\r·•|/]\s*(?:CH-)?(\d{4})\s+([A-ZÄÖÜa-zäöüéèê][\wäöüéèê .()-]+)/gmi,
];
interface AddressResult {
street: string;
zip: string;
city: string;
source: string;
}
async function fetchPage(url: string): Promise<string> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, {
signal: controller.signal,
headers: { 'User-Agent': 'RevampInfo-AddressEnrich/1.0 (+https://revamp-info.vercel.app)' },
redirect: 'follow',
});
if (!res.ok) return '';
const html = await res.text();
// Strip tags, decode entities, normalize whitespace
return html
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, '\n')
.replace(/&amp;/g, '&')
.replace(/&nbsp;/g, ' ')
.replace(/&#\d+;/g, ' ')
.replace(/\n{3,}/g, '\n\n');
} catch {
return '';
} finally {
clearTimeout(timeout);
}
}
function extractAddress(text: string, sourceUrl: string): AddressResult | null {
for (const pattern of ADDR_PATTERNS) {
pattern.lastIndex = 0;
const match = pattern.exec(text);
if (match) {
const street = match[1].trim();
const zip = match[2];
// Clean city: stop at common terminators (phone, email, pipe, newline artifacts)
const city = match[3].trim()
.replace(/\s*[·•|/\\].*$/, '')
.replace(/\s*Tel\.?.*$/i, '')
.replace(/\s*Fon.*$/i, '')
.replace(/\s*\+\d.*$/, '')
.replace(/\s*\(?\d{3}.*$/, '')
.replace(/[.\s]+$/, '');
// Sanity check: Swiss zip is 1000-9999, city is 2+ chars
if (parseInt(zip) >= 1000 && parseInt(zip) <= 9999 && city.length >= 2 && street.length >= 3) {
return { street, zip, city, source: sourceUrl };
}
}
}
return null;
}
async function enrichFoundation(row: { id: string; name: string; website: string; config_data: Foundation }): Promise<AddressResult | null> {
const base = row.website.replace(/\/+$/, '');
for (const sub of SUBPAGES) {
const url = base + sub;
const text = await fetchPage(url);
if (!text) continue;
const addr = extractAddress(text, url);
if (addr) return addr;
}
return null;
}
async function main() {
console.log('━'.repeat(60));
console.log(' Address Enrichment');
console.log('━'.repeat(60));
console.log(` MODE: ${DRY_RUN ? 'Dry run' : 'LIVE — will update DB'}`);
console.log(` LIMIT: ${LIMIT}`);
console.log();
// Get foundations: high fit, no ZIP in address, has real website
const rows = await sql`
SELECT id, name,
config_data->>'websiteUrl' as website,
config_data as config_data
FROM fundraising_foundations
WHERE config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' NOT LIKE '%zefix.ch%'
AND config_data->>'websiteUrl' NOT LIKE '%stiftungschweiz.ch%'
AND config_data->>'fitScore' IS NOT NULL
AND (config_data->>'fitScore')::int >= 4
AND (
config_data->'contact'->>'address' IS NULL
OR config_data->'contact'->>'address' NOT SIMILAR TO '%[0-9]{4}%'
)
ORDER BY (config_data->>'fitScore')::int DESC, (config_data->>'priority')::int ASC
LIMIT ${LIMIT}
` as { id: string; name: string; website: string; config_data: Foundation }[];
console.log(` Found ${rows.length} foundations with website but no street address\n`);
let enriched = 0;
let failed = 0;
// Process in batches
for (let i = 0; i < rows.length; i += CONCURRENCY) {
const batch = rows.slice(i, i + CONCURRENCY);
const results = await Promise.all(batch.map(async (row) => {
const addr = await enrichFoundation(row);
return { row, addr };
}));
for (const { row, addr } of results) {
if (addr) {
enriched++;
const fullAddr = `${addr.street}, ${addr.zip} ${addr.city}`;
console.log(` ✓ ${row.name.slice(0, 40).padEnd(40)} → ${fullAddr}`);
console.log(` source: ${addr.source}`);
if (!DRY_RUN) {
// Merge address into config_data.contact
const cd = row.config_data as Record<string, unknown>;
const contact = (cd.contact ?? {}) as Record<string, unknown>;
contact.address = fullAddr;
cd.contact = contact;
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb,
updated_at = NOW()
WHERE id = ${row.id}
`;
}
} else {
failed++;
if (i + CONCURRENCY <= 20) { // Only log first failures
console.log(` ✗ ${row.name.slice(0, 40).padEnd(40)} — no address found`);
}
}
}
}
console.log('\n' + '━'.repeat(60));
console.log(` RESULTS`);
console.log('━'.repeat(60));
console.log(` Processed: ${rows.length}`);
console.log(` Enriched: ${enriched}`);
console.log(` No address: ${failed}`);
if (DRY_RUN) console.log('\n DRY RUN — no DB changes made.');
else if (enriched > 0) console.log(`\n Run 'npm run sync && npm run build' to regenerate site.`);
console.log();
}
main().catch(console.error);
-261
View File
@@ -1,261 +0,0 @@
#!/usr/bin/env tsx
/**
* ⚠️ CAUTION: Direct DB writer — no provenance tracking.
* Data written by this script has no source/confidence metadata.
* ALWAYS run with --dry-run first and verify output manually.
*
* Contact Enrichment via LLM — Find website, email, phone, address for foundations
*
* For each foundation: fetches website content (homepage + /kontakt + /impressum),
* sends to Groq LLM to extract structured contact data. Updates DB directly.
*
* Usage:
* npx tsx scripts/enrich-contacts-llm.ts --dry-run --limit=5
* npx tsx scripts/enrich-contacts-llm.ts --limit=50
* npx tsx scripts/enrich-contacts-llm.ts # all eligible
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import { callGroqJSON, GROQ_MODELS } from './lib/groq-client';
import type { Foundation } from '../src/lib/schemas/foundation';
const sql = neon(process.env.DATABASE_URL!);
const DRY_RUN = process.argv.includes('--dry-run');
const LIMIT = parseInt(process.argv.find(a => a.startsWith('--limit='))?.split('=')[1] ?? '200');
const TIMEOUT_MS = 8000;
const CONCURRENCY = 2; // Groq rate limits
// Pages to try for contact info
const CONTACT_PAGES = ['', '/kontakt', '/contact', '/impressum', '/ueber-uns', '/about', '/stiftung'];
// ============================================================================
// Web fetching
// ============================================================================
async function fetchPageText(url: string): Promise<string> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, {
signal: controller.signal,
headers: { 'User-Agent': 'RevampInfo-Research/1.0' },
redirect: 'follow',
});
if (!res.ok) return '';
const html = await res.text();
return html
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]*>/g, '\n')
.replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ').replace(/&#\d+;/g, ' ')
.replace(/\n{3,}/g, '\n')
.trim()
.slice(0, 8000); // Limit context for LLM
} catch {
return '';
} finally {
clearTimeout(timeout);
}
}
async function fetchContactContent(baseUrl: string): Promise<string> {
const base = baseUrl.replace(/\/+$/, '');
const parts: string[] = [];
for (const sub of CONTACT_PAGES) {
const url = base + sub;
const text = await fetchPageText(url);
if (text && text.length > 100) {
parts.push(`--- ${url} ---\n${text.slice(0, 4000)}`);
if (parts.join('\n').length > 12000) break; // Enough context
}
}
return parts.join('\n\n').slice(0, 15000);
}
// ============================================================================
// LLM extraction
// ============================================================================
const EXTRACT_PROMPT = `Du erhältst den Textinhalt einer Schweizer Stiftungswebsite. Extrahiere die Kontaktdaten der STIFTUNG (nicht von Partnern, Webdesignern, oder anderen Organisationen).
Antworte NUR mit einem JSON-Objekt:
{
"email": "info@example.ch oder null wenn nicht gefunden",
"phone": "+41 XX XXX XX XX oder null",
"street": "Strassenname Hausnummer oder null",
"zip": "4-stellige PLZ oder null",
"city": "Ortsname oder null"
}
Regeln:
- NUR Kontaktdaten der Stiftung selbst, nicht von Webdesignern oder Hosting-Firmen
- Schweizer PLZ ist immer 4-stellig (1000-9999)
- Wenn "CH-" vor der PLZ steht, entferne das Präfix
- Wenn keine Strasse gefunden, aber Stadt/PLZ, gib nur Stadt und PLZ
- Wenn gar nichts gefunden: alle Felder null
- Bevorzuge info@, kontakt@, stiftung@ E-Mail-Adressen
- Ignoriere noreply@, webmaster@, datenschutz@ Adressen`;
interface ExtractedContact {
email: string | null;
phone: string | null;
street: string | null;
zip: string | null;
city: string | null;
}
async function extractContactsViaLLM(websiteContent: string, foundationName: string): Promise<ExtractedContact | null> {
if (!websiteContent || websiteContent.length < 50) return null;
try {
const result = await callGroqJSON(
EXTRACT_PROMPT,
`Stiftung: ${foundationName}\n\nWebsite-Inhalt:\n${websiteContent}`,
{ temperature: 0, model: GROQ_MODELS['70b'] },
);
if (!result.ok) return null;
const r = result.data as Record<string, unknown>;
return {
email: typeof r.email === 'string' && r.email.includes('@') ? r.email : null,
phone: typeof r.phone === 'string' && r.phone.includes('+') ? r.phone : null,
street: typeof r.street === 'string' && r.street.length > 3 ? r.street : null,
zip: typeof r.zip === 'string' && /^\d{4}$/.test(r.zip) ? r.zip : null,
city: typeof r.city === 'string' && r.city.length > 1 ? r.city : null,
};
} catch (e) {
return null;
}
}
// ============================================================================
// Main
// ============================================================================
async function main() {
console.log('━'.repeat(60));
console.log(' Contact Enrichment via LLM (Groq)');
console.log('━'.repeat(60));
console.log(` MODE: ${DRY_RUN ? 'Dry run' : 'LIVE — will update DB'}`);
console.log(` LIMIT: ${LIMIT}\n`);
// Get foundations with website but missing email OR street address
const rows = await sql`
SELECT id, name,
config_data->>'websiteUrl' as website,
config_data as config_data
FROM fundraising_foundations
WHERE config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' NOT LIKE '%zefix.ch%'
AND config_data->>'websiteUrl' NOT LIKE '%stiftungschweiz.ch%'
AND config_data->>'websiteUrl' != ''
AND (
config_data->'contact'->>'email' IS NULL
OR config_data->'contact'->>'address' IS NULL
OR config_data->'contact'->>'address' NOT SIMILAR TO '%[0-9]{4}%'
)
ORDER BY (config_data->>'fitScore')::int DESC NULLS LAST,
(config_data->>'priority')::int ASC NULLS LAST
LIMIT ${LIMIT}
` as { id: string; name: string; website: string; config_data: Foundation }[];
console.log(` Found ${rows.length} foundations to enrich\n`);
let enriched = 0;
let newEmails = 0;
let newAddresses = 0;
let newPhones = 0;
let errors = 0;
for (let i = 0; i < rows.length; i += CONCURRENCY) {
const batch = rows.slice(i, i + CONCURRENCY);
const results = await Promise.all(batch.map(async (row) => {
try {
const content = await fetchContactContent(row.website);
if (!content) return { row, contact: null };
const contact = await extractContactsViaLLM(content, row.name);
return { row, contact };
} catch {
return { row, contact: null };
}
}));
for (const { row, contact } of results) {
if (!contact) {
errors++;
continue;
}
const cd = row.config_data as Record<string, unknown>;
const existing = (cd.contact ?? {}) as Record<string, string | undefined>;
let changed = false;
// Only fill in MISSING data — never overwrite existing
if (contact.email && !existing.email) {
existing.email = contact.email;
newEmails++;
changed = true;
}
if (contact.phone && !existing.phone) {
existing.phone = contact.phone;
newPhones++;
changed = true;
}
if (contact.zip && contact.city) {
const currentAddr = existing.address ?? '';
const hasZip = /\d{4}/.test(currentAddr);
if (!hasZip) {
const street = contact.street ?? '';
existing.address = street
? `${street}, ${contact.zip} ${contact.city}`
: `${contact.zip} ${contact.city}`;
newAddresses++;
changed = true;
}
}
if (changed) {
enriched++;
cd.contact = existing;
const emoji = contact.email ? '📧' : contact.zip ? '📍' : '📞';
console.log(` ${emoji} ${row.name.slice(0, 40).padEnd(40)} → email: ${contact.email ?? '-'} | ${contact.street ?? '-'}, ${contact.zip ?? '-'} ${contact.city ?? '-'} | ${contact.phone ?? '-'}`);
if (!DRY_RUN) {
await sql`
UPDATE fundraising_foundations
SET config_data = ${JSON.stringify(cd)}::jsonb,
updated_at = NOW()
WHERE id = ${row.id}
`;
}
}
}
// Progress
if ((i + CONCURRENCY) % 20 === 0 || i + CONCURRENCY >= rows.length) {
console.log(` ... ${Math.min(i + CONCURRENCY, rows.length)}/${rows.length} processed, ${enriched} enriched`);
}
}
console.log('\n' + '━'.repeat(60));
console.log(' RESULTS');
console.log('━'.repeat(60));
console.log(` Processed: ${rows.length}`);
console.log(` Enriched: ${enriched}`);
console.log(` New emails: ${newEmails}`);
console.log(` New addresses: ${newAddresses}`);
console.log(` New phones: ${newPhones}`);
console.log(` Errors/empty: ${errors}`);
if (DRY_RUN) console.log('\n DRY RUN — no DB changes made.');
else if (enriched > 0) console.log('\n Run: npm run sync && npm run build');
console.log();
}
main().catch(console.error);
-541
View File
@@ -1,541 +0,0 @@
#!/usr/bin/env tsx
/**
* ⚠️ CAUTION: Direct DB writer — no provenance tracking.
* Data written by this script has no source/confidence metadata.
* ALWAYS run with --dry-run first and verify output manually.
*
* Enrich foundation contacts via Spheriq (StiftungSchweiz) profile pages.
*
* Strategy: Spheriq profile pages contain contact data in the raw HTML even
* without login — entity JSON blobs have emails, and `mail-btn` links have
* website URLs and mailto links. We fetch the HTML and extract with regex.
*
* After Spheriq extraction, for foundations with real websites but still no
* email, we scrape the foundation website itself (homepage + /kontakt etc.).
*
* Usage:
* npx tsx scripts/enrich-contacts-spheriq.ts --dry-run # Preview
* npx tsx scripts/enrich-contacts-spheriq.ts # Write to DB
* npx tsx scripts/enrich-contacts-spheriq.ts --fit-min=4 # Only high-fit
* npx tsx scripts/enrich-contacts-spheriq.ts --limit=100 # Limit count
* npx tsx scripts/enrich-contacts-spheriq.ts --phase=spheriq # Only Spheriq
* npx tsx scripts/enrich-contacts-spheriq.ts --phase=websites # Only website scrape
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import { neon, type NeonQueryFunction } from '@neondatabase/serverless';
import { fetchRaw } from './lib/web-extract';
import { extractEmails, extractPhones } from './lib/contact-extractor';
import { isRegistryUrl } from '../src/lib/config/registry-domains';
// ============================================================================
// CONFIG
// ============================================================================
const SPHERIQ_BASE = 'https://app.spheriq.ch/organisation';
const CONCURRENCY = 5;
const SPHERIQ_DELAY_MS = 300; // Be polite to Spheriq
const WEBSITE_DELAY_MS = 200;
const PROGRESS_INTERVAL = 50;
// Subpages to try when scraping foundation websites
const CONTACT_SUBPAGES = ['/kontakt', '/contact', '/impressum', '/ueber-uns', '/about', '/stiftung'];
// Noise domains to filter from Spheriq extractions
const SPHERIQ_NOISE_EMAILS = new Set([
'office@spheriq.ch', 'support@spheriq.ch', 'kontakt@freihandlabor.com',
'info@example.com', 'test@test.com',
]);
const NOISE_EMAIL_DOMAINS = new Set([
'spheriq.ch', 'stiftungschweiz.ch', 'google.com', 'googleapis.com',
'cloudflare.com', 'wordpress.com', 'w3.org', 'schema.org',
'facebook.com', 'twitter.com', 'instagram.com', 'linkedin.com',
'youtube.com', 'example.com', 'sentry.io', 'intercom.io',
]);
// ============================================================================
// Types
// ============================================================================
interface DBRow {
id: string;
name: string;
config_data: Record<string, unknown>;
}
interface EnrichResult {
id: string;
name: string;
source: 'spheriq' | 'website';
email?: string;
phone?: string;
websiteUrl?: string;
}
// ============================================================================
// Spheriq extraction
// ============================================================================
function isNoiseEmail(email: string): boolean {
const lower = email.toLowerCase();
if (SPHERIQ_NOISE_EMAILS.has(lower)) return true;
const domain = lower.split('@')[1];
if (!domain) return true;
if (NOISE_EMAIL_DOMAINS.has(domain)) return true;
// Filter CSS/JS/image artifacts
if (lower.includes('{') || lower.includes('}') || lower.includes('\\')) return true;
if (lower.length < 5 || lower.length > 80) return true;
// Filter image/file extensions mistaken for emails
if (/\.(png|jpg|jpeg|gif|svg|css|js|pdf|webp|woff|woff2|ttf|eot|ico)$/i.test(lower)) return true;
// Filter hex-hash-like local parts (CSS class names, UUIDs)
if (/^[a-f0-9]{8,}@/.test(lower)) return true;
// Filter domains that look like version numbers or IPs
if (/^\d+\.\d+\.\d+/.test(domain)) return true;
if (/\.(webp|png|jpg)$/.test(domain)) return true;
// Must have a valid-looking TLD (2-6 chars, alpha only)
const tld = domain.split('.').pop() || '';
if (!/^[a-z]{2,6}$/.test(tld)) return true;
return false;
}
/** Build Spheriq slug from foundation name (they keep "Stiftung" etc.) */
function toSpheriqSlug(name: string): string {
return name
.toLowerCase()
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue')
.replace(/[^a-z0-9\s-]/g, '')
.trim()
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
}
async function fetchSpheriqPage(name: string): Promise<string | null> {
const slug = toSpheriqSlug(name);
try {
const url = `${SPHERIQ_BASE}/${slug}`;
const html = await fetchRaw(url);
// Spheriq returns a tiny redirect page (< 500 bytes) for 404s
if (html.length < 500) return null;
return html;
} catch {
return null;
}
}
function extractFromSpheriq(html: string): { email?: string; website?: string; phone?: string } {
const result: { email?: string; website?: string; phone?: string } = {};
// 1. Entity JSON: :entity="{&quot;email&quot;:&quot;info@example.ch&quot;,...}"
const entityMatch = html.match(/:entity="\{[^}]*\}"/);
if (entityMatch) {
const decoded = entityMatch[0].replace(/&quot;/g, '"');
const emailMatch = decoded.match(/"email":"([^"]+)"/);
if (emailMatch && emailMatch[1] !== 'null' && !isNoiseEmail(emailMatch[1])) {
result.email = emailMatch[1].toLowerCase();
}
}
// 2. mail-btn links: <a class="mail-btn" href="mailto:..."> and <a class="mail-btn" href="https://...">
const mailBtnMatches = html.matchAll(/<a\s+class="mail-btn"\s+href="([^"]+)"/g);
for (const m of mailBtnMatches) {
const href = m[1];
if (href.startsWith('mailto:') && !result.email) {
const email = href.replace('mailto:', '').toLowerCase();
if (!isNoiseEmail(email)) {
result.email = email;
}
} else if (href.startsWith('http') && !href.includes('spheriq') && !href.includes('stiftungschweiz') && !href.includes('javascript')) {
if (!result.website) {
result.website = href;
}
}
}
// 3. Phone — only from the contact section, not from Spheriq's own footer
// Look for phone near the foundation's entity/contact area, not in the page template
// Spheriq's own phone (+41 61 278 93 83) appears in footer — filter it out
const SPHERIQ_PHONE = '+41 61 278 93 83';
const phoneMatches = html.match(/(?:\+41|0041)[\s.]?\(?\d?\)?[\s./\-]?\d{2}[\s./\-]?\d{3}[\s./\-]?\d{2}[\s./\-]?\d{2}/g) || [];
const uniquePhones = [...new Set(phoneMatches.map(p => p.trim()))].filter(p => p !== SPHERIQ_PHONE);
if (uniquePhones.length > 0) {
result.phone = uniquePhones[0];
}
return result;
}
// ============================================================================
// Website scraping (for foundations with real website but no email)
// ============================================================================
async function scrapeWebsiteForEmail(websiteUrl: string): Promise<{ email?: string; phone?: string }> {
const result: { email?: string; phone?: string } = {};
// Try homepage first
try {
const html = await fetchRaw(websiteUrl);
const emails = extractEmails(html).filter(e => !isNoiseEmail(e));
const phones = extractPhones(html);
if (emails.length > 0) result.email = pickBestEmail(emails);
if (phones.length > 0) result.phone = phones[0];
if (result.email) return result;
} catch { /* continue to subpages */ }
// Try subpages
let baseUrl: string;
try {
const parsed = new URL(websiteUrl);
baseUrl = `${parsed.protocol}//${parsed.host}`;
} catch {
return result;
}
for (const subpage of CONTACT_SUBPAGES) {
try {
const html = await fetchRaw(`${baseUrl}${subpage}`);
const emails = extractEmails(html).filter(e => !isNoiseEmail(e));
const phones = extractPhones(html);
if (emails.length > 0 && !result.email) result.email = pickBestEmail(emails);
if (phones.length > 0 && !result.phone) result.phone = phones[0];
if (result.email) break;
} catch { /* subpage doesn't exist */ }
}
return result;
}
const PREFERRED_PREFIXES = [
'info@', 'kontakt@', 'contact@', 'stiftung@', 'sekretariat@',
'office@', 'admin@', 'hello@', 'mail@', 'geschaeftsstelle@',
];
function pickBestEmail(emails: string[]): string {
if (emails.length === 0) return '';
for (const prefix of PREFERRED_PREFIXES) {
const match = emails.find(e => e.toLowerCase().startsWith(prefix));
if (match) return match.toLowerCase();
}
return emails[0].toLowerCase();
}
// ============================================================================
// DB operations
// ============================================================================
async function updateFoundation(
sql: NeonQueryFunction<false, false>,
id: string,
updates: { email?: string; phone?: string; websiteUrl?: string },
) {
// Ensure contact object exists
if (updates.email || updates.phone) {
await sql`UPDATE fundraising_foundations
SET config_data = CASE
WHEN config_data->'contact' IS NULL
THEN jsonb_set(config_data, '{contact}', '{}'::jsonb)
ELSE config_data
END
WHERE id = ${id} AND config_data->'contact' IS NULL`;
}
if (updates.email) {
await sql`UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{contact,email}', to_jsonb(${updates.email}::text)),
updated_at = NOW()
WHERE id = ${id}`;
}
if (updates.phone) {
await sql`UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{contact,phone}', to_jsonb(${updates.phone}::text)),
updated_at = NOW()
WHERE id = ${id}`;
}
if (updates.websiteUrl) {
await sql`UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{websiteUrl}', to_jsonb(${updates.websiteUrl}::text)),
updated_at = NOW()
WHERE id = ${id}`;
}
}
async function queryFoundationsNoEmail(sql: NeonQueryFunction<false, false>): Promise<DBRow[]> {
const rows = await sql`
SELECT id, name, config_data
FROM fundraising_foundations
WHERE config_data IS NOT NULL
AND archived = false
AND (config_data->'contact'->>'email' IS NULL OR config_data->'contact'->>'email' = '')
ORDER BY (config_data->>'fitScore')::int DESC NULLS LAST, id
`;
return rows as unknown as DBRow[];
}
async function queryFoundationsWithWebsiteNoEmail(sql: NeonQueryFunction<false, false>): Promise<DBRow[]> {
const rows = await sql`
SELECT id, name, config_data
FROM fundraising_foundations
WHERE config_data IS NOT NULL
AND archived = false
AND config_data->>'websiteUrl' IS NOT NULL
AND config_data->>'websiteUrl' != ''
AND (config_data->'contact'->>'email' IS NULL OR config_data->'contact'->>'email' = '')
ORDER BY (config_data->>'fitScore')::int DESC NULLS LAST, id
`;
return rows as unknown as DBRow[];
}
function applyFilters(rows: DBRow[], fitMin: number, limit: number): DBRow[] {
let filtered = rows;
if (fitMin > 0) {
filtered = filtered.filter(r => {
const score = parseInt(String(r.config_data?.fitScore ?? '0'), 10);
return score >= fitMin;
});
}
if (limit > 0) {
filtered = filtered.slice(0, limit);
}
return filtered;
}
// ============================================================================
// Main
// ============================================================================
async function main() {
const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run');
const fitMin = parseInt(args.find(a => a.startsWith('--fit-min='))?.split('=')[1] || '0');
const limit = parseInt(args.find(a => a.startsWith('--limit='))?.split('=')[1] || '0');
const phase = args.find(a => a.startsWith('--phase='))?.split('=')[1] || 'all';
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(' Foundation Contact Enrichment — Spheriq + Website Scraping');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(` Mode: ${dryRun ? 'DRY RUN' : 'WRITE TO DB'}`);
console.log(` Phase: ${phase}`);
if (fitMin > 0) console.log(` Fit minimum: ${fitMin}`);
if (limit > 0) console.log(` Limit: ${limit}`);
if (!process.env.DATABASE_URL) {
console.error('DATABASE_URL not set');
process.exit(1);
}
const sql = neon(process.env.DATABASE_URL);
// ── Phase 1: Spheriq scraping ──────────────────────────────────────────
if (phase === 'all' || phase === 'spheriq') {
console.log('\n── Phase 1: Spheriq Profile Scraping ──────────────────────');
const allRows = await queryFoundationsNoEmail(sql);
const rows = applyFilters(allRows, fitMin, limit);
console.log(` Foundations without email: ${allRows.length} (processing: ${rows.length})`);
let processed = 0;
let foundEmail = 0;
let foundWebsite = 0;
let foundPhone = 0;
const results: EnrichResult[] = [];
for (let i = 0; i < rows.length; i += CONCURRENCY) {
const batch = rows.slice(i, i + CONCURRENCY);
const batchResults = await Promise.all(batch.map(async (row) => {
const html = await fetchSpheriqPage(row.name);
if (!html) return null;
const extracted = extractFromSpheriq(html);
if (!extracted.email && !extracted.website && !extracted.phone) return null;
const existing = row.config_data;
const existingContact = (existing?.contact || {}) as Record<string, string>;
const existingWebsite = (existing?.websiteUrl || '') as string;
const result: EnrichResult = { id: row.id, name: row.name, source: 'spheriq' };
let hasNew = false;
if (extracted.email && !existingContact.email) {
result.email = extracted.email;
hasNew = true;
}
if (extracted.phone && !existingContact.phone) {
result.phone = extracted.phone;
hasNew = true;
}
if (extracted.website && (!existingWebsite || isRegistryUrl(existingWebsite))) {
result.websiteUrl = extracted.website;
hasNew = true;
}
return hasNew ? result : null;
}));
for (const r of batchResults) {
if (r) {
results.push(r);
if (r.email) foundEmail++;
if (r.websiteUrl) foundWebsite++;
if (r.phone) foundPhone++;
}
}
processed += batch.length;
if (processed % PROGRESS_INTERVAL === 0 || processed === rows.length) {
console.log(` [${processed}/${rows.length}] emails: ${foundEmail}, websites: ${foundWebsite}, phones: ${foundPhone}`);
}
await new Promise(r => setTimeout(r, SPHERIQ_DELAY_MS));
}
console.log(`\n Spheriq results:`);
console.log(` New emails: ${foundEmail}`);
console.log(` New websites: ${foundWebsite}`);
console.log(` New phones: ${foundPhone}`);
if (results.length > 0) {
console.log(`\n Sample (first 20):`);
for (const r of results.slice(0, 20)) {
const parts = [];
if (r.email) parts.push(`email: ${r.email}`);
if (r.websiteUrl) parts.push(`web: ${r.websiteUrl}`);
if (r.phone) parts.push(`phone: ${r.phone}`);
console.log(` ${r.name.substring(0, 45).padEnd(47)} ${parts.join(', ')}`);
}
if (results.length > 20) console.log(` ... and ${results.length - 20} more`);
}
if (!dryRun && results.length > 0) {
console.log(`\n Writing ${results.length} updates to DB...`);
let written = 0;
for (const r of results) {
try {
await updateFoundation(sql, r.id, {
email: r.email,
phone: r.phone,
websiteUrl: r.websiteUrl,
});
written++;
} catch (err) {
console.error(` Error updating ${r.id}: ${err}`);
}
}
console.log(` Written: ${written}`);
}
}
// ── Phase 2: Website scraping ──────────────────────────────────────────
if (phase === 'all' || phase === 'websites') {
console.log('\n── Phase 2: Website Scraping for Email ─────────────────────');
const allRows = await queryFoundationsWithWebsiteNoEmail(sql);
const filtered = applyFilters(allRows, fitMin, 0); // no limit for phase 2
// Filter to only real websites
const withRealWebsites = filtered.filter(r => {
const url = r.config_data?.websiteUrl as string;
return url && !isRegistryUrl(url);
});
if (limit > 0) {
withRealWebsites.splice(limit);
}
console.log(` Foundations with real website but no email: ${withRealWebsites.length}`);
let processed = 0;
let foundEmail = 0;
let foundPhone = 0;
const results: EnrichResult[] = [];
for (let i = 0; i < withRealWebsites.length; i += CONCURRENCY) {
const batch = withRealWebsites.slice(i, i + CONCURRENCY);
const batchResults = await Promise.all(batch.map(async (row) => {
const url = row.config_data?.websiteUrl as string;
const scraped = await scrapeWebsiteForEmail(url);
if (!scraped.email && !scraped.phone) return null;
const existingContact = (row.config_data?.contact || {}) as Record<string, string>;
const result: EnrichResult = { id: row.id, name: row.name, source: 'website' };
let hasNew = false;
if (scraped.email && !existingContact.email) {
result.email = scraped.email;
hasNew = true;
}
if (scraped.phone && !existingContact.phone) {
result.phone = scraped.phone;
hasNew = true;
}
return hasNew ? result : null;
}));
for (const r of batchResults) {
if (r) {
results.push(r);
if (r.email) foundEmail++;
if (r.phone) foundPhone++;
}
}
processed += batch.length;
if (processed % PROGRESS_INTERVAL === 0 || processed === withRealWebsites.length) {
console.log(` [${processed}/${withRealWebsites.length}] emails: ${foundEmail}, phones: ${foundPhone}`);
}
await new Promise(r => setTimeout(r, WEBSITE_DELAY_MS));
}
console.log(`\n Website scraping results:`);
console.log(` New emails: ${foundEmail}`);
console.log(` New phones: ${foundPhone}`);
if (results.length > 0) {
console.log(`\n Sample (first 20):`);
for (const r of results.slice(0, 20)) {
const parts = [];
if (r.email) parts.push(`email: ${r.email}`);
if (r.phone) parts.push(`phone: ${r.phone}`);
console.log(` ${r.name.substring(0, 45).padEnd(47)} ${parts.join(', ')}`);
}
}
if (!dryRun && results.length > 0) {
console.log(`\n Writing ${results.length} updates to DB...`);
let written = 0;
for (const r of results) {
try {
await updateFoundation(sql, r.id, { email: r.email, phone: r.phone });
written++;
} catch (err) {
console.error(` Error updating ${r.id}: ${err}`);
}
}
console.log(` Written: ${written}`);
}
}
// ── Summary ────────────────────────────────────────────────────────────
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
const finalCounts = await sql`
SELECT
COUNT(CASE WHEN config_data->'contact'->>'email' IS NOT NULL AND config_data->'contact'->>'email' != '' THEN 1 END) as emails,
COUNT(CASE WHEN config_data->'contact'->>'phone' IS NOT NULL AND config_data->'contact'->>'phone' != '' THEN 1 END) as phones,
COUNT(CASE WHEN config_data->>'websiteUrl' IS NOT NULL AND config_data->>'websiteUrl' != '' THEN 1 END) as websites
FROM fundraising_foundations
`;
console.log(` DB totals: ${JSON.stringify(finalCounts[0])}`);
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
}
main().catch(err => {
console.error('Fatal:', err);
process.exit(1);
});
+4 -15
View File
@@ -160,21 +160,10 @@ async function main() {
});
// Map 0-10 → display 0-3 (gated: rapid tier → fit=0)
const fitDisplay = fitScoreToDisplay(fitScore, researchDepth === 'rapid');
// Priority from fitScore — rapid depth → always P4
const isFunderFlag = a.isFunder;
const isZurich = (esa.canton === 'ZH');
let computedPriority: 1 | 2 | 3 | 4;
if (researchDepth === 'rapid') {
computedPriority = 4;
} else if (fitScore >= 7 && isFunderFlag) {
computedPriority = 1;
} else if (fitScore >= 4 && (isFunderFlag || isZurich)) {
computedPriority = 2;
} else if (fitScore >= 4) {
computedPriority = 3;
} else {
computedPriority = 4;
}
// Priority is NOT computed here — it's derived by sync script via
// computePriorityScore() which uses fitScore + readiness + penalties.
// Pipeline sets P4 as default; sync corrects to the real value.
const computedPriority = 4;
// --- Layer 2: Merged configData (backward compat for sync pipeline) ---
// Full config for INSERT (new entries)
+6 -10
View File
@@ -77,16 +77,12 @@ async function main() {
// Use best of algorithmic and LLM-assessed score (LLM has context we lack: canton, purpose nuance)
const fitScore = Math.max(algoScore, (entry as any).fitScore ?? 0);
// Priority from fitScore
let priority: 1 | 2 | 3 | 4;
if (fitScore >= 7 && entry.isFunder) priority = 1;
else if (fitScore >= 4 && entry.isFunder) priority = 2;
else if (fitScore >= 4) priority = 3;
else priority = 4;
// Note: rapid gate applied below based on hasSubstantialData
// Priority is NOT computed here — sync script derives it via
// computePriorityScore() which uses fitScore + readiness + penalties.
const priority = 4;
const fitLabel = fitScore >= 7 ? '★★★' : fitScore >= 4 ? '★★☆' : '★☆☆';
console.log(` ${entry.name}: fit=${fitScore} ${fitLabel}, P${priority}, themes=[${validThemes.join(',')}]`);
console.log(` ${entry.name}: fit=${fitScore} ${fitLabel}, themes=[${validThemes.join(',')}]`);
if (!DRY_RUN) {
const mergeConfig: Record<string, unknown> = {
@@ -106,8 +102,8 @@ async function main() {
// Upgrade from rapid when we have substantial analysis data
const hasSubstantialData = entry.purposeSummary.length >= 100 && validThemes.length > 0;
// Gate: foundations staying at rapid depth are never actionable (P4)
const writePriority = hasSubstantialData ? priority : 4;
// Priority is always P4 at write time — sync computes the real value
const writePriority = 4;
// Set researchDepth in mergeConfig so the trigger picks it up
const writeDepth = hasSubstantialData ? 'standard' : 'rapid';
+6 -9
View File
@@ -460,13 +460,10 @@ async function phase2LlmTriage(
// Don't double-count LLM's suggestedFit (it can only inflate, never correct).
const fitScore = algoScore;
// Priority from fitScore — rapid foundations are always P4 (not enough data to act on)
const isZurich = candidate.canton === 'ZH';
let priority: 1 | 2 | 3 | 4;
if (fitScore >= 7 && isFunder) priority = 1;
else if (fitScore >= 4 && (isFunder || isZurich)) priority = 2;
else if (fitScore >= 4) priority = 3;
else priority = 4;
// Priority is NOT computed here — sync script derives it via
// computePriorityScore() which uses fitScore + readiness + penalties.
// Pipeline sets P4 as default; sync corrects to the real value.
const priority = 4;
const result: TriageResult = {
slug: candidate.slug,
@@ -553,8 +550,8 @@ async function phase3Upsert(
// Upgrade from rapid when we have substantial analysis data
const hasSubstantialData = r.purposeSummary.length >= 100 && r.themes.length > 0;
// Gate: foundations staying at rapid depth are never actionable (P4)
const writePriority = hasSubstantialData ? r.priority : 4;
// Priority is always P4 at write time — sync computes the real value
const writePriority = 4;
// Set researchDepth in mergeConfig so the trigger picks it up
const writeDepth = hasSubstantialData ? 'standard' : 'rapid';
@@ -1,6 +1,6 @@
// AUTO-GENERATED — DO NOT EDIT MANUALLY
// Source: Neon DB (fundraising_foundations.config_data)
// Generated: 2026-04-09T09:11:39.734Z
// Generated: 2026-04-09T09:36:32.468Z
// Run `npm run sync` to regenerate from database
// Foundations: 1239
+25
View File
@@ -26,6 +26,8 @@ import { writeFileSync } from 'fs';
import { resolve } from 'path';
import { neon } from '@neondatabase/serverless';
import { foundationSchema } from '../lib/schemas/foundation';
import type { Foundation } from '../lib/schemas/foundation';
import { computePriorityScore } from '../lib/domain/foundation-scores';
const OUTPUT_PATH = resolve(__dirname, '../lib/config/foundations/stiftungen-generated.ts');
@@ -82,6 +84,29 @@ async function syncFoundations() {
process.exit(1);
}
// Recompute priority from the authoritative computePriorityScore()
// Pipeline scripts set fitScore; priority is DERIVED from fit + readiness + penalties.
// This ensures stored priority always matches what the UI displays.
let priorityUpdates = 0;
for (const f of valid as Foundation[]) {
const computed = computePriorityScore(f);
if (f.priority !== computed.level) {
(f as Record<string, unknown>).priority = computed.level;
priorityUpdates++;
}
}
if (priorityUpdates > 0) {
console.log(` Recomputed priority for ${priorityUpdates} foundations`);
// Write corrected priorities back to DB (trigger syncs flat column)
for (const f of valid as Foundation[]) {
await sql`
UPDATE fundraising_foundations
SET config_data = jsonb_set(config_data, '{priority}', ${JSON.stringify(f.priority)}::jsonb)
WHERE id = ${f.slug} AND (config_data->>'priority')::int != ${f.priority}
`;
}
}
// Generate TypeScript file
// WHY JSON.parse: With 5,500+ foundations, a raw array literal causes
// TS2590 "union type too complex to represent". JSON.parse avoids this