Modul:Entity/Commodity
Aus Star Citizen Wiki
Weitere Optionen
Die Dokumentation für dieses Modul kann unter Modul:Entity/Commodity/doc erstellt werden
require('strict')
--- @module Entity/Commodity
--- Commodity kind. Backed by the /api/commodities endpoint (a substance-level
--- entity), distinct from the per-cargo-box /items records. Renders one unified
--- page per substance; the raw and refined records are merged via the enrich
--- hook (record assembly lives in Module:Entity/Commodity/Records).
--- Type/group come from the API `commodity_groups` taxonomy (parent + finest
--- leaf); see the LABELS / CATEGORIES maps below.
--- Mining-stat formatting lives in Module:Entity/Commodity/Mining.
local format = require('Module:Entity/Format')
local mining = require('Module:Entity/Commodity/Mining')
local records = require('Module:Entity/Commodity/Records')
local acq = require('Module:Entity/Acquisition')
local Boolean = require('Module:Boolean')
local msg = require('Module:Entity/Message').msg
local Vocab = require('Module:Entity/Vocab')
-- API commodity_groups token → German display label. Drives the infobox Typ
-- row, the short description, and the stored Warengruppe / Warenart values
-- (D5: SMW holds German). Mineral/Metall/Halogen/Lebensmittel are grounded in
-- the live singular categories; the rest are approved coinages.
local LABELS = {
ProcessedGoods = 'Verarbeitete Güter',
Vice = 'Genussmittel',
SyntheticMaterials = 'Synthetische Materialien',
Bulk_Supplies = 'Massenware',
Metal = 'Metall',
Alloy = 'Legierung',
UnrefinedOres = 'Unverarbeitete Erze',
Organic = 'Organisch',
Food = 'Lebensmittel',
Mineral = 'Mineral',
Raw_Minerals = 'Rohmineralien',
Gas = 'Gas',
Nonmetal = 'Nichtmetall',
Halogen = 'Halogen',
Waste = 'Abfall',
}
-- Parent (first commodity_groups element) → group category page name, singular
-- German per the wiki's category habit (live: Mineral, Metall, Halogen,
-- Lebensmittel). A parent absent here is a placeholder / unknown
-- (HeatPlaceholder, PowerPlaceholder, LifeSupportPlaceholder, CleanAir) → no
-- group, no category. Doubles as the valid-parent allowlist.
local CATEGORIES = {
ProcessedGoods = 'Verarbeitete Güter',
Metal = 'Metall',
Organic = 'Organisch',
Mineral = 'Mineral',
Gas = 'Gas',
Nonmetal = 'Nichtmetall',
Waste = 'Abfall',
}
--- Parses apiData.commodity_groups (ordered parent→child; last = finest type)
--- into its parent + leaf tokens. Returns nil when the array is absent/empty or
--- the parent is a placeholder/unknown (not in CATEGORIES), so unmapped
--- commodities collapse cleanly (no Type row, no group, no group category).
---
--- @param apiData table
--- @return { parent: string, leaf: string }|nil
local function resolveGroups(apiData)
local groups = apiData.commodity_groups
if type(groups) ~= 'table' or groups[1] == nil then
return nil
end
local parent = groups[1]
if CATEGORIES[parent] == nil then
return nil
end
return { parent = parent, leaf = groups[#groups] }
end
local p = {}
--- Canonical kind name, exposed as Data.get(args).kind (non-empty and
--- unique, enforced by the Registry conformance test).
p.name = 'Commodity'
--- @type string
p.parent = 'Entity/Base'
--- @return EntityApiConfig[]
function p.getApiConfigs()
return {
{
name = 'StarCitizenWikiAPI',
endpoint = 'commodities/%s',
-- `items` links the substance to its in-game item records (cargo boxes
-- and, for edible commodities, a Harvestable item that carries the
-- `food` object). p.enrich reads it to light up the consumable facet.
-- de_DE is a no-op on /commodities (byte-identical responses, probed
-- 2026-11-03); requested for chain consistency.
params = { locale = 'de_DE', include = 'items' },
responseDataPath = 'data',
},
}
end
--- Positive identification: commodity records carry `box_sizes_scu` (the SCU
--- packaging ladder), a field neither items nor vehicles return. Safe on
--- nil / empty / malformed apiData (returns false, never throws).
---
--- @param apiData table|nil
--- @return boolean
function p.matches(apiData)
return apiData ~= nil and apiData.box_sizes_scu ~= nil
end
--- Post-fetch hook (run by Module:Entity/Data's chain enrich pass; Commodity is
--- its own chain's only enrich link). Delegates record assembly to
--- Module:Entity/Commodity/Records, passing the commodities endpoint config so
--- the counterpart fetch stays single-sourced here.
---
--- @param ctx EntityHookContext
--- @return table apiData (mutated and returned)
function p.enrich(ctx)
return records.enrich(ctx.apiData, p.getApiConfigs()[1])
end
-- Public alias so sibling renderers (Module:Entity/Availability) can title the
-- Mining card with the same method-aware label the infobox uses.
p.acquisitionLabel = mining.acquisitionLabel
--- Resolves display metadata from the API commodity_groups taxonomy. `name` is
--- the finest type (leaf) label → infobox subtitle + Typ row. `category` is the
--- parent group category (Metall, Mineral, ...). `categories` carries the extra
--- Handelsware membership (159 live pages) so the index Data table can query
--- every commodity in one category
--- (Module:Entity/Categories honours typeInfo.categories). Returns nil for
--- placeholder/unmapped parents so the subtitle and categories collapse out.
---
--- @param ctx EntityHookContext
--- @return table|nil { name, category, categories }
function p.getTypeInfo(ctx)
local apiData = ctx.apiData
local g = resolveGroups(apiData)
if not g then
return nil
end
return {
name = LABELS[g.leaf],
category = CATEGORIES[g.parent],
categories = { 'Handelsware' },
}
end
--- @param ctx EntityHookContext
--- @return table[]
function p.getSections(ctx)
local apiData = ctx.apiData
local raw = apiData._rawRecord
local refined = apiData._refinedRecord or apiData
local typeInfo = p.getTypeInfo(ctx)
local tier = apiData.tier or (raw and raw.tier)
local refinable = (apiData.refined_version and apiData.refined_version.uuid)
or (refined and refined.raw_versions and refined.raw_versions[1])
-- `systems` is intentionally NOT an infobox row: the set of star systems
-- grows as the game expands, so an enumerated list doesn't scale. The
-- per-system Deposit-locations tables are the scalable home for "where",
-- and `systems` is still persisted to structured data for querying.
local overview = {
key = 'overview',
items = {
{ label = msg('Type'), content = typeInfo and typeInfo.name },
{
label = msg('Rarity'),
content = tier and (Vocab.toGerman('rarity', tier) or tier:gsub('^%l', string.upper)),
},
{ label = msg('Acquisition'), content = mining.acquisitionLabel(raw, apiData.kind or (raw and raw.kind)) },
-- `refinable` is a uuid / version object (presence = refinable), not a
-- boolean, so render the presence flag rather than the raw value.
{ label = msg('Refinable'), content = refinable ~= nil and Boolean.render(true) or nil },
},
}
local sections = { overview }
if raw and raw.is_mineable then
local items = {}
-- Signature is a scan/detectability stat that applies to any acquisition
-- method (ship, vehicle, FPS, harvesting), so it shows whenever present.
if raw.signature then
items[#items + 1] = { label = msg('Signature'), content = format.formatNum(raw.signature) }
end
-- Instability / resistance are laser-mining mechanics (ship & ground
-- vehicle only); FPS and harvesting report them as zero / nil.
if mining.isLaserMining(raw) then
if raw.instability and raw.instability > 0 then
items[#items + 1] = { label = msg('Instability'), content = format.formatNum(raw.instability) }
end
if raw.resistance and raw.resistance > 0 then
items[#items + 1] = { label = msg('Resistance'), content = tostring(raw.resistance) }
end
end
local quality = mining.qualityRange(raw)
if quality then
items[#items + 1] = { label = msg('Quality'), content = quality }
end
-- Only render the group when it has at least one stat — otherwise a
-- stat-less acquisition (e.g. a harvestable with no signature/quality)
-- would leave a labelled-but-empty section.
if #items > 0 then
local kind = raw.kind or apiData.kind
local label = msg('Mining')
if kind == 'harvestable' then
label = msg('Harvesting')
elseif kind == 'remains' then
label = msg('Collection')
end
sections[#sections + 1] = {
key = 'mining',
label = label,
collapsible = true,
items = items,
}
end
end
return sections
end
--- @param ctx EntityHookContext
--- @return table<string, any>
function p.getStructuredData(ctx)
local apiData = ctx.apiData
local raw = apiData._rawRecord
local g = resolveGroups(apiData)
return {
commodity_group = g and LABELS[g.parent] or nil,
commodity_type = g and LABELS[g.leaf] or nil,
tier = apiData.tier or (raw and raw.tier),
mineable = (raw and raw.is_mineable) or false,
acquisition_kind = apiData.kind or (raw and raw.kind),
density = raw and raw.density_g_per_cc,
signature = raw and raw.signature,
-- `systems` is intentionally NOT an infobox row: the set of star systems
-- grows as the game expands, so an enumerated list doesn't scale. It is
-- persisted to structured data for querying.
systems = (raw and raw.systems) or apiData.systems,
}
end
-- Kind token → German attributive adjective stem for the short description;
-- the ending follows the family noun's gender (feminine and plural -e,
-- masculine -er, else neuter -es).
local KIND_ADJECTIVES = {
mineable = 'abbaubar',
harvestable = 'erntbar',
salvage = 'wiederverwertbar',
}
local ADJECTIVE_ENDINGS = {
['Verarbeitete Güter'] = 'e',
Genussmittel = 'e',
['Synthetische Materialien'] = 'e',
Massenware = 'e',
Legierung = 'e',
['Unverarbeitete Erze'] = 'e',
Lebensmittel = 'e',
Rohmineralien = 'e',
Organisch = 'e',
Abfall = 'er',
}
--- German noun-phrase short description, e.g. "Abbaubares Mineral",
--- "Erntbares Lebensmittel" - the live pages' lead pattern ("ist ein Mineral,
--- welches durch Bergbau gewonnen werden kann") without its clause. The tier
--- is deliberately dropped: the rarity badge and the Seltenheit row carry it.
--- Kinds without an adjective (remains) render the bare family noun.
---
--- @param ctx EntityHookContext
--- @return string
function p.getShortDescription(ctx)
local apiData, typeInfo = ctx.apiData, ctx.typeInfo
local noun = (typeInfo and typeInfo.name) or 'Handelsware'
local kind = apiData.kind or (apiData._rawRecord and apiData._rawRecord.kind)
local stem = kind and KIND_ADJECTIVES[kind]
if not stem then
return noun
end
local adjective = stem .. (ADJECTIVE_ENDINGS[noun] or 'es')
return adjective:gsub('^%l', string.upper) .. ' ' .. noun
end
--- Acquisition data for {{Entity/Availability}}: Mine/Harvest/Buy summary flags
--- and a Mining deposit card (pre-rendered HTML) + a Trade card (UEX terminal
--- table when priced, else a SC-Trade-Tools/UEX link-out keyed on slug).
---
--- @param ctx EntityHookContext
--- @return { summary: table[], cards: table[] }
function p.getAcquisition(ctx)
local apiData, args = ctx.apiData, ctx.args
local raw = apiData._rawRecord or apiData
local refined = apiData._refinedRecord or apiData
local purchase = type(refined.uex_prices) == 'table' and refined.uex_prices.purchase or nil
local summary = {
{ label = msg('Mine'), icon = '⛏️', value = acq.resolveFlag(args.canMine, raw.is_mineable) },
{ label = msg('Harvest'), icon = '🌿', value = acq.resolveFlag(args.canHarvest, raw.has_harvestables) },
{
label = msg('Buy'),
icon = '🛒',
value = acq.resolveFlag(args.canBuy, acq.inferCanAcquire(purchase, 'price_buy')),
},
}
local cards = {}
local miningHtml = mining.renderMiningCard(apiData._rawRecord)
if miningHtml then
cards[#cards + 1] = { type = 'html', html = miningHtml }
end
local purchasePrices = type(purchase) == 'table' and purchase or {}
if #purchasePrices > 0 then
local hasSell = acq.priceRange(purchasePrices, 'price_sell') ~= nil
local priceColumns = { { id = 'buy', key = 'price_buy', label = msg('Buy') } }
if hasSell then
priceColumns[#priceColumns + 1] = { id = 'sell', key = 'price_sell', label = msg('Sell') }
end
cards[#cards + 1] = {
type = 'terminals',
title = '<span aria-hidden="true">🛒</span> ' .. msg('Trade'),
caption = msg('Trade terminals'),
description = hasSell and acq.buildShopTerminalsDescription(purchasePrices)
or acq.buildSinglePriceDescription(purchasePrices, 'price_buy'),
prices = purchasePrices,
priceColumns = priceColumns,
}
else
local slug = mw.uri.encode(refined.slug or apiData.slug or '', 'PATH')
cards[#cards + 1] = {
type = 'links',
title = msg('Browse trade data'),
buttons = {
{ label = 'SC Trade Tools', url = 'https://sc-trade.tools/commodities/' .. slug, weight = 'normal' },
{ label = 'UEX', url = 'https://uexcorp.space/commodities/info/name/' .. slug, weight = 'normal' },
},
}
end
return { summary = summary, cards = cards }
end
--- Cargo packaging variants as { scu, mass_kg } rows (mass = SCU × density
--- × 1000), ascending. Safe on nil/non-table boxSizes (returns {}).
--- @param boxSizes number[]|nil
--- @param density number|nil
--- @return { scu: number, mass_kg: number }[]
local function buildCargoRows(boxSizes, density)
local rows = {}
if type(boxSizes) ~= 'table' then
return rows
end
local d = tonumber(density) or 0
for _, scu in ipairs(boxSizes) do
rows[#rows + 1] = { scu = scu, mass_kg = scu * d * 1000 }
end
table.sort(rows, function(a, b)
return a.scu < b.scu
end)
return rows
end
--- A commodity's "related entities" are its cargo-box packaging variants:
--- they share one image and have no own pages, so {{Entity/Related}}
--- renders them as a table rather than tiles. The refined record
--- (commodities endpoint) carries the box ladder and density.
--- @param ctx EntityHookContext
--- @return EntityRelatedPayload
function p.getRelated(ctx)
local apiData = ctx.apiData
local refined = apiData._refinedRecord or apiData
return { cargo = buildCargoRows(refined.box_sizes_scu, refined.density_g_per_cc) }
end
--- Commodities are crafting INPUTS, never outputs, so {{Entity/Blueprints}}
--- renders the recipes that consume this commodity rather than a blueprint
--- list. The refined record carries the canonical ingredient name; the
--- `ingredient` table is present even without a name so the renderer still
--- takes the used-in path (and reports the missing name) rather than the
--- blueprint list.
--- @param ctx EntityHookContext
--- @return EntityBlueprintsPayload
function p.getBlueprints(ctx)
local apiData = ctx.apiData
local refined = apiData._refinedRecord or apiData
return { ingredient = { name = refined.name or apiData.name } }
end
--- Contributes commodity community-site links (UEX, SC Trade Tools) to the
--- infobox External sites section, mirroring Module:Entity/Item. Keyed on the
--- commodity `slug` (url-safe; both sites resolve commodities by slug).
---
--- @param ctx EntityHookContext
--- @return EntityItemData[]
function p.getExternalSiteItems(ctx)
local apiData, args = ctx.apiData, ctx.args
local siteDefs = mw.loadJsonData('Module:Entity/Commodity/communitySites.json')
local links = format.buildSiteLinks(siteDefs, {
name = args.name or apiData.name,
slug = apiData.slug,
})
if not links then
return {}
end
return { { label = msg('Community sites'), content = links } }
end
-- Test-only exports. Not part of the public API.
p._internal = {
buildCargoRows = buildCargoRows,
}
return p