Modulo:Dipartimenti interessati

Da Wikiversità, l'apprendimento libero.

--[[
* Modulo che implementa il template Progetti interessati.
*
* Il modulo è stato importato da:
* https://it.wikipedia.org/w/index.php?title=Modulo:Progetti_interessati&oldid=79441323
]]--

require('Modulo:No globals')

local getArgs = require('Modulo:Arguments').getArgs

-- Configurazione
local cfg = mw.loadData('Modulo:Progetti interessati/Configurazione')

-- Variabili globali
local gradeParams = { 'accuratezza', 'scrittura', 'fonti', 'immagini' }
local validGrades = { a = true, b = true, c = true, d = true, e = true }

-------------------------------------------------------------------------------
--                             Funzioni di utilità
-------------------------------------------------------------------------------

-- Wrapper di mw.title.exists, verifica sia che name sia valido, sia che esista
local function titleExists(name)
	local title = mw.title.new(name)
	return title and title.exists
end

local function lowestGrade(args)
	local t = { args.accuratezza, args.scrittura, args.fonti, args.immagini }
	table.sort(t)
	return t[4]
end

local function parseArgs(args)
	local errcat = {}
	local projects = {}

	-- controllo valutazioni
	for _, param in ipairs(gradeParams) do
		if args[param] and not validGrades[args[param]] then
			if args[param] ~= 'nc' then
				table.insert(errcat, '[[Categoria:Pagine con template Progetti interessati con valutazione invalida]]')
			end
			args[param] = nil
		end
	end
	args.data = args.data and args.data:lower() or nil

	-- popola la tabella projects
	if args.progetto then
		for _, param in ipairs({ 'progetto', 'progetto2', 'progetto3', 'progetto4' }) do
			if args[param] then
				local name = cfg.alias[args[param] and args[param]:lower()] or
							 mw.language.getContentLanguage():ucfirst(args[param])
				if titleExists('Progetto:' .. name) then
					table.insert(projects, {
						name = name,
						subpage = mw.title.new('Progetto:' .. name).subpageText,
						monitoraggio = titleExists(string.format('Progetto:%s/Monitoraggio voci', name))
					})
				else
					table.insert(errcat, '[[Categoria:Pagine con template Progetti interessati con progetto non esistente]]')
				end
			end
		end
	else
		-- almeno un progetto deve essere specificato
		table.insert(errcat, '[[Categoria:Errori di compilazione del template Dipartimenti interessati]]')
	end

	return args, projects, errcat
end

local function getLabelGrade(value)
	local codeStyle = {
		['font-weight'] = 'bold',
		['font-size'] = '155%',
		['padding-left'] = '.2em',
		['padding-right'] = '.2em',
		border = '1px solid lightsteelblue',
		background = cfg.colors[value] or 'white'
	}
	return mw.html.create('code')
		:css(codeStyle)
		:wikitext(value and value:upper() or '<small>nc</small>')
end

local function hasMonitoraggio(projects)
	local ret = false
	for _, project in ipairs(projects) do
		if project.monitoraggio then
			ret = true
			break
		end
	end
	return ret
end

-------------------------------------------------------------------------------
--                             Monitoraggio
-------------------------------------------------------------------------------

local function getLivello(args)
	local ret

	-- è presente accuratezza
	if args.accuratezza then
		if not args.scrittura then
			ret = '0.4'
		elseif not args.fonti then
			ret = '0.3'
		elseif not args.immagini then
			ret = '0.2'
		else
			-- sono presenti tutti e quattro i parametri di valutazione
			if args.accuratezza == 'e' then
				ret = 'BOZZA'
			elseif args.scrittura == 'e' then
				ret = 'W'
			elseif args.fonti == 'e' then
				ret = 'F'
			elseif args.immagini == 'e' then
				ret = 'IMMAGINI'
			else
				local values = { a = 4, b = 3, c = 2, d = 1 }
				ret = tostring(values[lowestGrade(args)])
			end
		end
	-- manca accuratezza
	else
		if args.scrittura or args.fonti or args.immagini then
			ret = '0.5'
		else
			ret = nil
		end
	end

	return ret
end

local function getCategories(livello, args, projects)
	local ret = {}
	local cat

	local suffix = livello and cfg.livello[livello].cat or 'non compilate'

	-- per la "Situazione generale" di [[Progetto:Qualità/Monitoraggio voci/Tabella]]
	cat = string.format('[[Categoria:Voci monitorate - %s]]', suffix)
	table.insert(ret, cat)

	for _, project in ipairs(projects) do
		if project.monitoraggio then
			cat = string.format('[[Categoria:Voci monitorate Progetto %s]]', project.name)
			table.insert(ret, cat)
		end
	end

	for _, gradeParam in ipairs(gradeParams) do
		-- per la "Situazione monitoraggio per parametro" di [[Progetto:Qualità/Monitoraggio voci/Tabella]]
		cat = string.format('[[Categoria:Voci monitorate - %s %s]]',
							gradeParam, (args[gradeParam] or 'nc'):upper())
		table.insert(ret, cat)

		-- categorie per il [[template:Tabella monitoraggio]]
		for _, project in ipairs(projects) do
			if project.monitoraggio then
				cat = string.format('Categoria:Progetto:%s/Tabella monitoraggio automatico - %s %s',
									project.name, gradeParam, args[gradeParam] or 'nc')
				if titleExists(cat) then
					table.insert(ret, '[[' .. cat .. ']]')
				end
			end
		end
	end

	-- categorie per il [[template:Tabella monitoraggio]]
	for _, project in ipairs(projects) do
		if project.monitoraggio then
			cat = string.format('Categoria:Voci monitorate Progetto %s - %s',
								project.name, suffix)
			if titleExists(cat) then
				table.insert(ret, '[[' .. cat .. ']]')
			end
		end
	end

	-- per la "Situazione monitoraggio per mese" di [[Progetto:Qualità/Monitoraggio voci/Tabella]]
	if args.data then
		cat = string.format('Categoria:Voci monitorate - %s', args.data)
		if titleExists(cat) then
			table.insert(ret, '[[' .. cat .. ']]')
		else
			table.insert(ret, '[[Categoria:Errori di compilazione del template Dipartimenti interessati]]')
		end
	else
		table.insert(ret, '[[Categoria:Voci monitorate - non datate]]')
	end

	return ret
end

------------------------------------------------------------------------------
--                           classe ProjectsTable
-------------------------------------------------------------------------------

local ProjectsTable = {}

function ProjectsTable:new(projects)
	local self = {}
	setmetatable(self, { __index = ProjectsTable })
	self.projects = projects
	return self
end

function ProjectsTable:getHTML()
	local tableStyle = {
		margin = '5px 10%',
		width = '80%',
		border = '1px solid #a7d7f9',
		['background-color'] = cfg.bgcolor,
	}
	local text = (#self.projects > 1 and cfg.progetti.text2 or cfg.progetti.text) ..
				 (hasMonitoraggio(self.projects) and
					(#self.projects > 1 and cfg.progetti.text4 or cfg.progetti.text3) or '') .. '</p>'
	local tableNode = mw.html.create('table'):css(tableStyle)
	tableNode
		:tag('tr')
			:tag('td')
				:css('width', '52px')
				:css('text-align', 'center')
				:wikitext(cfg.progetti.icon)
				:done()
			:tag('td')
				:wikitext(mw.getCurrentFrame():preprocess(text))
				:done()
		:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				:node(self:getNodeProjects())
				:done()

	return tostring(tableNode)
end

function ProjectsTable:getNodeProjects()
	local tableStyle = {
		width = '100%',
		['border-collapse'] = 'collapse'
	}
	local tableNode = mw.html.create('table'):css(tableStyle)

	-- progetti
	for _, project in ipairs(self.projects) do
		tableNode:tag('tr')
			:css('background-color', 'white')
			:css('border', 'thin solid #D8D8D8')
			:tag('td')
				:css('width', '28px')
				:css('text-align', 'center')
				:wikitext(self:getIconProject(project))
				:done()
			:tag('td')
				:css('width', '1px')
				:css('white-space', 'nowrap')
				:wikitext(string.format("'''[[Progetto:%s|%s]]'''", project.name, project.subpage))
				:done()
			:tag('td')
				:wikitext('<div class="plainlinks" style="padding-left: 5px">' .. self:getWlinkProject(project) .. '</div>')
				:done()
	end

	return tableNode
end

function ProjectsTable:getIconProject(project)
	local icon = mw.getCurrentFrame():expandTemplate {
		title = 'Icona argomento',
		args = { project.subpage }
	}
	icon = icon == '' and 'Crystal Clear app ksirtet.png' or icon

	return string.format('[[File:%s|25x40px]]', icon)
end

function ProjectsTable:getWlinkProject(project)
	local links = {}
	local fmtIcon = '[[File:Rpb dialog icon.svg|23x15px|bar di progetto|link=Discussioni progetto:%s]]'
	local fmtIcon2 = '[[File:VisualEditor - Icon - Search-big.svg|20x20px|monitoraggio delle voci|link=Progetto:%s/Monitoraggio voci]]'

	table.insert(links, string.format(fmtIcon, project.name))
	table.insert(links, string.format('[[Discussioni progetto:%s|bar di progetto]]', project.name))
	-- link monitoraggio opzionale
	if project.monitoraggio then
		table.insert(links, string.format(fmtIcon2, project.name))
		table.insert(links, string.format('[[Progetto:%s/Monitoraggio voci|monitoraggio delle voci]]', project.name))
	end

	return table.concat(links, ' ')
end

-------------------------------------------------------------------------------
--                           classe PreMonitoraggioTable
-------------------------------------------------------------------------------

local PreMonitoraggioTable = {}

function PreMonitoraggioTable:new()
	local self = {}
	setmetatable(self, { __index = PreMonitoraggioTable })
	return self
end

function PreMonitoraggioTable:getHTML()
	local tableStyle = {
		margin = '5px 10% 0 10%',
		width = '80%',
		border = '1px solid #a7d7f9',
		['background-color'] = cfg.bgcolor,
	}
	local tableNode = mw.html.create('table'):css(tableStyle)
	tableNode
		:tag('tr')
			:tag('td')
				:css('width', '52px')
				:css('text-align', 'center')
				:wikitext(cfg.monitoraggio.icon)
				:done()
			:tag('td')
				:wikitext(cfg.monitoraggio.text)
				:done()

	return tostring(tableNode)
end

-------------------------------------------------------------------------------
--                           classe MonitoraggioTable
-------------------------------------------------------------------------------

local MonitoraggioTable = {}

function MonitoraggioTable:new(livello, args)
	local self = {}
	setmetatable(self, { __index = MonitoraggioTable })
	self.livello = livello
	self.args = args
	return self
end

function MonitoraggioTable:getHTML()
	local tableStyle = {
		margin = '0 10% 5px 10%',
		width = '80%',
		border = '1px solid #a7d7f9',
		['background-color'] = cfg.bgcolor,
		['border-top'] = '0',
	}
	local tableNode = mw.html.create('table')
	tableNode
		:addClass('mw-collapsible mw-collapsed')
		:css(tableStyle)

	-- livello	
	tableNode
		:node(self:getNodeLivello())
	-- valutazioni
	tableNode
		:tag('tr')
			:tag('td')
				:attr('colspan', '3')
				:css('background-color', 'none')
				:css('font-size', '95%')
				:tag('table')
					:css('width', '100%')
					:css('border-collapse', 'collapse')
					:node(self:getNodeGrade('accuratezza'))
					:node(self:getNodeGrade('scrittura'))
					:node(self:getNodeGrade('fonti'))
					:node(self:getNodeGrade('immagini'))
	-- note
	if self.args.note then
		tableNode
			:tag('tr')
				:tag('td')
					:css('padding-left', '0.2em')
					:attr('colspan', '3')
					:wikitext(string.format("'''Note:''' %s%s",
							  self.args.note:match('^[#*]') and '\n' or '',
							  self.args.note))
	end

	return tostring(tableNode)
end

function MonitoraggioTable:getNodeLivello()
	local url = mw.title.getCurrentTitle():fullUrl( { action = 'edit' } )
	return mw.html.create('tr')
		:tag('td')
			:css('background-color', 'none')
			:css('width', '90px')
			:node(self:getWlinkLivello())
			:done()
		:tag('td')
			:wikitext(self.livello and cfg.livello[self.livello].msg .. ' ' .. self:getTextData() or
				'<div class="plainlinks">La voce non è stata ancora valutata, [' .. url .. ' fallo ora]!</div>')
			:done()
		:tag('td')
			:css('width', '80px')
			:wikitext('')
			:done()
end

function MonitoraggioTable:getWlinkLivello()
	local codeStyle = {
		['font-weight'] = 'bold',
		['font-size'] = '125%',
		['padding-left'] = '.4em',
		['padding-right'] = '.4em',
		border = '1px solid lightsteelblue',
		background = (self.livello and cfg.livello[self.livello].color) and cfg.livello[self.livello].color or 'white',
		color  = 'blue'
	}
	local codeNode = mw.html.create('code')
	local text
	if self.livello and cfg.livello[self.livello].label then
		text = string.format('[[:Categoria:Voci monitorate - %s|%s]]',
							 cfg.livello[self.livello].cat, cfg.livello[self.livello].label)
	elseif not self.livello then
		text = '[[:Categoria:Voci monitorate - non compilate|NC]]'
	end
	if text then
		codeNode:css(codeStyle)
	else
		text = '[[File:Symbol stub class.svg|25px|center]]'
	end
	codeNode:wikitext(text)

	return codeNode
end

function MonitoraggioTable:getTextData()
	local ret
	if self.args.data then
		local cat = string.format('Categoria:Voci monitorate - %s', self.args.data)
		if titleExists(cat) then
			ret = string.format('<small>(%s)</small>', self.args.data)
		end
	end
	return ret or "(<span style=\"color:red;\"><small>'''''mese e anno'''''</small></span>)"
end

function MonitoraggioTable:getNodeGrade(param)
	return  mw.html.create('tr')
		:css('background-color', 'white')
		:css('border', 'thin solid #D8D8D8')
		:tag('td')
			:css('width', '52px')
			:css('text-align', 'center')
			:node(getLabelGrade(self.args[param]))
			:done()
		:tag('td')
			:wikitext(cfg[param][self.args[param] or 'nc'] .. ' ' .. cfg[param].help)
			:done()
end

-------------------------------------------------------------------------------
--                                    API
-------------------------------------------------------------------------------

local p = {}

-- Per l'utilizzo da un altro modulo
function p._livello(args)
	return getLivello(parseArgs(args))	
end

-- Entry-point per {{#invoke:Progetti interessati|livello}}
function p.livello(frame)
	return p._livello(getArgs(frame))
end

-- Entry-point per {{#invoke:Progetti interessati|categorie}}
function p.categorie(frame)
	local args, projects = parseArgs(getArgs(frame))
	local livello = getLivello(args)	
	local categories = getCategories(livello, args, projects)
	return args.debug and ( table.concat(categories, '<br />'):gsub('%[%[', '[[:') ) .. '<br />' or
		   table.concat(categories)
end

-- Entry-point per {{Progetti interessati/classe}}
-- per retrocompatibilità con template che lo usavano
function p.classe(frame)
	local value = frame:getParent().args[1]
	return tostring(getLabelGrade(validGrades[value] and value or nil))
end

-- Entry-point per il template {{Progetti interessati}}
function p.main(frame)
	local args, projects, errcat = parseArgs(getArgs(frame, {parentOnly = true}))
	if hasMonitoraggio(projects) then
		local livello = getLivello(args)
		local categories = mw.title.getCurrentTitle().namespace == 1 and
					   	(table.concat(getCategories(livello, args, projects)) .. table.concat(errcat)) or ''
		return ProjectsTable:new(projects):getHTML() ..
			   PreMonitoraggioTable:new():getHTML() ..
			   MonitoraggioTable:new(livello, args):getHTML() ..
			   categories
	else
		return ProjectsTable:new(projects):getHTML() ..
			   table.concat(errcat)
	end
end

return p