יחידה:נתוני מכירות

מתוך ויקיפדיה, האנציקלופדיה החופשית

ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:נתוני מכירות/תיעוד

-- Check the next pages:
-- Template:Certification Table Entry/Region
-- Template:Certification Table Entry/Sales
-- Template:Certification Table Entry/Foot
-- Template:Certification Table Entry/Foot/helper
local p = {}
local Date = require('Module:תאריך')
local data = require('Module:נתוני מכירות/נתונים')
local CountryData = data[1]
local StyleData = data[2]
local naStyle = 'style="background: #ececec; color: #2C2C2C; vertical-align: middle; font-size: smaller; text-align: center" class="table-na" |—'

local function splitStringByIndex(str, index)
    local length = #str
    local firstPart = string.sub(str, 1, length - index)
    local lastChar = string.sub(str, length - index + 1, length)
    
    return {firstPart, lastChar}
end

-- Split the comma-separated lists into tables and sort them
local function splitString(inputstr, sep)
    local sep, fields = sep or ",", {}
    local pattern = string.format("([^%s]+)", sep)
    inputstr:gsub(pattern, function(c) fields[#fields + 1] = c end)
    return fields
end

function splitStringToCharsAndNumbers(inputString)
    local letters = {}
    local numbers = {}

    for i = 1, #inputString do
        local char = inputString:sub(i, i)
        if char:match('%d') then -- Check if the character is a number
        	table.insert(numbers, tonumber(char))
        else
            table.insert(letters, char)
        end
    end

    return letters, numbers
end

local function trim(s)
    return (s:gsub("^%s*(.-)%s*$", "%1"))
end

local function detailStyle(detail)
	local sDetail = splitString(detail, ",")
	for i, sd in ipairs(sDetail) do sDetail[i] = trim(sd) end
	
	if #sDetail == 0 then
		return naStyle
	elseif #sDetail == 1 then
		return detail
	else
		return sDetail[2] .. "× " .. sDetail[1]
	end
end

-- Function to compare dates for sorting
local function compareDates(date1, date2)
    if date1 == "הווה" then
        return false
    elseif date2 == "הווה" then
        return true
    else
        return os.time(date1) < os.time(date2)
    end
end

-- Function to check if the middle date is the same before and after sorting
local function isMiddleDateSameBeforeAndAfterSort(dates)
    -- Copy the original array
    local originalDates = {}
    for _, tDate in ipairs(dates) do
        table.insert(originalDates, tDate)
    end

    -- Sort the dates
    table.sort(dates, compareDates)

	if (dates[2] ~= "הווה" and originalDates[2] == "הווה") or (dates[2] == "הווה" and originalDates[2] ~= "הווה") then
		return false
	end
	if (dates[2] == "הווה" and originalDates[2] == "הווה") then
		return true
	end
	
    -- Check if the middle date is the same before and after sorting
    return os.time(originalDates[2]) == os.time(dates[2])
end

local function findData(country, detail, tDate, dType, isLocal)
	local letters, numbers = splitStringToCharsAndNumbers(country)
	local rc = table.concat(letters, "")
	for i, cd in pairs(CountryData) do
		if rc == i then
			for j, cin in ipairs(cd) do
				if dType == cin[1] or (isLocal == true and cin[1] == 'local ' .. dType) then
					if (cin[6] == nil and cin[7] == nil) or (cin[6] and cin[7] and isMiddleDateSameBeforeAndAfterSort({cin[6], tDate, cin[7]})) then
						if detail then
							if detail == 'כסף' then
								return cin[2]
							elseif detail == 'זהב' then
								return cin[3]
							elseif detail == 'פלטינה' then
								return cin[4]
							elseif detail == 'יהלום' then
								return cin[5]
							end
						end
					end
				end
			end
		end
	end
	return nil
end

local function returnTypeOfFootnote(country, tDate, dType)
	local footnoteStyle = {
		['sales'] = '*',
		['shipments'] = '^',
		['streamsonly'] = '†',
		['streaming'] = '‡'
	}
	local letters, numbers = splitStringToCharsAndNumbers(country)
	local rc = table.concat(letters, "")
	for i, cd in pairs(StyleData) do
		if rc == i then
			for j, cin in ipairs(cd) do
				if cin[1] == nil or (cin[1] and (dType == cin[1] or (isLocal == true and cin[1] == 'local ' .. dType))) then
					if cin[4] and ((cin[2] == nil and cin[3] == nil) or (cin[2] and cin[3] and isMiddleDateSameBeforeAndAfterSort({cin[2], tDate, cin[3]}))) then
						return footnoteStyle[cin[4]]
					end
				end
			end
		end
	end
	return ""
end

local function unitsPerDetail(country, detail, tDate, dType, isLocal)
	local sDetail = splitString(detail, ",")
	for i, sd in ipairs(sDetail) do sDetail[i] = trim(sd) end
	
	if #sDetail == 0 then
		return naStyle
	end
	
	local sd = findData(country, sDetail[1], tDate, dType, isLocal)
	if sd == nil or sd == "" then return naStyle end
	
	if #sDetail > 1 then
		return sd * tonumber(sDetail[2])
	else
		return sd
	end
end

local function countryStyle(country)
	local letters, numbers = splitStringToCharsAndNumbers(country)
	local res = table.concat(letters, "")
	local countryStyles = {
	    ["ארגנטינה"] = '[[CAPIF]]',
	    ["אוסטרליה"] = '[[ARIA]]',
	    ["אוסטריה"] = '[[IFPI Austria]]',
	    ["בלגיה"] = "[[BEA]]",
	    ["ברזיל"] = "[[Pro-Música Brasil]]",
	    ["קנדה"] = "[[Music Canada]]",
	    ["צ'ילה"] = "[[IFPI Chile]]",
	    ["סין"] = "[[NRTA]]",
	    ["קולומביה"] = "[[ASINCOL]]",
	    ["קרואטיה"] = "[[HDU]]",
	    ["צ'כיה"] = "[[ČNS IFPI]]",
	    ["דנמרק"] = "[[IFPI Denmark]]",
	    ["אקוודור"] = "[[IFPI Ecuador]]",
	    ["פינלנד"] = "[[Musiikkituottajat]]",
	    ["צרפת"] = "[[SNEP]]",
	    ["גרמניה"] = "[[BVMI]]",
	    ["יוון"] = "[[IFPI Greece]]",
	    ["הונג קונג"] = "[[IFPI Hong Kong]]",
	    ["הונגריה"] = "[[MAHASZ]]",
	    ["איסלנד"] = "[[FHF]]",
	    ["הודו"] = "[[IMI]]",
	    ["אינדונזיה"] = "[[ASIRI]]",
	    ["אירלנד"] = "[[IRMI]]",
	    ["ישראל"] = "[[הפדרציה לתקליטים]]",
	    ["איטליה"] = "[[FIMI]]",
	    ["יפן"] = "[[RIAJ]]",
	    ["לטביה"] = "[[LaIPA]]",
	    ["לבנון"] = "[[IFPI Lebanon]]",
	    ["מלזיה"] = "[[RIM]]",
	    ["מקסיקו"] = "[[AMPROFON]]",
	    ["הולנד"] = "[[NVPI]]",
	    ["ניו זילנד"] = "[[Recorded Music NZ]]",
	    ["ניגריה"] = "[[TCSN]]",
	    ["נורווגיה"] = "[[IFPI Norge]]",
	    ["פרגוואי"] = "[[SGP]]",
	    ["פרו"] = "[[UNIMPRO]]",
	    ["הפיליפינים"] = "[[PARI]]",
	    ["פולין"] = "[[ZPAV]]",
	    ["פורטוגל"] = "[[איגוד תעשיית ההקלטות הפורטוגזי|AFP]]",
	    ["רומניה"] = "[[UPFR]]",
	    ["רוסיה"] = "[[NFPF]]",
	    ["סינגפור"] = "[[RIAS]]",
	    ["סלובקיה"] = "[[ČNS IFPI]]",
	    ["דרום אפריקה"] = "[[RiSA]]",
	    ["קוריאה הדרומית"] = "[[KMCA]]",
	    ["ספרד"] = "[[PROMUSICAE]]",
	    ["שוודיה"] = "[[IFPI Sweeden]]",
	    ["שווייץ"] = "[[IFPI Switzerland]]",
	    ["טאיוואן"] = "[[RIT]]",
	    ["תאילנד"] = "[[TECA]]",
	    ["טורקיה"] = "[[Mü-Yap]]",
	    ["אוקראינה"] = "[[IFPI Ukraine]]",
	    ["בריטניה"] = "[[BPI]]",
	    ["ארצות הברית"] = "[[RIAA]]",
	    ["אורווגאי"] = "[[CUD]]",
	    ["ונצואלה"] = "[[APFV]]",
	    ["אירופה"] = "[[IFPI]]",
	    ["מועצת שיתוף הפעולה של מדינות המפרץ"] = "[[IFPI]]",
	    ["מצרים"] = "[[IFPI Egypt]]",
	    ['אורוגוואי'] = "[[CUD]]",
		['אמריקה המרכזית'] = "[[CFC]]",
		['בולגריה'] = "[[BAMP]]"
	}
	
	if countryStyles[res] then
		res = res .. " (" .. countryStyles[res] .. ")"
	end
	
	if res == 'איגוד חברות התקליטים העצמאיות' then
		res = 'אירופה ([[IMPALA]])'
	end
	
	return res
end

local function formatNumberWithCommas(number)
	if number == naStyle then return number end
    local formattedNumber = tostring(number)
    local reverseFormattedNumber = string.reverse(formattedNumber)
    
    local result = ""
    
    for i = 1, string.len(reverseFormattedNumber) do
        result = result .. string.sub(reverseFormattedNumber, i, i)
        if i % 3 == 0 and i < string.len(reverseFormattedNumber) then
            result = result .. ","
        end
    end
    
    return string.reverse(result)
end

local function isCountry(country)
	return string.find(country, "הערה", 1, true) == nil and string.find(country, "סיווג", 1, true) == nil and string.find(country, "סיכום", 1, true) == nil and string.find(country, "הערת מכירות", 1, true) == nil and country ~= "מדינת מקור" and country ~= "תאריך"
end

local function sameLang(value)
	if value == "אלבום" or value == "album" then
		return "album"
	elseif value == "mini-album" or value == "מיני-אלבום" or value == "EP" then
		return "mini-album"
	elseif value == "video album" or value == "אלבום וידאו" then
		return "video album"
	elseif value == "video single" or value == "סינגל וידאו" then
		return "video single"
	elseif value == "סינגל" or value == "single" then
		return "single"
	elseif value == "digital download" or value == "download" or value == "הורדת מוזיקה" or value == "הורדה" then
		return "download"
	elseif value == "streaming" or value == "סטרימינג" or value == "הזרמת מוזיקה" then
		return "streaming"
	elseif value == "אלבום פופולרי" or value == "popular album" then
		return "popular album"
	elseif value == "אלבום ג'אז" or value == "jazz album" then
		return "jazz album"
	elseif value == "latin" or value == "לטיני" then
		return "latin"
	elseif value == "DVD" or value == "Video Clip" or value == "Music Video" or value == "וידאו קליפ" or value == "video" then
		return "DVD"
	elseif value == "rington" or value == "masterton" or value == "רינגטון" or value == "מאסטרטון" then
		return "rington"
	elseif value == "compilation album" or value == "אלבום אוסף" then
		return "compilation album"
	end
	return ""
end

-- Custom comparison function for sorting keys
local function compareKeys(a, b)
    return tostring(a) < tostring(b)
end

function p.generateTable(frame)
	local pargs = frame:getParent().args
	local args = frame.args
	
	-- Construct the table in the desired format
    local table_text = "{| class=\"wikitable\"\n"
    table_text = table_text .. "|-\n! אזור !! תואר !! מכירות\n"
    
    local sum = 0
    
    local originCountry = pargs['מדינת מקור'] or ""
    originCountry = trim(originCountry)
    
    local keys = {}
	for key in pairs(pargs) do
	    table.insert(keys, key)
	end
    -- Sort the keys
	table.sort(keys, compareKeys)
	
    for _, key in ipairs(keys) do
    	country = key
    	detail = pargs[key]
    	country = trim(country)
    	table_text = table_text .. "|-\n"
    	local temp = splitStringByIndex(country, 13)
    	if isCountry(country) then
	    	if temp[2] ~= " מכירות" then
	    		table_text = table_text .. "|-\n"
	    		table_text = table_text .. "! " .. countryStyle(country) .. (pargs[country .. " הערה"] or "") .. "\n"
	    		table_text = table_text .. "| " .. detailStyle(detail) .. "\n"
	    		if pargs[country .. " מכירות"] then
	    			sum = sum + pargs[country .. " מכירות"]
	    			table_text = table_text .. "| " .. formatNumberWithCommas(pargs[country .. " מכירות"]) .. pargs[country .. " הערת מכירות"] .. "\n"
	    		else
	    			local tDate = pargs[country .. " תאריך"] or pargs['תאריך'] or "הווה"
				    if tDate ~= "הווה" then
					    local success, DateRes = pcall(Date.newFromWikitext, tDate)
					    if success then
					    	tDate = DateRes
					    end
					end
	    			local upd = unitsPerDetail(country, detail, tDate, sameLang(pargs[country .. ' סיווג'] or pargs['סיווג']), country == originCountry)
	    			local footnote =  returnTypeOfFootnote(country, tDate, sameLang(pargs[country .. ' סיווג'] or pargs['סיווג']))
	    			table_text = table_text .. "| " .. formatNumberWithCommas(upd)
	    			if upd ~= naStyle then
	    				sum = sum + upd
	    				table_text = table_text .. footnote
	    			end
	    			table_text = table_text .. "\n"
	    		end
	    	else
	    		if pargs[temp[1]] == nil then
	    			local r = string.gsub(detail, ",", "")
    				r = string.gsub(r, "%.", ".")
		    		table_text = table_text .. "|-\n"
		    		table_text = table_text .. "! " .. countryStyle(temp[1]) .. (pargs[temp[1] .. " הערה"] or "") .. "\n"
		    		table_text = table_text .. "| " .. naStyle .. '\n'
		    		table_text = table_text .. "| " .. formatNumberWithCommas(r) .. (pargs[temp[1] .. " הערת מכירות"] or "") .. "\n"
		    		sum = sum + r
	    		end
	    	end
    	end
    end
    
    if pargs['ללא סיכום'] ~= 'כן' then
		table_text = table_text .. "|-\n!colspan=3| סיכום\n"
		table_text = table_text .. "|-\n"
		table_text = table_text .. "! בכל העולם\n"
		table_text = table_text .. "| " .. naStyle .. '\n'
		table_text = table_text .. "| " .. (pargs['סיכום'] or formatNumberWithCommas(sum)) .. (pargs["הערת סיכום"] or "") .. "\n"
    end
	table_text = table_text .. "|}"
    
    return table_text
end

return p