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:
-- Module:BassaridEmployment
-- Employment report for the General Port of Lake Morovia.
--
-- Key changes:
--  • Includes ALL companies listed on [[General Port of Lake Morovia]] Company Table (auto-parsed).
--  • Factors in: costs (Ag/Manf/Serv price modules), weather (BassaridiaForecast),
--    War League activity (WarLeagueDivisionOpsBVR), Temple Bank activity (MissionaryDailyOpsBVR),
--    market sentiment (BassaridMarketActivity), and (optionally) Hatch Ministry ops.
--
-- Usage:
--  {{#invoke:BassaridEmployment|generateTable}}
--  {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}}
--  {{#invoke:BassaridEmployment|generateTable|limit=80}}
--  {{#invoke:BassaridEmployment|generateTable|sector=Agricultural}}
--  {{#invoke:BassaridEmployment|generateTable|dashboard=no}}
--
-- Notes:
--  • This module is designed to be deterministic per day (stable output on the same day).
--  • If the port page format changes, parsing may need a small adjustment.
local p = {}
local p = {}


---------------------------------------------------------
--------------------------------------------------------------------------------
-- 1. getCurrentDate
-- 0) BASIC UTILS
--   Returns a date string in PSSC format, plus day/month
--------------------------------------------------------------------------------
---------------------------------------------------------
local function trim(s)
local function getCurrentDate()
s = tostring(s or "")
    local startDate = os.time({year = 1999, month = 8, day = 6})
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
    local secondsInDay = 86400
end
    local daysPerYear = 183
 
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(" ", " ")
return trim(s)
end
 
local function safeNumber(x)
local n = tonumber(x)
if not n then return nil end
return n
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)
-- stable 0..1 from md5 hex
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
 
--------------------------------------------------------------------------------
-- 1) DATE (PSSC) – keep same base logic as your other modules
--------------------------------------------------------------------------------
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
 
--------------------------------------------------------------------------------
-- 2) PULL ALL PORT COMPANIES (auto-parse from the General Port page)
--------------------------------------------------------------------------------
local PORT_PAGE = "General Port of Lake Morovia"
 
local function parsePortCompanies()
local title = mw.title.new(PORT_PAGE)
if not title then return {} end
local content = title:getContent() or ""
if content == "" then return {} end
 
-- We track sector based on headers.
-- Your page uses a Company Table split into Agricultural / Mining/Manufacturing / Services.
local sector = nil
local companies = {}
local seen = {}
 
local function push(name, sec)
name = stripWiki(name)
if name == "" then return end
if not seen[name] then
seen[name] = true
table.insert(companies, { name = name, sector = sec or "Unknown" })
end
end
 
for line in content:gmatch("[^\n]+") do
local l = trim(line)
 
-- sector headers (tolerant patterns)
if l:match("^=+%s*Agricultural%s*=+") then
sector = "Agricultural"
elseif l:match("^=+%s*Mining/Manufacturing%s*=+") or l:match("^=+%s*Mining%s*/%s*Manufacturing%s*=+") then
sector = "Mining/Manufacturing"
elseif l:match("^=+%s*Services%s*=+") then
sector = "Services"
end
 
-- Company cell style you use: | **Company Name**
local boldName = l:match("%|%s*%*%*([^%*]+)%*%*")
if boldName then
push(boldName, sector)
end
end
 
return companies
end
 
--------------------------------------------------------------------------------
-- 3) COST INDICES FROM PRICE MODULES (avg adjusted vs avg base)
--------------------------------------------------------------------------------
local function getCostIndex(moduleName, mode)
local ok, m = pcall(require, moduleName)
if not ok or not m or type(m.generateTable) ~= "function" then
return { ratio = 1.0, avgNew = nil, avgBase = nil }
end
 
-- call generateTable in summary mode (your modules accept frame tables)
local out = m.generateTable({ args = { mode = mode or "summary" } }) or ""
-- parse: "Average adjusted (X) vs base (Y)"
local aNew, aBase = out:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)")
aNew, aBase = safeNumber(aNew), safeNumber(aBase)
if not aNew or not aBase or aBase == 0 then
return { ratio = 1.0, avgNew = aNew, avgBase = aBase }
end
return { ratio = aNew / aBase, avgNew = aNew, avgBase = aBase }
end
 
--------------------------------------------------------------------------------
-- 4) MARKET ACTIVITY (investor sentiment proxy)
--------------------------------------------------------------------------------
local function getMarketSentiment()
local ok, m = pcall(require, "Module:BassaridMarketActivity")
if not ok or not m or type(m.generateTable) ~= "function" then
return { avgPct = 0.0, bias = 0.0 }
end
 
local out = m.generateTable({ args = {} }) or ""
-- Extract pct values like " -1.23%" or " 2.50%"
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 { avgPct = avg, bias = bias }
end
 
--------------------------------------------------------------------------------
-- 5) WEATHER / OPS IMPACT (default city Vaeringheim)
--------------------------------------------------------------------------------
local function getWeatherSignal(city, year, dayOfYear)
local ok, wx = pcall(require, "Module:BassaridiaForecast")
if not ok or not wx or type(wx.getOpsData) ~= "function" then
return { level = 0, label = "Green", impacts = {}, condition = "" }
end
local op = wx.getOpsData(city, year, dayOfYear)
if not op or not op.alert then
return { level = 0, label = "Green", impacts = {}, condition = "" }
end
return {
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)
-- Base by alert level
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 "")
 
-- Sector-sensitive penalties
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


    local currentDate = os.time()
--------------------------------------------------------------------------------
    local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
-- 6) WAR LEAGUE TEMPO (table-derived)
--------------------------------------------------------------------------------
local function getWarTempo(di)
local ok, wl = pcall(require, "Module:WarLeagueDivisionOpsBVR")
if not ok or not wl or type(wl.makeTable) ~= "function" then
return { score = 0, redRate = 0 }
end


    local yearFraction = totalDaysElapsed / daysPerYear
local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
    local psscYear    = math.floor(yearFraction)
local rows = 0
    local dayOfYear    = math.floor((yearFraction - psscYear) * daysPerYear) + 1
local high, critical = 0, 0


    local month, dayOfMonth
-- Count urgency tokens
    if dayOfYear <= 61 then
for urg in out:gmatch("||%s*([A-Z]+)%s*||%s*%d") do
        month = 1; dayOfMonth = dayOfYear
-- not reliable; fall back below
    elseif dayOfYear <= 122 then
end
        month = 2; dayOfMonth = dayOfYear - 61
for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do
    else
rows = rows + 1
        month = 3; dayOfMonth = dayOfYear - 122
if u == "HIGH" then high = high + 1 end
    end
if u == "CRITICAL" then critical = critical + 1 end
end


    return string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear), dayOfMonth, month
if rows == 0 then rows = 36 end
local severity = (high * 1.0 + critical * 2.0) / rows
return { score = severity, redRate = (high + critical) / rows }
end
end


---------------------------------------------------------
local function warMultiplier(war, sector)
-- 2. Basic Setup
-- War tempo raises security/logistics employment, can mildly depress agriculture (labor diversion).
---------------------------------------------------------
local s = tonumber(war.score or 0) or 0
local population      = 55499301
if sector == "Services" then
local unemploymentRate = 0.04 -- 4% unemployment
return clamp(1.0 + (s * 0.08), 0.95, 1.18)
local employedPopulation = math.floor(population * (1 - unemploymentRate))
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


-- Company table and their employment percentages
--------------------------------------------------------------------------------
local companies = {
-- 7) TEMPLE BANK / MISSIONARY ACTIVITY (table-derived)
    {name = "Lake Morovia Blockade Fund", employmentPercentage = 0.0300},
--------------------------------------------------------------------------------
    {name = "Gladeseed Farmers' Union",      employmentPercentage = 0.1205},
local function getTempleTempo(di)
    {name = "Atterian Cattle Drivers",        employmentPercentage = 0.0502},
local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR")
    {name = "Roving Wind Farm Corporation",  employmentPercentage = 0.0210},
if not ok or not tb or type(tb.makeTable) ~= "function" then
    {name = "Baratar Corporation",            employmentPercentage = 0.0401},
return { redRate = 0 }
    {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ái 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},
}


---------------------------------------------------------
-- Keep it light: Core only, limited rows, no econ scan
-- 3. Random Variation
local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
--   Up to ±25% daily shift in each company's employees
local red, n = 0, 0
---------------------------------------------------------
 
local function calculateEmployees(company)
-- Severity column is last; values like Green/Yellow/Red (and sometimes richer labels)
    local currentEmployees = math.floor(employedPopulation * company.employmentPercentage)
for sev in out:gmatch("||%s*([^|\n]+)%s*$") do
    local maxChange        = math.floor(currentEmployees * 0.25)
-- too broad; instead count explicit "Red" tokens in the table rows
    local changeAmount      = math.random(-maxChange, maxChange)
end
    local newEmployees      = math.max(1, currentEmployees + changeAmount)
for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do
    return currentEmployees, newEmployees
n = n + 1
if sev == "Red" then red = red + 1 end
end
 
if n == 0 then n = 40 end
return { redRate = red / n }
end
end


---------------------------------------------------------
local function templeMultiplier(temple, sector)
-- 4. generateTable
-- Temple activity tends to lift services/admin and stabilize labor participation.
--   Seeds randomness by the day so that results are
local r = tonumber(temple.redRate or 0) or 0
--   stable for that day but refresh the next day.
if sector == "Services" then
--   Rows colored:
return clamp(1.0 + (r * 0.06), 0.98, 1.10)
--     • Increase ⇒ light blue
end
--     • Same    ⇒ light green
return clamp(1.0 + (r * 0.02), 0.98, 1.06)
--     • Decrease ⇒ light red
end
---------------------------------------------------------
 
function p.generateTable()
--------------------------------------------------------------------------------
    -- (A) Seed daily randomness
-- 8) OPTIONAL: HATCH MINISTRY OPS (if you add a module later)
    local localTime = os.date("*t")
--------------------------------------------------------------------------------
    math.randomseed(localTime.year * 1000 + localTime.yday)
local function getHatchTempo(di)
local ok, hm = pcall(require, "Module:HatchMinistryDailyOpsBVR")
if not ok or 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 ""
-- naive proxy: count "Interdiction" / "Inspection" / "Seizure"
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.present then return 1.0 end
local x = tonumber(hatch.intensity or 0) or 0
-- More ops -> more services + compliance work; mild drag on throughput-heavy sectors
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
 
--------------------------------------------------------------------------------
-- 9) BUILD BASE EMPLOYMENT SHARES ACROSS ALL PORT COMPANIES
--------------------------------------------------------------------------------
local function buildBaseShares(allCompanies)
-- Sector shares (can be tuned later)
local sectorTarget = {
["Agricultural"] = 0.34,
["Mining/Manufacturing"] = 0.33,
["Services"] = 0.33,
["Unknown"] = 0.00
}
 
-- Collect by sector
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {}, Unknown = {} }
for _, c in ipairs(allCompanies) do
local sec = c.sector or "Unknown"
if not bySector[sec] then sec = "Unknown" end
table.insert(bySector[sec], c)
end
 
-- Assign raw weights per company (stable)
local weights = {}
for sec, list in pairs(bySector) do
local sum = 0
for _, c in ipairs(list) do
local w = 0.6 + (hashFrac("w:" .. c.name) * 1.4)  -- 0.6..2.0
weights[c.name] = { raw = w, sector = sec }
sum = sum + w
end
-- normalize to sector target
local target = sectorTarget[sec] or 0
for _, c in ipairs(list) do
local raw = weights[c.name].raw
local share = (sum > 0) and (raw / sum) * target or 0
weights[c.name].share = share
end
end
 
return weights
end
 
--------------------------------------------------------------------------------
-- 10) MAIN TABLE
--------------------------------------------------------------------------------
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 "")) -- Agricultural | Mining/Manufacturing | Services
local limit = tonumber(args.limit or "")               -- optional row cap
local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"
 
-- Seed (stable per day)
math.randomseed(di.year * 1000 + di.dayOfYear)
 
-- Pull all companies from the port page
local companies = parsePortCompanies()
 
-- Fallback to legacy list if parsing fails
if #companies == 0 then
companies = {
{ name = "Gladeseed Farmers' Union", sector = "Agricultural" },
{ name = "Atterian Cattle Drivers", sector = "Agricultural" },
{ name = "Noctic Fleet", sector = "Agricultural" },
{ name = "Baratar Corporation", sector = "Mining/Manufacturing" },
{ name = "Hatch Ministry", sector = "Services" },
}
end
 
local shares = buildBaseShares(companies)
 
-- Cost indices by sector from your three pricing modules
local costAg  = getCostIndex("Module:AutoUpdateAgPrices", "summary")
local costManf = getCostIndex("Module:AutoUpdateManfPrices", "summary")
local costServ = getCostIndex("Module:AutoUpdateServPrices", "summary")
 
-- Market sentiment
local market = getMarketSentiment()
 
-- Weather / ops
local wx = getWeatherSignal(city, di.year, di.dayOfYear)
 
-- War / Temple / Hatch
local war = getWarTempo(di)
local temple = getTempleTempo(di)
local hatch = getHatchTempo(di)
 
-- Macro unemployment baseline (tune here)
-- Using national population referenced on the Port page; keep unemployment modest.
local population = 94160000
local unemploymentRate = 0.04
 
-- Small macro adjustment:
-- • positive market bias reduces unemployment slightly
-- • severe weather increases it slightly
local u = unemploymentRate
u = u - clamp(market.bias * 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 sectorCostMultiplier(sec)
-- In your price modules, "Low" corresponds to higher adjusted price (better voucher yield).
-- So ratio > 1 => affordability/availability tailwind.
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
 
local function marketMultiplier(sec)
-- Small demand signal; services most responsive.
local b = clamp(market.bias or 0, -1, 1)
if sec == "Services" then
return clamp(1.0 + b * 0.03, 0.95, 1.05)
elseif sec == "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
 
-- Build one combined multiplier by sector
local function combinedMultiplier(sec)
local m = 1.0
m = m * sectorCostMultiplier(sec)
m = m * weatherMultiplier(wx, sec)
m = m * warMultiplier(war, sec)
m = m * templeMultiplier(temple, sec)
m = m * hatchMultiplier(hatch, sec)
m = m * marketMultiplier(sec)
return clamp(m, 0.65, 1.25)
end
 
-- Dashboard (top)
local out = {}
if showDashboard then
table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"")
table.insert(out, "! colspan=\"4\" | General Port Employment Signals — " .. di.dateString)
table.insert(out, "|-")
table.insert(out, string.format("| '''Weather''' || %s (%s) || '''Market bias''' || %.2f",
(wx.label or "Green"), (wx.condition or ""), (market.bias or 0)))
table.insert(out, "|-")
table.insert(out, string.format("| '''Cost ratio (Ag/Manf/Serv)''' || %.3f / %.3f / %.3f || '''War tempo (red-rate)''' || %.2f",
(costAg.ratio or 1.0), (costManf.ratio or 1.0), (costServ.ratio or 1.0),
(war.redRate or 0)))
table.insert(out, "|-")
table.insert(out, string.format("| '''Temple tempo (red-rate)''' || %.2f || '''Unemployment (modeled)''' || %.2f%%",
(temple.redRate or 0), u * 100))
table.insert(out, "|}")
table.insert(out, "")
end
 
-- Main table (sortable); can be huge, so keep it scrollable
table.insert(out, '<div style="overflow-x:auto;">')
table.insert(out, "{| class=\"wikitable sortable\"")
table.insert(out, "! Date !! Sector !! Company !! Base Share % !! Previous Employees !! Current Employees !! Δ !! Drivers")
 
local count = 0
for _, c in ipairs(companies) do
local sec = c.sector or "Unknown"
if sectorFilter == "" or sec == sectorFilter then
local share = (shares[c.name] and shares[c.name].share) or 0


    -- (B) Get date
-- baseline
    local date, _, _ = getCurrentDate()
local prev = math.max(1, math.floor(employedPopulation * share))


    -- (C) Table header
-- daily company-level jitter (stable per company/day)
    local wikitable = "{| class=\"wikitable\"\n"
local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18 -- ±9%
        .. "! Date !! Company !! Employment % !! Previous Employees !! Current Employees !! Change\n"
local mult = combinedMultiplier(sec) * (1.0 + jitter)
local curr = math.max(1, math.floor(prev * mult))


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


    -- (D) Per-company rows
-- row color
    for _, company in ipairs(companies) do
local rowStyle = ""
        local prevE, currE = calculateEmployees(company)
if curr > prev then rowStyle = ' style="background-color:lightblue;"'
        local changeType
elseif curr == prev then rowStyle = ' style="background-color:lightgreen;"'
        if currE > prevE then
else rowStyle = ' style="background-color:#ffcccb;"' end
            changeType = "Increased"
        elseif currE < prevE then
            changeType = "Decreased"
        else
            changeType = "Same"
        end


        -- choose row color
local drivers = string.format(
        local rowStyle
"cost×%.2f; wx×%.2f; war×%.2f; temple×%.2f; hatch×%.2f; mkt×%.2f",
        if changeType == "Increased" then
sectorCostMultiplier(sec),
            rowStyle = ' style="background-color:lightblue;"'
weatherMultiplier(wx, sec),
        elseif changeType == "Same" then
warMultiplier(war, sec),
            rowStyle = ' style="background-color:lightgreen;"'
templeMultiplier(temple, sec),
        else
hatchMultiplier(hatch, sec),
            rowStyle = ' style="background-color:#ffcccb;"'
marketMultiplier(sec)
        end
)


        totalEmployed = totalEmployed + currE
table.insert(out, string.format(
"|-%s\n| %s || %s || %s || %.3f%% || %d || %d || %s || %s",
rowStyle,
di.dateString,
sec,
c.name,
share * 100,
prev,
curr,
deltaSym,
drivers
))


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


    -- (E) Totals row
table.insert(out, "|}")
    local totalUnemployed = population - totalEmployed
table.insert(out, "</div>")
    wikitable = wikitable
        .. string.format("|-\n| Total Employed  || || || || %d ||\n", totalEmployed)
        .. string.format("|-\n| Total Unemployed || || || || %d ||\n|}", totalUnemployed)


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


return p
return p

Revision as of 18:44, 19 January 2026

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

-- Module:BassaridEmployment
-- Employment report for the General Port of Lake Morovia.
--
-- Key changes:
--  • Includes ALL companies listed on [[General Port of Lake Morovia]] Company Table (auto-parsed).
--  • Factors in: costs (Ag/Manf/Serv price modules), weather (BassaridiaForecast),
--    War League activity (WarLeagueDivisionOpsBVR), Temple Bank activity (MissionaryDailyOpsBVR),
--    market sentiment (BassaridMarketActivity), and (optionally) Hatch Ministry ops.
--
-- Usage:
--   {{#invoke:BassaridEmployment|generateTable}}
--   {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}}
--   {{#invoke:BassaridEmployment|generateTable|limit=80}}
--   {{#invoke:BassaridEmployment|generateTable|sector=Agricultural}}
--   {{#invoke:BassaridEmployment|generateTable|dashboard=no}}
--
-- Notes:
--  • This module is designed to be deterministic per day (stable output on the same day).
--  • If the port page format changes, parsing may need a small adjustment.

local p = {}

--------------------------------------------------------------------------------
-- 0) BASIC UTILS
--------------------------------------------------------------------------------
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 safeNumber(x)
	local n = tonumber(x)
	if not n then return nil end
	return n
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)
	-- stable 0..1 from md5 hex
	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

--------------------------------------------------------------------------------
-- 1) DATE (PSSC) – keep same base logic as your other modules
--------------------------------------------------------------------------------
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

--------------------------------------------------------------------------------
-- 2) PULL ALL PORT COMPANIES (auto-parse from the General Port page)
--------------------------------------------------------------------------------
local PORT_PAGE = "General Port of Lake Morovia"

local function parsePortCompanies()
	local title = mw.title.new(PORT_PAGE)
	if not title then return {} end
	local content = title:getContent() or ""
	if content == "" then return {} end

	-- We track sector based on headers.
	-- Your page uses a Company Table split into Agricultural / Mining/Manufacturing / Services.
	local sector = nil
	local companies = {}
	local seen = {}

	local function push(name, sec)
		name = stripWiki(name)
		if name == "" then return end
		if not seen[name] then
			seen[name] = true
			table.insert(companies, { name = name, sector = sec or "Unknown" })
		end
	end

	for line in content:gmatch("[^\n]+") do
		local l = trim(line)

		-- sector headers (tolerant patterns)
		if l:match("^=+%s*Agricultural%s*=+") then
			sector = "Agricultural"
		elseif l:match("^=+%s*Mining/Manufacturing%s*=+") or l:match("^=+%s*Mining%s*/%s*Manufacturing%s*=+") then
			sector = "Mining/Manufacturing"
		elseif l:match("^=+%s*Services%s*=+") then
			sector = "Services"
		end

		-- Company cell style you use: | **Company Name**
		local boldName = l:match("%|%s*%*%*([^%*]+)%*%*")
		if boldName then
			push(boldName, sector)
		end
	end

	return companies
end

--------------------------------------------------------------------------------
-- 3) COST INDICES FROM PRICE MODULES (avg adjusted vs avg base)
--------------------------------------------------------------------------------
local function getCostIndex(moduleName, mode)
	local ok, m = pcall(require, moduleName)
	if not ok or not m or type(m.generateTable) ~= "function" then
		return { ratio = 1.0, avgNew = nil, avgBase = nil }
	end

	-- call generateTable in summary mode (your modules accept frame tables)
	local out = m.generateTable({ args = { mode = mode or "summary" } }) or ""
	-- parse: "Average adjusted (X) vs base (Y)"
	local aNew, aBase = out:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)")
	aNew, aBase = safeNumber(aNew), safeNumber(aBase)
	if not aNew or not aBase or aBase == 0 then
		return { ratio = 1.0, avgNew = aNew, avgBase = aBase }
	end
	return { ratio = aNew / aBase, avgNew = aNew, avgBase = aBase }
end

--------------------------------------------------------------------------------
-- 4) MARKET ACTIVITY (investor sentiment proxy)
--------------------------------------------------------------------------------
local function getMarketSentiment()
	local ok, m = pcall(require, "Module:BassaridMarketActivity")
	if not ok or not m or type(m.generateTable) ~= "function" then
		return { avgPct = 0.0, bias = 0.0 }
	end

	local out = m.generateTable({ args = {} }) or ""
	-- Extract pct values like " -1.23%" or " 2.50%"
	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 { avgPct = avg, bias = bias }
end

--------------------------------------------------------------------------------
-- 5) WEATHER / OPS IMPACT (default city Vaeringheim)
--------------------------------------------------------------------------------
local function getWeatherSignal(city, year, dayOfYear)
	local ok, wx = pcall(require, "Module:BassaridiaForecast")
	if not ok or not wx or type(wx.getOpsData) ~= "function" then
		return { level = 0, label = "Green", impacts = {}, condition = "" }
	end
	local op = wx.getOpsData(city, year, dayOfYear)
	if not op or not op.alert then
		return { level = 0, label = "Green", impacts = {}, condition = "" }
	end
	return {
		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)
	-- Base by alert level
	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 "")

	-- Sector-sensitive penalties
	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

--------------------------------------------------------------------------------
-- 6) WAR LEAGUE TEMPO (table-derived)
--------------------------------------------------------------------------------
local function getWarTempo(di)
	local ok, wl = pcall(require, "Module:WarLeagueDivisionOpsBVR")
	if not ok or not wl or type(wl.makeTable) ~= "function" then
		return { score = 0, redRate = 0 }
	end

	local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
	local rows = 0
	local high, critical = 0, 0

	-- Count urgency tokens
	for urg in out:gmatch("||%s*([A-Z]+)%s*||%s*%d") do
		-- not reliable; fall back below
	end
	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 { score = severity, redRate = (high + critical) / rows }
end

local function warMultiplier(war, sector)
	-- War tempo raises security/logistics employment, can mildly depress agriculture (labor diversion).
	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

--------------------------------------------------------------------------------
-- 7) TEMPLE BANK / MISSIONARY ACTIVITY (table-derived)
--------------------------------------------------------------------------------
local function getTempleTempo(di)
	local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR")
	if not ok or not tb or type(tb.makeTable) ~= "function" then
		return { redRate = 0 }
	end

	-- Keep it light: Core only, limited rows, no econ scan
	local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
	local red, n = 0, 0

	-- Severity column is last; values like Green/Yellow/Red (and sometimes richer labels)
	for sev in out:gmatch("||%s*([^|\n]+)%s*$") do
		-- too broad; instead count explicit "Red" tokens in the table rows
	end
	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 { redRate = red / n }
end

local function templeMultiplier(temple, sector)
	-- Temple activity tends to lift services/admin and stabilize labor participation.
	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

--------------------------------------------------------------------------------
-- 8) OPTIONAL: HATCH MINISTRY OPS (if you add a module later)
--------------------------------------------------------------------------------
local function getHatchTempo(di)
	local ok, hm = pcall(require, "Module:HatchMinistryDailyOpsBVR")
	if not ok or 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 ""
	-- naive proxy: count "Interdiction" / "Inspection" / "Seizure"
	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.present then return 1.0 end
	local x = tonumber(hatch.intensity or 0) or 0
	-- More ops -> more services + compliance work; mild drag on throughput-heavy sectors
	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

--------------------------------------------------------------------------------
-- 9) BUILD BASE EMPLOYMENT SHARES ACROSS ALL PORT COMPANIES
--------------------------------------------------------------------------------
local function buildBaseShares(allCompanies)
	-- Sector shares (can be tuned later)
	local sectorTarget = {
		["Agricultural"] = 0.34,
		["Mining/Manufacturing"] = 0.33,
		["Services"] = 0.33,
		["Unknown"] = 0.00
	}

	-- Collect by sector
	local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {}, Unknown = {} }
	for _, c in ipairs(allCompanies) do
		local sec = c.sector or "Unknown"
		if not bySector[sec] then sec = "Unknown" end
		table.insert(bySector[sec], c)
	end

	-- Assign raw weights per company (stable)
	local weights = {}
	for sec, list in pairs(bySector) do
		local sum = 0
		for _, c in ipairs(list) do
			local w = 0.6 + (hashFrac("w:" .. c.name) * 1.4)  -- 0.6..2.0
			weights[c.name] = { raw = w, sector = sec }
			sum = sum + w
		end
		-- normalize to sector target
		local target = sectorTarget[sec] or 0
		for _, c in ipairs(list) do
			local raw = weights[c.name].raw
			local share = (sum > 0) and (raw / sum) * target or 0
			weights[c.name].share = share
		end
	end

	return weights
end

--------------------------------------------------------------------------------
-- 10) MAIN TABLE
--------------------------------------------------------------------------------
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 "")) -- Agricultural | Mining/Manufacturing | Services
	local limit = tonumber(args.limit or "")               -- optional row cap
	local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"

	-- Seed (stable per day)
	math.randomseed(di.year * 1000 + di.dayOfYear)

	-- Pull all companies from the port page
	local companies = parsePortCompanies()

	-- Fallback to legacy list if parsing fails
	if #companies == 0 then
		companies = {
			{ name = "Gladeseed Farmers' Union", sector = "Agricultural" },
			{ name = "Atterian Cattle Drivers", sector = "Agricultural" },
			{ name = "Noctic Fleet", sector = "Agricultural" },
			{ name = "Baratar Corporation", sector = "Mining/Manufacturing" },
			{ name = "Hatch Ministry", sector = "Services" },
		}
	end

	local shares = buildBaseShares(companies)

	-- Cost indices by sector from your three pricing modules
	local costAg   = getCostIndex("Module:AutoUpdateAgPrices", "summary")
	local costManf = getCostIndex("Module:AutoUpdateManfPrices", "summary")
	local costServ = getCostIndex("Module:AutoUpdateServPrices", "summary")

	-- Market sentiment
	local market = getMarketSentiment()

	-- Weather / ops
	local wx = getWeatherSignal(city, di.year, di.dayOfYear)

	-- War / Temple / Hatch
	local war = getWarTempo(di)
	local temple = getTempleTempo(di)
	local hatch = getHatchTempo(di)

	-- Macro unemployment baseline (tune here)
	-- Using national population referenced on the Port page; keep unemployment modest.
	local population = 94160000
	local unemploymentRate = 0.04

	-- Small macro adjustment:
	-- • positive market bias reduces unemployment slightly
	-- • severe weather increases it slightly
	local u = unemploymentRate
	u = u - clamp(market.bias * 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 sectorCostMultiplier(sec)
		-- In your price modules, "Low" corresponds to higher adjusted price (better voucher yield).
		-- So ratio > 1 => affordability/availability tailwind.
		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

	local function marketMultiplier(sec)
		-- Small demand signal; services most responsive.
		local b = clamp(market.bias or 0, -1, 1)
		if sec == "Services" then
			return clamp(1.0 + b * 0.03, 0.95, 1.05)
		elseif sec == "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

	-- Build one combined multiplier by sector
	local function combinedMultiplier(sec)
		local m = 1.0
		m = m * sectorCostMultiplier(sec)
		m = m * weatherMultiplier(wx, sec)
		m = m * warMultiplier(war, sec)
		m = m * templeMultiplier(temple, sec)
		m = m * hatchMultiplier(hatch, sec)
		m = m * marketMultiplier(sec)
		return clamp(m, 0.65, 1.25)
	end

	-- Dashboard (top)
	local out = {}
	if showDashboard then
		table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"")
		table.insert(out, "! colspan=\"4\" | General Port Employment Signals — " .. di.dateString)
		table.insert(out, "|-")
		table.insert(out, string.format("| '''Weather''' || %s (%s) || '''Market bias''' || %.2f",
			(wx.label or "Green"), (wx.condition or ""), (market.bias or 0)))
		table.insert(out, "|-")
		table.insert(out, string.format("| '''Cost ratio (Ag/Manf/Serv)''' || %.3f / %.3f / %.3f || '''War tempo (red-rate)''' || %.2f",
			(costAg.ratio or 1.0), (costManf.ratio or 1.0), (costServ.ratio or 1.0),
			(war.redRate or 0)))
		table.insert(out, "|-")
		table.insert(out, string.format("| '''Temple tempo (red-rate)''' || %.2f || '''Unemployment (modeled)''' || %.2f%%",
			(temple.redRate or 0), u * 100))
		table.insert(out, "|}")
		table.insert(out, "")
	end

	-- Main table (sortable); can be huge, so keep it scrollable
	table.insert(out, '<div style="overflow-x:auto;">')
	table.insert(out, "{| class=\"wikitable sortable\"")
	table.insert(out, "! Date !! Sector !! Company !! Base Share % !! Previous Employees !! Current Employees !! Δ !! Drivers")

	local count = 0
	for _, c in ipairs(companies) do
		local sec = c.sector or "Unknown"
		if sectorFilter == "" or sec == sectorFilter then
			local share = (shares[c.name] and shares[c.name].share) or 0

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

			-- daily company-level jitter (stable per company/day)
			local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18 -- ±9%
			local mult = combinedMultiplier(sec) * (1.0 + jitter)
			local curr = math.max(1, math.floor(prev * mult))

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

			-- row color
			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

			local drivers = string.format(
				"cost×%.2f; wx×%.2f; war×%.2f; temple×%.2f; hatch×%.2f; mkt×%.2f",
				sectorCostMultiplier(sec),
				weatherMultiplier(wx, sec),
				warMultiplier(war, sec),
				templeMultiplier(temple, sec),
				hatchMultiplier(hatch, sec),
				marketMultiplier(sec)
			)

			table.insert(out, string.format(
				"|-%s\n| %s || %s || %s || %.3f%% || %d || %d || %s || %s",
				rowStyle,
				di.dateString,
				sec,
				c.name,
				share * 100,
				prev,
				curr,
				deltaSym,
				drivers
			))

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

	table.insert(out, "|}")
	table.insert(out, "</div>")

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

return p