Модуль:FetchData2: відмінності між версіями

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


----------------------------------------------------------------------
-- Цільова дата для розрахунку днів з моменту приєднання (25 жовтня 2024 року)
-- Функція: шукає у таблиці рядок, де друга колонка = player_name
local TARGET_DATE_STR = "25.10.2024"
-- Повертає дані з column_index того ж рядка
local TARGET_TIMESTAMP = os.time({year=2024, month=10, day=25, hour=0, min=0, sec=0})
----------------------------------------------------------------------


--- Функція для вилучення даних з вказаної сторінки та колонки
-- @param page_title Назва сторінки (наприклад, "Гравці")
-- @param player_name Ім'я гравця для пошуку (PAGENAME)
-- @param column_index Індекс колонки для вилучення (1 = №, 2 = Пан/Пані, 3 = Дата/Сума/Рахунок, 4 = Провідник)
-- @return Очищене значення або nil
local function fetch_data_from_table(page_title, player_name, column_index)
local function fetch_data_from_table(page_title, player_name, column_index)
     local title = mw.title.new(page_title)
     local title = mw.title.new(page_title)
     if not title then return nil end
     local content = title and title:getContent()


    local content = title:getContent()
     if not content then
     if not content then return nil end
        return nil
    end


     local table_content = mw.ustring.match(content, "{|.-|}")
    -- Вилучаємо вміст таблиці wikitable
     if not table_content then return nil end
     local table_content = mw.ustring.match(content, "{|%s*class%s*=%s*\"wikitable\".-([|]-.-[|]})")
     if not table_content then
        return nil
    end


    -- Обробляємо можливі варіанти написання імені в таблиці
     local escaped_player = mw.ustring.gsub(player_name, "([%(%)%.%-%+%[%]])", "%%%1")
     local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
     local player_link_pattern = "%[?%[" .. escaped_player .. "%]%]?"
     local player_pattern =
        "%[%[" .. escaped .. "%]%]" ..
        "|%[%[" .. escaped .. "|.-%]%]" ..
        "|" .. escaped


     local target_row = nil
    -- 1. Знайти рядок, де гравець знаходиться у ДРУГІЙ колонці.
    -- У вашій розмітці:
    -- \n| <№>
    -- \n| [[<Гравець>]]
    -- \n| <Дата>
    -- \n| <Провідник>
   
    -- Шаблон: \n| <№>\n| [[<Гравець>]]\n| <Дата>\n| <Провідник>
    -- Ми шукаємо:
    -- 1. \n| будь-які символи (№)
    -- 2. \n| + посилання на гравця
    -- 3. (.-) - захоплюємо решту даних у цьому рядку (Дата та Провідник)
    -- 4. \n|- або |} - до кінця рядка або таблиці
   
     local search_pattern =  
        "([|]%s*.-%s*%s*[|]%s*" .. player_link_pattern .. "%s*[|].-)" -- Починаємо з першої колонки і захоплюємо до кінця рядка
   
    local full_row_match = mw.ustring.match(table_content, search_pattern)


     for line in mw.ustring.gmatch(table_content, "[^\n]+") do
    if not full_row_match then
         if mw.ustring.match(line, player_pattern) then
        -- Якщо не знайшли вільний рядок, шукаємо рядок, що починається з |-
            target_row = line
        search_pattern =
            break
            "[|]%s*.-%s*[%-]%s*([|]%s*.-%s*[|]%s*" .. player_link_pattern .. "%s*[|].-)"
        full_row_match = mw.ustring.match(table_content, search_pattern)
        if not full_row_match then
            return nil
        end
    end
   
    local columns = {}
   
    -- 2. Надійне розділення на комірки.
    -- Ми використовуємо gmatch, щоб розділити весь захоплений блок на окремі комірки по |
     for cell in mw.ustring.gmatch(full_row_match, "[|](.-)") do
        local trimmed_cell = mw.text.trim(cell)
        -- Перевіряємо, чи це не заголовок і не порожній рядок
         if trimmed_cell ~= "" and not mw.ustring.match(trimmed_cell, "^!") then
            table.insert(columns, trimmed_cell)
         end
         end
     end
     end
   
    -- Колонка 1 = №, Колонка 2 = Пан/Пані, Колонка 3 = Дата/Сума, Колонка 4 = Провідник
    local result = columns[column_index]


     if not target_row then return nil end
     if result then
 
        -- 3. Очищення результату
    -- очищення "|-"
        -- Очищуємо від вікі-посилань (наприклад, [[Демон]] -> Демон)
    target_row = mw.ustring.gsub(target_row, "^%s*|%-", "")
        result = mw.text.trim(mw.ustring.gsub(result, "%[?%[?(.+)%]%]?", "%1"))
 
        return result
     -- розбиття на комірки
     else
    local cells = {}
         return nil
    for cell in mw.ustring.gmatch(target_row, "%s*|%s*([^|]+)") do
         table.insert(cells, mw.text.trim(cell))
     end
     end
    local result = cells[column_index]
    if not result then return nil end
    -- прибираємо [[link]]
    result = mw.ustring.gsub(result, "%[%[([^%]|]+)|?([^%]]*)%]%]", "%2")
    result = mw.text.trim(result)
    result = result ~= "" and result or nil
    return result
end
end


--- Функції, що викликаються шаблоном MCC Player New ---


----------------------------------------------------------------------
function p.date_added(frame)
-- Рахує різницю в днях між датою у таблиці та 25.10.2024
    local player = frame.args.player
----------------------------------------------------------------------
    -- Колонка 3 для Дата приєднання
    local date_str = fetch_data_from_table("Гравці", player, 3)


local function getDaysDifference(dateString)
     if not date_str or date_str == "" then
     if not dateString then return "" end
        return "''Невідомо''"
    end


     local d, m, y = dateString:match("(%d%d)%.(%d%d)%.(%d%d%d%d)")
    -- Парсинг дати у форматі DD.MM.YYYY
     if not d then return dateString end
     local day, month, year = mw.ustring.match(date_str, "(%d%d)%.(%d%d)%.(%d%d%d%d)")
   
     if not day then
        return date_str .. " (Помилка формату)"
    end


     local start = os.time({day = d, month = m, year = y})
     local join_timestamp = os.time({year=tonumber(year), month=tonumber(month), day=tonumber(day), hour=0, min=0, sec=0})
    local finish = os.time({day = 25, month = 10, year = 2024})
   
    local diff_seconds = TARGET_TIMESTAMP - join_timestamp
   
    if diff_seconds < 0 then
        return date_str
    end


     local diff = math.floor((finish - start) / 86400)
    -- Розрахунок днів
     return string.format("%s (%d днів)", dateString, diff)
     local diff_days = math.floor(diff_seconds / 86400)
   
     return string.format("%s (%d д)", date_str, diff_days)
end
end
----------------------------------------------------------------------
-- ДАНІ З ТАБЛИЦІ "Гравці"
----------------------------------------------------------------------


function p.recruiter(frame)
function p.recruiter(frame)
     local name = mw.title.getCurrentTitle().text
     local player = frame.args.player
     return fetch_data_from_table("Гравці", name, 4) or "Невідомо"
    -- Колонка 4 для Провідника
end
     local recruiter_name = fetch_data_from_table("Гравці", player, 4)


function p.date_added(frame)
    if not recruiter_name or recruiter_name == "" or recruiter_name == "Не вказано" or recruiter_name == "-" or recruiter_name == "Відсутній" then
     local name = mw.title.getCurrentTitle().text
        return "Не вказано"
     local raw_date = fetch_data_from_table("Гравці", name, 3)
    end
     return raw_date and getDaysDifference(raw_date) or "Невідомо"
   
    -- Додаємо вікі-посилання, якщо його немає
     if mw.ustring.match(recruiter_name, "%[?%[?") then
        return recruiter_name
     else
        return string.format("[[%s|%s]]", recruiter_name, recruiter_name)
     end
end
end


function p.prize_pool(frame)
    local player = frame.args.player
    -- Колонка 3 для Суми
    local amount = fetch_data_from_table("Призовий_фонд", player, 3)


----------------------------------------------------------------------
    if not amount or amount == "" then
-- ДАНІ З ТАБЛИЦІ "Призовий_фонд"
        return "0 ₴"
----------------------------------------------------------------------
    end


function p.prize_pool(frame)
    -- Очищення від символів валют
     local name = mw.title.getCurrentTitle().text
    amount = mw.ustring.gsub(amount, "[^%d%s]", "")
     return fetch_data_from_table("Призовий_фонд", name, 3) or "0"
     amount = mw.text.trim(amount)
   
     return amount .. " "
end
end


function p.foundation(frame)
    local player = frame.args.player
    -- Колонка 3 для Суми
    local amount = fetch_data_from_table("Фундація", player, 3)


----------------------------------------------------------------------
    if not amount or amount == "" then
-- ДАНІ З ТАБЛИЦІ "Фундація"
        return "0 ₴"
----------------------------------------------------------------------
    end


function p.foundation(frame)
    amount = mw.ustring.gsub(amount, "[^%d%s]", "")
     local name = mw.title.getCurrentTitle().text
     amount = mw.text.trim(amount)
     return fetch_data_from_table("Фундація", name, 2) or "0"
   
     return amount .. " "
end
end


function p.final(frame)
    local player = frame.args.player
    -- Колонка 3 для Кількість/Рахунок
    local count = fetch_data_from_table("Фіналіст", player, 3)


----------------------------------------------------------------------
    if not count or count == "" then
-- ДАНІ З ТАБЛИЦІ "Фіналіст"
        return "0/9"
----------------------------------------------------------------------
    end


function p.final(frame)
    -- Вилучення лише числа з рядка
     local name = mw.title.getCurrentTitle().text
     count = mw.ustring.match(count, "(%d+)")
     return fetch_data_from_table("Фіналіст", name, 2) or "Ні"
   
     if not count then
        return "0/9"
    end
   
    return count .. "/9"
end
end


return p
return p