<% /*
     $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_arr  search for contracts with the given contractsoort keys (discipline key)  //SGGR#74615 PF
         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_arr     search for contracts with the given regio keys
         dist_key_arr    search for contracts with the given district keys
         loc_key_arr     search for contracts with the given location keys
         bld_key_arr     search for contracts with the given building keys
         flr_key_arr     search for contracts with the given floor keys
         room_key_arr    search for contracts with the given room keys
         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
         cntNotclosed    select all contracts which are not closed (used from alg_locatie)
         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/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", "jquery-ui.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_arr : Array of 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.flr_key        : key
  // params.room_key       : key
  // params.objectsrt_key  : key
  // params.mantel_key     : key
  // params.descript       : wildcard string
  // params.refDate        : date
  // params.cntNotclosed   : boolean (true | false)
  // 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 tiny = params.tiny;
  var showall = params.showall;

  var room_key_arr = params.room_key_arr || [];

  var rstFilters = params.rst_filters;

  var transitParam = buildTransitParam(["loc_key", "urole", "tiny", "ffutu", "fact", "frap", "fopz", "sact", "cnt_full", "ins_key"]);
  var checkBoxes = [
    {
     lcl: L("lcl_cnt_inactive"),
     param: 'sinact',
     checked: cntInact,
     transitParams: transitParam
    }
  ];
  var rstCheckBoxes = rstFilters ? checkBoxes : [];
%>

  <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();

      var sql = cnt.getfromwherelist_sql(pautfunction, params);

      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();  // je zou kunnen denken om ook hier de peildatum refdate voor te gebruiken, maar... nah.
      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 fncolPlaats(oRs)
      {
        var cnt_loc = oRs("alg_locatie_count").Value || 0;
        var cnt_bld = oRs("alg_gebouw_count").Value || 0;
        var cnt_flr = oRs("alg_verdieping_count").Value || 0;
        var cnt_roo = oRs("alg_ruimte_count").Value || 0;
        var oms = [];
        if (cnt_loc == 1)
        {
          //oms.push(oRs("alg_locatie_code").Value);
          if (cnt_bld == 1)
          {
            oms.push(oRs("alg_gebouw_code").Value);
            if (cnt_flr == 1)
            {
              oms.push(oRs("alg_verdieping_code").Value);
              if (cnt_roo == 1)
              {
                oms.push(oRs("alg_ruimte_nr").Value);
              }
              else if (cnt_roo > 1)
                oms.push(L("lcl_cnt_ruimte_m") +"("+cnt_roo+")");
            }
            else if (cnt_flr > 1)
              oms.push(L("lcl_cnt_verdieping_m") +"("+cnt_flr+")");
          }
          else if (cnt_bld > 1)
            oms.push(L("lcl_cnt_gebouw_m") +"("+cnt_bld+")");
        }
        //else if (cnt_loc > 1)
        //  oms.push(L("lcl_cnt_locatie_m") +"("+cnt_loc+")");

        var plaats = oms.join(" - ");
        return safe.html(plaats);
      }

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

      var deleted_room = false;
      if (room_key_arr.length)
      {
        var sqlr = "SELECT alg_ruimte_verwijder"
                + "  FROM alg_ruimte"
                + " WHERE alg_ruimte_key IN (" + room_key_arr.join(",") + ")";
        var oRsr = Oracle.Execute(sqlr);
        deleted_room = oRsr("alg_ruimte_verwijder").Value != null;
        oRsr.Close();
      }

      var buttons = [];
      buttons.push({ icon: "fa-columns",  title: L("lcl_scf_columns"), action: "openColumns()"});
      if (!deleted_room)
      {
        // als tiny dan tonen we een shortcut naar contractbeheer
        // voorlasnog alleen bij relatiebeheer. Dit mag ook voor Locaties, Gebouwen en Objecten?
        if (tiny == 1 && uitvoerder_key > 0)
        {
          var cnturl = "appl/cnt/cnt_search.asp";
          if (uitvoerder_key > 0)
            cnturl += "?comp_key=" + uitvoerder_key + "&autosearch=1"

          buttons.push({title: L("lcl_menu_cnt_bo"),  icon: "fa-book", action: "FcltMgr.openDetail('"+cnturl+"', '"+safe.jsstring(L("lcl_menu_cnt_bo"))+"')" });
        }

        if (!frontend)
          buttons.push({ icon: "fa-list-ul",  title: L("lcl_mld_legenda"), action: 'openLegenda()' });

        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))
        {
          var addurl = "appl/cnt/cnt_contract.asp?urole=bo";
          buttons.push({ icon: "fa-plus", title: L("lcl_add"), action: "FcltMgr.openDetail('"+addurl+"', '"+safe.jsstring(L("lcl_add"))+"')" });
        }
      }
      buttons.push({ icon: "fa-fclt-refresh", title: L("lcl_refresh"), action: "FcltMgr.reload()", id: "btn_scf_refresh" });

     var rst = new ResultsetTable({ keyColumn: "cnt_contract_key",
                                     ID: "cnttable",
                                     tabs_code: "cnt_list-" + urole + (tiny?"1":""), // inline kun je ook anders willen
                                     rowClass: fnrowClass,
                                     rowData: fnrowData,
                                     rowActionEnabler: fnrowActionEnabler,
                                     multiActionEnabler: true,
                                     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,
                                     rstCheckBoxes: rstCheckBoxes
                                   });

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

      rst.addColumn(new Column({caption: L("lcl_prs_companies_dienst"), content: "prs_dienst_omschrijving", purpose: PRINTING_ONLY}));

      rst.addColumn(new Column({caption: L("lcl_cnt_owner"), content: "eigenaar"}));
      rst.addColumn(new Column({caption: L("lcl_cnt_contact_eig"), content: "manager", xpurpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_cnt_manager"), content: "perslid_naam_beh", combine: true}));

      rst.addColumn(new Column({caption: L("lcl_prs_kostenpl_group"), content: "kostenplaatsgrp"}));
      rst.addColumn(new Column({caption: L("lcl_cnt_kostenplaats"), content: "kostenplaats", xpurpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_cnt_status"), content: fncolStatus, colName: "fncolStatus", nowrap: true}));
      rst.addColumn(new Column({caption: L("lcl_remark"), content: "cnt_contract_opmerking"}));
      rst.addColumn(new Column({caption: L("lcl_cnt_date_start"), content: "begindatum", nowrap: true}));
      rst.addColumn(new Column({caption: L("lcl_cnt_rappel_date"), content: "cnt_rappeldatum", purpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_cnt_cancel_date"), content: "cnt_opzegdatum", purpose: PRINTING_ONLY}));
      rst.addColumn(new Column({caption: L("lcl_cnt_enddate"), content: "einddatum", nowrap: true}));
      rst.addColumn(new Column({caption: L("lcl_cnt_contract_sum") + "&nbsp;(" + L("lcl_valutasign") + ")", content: "cnt_contract_kosten", colText: L("lcl_cnt_contract_sum"), datatype: "currency", total: true}));

      rst.addColumn(new Column({caption: L("lcl_cnt_period_period"), content: "factuur_termijn", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_cancel_period"), content: "opzeg_termijn", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_rappel_period"), content: "rappel_termijn", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_verlengen"), content: "verlenging", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_prolongation_period"), content: "verleng_termijn", combine: true, showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_period_sum") + "&nbsp;(" + L("lcl_valutasign") + ")", content: "cnt_contract_termijnkosten", datatype: "currency", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_discount"), content: "cnt_contract_korting", datatype: "number", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_hour_rate"), content: "cnt_contract_uurloon", datatype: "currency", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_mantel"), content: "mantel", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_cnt_contact_prs"), content: "contactpersoon", showDefault: false}));
      rst.addColumn(new Column({caption: L("lcl_person"), content: "persoon", showDefault: false}));

      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
      rst.addAction({ action: "cntSplit", caption: L("lcl_cnt_newversion"), enabler: "eSplit", multi: true, multiOnce: true, single: false });
      rst.addAction({ action: "cntClose", caption: L("lcl_cnt_inactivate"), enabler: "eClose", multi: true, multiOnce: true, single: false });
      rst.addAction({ action: "cntKenmerk", caption: L("lcl_properties"), enabler: "eKenmerk", multi: true, multiOnce: true, single: false });

      var count = rst.processResultset();
      if (!excel && !print)
      {
%>
      <!-- LEGENDA  -->
      <script type="text/javascript">
<%    if (Request.ServerVariables("REQUEST_METHOD") == "POST") { %>
        if (FcltMgr._frmaccessible(parent) && FcltMgr._safe_parent() !== window && typeof parent.window.doSubmit === "function") {
          var fnReloadByPost = parent.window.doSubmit.bind(null, 0);
        }
<%    } %>

        $(function() {
          $(".clickParent").parent().on("click", function(e) { e.stopPropagation(); $(this).find("> .clickParent").trigger("click"); });
        });

        function openLegenda()
        {
            var myPosition = "right top+30";
            if (elems.$originalHeaderRow && elems.$originalHeaderRow.length)
                myPosition = "right-15 top+"+(parseInt(elems.$fcltFrameHeader.css("top"))+30);
            params = { width: 250,
                       minWidth: 250,
                       minHeight: 10,
                       resizable: false,
                       position: {my: "right top", at: myPosition},
                       title: L("lcl_ins_controle_legenda"),
                       create: FcltMgr.fnCreateCloseButton("div#legenda")
                     };
            $('div#legenda').dialog(params).dialog('open');
            FcltMgr.resized();
        }
      </script>
      <div id="legenda" style="display:none; line-height: 30px;">
        <table id="contractlegenda">
          <tr class="cntfuture">
            <td title="<%=safe.htmlattr(L("lcl_cnt_future"))%>"><%= L("lcl_cnt_future") %></td>
          </tr>
          <tr class="cntactive">
            <td title="<%=safe.htmlattr(L("lcl_cnt_active"))%>"><%= L("lcl_cnt_active") %></td>
          </tr>
          <tr class="cntrappel">
            <td title="<%=safe.htmlattr(L("lcl_cnt_warn"))%>"><%= L("lcl_cnt_warn") %></td>
          </tr>
          <tr class="cntopzeg">
            <td title="<%=safe.htmlattr(L("lcl_cnt_cancel"))%>"><%= L("lcl_cnt_cancel") %></td>
          </tr>
          <tr class="cntpast">
            <td title="<%=safe.htmlattr(L("lcl_cnt_past"))%>"><%= L("lcl_cnt_past") %></td>
          </tr>
          <tr class="cntinactive">
            <td title="<%=safe.htmlattr(L("lcl_cnt_inactive"))%>"><%= L("lcl_cnt_inactive") %></td>
          </tr>
        </table>
      </div>
<% } %>
    </body>
  </html>
<%
}
%>
