<% /*
     $Revision$
     $Id$

    File:               prs_perslid_list.inc
    Description:        Show an overview of persons in list-form,
                        which meets with the given requirements
    Parameters:
    Context:            Search action from prs_perslid_search.asp form
    Note:               - Check de sopes nog eens goed?
                        - De kolom WP is soms leeg terwijl er wel een WP is. Virtueel of zo? TODO
*/ %>

<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/getkenmerksql.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"] })

function fnrowData(oRs)
{
  var key = oRs("prs_perslid_key").value;
  var data = {key: key};
  return JSON.stringify(data);
}
%>
<script type="text/javascript">
  var autosearch = 1; // automatisch laden van resultaat op search pagina

  function persoonEdit(row)
  {
    var algData = JSON.parse(row.getAttribute("ROWDATA"));
    var url = "appl/prs/prs_perslid.asp?mode=viewUpdate&key="+algData.key;
    FcltMgr.openDetail(url, L("lcl_person"));
  }

  function doChange(rowArray, isMulti)
  {
      var prsKeyString = getKeyString(rowArray);
      var subject = L("lcl_alg_multi_edit");
      var url = "../prs/prs_edit_perslid_multi.asp?prs_keys=" + prsKeyString;
      FcltMgr.openModalDetail(url, subject, {callback: FcltCallbackRefresh});
  }

  function doDelete(rowArray, isMulti)
  {
    FcltMgr.confirm(L("lcl_alg_del_txt_ruimte"), { autoconfirm: isMulti }, function() {
        var prsKeyString = getKeyString(rowArray);
        var data = {
            key: prsKeyString,
            level: "P"
        };
        <% protectRequest.dataToken("data"); %>
        $.post("prs_delete.asp",
            data,
            FcltCallbackRefresh,
            "json");
    });
  }

  function mandateAdd(rowArray, isMulti)
  {
    var prsKeyString = getKeyString(rowArray);
    var url = "kpn_edit_mandate.asp?modal=1&prs_keys="+prsKeyString;
    var aantalPrs = prsKeyString.split(',').length;
    var title = "[" + aantalPrs + "] " + (aantalPrs == 1 ? L("prs_perslid") : L("prs_perslid_m"));

    FcltMgr.openModalDetail(url, title, { callback: FcltCallbackRefresh});
  }

  function authgroupAdd(rowArray, isMulti)
  {
    var prsKeyArray = getKeyString(rowArray).split(",");
    var aantalPrs = prsKeyArray.length;
    var prsKey = prsKeyArray.shift();
    var url = "../mgt/prs_perslid.asp?mode=edit&model=authorization&person="+prsKey
            + (prsKeyArray.length>0 ? "&prsarr="+prsKeyArray.join(",") : "");
    var title = "[" + aantalPrs + "] " + (aantalPrs == 1 ? L("prs_perslid") : L("prs_perslid_m"));
    FcltMgr.openModalDetail(url, title, {callback: FcltCallbackRefresh});
  }

</script>
<%

function perslid_list(pautfunction, params)
{
  // De functie checkAutorisation(autfunction) geeft een Response.End indien er geen autorisatie voor autfunction wordt gevonden
  var addButton = [];

  var autfunction = "WEB_PRSUSE";
  var authparams = user.checkAutorisation(autfunction);

  var authparamsPRSMAN = user.checkAutorisation("WEB_PRSMAN", true);
  var authparamsFINMSU = user.checkAutorisation("WEB_FINMSU", true);
  var authparamsFACMAN = user.checkAutorisation("WEB_FACMAN", true);
  var authparamsPRSSYS = user.checkAutorisation("WEB_PRSSYS", true);
  var authparamsPRSMSU = user.checkAutorisation("WEB_PRSMSU", true);
  var canImport = (user.checkAutorisation("WEB_IMPORT", true) != null);
  var canAdd = (authparamsPRSMAN && authparamsPRSMAN.ALGwritelevel < 9 && authparamsPRSMAN.PRSwritelevel < 9);
  var canMultiAdd = ((authparamsFINMSU && authparamsFINMSU.ALGwritelevel < 9) ||
                     (authparamsFACMAN && authparamsFACMAN.PRSwritelevel < 9));
  var canMultiAut = (authparamsPRSSYS || (authparamsPRSMSU && authparamsPRSMSU.PRSwritelevel < 9));

  // Voor resulttable de globalen zetten; zou ng anders moeten.
  var outputmode = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var showall = params.showall;

  var dis_key = params.dis_key;
  var loc_key = params.loc_key;
  var bld_key = params.bld_key;

  var prsName = params.prsName;
  var prsFirstName = params.prsFirstName;
  var prsNR =  params.prsNR;
  var prsEnddate = params.prsEnddate;
  var prsLogin = params.prsLogin;
  var prsEmail = params.prsEmail;
  var profiel_key = params.profiel_key;
  var func = params.func;
  var dept = params.dept;
  var bdr_key = params.bdr_key;
  var altloc = params.altloc;
  var apionly = params.apionly;
  var unconfirmed_users = params.unconfirmedUsers

  function fnrowActionEnabler(oRs)
  {
    /*  var eDelete = false;
      if (alg.canWriteRuimte(oRs("alg_ruimte_key").value, authparams.mALGwritelevel)) */
      var eChange = true;
      var eDelete = true;
      var eMandate = false; // alleen multi
      var eAuthgroup = true;

      return {eChange: eChange,
              eDelete: eDelete,
              eMandate: eMandate,
              eAuthgroup: eAuthgroup
             };
  }
%>

  <html>
    <head>
      <% FCLTHeader.Generate({outputmode: outputmode}) %>
    </head>
    <body id="listbody">
<%
    // Zijn er profielen aanwezig?
    sql = "SELECT count(*) aantal"
        + "  FROM fac_profiel";
    oRs = Oracle.Execute(sql);
    var hasProfiel = (parseInt(oRs('aantal').value) > 0);
    oRs.Close();

    // Fast check to see if we have any listable flex at all, to prevent superfluous column
    var sql = "SELECT "
            + lcl.xsql('k.prs_kenmerk_omschrijving', 'k.prs_kenmerk_key') +" prs_kenmerk_omschrijving  "
            + "     , k.prs_kenmerk_kenmerktype"
            + "  FROM prs_kenmerk k"
            + " WHERE BITAND (prs_kenmerk_inlijst, 1) = 1"
            + "   AND BITAND (prs_kenmerk_systeem, 4) = 0"  // niet als vertrouwelijk
            + "   AND k.prs_kenmerk_niveau = 'P'"
            + "   AND k.prs_kenmerk_verwijder IS NULL";
    var oRs = Oracle.Execute(sql);
    var anyflex = !oRs.eof;
    if (anyflex)
      {
          var multiflex = false;
          var bijlageflex = (oRs("prs_kenmerk_kenmerktype").Value == "M");
          var flexlabel = oRs("prs_kenmerk_omschrijving").Value;
          oRs.MoveNext();
          if (!oRs.Eof)
          {
              multiflex = true;
              flexlabel = L("lcl_flexlist");

              while (!oRs.eof)
              {
                  if (oRs("prs_kenmerk_kenmerktype").Value == "M")
                      bijlageflex = true;
                  oRs.MoveNext();
              }
          }
      }
      oRs.close();

    // is distinct echt vereist? dan zeggen waarom: ik denk omdat afdeling_boom ervoor zorgt dat een persoon
    // meerdere keren in het resultaat komt, en de distinct dus nodig is.
      var sqln = "SELECT DISTINCT p.prs_perslid_key"
               + "     , pf.prs_perslid_naam_full"
               + "     , p.prs_perslid_nr"
               + "     , " + S("prs_dep_string") + " organisatie"
               + "     , COALESCE (p.prs_perslid_telefoonnr, ' ') telefoon"
               + "     , COALESCE (" + lcl.xsql("srt_p.prs_srtperslid_omschrijving", "srt_p.prs_srtperslid_key") + ", ' ') functie"
               + "     , p.prs_perslid_upper"
               + "     , wp.alg_ruimte_aanduiding"
                 + (altloc
                   ? ""
                   : " || DECODE (hwp.aantal,1,'','...') alg_ruimte_aanduiding")
               + "     , wp.prs_werkplek_aanduiding"
                 + (altloc
                   ? ""
                   : " || DECODE (hwp.aantal,1,'','...') prs_werkplek_aanduiding")
               + "     , l.alg_locatie_omschrijving"
               + "     , p.prs_perslid_mobiel"
               + "     , p.prs_perslid_email"
               + "     , p.prs_perslid_titel"
               + "     , p.prs_perslid_login"
               + "     , COALESCE(p.prs_perslid_oslogin2, prs_perslid_oslogin) prs_perslid_oslogin"
               + "     , fp.fac_profiel_omschrijving"
               + "     , (SELECT kp.prs_kostenplaats_nr"
                    + "     FROM prs_kostenplaats kp"
                    + "    WHERE kp.prs_kostenplaats_key = COALESCE(p.prs_kostenplaats_key, d.prs_kostenplaats_key)"
                    + "  ) prs_kostenplaats_nr"
               + "     , (SELECT prs_perslid_naam_friendly FROM prs_v_perslid_fullnames_all pf WHERE pf.prs_perslid_key = p.prs_perslid_key_verantw) prs_perslid_verantw"
                + (anyflex
                    ? ", (SELECT LISTAGG("
                      + (multiflex ? lcl.xsql("k.prs_kenmerk_omschrijving", "k.prs_kenmerk_key")
                            + " || ':'|| CHR(160) ||"
                          : "")
                      + "            CASE"
                      + "            WHEN k.prs_kenmerk_kenmerktype = 'R' OR k.prs_kenmerk_kenmerktype = 'r' OR k.prs_kenmerk_kenmerktype = 'S'"
                      + "            THEN flx.getdomeinwaarde (k.fac_kenmerkdomein_key, km.prs_kenmerklink_waarde)"
                      + "            WHEN k.prs_kenmerk_kenmerktype = 'N'"
                      + "             AND k.prs_kenmerk_lengte = 1 "
                      + "             AND k.prs_kenmerk_nmin = 0 "
                      + "             AND k.prs_kenmerk_nmax = 1 "
                      + "             AND (k.prs_kenmerk_dec = 0 OR k.prs_kenmerk_dec IS NULL) "
                      + "            THEN DECODE (km.prs_kenmerklink_waarde, "
                      + "                         0, "+safe.qL("lcl_check_0")+", "
                      + "                         1, "+safe.qL("lcl_check_1")+", "
                      + "                         km.prs_kenmerklink_waarde)"
                      + "            ELSE km.prs_kenmerklink_waarde"
                      + "            END, CHR(13)) "
                      + "           WITHIN GROUP (ORDER BY prs_kenmerk_volgnr) "
                      + "  FROM prs_kenmerk k, prs_kenmerklink km"
                      + " WHERE km.prs_link_key = p.prs_perslid_key"
                      + "   AND k.prs_kenmerk_key = km.prs_kenmerk_key"
                      + "   AND BITAND(k.prs_kenmerk_inlijst,1) = 1"
                      + "   AND BITAND(k.prs_kenmerk_systeem,4) = 0"  // niet als vertrouwelijk
                      + "   AND k.prs_kenmerk_niveau='P'"
                      + "   AND k.prs_kenmerk_verwijder IS NULL"
                      + "   AND km.prs_kenmerklink_verwijder IS NULL) flex"
                  : "")
               + "  FROM prs_v_aanwezigperslid p"
               + (dept
                 ? "     , prs_v_afdeling_familie bm"
                 : "")
               + "     , prs_v_perslid_fullnames pf"
               + "     , prs_v_afdeling d"
               + "     , prs_srtperslid srt_p"
               + (altloc
                 ? "   , prs_perslidwerkplek hwp"
                 : "   , prs_v_hoofdperslidwerkplek hwp")
               + "     , prs_v_werkplek_gegevens wp"
               + "     , alg_locatie l"
               + "     , fac_profiel fp"
               + " WHERE d.prs_afdeling_key = p.prs_afdeling_key"
               + (dept
                 ? " AND p.prs_afdeling_key = bm.prs_afdeling_key"
                 : "")
               + "   AND srt_p.prs_srtperslid_key = p.prs_srtperslid_key"
               + "   AND pf.prs_perslid_key = p.prs_perslid_key"
               + "   AND l.alg_locatie_key(+) = wp.alg_locatie_key"
               + "   AND wp.prs_werkplek_key(+) = hwp.prs_werkplek_key"
               + "   AND hwp.prs_perslid_key(+) = p.prs_perslid_key"
               + "   AND p.prs_perslid_verwijder IS NULL"
               + "   AND p.fac_profiel_key = fp.fac_profiel_key (+)";

      if (authparams.ALGreadlevel > -1)
      {  // Er is een scope-beperking van kracht
        if (loc_key)
        {
          sqln += " AND l.ALG_DISTRICT_KEY IN "
               +  " (SELECT alg_district_key FROM fac_v_my_districts "
               +   "WHERE prs_perslid_key="+user_key
               +    " AND niveau=" + authparams.ALGreadlevel + ")";
        }

        if (bld_key)
        {
          sqln += " AND l.ALG_LOCATIE_KEY IN "
               +  " (SELECT alg_locatie_key FROM fac_v_my_locations "
               +  " WHERE prs_perslid_key="+user_key
               +  " AND niveau=" + authparams.ALGreadlevel + ")";
        }

        sqln += " AND wp.ALG_GEBOUW_KEY IN "
             +  " (SELECT alg_gebouw_key FROM fac_v_my_buildings "
  	         +  " WHERE prs_perslid_key="+user_key
  	         +  " AND niveau=" + authparams.ALGreadlevel + ")";
      }

      if (authparams.PRSreadlevel > 0)
      {
        sqln += " AND d.prs_afdeling_key IN "
             +  "    (SELECT prs_afdeling_key FROM prs_v_afdeling_familie a"
             +  "      WHERE a.prs_afdeling_elder_key IN"
             +  "        (SELECT aa.prs_afdeling_elder_key"
             +  "           FROM prs_v_afdeling_familie aa"
             +  "          WHERE aa.prs_afdeling_key = " + user.prs_afdeling_key()
             +  "            AND aa.niveau = " + authparams.PRSreadlevel + "))";
      }

      if (authparams.PRSreadlevel == 0) // (PRSreadlevel == 0) ==> prs_bedrijf
      {
        sqln += " AND d.prs_afdeling_key IN "
             +  " (SELECT a.prs_afdeling_key FROM prs_v_afdeling a "
  	         +  " WHERE a.prs_bedrijf_key = " + user.afdeling().prs_bedrijf_key() + ")";
      }

      sqln += getKenmerkSql("PRS", "p.prs_perslid_key");

      if (bld_key)
      {
        sqln += " AND wp.alg_gebouw_key = " + bld_key;
      }
      else if (loc_key)
      {
        sqln += " AND l.alg_locatie_key = " + loc_key;
      }
      else if (dis_key)
      {
        sqln += " AND l.alg_district_key = " + dis_key;
      }

      if (prsName)
      {
        Oracle.Execute("alter session set nls_comp = 'LINGUISTIC' NLS_SORT = 'BINARY_AI'"); // Zodat müller gevonden wordt
        sqln += " AND p.prs_perslid_upper LIKE " + safe.quoted_sql_wild(prsName + "%");
      }

      if (prsFirstName)
      {
        Oracle.Execute("alter session set nls_comp = 'LINGUISTIC' NLS_SORT = 'BINARY_AI'"); // Zodat müller gevonden wordt
        sqln += " AND p.prs_perslid_voornaam LIKE " + safe.quoted_sql_wild(prsFirstName + "%");
      }

      if (prsEnddate)
      {
        sqln += " AND p.prs_perslid_einddatum <= " + prsEnddate.endToSQL()
      }

      if (prsLogin)
      {
        sqln += " AND (p.prs_perslid_oslogin LIKE " + safe.quoted_sql_wild(prsLogin + "%")
             + "   OR (p.prs_perslid_oslogin2 LIKE " + safe.quoted_sql_wild(prsLogin + "%")
             + "       AND NOT EXISTS (SELECT p2.prs_perslid_oslogin "
             + "                         FROM prs_perslid p2 "
             + "                        WHERE p2.prs_perslid_oslogin = p.prs_perslid_oslogin2))) ";
      }

      if (prsEmail)
      {
        sqln += " AND UPPER(p.prs_perslid_email) LIKE " + safe.quoted_sql_wild(prsEmail + "%");
      }

      if (func)
      {
        sqln += " AND p.prs_srtperslid_key = " + func;
      }

      if (prsNR)
      {
        sqln += " AND UPPER(p.prs_perslid_nr) LIKE " + safe.quoted_sql_wild(prsNR + "%")
      }

      if (dept)
      {
        sqln += " AND bm.prs_afdeling_elder_key = " + dept;
      }

      if (bdr_key)
      {
        sqln += " AND d.prs_bedrijf_key = " + bdr_key;
      }

      if (profiel_key)
      {
        sqln += " AND fp.fac_profiel_key = " + profiel_key;
      }

      if (!inactief)
        sqln += " AND p.prs_perslid_inactief IS NULL";
      else
        sqln += " AND p.prs_perslid_inactief IS NOT NULL";

      if (apionly)
        sqln += " AND (p.prs_perslid_apikey IS NOT NULL OR p.prs_perslid_systeemadres IS NOT NULL)";

      if (unconfirmed_users)
        sqln += " AND BITAND (prs_perslid_flags, 2) = 2";

      sqln += " ORDER BY pf.prs_perslid_naam_full";

      function fncolFlexBijlagen(oRs)
      {
        var flexval = oRs("flex").Value;
        var bijlagen_aantal = 0;
        if (bijlageflex)
        {
            var prs_key = oRs("prs_perslid_key").Value;
            var bijlagen_oms = "";
            var bijlagen_lijst = [];

            var sql = "SELECT k.prs_kenmerk_key, "
                    + lcl.xsql("k.prs_kenmerk_omschrijving", "k.prs_kenmerk_key")
                    + "     , CASE"
                    + "       WHEN BITAND(k.prs_kenmerk_inlijst,1) = 1"
                      + "     THEN 1"
                      + "     ELSE 0"
                    + "       END in_overzicht_tonen"
                    + "  FROM prs_kenmerk k"
                    + " WHERE k.prs_kenmerk_niveau='P'"
                    + "   AND k.prs_kenmerk_kenmerktype = 'M'"
                    + "   AND k.prs_kenmerk_verwijder IS NULL";
            var oRs_k = Oracle.Execute(sql);

            while (!oRs_k.eof)
            {
                if (oRs_k("in_overzicht_tonen").Value == 1)
                {
                    var kenmerk_key = oRs_k("prs_kenmerk_key").Value;
                    var bijlagen_oms = oRs_k("prs_kenmerk_omschrijving").Value;
                    var bestanden = flexProps("PRS", prs_key, kenmerk_key, "P", {getFiles: true});
                    var km_aantal = bestanden.files.length;
                    for (i=0; i<km_aantal; i++)
                    {
                        bijlagen_lijst.push(bestanden.files[i].name);
                    }
                    bijlagen_aantal += km_aantal;
                }
                oRs_k.MoveNext();
            }

            oRs_k.Close();
        }
        return (flexval ? safe.html(flexval.replace(/\r/g, "\n")+ "\n") : "")
             + ( bijlagen_aantal > 0
               ?   "<span title='" +  safe.htmlattr(bijlagen_lijst.join("\n"))  + "'>"
                 + safe.html(bijlagen_oms) + ": " + bijlagen_aantal
                 + "</span>"
               : ""
               );
      }

      var addurl = "appl/prs/prs_perslid.asp";
      if (canAdd)
      {
        addButton = [{ icon: "fa-plus", title: L("lcl_add"), action: "FcltMgr.openDetail('" + addurl + "', '" + safe.jsstring(L("lcl_add")) + "')" }]
      }

      var rst = new ResultsetTable({sql: sqln,
                                     keyColumn: "prs_perslid_key",
                                     ID: "prstable",
                                     showAll: showall,
                                     rowData: fnrowData,
                                     rowActionEnabler: fnrowActionEnabler,
                                     outputmode: outputmode,
                                     title: L("lcl_search_pers"),
                                     flexModule: "PRS",
                                     flexId: "prs_perslid_key",
                                     filterParams: params,
                                    //  roundtripCode: (canImport ? "PERSLID" : ""),
                                     buttons: addButton
                                    });

      rst.addColumn(new Column({caption: L("lcl_prs_person_name"), content: "prs_perslid_naam_full"}));
      rst.addColumn(new Column({caption: L("lcl_prs_person_nr"), content: "prs_perslid_nr"}));
      rst.addColumn(new Column({caption: L("lcl_prs_organisatie"), content: "organisatie"}));
      rst.addColumn(new Column({caption: L("lcl_prs_person_function"), content: "functie"}));
      rst.addColumn(new Column({caption: L("lcl_prs_dept_kosten"), content: "prs_kostenplaats_nr"}));
      if (hasProfiel)
      {
        rst.addColumn(new Column({caption: L("lcl_prs_profile"), content: "fac_profiel_omschrijving", combine:true}));
      }
      if (S("prs_hide_fixed_fields") == 0) {
        rst.addColumn(new Column({caption: L("lcl_prs_person_phone"), content: "telefoon"}));
      }
      rst.addColumn(new Column({caption: L("lcl_prs_person_verantw"), content: "prs_perslid_verantw"}));
      if (outputmode != 0)
        rst.addColumn(new Column({caption: L("lcl_location"), content: "alg_locatie_omschrijving"}));
      rst.addColumn(new Column({caption: ( S("prs_werkplek_implicit")==1 ? L("lcl_workplace") : L("lcl_workplace")),
                                    content: ( S("prs_werkplek_implicit")==1 ? "alg_ruimte_aanduiding": "prs_werkplek_aanduiding")}));
      if (user.has("WEB_PRSSYS"))
      {
        rst.addColumn(new Column({caption: L("lcl_prs_person_login"), content: "prs_perslid_oslogin"}));
        rst.addColumn(new Column({caption: L("lcl_prs_person_lastlogin"), content: "prs_perslid_login"}));
      }
      rst.addColumn(new Column({caption: L("lcl_prs_person_mobile"), content: "prs_perslid_mobiel", purpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_prs_person_email"), content: "prs_perslid_email", purpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_prs_person_title"), content: "prs_perslid_titel", purpose: PRINTING_ONLY}));
      if (anyflex)
      {
        rst.addColumn(new Column({caption: flexlabel, content: fncolFlexBijlagen, colName: "fncolFlexBijlagen" }));
      }

      rst.addAction({ action: "persoonEdit", caption: L("lcl_edit"), isDefault: true});
      rst.addAction({ action: "doChange", caption: L("lcl_change"), enabler: "eChange", single: false, multi: true, multiOnce: true});
      if (canAdd)
          rst.addAction({ action: "doDelete", caption: L("lcl_delete"), enabler: "eDelete", single: false, multi: true, multiOnce: true});
      if (canMultiAdd)
          rst.addAction({ action: "mandateAdd", caption: L("lcl_prs_mandatering"), enabler: "eMandate", single: false, multi: true, multiOnce: true});
      if (canMultiAut)
          rst.addAction({ action: "authgroupAdd", caption: L("fac_groep"), enabler: "eAuthgroup", single: false, multi: true, multiOnce: true});
      var cnt = rst.processResultset();
%>
    </body>
  </html>
<%
}
%>

