Módulo:BibRules

De Wikincat
Revisão de 21h25min de 14 de agosto de 2021 por imported>Jaideraf
Ir para navegação Ir para pesquisar

A documentação para este módulo pode ser criada em Módulo:BibRules/doc

local p = {}

function p.BibRules(frame)
  -- Define o alvo das regras
  local target = frame:getParent().args[1]
  if target == "" or target == nil then
    target = mw.uri.decode(frame:callParserFunction("#urlget", "fullpagename"))
  end
  if target == "" or target == nil then
    target = mw.title.getCurrentTitle().prefixedText
  end
  -- Semantic Scribunto foi carregado?
  if not mw.smw then
    return "mw.smw module not found"
  end
  -- Define variáveis básicas
  local test, info, queryResult
  local f100 = ''
  local infos = {}
  -- Somente realize as análises de existir o campo 245
  if frame:expandTemplate {title = "Exist", args = {"245"}} ~= "" then
    -- Record status
    test = frame:expandTemplate {title = "Field data string", args = {"000", "5", "1", property = "Leader"}} or false
    if test == "n" then
      info =
        "* Segundo o Líder, este é um registro '''novo''' (não um alterado ou revisado, expandido, excluído, etc.)."
      table.insert(infos, info)
    elseif test == "c" then
      info =
        "* Segundo o Líder, este é um registro '''alterado ou revisado''' (não um novo, expandido, excluído, etc.)."
      table.insert(infos, info)
    elseif test == "a" or test == "d" or test == "p" then
      info = "* Segundo o Líder, este é um registro '''expandido''' ou '''excluído''' (não novo)."
      table.insert(infos, info)
    end
    -- Type of record
    test = frame:expandTemplate {title = "Field data string", args = {"000", "6", "1", property = "Leader"}} or false
    if test == "a" then
      info = "* Segundo o Líder, este registro descreve um '''material textual'''."
      table.insert(infos, info)
    end
    -- Bibliographic level
    test = frame:expandTemplate {title = "Field data string", args = {"000", "7", "1", property = "Leader"}} or false
    if test == "m" then
      info =
        "* Segundo o Líder, este registro descreve um '''item monográfico''' (não parte de um item, não um item seriado, não uma coleção, etc.)."
      table.insert(infos, info)
    end
    -- Encoding level
    test = frame:expandTemplate {title = "Field data string", args = {"000", "17", "1", property = "Leader"}} or false
    if test == "1" then
      info =
        "* Segundo o Líder, este registro tem um nível '''completo''' de catalogação (mas o material não foi examinado)."
      table.insert(infos, info)
    elseif test == "#" then
      info =
        "* Segundo o Líder, este registro tem um nível '''completo''' de catalogação (a descrição foi realizada com o material em mãos)."
      table.insert(infos, info)
    end
    -- Descriptive cataloging form
    test = frame:expandTemplate {title = "Field data string", args = {"000", "18", "1", property = "Leader"}} or false
    if test == "a" then
      info = "* Segundo o Líder, este registro possui uma catalogação '''compatível com as regras do AACR 2'''."
      table.insert(infos, info)
    else
      info = "* Segundo o Líder, este registro possui uma catalogação '''não compatível com as regras da ISBD'''."
      table.insert(infos, info)
    end
    -- Explica a sintaxe "(Biblioteca)NúmeroDeControle"
    local f001 =
      frame:expandTemplate {title = "Field data string", args = {"001", "0", "", property = "Control field data"}}
    info =
      '* Internamente, este registro é identificado pelo código "' ..
      f001 ..
        '"; para sistemas externos, o código é "(' ..
          frame:expandTemplate {
            title = "Field data string",
            args = {"003", "0", "", property = "Control field data"}
          } ..
            ")" .. f001 .. '".'
    table.insert(infos, info)
    -- Campo 005
    queryResult = mw.smw.ask("[[" .. target .. "]]|?Creation date#-F[l, d \\d\\e F \\d\\e Y]|headers=hide|mainlabel=-")
    local creationDate = ""
    if type(queryResult) == "table" then
      for _, row in pairs(queryResult) do
        for _, data in pairs(row) do
          creationDate = data
        end
      end
    end
    queryResult =
      mw.smw.ask("[[" .. target .. "]]|?Modification date#-F[l, d \\d\\e F \\d\\e Y]|headers=hide|mainlabel=-")
    local modificationDate = ""
    if type(queryResult) == "table" then
      for _, row in pairs(queryResult) do
        for _, data in pairs(row) do
          modificationDate = data
        end
      end
    end
    info =
      "* O registro foi criado em: " .. creationDate .. ". Sua última transação foi em: " .. modificationDate .. "."
    table.insert(infos, info)
    -- Campo 008
    local invalidCode = "<strong class='error'>código inválido para o local de publicação</strong>"
    local pubPlace_tbl = {
      ["acb"] = "Acre",
      ["alb"] = "Alagoas",
      ["amb"] = "Amazonas",
      ["apb"] = "Amapá",
      ["bab"] = "Bahia",
      ["ceb"] = "Ceará",
      ["dfb"] = "Distrito Federal",
      ["esb"] = "Espírito Santo",
      ["gob"] = "Goiás",
      ["mab"] = "Maranhão",
      ["mgb"] = "Minas Gerais",
      ["msb"] = "Mato Grosso do Sul",
      ["mtb"] = "Mato Grosso",
      ["pab"] = "Pará",
      ["pbb"] = "Paraíba",
      ["peb"] = "Pernambuco",
      ["pib"] = "Piauí",
      ["prb"] = "Paraná",
      ["rjb"] = "Rio de Janeiro",
      ["rnb"] = "Rio Grande do Norte",
      ["rob"] = "Rondônia",
      ["rrb"] = "Roraima",
      ["rsb"] = "Rio Grande do Sul",
      ["scb"] = "Santa Catarina",
      ["seb"] = "Sergipe",
      ["spb"] = "São Paulo",
      ["tob"] = "Tocantins",
      ["bl "] = "Brasil",
      ["xxu"] = "Estados Unidos",
      ["flu"] = "Flórida, EUA",
      ["nyu"] = "Nova York, EUA",
      ["po "] = "Portugal",
      ["xxk"] = "Reino Unido",
      ["fr "] = "França",
      ["sp "] = "Espanha",
      ["gw "] = "Alemanha",
      ["xx "] = "<strong class='error'>não foi identificado um local de publicação no campo 008</strong>",
      ["vp "] = "há vários locais de publicação",
      ["esp"] = invalidCode,
      ["eua"] = invalidCode,
      ["fra"] = invalidCode,
      ["   "] = "<strong class='error'>é necessário informar um código de local de publicação, campo 008.</strong>"
    }
    local f008pubPlace =
      frame:expandTemplate {
      title = "Field data string",
      args = {"008", "15", "3", property = "Control field data"}
    }
    if string.match(f008pubPlace, "^[A-Z]") then
      info = "* <strong class='error'>O uso de maiúsculas não é permitido no campo 008, local de publicação.</strong>"
      table.insert(infos, info)
    elseif pubPlace_tbl[f008pubPlace] then
      info = "* O item possui a seguinte origem: " .. tostring(pubPlace_tbl[f008pubPlace]) .. "."
      table.insert(infos, info)
    else
      info = "* O item possui a seguinte origem: " .. f008pubPlace .. "."
      table.insert(infos, info)
    end
    invalidCode = "<strong class='error'>código inválido para o idioma (campo 008 ou subcampo $h do campo 041)</strong>"
    local lang_tbl = {
      ["por"] = "português",
      ["eng"] = "inglês",
      ["spa"] = "espanhol",
      ["ger"] = "alemão",
      ["fre"] = "francês",
      ["ita"] = "italiano",
      ["chi"] = "chinês",
      ["esp"] = invalidCode,
      ["ing"] = invalidCode,
      ["fra"] = invalidCode,
      ["pt"] = invalidCode,
      ["en"] = invalidCode,
      ["es"] = invalidCode,
      ["   "] = "<strong class='error'>é necessário informar um código de idioma no campo 008.</strong>"
    }
    local f008lang =
      frame:expandTemplate {
      title = "Field data string",
      args = {"008", "35", "3", property = "Control field data"}
    }
    if string.match(f008lang, "^[A-Z]") then
      info = "* <strong class='error'>O uso de maiúsculas não é permitido no campo 008, idioma.</strong>"
    elseif lang_tbl[f008lang] then
      info = "* Majoritariamente, o item se expressa no seguinte idioma: " .. tostring(lang_tbl[f008lang])
    else
      info = "* Majoritariamente, o item se expressa no seguinte idioma: " .. f008lang
    end
    -- Se existe o campo 041, mostra "(traduzido do... )" na mesma linha do idioma presente no 008
    test = frame:expandTemplate {title = "Exist", args = {"041"}}
    if test ~= "" then
      test = frame:expandTemplate {title = "Field data string", args = {"041", "0", "1"}} or false
      if test == "1" then
        local f041h = frame:expandTemplate {title = "Select", args = {"041", "h"}}
        f041h = lang_tbl[f041h] or f041h
        info = info .. "&#32;(traduzido do " .. f041h .. ")."
      end
    end
    table.insert(infos, info)
    -- Testa se existe(m) ISBN(s) inválido(s)
    test = frame:expandTemplate {title = "Exist", args = {"020"}} or false
    if test ~= "" then
      test = frame:expandTemplate {title = "Print ISBN"} or false
      if string.match(test, "error") then
        info = "* <strong class='error'>ISBN inválido, por favor, reveja os números informados.</strong>"
        table.insert(infos, info)
      end
      -- Testa se existe(m) hifen(s) ou x minúsculo no ISBN
      queryResult = mw.smw.ask("[[" .. target .. "#020]]|?Field data#|headers=hide|mainlabel=-")
      local f020 = ""
      if type(queryResult) == "table" then
        for _, row in pairs(queryResult) do
          for _, data in pairs(row) do
            f020 = mw.text.trim(table.concat(data))
          end
        end
      end
      if string.match(f020, "-") then
        info = '* <strong class=\'error\'>O ISBN não pode conter hifens. Apenas números e "X" maiúsculo.</strong>'
        table.insert(infos, info)
      elseif string.match(f020, "x") then
        info =
          '* <strong class=\'error\'>O ISBN não pode conter um x minúsculo. Apenas números e "X" maiúsculo.</strong>'
        table.insert(infos, info)
      end
      -- Testa se há indicadores no campo 020
      if string.sub(f020, 1, 1) ~= "#" then
        info =
          "* <strong class='error'>O primeiro indicador do campo 020 foi preenchido, porém, ele não deve ser preenchido.</strong>"
        table.insert(infos, info)
      end
      if string.sub(f020, 2, 2) ~= "#" then
        info =
          "* <strong class='error'>O segundo indicador do campo 020 foi preenchido, porém, ele não deve ser preenchido.</strong>"
        table.insert(infos, info)
      end
    end
    -- Testa o uso de maiúsculas no campo 041
    test = frame:expandTemplate {title = "Exist", args = {"041"}} or false
    if test ~= "" then
      test = frame:expandTemplate {title = "Field data string", args = {"041", "0", "1"}} or false
      if test == "#" then
        info = "* <strong class='error'>Talvez o primeiro indicador do campo 041 tenha sido esquecido.</strong>"
        table.insert(infos, info)
      end
      test = frame:expandTemplate {title = "Select", args = {"041", "a"}} or false
      if string.match(test, "^[A-Z]") then
        info = "* <strong class='error'>O uso de maiúsculas não é permitido nos códigos de idioma (campo 041).</strong>"
        table.insert(infos, info)
      end
    end
    -- Verifica a presença de pontos de acesso principais 1XX
    -- TODO: trocar callParserFunction por mw.smw.ask
    -- queryResult = mw.smw.ask( '[[' .. target .. '#100||' .. target .. '#110||' .. target .. '#111||' .. target .. '#130]]' )
    local accessPointPresence =
      frame:callParserFunction {
      name = "#ask:[[" .. target .. "#100||" .. target .. "#110||" .. target .. "#111||" .. target .. "#130]]",
      args = {"?Field data", format = "count", mainlabel = "-"}
    }
    -- A seguir, testa se há subcampo $b e se há espaço no subcampo $c do campo 090
    test = frame:expandTemplate {title = "Exist", args = {"090"}} or false
    if test ~= "" then
      test = frame:expandTemplate {title = "Select", args = {"090", "b"}} or false
      if test == "" then
        info = "* <strong class='error'>Está faltando o subcampo $b do campo 090 (notação de Cutter).</strong>"
        table.insert(infos, info)
      end
      -- A seguir, testa se não foi esquecida a letra do tíulo na notação de Cutter, caso haja um ponto de acesso 1XX
      if tonumber(accessPointPresence) >= 1 and string.match(test, "[0-9]$") then
        info = "* <strong class='error'>Falta a letra do título na notação de Cutter.</strong>"
        table.insert(infos, info)
      end
      test = frame:expandTemplate {title = "Select", args = {"090", "c"}} or false
      if string.match(test, "%sed") then
        info =
          "* <strong class='error'>Nossa política de catalogação proíbe espaços na indicação de edição no número de chamada (090 $c).</strong>"
        table.insert(infos, info)
      end
    end
    -- A seguir, testa (conta) se existe mais de um ponto de acesso principal
    local f100existance = frame:expandTemplate {title = "Exist", args = {"100"}}
    if tonumber(accessPointPresence) > 1 or f100existance == "multiple" then
      info =
        "* <strong class='error'>Foi registrado '''mais de um ponto de acesso principal'''. Isso não é permitido.</strong>"
      table.insert(infos, info)
    end
    if f100existance ~= "" then
      f100 = frame:expandTemplate {title = "Field data string", args = {"100", "0", "0"}}
      info = "* O ponto de acesso principal foi dado a uma '''pessoa'''"
      if f100:sub(1, 1) == "0" then
        info = info .. " e a entrada começa pelo seu '''primeiro nome'''."
        table.insert(infos, info)
      elseif f100:sub(1, 1) == "1" then
        info = info .. " e a entrada começa pelo seu '''sobrenome'''."
        table.insert(infos, info)
      elseif f100:sub(1, 1) == "3" then
        info = info .. " e a entrada começa pelo seu '''nome de família'''."
        table.insert(infos, info)
      elseif f100:sub(1, 1) == "#" then
        info = info .. ", porém, <strong class='error'>o primeiro indicador não foi preenchido.</strong>"
        table.insert(infos, info)
      elseif
        f100:sub(1, 1) == "2" or f100:sub(1, 1) == "4" or f100:sub(1, 1) == "5" or f100:sub(1, 1) == "6" or
          f100:sub(1, 1) == "7" or
          f100:sub(1, 1) == "8" or
          f100:sub(1, 1) == "9"
       then
        info = info .. ", porém, <strong class='error'>o primeiro indicador foi preenchido incorretamente.</strong>"
        table.insert(infos, info)
      end
      if f100:sub(2, 2) ~= "#" then
        info =
          "* <strong class='error'>O segundo indicador do campo 100 foi preenchido, porém, ele não deve ser preenchido.</strong>"
        table.insert(infos, info)
      end
      -- Testa se existe ", " no subcampo $a (Nome, Sobrenome)
      local f100a = frame:expandTemplate {title = "Select", args = {"100", "a"}}
      if f100a ~= "" then
        if not string.match(f100a, ".-,.") then
          info =
            "* <strong class='error'>Em pontos de acesso, o nome pessoal deve ser invertido (Nome, Sobrenome). Verifique o campo 100.</strong>"
          table.insert(infos, info)
        end
        if string.match(f100a, "[a-zÀ-ü],[A-ZÀ-ü]") then
          info = "* <strong class='error'>Falta espaço após a vírgula. Verifique o campo 100.</strong>"
          table.insert(infos, info)
        end
      end
      local f100q = frame:expandTemplate {title = "Select", args = {"100", "q"}}
      if f100q ~= "" then
        if not string.match(f100q, "^%(") then
          info = "* <strong class='error'>O subcampo $q do campo 100 necessita parênteses.</strong>"
          table.insert(infos, info)
        end
      end
      local f100d = frame:expandTemplate {title = "Select", args = {"100", "d"}}
      if f100d ~= "" then
        if string.match(f100, "%$d %d%d%d%d$") then
          info = "* <strong class='error'>O subcampo $d do campo 100 necessita hífen.</strong>"
          table.insert(infos, info)
        end
      end
    end
    -- A seguir, testa se existe um ponto de acesso principal 110
    local f110existance = frame:expandTemplate {title = "Exist", args = {"110"}}
    if f110existance ~= "" then
      local f110 = frame:expandTemplate {title = "Field data string", args = {"110", "0", "0"}} or ""
      info = "* O ponto de acesso principal foi dado a uma '''entidade coletiva'''"
      if f110:sub(1, 1) == "0" then
        info = info .. " e a entrada começa por um '''nome invertido'''."
        table.insert(infos, info)
      elseif f110:sub(1, 1) == "1" then
        info = info .. " e a entrada começa por um '''nome de jurisdição'''."
        table.insert(infos, info)
      elseif f110:sub(1, 1) == "2" then
        info = info .. " e a entrada começa por um '''nome em ordem direta'''."
        table.insert(infos, info)
      elseif f110:sub(1, 1) == "#" then
        info = info .. ", porém, <strong class='error'>o primeiro indicador não foi preenchido.</strong>"
        table.insert(infos, info)
      elseif
        f110:sub(1, 1) == "3" or f110:sub(1, 1) == "4" or f110:sub(1, 1) == "5" or f110:sub(1, 1) == "6" or
          f110:sub(1, 1) == "7" or
          f110:sub(1, 1) == "8" or
          f110:sub(1, 1) == "9"
       then
        info = info .. ", porém, <strong class='error'>o primeiro indicador foi preenchido incorretamente.</strong>"
        table.insert(infos, info)
      end
      if f110:sub(2, 2) ~= "#" then
        info =
          "* <strong class='error'>O segundo indicador do campo 110 foi preenchido, porém, ele não deve ser preenchido.</strong>"
        table.insert(infos, info)
      end
    end
  --[[
      --]]
  end -- end if 245
  return table.concat(infos, "\n"), "m" .. f100:sub(2, 2) .. "m"
end

return p