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:RentalVehicleGrid/doc aus übernommen. Änderungen können auf der Diskussionsseite vorgeschlagen werden.
Function list
L 27 — parseData
L 44 — parseVersion
L 62 — isVersionGreater
L 75 — isDateGreater
L 91 — formatDateString
L 123 — normalizeKey
L 131 — resolveRedirect
L 154 — splitRoles
L 159 — addParts
L 181 — resolveManufacturer
L 208 — getTerminalLocationKeys
L 243 — getUniqueShipNames
L 264 — updateHighestMetadata
L 282 — getCoreDatabase
L 332 — mapWikiShips
L 347 — fetchWikiShipProperties
L 358 — computeRentalPrices
L 370 — footerValues
L 382 — createTableFooter
L 405 — locationEyebrow
L 448 — germanNumber
L 479 — germanError
L 506 — isPageName
L 514 — shipCell
L 531 — locationCell
L 546 — roleCell
L 559 — manufacturerCell
L 580 — imageCell
L 605 — renderSmwTable
L 642 — p.master_table
L 914 — p.main

Rendert die Mietpreistabelle als sortierbare, filterbare Tabelle, eine Zeile pro Fahrzeug/Standort-Paarung zum niedrigsten verfügbaren Mietpreis. Das Backend wählt den Render: auf SMW (dieses Wiki) eine sortierbare Wikitabelle, auf Bucket AG Grid.

Für Editoren

Eine rufende Vorlage existiert auf diesem Wiki noch nicht; nach Anlage ruft sie p.main. Keine Parameter.

Jede Preis-, Fahrzeug- und Terminalzeile kommt von UEX über die Apiunto-Extension; Hersteller, Rolle und Vorschaubild kommen aus Modul:Entity/Store, verschlüsselt nach dem Seitentitel des Schiffs nach Redirect-Auflösung. Ein Schiff, das UEX meldet, ohne dass eine Store-Zeile passt, erscheint trotzdem mit leerem Hersteller/Rolle/Bild.

Für Modul-Editoren

API

  • getCoreDatabase(): holt und indiziert die drei UEX-Datensätze (vehicles_rentals_prices_all, vehicles, terminals); nil plus Fehlermeldung bei fehlender Extension oder unparsebarer Antwort.
  • fetchWikiShipProperties(shipNames): Store.resolvePages auf { manufacturer, role, image } pro Seite, verschlüsselt nach normalizeKey(page).
  • getTerminalLocationKeys(terminal, rental): die Standort-Label(s), unter denen eine Miete gruppiert; Fallback auf die Erkennung von „Vantage“/„Traveler“ im Terminal- oder Firmennamen, wenn UEX' eigener city_name leer ist.
  • p.master_table(frame) / p.main(frame): bauen den Datensatz, lösen Hersteller über Modul:Manufacturers und liefern die Tabelle plus UEX-Attributions-Fußzeile.

Stolperfallen

  • resolveRedirect folgt dem Seiten-Redirect eines Schiffs, bevor jeder Store-Lookup und Anzeige-Link läuft; ein Schiff gruppieren und preisen so unter seinem kanonischen Titel, auch wenn UEX noch den alten Namen meldet.
  • Nur die günstigste Miete pro Fahrzeug/Standort-Paarung überlebt; ein teurerer Duplikat am selben Ort wird verworfen.
  • SMW-Fehlermeldungen der Store-Schicht werden ins Deutsche übersetzt (Präfix-Tabelle); der Footer nennt die Quelle.
  • Modul:RentalVehicleGrid/styles.css formatiert den .t-pledge-grid-Wrapper, den sich dieses Modul mit Modul:PledgeVehicleGrid teilt; jedes Modul lädt seine eigene Kopie.

require('strict')

local p = {}

-- Initialize Apiunto (Wiki extension to fetch remote API data during page parse)
local api = mw.ext.Apiunto

-- Load native Wiki modules
local manufacturers = require('Module:Manufacturers')
local Date = require('Module:Date')._Date
local Store = require('Module:Entity/Store')
local Vocab = require('Module:Entity/Vocab')

-- AG Grid loads only inside p.master_table's Bucket branch: the German wiki
-- has no AGGrid extension, and a load-time require would fail the whole
-- module there before the backend branch is ever reached.
local aggrid
local AGGridColumns

-- Cache resolved manufacturers to avoid redundant lookups
local manufacturerCache = {}

-- Cache resolved redirects to avoid redundant mw.title.new lookups
local redirectCache = {}

-- Helper: Safe JSON decoder that handles UEX response wrapping
local function parseData(rawData)
	if not rawData then
		return nil
	end
	local decoded = nil
	if type(rawData) == 'string' then
		local success, result = pcall(mw.text.jsonDecode, rawData)
		if success then
			decoded = result
		end
	elseif type(rawData) == 'table' then
		decoded = rawData
	end
	return decoded and (decoded.data or decoded) or nil
end

-- Helper: Convert version strings to numeric tables for robust comparison
local function parseVersion(vStr)
	if not vStr or type(vStr) ~= 'string' then
		return { 0, 0, 0, 0 }
	end
	local major, minor, patch, build = vStr:match('^(%d+)%.(%d+)%.(%d+)%-live%.(%d+)')
	if not major then
		major, minor, patch = vStr:match('^(%d+)%.(%d+)%.(%d+)')
		build = vStr:match('(%d+)$')
	end
	return {
		tonumber(major) or 0,
		tonumber(minor) or 0,
		tonumber(patch) or 0,
		tonumber(build) or 0,
	}
end

-- Helper: Numeric comparator for semantic versions
local function isVersionGreater(v1, v2)
	for i = 1, 4 do
		if v1[i] > v2[i] then
			return true
		end
		if v1[i] < v2[i] then
			return false
		end
	end
	return false
end

-- Helper: Safe date comparison supporting timestamps or ISO strings
local function isDateGreater(d1, d2)
	if not d1 then
		return false
	end
	if not d2 then
		return true
	end

	local n1, n2 = tonumber(d1), tonumber(d2)
	if n1 and n2 then
		return n1 > n2
	end
	return tostring(d1) > tostring(d2)
end

-- Helper: Formats timestamp or ISO date to wiki localized format via Module:Date
local function formatDateString(rawDateVal, backend)
	if not rawDateVal then
		return '--'
	end
	local numDate = tonumber(rawDateVal)
	local success, dObj

	if numDate then
		-- Convert Unix timestamp to Julian Date
		local jd = 2440587.5 + numDate / 86400
		success, dObj = pcall(Date, 'juliandate', jd)
	else
		-- Parse ISO date (YYYY-MM-DD) and format via Module:Date
		local y, m, d = tostring(rawDateVal):match('^(%d+)%-%s*(%d+)%-%s*(%d+)')
		if y then
			success, dObj = pcall(Date, { year = tonumber(y), month = tonumber(m), day = tonumber(d) })
		end
	end

	if success and dObj then
		local successFormat, formatted = pcall(function()
			return dObj:text(backend == 'smw' and '%-d. %B %-Y' or '%B %-d %-Y')
		end)
		if successFormat and formatted then
			return formatted
		end
	end

	return tostring(rawDateVal)
end

-- Helper: Normalizes keys for lookup matching
local function normalizeKey(str)
	if not str then
		return ''
	end
	return mw.text.trim(tostring(str)):lower()
end

-- Helper: Automatically resolve redirect pages (e.g. "Dragonfly Black" -> "Dragonfly") via Scribunto mw.title
local function resolveRedirect(pageName)
	if not pageName or pageName == '' then
		return pageName
	end
	if redirectCache[pageName] then
		return redirectCache[pageName]
	end

	local resolved = pageName
	local success, title = pcall(mw.title.new, pageName)
	if success and title then
		if title.isRedirect then
			local target = title.redirectTarget
			if target and target.prefixedText then
				resolved = target.prefixedText
			end
		end
	end
	redirectCache[pageName] = resolved
	return resolved
end

-- Helper: Splits combined roles (e.g. "Gunship / Light Freight") into a table list
local function splitRoles(val)
	if not val then
		return nil
	end
	local roles = {}
	local function addParts(str)
		for part in str:gmatch('[^/,]+') do
			part = mw.text.trim(part)
			if part ~= '' and part ~= '--' then
				table.insert(roles, part)
			end
		end
	end

	-- Role is a repeated Bucket field, so the read already gives one value per
	-- role; older rows still arrive as a single separator-joined string.
	if type(val) == 'table' then
		for _, part in ipairs(val) do
			addParts(part)
		end
	else
		addParts(val)
	end
	return #roles > 0 and roles or nil
end

-- Helper: Resolve manufacturer details using Module:Manufacturers
local function resolveManufacturer(name)
	if type(name) ~= 'string' or name == '' or name == '--' then
		return '--', '--', '--'
	end
	local key = name:lower()

	local cache = manufacturerCache[key]
	if cache then
		return cache.code, cache.page, cache.short
	end

	local resolved = manufacturers.resolve(name)
	local entry
	if resolved then
		entry = {
			code = resolved.code or '--',
			page = resolved.page or '--',
			short = resolved.name or resolved.short or '--',
		}
	else
		entry = { code = name, page = name, short = name }
	end
	manufacturerCache[key] = entry
	return entry.code, entry.page, entry.short
end

-- Helper: Determine location keys from terminal data
local function getTerminalLocationKeys(terminal, rental)
	if terminal and (terminal.id_city or 0) > 0 and terminal.city_name and terminal.city_name ~= '' then
		return { terminal.city_name }
	end

	local name = ((terminal and terminal.fullname) or (rental and rental.terminal_name) or ''):lower()
	local matched = {}

	local isVantage = name:find('vantage')
		or (
			terminal
			and ((terminal.company_name or ''):lower():find('vantage') or (terminal.name or ''):lower():find('vantage'))
		)
	if isVantage then
		table.insert(matched, 'Refinery Deck')
	end

	local isTraveler = name:find('traveler')
		or (
			terminal
			and (
				(terminal.company_name or ''):lower():find('traveler')
				or (terminal.name or ''):lower():find('traveler')
			)
		)
	if isTraveler then
		if (tonumber(terminal and terminal.is_shop_vehicle) or 0) == 0 then
			table.insert(matched, 'Cargo Deck')
		end
	end

	return #matched > 0 and matched or { '--' }
end

-- Helper: Compile list of unique rentable ship names to target our Store query
local function getUniqueShipNames(db)
	local shipNamesMap = {}
	local shipNames = {}
	for _, rental in ipairs(db.prices) do
		local vehicleId = rental.id_vehicle
		if vehicleId then
			local vehicleSpec = db.vehicles[vehicleId] or {}
			local shipName = vehicleSpec.name or rental.vehicle_name
			if shipName and shipName ~= '' then
				local targetName = resolveRedirect(shipName)
				if not shipNamesMap[targetName] then
					shipNamesMap[targetName] = true
					table.insert(shipNames, targetName)
				end
			end
		end
	end
	return shipNames
end

-- Helper: Updates running highest version and latest date modified
local function updateHighestMetadata(spec, highestParsed, highestVersionStr, highestDateVal)
	local ver = spec.game_version or spec.version
	if ver then
		local parsed = parseVersion(ver)
		if isVersionGreater(parsed, highestParsed) then
			highestParsed = parsed
			highestVersionStr = ver
		end
	end

	local dateVal = spec.date_modified
	if dateVal and (not highestDateVal or isDateGreater(dateVal, highestDateVal)) then
		highestDateVal = dateVal
	end
	return highestParsed, highestVersionStr, highestDateVal
end

-- Fetch UEX API datasets
local function getCoreDatabase()
	if not api then
		return nil, 'Error: Apiunto extension not loaded.'
	end

	local ok1, rawPrices = pcall(api.fetch, 'UEX', 'vehicles_rentals_prices_all')
	local ok2, rawVehicles = pcall(api.fetch, 'UEX', 'vehicles')
	local ok3, rawTerminals = pcall(api.fetch, 'UEX', 'terminals')

	if not ok1 then
		return nil, 'Error: Failed to fetch pricing. Apiunto: ' .. tostring(rawPrices)
	end
	if not ok2 then
		return nil, 'Error: Failed to fetch vehicles. Apiunto: ' .. tostring(rawVehicles)
	end

	local pricesList = parseData(rawPrices)
	local vehiclesList = parseData(rawVehicles)
	local terminalsList = parseData(rawTerminals) or {}

	if not pricesList or not vehiclesList then
		return nil, 'Error: UEX data successfully returned, but structures could not be parsed as valid JSON.'
	end

	local vehiclesById = {}
	for _, vehicle in ipairs(vehiclesList) do
		if vehicle.id then
			vehiclesById[vehicle.id] = vehicle
		end
	end

	local terminalsById = {}
	for _, terminal in ipairs(terminalsList) do
		if terminal.id then
			terminalsById[terminal.id] = terminal
		end
	end

	return {
		prices = pricesList,
		vehicles = vehiclesById,
		terminals = terminalsById,
	}
end

--- Maps Module:Entity/Store's resolvePages rows (bare titles, keyed by page
--- name) to this module's lookup shape (manufacturer, role, image, keyed by
--- normalizeKey(page)).
--- @param rows table<string, { name: string|nil, manufacturer: string|nil, role: string|nil, image: string|nil }>
--- @return table<string, { manufacturer: string|nil, role: string|nil, image: string|nil }>
local function mapWikiShips(rows)
	local wikiShips = {}
	for page, row in pairs(rows) do
		wikiShips[normalizeKey(page)] = {
			manufacturer = row.manufacturer,
			role = row.role,
			image = row.image,
		}
	end
	return wikiShips
end

--- Query Bucket for ship properties via Module:Entity/Store.
--- @param shipNames string[]
--- @return table<string, { manufacturer: string|nil, role: string|nil, image: string|nil }>
local function fetchWikiShipProperties(shipNames)
	if not shipNames or #shipNames == 0 then
		return {}
	end

	return mapWikiShips(Store.resolvePages(shipNames))
end

-- The three rental prices for one pairing: 3 days at 10% off, 7 days at 25%
-- off, both rounded half up. A missing or nonpositive daily price has no
-- discounted prices either, rather than a free rental.
local function computeRentalPrices(rawPrice)
	local price1d = tonumber(rawPrice)
	if not price1d or price1d <= 0 then
		return nil, nil, nil
	end
	return price1d, math.floor(price1d * 3 * 0.90 + 0.5), math.floor(price1d * 7 * 0.75 + 0.5)
end

-- Footer display values: the version as 'Alpha X.Y.Z' when it parses, verbatim
-- otherwise, and '--' when unknown; the date verbatim with the same fallback.
-- Both stay unescaped: the Bucket render must keep the upstream footer byte
-- for byte, so the SMW render escapes at its own call site.
local function footerValues(versionStr, dateStr)
	local displayVersion = '--'
	if versionStr and versionStr ~= 'Unknown Version' then
		local cleaned = versionStr:match('^([%d%.]+)')
		displayVersion = cleaned and ('Alpha ' .. cleaned) or versionStr
	end
	local displayDate = dateStr or '--'
	return displayVersion, displayDate
end

-- Generate table footer containing update metadata and partner badge. Both
-- renders share it; only the update line's wording is the caller's.
local function createTableFooter(displayVersion, displayDate, updateCaption)
	local container = mw.html
		.create('div')
		:css('display', 'flex')
		:css('flex-wrap', 'wrap')
		:css('align-items', 'center')
		:css('gap', '1em')
		:css('margin-top', '0.65em')
		:css('font-size', '0.85em')
		:css('color', '#a2a9b1')

	container
		:tag('div')
		:css('display', 'flex')
		:css('align-items', 'center')
		:wikitext('[[File:Powered by UEX.png|class=metadata|link=https://uexcorp.space|140px|powered by UEX]]')

	container:tag('div'):css('font-style', 'italic'):wikitext(updateCaption)

	return container
end

-- Helper: Build the location eyebrow (Location Name) for the ship card column
local function locationEyebrow(result)
	local name = result['locKey']
	if type(name) ~= 'string' or name == '' then
		return nil
	end
	-- `aggrid` is assigned in the Bucket branch, the only render that runs this.
	local link = aggrid.link(name, name)
	return { text = name, full = name, href = link and link.href }
end

-- German display labels for the SMW render. aUEC and the UEX-reported ship
-- and city names stay verbatim. The grouping keys (locKey) keep the UEX
-- strings so grouping is untouched.
local SMW_LABELS = {
	image = 'Bild',
	ship = 'Raumschiff',
	location = 'Ort',
	manufacturer = 'Hersteller',
	role = 'Rolle',
	price1d = '1 Tag',
	price3d = '3 Tage (-10%)',
	price7d = '7 Tage (-25%)',
	-- \226\128\162 is the U+2022 bullet separator, written as byte escapes
	-- because edit tooling normalizes a literal bullet to ASCII.
	updated = 'Letzte Aktualisierung: %s \226\128\162 Star Citizen %s',
	-- A deck fallback label is also its link target. Canonical German governs
	-- even where the wiki still holds the English page name ('Cargo Deck' is
	-- the German wiki's live article title): the targets are the canonical
	-- German terms, and the links stay red until those pages exist.
	locations = {
		['Cargo Deck'] = 'Frachtdeck',
		['Refinery Deck'] = 'Raffineriedeck',
	},
}

-- Thumbnail width for the SMW table's image column. This render loads no
-- stylesheet, so the wikitext size parameter is the only sizing control.
local SMW_IMAGE_WIDTH = '120px'

-- German display format for a price: dot thousands grouping, comma decimal.
-- Formatted directly rather than through mw.language:formatNum, whose output
-- follows the wiki's content language, so the German output is identical
-- wherever the SMW backend renders.
local function germanNumber(n)
	-- The whole absolute value is formatted at once so a fraction that rounds
	-- up to 1 at the 6th decimal (0.9999999) carries into the integer part
	-- instead of rendering as ",1".
	local intPart, fracPart = string.format('%.6f', math.abs(n)):match('^(%d+)%.([%d]+)$')
	fracPart = fracPart:gsub('0+$', '')
	local grouped = intPart:reverse():gsub('(%d%d%d)', '%1.')
	grouped = grouped:reverse():gsub('^%.', '')
	local out = n < 0 and '-' or ''
	out = out .. grouped
	if fracPart ~= '' then
		out = out .. ',' .. fracPart
	end
	return out
end

-- German fetch errors for the SMW render, keyed by getCoreDatabase's English
-- messages: 'Failed to fetch' strings carry the extension's error detail after
-- a fixed prefix, so they match by prefix. The Bucket render keeps the English
-- strings upstream ships.
local SMW_ERRORS = {
	exact = {
		['Error: Apiunto extension not loaded.'] = 'Fehler: Die Erweiterung Apiunto ist nicht geladen.',
		['Error: UEX data successfully returned, but structures could not be parsed as valid JSON.'] = 'Fehler: Die UEX-Daten wurden zwar empfangen, ließen sich aber nicht als gültiges JSON auswerten.',
	},
	prefix = {
		['Error: Failed to fetch pricing. Apiunto: '] = 'Fehler: Mietpreise konnten nicht abgerufen werden. Apiunto: ',
		['Error: Failed to fetch vehicles. Apiunto: '] = 'Fehler: Fahrzeuge konnten nicht abgerufen werden. Apiunto: ',
	},
}

local function germanError(message)
	if type(message) ~= 'string' then
		return message
	end
	local german = SMW_ERRORS.exact[message]
	if not german then
		for english, translation in pairs(SMW_ERRORS.prefix) do
			if message:sub(1, #english) == english then
				german = translation .. message:sub(#english + 1)
				break
			end
		end
	end
	-- The Apiunto detail is remote text appended after a fixed prefix; escaped
	-- so it renders as text, not parses as markup.
	return mw.text.nowiki(german or message)
end

-- SMW table cell helpers. A ship links its redirect target under the
-- UEX-reported name; a location links the UEX key or its German label; a
-- missing value is an empty cell, never a shifted row.

-- Whether an untrusted string names a main-namespace page: a Title cannot hold
-- the wikitext link delimiters, so a name that passes is safe to interpolate
-- into link markup, and one that does not renders as escaped plain text
-- instead. mw.title.new is pcall'd because resolveRedirect guards it the same
-- way; on-wiki it answers nil for invalid names rather than raising.
local function isPageName(name)
	if type(name) ~= 'string' or name == '' then
		return false
	end
	local ok, title = pcall(mw.title.new, name)
	return ok and title ~= nil and title.namespace == 0
end

local function shipCell(result)
	local label = result.Name
	if label == '' or label == '--' then
		label = nil
	end
	local target = result.target
	-- A UEX-reported name that is no valid page title renders as text, not as
	-- markup: escaping keeps a name carrying ]] or | inert.
	if not target or target == '--' or not isPageName(target) then
		return label and mw.text.nowiki(label) or ''
	end
	if label and label ~= target then
		return '[[' .. target .. '|' .. mw.text.nowiki(label) .. ']]'
	end
	return '[[' .. target .. ']]'
end

local function locationCell(locKey)
	if not locKey or locKey == '' or locKey == '--' then
		return ''
	end
	local label = SMW_LABELS.locations[locKey] or locKey
	if not isPageName(label) then
		return mw.text.nowiki(label)
	end
	return '[[' .. label .. ']]'
end

-- A role arrives as an English machine token, the store's read-back contract:
-- SMW holds the German value and Store/Smw hands the token back, so the cell
-- translates through Vocab for display. Unmapped tokens pass through
-- untranslated; every value is escaped plain text.
local function roleCell(role)
	local values = type(role) == 'table' and role or { role }
	local out = {}
	for i, value in ipairs(values) do
		out[i] = mw.text.nowiki(Vocab.toGerman('role', tostring(value)))
	end
	return table.concat(out, ', ')
end

-- A manufacturer links its resolved page under the display name. Built from
-- the raw parts, not the grid's prebuilt [[Target|Display]] markup, because an
-- unresolvable manufacturer falls back to the stored string as page and
-- label alike, and that raw value must not reach wikitext as markup.
local function manufacturerCell(result)
	local target = result.companyPage
	if not target then
		return ''
	end
	local label = result.companyName or target
	if not isPageName(target) then
		return mw.text.nowiki(label)
	end
	if label ~= target then
		return '[[' .. target .. '|' .. mw.text.nowiki(label) .. ']]'
	end
	return '[[' .. target .. ']]'
end

-- A thumbnail linked to the row's ship page. Both the stored filename and the
-- UEX ship name reach wikitext, so both are validated as Titles: a rejected
-- filename drops its own cell, and a rejected ship page keeps the thumbnail
-- without its link, mirroring Module:DataGrid/Static's guard. A namespace
-- prefix is stripped because the SMW writer stores images with one
-- ('Datei:...').
local function imageCell(value, page)
	if type(value) ~= 'string' or value == '' then
		return ''
	end
	local file = value:gsub('^%a+:', '')
	if file == '' then
		return ''
	end
	local ok, fileTitle = pcall(mw.title.new, 'File:' .. file)
	if not ok or not fileTitle then
		return ''
	end
	if isPageName(page) then
		return '[[File:' .. file .. '|' .. SMW_IMAGE_WIDTH .. '|link=' .. page .. ']]'
	end
	return '[[File:' .. file .. '|' .. SMW_IMAGE_WIDTH .. ']]'
end

-- The German wiki's render: the same computed rows as the AG Grid, as a plain
-- sortable wikitable. The German wiki has no AGGrid extension, so this branch
-- loads neither it nor Module:AGGridColumns. It adds no queries of its own,
-- but the row pipeline it shares with the grid still ran Module:Entity/Store
-- enrichment, which on SMW is one #ask per unique rentable ship page.
-- Header-click sorting and browser find cover the grid's sorting and search;
-- the grid's set filters, column resize and expand do not exist here.
local function renderSmwTable(results, displayVersion, displayDate)
	local root = mw.html.create('table'):addClass('wikitable'):addClass('sortable')
	local header = root:tag('tr')
	header:tag('th'):addClass('unsortable'):wikitext(SMW_LABELS.image)
	header:tag('th'):wikitext(SMW_LABELS.ship)
	header:tag('th'):wikitext(SMW_LABELS.location)
	header:tag('th'):wikitext(SMW_LABELS.manufacturer)
	header:tag('th'):wikitext(SMW_LABELS.role)
	header:tag('th'):wikitext(SMW_LABELS.price1d)
	header:tag('th'):wikitext(SMW_LABELS.price3d)
	header:tag('th'):wikitext(SMW_LABELS.price7d)

	for _, result in ipairs(results) do
		local tr = root:tag('tr')
		tr:tag('td'):wikitext(imageCell(result.Image, result.target))
		tr:tag('td'):wikitext(shipCell(result))
		tr:tag('td'):wikitext(locationCell(result.locKey))
		tr:tag('td'):wikitext(manufacturerCell(result))
		tr:tag('td'):wikitext(roleCell(result.Role))
		for _, key in ipairs({ 'price1d', 'price3d', 'price7d' }) do
			local td = tr:tag('td')
			local price = result[key]
			if price then
				-- Numeric sort key: the German grouped display would otherwise
				-- sort as text ('9.000' after '12.000').
				td:attr('data-sort-value', tostring(price)):wikitext(germanNumber(price) .. ' aUEC')
			end
		end
	end

	local footer =
		createTableFooter(displayVersion, displayDate, string.format(SMW_LABELS.updated, displayDate, displayVersion))
	return tostring(root) .. tostring(footer)
end

-- MODULE ENTRY POINT: MASTER RENTAL TABLE. One shared row pipeline; the
-- backend selects the render (wikitable on SMW, AG Grid on Bucket).
function p.master_table(frame)
	local backend = require('Module:Entity/StructuredData').backend()
	local db, err = getCoreDatabase()
	if not db then
		if backend == 'smw' then
			err = germanError(err)
		end
		return tostring(mw.html.create('div'):addClass('error'):wikitext(err or 'Failed to load database'))
	end

	-- Compile list of unique rentable ship names to target our Store query
	local shipNames = getUniqueShipNames(db)
	local wikiShips = fetchWikiShipProperties(shipNames)

	local seen = {}

	for _, rental in ipairs(db.prices) do
		local vehicleId = rental.id_vehicle
		if vehicleId then
			local vehicleSpec = db.vehicles[vehicleId] or {}
			local terminalSpec = db.terminals[rental.id_terminal] or {}
			local locKeys = getTerminalLocationKeys(terminalSpec, rental)

			for _, locKey in ipairs(locKeys) do
				if locKey ~= '--' and locKey ~= '' then
					local uniqKey = vehicleId .. '_' .. locKey
					local existing = seen[uniqKey]

					local currentPrice = tonumber(rental.price_rent) or 0
					local existingPrice = existing and (tonumber(existing.rental.price_rent) or 0) or 0

					if not existing or (currentPrice > 0 and (existingPrice == 0 or currentPrice < existingPrice)) then
						local shipName = vehicleSpec.name or rental.vehicle_name or '--'
						local targetName = resolveRedirect(shipName)

						local wikiData = wikiShips[normalizeKey(targetName)] or {}
						local compCode, compPage, compShort = resolveManufacturer(wikiData.manufacturer)
						local role = splitRoles(wikiData.role)

						seen[uniqKey] = {
							rental = rental,
							vehicleSpec = vehicleSpec,
							locKey = locKey,
							companyCode = compCode,
							companyPage = compPage,
							companyShort = compShort,
							name = shipName,
							role = role,
						}
					end
				end
			end
		end
	end

	local displayList = {}
	local highestVersionStr = 'Unknown Version'
	local highestParsed = { 0, 0, 0, 0 }
	local highestDateVal = nil

	for _, item in pairs(seen) do
		highestParsed, highestVersionStr, highestDateVal =
			updateHighestMetadata(item.vehicleSpec, highestParsed, highestVersionStr, highestDateVal)
		table.insert(displayList, item)
	end

	table.sort(displayList, function(a, b)
		if a.name ~= b.name then
			return a.name < b.name
		end
		if a.locKey ~= b.locKey then
			return a.locKey < b.locKey
		end
		return a.companyShort < b.companyShort
	end)

	local FMT_AUEC = { style = 'number', suffix = ' aUEC' }

	local columns = {
		{
			field = 'ship',
			header = 'Ship / Location',
			kind = 'card',
			titleLabel = 'Name',
			imageLabel = 'Image',
			eyebrow = locationEyebrow,
			filter = 'aggridSet',
			filterOn = 'eyebrow',
			width = 240,
			minWidth = 180,
			flex = 1,
			sort = 'asc',
		},
		{ field = 'shipName', header = 'Ship Name', kind = 'text', label = 'Name', hide = true },
		{
			field = 'company',
			header = 'Manufacturer',
			kind = 'link',
			label = 'Manufacturer',
			filter = 'aggridSet',
			width = 190,
			minWidth = 140,
		},
		{
			field = 'locationName',
			header = 'Location',
			kind = 'text',
			label = 'locKey',
			filter = 'aggridSet',
			hide = true,
		},
		{
			field = 'role',
			header = 'Role',
			kind = 'valueList',
			label = 'Role',
			filter = 'aggridSet',
			-- Cells hold one line, so this has to fit the longest value rather than
			-- wrap it: two roles joined by a comma ("Starter, Light Fighter") need
			-- about 160px once the cell's own padding is counted.
			width = 175,
			minWidth = 120,
		},
	}
	table.insert(columns, {
		field = 'price1d',
		header = '1 Day Price',
		kind = 'number',
		format = FMT_AUEC,
		label = 'price1d',
		filter = 'agNumberColumnFilter',
		width = 125,
		minWidth = 90,
	})
	table.insert(columns, {
		field = 'price3d',
		header = '3 Days (-10%)',
		kind = 'number',
		format = FMT_AUEC,
		label = 'price3d',
		filter = 'agNumberColumnFilter',
		width = 125,
		minWidth = 90,
	})
	table.insert(columns, {
		field = 'price7d',
		header = '7 Days (-25%)',
		kind = 'number',
		format = FMT_AUEC,
		label = 'price7d',
		filter = 'agNumberColumnFilter',
		width = 125,
		minWidth = 90,
	})

	-- Sorted, grouped rows carrying every field a render reads. Both renders
	-- share the price math and enrichment; `target` is the redirect-resolved
	-- page, which the SMW table links under the UEX-reported name.
	local results = {}
	for _, item in ipairs(displayList) do
		local price1d, price3d, price7d = computeRentalPrices(item.rental.price_rent)
		local targetName = resolveRedirect(item.name)
		local wikiData = wikiShips[normalizeKey(targetName)] or {}

		local result = {
			-- [[Target|Display]] markup, not a bare title: it carries a target and a
			-- different display name, and the link kind's single `label` key has no
			-- other way to carry both.
			Manufacturer = item.companyPage ~= '--' and ('[[' .. item.companyPage .. '|' .. item.companyShort .. ']]')
				or nil,
			-- Raw manufacturer parts for renders that build the link themselves;
			-- an unresolvable manufacturer stores its raw string in both.
			companyPage = item.companyPage ~= '--' and item.companyPage or nil,
			companyName = item.companyShort ~= '--' and item.companyShort or nil,
			Name = item.name ~= '--' and item.name or nil,
			Image = wikiData.image,
			Role = item.role,
			locKey = item.locKey ~= '--' and item.locKey or nil,
			price1d = price1d,
			price3d = price3d,
			price7d = price7d,
			target = targetName,
		}
		table.insert(results, result)
	end

	local displayVersion, displayDate = footerValues(highestVersionStr, formatDateString(highestDateVal, backend))

	-- The German wiki's store selects the wikitable render; the AG Grid render
	-- below is the upstream path and stays as it is.
	if backend == 'smw' then
		-- Both values are remote UEX strings (the verbatim version, the date that
		-- parses as neither timestamp nor ISO date), so they are escaped before
		-- they reach a wikitext caption. The '--' placeholders stay plain,
		-- because nowiki would entity-encode their leading dash.
		if displayVersion ~= '--' then
			displayVersion = mw.text.nowiki(displayVersion)
		end
		if displayDate ~= '--' then
			displayDate = mw.text.nowiki(displayDate)
		end
		return renderSmwTable(results, displayVersion, displayDate)
	elseif backend ~= 'bucket' then
		error('Unknown structured-data backend: ' .. tostring(backend))
	end

	aggrid = require('mw.ext.aggrid')
	AGGridColumns = require('Module:AGGridColumns')

	local colDefs = AGGridColumns.buildColumnDefs(columns)
	local specMap = {}
	for _, spec in ipairs(columns) do
		specMap[spec.field] = spec
	end
	for _, def in ipairs(colDefs) do
		local spec = specMap[def.field]
		if spec then
			if spec.width then
				def.width = spec.width
			end
			if spec.minWidth then
				def.minWidth = spec.minWidth
			end
			if spec.flex then
				def.flex = spec.flex
			end
			if spec.hide ~= nil then
				def.hide = spec.hide
			end
			if spec.sort then
				def.sort = spec.sort
			end
		end
	end

	local rowHeight = 64

	local gridOptions = {
		columnDefs = colDefs,
		rowData = AGGridColumns.buildRowData(results, columns),
		quickSearch = true,
		includeHiddenColumnsInQuickFilter = true,
		expand = true,
		pagination = false,
		rowHeight = rowHeight,
		autoSizeStrategy = { type = 'fitGridWidth' },
		defaultColDef = { sortable = true, resizable = true },
	}

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

	local footer = createTableFooter(
		displayVersion,
		displayDate,
		string.format('Last updated: %s \226\128\162 Star Citizen %s', displayDate, displayVersion)
	)

	local mediaSize = rowHeight - 12
	local wrapperStyle = 'width: 100%; --scw-entitycard-media-size: ' .. mediaSize .. 'px;'

	return styles
		.. '<div class="t-pledge-grid" style="'
		.. wrapperStyle
		.. '">'
		.. aggrid.render(gridOptions)
		.. '</div>'
		.. tostring(footer)
end

function p.main(frame)
	return p.master_table(frame)
end

-- Test-only exports. Not part of the public API.
--- @class RentalVehicleGridInternal
--- @field mapWikiShips fun(rows: table): table
--- @field germanNumber fun(n: number): string
p._internal = {
	mapWikiShips = mapWikiShips,
	germanNumber = germanNumber,
}

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.