3.0a Organisation Data Intelligence
Specification, workflow, and technical reference for the organisation data intelligence module.
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Companies House · Logo Backfill · Professional Qualifications · UK Jurisdiction
Automated pipeline to enrich tbl_organisations with logos, registered office addresses, company status, SIC codes, and professional qualification signals — sourced from Clearbit, Google Favicons, and the Companies House public API.
SYNOPSIS At a Glance
Goal of this pipeline: Replace every grey initials-circle in the portal sidebar and organisation modals with a real logo. Simultaneously harvest Companies House data (registered address, SIC codes, company status) and infer professional qualification requirements from trade codes.
CH. 1 The Problem
Organisations appear throughout the RAIA (Real estate Artificial Intelligence Agent) portal in three sidebar sections — Suppliers, Building contacts, and Tenancy partners. Without a logo, each org renders as a grey circle containing its initials (e.g. AI for Attic Inventory). This degrades visual scanning and brand recognition, particularly when an agent manages 50+ supplier relationships.
Clearbit ✓
Google fav ✓
Google fav ✓
Google fav ✓
No logo ✗
What we need per organisation
- Logo — for visual identity in the portal sidebar and org modal (44×44 px circle)
- Registered office address — from Companies House (authoritative UK source, not self-reported)
- Professional qualifications — e.g. Gas Safe (plumbers), NICEIC/NAPIT (electricians), ARLA/NAEA (letting agents), RICS (surveyors), CHAS/SafeContractor (general contractors)
- Company type and status — active, dissolved, dormant — so the portal can surface warnings on dissolved suppliers
Data sources — priority order
CH. 2 Data Model
Three tables are involved. Two are existing; one migration adds two new columns.
tbl_organisations — core record
tbl_organisations_attributes — EAV qualifications store
tbl_organisations_addresses — address link
The head office address is stored in a separate addresses table and linked via head_office_address_id FK on tbl_organisations. When Companies House returns a registered_office_address, the pipeline upserts a row in tbl_organisations_addresses and updates the FK.
Migration — add new columns
Run this migration to add the two new columns before executing the pipeline:
-- Migration: add website and sic_codes to tbl_organisations -- File: supabase/migrations/20260602_add_org_website_sic_codes.sql ALTER TABLE tbl_organisations ADD COLUMN IF NOT EXISTS website TEXT, ADD COLUMN IF NOT EXISTS sic_codes TEXT[]; -- Optional: index sic_codes for reporting queries CREATE INDEX IF NOT EXISTS idx_org_sic_codes ON tbl_organisations USING GIN (sic_codes);
Run the migration first. The pipeline will throw if website or sic_codes columns are absent when it tries to write them via the Supabase client.
CH. 3 The Pipeline — backfill-org-data.cjs
Pipeline step-by-step
-
1Load target organisations from Supabase
Query:
SELECT * FROM tbl_organisations WHERE logo_url IS NULL AND status != 'deleted'. Respects--limit=Nand--org=UUIDflags for scoped runs. -
2Companies House lookup (if company_reg_num present)
Zero-pad the reg number to 8 digits. Call
GET /company/{number}on the CH API. Extracts:registered_office_address,sic_codes,company_status,company_type,date_of_creation. Rate-limited to 1 req/s (see--delay=MS). Responses cached in memory for duplicate reg numbers. -
3Extract domain
Tries in order: (a) parse domain from
company_registry_urlorwebsitecolumn, (b) name-normalise to{slug}.co.ukas a guess, (c) Companies House registered name → domain heuristic. Domain is used for logo lookup in steps 4–5. -
4Clearbit logo attempt
HEAD https://logo.clearbit.com/{domain}— if HTTP 200 andContent-Typeis image, use this URL aslogo_url. UsesUser-Agent: Mozilla/5.0to avoid server-IP blocks (see P-01). -
5Google Favicon fallback
https://www.google.com/s2/favicons?sz=128&domain={domain}— always returns an image, but verify the response image dimensions are >32×32 px before accepting (a 16×16 globe means Google doesn't know the domain — see P-02). -
6Map SIC codes → qualification categories
Built-in SIC→qualification map (see Ch.5). For each matching SIC code, record the expected qualification category. Does not write actual registration numbers — those must be entered manually by agents.
-
7Write results (--write mode only)
UPDATE
tbl_organisationswithlogo_url,website,sic_codes,incorporation_date. UPSERTtbl_organisations_attributesfor each qualification category withattribute_value = 'REQUIRED'as a placeholder. In dry-run mode, only prints what would be written.
CLI flags
| Flag | Default | Purpose |
|---|---|---|
--write | off | Execute writes to Supabase. Without this flag the script is always a dry run. |
--dry-run | default | Alias — explicit dry-run mode (no writes, prints proposed changes). |
--limit=N | unlimited | Process at most N organisations. Useful for testing or rate-limited batches. |
--org=UUID | all | Process a single organisation by UUID. Useful for manual spot-checks. |
--delay=MS | 1000 | Milliseconds to wait between Companies House API requests. Set ≥1100 to stay inside 600 req/day safely. |
--report | off | Write a JSON summary to org-backfill-report.json after completion. |
Environment variables
COMPANIES_HOUSE_API_KEY— Basic-auth username for the Companies House API (password is blank). Obtain from the CH developer hub.SUPABASE_URL— Supabase project URL (already in.env.local)SUPABASE_SERVICE_ROLE_KEY— Service-role key for write access (already in.env.local)
Key code section
// backfill-org-data.cjs — core loop (simplified) const orgs = await loadTargetOrgs(supabase, { limit, orgId }); for (const org of orgs) { const result = { organisation_id: org.organisation_id }; // 1. Companies House if (org.company_reg_num) { const regNum = org.company_reg_num.padStart(8, '0'); const ch = await fetchCompaniesHouse(regNum, apiKey); if (ch) { result.sic_codes = ch.sic_codes; result.incorporation_date = ch.date_of_creation; result.ch_status = ch.company_status; } await sleep(delay); // rate limit } // 2. Domain extraction const domain = extractDomain(org); // 3. Clearbit → 4. Google favicon if (domain) { result.logo_url = await tryClearbit(domain) ?? await tryGoogleFavicon(domain); } // 5. SIC → qualifications const quals = mapSicToQualifications(result.sic_codes ?? []); if (writeMode) { await writeOrgData(supabase, result); await writeQualifications(supabase, org.organisation_id, quals); } else { console.log('[DRY-RUN]', org.name, result); } }
CH. 4 Running the Pipeline
-
1Get a Companies House API key
Register at developer.company-information.service.gov.uk — free, instant approval. Your API key is used as the Basic-auth username; the password is blank.
-
2Add the key to .env.local
COMPANIES_HOUSE_API_KEY=your_key_here— do not commit this to git. The.env.localfile is gitignored by default. -
3Dry run — see what would change
node backfill-org-data.cjs --limit=50— prints a table of proposedlogo_urlvalues and SIC codes for the first 50 orgs. No writes. Verify the output looks correct before proceeding. -
4Live run — write to Supabase
node backfill-org-data.cjs --write --report— processes all eligible orgs (logo_url IS NULL), writes logos and SIC codes to Supabase, emitsorg-backfill-report.json. Runs at ~1 org/s due to Companies House rate limiting. For 8,248 orgs ≈ 14 days of CH lookups at 600/day; run logo-only first (faster, no CH calls). -
5Check the report
cat org-backfill-report.json— shows counts: processed, logo_found, logo_missing, ch_found, ch_missing, errors. Commit to the repo as an audit trail.
Useful one-liners
# Single org test node backfill-org-data.cjs --org=550e8400-e29b-41d4-a716-446655440000 # Logo-only pass (no CH API, faster) node backfill-org-data.cjs --write --delay=0 --limit=500 # Companies House enrichment pass (CH only, slower) node backfill-org-data.cjs --write --delay=1100 --limit=550 # Full report run node backfill-org-data.cjs --write --report 2>&1 | tee run.log
Time estimate: 8,248 orgs × 1.1s delay = ~2.5 hours per 600-org batch for CH lookups. Logo-only (Clearbit + Google) runs in minutes. Recommended strategy: run logo pass first (no delay needed), then run CH enrichment in nightly batches of 550 orgs.
CH. 5 Qualification Framework
UK SIC codes returned by Companies House map to trade categories which have known mandatory certification requirements. The pipeline uses this table to populate tbl_organisations_attributes with qualification placeholders. Agents then fill in the actual registration numbers.
| SIC Code | Trade / Sector | Mandatory Certification | Regulator |
|---|---|---|---|
43220 |
Plumbing & Heating | Gas Safe Register | HSE |
43210 |
Electrical | NICEIC or NAPIT | OZAS |
43310 |
Plastering | n/a | — |
43320 |
Joinery / Carpentry | n/a | — |
43341 |
Painting & Decorating | n/a | — |
43390 |
Other building finishing | n/a | — |
68100 |
Letting / Estate Agency | ARLA Propertymark | RICS |
68209 |
Property Management | ARLA or RICS | RICS |
41100 |
Property Development | n/a | — |
81100 |
Building Management / FM | CHAS / SafeContractor | SSIP |
35110 |
Electricity Supply | Ofgem Supplier Licence | Ofgem |
36000 |
Water Supply | Ofwat Licence | Ofwat |
Storage in tbl_organisations_attributes
Each qualification is stored as a row with category = 'qualification'. The pipeline writes placeholder rows; agents complete the actual registration numbers in the portal:
gas_safe_number— Gas Safe Register IDniceic_number— NICEIC contractor numbernapit_number— NAPIT member numberarla_membership— ARLA Propertymark refrics_number— RICS firm numberchas_number— CHAS accreditation ref
attribute_key:gas_safe_numberattribute_value:123456category:qualificationis_secret:false- Pipeline writes value = "REQUIRED" as placeholder; agents then paste real numbers.
-- Query to see all qualification gaps SELECT o.name, a.attribute_key, a.attribute_value FROM tbl_organisations_attributes a JOIN tbl_organisations o USING (organisation_id) WHERE a.category = 'qualification' AND a.attribute_value = 'REQUIRED' ORDER BY o.name;
CH. 6 Manual Override in Portal
Agents should not need to run the CLI. All org data is editable directly in the portal via the OrganisationCardModal.
OrganisationCardModal has a logo URL input field. Agents can paste any HTTPS image URL. The 44×44 circle preview renders immediately. On save, calls PATCH /api/organisations/{id} with { logo_url }.
The new website column is exposed in the modal. Agents can paste the org's website URL. This feeds back into the pipeline domain extraction on subsequent runs.
A Qualifications tab in OrganisationCardModal queries tbl_organisations_attributes WHERE category = 'qualification'. Displays key/value pairs with edit-in-place. Agents paste real registration numbers to replace pipeline placeholders.
API endpoints
| Method | Endpoint | Body | Effect |
|---|---|---|---|
| PATCH | /api/organisations/{id} |
{ logo_url, website } |
Updates org logo and/or website URL directly in tbl_organisations |
| GET | /api/organisations/{id}/attributes?category=qualification |
— | Returns all qualification attributes for the org |
| PUT | /api/organisations/{id}/attributes/{key} |
{ value } |
Upserts a single qualification attribute (e.g. sets gas_safe_number) |
⚠ Pitfalls
Clearbit's logo endpoint detects and blocks requests from cloud/data-centre IP ranges. Always set User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 in the request headers. This mimics a browser and is accepted by Clearbit's CDN.
If Google has no favicon data for the domain, it returns a generic 16×16 grey globe icon. Always fetch the image and check width > 32 && height > 32 before storing the URL as a logo. Images smaller than 32×32 should be rejected and treated as "no logo".
Exceeding 600 requests/day results in HTTP 429 errors and a potential temporary ban. Set --delay=1100 (1.1 seconds per request) to guarantee you stay within 600/day. Cache Companies House responses in memory to avoid re-fetching duplicate company_reg_num values in the same run.
Companies House expects exactly 8 digits, zero-padded (e.g. 2366661 → 02366661). Some entries in tbl_organisations were imported without zero-padding. Always call .padStart(8, '0') before constructing the CH API URL. Non-numeric characters (letters, spaces, dashes) indicate a foreign or non-standard registration — skip CH lookup for those.
Local councils (e.g. K&C Council) have no Companies House number. Charities use a Charity Commission number. Foreign-registered companies don't appear in CH at all. For these, skip the CH lookup entirely and proceed with logo-only enrichment. Do not attempt a CH name search as a fallback — the results are too ambiguous.
Not all UK companies file SIC codes. When sic_codes is absent or empty in the CH response, fall back to the org's org_type field (e.g. org_type = 'utility') or apply name-based classification (e.g. name contains "Gas" → flag for gas_safe check). Document all fallback classifications in the report so agents can review.
Logo URLs sourced from Google Favicons (google.com/s2/favicons?domain=…) are ephemeral — if the company's domain changes or lapses, the URL returns a blank. Best practice: after validating a logo URL, fetch the image and store it to GCS (using the same avatar upload pipeline as tbl_persons.avatar_url), then write the permanent GCS URL to tbl_organisations.logo_url. Clearbit CDN URLs are more stable but still not permanent.
Once complete, this pipeline transforms the portal sidebar from a wall of grey initials-circles into a visually scannable directory of branded organisations — improving agent efficiency and reducing mis-selection errors when assigning suppliers to jobs or tenancy contacts to properties.
Author: RAIA (Real estate Artificial Intelligence Agent) OS — EstateAigents.com · Version: 1.0 · Last updated: June 2026
Repository Code
The live codebase implementation for this textbook logic sits within the following repository folder: