Files
toolshed-extensions/brreg/init.lua
T

294 lines
13 KiB
Lua

-- Brønnøysundregistrene: "brreg equinor" finds companies by name, "brreg 923 609 016" by
-- organisation number, sub-units (avdelinger) too, and "brreg" alone a number selected in the app
-- Toolshed was opened from; a number selected or copied is offered under Suggested. Enter shows
-- what the Central Coordinating Register knows, with the unit it's part of and a company's
-- sub-units under it, each shown in turn; ⌘K opens it on brreg.no or copies its number, name or
-- address. Its text is in locales/; what the register says (forms, industries) is in Norwegian,
-- as it gives it.
local api = "https://data.brreg.no/enhetsregisteret/api/"
local encode = toolshed.url_encode
local escape = toolshed.escape
local function get(path, max_seconds)
return toolshed.json.decode(toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), api .. path }))
end
-- 923609016 reads as 923 609 016, as brreg.no writes it.
local function spaced(number)
return (number:gsub("^(%d%d%d)(%d%d%d)(%d%d%d)$", "%1 %2 %3"))
end
-- The register writes names and places in capitals; "STAVANGER" reads better as "Stavanger".
-- Lua's lower and upper know only ASCII, so Æ, Ø and Å are handled by hand; Lua 5.1 has no \x
-- escapes, so their first byte is written in decimal.
local function titled(s)
local text = tostring(s or ""):lower():gsub("Æ", "æ"):gsub("Ø", "ø"):gsub("Å", "å")
local upper = { ["æ"] = "Æ", ["ø"] = "Ø", ["å"] = "Å" }
return (text:gsub("[^%s%-]+", function(word)
local first = word:match("^[\195][\128-\191]") or word:sub(1, 1)
return (upper[first] or first:upper()) .. word:sub(#first + 1)
end))
end
local function address(a)
if not a then return nil end
local parts = {}
for _, line in ipairs(a.adresse or {}) do table.insert(parts, line) end
local place = table.concat({ a.postnummer or "", titled(a.poststed) }, " "):match("^%s*(.-)%s*$")
if place ~= "" then table.insert(parts, place) end
if a.landkode and a.landkode ~= "NO" and a.land then table.insert(parts, a.land) end
return #parts > 0 and table.concat(parts, ", ") or nil
end
-- A sub-unit is where a company works (a shop, an office), found under its own path.
local function location(unit)
return unit.forretningsadresse or unit.beliggenhetsadresse
end
local function status(unit)
if unit.slettedato then return toolshed.t("status.deleted", { date = unit.slettedato }) end
if unit.konkurs then return toolshed.t("status.bankrupt") end
if unit.underTvangsavviklingEllerTvangsopplosning then return toolshed.t("status.dissolved") end
if unit.underAvvikling then return toolshed.t("status.wound-up") end
return nil
end
local function jig(unit, kind)
local subtitle = { spaced(unit.organisasjonsnummer) }
if unit.organisasjonsform then table.insert(subtitle, unit.organisasjonsform.kode) end
local where = location(unit)
if where and where.poststed then table.insert(subtitle, titled(where.poststed)) end
table.insert(subtitle, status(unit))
return {
title = unit.navn,
subtitle = table.concat(subtitle, " · "),
data = { number = unit.organisasjonsnummer, kind = kind, name = unit.navn, address = address(location(unit)) },
}
end
-- by_number looks a number up as a company first, then as a sub-unit; nil when it's neither.
local function by_number(number, max_seconds)
for _, kind in ipairs({ "enheter", "underenheter" }) do
local ok, unit = pcall(get, kind .. "/" .. number, max_seconds)
if ok then return unit, kind end
end
return nil
end
local function page_address(data)
return toolshed.t("link") .. data.kind .. "/" .. data.number
end
local function tile(icon)
return '<span class="tile small" data-icon="' .. icon .. '"></span>'
end
local function card(title, icon, tint, facts)
local rows = {}
for _, f in ipairs(facts) do
if f[2] and f[2] ~= "" then table.insert(rows, "<dt>" .. escape(toolshed.t(f[1])) .. "</dt><dd>" .. f[2] .. "</dd>") end
end
if #rows == 0 then return "" end
return '<div class="card" data-tint="' .. tint .. '"><div class="card-head">' .. tile(icon) .. escape(toolshed.t(title)) ..
'</div><dl class="kv">' .. table.concat(rows) .. "</dl></div>"
end
local function industries(unit)
local out = {}
for i = 1, 3 do
local code = unit["naeringskode" .. i]
if code then table.insert(out, escape(code.beskrivelse) .. ' <span class="dim">' .. escape(code.kode) .. "</span>") end
end
return table.concat(out, "<br>")
end
-- details is a unit's page, and the jigs it draws: the unit it's part of, in Part of, and what's
-- under a company in lines under its cards, each kind under its own heading.
local function details(unit, kind, parent_unit, under)
local jigs = {}
local trouble = status(unit)
local state = '<span class="dot' .. (trouble and "" or " on") .. '"></span>' .. escape(trouble or toolshed.t("status.active"))
local form = unit.organisasjonsform
local parent = unit.overordnetEnhet and escape(spaced(unit.overordnetEnhet))
if parent and parent_unit then
table.insert(jigs, jig(parent_unit, "enheter"))
parent = '<span data-jig="' .. #jigs .. '">' .. escape(parent_unit.navn) .. ' <span class="dim">' .. parent .. "</span></span>"
end
local registered = {}
if unit.registrertIForetaksregisteret then table.insert(registered, toolshed.t("register.business")) end
if unit.registrertIMvaregisteret then table.insert(registered, toolshed.t("register.vat")) end
if unit.registrertIStiftelsesregisteret then table.insert(registered, toolshed.t("register.foundations")) end
if unit.registrertIFrivillighetsregisteret then table.insert(registered, toolshed.t("register.non-profit")) end
local employees = unit.harRegistrertAntallAnsatte and unit.antallAnsatte and tostring(unit.antallAnsatte) or nil
local site = unit.hjemmeside
local cards = {
card(kind == "underenheter" and "card.sub-unit" or "card.company", "building", "sand", {
{ "fact.number", escape(spaced(unit.organisasjonsnummer)) },
{ "fact.form", form and (escape(form.beskrivelse) .. ' <span class="dim">' .. escape(form.kode) .. "</span>") },
{ "fact.status", state },
{ "fact.part-of", parent },
{ "fact.founded", escape(unit.stiftelsesdato or unit.oppstartsdato) },
{ "fact.registered", escape(unit.registreringsdatoEnhetsregisteret) },
}),
card("card.business", "briefcase", "purple", {
{ "fact.industry", industries(unit) },
{ "fact.employees", employees and escape(employees) },
{ "fact.sector", unit.institusjonellSektorkode and escape(unit.institusjonellSektorkode.beskrivelse) },
{ "fact.registers", escape(table.concat(registered, ", ")) },
}),
card("card.address", "map-pin", "orange", {
{ kind == "underenheter" and "fact.location" or "fact.business-address", escape(address(location(unit))) },
{ "fact.postal", escape(address(unit.postadresse)) },
{ "fact.municipality", location(unit) and location(unit).kommune and escape(titled(location(unit).kommune)) },
{ "fact.website", site and escape(site) },
}),
}
-- What's under it are rows the launcher draws where the page puts them, under their heading.
local lists = {}
for _, group in ipairs(under) do
local heading = toolshed.t(group.heading, { count = group.total })
for _, u in ipairs(group.units) do
local row = jig(u, group.kind)
row.section = heading
table.insert(jigs, row)
end
if group.total > #group.units then
table.insert(jigs, {
title = toolshed.t("all-" .. group.heading, { count = group.total }), icon = "external-link", action = "open", section = heading,
data = { number = unit.organisasjonsnummer, kind = "enheter" },
})
end
table.insert(lists, '<div data-rows="' .. escape(heading) .. '" style="margin-top: 8px"></div>')
end
return '<div class="page"><div class="cards">' .. table.concat(cards) .. "</div>" .. table.concat(lists) .. "</div>", jigs
end
-- most_under is how many of each kind under a company its page lists; the rest are on brreg.no.
local most_under = 49
-- A company has two kinds under it: units of their own that are part of it, like the
-- directorates under a ministry, and its sub-units, the places where it does business.
local kinds_under = {
{ kind = "enheter", heading = "units-under" },
{ kind = "underenheter", heading = "sub-units" },
}
-- related fetches the unit a unit is part of, and what's under a company, each kind with how many
-- there are. What can't be fetched is left out, so the page still shows.
local function related(unit, kind)
local parent, under = nil, {}
if unit.overordnetEnhet then
local ok, found = pcall(get, "enheter/" .. unit.overordnetEnhet, 5)
if ok then parent = found end
end
if kind == "enheter" then
for _, k in ipairs(kinds_under) do
local ok, found = pcall(get, k.kind .. "?size=" .. most_under .. "&overordnetEnhet=" .. unit.organisasjonsnummer, 5)
if ok and found._embedded and found._embedded[k.kind] then
table.insert(under, { kind = k.kind, heading = k.heading, units = found._embedded[k.kind], total = found.page and found.page.totalElements or 0 })
end
end
end
return parent, under
end
return toolshed.toolbox {
key = "brreg",
title = "i18n:toolbox.title",
description = "i18n:toolbox.description",
icon = "assets/brreg.svg",
tint = "sand",
tools = {
{
key = "search",
title = "i18n:tool.search.title",
words = { "brreg" },
examples = { "brreg equinor", "brreg 923 609 016" },
keywords = { "company", "organisation number", "orgnr", "enhetsregisteret", "foretak", "bedrift", "organisasjonsnummer" },
items = true,
-- brreg.no is asked once typing pauses, not for every letter on the way.
debounce = true,
-- Nine digits are offered as a number to look up; nothing is asked of brreg.no until Enter.
suggest = function(text)
local number = text:gsub("[%s%.]", "")
if not number:match("^%d%d%d%d%d%d%d%d%d$") then return nil end
return {
title = toolshed.t("suggest", { number = spaced(number) }),
data = { number = number }, actions = { "details" },
}
end,
search = function(rest, settings)
-- "brreg" on its own looks up an organisation number selected where Toolshed was opened
-- from; other selected text is left alone, as it may be anything.
if rest == "" then
local selected = (toolshed.selection() or ""):gsub("[%s%.]", "")
if not selected:match("^%d%d%d%d%d%d%d%d%d$") then return {} end
rest = selected
end
local number = rest:gsub("[%s%.]", "")
if number:match("^%d+$") then
if #number ~= 9 then return {} end
local unit, kind = by_number(number, 1.5)
return unit and { jig(unit, kind) } or {}
end
local ok, found = pcall(get, "enheter?size=15&navn=" .. encode(rest), 1.5)
local jigs = {}
for _, unit in ipairs(ok and found._embedded and found._embedded.enheter or {}) do
table.insert(jigs, jig(unit, "enheter"))
end
return jigs
end,
actions = {
{
key = "details", title = "i18n:action.search.details", icon = "info",
run = function(ctx)
local unit, kind
if ctx.data.kind then
unit, kind = get(ctx.data.kind .. "/" .. ctx.data.number, 10), ctx.data.kind
else
-- A suggested number, not yet looked up: a company or a sub-unit.
unit, kind = by_number(ctx.data.number, 10)
if not unit then error(toolshed.t("not-found", { number = spaced(ctx.data.number) })) end
end
local html, jigs = details(unit, kind, related(unit, kind))
return { html = html, jigs = jigs }
end,
},
{
key = "open", title = "i18n:action.search.open", icon = "external-link", shortcut = "cmd+enter",
run = function(ctx) toolshed.open(page_address(ctx.data)) end,
},
{
key = "copy-number", title = "i18n:action.search.copy-number", icon = "hash", shortcut = "cmd+shift+c",
run = function(ctx)
toolshed.clipboard.copy(ctx.data.number)
return toolshed.t("number-copied")
end,
},
{
key = "copy-name", title = "i18n:action.search.copy-name", icon = "copy",
run = function(ctx)
toolshed.clipboard.copy(ctx.data.name)
return toolshed.t("name-copied")
end,
},
{
key = "copy-address", title = "i18n:action.search.copy-address", icon = "map-pin",
run = function(ctx)
if not ctx.data.address then error(toolshed.t("no-address")) end
toolshed.clipboard.copy(ctx.data.address)
return toolshed.t("address-copied")
end,
},
},
},
},
}