Module:CommunityResearchOutcomesList

From MaRDI portal
Revision as of 19:39, 9 September 2024 by Tconrad (talk | contribs)

Documentation for this module may be created at Module:CommunityResearchOutcomesList/doc

-- Required module containing helper methods
local helper = require('Module:HelperMethods')

-- Required modules for SPARQL queries and HTML table generation
local sparql = require('SPARQL')
local mwHtml = require('mw.html')

-- Main table to hold all functions
local p = {}

-- Function to build a HTML table from SPARQL query results
function p.buildTableFromSparql(frame)
    
    -- Retrieve target1 from frame arguments or return error message if not set
    local target1 = frame.args[1]
    if not target1 or target1 == '' then
        return "No records found"
    end    
    
    local height = frame.args[2] or '400px' -- Default height if not specified
    local width = frame.args[3] or '800px' -- Default width if not specified
    
    -- Get the current URL
    local baseUrl = mw.site.server

    -- Constructing the SPARQL query with dynamic entity target1 and performance improvements
    local sparqlQuery = [[
PREFIX target1: <https://portal.mardi4nfdi.de/entity/]] .. target1 .. [[>
PREFIX wdt: <https://portal.mardi4nfdi.de/prop/direct/>
PREFIX wd: <https://portal.mardi4nfdi.de/entity/>

SELECT
  ?publication_date ?work ?workLabel 
  (REPLACE(STR(?work), "^.*/", "") AS ?qid)
  ?item_type
  ?item_type_label
  ?internal_project_item
  ?internal_project_label
  
WHERE {
  ?work wdt:P1495 target1: .
  
  # Restrict to allowed item types using VALUES for performance
  VALUES (?item_type ?item_type_label) { 
    (wd:Q5976449 "Paper") 
    (wd:Q5984635 "Dataset") 
    (wd:Q5976450 "Software")
  }
  
  # Match the item type
  ?work wdt:P1460 ?item_type .

  # Optional publication date
  OPTIONAL { ?work wdt:P28 ?publication_datetime. }
  BIND(COALESCE(xsd:date(?publication_datetime), "N/A") AS ?publication_date)

  # Optional internal project item and label retrieval
  OPTIONAL {
    ?work wdt:P1507 ?internal_project_item .
    OPTIONAL {
      ?internal_project_item rdfs:label ?internal_project_label .
      FILTER(LANG(?internal_project_label) = "en" || LANG(?internal_project_label) = "de")
    }
  }

  # Ensure labels are fetched in English or German
  SERVICE wikibase:label { bd:serviceParam wikibase:language "de,en". }
}

ORDER BY DESC(?publication_date)
    ]]

    -- Log and run the SPARQL query
    mw.log(sparqlQuery)
    local jsonResults = sparql.runQuery(sparqlQuery)
    
    -- Handle errors or empty results
    if jsonResults and jsonResults.error then
        mw.log("Error in SPARQL query: " .. tostring(jsonResults.error))
        return nil
    end

    if not jsonResults then
        return "Could not fetch data."
    end

    if helper.countElementsInBindings(jsonResults.results.bindings) == 0 then
        return "No records found."
    end

    -- Convert the JSON results into a Lua table
    local fieldOrder = {"qid", "workLabel", "publication_date", "internal_project_item", "internal_project_label", "item_type", "item_type_label"}
    local dataTable = helper.convertJsonToTableOrdered(jsonResults, fieldOrder)
    
    -- Generate the workUrl based on the qid and item_type_label
    for _, row in ipairs(dataTable) do
        local qid = row.qid
        local itemTypeLabel = row.item_type_label

        -- Check if qid is not nil before generating the workUrl
        if qid and itemTypeLabel then
            -- Dynamically generate the workUrl based on item type
            if itemTypeLabel == "Paper" then
                row.workUrl = baseUrl .. "/wiki/Publication:" .. qid
            elseif itemTypeLabel == "Dataset" then
                row.workUrl = baseUrl .. "/wiki/Dataset:" .. qid
            elseif itemTypeLabel == "Software" then
                row.workUrl = baseUrl .. "/wiki/Software:" .. qid
            else
                row.workUrl = baseUrl .. "/wiki/" .. qid -- Fallback
            end
        else
            -- Handle missing qid or item_type_label
            row.workUrl = "URL not available"
        end
    end
    
    -- Create and return HTML table from the data
    local headers = {"Title", "Date of Publication", "Project", "Type"}
    local htmlTable = helper.createHtmlTableWithMergedCols(dataTable, headers, {{1, 2}, {4}, {6, 7}, {8, 9}})

    -- Generate histogram data
    local histogramChart = helper.generateHistogramChartFromTable(dataTable, 4)
    local histogramChartJson = mw.text.jsonEncode(histogramChart)

    -- Create a parent container for both the table and the chart
    local parentContainer = mw.html.create('div')
        :addClass('parent-container')
        :css('width', width)

    -- Create chart container
    local chartContainer = mw.html.create('div')
        :addClass('wikiChartContainer')
        :css('height', height)
        :css('width', width)
        :attr('data-chartdata', histogramChartJson)

    -- Add the table and chart to the parent container
    parentContainer
        :node(htmlTable)
        :node(mw.html.create('h2'):wikitext('Research outcomes over time'))
        :node(chartContainer)

    return tostring(parentContainer)
end

-- Return the created HTML table
return p