Немає опису редагування
Немає опису редагування
Рядок 1: Рядок 1:
local p = {}
local p = {}


--- Функція для виведення помилки на сторінку
function p.season_result(frame)
local function error_output(context, error_details)
     local season = frame.args.season
     local safe_details = error_details or "N/A"
     local player = frame.args.player
     return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Page: %s]</span>", context or "Unknown Context", safe_details)
end


--- Видаляє вікі-посилання [[link|text]] і [[link]]
     -- Updated list of seasons with new entries
local function clean_wikilinks(text)
     local season_titles = {
    if not text then return nil end
        "Перший_сезон", "Другий_сезон", "Третій_сезон",
     -- [[link|text]] -> text
        "Четвертий_сезон", "П'ятий_сезон", "Шостий_сезон",
     text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
        "Сьомий_сезон", "Восьмий_сезон", "Дев'ятий_сезон"
    -- [[link]] -> link
     }
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
     return mw.text.trim(text)
end


----------------------------------------------------------------------
    mw.log("Season index: ", season)
-- ГОЛОВНИЙ ПОШУК (Виправлено парсинг, використовує ім'я гравця)
    mw.log("Player name: ", player)
----------------------------------------------------------------------


local function fetch_from_table(page_title, player_name, column_index)
    local season_title = season_titles[tonumber(season)]
      
     mw.log("Season page title: ", season_title)
    if not player_name or player_name == "" then
 
        -- Повертаємо помилку, якщо ім'я гравця не передано
     if not season_title then
        return error_output("No Player Name", page_title)  
         return "??"
    end
   
    local title = mw.title.new(page_title)
     if not title or not title.exists then  
         return error_output("Page Missing", page_title)
     end
     end


     local content = title:getContent()
     local title = mw.title.new(season_title)
     if not content then return error_output("Content Read Fail", page_title) end
     local content = title and title:getContent()


     -- Шукаємо вміст таблиці
     if not content then
    local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
        mw.log("Error: Content not found for the season page.")
    if not table_content then
         return "??"
         return error_output("Table Missing", page_title)
     end
     end


     local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
     mw.log("Page content loaded, length: ", string.len(content))
     -- Шукаємо гравця у форматі [[Player]]
     mw.log("Page content preview: ", mw.ustring.sub(content, 1, 500))
    local player_pattern = "%[%[" .. escaped .. "%]%]"


    local result = nil
     -- Attempt to extract the "Рейтинг" section
   
     local rating_section = mw.ustring.match(content, "==%s*Рейтинг%s*==.-{|%s*class%s*=%s*\"wikitable sortable\"(.-)|}")
     -- Ітерація по всіх рядках, що починаються з `|-`
    if not rating_section then
     for row in mw.ustring.gmatch(table_content, "\n%s*|-[^%s]*\n(.-)") do
        mw.log("Error: Rating section not found within the page content.")
       
        mw.log("Page content: ", mw.ustring.sub(content, 1, 1000)) -- Log more content for better debugging
        -- Перевіряємо, чи містить рядок ім'я гравця
         return "Rating section not found"
        if mw.ustring.find(row, player_pattern, 1, true) then
           
            -- --- ПОКРАЩЕНА ЛОГІКА ПАРСИНГУ КОМІРОК ---
            local cell_data = {}
           
            -- 1. Видаляємо маркер початку рядка (пробіли та перший '|')
            local cleaned_row = mw.ustring.gsub(row, "^%s*[|]%s*", "")
           
            -- 2. Розділяємо рядок за '||'. Це надійно захоплює всі комірки.
            local cell_parts = mw.text.split(cleaned_row, '||')
           
            -- 3. Обрізаємо пробіли для кожної частини і заповнюємо cell_data
            for _, cell in ipairs(cell_parts) do
                table.insert(cell_data, mw.text.trim(cell))
            end
            -- --- КІНЕЦЬ ПОКРАЩЕНОЇ ЛОГІКИ ---
           
            -- Перевіряємо, що ми знайшли [[Player]] саме в Колонці 2
            if #cell_data >= 2 and mw.ustring.find(cell_data[2], player_pattern) then
               
                -- Перевірка, чи існує потрібна колонка
                if column_index <= #cell_data and cell_data[column_index] then
                    result = clean_wikilinks(cell_data[column_index])
                    break -- Знайшли, виходимо
                end
            end
         end
     end
     end


     return result
     mw.log("Rating section extracted, length: ", string.len(rating_section))
end
     mw.log("Rating section preview: ", mw.ustring.sub(rating_section, 1, 500))
 
----------------------------------------------------------------------
-- ФУНКЦІЇ ДЛЯ {{MCC Player New}} (використовують fetch_from_table)
----------------------------------------------------------------------
 
function p.recruiter(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4) -- Колонка 4
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
    if raw == "Відсутній" or raw == "-" then return "Не вказано" end
    return raw or "Не вказано"
end
 
function p.date_added(frame)
     local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3) -- Колонка 3
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
    return raw or "Невідомо"
end


function p.prize_pool(frame)
     -- Adjusted to fetch the player's position (column 1 "") instead of points
     local name = frame.args.player
     local pattern = "|%s*(%d+)%s*|%s*%[%[" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%]%]"
    local raw = fetch_from_table("Призовий_фонд", name, 3)  
     local direct_pattern = "|%s*(%d+)%s*|%s*" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%s*"
      
    local rank = mw.ustring.match(rating_section, pattern) or mw.ustring.match(rating_section, direct_pattern)
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
      
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
    return (raw or "0") .. " ₴"
end


function p.foundation(frame)
    if not rank then
    local name = frame.args.player
        mw.log("Error: Player not found in season rankings or regex failed.")
    local raw = fetch_from_table("Фундація", name, 3)
        mw.log("Pattern used: ", pattern)
   
         mw.log("Direct pattern used: ", direct_pattern)
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
         return "--"
   
    if raw then
         raw = mw.ustring.gsub(raw, "[^%d%s]", "")
         raw = mw.text.trim(raw)
     end
     end
    return (raw or "0") .. " ₴"
end


function p.final(frame)
     mw.log("Player rank found: ", rank)
    local name = frame.args.player
     return rank
    local raw = fetch_from_table("Фіналіст", name, 3)
      
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
    local count = raw and mw.ustring.match(raw, "(%d+)")
   
    if count then
        return count
    else
        return "0"
    end
end
 
-- Ця функція залишається порожньою, як ви просили на початку, щоб не чіпати сезони
function p.season_result(frame)
     return nil
end
end


return p
return p

Версія за 00:55, 24 листопада 2025

Документацію для цього модуля можна створити у Модуль:FetchData2/документація

local p = {}

function p.season_result(frame)
    local season = frame.args.season
    local player = frame.args.player

    -- Updated list of seasons with new entries
    local season_titles = {
        "Перший_сезон", "Другий_сезон", "Третій_сезон",
        "Четвертий_сезон", "П'ятий_сезон", "Шостий_сезон", 
        "Сьомий_сезон", "Восьмий_сезон", "Дев'ятий_сезон"
    }

    mw.log("Season index: ", season)
    mw.log("Player name: ", player)

    local season_title = season_titles[tonumber(season)]
    mw.log("Season page title: ", season_title)

    if not season_title then
        return "??"
    end

    local title = mw.title.new(season_title)
    local content = title and title:getContent()

    if not content then
        mw.log("Error: Content not found for the season page.")
        return "??"
    end

    mw.log("Page content loaded, length: ", string.len(content))
    mw.log("Page content preview: ", mw.ustring.sub(content, 1, 500))

    -- Attempt to extract the "Рейтинг" section
    local rating_section = mw.ustring.match(content, "==%s*Рейтинг%s*==.-{|%s*class%s*=%s*\"wikitable sortable\"(.-)|}")
    if not rating_section then
        mw.log("Error: Rating section not found within the page content.")
        mw.log("Page content: ", mw.ustring.sub(content, 1, 1000)) -- Log more content for better debugging
        return "Rating section not found"
    end

    mw.log("Rating section extracted, length: ", string.len(rating_section))
    mw.log("Rating section preview: ", mw.ustring.sub(rating_section, 1, 500))

    -- Adjusted to fetch the player's position (column 1 "№") instead of points
    local pattern = "|%s*(%d+)%s*|%s*%[%[" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%]%]"
    local direct_pattern = "|%s*(%d+)%s*|%s*" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%s*"
    local rank = mw.ustring.match(rating_section, pattern) or mw.ustring.match(rating_section, direct_pattern)

    if not rank then
        mw.log("Error: Player not found in season rankings or regex failed.")
        mw.log("Pattern used: ", pattern)
        mw.log("Direct pattern used: ", direct_pattern)
        return "--"
    end

    mw.log("Player rank found: ", rank)
    return rank
end

return p