Module:BassaridEmployment: Difference between revisions

From MicrasWiki
Jump to navigationJump to search
NewZimiaGov (talk | contribs)
No edit summary
NewZimiaGov (talk | contribs)
No edit summary
Line 1: Line 1:
local p = {}
-- Module:BassaridEmployment (Optimized, no feature removal)
 
--
---------------------------------------------------------
-- Employment report derived from company rosters inside:
-- Module:BassaridEmployment (Optimized)
--   Module:AutoUpdateAgPrices
--   Module:AutoUpdateManfPrices
--   Module:AutoUpdateServPrices
--
-- Factors:
--   costs (price-module ratios), weather (BassaridiaForecast), market (BassaridMarketActivity),
--   War League tempo (WarLeagueDivisionOpsBVR), Temple tempo (MissionaryDailyOpsBVR),
--   optional Hatch Ministry tempo (HatchMinistryDailyOpsBVR if present).
--
-- Auditable output:
--   Shows distinct product counts per company and per-row multipliers for each factor.
--
--
-- What this module does
-- OPTIMIZATIONS (no output/features removed):
-- • Computes a daily "previous vs current" employment estimate per company
--  1) Each price module is rendered ONCE per page render (breakdown), and we extract:
-- • Uses deterministic per-company variation so:
--       - roster + distinct products per company
--     - results are stable for a given day
--       - sector membership
--      - results do NOT depend on loop order / table order
--       - average adjusted vs base (for cost ratio)
-- • Builds wiki output using buffers (table.concat) for speed
--      This replaces the previous double-render (breakdown + summary) per price module.
--   2) All requires are cached (pcall(require) once per dependency).
--  3) Fast splitting for "||" lines (no mw.text.split per row).
--  4) Output is still built with table buffers.
--
--
-- Usage:
-- Usage:
--  {{#invoke:BassaridEmployment|generateTable}}
--  {{#invoke:BassaridEmployment|generateTable}}
--   Optional args:
--     |city=Vaeringheim
--    |population=55499301
--    |sector= (optional: Agricultural | Mining/Manufacturing | Services)
--    |unemployment=0.04
--    |limit= (optional: numeric)
--    |maxChange=0.25
--    |dashboard=yes/no
---------------------------------------------------------
local p = {}
 
--------------------------------------------------------------------------------
-- UTIL
--------------------------------------------------------------------------------
local function trim(s)
s = tostring(s or "")
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end


---------------------------------------------------------
local function stripWiki(s)
-- 1) getCurrentDate
s = tostring(s or "")
--   Returns a date string in PSSC format, plus day/month/year/dayOfYear.
s = s:gsub("%{%b{}%}", "")                                -- templates
---------------------------------------------------------
s = s:gsub("%[%[[^%]|]+|([^%]]+)%]%]", "%1")              -- piped links
local function getCurrentDate()
s = s:gsub("%[%[([^%]]+)%]%]", "%1")                      -- plain links
local startDate = os.time({ year = 1999, month = 8, day = 6 })
s = s:gsub("'''''", ""):gsub("'''", ""):gsub("''", "")    -- ital/bold
s = s:gsub(" ", " ")
return trim(s)
end
 
local function clamp(x, lo, hi)
if x < lo then return lo end
if x > hi then return hi end
return x
end
 
local function hashFrac(s)
local ok, h = pcall(function() return mw.hash.hashValue("md5", tostring(s or "")) end)
if not ok or not h or #h < 8 then return 0.5 end
local n = tonumber(h:sub(1, 8), 16) or 0
return (n % 1000000) / 1000000
end
 
--------------------------------------------------------------------------------
-- SAFE REQUIRE (cached)
--------------------------------------------------------------------------------
local _reqCache = {}
local function safeRequire(name)
if _reqCache[name] ~= nil then
return _reqCache[name]
end
local ok, mod = pcall(require, name)
if not ok then mod = false end
_reqCache[name] = mod
return mod
end
 
--------------------------------------------------------------------------------
-- DATE (PSSC)
--------------------------------------------------------------------------------
local DAYS_IN_YEAR = 183
local function getCurrentDateInfo()
local startDate = os.time({year = 1999, month = 8, day = 6})
local secondsInDay = 86400
local secondsInDay = 86400
local daysPerYear = 183
local now = os.time()
local totalDays = math.floor((now - startDate) / secondsInDay)
local yearFraction = totalDays / DAYS_IN_YEAR
local psscYear = math.floor(yearFraction)
local dayOfYear = math.floor((yearFraction - psscYear) * DAYS_IN_YEAR) + 1
local month, dayOfMonth
if dayOfYear <= 61 then month, dayOfMonth = 1, dayOfYear
elseif dayOfYear <= 122 then month, dayOfMonth = 2, dayOfYear - 61
else month, dayOfMonth = 3, dayOfYear - 122 end


local currentDate = os.time()
return {
local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
dateString = string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear),
local yearFraction = totalDaysElapsed / daysPerYear
year = psscYear,
local psscYear    = math.floor(yearFraction)
dayOfYear = dayOfYear
local dayOfYear    = math.floor((yearFraction - psscYear) * daysPerYear) + 1
}
end


local month, dayOfMonth
--------------------------------------------------------------------------------
if dayOfYear <= 61 then
-- FAST "||" SPLITTER FOR PRICE-MODULE DATA LINES
month = 1; dayOfMonth = dayOfYear
--------------------------------------------------------------------------------
elseif dayOfYear <= 122 then
local function splitCellsByDoublePipeFast(line)
month = 2; dayOfMonth = dayOfYear - 61
line = trim(line):gsub("^|%s*", "")
else
local cells = {}
month = 3; dayOfMonth = dayOfYear - 122
local i = 1
for part in line:gmatch("([^|][^|]*)%s*%|%|%s*") do
cells[i] = trim(part)
i = i + 1
end
local tail = line:match("||%s*([^|].*)$")
if tail then
cells[i] = trim(tail)
end
return cells
end
 
--------------------------------------------------------------------------------
-- PRICE MODULE CACHE (render once; extract roster + product counts + cost ratio)
--------------------------------------------------------------------------------
local priceCache = {} -- moduleName -> pack
 
local function parseAverageAdjustedVsBase(text)
local aNew, aBase = text:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)")
aNew, aBase = tonumber(aNew), tonumber(aBase)
if not aNew or not aBase or aBase == 0 then return nil, nil end
return aNew, aBase
end
 
local function extractFromPriceModule(modName, sectorLabel)
if priceCache[modName] then return priceCache[modName] end
 
local m = safeRequire(modName)
if not m or type(m.generateTable) ~= "function" then
local pack = { present = false, companies = {}, productCount = {}, ratio = 1.0, sector = sectorLabel }
priceCache[modName] = pack
return pack
end
 
local out = m.generateTable({ args = { mode = "breakdown", collapse = "no" } }) or ""
 
local companies, seenCompany = {}, {}
local productsSeenByCompany = {}
 
for line in out:gmatch("[^\n]+") do
line = trim(line)
if line:match("^|%s*%d+/%d+/%d+%s*%[%[PSSC%]%]%s*||") then
local cells = splitCellsByDoublePipeFast(line)
local product = stripWiki(cells[2] or "")
local company = stripWiki(cells[3] or "")
if company ~= "" then
if not seenCompany[company] then
seenCompany[company] = true
companies[#companies + 1] = { name = company, sector = sectorLabel }
end
if product ~= "" then
local set = productsSeenByCompany[company]
if not set then
set = {}
productsSeenByCompany[company] = set
end
set[product] = true
end
end
end
end
 
local distinctCount = {}
for company, set in pairs(productsSeenByCompany) do
local n = 0
for _ in pairs(set) do n = n + 1 end
distinctCount[company] = n
end
 
local aNew, aBase = parseAverageAdjustedVsBase(out)
local ratio = 1.0
if aNew and aBase and aBase ~= 0 then ratio = aNew / aBase end
 
local pack = {
present = true,
companies = companies,
productCount = distinctCount,
ratio = ratio,
sector = sectorLabel
}
priceCache[modName] = pack
return pack
end
 
local function buildCompanyRosterAndCounts()
local roster = {}
local counts = {}
local seen = {}
 
local ag = extractFromPriceModule("Module:AutoUpdateAgPrices", "Agricultural")
local mf = extractFromPriceModule("Module:AutoUpdateManfPrices", "Mining/Manufacturing")
local sv = extractFromPriceModule("Module:AutoUpdateServPrices", "Services")
 
local function addPack(pack)
for _, c in ipairs(pack.companies or {}) do
if not seen[c.name] then
seen[c.name] = true
roster[#roster + 1] = c
end
counts[c.name] = (counts[c.name] or 0) + (pack.productCount[c.name] or 0)
end
end
end


return string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear), dayOfMonth, month, psscYear, dayOfYear
addPack(ag); addPack(mf); addPack(sv)
 
return {
roster = roster,
productCounts = counts,
modulePresence = { ag = ag.present, mf = mf.present, sv = sv.present },
pricePacks = { ag = ag, mf = mf, sv = sv }
}
end
end


---------------------------------------------------------
--------------------------------------------------------------------------------
-- 2) Company table (same data as current module)
-- COST INDEX MULTIPLIER (sector-based)
---------------------------------------------------------
--------------------------------------------------------------------------------
local companies = {
local function sectorCostMultiplier(sec, costAg, costManf, costServ)
{name = "Lake Morovia Blockade Fund", employmentPercentage = 0.0300},
local r = 1.0
{name = "Gladeseed Farmers' Union", employmentPercentage = 0.1205},
if sec == "Agricultural" then r = costAg.ratio or 1.0
{name = "Atterian Cattle Drivers", employmentPercentage = 0.0502},
elseif sec == "Mining/Manufacturing" then r = costManf.ratio or 1.0
{name = "Roving Wind Farm Corporation", employmentPercentage = 0.0210},
elseif sec == "Services" then r = costServ.ratio or 1.0 end
{name = "Baratar Corporation", employmentPercentage = 0.0401},
return clamp(0.92 + (r - 1.0) * 0.20, 0.85, 1.12)
{name = "Noctic Fleet", employmentPercentage = 0.0603},
end
{name = "Keepers of the Bloodbaths of Laprind", employmentPercentage = 0.0105},
{name = "Jogiani Merchants of Manwine", employmentPercentage = 0.0208},
{name = "Keepers of the Grove of Zoe Elm", employmentPercentage = 0.0112},
{name = "Plains of Jogi", employmentPercentage = 0.0807},
{name = "Ale of the Night Central Brewery", employmentPercentage = 0.0201},
{name = "Camel Herders of the Jangsong Province", employmentPercentage = 0.0306},
{name = "Thalassian Temple Granite Export Cooperative", employmentPercentage = 0.0310},
{name = "East Keltian Iron Company", employmentPercentage = 0.0415},
{name = "Mylecian Coal Ports", employmentPercentage = 0.0317},
{name = "Merchants of the Valley of Diamonds", employmentPercentage = 0.0102},
{name = "Maritime Guild of the Cult of Maskmakers", employmentPercentage = 0.0109},
{name = "Hatch Ministry", employmentPercentage = 0.0203},
{name = "Anterran Imports and Services", employmentPercentage = 0.0113},
{name = "East Keltian Timber Company", employmentPercentage = 0.0312},
{name = "Grand Cave Bee Meadery", employmentPercentage = 0.0215},
{name = "Merchant Guild of the Poppy Goddess", employmentPercentage = 0.0111},
{name = "Cinnamon Plains of Rouge", employmentPercentage = 0.0218},
{name = "Seamstresses of Rouge", employmentPercentage = 0.0114},
{name = "Salurian Temple of Sacred Horehound", employmentPercentage = 0.0212},
{name = "Suncliff Fisheries", employmentPercentage = 0.0309},
{name = "Bird Keepers of Saluria", employmentPercentage = 0.0108},
{name = "Velvet Homestead", employmentPercentage = 0.0110},
{name = "Hunters of the Giant Fanged Penguin", employmentPercentage = 0.0116},
{name = "Professional Pillarion League", employmentPercentage = 0.0052},
{name = "La S\u00e1i Ebile", employmentPercentage = 0.0104},
{name = "Temple Bank of the Reformed Stripping Path", employmentPercentage = 0.0118},
{name = "Market Hanavusu", employmentPercentage = 0.0157},
{name = "Couriers of the Lizard Queen", employmentPercentage = 0.0117},
{name = "Temple University of Delphica", employmentPercentage = 0.0209},
{name = "Trans-Morovian Railway Company", employmentPercentage = 0.0155},
}


---------------------------------------------------------
--------------------------------------------------------------------------------
-- 3) Deterministic RNG helpers (fast; no global math.random)
-- MARKET SENTIMENT
---------------------------------------------------------
--------------------------------------------------------------------------------
local MOD = 2147483647 -- 2^31 - 1
local function getMarketSentiment()
local A  = 1103515245
local m = safeRequire("Module:BassaridMarketActivity")
local C  = 12345
if not m or type(m.generateTable) ~= "function" then
return { present = false, bias = 0.0, avgPct = 0.0 }
end
local out = m.generateTable({ args = {} }) or ""
local sum, n, pos, neg = 0, 0, 0, 0
for pct in out:gmatch("([%+%-]?%d+%.?%d*)%%") do
local v = tonumber(pct)
if v then
sum = sum + v
n = n + 1
if v > 0 then pos = pos + 1 elseif v < 0 then neg = neg + 1 end
end
end
local avg = (n > 0) and (sum / n) or 0.0
local bias = (n > 0) and ((pos - neg) / n) or 0.0
return { present = true, bias = bias, avgPct = avg }
end
 
local function marketMultiplier(market, sector)
local b = clamp(market.bias or 0, -1, 1)
if sector == "Services" then
return clamp(1.0 + b * 0.03, 0.95, 1.05)
elseif sector == "Mining/Manufacturing" then
return clamp(1.0 + b * 0.02, 0.96, 1.04)
else
return clamp(1.0 + b * 0.01, 0.97, 1.03)
end
end


local function hashString(s)
--------------------------------------------------------------------------------
s = tostring(s or "")
-- WEATHER
local h = 0
--------------------------------------------------------------------------------
for i = 1, #s do
local function getWeatherSignal(city, year, dayOfYear)
h = (h * 31 + s:byte(i)) % MOD
local wx = safeRequire("Module:BassaridiaForecast")
if not wx or type(wx.getOpsData) ~= "function" then
return { present = false, level = 0, label = "Green", impacts = {}, condition = "" }
end
local op = wx.getOpsData(city, year, dayOfYear)
if not op or not op.alert then
return { present = true, level = 0, label = "Green", impacts = {}, condition = "" }
end
end
return h
return {
present = true,
level = tonumber(op.alert.level) or 0,
label = tostring(op.alert.label or "Green"),
condition = tostring(op.condition or ""),
impacts = op.impacts or {}
}
end
end


local function lcg(seed)
local function weatherMultiplier(wx, sector)
seed = seed % MOD
local lvl = tonumber(wx.level or 0) or 0
return function()
local m = 1.0
seed = (A * seed + C) % MOD
if lvl == 1 then m = 0.98
return seed
elseif lvl == 2 then m = 0.93
elseif lvl >= 3 then m = 0.85 end
 
local imp = wx.impacts or {}
local g = tostring(imp.ground or "")
local s = tostring(imp.sea or "")
local a = tostring(imp.air or "")
if sector == "Agricultural" then
if g == "No-Go" then m = m * 0.75
elseif g == "Degraded" then m = m * 0.90 end
elseif sector == "Mining/Manufacturing" then
if g == "No-Go" then m = m * 0.78
elseif g == "Degraded" then m = m * 0.92 end
elseif sector == "Services" then
if s == "Closed" then m = m * 0.85
elseif s == "Degraded" then m = m * 0.93 end
if a == "No-Go" then m = m * 0.92 end
end
end
return clamp(m, 0.65, 1.10)
end
end


local function randIntInclusive(nextInt, lo, hi)
--------------------------------------------------------------------------------
if hi < lo then lo, hi = hi, lo end
-- WAR LEAGUE TEMPO
local span = (hi - lo) + 1
--------------------------------------------------------------------------------
local r = (nextInt() + nextInt()) % MOD
local function getWarTempo(di)
return lo + (r % span)
local wl = safeRequire("Module:WarLeagueDivisionOpsBVR")
if not wl or type(wl.makeTable) ~= "function" then
return { present = false, score = 0, redRate = 0 }
end
local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
local rows, high, critical = 0, 0, 0
for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do
rows = rows + 1
if u == "HIGH" then high = high + 1 end
if u == "CRITICAL" then critical = critical + 1 end
end
if rows == 0 then rows = 36 end
local severity = (high * 1.0 + critical * 2.0) / rows
return { present = true, score = severity, redRate = (high + critical) / rows }
end
end


---------------------------------------------------------
local function warMultiplier(war, sector)
-- 4) Per-company calculation
local s = tonumber(war.score or 0) or 0
---------------------------------------------------------
if sector == "Services" then
local function calculateEmployees(company, employedPopulation, maxChangeFrac, dailySeed)
return clamp(1.0 + (s * 0.08), 0.95, 1.18)
local base = math.floor(employedPopulation * company.employmentPercentage)
elseif sector == "Mining/Manufacturing" then
return clamp(1.0 + (s * 0.06), 0.95, 1.15)
elseif sector == "Agricultural" then
return clamp(1.0 - (s * 0.03), 0.88, 1.05)
end
return 1.0
end


local h = hashString(company.name)
--------------------------------------------------------------------------------
local nextInt = lcg(dailySeed + h)
-- TEMPLE TEMPO
--------------------------------------------------------------------------------
local function getTempleTempo()
local tb = safeRequire("Module:MissionaryDailyOpsBVR")
if not tb or type(tb.makeTable) ~= "function" then
return { present = false, redRate = 0 }
end
local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
local red, n = 0, 0
for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do
n = n + 1
if sev == "Red" then red = red + 1 end
end
if n == 0 then n = 40 end
return { present = true, redRate = red / n }
end


local maxChange = math.floor(base * maxChangeFrac)
local function templeMultiplier(temple, sector)
if maxChange < 0 then maxChange = 0 end
local r = tonumber(temple.redRate or 0) or 0
if sector == "Services" then
return clamp(1.0 + (r * 0.06), 0.98, 1.10)
end
return clamp(1.0 + (r * 0.02), 0.98, 1.06)
end


local changeAmount = 0
--------------------------------------------------------------------------------
if maxChange > 0 then
-- OPTIONAL HATCH MINISTRY TEMPO
changeAmount = randIntInclusive(nextInt, -maxChange, maxChange)
--------------------------------------------------------------------------------
local function getHatchTempo(di)
local hm = safeRequire("Module:HatchMinistryDailyOpsBVR")
if not hm or type(hm.makeTable) ~= "function" then
return { present = false, intensity = 0 }
end
end
local out = hm.makeTable({ args = { rows = 30, seed = (di.year * 1000 + di.dayOfYear) } }) or ""
local c = 0
for _ in out:gmatch("[Ii]nterdict") do c = c + 1 end
for _ in out:gmatch("[Ii]nspect")  do c = c + 1 end
for _ in out:gmatch("[Ss]eiz")      do c = c + 1 end
return { present = true, intensity = c }
end


local prevEmployees = base
local function hatchMultiplier(hatch, sector)
local currEmployees = base + changeAmount
if not hatch or not hatch.present then return 1.0 end
if currEmployees < 1 then currEmployees = 1 end
local x = tonumber(hatch.intensity or 0) or 0
if sector == "Services" then
return clamp(1.0 + (x * 0.002), 1.0, 1.12)
else
return clamp(1.0 - (x * 0.001), 0.90, 1.02)
end
end


return prevEmployees, currEmployees
--------------------------------------------------------------------------------
-- BASE SHARES (uses distinct product counts as size proxy)
--------------------------------------------------------------------------------
local function buildBaseShares(roster, productCounts)
local sectorTarget = { Agricultural = 0.34, ["Mining/Manufacturing"] = 0.33, Services = 0.33 }
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {} }
for _, c in ipairs(roster) do
bySector[c.sector][#bySector[c.sector] + 1] = c
end
local shares = {}
for sec, list in pairs(bySector) do
local rawSum = 0
for _, c in ipairs(list) do
local nprod = productCounts[c.name] or 1
local w = math.sqrt(math.max(1, nprod)) * (0.7 + hashFrac("w:" .. c.name) * 1.2)
shares[c.name] = { share = 0, nprod = nprod, raw = w, sector = sec }
rawSum = rawSum + w
end
local target = sectorTarget[sec] or 0
for _, c in ipairs(list) do
local rec = shares[c.name]
rec.share = (rawSum > 0) and (rec.raw / rawSum) * target or 0
end
end
return shares
end
end


---------------------------------------------------------
--------------------------------------------------------------------------------
-- 5) generateTable
-- MAIN
---------------------------------------------------------
--------------------------------------------------------------------------------
function p.generateTable(frame)
function p.generateTable(frame)
frame = frame or {}
local args = (frame and frame.args) or {}
local args = (frame.getParent and frame:getParent() and frame:getParent().args) or {}
local di = getCurrentDateInfo()
local fargs = frame.args or {}
local city = tostring(args.city or "Vaeringheim")
local sectorFilter = trim(tostring(args.sector or ""))
local limit = tonumber(args.limit or "")
local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"
 
math.randomseed(di.year * 1000 + di.dayOfYear)
 
local rosterPack = buildCompanyRosterAndCounts()
local roster = rosterPack.roster
local productCounts = rosterPack.productCounts
 
if #roster == 0 then
return "''BassaridEmployment error: could not read company rosters from the three price modules.''"
end


local population = tonumber(fargs.population or args.population) or 55499301
local shares = buildBaseShares(roster, productCounts)
local unemploymentRate = tonumber(fargs.unemployment or args.unemployment) or 0.04
local maxChangeFrac = tonumber(fargs.maxChange or args.maxChange) or 0.25


if unemploymentRate < 0 then unemploymentRate = 0 end
-- cost ratios (extracted from price-module breakdown output)
if unemploymentRate > 1 then unemploymentRate = 1 end
local costAg  = rosterPack.pricePacks.ag
if maxChangeFrac < 0 then maxChangeFrac = 0 end
local costManf = rosterPack.pricePacks.mf
if maxChangeFrac > 1 then maxChangeFrac = 1 end
local costServ = rosterPack.pricePacks.sv


local employedPopulation = math.floor(population * (1 - unemploymentRate))
local market = getMarketSentiment()
local wx = getWeatherSignal(city, di.year, di.dayOfYear)
local war = getWarTempo(di)
local temple = getTempleTempo()
local hatch = getHatchTempo(di)


local localTime = os.date("*t")
local population = 94160000
local dailySeed = localTime.year * 1000 + localTime.yday
local baseU = 0.04
local u = baseU
u = u - clamp((market.bias or 0) * 0.01, -0.01, 0.01)
u = u + clamp((wx.level or 0) * 0.005, 0, 0.02)
u = clamp(u, 0.02, 0.08)
local employedPopulation = math.floor(population * (1 - u))


local dateString = getCurrentDate()
local function combinedMultiplier(sec)
local mCost = sectorCostMultiplier(sec, costAg, costManf, costServ)
local mWx = weatherMultiplier(wx, sec)
local mWar = warMultiplier(war, sec)
local mTemple = templeMultiplier(temple, sec)
local mHatch = hatchMultiplier(hatch, sec)
local mMkt = marketMultiplier(market, sec)
return clamp(mCost * mWx * mWar * mTemple * mHatch * mMkt, 0.65, 1.25),
      mCost, mWx, mWar, mTemple, mHatch, mMkt
end


local out = {}
local out = {}
out[#out + 1] = "{| class=\"wikitable\"\n"
out[#out + 1] = "! Date !! Company !! Employment % !! Previous Employees !! Current Employees !! Change\n"


local totalEmployed = 0
if showDashboard then
out[#out + 1] = "{| class=\"wikitable\" style=\"width:100%;\""
out[#out + 1] = "! colspan=\"4\" | Employment factor audit — " .. di.dateString
out[#out + 1] = "|-"
out[#out + 1] = string.format("| '''Rosters present''' || Ag=%s; Manf=%s; Serv=%s || '''Weather''' || %s (%s)",
tostring(rosterPack.modulePresence.ag),
tostring(rosterPack.modulePresence.mf),
tostring(rosterPack.modulePresence.sv),
(wx.label or "Green"), (wx.condition or ""))
out[#out + 1] = "|-"
out[#out + 1] = string.format("| '''Costs present''' || Ag=%s (%.3f); Manf=%s (%.3f); Serv=%s (%.3f) || '''Market present''' || %s (bias %.2f)",
tostring(costAg.present), (costAg.ratio or 1.0),
tostring(costManf.present), (costManf.ratio or 1.0),
tostring(costServ.present), (costServ.ratio or 1.0),
tostring(market.present), (market.bias or 0))
out[#out + 1] = "|-"
out[#out + 1] = string.format("| '''War present''' || %s (red-rate %.2f) || '''Temple present''' || %s (red-rate %.2f)",
tostring(war.present), (war.redRate or 0),
tostring(temple.present), (temple.redRate or 0))
out[#out + 1] = "|-"
out[#out + 1] = string.format("| '''Hatch present''' || %s (intensity %d) || '''Modeled unemployment''' || %.2f%%",
tostring(hatch.present), (hatch.intensity or 0), u * 100)
out[#out + 1] = "|}"
out[#out + 1] = ""
end


for _, company in ipairs(companies) do
out[#out + 1] = '<div style="overflow-x:auto;">'
local prevE, currE = calculateEmployees(company, employedPopulation, maxChangeFrac, dailySeed)
out[#out + 1] = "{| class=\"wikitable sortable\""
out[#out + 1] = "! Date !! Sector !! Company !! Products (distinct) !! Base Share % !! Prev Emp. !! Curr Emp. !! Δ !! mCost !! mWx !! mWar !! mTemple !! mHatch !! mMkt"


local changeType
local n = 0
if currE > prevE then
for _, c in ipairs(roster) do
changeType = "Increased"
local sec = c.sector
elseif currE < prevE then
if sectorFilter == "" or sec == sectorFilter then
changeType = "Decreased"
local rec = shares[c.name]
else
local share = (rec and rec.share) or 0
changeType = "Same"
local nprod = (rec and rec.nprod) or (productCounts[c.name] or 0)
end
 
local prev = math.max(1, math.floor(employedPopulation * share))
 
local mAll, mCost, mWx, mWar, mTemple, mHatch, mMkt = combinedMultiplier(sec)
local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18
local curr = math.max(1, math.floor(prev * mAll * (1.0 + jitter)))
 
local deltaSym = "•"
if curr > prev then deltaSym = "↑"
elseif curr < prev then deltaSym = "↓" end


local rowStyle
local rowStyle
if changeType == "Increased" then
if curr > prev then rowStyle = ' style="background-color:lightblue;"'
rowStyle = ' style="background-color:lightblue;"'
elseif curr == prev then rowStyle = ' style="background-color:lightgreen;"'
elseif changeType == "Same" then
else rowStyle = ' style="background-color:#ffcccb;"' end
rowStyle = ' style="background-color:lightgreen;"'
else
rowStyle = ' style="background-color:#ffcccb;"'
end


totalEmployed = totalEmployed + currE
out[#out + 1] = string.format(
"|-%s\n| %s || %s || %s || %d || %.3f%% || %d || %d || %s || %.2f || %.2f || %.2f || %.2f || %.2f || %.2f",
rowStyle,
di.dateString,
sec,
c.name,
nprod,
share * 100,
prev,
curr,
deltaSym,
mCost, mWx, mWar, mTemple, mHatch, mMkt
)


out[#out + 1] = string.format(
n = n + 1
"|-%s\n| %s || %s || %.2f%% || %d || %d || %s\n",
if limit and n >= limit then break end
rowStyle,
end
dateString,
company.name,
company.employmentPercentage * 100,
prevE,
currE,
changeType
)
end
end


local totalUnemployed = population - totalEmployed
out[#out + 1] = string.format("|-\n! colspan=\"4\" | Total Employed || %d || \n", totalEmployed)
out[#out + 1] = string.format("|-\n! colspan=\"4\" | Total Unemployed || %d || \n", totalUnemployed)
out[#out + 1] = "|}"
out[#out + 1] = "|}"
out[#out + 1] = "</div>"


return table.concat(out)
return table.concat(out, "\n")
end
end


return p
return p

Revision as of 01:28, 20 January 2026

Documentation for this module may be created at Module:BassaridEmployment/doc

-- Module:BassaridEmployment (Optimized, no feature removal)
--
-- Employment report derived from company rosters inside:
--   Module:AutoUpdateAgPrices
--   Module:AutoUpdateManfPrices
--   Module:AutoUpdateServPrices
--
-- Factors:
--   costs (price-module ratios), weather (BassaridiaForecast), market (BassaridMarketActivity),
--   War League tempo (WarLeagueDivisionOpsBVR), Temple tempo (MissionaryDailyOpsBVR),
--   optional Hatch Ministry tempo (HatchMinistryDailyOpsBVR if present).
--
-- Auditable output:
--   Shows distinct product counts per company and per-row multipliers for each factor.
--
-- OPTIMIZATIONS (no output/features removed):
--   1) Each price module is rendered ONCE per page render (breakdown), and we extract:
--        - roster + distinct products per company
--        - sector membership
--        - average adjusted vs base (for cost ratio)
--      This replaces the previous double-render (breakdown + summary) per price module.
--   2) All requires are cached (pcall(require) once per dependency).
--   3) Fast splitting for "||" lines (no mw.text.split per row).
--   4) Output is still built with table buffers.
--
-- Usage:
--   {{#invoke:BassaridEmployment|generateTable}}
--     |city=Vaeringheim
--     |sector= (optional: Agricultural | Mining/Manufacturing | Services)
--     |limit= (optional: numeric)
--     |dashboard=yes/no
local p = {}

--------------------------------------------------------------------------------
-- UTIL
--------------------------------------------------------------------------------
local function trim(s)
	s = tostring(s or "")
	return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end

local function stripWiki(s)
	s = tostring(s or "")
	s = s:gsub("%{%b{}%}", "")                                 -- templates
	s = s:gsub("%[%[[^%]|]+|([^%]]+)%]%]", "%1")               -- piped links
	s = s:gsub("%[%[([^%]]+)%]%]", "%1")                       -- plain links
	s = s:gsub("'''''", ""):gsub("'''", ""):gsub("''", "")     -- ital/bold
	s = s:gsub("&nbsp;", " ")
	return trim(s)
end

local function clamp(x, lo, hi)
	if x < lo then return lo end
	if x > hi then return hi end
	return x
end

local function hashFrac(s)
	local ok, h = pcall(function() return mw.hash.hashValue("md5", tostring(s or "")) end)
	if not ok or not h or #h < 8 then return 0.5 end
	local n = tonumber(h:sub(1, 8), 16) or 0
	return (n % 1000000) / 1000000
end

--------------------------------------------------------------------------------
-- SAFE REQUIRE (cached)
--------------------------------------------------------------------------------
local _reqCache = {}
local function safeRequire(name)
	if _reqCache[name] ~= nil then
		return _reqCache[name]
	end
	local ok, mod = pcall(require, name)
	if not ok then mod = false end
	_reqCache[name] = mod
	return mod
end

--------------------------------------------------------------------------------
-- DATE (PSSC)
--------------------------------------------------------------------------------
local DAYS_IN_YEAR = 183
local function getCurrentDateInfo()
	local startDate = os.time({year = 1999, month = 8, day = 6})
	local secondsInDay = 86400
	local now = os.time()
	local totalDays = math.floor((now - startDate) / secondsInDay)
	local yearFraction = totalDays / DAYS_IN_YEAR
	local psscYear = math.floor(yearFraction)
	local dayOfYear = math.floor((yearFraction - psscYear) * DAYS_IN_YEAR) + 1
	local month, dayOfMonth
	if dayOfYear <= 61 then month, dayOfMonth = 1, dayOfYear
	elseif dayOfYear <= 122 then month, dayOfMonth = 2, dayOfYear - 61
	else month, dayOfMonth = 3, dayOfYear - 122 end

	return {
		dateString = string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear),
		year = psscYear,
		dayOfYear = dayOfYear
	}
end

--------------------------------------------------------------------------------
-- FAST "||" SPLITTER FOR PRICE-MODULE DATA LINES
--------------------------------------------------------------------------------
local function splitCellsByDoublePipeFast(line)
	line = trim(line):gsub("^|%s*", "")
	local cells = {}
	local i = 1
	for part in line:gmatch("([^|][^|]*)%s*%|%|%s*") do
		cells[i] = trim(part)
		i = i + 1
	end
	local tail = line:match("||%s*([^|].*)$")
	if tail then
		cells[i] = trim(tail)
	end
	return cells
end

--------------------------------------------------------------------------------
-- PRICE MODULE CACHE (render once; extract roster + product counts + cost ratio)
--------------------------------------------------------------------------------
local priceCache = {} -- moduleName -> pack

local function parseAverageAdjustedVsBase(text)
	local aNew, aBase = text:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)")
	aNew, aBase = tonumber(aNew), tonumber(aBase)
	if not aNew or not aBase or aBase == 0 then return nil, nil end
	return aNew, aBase
end

local function extractFromPriceModule(modName, sectorLabel)
	if priceCache[modName] then return priceCache[modName] end

	local m = safeRequire(modName)
	if not m or type(m.generateTable) ~= "function" then
		local pack = { present = false, companies = {}, productCount = {}, ratio = 1.0, sector = sectorLabel }
		priceCache[modName] = pack
		return pack
	end

	local out = m.generateTable({ args = { mode = "breakdown", collapse = "no" } }) or ""

	local companies, seenCompany = {}, {}
	local productsSeenByCompany = {}

	for line in out:gmatch("[^\n]+") do
		line = trim(line)
		if line:match("^|%s*%d+/%d+/%d+%s*%[%[PSSC%]%]%s*||") then
			local cells = splitCellsByDoublePipeFast(line)
			local product = stripWiki(cells[2] or "")
			local company = stripWiki(cells[3] or "")
			if company ~= "" then
				if not seenCompany[company] then
					seenCompany[company] = true
					companies[#companies + 1] = { name = company, sector = sectorLabel }
				end
				if product ~= "" then
					local set = productsSeenByCompany[company]
					if not set then
						set = {}
						productsSeenByCompany[company] = set
					end
					set[product] = true
				end
			end
		end
	end

	local distinctCount = {}
	for company, set in pairs(productsSeenByCompany) do
		local n = 0
		for _ in pairs(set) do n = n + 1 end
		distinctCount[company] = n
	end

	local aNew, aBase = parseAverageAdjustedVsBase(out)
	local ratio = 1.0
	if aNew and aBase and aBase ~= 0 then ratio = aNew / aBase end

	local pack = {
		present = true,
		companies = companies,
		productCount = distinctCount,
		ratio = ratio,
		sector = sectorLabel
	}
	priceCache[modName] = pack
	return pack
end

local function buildCompanyRosterAndCounts()
	local roster = {}
	local counts = {}
	local seen = {}

	local ag = extractFromPriceModule("Module:AutoUpdateAgPrices", "Agricultural")
	local mf = extractFromPriceModule("Module:AutoUpdateManfPrices", "Mining/Manufacturing")
	local sv = extractFromPriceModule("Module:AutoUpdateServPrices", "Services")

	local function addPack(pack)
		for _, c in ipairs(pack.companies or {}) do
			if not seen[c.name] then
				seen[c.name] = true
				roster[#roster + 1] = c
			end
			counts[c.name] = (counts[c.name] or 0) + (pack.productCount[c.name] or 0)
		end
	end

	addPack(ag); addPack(mf); addPack(sv)

	return {
		roster = roster,
		productCounts = counts,
		modulePresence = { ag = ag.present, mf = mf.present, sv = sv.present },
		pricePacks = { ag = ag, mf = mf, sv = sv }
	}
end

--------------------------------------------------------------------------------
-- COST INDEX MULTIPLIER (sector-based)
--------------------------------------------------------------------------------
local function sectorCostMultiplier(sec, costAg, costManf, costServ)
	local r = 1.0
	if sec == "Agricultural" then r = costAg.ratio or 1.0
	elseif sec == "Mining/Manufacturing" then r = costManf.ratio or 1.0
	elseif sec == "Services" then r = costServ.ratio or 1.0 end
	return clamp(0.92 + (r - 1.0) * 0.20, 0.85, 1.12)
end

--------------------------------------------------------------------------------
-- MARKET SENTIMENT
--------------------------------------------------------------------------------
local function getMarketSentiment()
	local m = safeRequire("Module:BassaridMarketActivity")
	if not m or type(m.generateTable) ~= "function" then
		return { present = false, bias = 0.0, avgPct = 0.0 }
	end
	local out = m.generateTable({ args = {} }) or ""
	local sum, n, pos, neg = 0, 0, 0, 0
	for pct in out:gmatch("([%+%-]?%d+%.?%d*)%%") do
		local v = tonumber(pct)
		if v then
			sum = sum + v
			n = n + 1
			if v > 0 then pos = pos + 1 elseif v < 0 then neg = neg + 1 end
		end
	end
	local avg = (n > 0) and (sum / n) or 0.0
	local bias = (n > 0) and ((pos - neg) / n) or 0.0
	return { present = true, bias = bias, avgPct = avg }
end

local function marketMultiplier(market, sector)
	local b = clamp(market.bias or 0, -1, 1)
	if sector == "Services" then
		return clamp(1.0 + b * 0.03, 0.95, 1.05)
	elseif sector == "Mining/Manufacturing" then
		return clamp(1.0 + b * 0.02, 0.96, 1.04)
	else
		return clamp(1.0 + b * 0.01, 0.97, 1.03)
	end
end

--------------------------------------------------------------------------------
-- WEATHER
--------------------------------------------------------------------------------
local function getWeatherSignal(city, year, dayOfYear)
	local wx = safeRequire("Module:BassaridiaForecast")
	if not wx or type(wx.getOpsData) ~= "function" then
		return { present = false, level = 0, label = "Green", impacts = {}, condition = "" }
	end
	local op = wx.getOpsData(city, year, dayOfYear)
	if not op or not op.alert then
		return { present = true, level = 0, label = "Green", impacts = {}, condition = "" }
	end
	return {
		present = true,
		level = tonumber(op.alert.level) or 0,
		label = tostring(op.alert.label or "Green"),
		condition = tostring(op.condition or ""),
		impacts = op.impacts or {}
	}
end

local function weatherMultiplier(wx, sector)
	local lvl = tonumber(wx.level or 0) or 0
	local m = 1.0
	if lvl == 1 then m = 0.98
	elseif lvl == 2 then m = 0.93
	elseif lvl >= 3 then m = 0.85 end

	local imp = wx.impacts or {}
	local g = tostring(imp.ground or "")
	local s = tostring(imp.sea or "")
	local a = tostring(imp.air or "")
	if sector == "Agricultural" then
		if g == "No-Go" then m = m * 0.75
		elseif g == "Degraded" then m = m * 0.90 end
	elseif sector == "Mining/Manufacturing" then
		if g == "No-Go" then m = m * 0.78
		elseif g == "Degraded" then m = m * 0.92 end
	elseif sector == "Services" then
		if s == "Closed" then m = m * 0.85
		elseif s == "Degraded" then m = m * 0.93 end
		if a == "No-Go" then m = m * 0.92 end
	end

	return clamp(m, 0.65, 1.10)
end

--------------------------------------------------------------------------------
-- WAR LEAGUE TEMPO
--------------------------------------------------------------------------------
local function getWarTempo(di)
	local wl = safeRequire("Module:WarLeagueDivisionOpsBVR")
	if not wl or type(wl.makeTable) ~= "function" then
		return { present = false, score = 0, redRate = 0 }
	end
	local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
	local rows, high, critical = 0, 0, 0
	for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do
		rows = rows + 1
		if u == "HIGH" then high = high + 1 end
		if u == "CRITICAL" then critical = critical + 1 end
	end
	if rows == 0 then rows = 36 end
	local severity = (high * 1.0 + critical * 2.0) / rows
	return { present = true, score = severity, redRate = (high + critical) / rows }
end

local function warMultiplier(war, sector)
	local s = tonumber(war.score or 0) or 0
	if sector == "Services" then
		return clamp(1.0 + (s * 0.08), 0.95, 1.18)
	elseif sector == "Mining/Manufacturing" then
		return clamp(1.0 + (s * 0.06), 0.95, 1.15)
	elseif sector == "Agricultural" then
		return clamp(1.0 - (s * 0.03), 0.88, 1.05)
	end
	return 1.0
end

--------------------------------------------------------------------------------
-- TEMPLE TEMPO
--------------------------------------------------------------------------------
local function getTempleTempo()
	local tb = safeRequire("Module:MissionaryDailyOpsBVR")
	if not tb or type(tb.makeTable) ~= "function" then
		return { present = false, redRate = 0 }
	end
	local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
	local red, n = 0, 0
	for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do
		n = n + 1
		if sev == "Red" then red = red + 1 end
	end
	if n == 0 then n = 40 end
	return { present = true, redRate = red / n }
end

local function templeMultiplier(temple, sector)
	local r = tonumber(temple.redRate or 0) or 0
	if sector == "Services" then
		return clamp(1.0 + (r * 0.06), 0.98, 1.10)
	end
	return clamp(1.0 + (r * 0.02), 0.98, 1.06)
end

--------------------------------------------------------------------------------
-- OPTIONAL HATCH MINISTRY TEMPO
--------------------------------------------------------------------------------
local function getHatchTempo(di)
	local hm = safeRequire("Module:HatchMinistryDailyOpsBVR")
	if not hm or type(hm.makeTable) ~= "function" then
		return { present = false, intensity = 0 }
	end
	local out = hm.makeTable({ args = { rows = 30, seed = (di.year * 1000 + di.dayOfYear) } }) or ""
	local c = 0
	for _ in out:gmatch("[Ii]nterdict") do c = c + 1 end
	for _ in out:gmatch("[Ii]nspect")   do c = c + 1 end
	for _ in out:gmatch("[Ss]eiz")      do c = c + 1 end
	return { present = true, intensity = c }
end

local function hatchMultiplier(hatch, sector)
	if not hatch or not hatch.present then return 1.0 end
	local x = tonumber(hatch.intensity or 0) or 0
	if sector == "Services" then
		return clamp(1.0 + (x * 0.002), 1.0, 1.12)
	else
		return clamp(1.0 - (x * 0.001), 0.90, 1.02)
	end
end

--------------------------------------------------------------------------------
-- BASE SHARES (uses distinct product counts as size proxy)
--------------------------------------------------------------------------------
local function buildBaseShares(roster, productCounts)
	local sectorTarget = { Agricultural = 0.34, ["Mining/Manufacturing"] = 0.33, Services = 0.33 }
	local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {} }
	for _, c in ipairs(roster) do
		bySector[c.sector][#bySector[c.sector] + 1] = c
	end
	local shares = {}
	for sec, list in pairs(bySector) do
		local rawSum = 0
		for _, c in ipairs(list) do
			local nprod = productCounts[c.name] or 1
			local w = math.sqrt(math.max(1, nprod)) * (0.7 + hashFrac("w:" .. c.name) * 1.2)
			shares[c.name] = { share = 0, nprod = nprod, raw = w, sector = sec }
			rawSum = rawSum + w
		end
		local target = sectorTarget[sec] or 0
		for _, c in ipairs(list) do
			local rec = shares[c.name]
			rec.share = (rawSum > 0) and (rec.raw / rawSum) * target or 0
		end
	end
	return shares
end

--------------------------------------------------------------------------------
-- MAIN
--------------------------------------------------------------------------------
function p.generateTable(frame)
	local args = (frame and frame.args) or {}
	local di = getCurrentDateInfo()
	local city = tostring(args.city or "Vaeringheim")
	local sectorFilter = trim(tostring(args.sector or ""))
	local limit = tonumber(args.limit or "")
	local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"

	math.randomseed(di.year * 1000 + di.dayOfYear)

	local rosterPack = buildCompanyRosterAndCounts()
	local roster = rosterPack.roster
	local productCounts = rosterPack.productCounts

	if #roster == 0 then
		return "''BassaridEmployment error: could not read company rosters from the three price modules.''"
	end

	local shares = buildBaseShares(roster, productCounts)

	-- cost ratios (extracted from price-module breakdown output)
	local costAg   = rosterPack.pricePacks.ag
	local costManf = rosterPack.pricePacks.mf
	local costServ = rosterPack.pricePacks.sv

	local market = getMarketSentiment()
	local wx = getWeatherSignal(city, di.year, di.dayOfYear)
	local war = getWarTempo(di)
	local temple = getTempleTempo()
	local hatch = getHatchTempo(di)

	local population = 94160000
	local baseU = 0.04
	local u = baseU
	u = u - clamp((market.bias or 0) * 0.01, -0.01, 0.01)
	u = u + clamp((wx.level or 0) * 0.005, 0, 0.02)
	u = clamp(u, 0.02, 0.08)
	local employedPopulation = math.floor(population * (1 - u))

	local function combinedMultiplier(sec)
		local mCost = sectorCostMultiplier(sec, costAg, costManf, costServ)
		local mWx = weatherMultiplier(wx, sec)
		local mWar = warMultiplier(war, sec)
		local mTemple = templeMultiplier(temple, sec)
		local mHatch = hatchMultiplier(hatch, sec)
		local mMkt = marketMultiplier(market, sec)
		return clamp(mCost * mWx * mWar * mTemple * mHatch * mMkt, 0.65, 1.25),
		       mCost, mWx, mWar, mTemple, mHatch, mMkt
	end

	local out = {}

	if showDashboard then
		out[#out + 1] = "{| class=\"wikitable\" style=\"width:100%;\""
		out[#out + 1] = "! colspan=\"4\" | Employment factor audit — " .. di.dateString
		out[#out + 1] = "|-"
		out[#out + 1] = string.format("| '''Rosters present''' || Ag=%s; Manf=%s; Serv=%s || '''Weather''' || %s (%s)",
			tostring(rosterPack.modulePresence.ag),
			tostring(rosterPack.modulePresence.mf),
			tostring(rosterPack.modulePresence.sv),
			(wx.label or "Green"), (wx.condition or ""))
		out[#out + 1] = "|-"
		out[#out + 1] = string.format("| '''Costs present''' || Ag=%s (%.3f); Manf=%s (%.3f); Serv=%s (%.3f) || '''Market present''' || %s (bias %.2f)",
			tostring(costAg.present), (costAg.ratio or 1.0),
			tostring(costManf.present), (costManf.ratio or 1.0),
			tostring(costServ.present), (costServ.ratio or 1.0),
			tostring(market.present), (market.bias or 0))
		out[#out + 1] = "|-"
		out[#out + 1] = string.format("| '''War present''' || %s (red-rate %.2f) || '''Temple present''' || %s (red-rate %.2f)",
			tostring(war.present), (war.redRate or 0),
			tostring(temple.present), (temple.redRate or 0))
		out[#out + 1] = "|-"
		out[#out + 1] = string.format("| '''Hatch present''' || %s (intensity %d) || '''Modeled unemployment''' || %.2f%%",
			tostring(hatch.present), (hatch.intensity or 0), u * 100)
		out[#out + 1] = "|}"
		out[#out + 1] = ""
	end

	out[#out + 1] = '<div style="overflow-x:auto;">'
	out[#out + 1] = "{| class=\"wikitable sortable\""
	out[#out + 1] = "! Date !! Sector !! Company !! Products (distinct) !! Base Share % !! Prev Emp. !! Curr Emp. !! Δ !! mCost !! mWx !! mWar !! mTemple !! mHatch !! mMkt"

	local n = 0
	for _, c in ipairs(roster) do
		local sec = c.sector
		if sectorFilter == "" or sec == sectorFilter then
			local rec = shares[c.name]
			local share = (rec and rec.share) or 0
			local nprod = (rec and rec.nprod) or (productCounts[c.name] or 0)

			local prev = math.max(1, math.floor(employedPopulation * share))

			local mAll, mCost, mWx, mWar, mTemple, mHatch, mMkt = combinedMultiplier(sec)
			local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18
			local curr = math.max(1, math.floor(prev * mAll * (1.0 + jitter)))

			local deltaSym = "•"
			if curr > prev then deltaSym = "↑"
			elseif curr < prev then deltaSym = "↓" end

			local rowStyle
			if curr > prev then rowStyle = ' style="background-color:lightblue;"'
			elseif curr == prev then rowStyle = ' style="background-color:lightgreen;"'
			else rowStyle = ' style="background-color:#ffcccb;"' end

			out[#out + 1] = string.format(
				"|-%s\n| %s || %s || %s || %d || %.3f%% || %d || %d || %s || %.2f || %.2f || %.2f || %.2f || %.2f || %.2f",
				rowStyle,
				di.dateString,
				sec,
				c.name,
				nprod,
				share * 100,
				prev,
				curr,
				deltaSym,
				mCost, mWx, mWar, mTemple, mHatch, mMkt
			)

			n = n + 1
			if limit and n >= limit then break end
		end
	end

	out[#out + 1] = "|}"
	out[#out + 1] = "</div>"

	return table.concat(out, "\n")
end

return p