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

    File:           fac_fiattering_list_xd.asp
    Description:    XD overzicht fiatteringsverzoeken
    Parameters:
    Context:        Vanuit fac_fiattering_search.asp
    Requires:       WEB_ORDOAP autorisatie

    Notes:          Vergelijk ook fac_fiattering_list.asp, die lijkt hier sterk op

*/
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/status.inc" -->
<!-- #include file="../shared/data_recordset.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../BES/bes.inc" -->
<!-- #include file="../CNT/cnt.inc" -->
<!-- #include file="fac.inc" -->
<!-- #include file="../MLD/mld.inc" -->
<!-- #include file="../FIN/fin.inc" -->
<!-- #include file="../FAC/fac_fiattering_list.inc" -->
<!-- #include file="../Shared/xd.inc" -->

<%
var outputmode = getQParamInt("outputmode", 0); //  0 = screen, 1 = print, 2 = excel etc
var showall = getQParamInt("showall", 0) == 1;

var getOpen = getQParamInt("open", 0) == 1;
var getClosed = getQParamInt("close", 0) == 1;
var getRejected = getQParamInt("reject", 0) == 1;
var betreft = getQParamArray("betreft", []); // Betreft module BES, CNT, FIN, MLDOF of MLDOP.

if (!getOpen && !getClosed && !getRejected)
    getOpen = true;

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

<html>
  <head>
<%  FCLTHeader.Generate({outputmode: outputmode}) %>
<script>
    var sd = <%=JSON.stringify(xd.SecundaryDomains)%>;

    // Vergelijk fac_fiattering_list.asp/fac_edit()
    function xd_edit(row)
    {
      $(row).addClass('dirty');
      var lKey = row.getAttribute("ROWKEY");
      var lData = JSON.parse(row.getAttribute("ROWDATA"));
      var module = lData.module;
      var name = $(row).find("span.xdcustname").text()||"";

      // We geven urole=fe mee omdat dat de lading het best dekt
      switch (module)
      {
        case "BES":
        {
          url = sd[lData.custid].deeplinkurl + "appl/bes/bes_bestelling.asp?urole=fe&bes_key=" + lKey;
          break;
        }
        case "CNT":
        {
          url = sd[lData.custid].deeplinkurl + "appl/cnt/cnt_contract.asp?urole=fe&cnt_key=" + lKey;
          break;
        }
        case "MLD":
        case "GOED":
        case "OFFERTE":
        {
          url = sd[lData.custid].deeplinkurl + "appl/mld/mld_opdr.asp?opdr_key=" + lKey;
          break;
        }
        case "FIN":
        case "FIN2":
        {
          url = sd[lData.custid].deeplinkurl + "appl/fin/fin_factuur.asp?fin_key=" + lKey;
          break;
        }
        default: INTERNAL_ERROR;
      }

      FcltMgr.openDetail(url + "<%=S("xd_add2deeplinkurl")%>", { 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/approvals.json?x=1";

    // Condities toevoegen (komen van fac_fiattering_search.asp)
    var statussen = [];
    if (getOpen)
        statussen.push("o");
    if (getClosed)
        statussen.push("c");
    if (getRejected)
        statussen.push("r");

    if (statussen.length > 0)
        url += "&status="+statussen.join(',');

    if (betreft.length)
        url += "&betreft="+safe.url(betreft.join(','));

    if (__Logging & 1)
        url += "&logging=1";

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

    reqresult = HTTP.getJSON(url, { APIKEY : myAPIKEY });
    // This result is:
    // {issues: [{...}]}} in case of matching results
    // {} in case of HTTP-errors or no result
    // {issue : {}} in case of GET by existing ID (unique)
    if (reqresult) {
        gottenitems[cid] = "approval" in reqresult ? [reqresult["approval"]] : reqresult.approvals;
    } else {
        __Log("no result for " + cid.name);
    }
}

// Merge these result objects into one list for the resultset to process.
// Note: we could have combined this with the previous loop but we did not
var dataset = [];
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];
       thisdata.custid = cid;
       dataset.push(thisdata);
    }
}
dataset.sort(function (a, b) { return (a.sortdate <= b.sortdate? -1: 1) });

    function fnRowData(oRs)
    {
        var data = { custid: oRs.Fields("custid").Value,
                     module: oRs.Fields("module").Value };
        return JSON.stringify(data);
    }

    function fncolBesNr(oRs)
    { // Eigenlijk wil je een markering bij de parent, niet bij het child TODO
        if (oRs.Fields("module").Value != "BES")
            return xd.fnCustName(oRs);
      return  S("bes_bestelling_prefix") + (oRs.Fields("poparent").Value > 0 ? oRs.Fields("poparent").Value + "*" : xd.fnCustName(oRs));
    }

    function prepareModule(oRs)
    {
        switch (oRs.Fields("module").Value)
        {
          case "BES": return L("lcl_bes_bestelling"); break;
          case "CNT": return L("lcl_cnt_contract"); break;
          case "MLD":
          case "GOED": return L("lcl_shared_order") + "<br>" + safe.html(oRs.Fields("type").Value); break;
          case "OFFERTE": return safe.html(oRs.Fields("type").Value) + "<br>" + safe.html(oRs.Fields("supplier").Value); break;
          case "FIN":
          case "FIN2": return L("lcl_fin_factuur_type") + "<br>" + safe.html(oRs.Fields("type").Value); break;
          default: INTERNAL_ERROR;
        }
    }

    function fncolGebouwTerrein(oRs)
    {
      if (oRs.Fields("building").Value == " " || oRs.Fields("building").Value == null)
        if (oRs.Fields("terrain").Value == " " || oRs.Fields("terrain").Value == null)
          return "";
        else return oRs.Fields("terrain").Value;
      else return oRs.Fields("building").Value;
    }

    function fncolStatus(oRs)
    {
      switch (oRs.Fields("module").Value)
      {
        case "BES":     { return bes.getbesbestellingstatustext(oRs.Fields("status").Value); break; }
        case "CNT":     { return cnt.getcntstatustext(oRs.Fields("status").Value); break; }
        case "MLD":
        case "GOED":    { return status.getopdrstatustext(oRs.Fields("status").Value); break; }
        case "OFFERTE": { return L("lcl_mld_ter_acceptatie"); break; }
        case "FIN":
        case "FIN2":    { return fin.getfinstatustext(oRs.Fields("status").Value); break; }
      }
    }

   function fncolfiatteur(oRs)
    {
      switch (oRs.Fields("module").Value)
      {
        case "BES":
        case "MLD":
        case "GOED":
        case "OFFERTE":
        case "FIN":
        case "FIN2":    { return oRs.Fields("approver").Value; break; }
        case "CNT":     { switch (oRs.Fields("approver").Value)
                          {
                            case "0": { return ''; break; } // Kan eigenlijk niet voorkomen.
                            case "1": { return L("lcl_cnt_approved_upto").format(S("cnt_contract_limit1")); break; }
                            case "2": { return L("lcl_cnt_approved_upto").format(S("cnt_contract_limit2")); break; }
                            case "3": { return L("lcl_cnt_approved_upto").format(S("cnt_contract_limit3")); break; }
                          }
                        }
      }
    }
    var rst = new ResultsetTable({keyColumn: "id",
                                  ID: "multi-approve-table",
                                  dataset: dataset,
                                  rowData: fnRowData,
                                  outputmode: outputmode,
                                  //filterParams: params,
                                  showAll: showall,
                                  emptySetString: L("lcl_rfo_no_items_to_approve")});

    rst.addColumn(new Column({caption: L("lcl_request_key"), content: fncolBesNr}));
    rst.addColumn(new Column({caption: L("lcl_date"), content: "date", datatype: "date"}));
    rst.addColumn(new Column({caption: L("lcl_rfo_requestor"), content: "requestor", hasActions: true }));
    rst.addColumn(new Column({caption: L("lcl_rfo_total_sum"), content: "amount", datatype: "currency"}));
    rst.addColumn(new Column({caption: L("lcl_rfo_type"), content: prepareModule}));
    rst.addColumn(new Column({caption: L("lcl_rfo_category"), content: "category"}));
    rst.addColumn(new Column({caption: L("lcl_bes_RFO_status"), content: fncolStatus}));
//    if (user.hasCollegas()) // Gewoon altijd Cross Domain
      rst.addColumn(new Column({caption: L("lcl_bes_approver"), content: fncolfiatteur}));
    rst.addColumn(new Column({caption: L("lcl_location"), content: "location"}));
    rst.addColumn(new Column({caption: L("lcl_bld_terra"), content: fncolGebouwTerrein, combine: true}));

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


    var cnt = rst.processResultset();
%>
  </body>
</html>
<% ASPPAGE_END(); %> 
