Немає опису редагування
Немає опису редагування
Мітка: Ручний відкіт
 
(Не показані 44 проміжні версії цього користувача)
Рядок 1: Рядок 1:
local p = {}
local p = {}


-- Цільова дата для розрахунку днів з моменту приєднання (25 жовтня 2024 року)
-- ================================================
local TARGET_DATE_STR = "25.10.2024"
-- КЕШУВАННЯ
local TARGET_TIMESTAMP = os.time({year=2024, month=10, day=25, hour=0, min=0, sec=0})
-- ================================================


--- Функція для вилучення даних з вказаної сторінки та колонки
local page_cache = {}
-- @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 title = mw.title.new(page_title)
    local content = title and title:getContent()


     if not content then
local function get_page_content(page_name)
         return nil
     if page_cache[page_name] then
         return page_cache[page_name]
     end
     end
 
      
    -- Вилучаємо вміст таблиці wikitable
     local title = mw.title.new(page_name)
     -- Використовуємо нежадібний пошук (.-?) між {| і |}
     if not title or not title.exists then
     local table_content = mw.ustring.match(content, "{|%s*class%s*=%s*\"wikitable\".-([|].-.-[|]})")
        page_cache[page_name] = nil
     if not table_content then
         return nil
         return nil
     end
     end
   
    local content = title:getContent()
    page_cache[page_name] = content
    return content
end


    local escaped_player = mw.ustring.gsub(player_name, "([%(%)%.%-%+%[%]])", "%%%1")
-- ================================================
    local player_link_pattern = "%[?%[" .. escaped_player .. "%]%]?"
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================


    -- 1. СТІЙКИЙ ПОШУК РЯДКА: Шукаємо гравця у ДРУГІЙ колонці
function p.section_menu(frame)
    -- Шаблон:
     local page_name = frame.args.page or mw.title.getCurrentTitle().text
    -- 1. `[|]%s*.-` - Перша колонка (| 000)
     local content = get_page_content(page_name)
     -- 2. `[|]%s*` - Роздільник
    -- 3. `(.-)` - Друга колонка (захоплюємо вміст, який включає гравця)
     -- 4. `[|]%s*.-[|]` - Захоплюємо решту колонок (3 і 4)
      
      
    -- Шукаємо послідовність, що включає | <№> | [[Гравець]] |
     if not content then
    local search_pattern = "([|]%s*.-%s*[|]%s*" .. player_link_pattern .. "%s*[|].-)"
         return ""
    local full_row_match = mw.ustring.match(table_content, search_pattern)
 
     if not full_row_match then
         -- Додатковий пошук на випадок, якщо потрібен символ початку рядка |-\n
        local row_start_pattern = "[|]%s*.-%s*[%-]%s*([|]%s*.-%s*[|]%s*" .. player_link_pattern .. "%s*[|].-)"
        full_row_match = mw.ustring.match(table_content, row_start_pattern)
        if not full_row_match then
            return nil
        end
     end
     end
      
      
     local columns = {}
     local sections = {}
      
      
     -- 2. Надійне розділення на комірки.
     for line in mw.ustring.gmatch(content, "[^\n]+") do
    -- Розділяємо весь захоплений блок на окремі комірки по |
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
    for cell in mw.ustring.gmatch(full_row_match, "[|](.-)") do
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
        local trimmed_cell = mw.text.trim(cell)
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
        -- Видаляємо службові елементи
           
        if trimmed_cell ~= "" and not mw.ustring.match(trimmed_cell, "^!") then
            if section_name and section_name ~= "" then
            table.insert(columns, trimmed_cell)
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
               
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
               
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
         end
         end
     end
     end
      
      
     -- Колонка 1 = №, Колонка 2 = Пан/Пані, Колонка 3 = Дата/Сума, Колонка 4 = Провідник
     if #sections == 0 then
    local result = columns[column_index]
         return ""
 
    if result then
         -- 3. Очищення результату: видалення зовнішніх [[ ]]
        result = mw.text.trim(mw.ustring.gsub(result, "%[?%[?(.+)%]%]?", "%1"))
        return result
    else
        return nil
     end
     end
end
--- Функції, що викликаються шаблоном MCC Player New ---
function p.date_added(frame)
    local player = frame.args.player
    -- Колонка 3 для Дата приєднання
    local date_str = fetch_data_from_table("Гравці", player, 3)
    if not date_str or date_str == "" then
        return "''Невідомо''"
    end
    -- Парсинг дати у форматі DD.MM.YYYY
    local day, month, year = mw.ustring.match(date_str, "(%d%d)%.(%d%d)%.(%d%d%d%d)")
      
      
     if not day then
     -- Будуємо HTML
        return date_str .. " (Помилка формату)"
     local html_parts = {}
    end
 
     local join_timestamp = os.time({year=tonumber(year), month=tonumber(month), day=tonumber(day), hour=0, min=0, sec=0})
      
      
     local diff_seconds = TARGET_TIMESTAMP - join_timestamp
     table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
      
      
     if diff_seconds < 0 then
     table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
        return date_str
    end
 
    -- Розрахунок днів
    local diff_days = math.floor(diff_seconds / 86400)
      
      
     return string.format("%s (%d д)", date_str, diff_days)
     for i, section in ipairs(sections) do
end
        local border = ""
 
        if i < #sections then
function p.recruiter(frame)
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
    local player = frame.args.player
         end
    -- Колонка 4 для Провідника
       
    local recruiter_name = fetch_data_from_table("Гравці", player, 4)
         table.insert(html_parts, string.format(
 
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
    if not recruiter_name or recruiter_name == "" or recruiter_name == "Не вказано" or recruiter_name == "-" or recruiter_name == "Відсутній" then
            border, section.anchor, section.display
        return "Не вказано"
        ))
    end
   
    -- Додаємо вікі-посилання, якщо його немає
    if mw.ustring.match(recruiter_name, "%[?%[?") then
         return recruiter_name
    else
         return string.format("[[%s|%s]]", recruiter_name, recruiter_name)
    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
 
    -- Очищення від символів валют та пробілів
    amount = mw.ustring.gsub(amount, "[^%d%s]", "")
    amount = mw.text.trim(amount)
   
    return amount .. " ₴"
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
     end
    amount = mw.ustring.gsub(amount, "[^%d%s]", "")
    amount = mw.text.trim(amount)
      
      
     return amount .. " ₴"
     table.insert(html_parts, '</div>')
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
 
    -- Вилучення лише числа з рядка
    count = mw.ustring.match(count, "(%d+)")
   
    if not count then
        return "0/9"
    end
      
      
     return count .. "/9"
     return table.concat(html_parts, '\n')
end
end


return p
return p

Поточна версія на 10:24, 8 грудня 2025

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

local p = {}

-- ================================================
-- КЕШУВАННЯ
-- ================================================

local page_cache = {}

local function get_page_content(page_name)
    if page_cache[page_name] then
        return page_cache[page_name]
    end
    
    local title = mw.title.new(page_name)
    if not title or not title.exists then
        page_cache[page_name] = nil
        return nil
    end
    
    local content = title:getContent()
    page_cache[page_name] = content
    return content
end

-- ================================================
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================

function p.section_menu(frame)
    local page_name = frame.args.page or mw.title.getCurrentTitle().text
    local content = get_page_content(page_name)
    
    if not content then
        return ""
    end
    
    local sections = {}
    
    for line in mw.ustring.gmatch(content, "[^\n]+") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
            
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
                
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
                
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
        end
    end
    
    if #sections == 0 then
        return ""
    end
    
    -- Будуємо HTML
    local html_parts = {}
    
    table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
    
    table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    
    for i, section in ipairs(sections) do
        local border = ""
        if i < #sections then
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
        end
        
        table.insert(html_parts, string.format(
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
            border, section.anchor, section.display
        ))
    end
    
    table.insert(html_parts, '</div>')
    
    return table.concat(html_parts, '\n')
end

return p