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

    File:           cnt_search_list_xd.asp
    Description:    Show a readonly list of contracts from multiple environments (crossdomain xd) as defined bij S("xd.secundarydomainurls")
                    using the contracts-API
                    providing a means to access these in their native environment by a single click
    Parameters:     see below
    Context:        -

    Status:
    Note:

*/ %>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../shared/data_recordset.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../cnt/cnt.inc" -->
<!-- #include file="../Shared/xd.inc" -->
<%
var outputmode         = getFParamInt("outputmode", 0);
var showall            = getFParamInt("showall", 0) == 1;
var urole              = getFParamSafe("urole", "fe");

var cntnum             = getFParam("cntnum", null); // Contractnummer
var descript           = getFParam("descript", ""); // Beschrijving
var cnt_persoon_omschr = getFParam("cnt_persoon_omschr", ""); // Persoon (Contractpartij)
var disc_omschr        = getFParam("disc_omschr", ""); // Contractsoort / discipline omschrijving
var uitvoerder_omschr  = getFParam("comp_omschr", ""); // Uitvoerder
var loc_omschr         = getFParam("loc_omschr", ""); // Locatie omschrijving
var myself             = getFParamInt("zelf", 0) == 1; // Alleen mijnes (dat is wel algemeen), verwachte extensie in cnt_search.asp
// Statussen
var cntAct             = getFParamInt("cntAct", 0) == 1; // Status Actief(0)
var cntInact           = getFParamInt("cntInact", 0) == 1; // Status Inactief(1)
var cntNew             = getFParamInt("cntNew", 0) == 1; // Status Nieuw(2)
var cntTgoe            = getFParamInt("cntTgoe", 0) == 1; // Status Ter goedkeuring(3)
// Fases
//var cntFFutu           = getFParamInt("cntFFutu", 0) == 1; // Fase Toekomstig binnen status actief
//var cntFAct            = getFParamInt("cntFAct", 0) == 1; // Fase Actueel binnen status actief
//var cntFRap            = getFParamInt("cntFRap", 0) == 1; // Fase Rappel binnen status actief
//var cntFOpz            = getFParamInt("cntFOpz", 0) == 1; // Fase In opzegtermijn binnen status actief
//var cntFVerl           = getFParamInt("cntFVerl", 0) == 1; // Fase Verlopen binnen status actief


FCLTHeader.Requires({ plugins: ["jQuery"],
                      js: ["jquery-ui.js"]});
FCLTHeader.Title(L("lcl_xd_contracts"));
%>
<html>
  <head>
<%  FCLTHeader.Generate({ outputmode: outputmode }); %>
    <script>
      var sd = <%=JSON.stringify(xd.SecundaryDomains)%>;

      function xd_edit(row)
      {
        $(row).addClass('dirty');
        var lKey = row.getAttribute("ROWKEY");
        var lData = eval("(" + row.getAttribute("ROWDATA") + ")");
        var name = $(row).find("span.xdcustname").text() || "";
        url = sd[lData.custid].deeplinkurl + "appl/cnt/cnt_contract.asp?cnt_key=" + lKey + "<%=S("xd_add2deeplinkurl")%>";
        FcltMgr.openDetail(url, { reuse: true, titel: name });
      }
    </script>
  </head>
<%

  var myAPIKEY = user.prs_perslid_apikey();
  if (!myAPIKEY) shared.simpel_page(L("lcl_xd_crossdomain_noapikey"));

  var gottenitems = [];
  var url = "";
// Execute the API2 request for all domains
  for (var cid in xd.SecundaryDomains)
  {
    url = xd.SecundaryDomains[cid].apiurl + "api2/contracts.json?x=1";

    // Condities toevoegen (komen van cnt_search.asp)
    if (cntnum)
      url += "&name="+ safe.url(cntnum);
    else
    { // Alleen als cntnum (contract key) niet opgegeven is, zijn de resterende parameters van belang!
      if (descript != "") url += "&description=" + safe.url(descript);
      if (cnt_persoon_omschr != "") url += "&person=~" + safe.url(cnt_persoon_omschr);
      if (disc_omschr != "") url += "&contracttype=~" + safe.url(disc_omschr);
      if (uitvoerder_omschr != "") url += "&contractor=~" + safe.url(uitvoerder_omschr);
      if (loc_omschr != "") url += "&location=~" + safe.url(loc_omschr);

      var statussen = [];
      if (cntAct)   statussen.push (0);
      if (cntInact) statussen.push (1);
      if (cntNew)   statussen.push (2);
      if (cntTgoe)  statussen.push (3);
      if (statussen.length > 0)
        url += "&status=" + statussen.join(',');
    }


    // TODO: de scope hier en/of in het model aanscherpen: CNTMAN/USE-read of self zijn de 2 smaken?
    if (myself)
        url += "&scope=fe";
    else
        url += "&scope=bo";//+ safe.url(urole);

    var sysdate = new Date();
    // Dit is een naar stukje; het vergt een matrix om te begrijpen hoe de vinkjes vertaald
    // kunnen worden naar ranges over de 4 datumvelden, maar dit moet het dan zijn.
    // Alle combinaties komen voor, met de irrelevante weggelaten. Volgorde per datumveld
    // Denk Karnaugh
    // Maar toch hebben we DeMorgan ook nog nodig, de combinatie van parameters
    // is een AND, en we hebben een OR nodig. De NOT hebben we echter niet!
    // Ergo: laten we het hier maar eens mee doen. ALs het tot problemen gaat leiden
    // dan gaan we de filtering weglaten en alleen actieve (niet toekomstig/niet verlopen)
    // contracten opleveren.
    // Weet je wat: dat doen we direct maar, geloofwaardig genoeg. Jammer van de moeite
    if (0)
    {
      //if ( cntFFutu && !cntFAct && !cntFRap && !cntFOpz && !cntFVerl)
      //    url += "&start_startdate="+sysdate.toISOString();
      //if ((!cntFFutu &&  cntFAct && !cntFRap && !cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct &&  cntFRap && !cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct &&  cntFRap &&  cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct &&  cntFRap &&  cntFOpz &&  cntFVerl))
      //    url += "&end_startdate="+sysdate.toISOString();
      //if ((!cntFFutu &&  cntFAct && !cntFRap && !cntFOpz && !cntFVerl)
      // || ( cntFFutu &&  cntFAct && !cntFRap && !cntFOpz && !cntFVerl))
      //    url += "&start_reminderdate="+sysdate.toISOString();
      //if ((!cntFFutu && !cntFAct &&  cntFRap && !cntFOpz && !cntFVerl)
      // || (!cntFFutu && !cntFAct &&  cntFRap &&  cntFOpz && !cntFVerl)
      // || (!cntFFutu && !cntFAct &&  cntFRap &&  cntFOpz &&  cntFVerl))
      //    url += "&end_reminderdate="+sysdate.toISOString();
      //if ((!cntFFutu && !cntFAct &&  cntFRap && !cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct &&  cntFRap && !cntFOpz && !cntFVerl)
      // || ( cntFFutu &&  cntFAct &&  cntFRap && !cntFOpz && !cntFVerl))
      //    url += "&start_canceldate="+sysdate.toISOString();
      //if ((!cntFFutu && !cntFAct && !cntFRap &&  cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct && !cntFRap &&  cntFOpz &&  cntFVerl))
      //    url += "&end_canceldate="+sysdate.toISOString()
      //if ((!cntFFutu && !cntFAct && !cntFRap &&  cntFOpz && !cntFVerl)
      // || (!cntFFutu && !cntFAct &&  cntFRap &&  cntFOpz && !cntFVerl)
      // || (!cntFFutu &&  cntFAct &&  cntFRap &&  cntFOpz && !cntFVerl)
      // || ( cntFFutu &&  cntFAct &&  cntFRap &&  cntFOpz && !cntFVerl))
      //    url += "&start_enddate="+sysdate.toISOString();
      //if (!cntFFutu && !cntFAct && !cntFRap && !cntFOpz &&  cntFVerl)
      //    url += "&end_enddate="+sysdate.toISOString();
    } else {
      url += "&end_startdate="+sysdate.toISOString();
      url += "&start_enddate="+sysdate.toISOString();
    }
    if (Session("logging")&1)
      url += "&logging=1";

    if (showall)
      url += "&limit=-1";

    reqresult = HTTP.getJSON(url, { APIKEY : myAPIKEY });
    if (reqresult) {
      gottenitems[cid] = "contract" in reqresult ? [reqresult["contract"]] : reqresult.contracts;
    } else {
      __Log("no result for " + cid.name);
    }
  }

  // Merge these result objects into one list for the resultset to process.
  var dataset = [];
  __Log("gottenitems.length:" +gottenitems.length);
  for (var cid in gottenitems)
  { // per omgeving
    var gottenitem = gottenitems[cid]
    __Log("gottenitems["+cid+"].length:" +gottenitem.length);
    for (var j=0; j < gottenitem.length; j++)
    { // de issues
      var thisdata = gottenitem[j];
      dataset.push({
                     custid: cid,
                     id: thisdata.id,
                     name: thisdata.name,
                     startdate: thisdata.startdate,
                     reminderdate: thisdata.reminderdate,
                     canceldate: thisdata.canceldate,
                     enddate: thisdata.enddate,
                     description: thisdata.description,
                     service: thisdata.service ? thisdata.service.name : null,
                     department: thisdata.department ? thisdata.department.name : null,
                     contracttype: thisdata.contracttype.name,
                     status: thisdata.status.name,
                     contractor: thisdata.contractor ? thisdata.contractor.name : null,
                     person: thisdata.person ? thisdata.person.name : null
                  });
    }
  }
  dataset.sort(function (a, b) { return (a.enddate <= b.enddate? -1: 1) });

  function fnrowClass(oRs)
  {
    var resclass ="";
    var lnow = new Date();
    if (oRs.Fields("canceldate").Value < lnow)
      resclass += ' expired2';
    else if (oRs.Fields("reminderdate").Value < lnow)
      resclass += ' expired1';
    return resclass;
  }

  var rst = new ResultsetTable({ dataset: dataset,
                                 keyColumn: "id",
                                 rowData: xd.fnRowData,
                                 rowClass: fnrowClass,
                                 ID: "multi-contracts-table",
                                 title: L("lcl_xd_contracts"),
                                 outputmode: outputmode,
                                 showAll: showall
                                });

  rst.addColumn(new Column({caption: L("lcl_cnt_intern_nr"), content:xd.fnCustName }));
  rst.addColumn(new Column({caption: L("lcl_cnt_srttype"), content:"contracttype"}));
  rst.addColumn(new Column({caption: L("lcl_cnt_contractant"), content:"contractor"}));
  rst.addColumn(new Column({caption: L("lcl_prs_companies_dienst"), content:"service"}));
  rst.addColumn(new Column({caption: L("lcl_txt"), content:"description"}));
  rst.addColumn(new Column({caption: L("lcl_cnt_owner"), content:"department"}));
  rst.addColumn(new Column({caption: L("lcl_cnt_date_start"), content: "startdate", datatype: "date", purpose: PRINTING_ONLY}));
  rst.addColumn(new Column({caption: L("lcl_cnt_cancel_date"), content: "canceldate", datatype: "date"}));
  rst.addColumn(new Column({caption: L("lcl_cnt_enddate"), content: "enddate", datatype: "date"}));
  rst.addColumn(new Column({caption: L("lcl_cnt_status"), content: "status"}));

  rst.addAction({ action: "xd_edit", caption: L("lcl_edit"), isDefault: true } );

  rst.processResultset();
%>
</html>