Module:Products: Difference between revisions

From Brighter Shores Wiki
Jump to navigation Jump to search
Content added Content deleted
m (Spaces to tabs)
(recipes which have the passive tag will have their quantities displayed as per-hour, rather than per-recipe)
 
(11 intermediate revisions by 3 users not shown)
Line 1: Line 1:
require('Module:Mw.html extension')
local Array = require('Module:Array')
local currency = require('Module:Currency').parse
local currency = require('Module:Currency').parse
local yesno = require('Module:Yesno')
local purge = require('Module:Purge')._purge


local p = {}
local p = {}
Line 5: Line 9:
function p.main(frame)
function p.main(frame)
return p._main(frame:getParent().args)
return p._main(frame:getParent().args)
end

local function recipe_sort(recipe_a, recipe_b)
--if one is nil but not both, put nil levels after known levels
if (recipe_a.level == nil) ~= (recipe_b.level == nil) then
return recipe_b.level == nil
end
-- if both are nil, sort by name
if recipe_a.level == nil then
return recipe_a.output[1].name < recipe_b.output[1].name
end
-- if neither is nil, sort first by level
if recipe_a.level ~= recipe_b.level then
return recipe_a.level < recipe_b.level
end

-- if neither is nil and levels are the same, sort by name
return recipe_a.output[1].name < recipe_b.output[1].name
end
end


function p._main(args)
function p._main(args)
args = args or {}
args = args or {}
args.item = args.item or mw.title.getCurrentTitle().text
local item = args[1] or mw.title.getCurrentTitle().text
local showPrices = args.showPrices or false
local showPrices = yesno(args.showPrices)
local showValues = args.showValues or false
local showValues = yesno(args.showValues)
local products = p.getProducts(args)
local limit = tonumber(args.limit or 0) or 0
if products ~= 0 then
if limit <= 0 then
limit = 500
local recipeNames = p.extractRecipeNames(products)
end
local prodprices = p.getShopBuyPrices(products)
-- Generate and return a table containing the product information
-- Query for data
local output = p.displayProductTable(prodprices, showPrices, showValues)
local smw_data = mw.smw.ask{
return output
'[[Uses item::' .. item .. ']] OR [[Activity input::' .. item .. ']] OR [[Activity container::' .. item .. ']]',
else
'?Recipe JSON',
return "There are no known products for item '''args.item'''"
'?Activity JSON',
showValues and '?Value',
limit = limit
}
if not smw_data then
return ":''No products found. To force an update, click "
..purge('dml-'..mw.uri.anchorEncode(item), 'here', 'span')
..".''[[Category:Empty products lists]]"
end
end
end


-- Create a list of all recipes that use this item
function p.extractRecipeNames(products)
local recipeNames = {}
local recipes = {}
for _, recipeInfo in ipairs(products) do
for _, product in ipairs(smw_data) do
-- this part will need to be addressed if a page has both a recipe and an activity
local recipeLink = recipeInfo["Recipe"]
local jsons = product['Recipe JSON'] or product['Activity JSON']
if recipeLink then
if type(jsons) == 'string' then
local displayName = recipeLink:match("%[%[.-|(.+)%]%]")
jsons = { jsons }
if displayName then
end
table.insert(recipeNames, displayName)
for _, json in ipairs(jsons) do
local json = mw.text.jsonDecode(json)
json.Value = product.Value
-- Filter out when this item isn't actually used (Will happen on pages with multiple recipes)
if Array.any(json.materials, function(mat)
return mat.name == item
end) then
table.insert(recipes, json)
end
end
end
end
end
end
return recipeNames
end


-- Sort list of recipes by the level of the recipe (cross-profession)
function p.getProducts(args)
table.sort(recipes, recipe_sort)
local item = mw.smw.ask('[[:+]][[Uses item::' .. args.item .. ']]|?Uses item |?Uses item and quantity |?Profession A |?Profession Level A|?Value |mainlabel=Recipe') or 0
return item
end


-- if recipe is passive, want per hour
function p.getShopBuyPrices(products)
for _, product in ipairs(products) do
for _, recipe in ipairs(recipes) do
recipe.recipePerHour = recipe.duration and math.floor(3600/recipe.duration)
local usesItems = product["Uses item and quantity"]
-- replace quantities with per-hour quantities
if type(usesItems) == "string" then
-- if recipe.passive then
-- Single value
for _,item in ipairs(recipe.output) do
usesItems = { usesItems }
item.displayQuantity = (item.quantity and recipe.recipePerHour and item.quantity * recipe.recipePerHour) or ''
end
end
for _, item in ipairs(usesItems) do
for _,item in ipairs(recipe.materials) do
-- Extract item name and quantity from the "item,#" format
item.displayQuantity = (item.quantity and recipe.recipePerHour and item.quantity * recipe.recipePerHour) or ''
local itemName, quantity = item:match("^([^,]+),([0-9.]+)$")
end
quantity = tonumber(quantity) or 1 -- Default to 1 if quantity is missing
-- end
end
-- Calculate shop prices
if showPrices then
local price_cache = {}
for _, recipe in ipairs(recipes) do
for _, item in ipairs(recipe.materials) do
-- Extract item name and quantity from the "item,#" format


if itemName then
-- Query for the shop buy price of the item
-- Query for the shop buy price of the item
local shopPriceResult = price_cache[item.name] or mw.smw.ask{
local shopPriceQuery = '[[:+]][[Sold item::' .. itemName .. ']]|?Shop buy price|mainlabel=' .. itemName
'[[Sold item::' .. item.name .. ']]',
local shopPriceResult = mw.smw.ask(shopPriceQuery) or {}
local shopPrice = 0
'?Shop buy price'
} or {}
price_cache[item.name] = shopPriceResult
local shopPrice


if shopPriceResult[1] and shopPriceResult[1]["Shop buy price"] then
if shopPriceResult[1] then
shopPrice = tonumber(shopPriceResult[1]["Shop buy price"]) or 0
shopPrice = tonumber(shopPriceResult[1]['Shop buy price'] or 0) or 0
end
end


-- Multiply the price by the quantity
-- Update the product with the total price
local totalPrice = shopPrice * quantity
if shopPrice ~= nil then
item.price = shopPrice * item.quantity

end
-- Update the product with the formatted string and total price
product[itemName .. "_Shop_buy_price"] = totalPrice > 0 and totalPrice or "N/A"
product[itemName .. "_Formatted"] = tostring(quantity) .. " &times; " .. itemName
end
end
end
end
end
end
return products
end


-- Create table
function p.displayProductTable(products, showPrices, showValues)
local out = {}
local out = mw.html.create('table')
table.insert(out, '{| class="wikitable"')
:addClass('wikitable align-right-1 sortable')
:tag('tr')
:tag('th')
:attr{ colspan = '3' }
:wikitext('Product')
:done()
:tag('th'):wikitext('Level'):done()
:IF(showValues)
:tag('th'):wikitext('Value'):done()
:END()
:tag('th'):wikitext('Inputs'):done()
:IF(showPrices)
:tag('th'):wikitext('Price'):done()
:END()
:done()


for _, recipe in ipairs(recipes) do
local headerRow = {}
local row = out:tag('tr')
table.insert(headerRow, '!colspan="2" | Recipe')
:tag('td')
table.insert(headerRow, '!! Level')
:css{ ['border-right'] = '0', ['padding-right'] = '0' }
:attr{ ['data-sort-value'] = recipe.output[1].name }
:IF(recipe.passive)
:wikitext(recipe.output[1].displayQuantity .. ' (/hr) &times;')
:ELSE()
:wikitext(recipe.output[1].quantity .. ' &times;')
:END()
:done()
:tag('td')
:addClass('plinkt-image no-border')
:css{ ['border-left'] = '0', ['padding-left'] = '0' }
:wikitext('[[File:' .. recipe.output[1].name .. '.png|link=' .. recipe.output[1].name .. '|30px]]')
:done()
:tag('td')
:addClass('plinkt-link no-border')
:wikitext('[[' .. recipe.output[1].name .. ']]')
:done()
:tag('td')
:IF(recipe.profession)
:wikitext(('[[File:%s small icon.png|15px|link=%s]] %s'):format(recipe.profession, recipe.profession, recipe.level or 'Unknown'))
:ELSE()
:wikitext(('[[FileUnknown profession small icon.png|15px|link=Professions]] %s'):format(recipe.level or 'Unknown'))
:END()
:done()


if showValues then
if showValues then
if recipe.Value then
table.insert(headerRow, '!! Value')
row:tag('td')
end
:wikitext(currency(recipe.Value))

:done()
table.insert(headerRow, '!! Ingredients')
else

row:tag('td')
if showPrices then
:attr{ ['data-sort-value'] = '' }
table.insert(headerRow, '!! Price')
:wikitext('Unknown')
end
:done()

table.insert(out, table.concat(headerRow, ' '))

for _, product in ipairs(products) do
local recipeRawText = product["Recipe"]:match("%[%[.-|(.+)%]%]")
local recipeImage = "[[File:" .. recipeRawText .. ".png|30px]]"
local recipe = product["Recipe"] or "Unknown"
local professionName = product["Profession A"]:match("%[%[.-|(.+)%]%]") or product["Profession A"]:match("%[%[(.-)%]%]") or product["Profession A"] or "Unknown"
local professionLevel = "[[File:" .. professionName .. " small icon.png|15px]] " .. (product["Profession Level A"] or "Unknown")
local usesItems = product["Uses item"] or {}
local value = currency(product["Value"]) or "Unknown"

-- Concatenate uses items and their shop buy prices in unordered lists
local usesItemStr = "<ul style='list-style:none; margin:0; padding-left:0;'>"
local shopBuyPriceStr = "<ul style='list-style:none; margin:0; padding-left:0; text-align:right;'>"

if type(usesItems) == "table" then
for _, item in ipairs(usesItems) do
local itemName = item:match("%[%[.-|(.+)%]%]") or item:match("%[%[(.-)%]%]") or item
usesItemStr = usesItemStr .. "<li>" .. product[itemName .. "_Formatted"] .. "</li>"
local shopBuyPrice = product[itemName .. "_Shop_buy_price"] or 0
if shopBuyPrice == "N/A" then shopBuyPrice = 0 end
shopBuyPriceStr = shopBuyPriceStr .. "<li>" .. currency(shopBuyPrice) .. "</li>"
end
end
elseif type(usesItems) == "string" then
local itemName = usesItems:match("%[%[.-|(.+)%]%]") or usesItems:match("%[%[(.-)%]%]") or usesItems
usesItemStr = usesItemStr .. "<li>" .. product[itemName .. "_Formatted"] .. "</li>"
local shopBuyPrice = product[itemName .. "_Shop_buy_price"] or 0
if shopBuyPrice == "N/A" then shopBuyPrice = 0 end
shopBuyPriceStr = shopBuyPriceStr .. "<li>" .. currency(shopBuyPrice) .. "</li>"
end
end


local ingredients = row:tag('td')
usesItemStr = usesItemStr .. "</ul>"
:attr{ ['data-sort-value'] = table.concat(Array.map(recipe.materials, function(item) return item.name end), '\0') }
shopBuyPriceStr = shopBuyPriceStr .. "</ul>"
:tag('ul')
:css{ ['list-style'] = 'none', ['margin'] = '0', ['padding-left'] = '0' }


for _, item in ipairs(recipe.materials) do
table.insert(out, '|-')
ingredients:tag('li')

:IF(recipe.passive)
local valuesRow = {}
:wikitext(('%s (/hr) &times; [[File:%s.png|link=%s|18px]] [[%s]]'):format(item.displayQuantity, item.name, item.name, item.name))

:ELSE()
table.insert(valuesRow, '| ' .. recipeImage)
:wikitext(('%s &times; [[File:%s.png|link=%s|18px]] [[%s]]'):format(item.quantity, item.name, item.name, item.name))
table.insert(valuesRow, '|| ' .. recipe)
:END()
table.insert(valuesRow, '|| ' .. professionLevel)
:done()

if showValues then
table.insert(valuesRow, '|| ' .. value)
end
end

table.insert(valuesRow, '|| ' .. usesItemStr)


if showPrices then
if showPrices then
local prices = row:tag('td')
table.insert(valuesRow, '|| ' .. shopBuyPriceStr)
:tag('ul')
end
:css{ ['list-style'] = 'none', ['margin'] = '0', ['padding-left'] = '0' }

table.insert(out, table.concat(valuesRow, ' '))


for _, item in ipairs(recipe.materials) do
if item.price then
prices:tag('li'):wikitext(currency(item.price)):done()
else
prices:tag('li'):wikitext('Unknown'):done()
end
end
end


--table.insert(out, '| ' .. recipe .. ' || ' .. professionLevel .. ' || ' .. value .. ' || ' .. usesItemStr .. ' || ' .. shopBuyPriceStr)
end
end


return out
table.insert(out, '|}')
return table.concat(out, '\n')
end
end



Latest revision as of 19:16, 28 December 2024

Module documentation
This documentation is transcluded from Module:Products/doc. [edit] [history] [purge]
This module does not have any documentation. Please consider adding documentation at Module:Products/doc. [edit]
Module:Products's function main is invoked by Template:Products.
Module:Products requires Module:Array.
Module:Products requires Module:Currency.
Module:Products requires Module:Mw.html extension.
Module:Products requires Module:Purge.
Module:Products requires Module:Yesno.

require('Module:Mw.html extension')
local Array = require('Module:Array')
local currency = require('Module:Currency').parse
local yesno = require('Module:Yesno')
local purge = require('Module:Purge')._purge

local p = {}

function p.main(frame)
	return p._main(frame:getParent().args)
end

local function recipe_sort(recipe_a, recipe_b)
	--if one is nil but not both, put nil levels after known levels
	if (recipe_a.level == nil) ~= (recipe_b.level == nil) then
		return recipe_b.level == nil
	end
	
	-- if both are nil, sort by name
	if recipe_a.level == nil then
		return recipe_a.output[1].name < recipe_b.output[1].name
	end
	
	-- if neither is nil, sort first by level
	if recipe_a.level ~= recipe_b.level then
		return recipe_a.level < recipe_b.level
	end

	-- if neither is nil and levels are the same, sort by name
	return recipe_a.output[1].name < recipe_b.output[1].name
end

function p._main(args)
	args = args or {}
	local item = args[1] or mw.title.getCurrentTitle().text
	local showPrices = yesno(args.showPrices)
	local showValues = yesno(args.showValues)
	local limit = tonumber(args.limit or 0) or 0
	if limit <= 0 then
		limit = 500
	end
	
	-- Query for data
	local smw_data = mw.smw.ask{
		'[[Uses item::' .. item .. ']] OR [[Activity input::' .. item .. ']] OR [[Activity container::' .. item .. ']]',
		'?Recipe JSON',
		'?Activity JSON',
		showValues and '?Value',
		limit = limit
	}
	if not smw_data then
		return ":''No products found. To force an update, click "
				..purge('dml-'..mw.uri.anchorEncode(item), 'here', 'span')
				..".''[[Category:Empty products lists]]"
	end

	-- Create a list of all recipes that use this item
	local recipes = {}
	for _, product in ipairs(smw_data) do
		-- this part will need to be addressed if a page has both a recipe and an activity
		local jsons = product['Recipe JSON'] or product['Activity JSON'] 
		if type(jsons) == 'string' then
			jsons = { jsons }
		end
		for _, json in ipairs(jsons) do
			local json = mw.text.jsonDecode(json)
			json.Value = product.Value
			-- Filter out when this item isn't actually used (Will happen on pages with multiple recipes)
			if Array.any(json.materials, function(mat)
				return mat.name == item
			end) then
				table.insert(recipes, json)
			end
		end
	end

	-- Sort list of recipes by the level of the recipe (cross-profession)
	table.sort(recipes, recipe_sort)

	-- if recipe is passive, want per hour
	for _, recipe in ipairs(recipes) do
		recipe.recipePerHour = recipe.duration and math.floor(3600/recipe.duration)
		-- replace quantities with per-hour quantities
--		if recipe.passive then
			for _,item in ipairs(recipe.output) do
				item.displayQuantity = (item.quantity and recipe.recipePerHour and item.quantity * recipe.recipePerHour) or ''
			end
			for _,item in ipairs(recipe.materials) do
				item.displayQuantity = (item.quantity and recipe.recipePerHour and item.quantity * recipe.recipePerHour) or ''
			end
--		end
	end
	
	-- Calculate shop prices
	if showPrices then
		local price_cache = {}
		for _, recipe in ipairs(recipes) do
			for _, item in ipairs(recipe.materials) do
				-- Extract item name and quantity from the "item,#" format

				-- Query for the shop buy price of the item
				local shopPriceResult = price_cache[item.name] or mw.smw.ask{
					'[[Sold item::' .. item.name .. ']]',
					'?Shop buy price'
				} or {}
				price_cache[item.name] = shopPriceResult
				local shopPrice

				if shopPriceResult[1] then
					shopPrice = tonumber(shopPriceResult[1]['Shop buy price'] or 0) or 0
				end

				-- Update the product with the total price
				if shopPrice ~= nil then
					item.price = shopPrice * item.quantity
				end
			end
		end
	end

	-- Create table
	local out = mw.html.create('table')
		:addClass('wikitable align-right-1 sortable')
		:tag('tr')
			:tag('th')
				:attr{ colspan = '3' }
				:wikitext('Product')
			:done()
			:tag('th'):wikitext('Level'):done()
			:IF(showValues)
				:tag('th'):wikitext('Value'):done()
			:END()
			:tag('th'):wikitext('Inputs'):done()
			:IF(showPrices)
				:tag('th'):wikitext('Price'):done()
			:END()
		:done()

	for _, recipe in ipairs(recipes) do
		local row = out:tag('tr')
			:tag('td')
				:css{ ['border-right'] = '0', ['padding-right'] = '0' }
				:attr{ ['data-sort-value'] = recipe.output[1].name }
				:IF(recipe.passive)
					:wikitext(recipe.output[1].displayQuantity .. ' (/hr) &times;')
				:ELSE()
					:wikitext(recipe.output[1].quantity .. ' &times;')
				:END()
			:done()
			:tag('td')
				:addClass('plinkt-image no-border')
				:css{ ['border-left'] = '0', ['padding-left'] = '0' }
				:wikitext('[[File:' .. recipe.output[1].name .. '.png|link=' .. recipe.output[1].name .. '|30px]]')
			:done()
			:tag('td')
				:addClass('plinkt-link no-border')
				:wikitext('[[' .. recipe.output[1].name .. ']]')
			:done()
			:tag('td')
				:IF(recipe.profession)
					:wikitext(('[[File:%s small icon.png|15px|link=%s]] %s'):format(recipe.profession, recipe.profession, recipe.level or 'Unknown'))
				:ELSE()
					:wikitext(('[[FileUnknown profession small icon.png|15px|link=Professions]] %s'):format(recipe.level or 'Unknown'))
				:END()
			:done()

		if showValues then
			if recipe.Value then
				row:tag('td')
					:wikitext(currency(recipe.Value))
				:done()
			else
				row:tag('td')
					:attr{ ['data-sort-value'] = '' }
					:wikitext('Unknown')
				:done()
			end
		end

		local ingredients = row:tag('td')
			:attr{ ['data-sort-value'] = table.concat(Array.map(recipe.materials, function(item) return item.name end), '\0') }
			:tag('ul')
				:css{ ['list-style'] = 'none', ['margin'] = '0', ['padding-left'] = '0' }

		for _, item in ipairs(recipe.materials) do
			ingredients:tag('li')
				:IF(recipe.passive)
					:wikitext(('%s (/hr) &times; [[File:%s.png|link=%s|18px]] [[%s]]'):format(item.displayQuantity, item.name, item.name, item.name))
				:ELSE()
					:wikitext(('%s &times; [[File:%s.png|link=%s|18px]] [[%s]]'):format(item.quantity, item.name, item.name, item.name))
				:END()
			:done()
		end

		if showPrices then
			local prices = row:tag('td')
				:tag('ul')
					:css{ ['list-style'] = 'none', ['margin'] = '0', ['padding-left'] = '0' }

			for _, item in ipairs(recipe.materials) do
				if item.price then
					prices:tag('li'):wikitext(currency(item.price)):done()
				else
					prices:tag('li'):wikitext('Unknown'):done()
				end
			end
		end

	end

	return out
end

return p