Jump to content
Menü aufrufen
Toggle preferences menu
Persönliches Menü aufrufen
Nicht angemeldet
Ihre IP-Adresse wird öffentlich sichtbar sein, wenn Sie Änderungen vornehmen.
Modul Dokumentation[view][edit][history][purge]
Diese Dokumentation wird von Modul:Company/doc aus übernommen. Änderungen können auf der Diskussionsseite vorgeschlagen werden.
Function list
L 45 — germanRace
L 49 — germanRacePlural
L 56 — germanArgs
L 105 — delink
L 121 — pageTitle
L 137 — splitSemi
L 153 — lastLink
L 169 — foundedDisplay
L 183 — multiList
L 200 — push
L 213 — makeSection
L 267 — p.normalizeRace
L 281 — p.resolveCode
L 290 — p.raceLink
L 308 — collect
L 383 — p.getStructuredData
L 391 — p.getSmwStructuredData
L 400 — p.bucketRows
L 414 — p.getShortDescription
L 436 — p.getCategories
L 452 — p.getHeader
L 478 — p.getContentSections
L 480 — add
L 528 — p.getMetadataSection
L 538 — p.getExternalSitesSection
L 557 — p.getFooterSection
L 579 — p.getSections
L 601 — p.main

Dieses Modul setzt die Vorlage:Unternehmen um. Anweisungen zur Verwendung findest du auf der Vorlagenseite.


require('strict')

--- @module Company
--- Renders the company infobox (Template:Infobox company) via Module:InfoboxLua.
--- Standalone, manual params, no API; pure builders decoupled from p.main so a
--- future organization/faction Entity can consume the company facet.

local infobox = require('Module:InfoboxLua')
local manufacturers = require('Module:Manufacturers')
local button = require('Module:ButtonLua')
local makeList = require('Module:list').makeList
local StructuredData = require('Module:Entity/StructuredData')
local Vocab = require('Module:Entity/Vocab')

local lang = mw.language.getContentLanguage()
local GERMAN_LABELS = {
	Company = 'Unternehmen',
	Industry = 'Branche',
	Products = 'Produkte',
	Race = 'Volk',
	Headquarters = 'Hauptsitz',
	['Area served'] = 'Gebiet',
	['Key people'] = 'Schlüsselpersonen',
	Founder = 'Gründer',
	Founded = 'Gründung',
	People = 'Personal',
	Fate = 'Schicksal',
	Defunct = 'Aufgelöst',
	Formerly = 'Ehemals',
	Predecessor = 'Vorgänger',
	Successor = 'Nachfolger',
	Parent = 'Muttergesellschaft',
	Subsidiaries = 'Tochtergesellschaften',
	Allies = 'Verbündete',
	Rivals = 'Rivalen',
	Metadata = 'Metadaten',
	['Manufacturer code'] = 'Hersteller Code',
	['External sites'] = 'Externe Links',
	Portfolio = 'Portfolio',
	Galactapedia = 'Galactapedia',
	History = 'Geschichte',
	Relations = 'Beziehungen',
}

local function germanRace(race)
	return Vocab.toGerman('race', race)
end

local function germanRacePlural(race)
	if race == 'Mensch' then
		return 'Menschen'
	end
	return race
end

local function germanArgs(args)
	local out = {}
	for key, value in pairs(args) do
		out[key] = value
	end
	local aliases = {
		name = { 'Name', 'Unternehmen' },
		industry = { 'Branche' },
		products = { 'Produkte' },
		race = { 'Volk' },
		headquarters = { 'Hauptsitz' },
		areaserved = { 'Gebiet', 'Einsatzgebiet' },
		founder = { 'Gründer' },
		founded = { 'Gründung' },
		parent = { 'Muttergesellschaft' },
		subsidiaries = { 'Tochtergesellschaften' },
		predecessor = { 'Vorgänger' },
		successor = { 'Nachfolger' },
		image = { 'Bild' },
		imagebg = { 'Bildhintergrund' },
		keypeople = { 'Schlüsselpersonen' },
		fate = { 'Schicksal' },
		defunct = { 'Aufgelöst' },
		formerly = { 'Ehemals' },
		allies = { 'Verbündete' },
		rivals = { 'Rivalen' },
		portfoliourl = { 'Portfolio-URL' },
		galactapediaurl = { 'Galactapedia-URL' },
	}
	for key, names in pairs(aliases) do
		if out[key] == nil then
			for _, name in ipairs(names) do
				if args[name] ~= nil then
					out[key] = args[name]
					break
				end
			end
		end
	end
	return out
end

local p = {}

local PROPERTIES = mw.loadJsonData('Module:Company/properties.json')

--- Strip wiki-link markup, keeping display text: [[A|B]] -> B, [[A]] -> A.
--- @param text string|nil
--- @return string|nil
local function delink(text)
	if not text or text == '' then
		return text
	end
	text = text:gsub('%[%[[^%]|]*|([^%]]-)%]%]', '%1') -- piped link -> label
	text = text:gsub('%[%[([^%]]-)%]%]', '%1') -- simple link -> target
	return text
end

--- Extract the link TARGET (page title) for PAGE-type properties:
--- [[Target|Label]] -> Target, [[Target]] -> Target, plain text -> itself
--- trimmed. A value with a link keeps ONLY that first link's target; trailing
--- markup outside the brackets (e.g. "[[Hurston]] <small>(HQ)</small>") is
--- dropped rather than stored as part of the title.
--- @param text string|nil
--- @return string|nil
local function pageTitle(text)
	if not text or text == '' then
		return text
	end
	local target = text:match('%[%[([^%]|]*)|?[^%]]-%]%]')
	if target then
		return target
	end
	return mw.text.trim(text)
end

--- Split a semicolon-separated list into trimmed, non-empty parts. Semicolon is
--- the multi-value separator (collision-resistant vs commas, which appear inside
--- company names, addresses, and link labels).
--- @param text string
--- @return string[]
local function splitSemi(text)
	local parts = {}
	for part in (text .. ';'):gmatch('([^;]*);') do
		part = mw.text.trim(part)
		if part ~= '' then
			parts[#parts + 1] = part
		end
	end
	return parts
end

--- The TARGET of the last wikilink in a string ([[A|B]] / [[A]] -> A), or nil.
--- Used for Headquarters: the convention is "place, …, system", so the last
--- link of each HQ segment is its star system.
--- @param text string
--- @return string|nil
local function lastLink(text)
	local last
	for target in text:gmatch('%[%[([^%]]-)%]%]') do
		last = mw.text.trim((target:gsub('|.*$', '')))
	end
	if last == '' then
		last = nil
	end
	return last
end

--- Founded display: a bare SC year renders via {{Start date and age}} (so the
--- editor passes a clean year and the stored value is the year, not rendered
--- template output); any other value (full date, "Unknown", …) shows as-is.
--- @param value string|nil
--- @return string|nil
local function foundedDisplay(value)
	if value and value:match('^%s*%d+%s*$') then
		return '{{Start date and age|' .. mw.text.trim(value) .. '|sctime=yes}}'
	end
	return value
end

--- Display helper for multi-value fields: a semicolon list with 2+ items renders
--- as a Module:list unbulleted list with a hanging indent; a single item renders
--- plain. Calls Module:list directly (rather than the {{Unbulleted indent list}}
--- wrapper) to avoid re-parsing a template invocation per field — items pass as
--- Lua values, so piped links need no {{!}} escaping.
--- @param value string|nil
--- @return string|nil
local function multiList(value)
	if not value or value == '' then
		return value
	end
	local items = splitSemi(value)
	if #items <= 1 then
		return value
	end
	-- Hanging indent matches Template:Unbulleted indent list's default.
	items.list_style = 'margin-left:1em;text-indent:-1em'
	return makeList('unbulleted', items)
end

--- Append a {label, content} item only when content is a non-empty string.
--- @param items table[]
--- @param label string
--- @param content string|nil
local function push(items, label, content, backend)
	if content ~= nil and content ~= '' then
		items[#items + 1] =
			{ label = backend == 'bucket' and label or GERMAN_LABELS[label] or label, content = content }
	end
end

--- Build a section from a dense items array; nil when no items survived.
--- InfoboxLua renders an empty <dl> for a section whose items array is
--- non-empty but all-dropped, so filtering MUST happen here.
--- @param items table[]
--- @param opts table|nil  -- { label, collapsible, collapsed, columns, class }
--- @return table|nil
local function makeSection(items, opts, backend)
	if #items == 0 then
		return nil
	end
	local section = { items = items }
	if opts then
		section.label = backend == 'bucket' and opts.label or GERMAN_LABELS[opts.label] or opts.label
		section.collapsible = opts.collapsible
		section.collapsed = opts.collapsed
		section.columns = opts.columns
		section.class = opts.class
	end
	return section
end

local TRANSFORMS = {
	-- Page scalar: single link target.
	page = function(v)
		return pageTitle(v)
	end,
	-- Page list: semicolon-split, each item's link target.
	pageList = function(v)
		local out = {}
		for _, item in ipairs(splitSemi(v)) do
			out[#out + 1] = pageTitle(item)
		end
		return out
	end,
	-- Headquarters: one star system per HQ — the last wikilink of each
	-- semicolon-separated HQ segment (the convention is "place, …, system").
	hqSystems = function(v)
		local out = {}
		for _, segment in ipairs(splitSemi(v)) do
			local sys = lastLink(segment)
			if sys then
				out[#out + 1] = sys
			end
		end
		return out
	end,
	-- Industry/Products: semicolon-split and delinked before backend-specific
	-- capitalization is applied.
	textList = function(v)
		local out = {}
		for _, item in ipairs(splitSemi(v)) do
			out[#out + 1] = delink(item)
		end
		return out
	end,
}

--- Race, trimmed; defaults to "Human" when absent.
--- @param race string|nil
--- @return string
function p.normalizeRace(race)
	race = race and mw.text.trim(race) or ''
	if race == '' then
		return 'Human'
	end
	return race
end

--- Resolve the manufacturer code by looking up the company name via
--- Module:Manufacturers, the single source of truth. There is deliberately no
--- override parameter — the registry is authoritative, so an explicit `code`
--- arg is ignored. Returns nil when the name matches no known manufacturer.
--- @param args table
--- @return string|nil
function p.resolveCode(args)
	local name = args.name and mw.text.trim(args.name) or nil
	local record = name and manufacturers.resolve(name) or nil
	return record and record.code or nil
end

--- The Race infobox cell defaults to Human when no race is provided.
--- @param args table
--- @return string
function p.raceLink(args, backend)
	local race = p.normalizeRace(args.race)
	if backend == 'bucket' then
		local english = race
		return '[[:Category:' .. english .. ' companies|' .. english .. ']]'
	end
	local label = germanRace(race)
	local categoryRace = label == 'Mensch' and 'Menschen' or label
	return '[[:Kategorie:Unternehmen (' .. categoryRace .. ')|' .. label .. ']]'
end

--- Every manifest value for the page, keyed by property: source parameter,
--- trimmed, defaulted, transformed; arrays only when non-empty. Image is
--- validated the way Module:Entity/Base validates it: a
--- leading File: prefix stripped, kept only when `mw.title.new('File:' ..
--- image)` resolves, so an unparseable filename never reaches Bucket.
--- @param args table
--- @return table<string, any>
local function collect(args, preserveTextCase)
	local image = args.image
	if type(image) == 'string' then
		image = mw.text.trim(image):gsub('^[Ff]ile:', ''):gsub('^[Dd]atei:', '')
		if image == '' or not mw.title.new('File:' .. image) then
			image = nil
		end
	else
		image = nil
	end

	local race = args.race and mw.text.trim(args.race) or ''
	if race == '' then
		race = 'Human'
	end
	if preserveTextCase then
		race = p.normalizeRace(args.race)
	end

	local src = {
		name = args.name,
		industry = args.industry,
		products = args.products,
		code = p.resolveCode(args),
		race = race,
		headquarters = args.headquarters,
		areaserved = args.areaserved,
		founder = args.founder,
		founded = args.founded,
		parent = args.parent,
		subsidiaries = args.subsidiaries,
		predecessor = args.predecessor,
		successor = args.successor,
		image = image,
	}

	local data = {}
	for prop, def in pairs(PROPERTIES) do
		if prop:sub(1, 1) ~= '%' then
			local value = src[def.source]
			if type(value) == 'string' then
				value = mw.text.trim(value)
			end
			if (value == nil or value == '') and def.default then
				value = def.default
			end
			if prop == 'Race' and preserveTextCase and value ~= nil then
				value = germanRace(value)
			end
			if value ~= nil and value ~= '' then
				if def.transform then
					value = TRANSFORMS[def.transform](value)
					if def.transform == 'textList' and not preserveTextCase then
						for index, item in ipairs(value) do
							value[index] = lang:lcfirst(item)
						end
					end
				end
				if type(value) == 'table' then
					if #value > 0 then
						data[prop] = value
					end
				elseif value ~= '' then
					data[prop] = value
				end
			end
		end
	end
	return data
end

--- The page's manifest values, keyed by property display name. Pure (no
--- frame); `bucketRows` routes the same values into their Bucket columns.
--- @param args table
--- @return table<string, string|string[]>
function p.getStructuredData(args)
	return collect(args)
end

--- Structured values for the German SMW writer. Text labels retain German
--- capitalization; the English Bucket rows continue to use upstream lcfirst.
--- @param args table
--- @return table<string, string|string[]>
function p.getSmwStructuredData(args)
	return collect(args, true)
end

--- Bucket rows for the page, keyed by bucket: the manifest's bucket/field per
--- property, values shaped by Module:Entity/StructuredData (PAGE titles
--- normalised, repeated values as arrays). Pure (no frame).
--- @param args table
--- @return table<string, table<string, any>>
function p.bucketRows(args, values)
	local rows = {}
	for prop, value in pairs(values or collect(args)) do
		local def = PROPERTIES[prop]
		rows[def.bucket] = rows[def.bucket] or {}
		rows[def.bucket][def.field] = StructuredData.shape(def, value)
	end
	return rows
end

--- Short description: "<race> company in the <industry> industry", or
--- "<race> company in Star Citizen" when no industry. Pure (no frame).
--- @param args table
--- @return string
function p.getShortDescription(args, backend)
	if backend == 'bucket' then
		local race = p.normalizeRace(args.race)
		local industry = args.industry and mw.text.trim(args.industry) or ''
		if industry ~= '' then
			local first = splitSemi(industry)[1] or industry
			return race .. ' company in the ' .. lang:lcfirst(delink(first)) .. ' industry'
		end
		return race .. ' company in Star Citizen'
	end
	local race = germanRacePlural(germanRace(p.normalizeRace(args.race)))
	local industry = args.industry and mw.text.trim(args.industry) or ''
	if industry ~= '' then
		local first = splitSemi(industry)[1] or industry
		return 'Unternehmen der ' .. race .. ' in der Branche ' .. delink(first)
	end
	return 'Unternehmen der ' .. race .. ' im Star-Citizen-Universum'
end

--- Content categories (mainspace gating is the caller's job). Pure.
--- @param args table
--- @return string[]
function p.getCategories(args, backend)
	if backend == 'bucket' then
		return { 'Companies', p.normalizeRace(args.race) .. ' companies' }
	end
	return { 'Unternehmen' }
end

--- @class CompanyHeaderData
--- @field title string
--- @field subtitle string
--- @field image table|nil

--- Header data for InfoboxLua. Pure. image is nil when no filename (InfoboxLua
--- supplies its own placeholder); imagebg maps to the image background class.
--- @param args table
--- @return CompanyHeaderData
function p.getHeader(args, backend)
	local bgClass = nil
	if args.imagebg == 'light' or args.imagebg == 'hell' then
		bgClass = 't-infobox-image--light'
	elseif args.imagebg == 'dark' or args.imagebg == 'dunkel' then
		bgClass = 't-infobox-image--dark'
	end

	local image = nil
	if args.image and args.image ~= '' then
		image = { src = args.image, class = bgClass }
	end

	return {
		title = (args.name and args.name ~= '' and args.name) or mw.title.getCurrentTitle().text,
		subtitle = backend == 'bucket' and 'Company' or 'Unternehmen',
		image = image,
	}
end

--- The grouped content sections: an unlabelled top group (common descriptive
--- fields, always inline) plus collapsible People / History / Relations.
--- Metadata / external-sites / footer are added by getSections. Pure (no
--- frame). Empty rows and empty groups self-drop.
--- @param args table
--- @return table[]
function p.getContentSections(args, backend)
	local sections = {}
	local function add(section)
		if section then
			sections[#sections + 1] = section
		end
	end

	-- Top group (unlabelled) — the common descriptive fields appear immediately,
	-- with no collapse header. Manufacturer code is an identifier, not descriptive
	-- content, so it lives in the collapsed Metadata section, mirroring Entity.
	local top = {}
	push(top, 'Industry', multiList(args.industry), backend)
	push(top, 'Products', multiList(args.products), backend)
	push(top, 'Race', p.raceLink(args, backend), backend) -- always present (defaults to Human)
	push(top, 'Headquarters', multiList(args.headquarters), backend)
	push(top, 'Area served', multiList(args.areaserved), backend)
	add(makeSection(top, nil, backend))

	-- Founding context (Founder + Founded) sits with People rather than the
	-- top group; intentional grouping, differs from Wikipedia's layout.
	local people = {}
	push(people, 'Key people', multiList(args.keypeople), backend)
	push(people, 'Founder', multiList(args.founder), backend)
	push(people, 'Founded', foundedDisplay(args.founded), backend)
	add(makeSection(people, { label = 'People', collapsible = true }, backend))

	local history = {}
	push(history, 'Fate', args.fate, backend)
	push(history, 'Defunct', args.defunct, backend)
	push(history, 'Formerly', args.formerly, backend)
	push(history, 'Predecessor', multiList(args.predecessor), backend)
	push(history, 'Successor', multiList(args.successor), backend)
	add(makeSection(history, { label = 'History', collapsible = true }, backend))

	local relations = {}
	push(relations, 'Parent', args.parent, backend)
	push(relations, 'Subsidiaries', multiList(args.subsidiaries), backend)
	push(relations, 'Allies', multiList(args.allies), backend)
	push(relations, 'Rivals', multiList(args.rivals), backend)
	add(makeSection(relations, { label = 'Relations', collapsible = true }, backend))

	return sections
end

--- Collapsed "Metadata" section for identifiers (manufacturer code) rather than
--- descriptive content, mirroring Module:Entity/Infobox's metadata section.
--- nil when there is no metadata. Pure (no frame).
--- @param args table
--- @return table|nil
function p.getMetadataSection(args, backend)
	local items = {}
	push(items, 'Manufacturer code', p.resolveCode(args), backend)
	return makeSection(items, { label = 'Metadata', collapsible = true, collapsed = true }, backend)
end

--- Collapsed "External sites" section holding the Portfolio link (the Entity
--- external-sites pattern). nil when no portfolio URL.
--- @param args table
--- @return table|nil
function p.getExternalSitesSection(args, backend)
	if not args.portfoliourl or args.portfoliourl == '' then
		return nil
	end
	return {
		label = backend == 'bucket' and 'External sites' or GERMAN_LABELS['External sites'],
		collapsible = true,
		collapsed = true,
		items = {
			{ label = 'Portfolio', content = '[' .. args.portfoliourl .. ' RSI Portfolio]' },
		},
	}
end

--- Footer action row with the Galactapedia button (Module:ButtonLua), mirroring
--- Module:Entity/Infobox buildFooterSection. Flat (not collapsible). nil when no
--- Galactapedia URL.
--- @param args table
--- @return table|nil
function p.getFooterSection(args)
	if not args.galactapediaurl or args.galactapediaurl == '' then
		return nil
	end
	local btn = button.render({
		label = 'Galactapedia',
		url = args.galactapediaurl,
		icon = 'Sc-icon-galactapedia.svg',
		weight = 'normal',
		class = 't-button--galactapedia',
	})
	local actions = mw.html.create('div'):addClass('t-infobox-footer-actions'):wikitext(btn)
	return {
		content = tostring(actions),
		class = 't-infobox-section--footer',
	}
end

--- All infobox sections: content groups, then metadata, then external sites,
--- then footer (mirrors Module:Entity/Infobox's assembly order).
--- @param args table
--- @return table[]
function p.getSections(args, backend)
	local sections = p.getContentSections(args, backend)
	local meta = p.getMetadataSection(args, backend)
	if meta then
		sections[#sections + 1] = meta
	end
	local ext = p.getExternalSitesSection(args, backend)
	if ext then
		sections[#sections + 1] = ext
	end
	local footer = p.getFooterSection(args)
	if footer then
		sections[#sections + 1] = footer
	end
	return sections
end

--- Wikitext entry point. Renders the infobox and wires page-meta.
--- @param frame mw.frame
--- @return string
p.getGermanArgs = germanArgs

function p.main(frame)
	local args = germanArgs(require('Module:Arguments').getArgs(frame))

	local styles = frame:extensionTag({
		name = 'templatestyles',
		args = { src = 'Module:Company/styles.css' },
	})

	local backend = StructuredData.backend()
	local header = p.getHeader(args, backend)
	local html = infobox.render({
		title = header.title,
		subtitle = header.subtitle,
		image = header.image,
		class = 't-company',
		sections = p.getSections(args, backend),
	})

	-- Short description (matches legacy: emitted in every transcluding namespace).
	frame:callParserFunction('SHORTDESC', p.getShortDescription(args, backend))

	-- Structured data + content categories: mainspace only, so /doc and sandbox
	-- pages don't pollute canonical Bucket rows / the category tree.
	local categories = ''
	if mw.title.getCurrentTitle():inNamespace(0) then
		local values = backend == 'smw' and p.getSmwStructuredData(args) or nil
		local storageErr = StructuredData.writeRouted(p.bucketRows(args, values))
		if storageErr then
			local errorCategory = backend == 'bucket' and 'Pages with structured data errors'
				or 'Seiten mit Fehlern in strukturierten Daten'
			categories = categories .. '[[Category:' .. errorCategory .. ']]'
		end
		for _, name in ipairs(p.getCategories(args, backend)) do
			categories = categories .. '[[Category:' .. name .. ']]'
		end
	end

	return styles .. html .. categories
end

-- Vorlage:Unternehmen uses this legacy entrypoint.
p.infoBox = p.main

return p
Cookies helfen uns bei der Bereitstellung dieses Wikis. Durch die Nutzung des Star Citizen Wiki erklärst du dich damit einverstanden, dass wir Cookies speichern.