<% /*
     $Revision$
     $Id$
     File:               cnt_list.inc
     Description:        Show an overview of contracts in list-form,
                         which meets with the given requirements
     Parameters:
         urole           user role (fe, fo, bo, mi)
         outputmode      behave in an output mode, print to 0 = screen, 1 = printer, 2 = excel, etc.
         showall         show all orders which meets with the given requirements
         cntsrt_key      search for contracts with the given contractsoort key (discipline key)
         cntnum          search for contracts with the given cnt number
         dienst_key      search for contracts with the given dienst_key
         uitvoerder_key  search for contracts with the given uitvoerder_key
         cnt_persoon_key search for contracts with the given cnt_persoon_key (persoon contractpartij)
         eigenaar_key    search for contracts for the selected owner (department)
         beheerder_key   search for contracts with the given beheerder key
         reg_key         search for contracts with the given regio key
         dist_key        search for contracts with the given district key
         loc_key         search for contracts with the given location key
         bld_key         search for contracts with the given building key
         objectsrt_key   search for contracts with the given objectsoort key (srtdeel key)
         ins_key         search for contracts with the given object key
         kp_key          search for contracts with the given kostenplaats key
         ks_key          search for contracts with the given kostensoort key
         mantel_key      search for contracts with the given mantel key
         descript        search for contracts with the given contract text in contract description
         cntNew          search for contracts which are Nieuw
         cntTgoe         search for contracts which are Ter goedkeuring
         cntAct          search for contracts which are Actueel
         cntRap          search for contracts which are In rappel
         cntOpz          search for contracts which are In opzegtermijn
         cntVerl         search for contracts which are Verlopen
         cntFutu         search for contracts which are Toekomstig
         cntInact        search for contracts which are Inactive
     Context:            Search action from cnt_search.asp form
     Note:               PF: ik heb de "mi" mode laten vervallen

*/ %>

<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/getkenmerksql.inc" -->
<!-- #include file="../Shared/discx3d.inc" -->
<!-- #include file="cnt.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["../cnt/cnt_list.js"]
                    });

function cnt_list (pautfunction, params)
{
  // Valid and supported parameters are:
  // params.urole          : the usuals two-letter lowercase string
  // params.outputmode     : print to 0 = screen, 1 = printer, 2 = excel, etc.
  // params.showall        : boolean (true | false)
  // params.cntsrt_key     : key
  // params.cntnum         : tekst
  // params.dienst_key     : key
  // params.uitvoerder_key : key
  // params.cnt_persoon_key: key
  // params.eigenaar_key   : key
  // params.manager_key    : key
  // params.beheerder_key  : key
  // params.reg_key        : key
  // params.dist_key       : key
  // params.loc_key        : key
  // params.bld_key        : key
  // params.objectsrt_key  : key
  // params.cntsrt_key     : key
  // params.mantel_key     : key
  // params.descript       : wildcard string
  // params.cntAct         : boolean (true | false)
  // params.cntInact       : boolean (true | false)
  // params.cntNew         : boolean (true | false)
  // params.cntTgoe        : boolean (true | false)
  // params.cntFFutu       : boolean (true | false)
  // params.cntFAct        : boolean (true | false)
  // params.cntFRap        : boolean (true | false)
  // params.cntFOpz        : boolean (true | false)
  // params.cntFVerl       : boolean (true | false)

  var authparamsCNTUSE = user.checkAutorisation("WEB_CNTUSE", true);
  var authparamsCNTMAN = user.checkAutorisation("WEB_CNTMAN", true);
  var authparamsCNTMSU = user.checkAutorisation("WEB_CNTMSU", true);

  var urole = params.urole;
  var fronto = (urole == "fo");
  var backo = (urole == "bo");
  var minfo = (urole == "mi"); // NOT APPLICABLE?
  var frontend = (urole == "fe" || (!fronto & !backo & !minfo));

  var outputmode = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var print = (outputmode == 1 || outputmode == 5);
  var excel = (outputmode == 2 || outputmode == 6);
  var showall = params.showall;

  var cntsrt_key = params.cntsrt_key;
  var cntnum = params.cntnum;
  var dienst_key = params.dienst_key;
  var uitvoerder_key = params.uitvoerder_key;
  var cnt_persoon_key = params.cnt_persoon_key;
  var eigenaar_key = params.eigenaar_key;
  var manager_key = params.manager_key;
  var beheerder_key = params.beheerder_key;
  var reg_key = params.reg_key;
  var dist_key = params.dist_key;
  var loc_key = params.loc_key;
  var bld_key = params.bld_key;
  var objectsrt_key = params.objectsrt_key;
  var mantel_key = params.mantel_key;
  var descript = params.descript;
  var ins_key = params.ins_key;
  var kp_key = params.kp_key;
  var ksgrp_key = params.ksgrp_key;
  var ks_key = params.ks_key;
  // Statussen.
  var cntAct = params.cntAct;
  var cntInact = params.cntInact;
  var cntNew = params.cntNew;
  var cntTgoe = params.cntTgoe;
  // Fases binnen status Acief
  var cntFFutu = params.cntFFutu;
  var cntFAct = params.cntFAct;
  var cntFRap = params.cntFRap;
  var cntFOpz = params.cntFOpz;
  var cntFVerl = params.cntFVerl;
%>

  <html>
    <head>
<%
      FCLTHeader.Generate({ outputmode: outputmode });
%>
      <script type="text/javascript">
        // Text strings used by cnt_list.js
        var urole = "<%=urole%>";
      </script>
    </head>
    <body id="listbody">
<%
      var tbl = new Array();
      var dts = new Array();

      // Voeg laatste tracking datum toe
      sqltrack = ", (SELECT MAX(t.fac_tracking_datum)"
               + "     FROM fac_tracking t"
               + "        , fac_srtnotificatie sn"
               + "    WHERE t.fac_srtnotificatie_key = sn.fac_srtnotificatie_key"
               + "      AND t.fac_tracking_refkey = c.cnt_contract_key" // contract key uit "sql"
               + "      AND sn.fac_srtnotificatie_xmlnode = 'contract') recentdatum";

      sql = "SELECT c.cnt_contract_nummer"
          + "     , c.cnt_contract_versie"
          + "     , c.cnt_contract_omschrijving"
          + "     , c.cnt_contract_document"
          + "     , COALESCE(b.prs_bedrijf_naam, af" + S("prs_dep_string") + ", " + S("prs_pers_string") + ") uitvoerder" // af" + S("prs_dep_string") heeft parameter afd.
          + "     , " + S("prs_dep_string") + " eigenaar"
          + "     , c.cnt_contract_looptijd_van begindatum"
          + "     , c.cnt_contract_looptijd_tot einddatum"
          + "     , cnt.cnt_getOpzegdatum(c.cnt_contract_key) cnt_opzegdatum"
          + "     , cnt.cnt_getRappeldatum(c.cnt_contract_key) cnt_rappeldatum"
          + "     , cnt.cnt_contract_status("
            + "      c.cnt_contract_looptijd_van"
            + "     , cnt.cnt_getRappeldatum(c.cnt_contract_key)"
            + "     , cnt.cnt_getOpzegdatum(c.cnt_contract_key)"
            + "     , c.cnt_contract_looptijd_tot) fase_actief"
          + "     , c.cnt_contract_status"
          + "     , c.cnt_contract_key cnt_contract_key"
          + "     , COALESCE(c.ins_discipline_key, -1) disc_key"
          + "     , c.prs_afdeling_key_eig eigenaar_key"
          + "     , c.cnt_contract_nummer_intern"
          + "     , dp.cnt_srtcontract_type"
          + "     , alg_locatie_oms"
          + "     , alg_locatie_omschrijving"
          + "     , alg_district_omschrijving"
          + "     , alg_locatie_code"
          + "     , alg_locatie_count"
          + "     , c.ins_discipline_key"
          + "     , " + lcl.xsqla('cd.ins_discipline_omschrijving','cd.ins_discipline_key')
          + "     , c.cnt_contract_kosten"
          + "     , di.prs_dienst_omschrijving"
          + sqltrack
          + "  FROM prs_v_aanwezigbedrijf b"
          + "     , cnt_v_aanwezigcontract c"
          + "     , prs_dienst di"
          + (ksgrp_key
            ? "   , prs_kostensoort ks"
            : "")
          + "     , prs_v_afdeling d"
          + "     , prs_v_afdeling afd"
          + "     , prs_perslid p"
          + "     , alg_district ad"
          + "     , cnt_disc_params dp"
          + "     , cnt_discipline cd";

      // Om drie redenen hebben we de locatie_key nodig in de hoofd query
      //   - Voor als de gebruiker filtert op locatie (optioneel)
      //   - Voor als de gebruiker beperkte autorisatie heeft (optioneel)
      //   - Om de locatieomschrijving in de lijst te kunnen tonen (niet bij maninfo)
      // Voor die eerste twee is sql_cnt_loc_keyA die bij contracten met meerdere locaties alles bevat
      //  Voor de tweede is sql_cnt_loc_key die groeppeert en telt per locatie
      // LET OP: - type 4 (algemeen / generiek) zit er niet in
      sql_cnt_loc_keyA = " SELECT cp.cnt_contract_key"
                       + "      , cp.cnt_alg_plaats_key alg_locatie_key"
                       + "   FROM cnt_contract_plaats cp"
                       + "  WHERE cnt_alg_plaats_code = 'L'"
                       + " UNION ALL"
                       + " SELECT cp.cnt_contract_key"
                       + "      , g.alg_locatie_key"
                       + "   FROM cnt_contract_plaats cp, alg_gebouw g"
                       + "  WHERE cnt_alg_plaats_code = 'G'"
                       + "    AND cp.cnt_alg_plaats_key = g.alg_gebouw_key"
                       + " UNION ALL"
                       + " SELECT cp.cnt_contract_key"
                       + "      , t.alg_locatie_key"
                       + "   FROM cnt_contract_plaats cp, alg_terreinsector t"
                       + "  WHERE cnt_alg_plaats_code = 'T'"
                       + "    AND cp.cnt_alg_plaats_key = t.alg_terreinsector_key"
                       + " UNION ALL"
                       + " SELECT co.cnt_contract_key"
                       + "      , d.ins_alg_locatie_key"
                       + "   FROM cnt_contract_object co"
                       + "      , ins_deel d"
                       + "  WHERE co.cnt_ins_deel_key = d.ins_deel_key"
                       + " UNION ALL"
                       + " SELECT co.cnt_contract_key"
                       + "      , g.alg_locatie_key"
                       + "   FROM cnt_contract_onrgoed co"
                       + "      , alg_gebouw g"
                       + "      , alg_verdieping v"
                       + "      , alg_ruimte r"
                       + " WHERE co.alg_onrgoed_niveau = 'R'"
                       + "   AND co.alg_onrgoed_key = r.alg_ruimte_key"
                       + "   AND r.alg_verdieping_key = v.alg_verdieping_key"
                       + "   AND v.alg_gebouw_key = g.alg_gebouw_key"
                       + " UNION ALL"
                       + " SELECT co.cnt_contract_key"
                       + "      , t.alg_locatie_key"
                       + "   FROM cnt_contract_onrgoed co, alg_terreinsector t"
                       + "  WHERE co.alg_onrgoed_niveau = 'T'"
                       + "    AND co.alg_onrgoed_key = t.alg_terreinsector_key";

      sql_cnt_loc_key = "SELECT MIN(alg_locatie_omschrijving || ' (' || alg_locatie_code || ')') alg_locatie_oms"
                      + "     , MIN(alg_locatie_omschrijving) alg_locatie_omschrijving"
                      + "     , MIN(alg_locatie_code) alg_locatie_code"
                      + "     , MIN(alg_district_key) alg_district_key"
                      + "     , cnt_contract_key"
                      + "     , MIN(ll.alg_locatie_key) alg_locatie_key"
                      + "     , COUNT(distinct alg_locatie_code) alg_locatie_count"
                      + "  FROM alg_locatie ll"
                      + "     , (" + sql_cnt_loc_keyA + ") scloc"
                      + "  WHERE ll.alg_locatie_key = scloc.alg_locatie_key"
                      + " GROUP BY cnt_contract_key";


      sql += ", (" + sql_cnt_loc_key + ") cloc";

      sql += " WHERE b.prs_bedrijf_key(+) = c.cnt_prs_bedrijf_key"
           + " AND c.cnt_prs_afdeling_key = afd.prs_afdeling_key(+)"
           + " AND c.cnt_prs_perslid_key = p.prs_perslid_key(+)"
           + " AND c.prs_dienst_key = di.prs_dienst_key(+)"
           + " AND d.prs_afdeling_key = c.prs_afdeling_key_eig"
           + " AND c.ins_discipline_key = dp.cnt_ins_discipline_key"
           + " AND c.ins_discipline_key = cd.ins_discipline_key"
           + " AND cloc.cnt_contract_key(+) = c.cnt_contract_key"
           + " AND cloc.alg_district_key = ad.alg_district_key(+)";

      if (cntsrt_key)
      {
        sql += " AND c.ins_discipline_key = " + cntsrt_key;
      }

      sql += getKenmerkSql("CNT", "c.cnt_contract_key", true);
      // Dienst
      if (dienst_key)
      {
        sql += " AND (c.prs_dienst_key = " + dienst_key
            +  "      OR (c.prs_dienst_key IS NULL "
            +  "          AND EXISTS (SELECT '' FROM prs_bedrijfdienstlocatie dl "
            +  "                       WHERE dl.prs_bedrijf_key = b.prs_bedrijf_key AND dl.prs_dienst_key = " + dienst_key +")))";
      }

      // Uitvoerder
      if (uitvoerder_key)
      {
        sql += " AND b.prs_bedrijf_key = " + uitvoerder_key;
      }

      // Persoon (Contractpartij)
      if (cnt_persoon_key)
      {
        sql += " AND c.cnt_prs_perslid_key = " + cnt_persoon_key;
      }

      // Mantel
      if (mantel_key)
      {
        sql += " AND c.cnt_contract_mantel_key = " + mantel_key;
      }

      // Afdeling (Eigenaar)
      if (eigenaar_key)
      {
        sql += " AND c.prs_afdeling_key_eig = " + eigenaar_key;
      }

      // Verantwoordelijk manager
      if (manager_key)
      {
        sql += " AND c.prs_perslid_key_eig = " + manager_key;
      }

      // Beheerder
      if (beheerder_key)
      {
        sql += " AND c.prs_perslid_key_beh = " + beheerder_key;
      }

      // Regio, District, Locatie en gebouw
      if (bld_key)
      {
        sql_bld = bld_key;
        sql_loc = loc_key;
      }
      else if (loc_key)
      {
        sql_loc = loc_key;
      }
      else if (dist_key)
      {
        sql_loc = "SELECT alg_locatie_key FROM alg_locatie WHERE alg_district_key = " + dist_key;
      }
      else if (reg_key)
      {
        sql_loc = "SELECT alg_locatie_key FROM alg_locatie l, alg_district d WHERE l.alg_district_key = d.alg_district_key AND d.alg_regio_key = " + reg_key;
      }

      // Merk op dat we hier niet kunnen verwijzen naar cloc binnen sql omdat die MIN(alg_locatie_key) en MIN(alg_gebouw_key) bevat
      if (reg_key || dist_key || loc_key)
      {
        sql += " AND c.cnt_contract_key IN"
             + " (SELECT cnt_contract_key FROM cnt_v_aanwezigcontract_plaats"
             + " WHERE (cnt_alg_plaats_code = 'L' AND cnt_alg_plaats_key IN (" + sql_loc + "))";
        if (bld_key)
        {
          sql += " OR (cnt_alg_plaats_code = 'G' AND cnt_alg_plaats_key = "
               + bld_key
               + ") OR (cnt_alg_plaats_code = 'T' AND cnt_alg_plaats_key = "
               + bld_key + ")";
        }
        else
        {
          sql += " OR (cnt_alg_plaats_code = 'G' AND cnt_alg_plaats_key IN "
               + " (SELECT alg_gebouw_key FROM alg_v_aanweziggebouw WHERE alg_locatie_key IN (" + sql_loc + "))"
               + " OR cnt_alg_plaats_code = 'T' AND cnt_alg_plaats_key IN "
               + " (SELECT alg_terreinsector_key FROM alg_v_aanwezigterreinsector WHERE alg_locatie_key IN (" + sql_loc + ")))";
        }
        sql += " UNION SELECT cnt_contract_key FROM cnt_v_aanwezigcontract_object co, ins_v_aanwezigdeel ad"
             + " WHERE cnt_ins_deel_key = ad.ins_deel_key AND ad.ins_alg_locatie_key IN (" + sql_loc + ")";

        sql += " UNION SELECT cnt_contract_key FROM cnt_v_contract_locatie_geg cl"
             + " WHERE alg_locatie_key IN (" + sql_loc + "))";
      }

      // Objectsoort
      if (objectsrt_key)
      {
        sql += " AND c.cnt_contract_key IN "
             + " (SELECT cnt_contract_key FROM cnt_v_aanwezigcontract_object"
             + " WHERE cnt_ins_srtdeel_key = " + objectsrt_key +")";
      // we assume that srtdeel is defined if deel is defined. It is.
      //     + " OR cnt_ins_deel_key IN "
      //     + "(SELECT ins_deel_key FROM ins_v_aanwezigdeel WHERE ins_srtdeel_key = " + objectsrt_key + "))";
      }
      if (ins_key)
      {
        sql += " AND c.cnt_contract_key IN "
             + " (SELECT   DISTINCT cnt_contract_key"
             + " FROM   (SELECT   cnt_contract_key"
             + " FROM   cnt_contract_object"
             + " WHERE   cnt_ins_deel_key =" + ins_key + ""
             + " UNION"
             + " SELECT   co.cnt_contract_key"
             + " FROM   CNT_V_AANWEZIGCONTRACT_OBJECT co,"
             + "      ins_deel d,"
             + "     cnt_v_aanwezigcontract_plaats ccp,"
             + "      alg_v_allonroerendgoed aao"
             + " WHERE       cnt_ins_deel_key IS NULL"
             + "      AND co.cnt_ins_srtdeel_key = d.ins_srtdeel_key"
             + "      AND d.ins_deel_key =" + ins_key + ""
             + "      AND ccp.cnt_contract_key = co.cnt_contract_key"
             + "      AND COALESCE (d.ins_alg_ruimte_type_org,"
             + "                    ins_alg_ruimte_type) = 'R'"
             + "      AND COALESCE (d.ins_alg_ruimte_key_org,"
             + "                    ins_alg_ruimte_key) = aao.alg_ruimte_key"
             + "      AND ( (ccp.cnt_alg_plaats_code = 'L'"
             + "             AND ccp.cnt_alg_plaats_key = aao.alg_locatie_key)"
             + "           OR (ccp.cnt_alg_plaats_code = 'G'"
             + "               AND ccp.cnt_alg_plaats_key = aao.alg_gebouw_key))"
             + " UNION"
             + " SELECT   co.cnt_contract_key"
             + " FROM   CNT_V_AANWEZIGCONTRACT_OBJECT co, ins_deel d"
             + " WHERE       cnt_ins_deel_key IS NULL"
             + "      AND co.cnt_ins_srtdeel_key = d.ins_srtdeel_key"
             + "      AND d.ins_deel_key =" + ins_key + ""
             + "      AND (co.cnt_contract_key NOT IN"
             + "                  (SELECT   cnt_contract_key"
             + "                     FROM   cnt_v_aanwezigcontract_plaats)"
             + "            OR COALESCE (d.ins_alg_ruimte_type_org,"
             + "                         ins_alg_ruimte_type) != 'R')))";
       }

      if (kp_key)
      {
        sql += " AND c.prs_kostenplaats_key = " + kp_key;
      }

      if (ksgrp_key)
      {
         sql += " AND c.prs_kostensoort_key = ks.prs_kostensoort_key"
              + " AND ks.prs_kostensoortgrp_key = " + ksgrp_key;
      }

      if (ks_key)
      {
         // Ook die van het contractsoort beschouwen, het gaat om de geldende ks, niet per se de geregistreerde
         // deze is niks sneller: sql += " AND (c.prs_kostensoort_key = " + ks_key + " OR (cd.prs_kostensoort_key = " + ks_key + " AND c.prs_kostensoort_key IS NULL))";
         sql += " AND COALESCE(c.prs_kostensoort_key, cd.prs_kostensoort_key) = " + ks_key;
      }

      // Beschrijving
      if (descript)
      {
        sql += " AND UPPER(c.cnt_contract_omschrijving) LIKE " + safe.quoted_sql_wild("%"+descript+"%");
      }

      // we don't use status field because we don't have mechanism to change its value
      // in case of mld_melding status was changed as the result of user's actions
      // here it gets changed as the result of current date changing

      // Contract number
      if (cntnum)
      {
          sql += " AND (UPPER(c.cnt_contract_nummer) LIKE " + safe.quoted_sql_wild(cntnum + "%")
               + " OR UPPER(c.cnt_contract_nummer_intern) LIKE " + safe.quoted_sql_wild(cntnum + "%") + ")";
      }
      else
      {
        var statussen = "";
        var komma = ", ";
        var actief = false;
        var sqlactief = "";
        if (cntAct)
        {
          //statussen = "0", en dan ook naar de fases binnen de status Actief kijken.
          sqlactief += " (c.cnt_contract_status = 0"
                     + cnt.getfaseconditionsql({cntffutu: cntFFutu, cntfact: cntFAct, cntfrap: cntFRap, cntfopz: cntFOpz, cntfverl: cntFVerl})
                     + ")";
        }
        if (cntInact)
          statussen += "1";
        if (cntNew)
          statussen += (statussen != ""? komma : "") + "2";
        if (cntTgoe)
          statussen += (statussen != ""? komma : "") + "3";
        var sqlINT = statussen == ""? "" :  " (c.cnt_contract_status IN (" + statussen + "))";

        if (sqlactief != "" && sqlINT != "")
          sql += " AND (" + sqlactief + " OR" + sqlINT + ")";
        else if (sqlactief != "" || sqlINT != "")
          sql += " AND" + sqlactief + sqlINT; // Één van beide is een lege string.
        else
          sql += " AND 1 = 0";
      }

      // scope
      // sql bevat al wel een alg_locatie_key maar er zit een group-by (en een MIN) in
      // wat te streng is voor scope
      // Daarom teruggrijpen op sql_cnt_loc_keyA die nog geen group-by op contract heeft gedaan
      sql_scope = " SELECT cnt_contract_key"
                + " FROM ("
                  + " SELECT cc.cnt_contract_key"
                  + ", ins_discipline_key"
                  + ", di.alg_regio_key"
                  + ", ll.alg_district_key"
                  + ", clk.alg_locatie_key"
                  + " FROM (" + sql_cnt_loc_keyA + ") clk"
                  + ", cnt_contract cc"
                  + ", alg_locatie ll"
                  + ", alg_district di"
                  + "  WHERE cc.cnt_contract_key = clk.cnt_contract_key"
                  + " AND ll.alg_locatie_key(+) = clk.alg_locatie_key" // persoons/afdelingsgebonden objecten hebben geen ins_alg_locatie_key vandaar (+)
                  + " AND ll.alg_district_key = di.alg_district_key(+)" // persoons/afdelingsgebonden objecten hebben geen ins_alg_locatie_key vandaar (+)
                  + ") sc"
                + ", prs_v_afdeling_boom boom"
                + " WHERE boom.prs_afdeling_key = c.prs_afdeling_key_eig";

      // Autorisatie voor ALG (cnt_contract_plaats) en PRS (cnt_contract.prs_afdeling_key_eig)
      sql_scope = discx3d (sql_scope,
                           "sc.ins_discipline_key",
                           "sc.alg_regio_key",
                           "sc.alg_district_key",
                           "sc.alg_locatie_key",
                           "sc.alg_gebouw_key",
                           "", // verdieping not supported
                           "", // ruimte not supported
                           "boom.prs_bedrijf_key",
                           "boom.prs_afdeling_key",
                           pautfunction,
                           (!cntnum && cntsrt_key? cntsrt_key : ""),
                           2);

      // Scopeloos contract of nog geen scope toegekend. Alleen disc en eigenaar controleren
      sql_scopeloos = "SELECT cnt_contract_key"
                    + " FROM cnt_contract c"
                    + ", prs_v_afdeling_boom boom"
                    + " WHERE NOT EXISTS (SELECT cnt_contract_key"
                      + " FROM cnt_contract_plaats cp"
                      + " WHERE cp.cnt_contract_key = c.cnt_contract_key)"
                    + " AND NOT EXISTS (SELECT cnt_contract_key"
                      + " FROM cnt_contract_onrgoed co"
                      + " WHERE co.cnt_contract_key = c.cnt_contract_key)"
                    + " AND NOT EXISTS (SELECT cnt_contract_key"
                      + " FROM cnt_contract_object co"
                      + " WHERE co.cnt_contract_key = c.cnt_contract_key"
                    + " AND co.cnt_ins_deel_key IS NOT NULL)"  // alleen de contracten met objecten uitsluiten. Niet de contracten met contractsoorten uitsluiten.
                    + " AND boom.prs_afdeling_key = c.prs_afdeling_key_eig";

      // Autorisatie voor PRS (cnt_contract.prs_afdeling_key_eig)
      sql_scopeloos = discx3d (sql_scopeloos,
                               "c.ins_discipline_key",
                               "", // regio not supported
                               "", // district not supported
                               "", // locatie not supported
                               "", // gebouw not supported
                               "", // verdieping not supported
                               "", // ruimte not supported
                               "boom.prs_bedrijf_key",
                               "boom.prs_afdeling_key",
                               pautfunction,
                               (cntsrt_key? cntsrt_key : ""),
                               1);

      // En de contracten waarvan ik eigenaar of beheerder ben, ook al zouden die verder buiten de scope vallen
      sql_mine = "SELECT cnt_contract_key FROM cnt_contract WHERE c.prs_perslid_key_beh = " + user_key + " OR c.prs_perslid_key_eig = " + user_key;

      sql = sql + " AND c.cnt_contract_key IN (" + sql_scope + " UNION ALL " + sql_scopeloos + " UNION ALL " + sql_mine + ")";

      // Op datum (c.cnt_contract_looptijd_tot) sorteren: UWVA#13274 en daarbinnen op c.cnt_contract_nummer en c.cnt_contract_nummer_intern: UWVA#14609
      sql += " ORDER BY" + (excel? " UPPER("+ lcl.xsql('cd.ins_discipline_omschrijving','cd.ins_discipline_key') +")," : "")
           + " c.cnt_contract_looptijd_tot"
           + ", c.cnt_contract_nummer"
           + ", c.cnt_contract_nummer_intern";

      var count = 0;
      var bReado;
      var eSubmit = false;

      colors = new Array();
      colors[0] = "cntfuture";
      colors[1] = "cntactive";
      colors[2] = "cntrappel";
      colors[3] = "cntopzeg";
      colors[4] = "cntpast";
      colors[5] = "cntinactive";

      /**********************************
       * Callback functies ResultsetTable
       *********************************/
      var recent = new Date();
      recent.setMinutes(recent.getMinutes() - S("cnt_contract_recent"));
      function fnrowClass(oRs)
      {
        if (oRs("cnt_contract_status").value == 1)
          class1 = colors[5];
        else
          class1 = colors[oRs("fase_actief").value];
        if (excel || print)
          class1 = "";

        var cnt_recent = new Date(oRs("recentdatum").value);
        if (cnt_recent > recent)
        {
          class1 += " updated";
        }
        return class1;
      }

      // Extra data voor de client om daar dynamisch buttons te kunnen activeren.
      function fnrowData(oRs)
      {
        var cntNummerIntern = oRs("cnt_contract_nummer_intern").Value;
        var data = {cntNummerIntern: cntNummerIntern};

        return JSON.stringify(data);
      }
      function fnrowActionEnabler(oRs)
      {
        var data = {};
        // status 2 is 'ter goedkeuring'
        if (S("cnt_contract_approval") == 1 && oRs("cnt_contract_status").Value == 2) // Voorkennis. Voorkom dure cnt.func_enabled_contract
        {
            var this_cnt = cnt.func_enabled_contract(oRs("cnt_contract_key").Value);
            data.eForApproval = this_cnt.forApproval; // Ter goedkeuring
        }
        return data;
      }

      function fncolContractnr(oRs)
      {
        var cnt_nr = oRs("cnt_contract_nummer_intern").value;
        if (oRs("cnt_contract_versie").value)
          cnt_nr += "."+oRs("cnt_contract_versie").value;
        return safe.html(cnt_nr);
      }

      function fncolLoc(oRs)
      {
        var locatieName = oRs("alg_locatie_oms").value;
        var aantalLoc = oRs("alg_locatie_count").value;
        if (aantalLoc > 1)
          locatieName = L("lcl_cnt_locatie_m") + " (" + aantalLoc + ")";
        return safe.html(locatieName);
      }

      function fncolLocOms(oRs)
      {
        var locatieOms = oRs("alg_locatie_omschrijving").value;
        var aantalLoc = oRs("alg_locatie_count").value;
        if (aantalLoc > 1)
          locatieOms = L("lcl_cnt_locatie_m") + " (" + aantalLoc + ")";
        return safe.html(locatieOms);
      }

      function fncolLocCode(oRs)
      {
        var locatieCode = oRs("alg_locatie_code").value;
        var aantalLoc = oRs("alg_locatie_count").value;
        if (aantalLoc > 1)
          locatieCode = L("lcl_cnt_locatie_m") + " (" + aantalLoc + ")";
        return safe.html(locatieCode);
      }

      function fncolStatus(oRs)
      {
        return safe.html(cnt.getcntstatustext(oRs("cnt_contract_status").Value));
      }

      var buttons = [];
      if ((S("cnt_contract_approval") == 0 && authparamsCNTMAN && authparamsCNTMAN.ALGwritelevel < 9 && authparamsCNTMAN.PRSwritelevel < 9) ||
          (S("cnt_contract_approval") == 1 && authparamsCNTUSE && authparamsCNTUSE.ALGwritelevel < 9 && authparamsCNTUSE.PRSwritelevel < 9))
      {
        buttons.push({ icon: "page_refresh.png", title: L("lcl_refresh"), action: "FcltMgr.reload()" });
        var addurl = "appl/cnt/cnt_contract.asp?urole=bo";
        buttons.push({ icon: "plus.png", title: L("lcl_add"), action: "FcltMgr.openDetail('"+addurl+"', '"+L("lcl_add")+"')" });
      }
      var rst = new ResultsetTable({ keyColumn: "cnt_contract_key",
                                     ID: "cnttable",
                                     rowClass: fnrowClass,
                                     rowData: fnrowData,
                                     rowActionEnabler: fnrowActionEnabler,
                                     sql: sql,
                                     flexModule: "CNT",
                                     flexId: "cnt_contract_key",
                                     flexGroupId: "ins_discipline_key",
                                     filterParams: params,
                                     outputmode: outputmode,
                                     title: L("lcl_cnt_contracts"),
                                     showAll: showall,
                                     buttons: buttons
                                   });

      rst.addColumn(new Column({caption: L("lcl_cnt_intern_nr"), content: fncolContractnr}));
      if (outputmode == 0)
        rst.addColumn(new Column({caption: L("lcl_location"), content: fncolLoc, hasActions: true}));
      else
      {
        rst.addColumn(new Column({caption: L("lcl_district"), content: "alg_district_omschrijving"}));
        rst.addColumn(new Column({caption: L("lcl_location"), content: fncolLocOms}));
        rst.addColumn(new Column({caption: L("lcl_estate_locatie_man_code"), content: fncolLocCode}));
      }
      rst.addColumn(new Column({caption: L("lcl_cnt_contractnr"), content: "cnt_contract_nummer"}));
      rst.addColumn(new Column({caption: L("lcl_cnt_beschrijv"), content: "cnt_contract_omschrijving"}));
      if (outputmode != 0)
      {
        rst.addColumn(new Column({caption: L("lcl_cnt_document"), content: "cnt_contract_document"}));
      }
      rst.addColumn(new Column({caption: L("lcl_cnt_effecter"), content: "uitvoerder"}));

      if (outputmode != 0)
      {
        rst.addColumn(new Column({caption: L("lcl_prs_companies_dienst"), content: "prs_dienst_omschrijving"}));
      }

      rst.addColumn(new Column({caption: L("lcl_cnt_owner"), content: "eigenaar"}));
      rst.addColumn(new Column({caption: L("lcl_cnt_status"), content: fncolStatus}));
      if (outputmode != 0)
      {
        rst.addColumn(new Column({caption: L("lcl_cnt_date_start"), content: "begindatum"}));
        rst.addColumn(new Column({caption: L("lcl_cnt_rappel_date"), content: "cnt_rappeldatum"}));
        rst.addColumn(new Column({caption: L("lcl_cnt_cancel_date"), content: "cnt_opzegdatum"}));
      }
      rst.addColumn(new Column({caption: L("lcl_cnt_enddate"), content: "einddatum"}));
      if (outputmode != 0)
      {
        rst.addColumn(new Column({caption: L("lcl_cnt_contract_sum") + "&nbsp;(" + L("lcl_valutasign") + ")", content: "cnt_contract_kosten", datatype: "currency"}));
      }

      rst.addAction({ action: "cntEdit", caption: L("lcl_edit"), isDefault: true });
      if (S("cnt_contract_approval") == 1)
        rst.addAction({ action: "cntForApproval", caption: L("lcl_cnt_forapproval"), enabler:"eForApproval", multi: true, multiOnce: true });
      // PF: ik vermoed dat de opdrachten -action niet meer nodig is, ik denk aan een opdrachten-frame in het contractdetail (cnt_contract.asp)
      //rst.addAction({ action: "cntOrders", caption: L("lcl_cnt_order"), enabler: "eOrder"});
      // TODO: IK mis hier nog opdrachten algemeen zonder dat contract_key automatisch wordt ingevuld. Is niet afhankelijk van de geselecteerde regel

      var count = rst.processResultset();
%>
    </body>
  </html>
<%
}
%>
