local M = {}
local lp = require("assay.lead_provider")
local url = require("assay.url")
local PROVIDER = "registry:brreg"
local function trim(s) return (tostring(s or ""):gsub("^%s+", ""):gsub("%s+$", "")) end
local bare_domain = lp.bare_domain
local function status_of(e)
if e.konkurs then return "BANKRUPT" end
if e.underAvvikling then return "LIQUIDATING" end
if e.underTvangsavviklingEllerTvangsopplosning then return "COMPULSORY_LIQUIDATION" end
return "ACTIVE"
end
local function normalize(e, from)
e = e or {}
local addr = e.forretningsadresse or e.postadresse or {}
return lp.company(PROVIDER, from, {
registry_id = e.organisasjonsnummer,
name = e.navn,
domain = bare_domain(e.hjemmeside),
status = status_of(e),
legal_form = e.organisasjonsform and e.organisasjonsform.kode or nil,
jurisdiction = "NO",
city = addr.poststed,
country = addr.landkode or addr.land,
industry = e.naeringskode1 and e.naeringskode1.beskrivelse or nil,
industry_code = e.naeringskode1 and e.naeringskode1.kode or nil,
employees = e.harRegistrertAntallAnsatte and e.antallAnsatte or nil,
phone = e.telefon,
founded_at = e.stiftelsesdato,
registered_at = e.registreringsdatoEnhetsregisteret,
})
end
function M.client(opts)
opts = opts or {}
local base_url = (opts.base_url or "https://data.brreg.no/enhetsregisteret/api"):gsub("/+$", "")
local function api_get(path_str)
local target = base_url .. path_str
local resp = http.get(target, { headers = { Accept = "application/json" } })
if resp.status == 404 then return nil, target end
if resp.status ~= 200 then
error("brreg: GET " .. path_str .. " HTTP " .. resp.status .. ": " .. (resp.body or ""))
end
local ok, parsed = pcall(json.parse, resp.body or "")
if not ok then error("brreg: " .. path_str .. " returned unparseable JSON") end
return parsed, target
end
local function collect(body, from, key)
local out = {}
local embedded = body and body._embedded
for _, e in ipairs(embedded and embedded[key] or {}) do
out[#out + 1] = normalize(e, from)
end
return out
end
local c = {}
function c:search(name, o)
o = o or {}
local body, from = api_get("/enheter?navn=" .. url.encode(trim(name))
.. "&size=" .. tostring(o.limit or 10))
return collect(body, from, "enheter")
end
function c:get(orgnr)
local id = trim(orgnr):gsub("%s", "")
local body, from = api_get("/enheter/" .. url.encode(id))
if not body or not body.organisasjonsnummer then return nil end
return normalize(body, from)
end
function c:by_website(domain)
local d = bare_domain(domain)
if not d then return {} end
for _, form in ipairs({ d, "www." .. d }) do
local body, from = api_get("/enheter?hjemmeside=" .. url.encode(form) .. "&size=10")
local hits = collect(body, from, "enheter")
if #hits > 0 then return hits end
end
return {}
end
function c:sub_entities(orgnr)
local id = trim(orgnr):gsub("%s", "")
local body, from = api_get("/underenheter?overordnetEnhet=" .. url.encode(id) .. "&size=50")
return collect(body, from, "underenheter")
end
return c
end
return M