<%@ language = "JavaScript" %>
<% /*
     $Revision$
     $Id$

    File:        fac_faq_list.asp
    Status:      prototype
    Description: zoekt op basis van de zoekvelden in de kennisbank
    Parameters:  search: zoekstring
                 urole: voor FO is meer info beschikbaar dan voor de fe (default)
                        op basis van fac_faq_level
    Context:     Vanuit fac_faq_search.asp
    */
%>
<!--#include file="../Shared/common.inc" -->
<!--#include file="../Shared/getkenmerksql.inc" -->
<!--#include file="../Shared/resultset_table_v2.inc" -->
<!--#include file="fac.inc" -->

<%
FCLTHeader.Requires({js: []});

var faqnum = getQParamInt("faqnum", -1, true);
var searchtext = getQParam("searchtext", null);
var chksearchtextOR = getQParamInt("chksearchtextOR", 0) == 1; // boolean zoeken in tekst met OR

var faq_disc_key_arr = getQParamKeyArray("faq_disc", []); // Kennisbank catalogus
var mld_disc_key_arr = getQParamKeyArray("mld_disc", []); // Productgroep
var stdm_key_arr = getQParamKeyArray("stdmmulti", []); // Melding (Stdmelding)
var loc_key = getQParamInt("locatiekey", -1); // Locatie
var bld_key = getQParamInt("gebouwkey", -1); // Gebouw
var flr_key = getQParamInt("verdiepingkey", -1); // Verdieping
var room_key = getQParamInt("ruimtekey", -1); // Ruimte
var fac_faq_level = getQParamInt("fac_faq_level", -1); // Zichtbaar voor
var fac_faq_lang = getQParam("fac_faq_lang", null); // Taal
if (fac_faq_lang == "-1") fac_faq_lang = null;
var wijzigdate_from = getQParamDate("wijzigdate_from", null);
var wijzigdate_to = getQParamDate("wijzigdate_to", null);

faq_disc_key_arr = (faq_disc_key_arr.length > 0 ? faq_disc_key_arr : null);
mld_disc_key_arr = (mld_disc_key_arr.length > 0 ? mld_disc_key_arr : null);
stdm_key_arr = (stdm_key_arr.length > 0 ? stdm_key_arr : null);

var params = {searchtext: searchtext,
              faq_disc_key_arr: faq_disc_key_arr,
              mld_disc_key_arr: mld_disc_key_arr,
              stdm_key_arr: stdm_key_arr,
              fac_faq_level: fac_faq_level,
              fac_faq_lang: fac_faq_lang};

var urole = getQParamSafe("urole", "fe");
var fronto = (urole == "fo");
var outputmode = getQParamInt("outputmode", 0); //  0 = screen, 1 = print, 2 = excel etc
var print = (outputmode == 1 || outputmode == 5);
var excel = (outputmode == 2 || outputmode == 6);
var showall = getQParamInt("showall", 0) == 1;
var wholeword = getQParam("wholeword", "off") == "on";
var faq_terminated = getQParam("faq_terminated", "off") == "on";

var authparamsUSE = user.checkAutorisation("WEB_FAQUSE", true); // Frontend mag ingevoerde items bekijken (eigen items).
var authparamsFOF = user.checkAutorisation("WEB_FAQFOF", true); // Frontoffice mag items aanmaken en bewerken.
var authparamsBOF = user.checkAutorisation("WEB_FAQBOF", true); // Backoffice mag alle items aanmaken, bewerken en publiceren (publicatie datum zetten/aanpassen).

user.checkAutorisation(["WEB_FAQUSE", "WEB_FAQFOF", "WEB_FAQBOF"]);

var this_user = user.func_enabled2("FAQ", {prs_key: user_key, checkOptimistic: true});

function make_faq_list (searchtext, ororand)
{
  var supper = searchtext.toUpperCase();

  var sql = "SELECT f.fac_faq_key"
          + "     , f.fac_faq_question"
          + "     , f.fac_faq_answer"
          + "     , f.fac_faq_datum"
          + "     , f.fac_faq_datum"
          + "     , COALESCE((SELECT MAX(tr.fac_tracking_datum)"
          + "                   FROM fac_tracking tr"
          + "                      , fac_srtnotificatie str"
          + "                  WHERE tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
          + "                    AND tr.fac_tracking_refkey = f.fac_faq_key"
          + "                    AND str.fac_srtnotificatie_xmlnode = 'kennisbank'"
          + "                )"
          + "              , f.fac_faq_wijzigdatum"
          + "               ) wijzigdatum"
          + "     , f.fac_faq_vervaldatum"
          + "     , f.fac_faq_source"
          + "     , f.fac_faq_url"
          + "     , f.fac_faq_lang"
          + "     , f.fac_faq_level"
              + " , (SELECT MIN(" + lcl.xsql('sm.mld_stdmelding_omschrijving', 'sm.mld_stdmelding_key')
              + "              )"
              + "      FROM mld_stdmeldingfaq mf"
              + "         , mld_stdmelding sm"
              + "     WHERE mf.mld_stdmelding_key = sm.mld_stdmelding_key(+)"
              + "       AND mf.fac_faq_key = f.fac_faq_key"
              + "   ) mld_stdmelding_omschrijving"
              + " , (SELECT MIN(CASE"
              + "               WHEN sd.ins_srtdiscipline_prefix IS NULL"
              + "               THEN ''"
              + "               ELSE sd.ins_srtdiscipline_prefix || '-'"
              + "               END"
              + "               ||" + lcl.xsql('m1.ins_discipline_omschrijving', 'm1.ins_discipline_key')
              + "              )"
              + "      FROM mld_v_aanwezigdiscipline m1"
              + "         , ins_srtdiscipline sd"
              + "         , mld_stdmeldingfaq mf"
              + "     WHERE m1.ins_srtdiscipline_key = sd.ins_srtdiscipline_key"
              + "       AND m1.ins_discipline_key = mf.ins_discipline_key"
              + "       AND mf.fac_faq_key = f.fac_faq_key"
              + "   ) vakgroep"
              + " , (SELECT MIN(NVL(o.alg_type, 'L'))"
              + "      FROM alg_v_allonroerendgoed o, alg_algfaq af"
              + "     WHERE af.alg_onroerendgoed_keys = o.alg_onroerendgoed_keys(+)"
              + "       AND af.fac_faq_key = f.fac_faq_key) scope"
              + " , (SELECT MIN(l.alg_locatie_code || "
              + "           DECODE(o.alg_plaatsaanduiding, NULL, NULL, '-' || o.alg_plaatsaanduiding))"
              + "      FROM alg_v_aanweziglocatie l, alg_v_onroerendgoed_gegevens o, alg_algfaq af"
              + "     WHERE af.alg_onroerendgoed_keys = o.alg_onroerendgoed_keys(+)"
              + "       AND af.alg_locatie_key = l.alg_locatie_key"
              + "       AND af.fac_faq_key = f.fac_faq_key) plaats"
          + "     , fac_faq_hint"
              + ",  (SELECT " + S("prs_pers_string") + " naam"
              + "      FROM prs_perslid p"
              + "     WHERE p.prs_perslid_key = f.prs_perslid_key"
              + "   ) aangepastdoor"
          + "     , (SELECT count(*)"
              + "     FROM mld_stdmeldingfaq mf"
              + "    WHERE mf.fac_faq_key = f.fac_faq_key"
              + "   ) mld_stdmelding_count"
          + "     , (SELECT count(*)"
              + "     FROM alg_algfaq af"
              + "    WHERE af.fac_faq_key = f.fac_faq_key"
              + "   ) alg_alg_count"
          + "     , (SELECT itd.ins_discipline_omschrijving"
              + "     FROM ins_tab_discipline itd"
              + "    WHERE itd.ins_discipline_key = f.faq_ins_discipline_key) discipline_omschrijving"
          + "     , 'M:' || CASE WHEN BITAND(f.fac_faq_displaymode, 1)=0 THEN '-' ELSE 'A' END"          // zichtbaar in kb-info blok
              + "        || CASE WHEN BITAND(f.fac_faq_displaymode, 2)=0 THEN '-' ELSE 'P' END ||' '||"  // zichtbaar in pop-up
              + "   'O:' || CASE WHEN BITAND(f.fac_faq_displaymode, 4)=0 THEN '-' ELSE 'A' END"
              + "        || CASE WHEN BITAND(f.fac_faq_displaymode, 8)=0 THEN '-' ELSE 'P' END ||' '||"
              + "   'A:' || CASE WHEN BITAND(f.fac_faq_displaymode,16)=0 THEN '-' ELSE 'A' END"
              + "        || CASE WHEN BITAND(f.fac_faq_displaymode,23)=0 THEN '-' ELSE 'P' END zichtbaar_voor"
          + "  FROM fac_faq f"
          + " WHERE 1 = 1"
          + (!faq_terminated
            ? "   AND (f.fac_faq_vervaldatum IS NULL OR f.fac_faq_vervaldatum > SYSDATE)"
            : "");

  if (!authparamsBOF) {
    sql += " AND (  fac_functie_key IS NULL"
         + "     OR fac_functie_key IN "
         + "        (SELECT DISTINCT fac_functie_key"
         + "           FROM fac_v_webgebruiker"
         + "          WHERE prs_perslid_key = " + user_key
         + "            AND fac_gebruiker_prs_level_read < 9"
         + "            AND fac_gebruiker_alg_level_read < 9"
         + "        )"
         + "     )";
  }

  if (faqnum > 0)
  { // Selectie op nummer negeert alle andere filters
    sql += " AND f.fac_faq_key = " + faqnum;
  }
  else
  {
    if (ororand)
    {
        sql += "   AND (" + fac.createOrOrClause("UPPER(fac_faq_hint)", supper, 0, wholeword)
        if (S("faq_search_hints_only") <= 0)
        {
            sql += "        OR " + fac.createOrOrClause("UPPER(fac_faq_question)", supper, wholeword)
                 + "        OR " + fac.createOrOrClause("UPPER(fac_faq_answer)", supper, wholeword)
                 + "        OR " + fac.createOrOrClause("UPPER(fac_faq_answer2)", supper, wholeword);
        }
        sql += ")";
    }
    else
    {
        var fieldstrarr = ["UPPER(fac_faq_hint)"];
        if (S("faq_search_hints_only") <= 0)
        {
            fieldstrarr.push("UPPER(fac_faq_question)","UPPER(fac_faq_answer)","UPPER(fac_faq_answer2)");
        }
        sql += "   AND " + fac.createOrClause2(fieldstrarr, supper, wholeword);
    }

    if (stdm_key_arr)
      sql += " AND EXISTS (SELECT ''"
                       + "   FROM mld_stdmeldingfaq"
                       + "  WHERE mld_stdmelding_key IN (" + stdm_key_arr + ") "
                       + "    AND fac_faq_key = f.fac_faq_key"
                       + ")";
    else
      if (mld_disc_key_arr)
        sql += " AND EXISTS (SELECT ''"
                         + "   FROM mld_stdmeldingfaq"
                         + "  WHERE ins_discipline_key IN (" + mld_disc_key_arr + ")"
                         + "    AND fac_faq_key = f.fac_faq_key"
                         + ")";

    if (faq_disc_key_arr) {
        sql += " AND faq_ins_discipline_key IN (" + faq_disc_key_arr.join(", ") + ")";
    }

    var sqlOnroer = "";
    if (room_key > -1)
      sqlOnroer = "alg_onroerendgoed_keys = " + room_key
    else if (flr_key > -1)
      sqlOnroer = "alg_onroerendgoed_keys = " + flr_key
    else if (bld_key > -1)
      sqlOnroer = "alg_onroerendgoed_keys = " + bld_key
    else if (loc_key > -1)
      sqlOnroer = "alg_onroerendgoed_keys IS NULL"

    if (sqlOnroer != "")
      sql += " AND EXISTS (SELECT ''"
                       + "   FROM alg_algfaq"
                       + "  WHERE " + sqlOnroer
                       + "    AND alg_locatie_key = " + loc_key
                       + "    AND fac_faq_key = f.fac_faq_key"
                       + ")";

    if (fac_faq_level > 0)
      sql += " AND BITAND(f.fac_faq_level, " + fac_faq_level + ") = " + fac_faq_level;

    if (fac_faq_lang != null)
    {
      sql += " AND f.fac_faq_lang LIKE " + safe.quoted_sql(fac_faq_lang);
    }
    else
    {
      if (!authparamsBOF)
      {
        // Met FAQFOF-rechten op een discipline mag je alleen de kennisbank-items van je eigen taal zien.
        sql += " AND (  f.fac_faq_lang = (CASE WHEN f.faq_ins_discipline_key IN (SELECT fw3.ins_discipline_key"
                                                                            + "    FROM fac_v_webgebruiker fw3"
                                                                            + "       , fac_functie f3"
                                                                            + "   WHERE f3.fac_functie_key = fw3.fac_functie_key"
                                                                            + "     AND f3.fac_functie_code = 'WEB_FAQFOF'"
                                                                            + "     AND fw3.fac_gebruiker_prs_level_read < 9"
                                                                            + "     AND fw3.fac_gebruiker_alg_level_read < 9"
                                                                            + "     AND fw3.prs_perslid_key = " + user_key
                                                                            + " )"
                                       + "     THEN " + safe.quoted_sql(user.lang())
                                       + "     ELSE f.fac_faq_lang"
                                       + " END"
                                       + ")"
             + "     OR f.fac_faq_lang IS NULL"
             + "     )";
      }
    }

    sql += getKenmerkSql("FAQ", "f.fac_faq_key"); // Zoeken op kenmerken, indien geavanceerd ingevuld
  }

  if (wijzigdate_from)
  {
    sql += " AND COALESCE((SELECT MAX(tr.fac_tracking_datum)"
         + "                 FROM fac_tracking tr"
         + "                    , fac_srtnotificatie str"
         + "                WHERE tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
         + "                  AND tr.fac_tracking_refkey = f.fac_faq_key"
         + "                  AND str.fac_srtnotificatie_xmlnode = 'kennisbank'"
         + "              )"
         + "            , f.fac_faq_wijzigdatum"
         + "             ) >= " + wijzigdate_from.beginToSQL();
  }
  if (wijzigdate_to)
  {
    sql += " AND COALESCE((SELECT MAX(tr.fac_tracking_datum)"
         + "                 FROM fac_tracking tr"
         + "                    , fac_srtnotificatie str"
         + "                WHERE tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
         + "                  AND tr.fac_tracking_refkey = f.fac_faq_key"
         + "                  AND str.fac_srtnotificatie_xmlnode = 'kennisbank'"
         + "              )"
         + "            , f.fac_faq_wijzigdatum"
         + "             ) < " + wijzigdate_to.endToSQL();
  }
  // Frontend mag ingevoerde items bekijken.
  // Frontoffice mag items aanmaken en bewerken
  // Backoffice mag ingevoerde items publiceren (publicatie datum zetten/aanpassen).
  // Eigen meldingen mag je ook inzien en bewerken.
  sql += " AND (f.faq_ins_discipline_key IN (SELECT fw.ins_discipline_key"
       + "                                     FROM fac_v_webgebruiker fw"
       + "                                        , fac_functie f2"
       + "                                    WHERE fw.fac_functie_key = f2.fac_functie_key"
       + "                                      AND f2.fac_functie_code IN ('WEB_FAQFOF', 'WEB_FAQBOF', 'WEB_FAQUSE')"
       + "                                      AND fw.fac_gebruiker_prs_level_read <= 9"
       + "                                      AND fw.fac_gebruiker_alg_level_read < 9"
       + "                                      AND fw.prs_perslid_key = " + user_key + ")"
       + "   OR f.prs_perslid_key = " + user_key + ")";

  sql += " AND (    f.faq_ins_discipline_key IN "
      + "             (SELECT ins_discipline_key FROM fac_v_webgebruiker"
      + "                WHERE prs_perslid_key = " + user_key
      + "                  AND fac_functie_key = " + F("WEB_FAQBOF") + ")"
      + "       OR BITAND (fac_faq_level, 2) = 2" // Zichtbaar frontoffice
      + "          AND f.faq_ins_discipline_key IN "
      + "             (SELECT ins_discipline_key FROM fac_v_webgebruiker"
      + "                WHERE prs_perslid_key = " + user_key
      + "                  AND fac_functie_key = " + F("WEB_FAQFOF") + ")"
      + "       OR BITAND (fac_faq_level, 1) = 1" // Zichtbaar frontend
      + "          AND f.faq_ins_discipline_key IN "
      + "             (SELECT ins_discipline_key FROM fac_v_webgebruiker"
      + "                WHERE prs_perslid_key = " + user_key
      + "                  AND fac_functie_key = " + F("WEB_FAQUSE") + ")"
      + "     )"

  // Welke items zichtbaar zijn voor zelfservice en/of professionals wordt bepaald door fac_faq_level.
  if (!authparamsBOF)
  {
    if (!authparamsFOF)
      sql += " AND (fac_faq_datum < SYSDATE OR prs_perslid_key = " + user_key + ")"; // zelf ingevoerd zie je wel terug.
  }

  sql += " ORDER BY f.fac_faq_rank DESC NULLS LAST"
       + "        , f.fac_faq_datum DESC"
       + "        , f.fac_faq_question";

  function fnQuestion(oRs)
  {
    return "<div class='faqq'>" + safe.html(shared.stripbbcodes(oRs("fac_faq_question").value)) + "</div>";
  }

  function fnLevel(oRs)
  {
      var r = "?";
      switch (oRs("fac_faq_level").value)
      {
          case 1: r = L("lcl_faq_level1"); break;
          case 2: r = L("lcl_faq_level2"); break;
          case 3: r = L("lcl_faq_level3"); break;
      }
      return r;
  }

  function fnSource(oRs)
  {
    var lref = "";
    if (oRs("fac_faq_url").value)
    {
      if (oRs("fac_faq_url").Value.slice(0,4) == "http") // extern
        var url = oRs("fac_faq_url").Value;
      else // in cust subdir
        var url = custpath + "/" + oRs("fac_faq_url").Value;

      lref = "<a target=_new href='" + safe.htmlattr(url) + "'>" + safe.html(oRs("fac_faq_source").value) + "</a>";
    }
    else
      lref = safe.html(oRs("fac_faq_source").value);
    return lref;
  }

  function fnVakgroep(oRs)
  {
    var vakgroep = "";
    if (oRs("mld_stdmelding_count").value > 1)
    {
      vakgroep = L("lcl_faq_stdmelding_m").format(oRs("mld_stdmelding_count").value);
    }
    else
    {
      vakgroep = oRs("vakgroep").value;
    }
    return safe.html(vakgroep);
  }

  function fnStdmelding(oRs)
  {
    var stdmelding = "";
    if (oRs("mld_stdmelding_count").value == 1)
    {
      stdmelding = oRs("mld_stdmelding_omschrijving").value;
    }
    return safe.html(stdmelding);
  }

  function fnScope(oRs)
  {
    var scope = "";
    if (oRs("alg_alg_count").value > 1)
    {
        scope = L("lcl_faq_alg_l").format(oRs("alg_alg_count").value);
    }
    else
    {
        switch (oRs("scope").Value)
        {
            case "L": scope = L("lcl_location"); break;
            case "G": scope = L("lcl_building"); break;
            case "T": scope = L("lcl_terra"); break;
            case "V": scope = L("lcl_floor"); break;
            case "R": scope = L("lcl_room"); break;
        }
    }
    return safe.html(scope);
  }

  function fnPlaats(oRs)
  {
    var plaats = "";
    if (oRs("alg_alg_count").value == 1)
    {
      plaats = oRs("plaats").value;
    }
    return safe.html(plaats);
  }

     var canAdd = authparamsFOF && authparamsFOF.PRSwritelevel < 9 && authparamsFOF.ALGwritelevel < 9;

      buttons = [];
      if (canAdd)
      {
        var addurl = "appl/fac/fac_faq.asp";
        buttons = [{ icon: "fa-plus", title: L("lcl_add"), action: "FcltMgr.openDetail('" + addurl + "', '" + L("lcl_add") + "', {callback: FcltMgr.reload })" }]
      }
      var rst = new ResultsetTable({ sql: sql,
                                     keyColumn: "fac_faq_key",
                                     flexModule: "FAQ",
                                     flexId: "fac_faq_key",
                                     ID: "faqtable",
                                     title: L("lcl_faq_items"),
                                     outputmode: outputmode,
                                     showAll: showall,
                                     filterParams: params,
                                     buttons: buttons
                                    });
      rst.addColumn(new Column({caption: L("lcl_faq_kennisbank_nr"), content: "fac_faq_key", datatype: "number"}));
      rst.addColumn(new Column({hasActions: true, caption: L("lcl_faq_question"), content: fnQuestion}));
      rst.addColumn(new Column({caption: L("lcl_faq_answer"), combine: true, content: "fac_faq_answer"}));
      rst.addColumn(new Column({caption: L("faq_discipline"), content: "discipline_omschrijving"}));

      rst.addColumn(new Column({caption: L("lcl_faq_bron"), content: fnSource}));
      rst.addColumn(new Column({caption: L("lcl_faq_datum"), content: "fac_faq_datum", datatype: "date", nowrap: true}));
      rst.addColumn(new Column({caption: L("lcl_faq_wijzigdatum"), content: "wijzigdatum", datatype: "date", nowrap: true}));

      // BOF altijd, FOF bij printen
      if (authparamsBOF || (authparamsFOF && outputmode != 0))
      {
          rst.addColumn(new Column({caption: L("lcl_vakgroup"), content: fnVakgroep}));
          rst.addColumn(new Column({caption: L("lcl_complain"), content: fnStdmelding, combine: true}));

          rst.addColumn(new Column({caption: L("lcl_faq_alg_scope"), content: fnScope}));
          rst.addColumn(new Column({caption: L("lcl_plaatsgegevens"), content: fnPlaats, combine: true}));

          if (fac_faq_lang == null)
            rst.addColumn(new Column({caption: L("lcl_faq_lang"), content: "fac_faq_lang"}));
          if (fac_faq_level < 0)
            rst.addColumn(new Column({caption: L("lcl_faq_level"), content: fnLevel}));
      }
      if (outputmode != 0 && (authparamsBOF || authparamsFOF))
      { // Met printen wel tonen?
        rst.addColumn(new Column({caption: L("lcl_faq_hint"), content: "fac_faq_hint"}));
        rst.addColumn(new Column({caption: L("lcl_faq_link"), content: "fac_faq_url"}));
        rst.addColumn(new Column({caption: L("lcl_faq_ingevoerd"), content: "aangepastdoor"}));
      }
      rst.addColumn(new Column({caption: L("lcl_faq_vervaldatum"), content: "fac_faq_vervaldatum", datatype: "date", nowrap: true}));
      //rst.addColumn(new Column({caption: "Weergeven bij", content: "zichtbaar_voor", nowrap: true})); // tonen wanneer een kb-item zichtbaar is. hierop kunnen filteren.

      rst.addAction({ action: "faq_edit", caption: L("lcl_edit"), isDefault: true } );
      var cnt = rst.processResultset();

  return cnt;
}
%>
<html>
  <head>
   <% FCLTHeader.Generate({ outputmode: outputmode }); %>
<script>
   function faq_edit(row) {
       var faq_key = row.getAttribute("ROWKEY");

       FcltMgr.openDetail("appl/fac/fac_faq.asp?urole=<%=urole%>&faq_key=" + faq_key, L("lcl_faq_item"));
   }
</script>
</head>
<body id="listbody">
<%
if (searchtext != null)
{
    var cnt = make_faq_list (searchtext, chksearchtextOR);
}
%>
</body>
</html>

<% ASPPAGE_END(); %>
