Jump to content

Module:AssetID

From Costa Sano MediaWiki

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

local p = {}
local cargo = mw.ext.cargo

local function pad(n)
    return string.format("%04d", tonumber(n))
end

function p.generate(frame)
    local a = frame.args
    local chapter = a.Chapter
    local place = a.Place
    local org = a.Organisation

    if place ~= "" and org ~= "" then
        return mw.text.jsonEncode({ error = "Choose Place OR Organisation." })
    end

    if place == "" and org == "" then
        return mw.text.jsonEncode({ error = "Place or Organisation required." })
    end

    local ctxField = place ~= "" and "Place" or "Organisation"
    local ctxValue = place ~= "" and place or org

    local res = cargo.query(
        "Assets",
        "MAX(Sequence)=max",
        {
            where = string.format(
                "Chapter='%s' AND %s='%s'",
                chapter, ctxField, ctxValue
            )
        }
    )

    local nextSeq = (res[1] and res[1].max or 0) + 1

    local code = string.format(
        "%s-%s-%s",
        mw.title.new(chapter).text,
        mw.title.new(ctxValue).text,
        pad(nextSeq)
    )

    return mw.text.jsonEncode({
        identifier = code,
        sequence = nextSeq
    })
end

return p