Модуль:Объекты/lab

Материал из Справочника наблюдателя
Перейти к:навигация, поиск

(i)      Описание модуля[]

Документация отсутствует!


--[[
--]]
local getArgs = require('Module:Arguments').getArgs
local p = {}

local tab = {}

function p.Data (frame)
	
-- Разбор параметров
	local objT = mw.ustring.lower(v(frame.args['тип']))
	if objT == '' then
		objT = 'уик'
	end
	local outF = mw.ustring.lower(v (frame.args['формат']))
	if outF =='{{{1}}}---' then -- на самой странице. Проверяем качество таблицы
		local args = getArgs(frame)
		local report = ''
--		local numnam = ''
			
		for key,val in pairs (args) do
			if key then
				if type (key) == 'string' then
					if (key == 'тип') or (key == 'формат') or (key == 'url') then
					else
						report = report .. '<br />Некорректное значение параметра: «<code><nowiki>' .. key .. val .. '</nowiki></code>»'
					end
--[[ порядок отдачи не тот что надо
				else
					local mykey, myval = mw.ustring.match (val, '^([^:]+)%:[\t\r\n\f ]*(.*)$')
					if mykey then
						mykey = mw.text.trim (mykey)
						if (mykey == 'номер') or (mykey == 'наименование') then
							numnam = mw.text.trim (v(myval))
						end
					end
--]]					
				end
			end
		end
--		until not key
		if report ~= '' then
			return frame:preprocess ("<br />{{Box|type=serious|text='''Обнаружены ошибки в данных об объектах!'''" .. report 
				.. '|text-small=Скорее всего, необходимо заключить в двойные фигурные скобки содержащиеся в строке знаки равенства (уже расставленные скобки в этом сообщении об ошибке не показываются)}}')
		end
		
	
	end
		
	if (outF == '') or (outF =='{{{1}}}') then
		outF = ({['уик']='номер,округ,адрес,телефон,границы',
				['власти']='тип,наименование,адрес,телефон',
				}) [objT]
	end
	local url = mw.ustring.lower(v(frame.args['url']))

	tabInit ()

-- Формирование заголовков
	local result, objN = {}, 1
	local columns, geoTemplate
	
	if mw.ustring.sub(outF,1,5) ~= 'карта' then
		columns = mw.text.split (outF, '[\t\r\n\f ]*[,;][\t\r\n\f ]*')
	    local colStyle, colText, colName
	    local header = ''
    	for column = 1, #columns do
        	colName = columns[column]
        	if tab.headerText [colName] then
        	    colText = tab.headerText [colName]
            	colStyle = tab.headerStyle [colName]
    	    else
            	colText = '«'..v(colname)..'»'
	            colStyle = 'style="background-color:red;"'
        	end
	        header = header .. '<th ' .. colStyle .. '>' .. colText .. '</th>'
    	end
		result [1] = header
		objN = 2
	else
		if mw.ustring.sub(outF,-3) == 'kml' then
			geoTemplate = '{{ геокарта |'
		else
			geoTemplate = '{{ multimaps |'
		end
	end
	
-- Идем по объектам
--	local info 
--	local infoIdx = 1 -- номер выбираемого параметра (аргумента шаблона)
--	local debreport = ''
--	repeat
	local data = {}
	local dataYes
	for infoIdx, info in pairs (frame.args) do
--			info, infoIdx = frame.args [infoIdx], infoIdx+1;
			
--		debreport=debreport.. '(((' .. v(infoIdx) .. '|||' .. v (info) .. ')))'
		if info then
			info = mw.text.trim (info)
			if (info ~= '') and (info ~= '-') and (infoIdx ~= 'тип') and (infoIdx ~= 'формат') and (infoIdx ~= 'url') then
				local key, val = mw.ustring.match (info, '^([^:]+)%:[\t\r\n\f ]*(.*)$')
				key = mw.text.trim (v(key))
				if key ~= '' then
					val = mw.text.trim (val)
					if val ~= '' then
						data [key] = val
						dataYes = true
					end
				else
					return 'Некорректные данные «' .. info .. '», параметр ' .. infoIdx
				end
			elseif dataYes then
--	перерабатываем адреса
				if ne(data ['адрес']) then
					data ['адрес'] = addrSplit (data ['адрес'])
				end
				if ne(data ['адрес офиса']) then
					data ['адрес офиса'] = addrSplit (data ['адрес офиса'])
				end
			
				local res = ''
			
				if columns then		-- то есть не карта
					for column = 1, #columns do
						local colName = columns[column]
						local dataT, dataColumn = tab.dataType[colName], data[colName]
						if not dataT then
							if not dataColumn then
								dataColumn = ''
							end
						elseif type(dataT) == 'function' then
							dataColumn = dataT (dataColumn)
						else
							dataColumn = ''
						end
						res = res .. '<td ' .. v(tab.dataStyle[colName]) .. '>' .. dataColumn .. '</td>'
					end
					result[objN], objN  = res, objN+1
				else
-- карты. УИК
					if objT == 'уик' then
						local numb = mw.ustring.sub ('0000' .. normUIK (data['номер']),-4)
						result[objN] = geoTemplate .. 'УИК|' .. data['номер'] .. '|' .. data ['адрес'][1] .. '|' .. data ['адрес'][2] .. '|' .. data ['адрес'] [3] .. '|' .. data ['адрес'] [4] 
													.. '|/E/' .. string.sub (numb,1,1) .. '/uik' .. numb .. '-e.png}}'
						objN = objN +1
					else
						local tipus = v(data['тип'])
						local icon = tab.icoName [tipus]
						if icon then
							icon = '|/E/gov/' .. icon .. '-e.png'
						else
							icon = '|'
						end
						result[objN] = geoTemplate .. tipus .. '|' .. v (data['метка']) .. '|' .. data ['адрес'][1] .. '|' .. data ['адрес'][2] .. '|' .. data ['адрес'] [3] .. '|' .. data ['адрес'] [4] 
													.. icon .. '}}'
						objN = objN +1
					end	

				end
				data = {}
				dataYes = nil

----
			end
			
		end
				
	end
	
-- завершающие операции	
	
	
	
	
	
	if columns then
		if url ~= '' then
			url ='<caption class=plainlinks style="font-size:80%; line-height:110%; text-align:right;">' 
			.. 'Сведения об объектах вносятся '
			.. ' [{{fullurl:{{{url|{{FULLPAGENAME}}/{{{тип|УИК}}}}}}|action=edit}} здесь].</caption>'
		end
		return frame:preprocess ('<table  class="wikitable sortable">' .. url 
			.. '<tr>' .. table.concat (result, '</tr><tr>') .. '</tr></table>' )
	else
		return frame:preprocess (table.concat (result))
	end
	
end



--[[
function array2table (txt)
	local res = {}
	for line = 2, #txt-1 do
		local key,val = mw.ustring.match (txt[line], '^([^\n%=]+)%=(.*)$', 1);
		
		if key then
--			mw.log (txt[line],'<<'..type (key) ..'<<'..val..'>>');
--			mw.log (txt[line],'<<'..mw.ustring.trim(''..key)..'<<');
--			mw.log ('(('..mw.ustring.trim(val)..'>>');
			res[mw.text.trim(key)]=mw.text.trim(val)
			mw.log (key .. '=>' .. val)
		end
	end
	mw.log (tostring (res).. '::' .. res ['номер']) --, '///'))
	return res
end
--]]
function addrSplit (addr)
	local a = mw.text.split (addr..'::', '[\t\r\n\f ]*:[\t\r\n\f ]*')
	local c = {'', ''}
	if ne(a[3]) then
		c = mw.text.split (a[3]..',', '[\t\r\n\f ]*,[\t\r\n\f ]*')
	end
	return { a[1], a[2], c[1], c[2] }
end

function e (t)
	return (t or '') == ''
end

function ne (t)
	return (t or '') ~= ''
end

function v (t)
	return (t or '')
end

function normUIK (numbUIK)
	return ( string.gsub (numbUIK, '^0*([0-9]+)[%-/]?([0-9]*)$','%1%2'))..''
end

function tabInit ()
	tab.headerStyle = {
		['номер']          = 'style="width:4en;"';
		['округ']          = 'style="width:3en;"';
		['коиб']           = 'style="width:2en;"';
		['временный']      = 'style="width:2en;"';
		['численность']    = 'style="width:6en;"';
		['прг']            = '';
		['адрес']      	   = 'class=unsortable';
		['телефон']        = 'class=unsortable';
		['адрес офиса']    = 'class=unsortable';
		['телефон офиса']  = 'class=unsortable';
		['границы']        = 'class=unsortable';
		['номер0412']      = 'style="width:4en; font-size:75%; line-height:80%"';
		['итог0412']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['явка0412']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['дом0412']        = 'style="width:4en; font-size:75%; line-height:80%"';
		['числ0412']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['номер0403']      = 'style="width:4en; font-size:75%; line-height:80%"';
		['итог0403']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['явка0403']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['дом0403']        = 'style="width:4en; font-size:75%; line-height:80%"';
		['числ0403']       = 'style="width:4en; font-size:75%; line-height:80%"';
		['галерея']        = 'style="width:2en;"';
		['тип']            = 'style="width:3en; border-right:0px;"';
		['наименование']   = '';
		['метка']          = '';
		['сайты']          = 'class=unsortable';
		['примечание']     = 'class=unsortable';
	}
	 
	tab.headerText = {
		['номер']          = 'УИK';
		['округ']          = '<small>округ</small>';
		['коиб']           = '<small>KОИБ</small>';
		['временный']      = '<small>{{подсказка|вр.|участок, созданный для временно пребывающих}}</small>';
		['численность']    = 'изб.';
		['прг']            = '{{подсказка|ПPГ|число членов комиссии с правом решающего голоса}}';
		['адрес']          = 'адрес помещения';
		['телефон']        = 'телефон';
		['адрес офиса']    = 'адрес офиса';
		['телефон офиса']  = 'тел. офиса';
		['границы']        = 'границы избирательного участка';
		['номер0412']      = '04.12<br />№ УИК';
		['итог0412']       = '04.12<br />за ЕР';
		['явка0412']       = '04.12<br />явка';
		['дом0412']        = '04.12<br />дома';
		['числ0412']       = '04.12<br />число';
		['номер0403']      = '04.03<br />№ УИК';
		['итог0403']       = '04.03<br />Путин';
		['явка0403']       = '04.03<br />явка';
		['дом0403']        = '04.03<br />дома';
		['числ0403']       = '04.03<br />число';
		['галерея']        = '<small>фото</small>';
		['тип']            = ' ';
		['наименование']   = 'наименование органа';
		['метка']          = 'сокр.';
		['сайты']          = 'сайт';
		['примечание']     = 'примечание';
	}
	tab.dataStyle = {
		['номер']          = 'class=plainlinks style="text-align:center; font-weight:bold; background-color:#f2f2f2;"';
		['округ']          = 'style="text-align:center; "';
		['КОИБ']           = 'style="text-align:center; "';
		['временный']      = 'style="text-align:center; "';
		['численность']    = 'style="text-align:right; background-color:Beige;"';
		['ПРГ']            = 'style="text-align:center; "';
		['адрес']          = 'style="font-size:92%; line-height:95%;"';
		['телефон']        = '';
		['адрес офиса']    = 'style="font-size:92%; line-height:95%;"';
		['телефон офиса']  = '';
		['границы']        = 'style="font-size:83%; line-height:95%;"';
		['номер0412']      = 'style="text-align:center; font-weight:bold; background-color:#f2f2f2;"';
		['итог0412']       = 'style="text-align:right; "';
		['явка0412']       = 'style="text-align:right; background-color:Ivory; "';
		['дом0412']        = 'style="text-align:right; background-color:Honeydew; "';
		['числ0412']       = 'style="text-align:right;  background-color:Beige;"';
		['номер0403']      = 'style="text-align:center; font-weight:bold; background-color:#f2f2f2;"';
		['итог0403']       = 'style="text-align:right; "';
		['явка0403']       = 'style="text-align:right; background-color:Ivory; "';
		['дом0403']        = 'style="text-align:right; background-color:Honeydew; "';
		['числ0403']       = 'style="text-align:right;  background-color:Beige;"';
		['галерея']        = '';
		['тип']            = 'style="border-right:0px;"';
		['наименование']   = '';
		['метка']          = '';
		['сайты']          = 'style="font-size:83%; line-height:95%;"';
		['примечание']     = 'style="font-size:83%; line-height:95%;"';
	}
	tab.icoName = {
		['ИК']          = 'ik';
		['ТИК']         = 'tik';
		['ИКМО']        = 'ikmo';
		['полиция']     = 'ovd';
		['прокуратура'] = 'proc';
		['СК']          = 'ck';
		['суд']         = 'sud2';
		['адм']         = 'adm2';
	}	

	
	tab.dataType = {}
	tab.dataType['галерея']=function (s)
		if (not s) or (s == '') then
			return ''
		else
			return '[[Файл:Фотофайлы.png|link=' .. s .. ']]'
		end
	end

	tab.dataType['номер']=function (s)
		if (not s) or (s == '') then
			return ''
		else
			return '[https://www.wikiuiki.org/ik/{{#var:RegCode}}-uik-' .. normUIK (s) .. ' ' .. s .. ']'
		end
	end

	tab.dataType['адрес']=function (s)
		if (not s) or (s == '') then
			return ''
		else
			return '{{геоадрес|' .. table.concat(s,'|') .. '}}';
		end
	end
end		



return p