Módulo:ExchangeDefault

De RuneScape Wiki
Ir para: navegação, pesquisa

A documentação para este módulo pode ser criada em Módulo:ExchangeDefault/doc

-- <pre>
-- Default view for {{ExchangeItem}} for use on Exchange ns pages
--
-- Use of this via #invoke is deprecated and will eventually be removed
-- This is intended for use by [[Module:Exchange]]
--

local p = {}

-- imports
local excgdata = require( 'Module:ExchangeData' )._main
local round = require( 'Module:Number' )._round
local timeago = require( 'Module:TimeAgo' )._ago
local yesno = require( 'Module:Yesno' )

function p.main( item )
    local frame = mw.getCurrentFrame()
    local lang = mw.language.getContentLanguage()
    local title = mw.title.getCurrentTitle()
    local data  = mw.loadData( 'Módulo:Mercado/' .. item )

    -- set variables here if possible to keep table building easier to follow
    local rowspan = 8
    local volDate = data.volumeDate or lang:formatDate( 'c' )
    local dateDiffZ = lang:formatDate( 'z' ) - lang:formatDate( 'z', volDate )
    local dateDiffY = lang:formatDate( 'Y' ) - lang:formatDate( 'Y', volDate )
    local price = data.price and lang:formatNum( data.price ) or '<i>Sem informação</i>'
    local priceDiff = (data.price or 0) - (data.last or 0)
    local priceDiffF = lang:formatNum(priceDiff) or '<i>Sem informação</i>'
    local priceDiffPerc = ''
    local priceDiffClass = 'unchanged' --todo neutral
    local priceDiffSlide = '' --todo neutral
    local priceDiffIcon = 'Unchanged' --todo neutral
    local itemIcon = data.icon or (( data.item or 'Moedas 1000') .. '.png')
    local date = '<i>Sem informação</i>'
    local lowAlchMultiplier = 0.4
    local highAlchMultiplier = 0.6
    local rawLowAlch = -1
    local rawHighAlch = -1
    local lowAlch = '<i>-</i>'
    local highAlch = '<i>-</i>'
    local memsIcon = ''
    local usage = ''

    if data.volume and ( dateDiffZ + 365 * dateDiffY ) <= 7 then
        rowspan = 10
    end

    if data.date then
        date = lang:formatDate( 'j F Y, H:i "(UTC)"', data.date )
    end
    
    if data.alchable == nil or yesno( data.alchable ) then
        if data.value then
	    	if data.alchmultiplier then
	    		highAlchMultiplier = data.alchmultiplier
	    		lowAlchMultiplier = highAlchMultiplier * 2/3
	    	end
            rawLowAlch = math.floor( data.value * lowAlchMultiplier )
            rawHighAlch = math.floor( data.value * highAlchMultiplier )
            lowAlch = lang:formatNum( rawLowAlch )
            highAlch = lang:formatNum( rawHighAlch )
        else
            lowAlch, highAlch = '<i>Sem informação</i>', '<i>Sem informação</i>'
        end
    end

    if data.members ~= nil then
        if data.members then
            memsIcon = 'Membros'
        else
            memsIcon = 'Gratuitos'
        end
    end
    
    if priceDiff > 0 then
    	priceDiffClass = 'positive'
    	priceDiffSlide = 'slide-up'
    	priceDiffIcon = 'Up'
    elseif priceDiff < 0 then
    	priceDiffClass = 'negative'
    	priceDiffSlide = 'slide-down'
    	priceDiffIcon = 'Down'
    end
    
    if data.last and data.last > 0 then
    	priceDiffPerc = round(priceDiff / data.last * 100, 2) .. '%'
    end
    if priceDiff >= 0 then
    	priceDiffF = '+'..priceDiffF
    	priceDiffPerc = '+'..priceDiffPerc
    end
    
    -- workaround so we can use `table.concat`
    usage = {}

    for k, v in ipairs( data.usage ) do
        usage[k] = v
    end

    if #usage == 0 then
    	usage = "\n* ''Nenhum''"
	else
        usage = '\n* [[' .. table.concat( usage, ']]\n* [[' ) .. ']]'
    end
    
    local noErr, chartdata = pcall( excgdata, { item }, true )
    
    if not noErr then
        chartdata = 'Gráfico indisponível'
    end

    -- build table
    local div = mw.html.create('div')
    	:addClass('gemw-container')
    
    	--header
    div	:tag('div')
    		:addClass('gemw-header')
    		:addClass(priceDiffClass)
    		:tag('div')
    			:addClass('gemw-section-left')
                :tag('p')
                    :addClass('gemw-image inventory-image')
                    :wikitext('[[Arquivo:'..itemIcon..'|link='..data.item..']]')
                    :done()
    			:tag('p')
    				:addClass('gemw-name')
    				:wikitext('[['..data.item..']]')
    				:done()
    			:tag('p')
    				:addClass('gemw-examine')
    				:wikitext(data.examine or '')
    				:done()
    			:tag('div')
    				:tag('span')
    					:addClass('gemw-price')
    					:addClass(priceDiffSlide)
    					:attr('id', 'GEPrice')
    					:wikitext(price)
    					:done()
    				:tag('span')
    					:addClass('gemw-change')
    					:addClass(priceDiffSlide..'-2')
    					:wikitext(priceDiffF)
    					:wikitext(' ')
    					:wikitext(priceDiffPerc)
    					:wikitext(' [[Arquivo:'..priceDiffIcon..'.svg|12px|link=]]')
    					:done()
    				:done()
    			:done()
    		:tag('div')	
    			:addClass('gemw-section-right')
    			:tag('p')
    				:addClass('gemw-updated')
    				:attr('data-date', date) -- used by [[MediaWiki:Gadget-gemwupdate.js]]
    				:wikitext('Atualizado há ')
    				:tag('span')
    					:addClass('gemw-time')
    					:wikitext(timeago{data.date, purge='yes', purgeText='refresh'})
    					:done()
    				:tag('br'):done()
    				:wikitext(' em ')
    				:wikitext(date)
    				:done()
    			:tag('div')
    				:addClass('gemw-button-wrapper gemw-update-price')
    				:attr('id', 'gemw_guide')
    				:wikitext('')
    				:done()
    			:done()	
    		:done() --close header
    
    -- body		
    local dlTag = div	:tag('div')
    		:addClass('gemw-body')	
    		:tag('div')
    			:addClass('gemw-section-left')
    			:tag('dl')
    			
    dlTag			:tag('div')
    					:addClass('gemw-property gemw-members')
    					:tag('dt')
    						:wikitext('Estado')
    						:done()
    					:tag('dd')
    						:wikitext(memsIcon)
    						:done()
    					:done()
    				:tag('div')
    					:addClass('gemw-property gemw-limit')
    					:tag('dt')
    						:wikitext('[[Mercado Geral#Trade restrictions|Limite de compra]]')
    						:done()
    					:tag('dd')
    						:wikitext(data.limit and lang:formatNum( data.limit ) or '<i>Sem informação</i>' )
    						:done()
    					:done()
    				:tag('div')
    					:addClass('gemw-property gemw-id')
    					:tag('dt')
    						:wikitext('Item ID')
    						:done()
    					:tag('dd')
    						:wikitext(data.itemId or '<i>Sem informação</i>')
    						:done()
    					:done()
    				:tag('div')
    					:addClass('gemw-property gemw-highalch')
    					:tag('dt')
    						:wikitext('[[Alquimia avançada]]')
    						:done()
    					:tag('dd')
    						:wikitext(highAlch)
    						:done()
    					:done()
    				:tag('div')
    					:addClass('gemw-property gemw-lowalch')
    					:tag('dt')
    						:wikitext('[[Alquimia básica]]')
    						:done()
    					:tag('dd')
    						:wikitext(lowAlch)
    						:done()
    					:done()
    				:tag('div')
    					:addClass('gemw-property gemw-value')
    					:tag('dt')
    						:wikitext('[[Valor]]')
    						:done()
    					:tag('dd')
    						:wikitext(data.value and lang:formatNum( data.value ) or '<i>Sem informação</i>')
    						:done()
    					:done()
    				:done()
    			:tag('div')
    				:tag('p')
    					:addClass('gemw-links')
    					:wikitext('Links externos')
    					:done()
    				:tag('div')
    					:addClass('gemw-button secondary')
    					:wikitext('[http://services.runescape.com/m=itemdb_rs/l=3/viewitem.ws?obj=' .. data.itemId .. ' MG Oficial]')
    					:done()
    				:tag('div')
    					:addClass('gemw-button secondary')
    					:wikitext('[http://services.runescape.com/m=itemdb_rs/l=3/results.ws?query=' .. mw.uri.encode( item, 'QUERY' ) .. ' Objetos relacionados]')
    					:done()
    				:done()
    			:tag('div')
    				:tag('p')
    					:addClass('gemw-links')
    					:wikitext('Links do módulo')
    					:done()
    				:tag('div')
    					:addClass('gemw-button secondary')
    					:wikitext('[[Módulo:Mercado/' .. item .. '|Info do mercado]]')
    					:done()
    				:tag('div')
    					:addClass('gemw-button secondary')
    					:wikitext('[[Módulo:Mercado/' .. item .. '/Data|Histórico do preço]]')
    					:done()
    				:done()
    			:done()
    		:tag('div')
    			:addClass('gemw-section-right gemw-chart')
    			:wikitext(chartdata)
    			:done()

	if data.volume and ( dateDiffZ + 365 * dateDiffY ) <= 7 then
		dlTag:tag('div')
				:addClass('gemw-property gemw-volume')
				:tag('dt')
					:wikitext('volume na semana')
					:done()
				:tag('dd')
					:wikitext(lang:formatNum( 1000000 * data.volume ))
					:done()
	end

    div = tostring( div )

    -- categories
    local cats = ''
    local natPrice

    if title.nsText == 'Mercado' then
        cats = cats .. '[[Categoria:Mercado Geral]]'
                    .. '[[Categoria:Mercado Geral por data de atualização|*' .. lang:formatDate( 'c', data.date ) .. data.itemId .. ']]'

        if item ~= title.text then
            cats = cats .. '[[Categoria:Nomes do mercado que precisam de revificação]]'
        end

        -- have to preprocess this for it to work
        cats = cats .. frame:preprocess( '{{DEFAULTSORT:' .. data.item .. '}}' )

        if not data.itemId then
            cats = cats .. '[[Categoria:Objetos do Mercado sem ID]]'
        end

        if data.price and data.value and ( data.alchable == nil or yesno( data.alchable ) ) then
            if mw.ustring.lower( item ) == 'runa da natureza' then
                natPrice = data.price
            else
                natPrice = mw.loadData( 'Módulo:Mercado/Runa da natureza' ).price
            end

            if math.floor( ( data.value * 0.6 ) - data.price - natPrice ) > 0 then
                cats = cats .. '[[Categoria:Objetos de alquimia avançada com lucro]]'
            end

            if math.floor( ( data.value * 0.4 ) - data.price - natPrice ) > 0 then
                cats = cats .. '[[Category:Objetos de alquimia básica com lucro]]'
            end

            if math.floor( ( data.value * 0.3 ) - data.price ) > 0 then
                cats = cats .. '[[Categoria:Objetos de loja com lucro]]'
            end

        elseif not data.value then
            cats = cats .. '[[Categoria:Objetos do mercado sem valor]]'
        end

        -- this doesn't allow for the update time to be in the previous day but less than 24 hours
        -- if that's the case, then the page will end up in the 7 days category
        -- the same will happen for the other 2 categories too
        -- but it's not so noticeable given the already elapsed time
        local lastUpdate = ( lang:formatDate( 'z' ) - lang:formatDate( 'z', data.date ) + 365 * ( lang:formatDate( 'Y' ) - lang:formatDate( 'Y', data.date ) ) + 3 ) / 7
        lastUpdate = round( lastUpdate, 0 )
 
        if lastUpdate == 1 then
            cats = cats .. '[[Categoria:Precisa de preço atualizado/7 dias]]'
        elseif lastUpdate >= 2 and lastUpdate <= 4 then
            cats = cats .. '[[Categoria:Precisa de preço atualizado/28 dias]]'
        elseif lastUpdate > 4 then
            cats = cats .. '[[Categoria:Precisa de preço atualizado/29+ dias]]'
        end

        if not data.limit then
            cats = cats .. '[[Categoria:Objetos do mercado sem limite]]'
        end

        if not data.category then
            cats = cats .. '[[Categoria:Objetos do mercado sem categoria]]'
        end

        -- Error checking
        if not data.price or data.price < 1 then
            cats = cats .. '[[Categoria:Objetos do mercado sem preço]]'
        end
    end
    
    local smw_to_json_names = {
    	id = 'Exchange ID',
    	name = 'Exchange name',
    	limit = 'Exchange limit',
    	value = 'Exchange value',
    	isalchable = 'Exchange is alchable',
    	highalch = 'Exchange high alch',
    	lowalch = 'Exchange low alch',
    	info = 'Exchange module',
    	history = 'Exchange history module'
    }
    local smw_json = {}
    local smw_data_arr = {}
    smw_json.id = data.itemId
    smw_json.name = item
    smw_json.limit = data.limit
    smw_json.value = data.value
    smw_json.isalchable = data.alchable == nil or yesno( data.alchable )
    if smw_json.isalchable then
    	smw_json.highalch = rawHighAlch
    	smw_json.lowalch = rawLowAlch
    end
    smw_json.info = 'Módulo:Mercado/' .. data.item
    smw_json.history = 'Módulo:Mercado/' .. data.item .. '/Data'
    
    for k,v in pairs(smw_to_json_names) do
    	smw_data_arr[v] = smw_json[k]
    end
    local smwJsonGood, smwJsonEncoded = pcall(mw.text.jsonEncode,smw_json)
	if smwJsonGood then
		smw_data_arr['Exchange JSON'] = smwJsonEncoded
	else
		div = div .. '<div style="display:none;">Error making JSON for SMW</div>'
	end
    local res = mw.smw.set(smw_data_arr)
	if not res == true then
		div = div .. '<div style="display:none;">Error setting SMW properties: '..res.error..'</div>'
	end
 
    return div .. cats
end

return p